From 9d31fed5f75186f618e95ab7492ef6bc2b511d5f Mon Sep 17 00:00:00 2001
From: Paul Holzinger <paul.holzinger@web.de>
Date: Tue, 19 Jan 2021 23:03:51 +0100
Subject: [PATCH] podman volume exists

Add podman volume exists command with remote support.

Signed-off-by: Paul Holzinger <paul.holzinger@web.de>
---
 cmd/podman/volumes/exists.go                  | 40 +++++++++
 .../markdown/podman-network-exists.1.md       |  4 +-
 .../source/markdown/podman-volume-exists.1.md | 43 +++++++++
 docs/source/markdown/podman-volume.1.md       |  1 +
 docs/source/volume.rst                        |  2 +
 pkg/api/handlers/libpod/volumes.go            | 19 ++++
 pkg/api/server/register_volumes.go            | 22 +++++
 pkg/bindings/volumes/types.go                 |  6 ++
 pkg/bindings/volumes/types_exists_options.go  | 88 +++++++++++++++++++
 pkg/bindings/volumes/volumes.go               | 13 +++
 pkg/domain/entities/engine_container.go       |  1 +
 pkg/domain/infra/abi/volumes.go               |  9 ++
 pkg/domain/infra/tunnel/volumes.go            | 11 +++
 test/e2e/volume_exists_test.go                | 50 +++++++++++
 14 files changed, 307 insertions(+), 2 deletions(-)
 create mode 100644 cmd/podman/volumes/exists.go
 create mode 100644 docs/source/markdown/podman-volume-exists.1.md
 create mode 100644 pkg/bindings/volumes/types_exists_options.go
 create mode 100644 test/e2e/volume_exists_test.go

