summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorOpenShift Merge Robot <openshift-merge-robot@users.noreply.github.com>2021-01-19 16:56:17 -0500
committerGitHub <noreply@github.com>2021-01-19 16:56:17 -0500
commit5e7262ddf595f9187d01e12f5dcee2fe1c713798 (patch)
tree6cde028a76610dfc85eb7e27af7743af2e9842bb
parent37470c4d200c5cde2f8e233dbaa6d200d94919cc (diff)
parenta45d22a1ddd2840cf8c3a38540aa8683cc0d5c7d (diff)
downloadpodman-5e7262ddf595f9187d01e12f5dcee2fe1c713798.tar.gz
podman-5e7262ddf595f9187d01e12f5dcee2fe1c713798.tar.bz2
podman-5e7262ddf595f9187d01e12f5dcee2fe1c713798.zip
Merge pull request #9021 from Luap99/podman-network-exists
podman network exists
-rw-r--r--cmd/podman/networks/exists.go40
-rw-r--r--docs/source/markdown/podman-network-exists.1.md44
-rw-r--r--docs/source/markdown/podman-network.1.md1
-rw-r--r--docs/source/network.rst2
-rw-r--r--pkg/api/handlers/libpod/networks.go18
-rw-r--r--pkg/api/server/register_networks.go22
-rw-r--r--pkg/bindings/network/network.go13
-rw-r--r--pkg/bindings/network/types.go6
-rw-r--r--pkg/bindings/network/types_exists_options.go88
-rw-r--r--pkg/domain/entities/engine_container.go1
-rw-r--r--pkg/domain/infra/abi/network.go15
-rw-r--r--pkg/domain/infra/tunnel/network.go11
-rw-r--r--test/e2e/network_test.go16
13 files changed, 277 insertions, 0 deletions
diff --git a/cmd/podman/networks/exists.go b/cmd/podman/networks/exists.go
new file mode 100644
index 000000000..2eb485b36
--- /dev/null
+++ b/cmd/podman/networks/exists.go
@@ -0,0 +1,40 @@
+package network
+
+import (
+ "github.com/containers/podman/v2/cmd/podman/common"
+ "github.com/containers/podman/v2/cmd/podman/registry"
+ "github.com/containers/podman/v2/pkg/domain/entities"
+ "github.com/spf13/cobra"
+)
+
+var (
+ networkExistsDescription = `If the named network exists, podman network exists exits with 0, otherwise the exit code will be 1.`
+ networkExistsCommand = &cobra.Command{
+ Use: "exists NETWORK",
+ Short: "network exists",
+ Long: networkExistsDescription,
+ RunE: networkExists,
+ Example: `podman network exists net1`,
+ Args: cobra.ExactArgs(1),
+ ValidArgsFunction: common.AutocompleteNetworks,
+ }
+)
+
+func init() {
+ registry.Commands = append(registry.Commands, registry.CliCommand{
+ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
+ Command: networkExistsCommand,
+ Parent: networkCmd,
+ })
+}
+
+func networkExists(cmd *cobra.Command, args []string) error {
+ response, err := registry.ContainerEngine().NetworkExists(registry.GetContext(), args[0])
+ if err != nil {
+ return err
+ }
+ if !response.Value {
+ registry.SetExitCode(1)
+ }
+ return nil
+}
diff --git a/docs/source/markdown/podman-network-exists.1.md b/docs/source/markdown/podman-network-exists.1.md
new file mode 100644
index 000000000..c7edc2ac7
--- /dev/null
+++ b/docs/source/markdown/podman-network-exists.1.md
@@ -0,0 +1,44 @@
+% podman-network-exists(1)
+
+## NAME
+podman\-network\-exists - Check if the given network exists
+
+## SYNOPSIS
+**podman network exists** *network*
+
+## DESCRIPTION
+**podman network exists** checks if a network exists. The **Name** or **ID**
+of the network may be used as input. Podman will return an exit code
+of `0` when the network is found. A `1` will be returned otherwise. An exit code of
+`125` indicates there was an other issue.
+
+
+## OPTIONS
+
+#### **--help**, **-h**
+
+Print usage statement
+
+## EXAMPLE
+
+Check if a network called `net1` exists (the network does actually exist).
+```
+$ podman network exists net1
+$ echo $?
+0
+$
+```
+
+Check if an network called `webbackend` exists (the network does not actually exist).
+```
+$ podman network exists webbackend
+$ echo $?
+1
+$
+```
+
+## SEE ALSO
+podman(1), podman-network-create(1), podman-network-rm(1)
+
+## HISTORY
+January 2021, Originally compiled by Paul Holzinger <paul.holzinger@web.de>
diff --git a/docs/source/markdown/podman-network.1.md b/docs/source/markdown/podman-network.1.md
index 41e2ae885..3ad37b8bf 100644
--- a/docs/source/markdown/podman-network.1.md
+++ b/docs/source/markdown/podman-network.1.md
@@ -16,6 +16,7 @@ The network command manages CNI networks for Podman.
| connect | [podman-network-connect(1)](podman-network-connect.1.md) | Connect a container to a network |
| create | [podman-network-create(1)](podman-network-create.1.md) | Create a Podman CNI network |
| disconnect | [podman-network-disconnect(1)](podman-network-disconnect.1.md) | Disconnect a container from a network |
+| exists | [podman-network-exists(1)](podman-network-exists.1.md) | Check if the given network exists |
| inspect | [podman-network-inspect(1)](podman-network-inspect.1.md) | Displays the raw CNI network configuration for one or more networks |
| ls | [podman-network-ls(1)](podman-network-ls.1.md) | Display a summary of CNI networks |
| reload | [podman-network-reload(1)](podman-network-reload.1.md) | Reload network configuration for containers |
diff --git a/docs/source/network.rst b/docs/source/network.rst
index 2ecb97858..b5829876e 100644
--- a/docs/source/network.rst
+++ b/docs/source/network.rst
@@ -7,6 +7,8 @@ Network
:doc:`disconnect <markdown/podman-network-disconnect.1>` network disconnect
+:doc:`exists <markdown/podman-network-exists.1>` network exists
+
:doc:`inspect <markdown/podman-network-inspect.1>` network inspect
:doc:`ls <markdown/podman-network-ls.1>` network list
diff --git a/pkg/api/handlers/libpod/networks.go b/pkg/api/handlers/libpod/networks.go
index 8511e2733..d3bf06988 100644
--- a/pkg/api/handlers/libpod/networks.go
+++ b/pkg/api/handlers/libpod/networks.go
@@ -157,3 +157,21 @@ func Connect(w http.ResponseWriter, r *http.Request) {
}
utils.WriteResponse(w, http.StatusOK, "OK")
}
+
+// ExistsNetwork check if a network exists
+func ExistsNetwork(w http.ResponseWriter, r *http.Request) {
+ runtime := r.Context().Value("runtime").(*libpod.Runtime)
+ name := utils.GetName(r)
+
+ ic := abi.ContainerEngine{Libpod: runtime}
+ report, err := ic.NetworkExists(r.Context(), name)
+ if err != nil {
+ utils.Error(w, "Something went wrong.", http.StatusInternalServerError, err)
+ return
+ }
+ if !report.Value {
+ utils.Error(w, "network not found", http.StatusNotFound, define.ErrNoSuchNetwork)
+ return
+ }
+ utils.WriteResponse(w, http.StatusNoContent, "")
+}
diff --git a/pkg/api/server/register_networks.go b/pkg/api/server/register_networks.go
index 967d7da76..3d9e7fb89 100644
--- a/pkg/api/server/register_networks.go
+++ b/pkg/api/server/register_networks.go
@@ -226,6 +226,28 @@ func (s *APIServer) registerNetworkHandlers(r *mux.Router) error {
// 500:
// $ref: "#/responses/InternalError"
r.HandleFunc(VersionedPath("/libpod/networks/{name}/json"), s.APIHandler(libpod.InspectNetwork)).Methods(http.MethodGet)
+ // swagger:operation GET /libpod/networks/{name}/exists libpod libpodExistsNetwork
+ // ---
+ // tags:
+ // - networks
+ // summary: Network exists
+ // description: Check if network exists
+ // parameters:
+ // - in: path
+ // name: name
+ // type: string
+ // required: true
+ // description: the name or ID of the network
+ // produces:
+ // - application/json
+ // responses:
+ // 204:
+ // description: network exists
+ // 404:
+ // $ref: '#/responses/NoSuchNetwork'
+ // 500:
+ // $ref: '#/responses/InternalError'
+ r.Handle(VersionedPath("/libpod/networks/{name}/exists"), s.APIHandler(libpod.ExistsNetwork)).Methods(http.MethodGet)
// swagger:operation GET /libpod/networks/json libpod libpodListNetwork
// ---
// tags:
diff --git a/pkg/bindings/network/network.go b/pkg/bindings/network/network.go
index 7cd251b0e..8debeee84 100644
--- a/pkg/bindings/network/network.go
+++ b/pkg/bindings/network/network.go
@@ -167,3 +167,16 @@ func Connect(ctx context.Context, networkName string, ContainerNameOrId string,
}
return response.Process(nil)
}
+
+// Exists returns true if a given network exists
+func Exists(ctx context.Context, nameOrID string, options *ExistsOptions) (bool, error) {
+ conn, err := bindings.GetClient(ctx)
+ if err != nil {
+ return false, err
+ }
+ response, err := conn.DoRequest(nil, http.MethodGet, "/networks/%s/exists", nil, nil, nameOrID)
+ if err != nil {
+ return false, err
+ }
+ return response.IsSuccess(), nil
+}
diff --git a/pkg/bindings/network/types.go b/pkg/bindings/network/types.go
index 2a7e500dd..91cbcf044 100644
--- a/pkg/bindings/network/types.go
+++ b/pkg/bindings/network/types.go
@@ -68,3 +68,9 @@ type ConnectOptions struct {
// when using the dns plugin
Aliases *[]string
}
+
+//go:generate go run ../generator/generator.go ExistsOptions
+// ExistsOptions are optional options for checking
+// if a network exists
+type ExistsOptions struct {
+}
diff --git a/pkg/bindings/network/types_exists_options.go b/pkg/bindings/network/types_exists_options.go
new file mode 100644
index 000000000..8076a18e8
--- /dev/null
+++ b/pkg/bindings/network/types_exists_options.go
@@ -0,0 +1,88 @@
+package network
+
+import (
+ "net/url"
+ "reflect"
+ "strconv"
+ "strings"
+
+ jsoniter "github.com/json-iterator/go"
+ "github.com/pkg/errors"
+)
+
+/*
+This file is generated automatically by go generate. Do not edit.
+*/
+
+// Changed
+func (o *ExistsOptions) Changed(fieldName string) bool {
+ r := reflect.ValueOf(o)
+ value := reflect.Indirect(r).FieldByName(fieldName)
+ return !value.IsNil()
+}
+
+// ToParams
+func (o *ExistsOptions) ToParams() (url.Values, error) {
+ params := url.Values{}
+ if o == nil {
+ return params, nil
+ }
+ json := jsoniter.ConfigCompatibleWithStandardLibrary
+ s := reflect.ValueOf(o)
+ if reflect.Ptr == s.Kind() {
+ s = s.Elem()
+ }
+ sType := s.Type()
+ for i := 0; i < s.NumField(); i++ {
+ fieldName := sType.Field(i).Name
+ if !o.Changed(fieldName) {
+ continue
+ }
+ fieldName = strings.ToLower(fieldName)
+ f := s.Field(i)
+ if reflect.Ptr == f.Kind() {
+ f = f.Elem()
+ }
+ switch f.Kind() {
+ case reflect.Bool:
+ params.Set(fieldName, strconv.FormatBool(f.Bool()))
+ case reflect.String:
+ params.Set(fieldName, f.String())
+ case reflect.Int, reflect.Int64:
+ // f.Int() is always an int64
+ params.Set(fieldName, strconv.FormatInt(f.Int(), 10))
+ case reflect.Uint, reflect.Uint64:
+ // f.Uint() is always an uint64
+ params.Set(fieldName, strconv.FormatUint(f.Uint(), 10))
+ case reflect.Slice:
+ typ := reflect.TypeOf(f.Interface()).Elem()
+ switch typ.Kind() {
+ case reflect.String:
+ sl := f.Slice(0, f.Len())
+ s, ok := sl.Interface().([]string)
+ if !ok {
+ return nil, errors.New("failed to convert to string slice")
+ }
+ for _, val := range s {
+ params.Add(fieldName, val)
+ }
+ default:
+ return nil, errors.Errorf("unknown slice type %s", f.Kind().String())
+ }
+ case reflect.Map:
+ lowerCaseKeys := make(map[string][]string)
+ iter := f.MapRange()
+ for iter.Next() {
+ lowerCaseKeys[iter.Key().Interface().(string)] = iter.Value().Interface().([]string)
+
+ }
+ s, err := json.MarshalToString(lowerCaseKeys)
+ if err != nil {
+ return nil, err
+ }
+
+ params.Set(fieldName, s)
+ }
+ }
+ return params, nil
+}
diff --git a/pkg/domain/entities/engine_container.go b/pkg/domain/entities/engine_container.go
index d2552770c..7b43ac961 100644
--- a/pkg/domain/entities/engine_container.go
+++ b/pkg/domain/entities/engine_container.go
@@ -60,6 +60,7 @@ type ContainerEngine interface {
NetworkConnect(ctx context.Context, networkname string, options NetworkConnectOptions) error
NetworkCreate(ctx context.Context, name string, options NetworkCreateOptions) (*NetworkCreateReport, error)
NetworkDisconnect(ctx context.Context, networkname string, options NetworkDisconnectOptions) error
+ NetworkExists(ctx context.Context, networkname string) (*BoolReport, error)
NetworkInspect(ctx context.Context, namesOrIds []string, options InspectOptions) ([]NetworkInspectReport, []error, error)
NetworkList(ctx context.Context, options NetworkListOptions) ([]*NetworkListReport, error)
NetworkReload(ctx context.Context, names []string, options NetworkReloadOptions) ([]*NetworkReloadReport, error)
diff --git a/pkg/domain/infra/abi/network.go b/pkg/domain/infra/abi/network.go
index e5ecf5c72..bc4328fcd 100644
--- a/pkg/domain/infra/abi/network.go
+++ b/pkg/domain/infra/abi/network.go
@@ -140,3 +140,18 @@ func (ic *ContainerEngine) NetworkDisconnect(ctx context.Context, networkname st
func (ic *ContainerEngine) NetworkConnect(ctx context.Context, networkname string, options entities.NetworkConnectOptions) error {
return ic.Libpod.ConnectContainerToNetwork(options.Container, networkname, options.Aliases)
}
+
+// NetworkExists checks if the given network exists
+func (ic *ContainerEngine) NetworkExists(ctx context.Context, networkname string) (*entities.BoolReport, error) {
+ config, err := ic.Libpod.GetConfig()
+ if err != nil {
+ return nil, err
+ }
+ exists, err := network.Exists(config, networkname)
+ if err != nil {
+ return nil, err
+ }
+ return &entities.BoolReport{
+ Value: exists,
+ }, nil
+}
diff --git a/pkg/domain/infra/tunnel/network.go b/pkg/domain/infra/tunnel/network.go
index d4e827580..bdb1beb03 100644
--- a/pkg/domain/infra/tunnel/network.go
+++ b/pkg/domain/infra/tunnel/network.go
@@ -78,3 +78,14 @@ func (ic *ContainerEngine) NetworkConnect(ctx context.Context, networkname strin
options := new(network.ConnectOptions).WithAliases(opts.Aliases)
return network.Connect(ic.ClientCtx, networkname, opts.Container, options)
}
+
+// NetworkExists checks if the given network exists
+func (ic *ContainerEngine) NetworkExists(ctx context.Context, networkname string) (*entities.BoolReport, error) {
+ exists, err := network.Exists(ic.ClientCtx, networkname, nil)
+ if err != nil {
+ return nil, err
+ }
+ return &entities.BoolReport{
+ Value: exists,
+ }, nil
+}
diff --git a/test/e2e/network_test.go b/test/e2e/network_test.go
index 4e8ab5ad5..98512f01a 100644
--- a/test/e2e/network_test.go
+++ b/test/e2e/network_test.go
@@ -456,4 +456,20 @@ var _ = Describe("Podman network", func() {
nc.WaitWithDefaultTimeout()
Expect(nc.ExitCode()).To(Equal(0))
})
+
+ It("podman network exists", func() {
+ net := "net" + stringid.GenerateNonCryptoID()
+ session := podmanTest.Podman([]string{"network", "create", net})
+ session.WaitWithDefaultTimeout()
+ defer podmanTest.removeCNINetwork(net)
+ Expect(session.ExitCode()).To(BeZero())
+
+ session = podmanTest.Podman([]string{"network", "exists", net})
+ session.WaitWithDefaultTimeout()
+ Expect(session.ExitCode()).To(Equal(0))
+
+ session = podmanTest.Podman([]string{"network", "exists", stringid.GenerateNonCryptoID()})
+ session.WaitWithDefaultTimeout()
+ Expect(session.ExitCode()).To(Equal(1))
+ })
})