Merge pull request #5848 from jwhonce/wip/options

V2 Enable rootless
This commit is contained in:
OpenShift Merge Robot
2020-04-16 11:56:16 -07:00
committed by GitHub
64 changed files with 419 additions and 851 deletions

View File

@ -1,7 +1,9 @@
all: podman podman-remote all: podman podman-remote
BUILD_TAGS='ABISupport systemd varlink seccomp selinux exclude_graphdriver_devicemapper'
podman: 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: podman-remote:
CGO_ENABLED=1 GO111MODULE=off go build -tags '!ABISupport systemd seccomp selinux' -o podmanV2-remote CGO_ENABLED=1 GO111MODULE=off go build -tags '!ABISupport systemd seccomp selinux' -o podmanV2-remote

View File

@ -2,30 +2,15 @@ package common
import ( import (
"fmt" "fmt"
"os"
buildahcli "github.com/containers/buildah/pkg/cli" buildahcli "github.com/containers/buildah/pkg/cli"
"github.com/containers/common/pkg/config" "github.com/containers/libpod/cmd/podmanV2/registry"
"github.com/sirupsen/logrus"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
const ( const sizeWithUnitFormat = "(format: `<number>[<unit>]`, where unit = b (bytes), k (kilobytes), m (megabytes), or g (gigabytes))"
sizeWithUnitFormat = "(format: `<number>[<unit>]`, where unit = b (bytes), k (kilobytes), m (megabytes), or g (gigabytes))"
)
var ( var containerConfig = registry.NewPodmanConfig()
defaultContainerConfig = getDefaultContainerConfig()
)
func getDefaultContainerConfig() *config.Config {
defaultContainerConfig, err := config.Default()
if err != nil {
logrus.Error(err)
os.Exit(1)
}
return defaultContainerConfig
}
func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet { func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet {
createFlags := pflag.FlagSet{} createFlags := pflag.FlagSet{}
@ -337,13 +322,13 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet {
"override-arch", "", "override-arch", "",
"use `ARCH` instead of the architecture of the machine for choosing images", "use `ARCH` instead of the architecture of the machine for choosing images",
) )
//markFlagHidden(createFlags, "override-arch") // markFlagHidden(createFlags, "override-arch")
createFlags.StringVar( createFlags.StringVar(
&cf.OverrideOS, &cf.OverrideOS,
"override-os", "", "override-os", "",
"use `OS` instead of the running OS for choosing images", "use `OS` instead of the running OS for choosing images",
) )
//markFlagHidden(createFlags, "override-os") // markFlagHidden(createFlags, "override-os")
createFlags.StringVar( createFlags.StringVar(
&cf.PID, &cf.PID,
"pid", getDefaultPidNS(), "pid", getDefaultPidNS(),
@ -407,7 +392,7 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet {
createFlags.StringArrayVar( createFlags.StringArrayVar(
&cf.SecurityOpt, &cf.SecurityOpt,
"security-opt", getDefaultSecurityOptions(), "security-opt", getDefaultSecurityOptions(),
fmt.Sprintf("Security Options"), "Security Options",
) )
createFlags.StringVar( createFlags.StringVar(
&cf.ShmSize, &cf.ShmSize,
@ -421,7 +406,7 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet {
) )
createFlags.UintVar( createFlags.UintVar(
&cf.StopTimeout, &cf.StopTimeout,
"stop-timeout", defaultContainerConfig.Engine.StopTimeout, "stop-timeout", containerConfig.Engine.StopTimeout,
"Timeout (in seconds) to stop a container. Default is 10", "Timeout (in seconds) to stop a container. Default is 10",
) )
createFlags.StringSliceVar( createFlags.StringSliceVar(
@ -513,7 +498,7 @@ func GetCreateFlags(cf *ContainerCLIOpts) *pflag.FlagSet {
return &createFlags return &createFlags
} }
func AliasFlags(f *pflag.FlagSet, name string) pflag.NormalizedName { func AliasFlags(_ *pflag.FlagSet, name string) pflag.NormalizedName {
switch name { switch name {
case "healthcheck-command": case "healthcheck-command":
name = "health-cmd" name = "health-cmd"

View File

@ -8,6 +8,7 @@ import (
"github.com/containers/libpod/pkg/apparmor" "github.com/containers/libpod/pkg/apparmor"
"github.com/containers/libpod/pkg/cgroups" "github.com/containers/libpod/pkg/cgroups"
"github.com/containers/libpod/pkg/rootless" "github.com/containers/libpod/pkg/rootless"
"github.com/containers/libpod/pkg/specgen"
"github.com/containers/libpod/pkg/sysinfo" "github.com/containers/libpod/pkg/sysinfo"
"github.com/opencontainers/selinux/go-selinux" "github.com/opencontainers/selinux/go-selinux"
) )
@ -31,13 +32,13 @@ var (
// once we are "on" the host system. // once we are "on" the host system.
func getDefaultSecurityOptions() []string { func getDefaultSecurityOptions() []string {
securityOpts := []string{} securityOpts := []string{}
if defaultContainerConfig.Containers.SeccompProfile != "" && defaultContainerConfig.Containers.SeccompProfile != parse.SeccompDefaultPath { if containerConfig.Containers.SeccompProfile != "" && containerConfig.Containers.SeccompProfile != parse.SeccompDefaultPath {
securityOpts = append(securityOpts, fmt.Sprintf("seccomp=%s", defaultContainerConfig.Containers.SeccompProfile)) securityOpts = append(securityOpts, fmt.Sprintf("seccomp=%s", containerConfig.Containers.SeccompProfile))
} }
if apparmor.IsEnabled() && defaultContainerConfig.Containers.ApparmorProfile != "" { if apparmor.IsEnabled() && containerConfig.Containers.ApparmorProfile != "" {
securityOpts = append(securityOpts, fmt.Sprintf("apparmor=%s", defaultContainerConfig.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])) securityOpts = append(securityOpts, fmt.Sprintf("label=%s", selinux.DisableSecOpt()[0]))
} }
return securityOpts return securityOpts
@ -45,66 +46,66 @@ func getDefaultSecurityOptions() []string {
// getDefaultSysctls // getDefaultSysctls
func getDefaultSysctls() []string { func getDefaultSysctls() []string {
return defaultContainerConfig.Containers.DefaultSysctls return containerConfig.Containers.DefaultSysctls
} }
func getDefaultVolumes() []string { func getDefaultVolumes() []string {
return defaultContainerConfig.Containers.Volumes return containerConfig.Containers.Volumes
} }
func getDefaultDevices() []string { func getDefaultDevices() []string {
return defaultContainerConfig.Containers.Devices return containerConfig.Containers.Devices
} }
func getDefaultDNSServers() []string { //nolint func getDefaultDNSServers() []string { //nolint
return defaultContainerConfig.Containers.DNSServers return containerConfig.Containers.DNSServers
} }
func getDefaultDNSSearches() []string { //nolint func getDefaultDNSSearches() []string { //nolint
return defaultContainerConfig.Containers.DNSSearches return containerConfig.Containers.DNSSearches
} }
func getDefaultDNSOptions() []string { //nolint func getDefaultDNSOptions() []string { //nolint
return defaultContainerConfig.Containers.DNSOptions return containerConfig.Containers.DNSOptions
} }
func getDefaultEnv() []string { func getDefaultEnv() []string {
return defaultContainerConfig.Containers.Env return containerConfig.Containers.Env
} }
func getDefaultInitPath() string { func getDefaultInitPath() string {
return defaultContainerConfig.Containers.InitPath return containerConfig.Containers.InitPath
} }
func getDefaultIPCNS() string { func getDefaultIPCNS() string {
return defaultContainerConfig.Containers.IPCNS return containerConfig.Containers.IPCNS
} }
func getDefaultPidNS() string { func getDefaultPidNS() string {
return defaultContainerConfig.Containers.PidNS return containerConfig.Containers.PidNS
} }
func getDefaultNetNS() string { //nolint func getDefaultNetNS() string { //nolint
if defaultContainerConfig.Containers.NetNS == "private" && rootless.IsRootless() { if containerConfig.Containers.NetNS == string(specgen.Private) && rootless.IsRootless() {
return "slirp4netns" return string(specgen.Slirp)
} }
return defaultContainerConfig.Containers.NetNS return containerConfig.Containers.NetNS
} }
func getDefaultCgroupNS() string { func getDefaultCgroupNS() string {
return defaultContainerConfig.Containers.CgroupNS return containerConfig.Containers.CgroupNS
} }
func getDefaultUTSNS() string { func getDefaultUTSNS() string {
return defaultContainerConfig.Containers.UTSNS return containerConfig.Containers.UTSNS
} }
func getDefaultShmSize() string { func getDefaultShmSize() string {
return defaultContainerConfig.Containers.ShmSize return containerConfig.Containers.ShmSize
} }
func getDefaultUlimits() []string { func getDefaultUlimits() []string {
return defaultContainerConfig.Containers.DefaultUlimits return containerConfig.Containers.DefaultUlimits
} }
func getDefaultUserNS() string { func getDefaultUserNS() string {
@ -112,14 +113,14 @@ func getDefaultUserNS() string {
if userns != "" { if userns != "" {
return userns return userns
} }
return defaultContainerConfig.Containers.UserNS return containerConfig.Containers.UserNS
} }
func getDefaultPidsLimit() int64 { func getDefaultPidsLimit() int64 {
if rootless.IsRootless() { if rootless.IsRootless() {
cgroup2, _ := cgroups.IsCgroup2UnifiedMode() cgroup2, _ := cgroups.IsCgroup2UnifiedMode()
if cgroup2 { if cgroup2 {
return defaultContainerConfig.Containers.PidsLimit return containerConfig.Containers.PidsLimit
} }
} }
return sysinfo.GetDefaultPidsLimit() return sysinfo.GetDefaultPidsLimit()
@ -130,5 +131,5 @@ func getDefaultPidsDescription() string {
} }
func GetDefaultDetachKeys() string { func GetDefaultDetachKeys() string {
return defaultContainerConfig.Engine.DetachKeys return containerConfig.Engine.DetachKeys
} }

View File

@ -4,18 +4,10 @@ import (
"net" "net"
"github.com/containers/libpod/pkg/domain/entities" "github.com/containers/libpod/pkg/domain/entities"
"github.com/containers/libpod/pkg/rootless"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
func getDefaultNetwork() string {
if rootless.IsRootless() {
return "slirp4netns"
}
return "bridge"
}
func GetNetFlags() *pflag.FlagSet { func GetNetFlags() *pflag.FlagSet {
netFlags := pflag.FlagSet{} netFlags := pflag.FlagSet{}
netFlags.StringSlice( netFlags.StringSlice(
@ -23,15 +15,15 @@ func GetNetFlags() *pflag.FlagSet {
"Add a custom host-to-IP mapping (host:ip) (default [])", "Add a custom host-to-IP mapping (host:ip) (default [])",
) )
netFlags.StringSlice( netFlags.StringSlice(
"dns", []string{}, "dns", getDefaultDNSServers(),
"Set custom DNS servers", "Set custom DNS servers",
) )
netFlags.StringSlice( netFlags.StringSlice(
"dns-opt", []string{}, "dns-opt", getDefaultDNSOptions(),
"Set custom DNS options", "Set custom DNS options",
) )
netFlags.StringSlice( netFlags.StringSlice(
"dns-search", []string{}, "dns-search", getDefaultDNSSearches(),
"Set custom DNS search domains", "Set custom DNS search domains",
) )
netFlags.String( netFlags.String(
@ -43,7 +35,7 @@ func GetNetFlags() *pflag.FlagSet {
"Container MAC address (e.g. 92:d0:c6:0a:29:33)", "Container MAC address (e.g. 92:d0:c6:0a:29:33)",
) )
netFlags.String( netFlags.String(
"network", getDefaultNetwork(), "network", getDefaultNetNS(),
"Connect a container to a network", "Connect a container to a network",
) )
netFlags.StringSliceP( netFlags.StringSliceP(

View File

@ -23,7 +23,6 @@ var (
} }
return nil return nil
}, },
PreRunE: preRunE,
Example: `podman attach ctrID Example: `podman attach ctrID
podman attach 1234 podman attach 1234
podman attach --no-stdin foobar`, podman attach --no-stdin foobar`,

View File

@ -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.` 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{ commitCommand = &cobra.Command{
Use: "commit [flags] CONTAINER [IMAGE]", Use: "commit [flags] CONTAINER [IMAGE]",
Short: "Create new image based on the changed container", Short: "Create new image based on the changed container",
Long: commitDescription, Long: commitDescription,
RunE: commit, RunE: commit,
PreRunE: preRunE, Args: cobra.MinimumNArgs(1),
Args: cobra.MinimumNArgs(1),
Example: `podman commit -q --message "committing container to image" reverent_golick image-committed 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 --author "firstName lastName" reverent_golick image-committed
podman commit -q --pause=false containerID image-committed podman commit -q --pause=false containerID image-committed

View File

@ -13,12 +13,11 @@ import (
var ( var (
// Command: podman _container_ // Command: podman _container_
containerCmd = &cobra.Command{ containerCmd = &cobra.Command{
Use: "container", Use: "container",
Short: "Manage containers", Short: "Manage containers",
Long: "Manage containers", Long: "Manage containers",
TraverseChildren: true, TraverseChildren: true,
PersistentPreRunE: preRunE, RunE: registry.SubCommandExists,
RunE: registry.SubCommandExists,
} }
defaultContainerConfig = getDefaultContainerConfig() defaultContainerConfig = getDefaultContainerConfig()
@ -29,13 +28,6 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: containerCmd, 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 { func getDefaultContainerConfig() *config.Config {

View File

@ -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 <container_id> command. The container will be created with the initial state 'created'.` The container ID is then printed to stdout. You can then start it at any time with the podman start <container_id> command. The container will be created with the initial state 'created'.`
createCommand = &cobra.Command{ createCommand = &cobra.Command{
Use: "create [flags] IMAGE [COMMAND [ARG...]]", Use: "create [flags] IMAGE [COMMAND [ARG...]]",
Short: "Create but do not start a container", Short: "Create but do not start a container",
Long: createDescription, Long: createDescription,
RunE: create, RunE: create,
PersistentPreRunE: preRunE, Args: cobra.MinimumNArgs(1),
Args: cobra.MinimumNArgs(1),
Example: `podman create alpine ls Example: `podman create alpine ls
podman create --annotation HELLO=WORLD alpine ls podman create --annotation HELLO=WORLD alpine ls
podman create -t -i --name myctr alpine ls`, podman create -t -i --name myctr alpine ls`,

View File

@ -11,12 +11,11 @@ import (
var ( var (
// podman container _diff_ // podman container _diff_
diffCmd = &cobra.Command{ diffCmd = &cobra.Command{
Use: "diff [flags] CONTAINER", Use: "diff [flags] CONTAINER",
Args: registry.IdOrLatestArgs, Args: registry.IdOrLatestArgs,
Short: "Inspect changes on container's file systems", Short: "Inspect changes on container's file systems",
Long: `Displays changes on a container filesystem. The container will be compared to its parent layer.`, Long: `Displays changes on a container filesystem. The container will be compared to its parent layer.`,
PreRunE: preRunE, RunE: diff,
RunE: diff,
Example: `podman container diff myCtr Example: `podman container diff myCtr
podman container diff -l --format json myCtr`, podman container diff -l --format json myCtr`,
} }

View File

@ -16,11 +16,10 @@ var (
execDescription = `Execute the specified command inside a running container. execDescription = `Execute the specified command inside a running container.
` `
execCommand = &cobra.Command{ execCommand = &cobra.Command{
Use: "exec [flags] CONTAINER [COMMAND [ARG...]]", Use: "exec [flags] CONTAINER [COMMAND [ARG...]]",
Short: "Run a process in a running container", Short: "Run a process in a running container",
Long: execDescription, Long: execDescription,
PreRunE: preRunE, RunE: exec,
RunE: exec,
Example: `podman exec -it ctrID ls Example: `podman exec -it ctrID ls
podman exec -it -w /tmp myCtr pwd podman exec -it -w /tmp myCtr pwd
podman exec --user root ctrID ls`, podman exec --user root ctrID ls`,

View File

@ -17,12 +17,11 @@ var (
" and saves it on the local machine." " and saves it on the local machine."
exportCommand = &cobra.Command{ exportCommand = &cobra.Command{
Use: "export [flags] CONTAINER", Use: "export [flags] CONTAINER",
Short: "Export container's filesystem contents as a tar archive", Short: "Export container's filesystem contents as a tar archive",
Long: exportDescription, Long: exportDescription,
PersistentPreRunE: preRunE, RunE: export,
RunE: export, Args: cobra.ExactArgs(1),
Args: cobra.ExactArgs(1),
Example: `podman export ctrID > myCtr.tar Example: `podman export ctrID > myCtr.tar
podman export --output="myCtr.tar" ctrID`, podman export --output="myCtr.tar" ctrID`,
} }
@ -37,8 +36,6 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: exportCommand, Command: exportCommand,
}) })
exportCommand.SetHelpTemplate(registry.HelpTemplate())
exportCommand.SetUsageTemplate(registry.UsageTemplate())
flags := exportCommand.Flags() flags := exportCommand.Flags()
flags.StringVarP(&exportOpts.Output, "output", "o", "", "Write to a specified file (default: stdout, which must be redirected)") flags.StringVarP(&exportOpts.Output, "output", "o", "", "Write to a specified file (default: stdout, which must be redirected)")
} }

View File

@ -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.` initDescription = `Initialize one or more containers, creating the OCI spec and mounts for inspection. Container names or IDs can be used.`
initCommand = &cobra.Command{ initCommand = &cobra.Command{
Use: "init [flags] CONTAINER [CONTAINER...]", Use: "init [flags] CONTAINER [CONTAINER...]",
Short: "Initialize one or more containers", Short: "Initialize one or more containers",
Long: initDescription, Long: initDescription,
PreRunE: preRunE, RunE: initContainer,
RunE: initContainer,
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
return parse.CheckAllLatestAndCIDFile(cmd, args, false, false) return parse.CheckAllLatestAndCIDFile(cmd, args, false, false)
}, },

View File

@ -18,11 +18,10 @@ import (
var ( var (
// podman container _inspect_ // podman container _inspect_
inspectCmd = &cobra.Command{ inspectCmd = &cobra.Command{
Use: "inspect [flags] CONTAINER", Use: "inspect [flags] CONTAINER",
Short: "Display the configuration of a container", Short: "Display the configuration of a container",
Long: `Displays the low-level information on a container identified by name or ID.`, Long: `Displays the low-level information on a container identified by name or ID.`,
PreRunE: preRunE, RunE: inspect,
RunE: inspect,
Example: `podman container inspect myCtr Example: `podman container inspect myCtr
podman container inspect -l --format '{{.Id}} {{.Config.Labels}}'`, podman container inspect -l --format '{{.Id}} {{.Config.Labels}}'`,
} }

View File

@ -16,11 +16,10 @@ import (
var ( var (
killDescription = "The main process inside each container specified will be sent SIGKILL, or any signal specified with option --signal." killDescription = "The main process inside each container specified will be sent SIGKILL, or any signal specified with option --signal."
killCommand = &cobra.Command{ killCommand = &cobra.Command{
Use: "kill [flags] CONTAINER [CONTAINER...]", Use: "kill [flags] CONTAINER [CONTAINER...]",
Short: "Kill one or more running containers with a specific signal", Short: "Kill one or more running containers with a specific signal",
Long: killDescription, Long: killDescription,
RunE: kill, RunE: kill,
PersistentPreRunE: preRunE,
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
return parse.CheckAllLatestAndCIDFile(cmd, args, false, false) return parse.CheckAllLatestAndCIDFile(cmd, args, false, false)
}, },

View File

@ -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). 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{ logsCommand = &cobra.Command{
Use: "logs [flags] CONTAINER [CONTAINER...]", Use: "logs [flags] CONTAINER [CONTAINER...]",
Short: "Fetch the logs of one or more container", Short: "Fetch the logs of one or more container",
Long: logsDescription, Long: logsDescription,
RunE: logs, RunE: logs,
PreRunE: preRunE,
Example: `podman logs ctrID Example: `podman logs ctrID
podman logs --names ctrID1 ctrID2 podman logs --names ctrID1 ctrID2
podman logs --tail 2 mywebserver podman logs --tail 2 mywebserver
@ -39,11 +38,10 @@ var (
} }
containerLogsCommand = &cobra.Command{ containerLogsCommand = &cobra.Command{
Use: logsCommand.Use, Use: logsCommand.Use,
Short: logsCommand.Short, Short: logsCommand.Short,
Long: logsCommand.Long, Long: logsCommand.Long,
PreRunE: logsCommand.PreRunE, RunE: logsCommand.RunE,
RunE: logsCommand.RunE,
Example: `podman container logs ctrID Example: `podman container logs ctrID
podman container logs --names ctrID1 ctrID2 podman container logs --names ctrID1 ctrID2
podman container logs --tail 2 mywebserver podman container logs --tail 2 mywebserver
@ -59,9 +57,6 @@ func init() {
Command: logsCommand, Command: logsCommand,
}) })
logsCommand.SetHelpTemplate(registry.HelpTemplate())
logsCommand.SetUsageTemplate(registry.UsageTemplate())
flags := logsCommand.Flags() flags := logsCommand.Flags()
logsFlags(flags) logsFlags(flags)

View File

@ -23,16 +23,15 @@ var (
` `
mountCommand = &cobra.Command{ mountCommand = &cobra.Command{
Use: "mount [flags] [CONTAINER]", Use: "mount [flags] [CONTAINER]",
Short: "Mount a working container's root filesystem", Short: "Mount a working container's root filesystem",
Long: mountDescription, Long: mountDescription,
PreRunE: preRunE, RunE: mount,
RunE: mount,
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
return parse.CheckAllLatestAndCIDFile(cmd, args, true, false) return parse.CheckAllLatestAndCIDFile(cmd, args, true, false)
}, },
Annotations: map[string]string{ Annotations: map[string]string{
registry.RootRequired: "true", registry.ParentNSRequired: "",
}, },
} }
) )

View File

@ -15,11 +15,10 @@ import (
var ( var (
pauseDescription = `Pauses one or more running containers. The container name or ID can be used.` pauseDescription = `Pauses one or more running containers. The container name or ID can be used.`
pauseCommand = &cobra.Command{ pauseCommand = &cobra.Command{
Use: "pause [flags] CONTAINER [CONTAINER...]", Use: "pause [flags] CONTAINER [CONTAINER...]",
Short: "Pause all the processes in one or more containers", Short: "Pause all the processes in one or more containers",
Long: pauseDescription, Long: pauseDescription,
RunE: pause, RunE: pause,
PersistentPreRunE: preRunE,
Example: `podman pause mywebserver Example: `podman pause mywebserver
podman pause 860a4b23 podman pause 860a4b23
podman pause -a`, podman pause -a`,
@ -35,8 +34,6 @@ func init() {
}) })
flags := pauseCommand.Flags() flags := pauseCommand.Flags()
flags.BoolVarP(&pauseOpts.All, "all", "a", false, "Pause all running containers") 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 { func pause(cmd *cobra.Command, args []string) error {

View File

@ -24,12 +24,11 @@ import (
var ( var (
psDescription = "Prints out information about the containers" psDescription = "Prints out information about the containers"
psCommand = &cobra.Command{ psCommand = &cobra.Command{
Use: "ps", Use: "ps",
Args: checkFlags, Args: checkFlags,
Short: "List containers", Short: "List containers",
Long: psDescription, Long: psDescription,
RunE: ps, RunE: ps,
PreRunE: preRunE,
Example: `podman ps -a Example: `podman ps -a
podman ps -a --format "{{.ID}} {{.Image}} {{.Labels}} {{.Mounts}}" podman ps -a --format "{{.ID}} {{.Image}} {{.Labels}} {{.Mounts}}"
podman ps --size --sort names`, podman ps --size --sort names`,

View File

@ -19,11 +19,10 @@ var (
A timeout before forcibly stopping can be set, but defaults to %d seconds.`, defaultContainerConfig.Engine.StopTimeout) A timeout before forcibly stopping can be set, but defaults to %d seconds.`, defaultContainerConfig.Engine.StopTimeout)
restartCommand = &cobra.Command{ restartCommand = &cobra.Command{
Use: "restart [flags] CONTAINER [CONTAINER...]", Use: "restart [flags] CONTAINER [CONTAINER...]",
Short: "Restart one or more containers", Short: "Restart one or more containers",
Long: restartDescription, Long: restartDescription,
RunE: restart, RunE: restart,
PersistentPreRunE: preRunE,
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
return parse.CheckAllLatestAndCIDFile(cmd, args, false, false) return parse.CheckAllLatestAndCIDFile(cmd, args, false, false)
}, },

View File

@ -19,11 +19,10 @@ var (
Command does not remove images. Running or unusable containers will not be removed without the -f option.` Command does not remove images. Running or unusable containers will not be removed without the -f option.`
rmCommand = &cobra.Command{ rmCommand = &cobra.Command{
Use: "rm [flags] CONTAINER [CONTAINER...]", Use: "rm [flags] CONTAINER [CONTAINER...]",
Short: "Remove one or more containers", Short: "Remove one or more containers",
Long: rmDescription, Long: rmDescription,
RunE: rm, RunE: rm,
PersistentPreRunE: preRunE,
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
return parse.CheckAllLatestAndCIDFile(cmd, args, false, true) return parse.CheckAllLatestAndCIDFile(cmd, args, false, true)
}, },

View File

@ -19,11 +19,10 @@ import (
var ( var (
runDescription = "Runs a command in a new container from the given image" runDescription = "Runs a command in a new container from the given image"
runCommand = &cobra.Command{ runCommand = &cobra.Command{
Use: "run [flags] IMAGE [COMMAND [ARG...]]", Use: "run [flags] IMAGE [COMMAND [ARG...]]",
Short: "Run a command in a new container", Short: "Run a command in a new container",
Long: runDescription, Long: runDescription,
PreRunE: preRunE, RunE: run,
RunE: run,
Example: `podman run imageID ls -alF /etc Example: `podman run imageID ls -alF /etc
podman run --network=host imageID dnf -y install java podman run --network=host imageID dnf -y install java
podman run --volume /var/hostdir:/var/ctrdir -i -t fedora /bin/bash`, 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 { func run(cmd *cobra.Command, args []string) error {
var ( var err error
err error
)
cliVals.Net, err = common.NetFlagsToNetOptions(cmd) cliVals.Net, err = common.NetFlagsToNetOptions(cmd)
if err != nil { if err != nil {
return err return err
} }
if af := cliVals.Authfile; len(af) > 0 { if af := cliVals.Authfile; len(af) > 0 {
if _, err := os.Stat(af); err != nil { if _, err := os.Stat(af); err != nil {
return errors.Wrapf(err, "error checking authfile path %s", af) return errors.Wrapf(err, "error checking authfile path %s", af)
@ -74,11 +72,7 @@ func run(cmd *cobra.Command, args []string) error {
return err return err
} }
ie, err := registry.NewImageEngine(cmd, args) br, err := registry.ImageEngine().Exists(registry.GetContext(), args[0])
if err != nil {
return err
}
br, err := ie.Exists(registry.GetContext(), args[0])
if err != nil { if err != nil {
return err return err
} }
@ -90,7 +84,7 @@ func run(cmd *cobra.Command, args []string) error {
if pullPolicy == config.PullImageNever { if pullPolicy == config.PullImageNever {
return errors.New("unable to find a name and tag match for busybox in repotags: no such image") 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, Authfile: cliVals.Authfile,
Quiet: cliVals.Quiet, Quiet: cliVals.Quiet,
}) })
@ -131,6 +125,7 @@ func run(cmd *cobra.Command, args []string) error {
return err return err
} }
runOpts.Spec = s runOpts.Spec = s
report, err := registry.ContainerEngine().ContainerRun(registry.GetContext(), runOpts) report, err := registry.ContainerEngine().ContainerRun(registry.GetContext(), runOpts)
// report.ExitCode is set by ContainerRun even it it returns an error // report.ExitCode is set by ContainerRun even it it returns an error
if report != nil { if report != nil {

View File

@ -16,12 +16,11 @@ import (
var ( var (
startDescription = `Starts one or more containers. The container name or ID can be used.` startDescription = `Starts one or more containers. The container name or ID can be used.`
startCommand = &cobra.Command{ startCommand = &cobra.Command{
Use: "start [flags] CONTAINER [CONTAINER...]", Use: "start [flags] CONTAINER [CONTAINER...]",
Short: "Start one or more containers", Short: "Start one or more containers",
Long: startDescription, Long: startDescription,
RunE: start, RunE: start,
PreRunE: preRunE, Args: cobra.MinimumNArgs(1),
Args: cobra.MinimumNArgs(1),
Example: `podman start --latest Example: `podman start --latest
podman start 860a4b231279 5421ab43b45 podman start 860a4b231279 5421ab43b45
podman start --interactive --attach imageID`, podman start --interactive --attach imageID`,

View File

@ -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) A timeout to forcibly stop the container can also be set but defaults to %d seconds otherwise.`, defaultContainerConfig.Engine.StopTimeout)
stopCommand = &cobra.Command{ stopCommand = &cobra.Command{
Use: "stop [flags] CONTAINER [CONTAINER...]", Use: "stop [flags] CONTAINER [CONTAINER...]",
Short: "Stop one or more containers", Short: "Stop one or more containers",
Long: stopDescription, Long: stopDescription,
RunE: stop, RunE: stop,
PersistentPreRunE: preRunE,
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
return parse.CheckAllLatestAndCIDFile(cmd, args, false, true) return parse.CheckAllLatestAndCIDFile(cmd, args, false, true)
}, },
@ -63,11 +62,6 @@ func stop(cmd *cobra.Command, args []string) error {
stopOptions.Timeout = stopTimeout 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) responses, err := registry.ContainerEngine().ContainerStop(context.Background(), args, stopOptions)
if err != nil { if err != nil {
return err return err

View File

@ -26,12 +26,11 @@ var (
topOptions = entities.TopOptions{} topOptions = entities.TopOptions{}
topCommand = &cobra.Command{ topCommand = &cobra.Command{
Use: "top [flags] CONTAINER [FORMAT-DESCRIPTORS|ARGS]", Use: "top [flags] CONTAINER [FORMAT-DESCRIPTORS|ARGS]",
Short: "Display the running processes of a container", Short: "Display the running processes of a container",
Long: topDescription, Long: topDescription,
PersistentPreRunE: preRunE, RunE: top,
RunE: top, Args: cobra.ArbitraryArgs,
Args: cobra.ArbitraryArgs,
Example: `podman top ctrID Example: `podman top ctrID
podman top --latest podman top --latest
podman top ctrID pid seccomp args %C podman top ctrID pid seccomp args %C
@ -45,9 +44,6 @@ func init() {
Command: topCommand, Command: topCommand,
}) })
topCommand.SetHelpTemplate(registry.HelpTemplate())
topCommand.SetUsageTemplate(registry.UsageTemplate())
flags := topCommand.Flags() flags := topCommand.Flags()
flags.SetInterspersed(false) flags.SetInterspersed(false)
flags.BoolVar(&topOptions.ListDescriptors, "list-descriptors", false, "") flags.BoolVar(&topOptions.ListDescriptors, "list-descriptors", false, "")

View File

@ -23,7 +23,6 @@ var (
Short: "Unmounts working container's root filesystem", Short: "Unmounts working container's root filesystem",
Long: description, Long: description,
RunE: unmount, RunE: unmount,
PreRunE: preRunE,
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
return parse.CheckAllLatestAndCIDFile(cmd, args, false, false) return parse.CheckAllLatestAndCIDFile(cmd, args, false, false)
}, },

View File

@ -15,11 +15,10 @@ import (
var ( var (
unpauseDescription = `Unpauses one or more previously paused containers. The container name or ID can be used.` unpauseDescription = `Unpauses one or more previously paused containers. The container name or ID can be used.`
unpauseCommand = &cobra.Command{ unpauseCommand = &cobra.Command{
Use: "unpause [flags] CONTAINER [CONTAINER...]", Use: "unpause [flags] CONTAINER [CONTAINER...]",
Short: "Unpause the processes in one or more containers", Short: "Unpause the processes in one or more containers",
Long: unpauseDescription, Long: unpauseDescription,
RunE: unpause, RunE: unpause,
PersistentPreRunE: preRunE,
Example: `podman unpause ctrID Example: `podman unpause ctrID
podman unpause --all`, podman unpause --all`,
} }

View File

@ -17,12 +17,11 @@ var (
waitDescription = `Block until one or more containers stop and then print their exit codes. waitDescription = `Block until one or more containers stop and then print their exit codes.
` `
waitCommand = &cobra.Command{ waitCommand = &cobra.Command{
Use: "wait [flags] CONTAINER [CONTAINER...]", Use: "wait [flags] CONTAINER [CONTAINER...]",
Short: "Block on one or more containers", Short: "Block on one or more containers",
Long: waitDescription, Long: waitDescription,
RunE: wait, RunE: wait,
PersistentPreRunE: preRunE, Args: registry.IdOrLatestArgs,
Args: registry.IdOrLatestArgs,
Example: `podman wait --latest Example: `podman wait --latest
podman wait --interval 5000 ctrID podman wait --interval 5000 ctrID
podman wait ctrID1 ctrID2`, podman wait ctrID1 ctrID2`,

View File

@ -35,9 +35,6 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: diffCmd, Command: diffCmd,
}) })
diffCmd.SetHelpTemplate(registry.HelpTemplate())
diffCmd.SetUsageTemplate(registry.UsageTemplate())
flags := diffCmd.Flags() flags := diffCmd.Flags()
flags.BoolVar(&diffOpts.Archive, "archive", true, "Save the diff as a tar archive") flags.BoolVar(&diffOpts.Archive, "archive", true, "Save the diff as a tar archive")
_ = flags.MarkHidden("archive") _ = flags.MarkHidden("archive")
@ -49,23 +46,13 @@ func init() {
} }
func diff(cmd *cobra.Command, args []string) error { func diff(cmd *cobra.Command, args []string) error {
ie, err := registry.NewImageEngine(cmd, args) if found, err := registry.ImageEngine().Exists(registry.GetContext(), args[0]); err != nil {
if err != nil {
return err
}
if found, err := ie.Exists(registry.GetContext(), args[0]); err != nil {
return err return err
} else if found.Value { } else if found.Value {
return images.Diff(cmd, args, diffOpts) return images.Diff(cmd, args, diffOpts)
} }
ce, err := registry.NewContainerEngine(cmd, args) if found, err := registry.ContainerEngine().ContainerExists(registry.GetContext(), args[0]); err != nil {
if err != nil {
return err
}
if found, err := ce.ContainerExists(registry.GetContext(), args[0]); err != nil {
return err return err
} else if found.Value { } else if found.Value {
return containers.Diff(cmd, args, diffOpts) return containers.Diff(cmd, args, diffOpts)

View File

@ -9,12 +9,11 @@ import (
var ( var (
// Command: healthcheck // Command: healthcheck
healthCmd = &cobra.Command{ healthCmd = &cobra.Command{
Use: "healthcheck", Use: "healthcheck",
Short: "Manage Healthcheck", Short: "Manage Healthcheck",
Long: "Manage Healthcheck", Long: "Manage Healthcheck",
TraverseChildren: true, TraverseChildren: true,
PersistentPreRunE: preRunE, RunE: registry.SubCommandExists,
RunE: registry.SubCommandExists,
} }
) )
@ -23,11 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: healthCmd, 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
} }

View File

@ -11,12 +11,11 @@ import (
var ( var (
// podman container _inspect_ // podman container _inspect_
diffCmd = &cobra.Command{ diffCmd = &cobra.Command{
Use: "diff [flags] CONTAINER", Use: "diff [flags] CONTAINER",
Args: registry.IdOrLatestArgs, Args: registry.IdOrLatestArgs,
Short: "Inspect changes on image's file systems", 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.`, Long: `Displays changes on a image's filesystem. The image will be compared to its parent layer.`,
PreRunE: preRunE, RunE: diff,
RunE: diff,
Example: `podman image diff myImage Example: `podman image diff myImage
podman image diff --format json redis:alpine`, podman image diff --format json redis:alpine`,
} }

View File

@ -25,13 +25,12 @@ var (
// podman _history_ // podman _history_
historyCmd = &cobra.Command{ historyCmd = &cobra.Command{
Use: "history [flags] IMAGE", Use: "history [flags] IMAGE",
Short: "Show history of a specified image", Short: "Show history of a specified image",
Long: long, Long: long,
Example: "podman history quay.io/fedora/fedora", Example: "podman history quay.io/fedora/fedora",
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
PersistentPreRunE: preRunE, RunE: history,
RunE: history,
} }
opts = struct { opts = struct {
@ -48,9 +47,6 @@ func init() {
Command: historyCmd, Command: historyCmd,
}) })
historyCmd.SetHelpTemplate(registry.HelpTemplate())
historyCmd.SetUsageTemplate(registry.UsageTemplate())
flags := historyCmd.Flags() flags := historyCmd.Flags()
flags.StringVar(&opts.format, "format", "", "Change the output to JSON or a Go template") 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") flags.BoolVarP(&opts.human, "human", "H", true, "Display sizes and dates in human readable format")

View File

@ -9,12 +9,11 @@ import (
var ( var (
// Command: podman _image_ // Command: podman _image_
imageCmd = &cobra.Command{ imageCmd = &cobra.Command{
Use: "image", Use: "image",
Short: "Manage images", Short: "Manage images",
Long: "Manage images", Long: "Manage images",
TraverseChildren: true, TraverseChildren: true,
PersistentPreRunE: preRunE, RunE: registry.SubCommandExists,
RunE: registry.SubCommandExists,
} }
) )
@ -23,13 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: imageCmd, 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
} }

View File

@ -15,7 +15,6 @@ var (
Args: listCmd.Args, Args: listCmd.Args,
Short: listCmd.Short, Short: listCmd.Short,
Long: listCmd.Long, Long: listCmd.Long,
PreRunE: preRunE,
RunE: listCmd.RunE, RunE: listCmd.RunE,
Example: strings.Replace(listCmd.Example, "podman image list", "podman images", -1), Example: strings.Replace(listCmd.Example, "podman image list", "podman images", -1),
} }
@ -26,8 +25,6 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: imagesCmd, Command: imagesCmd,
}) })
imagesCmd.SetHelpTemplate(registry.HelpTemplate())
imagesCmd.SetUsageTemplate(registry.UsageTemplate())
imageListFlagSet(imagesCmd.Flags()) imageListFlagSet(imagesCmd.Flags())
} }

View File

@ -18,11 +18,10 @@ var (
Note remote tar balls can be specified, via web address. Note remote tar balls can be specified, via web address.
Optionally tag the image. You can specify the instructions using the --change option.` Optionally tag the image. You can specify the instructions using the --change option.`
importCommand = &cobra.Command{ importCommand = &cobra.Command{
Use: "import [flags] PATH [REFERENCE]", Use: "import [flags] PATH [REFERENCE]",
Short: "Import a tarball to create a filesystem image", Short: "Import a tarball to create a filesystem image",
Long: importDescription, Long: importDescription,
RunE: importCon, RunE: importCon,
PersistentPreRunE: preRunE,
Example: `podman import http://example.com/ctr.tar url-image 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 -q import --message "importing the ctr.tar tarball" - image-imported
cat ctr.tar | podman import -`, cat ctr.tar | podman import -`,
@ -39,8 +38,6 @@ func init() {
Command: importCommand, Command: importCommand,
}) })
importCommand.SetHelpTemplate(registry.HelpTemplate())
importCommand.SetUsageTemplate(registry.UsageTemplate())
flags := importCommand.Flags() 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.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") flags.StringVarP(&importOpts.Message, "message", "m", "", "Set commit message for imported image")

View File

@ -20,12 +20,11 @@ import (
var ( var (
loadDescription = "Loads an image from a locally stored archive (tar file) into container storage." loadDescription = "Loads an image from a locally stored archive (tar file) into container storage."
loadCommand = &cobra.Command{ loadCommand = &cobra.Command{
Use: "load [flags] [NAME[:TAG]]", Use: "load [flags] [NAME[:TAG]]",
Short: "Load an image from container archive", Short: "Load an image from container archive",
Long: loadDescription, Long: loadDescription,
RunE: load, RunE: load,
Args: cobra.MaximumNArgs(1), Args: cobra.MaximumNArgs(1),
PersistentPreRunE: preRunE,
} }
) )
@ -39,8 +38,6 @@ func init() {
Command: loadCommand, Command: loadCommand,
}) })
loadCommand.SetHelpTemplate(registry.HelpTemplate())
loadCommand.SetUsageTemplate(registry.UsageTemplate())
flags := loadCommand.Flags() flags := loadCommand.Flags()
flags.StringVarP(&loadOpts.Input, "input", "i", "", "Read from specified archive file (default: stdin)") flags.StringVarP(&loadOpts.Input, "input", "i", "", "Read from specified archive file (default: stdin)")
flags.BoolVarP(&loadOpts.Quiet, "quiet", "q", false, "Suppress the output") flags.BoolVarP(&loadOpts.Quiet, "quiet", "q", false, "Suppress the output")

View File

@ -7,8 +7,6 @@ import (
"github.com/containers/image/v5/types" "github.com/containers/image/v5/types"
"github.com/containers/libpod/cmd/podmanV2/registry" "github.com/containers/libpod/cmd/podmanV2/registry"
"github.com/containers/libpod/pkg/domain/entities" "github.com/containers/libpod/pkg/domain/entities"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
@ -28,11 +26,11 @@ var (
// Command: podman pull // Command: podman pull
pullCmd = &cobra.Command{ pullCmd = &cobra.Command{
Use: "pull [flags] IMAGE", Use: "pull [flags] IMAGE",
Short: "Pull an image from a registry", Args: cobra.ExactArgs(1),
Long: pullDescription, Short: "Pull an image from a registry",
PreRunE: preRunE, Long: pullDescription,
RunE: imagePull, RunE: imagePull,
Example: `podman pull imageName Example: `podman pull imageName
podman pull fedora:latest`, podman pull fedora:latest`,
} }
@ -41,11 +39,10 @@ var (
// It's basically a clone of `pullCmd` with the exception of being a // It's basically a clone of `pullCmd` with the exception of being a
// child of the images command. // child of the images command.
imagesPullCmd = &cobra.Command{ imagesPullCmd = &cobra.Command{
Use: pullCmd.Use, Use: pullCmd.Use,
Short: pullCmd.Short, Short: pullCmd.Short,
Long: pullCmd.Long, Long: pullCmd.Long,
PreRunE: pullCmd.PreRunE, RunE: pullCmd.RunE,
RunE: pullCmd.RunE,
Example: `podman image pull imageName Example: `podman image pull imageName
podman image pull fedora:latest`, podman image pull fedora:latest`,
} }
@ -58,9 +55,6 @@ func init() {
Command: pullCmd, Command: pullCmd,
}) })
pullCmd.SetHelpTemplate(registry.HelpTemplate())
pullCmd.SetUsageTemplate(registry.UsageTemplate())
flags := pullCmd.Flags() flags := pullCmd.Flags()
pullFlags(flags) pullFlags(flags)
@ -71,8 +65,6 @@ func init() {
Parent: imageCmd, Parent: imageCmd,
}) })
imagesPullCmd.SetHelpTemplate(registry.HelpTemplate())
imagesPullCmd.SetUsageTemplate(registry.UsageTemplate())
imagesPullFlags := imagesPullCmd.Flags() imagesPullFlags := imagesPullCmd.Flags()
pullFlags(imagesPullFlags) pullFlags(imagesPullFlags)
} }
@ -99,20 +91,6 @@ func pullFlags(flags *pflag.FlagSet) {
// imagePull is implement the command for pulling images. // imagePull is implement the command for pulling images.
func imagePull(cmd *cobra.Command, args []string) error { 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 pullOptsAPI := pullOptions.ImagePullOptions
// TLS verification in c/image is controlled via a `types.OptionalBool` // TLS verification in c/image is controlled via a `types.OptionalBool`
// which allows for distinguishing among set-true, set-false, unspecified // which allows for distinguishing among set-true, set-false, unspecified

View File

@ -25,11 +25,10 @@ var (
// Command: podman push // Command: podman push
pushCmd = &cobra.Command{ pushCmd = &cobra.Command{
Use: "push [flags] SOURCE DESTINATION", Use: "push [flags] SOURCE DESTINATION",
Short: "Push an image to a specified destination", Short: "Push an image to a specified destination",
Long: pushDescription, Long: pushDescription,
PreRunE: preRunE, RunE: imagePush,
RunE: imagePush,
Example: `podman push imageID docker://registry.example.com/repository:tag Example: `podman push imageID docker://registry.example.com/repository:tag
podman push imageID oci-archive:/path/to/layout:image: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 // It's basically a clone of `pushCmd` with the exception of being a
// child of the images command. // child of the images command.
imagePushCmd = &cobra.Command{ imagePushCmd = &cobra.Command{
Use: pushCmd.Use, Use: pushCmd.Use,
Short: pushCmd.Short, Short: pushCmd.Short,
Long: pushCmd.Long, Long: pushCmd.Long,
PreRunE: pushCmd.PreRunE, RunE: pushCmd.RunE,
RunE: pushCmd.RunE,
Example: `podman image push imageID docker://registry.example.com/repository:tag Example: `podman image push imageID docker://registry.example.com/repository:tag
podman image push imageID oci-archive:/path/to/layout:image:tag`, podman image push imageID oci-archive:/path/to/layout:image:tag`,
} }
@ -55,9 +53,6 @@ func init() {
Command: pushCmd, Command: pushCmd,
}) })
pushCmd.SetHelpTemplate(registry.HelpTemplate())
pushCmd.SetUsageTemplate(registry.UsageTemplate())
flags := pushCmd.Flags() flags := pushCmd.Flags()
pushFlags(flags) pushFlags(flags)
@ -68,8 +63,6 @@ func init() {
Parent: imageCmd, Parent: imageCmd,
}) })
imagePushCmd.SetHelpTemplate(registry.HelpTemplate())
imagePushCmd.SetUsageTemplate(registry.UsageTemplate())
pushFlags(imagePushCmd.Flags()) pushFlags(imagePushCmd.Flags())
} }

View File

@ -14,11 +14,10 @@ import (
var ( var (
rmDescription = "Removes one or more previously pulled or locally created images." rmDescription = "Removes one or more previously pulled or locally created images."
rmCmd = &cobra.Command{ rmCmd = &cobra.Command{
Use: "rm [flags] IMAGE [IMAGE...]", Use: "rm [flags] IMAGE [IMAGE...]",
Short: "Removes one or more images from local storage", Short: "Removes one or more images from local storage",
Long: rmDescription, Long: rmDescription,
PreRunE: preRunE, RunE: rm,
RunE: rm,
Example: `podman image rm imageID Example: `podman image rm imageID
podman image rm --force alpine podman image rm --force alpine
podman image rm c4dfb1609ee2 93fd78260bd1 c0ed59d05ff7`, podman image rm c4dfb1609ee2 93fd78260bd1 c0ed59d05ff7`,

View File

@ -14,7 +14,6 @@ var (
Args: rmCmd.Args, Args: rmCmd.Args,
Short: rmCmd.Short, Short: rmCmd.Short,
Long: rmCmd.Long, Long: rmCmd.Long,
PreRunE: rmCmd.PreRunE,
RunE: rmCmd.RunE, RunE: rmCmd.RunE,
Example: strings.Replace(rmCmd.Example, "podman image rm", "podman rmi", -1), Example: strings.Replace(rmCmd.Example, "podman image rm", "podman rmi", -1),
} }
@ -25,7 +24,5 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: rmiCmd, Command: rmiCmd,
}) })
rmiCmd.SetHelpTemplate(registry.HelpTemplate())
rmiCmd.SetUsageTemplate(registry.UsageTemplate())
imageRemoveFlagSet(rmiCmd.Flags()) imageRemoveFlagSet(rmiCmd.Flags())
} }

View File

@ -22,11 +22,10 @@ var (
saveDescription = `Save an image to docker-archive or oci-archive on the local machine. Default is docker-archive.` saveDescription = `Save an image to docker-archive or oci-archive on the local machine. Default is docker-archive.`
saveCommand = &cobra.Command{ saveCommand = &cobra.Command{
Use: "save [flags] IMAGE", Use: "save [flags] IMAGE",
Short: "Save image to an archive", Short: "Save image to an archive",
Long: saveDescription, Long: saveDescription,
PersistentPreRunE: preRunE, RunE: save,
RunE: save,
Args: func(cmd *cobra.Command, args []string) error { Args: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 { if len(args) == 0 {
return errors.Errorf("need at least 1 argument") return errors.Errorf("need at least 1 argument")

View File

@ -32,12 +32,14 @@ var (
// Command: podman search // Command: podman search
searchCmd = &cobra.Command{ searchCmd = &cobra.Command{
Use: "search [flags] TERM", Use: "search [flags] TERM",
Short: "Search registry for image", Short: "Search registry for image",
Long: searchDescription, Long: searchDescription,
PreRunE: preRunE, RunE: imageSearch,
RunE: imageSearch, Args: cobra.ExactArgs(1),
Args: cobra.ExactArgs(1), Annotations: map[string]string{
registry.ParentNSRequired: "",
},
Example: `podman search --filter=is-official --limit 3 alpine Example: `podman search --filter=is-official --limit 3 alpine
podman search registry.fedoraproject.org/ # only works with v2 registries podman search registry.fedoraproject.org/ # only works with v2 registries
podman search --format "table {{.Index}} {{.Name}}" registry.fedoraproject.org/fedora`, podman search --format "table {{.Index}} {{.Name}}" registry.fedoraproject.org/fedora`,
@ -45,12 +47,11 @@ var (
// Command: podman image search // Command: podman image search
imageSearchCmd = &cobra.Command{ imageSearchCmd = &cobra.Command{
Use: searchCmd.Use, Use: searchCmd.Use,
Short: searchCmd.Short, Short: searchCmd.Short,
Long: searchCmd.Long, Long: searchCmd.Long,
PreRunE: searchCmd.PreRunE, RunE: searchCmd.RunE,
RunE: searchCmd.RunE, Args: searchCmd.Args,
Args: searchCmd.Args,
Example: `podman image search --filter=is-official --limit 3 alpine Example: `podman image search --filter=is-official --limit 3 alpine
podman image search registry.fedoraproject.org/ # only works with v2 registries podman image search registry.fedoraproject.org/ # only works with v2 registries
podman image search --format "table {{.Index}} {{.Name}}" registry.fedoraproject.org/fedora`, podman image search --format "table {{.Index}} {{.Name}}" registry.fedoraproject.org/fedora`,
@ -64,8 +65,6 @@ func init() {
Command: searchCmd, Command: searchCmd,
}) })
searchCmd.SetHelpTemplate(registry.HelpTemplate())
searchCmd.SetUsageTemplate(registry.UsageTemplate())
flags := searchCmd.Flags() flags := searchCmd.Flags()
searchFlags(flags) searchFlags(flags)

View File

@ -9,12 +9,11 @@ import (
var ( var (
tagDescription = "Adds one or more additional names to locally-stored image." tagDescription = "Adds one or more additional names to locally-stored image."
tagCommand = &cobra.Command{ tagCommand = &cobra.Command{
Use: "tag [flags] IMAGE TARGET_NAME [TARGET_NAME...]", Use: "tag [flags] IMAGE TARGET_NAME [TARGET_NAME...]",
Short: "Add an additional name to a local image", Short: "Add an additional name to a local image",
Long: tagDescription, Long: tagDescription,
RunE: tag, RunE: tag,
PreRunE: preRunE, Args: cobra.MinimumNArgs(2),
Args: cobra.MinimumNArgs(2),
Example: `podman tag 0e3bbc2 fedora:latest Example: `podman tag 0e3bbc2 fedora:latest
podman tag imageID:latest myNewImage:newTag podman tag imageID:latest myNewImage:newTag
podman tag httpd myregistryhost:5000/fedora/httpd:v2`, podman tag httpd myregistryhost:5000/fedora/httpd:v2`,
@ -26,8 +25,6 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: tagCommand, Command: tagCommand,
}) })
tagCommand.SetHelpTemplate(registry.HelpTemplate())
tagCommand.SetUsageTemplate(registry.UsageTemplate())
} }
func tag(cmd *cobra.Command, args []string) error { func tag(cmd *cobra.Command, args []string) error {

View File

@ -24,8 +24,6 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: untagCommand, Command: untagCommand,
}) })
untagCommand.SetHelpTemplate(registry.HelpTemplate())
untagCommand.SetUsageTemplate(registry.UsageTemplate())
} }
func untag(cmd *cobra.Command, args []string) error { func untag(cmd *cobra.Command, args []string) error {

View File

@ -37,23 +37,13 @@ func init() {
} }
func inspect(cmd *cobra.Command, args []string) error { func inspect(cmd *cobra.Command, args []string) error {
ie, err := registry.NewImageEngine(cmd, args) if found, err := registry.ImageEngine().Exists(context.Background(), args[0]); err != nil {
if err != nil {
return err
}
if found, err := ie.Exists(context.Background(), args[0]); err != nil {
return err return err
} else if found.Value { } else if found.Value {
return images.Inspect(cmd, args, inspectOpts) return images.Inspect(cmd, args, inspectOpts)
} }
ce, err := registry.NewContainerEngine(cmd, args) if found, err := registry.ContainerEngine().ContainerExists(context.Background(), args[0]); err != nil {
if err != nil {
return err
}
if found, err := ce.ContainerExists(context.Background(), args[0]); err != nil {
return err return err
} else if found.Value { } else if found.Value {
return containers.Inspect(cmd, args, inspectOpts) return containers.Inspect(cmd, args, inspectOpts)

View File

@ -2,7 +2,6 @@ package main
import ( import (
"os" "os"
"reflect"
_ "github.com/containers/libpod/cmd/podmanV2/containers" _ "github.com/containers/libpod/cmd/podmanV2/containers"
_ "github.com/containers/libpod/cmd/podmanV2/healthcheck" _ "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. // had a specific job to do as a subprocess, and it's done.
return return
} }
for _, c := range registry.Commands { for _, c := range registry.Commands {
if Contains(registry.PodmanOptions.EngineMode, c.Mode) { for _, m := range c.Mode {
parent := rootCmd if registry.PodmanOptions.EngineMode == m {
if c.Parent != nil { parent := rootCmd
parent = c.Parent 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() Execute()
os.Exit(0) 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
}

View File

@ -9,12 +9,11 @@ import (
var ( var (
// Command: podman _network_ // Command: podman _network_
cmd = &cobra.Command{ cmd = &cobra.Command{
Use: "network", Use: "network",
Short: "Manage networks", Short: "Manage networks",
Long: "Manage networks", Long: "Manage networks",
TraverseChildren: true, TraverseChildren: true,
PersistentPreRunE: preRunE, RunE: registry.SubCommandExists,
RunE: registry.SubCommandExists,
} }
) )
@ -23,11 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode}, Mode: []entities.EngineMode{entities.ABIMode},
Command: cmd, 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
} }

View File

@ -9,12 +9,11 @@ import (
var ( var (
// Command: podman _pod_ // Command: podman _pod_
podCmd = &cobra.Command{ podCmd = &cobra.Command{
Use: "pod", Use: "pod",
Short: "Manage pods", Short: "Manage pods",
Long: "Manage pods", Long: "Manage pods",
TraverseChildren: true, TraverseChildren: true,
PersistentPreRunE: preRunE, RunE: registry.SubCommandExists,
RunE: registry.SubCommandExists,
} }
) )
@ -23,11 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: podCmd, 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
} }

View File

@ -24,12 +24,11 @@ var (
topOptions = entities.PodTopOptions{} topOptions = entities.PodTopOptions{}
topCommand = &cobra.Command{ topCommand = &cobra.Command{
Use: "top [flags] POD [FORMAT-DESCRIPTORS|ARGS]", Use: "top [flags] POD [FORMAT-DESCRIPTORS|ARGS]",
Short: "Display the running processes in a pod", Short: "Display the running processes in a pod",
Long: topDescription, Long: topDescription,
PersistentPreRunE: preRunE, RunE: top,
RunE: top, Args: cobra.ArbitraryArgs,
Args: cobra.ArbitraryArgs,
Example: `podman pod top podID Example: `podman pod top podID
podman pod top --latest podman pod top --latest
podman pod top podID pid seccomp args %C podman pod top podID pid seccomp args %C
@ -44,9 +43,6 @@ func init() {
Parent: podCmd, Parent: podCmd,
}) })
topCommand.SetHelpTemplate(registry.HelpTemplate())
topCommand.SetUsageTemplate(registry.UsageTemplate())
flags := topCommand.Flags() flags := topCommand.Flags()
flags.SetInterspersed(false) flags.SetInterspersed(false)
flags.BoolVar(&topOptions.ListDescriptors, "list-descriptors", false, "") flags.BoolVar(&topOptions.ListDescriptors, "list-descriptors", false, "")

View File

@ -12,11 +12,10 @@ import (
"github.com/containers/libpod/pkg/rootless" "github.com/containers/libpod/pkg/rootless"
"github.com/containers/libpod/pkg/util" "github.com/containers/libpod/pkg/util"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus"
) )
const ( const (
RootRequired = "RootRequired" ParentNSRequired = "ParentNSRequired"
) )
var ( var (
@ -26,7 +25,7 @@ var (
// NewPodmanConfig creates a PodmanConfig from the environment // NewPodmanConfig creates a PodmanConfig from the environment
func NewPodmanConfig() entities.PodmanConfig { func NewPodmanConfig() entities.PodmanConfig {
if err := setXdgDirs(); err != nil { if err := setXdgDirs(); err != nil {
logrus.Errorf(err.Error()) fmt.Fprintf(os.Stderr, err.Error())
os.Exit(1) os.Exit(1)
} }
@ -39,7 +38,7 @@ func NewPodmanConfig() entities.PodmanConfig {
case "linux": case "linux":
mode = entities.ABIMode mode = entities.ABIMode
default: 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) os.Exit(1)
} }
@ -47,18 +46,23 @@ func NewPodmanConfig() entities.PodmanConfig {
for _, v := range os.Args { for _, v := range os.Args {
// Prefix checking works because of how default EngineMode's // Prefix checking works because of how default EngineMode's
// have been defined. // have been defined.
if strings.HasPrefix(v, "--remote=") { if strings.HasPrefix(v, "--remote") {
mode = entities.TunnelMode mode = entities.TunnelMode
} }
} }
// FIXME: for rootless, where to get the path // FIXME: for rootless, add flag to get the path to override configuration
// TODO:
cfg, err := config.NewConfig("") cfg, err := config.NewConfig("")
if err != nil { if err != nil {
logrus.Error("Failed to obtain podman configuration") fmt.Fprint(os.Stderr, "Failed to obtain podman configuration: "+err.Error())
os.Exit(1) os.Exit(1)
} }
cfg.Network.NetworkConfigDir = cfg.Network.CNIPluginDirs[0]
if rootless.IsRootless() {
cfg.Network.NetworkConfigDir = ""
}
return entities.PodmanConfig{Config: cfg, EngineMode: mode} return entities.PodmanConfig{Config: cfg, EngineMode: mode}
} }
@ -71,34 +75,31 @@ func setXdgDirs() error {
} }
// Setup XDG_RUNTIME_DIR // Setup XDG_RUNTIME_DIR
runtimeDir := os.Getenv("XDG_RUNTIME_DIR") if _, found := os.LookupEnv("XDG_RUNTIME_DIR"); !found {
dir, err := util.GetRuntimeDir()
if runtimeDir == "" {
var err error
runtimeDir, err = util.GetRuntimeDir()
if err != nil { if err != nil {
return err return err
} }
} if err := os.Setenv("XDG_RUNTIME_DIR", dir); err != nil {
if err := os.Setenv("XDG_RUNTIME_DIR", runtimeDir); err != nil { return errors.Wrapf(err, "cannot set XDG_RUNTIME_DIR="+dir)
return errors.Wrapf(err, "cannot set XDG_RUNTIME_DIR") }
} }
if rootless.IsRootless() && os.Getenv("DBUS_SESSION_BUS_ADDRESS") == "" { if _, found := os.LookupEnv("DBUS_SESSION_BUS_ADDRESS"); !found {
sessionAddr := filepath.Join(runtimeDir, "bus") sessionAddr := filepath.Join(os.Getenv("XDG_RUNTIME_DIR"), "bus")
if _, err := os.Stat(sessionAddr); err == nil { 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 // Setup XDG_CONFIG_HOME
if cfgHomeDir := os.Getenv("XDG_CONFIG_HOME"); cfgHomeDir == "" { if _, found := os.LookupEnv("XDG_CONFIG_HOME"); !found {
cfgHomeDir, err := util.GetRootlessConfigHomeDir() cfgHomeDir, err := util.GetRootlessConfigHomeDir()
if err != nil { if err != nil {
return err return err
} }
if err := os.Setenv("XDG_CONFIG_HOME", cfgHomeDir); err != nil { 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 return nil

View File

@ -42,41 +42,6 @@ func GetExitCode() int {
return exitCode 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 { func ImageEngine() entities.ImageEngine {
return imageEngine return imageEngine
} }
@ -126,17 +91,26 @@ func IdOrLatestArgs(cmd *cobra.Command, args []string) error {
return nil return nil
} }
func GetContext() context.Context { type PodmanOptionsKey struct{}
func Context() context.Context {
if cliCtx == nil { if cliCtx == nil {
cliCtx = context.Background() cliCtx = ContextWithOptions(context.Background())
} }
return cliCtx return cliCtx
} }
type ContextOptionsKey string func ContextWithOptions(ctx context.Context) context.Context {
cliCtx = context.WithValue(ctx, PodmanOptionsKey{}, PodmanOptions)
const PodmanOptionsKey ContextOptionsKey = "PodmanOptions" return cliCtx
}
func GetContextWithOptions() context.Context {
return context.WithValue(GetContext(), PodmanOptionsKey, PodmanOptions) // GetContextWithOptions deprecated, use NewContextWithOptions()
func GetContextWithOptions() context.Context {
return ContextWithOptions(context.Background())
}
// GetContext deprecated, use Context()
func GetContext() context.Context {
return Context()
} }

View File

@ -1,12 +1,12 @@
package main package main
import ( import (
"context"
"fmt" "fmt"
"log/syslog" "log/syslog"
"os" "os"
"path" "path"
"runtime/pprof" "runtime/pprof"
"strings"
"github.com/containers/libpod/cmd/podmanV2/registry" "github.com/containers/libpod/cmd/podmanV2/registry"
"github.com/containers/libpod/pkg/domain/entities" "github.com/containers/libpod/pkg/domain/entities"
@ -21,6 +21,37 @@ import (
"github.com/spf13/pflag" "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 ( var (
rootCmd = &cobra.Command{ rootCmd = &cobra.Command{
Use: path.Base(os.Args[0]), Use: path.Base(os.Args[0]),
@ -28,20 +59,20 @@ var (
SilenceUsage: true, SilenceUsage: true,
SilenceErrors: true, SilenceErrors: true,
TraverseChildren: true, TraverseChildren: true,
PersistentPreRunE: preRunE, PersistentPreRunE: persistentPreRunE,
RunE: registry.SubCommandExists, RunE: registry.SubCommandExists,
PersistentPostRunE: postRunE, PersistentPostRunE: persistentPostRunE,
Version: version.Version, Version: version.Version,
} }
logLevels = entities.NewStringSet("debug", "info", "warn", "error", "fatal", "panic") logLevels = []string{"debug", "info", "warn", "error", "fatal", "panic"}
logLevel = "error" logLevel = "error"
useSyslog bool useSyslog bool
) )
func init() { func init() {
// Hooks are called before PersistentPreRunE()
cobra.OnInitialize( cobra.OnInitialize(
rootlessHook,
loggingHook, loggingHook,
syslogHook, syslogHook,
) )
@ -63,13 +94,21 @@ func Execute() {
os.Exit(registry.GetExitCode()) 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 // Update PodmanOptions now that we "know" more
// TODO: pass in path overriding configuration file // TODO: pass in path overriding configuration file
registry.PodmanOptions = registry.NewPodmanConfig() registry.PodmanOptions = registry.NewPodmanConfig()
cmd.SetHelpTemplate(registry.HelpTemplate()) // Prep the engines
cmd.SetUsageTemplate(registry.UsageTemplate()) 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 { if cmd.Flag("cpu-profile").Changed {
f, err := os.Create(registry.PodmanOptions.CpuProfile) f, err := os.Create(registry.PodmanOptions.CpuProfile)
@ -88,12 +127,28 @@ func preRunE(cmd *cobra.Command, _ []string) error {
registry.PodmanOptions.SpanCloser = closer registry.PodmanOptions.SpanCloser = closer
registry.PodmanOptions.Span = tracer.StartSpan("before-context") 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 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 { if cmd.Flag("cpu-profile").Changed {
pprof.StopCPUProfile() pprof.StopCPUProfile()
} }
@ -105,14 +160,21 @@ func postRunE(cmd *cobra.Command, args []string) error {
} }
func loggingHook() { func loggingHook() {
if !logLevels.Contains(logLevel) { var found bool
logrus.Errorf("Log Level \"%s\" is not supported, choose from: %s", logLevel, logLevels.String()) 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) os.Exit(1)
} }
level, err := logrus.ParseLevel(logLevel) level, err := logrus.ParseLevel(logLevel)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, err.Error()) fmt.Fprint(os.Stderr, err.Error())
os.Exit(1) os.Exit(1)
} }
logrus.SetLevel(level) logrus.SetLevel(level)
@ -123,26 +185,18 @@ func loggingHook() {
} }
func syslogHook() { func syslogHook() {
if useSyslog { if !useSyslog {
hook, err := logrusSyslog.NewSyslogHook("", "", syslog.LOG_INFO, "") return
if err != nil {
logrus.WithError(err).Error("Failed to initialize syslog hook")
}
if err == nil {
logrus.AddHook(hook)
}
} }
}
func rootlessHook() { hook, err := logrusSyslog.NewSyslogHook("", "", syslog.LOG_INFO, "")
if rootless.IsRootless() { if err != nil {
logrus.Error("rootless mode is currently not supported. Support will return ASAP.") 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) { 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 // Override default --help information of `--help` global flag
var dummyHelp bool var dummyHelp bool
flags.BoolVar(&dummyHelp, "help", false, "Help for podman") 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 // Hide these flags for both ABI and Tunneling
for _, f := range []string{ for _, f := range []string{
@ -189,7 +243,7 @@ func rootFlags(opts entities.PodmanConfig, flags *pflag.FlagSet) {
"trace", "trace",
} { } {
if err := flags.MarkHidden(f); err != nil { 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() { if !registry.IsRemote() {
flags.BoolVar(&useSyslog, "syslog", false, "Output logging information to syslog as well as the console (default false)") flags.BoolVar(&useSyslog, "syslog", false, "Output logging information to syslog as well as the console (default false)")
} }
} }

View File

@ -17,12 +17,11 @@ import (
var ( var (
eventsDescription = "Monitor podman events" eventsDescription = "Monitor podman events"
eventsCommand = &cobra.Command{ eventsCommand = &cobra.Command{
Use: "events", Use: "events",
Args: cobra.NoArgs, Args: cobra.NoArgs,
Short: "Show podman events", Short: "Show podman events",
Long: eventsDescription, Long: eventsDescription,
PersistentPreRunE: preRunE, RunE: eventsCmd,
RunE: eventsCmd,
Example: `podman events Example: `podman events
podman events --filter event=create podman events --filter event=create
podman events --since 1h30s`, podman events --since 1h30s`,

View File

@ -22,7 +22,6 @@ var (
Args: cobra.NoArgs, Args: cobra.NoArgs,
Long: infoDescription, Long: infoDescription,
Short: "Display podman system information", Short: "Display podman system information",
PreRunE: preRunE,
RunE: info, RunE: info,
Example: `podman info`, Example: `podman info`,
} }

View File

@ -9,12 +9,11 @@ import (
var ( var (
// Command: podman _system_ // Command: podman _system_
systemCmd = &cobra.Command{ systemCmd = &cobra.Command{
Use: "system", Use: "system",
Short: "Manage podman", Short: "Manage podman",
Long: "Manage podman", Long: "Manage podman",
TraverseChildren: true, TraverseChildren: true,
PersistentPreRunE: preRunE, RunE: registry.SubCommandExists,
RunE: registry.SubCommandExists,
} }
) )
@ -23,11 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: systemCmd, 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
} }

View File

@ -14,12 +14,11 @@ var (
Tools speaking varlink protocol can remotely manage pods, containers and images. Tools speaking varlink protocol can remotely manage pods, containers and images.
` `
varlinkCmd = &cobra.Command{ varlinkCmd = &cobra.Command{
Use: "varlink [flags] [URI]", Use: "varlink [flags] [URI]",
Args: cobra.MinimumNArgs(1), Args: cobra.MinimumNArgs(1),
Short: "Run varlink interface", Short: "Run varlink interface",
Long: varlinkDescription, Long: varlinkDescription,
PreRunE: preRunE, RunE: varlinkE,
RunE: varlinkE,
Example: `podman varlink unix:/run/podman/io.podman Example: `podman varlink unix:/run/podman/io.podman
podman varlink --timeout 5000 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}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: varlinkCmd, Command: varlinkCmd,
}) })
varlinkCmd.SetHelpTemplate(registry.HelpTemplate())
varlinkCmd.SetUsageTemplate(registry.UsageTemplate())
flags := varlinkCmd.Flags() 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.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") flags.Int64Var(&varlinkArgs.Timeout, "timeout", 1000, "Time until the varlink session expires in milliseconds. Use 0 to disable the timeout")

View File

@ -18,11 +18,13 @@ import (
var ( var (
versionCommand = &cobra.Command{ versionCommand = &cobra.Command{
Use: "version", Use: "version",
Args: cobra.NoArgs, Args: cobra.NoArgs,
Short: "Display the Podman Version Information", Short: "Display the Podman Version Information",
RunE: version, RunE: version,
PersistentPreRunE: preRunE, Annotations: map[string]string{
registry.ParentNSRequired: "",
},
} }
versionFormat string versionFormat string
) )

View File

@ -9,12 +9,11 @@ import (
var ( var (
// Command: podman _volume_ // Command: podman _volume_
volumeCmd = &cobra.Command{ volumeCmd = &cobra.Command{
Use: "volume", Use: "volume",
Short: "Manage volumes", Short: "Manage volumes",
Long: "Volumes are created in and can be shared between containers", Long: "Volumes are created in and can be shared between containers",
TraverseChildren: true, TraverseChildren: true,
PersistentPreRunE: preRunE, RunE: registry.SubCommandExists,
RunE: registry.SubCommandExists,
} }
) )
@ -23,11 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode}, Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: volumeCmd, 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
} }

View File

@ -2,17 +2,9 @@ package entities
import ( import (
"context" "context"
"fmt"
"io" "io"
"os"
"github.com/containers/buildah/pkg/parse"
"github.com/containers/common/pkg/config" "github.com/containers/common/pkg/config"
"github.com/containers/common/pkg/sysinfo"
"github.com/containers/libpod/pkg/apparmor"
"github.com/containers/libpod/pkg/cgroups"
"github.com/containers/libpod/pkg/rootless"
"github.com/opencontainers/selinux/go-selinux"
"github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go"
"github.com/spf13/pflag" "github.com/spf13/pflag"
) )
@ -54,214 +46,3 @@ type PodmanConfig struct {
StorageDriver string StorageDriver string
StorageOpts []string StorageOpts []string
} }
// DefaultSecurityOptions: getter for security options from configuration
func (c PodmanConfig) DefaultSecurityOptions() []string {
securityOpts := []string{}
if c.Containers.SeccompProfile != "" && c.Containers.SeccompProfile != parse.SeccompDefaultPath {
securityOpts = append(securityOpts, fmt.Sprintf("seccomp=%s", c.Containers.SeccompProfile))
}
if apparmor.IsEnabled() && c.Containers.ApparmorProfile != "" {
securityOpts = append(securityOpts, fmt.Sprintf("apparmor=%s", c.Containers.ApparmorProfile))
}
if selinux.GetEnabled() && !c.Containers.EnableLabeling {
securityOpts = append(securityOpts, fmt.Sprintf("label=%s", selinux.DisableSecOpt()[0]))
}
return securityOpts
}
// DefaultSysctls
func (c PodmanConfig) DefaultSysctls() []string {
return c.Containers.DefaultSysctls
}
func (c PodmanConfig) DefaultVolumes() []string {
return c.Containers.Volumes
}
func (c PodmanConfig) DefaultDevices() []string {
return c.Containers.Devices
}
func (c PodmanConfig) DefaultDNSServers() []string {
return c.Containers.DNSServers
}
func (c PodmanConfig) DefaultDNSSearches() []string {
return c.Containers.DNSSearches
}
func (c PodmanConfig) DefaultDNSOptions() []string {
return c.Containers.DNSOptions
}
func (c PodmanConfig) DefaultEnv() []string {
return c.Containers.Env
}
func (c PodmanConfig) DefaultInitPath() string {
return c.Containers.InitPath
}
func (c PodmanConfig) DefaultIPCNS() string {
return c.Containers.IPCNS
}
func (c PodmanConfig) DefaultPidNS() string {
return c.Containers.PidNS
}
func (c PodmanConfig) DefaultNetNS() string {
if c.Containers.NetNS == "private" && rootless.IsRootless() {
return "slirp4netns"
}
return c.Containers.NetNS
}
func (c PodmanConfig) DefaultCgroupNS() string {
return c.Containers.CgroupNS
}
func (c PodmanConfig) DefaultUTSNS() string {
return c.Containers.UTSNS
}
func (c PodmanConfig) DefaultShmSize() string {
return c.Containers.ShmSize
}
func (c PodmanConfig) DefaultUlimits() []string {
return c.Containers.DefaultUlimits
}
func (c PodmanConfig) DefaultUserNS() string {
if v, found := os.LookupEnv("PODMAN_USERNS"); found {
return v
}
return c.Containers.UserNS
}
func (c PodmanConfig) DefaultPidsLimit() int64 {
if rootless.IsRootless() {
cgroup2, _ := cgroups.IsCgroup2UnifiedMode()
if cgroup2 {
return c.Containers.PidsLimit
}
}
return sysinfo.GetDefaultPidsLimit()
}
func (c PodmanConfig) DefaultPidsDescription() string {
return "Tune container pids limit (set 0 for unlimited)"
}
func (c PodmanConfig) DefaultDetachKeys() string {
return c.Engine.DetachKeys
}
// TODO: Remove in rootless support PR
// // EngineOptions holds the environment for running the engines
// type EngineOptions struct {
// // Introduced with V2
// Uri string
// Identities []string
// FlagSet *pflag.FlagSet
// EngineMode EngineMode
// CGroupUsage string
//
// // Introduced with V1
// CGroupManager string // config.EngineConfig
// CniConfigDir string // config.NetworkConfig.NetworkConfigDir
// ConmonPath string // config.EngineConfig
// DefaultMountsFile string // config.ContainersConfig
// EventsBackend string // config.EngineConfig.EventsLogger
// HooksDir []string // config.EngineConfig
// MaxWorks int
// Namespace string // config.EngineConfig
// Root string //
// Runroot string // config.EngineConfig.StorageConfigRunRootSet??
// Runtime string // config.EngineConfig.OCIRuntime
// StorageDriver string // config.EngineConfig.StorageConfigGraphDriverNameSet??
// StorageOpts []string
// Syslog bool
// Trace bool
// NetworkCmdPath string // config.EngineConfig
//
// Config string
// CpuProfile string
// LogLevel string
// TmpDir string // config.EngineConfig
//
// RemoteUserName string // deprecated
// RemoteHost string // deprecated
// VarlinkAddress string // deprecated
// ConnectionName string
// RemoteConfigFilePath string
// Port int // deprecated
// IdentityFile string // deprecated
// IgnoreHosts bool
// }
//
// func NewEngineOptions(opts EngineOptions) (EngineOptions, error) {
// ctnrCfg, err := config.Default()
// if err != nil {
// logrus.Error(err)
// os.Exit(1)
// }
//
// cgroupManager := ctnrCfg.Engine.CgroupManager
// cgroupUsage := `Cgroup manager to use ("cgroupfs"|"systemd")`
// cgroupv2, _ := cgroups.IsCgroup2UnifiedMode()
// cniPluginDir := ctnrCfg.Network.CNIPluginDirs[0]
//
// cfg, err := config.NewConfig("")
// if err != nil {
// logrus.Errorf("Error loading container config %v\n", err)
// os.Exit(1)
// }
// cfg.CheckCgroupsAndAdjustConfig()
//
// if rootless.IsRootless() {
// if !cgroupv2 {
// cgroupManager = ""
// cgroupUsage = "Cgroup manager is not supported in rootless mode"
// }
// cniPluginDir = ""
// }
//
// return EngineOptions{
// CGroupManager: cgroupManager,
// CGroupUsage: cgroupUsage,
// CniConfigDir: cniPluginDir,
// Config: opts.Config, // TODO: deprecate
// ConmonPath: opts.ConmonPath,
// ConnectionName: opts.ConnectionName,
// CpuProfile: opts.CpuProfile,
// DefaultMountsFile: ctnrCfg.Containers.DefaultMountsFile,
// EngineMode: opts.EngineMode,
// EventsBackend: ctnrCfg.Engine.EventsLogger,
// FlagSet: opts.FlagSet, // TODO: deprecate
// HooksDir: append(ctnrCfg.Engine.HooksDir[:0:0], ctnrCfg.Engine.HooksDir...),
// Identities: append(opts.Identities[:0:0], opts.Identities...),
// IdentityFile: opts.IdentityFile, // TODO: deprecate
// IgnoreHosts: opts.IgnoreHosts,
// LogLevel: opts.LogLevel,
// MaxWorks: opts.MaxWorks,
// Namespace: ctnrCfg.Engine.Namespace,
// NetworkCmdPath: ctnrCfg.Engine.NetworkCmdPath,
// Port: opts.Port,
// RemoteConfigFilePath: opts.RemoteConfigFilePath,
// RemoteHost: opts.RemoteHost, // TODO: deprecate
// RemoteUserName: opts.RemoteUserName, // TODO: deprecate
// Root: opts.Root,
// Runroot: opts.Runroot,
// Runtime: opts.Runtime,
// StorageDriver: opts.StorageDriver,
// StorageOpts: append(opts.StorageOpts[:0:0], opts.StorageOpts...),
// Syslog: opts.Syslog,
// TmpDir: opts.TmpDir,
// Trace: opts.Trace,
// Uri: opts.Uri,
// VarlinkAddress: opts.VarlinkAddress,
// }, nil
// }

View File

@ -6,6 +6,7 @@ import (
"github.com/containers/common/pkg/config" "github.com/containers/common/pkg/config"
"github.com/containers/libpod/libpod/define" "github.com/containers/libpod/libpod/define"
"github.com/containers/libpod/pkg/specgen" "github.com/containers/libpod/pkg/specgen"
"github.com/spf13/cobra"
) )
type ContainerEngine interface { type ContainerEngine interface {
@ -24,9 +25,9 @@ type ContainerEngine interface {
ContainerInspect(ctx context.Context, namesOrIds []string, options InspectOptions) ([]*ContainerInspectReport, error) ContainerInspect(ctx context.Context, namesOrIds []string, options InspectOptions) ([]*ContainerInspectReport, error)
ContainerKill(ctx context.Context, namesOrIds []string, options KillOptions) ([]*KillReport, error) ContainerKill(ctx context.Context, namesOrIds []string, options KillOptions) ([]*KillReport, error)
ContainerList(ctx context.Context, options ContainerListOptions) ([]ListContainer, error) ContainerList(ctx context.Context, options ContainerListOptions) ([]ListContainer, error)
ContainerLogs(ctx context.Context, containers []string, options ContainerLogsOptions) error
ContainerMount(ctx context.Context, nameOrIds []string, options ContainerMountOptions) ([]*ContainerMountReport, error) ContainerMount(ctx context.Context, nameOrIds []string, options ContainerMountOptions) ([]*ContainerMountReport, error)
ContainerPause(ctx context.Context, namesOrIds []string, options PauseUnPauseOptions) ([]*PauseUnpauseReport, error) ContainerPause(ctx context.Context, namesOrIds []string, options PauseUnPauseOptions) ([]*PauseUnpauseReport, error)
ContainerLogs(ctx context.Context, containers []string, options ContainerLogsOptions) error
ContainerRestart(ctx context.Context, namesOrIds []string, options RestartOptions) ([]*RestartReport, error) ContainerRestart(ctx context.Context, namesOrIds []string, options RestartOptions) ([]*RestartReport, error)
ContainerRestore(ctx context.Context, namesOrIds []string, options RestoreOptions) ([]*RestoreReport, error) ContainerRestore(ctx context.Context, namesOrIds []string, options RestoreOptions) ([]*RestoreReport, error)
ContainerRm(ctx context.Context, namesOrIds []string, options RmOptions) ([]*RmReport, error) ContainerRm(ctx context.Context, namesOrIds []string, options RmOptions) ([]*RmReport, error)
@ -53,6 +54,7 @@ type ContainerEngine interface {
PodTop(ctx context.Context, options PodTopOptions) (*StringSliceReport, error) PodTop(ctx context.Context, options PodTopOptions) (*StringSliceReport, error)
PodUnpause(ctx context.Context, namesOrIds []string, options PodunpauseOptions) ([]*PodUnpauseReport, error) PodUnpause(ctx context.Context, namesOrIds []string, options PodunpauseOptions) ([]*PodUnpauseReport, error)
RestService(ctx context.Context, opts ServiceOptions) error RestService(ctx context.Context, opts ServiceOptions) error
SetupRootless(ctx context.Context, cmd *cobra.Command) error
VarlinkService(ctx context.Context, opts ServiceOptions) error VarlinkService(ctx context.Context, opts ServiceOptions) error
VolumeCreate(ctx context.Context, opts VolumeCreateOptions) (*IdOrNameResponse, error) VolumeCreate(ctx context.Context, opts VolumeCreateOptions) (*IdOrNameResponse, error)
VolumeInspect(ctx context.Context, namesOrIds []string, opts VolumeInspectOptions) ([]*VolumeInspectReport, error) VolumeInspect(ctx context.Context, namesOrIds []string, opts VolumeInspectOptions) ([]*VolumeInspectReport, error)

View File

@ -20,7 +20,7 @@ type ImageEngine interface {
Pull(ctx context.Context, rawImage string, opts ImagePullOptions) (*ImagePullReport, error) Pull(ctx context.Context, rawImage string, opts ImagePullOptions) (*ImagePullReport, error)
Push(ctx context.Context, source string, destination string, opts ImagePushOptions) error Push(ctx context.Context, source string, destination string, opts ImagePushOptions) error
Save(ctx context.Context, nameOrId string, tags []string, options ImageSaveOptions) error Save(ctx context.Context, nameOrId string, tags []string, options ImageSaveOptions) error
Search(ctx context.Context, term string, opts ImageSearchOptions) ([]ImageSearchReport, error)
Tag(ctx context.Context, nameOrId string, tags []string, options ImageTagOptions) error Tag(ctx context.Context, nameOrId string, tags []string, options ImageTagOptions) error
Untag(ctx context.Context, nameOrId string, tags []string, options ImageUntagOptions) error Untag(ctx context.Context, nameOrId string, tags []string, options ImageUntagOptions) error
Search(ctx context.Context, term string, opts ImageSearchOptions) ([]ImageSearchReport, error)
} }

View File

@ -668,9 +668,6 @@ func (ic *ContainerEngine) ContainerDiff(ctx context.Context, nameOrId string, o
} }
func (ic *ContainerEngine) ContainerRun(ctx context.Context, opts entities.ContainerRunOptions) (*entities.ContainerRunReport, error) { func (ic *ContainerEngine) ContainerRun(ctx context.Context, opts entities.ContainerRunOptions) (*entities.ContainerRunReport, error) {
var (
joinPod bool
)
if err := generate.CompleteSpec(ctx, ic.Libpod, opts.Spec); err != nil { if err := generate.CompleteSpec(ctx, ic.Libpod, opts.Spec); err != nil {
return nil, err return nil, err
} }
@ -679,6 +676,7 @@ func (ic *ContainerEngine) ContainerRun(ctx context.Context, opts entities.Conta
return nil, err return nil, err
} }
var joinPod bool
if len(ctr.PodID()) > 0 { if len(ctr.PodID()) > 0 {
joinPod = true joinPod = true
} }

View File

@ -100,7 +100,7 @@ func (ic *ContainerEngine) VarlinkService(_ context.Context, opts entities.Servi
return nil return nil
} }
func (ic *ContainerEngine) SetupRootless(cmd *cobra.Command) error { func (ic *ContainerEngine) SetupRootless(_ context.Context, cmd *cobra.Command) error {
// do it only after podman has already re-execed and running with uid==0. // do it only after podman has already re-execed and running with uid==0.
if os.Geteuid() == 0 { if os.Geteuid() == 0 {
ownsCgroup, err := cgroups.UserOwnsCurrentSystemdCgroup() ownsCgroup, err := cgroups.UserOwnsCurrentSystemdCgroup()
@ -123,10 +123,6 @@ func (ic *ContainerEngine) SetupRootless(cmd *cobra.Command) error {
} }
} }
if !executeCommandInUserNS(cmd) {
return nil
}
pausePidPath, err := util.GetRootlessPauseProcessPidPath() pausePidPath, err := util.GetRootlessPauseProcessPidPath()
if err != nil { if err != nil {
return errors.Wrapf(err, "could not get pause process pid file path") return errors.Wrapf(err, "could not get pause process pid file path")
@ -143,7 +139,8 @@ func (ic *ContainerEngine) SetupRootless(cmd *cobra.Command) error {
// if there is no pid file, try to join existing containers, and create a pause process. // if there is no pid file, try to join existing containers, and create a pause process.
ctrs, err := ic.Libpod.GetRunningContainers() ctrs, err := ic.Libpod.GetRunningContainers()
if err != nil { if err != nil {
logrus.WithError(err).Fatal("") logrus.Error(err.Error())
os.Exit(1)
} }
paths := []string{} paths := []string{}
@ -164,7 +161,8 @@ func (ic *ContainerEngine) SetupRootless(cmd *cobra.Command) error {
} }
} }
if err != nil { if err != nil {
logrus.WithError(err).Fatal("") logrus.Error(err)
os.Exit(1)
} }
if became { if became {
os.Exit(ret) os.Exit(ret)
@ -172,25 +170,6 @@ func (ic *ContainerEngine) SetupRootless(cmd *cobra.Command) error {
return nil return nil
} }
// Most podman commands when run in rootless mode, need to be executed in the
// users usernamespace. This function is updated with a list of commands that
// should NOT be run within the user namespace.
func executeCommandInUserNS(cmd *cobra.Command) bool {
return os.Geteuid() == 0
// if os.Geteuid() == 0 {
// return false
// }
// switch cmd {
// case _migrateCommand,
// _mountCommand,
// _renumberCommand,
// _searchCommand,
// _versionCommand:
// return false
// }
// return true
}
func movePauseProcessToScope() error { func movePauseProcessToScope() error {
pausePidPath, err := util.GetRootlessPauseProcessPidPath() pausePidPath, err := util.GetRootlessPauseProcessPidPath()
if err != nil { if err != nil {
@ -234,11 +213,3 @@ func setUMask() { // nolint:deadcode,unused
func checkInput() error { // nolint:deadcode,unused func checkInput() error { // nolint:deadcode,unused
return nil return nil
} }
// func getCNIPluginsDir() string {
// if rootless.IsRootless() {
// return ""
// }
//
// return registry.PodmanOptions.Network.CNIPluginDirs[0]
// }

View File

@ -7,6 +7,7 @@ import (
"github.com/containers/libpod/libpod/define" "github.com/containers/libpod/libpod/define"
"github.com/containers/libpod/pkg/bindings/system" "github.com/containers/libpod/pkg/bindings/system"
"github.com/containers/libpod/pkg/domain/entities" "github.com/containers/libpod/pkg/domain/entities"
"github.com/spf13/cobra"
) )
func (ic *ContainerEngine) Info(ctx context.Context) (*define.Info, error) { func (ic *ContainerEngine) Info(ctx context.Context) (*define.Info, error) {
@ -20,3 +21,7 @@ func (ic *ContainerEngine) RestService(_ context.Context, _ entities.ServiceOpti
func (ic *ContainerEngine) VarlinkService(_ context.Context, _ entities.ServiceOptions) error { func (ic *ContainerEngine) VarlinkService(_ context.Context, _ entities.ServiceOptions) error {
panic(errors.New("varlink service is not supported when tunneling")) panic(errors.New("varlink service is not supported when tunneling"))
} }
func (ic *ContainerEngine) SetupRootless(_ context.Context, cmd *cobra.Command) error {
panic(errors.New("rootless engine mode is not supported when tunneling"))
}

View File

@ -28,9 +28,9 @@ const (
// Bridge indicates that a CNI network stack // Bridge indicates that a CNI network stack
// should be used // should be used
Bridge NamespaceMode = "bridge" Bridge NamespaceMode = "bridge"
// Slirp indicates that a slirp4ns network stack should // Slirp indicates that a slirp4netns network stack should
// be used // be used
Slirp NamespaceMode = "slirp4ns" Slirp NamespaceMode = "slirp4netns"
) )
// Namespace describes the namespace // Namespace describes the namespace