From 1d93d212541616135da23bcf01ca49180f113e62 Mon Sep 17 00:00:00 2001 From: Jhon Honce Date: Wed, 15 Apr 2020 10:12:30 -0700 Subject: V2 Enable rootless * Enable running podman V2 rootless * Fixed cobra.PersistentPreRunE usage in all the commands * Leveraged cobra.PersistentPreRunE/cobra.PersistentPostRunE to manage: * rootless * trace (--trace) * profiling (--cpu-profile) * initializing the registry copies of Image/Container engines * Help and Usage templates autoset for all sub-commands Signed-off-by: Jhon Honce --- cmd/podmanV2/Makefile | 4 +- cmd/podmanV2/common/create.go | 31 +++------ cmd/podmanV2/common/default.go | 51 +++++++------- cmd/podmanV2/common/netflags.go | 16 ++--- cmd/podmanV2/containers/attach.go | 1 - cmd/podmanV2/containers/commit.go | 11 ++- cmd/podmanV2/containers/container.go | 18 ++--- cmd/podmanV2/containers/create.go | 11 ++- cmd/podmanV2/containers/diff.go | 11 ++- cmd/podmanV2/containers/exec.go | 9 ++- cmd/podmanV2/containers/export.go | 13 ++-- cmd/podmanV2/containers/init.go | 9 ++- cmd/podmanV2/containers/inspect.go | 9 ++- cmd/podmanV2/containers/kill.go | 9 ++- cmd/podmanV2/containers/logs.go | 21 +++--- cmd/podmanV2/containers/mount.go | 11 ++- cmd/podmanV2/containers/pause.go | 11 ++- cmd/podmanV2/containers/ps.go | 11 ++- cmd/podmanV2/containers/restart.go | 9 ++- cmd/podmanV2/containers/rm.go | 9 ++- cmd/podmanV2/containers/run.go | 23 +++--- cmd/podmanV2/containers/start.go | 11 ++- cmd/podmanV2/containers/stop.go | 14 ++-- cmd/podmanV2/containers/top.go | 14 ++-- cmd/podmanV2/containers/unmount.go | 1 - cmd/podmanV2/containers/unpause.go | 9 ++- cmd/podmanV2/containers/wait.go | 11 ++- cmd/podmanV2/diff.go | 17 +---- cmd/podmanV2/healthcheck/healthcheck.go | 18 ++--- cmd/podmanV2/images/diff.go | 11 ++- cmd/podmanV2/images/history.go | 16 ++--- cmd/podmanV2/images/image.go | 20 ++---- cmd/podmanV2/images/images.go | 3 - cmd/podmanV2/images/import.go | 11 ++- cmd/podmanV2/images/load.go | 13 ++-- cmd/podmanV2/images/pull.go | 40 +++-------- cmd/podmanV2/images/push.go | 23 +++--- cmd/podmanV2/images/rm.go | 9 ++- cmd/podmanV2/images/rmi.go | 3 - cmd/podmanV2/images/save.go | 9 ++- cmd/podmanV2/images/search.go | 27 ++++---- cmd/podmanV2/images/tag.go | 13 ++-- cmd/podmanV2/images/untag.go | 2 - cmd/podmanV2/inspect.go | 14 +--- cmd/podmanV2/main.go | 40 ++++------- cmd/podmanV2/networks/network.go | 18 ++--- cmd/podmanV2/pods/pod.go | 18 ++--- cmd/podmanV2/pods/top.go | 14 ++-- cmd/podmanV2/registry/config.go | 43 ++++++------ cmd/podmanV2/registry/registry.go | 56 ++++----------- cmd/podmanV2/root.go | 119 +++++++++++++++++++++++--------- cmd/podmanV2/system/events.go | 11 ++- cmd/podmanV2/system/info.go | 1 - cmd/podmanV2/system/system.go | 18 ++--- cmd/podmanV2/system/varlink.go | 14 ++-- cmd/podmanV2/system/version.go | 12 ++-- cmd/podmanV2/volumes/volume.go | 18 ++--- 57 files changed, 400 insertions(+), 589 deletions(-) (limited to 'cmd') diff --git a/cmd/podmanV2/Makefile b/cmd/podmanV2/Makefile index c951cbdd9..8a924670a 100644 --- a/cmd/podmanV2/Makefile +++ b/cmd/podmanV2/Makefile @@ -1,7 +1,9 @@ all: podman podman-remote +BUILD_TAGS='ABISupport systemd varlink seccomp selinux exclude_graphdriver_devicemapper' + podman: - CGO_ENABLED=1 GO111MODULE=off go build -tags 'ABISupport systemd varlink seccomp selinux' + CGO_ENABLED=1 GO111MODULE=off go build -tags $(BUILD_TAGS) podman-remote: CGO_ENABLED=1 GO111MODULE=off go build -tags '!ABISupport systemd seccomp selinux' -o podmanV2-remote diff --git a/cmd/podmanV2/common/create.go b/cmd/podmanV2/common/create.go index ecaaf38fb..0b2f4532c 100644 --- a/cmd/podmanV2/common/create.go +++ b/cmd/podmanV2/common/create.go @@ -2,30 +2,15 @@ package common import ( "fmt" - "os" buildahcli "github.com/containers/buildah/pkg/cli" - "github.com/containers/common/pkg/config" - "github.com/sirupsen/logrus" + "github.com/containers/libpod/cmd/podmanV2/registry" "github.com/spf13/pflag" ) -const ( - sizeWithUnitFormat = "(format: `[]`, where unit = b (bytes), k (kilobytes), m (megabytes), or g (gigabytes))" -) - -var ( - defaultContainerConfig = getDefaultContainerConfig() -) +const sizeWithUnitFormat = "(format: `[]`, where unit = b (bytes), k (kilobytes), m (megabytes), or g (gigabytes))" -func getDefaultContainerConfig() *config.Config { - defaultContainerConfig, err := config.Default() - if err != nil { - logrus.Error(err) - os.Exit(1) - } - return defaultContainerConfig -} +var containerConfig = registry.NewPodmanConfig() func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { createFlags := pflag.FlagSet{} @@ -337,13 +322,13 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { "override-arch", "", "use `ARCH` instead of the architecture of the machine for choosing images", ) - //markFlagHidden(createFlags, "override-arch") + // markFlagHidden(createFlags, "override-arch") createFlags.StringVar( &cf.OverrideOS, "override-os", "", "use `OS` instead of the running OS for choosing images", ) - //markFlagHidden(createFlags, "override-os") + // markFlagHidden(createFlags, "override-os") createFlags.StringVar( &cf.PID, "pid", getDefaultPidNS(), @@ -407,7 +392,7 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { createFlags.StringArrayVar( &cf.SecurityOpt, "security-opt", getDefaultSecurityOptions(), - fmt.Sprintf("Security Options"), + "Security Options", ) createFlags.StringVar( &cf.ShmSize, @@ -421,7 +406,7 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { ) createFlags.UintVar( &cf.StopTimeout, - "stop-timeout", defaultContainerConfig.Engine.StopTimeout, + "stop-timeout", containerConfig.Engine.StopTimeout, "Timeout (in seconds) to stop a container. Default is 10", ) createFlags.StringSliceVar( @@ -513,7 +498,7 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { return &createFlags } -func AliasFlags(f *pflag.FlagSet, name string) pflag.NormalizedName { +func AliasFlags(_ *pflag.FlagSet, name string) pflag.NormalizedName { switch name { case "healthcheck-command": name = "health-cmd" diff --git a/cmd/podmanV2/common/default.go b/cmd/podmanV2/common/default.go index bd793f168..853f87ab6 100644 --- a/cmd/podmanV2/common/default.go +++ b/cmd/podmanV2/common/default.go @@ -8,6 +8,7 @@ import ( "github.com/containers/libpod/pkg/apparmor" "github.com/containers/libpod/pkg/cgroups" "github.com/containers/libpod/pkg/rootless" + "github.com/containers/libpod/pkg/specgen" "github.com/containers/libpod/pkg/sysinfo" "github.com/opencontainers/selinux/go-selinux" ) @@ -31,13 +32,13 @@ var ( // once we are "on" the host system. func getDefaultSecurityOptions() []string { securityOpts := []string{} - if defaultContainerConfig.Containers.SeccompProfile != "" && defaultContainerConfig.Containers.SeccompProfile != parse.SeccompDefaultPath { - securityOpts = append(securityOpts, fmt.Sprintf("seccomp=%s", defaultContainerConfig.Containers.SeccompProfile)) + if containerConfig.Containers.SeccompProfile != "" && containerConfig.Containers.SeccompProfile != parse.SeccompDefaultPath { + securityOpts = append(securityOpts, fmt.Sprintf("seccomp=%s", containerConfig.Containers.SeccompProfile)) } - if apparmor.IsEnabled() && defaultContainerConfig.Containers.ApparmorProfile != "" { - securityOpts = append(securityOpts, fmt.Sprintf("apparmor=%s", defaultContainerConfig.Containers.ApparmorProfile)) + if apparmor.IsEnabled() && containerConfig.Containers.ApparmorProfile != "" { + securityOpts = append(securityOpts, fmt.Sprintf("apparmor=%s", containerConfig.Containers.ApparmorProfile)) } - if selinux.GetEnabled() && !defaultContainerConfig.Containers.EnableLabeling { + if selinux.GetEnabled() && !containerConfig.Containers.EnableLabeling { securityOpts = append(securityOpts, fmt.Sprintf("label=%s", selinux.DisableSecOpt()[0])) } return securityOpts @@ -45,66 +46,66 @@ func getDefaultSecurityOptions() []string { // getDefaultSysctls func getDefaultSysctls() []string { - return defaultContainerConfig.Containers.DefaultSysctls + return containerConfig.Containers.DefaultSysctls } func getDefaultVolumes() []string { - return defaultContainerConfig.Containers.Volumes + return containerConfig.Containers.Volumes } func getDefaultDevices() []string { - return defaultContainerConfig.Containers.Devices + return containerConfig.Containers.Devices } func getDefaultDNSServers() []string { //nolint - return defaultContainerConfig.Containers.DNSServers + return containerConfig.Containers.DNSServers } func getDefaultDNSSearches() []string { //nolint - return defaultContainerConfig.Containers.DNSSearches + return containerConfig.Containers.DNSSearches } func getDefaultDNSOptions() []string { //nolint - return defaultContainerConfig.Containers.DNSOptions + return containerConfig.Containers.DNSOptions } func getDefaultEnv() []string { - return defaultContainerConfig.Containers.Env + return containerConfig.Containers.Env } func getDefaultInitPath() string { - return defaultContainerConfig.Containers.InitPath + return containerConfig.Containers.InitPath } func getDefaultIPCNS() string { - return defaultContainerConfig.Containers.IPCNS + return containerConfig.Containers.IPCNS } func getDefaultPidNS() string { - return defaultContainerConfig.Containers.PidNS + return containerConfig.Containers.PidNS } func getDefaultNetNS() string { //nolint - if defaultContainerConfig.Containers.NetNS == "private" && rootless.IsRootless() { - return "slirp4netns" + if containerConfig.Containers.NetNS == string(specgen.Private) && rootless.IsRootless() { + return string(specgen.Slirp) } - return defaultContainerConfig.Containers.NetNS + return containerConfig.Containers.NetNS } func getDefaultCgroupNS() string { - return defaultContainerConfig.Containers.CgroupNS + return containerConfig.Containers.CgroupNS } func getDefaultUTSNS() string { - return defaultContainerConfig.Containers.UTSNS + return containerConfig.Containers.UTSNS } func getDefaultShmSize() string { - return defaultContainerConfig.Containers.ShmSize + return containerConfig.Containers.ShmSize } func getDefaultUlimits() []string { - return defaultContainerConfig.Containers.DefaultUlimits + return containerConfig.Containers.DefaultUlimits } func getDefaultUserNS() string { @@ -112,14 +113,14 @@ func getDefaultUserNS() string { if userns != "" { return userns } - return defaultContainerConfig.Containers.UserNS + return containerConfig.Containers.UserNS } func getDefaultPidsLimit() int64 { if rootless.IsRootless() { cgroup2, _ := cgroups.IsCgroup2UnifiedMode() if cgroup2 { - return defaultContainerConfig.Containers.PidsLimit + return containerConfig.Containers.PidsLimit } } return sysinfo.GetDefaultPidsLimit() @@ -130,5 +131,5 @@ func getDefaultPidsDescription() string { } func GetDefaultDetachKeys() string { - return defaultContainerConfig.Engine.DetachKeys + return containerConfig.Engine.DetachKeys } diff --git a/cmd/podmanV2/common/netflags.go b/cmd/podmanV2/common/netflags.go index 758f155c8..41eed2988 100644 --- a/cmd/podmanV2/common/netflags.go +++ b/cmd/podmanV2/common/netflags.go @@ -4,18 +4,10 @@ import ( "net" "github.com/containers/libpod/pkg/domain/entities" - "github.com/containers/libpod/pkg/rootless" "github.com/spf13/cobra" "github.com/spf13/pflag" ) -func getDefaultNetwork() string { - if rootless.IsRootless() { - return "slirp4netns" - } - return "bridge" -} - func GetNetFlags() *pflag.FlagSet { netFlags := pflag.FlagSet{} netFlags.StringSlice( @@ -23,15 +15,15 @@ func GetNetFlags() *pflag.FlagSet { "Add a custom host-to-IP mapping (host:ip) (default [])", ) netFlags.StringSlice( - "dns", []string{}, + "dns", getDefaultDNSServers(), "Set custom DNS servers", ) netFlags.StringSlice( - "dns-opt", []string{}, + "dns-opt", getDefaultDNSOptions(), "Set custom DNS options", ) netFlags.StringSlice( - "dns-search", []string{}, + "dns-search", getDefaultDNSSearches(), "Set custom DNS search domains", ) netFlags.String( @@ -43,7 +35,7 @@ func GetNetFlags() *pflag.FlagSet { "Container MAC address (e.g. 92:d0:c6:0a:29:33)", ) netFlags.String( - "network", getDefaultNetwork(), + "network", getDefaultNetNS(), "Connect a container to a network", ) netFlags.StringSliceP( diff --git a/cmd/podmanV2/containers/attach.go b/cmd/podmanV2/containers/attach.go index d62dcff86..9b6de0051 100644 --- a/cmd/podmanV2/containers/attach.go +++ b/cmd/podmanV2/containers/attach.go @@ -23,7 +23,6 @@ var ( } return nil }, - PreRunE: preRunE, Example: `podman attach ctrID podman attach 1234 podman attach --no-stdin foobar`, diff --git a/cmd/podmanV2/containers/commit.go b/cmd/podmanV2/containers/commit.go index 28eb42f33..083fcbc6c 100644 --- a/cmd/podmanV2/containers/commit.go +++ b/cmd/podmanV2/containers/commit.go @@ -17,12 +17,11 @@ var ( commitDescription = `Create an image from a container's changes. Optionally tag the image created, set the author with the --author flag, set the commit message with the --message flag, and make changes to the instructions with the --change flag.` commitCommand = &cobra.Command{ - Use: "commit [flags] CONTAINER [IMAGE]", - Short: "Create new image based on the changed container", - Long: commitDescription, - RunE: commit, - PreRunE: preRunE, - Args: cobra.MinimumNArgs(1), + Use: "commit [flags] CONTAINER [IMAGE]", + Short: "Create new image based on the changed container", + Long: commitDescription, + RunE: commit, + Args: cobra.MinimumNArgs(1), Example: `podman commit -q --message "committing container to image" reverent_golick image-committed podman commit -q --author "firstName lastName" reverent_golick image-committed podman commit -q --pause=false containerID image-committed diff --git a/cmd/podmanV2/containers/container.go b/cmd/podmanV2/containers/container.go index b922eea05..30829991d 100644 --- a/cmd/podmanV2/containers/container.go +++ b/cmd/podmanV2/containers/container.go @@ -13,12 +13,11 @@ import ( var ( // Command: podman _container_ containerCmd = &cobra.Command{ - Use: "container", - Short: "Manage containers", - Long: "Manage containers", - TraverseChildren: true, - PersistentPreRunE: preRunE, - RunE: registry.SubCommandExists, + Use: "container", + Short: "Manage containers", + Long: "Manage containers", + TraverseChildren: true, + RunE: registry.SubCommandExists, } defaultContainerConfig = getDefaultContainerConfig() @@ -29,13 +28,6 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: containerCmd, }) - containerCmd.SetHelpTemplate(registry.HelpTemplate()) - containerCmd.SetUsageTemplate(registry.UsageTemplate()) -} - -func preRunE(cmd *cobra.Command, args []string) error { - _, err := registry.NewContainerEngine(cmd, args) - return err } func getDefaultContainerConfig() *config.Config { diff --git a/cmd/podmanV2/containers/create.go b/cmd/podmanV2/containers/create.go index 63daf1702..8cfb74539 100644 --- a/cmd/podmanV2/containers/create.go +++ b/cmd/podmanV2/containers/create.go @@ -17,12 +17,11 @@ var ( The container ID is then printed to stdout. You can then start it at any time with the podman start command. The container will be created with the initial state 'created'.` createCommand = &cobra.Command{ - Use: "create [flags] IMAGE [COMMAND [ARG...]]", - Short: "Create but do not start a container", - Long: createDescription, - RunE: create, - PersistentPreRunE: preRunE, - Args: cobra.MinimumNArgs(1), + Use: "create [flags] IMAGE [COMMAND [ARG...]]", + Short: "Create but do not start a container", + Long: createDescription, + RunE: create, + Args: cobra.MinimumNArgs(1), Example: `podman create alpine ls podman create --annotation HELLO=WORLD alpine ls podman create -t -i --name myctr alpine ls`, diff --git a/cmd/podmanV2/containers/diff.go b/cmd/podmanV2/containers/diff.go index 3009cdfad..eb76858f3 100644 --- a/cmd/podmanV2/containers/diff.go +++ b/cmd/podmanV2/containers/diff.go @@ -11,12 +11,11 @@ import ( var ( // podman container _diff_ diffCmd = &cobra.Command{ - Use: "diff [flags] CONTAINER", - Args: registry.IdOrLatestArgs, - Short: "Inspect changes on container's file systems", - Long: `Displays changes on a container filesystem. The container will be compared to its parent layer.`, - PreRunE: preRunE, - RunE: diff, + Use: "diff [flags] CONTAINER", + Args: registry.IdOrLatestArgs, + Short: "Inspect changes on container's file systems", + Long: `Displays changes on a container filesystem. The container will be compared to its parent layer.`, + RunE: diff, Example: `podman container diff myCtr podman container diff -l --format json myCtr`, } diff --git a/cmd/podmanV2/containers/exec.go b/cmd/podmanV2/containers/exec.go index 4bff57dbb..b4583909e 100644 --- a/cmd/podmanV2/containers/exec.go +++ b/cmd/podmanV2/containers/exec.go @@ -16,11 +16,10 @@ var ( execDescription = `Execute the specified command inside a running container. ` execCommand = &cobra.Command{ - Use: "exec [flags] CONTAINER [COMMAND [ARG...]]", - Short: "Run a process in a running container", - Long: execDescription, - PreRunE: preRunE, - RunE: exec, + Use: "exec [flags] CONTAINER [COMMAND [ARG...]]", + Short: "Run a process in a running container", + Long: execDescription, + RunE: exec, Example: `podman exec -it ctrID ls podman exec -it -w /tmp myCtr pwd podman exec --user root ctrID ls`, diff --git a/cmd/podmanV2/containers/export.go b/cmd/podmanV2/containers/export.go index b93b60878..a7befdae9 100644 --- a/cmd/podmanV2/containers/export.go +++ b/cmd/podmanV2/containers/export.go @@ -17,12 +17,11 @@ var ( " and saves it on the local machine." exportCommand = &cobra.Command{ - Use: "export [flags] CONTAINER", - Short: "Export container's filesystem contents as a tar archive", - Long: exportDescription, - PersistentPreRunE: preRunE, - RunE: export, - Args: cobra.ExactArgs(1), + Use: "export [flags] CONTAINER", + Short: "Export container's filesystem contents as a tar archive", + Long: exportDescription, + RunE: export, + Args: cobra.ExactArgs(1), Example: `podman export ctrID > myCtr.tar podman export --output="myCtr.tar" ctrID`, } @@ -37,8 +36,6 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: exportCommand, }) - exportCommand.SetHelpTemplate(registry.HelpTemplate()) - exportCommand.SetUsageTemplate(registry.UsageTemplate()) flags := exportCommand.Flags() flags.StringVarP(&exportOpts.Output, "output", "o", "", "Write to a specified file (default: stdout, which must be redirected)") } diff --git a/cmd/podmanV2/containers/init.go b/cmd/podmanV2/containers/init.go index dd1e1d21b..0060c8f09 100644 --- a/cmd/podmanV2/containers/init.go +++ b/cmd/podmanV2/containers/init.go @@ -14,11 +14,10 @@ var ( initDescription = `Initialize one or more containers, creating the OCI spec and mounts for inspection. Container names or IDs can be used.` initCommand = &cobra.Command{ - Use: "init [flags] CONTAINER [CONTAINER...]", - Short: "Initialize one or more containers", - Long: initDescription, - PreRunE: preRunE, - RunE: initContainer, + Use: "init [flags] CONTAINER [CONTAINER...]", + Short: "Initialize one or more containers", + Long: initDescription, + RunE: initContainer, Args: func(cmd *cobra.Command, args []string) error { return parse.CheckAllLatestAndCIDFile(cmd, args, false, false) }, diff --git a/cmd/podmanV2/containers/inspect.go b/cmd/podmanV2/containers/inspect.go index 3147426cb..e6d4cb6bc 100644 --- a/cmd/podmanV2/containers/inspect.go +++ b/cmd/podmanV2/containers/inspect.go @@ -18,11 +18,10 @@ import ( var ( // podman container _inspect_ inspectCmd = &cobra.Command{ - Use: "inspect [flags] CONTAINER", - Short: "Display the configuration of a container", - Long: `Displays the low-level information on a container identified by name or ID.`, - PreRunE: preRunE, - RunE: inspect, + Use: "inspect [flags] CONTAINER", + Short: "Display the configuration of a container", + Long: `Displays the low-level information on a container identified by name or ID.`, + RunE: inspect, Example: `podman container inspect myCtr podman container inspect -l --format '{{.Id}} {{.Config.Labels}}'`, } diff --git a/cmd/podmanV2/containers/kill.go b/cmd/podmanV2/containers/kill.go index 3155d1f34..e145fbc3f 100644 --- a/cmd/podmanV2/containers/kill.go +++ b/cmd/podmanV2/containers/kill.go @@ -16,11 +16,10 @@ import ( var ( killDescription = "The main process inside each container specified will be sent SIGKILL, or any signal specified with option --signal." killCommand = &cobra.Command{ - Use: "kill [flags] CONTAINER [CONTAINER...]", - Short: "Kill one or more running containers with a specific signal", - Long: killDescription, - RunE: kill, - PersistentPreRunE: preRunE, + Use: "kill [flags] CONTAINER [CONTAINER...]", + Short: "Kill one or more running containers with a specific signal", + Long: killDescription, + RunE: kill, Args: func(cmd *cobra.Command, args []string) error { return parse.CheckAllLatestAndCIDFile(cmd, args, false, false) }, diff --git a/cmd/podmanV2/containers/logs.go b/cmd/podmanV2/containers/logs.go index d1a179495..db549c03b 100644 --- a/cmd/podmanV2/containers/logs.go +++ b/cmd/podmanV2/containers/logs.go @@ -26,11 +26,10 @@ var ( This does not guarantee execution order when combined with podman run (i.e., your run may not have generated any logs at the time you execute podman logs). ` logsCommand = &cobra.Command{ - Use: "logs [flags] CONTAINER [CONTAINER...]", - Short: "Fetch the logs of one or more container", - Long: logsDescription, - RunE: logs, - PreRunE: preRunE, + Use: "logs [flags] CONTAINER [CONTAINER...]", + Short: "Fetch the logs of one or more container", + Long: logsDescription, + RunE: logs, Example: `podman logs ctrID podman logs --names ctrID1 ctrID2 podman logs --tail 2 mywebserver @@ -39,11 +38,10 @@ var ( } containerLogsCommand = &cobra.Command{ - Use: logsCommand.Use, - Short: logsCommand.Short, - Long: logsCommand.Long, - PreRunE: logsCommand.PreRunE, - RunE: logsCommand.RunE, + Use: logsCommand.Use, + Short: logsCommand.Short, + Long: logsCommand.Long, + RunE: logsCommand.RunE, Example: `podman container logs ctrID podman container logs --names ctrID1 ctrID2 podman container logs --tail 2 mywebserver @@ -59,9 +57,6 @@ func init() { Command: logsCommand, }) - logsCommand.SetHelpTemplate(registry.HelpTemplate()) - logsCommand.SetUsageTemplate(registry.UsageTemplate()) - flags := logsCommand.Flags() logsFlags(flags) diff --git a/cmd/podmanV2/containers/mount.go b/cmd/podmanV2/containers/mount.go index 4f7b95d98..dbd83de57 100644 --- a/cmd/podmanV2/containers/mount.go +++ b/cmd/podmanV2/containers/mount.go @@ -23,16 +23,15 @@ var ( ` mountCommand = &cobra.Command{ - Use: "mount [flags] [CONTAINER]", - Short: "Mount a working container's root filesystem", - Long: mountDescription, - PreRunE: preRunE, - RunE: mount, + Use: "mount [flags] [CONTAINER]", + Short: "Mount a working container's root filesystem", + Long: mountDescription, + RunE: mount, Args: func(cmd *cobra.Command, args []string) error { return parse.CheckAllLatestAndCIDFile(cmd, args, true, false) }, Annotations: map[string]string{ - registry.RootRequired: "true", + registry.ParentNSRequired: "", }, } ) diff --git a/cmd/podmanV2/containers/pause.go b/cmd/podmanV2/containers/pause.go index a9b91b68f..d5493167c 100644 --- a/cmd/podmanV2/containers/pause.go +++ b/cmd/podmanV2/containers/pause.go @@ -15,11 +15,10 @@ import ( var ( pauseDescription = `Pauses one or more running containers. The container name or ID can be used.` pauseCommand = &cobra.Command{ - Use: "pause [flags] CONTAINER [CONTAINER...]", - Short: "Pause all the processes in one or more containers", - Long: pauseDescription, - RunE: pause, - PersistentPreRunE: preRunE, + Use: "pause [flags] CONTAINER [CONTAINER...]", + Short: "Pause all the processes in one or more containers", + Long: pauseDescription, + RunE: pause, Example: `podman pause mywebserver podman pause 860a4b23 podman pause -a`, @@ -35,8 +34,6 @@ func init() { }) flags := pauseCommand.Flags() flags.BoolVarP(&pauseOpts.All, "all", "a", false, "Pause all running containers") - pauseCommand.SetHelpTemplate(registry.HelpTemplate()) - pauseCommand.SetUsageTemplate(registry.UsageTemplate()) } func pause(cmd *cobra.Command, args []string) error { diff --git a/cmd/podmanV2/containers/ps.go b/cmd/podmanV2/containers/ps.go index 8ebbf6ebf..355b1b4be 100644 --- a/cmd/podmanV2/containers/ps.go +++ b/cmd/podmanV2/containers/ps.go @@ -24,12 +24,11 @@ import ( var ( psDescription = "Prints out information about the containers" psCommand = &cobra.Command{ - Use: "ps", - Args: checkFlags, - Short: "List containers", - Long: psDescription, - RunE: ps, - PreRunE: preRunE, + Use: "ps", + Args: checkFlags, + Short: "List containers", + Long: psDescription, + RunE: ps, Example: `podman ps -a podman ps -a --format "{{.ID}} {{.Image}} {{.Labels}} {{.Mounts}}" podman ps --size --sort names`, diff --git a/cmd/podmanV2/containers/restart.go b/cmd/podmanV2/containers/restart.go index 5f1d3fe51..becc56616 100644 --- a/cmd/podmanV2/containers/restart.go +++ b/cmd/podmanV2/containers/restart.go @@ -19,11 +19,10 @@ var ( A timeout before forcibly stopping can be set, but defaults to %d seconds.`, defaultContainerConfig.Engine.StopTimeout) restartCommand = &cobra.Command{ - Use: "restart [flags] CONTAINER [CONTAINER...]", - Short: "Restart one or more containers", - Long: restartDescription, - RunE: restart, - PersistentPreRunE: preRunE, + Use: "restart [flags] CONTAINER [CONTAINER...]", + Short: "Restart one or more containers", + Long: restartDescription, + RunE: restart, Args: func(cmd *cobra.Command, args []string) error { return parse.CheckAllLatestAndCIDFile(cmd, args, false, false) }, diff --git a/cmd/podmanV2/containers/rm.go b/cmd/podmanV2/containers/rm.go index 75655e4cd..916dd2577 100644 --- a/cmd/podmanV2/containers/rm.go +++ b/cmd/podmanV2/containers/rm.go @@ -19,11 +19,10 @@ var ( Command does not remove images. Running or unusable containers will not be removed without the -f option.` rmCommand = &cobra.Command{ - Use: "rm [flags] CONTAINER [CONTAINER...]", - Short: "Remove one or more containers", - Long: rmDescription, - RunE: rm, - PersistentPreRunE: preRunE, + Use: "rm [flags] CONTAINER [CONTAINER...]", + Short: "Remove one or more containers", + Long: rmDescription, + RunE: rm, Args: func(cmd *cobra.Command, args []string) error { return parse.CheckAllLatestAndCIDFile(cmd, args, false, true) }, diff --git a/cmd/podmanV2/containers/run.go b/cmd/podmanV2/containers/run.go index 0bf0f90f8..ca9db88f8 100644 --- a/cmd/podmanV2/containers/run.go +++ b/cmd/podmanV2/containers/run.go @@ -19,11 +19,10 @@ import ( var ( runDescription = "Runs a command in a new container from the given image" runCommand = &cobra.Command{ - Use: "run [flags] IMAGE [COMMAND [ARG...]]", - Short: "Run a command in a new container", - Long: runDescription, - PreRunE: preRunE, - RunE: run, + Use: "run [flags] IMAGE [COMMAND [ARG...]]", + Short: "Run a command in a new container", + Long: runDescription, + RunE: run, Example: `podman run imageID ls -alF /etc podman run --network=host imageID dnf -y install java podman run --volume /var/hostdir:/var/ctrdir -i -t fedora /bin/bash`, @@ -57,13 +56,12 @@ func init() { } func run(cmd *cobra.Command, args []string) error { - var ( - err error - ) + var err error cliVals.Net, err = common.NetFlagsToNetOptions(cmd) if err != nil { return err } + if af := cliVals.Authfile; len(af) > 0 { if _, err := os.Stat(af); err != nil { return errors.Wrapf(err, "error checking authfile path %s", af) @@ -74,11 +72,7 @@ func run(cmd *cobra.Command, args []string) error { return err } - ie, err := registry.NewImageEngine(cmd, args) - if err != nil { - return err - } - br, err := ie.Exists(registry.GetContext(), args[0]) + br, err := registry.ImageEngine().Exists(registry.GetContext(), args[0]) if err != nil { return err } @@ -90,7 +84,7 @@ func run(cmd *cobra.Command, args []string) error { if pullPolicy == config.PullImageNever { return errors.New("unable to find a name and tag match for busybox in repotags: no such image") } - _, pullErr := ie.Pull(registry.GetContext(), args[0], entities.ImagePullOptions{ + _, pullErr := registry.ImageEngine().Pull(registry.GetContext(), args[0], entities.ImagePullOptions{ Authfile: cliVals.Authfile, Quiet: cliVals.Quiet, }) @@ -131,6 +125,7 @@ func run(cmd *cobra.Command, args []string) error { return err } runOpts.Spec = s + report, err := registry.ContainerEngine().ContainerRun(registry.GetContext(), runOpts) // report.ExitCode is set by ContainerRun even it it returns an error if report != nil { diff --git a/cmd/podmanV2/containers/start.go b/cmd/podmanV2/containers/start.go index 0ae2f6d50..b5ed6d6f6 100644 --- a/cmd/podmanV2/containers/start.go +++ b/cmd/podmanV2/containers/start.go @@ -16,12 +16,11 @@ import ( var ( startDescription = `Starts one or more containers. The container name or ID can be used.` startCommand = &cobra.Command{ - Use: "start [flags] CONTAINER [CONTAINER...]", - Short: "Start one or more containers", - Long: startDescription, - RunE: start, - PreRunE: preRunE, - Args: cobra.MinimumNArgs(1), + Use: "start [flags] CONTAINER [CONTAINER...]", + Short: "Start one or more containers", + Long: startDescription, + RunE: start, + Args: cobra.MinimumNArgs(1), Example: `podman start --latest podman start 860a4b231279 5421ab43b45 podman start --interactive --attach imageID`, diff --git a/cmd/podmanV2/containers/stop.go b/cmd/podmanV2/containers/stop.go index 53ec2934d..d94df69be 100644 --- a/cmd/podmanV2/containers/stop.go +++ b/cmd/podmanV2/containers/stop.go @@ -16,11 +16,10 @@ var ( A timeout to forcibly stop the container can also be set but defaults to %d seconds otherwise.`, defaultContainerConfig.Engine.StopTimeout) stopCommand = &cobra.Command{ - Use: "stop [flags] CONTAINER [CONTAINER...]", - Short: "Stop one or more containers", - Long: stopDescription, - RunE: stop, - PersistentPreRunE: preRunE, + Use: "stop [flags] CONTAINER [CONTAINER...]", + Short: "Stop one or more containers", + Long: stopDescription, + RunE: stop, Args: func(cmd *cobra.Command, args []string) error { return parse.CheckAllLatestAndCIDFile(cmd, args, false, true) }, @@ -63,11 +62,6 @@ func stop(cmd *cobra.Command, args []string) error { stopOptions.Timeout = stopTimeout } - // TODO How do we access global attributes? - //if c.Bool("trace") { - // span, _ := opentracing.StartSpanFromContext(Ctx, "stopCmd") - // defer span.Finish() - //} responses, err := registry.ContainerEngine().ContainerStop(context.Background(), args, stopOptions) if err != nil { return err diff --git a/cmd/podmanV2/containers/top.go b/cmd/podmanV2/containers/top.go index a86c12e2a..233085e75 100644 --- a/cmd/podmanV2/containers/top.go +++ b/cmd/podmanV2/containers/top.go @@ -26,12 +26,11 @@ var ( topOptions = entities.TopOptions{} topCommand = &cobra.Command{ - Use: "top [flags] CONTAINER [FORMAT-DESCRIPTORS|ARGS]", - Short: "Display the running processes of a container", - Long: topDescription, - PersistentPreRunE: preRunE, - RunE: top, - Args: cobra.ArbitraryArgs, + Use: "top [flags] CONTAINER [FORMAT-DESCRIPTORS|ARGS]", + Short: "Display the running processes of a container", + Long: topDescription, + RunE: top, + Args: cobra.ArbitraryArgs, Example: `podman top ctrID podman top --latest podman top ctrID pid seccomp args %C @@ -45,9 +44,6 @@ func init() { Command: topCommand, }) - topCommand.SetHelpTemplate(registry.HelpTemplate()) - topCommand.SetUsageTemplate(registry.UsageTemplate()) - flags := topCommand.Flags() flags.SetInterspersed(false) flags.BoolVar(&topOptions.ListDescriptors, "list-descriptors", false, "") diff --git a/cmd/podmanV2/containers/unmount.go b/cmd/podmanV2/containers/unmount.go index 2a6ef14b0..ef6add950 100644 --- a/cmd/podmanV2/containers/unmount.go +++ b/cmd/podmanV2/containers/unmount.go @@ -23,7 +23,6 @@ var ( Short: "Unmounts working container's root filesystem", Long: description, RunE: unmount, - PreRunE: preRunE, Args: func(cmd *cobra.Command, args []string) error { return parse.CheckAllLatestAndCIDFile(cmd, args, false, false) }, diff --git a/cmd/podmanV2/containers/unpause.go b/cmd/podmanV2/containers/unpause.go index 6a3179f10..8b8cde9b2 100644 --- a/cmd/podmanV2/containers/unpause.go +++ b/cmd/podmanV2/containers/unpause.go @@ -15,11 +15,10 @@ import ( var ( unpauseDescription = `Unpauses one or more previously paused containers. The container name or ID can be used.` unpauseCommand = &cobra.Command{ - Use: "unpause [flags] CONTAINER [CONTAINER...]", - Short: "Unpause the processes in one or more containers", - Long: unpauseDescription, - RunE: unpause, - PersistentPreRunE: preRunE, + Use: "unpause [flags] CONTAINER [CONTAINER...]", + Short: "Unpause the processes in one or more containers", + Long: unpauseDescription, + RunE: unpause, Example: `podman unpause ctrID podman unpause --all`, } diff --git a/cmd/podmanV2/containers/wait.go b/cmd/podmanV2/containers/wait.go index 3d11c581e..0a165317b 100644 --- a/cmd/podmanV2/containers/wait.go +++ b/cmd/podmanV2/containers/wait.go @@ -17,12 +17,11 @@ var ( waitDescription = `Block until one or more containers stop and then print their exit codes. ` waitCommand = &cobra.Command{ - Use: "wait [flags] CONTAINER [CONTAINER...]", - Short: "Block on one or more containers", - Long: waitDescription, - RunE: wait, - PersistentPreRunE: preRunE, - Args: registry.IdOrLatestArgs, + Use: "wait [flags] CONTAINER [CONTAINER...]", + Short: "Block on one or more containers", + Long: waitDescription, + RunE: wait, + Args: registry.IdOrLatestArgs, Example: `podman wait --latest podman wait --interval 5000 ctrID podman wait ctrID1 ctrID2`, diff --git a/cmd/podmanV2/diff.go b/cmd/podmanV2/diff.go index 6e4263370..73f4661db 100644 --- a/cmd/podmanV2/diff.go +++ b/cmd/podmanV2/diff.go @@ -35,9 +35,6 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: diffCmd, }) - diffCmd.SetHelpTemplate(registry.HelpTemplate()) - diffCmd.SetUsageTemplate(registry.UsageTemplate()) - flags := diffCmd.Flags() flags.BoolVar(&diffOpts.Archive, "archive", true, "Save the diff as a tar archive") _ = flags.MarkHidden("archive") @@ -49,23 +46,13 @@ func init() { } func diff(cmd *cobra.Command, args []string) error { - ie, err := registry.NewImageEngine(cmd, args) - if err != nil { - return err - } - - if found, err := ie.Exists(registry.GetContext(), args[0]); err != nil { + if found, err := registry.ImageEngine().Exists(registry.GetContext(), args[0]); err != nil { return err } else if found.Value { return images.Diff(cmd, args, diffOpts) } - ce, err := registry.NewContainerEngine(cmd, args) - if err != nil { - return err - } - - if found, err := ce.ContainerExists(registry.GetContext(), args[0]); err != nil { + if found, err := registry.ContainerEngine().ContainerExists(registry.GetContext(), args[0]); err != nil { return err } else if found.Value { return containers.Diff(cmd, args, diffOpts) diff --git a/cmd/podmanV2/healthcheck/healthcheck.go b/cmd/podmanV2/healthcheck/healthcheck.go index 2af398ff0..e859f9463 100644 --- a/cmd/podmanV2/healthcheck/healthcheck.go +++ b/cmd/podmanV2/healthcheck/healthcheck.go @@ -9,12 +9,11 @@ import ( var ( // Command: healthcheck healthCmd = &cobra.Command{ - Use: "healthcheck", - Short: "Manage Healthcheck", - Long: "Manage Healthcheck", - TraverseChildren: true, - PersistentPreRunE: preRunE, - RunE: registry.SubCommandExists, + Use: "healthcheck", + Short: "Manage Healthcheck", + Long: "Manage Healthcheck", + TraverseChildren: true, + RunE: registry.SubCommandExists, } ) @@ -23,11 +22,4 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: healthCmd, }) - healthCmd.SetHelpTemplate(registry.HelpTemplate()) - healthCmd.SetUsageTemplate(registry.UsageTemplate()) -} - -func preRunE(cmd *cobra.Command, args []string) error { - _, err := registry.NewContainerEngine(cmd, args) - return err } diff --git a/cmd/podmanV2/images/diff.go b/cmd/podmanV2/images/diff.go index e913a603a..b54cb39a8 100644 --- a/cmd/podmanV2/images/diff.go +++ b/cmd/podmanV2/images/diff.go @@ -11,12 +11,11 @@ import ( var ( // podman container _inspect_ diffCmd = &cobra.Command{ - Use: "diff [flags] CONTAINER", - Args: registry.IdOrLatestArgs, - Short: "Inspect changes on image's file systems", - Long: `Displays changes on a image's filesystem. The image will be compared to its parent layer.`, - PreRunE: preRunE, - RunE: diff, + Use: "diff [flags] CONTAINER", + Args: registry.IdOrLatestArgs, + Short: "Inspect changes on image's file systems", + Long: `Displays changes on a image's filesystem. The image will be compared to its parent layer.`, + RunE: diff, Example: `podman image diff myImage podman image diff --format json redis:alpine`, } diff --git a/cmd/podmanV2/images/history.go b/cmd/podmanV2/images/history.go index e3bb7a051..d2e880ef7 100644 --- a/cmd/podmanV2/images/history.go +++ b/cmd/podmanV2/images/history.go @@ -25,13 +25,12 @@ var ( // podman _history_ historyCmd = &cobra.Command{ - Use: "history [flags] IMAGE", - Short: "Show history of a specified image", - Long: long, - Example: "podman history quay.io/fedora/fedora", - Args: cobra.ExactArgs(1), - PersistentPreRunE: preRunE, - RunE: history, + Use: "history [flags] IMAGE", + Short: "Show history of a specified image", + Long: long, + Example: "podman history quay.io/fedora/fedora", + Args: cobra.ExactArgs(1), + RunE: history, } opts = struct { @@ -48,9 +47,6 @@ func init() { Command: historyCmd, }) - historyCmd.SetHelpTemplate(registry.HelpTemplate()) - historyCmd.SetUsageTemplate(registry.UsageTemplate()) - flags := historyCmd.Flags() flags.StringVar(&opts.format, "format", "", "Change the output to JSON or a Go template") flags.BoolVarP(&opts.human, "human", "H", true, "Display sizes and dates in human readable format") diff --git a/cmd/podmanV2/images/image.go b/cmd/podmanV2/images/image.go index 9fc7b21d1..7b469bc59 100644 --- a/cmd/podmanV2/images/image.go +++ b/cmd/podmanV2/images/image.go @@ -9,12 +9,11 @@ import ( var ( // Command: podman _image_ imageCmd = &cobra.Command{ - Use: "image", - Short: "Manage images", - Long: "Manage images", - TraverseChildren: true, - PersistentPreRunE: preRunE, - RunE: registry.SubCommandExists, + Use: "image", + Short: "Manage images", + Long: "Manage images", + TraverseChildren: true, + RunE: registry.SubCommandExists, } ) @@ -23,13 +22,4 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: imageCmd, }) - imageCmd.SetHelpTemplate(registry.HelpTemplate()) - imageCmd.SetUsageTemplate(registry.UsageTemplate()) -} - -func preRunE(cmd *cobra.Command, args []string) error { - if _, err := registry.NewImageEngine(cmd, args); err != nil { - return err - } - return nil } diff --git a/cmd/podmanV2/images/images.go b/cmd/podmanV2/images/images.go index d00f0996e..588369a7e 100644 --- a/cmd/podmanV2/images/images.go +++ b/cmd/podmanV2/images/images.go @@ -15,7 +15,6 @@ var ( Args: listCmd.Args, Short: listCmd.Short, Long: listCmd.Long, - PreRunE: preRunE, RunE: listCmd.RunE, Example: strings.Replace(listCmd.Example, "podman image list", "podman images", -1), } @@ -26,8 +25,6 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: imagesCmd, }) - imagesCmd.SetHelpTemplate(registry.HelpTemplate()) - imagesCmd.SetUsageTemplate(registry.UsageTemplate()) imageListFlagSet(imagesCmd.Flags()) } diff --git a/cmd/podmanV2/images/import.go b/cmd/podmanV2/images/import.go index 09a15585f..c86db34bf 100644 --- a/cmd/podmanV2/images/import.go +++ b/cmd/podmanV2/images/import.go @@ -18,11 +18,10 @@ var ( Note remote tar balls can be specified, via web address. Optionally tag the image. You can specify the instructions using the --change option.` importCommand = &cobra.Command{ - Use: "import [flags] PATH [REFERENCE]", - Short: "Import a tarball to create a filesystem image", - Long: importDescription, - RunE: importCon, - PersistentPreRunE: preRunE, + Use: "import [flags] PATH [REFERENCE]", + Short: "Import a tarball to create a filesystem image", + Long: importDescription, + RunE: importCon, Example: `podman import http://example.com/ctr.tar url-image cat ctr.tar | podman -q import --message "importing the ctr.tar tarball" - image-imported cat ctr.tar | podman import -`, @@ -39,8 +38,6 @@ func init() { Command: importCommand, }) - importCommand.SetHelpTemplate(registry.HelpTemplate()) - importCommand.SetUsageTemplate(registry.UsageTemplate()) flags := importCommand.Flags() flags.StringArrayVarP(&importOpts.Changes, "change", "c", []string{}, "Apply the following possible instructions to the created image (default []): CMD | ENTRYPOINT | ENV | EXPOSE | LABEL | STOPSIGNAL | USER | VOLUME | WORKDIR") flags.StringVarP(&importOpts.Message, "message", "m", "", "Set commit message for imported image") diff --git a/cmd/podmanV2/images/load.go b/cmd/podmanV2/images/load.go index 315dbed3a..004daa288 100644 --- a/cmd/podmanV2/images/load.go +++ b/cmd/podmanV2/images/load.go @@ -20,12 +20,11 @@ import ( var ( loadDescription = "Loads an image from a locally stored archive (tar file) into container storage." loadCommand = &cobra.Command{ - Use: "load [flags] [NAME[:TAG]]", - Short: "Load an image from container archive", - Long: loadDescription, - RunE: load, - Args: cobra.MaximumNArgs(1), - PersistentPreRunE: preRunE, + Use: "load [flags] [NAME[:TAG]]", + Short: "Load an image from container archive", + Long: loadDescription, + RunE: load, + Args: cobra.MaximumNArgs(1), } ) @@ -39,8 +38,6 @@ func init() { Command: loadCommand, }) - loadCommand.SetHelpTemplate(registry.HelpTemplate()) - loadCommand.SetUsageTemplate(registry.UsageTemplate()) flags := loadCommand.Flags() flags.StringVarP(&loadOpts.Input, "input", "i", "", "Read from specified archive file (default: stdin)") flags.BoolVarP(&loadOpts.Quiet, "quiet", "q", false, "Suppress the output") diff --git a/cmd/podmanV2/images/pull.go b/cmd/podmanV2/images/pull.go index c7e325409..74090dee4 100644 --- a/cmd/podmanV2/images/pull.go +++ b/cmd/podmanV2/images/pull.go @@ -7,8 +7,6 @@ import ( "github.com/containers/image/v5/types" "github.com/containers/libpod/cmd/podmanV2/registry" "github.com/containers/libpod/pkg/domain/entities" - "github.com/opentracing/opentracing-go" - "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/spf13/pflag" ) @@ -28,11 +26,11 @@ var ( // Command: podman pull pullCmd = &cobra.Command{ - Use: "pull [flags] IMAGE", - Short: "Pull an image from a registry", - Long: pullDescription, - PreRunE: preRunE, - RunE: imagePull, + Use: "pull [flags] IMAGE", + Args: cobra.ExactArgs(1), + Short: "Pull an image from a registry", + Long: pullDescription, + RunE: imagePull, Example: `podman pull imageName podman pull fedora:latest`, } @@ -41,11 +39,10 @@ var ( // It's basically a clone of `pullCmd` with the exception of being a // child of the images command. imagesPullCmd = &cobra.Command{ - Use: pullCmd.Use, - Short: pullCmd.Short, - Long: pullCmd.Long, - PreRunE: pullCmd.PreRunE, - RunE: pullCmd.RunE, + Use: pullCmd.Use, + Short: pullCmd.Short, + Long: pullCmd.Long, + RunE: pullCmd.RunE, Example: `podman image pull imageName podman image pull fedora:latest`, } @@ -58,9 +55,6 @@ func init() { Command: pullCmd, }) - pullCmd.SetHelpTemplate(registry.HelpTemplate()) - pullCmd.SetUsageTemplate(registry.UsageTemplate()) - flags := pullCmd.Flags() pullFlags(flags) @@ -71,8 +65,6 @@ func init() { Parent: imageCmd, }) - imagesPullCmd.SetHelpTemplate(registry.HelpTemplate()) - imagesPullCmd.SetUsageTemplate(registry.UsageTemplate()) imagesPullFlags := imagesPullCmd.Flags() pullFlags(imagesPullFlags) } @@ -99,20 +91,6 @@ func pullFlags(flags *pflag.FlagSet) { // imagePull is implement the command for pulling images. func imagePull(cmd *cobra.Command, args []string) error { - // Sanity check input. - if len(args) == 0 { - return errors.Errorf("an image name must be specified") - } - if len(args) > 1 { - return errors.Errorf("too many arguments. Requires exactly 1") - } - - // Start tracing if requested. - if cmd.Flags().Changed("trace") { - span, _ := opentracing.StartSpanFromContext(registry.GetContext(), "pullCmd") - defer span.Finish() - } - pullOptsAPI := pullOptions.ImagePullOptions // TLS verification in c/image is controlled via a `types.OptionalBool` // which allows for distinguishing among set-true, set-false, unspecified diff --git a/cmd/podmanV2/images/push.go b/cmd/podmanV2/images/push.go index 82cc0c486..51a60664b 100644 --- a/cmd/podmanV2/images/push.go +++ b/cmd/podmanV2/images/push.go @@ -25,11 +25,10 @@ var ( // Command: podman push pushCmd = &cobra.Command{ - Use: "push [flags] SOURCE DESTINATION", - Short: "Push an image to a specified destination", - Long: pushDescription, - PreRunE: preRunE, - RunE: imagePush, + Use: "push [flags] SOURCE DESTINATION", + Short: "Push an image to a specified destination", + Long: pushDescription, + RunE: imagePush, Example: `podman push imageID docker://registry.example.com/repository:tag podman push imageID oci-archive:/path/to/layout:image:tag`, } @@ -38,11 +37,10 @@ var ( // It's basically a clone of `pushCmd` with the exception of being a // child of the images command. imagePushCmd = &cobra.Command{ - Use: pushCmd.Use, - Short: pushCmd.Short, - Long: pushCmd.Long, - PreRunE: pushCmd.PreRunE, - RunE: pushCmd.RunE, + Use: pushCmd.Use, + Short: pushCmd.Short, + Long: pushCmd.Long, + RunE: pushCmd.RunE, Example: `podman image push imageID docker://registry.example.com/repository:tag podman image push imageID oci-archive:/path/to/layout:image:tag`, } @@ -55,9 +53,6 @@ func init() { Command: pushCmd, }) - pushCmd.SetHelpTemplate(registry.HelpTemplate()) - pushCmd.SetUsageTemplate(registry.UsageTemplate()) - flags := pushCmd.Flags() pushFlags(flags) @@ -68,8 +63,6 @@ func init() { Parent: imageCmd, }) - imagePushCmd.SetHelpTemplate(registry.HelpTemplate()) - imagePushCmd.SetUsageTemplate(registry.UsageTemplate()) pushFlags(imagePushCmd.Flags()) } diff --git a/cmd/podmanV2/images/rm.go b/cmd/podmanV2/images/rm.go index 6784182d9..f93d6ed50 100644 --- a/cmd/podmanV2/images/rm.go +++ b/cmd/podmanV2/images/rm.go @@ -14,11 +14,10 @@ import ( var ( rmDescription = "Removes one or more previously pulled or locally created images." rmCmd = &cobra.Command{ - Use: "rm [flags] IMAGE [IMAGE...]", - Short: "Removes one or more images from local storage", - Long: rmDescription, - PreRunE: preRunE, - RunE: rm, + Use: "rm [flags] IMAGE [IMAGE...]", + Short: "Removes one or more images from local storage", + Long: rmDescription, + RunE: rm, Example: `podman image rm imageID podman image rm --force alpine podman image rm c4dfb1609ee2 93fd78260bd1 c0ed59d05ff7`, diff --git a/cmd/podmanV2/images/rmi.go b/cmd/podmanV2/images/rmi.go index 973763966..ae199b789 100644 --- a/cmd/podmanV2/images/rmi.go +++ b/cmd/podmanV2/images/rmi.go @@ -14,7 +14,6 @@ var ( Args: rmCmd.Args, Short: rmCmd.Short, Long: rmCmd.Long, - PreRunE: rmCmd.PreRunE, RunE: rmCmd.RunE, Example: strings.Replace(rmCmd.Example, "podman image rm", "podman rmi", -1), } @@ -25,7 +24,5 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: rmiCmd, }) - rmiCmd.SetHelpTemplate(registry.HelpTemplate()) - rmiCmd.SetUsageTemplate(registry.UsageTemplate()) imageRemoveFlagSet(rmiCmd.Flags()) } diff --git a/cmd/podmanV2/images/save.go b/cmd/podmanV2/images/save.go index ae39b7bce..29ee79392 100644 --- a/cmd/podmanV2/images/save.go +++ b/cmd/podmanV2/images/save.go @@ -22,11 +22,10 @@ var ( saveDescription = `Save an image to docker-archive or oci-archive on the local machine. Default is docker-archive.` saveCommand = &cobra.Command{ - Use: "save [flags] IMAGE", - Short: "Save image to an archive", - Long: saveDescription, - PersistentPreRunE: preRunE, - RunE: save, + Use: "save [flags] IMAGE", + Short: "Save image to an archive", + Long: saveDescription, + RunE: save, Args: func(cmd *cobra.Command, args []string) error { if len(args) == 0 { return errors.Errorf("need at least 1 argument") diff --git a/cmd/podmanV2/images/search.go b/cmd/podmanV2/images/search.go index 2ab9735ec..17c72784c 100644 --- a/cmd/podmanV2/images/search.go +++ b/cmd/podmanV2/images/search.go @@ -32,12 +32,14 @@ var ( // Command: podman search searchCmd = &cobra.Command{ - Use: "search [flags] TERM", - Short: "Search registry for image", - Long: searchDescription, - PreRunE: preRunE, - RunE: imageSearch, - Args: cobra.ExactArgs(1), + Use: "search [flags] TERM", + Short: "Search registry for image", + Long: searchDescription, + RunE: imageSearch, + Args: cobra.ExactArgs(1), + Annotations: map[string]string{ + registry.ParentNSRequired: "", + }, Example: `podman search --filter=is-official --limit 3 alpine podman search registry.fedoraproject.org/ # only works with v2 registries podman search --format "table {{.Index}} {{.Name}}" registry.fedoraproject.org/fedora`, @@ -45,12 +47,11 @@ var ( // Command: podman image search imageSearchCmd = &cobra.Command{ - Use: searchCmd.Use, - Short: searchCmd.Short, - Long: searchCmd.Long, - PreRunE: searchCmd.PreRunE, - RunE: searchCmd.RunE, - Args: searchCmd.Args, + Use: searchCmd.Use, + Short: searchCmd.Short, + Long: searchCmd.Long, + RunE: searchCmd.RunE, + Args: searchCmd.Args, Example: `podman image search --filter=is-official --limit 3 alpine podman image search registry.fedoraproject.org/ # only works with v2 registries podman image search --format "table {{.Index}} {{.Name}}" registry.fedoraproject.org/fedora`, @@ -64,8 +65,6 @@ func init() { Command: searchCmd, }) - searchCmd.SetHelpTemplate(registry.HelpTemplate()) - searchCmd.SetUsageTemplate(registry.UsageTemplate()) flags := searchCmd.Flags() searchFlags(flags) diff --git a/cmd/podmanV2/images/tag.go b/cmd/podmanV2/images/tag.go index f8799d4a7..bf3cf0de6 100644 --- a/cmd/podmanV2/images/tag.go +++ b/cmd/podmanV2/images/tag.go @@ -9,12 +9,11 @@ import ( var ( tagDescription = "Adds one or more additional names to locally-stored image." tagCommand = &cobra.Command{ - Use: "tag [flags] IMAGE TARGET_NAME [TARGET_NAME...]", - Short: "Add an additional name to a local image", - Long: tagDescription, - RunE: tag, - PreRunE: preRunE, - Args: cobra.MinimumNArgs(2), + Use: "tag [flags] IMAGE TARGET_NAME [TARGET_NAME...]", + Short: "Add an additional name to a local image", + Long: tagDescription, + RunE: tag, + Args: cobra.MinimumNArgs(2), Example: `podman tag 0e3bbc2 fedora:latest podman tag imageID:latest myNewImage:newTag podman tag httpd myregistryhost:5000/fedora/httpd:v2`, @@ -26,8 +25,6 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: tagCommand, }) - tagCommand.SetHelpTemplate(registry.HelpTemplate()) - tagCommand.SetUsageTemplate(registry.UsageTemplate()) } func tag(cmd *cobra.Command, args []string) error { diff --git a/cmd/podmanV2/images/untag.go b/cmd/podmanV2/images/untag.go index c84827bb3..5eca1cb78 100644 --- a/cmd/podmanV2/images/untag.go +++ b/cmd/podmanV2/images/untag.go @@ -24,8 +24,6 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: untagCommand, }) - untagCommand.SetHelpTemplate(registry.HelpTemplate()) - untagCommand.SetUsageTemplate(registry.UsageTemplate()) } func untag(cmd *cobra.Command, args []string) error { diff --git a/cmd/podmanV2/inspect.go b/cmd/podmanV2/inspect.go index 15d7579ea..25024d6f8 100644 --- a/cmd/podmanV2/inspect.go +++ b/cmd/podmanV2/inspect.go @@ -37,23 +37,13 @@ func init() { } func inspect(cmd *cobra.Command, args []string) error { - ie, err := registry.NewImageEngine(cmd, args) - if err != nil { - return err - } - - if found, err := ie.Exists(context.Background(), args[0]); err != nil { + if found, err := registry.ImageEngine().Exists(context.Background(), args[0]); err != nil { return err } else if found.Value { return images.Inspect(cmd, args, inspectOpts) } - ce, err := registry.NewContainerEngine(cmd, args) - if err != nil { - return err - } - - if found, err := ce.ContainerExists(context.Background(), args[0]); err != nil { + if found, err := registry.ContainerEngine().ContainerExists(context.Background(), args[0]); err != nil { return err } else if found.Value { return containers.Inspect(cmd, args, inspectOpts) diff --git a/cmd/podmanV2/main.go b/cmd/podmanV2/main.go index cfe20d1c1..de5308121 100644 --- a/cmd/podmanV2/main.go +++ b/cmd/podmanV2/main.go @@ -2,7 +2,6 @@ package main import ( "os" - "reflect" _ "github.com/containers/libpod/cmd/podmanV2/containers" _ "github.com/containers/libpod/cmd/podmanV2/healthcheck" @@ -27,36 +26,25 @@ func main() { // had a specific job to do as a subprocess, and it's done. return } + for _, c := range registry.Commands { - if Contains(registry.PodmanOptions.EngineMode, c.Mode) { - parent := rootCmd - if c.Parent != nil { - parent = c.Parent + for _, m := range c.Mode { + if registry.PodmanOptions.EngineMode == m { + parent := rootCmd + if c.Parent != nil { + parent = c.Parent + } + parent.AddCommand(c.Command) + + // - templates need to be set here, as PersistentPreRunE() is + // not called when --help is used. + // - rootCmd uses cobra default template not ours + c.Command.SetHelpTemplate(helpTemplate) + c.Command.SetUsageTemplate(usageTemplate) } - parent.AddCommand(c.Command) } } Execute() os.Exit(0) } - -func Contains(item interface{}, slice interface{}) bool { - s := reflect.ValueOf(slice) - - switch s.Kind() { - case reflect.Array: - fallthrough - case reflect.Slice: - break - default: - return false - } - - for i := 0; i < s.Len(); i++ { - if s.Index(i).Interface() == item { - return true - } - } - return false -} diff --git a/cmd/podmanV2/networks/network.go b/cmd/podmanV2/networks/network.go index fc92d2321..85fec545b 100644 --- a/cmd/podmanV2/networks/network.go +++ b/cmd/podmanV2/networks/network.go @@ -9,12 +9,11 @@ import ( var ( // Command: podman _network_ cmd = &cobra.Command{ - Use: "network", - Short: "Manage networks", - Long: "Manage networks", - TraverseChildren: true, - PersistentPreRunE: preRunE, - RunE: registry.SubCommandExists, + Use: "network", + Short: "Manage networks", + Long: "Manage networks", + TraverseChildren: true, + RunE: registry.SubCommandExists, } ) @@ -23,11 +22,4 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode}, Command: cmd, }) - cmd.SetHelpTemplate(registry.HelpTemplate()) - cmd.SetUsageTemplate(registry.UsageTemplate()) -} - -func preRunE(cmd *cobra.Command, args []string) error { - _, err := registry.NewContainerEngine(cmd, args) - return err } diff --git a/cmd/podmanV2/pods/pod.go b/cmd/podmanV2/pods/pod.go index 81c0d33e1..3434bfc02 100644 --- a/cmd/podmanV2/pods/pod.go +++ b/cmd/podmanV2/pods/pod.go @@ -9,12 +9,11 @@ import ( var ( // Command: podman _pod_ podCmd = &cobra.Command{ - Use: "pod", - Short: "Manage pods", - Long: "Manage pods", - TraverseChildren: true, - PersistentPreRunE: preRunE, - RunE: registry.SubCommandExists, + Use: "pod", + Short: "Manage pods", + Long: "Manage pods", + TraverseChildren: true, + RunE: registry.SubCommandExists, } ) @@ -23,11 +22,4 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: podCmd, }) - podCmd.SetHelpTemplate(registry.HelpTemplate()) - podCmd.SetUsageTemplate(registry.UsageTemplate()) -} - -func preRunE(cmd *cobra.Command, args []string) error { - _, err := registry.NewContainerEngine(cmd, args) - return err } diff --git a/cmd/podmanV2/pods/top.go b/cmd/podmanV2/pods/top.go index 5ef282238..e501bb478 100644 --- a/cmd/podmanV2/pods/top.go +++ b/cmd/podmanV2/pods/top.go @@ -24,12 +24,11 @@ var ( topOptions = entities.PodTopOptions{} topCommand = &cobra.Command{ - Use: "top [flags] POD [FORMAT-DESCRIPTORS|ARGS]", - Short: "Display the running processes in a pod", - Long: topDescription, - PersistentPreRunE: preRunE, - RunE: top, - Args: cobra.ArbitraryArgs, + Use: "top [flags] POD [FORMAT-DESCRIPTORS|ARGS]", + Short: "Display the running processes in a pod", + Long: topDescription, + RunE: top, + Args: cobra.ArbitraryArgs, Example: `podman pod top podID podman pod top --latest podman pod top podID pid seccomp args %C @@ -44,9 +43,6 @@ func init() { Parent: podCmd, }) - topCommand.SetHelpTemplate(registry.HelpTemplate()) - topCommand.SetUsageTemplate(registry.UsageTemplate()) - flags := topCommand.Flags() flags.SetInterspersed(false) flags.BoolVar(&topOptions.ListDescriptors, "list-descriptors", false, "") diff --git a/cmd/podmanV2/registry/config.go b/cmd/podmanV2/registry/config.go index de9d1f262..358f9172e 100644 --- a/cmd/podmanV2/registry/config.go +++ b/cmd/podmanV2/registry/config.go @@ -12,11 +12,10 @@ import ( "github.com/containers/libpod/pkg/rootless" "github.com/containers/libpod/pkg/util" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) const ( - RootRequired = "RootRequired" + ParentNSRequired = "ParentNSRequired" ) var ( @@ -26,7 +25,7 @@ var ( // NewPodmanConfig creates a PodmanConfig from the environment func NewPodmanConfig() entities.PodmanConfig { if err := setXdgDirs(); err != nil { - logrus.Errorf(err.Error()) + fmt.Fprintf(os.Stderr, err.Error()) os.Exit(1) } @@ -39,7 +38,7 @@ func NewPodmanConfig() entities.PodmanConfig { case "linux": mode = entities.ABIMode default: - logrus.Errorf("%s is not a supported OS", runtime.GOOS) + fmt.Fprintf(os.Stderr, "%s is not a supported OS", runtime.GOOS) os.Exit(1) } @@ -47,18 +46,23 @@ func NewPodmanConfig() entities.PodmanConfig { for _, v := range os.Args { // Prefix checking works because of how default EngineMode's // have been defined. - if strings.HasPrefix(v, "--remote=") { + if strings.HasPrefix(v, "--remote") { mode = entities.TunnelMode } } - // FIXME: for rootless, where to get the path - // TODO: + // FIXME: for rootless, add flag to get the path to override configuration cfg, err := config.NewConfig("") if err != nil { - logrus.Error("Failed to obtain podman configuration") + fmt.Fprint(os.Stderr, "Failed to obtain podman configuration: "+err.Error()) os.Exit(1) } + + cfg.Network.NetworkConfigDir = cfg.Network.CNIPluginDirs[0] + if rootless.IsRootless() { + cfg.Network.NetworkConfigDir = "" + } + return entities.PodmanConfig{Config: cfg, EngineMode: mode} } @@ -71,34 +75,31 @@ func setXdgDirs() error { } // Setup XDG_RUNTIME_DIR - runtimeDir := os.Getenv("XDG_RUNTIME_DIR") - - if runtimeDir == "" { - var err error - runtimeDir, err = util.GetRuntimeDir() + if _, found := os.LookupEnv("XDG_RUNTIME_DIR"); !found { + dir, err := util.GetRuntimeDir() if err != nil { return err } - } - if err := os.Setenv("XDG_RUNTIME_DIR", runtimeDir); err != nil { - return errors.Wrapf(err, "cannot set XDG_RUNTIME_DIR") + if err := os.Setenv("XDG_RUNTIME_DIR", dir); err != nil { + return errors.Wrapf(err, "cannot set XDG_RUNTIME_DIR="+dir) + } } - if rootless.IsRootless() && os.Getenv("DBUS_SESSION_BUS_ADDRESS") == "" { - sessionAddr := filepath.Join(runtimeDir, "bus") + if _, found := os.LookupEnv("DBUS_SESSION_BUS_ADDRESS"); !found { + sessionAddr := filepath.Join(os.Getenv("XDG_RUNTIME_DIR"), "bus") if _, err := os.Stat(sessionAddr); err == nil { - os.Setenv("DBUS_SESSION_BUS_ADDRESS", fmt.Sprintf("unix:path=%s", sessionAddr)) + os.Setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path="+sessionAddr) } } // Setup XDG_CONFIG_HOME - if cfgHomeDir := os.Getenv("XDG_CONFIG_HOME"); cfgHomeDir == "" { + if _, found := os.LookupEnv("XDG_CONFIG_HOME"); !found { cfgHomeDir, err := util.GetRootlessConfigHomeDir() if err != nil { return err } if err := os.Setenv("XDG_CONFIG_HOME", cfgHomeDir); err != nil { - return errors.Wrapf(err, "cannot set XDG_CONFIG_HOME") + return errors.Wrapf(err, "cannot set XDG_CONFIG_HOME="+cfgHomeDir) } } return nil diff --git a/cmd/podmanV2/registry/registry.go b/cmd/podmanV2/registry/registry.go index 5ef6a10d8..1c5e5d21b 100644 --- a/cmd/podmanV2/registry/registry.go +++ b/cmd/podmanV2/registry/registry.go @@ -42,41 +42,6 @@ func GetExitCode() int { return exitCode } -// HelpTemplate returns the help template for podman commands -// This uses the short and long options. -// command should not use this. -func HelpTemplate() string { - return `{{.Short}} - -Description: - {{.Long}} - -{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` -} - -// UsageTemplate returns the usage template for podman commands -// This blocks the displaying of the global options. The main podman -// command should not use this. -func UsageTemplate() string { - return `Usage(v2):{{if (and .Runnable (not .HasAvailableSubCommands))}} - {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} - {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} - -Aliases: - {{.NameAndAliases}}{{end}}{{if .HasExample}} - -Examples: - {{.Example}}{{end}}{{if .HasAvailableSubCommands}} - -Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}} - {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} - -Flags: -{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} -{{end}} -` -} - func ImageEngine() entities.ImageEngine { return imageEngine } @@ -126,17 +91,26 @@ func IdOrLatestArgs(cmd *cobra.Command, args []string) error { return nil } -func GetContext() context.Context { +type PodmanOptionsKey struct{} + +func Context() context.Context { if cliCtx == nil { - cliCtx = context.Background() + cliCtx = ContextWithOptions(context.Background()) } return cliCtx } -type ContextOptionsKey string - -const PodmanOptionsKey ContextOptionsKey = "PodmanOptions" +func ContextWithOptions(ctx context.Context) context.Context { + cliCtx = context.WithValue(ctx, PodmanOptionsKey{}, PodmanOptions) + return cliCtx +} +// GetContextWithOptions deprecated, use NewContextWithOptions() func GetContextWithOptions() context.Context { - return context.WithValue(GetContext(), PodmanOptionsKey, PodmanOptions) + return ContextWithOptions(context.Background()) +} + +// GetContext deprecated, use Context() +func GetContext() context.Context { + return Context() } diff --git a/cmd/podmanV2/root.go b/cmd/podmanV2/root.go index 0639257ea..801e728f0 100644 --- a/cmd/podmanV2/root.go +++ b/cmd/podmanV2/root.go @@ -1,12 +1,12 @@ package main import ( - "context" "fmt" "log/syslog" "os" "path" "runtime/pprof" + "strings" "github.com/containers/libpod/cmd/podmanV2/registry" "github.com/containers/libpod/pkg/domain/entities" @@ -21,6 +21,37 @@ import ( "github.com/spf13/pflag" ) +// HelpTemplate is the help template for podman commands +// This uses the short and long options. +// command should not use this. +const helpTemplate = `{{.Short}} + +Description: + {{.Long}} + +{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` + +// UsageTemplate is the usage template for podman commands +// This blocks the displaying of the global options. The main podman +// command should not use this. +const usageTemplate = `Usage(v2):{{if (and .Runnable (not .HasAvailableSubCommands))}} + {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} + {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} + +Aliases: + {{.NameAndAliases}}{{end}}{{if .HasExample}} + +Examples: + {{.Example}}{{end}}{{if .HasAvailableSubCommands}} + +Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} + +Flags: +{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} +{{end}} +` + var ( rootCmd = &cobra.Command{ Use: path.Base(os.Args[0]), @@ -28,20 +59,20 @@ var ( SilenceUsage: true, SilenceErrors: true, TraverseChildren: true, - PersistentPreRunE: preRunE, + PersistentPreRunE: persistentPreRunE, RunE: registry.SubCommandExists, - PersistentPostRunE: postRunE, + PersistentPostRunE: persistentPostRunE, Version: version.Version, } - logLevels = entities.NewStringSet("debug", "info", "warn", "error", "fatal", "panic") + logLevels = []string{"debug", "info", "warn", "error", "fatal", "panic"} logLevel = "error" useSyslog bool ) func init() { + // Hooks are called before PersistentPreRunE() cobra.OnInitialize( - rootlessHook, loggingHook, syslogHook, ) @@ -63,13 +94,21 @@ func Execute() { os.Exit(registry.GetExitCode()) } -func preRunE(cmd *cobra.Command, _ []string) error { +func persistentPreRunE(cmd *cobra.Command, args []string) error { + // TODO: Remove trace statement in podman V2.1 + logrus.Debugf("Called %s.PersistentPreRunE()", cmd.Name()) + // Update PodmanOptions now that we "know" more // TODO: pass in path overriding configuration file registry.PodmanOptions = registry.NewPodmanConfig() - cmd.SetHelpTemplate(registry.HelpTemplate()) - cmd.SetUsageTemplate(registry.UsageTemplate()) + // Prep the engines + if _, err := registry.NewImageEngine(cmd, args); err != nil { + return err + } + if _, err := registry.NewContainerEngine(cmd, args); err != nil { + return err + } if cmd.Flag("cpu-profile").Changed { f, err := os.Create(registry.PodmanOptions.CpuProfile) @@ -88,12 +127,28 @@ func preRunE(cmd *cobra.Command, _ []string) error { registry.PodmanOptions.SpanCloser = closer registry.PodmanOptions.Span = tracer.StartSpan("before-context") - registry.PodmanOptions.SpanCtx = opentracing.ContextWithSpan(context.Background(), registry.PodmanOptions.Span) + registry.PodmanOptions.SpanCtx = opentracing.ContextWithSpan(registry.Context(), registry.PodmanOptions.Span) + opentracing.StartSpanFromContext(registry.PodmanOptions.SpanCtx, cmd.Name()) + } + + // Setup Rootless environment, IFF: + // 1) in ABI mode + // 2) running as non-root + // 3) command doesn't require Parent Namespace + _, found := cmd.Annotations[registry.ParentNSRequired] + if !registry.IsRemote() && rootless.IsRootless() && !found { + err := registry.ContainerEngine().SetupRootless(registry.Context(), cmd) + if err != nil { + return err + } } return nil } -func postRunE(cmd *cobra.Command, args []string) error { +func persistentPostRunE(cmd *cobra.Command, args []string) error { + // TODO: Remove trace statement in podman V2.1 + logrus.Debugf("Called %s.PersistentPostRunE()", cmd.Name()) + if cmd.Flag("cpu-profile").Changed { pprof.StopCPUProfile() } @@ -105,14 +160,21 @@ func postRunE(cmd *cobra.Command, args []string) error { } func loggingHook() { - if !logLevels.Contains(logLevel) { - logrus.Errorf("Log Level \"%s\" is not supported, choose from: %s", logLevel, logLevels.String()) + var found bool + for _, l := range logLevels { + if l == logLevel { + found = true + break + } + } + if !found { + fmt.Fprintf(os.Stderr, "Log Level \"%s\" is not supported, choose from: %s\n", logLevel, strings.Join(logLevels, ", ")) os.Exit(1) } level, err := logrus.ParseLevel(logLevel) if err != nil { - fmt.Fprintf(os.Stderr, err.Error()) + fmt.Fprint(os.Stderr, err.Error()) os.Exit(1) } logrus.SetLevel(level) @@ -123,26 +185,18 @@ func loggingHook() { } func syslogHook() { - if useSyslog { - hook, err := logrusSyslog.NewSyslogHook("", "", syslog.LOG_INFO, "") - if err != nil { - logrus.WithError(err).Error("Failed to initialize syslog hook") - } - if err == nil { - logrus.AddHook(hook) - } + if !useSyslog { + return } -} -func rootlessHook() { - if rootless.IsRootless() { - logrus.Error("rootless mode is currently not supported. Support will return ASAP.") + hook, err := logrusSyslog.NewSyslogHook("", "", syslog.LOG_INFO, "") + if err != nil { + fmt.Fprint(os.Stderr, "Failed to initialize syslog hook: "+err.Error()) + os.Exit(1) + } + if err == nil { + logrus.AddHook(hook) } - // ce, err := registry.NewContainerEngine(rootCmd, []string{}) - // if err != nil { - // logrus.WithError(err).Fatal("failed to obtain container engine") - // } - // ce.SetupRootLess(rootCmd) } func rootFlags(opts entities.PodmanConfig, flags *pflag.FlagSet) { @@ -179,7 +233,7 @@ func rootFlags(opts entities.PodmanConfig, flags *pflag.FlagSet) { // Override default --help information of `--help` global flag var dummyHelp bool flags.BoolVar(&dummyHelp, "help", false, "Help for podman") - flags.StringVar(&logLevel, "log-level", logLevel, fmt.Sprintf("Log messages above specified level (%s)", logLevels.String())) + flags.StringVar(&logLevel, "log-level", logLevel, fmt.Sprintf("Log messages above specified level (%s)", strings.Join(logLevels, ", "))) // Hide these flags for both ABI and Tunneling for _, f := range []string{ @@ -189,7 +243,7 @@ func rootFlags(opts entities.PodmanConfig, flags *pflag.FlagSet) { "trace", } { if err := flags.MarkHidden(f); err != nil { - logrus.Warnf("unable to mark %s flag as hidden", f) + logrus.Warnf("unable to mark %s flag as hidden: %s", f, err.Error()) } } @@ -197,5 +251,4 @@ func rootFlags(opts entities.PodmanConfig, flags *pflag.FlagSet) { if !registry.IsRemote() { flags.BoolVar(&useSyslog, "syslog", false, "Output logging information to syslog as well as the console (default false)") } - } diff --git a/cmd/podmanV2/system/events.go b/cmd/podmanV2/system/events.go index 9fd27e2c1..95e6a5576 100644 --- a/cmd/podmanV2/system/events.go +++ b/cmd/podmanV2/system/events.go @@ -17,12 +17,11 @@ import ( var ( eventsDescription = "Monitor podman events" eventsCommand = &cobra.Command{ - Use: "events", - Args: cobra.NoArgs, - Short: "Show podman events", - Long: eventsDescription, - PersistentPreRunE: preRunE, - RunE: eventsCmd, + Use: "events", + Args: cobra.NoArgs, + Short: "Show podman events", + Long: eventsDescription, + RunE: eventsCmd, Example: `podman events podman events --filter event=create podman events --since 1h30s`, diff --git a/cmd/podmanV2/system/info.go b/cmd/podmanV2/system/info.go index 69b2871b7..6b0c6a13b 100644 --- a/cmd/podmanV2/system/info.go +++ b/cmd/podmanV2/system/info.go @@ -22,7 +22,6 @@ var ( Args: cobra.NoArgs, Long: infoDescription, Short: "Display podman system information", - PreRunE: preRunE, RunE: info, Example: `podman info`, } diff --git a/cmd/podmanV2/system/system.go b/cmd/podmanV2/system/system.go index b44632187..e62a0c150 100644 --- a/cmd/podmanV2/system/system.go +++ b/cmd/podmanV2/system/system.go @@ -9,12 +9,11 @@ import ( var ( // Command: podman _system_ systemCmd = &cobra.Command{ - Use: "system", - Short: "Manage podman", - Long: "Manage podman", - TraverseChildren: true, - PersistentPreRunE: preRunE, - RunE: registry.SubCommandExists, + Use: "system", + Short: "Manage podman", + Long: "Manage podman", + TraverseChildren: true, + RunE: registry.SubCommandExists, } ) @@ -23,11 +22,4 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: systemCmd, }) - systemCmd.SetHelpTemplate(registry.HelpTemplate()) - systemCmd.SetUsageTemplate(registry.UsageTemplate()) -} - -func preRunE(cmd *cobra.Command, args []string) error { - _, err := registry.NewContainerEngine(cmd, args) - return err } diff --git a/cmd/podmanV2/system/varlink.go b/cmd/podmanV2/system/varlink.go index da9af6fe4..27dd0a7e9 100644 --- a/cmd/podmanV2/system/varlink.go +++ b/cmd/podmanV2/system/varlink.go @@ -14,12 +14,11 @@ var ( Tools speaking varlink protocol can remotely manage pods, containers and images. ` varlinkCmd = &cobra.Command{ - Use: "varlink [flags] [URI]", - Args: cobra.MinimumNArgs(1), - Short: "Run varlink interface", - Long: varlinkDescription, - PreRunE: preRunE, - RunE: varlinkE, + Use: "varlink [flags] [URI]", + Args: cobra.MinimumNArgs(1), + Short: "Run varlink interface", + Long: varlinkDescription, + RunE: varlinkE, Example: `podman varlink unix:/run/podman/io.podman podman varlink --timeout 5000 unix:/run/podman/io.podman`, } @@ -33,9 +32,6 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: varlinkCmd, }) - varlinkCmd.SetHelpTemplate(registry.HelpTemplate()) - varlinkCmd.SetUsageTemplate(registry.UsageTemplate()) - flags := varlinkCmd.Flags() flags.Int64VarP(&varlinkArgs.Timeout, "time", "t", 1000, "Time until the varlink session expires in milliseconds. Use 0 to disable the timeout") flags.Int64Var(&varlinkArgs.Timeout, "timeout", 1000, "Time until the varlink session expires in milliseconds. Use 0 to disable the timeout") diff --git a/cmd/podmanV2/system/version.go b/cmd/podmanV2/system/version.go index 8d6e8b7a8..7004c3109 100644 --- a/cmd/podmanV2/system/version.go +++ b/cmd/podmanV2/system/version.go @@ -18,11 +18,13 @@ import ( var ( versionCommand = &cobra.Command{ - Use: "version", - Args: cobra.NoArgs, - Short: "Display the Podman Version Information", - RunE: version, - PersistentPreRunE: preRunE, + Use: "version", + Args: cobra.NoArgs, + Short: "Display the Podman Version Information", + RunE: version, + Annotations: map[string]string{ + registry.ParentNSRequired: "", + }, } versionFormat string ) diff --git a/cmd/podmanV2/volumes/volume.go b/cmd/podmanV2/volumes/volume.go index 84abe3d24..d1135d1bf 100644 --- a/cmd/podmanV2/volumes/volume.go +++ b/cmd/podmanV2/volumes/volume.go @@ -9,12 +9,11 @@ import ( var ( // Command: podman _volume_ volumeCmd = &cobra.Command{ - Use: "volume", - Short: "Manage volumes", - Long: "Volumes are created in and can be shared between containers", - TraverseChildren: true, - PersistentPreRunE: preRunE, - RunE: registry.SubCommandExists, + Use: "volume", + Short: "Manage volumes", + Long: "Volumes are created in and can be shared between containers", + TraverseChildren: true, + RunE: registry.SubCommandExists, } ) @@ -23,11 +22,4 @@ func init() { Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Command: volumeCmd, }) - volumeCmd.SetHelpTemplate(registry.HelpTemplate()) - volumeCmd.SetUsageTemplate(registry.UsageTemplate()) -} - -func preRunE(cmd *cobra.Command, args []string) error { - _, err := registry.NewContainerEngine(cmd, args) - return err } -- cgit v1.2.3-54-g00ecf