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
BUILD_TAGS='ABISupport systemd varlink seccomp selinux exclude_graphdriver_devicemapper'
podman:
CGO_ENABLED=1 GO111MODULE=off go build -tags 'ABISupport systemd varlink seccomp selinux'
CGO_ENABLED=1 GO111MODULE=off go build -tags $(BUILD_TAGS)
podman-remote:
CGO_ENABLED=1 GO111MODULE=off go build -tags '!ABISupport systemd seccomp selinux' -o podmanV2-remote

View File

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

View File

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

View File

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

View File

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

View File

@ -13,12 +13,11 @@ import (
var (
// Command: podman _container_
containerCmd = &cobra.Command{
Use: "container",
Short: "Manage containers",
Long: "Manage containers",
TraverseChildren: true,
PersistentPreRunE: preRunE,
RunE: registry.SubCommandExists,
Use: "container",
Short: "Manage containers",
Long: "Manage containers",
TraverseChildren: true,
RunE: registry.SubCommandExists,
}
defaultContainerConfig = getDefaultContainerConfig()
@ -29,13 +28,6 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: containerCmd,
})
containerCmd.SetHelpTemplate(registry.HelpTemplate())
containerCmd.SetUsageTemplate(registry.UsageTemplate())
}
func preRunE(cmd *cobra.Command, args []string) error {
_, err := registry.NewContainerEngine(cmd, args)
return err
}
func getDefaultContainerConfig() *config.Config {

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'.`
createCommand = &cobra.Command{
Use: "create [flags] IMAGE [COMMAND [ARG...]]",
Short: "Create but do not start a container",
Long: createDescription,
RunE: create,
PersistentPreRunE: preRunE,
Args: cobra.MinimumNArgs(1),
Use: "create [flags] IMAGE [COMMAND [ARG...]]",
Short: "Create but do not start a container",
Long: createDescription,
RunE: create,
Args: cobra.MinimumNArgs(1),
Example: `podman create alpine ls
podman create --annotation HELLO=WORLD alpine ls
podman create -t -i --name myctr alpine ls`,

View File

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

View File

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

View File

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

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.`
initCommand = &cobra.Command{
Use: "init [flags] CONTAINER [CONTAINER...]",
Short: "Initialize one or more containers",
Long: initDescription,
PreRunE: preRunE,
RunE: initContainer,
Use: "init [flags] CONTAINER [CONTAINER...]",
Short: "Initialize one or more containers",
Long: initDescription,
RunE: initContainer,
Args: func(cmd *cobra.Command, args []string) error {
return parse.CheckAllLatestAndCIDFile(cmd, args, false, false)
},

View File

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

View File

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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)
stopCommand = &cobra.Command{
Use: "stop [flags] CONTAINER [CONTAINER...]",
Short: "Stop one or more containers",
Long: stopDescription,
RunE: stop,
PersistentPreRunE: preRunE,
Use: "stop [flags] CONTAINER [CONTAINER...]",
Short: "Stop one or more containers",
Long: stopDescription,
RunE: stop,
Args: func(cmd *cobra.Command, args []string) error {
return parse.CheckAllLatestAndCIDFile(cmd, args, false, true)
},
@ -63,11 +62,6 @@ func stop(cmd *cobra.Command, args []string) error {
stopOptions.Timeout = stopTimeout
}
// TODO How do we access global attributes?
//if c.Bool("trace") {
// span, _ := opentracing.StartSpanFromContext(Ctx, "stopCmd")
// defer span.Finish()
//}
responses, err := registry.ContainerEngine().ContainerStop(context.Background(), args, stopOptions)
if err != nil {
return err

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -9,12 +9,11 @@ import (
var (
// Command: healthcheck
healthCmd = &cobra.Command{
Use: "healthcheck",
Short: "Manage Healthcheck",
Long: "Manage Healthcheck",
TraverseChildren: true,
PersistentPreRunE: preRunE,
RunE: registry.SubCommandExists,
Use: "healthcheck",
Short: "Manage Healthcheck",
Long: "Manage Healthcheck",
TraverseChildren: true,
RunE: registry.SubCommandExists,
}
)
@ -23,11 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: healthCmd,
})
healthCmd.SetHelpTemplate(registry.HelpTemplate())
healthCmd.SetUsageTemplate(registry.UsageTemplate())
}
func preRunE(cmd *cobra.Command, args []string) error {
_, err := registry.NewContainerEngine(cmd, args)
return err
}

View File

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

View File

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

View File

@ -9,12 +9,11 @@ import (
var (
// Command: podman _image_
imageCmd = &cobra.Command{
Use: "image",
Short: "Manage images",
Long: "Manage images",
TraverseChildren: true,
PersistentPreRunE: preRunE,
RunE: registry.SubCommandExists,
Use: "image",
Short: "Manage images",
Long: "Manage images",
TraverseChildren: true,
RunE: registry.SubCommandExists,
}
)
@ -23,13 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: imageCmd,
})
imageCmd.SetHelpTemplate(registry.HelpTemplate())
imageCmd.SetUsageTemplate(registry.UsageTemplate())
}
func preRunE(cmd *cobra.Command, args []string) error {
if _, err := registry.NewImageEngine(cmd, args); err != nil {
return err
}
return nil
}

View File

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

View File

@ -18,11 +18,10 @@ var (
Note remote tar balls can be specified, via web address.
Optionally tag the image. You can specify the instructions using the --change option.`
importCommand = &cobra.Command{
Use: "import [flags] PATH [REFERENCE]",
Short: "Import a tarball to create a filesystem image",
Long: importDescription,
RunE: importCon,
PersistentPreRunE: preRunE,
Use: "import [flags] PATH [REFERENCE]",
Short: "Import a tarball to create a filesystem image",
Long: importDescription,
RunE: importCon,
Example: `podman import http://example.com/ctr.tar url-image
cat ctr.tar | podman -q import --message "importing the ctr.tar tarball" - image-imported
cat ctr.tar | podman import -`,
@ -39,8 +38,6 @@ func init() {
Command: importCommand,
})
importCommand.SetHelpTemplate(registry.HelpTemplate())
importCommand.SetUsageTemplate(registry.UsageTemplate())
flags := importCommand.Flags()
flags.StringArrayVarP(&importOpts.Changes, "change", "c", []string{}, "Apply the following possible instructions to the created image (default []): CMD | ENTRYPOINT | ENV | EXPOSE | LABEL | STOPSIGNAL | USER | VOLUME | WORKDIR")
flags.StringVarP(&importOpts.Message, "message", "m", "", "Set commit message for imported image")

View File

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

View File

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

View File

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

View File

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

View File

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

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.`
saveCommand = &cobra.Command{
Use: "save [flags] IMAGE",
Short: "Save image to an archive",
Long: saveDescription,
PersistentPreRunE: preRunE,
RunE: save,
Use: "save [flags] IMAGE",
Short: "Save image to an archive",
Long: saveDescription,
RunE: save,
Args: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return errors.Errorf("need at least 1 argument")

View File

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

View File

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

View File

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

View File

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

View File

@ -2,7 +2,6 @@ package main
import (
"os"
"reflect"
_ "github.com/containers/libpod/cmd/podmanV2/containers"
_ "github.com/containers/libpod/cmd/podmanV2/healthcheck"
@ -27,36 +26,25 @@ func main() {
// had a specific job to do as a subprocess, and it's done.
return
}
for _, c := range registry.Commands {
if Contains(registry.PodmanOptions.EngineMode, c.Mode) {
parent := rootCmd
if c.Parent != nil {
parent = c.Parent
for _, m := range c.Mode {
if registry.PodmanOptions.EngineMode == m {
parent := rootCmd
if c.Parent != nil {
parent = c.Parent
}
parent.AddCommand(c.Command)
// - templates need to be set here, as PersistentPreRunE() is
// not called when --help is used.
// - rootCmd uses cobra default template not ours
c.Command.SetHelpTemplate(helpTemplate)
c.Command.SetUsageTemplate(usageTemplate)
}
parent.AddCommand(c.Command)
}
}
Execute()
os.Exit(0)
}
func Contains(item interface{}, slice interface{}) bool {
s := reflect.ValueOf(slice)
switch s.Kind() {
case reflect.Array:
fallthrough
case reflect.Slice:
break
default:
return false
}
for i := 0; i < s.Len(); i++ {
if s.Index(i).Interface() == item {
return true
}
}
return false
}

View File

@ -9,12 +9,11 @@ import (
var (
// Command: podman _network_
cmd = &cobra.Command{
Use: "network",
Short: "Manage networks",
Long: "Manage networks",
TraverseChildren: true,
PersistentPreRunE: preRunE,
RunE: registry.SubCommandExists,
Use: "network",
Short: "Manage networks",
Long: "Manage networks",
TraverseChildren: true,
RunE: registry.SubCommandExists,
}
)
@ -23,11 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode},
Command: cmd,
})
cmd.SetHelpTemplate(registry.HelpTemplate())
cmd.SetUsageTemplate(registry.UsageTemplate())
}
func preRunE(cmd *cobra.Command, args []string) error {
_, err := registry.NewContainerEngine(cmd, args)
return err
}

View File

@ -9,12 +9,11 @@ import (
var (
// Command: podman _pod_
podCmd = &cobra.Command{
Use: "pod",
Short: "Manage pods",
Long: "Manage pods",
TraverseChildren: true,
PersistentPreRunE: preRunE,
RunE: registry.SubCommandExists,
Use: "pod",
Short: "Manage pods",
Long: "Manage pods",
TraverseChildren: true,
RunE: registry.SubCommandExists,
}
)
@ -23,11 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: podCmd,
})
podCmd.SetHelpTemplate(registry.HelpTemplate())
podCmd.SetUsageTemplate(registry.UsageTemplate())
}
func preRunE(cmd *cobra.Command, args []string) error {
_, err := registry.NewContainerEngine(cmd, args)
return err
}

View File

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

View File

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

View File

@ -42,41 +42,6 @@ func GetExitCode() int {
return exitCode
}
// HelpTemplate returns the help template for podman commands
// This uses the short and long options.
// command should not use this.
func HelpTemplate() string {
return `{{.Short}}
Description:
{{.Long}}
{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
}
// UsageTemplate returns the usage template for podman commands
// This blocks the displaying of the global options. The main podman
// command should not use this.
func UsageTemplate() string {
return `Usage(v2):{{if (and .Runnable (not .HasAvailableSubCommands))}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
{{end}}
`
}
func ImageEngine() entities.ImageEngine {
return imageEngine
}
@ -126,17 +91,26 @@ func IdOrLatestArgs(cmd *cobra.Command, args []string) error {
return nil
}
func GetContext() context.Context {
type PodmanOptionsKey struct{}
func Context() context.Context {
if cliCtx == nil {
cliCtx = context.Background()
cliCtx = ContextWithOptions(context.Background())
}
return cliCtx
}
type ContextOptionsKey string
const PodmanOptionsKey ContextOptionsKey = "PodmanOptions"
func GetContextWithOptions() context.Context {
return context.WithValue(GetContext(), PodmanOptionsKey, PodmanOptions)
func ContextWithOptions(ctx context.Context) context.Context {
cliCtx = context.WithValue(ctx, PodmanOptionsKey{}, PodmanOptions)
return cliCtx
}
// GetContextWithOptions deprecated, use NewContextWithOptions()
func GetContextWithOptions() context.Context {
return ContextWithOptions(context.Background())
}
// GetContext deprecated, use Context()
func GetContext() context.Context {
return Context()
}

View File

@ -1,12 +1,12 @@
package main
import (
"context"
"fmt"
"log/syslog"
"os"
"path"
"runtime/pprof"
"strings"
"github.com/containers/libpod/cmd/podmanV2/registry"
"github.com/containers/libpod/pkg/domain/entities"
@ -21,6 +21,37 @@ import (
"github.com/spf13/pflag"
)
// HelpTemplate is the help template for podman commands
// This uses the short and long options.
// command should not use this.
const helpTemplate = `{{.Short}}
Description:
{{.Long}}
{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
// UsageTemplate is the usage template for podman commands
// This blocks the displaying of the global options. The main podman
// command should not use this.
const usageTemplate = `Usage(v2):{{if (and .Runnable (not .HasAvailableSubCommands))}}
{{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
{{end}}
`
var (
rootCmd = &cobra.Command{
Use: path.Base(os.Args[0]),
@ -28,20 +59,20 @@ var (
SilenceUsage: true,
SilenceErrors: true,
TraverseChildren: true,
PersistentPreRunE: preRunE,
PersistentPreRunE: persistentPreRunE,
RunE: registry.SubCommandExists,
PersistentPostRunE: postRunE,
PersistentPostRunE: persistentPostRunE,
Version: version.Version,
}
logLevels = entities.NewStringSet("debug", "info", "warn", "error", "fatal", "panic")
logLevels = []string{"debug", "info", "warn", "error", "fatal", "panic"}
logLevel = "error"
useSyslog bool
)
func init() {
// Hooks are called before PersistentPreRunE()
cobra.OnInitialize(
rootlessHook,
loggingHook,
syslogHook,
)
@ -63,13 +94,21 @@ func Execute() {
os.Exit(registry.GetExitCode())
}
func preRunE(cmd *cobra.Command, _ []string) error {
func persistentPreRunE(cmd *cobra.Command, args []string) error {
// TODO: Remove trace statement in podman V2.1
logrus.Debugf("Called %s.PersistentPreRunE()", cmd.Name())
// Update PodmanOptions now that we "know" more
// TODO: pass in path overriding configuration file
registry.PodmanOptions = registry.NewPodmanConfig()
cmd.SetHelpTemplate(registry.HelpTemplate())
cmd.SetUsageTemplate(registry.UsageTemplate())
// Prep the engines
if _, err := registry.NewImageEngine(cmd, args); err != nil {
return err
}
if _, err := registry.NewContainerEngine(cmd, args); err != nil {
return err
}
if cmd.Flag("cpu-profile").Changed {
f, err := os.Create(registry.PodmanOptions.CpuProfile)
@ -88,12 +127,28 @@ func preRunE(cmd *cobra.Command, _ []string) error {
registry.PodmanOptions.SpanCloser = closer
registry.PodmanOptions.Span = tracer.StartSpan("before-context")
registry.PodmanOptions.SpanCtx = opentracing.ContextWithSpan(context.Background(), registry.PodmanOptions.Span)
registry.PodmanOptions.SpanCtx = opentracing.ContextWithSpan(registry.Context(), registry.PodmanOptions.Span)
opentracing.StartSpanFromContext(registry.PodmanOptions.SpanCtx, cmd.Name())
}
// Setup Rootless environment, IFF:
// 1) in ABI mode
// 2) running as non-root
// 3) command doesn't require Parent Namespace
_, found := cmd.Annotations[registry.ParentNSRequired]
if !registry.IsRemote() && rootless.IsRootless() && !found {
err := registry.ContainerEngine().SetupRootless(registry.Context(), cmd)
if err != nil {
return err
}
}
return nil
}
func postRunE(cmd *cobra.Command, args []string) error {
func persistentPostRunE(cmd *cobra.Command, args []string) error {
// TODO: Remove trace statement in podman V2.1
logrus.Debugf("Called %s.PersistentPostRunE()", cmd.Name())
if cmd.Flag("cpu-profile").Changed {
pprof.StopCPUProfile()
}
@ -105,14 +160,21 @@ func postRunE(cmd *cobra.Command, args []string) error {
}
func loggingHook() {
if !logLevels.Contains(logLevel) {
logrus.Errorf("Log Level \"%s\" is not supported, choose from: %s", logLevel, logLevels.String())
var found bool
for _, l := range logLevels {
if l == logLevel {
found = true
break
}
}
if !found {
fmt.Fprintf(os.Stderr, "Log Level \"%s\" is not supported, choose from: %s\n", logLevel, strings.Join(logLevels, ", "))
os.Exit(1)
}
level, err := logrus.ParseLevel(logLevel)
if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
fmt.Fprint(os.Stderr, err.Error())
os.Exit(1)
}
logrus.SetLevel(level)
@ -123,26 +185,18 @@ func loggingHook() {
}
func syslogHook() {
if useSyslog {
hook, err := logrusSyslog.NewSyslogHook("", "", syslog.LOG_INFO, "")
if err != nil {
logrus.WithError(err).Error("Failed to initialize syslog hook")
}
if err == nil {
logrus.AddHook(hook)
}
if !useSyslog {
return
}
}
func rootlessHook() {
if rootless.IsRootless() {
logrus.Error("rootless mode is currently not supported. Support will return ASAP.")
hook, err := logrusSyslog.NewSyslogHook("", "", syslog.LOG_INFO, "")
if err != nil {
fmt.Fprint(os.Stderr, "Failed to initialize syslog hook: "+err.Error())
os.Exit(1)
}
if err == nil {
logrus.AddHook(hook)
}
// ce, err := registry.NewContainerEngine(rootCmd, []string{})
// if err != nil {
// logrus.WithError(err).Fatal("failed to obtain container engine")
// }
// ce.SetupRootLess(rootCmd)
}
func rootFlags(opts entities.PodmanConfig, flags *pflag.FlagSet) {
@ -179,7 +233,7 @@ func rootFlags(opts entities.PodmanConfig, flags *pflag.FlagSet) {
// Override default --help information of `--help` global flag
var dummyHelp bool
flags.BoolVar(&dummyHelp, "help", false, "Help for podman")
flags.StringVar(&logLevel, "log-level", logLevel, fmt.Sprintf("Log messages above specified level (%s)", logLevels.String()))
flags.StringVar(&logLevel, "log-level", logLevel, fmt.Sprintf("Log messages above specified level (%s)", strings.Join(logLevels, ", ")))
// Hide these flags for both ABI and Tunneling
for _, f := range []string{
@ -189,7 +243,7 @@ func rootFlags(opts entities.PodmanConfig, flags *pflag.FlagSet) {
"trace",
} {
if err := flags.MarkHidden(f); err != nil {
logrus.Warnf("unable to mark %s flag as hidden", f)
logrus.Warnf("unable to mark %s flag as hidden: %s", f, err.Error())
}
}
@ -197,5 +251,4 @@ func rootFlags(opts entities.PodmanConfig, flags *pflag.FlagSet) {
if !registry.IsRemote() {
flags.BoolVar(&useSyslog, "syslog", false, "Output logging information to syslog as well as the console (default false)")
}
}

View File

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

View File

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

View File

@ -9,12 +9,11 @@ import (
var (
// Command: podman _system_
systemCmd = &cobra.Command{
Use: "system",
Short: "Manage podman",
Long: "Manage podman",
TraverseChildren: true,
PersistentPreRunE: preRunE,
RunE: registry.SubCommandExists,
Use: "system",
Short: "Manage podman",
Long: "Manage podman",
TraverseChildren: true,
RunE: registry.SubCommandExists,
}
)
@ -23,11 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: systemCmd,
})
systemCmd.SetHelpTemplate(registry.HelpTemplate())
systemCmd.SetUsageTemplate(registry.UsageTemplate())
}
func preRunE(cmd *cobra.Command, args []string) error {
_, err := registry.NewContainerEngine(cmd, args)
return err
}

View File

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

View File

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

View File

@ -9,12 +9,11 @@ import (
var (
// Command: podman _volume_
volumeCmd = &cobra.Command{
Use: "volume",
Short: "Manage volumes",
Long: "Volumes are created in and can be shared between containers",
TraverseChildren: true,
PersistentPreRunE: preRunE,
RunE: registry.SubCommandExists,
Use: "volume",
Short: "Manage volumes",
Long: "Volumes are created in and can be shared between containers",
TraverseChildren: true,
RunE: registry.SubCommandExists,
}
)
@ -23,11 +22,4 @@ func init() {
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: volumeCmd,
})
volumeCmd.SetHelpTemplate(registry.HelpTemplate())
volumeCmd.SetUsageTemplate(registry.UsageTemplate())
}
func preRunE(cmd *cobra.Command, args []string) error {
_, err := registry.NewContainerEngine(cmd, args)
return err
}

View File

@ -2,17 +2,9 @@ package entities
import (
"context"
"fmt"
"io"
"os"
"github.com/containers/buildah/pkg/parse"
"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/spf13/pflag"
)
@ -54,214 +46,3 @@ type PodmanConfig struct {
StorageDriver 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/libpod/libpod/define"
"github.com/containers/libpod/pkg/specgen"
"github.com/spf13/cobra"
)
type ContainerEngine interface {
@ -24,9 +25,9 @@ type ContainerEngine interface {
ContainerInspect(ctx context.Context, namesOrIds []string, options InspectOptions) ([]*ContainerInspectReport, error)
ContainerKill(ctx context.Context, namesOrIds []string, options KillOptions) ([]*KillReport, 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)
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)
ContainerRestore(ctx context.Context, namesOrIds []string, options RestoreOptions) ([]*RestoreReport, 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)
PodUnpause(ctx context.Context, namesOrIds []string, options PodunpauseOptions) ([]*PodUnpauseReport, error)
RestService(ctx context.Context, opts ServiceOptions) error
SetupRootless(ctx context.Context, cmd *cobra.Command) error
VarlinkService(ctx context.Context, opts ServiceOptions) error
VolumeCreate(ctx context.Context, opts VolumeCreateOptions) (*IdOrNameResponse, 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)
Push(ctx context.Context, source string, destination string, opts ImagePushOptions) 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
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) {
var (
joinPod bool
)
if err := generate.CompleteSpec(ctx, ic.Libpod, opts.Spec); err != nil {
return nil, err
}
@ -679,6 +676,7 @@ func (ic *ContainerEngine) ContainerRun(ctx context.Context, opts entities.Conta
return nil, err
}
var joinPod bool
if len(ctr.PodID()) > 0 {
joinPod = true
}

View File

@ -100,7 +100,7 @@ func (ic *ContainerEngine) VarlinkService(_ context.Context, opts entities.Servi
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.
if os.Geteuid() == 0 {
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()
if err != nil {
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.
ctrs, err := ic.Libpod.GetRunningContainers()
if err != nil {
logrus.WithError(err).Fatal("")
logrus.Error(err.Error())
os.Exit(1)
}
paths := []string{}
@ -164,7 +161,8 @@ func (ic *ContainerEngine) SetupRootless(cmd *cobra.Command) error {
}
}
if err != nil {
logrus.WithError(err).Fatal("")
logrus.Error(err)
os.Exit(1)
}
if became {
os.Exit(ret)
@ -172,25 +170,6 @@ func (ic *ContainerEngine) SetupRootless(cmd *cobra.Command) error {
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 {
pausePidPath, err := util.GetRootlessPauseProcessPidPath()
if err != nil {
@ -234,11 +213,3 @@ func setUMask() { // nolint:deadcode,unused
func checkInput() error { // nolint:deadcode,unused
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/pkg/bindings/system"
"github.com/containers/libpod/pkg/domain/entities"
"github.com/spf13/cobra"
)
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 {
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
// should be used
Bridge NamespaceMode = "bridge"
// Slirp indicates that a slirp4ns network stack should
// Slirp indicates that a slirp4netns network stack should
// be used
Slirp NamespaceMode = "slirp4ns"
Slirp NamespaceMode = "slirp4netns"
)
// Namespace describes the namespace