diff --git a/cmd/podman/volumes/exists.go b/cmd/podman/volumes/exists.go
new file mode 100644
index 0000000000..71cd117aeb
--- /dev/null
+++ b/cmd/podman/volumes/exists.go
@@ -0,0 +1,40 @@
+package volumes
+
+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 (
+	volumeExistsDescription = `If the given volume exists, podman volume exists exits with 0, otherwise the exit code will be 1.`
+	volumeExistsCommand     = &cobra.Command{
+		Use:               "exists VOLUME",
+		Short:             "volume exists",
+		Long:              volumeExistsDescription,
+		RunE:              volumeExists,
+		Example:           `podman volume exists myvol`,
+		Args:              cobra.ExactArgs(1),
+		ValidArgsFunction: common.AutocompleteVolumes,
+	}
+)
+
+func init() {
+	registry.Commands = append(registry.Commands, registry.CliCommand{
+		Mode:    []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
+		Command: volumeExistsCommand,
+		Parent:  volumeCmd,
+	})
+}
+
+func volumeExists(cmd *cobra.Command, args []string) error {
+	response, err := registry.ContainerEngine().VolumeExists(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
index c7edc2ac79..3ad3ccedb8 100644
--- a/docs/source/markdown/podman-network-exists.1.md
+++ b/docs/source/markdown/podman-network-exists.1.md
@@ -10,7 +10,7 @@ podman\-network\-exists - Check if the given network exists
 **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.
+`125` indicates there was another issue.
 
 
 ## OPTIONS
@@ -41,4 +41,4 @@ $
 podman(1), podman-network-create(1), podman-network-rm(1)
 
 ## HISTORY
-January 2021, Originally compiled by Paul Holzinger <paul.holzinger@web.de>
+January 2021, Originally compiled by Paul Holzinger `<paul.holzinger@web.de>`
diff --git a/docs/source/markdown/podman-volume-exists.1.md b/docs/source/markdown/podman-volume-exists.1.md
new file mode 100644
index 0000000000..ead806bd9e
--- /dev/null
+++ b/docs/source/markdown/podman-volume-exists.1.md
@@ -0,0 +1,43 @@
+% podman-volume-exists(1)
+
+## NAME
+podman\-volume\-exists - Check if the given volume exists
+
+## SYNOPSIS
+**podman volume exists** *volume*
+
+## DESCRIPTION
+**podman volume exists** checks if a volume exists. Podman will return an exit code
+of `0` when the volume is found. A `1` will be returned otherwise. An exit code of
+`125` indicates there was another issue.
+
+
+## OPTIONS
+
+#### **--help**, **-h**
+
+Print usage statement
+
+## EXAMPLE
+
+Check if a volume called `myvol` exists (the volume does actually exist).
+```
+$ podman volume exists myvol
+$ echo $?
+0
+$
+```
+
+Check if an volume called `mysql` exists (the volume does not actually exist).
+```
+$ podman volume exists mysql
+$ echo $?
+1
+$
+```
+
+## SEE ALSO
+podman(1), podman-volume-create(1), podman-volume-rm(1)
+
+## HISTORY
+January 2021, Originally compiled by Paul Holzinger `<paul.holzinger@web.de>`
diff --git a/docs/source/markdown/podman-volume.1.md b/docs/source/markdown/podman-volume.1.md
index 288e57b825..5af5eb50e0 100644
--- a/docs/source/markdown/podman-volume.1.md
+++ b/docs/source/markdown/podman-volume.1.md
@@ -14,6 +14,7 @@ podman volume is a set of subcommands that manage volumes.
 | Command | Man Page                                               | Description                                                                    |
 | ------- | ------------------------------------------------------ | ------------------------------------------------------------------------------ |
 | create  | [podman-volume-create(1)](podman-volume-create.1.md)   | Create a new volume.                                                           |
+| exists  | [podman-volume-exists(1)](podman-volume-exists.1.md)   | Check if the given volume exists.                                              |
 | inspect | [podman-volume-inspect(1)](podman-volume-inspect.1.md) | Get detailed information on one or more volumes.                               |
 | ls      | [podman-volume-ls(1)](podman-volume-ls.1.md)           | List all the available volumes.                                                |
 | prune   | [podman-volume-prune(1)](podman-volume-prune.1.md)     | Remove all unused volumes.                                                     |
diff --git a/docs/source/volume.rst b/docs/source/volume.rst
index a966feafd5..ce9ea2cbd0 100644
--- a/docs/source/volume.rst
+++ b/docs/source/volume.rst
@@ -2,6 +2,8 @@ Volume
 ======
 :doc:`create <markdown/podman-volume-create.1>` Create a new volume
 
+:doc:`exists <markdown/podman-volume-exists.1>` Check if the given volume exists
+
 :doc:`inspect <markdown/podman-volume-inspect.1>` Display detailed information on one or more volumes
 
 :doc:`ls <markdown/podman-volume-ls.1>` List volumes
diff --git a/pkg/api/handlers/libpod/volumes.go b/pkg/api/handlers/libpod/volumes.go
index 38fdf1b4d1..1a8759c6c5 100644
--- a/pkg/api/handlers/libpod/volumes.go
+++ b/pkg/api/handlers/libpod/volumes.go
@@ -11,6 +11,7 @@ import (
 	"github.com/containers/podman/v2/pkg/domain/entities"
 	"github.com/containers/podman/v2/pkg/domain/entities/reports"
 	"github.com/containers/podman/v2/pkg/domain/filters"
+	"github.com/containers/podman/v2/pkg/domain/infra/abi"
 	"github.com/containers/podman/v2/pkg/domain/infra/abi/parse"
 	"github.com/gorilla/schema"
 	"github.com/pkg/errors"
@@ -203,3 +204,21 @@ func RemoveVolume(w http.ResponseWriter, r *http.Request) {
 	}
 	utils.WriteResponse(w, http.StatusNoContent, "")
 }
+
+// ExistsVolume check if a volume exists
+func ExistsVolume(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.VolumeExists(r.Context(), name)
+	if err != nil {
+		utils.Error(w, "Something went wrong.", http.StatusInternalServerError, err)
+		return
+	}
+	if !report.Value {
+		utils.Error(w, "volume not found", http.StatusNotFound, define.ErrNoSuchVolume)
+		return
+	}
+	utils.WriteResponse(w, http.StatusNoContent, "")
+}
diff --git a/pkg/api/server/register_volumes.go b/pkg/api/server/register_volumes.go
index aa0f67604e..68727f2e16 100644
--- a/pkg/api/server/register_volumes.go
+++ b/pkg/api/server/register_volumes.go
@@ -28,6 +28,28 @@ func (s *APIServer) registerVolumeHandlers(r *mux.Router) error {
 	//   '500':
 	//      "$ref": "#/responses/InternalError"
 	r.Handle(VersionedPath("/libpod/volumes/create"), s.APIHandler(libpod.CreateVolume)).Methods(http.MethodPost)
+	// swagger:operation GET /libpod/volumes/{name}/exists libpod libpodExistsVolume
+	// ---
+	// tags:
+	//  - volumes
+	// summary: Volume exists
+	// description: Check if a volume exists
+	// parameters:
+	//  - in: path
+	//    name: name
+	//    type: string
+	//    required: true
+	//    description: the name of the volume
+	// produces:
+	// - application/json
+	// responses:
+	//   204:
+	//     description: volume exists
+	//   404:
+	//     $ref: '#/responses/NoSuchVolume'
+	//   500:
+	//     $ref: '#/responses/InternalError'
+	r.Handle(VersionedPath("/libpod/volumes/{name}/exists"), s.APIHandler(libpod.ExistsVolume)).Methods(http.MethodGet)
 	// swagger:operation GET /libpod/volumes/json libpod libpodListVolumes
 	// ---
 	// tags:
diff --git a/pkg/bindings/volumes/types.go b/pkg/bindings/volumes/types.go
index 379174e33e..3fda77dddc 100644
--- a/pkg/bindings/volumes/types.go
+++ b/pkg/bindings/volumes/types.go
@@ -30,3 +30,9 @@ type RemoveOptions struct {
 	// Force removes the volume even if it is being used
 	Force *bool
 }
+
+//go:generate go run ../generator/generator.go ExistsOptions
+// ExistsOptions are optional options for checking
+// if a volume exists
+type ExistsOptions struct {
+}
diff --git a/pkg/bindings/volumes/types_exists_options.go b/pkg/bindings/volumes/types_exists_options.go
new file mode 100644
index 0000000000..c66586a239
--- /dev/null
+++ b/pkg/bindings/volumes/types_exists_options.go
@@ -0,0 +1,88 @@
+package volumes
+
+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/bindings/volumes/volumes.go b/pkg/bindings/volumes/volumes.go
index fe081eb469..60fdd0a236 100644
--- a/pkg/bindings/volumes/volumes.go
+++ b/pkg/bindings/volumes/volumes.go
@@ -114,3 +114,16 @@ func Remove(ctx context.Context, nameOrID string, options *RemoveOptions) error
 	}
 	return response.Process(nil)
 }
+
+// Exists returns true if a given volume 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, "/volumes/%s/exists", nil, nil, nameOrID)
+	if err != nil {
+		return false, err
+	}
+	return response.IsSuccess(), nil
+}
diff --git a/pkg/domain/entities/engine_container.go b/pkg/domain/entities/engine_container.go
index 7b43ac9612..39bda1d72f 100644
--- a/pkg/domain/entities/engine_container.go
+++ b/pkg/domain/entities/engine_container.go
@@ -86,6 +86,7 @@ type ContainerEngine interface {
 	Unshare(ctx context.Context, args []string) error
 	Version(ctx context.Context) (*SystemVersionReport, error)
 	VolumeCreate(ctx context.Context, opts VolumeCreateOptions) (*IDOrNameResponse, error)
+	VolumeExists(ctx context.Context, namesOrId string) (*BoolReport, error)
 	VolumeInspect(ctx context.Context, namesOrIds []string, opts InspectOptions) ([]*VolumeInspectReport, []error, error)
 	VolumeList(ctx context.Context, opts VolumeListOptions) ([]*VolumeListReport, error)
 	VolumePrune(ctx context.Context, options VolumePruneOptions) ([]*reports.PruneReport, error)
diff --git a/pkg/domain/infra/abi/volumes.go b/pkg/domain/infra/abi/volumes.go
index 8236050520..f15aa2d145 100644
--- a/pkg/domain/infra/abi/volumes.go
+++ b/pkg/domain/infra/abi/volumes.go
@@ -153,3 +153,12 @@ func (ic *ContainerEngine) VolumeList(ctx context.Context, opts entities.VolumeL
 	}
 	return reports, nil
 }
