diff options
Diffstat (limited to 'cmd/podman')
107 files changed, 3501 insertions, 1951 deletions
diff --git a/cmd/podman/attach.go b/cmd/podman/attach.go index a22aa92a1..86e89cfd7 100644 --- a/cmd/podman/attach.go +++ b/cmd/podman/attach.go @@ -30,11 +30,12 @@ var ( func init() { attachCommand.Command = _attachCommand + attachCommand.SetHelpTemplate(HelpTemplate()) attachCommand.SetUsageTemplate(UsageTemplate()) flags := attachCommand.Flags() flags.StringVar(&attachCommand.DetachKeys, "detach-keys", "", "Override the key sequence for detaching a container. Format is a single character [a-Z] or ctrl-<value> where <value> is one of: a-z, @, ^, [, , or _") flags.BoolVar(&attachCommand.NoStdin, "no-stdin", false, "Do not attach STDIN. The default is false") - flags.BoolVar(&attachCommand.SigProxy, "sig-proxy", true, "Proxy received signals to the process (default true)") + flags.BoolVar(&attachCommand.SigProxy, "sig-proxy", true, "Proxy received signals to the process") flags.BoolVarP(&attachCommand.Latest, "latest", "l", false, "Act on the latest container podman is aware of") markFlagHiddenForRemoteClient("latest", flags) } diff --git a/cmd/podman/build.go b/cmd/podman/build.go index cfeabfb4e..f0a67791a 100644 --- a/cmd/podman/build.go +++ b/cmd/podman/build.go @@ -1,6 +1,7 @@ package main import ( + "fmt" "os" "path/filepath" "strings" @@ -11,6 +12,7 @@ import ( "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/pkg/adapter" "github.com/docker/go-units" + "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" @@ -18,8 +20,7 @@ import ( var ( buildCommand cliconfig.BuildValues - buildDescription = "Builds an OCI or Docker image using instructions from one\n" + - "or more Dockerfiles and a specified build context directory." + buildDescription = "Builds an OCI or Docker image using instructions from one or more Dockerfiles and a specified build context directory." layerValues buildahcli.LayerResults budFlagsValues buildahcli.BudResults fromAndBudValues buildahcli.FromAndBudResults @@ -48,9 +49,10 @@ var ( func init() { buildCommand.Command = _buildCommand + buildCommand.SetHelpTemplate(HelpTemplate()) buildCommand.SetUsageTemplate(UsageTemplate()) flags := buildCommand.Flags() - flags.SetInterspersed(false) + flags.SetInterspersed(true) budFlags := buildahcli.GetBudFlags(&budFlagsValues) flag := budFlags.Lookup("pull") @@ -83,6 +85,26 @@ func getDockerfiles(files []string) []string { return dockerfiles } +func getNsValues(c *cliconfig.BuildValues) ([]buildah.NamespaceOption, error) { + var ret []buildah.NamespaceOption + if c.Network != "" { + if c.Network == "host" { + ret = append(ret, buildah.NamespaceOption{ + Name: string(specs.NetworkNamespace), + Host: true, + }) + } else if c.Network[0] == '/' { + ret = append(ret, buildah.NamespaceOption{ + Name: string(specs.NetworkNamespace), + Path: c.Network, + }) + } else { + return nil, fmt.Errorf("unsupported configuration network=%s", c.Network) + } + } + return ret, nil +} + func buildCmd(c *cliconfig.BuildValues) error { // The following was taken directly from containers/buildah/cmd/bud.go // TODO Find a away to vendor more of this in rather than copy from bud @@ -227,6 +249,11 @@ func buildCmd(c *cliconfig.BuildValues) error { } } + nsValues, err := getNsValues(c) + if err != nil { + return err + } + buildOpts := buildah.CommonBuildOptions{ AddHost: c.AddHost, CgroupParent: c.CgroupParent, @@ -257,6 +284,7 @@ func buildCmd(c *cliconfig.BuildValues) error { IIDFile: c.Iidfile, Labels: c.Label, Layers: layers, + NamespaceOptions: nsValues, NoCache: c.NoCache, Out: stdout, Output: output, diff --git a/cmd/podman/checkpoint.go b/cmd/podman/checkpoint.go index 367065766..dbf72c2cd 100644 --- a/cmd/podman/checkpoint.go +++ b/cmd/podman/checkpoint.go @@ -40,6 +40,7 @@ var ( func init() { checkpointCommand.Command = _checkpointCommand + checkpointCommand.SetHelpTemplate(HelpTemplate()) checkpointCommand.SetUsageTemplate(UsageTemplate()) flags := checkpointCommand.Flags() diff --git a/cmd/podman/cleanup.go b/cmd/podman/cleanup.go index fbbd337a7..17e637da1 100644 --- a/cmd/podman/cleanup.go +++ b/cmd/podman/cleanup.go @@ -37,6 +37,7 @@ var ( func init() { cleanupCommand.Command = _cleanupCommand + cleanupCommand.SetHelpTemplate(HelpTemplate()) cleanupCommand.SetUsageTemplate(UsageTemplate()) flags := cleanupCommand.Flags() diff --git a/cmd/podman/cliconfig/config.go b/cmd/podman/cliconfig/config.go index a9032202f..884bd7fdb 100644 --- a/cmd/podman/cliconfig/config.go +++ b/cmd/podman/cliconfig/config.go @@ -25,6 +25,7 @@ type MainFlags struct { StorageOpts []string Syslog bool Trace bool + NetworkCmdPath string Config string CpuProfile string @@ -52,10 +53,24 @@ type ImagesValues struct { Sort string } +type EventValues struct { + PodmanCommand + Filter []string + Format string + Since string + Stream bool + Until string +} + type TagValues struct { PodmanCommand } +type TreeValues struct { + PodmanCommand + WhatRequires bool +} + type WaitValues struct { PodmanCommand Interval uint @@ -100,6 +115,7 @@ type ExecValues struct { User string Latest bool Workdir string + PreserveFDs int } type ImageExistsValues struct { @@ -216,6 +232,10 @@ type PauseValues struct { All bool } +type HealthCheckValues struct { + PodmanCommand +} + type KubePlayValues struct { PodmanCommand Authfile string @@ -401,15 +421,15 @@ type RmiValues struct { type RunlabelValues struct { PodmanCommand Authfile string - Display bool CertDir string Creds string + Display bool Name string Opt1 string Opt2 string Opt3 string Quiet bool - Pull bool + Replace bool SignaturePolicy string TlsVerify bool } @@ -552,3 +572,9 @@ type SystemPruneValues struct { type SystemRenumberValues struct { PodmanCommand } + +type SystemDfValues struct { + PodmanCommand + Verbose bool + Format string +} diff --git a/cmd/podman/cliconfig/create.go b/cmd/podman/cliconfig/create.go index b5ca1be9c..49ab3d827 100644 --- a/cmd/podman/cliconfig/create.go +++ b/cmd/podman/cliconfig/create.go @@ -23,4 +23,5 @@ type BuildValues struct { type CpValues struct { PodmanCommand + Extract bool } diff --git a/cmd/podman/commands.go b/cmd/podman/commands.go index 2f9a9cfe2..875b2aec8 100644 --- a/cmd/podman/commands.go +++ b/cmd/podman/commands.go @@ -21,7 +21,6 @@ func getMainCommands() []*cobra.Command { &_psCommand, _loginCommand, _logoutCommand, - _logsCommand, _mountCommand, _pauseCommand, _portCommand, @@ -32,11 +31,9 @@ func getMainCommands() []*cobra.Command { _searchCommand, _startCommand, _statsCommand, - _stopCommand, _topCommand, _umountCommand, _unpauseCommand, - _waitCommand, } if len(_varlinkCommand.Use) > 0 { @@ -55,9 +52,6 @@ func getImageSubCommands() []*cobra.Command { // Commands that the local client implements func getContainerSubCommands() []*cobra.Command { - var _listSubCommand = _psCommand - _listSubCommand.Use = "list" - return []*cobra.Command{ _attachCommand, _checkpointCommand, @@ -68,8 +62,6 @@ func getContainerSubCommands() []*cobra.Command { _execCommand, _exportCommand, _killCommand, - &_listSubCommand, - _logsCommand, _mountCommand, _pauseCommand, _portCommand, @@ -90,14 +82,6 @@ func getContainerSubCommands() []*cobra.Command { } } -// Commands that the local client implements -func getPodSubCommands() []*cobra.Command { - return []*cobra.Command{ - _podStatsCommand, - _podTopCommand, - } -} - func getGenerateSubCommands() []*cobra.Command { return []*cobra.Command{ _containerKubeCommand, @@ -124,5 +108,13 @@ func getSystemSubCommands() []*cobra.Command { return []*cobra.Command{ _pruneSystemCommand, _renumberCommand, + _dfSystemCommand, + } +} + +// Commands that the local client implements +func getHealtcheckSubCommands() []*cobra.Command { + return []*cobra.Command{ + _healthcheckrunCommand, } } diff --git a/cmd/podman/commands_remoteclient.go b/cmd/podman/commands_remoteclient.go index 081043b25..9b09e7dbc 100644 --- a/cmd/podman/commands_remoteclient.go +++ b/cmd/podman/commands_remoteclient.go @@ -29,11 +29,6 @@ func getContainerSubCommands() []*cobra.Command { } // commands that only the remoteclient implements -func getPodSubCommands() []*cobra.Command { - return []*cobra.Command{} -} - -// commands that only the remoteclient implements func getGenerateSubCommands() []*cobra.Command { return []*cobra.Command{} } @@ -52,3 +47,8 @@ func getTrustSubCommands() []*cobra.Command { func getSystemSubCommands() []*cobra.Command { return []*cobra.Command{} } + +// Commands that the remoteclient implements +func getHealtcheckSubCommands() []*cobra.Command { + return []*cobra.Command{} +} diff --git a/cmd/podman/commit.go b/cmd/podman/commit.go index 43c54c320..584ab6880 100644 --- a/cmd/podman/commit.go +++ b/cmd/podman/commit.go @@ -19,10 +19,7 @@ import ( var ( commitCommand cliconfig.CommitValues - 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{ Use: "commit [flags] CONTAINER IMAGE", @@ -41,6 +38,7 @@ var ( func init() { commitCommand.Command = _commitCommand + commitCommand.SetHelpTemplate(HelpTemplate()) commitCommand.SetUsageTemplate(UsageTemplate()) flags := commitCommand.Flags() flags.StringSliceVarP(&commitCommand.Change, "change", "c", []string{}, fmt.Sprintf("Apply the following possible instructions to the created image (default []): %s", strings.Join(libpod.ChangeCmds, " | "))) diff --git a/cmd/podman/common.go b/cmd/podman/common.go index e980e10f9..771738302 100644 --- a/cmd/podman/common.go +++ b/cmd/podman/common.go @@ -3,7 +3,6 @@ package main import ( "context" "fmt" - "github.com/spf13/cobra" "os" "strings" @@ -14,6 +13,7 @@ import ( "github.com/containers/storage" "github.com/fatih/camelcase" "github.com/pkg/errors" + "github.com/spf13/cobra" ) var ( @@ -59,6 +59,24 @@ func checkAllAndLatest(c *cobra.Command, args []string, ignoreArgLen bool) error return nil } +// noSubArgs checks that there are no further positional parameters +func noSubArgs(c *cobra.Command, args []string) error { + if len(args) > 0 { + return errors.Errorf("`%s` takes no arguments", c.CommandPath()) + } + return nil +} + +func commandRunE() func(*cobra.Command, []string) error { + return func(cmd *cobra.Command, args []string) error { + if len(args) > 0 { + return errors.Errorf("unrecognized command `%s %s`\nTry '%s --help' for more information.", cmd.CommandPath(), args[0], cmd.CommandPath()) + } else { + return errors.Errorf("missing command '%s COMMAND'\nTry '%s --help' for more information.", cmd.CommandPath(), cmd.CommandPath()) + } + } +} + // getAllOrLatestContainers tries to return the correct list of containers // depending if --all, --latest or <container-id> is used. // It requires the Context (c) and the Runtime (runtime). As different @@ -208,7 +226,7 @@ func getCreateFlags(c *cliconfig.PodmanCommand) { ) createFlags.String( "detach-keys", "", - "Override the key sequence for detaching a container. Format is a single character `[a-Z]` or `ctrl-<value>` where `<value>` is one of: `a-z`, `@`, `^`, `[`, `,` or `_`", + "Override the key sequence for detaching a container. Format is a single character `[a-Z]` or `ctrl-<value>` where `<value>` is one of: `a-z`, `@`, `^`, `[`, `\\`, `]`, `^` or `_`", ) createFlags.StringSlice( "device", []string{}, @@ -246,7 +264,7 @@ func getCreateFlags(c *cliconfig.PodmanCommand) { "entrypoint", "", "Overwrite the default ENTRYPOINT of the image", ) - createFlags.StringSliceP( + createFlags.StringArrayP( "env", "e", []string{}, "Set environment variables in container", ) @@ -269,14 +287,33 @@ func getCreateFlags(c *cliconfig.PodmanCommand) { createFlags.Bool( "help", false, "", ) - + createFlags.String( + "healthcheck-command", "", + "set a healthcheck command for the container ('none' disables the existing healthcheck)", + ) + createFlags.String( + "healthcheck-interval", "30s", + "set an interval for the healthchecks (a value of disable results in no automatic timer setup)", + ) + createFlags.Uint( + "healthcheck-retries", 3, + "the number of retries allowed before a healthcheck is considered to be unhealthy", + ) + createFlags.String( + "healthcheck-start-period", "0s", + "the initialization time needed for a container to bootstrap", + ) + createFlags.String( + "healthcheck-timeout", "30s", + "the maximum time allowed to complete the healthcheck before an interval is considered failed", + ) createFlags.StringP( "hostname", "h", "", "Set container hostname", ) createFlags.String( "image-volume", "bind", - "Tells podman how to handle the builtin image volumes. The options are: 'bind', 'tmpfs', or 'ignore' (default 'bind')", + "Tells podman how to handle the builtin image volumes. The options are: 'bind', 'tmpfs', or 'ignore'", ) createFlags.Bool( "init", false, @@ -303,8 +340,8 @@ func getCreateFlags(c *cliconfig.PodmanCommand) { "kernel-memory", "", "Kernel memory limit (format: `<number>[<unit>]`, where unit = b, k, m or g)", ) - createFlags.StringSlice( - "label", []string{}, + createFlags.StringArrayP( + "label", "l", []string{}, "Set metadata on container (default [])", ) createFlags.StringSlice( @@ -337,7 +374,7 @@ func getCreateFlags(c *cliconfig.PodmanCommand) { ) createFlags.Int64( "memory-swappiness", -1, - "Tune container memory swappiness (0 to 100) (default -1)", + "Tune container memory swappiness (0 to 100, or -1 for system default)", ) createFlags.String( "name", "", @@ -513,11 +550,23 @@ func scrubServer(server string) string { return strings.TrimPrefix(server, "http://") } +// 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 desplaying of the global options. The main podman // command should not use this. func UsageTemplate() string { - return `Usage:{{if .Runnable}} + return `Usage:{{if (and .Runnable (not .HasAvailableSubCommands))}} {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} diff --git a/cmd/podman/container.go b/cmd/podman/container.go index 338bb005c..2e9cedbaa 100644 --- a/cmd/podman/container.go +++ b/cmd/podman/container.go @@ -1,27 +1,69 @@ package main import ( + "strings" + "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/spf13/cobra" ) -var containerDescription = "Manage containers" -var containerCommand = cliconfig.PodmanCommand{ - Command: &cobra.Command{ - Use: "container", - Short: "Manage Containers", - Long: containerDescription, - TraverseChildren: true, - }, -} +var ( + containerDescription = "Manage containers" + containerCommand = cliconfig.PodmanCommand{ + Command: &cobra.Command{ + Use: "container", + Short: "Manage Containers", + Long: containerDescription, + TraverseChildren: true, + RunE: commandRunE(), + }, + } -// Commands that are universally implemented. -var containerCommands = []*cobra.Command{ - _containerExistsCommand, - _inspectCommand, -} + contInspectSubCommand cliconfig.InspectValues + _contInspectSubCommand = &cobra.Command{ + Use: strings.Replace(_inspectCommand.Use, "| IMAGE", "", 1), + Short: "Display the configuration of a container", + Long: `Displays the low-level information on a container identified by name or ID.`, + RunE: func(cmd *cobra.Command, args []string) error { + contInspectSubCommand.InputArgs = args + contInspectSubCommand.GlobalFlags = MainGlobalOpts + return inspectCmd(&contInspectSubCommand) + }, + Example: `podman container inspect myCtr + podman container inspect -l --format '{{.Id}} {{.Config.Labels}}'`, + } + + listSubCommand cliconfig.PsValues + _listSubCommand = &cobra.Command{ + Use: strings.Replace(_psCommand.Use, "ps", "list", 1), + Args: noSubArgs, + Short: _psCommand.Short, + Long: _psCommand.Long, + Aliases: []string{"ls"}, + RunE: func(cmd *cobra.Command, args []string) error { + listSubCommand.InputArgs = args + listSubCommand.GlobalFlags = MainGlobalOpts + return psCmd(&listSubCommand) + }, + Example: strings.Replace(_psCommand.Example, "podman ps", "podman container list", -1), + } + + // Commands that are universally implemented. + containerCommands = []*cobra.Command{ + _containerExistsCommand, + _contInspectSubCommand, + _listSubCommand, + _logsCommand, + } +) func init() { + contInspectSubCommand.Command = _contInspectSubCommand + inspectInit(&contInspectSubCommand) + + listSubCommand.Command = _listSubCommand + psInit(&listSubCommand) + containerCommand.AddCommand(containerCommands...) containerCommand.AddCommand(getContainerSubCommands()...) containerCommand.SetUsageTemplate(UsageTemplate()) diff --git a/cmd/podman/containers_prune.go b/cmd/podman/containers_prune.go index 6e4960429..39be70c5b 100644 --- a/cmd/podman/containers_prune.go +++ b/cmd/podman/containers_prune.go @@ -21,6 +21,7 @@ var ( ` _pruneContainersCommand = &cobra.Command{ Use: "prune", + Args: noSubArgs, Short: "Remove all stopped containers", Long: pruneContainersDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -33,6 +34,7 @@ var ( func init() { pruneContainersCommand.Command = _pruneContainersCommand + pruneContainersCommand.SetHelpTemplate(HelpTemplate()) pruneContainersCommand.SetUsageTemplate(UsageTemplate()) flags := pruneContainersCommand.Flags() flags.BoolVarP(&pruneContainersCommand.Force, "force", "f", false, "Force removal of a running container. The default is false") diff --git a/cmd/podman/cp.go b/cmd/podman/cp.go index 30b6d75d2..6223676ac 100644 --- a/cmd/podman/cp.go +++ b/cmd/podman/cp.go @@ -27,8 +27,11 @@ import ( var ( cpCommand cliconfig.CpValues - cpDescription = "Copy files/folders between a container and the local filesystem" - _cpCommand = &cobra.Command{ + cpDescription = `Command copies the contents of SRC_PATH to the DEST_PATH. + + You can copy from the container's file system to the local machine or the reverse, from the local filesystem to the container. If "-" is specified for either the SRC_PATH or DEST_PATH, you can also stream a tar archive from STDIN or to STDOUT. The CONTAINER can be a running or stopped container. The SRC_PATH or DEST_PATH can be a file or directory. +` + _cpCommand = &cobra.Command{ Use: "cp [flags] SRC_PATH DEST_PATH", Short: "Copy files/folders between a container and the local filesystem", Long: cpDescription, @@ -43,6 +46,10 @@ var ( func init() { cpCommand.Command = _cpCommand + flags := cpCommand.Flags() + flags.BoolVar(&cpCommand.Extract, "extract", false, "Extract the tar file into the destination directory.") + cpCommand.SetHelpTemplate(HelpTemplate()) + cpCommand.SetUsageTemplate(UsageTemplate()) rootCmd.AddCommand(cpCommand.Command) } @@ -61,10 +68,11 @@ func cpCmd(c *cliconfig.CpValues) error { } defer runtime.Shutdown(false) - return copyBetweenHostAndContainer(runtime, args[0], args[1]) + extract := c.Flag("extract").Changed + return copyBetweenHostAndContainer(runtime, args[0], args[1], extract) } -func copyBetweenHostAndContainer(runtime *libpod.Runtime, src string, dest string) error { +func copyBetweenHostAndContainer(runtime *libpod.Runtime, src string, dest string, extract bool) error { srcCtr, srcPath := parsePath(runtime, src) destCtr, destPath := parsePath(runtime, dest) @@ -166,7 +174,7 @@ func copyBetweenHostAndContainer(runtime *libpod.Runtime, src string, dest strin var lastError error for _, src := range glob { - err := copy(src, destPath, dest, idMappingOpts, &containerOwner) + err := copy(src, destPath, dest, idMappingOpts, &containerOwner, extract) if lastError != nil { logrus.Error(lastError) } @@ -219,7 +227,7 @@ func getPathInfo(path string) (string, os.FileInfo, error) { return path, srcfi, nil } -func copy(src, destPath, dest string, idMappingOpts storage.IDMappingOptions, chownOpts *idtools.IDPair) error { +func copy(src, destPath, dest string, idMappingOpts storage.IDMappingOptions, chownOpts *idtools.IDPair, extract bool) error { srcPath, err := filepath.EvalSymlinks(src) if err != nil { return errors.Wrapf(err, "error evaluating symlinks %q", srcPath) @@ -263,17 +271,20 @@ func copy(src, destPath, dest string, idMappingOpts storage.IDMappingOptions, ch if destfi != nil && destfi.IsDir() { destPath = filepath.Join(destPath, filepath.Base(srcPath)) } - // Copy the file, preserving attributes. - logrus.Debugf("copying %q to %q", srcPath, destPath) - if err = copyFileWithTar(srcPath, destPath); err != nil { - return errors.Wrapf(err, "error copying %q to %q", srcPath, destPath) + } + + if extract { + // We're extracting an archive into the destination directory. + logrus.Debugf("extracting contents of %q into %q", srcPath, destPath) + if err = untarPath(srcPath, destPath); err != nil { + return errors.Wrapf(err, "error extracting %q into %q", srcPath, destPath) } return nil } - // We're extracting an archive into the destination directory. - logrus.Debugf("extracting contents of %q into %q", srcPath, destPath) - if err = untarPath(srcPath, destPath); err != nil { - return errors.Wrapf(err, "error extracting %q into %q", srcPath, destPath) + // Copy the file, preserving attributes. + logrus.Debugf("copying %q to %q", srcPath, destPath) + if err = copyFileWithTar(srcPath, destPath); err != nil { + return errors.Wrapf(err, "error copying %q to %q", srcPath, destPath) } return nil } diff --git a/cmd/podman/create.go b/cmd/podman/create.go index 95cb732d9..bceb606f6 100644 --- a/cmd/podman/create.go +++ b/cmd/podman/create.go @@ -1,46 +1,23 @@ package main import ( - "context" - "encoding/json" "fmt" - "io" - "io/ioutil" "os" - "path/filepath" - "strconv" - "strings" - "syscall" "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/libpod/cmd/podman/shared" - "github.com/containers/libpod/libpod" - "github.com/containers/libpod/libpod/image" - ann "github.com/containers/libpod/pkg/annotations" - "github.com/containers/libpod/pkg/inspect" - ns "github.com/containers/libpod/pkg/namespaces" "github.com/containers/libpod/pkg/rootless" - cc "github.com/containers/libpod/pkg/spec" - "github.com/containers/libpod/pkg/util" - "github.com/docker/docker/pkg/signal" - "github.com/docker/go-connections/nat" - "github.com/docker/go-units" - spec "github.com/opencontainers/runtime-spec/specs-go" - "github.com/opencontainers/selinux/go-selinux/label" - opentracing "github.com/opentracing/opentracing-go" + "github.com/opentracing/opentracing-go" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) var ( createCommand cliconfig.CreateValues - createDescription = "Creates a new container from the given image or" + - " storage and prepares it for running the specified command. 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'." + createDescription = `Creates a new container from the given image or storage and prepares it for running the specified command. + + 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", @@ -54,15 +31,11 @@ var ( podman create --annotation HELLO=WORLD alpine ls podman create -t -i --name myctr alpine ls`, } - - defaultEnvVariables = map[string]string{ - "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", - "TERM": "xterm", - } ) func init() { createCommand.PodmanCommand.Command = _createCommand + createCommand.SetHelpTemplate(HelpTemplate()) createCommand.SetUsageTemplate(UsageTemplate()) getCreateFlags(&createCommand.PodmanCommand) @@ -91,7 +64,7 @@ func createCmd(c *cliconfig.CreateValues) error { } defer runtime.Shutdown(false) - ctr, _, err := createContainer(&c.PodmanCommand, runtime) + ctr, _, err := shared.CreateContainer(getContext(), &c.PodmanCommand, runtime) if err != nil { return err } @@ -115,795 +88,3 @@ func createInit(c *cliconfig.PodmanCommand) error { return nil } - -func createContainer(c *cliconfig.PodmanCommand, runtime *libpod.Runtime) (*libpod.Container, *cc.CreateConfig, error) { - if c.Bool("trace") { - span, _ := opentracing.StartSpanFromContext(Ctx, "createContainer") - defer span.Finish() - } - - rtc := runtime.GetConfig() - ctx := getContext() - rootfs := "" - if c.Bool("rootfs") { - rootfs = c.InputArgs[0] - } - - var err error - var cidFile *os.File - if c.IsSet("cidfile") && os.Geteuid() == 0 { - cidFile, err = libpod.OpenExclusiveFile(c.String("cidfile")) - if err != nil && os.IsExist(err) { - return nil, nil, errors.Errorf("container id file exists. Ensure another container is not using it or delete %s", c.String("cidfile")) - } - if err != nil { - return nil, nil, errors.Errorf("error opening cidfile %s", c.String("cidfile")) - } - defer cidFile.Close() - defer cidFile.Sync() - } - - imageName := "" - var data *inspect.ImageData = nil - - if rootfs == "" && !rootless.SkipStorageSetup() { - var writer io.Writer - if !c.Bool("quiet") { - writer = os.Stderr - } - - newImage, err := runtime.ImageRuntime().New(ctx, c.InputArgs[0], rtc.SignaturePolicyPath, "", writer, nil, image.SigningOptions{}, false, nil) - if err != nil { - return nil, nil, err - } - data, err = newImage.Inspect(ctx) - names := newImage.Names() - if len(names) > 0 { - imageName = names[0] - } else { - imageName = newImage.ID() - } - } - createConfig, err := parseCreateOpts(ctx, c, runtime, imageName, data) - if err != nil { - return nil, nil, err - } - - ctr, err := createContainerFromCreateConfig(runtime, createConfig, ctx, nil) - if err != nil { - return nil, nil, err - } - if cidFile != nil { - _, err = cidFile.WriteString(ctr.ID()) - if err != nil { - logrus.Error(err) - } - - } - - logrus.Debugf("New container created %q", ctr.ID()) - return ctr, createConfig, nil -} - -func parseSecurityOpt(config *cc.CreateConfig, securityOpts []string) error { - var ( - labelOpts []string - ) - - if config.PidMode.IsHost() { - labelOpts = append(labelOpts, label.DisableSecOpt()...) - } else if config.PidMode.IsContainer() { - ctr, err := config.Runtime.LookupContainer(config.PidMode.Container()) - if err != nil { - return errors.Wrapf(err, "container %q not found", config.PidMode.Container()) - } - secopts, err := label.DupSecOpt(ctr.ProcessLabel()) - if err != nil { - return errors.Wrapf(err, "failed to duplicate label %q ", ctr.ProcessLabel()) - } - labelOpts = append(labelOpts, secopts...) - } - - if config.IpcMode.IsHost() { - labelOpts = append(labelOpts, label.DisableSecOpt()...) - } else if config.IpcMode.IsContainer() { - ctr, err := config.Runtime.LookupContainer(config.IpcMode.Container()) - if err != nil { - return errors.Wrapf(err, "container %q not found", config.IpcMode.Container()) - } - secopts, err := label.DupSecOpt(ctr.ProcessLabel()) - if err != nil { - return errors.Wrapf(err, "failed to duplicate label %q ", ctr.ProcessLabel()) - } - labelOpts = append(labelOpts, secopts...) - } - - for _, opt := range securityOpts { - if opt == "no-new-privileges" { - config.NoNewPrivs = true - } else { - con := strings.SplitN(opt, "=", 2) - if len(con) != 2 { - return fmt.Errorf("Invalid --security-opt 1: %q", opt) - } - - switch con[0] { - case "label": - labelOpts = append(labelOpts, con[1]) - case "apparmor": - config.ApparmorProfile = con[1] - case "seccomp": - config.SeccompProfilePath = con[1] - default: - return fmt.Errorf("Invalid --security-opt 2: %q", opt) - } - } - } - - if config.SeccompProfilePath == "" { - if _, err := os.Stat(libpod.SeccompOverridePath); err == nil { - config.SeccompProfilePath = libpod.SeccompOverridePath - } else { - if !os.IsNotExist(err) { - return errors.Wrapf(err, "can't check if %q exists", libpod.SeccompOverridePath) - } - if _, err := os.Stat(libpod.SeccompDefaultPath); err != nil { - if !os.IsNotExist(err) { - return errors.Wrapf(err, "can't check if %q exists", libpod.SeccompDefaultPath) - } - } else { - config.SeccompProfilePath = libpod.SeccompDefaultPath - } - } - } - config.LabelOpts = labelOpts - return nil -} - -// isPortInPortBindings determines if an exposed host port is in user -// provided ports -func isPortInPortBindings(pb map[nat.Port][]nat.PortBinding, port nat.Port) bool { - var hostPorts []string - for _, i := range pb { - hostPorts = append(hostPorts, i[0].HostPort) - } - return util.StringInSlice(port.Port(), hostPorts) -} - -// isPortInImagePorts determines if an exposed host port was given to us by metadata -// in the image itself -func isPortInImagePorts(exposedPorts map[string]struct{}, port string) bool { - for i := range exposedPorts { - fields := strings.Split(i, "/") - if port == fields[0] { - return true - } - } - return false -} - -func configureEntrypoint(c *cliconfig.PodmanCommand, data *inspect.ImageData) []string { - entrypoint := []string{} - if c.IsSet("entrypoint") { - // Force entrypoint to "" - if c.String("entrypoint") == "" { - return entrypoint - } - // Check if entrypoint specified is json - if err := json.Unmarshal([]byte(c.String("entrypoint")), &entrypoint); err == nil { - return entrypoint - } - // Return entrypoint as a single command - return []string{c.String("entrypoint")} - } - if data != nil { - return data.Config.Entrypoint - } - return entrypoint -} - -func configurePod(c *cliconfig.PodmanCommand, runtime *libpod.Runtime, namespaces map[string]string, podName string) (map[string]string, error) { - pod, err := runtime.LookupPod(podName) - if err != nil { - return namespaces, err - } - podInfraID, err := pod.InfraContainerID() - if err != nil { - return namespaces, err - } - if (namespaces["pid"] == cc.Pod) || (!c.IsSet("pid") && pod.SharesPID()) { - namespaces["pid"] = fmt.Sprintf("container:%s", podInfraID) - } - if (namespaces["net"] == cc.Pod) || (!c.IsSet("net") && !c.IsSet("network") && pod.SharesNet()) { - namespaces["net"] = fmt.Sprintf("container:%s", podInfraID) - } - if (namespaces["user"] == cc.Pod) || (!c.IsSet("user") && pod.SharesUser()) { - namespaces["user"] = fmt.Sprintf("container:%s", podInfraID) - } - if (namespaces["ipc"] == cc.Pod) || (!c.IsSet("ipc") && pod.SharesIPC()) { - namespaces["ipc"] = fmt.Sprintf("container:%s", podInfraID) - } - if (namespaces["uts"] == cc.Pod) || (!c.IsSet("uts") && pod.SharesUTS()) { - namespaces["uts"] = fmt.Sprintf("container:%s", podInfraID) - } - return namespaces, nil -} - -// Parses CLI options related to container creation into a config which can be -// parsed into an OCI runtime spec -func parseCreateOpts(ctx context.Context, c *cliconfig.PodmanCommand, runtime *libpod.Runtime, imageName string, data *inspect.ImageData) (*cc.CreateConfig, error) { - var ( - inputCommand, command []string - memoryLimit, memoryReservation, memorySwap, memoryKernel int64 - blkioWeight uint16 - namespaces map[string]string - ) - if c.IsSet("restart") { - return nil, errors.Errorf("--restart option is not supported.\nUse systemd unit files for restarting containers") - } - - idmappings, err := util.ParseIDMapping(c.StringSlice("uidmap"), c.StringSlice("gidmap"), c.String("subuidname"), c.String("subgidname")) - if err != nil { - return nil, err - } - - if c.String("mac-address") != "" { - return nil, errors.Errorf("--mac-address option not currently supported") - } - - imageID := "" - - inputCommand = c.InputArgs[1:] - if data != nil { - imageID = data.ID - } - - rootfs := "" - if c.Bool("rootfs") { - rootfs = c.InputArgs[0] - } - - sysctl, err := validateSysctl(c.StringSlice("sysctl")) - if err != nil { - return nil, errors.Wrapf(err, "invalid value for sysctl") - } - - if c.String("memory") != "" { - memoryLimit, err = units.RAMInBytes(c.String("memory")) - if err != nil { - return nil, errors.Wrapf(err, "invalid value for memory") - } - } - if c.String("memory-reservation") != "" { - memoryReservation, err = units.RAMInBytes(c.String("memory-reservation")) - if err != nil { - return nil, errors.Wrapf(err, "invalid value for memory-reservation") - } - } - if c.String("memory-swap") != "" { - memorySwap, err = units.RAMInBytes(c.String("memory-swap")) - if err != nil { - return nil, errors.Wrapf(err, "invalid value for memory-swap") - } - } - if c.String("kernel-memory") != "" { - memoryKernel, err = units.RAMInBytes(c.String("kernel-memory")) - if err != nil { - return nil, errors.Wrapf(err, "invalid value for kernel-memory") - } - } - if c.String("blkio-weight") != "" { - u, err := strconv.ParseUint(c.String("blkio-weight"), 10, 16) - if err != nil { - return nil, errors.Wrapf(err, "invalid value for blkio-weight") - } - blkioWeight = uint16(u) - } - var mountList []spec.Mount - if mountList, err = parseMounts(c.StringArray("mount")); err != nil { - return nil, err - } - - if err = parseVolumes(c.StringArray("volume")); err != nil { - return nil, err - } - - if err = parseVolumesFrom(c.StringSlice("volumes-from")); err != nil { - return nil, err - } - - tty := c.Bool("tty") - - if c.Flag("cpu-period").Changed && c.Flag("cpus").Changed { - return nil, errors.Errorf("--cpu-period and --cpus cannot be set together") - } - if c.Flag("cpu-quota").Changed && c.Flag("cpus").Changed { - return nil, errors.Errorf("--cpu-quota and --cpus cannot be set together") - } - - // EXPOSED PORTS - var portBindings map[nat.Port][]nat.PortBinding - if data != nil { - portBindings, err = cc.ExposedPorts(c.StringSlice("expose"), c.StringSlice("publish"), c.Bool("publish-all"), data.Config.ExposedPorts) - if err != nil { - return nil, err - } - } - - // Kernel Namespaces - // TODO Fix handling of namespace from pod - // Instead of integrating here, should be done in libpod - // However, that also involves setting up security opts - // when the pod's namespace is integrated - namespaceNet := c.String("network") - if c.Flag("net").Changed { - namespaceNet = c.String("net") - } - namespaces = map[string]string{ - "pid": c.String("pid"), - "net": namespaceNet, - "ipc": c.String("ipc"), - "user": c.String("userns"), - "uts": c.String("uts"), - } - - originalPodName := c.String("pod") - podName := strings.Replace(originalPodName, "new:", "", 1) - // after we strip out :new, make sure there is something left for a pod name - if len(podName) < 1 && c.IsSet("pod") { - return nil, errors.Errorf("new pod name must be at least one character") - } - if c.IsSet("pod") { - if strings.HasPrefix(originalPodName, "new:") { - if rootless.IsRootless() { - // To create a new pod, we must immediately create the userns. - became, ret, err := rootless.BecomeRootInUserNS() - if err != nil { - return nil, err - } - if became { - os.Exit(ret) - } - } - // pod does not exist; lets make it - var podOptions []libpod.PodCreateOption - podOptions = append(podOptions, libpod.WithPodName(podName), libpod.WithInfraContainer(), libpod.WithPodCgroups()) - if len(portBindings) > 0 { - ociPortBindings, err := cc.NatToOCIPortBindings(portBindings) - if err != nil { - return nil, err - } - podOptions = append(podOptions, libpod.WithInfraContainerPorts(ociPortBindings)) - } - - podNsOptions, err := shared.GetNamespaceOptions(strings.Split(DefaultKernelNamespaces, ",")) - if err != nil { - return nil, err - } - podOptions = append(podOptions, podNsOptions...) - // make pod - pod, err := runtime.NewPod(ctx, podOptions...) - if err != nil { - return nil, err - } - logrus.Debugf("pod %s created by new container request", pod.ID()) - - // The container now cannot have port bindings; so we reset the map - portBindings = make(map[nat.Port][]nat.PortBinding) - } - namespaces, err = configurePod(c, runtime, namespaces, podName) - if err != nil { - return nil, err - } - } - - pidMode := ns.PidMode(namespaces["pid"]) - if !cc.Valid(string(pidMode), pidMode) { - return nil, errors.Errorf("--pid %q is not valid", c.String("pid")) - } - - usernsMode := ns.UsernsMode(namespaces["user"]) - if !cc.Valid(string(usernsMode), usernsMode) { - return nil, errors.Errorf("--userns %q is not valid", namespaces["user"]) - } - - utsMode := ns.UTSMode(namespaces["uts"]) - if !cc.Valid(string(utsMode), utsMode) { - return nil, errors.Errorf("--uts %q is not valid", namespaces["uts"]) - } - - ipcMode := ns.IpcMode(namespaces["ipc"]) - if !cc.Valid(string(ipcMode), ipcMode) { - return nil, errors.Errorf("--ipc %q is not valid", ipcMode) - } - - // Make sure if network is set to container namespace, port binding is not also being asked for - netMode := ns.NetworkMode(namespaces["net"]) - if netMode.IsContainer() { - if len(portBindings) > 0 { - return nil, errors.Errorf("cannot set port bindings on an existing container network namespace") - } - } - - // USER - user := c.String("user") - if user == "" { - if data == nil { - user = "0" - } else { - user = data.Config.User - } - } - - // STOP SIGNAL - stopSignal := syscall.SIGTERM - signalString := "" - if data != nil { - signalString = data.Config.StopSignal - } - if c.IsSet("stop-signal") { - signalString = c.String("stop-signal") - } - if signalString != "" { - stopSignal, err = signal.ParseSignal(signalString) - if err != nil { - return nil, err - } - } - - // ENVIRONMENT VARIABLES - env := defaultEnvVariables - if data != nil { - for _, e := range data.Config.Env { - split := strings.SplitN(e, "=", 2) - if len(split) > 1 { - env[split[0]] = split[1] - } else { - env[split[0]] = "" - } - } - } - if err := readKVStrings(env, c.StringSlice("env-file"), c.StringSlice("env")); err != nil { - return nil, errors.Wrapf(err, "unable to process environment variables") - } - - // LABEL VARIABLES - labels, err := getAllLabels(c.StringSlice("label-file"), c.StringSlice("label")) - if err != nil { - return nil, errors.Wrapf(err, "unable to process labels") - } - if data != nil { - for key, val := range data.Config.Labels { - if _, ok := labels[key]; !ok { - labels[key] = val - } - } - } - - // ANNOTATIONS - annotations := make(map[string]string) - // First, add our default annotations - annotations[ann.ContainerType] = "sandbox" - annotations[ann.TTY] = "false" - if tty { - annotations[ann.TTY] = "true" - } - if data != nil { - // Next, add annotations from the image - for key, value := range data.Annotations { - annotations[key] = value - } - } - // Last, add user annotations - for _, annotation := range c.StringSlice("annotation") { - splitAnnotation := strings.SplitN(annotation, "=", 2) - if len(splitAnnotation) < 2 { - return nil, errors.Errorf("Annotations must be formatted KEY=VALUE") - } - annotations[splitAnnotation[0]] = splitAnnotation[1] - } - - // WORKING DIRECTORY - workDir := "/" - if c.IsSet("workdir") || c.IsSet("w") { - workDir = c.String("workdir") - } else if data != nil && data.Config.WorkingDir != "" { - workDir = data.Config.WorkingDir - } - - entrypoint := configureEntrypoint(c, data) - // Build the command - // If we have an entry point, it goes first - if len(entrypoint) > 0 { - command = entrypoint - } - if len(inputCommand) > 0 { - // User command overrides data CMD - command = append(command, inputCommand...) - } else if data != nil && len(data.Config.Cmd) > 0 && !c.IsSet("entrypoint") { - // If not user command, add CMD - command = append(command, data.Config.Cmd...) - } - - if data != nil && len(command) == 0 { - return nil, errors.Errorf("No command specified on command line or as CMD or ENTRYPOINT in this image") - } - - // SHM Size - shmSize, err := units.FromHumanSize(c.String("shm-size")) - if err != nil { - return nil, errors.Wrapf(err, "unable to translate --shm-size") - } - - // Verify the additional hosts are in correct format - for _, host := range c.StringSlice("add-host") { - if _, err := validateExtraHost(host); err != nil { - return nil, err - } - } - - // Check for . and dns-search domains - if util.StringInSlice(".", c.StringSlice("dns-search")) && len(c.StringSlice("dns-search")) > 1 { - return nil, errors.Errorf("cannot pass additional search domains when also specifying '.'") - } - - // Validate domains are good - for _, dom := range c.StringSlice("dns-search") { - if _, err := validateDomain(dom); err != nil { - return nil, err - } - } - - var ImageVolumes map[string]struct{} - if data != nil && c.String("image-volume") != "ignore" { - ImageVolumes = data.Config.Volumes - } - - var imageVolType = map[string]string{ - "bind": "", - "tmpfs": "", - "ignore": "", - } - if _, ok := imageVolType[c.String("image-volume")]; !ok { - return nil, errors.Errorf("invalid image-volume type %q. Pick one of bind, tmpfs, or ignore", c.String("image-volume")) - } - - var systemd bool - if command != nil && c.Bool("systemd") && ((filepath.Base(command[0]) == "init") || (filepath.Base(command[0]) == "systemd")) { - systemd = true - if signalString == "" { - stopSignal, err = signal.ParseSignal("RTMIN+3") - if err != nil { - return nil, errors.Wrapf(err, "error parsing systemd signal") - } - } - } - // This is done because cobra cannot have two aliased flags. So we have to check - // both - network := c.String("network") - if c.Flag("net").Changed { - network = c.String("net") - } - - var memorySwappiness int64 - if c.Flags().Lookup("memory-swappiness") != nil { - memorySwappiness, _ = c.Flags().GetInt64("memory-swappiness") - } - config := &cc.CreateConfig{ - Runtime: runtime, - Annotations: annotations, - BuiltinImgVolumes: ImageVolumes, - ConmonPidFile: c.String("conmon-pidfile"), - ImageVolumeType: c.String("image-volume"), - CapAdd: c.StringSlice("cap-add"), - CapDrop: c.StringSlice("cap-drop"), - CgroupParent: c.String("cgroup-parent"), - Command: command, - Detach: c.Bool("detach"), - Devices: c.StringSlice("device"), - DNSOpt: c.StringSlice("dns-opt"), - DNSSearch: c.StringSlice("dns-search"), - DNSServers: c.StringSlice("dns"), - Entrypoint: entrypoint, - Env: env, - //ExposedPorts: ports, - GroupAdd: c.StringSlice("group-add"), - Hostname: c.String("hostname"), - HostAdd: c.StringSlice("add-host"), - IDMappings: idmappings, - Image: imageName, - ImageID: imageID, - Interactive: c.Bool("interactive"), - //IP6Address: c.String("ipv6"), // Not implemented yet - needs CNI support for static v6 - IPAddress: c.String("ip"), - Labels: labels, - //LinkLocalIP: c.StringSlice("link-local-ip"), // Not implemented yet - LogDriver: c.String("log-driver"), - LogDriverOpt: c.StringSlice("log-opt"), - MacAddress: c.String("mac-address"), - Name: c.String("name"), - Network: network, - //NetworkAlias: c.StringSlice("network-alias"), // Not implemented - does this make sense in Podman? - IpcMode: ipcMode, - NetMode: netMode, - UtsMode: utsMode, - PidMode: pidMode, - Pod: podName, - Privileged: c.Bool("privileged"), - Publish: c.StringSlice("publish"), - PublishAll: c.Bool("publish-all"), - PortBindings: portBindings, - Quiet: c.Bool("quiet"), - ReadOnlyRootfs: c.Bool("read-only"), - Resources: cc.CreateResourceConfig{ - BlkioWeight: blkioWeight, - BlkioWeightDevice: c.StringSlice("blkio-weight-device"), - CPUShares: c.Uint64("cpu-shares"), - CPUPeriod: c.Uint64("cpu-period"), - CPUsetCPUs: c.String("cpuset-cpus"), - CPUsetMems: c.String("cpuset-mems"), - CPUQuota: c.Int64("cpu-quota"), - CPURtPeriod: c.Uint64("cpu-rt-period"), - CPURtRuntime: c.Int64("cpu-rt-runtime"), - CPUs: c.Float64("cpus"), - DeviceReadBps: c.StringSlice("device-read-bps"), - DeviceReadIOps: c.StringSlice("device-read-iops"), - DeviceWriteBps: c.StringSlice("device-write-bps"), - DeviceWriteIOps: c.StringSlice("device-write-iops"), - DisableOomKiller: c.Bool("oom-kill-disable"), - ShmSize: shmSize, - Memory: memoryLimit, - MemoryReservation: memoryReservation, - MemorySwap: memorySwap, - MemorySwappiness: int(memorySwappiness), - KernelMemory: memoryKernel, - OomScoreAdj: c.Int("oom-score-adj"), - PidsLimit: c.Int64("pids-limit"), - Ulimit: c.StringSlice("ulimit"), - }, - Rm: c.Bool("rm"), - StopSignal: stopSignal, - StopTimeout: c.Uint("stop-timeout"), - Sysctl: sysctl, - Systemd: systemd, - Tmpfs: c.StringSlice("tmpfs"), - Tty: tty, - User: user, - UsernsMode: usernsMode, - Mounts: mountList, - Volumes: c.StringArray("volume"), - WorkDir: workDir, - Rootfs: rootfs, - VolumesFrom: c.StringSlice("volumes-from"), - Syslog: c.GlobalFlags.Syslog, - } - if c.Bool("init") { - initPath := c.String("init-path") - if initPath == "" { - initPath = runtime.GetConfig().InitPath - } - if err := config.AddContainerInitBinary(initPath); err != nil { - return nil, err - } - } - - if config.Privileged { - config.LabelOpts = label.DisableSecOpt() - } else { - if err := parseSecurityOpt(config, c.StringArray("security-opt")); err != nil { - return nil, err - } - } - config.SecurityOpts = c.StringArray("security-opt") - warnings, err := verifyContainerResources(config, false) - if err != nil { - return nil, err - } - for _, warning := range warnings { - fmt.Fprintln(os.Stderr, warning) - } - return config, nil -} - -type namespace interface { - IsContainer() bool - Container() string -} - -func joinOrCreateRootlessUserNamespace(createConfig *cc.CreateConfig, runtime *libpod.Runtime) (bool, int, error) { - if os.Geteuid() == 0 { - return false, 0, nil - } - - if createConfig.Pod != "" { - pod, err := runtime.LookupPod(createConfig.Pod) - if err != nil { - return false, -1, err - } - inspect, err := pod.Inspect() - for _, ctr := range inspect.Containers { - prevCtr, err := runtime.LookupContainer(ctr.ID) - if err != nil { - return false, -1, err - } - s, err := prevCtr.State() - if err != nil { - return false, -1, err - } - if s != libpod.ContainerStateRunning && s != libpod.ContainerStatePaused { - continue - } - data, err := ioutil.ReadFile(prevCtr.Config().ConmonPidFile) - if err != nil { - return false, -1, errors.Wrapf(err, "cannot read conmon PID file %q", prevCtr.Config().ConmonPidFile) - } - conmonPid, err := strconv.Atoi(string(data)) - if err != nil { - return false, -1, errors.Wrapf(err, "cannot parse PID %q", data) - } - return rootless.JoinDirectUserAndMountNS(uint(conmonPid)) - } - } - - namespacesStr := []string{string(createConfig.IpcMode), string(createConfig.NetMode), string(createConfig.UsernsMode), string(createConfig.PidMode), string(createConfig.UtsMode)} - for _, i := range namespacesStr { - if cc.IsNS(i) { - return rootless.JoinNSPath(cc.NS(i)) - } - } - - namespaces := []namespace{createConfig.IpcMode, createConfig.NetMode, createConfig.UsernsMode, createConfig.PidMode, createConfig.UtsMode} - for _, i := range namespaces { - if i.IsContainer() { - ctr, err := runtime.LookupContainer(i.Container()) - if err != nil { - return false, -1, err - } - pid, err := ctr.PID() - if err != nil { - return false, -1, err - } - if pid == 0 { - if createConfig.Pod != "" { - continue - } - return false, -1, errors.Errorf("dependency container %s is not running", ctr.ID()) - } - return rootless.JoinNS(uint(pid)) - } - } - return rootless.BecomeRootInUserNS() -} - -func createContainerFromCreateConfig(r *libpod.Runtime, createConfig *cc.CreateConfig, ctx context.Context, pod *libpod.Pod) (*libpod.Container, error) { - runtimeSpec, err := cc.CreateConfigToOCISpec(createConfig) - if err != nil { - return nil, err - } - - options, err := createConfig.GetContainerCreateOptions(r, pod) - if err != nil { - return nil, err - } - became, ret, err := joinOrCreateRootlessUserNamespace(createConfig, r) - if err != nil { - return nil, err - } - if became { - os.Exit(ret) - } - - ctr, err := r.NewContainer(ctx, runtimeSpec, options...) - if err != nil { - return nil, err - } - - createConfigJSON, err := json.Marshal(createConfig) - if err != nil { - return nil, err - } - if err := ctr.AddArtifact("create-config", createConfigJSON); err != nil { - return nil, err - } - return ctr, nil -} diff --git a/cmd/podman/diff.go b/cmd/podman/diff.go index e232d7e66..e77e562d4 100644 --- a/cmd/podman/diff.go +++ b/cmd/podman/diff.go @@ -2,8 +2,8 @@ package main import ( "fmt" + "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/storage/pkg/archive" "github.com/pkg/errors" @@ -34,8 +34,7 @@ func (so stdoutStruct) Out() error { var ( diffCommand cliconfig.DiffValues - diffDescription = fmt.Sprint(`Displays changes on a container or image's filesystem. The - container or image will be compared to its parent layer`) + diffDescription = fmt.Sprint(`Displays changes on a container or image's filesystem. The container or image will be compared to its parent layer.`) _diffCommand = &cobra.Command{ Use: "diff [flags] CONTAINER | IMAGE", @@ -54,6 +53,7 @@ var ( func init() { diffCommand.Command = _diffCommand + diffCommand.SetHelpTemplate(HelpTemplate()) diffCommand.SetUsageTemplate(UsageTemplate()) flags := diffCommand.Flags() diff --git a/cmd/podman/errors.go b/cmd/podman/errors.go index 2572b8779..9731037f4 100644 --- a/cmd/podman/errors.go +++ b/cmd/podman/errors.go @@ -1,3 +1,5 @@ +// +build !remoteclient + package main import ( @@ -13,7 +15,8 @@ func outputError(err error) { if MainGlobalOpts.LogLevel == "debug" { logrus.Errorf(err.Error()) } else { - if ee, ok := err.(*exec.ExitError); ok { + ee, ok := err.(*exec.ExitError) + if ok { if status, ok := ee.Sys().(syscall.WaitStatus); ok { exitCode = status.ExitStatus() } diff --git a/cmd/podman/errors_remote.go b/cmd/podman/errors_remote.go new file mode 100644 index 000000000..ab255ea56 --- /dev/null +++ b/cmd/podman/errors_remote.go @@ -0,0 +1,43 @@ +// +build remoteclient + +package main + +import ( + "fmt" + "os" + "os/exec" + "syscall" + + "github.com/containers/libpod/cmd/podman/varlink" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" +) + +func outputError(err error) { + if MainGlobalOpts.LogLevel == "debug" { + logrus.Errorf(err.Error()) + } else { + if ee, ok := err.(*exec.ExitError); ok { + if status, ok := ee.Sys().(syscall.WaitStatus); ok { + exitCode = status.ExitStatus() + } + } + var ne error + switch e := err.(type) { + // For some reason golang wont let me list them with commas so listing them all. + case *iopodman.ImageNotFound: + ne = errors.New(e.Reason) + case *iopodman.ContainerNotFound: + ne = errors.New(e.Reason) + case *iopodman.PodNotFound: + ne = errors.New(e.Reason) + case *iopodman.VolumeNotFound: + ne = errors.New(e.Reason) + case *iopodman.ErrorOccurred: + ne = errors.New(e.Reason) + default: + ne = err + } + fmt.Fprintln(os.Stderr, "Error:", ne.Error()) + } +} diff --git a/cmd/podman/events.go b/cmd/podman/events.go new file mode 100644 index 000000000..f6c20e8ff --- /dev/null +++ b/cmd/podman/events.go @@ -0,0 +1,49 @@ +package main + +import ( + "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/pkg/adapter" + "github.com/pkg/errors" + "github.com/spf13/cobra" +) + +var ( + eventsCommand cliconfig.EventValues + eventsDescription = "Monitor podman events" + _eventsCommand = &cobra.Command{ + Use: "events", + Args: noSubArgs, + Short: "show podman events", + Long: eventsDescription, + RunE: func(cmd *cobra.Command, args []string) error { + eventsCommand.InputArgs = args + eventsCommand.GlobalFlags = MainGlobalOpts + return eventsCmd(&eventsCommand) + }, + Example: `podman events + podman events --filter event=create + podman events --since 1h30s`, + } +) + +func init() { + eventsCommand.Command = _eventsCommand + eventsCommand.SetUsageTemplate(UsageTemplate()) + flags := eventsCommand.Flags() + flags.StringArrayVar(&eventsCommand.Filter, "filter", []string{}, "filter output") + flags.StringVar(&eventsCommand.Format, "format", "", "format the output using a Go template") + flags.BoolVar(&eventsCommand.Stream, "stream", true, "stream new events; for testing only") + flags.StringVar(&eventsCommand.Since, "since", "", "show all events created since timestamp") + flags.StringVar(&eventsCommand.Until, "until", "", "show all events until timestamp") + flags.MarkHidden("stream") +} + +func eventsCmd(c *cliconfig.EventValues) error { + runtime, err := adapter.GetRuntime(&c.PodmanCommand) + if err != nil { + return errors.Wrapf(err, "error creating libpod runtime") + } + defer runtime.Shutdown(false) + + return runtime.Events(c) +} diff --git a/cmd/podman/exec.go b/cmd/podman/exec.go index 4917fb606..a6afbf75a 100644 --- a/cmd/podman/exec.go +++ b/cmd/podman/exec.go @@ -2,23 +2,23 @@ package main import ( "fmt" - "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/spf13/cobra" + "io/ioutil" "os" + "strconv" + "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/cmd/podman/libpodruntime" + "github.com/containers/libpod/cmd/podman/shared/parse" "github.com/containers/libpod/libpod" "github.com/containers/libpod/pkg/rootless" "github.com/pkg/errors" + "github.com/spf13/cobra" ) var ( execCommand cliconfig.ExecValues - execDescription = ` - podman exec - - Run a command in a running container + execDescription = `Execute the specified command inside a running container. ` _execCommand = &cobra.Command{ Use: "exec [flags] CONTAINER [COMMAND [ARG...]]", @@ -37,16 +37,18 @@ var ( func init() { execCommand.Command = _execCommand + execCommand.SetHelpTemplate(HelpTemplate()) execCommand.SetUsageTemplate(UsageTemplate()) flags := execCommand.Flags() flags.SetInterspersed(false) - flags.StringSliceVarP(&execCommand.Env, "env", "e", []string{}, "Set environment variables") + flags.StringArrayVarP(&execCommand.Env, "env", "e", []string{}, "Set environment variables") flags.BoolVarP(&execCommand.Interfactive, "interactive", "i", false, "Not supported. All exec commands are interactive by default") flags.BoolVarP(&execCommand.Latest, "latest", "l", false, "Act on the latest container podman is aware of") flags.BoolVar(&execCommand.Privileged, "privileged", false, "Give the process extended Linux capabilities inside the container. The default is false") flags.BoolVarP(&execCommand.Tty, "tty", "t", false, "Allocate a pseudo-TTY. The default is false") flags.StringVarP(&execCommand.User, "user", "u", "", "Sets the username or UID used and optionally the groupname or GID for the specified command") + flags.IntVar(&execCommand.PreserveFDs, "preserve-fds", 0, "Pass N additional file descriptors to the container") flags.StringVarP(&execCommand.Workdir, "workdir", "w", "", "Working directory inside the container") markFlagHiddenForRemoteClient("latest", flags) } @@ -82,22 +84,54 @@ func execCmd(c *cliconfig.ExecValues) error { return errors.Wrapf(err, "unable to exec into %s", args[0]) } - pid, err := ctr.PID() - if err != nil { - return err - } - became, ret, err := rootless.JoinNS(uint(pid)) - if err != nil { - return err + if c.PreserveFDs > 0 { + entries, err := ioutil.ReadDir("/proc/self/fd") + if err != nil { + return errors.Wrapf(err, "unable to read /proc/self/fd") + } + m := make(map[int]bool) + for _, e := range entries { + i, err := strconv.Atoi(e.Name()) + if err != nil { + if err != nil { + return errors.Wrapf(err, "cannot parse %s in /proc/self/fd", e.Name()) + } + } + m[i] = true + } + for i := 3; i < 3+c.PreserveFDs; i++ { + if _, found := m[i]; !found { + return errors.New("invalid --preserve-fds=N specified. Not enough FDs available") + } + } + } - if became { - os.Exit(ret) + + if os.Geteuid() != 0 { + var became bool + var ret int + + data, err := ioutil.ReadFile(ctr.Config().ConmonPidFile) + if err != nil { + return errors.Wrapf(err, "cannot read conmon PID file %q", ctr.Config().ConmonPidFile) + } + conmonPid, err := strconv.Atoi(string(data)) + if err != nil { + return errors.Wrapf(err, "cannot parse PID %q", data) + } + became, ret, err = rootless.JoinDirectUserAndMountNS(uint(conmonPid)) + if err != nil { + return err + } + if became { + os.Exit(ret) + } } // ENVIRONMENT VARIABLES env := map[string]string{} - if err := readKVStrings(env, []string{}, c.Env); err != nil { + if err := parse.ReadKVStrings(env, []string{}, c.Env); err != nil { return errors.Wrapf(err, "unable to process environment variables") } envs := []string{} @@ -113,5 +147,5 @@ func execCmd(c *cliconfig.ExecValues) error { streams.AttachError = true streams.AttachInput = true - return ctr.Exec(c.Tty, c.Privileged, envs, cmd, c.User, c.Workdir, streams) + return ctr.Exec(c.Tty, c.Privileged, envs, cmd, c.User, c.Workdir, streams, c.PreserveFDs) } diff --git a/cmd/podman/exists.go b/cmd/podman/exists.go index 109831e74..8a2f78c88 100644 --- a/cmd/podman/exists.go +++ b/cmd/podman/exists.go @@ -16,21 +16,12 @@ var ( containerExistsCommand cliconfig.ContainerExistsValues podExistsCommand cliconfig.PodExistsValues - imageExistsDescription = ` - podman image exists + imageExistsDescription = `If the named image exists in local storage, podman image exists exits with 0, otherwise the exit code will be 1.` - Check if an image exists in local storage -` - containerExistsDescription = ` - podman container exists + containerExistsDescription = `If the named container exists in local storage, podman container exists exits with 0, otherwise the exit code will be 1.` - Check if a container exists in local storage -` - podExistsDescription = ` - podman pod exists + podExistsDescription = `If the named pod exists in local storage, podman pod exists exits with 0, otherwise the exit code will be 1.` - Check if a pod exists in local storage -` _imageExistsCommand = &cobra.Command{ Use: "exists IMAGE", Short: "Check if an image exists in local storage", @@ -75,12 +66,15 @@ var ( func init() { imageExistsCommand.Command = _imageExistsCommand imageExistsCommand.DisableFlagsInUseLine = true + imageExistsCommand.SetHelpTemplate(HelpTemplate()) imageExistsCommand.SetUsageTemplate(UsageTemplate()) containerExistsCommand.Command = _containerExistsCommand containerExistsCommand.DisableFlagsInUseLine = true + containerExistsCommand.SetHelpTemplate(HelpTemplate()) containerExistsCommand.SetUsageTemplate(UsageTemplate()) podExistsCommand.Command = _podExistsCommand podExistsCommand.DisableFlagsInUseLine = true + podExistsCommand.SetHelpTemplate(HelpTemplate()) podExistsCommand.SetUsageTemplate(UsageTemplate()) } diff --git a/cmd/podman/export.go b/cmd/podman/export.go index d40c05019..92633facd 100644 --- a/cmd/podman/export.go +++ b/cmd/podman/export.go @@ -4,6 +4,7 @@ import ( "os" "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/cmd/podman/shared/parse" "github.com/containers/libpod/pkg/adapter" "github.com/containers/libpod/pkg/rootless" "github.com/pkg/errors" @@ -32,9 +33,10 @@ var ( func init() { exportCommand.Command = _exportCommand + exportCommand.SetHelpTemplate(HelpTemplate()) exportCommand.SetUsageTemplate(UsageTemplate()) flags := exportCommand.Flags() - flags.StringVarP(&exportCommand.Output, "output", "o", "/dev/stdout", "Write to a file, default is STDOUT") + flags.StringVarP(&exportCommand.Output, "output", "o", "", "Write to a specified file (default: stdout, which must be redirected)") } // exportCmd saves a container to a tarball on disk @@ -58,18 +60,19 @@ func exportCmd(c *cliconfig.ExportValues) error { } output := c.Output - if runtime.Remote && (output == "/dev/stdout" || len(output) == 0) { + if runtime.Remote && len(output) == 0 { return errors.New("remote client usage must specify an output file (-o)") } - if output == "/dev/stdout" { + if len(output) == 0 { file := os.Stdout if logrus.IsTerminal(file) { return errors.Errorf("refusing to export to terminal. Use -o flag or redirect") } + output = "/dev/stdout" } - if err := validateFileName(output); err != nil { + if err := parse.ValidateFileName(output); err != nil { return err } return runtime.Export(args[0], output) diff --git a/cmd/podman/formats/formats.go b/cmd/podman/formats/formats.go deleted file mode 100644 index 37f9b8a20..000000000 --- a/cmd/podman/formats/formats.go +++ /dev/null @@ -1,171 +0,0 @@ -package formats - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "os" - "strings" - "text/tabwriter" - "text/template" - - "github.com/ghodss/yaml" - "github.com/pkg/errors" - "golang.org/x/crypto/ssh/terminal" -) - -const ( - // JSONString const to save on duplicate variable names - JSONString = "json" - // IDString const to save on duplicates for Go templates - IDString = "{{.ID}}" - - parsingErrorStr = "Template parsing error" -) - -// Writer interface for outputs -type Writer interface { - Out() error -} - -// JSONStructArray for JSON output -type JSONStructArray struct { - Output []interface{} -} - -// StdoutTemplateArray for Go template output -type StdoutTemplateArray struct { - Output []interface{} - Template string - Fields map[string]string -} - -// JSONStruct for JSON output -type JSONStruct struct { - Output interface{} -} - -// StdoutTemplate for Go template output -type StdoutTemplate struct { - Output interface{} - Template string - Fields map[string]string -} - -// YAMLStruct for YAML output -type YAMLStruct struct { - Output interface{} -} - -func setJSONFormatEncoder(isTerminal bool, w io.Writer) *json.Encoder { - enc := json.NewEncoder(w) - enc.SetIndent("", " ") - if isTerminal { - enc.SetEscapeHTML(false) - } - return enc -} - -// Out method for JSON Arrays -func (j JSONStructArray) Out() error { - buf := bytes.NewBuffer(nil) - enc := setJSONFormatEncoder(terminal.IsTerminal(int(os.Stdout.Fd())), buf) - if err := enc.Encode(j.Output); err != nil { - return err - } - data := buf.Bytes() - - // JSON returns a byte array with a literal null [110 117 108 108] in it - // if it is passed empty data. We used bytes.Compare to see if that is - // the case. - if diff := bytes.Compare(data, []byte("null")); diff == 0 { - data = []byte("[]") - } - - // If the we did get NULL back, we should spit out {} which is - // at least valid JSON for the consumer. - fmt.Printf("%s", data) - humanNewLine() - return nil -} - -// Out method for Go templates -func (t StdoutTemplateArray) Out() error { - w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0) - if strings.HasPrefix(t.Template, "table") { - // replace any spaces with tabs in template so that tabwriter can align it - t.Template = strings.Replace(strings.TrimSpace(t.Template[5:]), " ", "\t", -1) - headerTmpl, err := template.New("header").Funcs(headerFunctions).Parse(t.Template) - if err != nil { - return errors.Wrapf(err, parsingErrorStr) - } - err = headerTmpl.Execute(w, t.Fields) - if err != nil { - return err - } - fmt.Fprintln(w, "") - } - t.Template = strings.Replace(t.Template, " ", "\t", -1) - tmpl, err := template.New("image").Funcs(basicFunctions).Parse(t.Template) - if err != nil { - return errors.Wrapf(err, parsingErrorStr) - } - for i, raw := range t.Output { - basicTmpl := tmpl.Funcs(basicFunctions) - if err := basicTmpl.Execute(w, raw); err != nil { - return errors.Wrapf(err, parsingErrorStr) - } - if i != len(t.Output)-1 { - fmt.Fprintln(w, "") - continue - } - } - fmt.Fprintln(w, "") - return w.Flush() -} - -// Out method for JSON struct -func (j JSONStruct) Out() error { - data, err := json.MarshalIndent(j.Output, "", " ") - if err != nil { - return err - } - fmt.Printf("%s", data) - humanNewLine() - return nil -} - -//Out method for Go templates -func (t StdoutTemplate) Out() error { - tmpl, err := template.New("image").Parse(t.Template) - if err != nil { - return errors.Wrapf(err, "template parsing error") - } - err = tmpl.Execute(os.Stdout, t.Output) - if err != nil { - return err - } - humanNewLine() - return nil -} - -// Out method for YAML -func (y YAMLStruct) Out() error { - var buf []byte - var err error - buf, err = yaml.Marshal(y.Output) - if err != nil { - return err - } - fmt.Printf("%s", string(buf)) - humanNewLine() - return nil -} - -// humanNewLine prints a new line at the end of the output only if stdout is the terminal -func humanNewLine() { - if terminal.IsTerminal(int(os.Stdout.Fd())) { - fmt.Println() - } -} diff --git a/cmd/podman/formats/formats_test.go b/cmd/podman/formats/formats_test.go deleted file mode 100644 index c75109d65..000000000 --- a/cmd/podman/formats/formats_test.go +++ /dev/null @@ -1,42 +0,0 @@ -package formats - -import ( - "bytes" - "strings" - "testing" - - "github.com/containers/libpod/pkg/inspect" -) - -func TestSetJSONFormatEncoder(t *testing.T) { - tt := []struct { - name string - imageData *inspect.ImageData - expected string - isTerminal bool - }{ - { - name: "HTML tags are not escaped", - imageData: &inspect.ImageData{Author: "dave <dave@corp.io>"}, - expected: `"Author": "dave <dave@corp.io>"`, - isTerminal: true, - }, - { - name: "HTML tags are escaped", - imageData: &inspect.ImageData{Author: "dave <dave@corp.io>"}, - expected: `"Author": "dave \u003cdave@corp.io\u003e"`, - isTerminal: false, - }, - } - - for _, tc := range tt { - buf := bytes.NewBuffer(nil) - enc := setJSONFormatEncoder(tc.isTerminal, buf) - if err := enc.Encode(tc.imageData); err != nil { - t.Errorf("test %#v failed encoding: %s", tc.name, err) - } - if !strings.Contains(buf.String(), tc.expected) { - t.Errorf("test %#v expected output to contain %#v. Output:\n%v\n", tc.name, tc.expected, buf.String()) - } - } -} diff --git a/cmd/podman/formats/templates.go b/cmd/podman/formats/templates.go deleted file mode 100644 index c2582552a..000000000 --- a/cmd/podman/formats/templates.go +++ /dev/null @@ -1,78 +0,0 @@ -package formats - -import ( - "bytes" - "encoding/json" - "strings" - "text/template" -) - -// basicFunctions are the set of initial -// functions provided to every template. -var basicFunctions = template.FuncMap{ - "json": func(v interface{}) string { - buf := &bytes.Buffer{} - enc := json.NewEncoder(buf) - enc.SetEscapeHTML(false) - _ = enc.Encode(v) - // Remove the trailing new line added by the encoder - return strings.TrimSpace(buf.String()) - }, - "split": strings.Split, - "join": strings.Join, - "title": strings.Title, - "lower": strings.ToLower, - "upper": strings.ToUpper, - "pad": padWithSpace, - "truncate": truncateWithLength, -} - -// HeaderFunctions are used to created headers of a table. -// This is a replacement of basicFunctions for header generation -// because we want the header to remain intact. -// Some functions like `split` are irrelevant so not added. -var headerFunctions = template.FuncMap{ - "json": func(v string) string { - return v - }, - "title": func(v string) string { - return v - }, - "lower": func(v string) string { - return v - }, - "upper": func(v string) string { - return v - }, - "truncate": func(v string, l int) string { - return v - }, -} - -// Parse creates a new anonymous template with the basic functions -// and parses the given format. -func Parse(format string) (*template.Template, error) { - return NewParse("", format) -} - -// NewParse creates a new tagged template with the basic functions -// and parses the given format. -func NewParse(tag, format string) (*template.Template, error) { - return template.New(tag).Funcs(basicFunctions).Parse(format) -} - -// padWithSpace adds whitespace to the input if the input is non-empty -func padWithSpace(source string, prefix, suffix int) string { - if source == "" { - return source - } - return strings.Repeat(" ", prefix) + source + strings.Repeat(" ", suffix) -} - -// truncateWithLength truncates the source string up to the length provided by the input -func truncateWithLength(source string, length int) string { - if len(source) < length { - return source - } - return source[:length] -} diff --git a/cmd/podman/generate.go b/cmd/podman/generate.go index 773d625ee..197fd26a6 100644 --- a/cmd/podman/generate.go +++ b/cmd/podman/generate.go @@ -12,6 +12,7 @@ var ( Use: "generate", Short: "Generated structured data", Long: generateDescription, + RunE: commandRunE(), } ) diff --git a/cmd/podman/generate_kube.go b/cmd/podman/generate_kube.go index fa2872b77..42cfba8d8 100644 --- a/cmd/podman/generate_kube.go +++ b/cmd/podman/generate_kube.go @@ -15,10 +15,12 @@ import ( var ( containerKubeCommand cliconfig.GenerateKubeValues - containerKubeDescription = "Generate Kubernetes Pod YAML" - _containerKubeCommand = &cobra.Command{ + containerKubeDescription = `Command generates Kubernetes Pod YAML (v1 specification) from a podman container or pod. + + Whether the input is for a container or pod, Podman will always generate the specification as a Pod. The input may be in the form of a pod or container name or ID.` + _containerKubeCommand = &cobra.Command{ Use: "kube [flags] CONTAINER | POD", - Short: "Generate Kubernetes pod YAML for a container or pod", + Short: "Generate Kubernetes pod YAML from a container or pod", Long: containerKubeDescription, RunE: func(cmd *cobra.Command, args []string) error { containerKubeCommand.InputArgs = args @@ -33,6 +35,7 @@ var ( func init() { containerKubeCommand.Command = _containerKubeCommand + containerKubeCommand.SetHelpTemplate(HelpTemplate()) containerKubeCommand.SetUsageTemplate(UsageTemplate()) flags := containerKubeCommand.Flags() flags.BoolVarP(&containerKubeCommand.Service, "service", "s", false, "Generate YAML for kubernetes service object") @@ -54,8 +57,8 @@ func generateKubeYAMLCmd(c *cliconfig.GenerateKubeValues) error { return errors.Wrapf(libpod.ErrNotImplemented, "rootless users") } args := c.InputArgs - if len(args) > 1 || (len(args) < 1 && !c.Bool("latest")) { - return errors.Errorf("you must provide one container|pod ID or name or --latest") + if len(args) != 1 { + return errors.Errorf("you must provide exactly one container|pod ID or name") } runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) diff --git a/cmd/podman/healthcheck.go b/cmd/podman/healthcheck.go new file mode 100644 index 000000000..48d6b6bbf --- /dev/null +++ b/cmd/podman/healthcheck.go @@ -0,0 +1,26 @@ +package main + +import ( + "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/spf13/cobra" +) + +var healthcheckDescription = "Manage health checks on containers" +var healthcheckCommand = cliconfig.PodmanCommand{ + Command: &cobra.Command{ + Use: "healthcheck", + Short: "Manage Healthcheck", + Long: healthcheckDescription, + RunE: commandRunE(), + }, +} + +// Commands that are universally implemented +var healthcheckCommands []*cobra.Command + +func init() { + healthcheckCommand.AddCommand(healthcheckCommands...) + healthcheckCommand.AddCommand(getHealtcheckSubCommands()...) + healthcheckCommand.SetUsageTemplate(UsageTemplate()) + rootCmd.AddCommand(healthcheckCommand.Command) +} diff --git a/cmd/podman/healthcheck_run.go b/cmd/podman/healthcheck_run.go new file mode 100644 index 000000000..bd3a4ea15 --- /dev/null +++ b/cmd/podman/healthcheck_run.go @@ -0,0 +1,53 @@ +package main + +import ( + "fmt" + "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/libpod" + "github.com/containers/libpod/pkg/adapter" + "github.com/pkg/errors" + "github.com/spf13/cobra" +) + +var ( + healthcheckRunCommand cliconfig.HealthCheckValues + healthcheckRunDescription = "run the health check of a container" + _healthcheckrunCommand = &cobra.Command{ + Use: "run [flags] CONTAINER", + Short: "run the health check of a container", + Long: healthcheckRunDescription, + Example: `podman healthcheck run mywebapp`, + RunE: func(cmd *cobra.Command, args []string) error { + healthcheckRunCommand.InputArgs = args + healthcheckRunCommand.GlobalFlags = MainGlobalOpts + return healthCheckCmd(&healthcheckRunCommand) + }, + Args: func(cmd *cobra.Command, args []string) error { + if len(args) < 1 || len(args) > 1 { + return errors.New("must provide the name or ID of one container") + } + return nil + }, + } +) + +func init() { + healthcheckRunCommand.Command = _healthcheckrunCommand + healthcheckRunCommand.SetUsageTemplate(UsageTemplate()) +} + +func healthCheckCmd(c *cliconfig.HealthCheckValues) error { + runtime, err := adapter.GetRuntime(&c.PodmanCommand) + if err != nil { + return errors.Wrap(err, "could not get runtime") + } + status, err := runtime.HealthCheck(c) + if err != nil { + if status == libpod.HealthCheckFailure { + fmt.Println("\nunhealthy") + } + return err + } + fmt.Println("healthy") + return nil +} diff --git a/cmd/podman/history.go b/cmd/podman/history.go index 533ee91cb..4b76ef0ca 100644 --- a/cmd/podman/history.go +++ b/cmd/podman/history.go @@ -6,8 +6,8 @@ import ( "strings" "time" + "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/libpod/image" "github.com/containers/libpod/pkg/adapter" "github.com/docker/go-units" @@ -37,8 +37,9 @@ type historyOptions struct { var ( historyCommand cliconfig.HistoryValues - historyDescription = "Displays the history of an image. The information can be printed out in an easy to read, " + - "or user specified format, and can be truncated." + historyDescription = `Displays the history of an image. + + The information can be printed out in an easy to read, or user specified format, and can be truncated.` _historyCommand = &cobra.Command{ Use: "history [flags] IMAGE", Short: "Show history of a specified image", @@ -53,6 +54,7 @@ var ( func init() { historyCommand.Command = _historyCommand + historyCommand.SetHelpTemplate(HelpTemplate()) historyCommand.SetUsageTemplate(UsageTemplate()) flags := historyCommand.Flags() flags.StringVar(&historyCommand.Format, "format", "", "Change the output to JSON or a Go template") diff --git a/cmd/podman/image.go b/cmd/podman/image.go index b5c1c3ccf..66c141686 100644 --- a/cmd/podman/image.go +++ b/cmd/podman/image.go @@ -1,6 +1,8 @@ package main import ( + "strings" + "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/spf13/cobra" ) @@ -12,38 +14,80 @@ var ( Use: "image", Short: "Manage images", Long: imageDescription, + RunE: commandRunE(), + }, + } + imagesSubCommand cliconfig.ImagesValues + _imagesSubCommand = &cobra.Command{ + Use: strings.Replace(_imagesCommand.Use, "images", "list", 1), + Short: _imagesCommand.Short, + Long: _imagesCommand.Long, + Aliases: []string{"ls"}, + RunE: func(cmd *cobra.Command, args []string) error { + imagesSubCommand.InputArgs = args + imagesSubCommand.GlobalFlags = MainGlobalOpts + return imagesCmd(&imagesSubCommand) }, + Example: strings.Replace(_imagesCommand.Example, "podman images", "podman image list", -1), + } + + inspectSubCommand cliconfig.InspectValues + _inspectSubCommand = &cobra.Command{ + Use: strings.Replace(_inspectCommand.Use, "CONTAINER | ", "", 1), + Short: "Display the configuration of an image", + Long: `Displays the low-level information on an image identified by name or ID.`, + RunE: func(cmd *cobra.Command, args []string) error { + inspectSubCommand.InputArgs = args + inspectSubCommand.GlobalFlags = MainGlobalOpts + return inspectCmd(&inspectSubCommand) + }, + Example: `podman image inspect alpine`, + } + + rmSubCommand cliconfig.RmiValues + _rmSubCommand = &cobra.Command{ + Use: strings.Replace(_rmiCommand.Use, "rmi", "rm", 1), + Short: _rmiCommand.Short, + Long: _rmiCommand.Long, + RunE: func(cmd *cobra.Command, args []string) error { + rmSubCommand.InputArgs = args + rmSubCommand.GlobalFlags = MainGlobalOpts + return rmiCmd(&rmSubCommand) + }, + Example: strings.Replace(_rmiCommand.Example, "podman rmi", "podman image rm", -1), } - _imagesSubCommand = _imagesCommand - _rmSubCommand = _rmiCommand ) //imageSubCommands are implemented both in local and remote clients var imageSubCommands = []*cobra.Command{ _buildCommand, _historyCommand, + _imagesSubCommand, _imageExistsCommand, _importCommand, - _inspectCommand, + _inspectSubCommand, _loadCommand, _pruneImagesCommand, _pullCommand, _pushCommand, + _rmSubCommand, _saveCommand, _tagCommand, + _treeCommand, } func init() { + rmSubCommand.Command = _rmSubCommand + rmiInit(&rmSubCommand) + + imagesSubCommand.Command = _imagesSubCommand + imagesInit(&imagesSubCommand) + + inspectSubCommand.Command = _inspectSubCommand + inspectInit(&inspectSubCommand) + imageCommand.SetUsageTemplate(UsageTemplate()) imageCommand.AddCommand(imageSubCommands...) imageCommand.AddCommand(getImageSubCommands()...) - // Setup of "images" to appear as "list" - _imagesSubCommand.Use = "list" - _imagesSubCommand.Aliases = []string{"ls"} - imageCommand.AddCommand(&_imagesSubCommand) - - // Setup of "rmi" to appears as "rm" - _rmSubCommand.Use = "rm" - imageCommand.AddCommand(&_rmSubCommand) } diff --git a/cmd/podman/imagefilters/filters.go b/cmd/podman/imagefilters/filters.go index d01eb7436..2932d61c0 100644 --- a/cmd/podman/imagefilters/filters.go +++ b/cmd/podman/imagefilters/filters.go @@ -2,11 +2,14 @@ package imagefilters import ( "context" + "fmt" + "path/filepath" "strings" "time" "github.com/containers/libpod/pkg/adapter" "github.com/containers/libpod/pkg/inspect" + "github.com/sirupsen/logrus" ) // ResultFilter is a mock function for image filtering @@ -61,6 +64,27 @@ func LabelFilter(ctx context.Context, labelfilter string) ResultFilter { } } +// ReferenceFilter allows you to filter by image name +// Replacing all '/' with '|' so that filepath.Match() can work +// '|' character is not valid in image name, so this is safe +func ReferenceFilter(ctx context.Context, referenceFilter string) ResultFilter { + filter := fmt.Sprintf("*%s*", referenceFilter) + filter = strings.Replace(filter, "/", "|", -1) + return func(i *adapter.ContainerImage) bool { + for _, name := range i.Names() { + newName := strings.Replace(name, "/", "|", -1) + match, err := filepath.Match(filter, newName) + if err != nil { + logrus.Errorf("failed to match %s and %s, %q", name, referenceFilter, err) + } + if match { + return true + } + } + return false + } +} + // OutputImageFilter allows you to filter by an a specific image name func OutputImageFilter(userImage *adapter.ContainerImage) ResultFilter { return func(i *adapter.ContainerImage) bool { diff --git a/cmd/podman/images.go b/cmd/podman/images.go index e6f4d9a60..6133450be 100644 --- a/cmd/podman/images.go +++ b/cmd/podman/images.go @@ -2,14 +2,15 @@ package main import ( "context" + "fmt" "reflect" "sort" "strings" "time" "unicode" + "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/cmd/podman/imagefilters" "github.com/containers/libpod/libpod/image" "github.com/containers/libpod/pkg/adapter" @@ -85,7 +86,7 @@ func (a imagesSortedSize) Less(i, j int) bool { var ( imagesCommand cliconfig.ImagesValues - imagesDescription = "lists locally stored images." + imagesDescription = "Lists images previously pulled to the system or created on the system." _imagesCommand = cobra.Command{ Use: "images [flags] [IMAGE]", @@ -102,28 +103,33 @@ var ( } ) -func init() { - imagesCommand.Command = &_imagesCommand - imagesCommand.SetUsageTemplate(UsageTemplate()) - - flags := imagesCommand.Flags() - flags.BoolVarP(&imagesCommand.All, "all", "a", false, "Show all images (default hides intermediate images)") - flags.BoolVar(&imagesCommand.Digests, "digests", false, "Show digests") - flags.StringSliceVarP(&imagesCommand.Filter, "filter", "f", []string{}, "Filter output based on conditions provided (default [])") - flags.StringVar(&imagesCommand.Format, "format", "", "Change the output format to JSON or a Go template") - flags.BoolVarP(&imagesCommand.Noheading, "noheading", "n", false, "Do not print column headings") +func imagesInit(command *cliconfig.ImagesValues) { + command.SetHelpTemplate(HelpTemplate()) + command.SetUsageTemplate(UsageTemplate()) + + flags := command.Flags() + flags.BoolVarP(&command.All, "all", "a", false, "Show all images (default hides intermediate images)") + flags.BoolVar(&command.Digests, "digests", false, "Show digests") + flags.StringSliceVarP(&command.Filter, "filter", "f", []string{}, "Filter output based on conditions provided (default [])") + flags.StringVar(&command.Format, "format", "", "Change the output format to JSON or a Go template") + flags.BoolVarP(&command.Noheading, "noheading", "n", false, "Do not print column headings") // TODO Need to learn how to deal with second name being a string instead of a char. // This needs to be "no-trunc, notruncate" - flags.BoolVar(&imagesCommand.NoTrunc, "no-trunc", false, "Do not truncate output") - flags.BoolVarP(&imagesCommand.Quiet, "quiet", "q", false, "Display only image IDs") - flags.StringVar(&imagesCommand.Sort, "sort", "created", "Sort by created, id, repository, size, or tag") + flags.BoolVar(&command.NoTrunc, "no-trunc", false, "Do not truncate output") + flags.BoolVarP(&command.Quiet, "quiet", "q", false, "Display only image IDs") + flags.StringVar(&command.Sort, "sort", "created", "Sort by created, id, repository, size, or tag") } +func init() { + imagesCommand.Command = &_imagesCommand + imagesInit(&imagesCommand) +} + func imagesCmd(c *cliconfig.ImagesValues) error { var ( filterFuncs []imagefilters.ResultFilter - newImage *adapter.ContainerImage + image string ) runtime, err := adapter.GetRuntime(&c.PodmanCommand) @@ -132,23 +138,23 @@ func imagesCmd(c *cliconfig.ImagesValues) error { } defer runtime.Shutdown(false) if len(c.InputArgs) == 1 { - newImage, err = runtime.NewImageFromLocal(c.InputArgs[0]) - if err != nil { - return err - } + image = c.InputArgs[0] } - if len(c.InputArgs) > 1 { return errors.New("'podman images' requires at most 1 argument") } - + if len(c.Filter) > 0 && image != "" { + return errors.New("can not specify an image and a filter") + } ctx := getContext() - if len(c.Filter) > 0 || newImage != nil { - filterFuncs, err = CreateFilterFuncs(ctx, runtime, c.Filter, newImage) - if err != nil { - return err - } + if len(c.Filter) > 0 { + filterFuncs, err = CreateFilterFuncs(ctx, runtime, c.Filter, nil) + } else { + filterFuncs, err = CreateFilterFuncs(ctx, runtime, []string{fmt.Sprintf("reference=%s", image)}, nil) + } + if err != nil { + return err } opts := imagesOptions{ @@ -169,7 +175,7 @@ func imagesCmd(c *cliconfig.ImagesValues) error { var filteredImages []*adapter.ContainerImage //filter the images - if len(c.Filter) > 0 || newImage != nil { + if len(c.Filter) > 0 || len(c.InputArgs) == 1 { filteredImages = imagefilters.FilterImages(images, filterFuncs) } else { filteredImages = images @@ -371,6 +377,9 @@ func CreateFilterFuncs(ctx context.Context, r *adapter.LocalRuntime, filters []s case "label": labelFilter := strings.Join(splitFilter[1:], "=") filterFuncs = append(filterFuncs, imagefilters.LabelFilter(ctx, labelFilter)) + case "reference": + referenceFilter := strings.Join(splitFilter[1:], "=") + filterFuncs = append(filterFuncs, imagefilters.ReferenceFilter(ctx, referenceFilter)) default: return nil, errors.Errorf("invalid filter %s ", splitFilter[0]) } diff --git a/cmd/podman/images_prune.go b/cmd/podman/images_prune.go index 79dcd097c..b6f335fb3 100644 --- a/cmd/podman/images_prune.go +++ b/cmd/podman/images_prune.go @@ -11,13 +11,12 @@ import ( var ( pruneImagesCommand cliconfig.PruneImagesValues - pruneImagesDescription = ` - podman image prune + pruneImagesDescription = `Removes all unnamed images from local storage. - Removes all unnamed images from local storage -` + If an image is not being used by a container, it will be removed from the system.` _pruneImagesCommand = &cobra.Command{ Use: "prune", + Args: noSubArgs, Short: "Remove unused images", Long: pruneImagesDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -30,6 +29,7 @@ var ( func init() { pruneImagesCommand.Command = _pruneImagesCommand + pruneImagesCommand.SetHelpTemplate(HelpTemplate()) pruneImagesCommand.SetUsageTemplate(UsageTemplate()) flags := pruneImagesCommand.Flags() flags.BoolVarP(&pruneImagesCommand.All, "all", "a", false, "Remove all unused images, not just dangling ones") diff --git a/cmd/podman/import.go b/cmd/podman/import.go index ddf1bd802..f3fb7c988 100644 --- a/cmd/podman/import.go +++ b/cmd/podman/import.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/cmd/podman/shared/parse" "github.com/containers/libpod/pkg/adapter" "github.com/pkg/errors" "github.com/spf13/cobra" @@ -13,9 +14,9 @@ var ( importCommand cliconfig.ImportValues importDescription = `Create a container image from the contents of the specified tarball (.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz). - Note remote tar balls can be specified, via web address. - Optionally tag the image. You can specify the instructions using the --change option. - ` + + 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", @@ -33,6 +34,7 @@ var ( func init() { importCommand.Command = _importCommand + importCommand.SetHelpTemplate(HelpTemplate()) importCommand.SetUsageTemplate(UsageTemplate()) flags := importCommand.Flags() flags.StringSliceVarP(&importCommand.Change, "change", "c", []string{}, "Apply the following possible instructions to the created image (default []): CMD | ENTRYPOINT | ENV | EXPOSE | LABEL | STOPSIGNAL | USER | VOLUME | WORKDIR") @@ -66,7 +68,7 @@ func importCmd(c *cliconfig.ImportValues) error { return errors.Errorf("too many arguments. Usage TARBALL [REFERENCE]") } - if err := validateFileName(source); err != nil { + if err := parse.ValidateFileName(source); err != nil { return err } diff --git a/cmd/podman/info.go b/cmd/podman/info.go index a1473dac9..195267c7f 100644 --- a/cmd/podman/info.go +++ b/cmd/podman/info.go @@ -4,8 +4,8 @@ import ( "fmt" rt "runtime" + "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/libpod" "github.com/containers/libpod/pkg/adapter" "github.com/containers/libpod/version" @@ -16,11 +16,15 @@ import ( var ( infoCommand cliconfig.InfoValues - infoDescription = "Display podman system information" - _infoCommand = &cobra.Command{ + infoDescription = `Display information pertaining to the host, current storage stats, and build of podman. + + Useful for the user and when reporting issues. +` + _infoCommand = &cobra.Command{ Use: "info", + Args: noSubArgs, Long: infoDescription, - Short: `Display information pertaining to the host, current storage stats, and build of podman. Useful for the user and when reporting issues.`, + Short: "Display podman system information", RunE: func(cmd *cobra.Command, args []string) error { infoCommand.InputArgs = args infoCommand.GlobalFlags = MainGlobalOpts @@ -32,6 +36,7 @@ var ( func init() { infoCommand.Command = _infoCommand + infoCommand.SetHelpTemplate(HelpTemplate()) infoCommand.SetUsageTemplate(UsageTemplate()) flags := infoCommand.Flags() diff --git a/cmd/podman/inspect.go b/cmd/podman/inspect.go index 1c93a03e1..3d6fd07e0 100644 --- a/cmd/podman/inspect.go +++ b/cmd/podman/inspect.go @@ -5,8 +5,8 @@ import ( "encoding/json" "strings" + "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/cmd/podman/shared" "github.com/containers/libpod/pkg/adapter" cc "github.com/containers/libpod/pkg/spec" @@ -24,8 +24,10 @@ const ( var ( inspectCommand cliconfig.InspectValues - inspectDescription = "This displays the low-level information on containers and images identified by name or ID. By default, this will render all results in a JSON array. If the container and image have the same name, this will return container JSON for unspecified type." - _inspectCommand = &cobra.Command{ + inspectDescription = `This displays the low-level information on containers and images identified by name or ID. + + If given a name that matches both a container and an image, this command inspects the container. By default, this will render all results in a JSON array.` + _inspectCommand = cobra.Command{ Use: "inspect [flags] CONTAINER | IMAGE", Short: "Display the configuration of a container or image", Long: inspectDescription, @@ -40,15 +42,34 @@ var ( } ) +func inspectInit(command *cliconfig.InspectValues) { + command.SetHelpTemplate(HelpTemplate()) + command.SetUsageTemplate(UsageTemplate()) + flags := command.Flags() + flags.StringVarP(&command.Format, "format", "f", "", "Change the output format to a Go template") + + // -t flag applicable only to 'podman inspect', not 'image/container inspect' + ambiguous := strings.Contains(command.Use, "|") + if ambiguous { + flags.StringVarP(&command.TypeObject, "type", "t", inspectAll, "Return JSON for specified type, (image or container)") + } + + if strings.Contains(command.Use, "CONTAINER") { + containers_only := " (containers only)" + if !ambiguous { + containers_only = "" + command.TypeObject = inspectTypeContainer + } + flags.BoolVarP(&command.Latest, "latest", "l", false, "Act on the latest container podman is aware of"+containers_only) + flags.BoolVarP(&command.Size, "size", "s", false, "Display total file size"+containers_only) + markFlagHiddenForRemoteClient("latest", flags) + } else { + command.TypeObject = inspectTypeImage + } +} func init() { - inspectCommand.Command = _inspectCommand - inspectCommand.SetUsageTemplate(UsageTemplate()) - flags := inspectCommand.Flags() - flags.StringVarP(&inspectCommand.TypeObject, "type", "t", inspectAll, "Return JSON for specified type, (e.g image, container or task)") - flags.StringVarP(&inspectCommand.Format, "format", "f", "", "Change the output format to a Go template") - flags.BoolVarP(&inspectCommand.Latest, "latest", "l", false, "Act on the latest container podman is aware of if the type is a container") - flags.BoolVarP(&inspectCommand.Size, "size", "s", false, "Display total file size if the type is container") - markFlagHiddenForRemoteClient("latest", flags) + inspectCommand.Command = &_inspectCommand + inspectInit(&inspectCommand) } func inspectCmd(c *cliconfig.InspectValues) error { diff --git a/cmd/podman/kill.go b/cmd/podman/kill.go index 76d2516b7..2c1e13eaf 100644 --- a/cmd/podman/kill.go +++ b/cmd/podman/kill.go @@ -2,16 +2,15 @@ package main import ( "fmt" - "syscall" + "reflect" + + "github.com/containers/libpod/pkg/adapter" + "github.com/opentracing/opentracing-go" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/libpodruntime" - "github.com/containers/libpod/cmd/podman/shared" - "github.com/containers/libpod/libpod" "github.com/containers/libpod/pkg/rootless" "github.com/docker/docker/pkg/signal" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -39,6 +38,7 @@ var ( func init() { killCommand.Command = _killCommand + killCommand.SetHelpTemplate(HelpTemplate()) killCommand.SetUsageTemplate(UsageTemplate()) flags := killCommand.Flags() @@ -51,54 +51,44 @@ func init() { // killCmd kills one or more containers with a signal func killCmd(c *cliconfig.KillValues) error { - var ( - killFuncs []shared.ParallelWorkerInput - killSignal uint = uint(syscall.SIGTERM) - ) + if c.Bool("trace") { + span, _ := opentracing.StartSpanFromContext(Ctx, "killCmd") + defer span.Finish() + } + + // Check if the signalString provided by the user is valid + // Invalid signals will return err + killSignal, err := signal.ParseSignal(c.Signal) + if err != nil { + return err + } rootless.SetSkipStorageSetup(true) - runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) + runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "could not get runtime") } defer runtime.Shutdown(false) - if c.Signal != "" { - // Check if the signalString provided by the user is valid - // Invalid signals will return err - sysSignal, err := signal.ParseSignal(c.Signal) - if err != nil { - return err - } - killSignal = uint(sysSignal) - } - - containers, err := getAllOrLatestContainers(&c.PodmanCommand, runtime, libpod.ContainerStateRunning, "running") + ok, failures, err := runtime.KillContainers(getContext(), c, killSignal) if err != nil { - if len(containers) == 0 { - return err - } - fmt.Println(err.Error()) + return err } - for _, ctr := range containers { - con := ctr - f := func() error { - return con.Kill(killSignal) - } - - killFuncs = append(killFuncs, shared.ParallelWorkerInput{ - ContainerID: con.ID(), - ParallelFunc: f, - }) + for _, id := range ok { + fmt.Println(id) } - maxWorkers := shared.Parallelize("kill") - if c.GlobalIsSet("max-workers") { - maxWorkers = c.GlobalFlags.MaxWorks - } - logrus.Debugf("Setting maximum workers to %d", maxWorkers) + if len(failures) > 0 { + keys := reflect.ValueOf(failures).MapKeys() + lastKey := keys[len(keys)-1].String() + lastErr := failures[lastKey] + delete(failures, lastKey) - killErrors, errCount := shared.ParallelExecuteWorkerPool(maxWorkers, killFuncs) - return printParallelOutput(killErrors, errCount) + for _, err := range failures { + outputError(err) + } + return lastErr + } + return nil } diff --git a/cmd/podman/libpodruntime/runtime.go b/cmd/podman/libpodruntime/runtime.go index 2b96f0c20..3faea493c 100644 --- a/cmd/podman/libpodruntime/runtime.go +++ b/cmd/podman/libpodruntime/runtime.go @@ -86,6 +86,9 @@ func getRuntime(c *cliconfig.PodmanCommand, renumber bool) (*libpod.Runtime, err if c.Flags().Changed("tmpdir") { options = append(options, libpod.WithTmpDir(c.GlobalFlags.TmpDir)) } + if c.Flags().Changed("network-cmd-path") { + options = append(options, libpod.WithNetworkCmdPath(c.GlobalFlags.NetworkCmdPath)) + } if c.Flags().Changed("cgroup-manager") { options = append(options, libpod.WithCgroupManager(c.GlobalFlags.CGroupManager)) diff --git a/cmd/podman/load.go b/cmd/podman/load.go index 5a0742aba..04ff9fcca 100644 --- a/cmd/podman/load.go +++ b/cmd/podman/load.go @@ -5,20 +5,24 @@ import ( "io" "io/ioutil" "os" + "strings" "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/cmd/podman/shared/parse" "github.com/containers/libpod/pkg/adapter" "github.com/pkg/errors" "github.com/spf13/cobra" + "golang.org/x/crypto/ssh/terminal" ) var ( loadCommand cliconfig.LoadValues - loadDescription = "Loads the image from docker-archive stored on the local machine." - _loadCommand = &cobra.Command{ - Use: "load [flags] [PATH]", - Short: "Load an image from docker archive", + 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: func(cmd *cobra.Command, args []string) error { loadCommand.InputArgs = args @@ -30,9 +34,10 @@ var ( func init() { loadCommand.Command = _loadCommand + loadCommand.SetHelpTemplate(HelpTemplate()) loadCommand.SetUsageTemplate(UsageTemplate()) flags := loadCommand.Flags() - flags.StringVarP(&loadCommand.Input, "input", "i", "/dev/stdin", "Read from archive file, default is STDIN") + flags.StringVarP(&loadCommand.Input, "input", "i", "", "Read from specified archive file (default: stdin)") flags.BoolVarP(&loadCommand.Quiet, "quiet", "q", false, "Suppress the output") flags.StringVar(&loadCommand.SignaturePolicy, "signature-policy", "", "Pathname of signature policy file (not usually used)") @@ -58,46 +63,43 @@ func loadCmd(c *cliconfig.LoadValues) error { } defer runtime.Shutdown(false) - input := c.Input - if runtime.Remote && len(input) == 0 { - return errors.New("the remote client requires you to load via -i and a tarball") - } - if input == "/dev/stdin" { - fi, err := os.Stdin.Stat() - if err != nil { + if len(c.Input) > 0 { + if err := parse.ValidateFileName(c.Input); err != nil { return err } - // checking if loading from pipe - if !fi.Mode().IsRegular() { - outFile, err := ioutil.TempFile("/var/tmp", "podman") - if err != nil { - return errors.Errorf("error creating file %v", err) - } - defer os.Remove(outFile.Name()) - defer outFile.Close() - - inFile, err := os.OpenFile(input, 0, 0666) - if err != nil { - return errors.Errorf("error reading file %v", err) - } - defer inFile.Close() - - _, err = io.Copy(outFile, inFile) - if err != nil { - return errors.Errorf("error copying file %v", err) - } + } else { + if terminal.IsTerminal(int(os.Stdin.Fd())) { + return errors.Errorf("cannot read from terminal. Use command-line redirection or the --input flag.") + } + outFile, err := ioutil.TempFile("/var/tmp", "podman") + if err != nil { + return errors.Errorf("error creating file %v", err) + } + defer os.Remove(outFile.Name()) + defer outFile.Close() - input = outFile.Name() + _, err = io.Copy(outFile, os.Stdin) + if err != nil { + return errors.Errorf("error copying file %v", err) } - } - if err := validateFileName(input); err != nil { - return err + + c.Input = outFile.Name() } names, err := runtime.LoadImage(getContext(), imageName, c) if err != nil { return err } + if len(imageName) > 0 { + split := strings.Split(names, ",") + newImage, err := runtime.NewImageFromLocal(split[0]) + if err != nil { + return err + } + if err := newImage.TagImage(imageName); err != nil { + return errors.Wrapf(err, "error adding '%s' to image %q", imageName, newImage.InputName) + } + } fmt.Println("Loaded image(s): " + names) return nil } diff --git a/cmd/podman/login.go b/cmd/podman/login.go index 48d4eefbc..4e96b43cb 100644 --- a/cmd/podman/login.go +++ b/cmd/podman/login.go @@ -37,6 +37,7 @@ var ( func init() { loginCommand.Command = _loginCommand + loginCommand.SetHelpTemplate(HelpTemplate()) loginCommand.SetUsageTemplate(UsageTemplate()) flags := loginCommand.Flags() @@ -44,7 +45,7 @@ func init() { flags.StringVar(&loginCommand.CertDir, "cert-dir", "", "Pathname of a directory containing TLS certificates and keys used to connect to the registry") flags.BoolVar(&loginCommand.GetLogin, "get-login", true, "Return the current login user for the registry") flags.StringVarP(&loginCommand.Password, "password", "p", "", "Password for registry") - flags.BoolVar(&loginCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries (default: true)") + flags.BoolVar(&loginCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries") flags.StringVarP(&loginCommand.Username, "username", "u", "", "Username for registry") flags.BoolVar(&loginCommand.StdinPassword, "password-stdin", false, "Take the password from stdin") diff --git a/cmd/podman/logout.go b/cmd/podman/logout.go index 2a540ceba..268e6b44c 100644 --- a/cmd/podman/logout.go +++ b/cmd/podman/logout.go @@ -30,6 +30,7 @@ var ( func init() { logoutCommand.Command = _logoutCommand + logoutCommand.SetHelpTemplate(HelpTemplate()) logoutCommand.SetUsageTemplate(UsageTemplate()) flags := logoutCommand.Flags() flags.BoolVarP(&logoutCommand.All, "all", "a", false, "Remove the cached credentials for all registries in the auth file") diff --git a/cmd/podman/logs.go b/cmd/podman/logs.go index a02010eda..a1b5fb4cc 100644 --- a/cmd/podman/logs.go +++ b/cmd/podman/logs.go @@ -1,24 +1,24 @@ package main import ( - "os" "time" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/libpod/libpod" - "github.com/containers/libpod/pkg/logs" + "github.com/containers/libpod/pkg/adapter" + "github.com/containers/libpod/pkg/util" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) var ( logsCommand cliconfig.LogsValues - logsDescription = "The podman logs command batch-retrieves whatever logs are present for a container at the time of execution. 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" + logsDescription = `Retrieves logs for one or more containers. + + 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", + Use: "logs [flags] CONTAINER [CONTAINER...]", Short: "Fetch the logs of a container", Long: logsDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -26,14 +26,25 @@ var ( logsCommand.GlobalFlags = MainGlobalOpts return logsCmd(&logsCommand) }, + Args: func(cmd *cobra.Command, args []string) error { + if len(args) > 0 && logsCommand.Latest { + return errors.New("no containers can be specified when using 'latest'") + } + if !logsCommand.Latest && len(args) < 1 { + return errors.New("specify at least one container name or ID to log") + } + return nil + }, Example: `podman logs ctrID podman logs --tail 2 mywebserver - podman logs --follow=true --since 10m ctrID`, + podman logs --follow=true --since 10m ctrID + podman logs mywebserver mydbserver`, } ) func init() { logsCommand.Command = _logsCommand + logsCommand.SetHelpTemplate(HelpTemplate()) logsCommand.SetUsageTemplate(UsageTemplate()) flags := logsCommand.Flags() flags.BoolVar(&logsCommand.Details, "details", false, "Show extra details provided to the logs") @@ -50,31 +61,25 @@ func init() { } func logsCmd(c *cliconfig.LogsValues) error { - var ctr *libpod.Container var err error - runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) + runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "could not get runtime") } defer runtime.Shutdown(false) - args := c.InputArgs - if len(args) != 1 && !c.Latest { - return errors.Errorf("'podman logs' requires exactly one container name/ID") - } - sinceTime := time.Time{} if c.Flag("since").Changed { // parse time, error out if something is wrong - since, err := parseInputTime(c.Since) + since, err := util.ParseInputTime(c.Since) if err != nil { return errors.Wrapf(err, "could not parse time: %q", c.Since) } sinceTime = since } - opts := &logs.LogOptions{ + opts := &libpod.LogOptions{ Details: c.Details, Follow: c.Follow, Since: sinceTime, @@ -82,52 +87,5 @@ func logsCmd(c *cliconfig.LogsValues) error { Timestamps: c.Timestamps, } - if c.Latest { - ctr, err = runtime.GetLatestContainer() - } else { - ctr, err = runtime.LookupContainer(args[0]) - } - if err != nil { - return err - } - - logPath := ctr.LogPath() - - state, err := ctr.State() - if err != nil { - return err - } - - // If the log file does not exist yet and the container is in the - // Configured state, it has never been started before and no logs exist - // Exit cleanly in this case - if _, err := os.Stat(logPath); err != nil { - if state == libpod.ContainerStateConfigured { - logrus.Debugf("Container has not been started, no logs exist yet") - return nil - } - } - return logs.ReadLogs(logPath, ctr, opts) -} - -// parseInputTime takes the users input and to determine if it is valid and -// returns a time format and error. The input is compared to known time formats -// or a duration which implies no-duration -func parseInputTime(inputTime string) (time.Time, error) { - timeFormats := []string{time.RFC3339Nano, time.RFC3339, "2006-01-02T15:04:05", "2006-01-02T15:04:05.999999999", - "2006-01-02Z07:00", "2006-01-02"} - // iterate the supported time formats - for _, tf := range timeFormats { - t, err := time.Parse(tf, inputTime) - if err == nil { - return t, nil - } - } - - // input might be a duration - duration, err := time.ParseDuration(inputTime) - if err != nil { - return time.Time{}, errors.Errorf("unable to interpret time value") - } - return time.Now().Add(-duration), nil + return runtime.Log(c, opts) } diff --git a/cmd/podman/main.go b/cmd/podman/main.go index 98e2f23ca..dd8b61408 100644 --- a/cmd/podman/main.go +++ b/cmd/podman/main.go @@ -36,21 +36,25 @@ var ( // implemented. var mainCommands = []*cobra.Command{ _buildCommand, + _eventsCommand, _exportCommand, _historyCommand, &_imagesCommand, _importCommand, _infoCommand, - _inspectCommand, + &_inspectCommand, _killCommand, _loadCommand, + _logsCommand, podCommand.Command, _pullCommand, _pushCommand, &_rmiCommand, _saveCommand, + _stopCommand, _tagCommand, _versionCommand, + _waitCommand, imageCommand.Command, systemCommand.Command, } @@ -63,26 +67,32 @@ var cmdsNotRequiringRootless = map[*cobra.Command]bool{ _exportCommand: true, //// `info` must be executed in an user namespace. //// If this change, please also update libpod.refreshRootless() - _loginCommand: true, - _logoutCommand: true, - _mountCommand: true, - _killCommand: true, - _pauseCommand: true, - _restartCommand: true, - _runCommand: true, - _unpauseCommand: true, - _searchCommand: true, - _statsCommand: true, - _stopCommand: true, - _topCommand: true, + _loginCommand: true, + _logoutCommand: true, + _mountCommand: true, + _killCommand: true, + _pauseCommand: true, + _podRmCommand: true, + _podKillCommand: true, + _podRestartCommand: true, + _podStatsCommand: true, + _podStopCommand: true, + _podTopCommand: true, + _restartCommand: true, + &_psCommand: true, + _rmCommand: true, + _runCommand: true, + _unpauseCommand: true, + _searchCommand: true, + _statsCommand: true, + _stopCommand: true, + _topCommand: true, } var rootCmd = &cobra.Command{ Use: "podman", Long: "manage pods and images", - RunE: func(cmd *cobra.Command, args []string) error { - return cmd.Help() - }, + RunE: commandRunE(), PersistentPreRunE: func(cmd *cobra.Command, args []string) error { return before(cmd, args) }, @@ -104,11 +114,12 @@ func init() { rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.CpuProfile, "cpu-profile", "", "Path for the cpu profiling results") rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.Config, "config", "", "Path of a libpod config file detailing container server configuration options") rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.ConmonPath, "conmon", "", "Path of the conmon binary") + rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.NetworkCmdPath, "network-cmd-path", "", "Path to the command for configuring the network") rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.CniConfigDir, "cni-config-dir", "", "Path of the configuration directory for CNI networks") rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.DefaultMountsFile, "default-mounts-file", "", "Path to default mounts file") rootCmd.PersistentFlags().MarkHidden("defaults-mount-file") rootCmd.PersistentFlags().StringSliceVar(&MainGlobalOpts.HooksDir, "hooks-dir", []string{}, "Set the OCI hooks directory path (may be set multiple times)") - rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.LogLevel, "log-level", "error", "Log messages above specified level: debug, info, warn, error (default), fatal or panic") + rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.LogLevel, "log-level", "error", "Log messages above specified level: debug, info, warn, error, fatal or panic") rootCmd.PersistentFlags().IntVar(&MainGlobalOpts.MaxWorks, "max-workers", 0, "The maximum number of workers for parallel operations") rootCmd.PersistentFlags().MarkHidden("max-workers") rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.Namespace, "namespace", "", "Set the libpod namespace, used to create separate views of the containers and pods on the system") diff --git a/cmd/podman/mount.go b/cmd/podman/mount.go index 3a3432194..d074551ce 100644 --- a/cmd/podman/mount.go +++ b/cmd/podman/mount.go @@ -5,8 +5,8 @@ import ( "fmt" "os" + of "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - of "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/libpod/pkg/rootless" "github.com/pkg/errors" @@ -17,16 +17,15 @@ import ( var ( mountCommand cliconfig.MountValues - mountDescription = ` - podman mount - Lists all mounted containers mount points + mountDescription = `podman mount + Lists all mounted containers mount points if no container is specified - podman mount CONTAINER-NAME-OR-ID - Mounts the specified container and outputs the mountpoint + podman mount CONTAINER-NAME-OR-ID + Mounts the specified container and outputs the mountpoint ` _mountCommand = &cobra.Command{ - Use: "mount [flags] CONTAINER", + Use: "mount [flags] [CONTAINER]", Short: "Mount a working container's root filesystem", Long: mountDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -42,6 +41,7 @@ var ( func init() { mountCommand.Command = _mountCommand + mountCommand.SetHelpTemplate(HelpTemplate()) mountCommand.SetUsageTemplate(UsageTemplate()) flags := mountCommand.Flags() flags.BoolVarP(&mountCommand.All, "all", "a", false, "Mount all containers") diff --git a/cmd/podman/pause.go b/cmd/podman/pause.go index 3a5b80359..fa4648128 100644 --- a/cmd/podman/pause.go +++ b/cmd/podman/pause.go @@ -14,12 +14,8 @@ import ( var ( pauseCommand cliconfig.PauseValues - pauseDescription = ` - podman pause - - Pauses one or more running containers. The container name or ID can be used. -` - _pauseCommand = &cobra.Command{ + 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, @@ -36,6 +32,7 @@ var ( func init() { pauseCommand.Command = _pauseCommand + pauseCommand.SetHelpTemplate(HelpTemplate()) pauseCommand.SetUsageTemplate(UsageTemplate()) flags := pauseCommand.Flags() flags.BoolVarP(&pauseCommand.All, "all", "a", false, "Pause all running containers") diff --git a/cmd/podman/play.go b/cmd/podman/play.go index 495a1f170..95eae653e 100644 --- a/cmd/podman/play.go +++ b/cmd/podman/play.go @@ -12,11 +12,13 @@ var ( Use: "play", Short: "Play a pod", Long: playDescription, + RunE: commandRunE(), } ) func init() { playCommand.Command = _playCommand + playCommand.SetHelpTemplate(HelpTemplate()) playCommand.SetUsageTemplate(UsageTemplate()) playCommand.AddCommand(getPlaySubCommands()...) } diff --git a/cmd/podman/play_kube.go b/cmd/podman/play_kube.go index 6f23e340e..10221a339 100644 --- a/cmd/podman/play_kube.go +++ b/cmd/podman/play_kube.go @@ -1,6 +1,7 @@ package main import ( + "context" "fmt" "io" "io/ioutil" @@ -25,10 +26,17 @@ import ( "k8s.io/api/core/v1" ) +const ( + // https://kubernetes.io/docs/concepts/storage/volumes/#hostpath + createDirectoryPermission = 0755 +) + var ( playKubeCommand cliconfig.KubePlayValues - playKubeDescription = "Play a Pod and its containers based on a Kubrernetes YAML" - _playKubeCommand = &cobra.Command{ + playKubeDescription = `Command reads in a structured file of Kubernetes YAML. + + It creates the pod and containers described in the YAML. The containers within the pod are then started and the ID of the new Pod is output.` + _playKubeCommand = &cobra.Command{ Use: "kube [flags] KUBEFILE", Short: "Play a pod based on Kubernetes YAML", Long: playKubeDescription, @@ -44,6 +52,7 @@ var ( func init() { playKubeCommand.Command = _playKubeCommand + playKubeCommand.SetHelpTemplate(HelpTemplate()) playKubeCommand.SetUsageTemplate(UsageTemplate()) flags := playKubeCommand.Flags() flags.StringVar(&playKubeCommand.Authfile, "authfile", "", "Path of the authentication file. Default is ${XDG_RUNTIME_DIR}/containers/auth.json. Use REGISTRY_AUTH_FILE environment variable to override") @@ -51,7 +60,7 @@ func init() { flags.StringVar(&playKubeCommand.Creds, "creds", "", "`Credentials` (USERNAME:PASSWORD) to use for authenticating to a registry") flags.BoolVarP(&playKubeCommand.Quiet, "quiet", "q", false, "Suppress output information when pulling images") flags.StringVar(&playKubeCommand.SignaturePolicy, "signature-policy", "", "`Pathname` of signature policy file (not usually used)") - flags.BoolVar(&playKubeCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries (default: true)") + flags.BoolVar(&playKubeCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries") } func playKubeYAMLCmd(c *cliconfig.KubePlayValues) error { @@ -90,11 +99,20 @@ func playKubeYAMLCmd(c *cliconfig.KubePlayValues) error { return errors.Wrapf(err, "unable to read %s as YAML", args[0]) } + // check for name collision between pod and container + podName := podYAML.ObjectMeta.Name + for _, n := range podYAML.Spec.Containers { + if n.Name == podName { + fmt.Printf("a container exists with the same name (%s) as the pod in your YAML file; changing pod name to %s_pod\n", podName, podName) + podName = fmt.Sprintf("%s_pod", podName) + } + } + podOptions = append(podOptions, libpod.WithInfraContainer()) - podOptions = append(podOptions, libpod.WithPodName(podYAML.ObjectMeta.Name)) + podOptions = append(podOptions, libpod.WithPodName(podName)) // TODO for now we just used the default kernel namespaces; we need to add/subtract this from yaml - nsOptions, err := shared.GetNamespaceOptions(strings.Split(DefaultKernelNamespaces, ",")) + nsOptions, err := shared.GetNamespaceOptions(strings.Split(shared.DefaultKernelNamespaces, ",")) if err != nil { return err } @@ -135,16 +153,45 @@ func playKubeYAMLCmd(c *cliconfig.KubePlayValues) error { dockerRegistryOptions.DockerInsecureSkipTLSVerify = types.NewOptionalBool(!c.TlsVerify) } + // map from name to mount point + volumes := make(map[string]string) + for _, volume := range podYAML.Spec.Volumes { + hostPath := volume.VolumeSource.HostPath + if hostPath == nil { + return errors.Errorf("HostPath is currently the only supported VolumeSource") + } + if hostPath.Type != nil { + switch *hostPath.Type { + case v1.HostPathDirectoryOrCreate: + if _, err := os.Stat(hostPath.Path); os.IsNotExist(err) { + if err := os.Mkdir(hostPath.Path, createDirectoryPermission); err != nil { + return errors.Errorf("Error creating HostPath %s at %s", volume.Name, hostPath.Path) + } + } + case v1.HostPathDirectory: + // do nothing here because we will verify the path exists in validateVolumeHostDir + break + default: + return errors.Errorf("Directories are the only supported HostPath type") + } + } + if err := shared.ValidateVolumeHostDir(hostPath.Path); err != nil { + return errors.Wrapf(err, "Error in parsing HostPath in YAML") + } + fmt.Println(volume.Name) + volumes[volume.Name] = hostPath.Path + } + for _, container := range podYAML.Spec.Containers { newImage, err := runtime.ImageRuntime().New(ctx, container.Image, c.SignaturePolicy, c.Authfile, writer, &dockerRegistryOptions, image2.SigningOptions{}, false, nil) if err != nil { return err } - createConfig := kubeContainerToCreateConfig(container, runtime, newImage, namespaces) + createConfig, err := kubeContainerToCreateConfig(ctx, container, runtime, newImage, namespaces, volumes) if err != nil { return err } - ctr, err := createContainerFromCreateConfig(runtime, createConfig, ctx, pod) + ctr, err := shared.CreateContainerFromCreateConfig(runtime, createConfig, ctx, pod) if err != nil { return err } @@ -185,7 +232,7 @@ func getPodPorts(containers []v1.Container) []ocicni.PortMapping { } // kubeContainerToCreateConfig takes a v1.Container and returns a createconfig describing a container -func kubeContainerToCreateConfig(containerYAML v1.Container, runtime *libpod.Runtime, newImage *image2.Image, namespaces map[string]string) *createconfig.CreateConfig { +func kubeContainerToCreateConfig(ctx context.Context, containerYAML v1.Container, runtime *libpod.Runtime, newImage *image2.Image, namespaces map[string]string, volumes map[string]string) (*createconfig.CreateConfig, error) { var ( containerConfig createconfig.CreateConfig envs map[string]string @@ -197,15 +244,25 @@ func kubeContainerToCreateConfig(containerYAML v1.Container, runtime *libpod.Run containerConfig.Name = containerYAML.Name containerConfig.Tty = containerYAML.TTY containerConfig.WorkDir = containerYAML.WorkingDir - if containerYAML.SecurityContext.ReadOnlyRootFilesystem != nil { - containerConfig.ReadOnlyRootfs = *containerYAML.SecurityContext.ReadOnlyRootFilesystem - } - if containerYAML.SecurityContext.Privileged != nil { - containerConfig.Privileged = *containerYAML.SecurityContext.Privileged + + imageData, _ := newImage.Inspect(ctx) + + containerConfig.User = "0" + if imageData != nil { + containerConfig.User = imageData.Config.User } - if containerYAML.SecurityContext.AllowPrivilegeEscalation != nil { - containerConfig.NoNewPrivs = !*containerYAML.SecurityContext.AllowPrivilegeEscalation + if containerConfig.SecurityOpts != nil { + if containerYAML.SecurityContext.ReadOnlyRootFilesystem != nil { + containerConfig.ReadOnlyRootfs = *containerYAML.SecurityContext.ReadOnlyRootFilesystem + } + if containerYAML.SecurityContext.Privileged != nil { + containerConfig.Privileged = *containerYAML.SecurityContext.Privileged + } + + if containerYAML.SecurityContext.AllowPrivilegeEscalation != nil { + containerConfig.NoNewPrivs = !*containerYAML.SecurityContext.AllowPrivilegeEscalation + } } containerConfig.Command = containerYAML.Command @@ -222,7 +279,9 @@ func kubeContainerToCreateConfig(containerYAML v1.Container, runtime *libpod.Run // disabled in code review per mheon //containerConfig.PidMode = ns.PidMode(namespaces["pid"]) containerConfig.UsernsMode = ns.UsernsMode(namespaces["user"]) - + if len(containerConfig.WorkDir) == 0 { + containerConfig.WorkDir = "/" + } if len(containerYAML.Env) > 0 { envs = make(map[string]string) } @@ -231,5 +290,16 @@ func kubeContainerToCreateConfig(containerYAML v1.Container, runtime *libpod.Run envs[e.Name] = e.Value } containerConfig.Env = envs - return &containerConfig + + for _, volume := range containerYAML.VolumeMounts { + host_path, exists := volumes[volume.Name] + if !exists { + return nil, errors.Errorf("Volume mount %s specified for container but not configured in volumes", volume.Name) + } + if err := shared.ValidateVolumeCtrDir(volume.MountPath); err != nil { + return nil, errors.Wrapf(err, "error in parsing MountPath") + } + containerConfig.Volumes = append(containerConfig.Volumes, fmt.Sprintf("%s:%s", host_path, volume.MountPath)) + } + return &containerConfig, nil } diff --git a/cmd/podman/pod.go b/cmd/podman/pod.go index c1350bd4d..9a9c7a702 100644 --- a/cmd/podman/pod.go +++ b/cmd/podman/pod.go @@ -1,20 +1,24 @@ package main import ( + "os" + "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/pkg/adapter" + "github.com/containers/libpod/pkg/rootless" + "github.com/pkg/errors" "github.com/spf13/cobra" ) var ( - podDescription = `Manage container pods. - -Pods are a group of one or more containers sharing the same network, pid and ipc namespaces.` + podDescription = `Pods are a group of one or more containers sharing the same network, pid and ipc namespaces.` ) var podCommand = cliconfig.PodmanCommand{ Command: &cobra.Command{ Use: "pod", Short: "Manage pods", Long: podDescription, + RunE: commandRunE(), }, } @@ -29,12 +33,56 @@ var podSubCommands = []*cobra.Command{ _podRestartCommand, _podRmCommand, _podStartCommand, + _podStatsCommand, _podStopCommand, + _podTopCommand, _podUnpauseCommand, } +func joinPodNS(runtime *adapter.LocalRuntime, all, latest bool, inputArgs []string) ([]string, bool, bool, error) { + if rootless.IsRootless() { + if os.Geteuid() == 0 { + return []string{rootless.Argument()}, false, false, nil + } else { + var err error + var pods []*adapter.Pod + if all { + pods, err = runtime.GetAllPods() + if err != nil { + return nil, false, false, errors.Wrapf(err, "unable to get pods") + } + } else if latest { + pod, err := runtime.GetLatestPod() + if err != nil { + return nil, false, false, errors.Wrapf(err, "unable to get latest pod") + } + pods = append(pods, pod) + } else { + for _, i := range inputArgs { + pod, err := runtime.LookupPod(i) + if err != nil { + return nil, false, false, errors.Wrapf(err, "unable to lookup pod %s", i) + } + pods = append(pods, pod) + } + } + for _, p := range pods { + _, ret, err := runtime.JoinOrCreateRootlessPod(p) + if err != nil { + return nil, false, false, err + } + if ret != 0 { + os.Exit(ret) + } + } + os.Exit(0) + } + } + return inputArgs, all, latest, nil +} + func init() { podCommand.AddCommand(podSubCommands...) - podCommand.AddCommand(getPodSubCommands()...) + podCommand.SetHelpTemplate(HelpTemplate()) podCommand.SetUsageTemplate(UsageTemplate()) } diff --git a/cmd/podman/pod_create.go b/cmd/podman/pod_create.go index f1bbecb84..2f7a6b415 100644 --- a/cmd/podman/pod_create.go +++ b/cmd/podman/pod_create.go @@ -5,6 +5,7 @@ import ( "os" "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/cmd/podman/shared" "github.com/containers/libpod/libpod" "github.com/containers/libpod/pkg/adapter" "github.com/pkg/errors" @@ -14,16 +15,16 @@ import ( var ( // Kernel namespaces shared by default within a pod - DefaultKernelNamespaces = "cgroup,ipc,net,uts" - podCreateCommand cliconfig.PodCreateValues - podCreateDescription = "Creates a new empty pod. The pod ID is then" + - " printed to stdout. You can then start it at any time with the" + - " podman pod start <pod_id> command. The pod will be created with the" + - " initial state 'created'." + podCreateCommand cliconfig.PodCreateValues + + podCreateDescription = `After creating the pod, the pod ID is printed to stdout. + + You can then start it at any time with the podman pod start <pod_id> command. The pod will be created with the initial state 'created'.` _podCreateCommand = &cobra.Command{ Use: "create", + Args: noSubArgs, Short: "Create a new empty pod", Long: podCreateDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -36,6 +37,7 @@ var ( func init() { podCreateCommand.Command = _podCreateCommand + podCreateCommand.SetHelpTemplate(HelpTemplate()) podCreateCommand.SetUsageTemplate(UsageTemplate()) flags := podCreateCommand.Flags() flags.SetInterspersed(false) @@ -49,7 +51,7 @@ func init() { flags.StringVarP(&podCreateCommand.Name, "name", "n", "", "Assign a name to the pod") flags.StringVar(&podCreateCommand.PodIDFile, "pod-id-file", "", "Write the pod ID to the file") flags.StringSliceVarP(&podCreateCommand.Publish, "publish", "p", []string{}, "Publish a container's port, or a range of ports, to the host (default [])") - flags.StringVar(&podCreateCommand.Share, "share", DefaultKernelNamespaces, "A comma delimited list of kernel namespaces the pod will share") + flags.StringVar(&podCreateCommand.Share, "share", shared.DefaultKernelNamespaces, "A comma delimited list of kernel namespaces the pod will share") } @@ -59,9 +61,6 @@ func podCreateCmd(c *cliconfig.PodCreateValues) error { podIdFile *os.File ) - if len(c.InputArgs) > 0 { - return errors.New("podman pod create does not accept any arguments") - } runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "error creating libpod runtime") @@ -89,7 +88,7 @@ func podCreateCmd(c *cliconfig.PodCreateValues) error { defer podIdFile.Sync() } - labels, err := getAllLabels(c.LabelFile, c.Labels) + labels, err := shared.GetAllLabels(c.LabelFile, c.Labels) if err != nil { return errors.Wrapf(err, "unable to process labels") } diff --git a/cmd/podman/pod_inspect.go b/cmd/podman/pod_inspect.go index 8b2747af0..851f39aa0 100644 --- a/cmd/podman/pod_inspect.go +++ b/cmd/podman/pod_inspect.go @@ -12,8 +12,11 @@ import ( var ( podInspectCommand cliconfig.PodInspectValues - podInspectDescription = "Display the configuration for a pod by name or id" - _podInspectCommand = &cobra.Command{ + podInspectDescription = `Display the configuration for a pod by name or id + + By default, this will render all results in a JSON array.` + + _podInspectCommand = &cobra.Command{ Use: "inspect [flags] POD", Short: "Displays a pod configuration", Long: podInspectDescription, @@ -28,9 +31,10 @@ var ( func init() { podInspectCommand.Command = _podInspectCommand + podInspectCommand.SetHelpTemplate(HelpTemplate()) podInspectCommand.SetUsageTemplate(UsageTemplate()) flags := podInspectCommand.Flags() - flags.BoolVarP(&podInspectCommand.Latest, "latest", "l", false, "Act on the latest container podman is aware of") + flags.BoolVarP(&podInspectCommand.Latest, "latest", "l", false, "Act on the latest pod podman is aware of") markFlagHiddenForRemoteClient("latest", flags) } @@ -40,6 +44,11 @@ func podInspectCmd(c *cliconfig.PodInspectValues) error { pod *adapter.Pod ) args := c.InputArgs + + if len(args) < 1 && !c.Latest { + return errors.Errorf("you must provide the name or id of a pod") + } + runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "could not get runtime") diff --git a/cmd/podman/pod_kill.go b/cmd/podman/pod_kill.go index 70d86d186..c538674a4 100644 --- a/cmd/podman/pod_kill.go +++ b/cmd/podman/pod_kill.go @@ -6,6 +6,7 @@ import ( "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/pkg/adapter" + "github.com/containers/libpod/pkg/rootless" "github.com/docker/docker/pkg/signal" "github.com/pkg/errors" "github.com/sirupsen/logrus" @@ -14,8 +15,10 @@ import ( var ( podKillCommand cliconfig.PodKillValues - podKillDescription = "The main process of each container inside the specified pod will be sent SIGKILL, or any signal specified with option --signal." - _podKillCommand = &cobra.Command{ + podKillDescription = `Signals are sent to the main process of each container inside the specified pod. + + The default signal is SIGKILL, or any signal specified with option --signal.` + _podKillCommand = &cobra.Command{ Use: "kill [flags] POD [POD...]", Short: "Send the specified signal or SIGKILL to containers in pod", Long: podKillDescription, @@ -35,6 +38,7 @@ var ( func init() { podKillCommand.Command = _podKillCommand + podKillCommand.SetHelpTemplate(HelpTemplate()) podKillCommand.SetUsageTemplate(UsageTemplate()) flags := podKillCommand.Flags() flags.BoolVarP(&podKillCommand.All, "all", "a", false, "Kill all containers in all pods") @@ -45,6 +49,7 @@ func init() { // podKillCmd kills one or more pods with a signal func podKillCmd(c *cliconfig.PodKillValues) error { + rootless.SetSkipStorageSetup(true) runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "could not get runtime") diff --git a/cmd/podman/pod_pause.go b/cmd/podman/pod_pause.go index f7c90dbbe..ff29e0e1d 100644 --- a/cmd/podman/pod_pause.go +++ b/cmd/podman/pod_pause.go @@ -11,8 +11,10 @@ import ( var ( podPauseCommand cliconfig.PodPauseValues - podPauseDescription = `Pauses one or more pods. The pod name or ID can be used.` - _podPauseCommand = &cobra.Command{ + podPauseDescription = `The pod name or ID can be used. + + All running containers within each specified pod will then be paused.` + _podPauseCommand = &cobra.Command{ Use: "pause [flags] POD [POD...]", Short: "Pause one or more pods", Long: podPauseDescription, @@ -32,6 +34,7 @@ var ( func init() { podPauseCommand.Command = _podPauseCommand + podPauseCommand.SetHelpTemplate(HelpTemplate()) podPauseCommand.SetUsageTemplate(UsageTemplate()) flags := podPauseCommand.Flags() flags.BoolVarP(&podPauseCommand.All, "all", "a", false, "Pause all running pods") diff --git a/cmd/podman/pod_ps.go b/cmd/podman/pod_ps.go index 70e077651..a956882cf 100644 --- a/cmd/podman/pod_ps.go +++ b/cmd/podman/pod_ps.go @@ -8,8 +8,8 @@ import ( "strings" "time" + "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/cmd/podman/shared" "github.com/containers/libpod/libpod" "github.com/containers/libpod/pkg/adapter" @@ -121,6 +121,7 @@ var ( _podPsCommand = &cobra.Command{ Use: "ps", Aliases: []string{"ls", "list"}, + Args: noSubArgs, Short: "List pods", Long: podPsDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -133,6 +134,7 @@ var ( func init() { podPsCommand.Command = _podPsCommand + podPsCommand.SetHelpTemplate(HelpTemplate()) podPsCommand.SetUsageTemplate(UsageTemplate()) flags := podPsCommand.Flags() flags.BoolVar(&podPsCommand.CtrNames, "ctr-names", false, "Display the container names") @@ -160,10 +162,6 @@ func podPsCmd(c *cliconfig.PodPsValues) error { } defer runtime.Shutdown(false) - if len(c.InputArgs) > 0 { - return errors.Errorf("too many arguments, ps takes no arguments") - } - opts := podPsOptions{ NoTrunc: c.NoTrunc, Quiet: c.Quiet, diff --git a/cmd/podman/pod_restart.go b/cmd/podman/pod_restart.go index ba77e1409..9c8d28424 100644 --- a/cmd/podman/pod_restart.go +++ b/cmd/podman/pod_restart.go @@ -2,9 +2,11 @@ package main import ( "fmt" + "os" "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/pkg/adapter" + "github.com/containers/libpod/pkg/rootless" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" @@ -12,8 +14,10 @@ import ( var ( podRestartCommand cliconfig.PodRestartValues - podRestartDescription = `Restarts one or more pods. The pod ID or name can be used.` - _podRestartCommand = &cobra.Command{ + podRestartDescription = `The pod ID or name can be used. + + All of the containers within each of the specified pods will be restarted. If a container in a pod is not currently running it will be started.` + _podRestartCommand = &cobra.Command{ Use: "restart [flags] POD [POD...]", Short: "Restart one or more pods", Long: podRestartDescription, @@ -33,6 +37,7 @@ var ( func init() { podRestartCommand.Command = _podRestartCommand + podRestartCommand.SetHelpTemplate(HelpTemplate()) podRestartCommand.SetUsageTemplate(UsageTemplate()) flags := podRestartCommand.Flags() flags.BoolVarP(&podRestartCommand.All, "all", "a", false, "Restart all running pods") @@ -43,12 +48,24 @@ func init() { func podRestartCmd(c *cliconfig.PodRestartValues) error { var lastError error + if os.Geteuid() != 0 { + rootless.SetSkipStorageSetup(true) + } runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "could not get runtime") } defer runtime.Shutdown(false) + if rootless.IsRootless() { + var err error + + c.InputArgs, c.All, c.Latest, err = joinPodNS(runtime, c.All, c.Latest, c.InputArgs) + if err != nil { + return err + } + } + restartIDs, conErrors, restartErrors := runtime.RestartPods(getContext(), c) for _, p := range restartIDs { diff --git a/cmd/podman/pod_rm.go b/cmd/podman/pod_rm.go index fa452b061..735676f8a 100644 --- a/cmd/podman/pod_rm.go +++ b/cmd/podman/pod_rm.go @@ -2,9 +2,11 @@ package main import ( "fmt" + "os" "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/pkg/adapter" + "github.com/containers/libpod/pkg/rootless" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" @@ -12,11 +14,9 @@ import ( var ( podRmCommand cliconfig.PodRmValues - podRmDescription = fmt.Sprintf(` -podman rm will remove one or more pods from the host. The pod name or ID can -be used. A pod with containers will not be removed without --force. -If --force is specified, all containers will be stopped, then removed. -`) + podRmDescription = fmt.Sprintf(`podman rm will remove one or more pods from the host. + + The pod name or ID can be used. A pod with containers will not be removed without --force. If --force is specified, all containers will be stopped, then removed.`) _podRmCommand = &cobra.Command{ Use: "rm [flags] POD [POD...]", Short: "Remove one or more pods", @@ -37,6 +37,7 @@ If --force is specified, all containers will be stopped, then removed. func init() { podRmCommand.Command = _podRmCommand + podRmCommand.SetHelpTemplate(HelpTemplate()) podRmCommand.SetUsageTemplate(UsageTemplate()) flags := podRmCommand.Flags() flags.BoolVarP(&podRmCommand.All, "all", "a", false, "Remove all running pods") @@ -47,11 +48,23 @@ func init() { // podRmCmd deletes pods func podRmCmd(c *cliconfig.PodRmValues) error { + if os.Geteuid() != 0 { + rootless.SetSkipStorageSetup(true) + } runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "could not get runtime") } defer runtime.Shutdown(false) + + if rootless.IsRootless() { + var err error + c.InputArgs, c.All, c.Latest, err = joinPodNS(runtime, c.All, c.Latest, c.InputArgs) + if err != nil { + return err + } + } + podRmIds, podRmErrors := runtime.RemovePods(getContext(), c) for _, p := range podRmIds { fmt.Println(p) diff --git a/cmd/podman/pod_start.go b/cmd/podman/pod_start.go index eef9d2a71..949af80d8 100644 --- a/cmd/podman/pod_start.go +++ b/cmd/podman/pod_start.go @@ -12,13 +12,11 @@ import ( var ( podStartCommand cliconfig.PodStartValues - podStartDescription = ` - podman pod start + podStartDescription = `The pod name or ID can be used. - Starts one or more pods. The pod name or ID can be used. -` + All containers defined in the pod will be started.` _podStartCommand = &cobra.Command{ - Use: "start POD [POD...]", + Use: "start [flags] POD [POD...]", Short: "Start one or more pods", Long: podStartDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -37,6 +35,7 @@ var ( func init() { podStartCommand.Command = _podStartCommand + podStartCommand.SetHelpTemplate(HelpTemplate()) podStartCommand.SetUsageTemplate(UsageTemplate()) flags := podStartCommand.Flags() flags.BoolVarP(&podStartCommand.All, "all", "a", false, "Start all pods") diff --git a/cmd/podman/pod_stats.go b/cmd/podman/pod_stats.go index f5edd21f8..e8ff322ce 100644 --- a/cmd/podman/pod_stats.go +++ b/cmd/podman/pod_stats.go @@ -11,10 +11,10 @@ import ( "encoding/json" tm "github.com/buger/goterm" + "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" - "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/libpod/libpod" + "github.com/containers/libpod/pkg/adapter" "github.com/pkg/errors" "github.com/spf13/cobra" "github.com/ulule/deepcopier" @@ -22,10 +22,11 @@ import ( var ( podStatsCommand cliconfig.PodStatsValues - podStatsDescription = "Display a live stream of resource usage statistics for the containers in or more pods" - _podStatsCommand = &cobra.Command{ - Use: "stats [flags] POD [POD...]", - Short: "Display percentage of CPU, memory, network I/O, block I/O and PIDs for containers in one or more pods", + podStatsDescription = `For each specified pod this command will display percentage of CPU, memory, network I/O, block I/O and PIDs for containers in one the pods.` + + _podStatsCommand = &cobra.Command{ + Use: "stats [flags] [POD...]", + Short: "Display a live stream of resource usage statistics for the containers in one or more pods", Long: podStatsDescription, RunE: func(cmd *cobra.Command, args []string) error { podStatsCommand.InputArgs = args @@ -40,6 +41,7 @@ var ( func init() { podStatsCommand.Command = _podStatsCommand + podStatsCommand.SetHelpTemplate(HelpTemplate()) podStatsCommand.SetUsageTemplate(UsageTemplate()) flags := podStatsCommand.Flags() flags.BoolVarP(&podStatsCommand.All, "all", "a", false, "Provide stats for all running pods") @@ -51,9 +53,10 @@ func init() { } func podStatsCmd(c *cliconfig.PodStatsValues) error { - var ( - podFunc func() ([]*libpod.Pod, error) - ) + + if os.Geteuid() != 0 { + return errors.New("stats is not supported in rootless mode") + } format := c.Format all := c.All @@ -76,7 +79,7 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error { all = true } - runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) + runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "could not get runtime") } @@ -87,29 +90,12 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error { times = 1 } - if len(c.InputArgs) > 0 { - podFunc = func() ([]*libpod.Pod, error) { return getPodsByList(c.InputArgs, runtime) } - } else if latest { - podFunc = func() ([]*libpod.Pod, error) { - latestPod, err := runtime.GetLatestPod() - if err != nil { - return nil, err - } - return []*libpod.Pod{latestPod}, err - } - } else if all { - podFunc = runtime.GetAllPods - } else { - podFunc = runtime.GetRunningPods - } - - pods, err := podFunc() + pods, err := runtime.GetStatPods(c) if err != nil { return errors.Wrapf(err, "unable to get a list of pods") } - // First we need to get an initial pass of pod/ctr stats (these are not printed) - var podStats []*libpod.PodContainerStats + var podStats []*adapter.PodContainerStats for _, p := range pods { cons, err := p.AllContainersByID() if err != nil { @@ -120,7 +106,7 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error { for _, c := range cons { emptyStats[c] = &libpod.ContainerStats{} } - ps := libpod.PodContainerStats{ + ps := adapter.PodContainerStats{ Pod: p, ContainerStats: emptyStats, } @@ -128,10 +114,10 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error { } // Create empty container stat results for our first pass - var previousPodStats []*libpod.PodContainerStats + var previousPodStats []*adapter.PodContainerStats for _, p := range pods { cs := make(map[string]*libpod.ContainerStats) - pcs := libpod.PodContainerStats{ + pcs := adapter.PodContainerStats{ Pod: p, ContainerStats: cs, } @@ -164,7 +150,7 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error { } for i := 0; i < times; i += step { - var newStats []*libpod.PodContainerStats + var newStats []*adapter.PodContainerStats for _, p := range pods { prevStat := getPreviousPodContainerStats(p.ID(), previousPodStats) newPodStats, err := p.GetPodStats(prevStat) @@ -174,7 +160,7 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error { if err != nil { return err } - newPod := libpod.PodContainerStats{ + newPod := adapter.PodContainerStats{ Pod: p, ContainerStats: newPodStats, } @@ -202,7 +188,7 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error { time.Sleep(time.Second) previousPodStats := new([]*libpod.PodContainerStats) deepcopier.Copy(newStats).To(previousPodStats) - pods, err = podFunc() + pods, err = runtime.GetStatPods(c) if err != nil { return err } @@ -211,7 +197,7 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error { return nil } -func podContainerStatsToPodStatOut(stats []*libpod.PodContainerStats) []*podStatOut { +func podContainerStatsToPodStatOut(stats []*adapter.PodContainerStats) []*podStatOut { var out []*podStatOut for _, p := range stats { for _, c := range p.ContainerStats { @@ -295,7 +281,7 @@ func outputToStdOut(stats []*podStatOut) { w.Flush() } -func getPreviousPodContainerStats(podID string, prev []*libpod.PodContainerStats) map[string]*libpod.ContainerStats { +func getPreviousPodContainerStats(podID string, prev []*adapter.PodContainerStats) map[string]*libpod.ContainerStats { for _, p := range prev { if podID == p.Pod.ID() { return p.ContainerStats @@ -304,7 +290,7 @@ func getPreviousPodContainerStats(podID string, prev []*libpod.PodContainerStats return map[string]*libpod.ContainerStats{} } -func outputJson(stats []*libpod.PodContainerStats) error { +func outputJson(stats []*adapter.PodContainerStats) error { b, err := json.MarshalIndent(&stats, "", " ") if err != nil { return err diff --git a/cmd/podman/pod_stop.go b/cmd/podman/pod_stop.go index 951cf082a..754a3a7db 100644 --- a/cmd/podman/pod_stop.go +++ b/cmd/podman/pod_stop.go @@ -2,9 +2,11 @@ package main import ( "fmt" + "os" "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/pkg/adapter" + "github.com/containers/libpod/pkg/rootless" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" @@ -12,11 +14,9 @@ import ( var ( podStopCommand cliconfig.PodStopValues - podStopDescription = ` - podman pod stop + podStopDescription = `The pod name or ID can be used. - Stops one or more running pods. The pod name or ID can be used. -` + This command will stop all running containers in each of the specified pods.` _podStopCommand = &cobra.Command{ Use: "stop [flags] POD [POD...]", @@ -38,6 +38,7 @@ var ( func init() { podStopCommand.Command = _podStopCommand + podStopCommand.SetHelpTemplate(HelpTemplate()) podStopCommand.SetUsageTemplate(UsageTemplate()) flags := podStopCommand.Flags() flags.BoolVarP(&podStopCommand.All, "all", "a", false, "Stop all running pods") @@ -47,12 +48,24 @@ func init() { } func podStopCmd(c *cliconfig.PodStopValues) error { + if os.Geteuid() != 0 { + rootless.SetSkipStorageSetup(true) + } + runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "could not get runtime") } defer runtime.Shutdown(false) + if rootless.IsRootless() { + var err error + c.InputArgs, c.All, c.Latest, err = joinPodNS(runtime, c.All, c.Latest, c.InputArgs) + if err != nil { + return err + } + } + podStopIds, podStopErrors := runtime.StopPods(getContext(), c) for _, p := range podStopIds { fmt.Println(p) diff --git a/cmd/podman/pod_top.go b/cmd/podman/pod_top.go index 6a26e3dff..f65d66df6 100644 --- a/cmd/podman/pod_top.go +++ b/cmd/podman/pod_top.go @@ -2,14 +2,14 @@ package main import ( "fmt" + "github.com/containers/libpod/pkg/adapter" "os" "strings" "text/tabwriter" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/libpodruntime" - "github.com/containers/libpod/cmd/podman/shared" "github.com/containers/libpod/libpod" + "github.com/containers/libpod/pkg/rootless" "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -17,12 +17,10 @@ import ( var ( podTopCommand cliconfig.PodTopValues - podTopDescription = fmt.Sprintf(`Display the running processes containers in a pod. Specify format descriptors -to alter the output. You may run "podman pod top -l pid pcpu seccomp" to print -the process ID, the CPU percentage and the seccomp mode of each process of -the latest pod. -%s -`, getDescriptorString()) + podTopDescription = fmt.Sprintf(`Specify format descriptors to alter the output. + + You may run "podman pod top -l pid pcpu seccomp" to print the process ID, the CPU percentage and the seccomp mode of each process of the latest pod. +%s`, getDescriptorString()) _podTopCommand = &cobra.Command{ Use: "top [flags] CONTAINER [FORMAT-DESCRIPTORS]", @@ -41,6 +39,7 @@ the latest pod. func init() { podTopCommand.Command = _podTopCommand + podTopCommand.SetHelpTemplate(HelpTemplate()) podTopCommand.SetUsageTemplate(UsageTemplate()) flags := podTopCommand.Flags() flags.BoolVarP(&podTopCommand.Latest, "latest,", "l", false, "Act on the latest pod podman is aware of") @@ -50,10 +49,15 @@ func init() { } func podTopCmd(c *cliconfig.PodTopValues) error { - var pod *libpod.Pod - var err error + var ( + descriptors []string + ) args := c.InputArgs + if os.Geteuid() != 0 { + rootless.SetSkipStorageSetup(true) + } + if c.ListDescriptors { descriptors, err := libpod.GetContainerPidInformationDescriptors() if err != nil { @@ -67,39 +71,43 @@ func podTopCmd(c *cliconfig.PodTopValues) error { return errors.Errorf("you must provide the name or id of a running pod") } - runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) + runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "error creating libpod runtime") } defer runtime.Shutdown(false) - var descriptors []string if c.Latest { descriptors = args - pod, err = runtime.GetLatestPod() } else { descriptors = args[1:] - pod, err = runtime.LookupPod(args[0]) - } - - if err != nil { - return errors.Wrapf(err, "unable to lookup requested container") } - podStatus, err := shared.GetPodStatus(pod) - if err != nil { - return err - } - if podStatus != "Running" { - return errors.Errorf("pod top can only be used on pods with at least one running container") + if os.Geteuid() != 0 { + var pod *adapter.Pod + var err error + if c.Latest { + pod, err = runtime.GetLatestPod() + } else { + pod, err = runtime.LookupPod(c.InputArgs[0]) + } + if err != nil { + return errors.Wrapf(err, "unable to lookup requested container") + } + became, ret, err := runtime.JoinOrCreateRootlessPod(pod) + if err != nil { + return err + } + if became { + os.Exit(ret) + } } - psOutput, err := pod.GetPodPidInformation(descriptors) + w := tabwriter.NewWriter(os.Stdout, 5, 1, 3, ' ', 0) + psOutput, err := runtime.PodTop(c, descriptors) if err != nil { return err } - - w := tabwriter.NewWriter(os.Stdout, 5, 1, 3, ' ', 0) for _, proc := range psOutput { fmt.Fprintln(w, proc) } diff --git a/cmd/podman/pod_unpause.go b/cmd/podman/pod_unpause.go index 6b142d573..0623c6abb 100644 --- a/cmd/podman/pod_unpause.go +++ b/cmd/podman/pod_unpause.go @@ -12,8 +12,10 @@ import ( var ( podUnpauseCommand cliconfig.PodUnpauseValues - podUnpauseDescription = `Unpauses one or more pods. The pod name or ID can be used.` - _podUnpauseCommand = &cobra.Command{ + podUnpauseDescription = `The podman unpause command will unpause all "paused" containers assigned to the pod. + + The pod name or ID can be used.` + _podUnpauseCommand = &cobra.Command{ Use: "unpause [flags] POD [POD...]", Short: "Unpause one or more pods", Long: podUnpauseDescription, @@ -33,6 +35,7 @@ var ( func init() { podUnpauseCommand.Command = _podUnpauseCommand + podUnpauseCommand.SetHelpTemplate(HelpTemplate()) podUnpauseCommand.SetUsageTemplate(UsageTemplate()) flags := podUnpauseCommand.Flags() flags.BoolVarP(&podUnpauseCommand.All, "all", "a", false, "Unpause all running pods") diff --git a/cmd/podman/port.go b/cmd/podman/port.go index ffb5749fb..b5a4d3eec 100644 --- a/cmd/podman/port.go +++ b/cmd/podman/port.go @@ -14,10 +14,7 @@ import ( var ( portCommand cliconfig.PortValues - portDescription = ` - podman port - - List port mappings for the CONTAINER, or lookup the public-facing port that is NAT-ed to the PRIVATE_PORT + portDescription = `List port mappings for the CONTAINER, or lookup the public-facing port that is NAT-ed to the PRIVATE_PORT ` _portCommand = &cobra.Command{ Use: "port [flags] CONTAINER", @@ -39,6 +36,7 @@ var ( func init() { portCommand.Command = _portCommand + portCommand.SetHelpTemplate(HelpTemplate()) portCommand.SetUsageTemplate(UsageTemplate()) flags := portCommand.Flags() diff --git a/cmd/podman/ps.go b/cmd/podman/ps.go index fe4173fdd..27774f95d 100644 --- a/cmd/podman/ps.go +++ b/cmd/podman/ps.go @@ -12,11 +12,12 @@ import ( "text/tabwriter" "time" + "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/libpod/cmd/podman/shared" "github.com/containers/libpod/libpod" + "github.com/containers/libpod/pkg/rootless" "github.com/containers/libpod/pkg/util" "github.com/cri-o/ocicni/pkg/ocicni" "github.com/docker/go-units" @@ -159,6 +160,7 @@ var ( psDescription = "Prints out information about the containers" _psCommand = cobra.Command{ Use: "ps", + Args: noSubArgs, Short: "List containers", Long: psDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -172,28 +174,36 @@ var ( } ) -func init() { - psCommand.Command = &_psCommand - psCommand.SetUsageTemplate(UsageTemplate()) - flags := psCommand.Flags() - flags.BoolVarP(&psCommand.All, "all", "a", false, "Show all the containers, default is only running containers") - flags.StringSliceVarP(&psCommand.Filter, "filter", "f", []string{}, "Filter output based on conditions given") - flags.StringVar(&psCommand.Format, "format", "", "Pretty-print containers to JSON or using a Go template") - flags.IntVarP(&psCommand.Last, "last", "n", -1, "Print the n last created containers (all states)") - flags.BoolVarP(&psCommand.Latest, "latest", "l", false, "Show the latest container created (all states)") - flags.BoolVar(&psCommand.Namespace, "namespace", false, "Display namespace information") - flags.BoolVar(&psCommand.Namespace, "ns", false, "Display namespace information") - flags.BoolVar(&psCommand.NoTrunct, "no-trunc", false, "Display the extended information") - flags.BoolVarP(&psCommand.Pod, "pod", "p", false, "Print the ID and name of the pod the containers are associated with") - flags.BoolVarP(&psCommand.Quiet, "quiet", "q", false, "Print the numeric IDs of the containers only") - flags.BoolVarP(&psCommand.Size, "size", "s", false, "Display the total file sizes") - flags.StringVar(&psCommand.Sort, "sort", "created", "Sort output by command, created, id, image, names, runningfor, size, or status") - flags.BoolVar(&psCommand.Sync, "sync", false, "Sync container state with OCI runtime") +func psInit(command *cliconfig.PsValues) { + command.SetHelpTemplate(HelpTemplate()) + command.SetUsageTemplate(UsageTemplate()) + flags := command.Flags() + flags.BoolVarP(&command.All, "all", "a", false, "Show all the containers, default is only running containers") + flags.StringSliceVarP(&command.Filter, "filter", "f", []string{}, "Filter output based on conditions given") + flags.StringVar(&command.Format, "format", "", "Pretty-print containers to JSON or using a Go template") + flags.IntVarP(&command.Last, "last", "n", -1, "Print the n last created containers (all states)") + flags.BoolVarP(&command.Latest, "latest", "l", false, "Show the latest container created (all states)") + flags.BoolVar(&command.Namespace, "namespace", false, "Display namespace information") + flags.BoolVar(&command.Namespace, "ns", false, "Display namespace information") + flags.BoolVar(&command.NoTrunct, "no-trunc", false, "Display the extended information") + flags.BoolVarP(&command.Pod, "pod", "p", false, "Print the ID and name of the pod the containers are associated with") + flags.BoolVarP(&command.Quiet, "quiet", "q", false, "Print the numeric IDs of the containers only") + flags.BoolVarP(&command.Size, "size", "s", false, "Display the total file sizes") + flags.StringVar(&command.Sort, "sort", "created", "Sort output by command, created, id, image, names, runningfor, size, or status") + flags.BoolVar(&command.Sync, "sync", false, "Sync container state with OCI runtime") markFlagHiddenForRemoteClient("latest", flags) } +func init() { + psCommand.Command = &_psCommand + psInit(&psCommand) +} + func psCmd(c *cliconfig.PsValues) error { + if os.Geteuid() != 0 { + rootless.SetSkipStorageSetup(true) + } if c.Bool("trace") { span, _ := opentracing.StartSpanFromContext(Ctx, "psCmd") defer span.Finish() @@ -215,10 +225,6 @@ func psCmd(c *cliconfig.PsValues) error { defer runtime.Shutdown(false) - if len(c.InputArgs) > 0 { - return errors.Errorf("too many arguments, ps takes no arguments") - } - opts := shared.PsOptions{ All: c.All, Format: c.Format, @@ -417,7 +423,7 @@ func generateContainerFilterFuncs(filter, filterValue string, runtime *libpod.Ru return false }, nil case "status": - if !util.StringInSlice(filterValue, []string{"created", "restarting", "running", "paused", "exited", "unknown"}) { + if !util.StringInSlice(filterValue, []string{"created", "running", "paused", "stopped", "exited", "unknown"}) { return nil, errors.Errorf("%s is not a valid status", filterValue) } return func(c *libpod.Container) bool { @@ -425,9 +431,14 @@ func generateContainerFilterFuncs(filter, filterValue string, runtime *libpod.Ru if err != nil { return false } + if filterValue == "stopped" { + filterValue = "exited" + } state := status.String() if status == libpod.ContainerStateConfigured { state = "created" + } else if status == libpod.ContainerStateStopped { + state = "exited" } return state == filterValue }, nil @@ -483,6 +494,14 @@ func generateContainerFilterFuncs(filter, filterValue string, runtime *libpod.Ru } return false }, nil + case "health": + return func(c *libpod.Container) bool { + hcStatus, err := c.HealthCheckStatus() + if err != nil { + return false + } + return hcStatus == filterValue + }, nil } return nil, errors.Errorf("%s is an invalid filter", filter) } diff --git a/cmd/podman/pull.go b/cmd/podman/pull.go index 5f4658fe1..8888c5e28 100644 --- a/cmd/podman/pull.go +++ b/cmd/podman/pull.go @@ -23,11 +23,9 @@ import ( var ( pullCommand cliconfig.PullValues - pullDescription = ` -Pulls an image from a registry and stores it locally. -An image can be pulled using its tag or digest. If a tag is not -specified, the image with the 'latest' tag (if it exists) is pulled -` + pullDescription = `Pulls an image from a registry and stores it locally. + + An image can be pulled using its tag or digest. If a tag is not specified, the image with the 'latest' tag (if it exists) is pulled.` _pullCommand = &cobra.Command{ Use: "pull [flags] IMAGE-PATH", Short: "Pull an image from a registry", @@ -45,6 +43,7 @@ specified, the image with the 'latest' tag (if it exists) is pulled func init() { pullCommand.Command = _pullCommand + pullCommand.SetHelpTemplate(HelpTemplate()) pullCommand.SetUsageTemplate(UsageTemplate()) flags := pullCommand.Flags() flags.BoolVar(&pullCommand.AllTags, "all-tags", false, "All tagged images inthe repository will be pulled") @@ -53,7 +52,7 @@ func init() { flags.StringVar(&pullCommand.Creds, "creds", "", "`Credentials` (USERNAME:PASSWORD) to use for authenticating to a registry") flags.BoolVarP(&pullCommand.Quiet, "quiet", "q", false, "Suppress output information when pulling images") flags.StringVar(&pullCommand.SignaturePolicy, "signature-policy", "", "`Pathname` of signature policy file (not usually used)") - flags.BoolVar(&pullCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries (default: true)") + flags.BoolVar(&pullCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries") } diff --git a/cmd/podman/push.go b/cmd/podman/push.go index bc909cb5e..a1dac24ae 100644 --- a/cmd/podman/push.go +++ b/cmd/podman/push.go @@ -20,10 +20,9 @@ import ( var ( pushCommand cliconfig.PushValues - pushDescription = fmt.Sprintf(` - Pushes an image to a specified location. - The Image "DESTINATION" uses a "transport":"details" format. - See podman-push(1) section "DESTINATION" for the expected format`) + pushDescription = fmt.Sprintf(`Pushes an image to a specified location. + + The Image "DESTINATION" uses a "transport":"details" format. See podman-push(1) section "DESTINATION" for the expected format.`) _pushCommand = &cobra.Command{ Use: "push [flags] IMAGE REGISTRY", @@ -42,6 +41,7 @@ var ( func init() { pushCommand.Command = _pushCommand + pushCommand.SetHelpTemplate(HelpTemplate()) pushCommand.SetUsageTemplate(UsageTemplate()) flags := pushCommand.Flags() flags.MarkHidden("signature-policy") @@ -54,7 +54,7 @@ func init() { flags.BoolVar(&pushCommand.RemoveSignatures, "remove-signatures", false, "Discard any pre-existing signatures in the image") flags.StringVar(&pushCommand.SignaturePolicy, "signature-policy", "", "`Pathname` of signature policy file (not usually used)") flags.StringVar(&pushCommand.SignBy, "sign-by", "", "Add a signature at the destination using the specified key") - flags.BoolVar(&pushCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries (default: true)") + flags.BoolVar(&pushCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries") } func pushCmd(c *cliconfig.PushValues) error { diff --git a/cmd/podman/refresh.go b/cmd/podman/refresh.go index 193be6953..ed2e173ab 100644 --- a/cmd/podman/refresh.go +++ b/cmd/podman/refresh.go @@ -12,9 +12,13 @@ import ( var ( refreshCommand cliconfig.RefreshValues - refreshDescription = "The refresh command resets the state of all containers to handle database changes after a Podman upgrade. All running containers will be restarted." - _refreshCommand = &cobra.Command{ + refreshDescription = `Resets the state of all containers to handle database changes after a Podman upgrade. + + All running containers will be restarted. +` + _refreshCommand = &cobra.Command{ Use: "refresh", + Args: noSubArgs, Short: "Refresh container state", Long: refreshDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -28,14 +32,11 @@ var ( func init() { _refreshCommand.Hidden = true refreshCommand.Command = _refreshCommand + refreshCommand.SetHelpTemplate(HelpTemplate()) refreshCommand.SetUsageTemplate(UsageTemplate()) } func refreshCmd(c *cliconfig.RefreshValues) error { - if len(c.InputArgs) > 0 { - return errors.Errorf("refresh does not accept any arguments") - } - runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "error creating libpod runtime") diff --git a/cmd/podman/restart.go b/cmd/podman/restart.go index 5aa12070e..e6a6d8434 100644 --- a/cmd/podman/restart.go +++ b/cmd/podman/restart.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "os" "github.com/containers/libpod/cmd/podman/cliconfig" @@ -16,8 +15,10 @@ import ( var ( restartCommand cliconfig.RestartValues - restartDescription = `Restarts one or more running containers. The container ID or name can be used. A timeout before forcibly stopping can be set, but defaults to 10 seconds` - _restartCommand = &cobra.Command{ + restartDescription = `Restarts one or more running containers. The container ID or name can be used. + + A timeout before forcibly stopping can be set, but defaults to 10 seconds.` + _restartCommand = &cobra.Command{ Use: "restart [flags] CONTAINER [CONTAINER...]", Short: "Restart one or more containers", Long: restartDescription, @@ -37,6 +38,7 @@ var ( func init() { restartCommand.Command = _restartCommand + restartCommand.SetHelpTemplate(HelpTemplate()) restartCommand.SetUsageTemplate(UsageTemplate()) flags := restartCommand.Flags() flags.BoolVarP(&restartCommand.All, "all", "a", false, "Restart all non-running containers") @@ -58,6 +60,15 @@ func restartCmd(c *cliconfig.RestartValues) error { if os.Geteuid() != 0 { rootless.SetSkipStorageSetup(true) } + if rootless.IsRootless() { + // If we are in the re-execed rootless environment, + // override the arg to deal only with one container. + if os.Geteuid() == 0 { + c.All = false + c.Latest = false + c.InputArgs = []string{rootless.Argument()} + } + } args := c.InputArgs runOnly := c.Running @@ -104,6 +115,20 @@ func restartCmd(c *cliconfig.RestartValues) error { } } + if os.Geteuid() != 0 { + // In rootless mode we can deal with one container at at time. + for _, c := range restartContainers { + _, ret, err := joinContainerOrCreateRootlessUserNS(runtime, c) + if err != nil { + return err + } + if ret != 0 { + os.Exit(ret) + } + } + os.Exit(0) + } + maxWorkers := shared.Parallelize("restart") if c.GlobalIsSet("max-workers") { maxWorkers = c.GlobalFlags.MaxWorks @@ -111,22 +136,6 @@ func restartCmd(c *cliconfig.RestartValues) error { logrus.Debugf("Setting maximum workers to %d", maxWorkers) - if rootless.IsRootless() { - // With rootless containers we cannot really restart an existing container - // as we would need to join the mount namespace as well to be able to reuse - // the storage. - if err := stopRootlessContainers(restartContainers, timeout, useTimeout, maxWorkers); err != nil { - return err - } - became, ret, err := rootless.BecomeRootInUserNS() - if err != nil { - return err - } - if became { - os.Exit(ret) - } - } - // We now have a slice of all the containers to be restarted. Iterate them to // create restart Funcs with a timeout as needed for _, ctr := range restartContainers { @@ -149,46 +158,3 @@ func restartCmd(c *cliconfig.RestartValues) error { restartErrors, errCount := shared.ParallelExecuteWorkerPool(maxWorkers, restartFuncs) return printParallelOutput(restartErrors, errCount) } - -func stopRootlessContainers(stopContainers []*libpod.Container, timeout uint, useTimeout bool, maxWorkers int) error { - var stopFuncs []shared.ParallelWorkerInput - for _, ctr := range stopContainers { - state, err := ctr.State() - if err != nil { - return err - } - if state != libpod.ContainerStateRunning { - continue - } - - ctrTimeout := ctr.StopTimeout() - if useTimeout { - ctrTimeout = timeout - } - - c := ctr - f := func() error { - return c.StopWithTimeout(ctrTimeout) - } - - stopFuncs = append(stopFuncs, shared.ParallelWorkerInput{ - ContainerID: c.ID(), - ParallelFunc: f, - }) - - restartErrors, errCount := shared.ParallelExecuteWorkerPool(maxWorkers, stopFuncs) - var lastError error - for _, result := range restartErrors { - if result != nil { - if errCount > 1 { - fmt.Println(result.Error()) - } - lastError = result - } - } - if lastError != nil { - return lastError - } - } - return nil -} diff --git a/cmd/podman/restore.go b/cmd/podman/restore.go index 73d355734..0f6828432 100644 --- a/cmd/podman/restore.go +++ b/cmd/podman/restore.go @@ -40,6 +40,7 @@ var ( func init() { restoreCommand.Command = _restoreCommand + restoreCommand.SetHelpTemplate(HelpTemplate()) restoreCommand.SetUsageTemplate(UsageTemplate()) flags := restoreCommand.Flags() flags.BoolVarP(&restoreCommand.All, "all", "a", false, "Restore all checkpointed containers") diff --git a/cmd/podman/rm.go b/cmd/podman/rm.go index 61b049840..253771e14 100644 --- a/cmd/podman/rm.go +++ b/cmd/podman/rm.go @@ -2,12 +2,16 @@ package main import ( "fmt" + "io/ioutil" + "os" + "strconv" "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/libpod/cmd/podman/shared" "github.com/containers/libpod/libpod" "github.com/containers/libpod/libpod/image" + "github.com/containers/libpod/pkg/rootless" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" @@ -15,11 +19,9 @@ import ( var ( rmCommand cliconfig.RmValues - rmDescription = fmt.Sprintf(` -Podman rm will remove one or more containers from the host. -The container name or ID can be used. This does not remove images. -Running containers will not be removed without the -f option. -`) + rmDescription = fmt.Sprintf(`Removes one or more containers from the host. The container name or ID can be used. + + Command does not remove images. Running containers will not be removed without the -f option.`) _rmCommand = &cobra.Command{ Use: "rm [flags] CONTAINER [CONTAINER...]", Short: "Remove one or more containers", @@ -40,6 +42,7 @@ Running containers will not be removed without the -f option. func init() { rmCommand.Command = _rmCommand + rmCommand.SetHelpTemplate(HelpTemplate()) rmCommand.SetUsageTemplate(UsageTemplate()) flags := rmCommand.Flags() flags.BoolVarP(&rmCommand.All, "all", "a", false, "Remove all containers") @@ -49,11 +52,39 @@ func init() { markFlagHiddenForRemoteClient("latest", flags) } +func joinContainerOrCreateRootlessUserNS(runtime *libpod.Runtime, ctr *libpod.Container) (bool, int, error) { + if os.Geteuid() == 0 { + return false, 0, nil + } + s, err := ctr.State() + if err != nil { + return false, -1, err + } + opts := rootless.Opts{ + Argument: ctr.ID(), + } + if s == libpod.ContainerStateRunning || s == libpod.ContainerStatePaused { + data, err := ioutil.ReadFile(ctr.Config().ConmonPidFile) + if err != nil { + return false, -1, errors.Wrapf(err, "cannot read conmon PID file %q", ctr.Config().ConmonPidFile) + } + conmonPid, err := strconv.Atoi(string(data)) + if err != nil { + return false, -1, errors.Wrapf(err, "cannot parse PID %q", data) + } + return rootless.JoinDirectUserAndMountNSWithOpts(uint(conmonPid), &opts) + } + return rootless.BecomeRootInUserNSWithOpts(&opts) +} + // saveCmd saves the image to either docker-archive or oci func rmCmd(c *cliconfig.RmValues) error { var ( deleteFuncs []shared.ParallelWorkerInput ) + if os.Geteuid() != 0 { + rootless.SetSkipStorageSetup(true) + } ctx := getContext() runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) @@ -62,6 +93,58 @@ func rmCmd(c *cliconfig.RmValues) error { } defer runtime.Shutdown(false) + if rootless.IsRootless() { + // When running in rootless mode we cannot manage different containers and + // user namespaces from the same context, so be sure to re-exec once for each + // container we are dealing with. + // What we do is to first collect all the containers we want to delete, then + // we re-exec in each of the container namespaces and from there remove the single + // container. + var container *libpod.Container + if os.Geteuid() == 0 { + // We are in the namespace, override InputArgs with the single + // argument that was passed down to us. + c.All = false + c.Latest = false + c.InputArgs = []string{rootless.Argument()} + } else { + exitCode = 0 + var containers []*libpod.Container + if c.All { + containers, err = runtime.GetContainers() + } else if c.Latest { + container, err = runtime.GetLatestContainer() + if err != nil { + return errors.Wrapf(err, "unable to get latest pod") + } + containers = append(containers, container) + } else { + for _, c := range c.InputArgs { + container, err = runtime.LookupContainer(c) + if err != nil { + if errors.Cause(err) == libpod.ErrNoSuchCtr { + exitCode = 1 + continue + } + return err + } + containers = append(containers, container) + } + } + // Now we really delete the containers. + for _, c := range containers { + _, ret, err := joinContainerOrCreateRootlessUserNS(runtime, c) + if err != nil { + return err + } + if ret != 0 { + os.Exit(ret) + } + } + os.Exit(exitCode) + } + } + failureCnt := 0 delContainers, err := getAllOrLatestContainers(&c.PodmanCommand, runtime, -1, "all") if err != nil { @@ -80,6 +163,9 @@ func rmCmd(c *cliconfig.RmValues) error { return err } if err != nil { + if errors.Cause(err) == libpod.ErrNoSuchCtr { + exitCode = 1 + } fmt.Println(err.Error()) } } @@ -114,5 +200,10 @@ func rmCmd(c *cliconfig.RmValues) error { exitCode = 1 } } + + if failureCnt > 0 { + exitCode = 125 + } + return err } diff --git a/cmd/podman/rmi.go b/cmd/podman/rmi.go index 5b8bf1ea3..149cd8d82 100644 --- a/cmd/podman/rmi.go +++ b/cmd/podman/rmi.go @@ -13,7 +13,7 @@ import ( var ( rmiCommand cliconfig.RmiValues - rmiDescription = "Removes one or more locally stored images." + rmiDescription = "Removes one or more previously pulled or locally created images." _rmiCommand = cobra.Command{ Use: "rmi [flags] IMAGE [IMAGE...]", Short: "Removes one or more images from local storage", @@ -29,12 +29,17 @@ var ( } ) +func rmiInit(command *cliconfig.RmiValues) { + command.SetHelpTemplate(HelpTemplate()) + command.SetUsageTemplate(UsageTemplate()) + flags := command.Flags() + flags.BoolVarP(&command.All, "all", "a", false, "Remove all images") + flags.BoolVarP(&command.Force, "force", "f", false, "Force Removal of the image") +} + func init() { rmiCommand.Command = &_rmiCommand - rmiCommand.SetUsageTemplate(UsageTemplate()) - flags := rmiCommand.Flags() - flags.BoolVarP(&rmiCommand.All, "all", "a", false, "Remove all images") - flags.BoolVarP(&rmiCommand.Force, "force", "f", false, "Force Removal of the image") + rmiInit(&rmiCommand) } func rmiCmd(c *cliconfig.RmiValues) error { diff --git a/cmd/podman/run.go b/cmd/podman/run.go index f66b939d3..32e7b3510 100644 --- a/cmd/podman/run.go +++ b/cmd/podman/run.go @@ -10,6 +10,7 @@ import ( "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/cmd/podman/libpodruntime" + "github.com/containers/libpod/cmd/podman/shared" "github.com/containers/libpod/libpod" "github.com/containers/libpod/pkg/rootless" opentracing "github.com/opentracing/opentracing-go" @@ -39,10 +40,11 @@ var ( func init() { runCommand.Command = _runCommand + runCommand.SetHelpTemplate(HelpTemplate()) runCommand.SetUsageTemplate(UsageTemplate()) flags := runCommand.Flags() flags.SetInterspersed(false) - flags.Bool("sig-proxy", true, "Proxy received signals to the process (default true)") + flags.Bool("sig-proxy", true, "Proxy received signals to the process") getCreateFlags(&runCommand.PodmanCommand) } @@ -65,7 +67,7 @@ func runCmd(c *cliconfig.RunValues) error { } defer runtime.Shutdown(false) - ctr, createConfig, err := createContainer(&c.PodmanCommand, runtime) + ctr, createConfig, err := shared.CreateContainer(getContext(), &c.PodmanCommand, runtime) if err != nil { return err } @@ -164,6 +166,10 @@ func runCmd(c *cliconfig.RunValues) error { exitCode = int(ecode) } + if c.IsSet("rm") { + runtime.RemoveContainer(ctx, ctr, false, true) + } + return nil } diff --git a/cmd/podman/run_test.go b/cmd/podman/run_test.go index 5ea39e457..a896f1dc7 100644 --- a/cmd/podman/run_test.go +++ b/cmd/podman/run_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/cmd/podman/shared" "github.com/containers/libpod/pkg/inspect" cc "github.com/containers/libpod/pkg/spec" "github.com/docker/go-units" @@ -80,7 +81,7 @@ func getRuntimeSpec(c *cliconfig.PodmanCommand) (*spec.Spec, error) { createConfig, err := parseCreateOpts(c, runtime, "alpine", generateAlpineImageData()) */ ctx := getContext() - createConfig, err := parseCreateOpts(ctx, c, nil, "alpine", generateAlpineImageData()) + createConfig, err := shared.ParseCreateOpts(ctx, c, nil, "alpine", generateAlpineImageData()) if err != nil { return nil, err } diff --git a/cmd/podman/runlabel.go b/cmd/podman/runlabel.go index bc4e650f9..f79aa8b0e 100644 --- a/cmd/podman/runlabel.go +++ b/cmd/podman/runlabel.go @@ -10,9 +10,11 @@ import ( "github.com/containers/libpod/cmd/podman/cliconfig" "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/libpod/cmd/podman/shared" + "github.com/containers/libpod/libpod" "github.com/containers/libpod/libpod/image" "github.com/containers/libpod/utils" "github.com/pkg/errors" + "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) @@ -38,12 +40,14 @@ Executes a command as described by a container image label. func init() { runlabelCommand.Command = _runlabelCommand + runlabelCommand.SetHelpTemplate(HelpTemplate()) runlabelCommand.SetUsageTemplate(UsageTemplate()) flags := runlabelCommand.Flags() flags.StringVar(&runlabelCommand.Authfile, "authfile", "", "Path of the authentication file. Default is ${XDG_RUNTIME_DIR}/containers/auth.json. Use REGISTRY_AUTH_FILE environment variable to override") flags.StringVar(&runlabelCommand.CertDir, "cert-dir", "", "`Pathname` of a directory containing TLS certificates and keys") flags.StringVar(&runlabelCommand.Creds, "creds", "", "`Credentials` (USERNAME:PASSWORD) to use for authenticating to a registry") flags.BoolVar(&runlabelCommand.Display, "display", false, "Preview the command that the label would run") + flags.BoolVar(&runlabelCommand.Replace, "replace", false, "Replace existing container with a new one from the image") flags.StringVar(&runlabelCommand.Name, "name", "", "Assign a name to the container") flags.StringVar(&runlabelCommand.Opt1, "opt1", "", "Optional parameter to pass for install") @@ -53,10 +57,12 @@ func init() { flags.MarkHidden("opt2") flags.MarkHidden("opt3") - flags.BoolVarP(&runlabelCommand.Pull, "pull", "p", false, "Pull the image if it does not exist locally prior to executing the label contents") + flags.BoolP("pull", "p", false, "Pull the image if it does not exist locally prior to executing the label contents") flags.BoolVarP(&runlabelCommand.Quiet, "quiet", "q", false, "Suppress output information when installing images") flags.StringVar(&runlabelCommand.SignaturePolicy, "signature-policy", "", "`Pathname` of signature policy file (not usually used)") - flags.BoolVar(&runlabelCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries (default: true)") + flags.BoolVar(&runlabelCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries") + + flags.MarkDeprecated("pull", "podman will pull if not found in local storage") } // installCmd gets the data from the command line and calls installImage @@ -95,7 +101,6 @@ func runlabelCmd(c *cliconfig.RunlabelValues) error { if len(args) > 2 { extraArgs = args[2:] } - pull := c.Pull label := args[0] runlabelImage := args[1] @@ -131,7 +136,7 @@ func runlabelCmd(c *cliconfig.RunlabelValues) error { } authfile := getAuthFile(c.Authfile) - runLabel, imageName, err := shared.GetRunlabel(label, runlabelImage, ctx, runtime, pull, c.Creds, dockerRegistryOptions, authfile, c.SignaturePolicy, stdOut) + runLabel, imageName, err := shared.GetRunlabel(label, runlabelImage, ctx, runtime, true, c.Creds, dockerRegistryOptions, authfile, c.SignaturePolicy, stdOut) if err != nil { return err } @@ -144,10 +149,33 @@ func runlabelCmd(c *cliconfig.RunlabelValues) error { return err } if !c.Quiet { - fmt.Printf("Command: %s\n", strings.Join(cmd, " ")) + fmt.Printf("command: %s\n", strings.Join(cmd, " ")) if c.Display { return nil } } + + // If container already exists && --replace given -- Nuke it + if c.Replace { + for i, entry := range cmd { + if entry == "--name" { + name := cmd[i+1] + ctr, err := runtime.LookupContainer(name) + if err != nil { + if errors.Cause(err) != libpod.ErrNoSuchCtr { + logrus.Debugf("Error occurred searching for container %s: %s", name, err.Error()) + return err + } + } else { + logrus.Debugf("Runlabel --replace option given. Container %s will be deleted. The new container will be named %s", ctr.ID(), name) + if err := runtime.RemoveContainer(ctx, ctr, true, false); err != nil { + return err + } + } + break + } + } + } + return utils.ExecCmdWithStdStreams(stdIn, stdOut, stdErr, env, cmd[0], cmd[1:]...) } diff --git a/cmd/podman/save.go b/cmd/podman/save.go index 3bc283772..c10679740 100644 --- a/cmd/podman/save.go +++ b/cmd/podman/save.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/cmd/podman/shared/parse" "github.com/containers/libpod/pkg/adapter" "github.com/containers/libpod/pkg/util" "github.com/pkg/errors" @@ -23,9 +24,7 @@ var validFormats = []string{ociManifestDir, ociArchive, v2s2ManifestDir, v2s2Arc var ( saveCommand cliconfig.SaveValues - 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{ Use: "save [flags] IMAGE", @@ -54,11 +53,12 @@ var ( func init() { saveCommand.Command = _saveCommand + saveCommand.SetHelpTemplate(HelpTemplate()) saveCommand.SetUsageTemplate(UsageTemplate()) flags := saveCommand.Flags() flags.BoolVar(&saveCommand.Compress, "compress", false, "Compress tarball image layers when saving to a directory using the 'dir' transport. (default is same compression type as source)") flags.StringVar(&saveCommand.Format, "format", v2s2Archive, "Save image to oci-archive, oci-dir (directory with oci manifest type), docker-archive, docker-dir (directory with v2s2 manifest type)") - flags.StringVarP(&saveCommand.Output, "output", "o", "/dev/stdout", "Write to a file, default is STDOUT") + flags.StringVarP(&saveCommand.Output, "output", "o", "", "Write to a specified file (default: stdout, which must be redirected)") flags.BoolVarP(&saveCommand.Quiet, "quiet", "q", false, "Suppress the output") } @@ -79,14 +79,14 @@ func saveCmd(c *cliconfig.SaveValues) error { return errors.Errorf("--compress can only be set when --format is either 'oci-dir' or 'docker-dir'") } - output := c.Output - if output == "/dev/stdout" { + if len(c.Output) == 0 { fi := os.Stdout if logrus.IsTerminal(fi) { return errors.Errorf("refusing to save to terminal. Use -o flag or redirect") } + c.Output = "/dev/stdout" } - if err := validateFileName(output); err != nil { + if err := parse.ValidateFileName(c.Output); err != nil { return err } return runtime.SaveImage(getContext(), c) diff --git a/cmd/podman/search.go b/cmd/podman/search.go index 5c14f1ff1..a10b9d419 100644 --- a/cmd/podman/search.go +++ b/cmd/podman/search.go @@ -1,11 +1,12 @@ package main import ( + "reflect" "strings" + "github.com/containers/buildah/pkg/formats" "github.com/containers/image/types" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/libpod/image" "github.com/pkg/errors" "github.com/spf13/cobra" @@ -18,9 +19,9 @@ const ( var ( searchCommand cliconfig.SearchValues - searchDescription = ` - Search registries for a given image. Can search all the default registries or a specific registry. - Can limit the number of results, and filter the output based on certain conditions.` + searchDescription = `Search registries for a given image. Can search all the default registries or a specific registry. + + Users can limit the number of results, and filter the output based on certain conditions.` _searchCommand = &cobra.Command{ Use: "search [flags] TERM", Short: "Search registry for image", @@ -38,6 +39,7 @@ var ( func init() { searchCommand.Command = _searchCommand + searchCommand.SetHelpTemplate(HelpTemplate()) searchCommand.SetUsageTemplate(UsageTemplate()) flags := searchCommand.Flags() flags.StringVar(&searchCommand.Authfile, "authfile", "", "Path of the authentication file. Default is ${XDG_RUNTIME_DIR}/containers/auth.json. Use REGISTRY_AUTH_FILE environment variable to override") @@ -45,7 +47,7 @@ func init() { flags.StringVar(&searchCommand.Format, "format", "", "Change the output format to a Go template") flags.IntVar(&searchCommand.Limit, "limit", 0, "Limit the number of results") flags.BoolVar(&searchCommand.NoTrunc, "no-trunc", false, "Do not truncate the output") - flags.BoolVar(&searchCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries (default: true)") + flags.BoolVar(&searchCommand.TlsVerify, "tls-verify", true, "Require HTTPS and verify certificates when contacting registries") } func searchCmd(c *cliconfig.SearchValues) error { @@ -78,7 +80,10 @@ func searchCmd(c *cliconfig.SearchValues) error { return err } format := genSearchFormat(c.Format) - out := formats.StdoutTemplateArray{Output: searchToGeneric(results), Template: format, Fields: results[0].HeaderMap()} + if len(results) == 0 { + return nil + } + out := formats.StdoutTemplateArray{Output: searchToGeneric(results), Template: format, Fields: genSearchOutputMap()} formats.Writer(out).Out() return nil } @@ -98,3 +103,16 @@ func searchToGeneric(params []image.SearchResult) (genericParams []interface{}) } return genericParams } + +func genSearchOutputMap() map[string]string { + io := image.SearchResult{} + v := reflect.Indirect(reflect.ValueOf(io)) + values := make(map[string]string) + + for i := 0; i < v.NumField(); i++ { + key := v.Type().Field(i).Name + value := key + values[key] = strings.ToUpper(splitCamelCase(value)) + } + return values +} diff --git a/cmd/podman/shared/container.go b/cmd/podman/shared/container.go index 81811e0f2..6826191c5 100644 --- a/cmd/podman/shared/container.go +++ b/cmd/podman/shared/container.go @@ -3,11 +3,11 @@ package shared import ( "context" "fmt" - "github.com/google/shlex" "io" "os" "path/filepath" "regexp" + "sort" "strconv" "strings" "sync" @@ -21,6 +21,7 @@ import ( "github.com/containers/libpod/pkg/util" "github.com/cri-o/ocicni/pkg/ocicni" "github.com/docker/go-units" + "github.com/google/shlex" "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" @@ -523,6 +524,7 @@ func GetCtrInspectInfo(config *libpod.ContainerConfig, ctrInspectData *inspect.C StopSignal: config.StopSignal, Cmd: config.Spec.Process.Args, Entrypoint: strings.Join(createArtifact.Entrypoint, " "), + Healthcheck: config.HealthCheckConfig, }, } return data, nil @@ -582,18 +584,93 @@ func getCgroup(spec *specs.Spec) string { return cgroup } +func comparePorts(i, j ocicni.PortMapping) bool { + if i.ContainerPort != j.ContainerPort { + return i.ContainerPort < j.ContainerPort + } + + if i.HostIP != j.HostIP { + return i.HostIP < j.HostIP + } + + if i.HostPort != j.HostPort { + return i.HostPort < j.HostPort + } + + return i.Protocol < j.Protocol +} + +// returns the group as <IP:startPort:lastPort->startPort:lastPort/Proto> +// e.g 0.0.0.0:1000-1006->1000-1006/tcp +func formatGroup(key string, start, last int32) string { + parts := strings.Split(key, "/") + groupType := parts[0] + var ip string + if len(parts) > 1 { + ip = parts[0] + groupType = parts[1] + } + group := strconv.Itoa(int(start)) + if start != last { + group = fmt.Sprintf("%s-%d", group, last) + } + if ip != "" { + group = fmt.Sprintf("%s:%s->%s", ip, group, group) + } + return fmt.Sprintf("%s/%s", group, groupType) +} + // portsToString converts the ports used to a string of the from "port1, port2" +// also groups continuous list of ports in readable format. func portsToString(ports []ocicni.PortMapping) string { + type portGroup struct { + first int32 + last int32 + } var portDisplay []string if len(ports) == 0 { return "" } + //Sort the ports, so grouping continuous ports become easy. + sort.Slice(ports, func(i, j int) bool { + return comparePorts(ports[i], ports[j]) + }) + + // portGroupMap is used for grouping continuous ports + portGroupMap := make(map[string]*portGroup) + var groupKeyList []string + for _, v := range ports { + hostIP := v.HostIP if hostIP == "" { hostIP = "0.0.0.0" } - portDisplay = append(portDisplay, fmt.Sprintf("%s:%d->%d/%s", hostIP, v.HostPort, v.ContainerPort, v.Protocol)) + // if hostPort and containerPort are not same, consider as individual port. + if v.ContainerPort != v.HostPort { + portDisplay = append(portDisplay, fmt.Sprintf("%s:%d->%d/%s", hostIP, v.HostPort, v.ContainerPort, v.Protocol)) + continue + } + + portMapKey := fmt.Sprintf("%s/%s", hostIP, v.Protocol) + + portgroup, ok := portGroupMap[portMapKey] + if !ok { + portGroupMap[portMapKey] = &portGroup{first: v.ContainerPort, last: v.ContainerPort} + // this list is required to travese portGroupMap + groupKeyList = append(groupKeyList, portMapKey) + continue + } + + if portgroup.last == (v.ContainerPort - 1) { + portgroup.last = v.ContainerPort + continue + } + } + // for each portMapKey, format group list and appned to output string + for _, portKey := range groupKeyList { + group := portGroupMap[portKey] + portDisplay = append(portDisplay, formatGroup(portKey, group.first, group.last)) } return strings.Join(portDisplay, ", ") } @@ -665,6 +742,14 @@ func GenerateRunlabelCommand(runLabel, imageName, name string, opts map[string]s return envmap["OPT2"] case "OPT3": return envmap["OPT3"] + case "PWD": + // I would prefer to use os.getenv but it appears PWD is not in the os env list + d, err := os.Getwd() + if err != nil { + logrus.Error("unable to determine current working directory") + return "" + } + return d } return "" } diff --git a/cmd/podman/shared/create.go b/cmd/podman/shared/create.go new file mode 100644 index 000000000..5ce0b8865 --- /dev/null +++ b/cmd/podman/shared/create.go @@ -0,0 +1,905 @@ +package shared + +import ( + "context" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" + + "github.com/containers/image/manifest" + "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/cmd/podman/shared/parse" + "github.com/containers/libpod/libpod" + "github.com/containers/libpod/libpod/image" + ann "github.com/containers/libpod/pkg/annotations" + "github.com/containers/libpod/pkg/inspect" + ns "github.com/containers/libpod/pkg/namespaces" + "github.com/containers/libpod/pkg/rootless" + cc "github.com/containers/libpod/pkg/spec" + "github.com/containers/libpod/pkg/util" + "github.com/docker/docker/pkg/signal" + "github.com/docker/go-connections/nat" + "github.com/docker/go-units" + "github.com/google/shlex" + spec "github.com/opencontainers/runtime-spec/specs-go" + "github.com/opencontainers/selinux/go-selinux/label" + "github.com/opentracing/opentracing-go" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" +) + +// getContext returns a non-nil, empty context +func getContext() context.Context { + return context.TODO() +} + +func CreateContainer(ctx context.Context, c *cliconfig.PodmanCommand, runtime *libpod.Runtime) (*libpod.Container, *cc.CreateConfig, error) { + var ( + healthCheck *manifest.Schema2HealthConfig + ) + if c.Bool("trace") { + span, _ := opentracing.StartSpanFromContext(ctx, "createContainer") + defer span.Finish() + } + + rtc := runtime.GetConfig() + rootfs := "" + if c.Bool("rootfs") { + rootfs = c.InputArgs[0] + } + + var err error + var cidFile *os.File + if c.IsSet("cidfile") && os.Geteuid() == 0 { + cidFile, err = libpod.OpenExclusiveFile(c.String("cidfile")) + if err != nil && os.IsExist(err) { + return nil, nil, errors.Errorf("container id file exists. Ensure another container is not using it or delete %s", c.String("cidfile")) + } + if err != nil { + return nil, nil, errors.Errorf("error opening cidfile %s", c.String("cidfile")) + } + defer cidFile.Close() + defer cidFile.Sync() + } + + imageName := "" + var data *inspect.ImageData = nil + + if rootfs == "" && !rootless.SkipStorageSetup() { + var writer io.Writer + if !c.Bool("quiet") { + writer = os.Stderr + } + + newImage, err := runtime.ImageRuntime().New(ctx, c.InputArgs[0], rtc.SignaturePolicyPath, "", writer, nil, image.SigningOptions{}, false, nil) + if err != nil { + return nil, nil, err + } + data, err = newImage.Inspect(ctx) + names := newImage.Names() + if len(names) > 0 { + imageName = names[0] + } else { + imageName = newImage.ID() + } + + var healthCheckCommandInput string + // if the user disabled the healthcheck with "none", we skip adding it + healthCheckCommandInput = c.String("healthcheck-command") + + // the user didnt disable the healthcheck but did pass in a healthcheck command + // now we need to make a healthcheck from the commandline input + if healthCheckCommandInput != "none" { + if len(healthCheckCommandInput) > 0 { + healthCheck, err = makeHealthCheckFromCli(c) + if err != nil { + return nil, nil, errors.Wrapf(err, "unable to create healthcheck") + } + } else { + // the user did not disable the health check and did not pass in a healthcheck + // command as input. so now we add healthcheck if it exists AND is correct mediatype + _, mediaType, err := newImage.Manifest(ctx) + if err != nil { + return nil, nil, errors.Wrapf(err, "unable to determine mediatype of image %s", newImage.ID()) + } + if mediaType == manifest.DockerV2Schema2MediaType { + healthCheck, err = newImage.GetHealthCheck(ctx) + if err != nil { + return nil, nil, errors.Wrapf(err, "unable to get healthcheck for %s", c.InputArgs[0]) + } + } + } + } + } + createConfig, err := ParseCreateOpts(ctx, c, runtime, imageName, data) + if err != nil { + return nil, nil, err + } + + // Because parseCreateOpts does derive anything from the image, we add health check + // at this point. The rest is done by WithOptions. + createConfig.HealthCheck = healthCheck + + ctr, err := CreateContainerFromCreateConfig(runtime, createConfig, ctx, nil) + if err != nil { + return nil, nil, err + } + if cidFile != nil { + _, err = cidFile.WriteString(ctr.ID()) + if err != nil { + logrus.Error(err) + } + + } + + logrus.Debugf("New container created %q", ctr.ID()) + return ctr, createConfig, nil +} + +func parseSecurityOpt(config *cc.CreateConfig, securityOpts []string) error { + var ( + labelOpts []string + ) + + if config.PidMode.IsHost() { + labelOpts = append(labelOpts, label.DisableSecOpt()...) + } else if config.PidMode.IsContainer() { + ctr, err := config.Runtime.LookupContainer(config.PidMode.Container()) + if err != nil { + return errors.Wrapf(err, "container %q not found", config.PidMode.Container()) + } + secopts, err := label.DupSecOpt(ctr.ProcessLabel()) + if err != nil { + return errors.Wrapf(err, "failed to duplicate label %q ", ctr.ProcessLabel()) + } + labelOpts = append(labelOpts, secopts...) + } + + if config.IpcMode.IsHost() { + labelOpts = append(labelOpts, label.DisableSecOpt()...) + } else if config.IpcMode.IsContainer() { + ctr, err := config.Runtime.LookupContainer(config.IpcMode.Container()) + if err != nil { + return errors.Wrapf(err, "container %q not found", config.IpcMode.Container()) + } + secopts, err := label.DupSecOpt(ctr.ProcessLabel()) + if err != nil { + return errors.Wrapf(err, "failed to duplicate label %q ", ctr.ProcessLabel()) + } + labelOpts = append(labelOpts, secopts...) + } + + for _, opt := range securityOpts { + if opt == "no-new-privileges" { + config.NoNewPrivs = true + } else { + con := strings.SplitN(opt, "=", 2) + if len(con) != 2 { + return fmt.Errorf("Invalid --security-opt 1: %q", opt) + } + + switch con[0] { + case "label": + labelOpts = append(labelOpts, con[1]) + case "apparmor": + config.ApparmorProfile = con[1] + case "seccomp": + config.SeccompProfilePath = con[1] + default: + return fmt.Errorf("Invalid --security-opt 2: %q", opt) + } + } + } + + if config.SeccompProfilePath == "" { + if _, err := os.Stat(libpod.SeccompOverridePath); err == nil { + config.SeccompProfilePath = libpod.SeccompOverridePath + } else { + if !os.IsNotExist(err) { + return errors.Wrapf(err, "can't check if %q exists", libpod.SeccompOverridePath) + } + if _, err := os.Stat(libpod.SeccompDefaultPath); err != nil { + if !os.IsNotExist(err) { + return errors.Wrapf(err, "can't check if %q exists", libpod.SeccompDefaultPath) + } + } else { + config.SeccompProfilePath = libpod.SeccompDefaultPath + } + } + } + config.LabelOpts = labelOpts + return nil +} + +func configureEntrypoint(c *cliconfig.PodmanCommand, data *inspect.ImageData) []string { + entrypoint := []string{} + if c.IsSet("entrypoint") { + // Force entrypoint to "" + if c.String("entrypoint") == "" { + return entrypoint + } + // Check if entrypoint specified is json + if err := json.Unmarshal([]byte(c.String("entrypoint")), &entrypoint); err == nil { + return entrypoint + } + // Return entrypoint as a single command + return []string{c.String("entrypoint")} + } + if data != nil { + return data.Config.Entrypoint + } + return entrypoint +} + +func configurePod(c *cliconfig.PodmanCommand, runtime *libpod.Runtime, namespaces map[string]string, podName string) (map[string]string, error) { + pod, err := runtime.LookupPod(podName) + if err != nil { + return namespaces, err + } + podInfraID, err := pod.InfraContainerID() + if err != nil { + return namespaces, err + } + if (namespaces["pid"] == cc.Pod) || (!c.IsSet("pid") && pod.SharesPID()) { + namespaces["pid"] = fmt.Sprintf("container:%s", podInfraID) + } + if (namespaces["net"] == cc.Pod) || (!c.IsSet("net") && !c.IsSet("network") && pod.SharesNet()) { + namespaces["net"] = fmt.Sprintf("container:%s", podInfraID) + } + if (namespaces["user"] == cc.Pod) || (!c.IsSet("user") && pod.SharesUser()) { + namespaces["user"] = fmt.Sprintf("container:%s", podInfraID) + } + if (namespaces["ipc"] == cc.Pod) || (!c.IsSet("ipc") && pod.SharesIPC()) { + namespaces["ipc"] = fmt.Sprintf("container:%s", podInfraID) + } + if (namespaces["uts"] == cc.Pod) || (!c.IsSet("uts") && pod.SharesUTS()) { + namespaces["uts"] = fmt.Sprintf("container:%s", podInfraID) + } + return namespaces, nil +} + +// Parses CLI options related to container creation into a config which can be +// parsed into an OCI runtime spec +func ParseCreateOpts(ctx context.Context, c *cliconfig.PodmanCommand, runtime *libpod.Runtime, imageName string, data *inspect.ImageData) (*cc.CreateConfig, error) { + var ( + inputCommand, command []string + memoryLimit, memoryReservation, memorySwap, memoryKernel int64 + blkioWeight uint16 + namespaces map[string]string + ) + if c.IsSet("restart") { + return nil, errors.Errorf("--restart option is not supported.\nUse systemd unit files for restarting containers") + } + + idmappings, err := util.ParseIDMapping(c.StringSlice("uidmap"), c.StringSlice("gidmap"), c.String("subuidname"), c.String("subgidname")) + if err != nil { + return nil, err + } + + if c.String("mac-address") != "" { + return nil, errors.Errorf("--mac-address option not currently supported") + } + + imageID := "" + + inputCommand = c.InputArgs[1:] + if data != nil { + imageID = data.ID + } + + rootfs := "" + if c.Bool("rootfs") { + rootfs = c.InputArgs[0] + } + + sysctl, err := validateSysctl(c.StringSlice("sysctl")) + if err != nil { + return nil, errors.Wrapf(err, "invalid value for sysctl") + } + + if c.String("memory") != "" { + memoryLimit, err = units.RAMInBytes(c.String("memory")) + if err != nil { + return nil, errors.Wrapf(err, "invalid value for memory") + } + } + if c.String("memory-reservation") != "" { + memoryReservation, err = units.RAMInBytes(c.String("memory-reservation")) + if err != nil { + return nil, errors.Wrapf(err, "invalid value for memory-reservation") + } + } + if c.String("memory-swap") != "" { + memorySwap, err = units.RAMInBytes(c.String("memory-swap")) + if err != nil { + return nil, errors.Wrapf(err, "invalid value for memory-swap") + } + } + if c.String("kernel-memory") != "" { + memoryKernel, err = units.RAMInBytes(c.String("kernel-memory")) + if err != nil { + return nil, errors.Wrapf(err, "invalid value for kernel-memory") + } + } + if c.String("blkio-weight") != "" { + u, err := strconv.ParseUint(c.String("blkio-weight"), 10, 16) + if err != nil { + return nil, errors.Wrapf(err, "invalid value for blkio-weight") + } + blkioWeight = uint16(u) + } + var mountList []spec.Mount + if mountList, err = parseMounts(c.StringArray("mount")); err != nil { + return nil, err + } + + if err = parseVolumes(c.StringArray("volume")); err != nil { + return nil, err + } + + if err = parseVolumesFrom(c.StringSlice("volumes-from")); err != nil { + return nil, err + } + + tty := c.Bool("tty") + + if c.Flag("cpu-period").Changed && c.Flag("cpus").Changed { + return nil, errors.Errorf("--cpu-period and --cpus cannot be set together") + } + if c.Flag("cpu-quota").Changed && c.Flag("cpus").Changed { + return nil, errors.Errorf("--cpu-quota and --cpus cannot be set together") + } + + // EXPOSED PORTS + var portBindings map[nat.Port][]nat.PortBinding + if data != nil { + portBindings, err = cc.ExposedPorts(c.StringSlice("expose"), c.StringSlice("publish"), c.Bool("publish-all"), data.Config.ExposedPorts) + if err != nil { + return nil, err + } + } + + // Kernel Namespaces + // TODO Fix handling of namespace from pod + // Instead of integrating here, should be done in libpod + // However, that also involves setting up security opts + // when the pod's namespace is integrated + namespaceNet := c.String("network") + if c.Flag("net").Changed { + namespaceNet = c.String("net") + } + namespaces = map[string]string{ + "pid": c.String("pid"), + "net": namespaceNet, + "ipc": c.String("ipc"), + "user": c.String("userns"), + "uts": c.String("uts"), + } + + originalPodName := c.String("pod") + podName := strings.Replace(originalPodName, "new:", "", 1) + // after we strip out :new, make sure there is something left for a pod name + if len(podName) < 1 && c.IsSet("pod") { + return nil, errors.Errorf("new pod name must be at least one character") + } + if c.IsSet("pod") { + if strings.HasPrefix(originalPodName, "new:") { + if rootless.IsRootless() { + // To create a new pod, we must immediately create the userns. + became, ret, err := rootless.BecomeRootInUserNS() + if err != nil { + return nil, err + } + if became { + os.Exit(ret) + } + } + // pod does not exist; lets make it + var podOptions []libpod.PodCreateOption + podOptions = append(podOptions, libpod.WithPodName(podName), libpod.WithInfraContainer(), libpod.WithPodCgroups()) + if len(portBindings) > 0 { + ociPortBindings, err := cc.NatToOCIPortBindings(portBindings) + if err != nil { + return nil, err + } + podOptions = append(podOptions, libpod.WithInfraContainerPorts(ociPortBindings)) + } + + podNsOptions, err := GetNamespaceOptions(strings.Split(DefaultKernelNamespaces, ",")) + if err != nil { + return nil, err + } + podOptions = append(podOptions, podNsOptions...) + // make pod + pod, err := runtime.NewPod(ctx, podOptions...) + if err != nil { + return nil, err + } + logrus.Debugf("pod %s created by new container request", pod.ID()) + + // The container now cannot have port bindings; so we reset the map + portBindings = make(map[nat.Port][]nat.PortBinding) + } + namespaces, err = configurePod(c, runtime, namespaces, podName) + if err != nil { + return nil, err + } + } + + pidMode := ns.PidMode(namespaces["pid"]) + if !cc.Valid(string(pidMode), pidMode) { + return nil, errors.Errorf("--pid %q is not valid", c.String("pid")) + } + + usernsMode := ns.UsernsMode(namespaces["user"]) + if !cc.Valid(string(usernsMode), usernsMode) { + return nil, errors.Errorf("--userns %q is not valid", namespaces["user"]) + } + + utsMode := ns.UTSMode(namespaces["uts"]) + if !cc.Valid(string(utsMode), utsMode) { + return nil, errors.Errorf("--uts %q is not valid", namespaces["uts"]) + } + + ipcMode := ns.IpcMode(namespaces["ipc"]) + if !cc.Valid(string(ipcMode), ipcMode) { + return nil, errors.Errorf("--ipc %q is not valid", ipcMode) + } + + // Make sure if network is set to container namespace, port binding is not also being asked for + netMode := ns.NetworkMode(namespaces["net"]) + if netMode.IsContainer() { + if len(portBindings) > 0 { + return nil, errors.Errorf("cannot set port bindings on an existing container network namespace") + } + } + + // USER + user := c.String("user") + if user == "" { + if data == nil { + user = "0" + } else { + user = data.Config.User + } + } + + // STOP SIGNAL + stopSignal := syscall.SIGTERM + signalString := "" + if data != nil { + signalString = data.Config.StopSignal + } + if c.IsSet("stop-signal") { + signalString = c.String("stop-signal") + } + if signalString != "" { + stopSignal, err = signal.ParseSignal(signalString) + if err != nil { + return nil, err + } + } + + // ENVIRONMENT VARIABLES + env := defaultEnvVariables + if data != nil { + for _, e := range data.Config.Env { + split := strings.SplitN(e, "=", 2) + if len(split) > 1 { + env[split[0]] = split[1] + } else { + env[split[0]] = "" + } + } + } + if err := parse.ReadKVStrings(env, c.StringSlice("env-file"), c.StringArray("env")); err != nil { + return nil, errors.Wrapf(err, "unable to process environment variables") + } + + // LABEL VARIABLES + labels, err := GetAllLabels(c.StringSlice("label-file"), c.StringArray("label")) + if err != nil { + return nil, errors.Wrapf(err, "unable to process labels") + } + if data != nil { + for key, val := range data.Config.Labels { + if _, ok := labels[key]; !ok { + labels[key] = val + } + } + } + + // ANNOTATIONS + annotations := make(map[string]string) + // First, add our default annotations + annotations[ann.ContainerType] = "sandbox" + annotations[ann.TTY] = "false" + if tty { + annotations[ann.TTY] = "true" + } + if data != nil { + // Next, add annotations from the image + for key, value := range data.Annotations { + annotations[key] = value + } + } + // Last, add user annotations + for _, annotation := range c.StringSlice("annotation") { + splitAnnotation := strings.SplitN(annotation, "=", 2) + if len(splitAnnotation) < 2 { + return nil, errors.Errorf("Annotations must be formatted KEY=VALUE") + } + annotations[splitAnnotation[0]] = splitAnnotation[1] + } + + // WORKING DIRECTORY + workDir := "/" + if c.IsSet("workdir") || c.IsSet("w") { + workDir = c.String("workdir") + } else if data != nil && data.Config.WorkingDir != "" { + workDir = data.Config.WorkingDir + } + + entrypoint := configureEntrypoint(c, data) + // Build the command + // If we have an entry point, it goes first + if len(entrypoint) > 0 { + command = entrypoint + } + if len(inputCommand) > 0 { + // User command overrides data CMD + command = append(command, inputCommand...) + } else if data != nil && len(data.Config.Cmd) > 0 && !c.IsSet("entrypoint") { + // If not user command, add CMD + command = append(command, data.Config.Cmd...) + } + + if data != nil && len(command) == 0 { + return nil, errors.Errorf("No command specified on command line or as CMD or ENTRYPOINT in this image") + } + + // SHM Size + shmSize, err := units.FromHumanSize(c.String("shm-size")) + if err != nil { + return nil, errors.Wrapf(err, "unable to translate --shm-size") + } + + // Verify the additional hosts are in correct format + for _, host := range c.StringSlice("add-host") { + if _, err := parse.ValidateExtraHost(host); err != nil { + return nil, err + } + } + + // Check for . and dns-search domains + if util.StringInSlice(".", c.StringSlice("dns-search")) && len(c.StringSlice("dns-search")) > 1 { + return nil, errors.Errorf("cannot pass additional search domains when also specifying '.'") + } + + // Validate domains are good + for _, dom := range c.StringSlice("dns-search") { + if _, err := parse.ValidateDomain(dom); err != nil { + return nil, err + } + } + + var ImageVolumes map[string]struct{} + if data != nil && c.String("image-volume") != "ignore" { + ImageVolumes = data.Config.Volumes + } + + var imageVolType = map[string]string{ + "bind": "", + "tmpfs": "", + "ignore": "", + } + if _, ok := imageVolType[c.String("image-volume")]; !ok { + return nil, errors.Errorf("invalid image-volume type %q. Pick one of bind, tmpfs, or ignore", c.String("image-volume")) + } + + var systemd bool + if command != nil && c.Bool("systemd") && ((filepath.Base(command[0]) == "init") || (filepath.Base(command[0]) == "systemd")) { + systemd = true + if signalString == "" { + stopSignal, err = signal.ParseSignal("RTMIN+3") + if err != nil { + return nil, errors.Wrapf(err, "error parsing systemd signal") + } + } + } + // This is done because cobra cannot have two aliased flags. So we have to check + // both + network := c.String("network") + if c.Flag("net").Changed { + network = c.String("net") + } + + var memorySwappiness int64 + if c.Flags().Lookup("memory-swappiness") != nil { + memorySwappiness, _ = c.Flags().GetInt64("memory-swappiness") + } + config := &cc.CreateConfig{ + Runtime: runtime, + Annotations: annotations, + BuiltinImgVolumes: ImageVolumes, + ConmonPidFile: c.String("conmon-pidfile"), + ImageVolumeType: c.String("image-volume"), + CapAdd: c.StringSlice("cap-add"), + CapDrop: c.StringSlice("cap-drop"), + CgroupParent: c.String("cgroup-parent"), + Command: command, + Detach: c.Bool("detach"), + Devices: c.StringSlice("device"), + DNSOpt: c.StringSlice("dns-opt"), + DNSSearch: c.StringSlice("dns-search"), + DNSServers: c.StringSlice("dns"), + Entrypoint: entrypoint, + Env: env, + //ExposedPorts: ports, + GroupAdd: c.StringSlice("group-add"), + Hostname: c.String("hostname"), + HostAdd: c.StringSlice("add-host"), + IDMappings: idmappings, + Image: imageName, + ImageID: imageID, + Interactive: c.Bool("interactive"), + //IP6Address: c.String("ipv6"), // Not implemented yet - needs CNI support for static v6 + IPAddress: c.String("ip"), + Labels: labels, + //LinkLocalIP: c.StringSlice("link-local-ip"), // Not implemented yet + LogDriver: c.String("log-driver"), + LogDriverOpt: c.StringSlice("log-opt"), + MacAddress: c.String("mac-address"), + Name: c.String("name"), + Network: network, + //NetworkAlias: c.StringSlice("network-alias"), // Not implemented - does this make sense in Podman? + IpcMode: ipcMode, + NetMode: netMode, + UtsMode: utsMode, + PidMode: pidMode, + Pod: podName, + Privileged: c.Bool("privileged"), + Publish: c.StringSlice("publish"), + PublishAll: c.Bool("publish-all"), + PortBindings: portBindings, + Quiet: c.Bool("quiet"), + ReadOnlyRootfs: c.Bool("read-only"), + Resources: cc.CreateResourceConfig{ + BlkioWeight: blkioWeight, + BlkioWeightDevice: c.StringSlice("blkio-weight-device"), + CPUShares: c.Uint64("cpu-shares"), + CPUPeriod: c.Uint64("cpu-period"), + CPUsetCPUs: c.String("cpuset-cpus"), + CPUsetMems: c.String("cpuset-mems"), + CPUQuota: c.Int64("cpu-quota"), + CPURtPeriod: c.Uint64("cpu-rt-period"), + CPURtRuntime: c.Int64("cpu-rt-runtime"), + CPUs: c.Float64("cpus"), + DeviceReadBps: c.StringSlice("device-read-bps"), + DeviceReadIOps: c.StringSlice("device-read-iops"), + DeviceWriteBps: c.StringSlice("device-write-bps"), + DeviceWriteIOps: c.StringSlice("device-write-iops"), + DisableOomKiller: c.Bool("oom-kill-disable"), + ShmSize: shmSize, + Memory: memoryLimit, + MemoryReservation: memoryReservation, + MemorySwap: memorySwap, + MemorySwappiness: int(memorySwappiness), + KernelMemory: memoryKernel, + OomScoreAdj: c.Int("oom-score-adj"), + PidsLimit: c.Int64("pids-limit"), + Ulimit: c.StringSlice("ulimit"), + }, + Rm: c.Bool("rm"), + StopSignal: stopSignal, + StopTimeout: c.Uint("stop-timeout"), + Sysctl: sysctl, + Systemd: systemd, + Tmpfs: c.StringSlice("tmpfs"), + Tty: tty, + User: user, + UsernsMode: usernsMode, + Mounts: mountList, + Volumes: c.StringArray("volume"), + WorkDir: workDir, + Rootfs: rootfs, + VolumesFrom: c.StringSlice("volumes-from"), + Syslog: c.GlobalFlags.Syslog, + } + if c.Bool("init") { + initPath := c.String("init-path") + if initPath == "" { + initPath = runtime.GetConfig().InitPath + } + if err := config.AddContainerInitBinary(initPath); err != nil { + return nil, err + } + } + + if config.Privileged { + config.LabelOpts = label.DisableSecOpt() + } else { + if err := parseSecurityOpt(config, c.StringArray("security-opt")); err != nil { + return nil, err + } + } + config.SecurityOpts = c.StringArray("security-opt") + warnings, err := verifyContainerResources(config, false) + if err != nil { + return nil, err + } + for _, warning := range warnings { + fmt.Fprintln(os.Stderr, warning) + } + return config, nil +} + +type namespace interface { + IsContainer() bool + Container() string +} + +func joinOrCreateRootlessUserNamespace(createConfig *cc.CreateConfig, runtime *libpod.Runtime) (bool, int, error) { + if os.Geteuid() == 0 { + return false, 0, nil + } + + if createConfig.Pod != "" { + pod, err := runtime.LookupPod(createConfig.Pod) + if err != nil { + return false, -1, err + } + inspect, err := pod.Inspect() + for _, ctr := range inspect.Containers { + prevCtr, err := runtime.LookupContainer(ctr.ID) + if err != nil { + return false, -1, err + } + s, err := prevCtr.State() + if err != nil { + return false, -1, err + } + if s != libpod.ContainerStateRunning && s != libpod.ContainerStatePaused { + continue + } + data, err := ioutil.ReadFile(prevCtr.Config().ConmonPidFile) + if err != nil { + return false, -1, errors.Wrapf(err, "cannot read conmon PID file %q", prevCtr.Config().ConmonPidFile) + } + conmonPid, err := strconv.Atoi(string(data)) + if err != nil { + return false, -1, errors.Wrapf(err, "cannot parse PID %q", data) + } + return rootless.JoinDirectUserAndMountNS(uint(conmonPid)) + } + } + + namespacesStr := []string{string(createConfig.IpcMode), string(createConfig.NetMode), string(createConfig.UsernsMode), string(createConfig.PidMode), string(createConfig.UtsMode)} + for _, i := range namespacesStr { + if cc.IsNS(i) { + return rootless.JoinNSPath(cc.NS(i)) + } + } + + namespaces := []namespace{createConfig.IpcMode, createConfig.NetMode, createConfig.UsernsMode, createConfig.PidMode, createConfig.UtsMode} + for _, i := range namespaces { + if i.IsContainer() { + ctr, err := runtime.LookupContainer(i.Container()) + if err != nil { + return false, -1, err + } + pid, err := ctr.PID() + if err != nil { + return false, -1, err + } + if pid == 0 { + if createConfig.Pod != "" { + continue + } + return false, -1, errors.Errorf("dependency container %s is not running", ctr.ID()) + } + return rootless.JoinNS(uint(pid), 0) + } + } + return rootless.BecomeRootInUserNS() +} + +func CreateContainerFromCreateConfig(r *libpod.Runtime, createConfig *cc.CreateConfig, ctx context.Context, pod *libpod.Pod) (*libpod.Container, error) { + runtimeSpec, err := cc.CreateConfigToOCISpec(createConfig) + if err != nil { + return nil, err + } + + options, err := createConfig.GetContainerCreateOptions(r, pod) + if err != nil { + return nil, err + } + became, ret, err := joinOrCreateRootlessUserNamespace(createConfig, r) + if err != nil { + return nil, err + } + if became { + os.Exit(ret) + } + + ctr, err := r.NewContainer(ctx, runtimeSpec, options...) + if err != nil { + return nil, err + } + + createConfigJSON, err := json.Marshal(createConfig) + if err != nil { + return nil, err + } + if err := ctr.AddArtifact("create-config", createConfigJSON); err != nil { + return nil, err + } + return ctr, nil +} + +var defaultEnvVariables = map[string]string{ + "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "TERM": "xterm", +} + +func makeHealthCheckFromCli(c *cliconfig.PodmanCommand) (*manifest.Schema2HealthConfig, error) { + inCommand := c.String("healthcheck-command") + inInterval := c.String("healthcheck-interval") + inRetries := c.Uint("healthcheck-retries") + inTimeout := c.String("healthcheck-timeout") + inStartPeriod := c.String("healthcheck-start-period") + + // Every healthcheck requires a command + if len(inCommand) == 0 { + return nil, errors.New("Must define a healthcheck command for all healthchecks") + } + + cmd, err := shlex.Split(inCommand) + if err != nil { + return nil, errors.Wrap(err, "failed to parse healthcheck command") + } + hc := manifest.Schema2HealthConfig{ + Test: cmd, + } + + if inInterval == "disable" { + inInterval = "0" + } + intervalDuration, err := time.ParseDuration(inInterval) + if err != nil { + return nil, errors.Wrapf(err, "invalid healthcheck-interval %s ", inInterval) + } + + hc.Interval = intervalDuration + + if inRetries < 1 { + return nil, errors.New("healthcheck-retries must be greater than 0.") + } + hc.Retries = int(inRetries) + timeoutDuration, err := time.ParseDuration(inTimeout) + if err != nil { + return nil, errors.Wrapf(err, "invalid healthcheck-timeout %s", inTimeout) + } + if timeoutDuration < time.Duration(time.Second*1) { + return nil, errors.New("healthcheck-timeout must be at least 1 second") + } + hc.Timeout = timeoutDuration + + startPeriodDuration, err := time.ParseDuration(inStartPeriod) + if err != nil { + return nil, errors.Wrapf(err, "invalid healthcheck-start-period %s", inStartPeriod) + } + if startPeriodDuration < time.Duration(0) { + return nil, errors.New("healthcheck-start-period must be a 0 seconds or greater") + } + hc.StartPeriod = startPeriodDuration + + return &hc, nil +} diff --git a/cmd/podman/create_cli.go b/cmd/podman/shared/create_cli.go index ae0549687..4f9cb1699 100644 --- a/cmd/podman/create_cli.go +++ b/cmd/podman/shared/create_cli.go @@ -1,4 +1,4 @@ -package main +package shared import ( "fmt" @@ -6,6 +6,7 @@ import ( "path/filepath" "strings" + "github.com/containers/libpod/cmd/podman/shared/parse" cc "github.com/containers/libpod/pkg/spec" "github.com/containers/libpod/pkg/sysinfo" "github.com/docker/go-units" @@ -19,9 +20,10 @@ const ( linuxMinMemory = 4194304 ) -func getAllLabels(labelFile, inputLabels []string) (map[string]string, error) { +// GetAllLabels ... +func GetAllLabels(labelFile, inputLabels []string) (map[string]string, error) { labels := make(map[string]string) - labelErr := readKVStrings(labels, labelFile, inputLabels) + labelErr := parse.ReadKVStrings(labels, labelFile, inputLabels) if labelErr != nil { return labels, errors.Wrapf(labelErr, "unable to process labels from --label and label-file") } @@ -149,12 +151,12 @@ func parseMounts(mounts []string) ([]spec.Mount, error) { if mountInfo.Type == "tmpfs" { return nil, errors.Errorf("cannot use src= on a tmpfs file system") } - if err := validateVolumeHostDir(kv[1]); err != nil { + if err := ValidateVolumeHostDir(kv[1]); err != nil { return nil, err } mountInfo.Source = kv[1] case "target", "dst", "destination": - if err := validateVolumeCtrDir(kv[1]); err != nil { + if err := ValidateVolumeCtrDir(kv[1]); err != nil { return nil, err } mountInfo.Destination = kv[1] @@ -173,10 +175,10 @@ func parseVolumes(volumes []string) error { if len(arr) < 2 { return errors.Errorf("incorrect volume format %q, should be host-dir:ctr-dir[:option]", volume) } - if err := validateVolumeHostDir(arr[0]); err != nil { + if err := ValidateVolumeHostDir(arr[0]); err != nil { return err } - if err := validateVolumeCtrDir(arr[1]); err != nil { + if err := ValidateVolumeCtrDir(arr[1]); err != nil { return err } if len(arr) > 2 { @@ -203,7 +205,8 @@ func parseVolumesFrom(volumesFrom []string) error { return nil } -func validateVolumeHostDir(hostDir string) error { +// ValidateVolumeHostDir ... +func ValidateVolumeHostDir(hostDir string) error { if len(hostDir) == 0 { return errors.Errorf("host directory cannot be empty") } @@ -217,7 +220,8 @@ func validateVolumeHostDir(hostDir string) error { return nil } -func validateVolumeCtrDir(ctrDir string) error { +// ValidateVolumeCtrDir ... +func ValidateVolumeCtrDir(ctrDir string) error { if len(ctrDir) == 0 { return errors.Errorf("container directory cannot be empty") } diff --git a/cmd/podman/create_cli_test.go b/cmd/podman/shared/create_cli_test.go index 9db007ff3..fea1a2390 100644 --- a/cmd/podman/create_cli_test.go +++ b/cmd/podman/shared/create_cli_test.go @@ -1,4 +1,4 @@ -package main +package shared import ( "io/ioutil" @@ -42,20 +42,20 @@ func TestValidateSysctlBadSysctl(t *testing.T) { func TestGetAllLabels(t *testing.T) { fileLabels := []string{} - labels, _ := getAllLabels(fileLabels, Var1) + labels, _ := GetAllLabels(fileLabels, Var1) assert.Equal(t, len(labels), 2) } func TestGetAllLabelsBadKeyValue(t *testing.T) { inLabels := []string{"=badValue", "="} fileLabels := []string{} - _, err := getAllLabels(fileLabels, inLabels) + _, err := GetAllLabels(fileLabels, inLabels) assert.Error(t, err, assert.AnError) } func TestGetAllLabelsBadLabelFile(t *testing.T) { fileLabels := []string{"/foobar5001/be"} - _, err := getAllLabels(fileLabels, Var1) + _, err := GetAllLabels(fileLabels, Var1) assert.Error(t, err, assert.AnError) } @@ -65,6 +65,6 @@ func TestGetAllLabelsFile(t *testing.T) { defer os.Remove(tFile) assert.NoError(t, err) fileLabels := []string{tFile} - result, _ := getAllLabels(fileLabels, Var1) + result, _ := GetAllLabels(fileLabels, Var1) assert.Equal(t, len(result), 3) } diff --git a/cmd/podman/shared/events.go b/cmd/podman/shared/events.go new file mode 100644 index 000000000..c62044271 --- /dev/null +++ b/cmd/podman/shared/events.go @@ -0,0 +1,115 @@ +package shared + +import ( + "fmt" + "strings" + "time" + + "github.com/containers/libpod/libpod/events" + "github.com/containers/libpod/pkg/util" + "github.com/pkg/errors" +) + +func generateEventFilter(filter, filterValue string) (func(e *events.Event) bool, error) { + switch strings.ToUpper(filter) { + case "CONTAINER": + return func(e *events.Event) bool { + if e.Type != events.Container { + return false + } + if e.Name == filterValue { + return true + } + return strings.HasPrefix(e.ID, filterValue) + }, nil + case "EVENT", "STATUS": + return func(e *events.Event) bool { + return fmt.Sprintf("%s", e.Status) == filterValue + }, nil + case "IMAGE": + return func(e *events.Event) bool { + if e.Type != events.Image { + return false + } + if e.Name == filterValue { + return true + } + return strings.HasPrefix(e.ID, filterValue) + }, nil + case "POD": + return func(e *events.Event) bool { + if e.Type != events.Pod { + return false + } + if e.Name == filterValue { + return true + } + return strings.HasPrefix(e.ID, filterValue) + }, nil + case "VOLUME": + return func(e *events.Event) bool { + if e.Type != events.Volume { + return false + } + return strings.HasPrefix(e.ID, filterValue) + }, nil + case "TYPE": + return func(e *events.Event) bool { + return fmt.Sprintf("%s", e.Type) == filterValue + }, nil + } + return nil, errors.Errorf("%s is an invalid filter", filter) +} + +func generateEventSinceOption(timeSince time.Time) func(e *events.Event) bool { + return func(e *events.Event) bool { + return e.Time.After(timeSince) + } +} + +func generateEventUntilOption(timeUntil time.Time) func(e *events.Event) bool { + return func(e *events.Event) bool { + return e.Time.Before(timeUntil) + + } +} + +func parseFilter(filter string) (string, string, error) { + filterSplit := strings.Split(filter, "=") + if len(filterSplit) != 2 { + return "", "", errors.Errorf("%s is an invalid filter", filter) + } + return filterSplit[0], filterSplit[1], nil +} + +func GenerateEventOptions(filters []string, since, until string) ([]events.EventFilter, error) { + var options []events.EventFilter + for _, filter := range filters { + key, val, err := parseFilter(filter) + if err != nil { + return nil, err + } + funcFilter, err := generateEventFilter(key, val) + if err != nil { + return nil, err + } + options = append(options, funcFilter) + } + + if len(since) > 0 { + timeSince, err := util.ParseInputTime(since) + if err != nil { + return nil, errors.Wrapf(err, "unable to convert since time of %s", since) + } + options = append(options, generateEventSinceOption(timeSince)) + } + + if len(until) > 0 { + timeUntil, err := util.ParseInputTime(until) + if err != nil { + return nil, errors.Wrapf(err, "unable to convert until time of %s", until) + } + options = append(options, generateEventUntilOption(timeUntil)) + } + return options, nil +} diff --git a/cmd/podman/parse.go b/cmd/podman/shared/parse/parse.go index 2e4959656..a3751835b 100644 --- a/cmd/podman/parse.go +++ b/cmd/podman/shared/parse/parse.go @@ -1,7 +1,7 @@ //nolint // most of these validate and parse functions have been taken from projectatomic/docker // and modified for cri-o -package main +package parse import ( "bufio" @@ -50,7 +50,7 @@ var ( // validateExtraHost validates that the specified string is a valid extrahost and returns it. // ExtraHost is in the form of name:ip where the ip has to be a valid ip (ipv4 or ipv6). // for add-host flag -func validateExtraHost(val string) (string, error) { //nolint +func ValidateExtraHost(val string) (string, error) { //nolint // allow for IPv6 addresses in extra hosts by only splitting on first ":" arr := strings.SplitN(val, ":", 2) if len(arr) != 2 || len(arr[0]) == 0 { @@ -140,10 +140,10 @@ func validateDNSSearch(val string) (string, error) { //nolint if val = strings.Trim(val, " "); val == "." { return val, nil } - return validateDomain(val) + return ValidateDomain(val) } -func validateDomain(val string) (string, error) { +func ValidateDomain(val string) (string, error) { if alphaRegexp.FindString(val) == "" { return "", fmt.Errorf("%s is not a valid domain", val) } @@ -181,7 +181,7 @@ func doesEnvExist(name string) bool { // reads a file of line terminated key=value pairs, and overrides any keys // present in the file with additional pairs specified in the override parameter // for env-file and labels-file flags -func readKVStrings(env map[string]string, files []string, override []string) error { +func ReadKVStrings(env map[string]string, files []string, override []string) error { for _, ef := range files { if err := parseEnvFile(env, ef); err != nil { return err @@ -494,9 +494,9 @@ func stringSlicetoUint32Slice(inputSlice []string) ([]uint32, error) { return outputSlice, nil } -// validateFileName returns an error if filename contains ":" +// ValidateFileName returns an error if filename contains ":" // as it is currently not supported -func validateFileName(filename string) error { +func ValidateFileName(filename string) error { if strings.Contains(filename, ":") { return errors.Errorf("invalid filename (should not contain ':') %q", filename) } diff --git a/cmd/podman/shared/pod.go b/cmd/podman/shared/pod.go index 5f65c40ac..4d936d61c 100644 --- a/cmd/podman/shared/pod.go +++ b/cmd/podman/shared/pod.go @@ -136,3 +136,5 @@ func CreatePortBindings(ports []string) ([]ocicni.PortMapping, error) { } return portBindings, nil } + +var DefaultKernelNamespaces = "cgroup,ipc,net,uts" diff --git a/cmd/podman/sign.go b/cmd/podman/sign.go index 2cf228d01..06418e4a5 100644 --- a/cmd/podman/sign.go +++ b/cmd/podman/sign.go @@ -22,7 +22,7 @@ import ( var ( signCommand cliconfig.SignValues - signDescription = "Create a signature file that can be used later to verify the image" + signDescription = "Create a signature file that can be used later to verify the image." _signCommand = &cobra.Command{ Use: "sign [flags] IMAGE [IMAGE...]", Short: "Sign an image", @@ -39,6 +39,7 @@ var ( func init() { signCommand.Command = _signCommand + signCommand.SetHelpTemplate(HelpTemplate()) signCommand.SetUsageTemplate(UsageTemplate()) flags := signCommand.Flags() flags.StringVarP(&signCommand.Directory, "directory", "d", "", "Define an alternate directory to store signatures") diff --git a/cmd/podman/start.go b/cmd/podman/start.go index 3ce04ea79..cf406cf66 100644 --- a/cmd/podman/start.go +++ b/cmd/podman/start.go @@ -15,11 +15,8 @@ import ( var ( startCommand cliconfig.StartValues - startDescription = ` - podman start + startDescription = `Starts one or more containers. The container name or ID can be used.` - 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", @@ -37,13 +34,14 @@ var ( func init() { startCommand.Command = _startCommand + startCommand.SetHelpTemplate(HelpTemplate()) startCommand.SetUsageTemplate(UsageTemplate()) flags := startCommand.Flags() flags.BoolVarP(&startCommand.Attach, "attach", "a", false, "Attach container's STDOUT and STDERR") flags.StringVar(&startCommand.DetachKeys, "detach-keys", "", "Override the key sequence for detaching a container. Format is a single character [a-Z] or ctrl-<value> where <value> is one of: a-z, @, ^, [, , or _") flags.BoolVarP(&startCommand.Interactive, "interactive", "i", false, "Keep STDIN open even if not attached") flags.BoolVarP(&startCommand.Latest, "latest", "l", false, "Act on the latest container podman is aware of") - flags.BoolVar(&startCommand.SigProxy, "sig-proxy", true, "Proxy received signals to the process (default true if attaching, false otherwise)") + flags.BoolVar(&startCommand.SigProxy, "sig-proxy", false, "Proxy received signals to the process (default true if attaching, false otherwise)") markFlagHiddenForRemoteClient("latest", flags) } @@ -64,14 +62,10 @@ func startCmd(c *cliconfig.StartValues) error { return errors.Errorf("you cannot start and attach multiple containers at once") } - sigProxy := c.SigProxy + sigProxy := c.SigProxy || attach if sigProxy && !attach { - if c.Flag("sig-proxy").Changed { - return errors.Wrapf(libpod.ErrInvalidArg, "you cannot use sig-proxy without --attach") - } else { - sigProxy = false - } + return errors.Wrapf(libpod.ErrInvalidArg, "you cannot use sig-proxy without --attach") } runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) diff --git a/cmd/podman/stats.go b/cmd/podman/stats.go index dcb274471..d379dbad7 100644 --- a/cmd/podman/stats.go +++ b/cmd/podman/stats.go @@ -8,8 +8,8 @@ import ( "time" tm "github.com/buger/goterm" + "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/libpod/libpod" "github.com/docker/go-units" @@ -31,10 +31,10 @@ type statsOutputParams struct { var ( statsCommand cliconfig.StatsValues - statsDescription = "display a live stream of one or more containers' resource usage statistics" + statsDescription = "Display percentage of CPU, memory, network I/O, block I/O and PIDs for one or more containers." _statsCommand = &cobra.Command{ Use: "stats [flags] CONTAINER [CONTAINER...]", - Short: "Display percentage of CPU, memory, network I/O, block I/O and PIDs for one or more containers", + Short: "Display a live stream of container resource usage statistics", Long: statsDescription, RunE: func(cmd *cobra.Command, args []string) error { statsCommand.InputArgs = args @@ -52,6 +52,7 @@ var ( func init() { statsCommand.Command = _statsCommand + statsCommand.SetHelpTemplate(HelpTemplate()) statsCommand.SetUsageTemplate(UsageTemplate()) flags := statsCommand.Flags() flags.BoolVarP(&statsCommand.All, "all", "a", false, "Show all containers. Only running containers are shown by default. The default is false") diff --git a/cmd/podman/stop.go b/cmd/podman/stop.go index ab9a2cf38..2a1470ad0 100644 --- a/cmd/podman/stop.go +++ b/cmd/podman/stop.go @@ -2,27 +2,22 @@ package main import ( "fmt" + "reflect" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/libpodruntime" - "github.com/containers/libpod/cmd/podman/shared" "github.com/containers/libpod/libpod" + "github.com/containers/libpod/pkg/adapter" "github.com/containers/libpod/pkg/rootless" - opentracing "github.com/opentracing/opentracing-go" + "github.com/opentracing/opentracing-go" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" ) var ( stopCommand cliconfig.StopValues - stopDescription = ` - podman stop + stopDescription = `Stops one or more running containers. The container name or ID can be used. - Stops one or more running containers. The container name or ID can be used. - A timeout to forcibly stop the container can also be set but defaults to 10 - seconds otherwise. -` + A timeout to forcibly stop the container can also be set but defaults to 10 seconds otherwise.` _stopCommand = &cobra.Command{ Use: "stop [flags] CONTAINER [CONTAINER...]", Short: "Stop one or more containers", @@ -43,6 +38,7 @@ var ( func init() { stopCommand.Command = _stopCommand + stopCommand.SetHelpTemplate(HelpTemplate()) stopCommand.SetUsageTemplate(UsageTemplate()) flags := stopCommand.Flags() flags.BoolVarP(&stopCommand.All, "all", "a", false, "Stop all running containers") @@ -52,63 +48,43 @@ func init() { markFlagHiddenForRemoteClient("latest", flags) } +// stopCmd stops a container or containers func stopCmd(c *cliconfig.StopValues) error { + if c.Flag("timeout").Changed && c.Flag("time").Changed { + return errors.New("the --timeout and --time flags are mutually exclusive") + } + if c.Bool("trace") { span, _ := opentracing.StartSpanFromContext(Ctx, "stopCmd") defer span.Finish() } rootless.SetSkipStorageSetup(true) - runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) + runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { return errors.Wrapf(err, "could not get runtime") } defer runtime.Shutdown(false) - containers, err := getAllOrLatestContainers(&c.PodmanCommand, runtime, libpod.ContainerStateRunning, "running") + ok, failures, err := runtime.StopContainers(getContext(), c) if err != nil { - if len(containers) == 0 { - return err - } - fmt.Println(err.Error()) + return err } - if c.Flag("timeout").Changed && c.Flag("time").Changed { - return errors.New("the --timeout and --time flags are mutually exclusive") + for _, id := range ok { + fmt.Println(id) } - var stopFuncs []shared.ParallelWorkerInput - for _, ctr := range containers { - con := ctr - var stopTimeout uint - if c.Flag("timeout").Changed || c.Flag("time").Changed { - stopTimeout = c.Timeout - } else { - stopTimeout = ctr.StopTimeout() - logrus.Debugf("Set timeout to container %s default (%d)", ctr.ID(), stopTimeout) - } - f := func() error { - if err := con.StopWithTimeout(stopTimeout); err != nil { - if errors.Cause(err) == libpod.ErrCtrStopped { - logrus.Debugf("Container %s already stopped", con.ID()) - return nil - } - return err - } - return nil - } - stopFuncs = append(stopFuncs, shared.ParallelWorkerInput{ - ContainerID: con.ID(), - ParallelFunc: f, - }) - } + if len(failures) > 0 { + keys := reflect.ValueOf(failures).MapKeys() + lastKey := keys[len(keys)-1].String() + lastErr := failures[lastKey] + delete(failures, lastKey) - maxWorkers := shared.Parallelize("stop") - if c.GlobalIsSet("max-workers") { - maxWorkers = c.GlobalFlags.MaxWorks + for _, err := range failures { + outputError(err) + } + return lastErr } - logrus.Debugf("Setting maximum workers to %d", maxWorkers) - - stopErrors, errCount := shared.ParallelExecuteWorkerPool(maxWorkers, stopFuncs) - return printParallelOutput(stopErrors, errCount) + return nil } diff --git a/cmd/podman/system.go b/cmd/podman/system.go index 741b79da5..528a594de 100644 --- a/cmd/podman/system.go +++ b/cmd/podman/system.go @@ -13,6 +13,7 @@ var ( Use: "system", Short: "Manage podman", Long: systemDescription, + RunE: commandRunE(), }, } ) diff --git a/cmd/podman/system_df.go b/cmd/podman/system_df.go new file mode 100644 index 000000000..183c5a7dd --- /dev/null +++ b/cmd/podman/system_df.go @@ -0,0 +1,639 @@ +package main + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "github.com/containers/buildah/pkg/formats" + "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/cmd/podman/libpodruntime" + "github.com/containers/libpod/libpod" + "github.com/containers/libpod/libpod/image" + units "github.com/docker/go-units" + "github.com/pkg/errors" + "github.com/sirupsen/logrus" + "github.com/spf13/cobra" +) + +var ( + dfSystemCommand cliconfig.SystemDfValues + dfSystemDescription = ` + podman system df + + Show podman disk usage + ` + _dfSystemCommand = &cobra.Command{ + Use: "df", + Short: "Show podman disk usage", + Long: dfSystemDescription, + RunE: func(cmd *cobra.Command, args []string) error { + dfSystemCommand.GlobalFlags = MainGlobalOpts + return dfSystemCmd(&dfSystemCommand) + }, + } +) + +type dfMetaData struct { + images []*image.Image + containers []*libpod.Container + activeContainers map[string]*libpod.Container + imagesUsedbyCtrMap map[string][]*libpod.Container + imagesUsedbyActiveCtr map[string][]*libpod.Container + volumes []*libpod.Volume + volumeUsedByContainerMap map[string][]*libpod.Container +} + +type systemDfDiskUsage struct { + Type string + Total int + Active int + Size string + Reclaimable string +} + +type imageVerboseDiskUsage struct { + Repository string + Tag string + ImageID string + Created string + Size string + SharedSize string + UniqueSize string + Containers int +} + +type containerVerboseDiskUsage struct { + ContainerID string + Image string + Command string + LocalVolumes int + Size string + Created string + Status string + Names string +} + +type volumeVerboseDiskUsage struct { + VolumeName string + Links int + Size string +} + +const systemDfDefaultFormat string = "table {{.Type}}\t{{.Total}}\t{{.Active}}\t{{.Size}}\t{{.Reclaimable}}" + +func init() { + dfSystemCommand.Command = _dfSystemCommand + dfSystemCommand.SetUsageTemplate(UsageTemplate()) + flags := dfSystemCommand.Flags() + flags.BoolVarP(&dfSystemCommand.Verbose, "verbose", "v", false, "Show detailed information on space usage") + flags.StringVar(&dfSystemCommand.Format, "format", "", "Pretty-print images using a Go template") +} + +func dfSystemCmd(c *cliconfig.SystemDfValues) error { + runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) + if err != nil { + return errors.Wrapf(err, "Could not get runtime") + } + defer runtime.Shutdown(false) + + ctx := getContext() + + metaData, err := getDfMetaData(ctx, runtime) + if err != nil { + return errors.Wrapf(err, "error getting disk usage data") + } + + if c.Verbose { + err := verboseOutput(ctx, metaData) + if err != nil { + return err + } + return nil + } + + systemDfDiskUsages, err := getDiskUsage(ctx, runtime, metaData) + if err != nil { + return errors.Wrapf(err, "error getting output of system df") + } + format := systemDfDefaultFormat + if c.Format != "" { + format = strings.Replace(c.Format, `\t`, "\t", -1) + } + generateSysDfOutput(systemDfDiskUsages, format) + return nil +} + +func generateSysDfOutput(systemDfDiskUsages []systemDfDiskUsage, format string) { + var systemDfHeader = map[string]string{ + "Type": "TYPE", + "Total": "TOTAL", + "Active": "ACTIVE", + "Size": "SIZE", + "Reclaimable": "RECLAIMABLE", + } + out := formats.StdoutTemplateArray{Output: systemDfDiskUsageToGeneric(systemDfDiskUsages), Template: format, Fields: systemDfHeader} + formats.Writer(out).Out() +} + +func getDiskUsage(ctx context.Context, runtime *libpod.Runtime, metaData dfMetaData) ([]systemDfDiskUsage, error) { + imageDiskUsage, err := getImageDiskUsage(ctx, metaData.images, metaData.imagesUsedbyCtrMap, metaData.imagesUsedbyActiveCtr) + if err != nil { + return nil, errors.Wrapf(err, "error getting disk usage of images") + } + containerDiskUsage, err := getContainerDiskUsage(metaData.containers, metaData.activeContainers) + if err != nil { + return nil, errors.Wrapf(err, "error getting disk usage of containers") + } + volumeDiskUsage, err := getVolumeDiskUsage(metaData.volumes, metaData.volumeUsedByContainerMap) + if err != nil { + return nil, errors.Wrapf(err, "error getting disk usage of volumess") + } + + systemDfDiskUsages := []systemDfDiskUsage{imageDiskUsage, containerDiskUsage, volumeDiskUsage} + return systemDfDiskUsages, nil +} + +func getDfMetaData(ctx context.Context, runtime *libpod.Runtime) (dfMetaData, error) { + var metaData dfMetaData + images, err := runtime.ImageRuntime().GetImages() + if err != nil { + return metaData, errors.Wrapf(err, "unable to get images") + } + containers, err := runtime.GetAllContainers() + if err != nil { + return metaData, errors.Wrapf(err, "error getting all containers") + } + volumes, err := runtime.GetAllVolumes() + if err != nil { + return metaData, errors.Wrap(err, "error getting all volumes") + } + activeContainers, err := activeContainers(containers) + if err != nil { + return metaData, errors.Wrapf(err, "error getting active containers") + } + imagesUsedbyCtrMap, imagesUsedbyActiveCtr, err := imagesUsedbyCtr(containers, activeContainers) + if err != nil { + return metaData, errors.Wrapf(err, "error getting getting images used by containers") + } + metaData = dfMetaData{ + images: images, + containers: containers, + activeContainers: activeContainers, + imagesUsedbyCtrMap: imagesUsedbyCtrMap, + imagesUsedbyActiveCtr: imagesUsedbyActiveCtr, + volumes: volumes, + volumeUsedByContainerMap: volumeUsedByContainer(containers), + } + return metaData, nil +} + +func imageUniqueSize(ctx context.Context, images []*image.Image) (map[string]uint64, error) { + imgUniqueSizeMap := make(map[string]uint64) + for _, img := range images { + parentImg := img + for { + next, err := parentImg.GetParent() + if err != nil { + return nil, errors.Wrapf(err, "error getting parent of image %s", parentImg.ID()) + } + if next == nil { + break + } + parentImg = next + } + imgSize, err := img.Size(ctx) + if err != nil { + return nil, err + } + if img.ID() == parentImg.ID() { + imgUniqueSizeMap[img.ID()] = *imgSize + } else { + parentImgSize, err := parentImg.Size(ctx) + if err != nil { + return nil, errors.Wrapf(err, "error getting size of parent image %s", parentImg.ID()) + } + imgUniqueSizeMap[img.ID()] = *imgSize - *parentImgSize + } + } + return imgUniqueSizeMap, nil +} + +func getImageDiskUsage(ctx context.Context, images []*image.Image, imageUsedbyCintainerMap map[string][]*libpod.Container, imageUsedbyActiveContainerMap map[string][]*libpod.Container) (systemDfDiskUsage, error) { + var ( + numberOfImages int + sumSize uint64 + numberOfActiveImages int + unreclaimableSize uint64 + imageDiskUsage systemDfDiskUsage + reclaimableStr string + ) + + imgUniqueSizeMap, err := imageUniqueSize(ctx, images) + if err != nil { + return imageDiskUsage, errors.Wrapf(err, "error getting unique size of images") + } + + for _, img := range images { + + unreclaimableSize += imageUsedSize(img, imgUniqueSizeMap, imageUsedbyCintainerMap, imageUsedbyActiveContainerMap) + + isParent, err := img.IsParent() + if err != nil { + return imageDiskUsage, err + } + parent, err := img.GetParent() + if err != nil { + return imageDiskUsage, errors.Wrapf(err, "error getting parent of image %s", img.ID()) + } + if isParent && parent != nil { + continue + } + numberOfImages++ + if _, isActive := imageUsedbyCintainerMap[img.ID()]; isActive { + numberOfActiveImages++ + } + + if !isParent { + size, err := img.Size(ctx) + if err != nil { + return imageDiskUsage, errors.Wrapf(err, "error getting disk usage of image %s", img.ID()) + } + sumSize += *size + } + + } + sumSizeStr := units.HumanSizeWithPrecision(float64(sumSize), 3) + reclaimable := sumSize - unreclaimableSize + if sumSize != 0 { + reclaimableStr = fmt.Sprintf("%s (%v%%)", units.HumanSizeWithPrecision(float64(reclaimable), 3), 100*reclaimable/sumSize) + } else { + reclaimableStr = fmt.Sprintf("%s (%v%%)", units.HumanSizeWithPrecision(float64(reclaimable), 3), 0) + } + imageDiskUsage = systemDfDiskUsage{ + Type: "Images", + Total: numberOfImages, + Active: numberOfActiveImages, + Size: sumSizeStr, + Reclaimable: reclaimableStr, + } + return imageDiskUsage, nil +} + +func imageUsedSize(img *image.Image, imgUniqueSizeMap map[string]uint64, imageUsedbyCintainerMap map[string][]*libpod.Container, imageUsedbyActiveContainerMap map[string][]*libpod.Container) uint64 { + var usedSize uint64 + imgUnique := imgUniqueSizeMap[img.ID()] + if _, isCtrActive := imageUsedbyActiveContainerMap[img.ID()]; isCtrActive { + return imgUnique + } + containers := imageUsedbyCintainerMap[img.ID()] + for _, ctr := range containers { + if len(ctr.UserVolumes()) > 0 { + usedSize += imgUnique + return usedSize + } + } + return usedSize +} + +func imagesUsedbyCtr(containers []*libpod.Container, activeContainers map[string]*libpod.Container) (map[string][]*libpod.Container, map[string][]*libpod.Container, error) { + imgCtrMap := make(map[string][]*libpod.Container) + imgActiveCtrMap := make(map[string][]*libpod.Container) + for _, ctr := range containers { + imgID, _ := ctr.Image() + imgCtrMap[imgID] = append(imgCtrMap[imgID], ctr) + if _, isActive := activeContainers[ctr.ID()]; isActive { + imgActiveCtrMap[imgID] = append(imgActiveCtrMap[imgID], ctr) + } + } + return imgCtrMap, imgActiveCtrMap, nil +} + +func getContainerDiskUsage(containers []*libpod.Container, activeContainers map[string]*libpod.Container) (systemDfDiskUsage, error) { + var ( + sumSize int64 + unreclaimableSize int64 + reclaimableStr string + ) + for _, ctr := range containers { + size, err := ctr.RWSize() + if err != nil { + return systemDfDiskUsage{}, errors.Wrapf(err, "error getting size of container %s", ctr.ID()) + } + sumSize += size + } + for _, activeCtr := range activeContainers { + size, err := activeCtr.RWSize() + if err != nil { + return systemDfDiskUsage{}, errors.Wrapf(err, "error getting size of active container %s", activeCtr.ID()) + } + unreclaimableSize += size + } + if sumSize == 0 { + reclaimableStr = fmt.Sprintf("%s (%v%%)", units.HumanSizeWithPrecision(0, 3), 0) + } else { + reclaimable := sumSize - unreclaimableSize + reclaimableStr = fmt.Sprintf("%s (%v%%)", units.HumanSizeWithPrecision(float64(reclaimable), 3), 100*reclaimable/sumSize) + } + containerDiskUsage := systemDfDiskUsage{ + Type: "Containers", + Total: len(containers), + Active: len(activeContainers), + Size: units.HumanSizeWithPrecision(float64(sumSize), 3), + Reclaimable: reclaimableStr, + } + return containerDiskUsage, nil +} + +func ctrIsActive(ctr *libpod.Container) (bool, error) { + state, err := ctr.State() + if err != nil { + return false, err + } + return state == libpod.ContainerStatePaused || state == libpod.ContainerStateRunning, nil +} + +func activeContainers(containers []*libpod.Container) (map[string]*libpod.Container, error) { + activeContainers := make(map[string]*libpod.Container) + for _, aCtr := range containers { + isActive, err := ctrIsActive(aCtr) + if err != nil { + return nil, err + } + if isActive { + activeContainers[aCtr.ID()] = aCtr + } + } + return activeContainers, nil +} + +func getVolumeDiskUsage(volumes []*libpod.Volume, volumeUsedByContainerMap map[string][]*libpod.Container) (systemDfDiskUsage, error) { + var ( + sumSize int64 + unreclaimableSize int64 + reclaimableStr string + ) + for _, volume := range volumes { + size, err := volumeSize(volume) + if err != nil { + return systemDfDiskUsage{}, errors.Wrapf(err, "error getting size of volime %s", volume.Name()) + } + sumSize += size + if _, exist := volumeUsedByContainerMap[volume.Name()]; exist { + unreclaimableSize += size + } + } + reclaimable := sumSize - unreclaimableSize + if sumSize != 0 { + reclaimableStr = fmt.Sprintf("%s (%v%%)", units.HumanSizeWithPrecision(float64(reclaimable), 3), 100*reclaimable/sumSize) + } else { + reclaimableStr = fmt.Sprintf("%s (%v%%)", units.HumanSizeWithPrecision(float64(reclaimable), 3), 0) + } + volumesDiskUsage := systemDfDiskUsage{ + Type: "Local Volumes", + Total: len(volumes), + Active: len(volumeUsedByContainerMap), + Size: units.HumanSizeWithPrecision(float64(sumSize), 3), + Reclaimable: reclaimableStr, + } + return volumesDiskUsage, nil +} + +func volumeUsedByContainer(containers []*libpod.Container) map[string][]*libpod.Container { + volumeUsedByContainerMap := make(map[string][]*libpod.Container) + for _, ctr := range containers { + + ctrVolumes := ctr.UserVolumes() + for _, ctrVolume := range ctrVolumes { + volumeUsedByContainerMap[ctrVolume] = append(volumeUsedByContainerMap[ctrVolume], ctr) + } + } + return volumeUsedByContainerMap +} + +func volumeSize(volume *libpod.Volume) (int64, error) { + var size int64 + err := filepath.Walk(volume.MountPoint(), func(path string, info os.FileInfo, err error) error { + if err == nil && !info.IsDir() { + size += info.Size() + } + return err + }) + return size, err +} + +func getImageVerboseDiskUsage(ctx context.Context, images []*image.Image, imagesUsedbyCtr map[string][]*libpod.Container) ([]imageVerboseDiskUsage, error) { + var imagesVerboseDiskUsage []imageVerboseDiskUsage + imgUniqueSizeMap, err := imageUniqueSize(ctx, images) + if err != nil { + return imagesVerboseDiskUsage, errors.Wrapf(err, "error getting unique size of images") + } + for _, img := range images { + isParent, err := img.IsParent() + if err != nil { + return imagesVerboseDiskUsage, errors.Wrapf(err, "error checking if %s is a parent images", img.ID()) + } + parent, err := img.GetParent() + if err != nil { + return imagesVerboseDiskUsage, errors.Wrapf(err, "error getting parent of image %s", img.ID()) + } + if isParent && parent != nil { + continue + } + size, err := img.Size(ctx) + if err != nil { + return imagesVerboseDiskUsage, errors.Wrapf(err, "error getting size of image %s", img.ID()) + } + numberOfContainers := 0 + if ctrs, exist := imagesUsedbyCtr[img.ID()]; exist { + numberOfContainers = len(ctrs) + } + var repo string + var tag string + if len(img.Names()) == 0 { + repo = "<none>" + tag = "<none>" + } + repopairs, err := image.ReposToMap([]string{img.Names()[0]}) + if err != nil { + logrus.Errorf("error finding tag/digest for %s", img.ID()) + } + for reponame, tags := range repopairs { + for _, tagname := range tags { + repo = reponame + tag = tagname + } + } + + imageVerbosedf := imageVerboseDiskUsage{ + Repository: repo, + Tag: tag, + ImageID: shortID(img.ID()), + Created: units.HumanDuration(time.Since((img.Created().Local()))) + " ago", + Size: units.HumanSizeWithPrecision(float64(*size), 3), + SharedSize: units.HumanSizeWithPrecision(float64(*size-imgUniqueSizeMap[img.ID()]), 3), + UniqueSize: units.HumanSizeWithPrecision(float64(imgUniqueSizeMap[img.ID()]), 3), + Containers: numberOfContainers, + } + imagesVerboseDiskUsage = append(imagesVerboseDiskUsage, imageVerbosedf) + } + return imagesVerboseDiskUsage, nil +} + +func getContainerVerboseDiskUsage(containers []*libpod.Container) (containersVerboseDiskUsage []containerVerboseDiskUsage, err error) { + for _, ctr := range containers { + imgID, _ := ctr.Image() + size, err := ctr.RWSize() + if err != nil { + return containersVerboseDiskUsage, errors.Wrapf(err, "error getting size of container %s", ctr.ID()) + } + state, err := ctr.State() + if err != nil { + return containersVerboseDiskUsage, errors.Wrapf(err, "error getting the state of container %s", ctr.ID()) + } + + ctrVerboseData := containerVerboseDiskUsage{ + ContainerID: shortID(ctr.ID()), + Image: shortImageID(imgID), + Command: strings.Join(ctr.Command(), " "), + LocalVolumes: len(ctr.UserVolumes()), + Size: units.HumanSizeWithPrecision(float64(size), 3), + Created: units.HumanDuration(time.Since(ctr.CreatedTime().Local())) + "ago", + Status: state.String(), + Names: ctr.Name(), + } + containersVerboseDiskUsage = append(containersVerboseDiskUsage, ctrVerboseData) + + } + return containersVerboseDiskUsage, nil +} + +func getVolumeVerboseDiskUsage(volumes []*libpod.Volume, volumeUsedByContainerMap map[string][]*libpod.Container) (volumesVerboseDiskUsage []volumeVerboseDiskUsage, err error) { + for _, vol := range volumes { + volSize, err := volumeSize(vol) + if err != nil { + return volumesVerboseDiskUsage, errors.Wrapf(err, "error getting size of volume %s", vol.Name()) + } + links := 0 + if linkCtr, exist := volumeUsedByContainerMap[vol.Name()]; exist { + links = len(linkCtr) + } + volumeVerboseData := volumeVerboseDiskUsage{ + VolumeName: vol.Name(), + Links: links, + Size: units.HumanSizeWithPrecision(float64(volSize), 3), + } + volumesVerboseDiskUsage = append(volumesVerboseDiskUsage, volumeVerboseData) + } + return volumesVerboseDiskUsage, nil +} + +func imagesVerboseOutput(ctx context.Context, metaData dfMetaData) error { + var imageVerboseHeader = map[string]string{ + "Repository": "REPOSITORY", + "Tag": "TAG", + "ImageID": "IMAGE ID", + "Created": "CREATED", + "Size": "SIZE", + "SharedSize": "SHARED SIZE", + "UniqueSize": "UNQUE SIZE", + "Containers": "CONTAINERS", + } + imagesVerboseDiskUsage, err := getImageVerboseDiskUsage(ctx, metaData.images, metaData.imagesUsedbyCtrMap) + if err != nil { + return errors.Wrapf(err, "error getting verbose output of images") + } + os.Stderr.WriteString("Images space usage:\n\n") + out := formats.StdoutTemplateArray{Output: systemDfImageVerboseDiskUsageToGeneric(imagesVerboseDiskUsage), Template: "table {{.Repository}}\t{{.Tag}}\t{{.ImageID}}\t{{.Created}}\t{{.Size}}\t{{.SharedSize}}\t{{.UniqueSize}}\t{{.Containers}}", Fields: imageVerboseHeader} + formats.Writer(out).Out() + return nil +} + +func containersVerboseOutput(ctx context.Context, metaData dfMetaData) error { + var containerVerboseHeader = map[string]string{ + "ContainerID": "CONTAINER ID ", + "Image": "IMAGE", + "Command": "COMMAND", + "LocalVolumes": "LOCAL VOLUMES", + "Size": "SIZE", + "Created": "CREATED", + "Status": "STATUS", + "Names": "NAMES", + } + containersVerboseDiskUsage, err := getContainerVerboseDiskUsage(metaData.containers) + if err != nil { + return errors.Wrapf(err, "error getting verbose output of containers") + } + os.Stderr.WriteString("\nContainers space usage:\n\n") + out := formats.StdoutTemplateArray{Output: systemDfContainerVerboseDiskUsageToGeneric(containersVerboseDiskUsage), Template: "table {{.ContainerID}}\t{{.Image}}\t{{.Command}}\t{{.LocalVolumes}}\t{{.Size}}\t{{.Created}}\t{{.Status}}\t{{.Names}}", Fields: containerVerboseHeader} + formats.Writer(out).Out() + return nil +} + +func volumesVerboseOutput(ctx context.Context, metaData dfMetaData) error { + var volumeVerboseHeader = map[string]string{ + "VolumeName": "VOLUME NAME", + "Links": "LINKS", + "Size": "SIZE", + } + volumesVerboseDiskUsage, err := getVolumeVerboseDiskUsage(metaData.volumes, metaData.volumeUsedByContainerMap) + if err != nil { + return errors.Wrapf(err, "error getting verbose ouput of volumes") + } + os.Stderr.WriteString("\nLocal Volumes space usage:\n\n") + out := formats.StdoutTemplateArray{Output: systemDfVolumeVerboseDiskUsageToGeneric(volumesVerboseDiskUsage), Template: "table {{.VolumeName}}\t{{.Links}}\t{{.Size}}", Fields: volumeVerboseHeader} + formats.Writer(out).Out() + return nil +} + +func verboseOutput(ctx context.Context, metaData dfMetaData) error { + if err := imagesVerboseOutput(ctx, metaData); err != nil { + return err + } + if err := containersVerboseOutput(ctx, metaData); err != nil { + return err + } + if err := volumesVerboseOutput(ctx, metaData); err != nil { + return err + } + return nil +} + +func systemDfDiskUsageToGeneric(diskUsages []systemDfDiskUsage) (out []interface{}) { + for _, usage := range diskUsages { + out = append(out, interface{}(usage)) + } + return out +} + +func systemDfImageVerboseDiskUsageToGeneric(diskUsages []imageVerboseDiskUsage) (out []interface{}) { + for _, usage := range diskUsages { + out = append(out, interface{}(usage)) + } + return out +} + +func systemDfContainerVerboseDiskUsageToGeneric(diskUsages []containerVerboseDiskUsage) (out []interface{}) { + for _, usage := range diskUsages { + out = append(out, interface{}(usage)) + } + return out +} + +func systemDfVolumeVerboseDiskUsageToGeneric(diskUsages []volumeVerboseDiskUsage) (out []interface{}) { + for _, usage := range diskUsages { + out = append(out, interface{}(usage)) + } + return out +} + +func shortImageID(id string) string { + const imageIDTruncLength int = 4 + if len(id) > imageIDTruncLength { + return id[:imageIDTruncLength] + } + return id +} diff --git a/cmd/podman/system_prune.go b/cmd/podman/system_prune.go index a823dcad1..624f24acb 100644 --- a/cmd/podman/system_prune.go +++ b/cmd/podman/system_prune.go @@ -23,6 +23,7 @@ var ( ` _pruneSystemCommand = &cobra.Command{ Use: "prune", + Args: noSubArgs, Short: "Remove unused data", Long: pruneSystemDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -35,6 +36,7 @@ var ( func init() { pruneSystemCommand.Command = _pruneSystemCommand + pruneSystemCommand.SetHelpTemplate(HelpTemplate()) pruneSystemCommand.SetUsageTemplate(UsageTemplate()) flags := pruneSystemCommand.Flags() flags.BoolVarP(&pruneSystemCommand.All, "all", "a", false, "Remove all unused data") diff --git a/cmd/podman/system_renumber.go b/cmd/podman/system_renumber.go index c8ce628b1..ed0b28a3c 100644 --- a/cmd/podman/system_renumber.go +++ b/cmd/podman/system_renumber.go @@ -18,6 +18,7 @@ var ( _renumberCommand = &cobra.Command{ Use: "renumber", + Args: noSubArgs, Short: "Migrate lock numbers", Long: renumberDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -30,6 +31,7 @@ var ( func init() { renumberCommand.Command = _renumberCommand + renumberCommand.SetHelpTemplate(HelpTemplate()) renumberCommand.SetUsageTemplate(UsageTemplate()) } diff --git a/cmd/podman/tag.go b/cmd/podman/tag.go index 98c6e3449..98d9a6856 100644 --- a/cmd/podman/tag.go +++ b/cmd/podman/tag.go @@ -10,7 +10,7 @@ import ( var ( tagCommand cliconfig.TagValues - 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{ Use: "tag [flags] IMAGE TAG [TAG...]", Short: "Add an additional name to a local image", @@ -28,6 +28,7 @@ var ( func init() { tagCommand.Command = _tagCommand + tagCommand.SetHelpTemplate(HelpTemplate()) tagCommand.SetUsageTemplate(UsageTemplate()) } diff --git a/cmd/podman/top.go b/cmd/podman/top.go index cdf270fa7..2512631c1 100644 --- a/cmd/podman/top.go +++ b/cmd/podman/top.go @@ -18,23 +18,23 @@ func getDescriptorString() string { descriptors, err := libpod.GetContainerPidInformationDescriptors() if err == nil { return fmt.Sprintf(` -Format Descriptors: -%s`, strings.Join(descriptors, ",")) + Format Descriptors: + %s`, strings.Join(descriptors, ",")) } return "" } var ( topCommand cliconfig.TopValues - topDescription = fmt.Sprintf(`Display the running processes of the container. Specify format descriptors -to alter the output. You may run "podman top -l pid pcpu seccomp" to print -the process ID, the CPU percentage and the seccomp mode of each process of -the latest container. -%s -`, getDescriptorString()) + topDescription = fmt.Sprintf(`Similar to system "top" command. + + Specify format descriptors to alter the output. + + Running "podman top -l pid pcpu seccomp" will print the process ID, the CPU percentage and the seccomp mode of each process of the latest container. +%s`, getDescriptorString()) _topCommand = &cobra.Command{ - Use: "top [flags] CONTAINER [FORMAT-DESCRIPTIOS]", + Use: "top [flags] CONTAINER [FORMAT-DESCRIPTORS]", Short: "Display the running processes of a container", Long: topDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -50,6 +50,7 @@ the latest container. func init() { topCommand.Command = _topCommand + topCommand.SetHelpTemplate(HelpTemplate()) topCommand.SetUsageTemplate(UsageTemplate()) flags := topCommand.Flags() flags.BoolVar(&topCommand.ListDescriptors, "list-descriptors", false, "") @@ -108,7 +109,7 @@ func topCmd(c *cliconfig.TopValues) error { if err != nil { return err } - became, ret, err := rootless.JoinNS(uint(pid)) + became, ret, err := rootless.JoinNS(uint(pid), 0) if err != nil { return err } diff --git a/cmd/podman/tree.go b/cmd/podman/tree.go new file mode 100644 index 000000000..c56e35aef --- /dev/null +++ b/cmd/podman/tree.go @@ -0,0 +1,190 @@ +package main + +import ( + "context" + "fmt" + + "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/cmd/podman/libpodruntime" + "github.com/containers/libpod/libpod/image" + units "github.com/docker/go-units" + "github.com/pkg/errors" + "github.com/spf13/cobra" +) + +const ( + middleItem = "├── " + continueItem = "│ " + lastItem = "└── " +) + +var ( + treeCommand cliconfig.TreeValues + + treeDescription = "Prints layer hierarchy of an image in a tree format" + _treeCommand = &cobra.Command{ + Use: "tree [flags] IMAGE", + Short: treeDescription, + Long: treeDescription, + RunE: func(cmd *cobra.Command, args []string) error { + treeCommand.InputArgs = args + treeCommand.GlobalFlags = MainGlobalOpts + return treeCmd(&treeCommand) + }, + Example: "podman image tree alpine:latest", + } +) + +func init() { + treeCommand.Command = _treeCommand + treeCommand.SetUsageTemplate(UsageTemplate()) + treeCommand.Flags().BoolVar(&treeCommand.WhatRequires, "whatrequires", false, "Show all child images and layers of the specified image") +} + +// infoImage keep information of Image along with all associated layers +type infoImage struct { + // id of image + id string + // tags of image + tags []string + // layers stores all layers of image. + layers []image.LayerInfo +} + +func treeCmd(c *cliconfig.TreeValues) error { + args := c.InputArgs + if len(args) == 0 { + return errors.Errorf("an image name must be specified") + } + if len(args) > 1 { + return errors.Errorf("you must provide at most 1 argument") + } + + runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) + if err != nil { + return errors.Wrapf(err, "error creating libpod runtime") + } + defer runtime.Shutdown(false) + + img, err := runtime.ImageRuntime().NewFromLocal(args[0]) + if err != nil { + return err + } + + // Fetch map of image-layers, which is used for printing output. + layerInfoMap, err := image.GetLayersMapWithImageInfo(runtime.ImageRuntime()) + if err != nil { + return errors.Wrapf(err, "error while retriving layers of image %q", img.InputName) + } + + // Create an imageInfo and fill the image and layer info + imageInfo := &infoImage{ + id: img.ID(), + tags: img.Names(), + } + + size, err := img.Size(context.Background()) + if err != nil { + return errors.Wrapf(err, "error while retriving image size") + } + fmt.Printf("Image ID: %s\n", imageInfo.id[:12]) + fmt.Printf("Tags:\t %s\n", imageInfo.tags) + fmt.Printf("Size:\t %v\n", units.HumanSizeWithPrecision(float64(*size), 4)) + fmt.Printf(fmt.Sprintf("Image Layers\n")) + + if !c.WhatRequires { + // fill imageInfo with layers associated with image. + // the layers will be filled such that + // (Start)RootLayer->...intermediate Parent Layer(s)-> TopLayer(End) + err := buildImageHierarchyMap(imageInfo, layerInfoMap, img.TopLayer()) + if err != nil { + return err + } + // Build output from imageInfo into buffer + printImageHierarchy(imageInfo) + + } else { + // fill imageInfo with layers associated with image. + // the layers will be filled such that + // (Start)TopLayer->...intermediate Child Layer(s)-> Child TopLayer(End) + // (Forks)... intermediate Child Layer(s) -> Child Top Layer(End) + err := printImageChildren(layerInfoMap, img.TopLayer(), "", true) + if err != nil { + return err + } + } + + return nil +} + +// Stores hierarchy of images such that all parent layers using which image is built are stored in imageInfo +// Layers are added such that (Start)RootLayer->...intermediate Parent Layer(s)-> TopLayer(End) +func buildImageHierarchyMap(imageInfo *infoImage, layerMap map[string]*image.LayerInfo, layerID string) error { + if layerID == "" { + return nil + } + ll, ok := layerMap[layerID] + if !ok { + return fmt.Errorf("lookup error: layerid %s not found", layerID) + } + if err := buildImageHierarchyMap(imageInfo, layerMap, ll.ParentID); err != nil { + return err + } + + imageInfo.layers = append(imageInfo.layers, *ll) + return nil +} + +// Stores all children layers which are created using given Image. +// Layers are stored as follows +// (Start)TopLayer->...intermediate Child Layer(s)-> Child TopLayer(End) +// (Forks)... intermediate Child Layer(s) -> Child Top Layer(End) +func printImageChildren(layerMap map[string]*image.LayerInfo, layerID string, prefix string, last bool) error { + if layerID == "" { + return nil + } + ll, ok := layerMap[layerID] + if !ok { + return fmt.Errorf("lookup error: layerid %s, not found", layerID) + } + fmt.Printf(prefix) + + //initialize intend with middleItem to reduce middleItem checks. + intend := middleItem + if !last { + // add continueItem i.e. '|' for next iteration prefix + prefix = prefix + continueItem + } else if len(ll.ChildID) > 1 || len(ll.ChildID) == 0 { + // The above condition ensure, alignment happens for node, which has more then 1 childern. + // If node is last in printing hierarchy, it should not be printed as middleItem i.e. ├── + intend = lastItem + prefix = prefix + " " + } + + var tags string + if len(ll.RepoTags) > 0 { + tags = fmt.Sprintf(" Top Layer of: %s", ll.RepoTags) + } + fmt.Printf("%sID: %s Size: %7v%s\n", intend, ll.ID[:12], units.HumanSizeWithPrecision(float64(ll.Size), 4), tags) + for count, childID := range ll.ChildID { + if err := printImageChildren(layerMap, childID, prefix, (count == len(ll.ChildID)-1)); err != nil { + return err + } + } + return nil +} + +// prints the layers info of image +func printImageHierarchy(imageInfo *infoImage) { + for count, l := range imageInfo.layers { + var tags string + intend := middleItem + if len(l.RepoTags) > 0 { + tags = fmt.Sprintf(" Top Layer of: %s", l.RepoTags) + } + if count == len(imageInfo.layers)-1 { + intend = lastItem + } + fmt.Printf("%s ID: %s Size: %7v%s\n", intend, l.ID[:12], units.HumanSizeWithPrecision(float64(l.Size), 4), tags) + } +} diff --git a/cmd/podman/trust.go b/cmd/podman/trust.go index 8b02dcdc6..0a79e1570 100644 --- a/cmd/podman/trust.go +++ b/cmd/podman/trust.go @@ -6,16 +6,21 @@ import ( ) var ( + trustDescription = `Manages which registries you trust as a source of container images based on its location. + + The location is determined by the transport and the registry host of the image. Using this container image docker://docker.io/library/busybox as an example, docker is the transport and docker.io is the registry host.` trustCommand = cliconfig.PodmanCommand{ Command: &cobra.Command{ Use: "trust", Short: "Manage container image trust policy", - Long: "podman image trust command", + Long: trustDescription, + RunE: commandRunE(), }, } ) func init() { + trustCommand.SetHelpTemplate(HelpTemplate()) trustCommand.SetUsageTemplate(UsageTemplate()) trustCommand.AddCommand(getTrustSubCommands()...) imageCommand.AddCommand(trustCommand.Command) diff --git a/cmd/podman/trust_set_show.go b/cmd/podman/trust_set_show.go index 746854249..d7a4ea6d6 100644 --- a/cmd/podman/trust_set_show.go +++ b/cmd/podman/trust_set_show.go @@ -7,9 +7,9 @@ import ( "sort" "strings" + "github.com/containers/buildah/pkg/formats" "github.com/containers/image/types" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/libpod/libpod/image" "github.com/containers/libpod/pkg/trust" @@ -50,8 +50,10 @@ var ( func init() { setTrustCommand.Command = _setTrustCommand + setTrustCommand.SetHelpTemplate(HelpTemplate()) setTrustCommand.SetUsageTemplate(UsageTemplate()) showTrustCommand.Command = _showTrustCommand + showTrustCommand.SetHelpTemplate(HelpTemplate()) showTrustCommand.SetUsageTemplate(UsageTemplate()) setFlags := setTrustCommand.Flags() setFlags.StringVar(&setTrustCommand.PolicyPath, "policypath", "", "") diff --git a/cmd/podman/umount.go b/cmd/podman/umount.go index 48c97fa31..a938c7c38 100644 --- a/cmd/podman/umount.go +++ b/cmd/podman/umount.go @@ -14,12 +14,11 @@ import ( var ( umountCommand cliconfig.UmountValues - description = ` -Container storage increments a mount counter each time a container is mounted. -When a container is unmounted, the mount counter is decremented and the -container's root filesystem is physically unmounted only when the mount -counter reaches zero indicating no other processes are using the mount. -An unmount can be forced with the --force flag. + description = `Container storage increments a mount counter each time a container is mounted. + + When a container is unmounted, the mount counter is decremented. The container's root filesystem is physically unmounted only when the mount counter reaches zero indicating no other processes are using the mount. + + An unmount can be forced with the --force flag. ` _umountCommand = &cobra.Command{ Use: "umount [flags] CONTAINER [CONTAINER...]", @@ -32,7 +31,7 @@ An unmount can be forced with the --force flag. return umountCmd(&umountCommand) }, Args: func(cmd *cobra.Command, args []string) error { - return checkAllAndLatest(cmd, args, true) + return checkAllAndLatest(cmd, args, false) }, Example: `podman umount ctrID podman umount ctrID1 ctrID2 ctrID3 @@ -42,6 +41,7 @@ An unmount can be forced with the --force flag. func init() { umountCommand.Command = _umountCommand + umountCommand.SetHelpTemplate(HelpTemplate()) umountCommand.SetUsageTemplate(UsageTemplate()) flags := umountCommand.Flags() flags.BoolVarP(&umountCommand.All, "all", "a", false, "Umount all of the currently mounted containers") diff --git a/cmd/podman/unpause.go b/cmd/podman/unpause.go index 58fd19fe1..0c52a2443 100644 --- a/cmd/podman/unpause.go +++ b/cmd/podman/unpause.go @@ -15,12 +15,8 @@ import ( var ( unpauseCommand cliconfig.UnpauseValues - unpauseDescription = ` - podman unpause - - Unpauses one or more running containers. The container name or ID can be used. -` - _unpauseCommand = &cobra.Command{ + 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, @@ -36,6 +32,7 @@ var ( func init() { unpauseCommand.Command = _unpauseCommand + unpauseCommand.SetHelpTemplate(HelpTemplate()) unpauseCommand.SetUsageTemplate(UsageTemplate()) flags := unpauseCommand.Flags() flags.BoolVarP(&unpauseCommand.All, "all", "a", false, "Unpause all paused containers") diff --git a/cmd/podman/utils.go b/cmd/podman/utils.go index 4ec0f8a13..45d081512 100644 --- a/cmd/podman/utils.go +++ b/cmd/podman/utils.go @@ -200,35 +200,6 @@ func getPodsFromContext(c *cliconfig.PodmanCommand, r *libpod.Runtime) ([]*libpo return pods, lastError } -func getVolumesFromContext(c *cliconfig.PodmanCommand, r *libpod.Runtime) ([]*libpod.Volume, error) { - args := c.InputArgs - var ( - vols []*libpod.Volume - lastError error - err error - ) - - if c.Bool("all") { - vols, err = r.Volumes() - if err != nil { - return nil, errors.Wrapf(err, "unable to get all volumes") - } - } - - for _, i := range args { - vol, err := r.GetVolume(i) - if err != nil { - if lastError != nil { - logrus.Errorf("%q", lastError) - } - lastError = errors.Wrapf(err, "unable to find volume %s", i) - continue - } - vols = append(vols, vol) - } - return vols, lastError -} - //printParallelOutput takes the map of parallel worker results and outputs them // to stdout func printParallelOutput(m map[string]error, errCount int) error { diff --git a/cmd/podman/varlink.go b/cmd/podman/varlink.go index f19d03885..787ad01cd 100644 --- a/cmd/podman/varlink.go +++ b/cmd/podman/varlink.go @@ -18,10 +18,9 @@ import ( var ( varlinkCommand cliconfig.VarlinkValues - varlinkDescription = ` - podman varlink + varlinkDescription = `Run varlink interface. Podman varlink listens on the specified unix domain socket for incoming connects. - run varlink interface + Tools speaking varlink protocol can remotely manage pods, containers and images. ` _varlinkCommand = &cobra.Command{ Use: "varlink [flags] URI", @@ -39,6 +38,7 @@ var ( func init() { varlinkCommand.Command = _varlinkCommand + varlinkCommand.SetHelpTemplate(HelpTemplate()) varlinkCommand.SetUsageTemplate(UsageTemplate()) flags := varlinkCommand.Flags() flags.Int64VarP(&varlinkCommand.Timeout, "timeout", "t", 1000, "Time until the varlink session expires in milliseconds. Use 0 to disable the timeout") @@ -49,6 +49,9 @@ func varlinkCmd(c *cliconfig.VarlinkValues) error { if len(args) < 1 { return errors.Errorf("you must provide a varlink URI") } + if len(args) > 1 { + return errors.Errorf("too many arguments. Requires exactly 1") + } timeout := time.Duration(c.Timeout) * time.Millisecond // Create a single runtime for varlink diff --git a/cmd/podman/varlink/io.podman.varlink b/cmd/podman/varlink/io.podman.varlink index 618af3481..ad2de56f8 100644 --- a/cmd/podman/varlink/io.podman.varlink +++ b/cmd/podman/varlink/io.podman.varlink @@ -19,6 +19,14 @@ type StringResponse ( message: string ) +type LogLine ( + device: string, + parseLogType : string, + time: string, + msg: string, + cid: string +) + # ContainerChanges describes the return struct for ListContainerChanges type ContainerChanges ( changed: []string, @@ -435,6 +443,23 @@ type Runlabel( opts: [string]string ) +# Event describes a libpod struct +type Event( + # TODO: make status and type a enum at some point? + # id is the container, volume, pod, image ID + id: string, + # image is the image name where applicable + image: string, + # name is the name of the pod, container, image + name: string, + # status describes the event that happened (i.e. create, remove, ...) + status: string, + # time the event happened + time: string, + # type describes object the event happened with (image, container...) + type: string +) + # GetVersion returns version and build information of the podman service method GetVersion() -> ( version: string, @@ -459,6 +484,11 @@ method ListContainers() -> (containers: []Container) # [InspectContainer](#InspectContainer). method GetContainer(id: string) -> (container: Container) +# GetContainersByContext allows you to get a list of container ids depending on all, latest, or a list of +# container names. The definition of latest container means the latest by creation date. In a multi- +# user environment, results might differ from what you expect. +method GetContainersByContext(all: bool, latest: bool, args: []string) -> (containers: []string) + # CreateContainer creates a new container from an image. It uses a [Create](#Create) type for input. The minimum # input required for CreateContainer is an image name. If the image name is not found, an [ImageNotFound](#ImageNotFound) # error will be returned. Otherwise, the ID of the newly created container will be returned. @@ -500,6 +530,8 @@ method ListContainerProcesses(name: string, opts: []string) -> (container: []str # capability of varlink if the client invokes it. method GetContainerLogs(name: string) -> (container: []string) +method GetContainersLogs(names: []string, follow: bool, latest: bool, since: string, tail: int, timestamps: bool) -> (log: LogLine) + # ListContainerChanges takes a name or ID of a container and returns changes between the container and # its base image. It returns a struct of changed, deleted, and added path names. method ListContainerChanges(name: string) -> (container: ContainerChanges) @@ -544,6 +576,10 @@ method ExportContainer(name: string, path: string) -> (tarfile: string) # ~~~ method GetContainerStats(name: string) -> (container: ContainerStats) +# GetContainerStatsWithHistory takes a previous set of container statistics and uses libpod functions +# to calculate the containers statistics based on current and previous measurements. +method GetContainerStatsWithHistory(previousStats: ContainerStats) -> (container: ContainerStats) + # This method has not be implemented yet. # method ResizeContainerTty() -> (notimplemented: NotImplemented) @@ -612,10 +648,10 @@ method UnpauseContainer(name: string) -> (container: string) # ~~~ method GetAttachSockets(name: string) -> (sockets: Sockets) -# WaitContainer takes the name or ID of a container and waits until the container stops. Upon stopping, the return -# code of the container is returned. If the container container cannot be found by ID or name, -# a [ContainerNotFound](#ContainerNotFound) error is returned. -method WaitContainer(name: string) -> (exitcode: int) +# WaitContainer takes the name or ID of a container and waits the given interval in milliseconds until the container +# stops. Upon stopping, the return code of the container is returned. If the container container cannot be found by ID +# or name, a [ContainerNotFound](#ContainerNotFound) error is returned. +method WaitContainer(name: string, interval: int) -> (exitcode: int) # RemoveContainer requires the name or ID of container as well a boolean representing whether a running container can be stopped and removed, and a boolean # indicating whether to remove builtin volumes. Upon successful removal of the @@ -647,7 +683,7 @@ method RemoveContainer(name: string, force: bool, removeVolumes: bool) -> (conta method DeleteStoppedContainers() -> (containers: []string) # ListImages returns information about the images that are currently in storage. -# See also [InspectImage](InspectImage). +# See also [InspectImage](#InspectImage). method ListImages() -> (images: []Image) # GetImage returns information about a single image in storage. @@ -947,8 +983,7 @@ method RemovePod(name: string, force: bool) -> (pod: string) # This method has not be implemented yet. # method WaitPod() -> (notimplemented: NotImplemented) -# This method has not been implemented yet. -# method TopPod() -> (notimplemented: NotImplemented) +method TopPod(pod: string, latest: bool, descriptors: []string) -> (stats: []string) # GetPodStats takes the name or ID of a pod and returns a pod name and slice of ContainerStats structure which # contains attributes like memory and cpu usage. If the pod cannot be found, a [PodNotFound](#PodNotFound) @@ -1076,7 +1111,7 @@ method ContainerArtifacts(name: string, artifactName: string) -> (config: string # ContainerInspectData returns a container's inspect data in string form. This call is for # development of Podman only and generally should not be used. -method ContainerInspectData(name: string) -> (config: string) +method ContainerInspectData(name: string, size: bool) -> (config: string) # ContainerStateData returns a container's state config in string form. This call is for # development of Podman only and generally should not be used. @@ -1115,6 +1150,9 @@ method GetPodsByContext(all: bool, latest: bool, args: []string) -> (pods: []str # LoadImage allows you to load an image into local storage from a tarball. method LoadImage(name: string, inputFile: string, quiet: bool, deleteFile: bool) -> (reply: MoreResponse) +# GetEvents returns known libpod events filtered by the options provided. +method GetEvents(filter: []string, since: string, until: string) -> (events: Event) + # ImageNotFound means the image could not be found by the provided name or ID in local storage. error ImageNotFound (id: string, reason: string) @@ -1144,3 +1182,6 @@ error ErrorOccurred (reason: string) # RuntimeErrors generally means a runtime could not be found or gotten. error RuntimeError (reason: string) + +# The Podman endpoint requires that you use a streaming connection. +error WantsMoreRequired (reason: string) diff --git a/cmd/podman/version.go b/cmd/podman/version.go index c65ba94f9..31b0b8e82 100644 --- a/cmd/podman/version.go +++ b/cmd/podman/version.go @@ -3,11 +3,12 @@ package main import ( "fmt" "os" + "strings" "text/tabwriter" "time" + "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/libpod" "github.com/pkg/errors" "github.com/spf13/cobra" @@ -17,6 +18,7 @@ var ( versionCommand cliconfig.VersionValues _versionCommand = &cobra.Command{ Use: "version", + Args: noSubArgs, Short: "Display the Podman Version Information", RunE: func(cmd *cobra.Command, args []string) error { versionCommand.InputArgs = args @@ -42,6 +44,9 @@ func versionCmd(c *cliconfig.VersionValues) error { versionOutputFormat := c.Format if versionOutputFormat != "" { + if strings.Join(strings.Fields(versionOutputFormat), "") == "{{json.}}" { + versionOutputFormat = formats.JSONString + } var out formats.Writer switch versionOutputFormat { case formats.JSONString: diff --git a/cmd/podman/volume.go b/cmd/podman/volume.go index 8a8664151..2a071d0c7 100644 --- a/cmd/podman/volume.go +++ b/cmd/podman/volume.go @@ -5,15 +5,14 @@ import ( "github.com/spf13/cobra" ) -var volumeDescription = `Manage volumes. - -Volumes are created in and can be shared between containers.` +var volumeDescription = `Volumes are created in and can be shared between containers.` var volumeCommand = cliconfig.PodmanCommand{ Command: &cobra.Command{ Use: "volume", Short: "Manage volumes", Long: volumeDescription, + RunE: commandRunE(), }, } var volumeSubcommands = []*cobra.Command{ diff --git a/cmd/podman/volume_create.go b/cmd/podman/volume_create.go index 96b2ed8c7..8f6237272 100644 --- a/cmd/podman/volume_create.go +++ b/cmd/podman/volume_create.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/cmd/podman/shared" "github.com/containers/libpod/pkg/adapter" "github.com/pkg/errors" "github.com/spf13/cobra" @@ -11,11 +12,7 @@ import ( var ( volumeCreateCommand cliconfig.VolumeCreateValues - volumeCreateDescription = ` -podman volume create - -Creates a new volume. If using the default driver, "local", the volume will -be created at.` + volumeCreateDescription = `If using the default driver, "local", the volume will be created on the host in the volumes directory under container storage.` _volumeCreateCommand = &cobra.Command{ Use: "create [flags] [NAME]", @@ -34,6 +31,7 @@ be created at.` func init() { volumeCreateCommand.Command = _volumeCreateCommand + volumeCommand.SetHelpTemplate(HelpTemplate()) volumeCreateCommand.SetUsageTemplate(UsageTemplate()) flags := volumeCreateCommand.Flags() flags.StringVar(&volumeCreateCommand.Driver, "driver", "", "Specify volume driver name (default local)") @@ -53,12 +51,12 @@ func volumeCreateCmd(c *cliconfig.VolumeCreateValues) error { return errors.Errorf("too many arguments, create takes at most 1 argument") } - labels, err := getAllLabels([]string{}, c.Label) + labels, err := shared.GetAllLabels([]string{}, c.Label) if err != nil { return errors.Wrapf(err, "unable to process labels") } - opts, err := getAllLabels([]string{}, c.Opt) + opts, err := shared.GetAllLabels([]string{}, c.Opt) if err != nil { return errors.Wrapf(err, "unable to process options") } diff --git a/cmd/podman/volume_inspect.go b/cmd/podman/volume_inspect.go index 8add7a375..fdd8b5b0b 100644 --- a/cmd/podman/volume_inspect.go +++ b/cmd/podman/volume_inspect.go @@ -9,12 +9,9 @@ import ( var ( volumeInspectCommand cliconfig.VolumeInspectValues - volumeInspectDescription = ` -podman volume inspect + volumeInspectDescription = `Display detailed information on one or more volumes. -Display detailed information on one or more volumes. Can change the format -from JSON to a Go template. -` + Use a Go template to change the format from JSON.` _volumeInspectCommand = &cobra.Command{ Use: "inspect [flags] VOLUME [VOLUME...]", Short: "Display detailed information on one or more volumes", @@ -32,6 +29,7 @@ from JSON to a Go template. func init() { volumeInspectCommand.Command = _volumeInspectCommand + volumeInspectCommand.SetHelpTemplate(HelpTemplate()) volumeInspectCommand.SetUsageTemplate(UsageTemplate()) flags := volumeInspectCommand.Flags() flags.BoolVarP(&volumeInspectCommand.All, "all", "a", false, "Inspect all volumes") diff --git a/cmd/podman/volume_ls.go b/cmd/podman/volume_ls.go index 5adfc1e91..2f35462a3 100644 --- a/cmd/podman/volume_ls.go +++ b/cmd/podman/volume_ls.go @@ -4,8 +4,8 @@ import ( "reflect" "strings" + "github.com/containers/buildah/pkg/formats" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/formats" "github.com/containers/libpod/pkg/adapter" "github.com/pkg/errors" "github.com/spf13/cobra" @@ -44,11 +44,11 @@ var ( podman volume ls List all available volumes. The output of the volumes can be filtered -and the output format can be changed to JSON or a user specified Go template. -` +and the output format can be changed to JSON or a user specified Go template.` _volumeLsCommand = &cobra.Command{ Use: "ls", Aliases: []string{"list"}, + Args: noSubArgs, Short: "List volumes", Long: volumeLsDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -61,6 +61,7 @@ and the output format can be changed to JSON or a user specified Go template. func init() { volumeLsCommand.Command = _volumeLsCommand + volumeLsCommand.SetHelpTemplate(HelpTemplate()) volumeLsCommand.SetUsageTemplate(UsageTemplate()) flags := volumeLsCommand.Flags() @@ -76,10 +77,6 @@ func volumeLsCmd(c *cliconfig.VolumeLsValues) error { } defer runtime.Shutdown(false) - if len(c.InputArgs) > 0 { - return errors.Errorf("too many arguments, ls takes no arguments") - } - opts := volumeLsOptions{ Quiet: c.Quiet, } diff --git a/cmd/podman/volume_prune.go b/cmd/podman/volume_prune.go index 1f7931aa4..70ba506e7 100644 --- a/cmd/podman/volume_prune.go +++ b/cmd/podman/volume_prune.go @@ -16,14 +16,13 @@ import ( var ( volumePruneCommand cliconfig.VolumePruneValues - volumePruneDescription = ` -podman volume prune + volumePruneDescription = `Volumes that are not currently owned by a container will be removed. -Remove all unused volumes. Will prompt for confirmation if not -using force. -` + The command prompts for confirmation which can be overridden with the --force flag. + Note all data will be destroyed.` _volumePruneCommand = &cobra.Command{ Use: "prune", + Args: noSubArgs, Short: "Remove all unused volumes", Long: volumePruneDescription, RunE: func(cmd *cobra.Command, args []string) error { @@ -36,6 +35,7 @@ using force. func init() { volumePruneCommand.Command = _volumePruneCommand + volumePruneCommand.SetHelpTemplate(HelpTemplate()) volumePruneCommand.SetUsageTemplate(UsageTemplate()) flags := volumePruneCommand.Flags() diff --git a/cmd/podman/volume_rm.go b/cmd/podman/volume_rm.go index 73b1a6668..8c6d5e97a 100644 --- a/cmd/podman/volume_rm.go +++ b/cmd/podman/volume_rm.go @@ -11,13 +11,9 @@ import ( var ( volumeRmCommand cliconfig.VolumeRmValues - volumeRmDescription = ` -podman volume rm + volumeRmDescription = `Remove one or more existing volumes. -Remove one or more existing volumes. Will only remove volumes that are -not being used by any containers. To remove the volumes anyways, use the ---force flag. -` + By default only volumes that are not being used by any containers will be removed. To remove the volumes anyways, use the --force flag.` _volumeRmCommand = &cobra.Command{ Use: "rm [flags] VOLUME [VOLUME...]", Aliases: []string{"remove"}, @@ -36,6 +32,7 @@ not being used by any containers. To remove the volumes anyways, use the func init() { volumeRmCommand.Command = _volumeRmCommand + volumeRmCommand.SetHelpTemplate(HelpTemplate()) volumeRmCommand.SetUsageTemplate(UsageTemplate()) flags := volumeRmCommand.Flags() flags.BoolVarP(&volumeRmCommand.All, "all", "a", false, "Remove all volumes") diff --git a/cmd/podman/wait.go b/cmd/podman/wait.go index 9df2e3208..4449898a0 100644 --- a/cmd/podman/wait.go +++ b/cmd/podman/wait.go @@ -2,11 +2,11 @@ package main import ( "fmt" - "os" + "reflect" "time" "github.com/containers/libpod/cmd/podman/cliconfig" - "github.com/containers/libpod/cmd/podman/libpodruntime" + "github.com/containers/libpod/pkg/adapter" "github.com/pkg/errors" "github.com/spf13/cobra" ) @@ -14,10 +14,7 @@ import ( var ( waitCommand cliconfig.WaitValues - waitDescription = ` - podman wait - - 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{ Use: "wait [flags] CONTAINER [CONTAINER...]", @@ -36,6 +33,7 @@ var ( func init() { waitCommand.Command = _waitCommand + waitCommand.SetHelpTemplate(HelpTemplate()) waitCommand.SetUsageTemplate(UsageTemplate()) flags := waitCommand.Flags() flags.UintVarP(&waitCommand.Interval, "interval", "i", 250, "Milliseconds to wait before polling for completion") @@ -49,43 +47,36 @@ func waitCmd(c *cliconfig.WaitValues) error { return errors.Errorf("you must provide at least one container name or id") } - runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand) + if c.Interval == 0 { + return errors.Errorf("interval must be greater then 0") + } + interval := time.Duration(c.Interval) * time.Millisecond + + runtime, err := adapter.GetRuntime(&c.PodmanCommand) if err != nil { - return errors.Wrapf(err, "error creating libpod runtime") + return errors.Wrapf(err, "error creating runtime") } defer runtime.Shutdown(false) + ok, failures, err := runtime.WaitOnContainers(getContext(), c, interval) if err != nil { - return errors.Wrapf(err, "could not get config") + return err } - var lastError error - if c.Latest { - latestCtr, err := runtime.GetLatestContainer() - if err != nil { - return errors.Wrapf(err, "unable to wait on latest container") - } - args = append(args, latestCtr.ID()) + for _, id := range ok { + fmt.Println(id) } - for _, container := range args { - ctr, err := runtime.LookupContainer(container) - if err != nil { - return errors.Wrapf(err, "unable to find container %s", container) - } - if c.Interval == 0 { - return errors.Errorf("interval must be greater then 0") - } - returnCode, err := ctr.WaitWithInterval(time.Duration(c.Interval) * time.Millisecond) - if err != nil { - if lastError != nil { - fmt.Fprintln(os.Stderr, lastError) - } - lastError = errors.Wrapf(err, "failed to wait for the container %v", container) - } else { - fmt.Println(returnCode) + if len(failures) > 0 { + keys := reflect.ValueOf(failures).MapKeys() + lastKey := keys[len(keys)-1].String() + lastErr := failures[lastKey] + delete(failures, lastKey) + + for _, err := range failures { + outputError(err) } + return lastErr } - - return lastError + return nil } |