+
+// VolumeExists check if a given volume name exists
+func (ic *ContainerEngine) VolumeExists(ctx context.Context, nameOrID string) (*entities.BoolReport, error) {
+	exists, err := ic.Libpod.HasVolume(nameOrID)
+	if err != nil {
+		return nil, err
+	}
+	return &entities.BoolReport{Value: exists}, nil
+}
diff --git a/pkg/domain/infra/tunnel/volumes.go b/pkg/domain/infra/tunnel/volumes.go
index f21336828d..ffd2c1d352 100644
--- a/pkg/domain/infra/tunnel/volumes.go
+++ b/pkg/domain/infra/tunnel/volumes.go
@@ -80,3 +80,14 @@ func (ic *ContainerEngine) VolumeList(ctx context.Context, opts entities.VolumeL
 	options := new(volumes.ListOptions).WithFilters(opts.Filter)
 	return volumes.List(ic.ClientCtx, options)
 }
+
+// VolumeExists checks if the given volume exists
+func (ic *ContainerEngine) VolumeExists(ctx context.Context, nameOrID string) (*entities.BoolReport, error) {
+	exists, err := volumes.Exists(ic.ClientCtx, nameOrID, nil)
+	if err != nil {
+		return nil, err
+	}
+	return &entities.BoolReport{
+		Value: exists,
+	}, nil
+}
diff --git a/test/e2e/volume_exists_test.go b/test/e2e/volume_exists_test.go
new file mode 100644
index 0000000000..6073c6d905
--- /dev/null
+++ b/test/e2e/volume_exists_test.go
@@ -0,0 +1,50 @@
+package integration
+
+import (
+	"os"
+
+	. "github.com/containers/podman/v2/test/utils"
+	"github.com/containers/storage/pkg/stringid"
+	. "github.com/onsi/ginkgo"
+	. "github.com/onsi/gomega"
+)
+
+var _ = Describe("Podman volume exists", func() {
+	var (
+		tempdir    string
+		err        error
+		podmanTest *PodmanTestIntegration
+	)
+
+	BeforeEach(func() {
+		tempdir, err = CreateTempDirInTempDir()
+		if err != nil {
+			os.Exit(1)
+		}
+		podmanTest = PodmanTestCreate(tempdir)
+		podmanTest.Setup()
+		podmanTest.SeedImages()
+	})
+
+	AfterEach(func() {
+		podmanTest.CleanupVolume()
+		f := CurrentGinkgoTestDescription()
+		processTestResult(f)
+
+	})
+
+	It("podman volume exists", func() {
+		vol := "vol" + stringid.GenerateNonCryptoID()
+		session := podmanTest.Podman([]string{"volume", "create", vol})
+		session.WaitWithDefaultTimeout()
+		Expect(session.ExitCode()).To(BeZero())
+
+		session = podmanTest.Podman([]string{"volume", "exists", vol})
+		session.WaitWithDefaultTimeout()
+		Expect(session.ExitCode()).To(Equal(0))
+
+		session = podmanTest.Podman([]string{"volume", "exists", stringid.GenerateNonCryptoID()})
+		session.WaitWithDefaultTimeout()
+		Expect(session.ExitCode()).To(Equal(1))
+	})
+})