diff options
30 files changed, 517 insertions, 69 deletions
diff --git a/cmd/podman/build.go b/cmd/podman/build.go index 647ff1e86..24be9bb46 100644 --- a/cmd/podman/build.go +++ b/cmd/podman/build.go @@ -267,7 +267,7 @@ func buildCmd(c *cliconfig.BuildValues) error { MemorySwap: memorySwap, ShmSize: c.ShmSize, Ulimit: c.Ulimit, - Volumes: c.Volume, + Volumes: c.Volumes, } options := imagebuildah.BuildOptions{ diff --git a/cmd/podman/cliconfig/config.go b/cmd/podman/cliconfig/config.go index 77156f47a..43ba7ddc9 100644 --- a/cmd/podman/cliconfig/config.go +++ b/cmd/podman/cliconfig/config.go @@ -177,6 +177,12 @@ type InfoValues struct { Format string } +type InitValues struct { + PodmanCommand + All bool + Latest bool +} + type InspectValues struct { PodmanCommand TypeObject string diff --git a/cmd/podman/commands.go b/cmd/podman/commands.go index 4b0641d82..14451d944 100644 --- a/cmd/podman/commands.go +++ b/cmd/podman/commands.go @@ -17,7 +17,6 @@ func getMainCommands() []*cobra.Command { _loginCommand, _logoutCommand, _mountCommand, - _portCommand, _refreshCommand, _searchCommand, _statsCommand, @@ -45,7 +44,6 @@ func getContainerSubCommands() []*cobra.Command { _commitCommand, _execCommand, _mountCommand, - _portCommand, _refreshCommand, _restoreCommand, _runlabelCommand, diff --git a/cmd/podman/container.go b/cmd/podman/container.go index b3058bf12..bbf01d1f8 100644 --- a/cmd/podman/container.go +++ b/cmd/podman/container.go @@ -56,12 +56,14 @@ var ( _diffCommand, _exportCommand, _createCommand, + _initCommand, _killCommand, _listSubCommand, _logsCommand, _pauseCommand, - _restartCommand, + _portCommand, _pruneContainersCommand, + _restartCommand, _runCommand, _rmCommand, _startCommand, diff --git a/cmd/podman/errors_remote.go b/cmd/podman/errors_remote.go index ab255ea56..1e276be10 100644 --- a/cmd/podman/errors_remote.go +++ b/cmd/podman/errors_remote.go @@ -33,6 +33,8 @@ func outputError(err error) { ne = errors.New(e.Reason) case *iopodman.VolumeNotFound: ne = errors.New(e.Reason) + case *iopodman.InvalidState: + ne = errors.New(e.Reason) case *iopodman.ErrorOccurred: ne = errors.New(e.Reason) default: diff --git a/cmd/podman/init.go b/cmd/podman/init.go new file mode 100644 index 000000000..68c80631d --- /dev/null +++ b/cmd/podman/init.go @@ -0,0 +1,64 @@ +package main + +import ( + "github.com/containers/libpod/cmd/podman/cliconfig" + "github.com/containers/libpod/pkg/adapter" + "github.com/opentracing/opentracing-go" + "github.com/pkg/errors" + "github.com/spf13/cobra" +) + +var ( + initCommand cliconfig.InitValues + initDescription = `Initialize one or more containers, creating the OCI spec and mounts for inspection. Container names or IDs can be used.` + + _initCommand = &cobra.Command{ + Use: "init [flags] CONTAINER [CONTAINER...]", + Short: "Initialize one or more containers", + Long: initDescription, + RunE: func(cmd *cobra.Command, args []string) error { + initCommand.InputArgs = args + initCommand.GlobalFlags = MainGlobalOpts + initCommand.Remote = remoteclient + return initCmd(&initCommand) + }, + Args: func(cmd *cobra.Command, args []string) error { + return checkAllAndLatest(cmd, args, false) + }, + Example: `podman init --latest + podman init 3c45ef19d893 + podman init test1`, + } +) + +func init() { + initCommand.Command = _initCommand + initCommand.SetHelpTemplate(HelpTemplate()) + initCommand.SetUsageTemplate(UsageTemplate()) + flags := initCommand.Flags() + flags.BoolVarP(&initCommand.All, "all", "a", false, "Initialize all containers") + flags.BoolVarP(&initCommand.Latest, "latest", "l", false, "Act on the latest container podman is aware of") + markFlagHiddenForRemoteClient("latest", flags) +} + +// initCmd initializes a container +func initCmd(c *cliconfig.InitValues) error { + if c.Bool("trace") { + span, _ := opentracing.StartSpanFromContext(Ctx, "initCmd") + defer span.Finish() + } + + ctx := getContext() + + runtime, err := adapter.GetRuntime(ctx, &c.PodmanCommand) + if err != nil { + return errors.Wrapf(err, "could not get runtime") + } + defer runtime.Shutdown(false) + + ok, failures, err := runtime.InitContainers(ctx, c) + if err != nil { + return err + } + return printCmdResults(ok, failures) +} diff --git a/cmd/podman/main.go b/cmd/podman/main.go index f501ee674..787dd55c0 100644 --- a/cmd/podman/main.go +++ b/cmd/podman/main.go @@ -39,12 +39,14 @@ var mainCommands = []*cobra.Command{ &_imagesCommand, _importCommand, _infoCommand, + _initCommand, &_inspectCommand, _killCommand, _loadCommand, _logsCommand, _pauseCommand, podCommand.Command, + _portCommand, &_psCommand, _pullCommand, _pushCommand, diff --git a/cmd/podman/port.go b/cmd/podman/port.go index 7a9f01fe6..1bd2d623e 100644 --- a/cmd/podman/port.go +++ b/cmd/podman/port.go @@ -6,8 +6,7 @@ import ( "strings" "github.com/containers/libpod/cmd/podman/cliconfig" - "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" ) @@ -51,10 +50,7 @@ func portCmd(c *cliconfig.PortValues) error { var ( userProto, containerName string userPort int - container *libpod.Container - containers []*libpod.Container ) - args := c.InputArgs if c.Latest && c.All { @@ -66,9 +62,6 @@ func portCmd(c *cliconfig.PortValues) error { if len(args) == 0 && !c.Latest && !c.All { return errors.Errorf("you must supply a running container name or id") } - if !c.Latest && !c.All { - containerName = args[0] - } port := "" if len(args) > 1 && !c.Latest { @@ -98,36 +91,14 @@ func portCmd(c *cliconfig.PortValues) error { } } - runtime, err := libpodruntime.GetRuntime(getContext(), &c.PodmanCommand) + runtime, err := adapter.GetRuntime(getContext(), &c.PodmanCommand) if err != nil { return errors.Wrapf(err, "could not get runtime") } defer runtime.Shutdown(false) - if !c.Latest && !c.All { - container, err = runtime.LookupContainer(containerName) - if err != nil { - return errors.Wrapf(err, "unable to find container %s", containerName) - } - containers = append(containers, container) - } else if c.Latest { - container, err = runtime.GetLatestContainer() - if err != nil { - return errors.Wrapf(err, "unable to get last created container") - } - containers = append(containers, container) - } else { - containers, err = runtime.GetRunningContainers() - if err != nil { - return errors.Wrapf(err, "unable to get all containers") - } - } - + containers, err := runtime.Port(c) for _, con := range containers { - if state, _ := con.State(); state != libpod.ContainerStateRunning { - continue - } - portmappings, err := con.PortMappings() if err != nil { return err diff --git a/cmd/podman/shared/workers.go b/cmd/podman/shared/workers.go index 112af89cc..b6e3f10e7 100644 --- a/cmd/podman/shared/workers.go +++ b/cmd/podman/shared/workers.go @@ -110,9 +110,14 @@ func (p *Pool) newWorker(slot int) { func DefaultPoolSize(name string) int { numCpus := runtime.NumCPU() switch name { + case "init": + fallthrough case "kill": + fallthrough case "pause": + fallthrough case "rm": + fallthrough case "unpause": if numCpus <= 3 { return numCpus * 3 diff --git a/cmd/podman/varlink/io.podman.varlink b/cmd/podman/varlink/io.podman.varlink index 309f9765a..912d001e9 100644 --- a/cmd/podman/varlink/io.podman.varlink +++ b/cmd/podman/varlink/io.podman.varlink @@ -641,6 +641,14 @@ method StartContainer(name: string) -> (container: string) # ~~~ method StopContainer(name: string, timeout: int) -> (container: string) +# InitContainer initializes the given container. It accepts a container name or +# ID, and will initialize the container matching that ID if possible, and error +# if not. Containers can only be initialized when they are in the Created or +# Exited states. Initialization prepares a container to be started, but does not +# start the container. It is intended to be used to debug a container's state +# prior to starting it. +method InitContainer(name: string) -> (container: string) + # RestartContainer will restart a running container given a container name or ID and timeout value. The timeout # value is the time before a forcible stop is used to stop the container. If the container cannot be found by # name or ID, a [ContainerNotFound](#ContainerNotFound) error will be returned; otherwise, the ID of the @@ -1225,7 +1233,7 @@ error PodNotFound (name: string, reason: string) # VolumeNotFound means the volume could not be found by the name or ID in local storage. error VolumeNotFound (id: string, reason: string) -# PodContainerError means a container associated with a pod failed to preform an operation. It contains +# PodContainerError means a container associated with a pod failed to perform an operation. It contains # a container ID of the container that failed. error PodContainerError (podname: string, errors: []PodContainerErrorData) @@ -1233,6 +1241,9 @@ error PodContainerError (podname: string, errors: []PodContainerErrorData) # the pod ID. error NoContainersInPod (name: string) +# InvalidState indicates that a container or pod was in an improper state for the requested operation +error InvalidState (id: string, reason: string) + # ErrorOccurred is a generic error for an error that occurs during the execution. The actual error message # is includes as part of the error's text. error ErrorOccurred (reason: string) @@ -1241,4 +1252,4 @@ error ErrorOccurred (reason: string) error RuntimeError (reason: string) # The Podman endpoint requires that you use a streaming connection. -error WantsMoreRequired (reason: string) +error WantsMoreRequired (reason: string)
\ No newline at end of file diff --git a/commands.md b/commands.md index 1c05640f2..88290dc1d 100644 --- a/commands.md +++ b/commands.md @@ -34,6 +34,7 @@ Command | Descr [podman-images(1)](/docs/podman-images.1.md) | List images in local storage | [![...](/docs/play.png)](https://podman.io/asciinema/podman/images/) | [Here](https://github.com/containers/Demos/blob/master/podman_cli/podman_images.sh) [podman-import(1)](/docs/podman-import.1.md) | Import a tarball and save it as a filesystem image | [podman-info(1)](/docs/podman-info.1.md) | Display system information | +[podman-init(1)](/docs/podman-init.1.md) | Initialize a container | [podman-inspect(1)](/docs/podman-inspect.1.md) | Display the configuration of a container or image | [![...](/docs/play.png)](https://asciinema.org/a/133418) [podman-kill(1)](/docs/podman-kill.1.md) | Kill the main process in one or more running containers | [podman-load(1)](/docs/podman-load.1.md) | Load an image from a container image archive | diff --git a/completions/bash/podman b/completions/bash/podman index b5963f8b9..a02a47190 100644 --- a/completions/bash/podman +++ b/completions/bash/podman @@ -780,6 +780,10 @@ _podman_container_export() { _podman_export } +_podman_container_init() { + _podman_init +} + _podman_container_inspect() { _podman_inspect } @@ -2223,6 +2227,27 @@ _podman_ps() { _complete_ "$options_with_args" "$boolean_options" } +_podman_init() { + local boolean_options=" + --all + -a + --help + -h + --latest + -l + " + local options_with_args=" + " + case "$cur" in + -*) + COMPREPLY=($(compgen -W "$boolean_options $options_with_args" -- "$cur")) + ;; + *) + __podman_complete_containers_unpauseable + ;; + esac +} + _podman_start() { local options_with_args=" --detach-keys diff --git a/docs/podman-container.1.md b/docs/podman-container.1.md index 1ba957480..564d791fa 100644 --- a/docs/podman-container.1.md +++ b/docs/podman-container.1.md @@ -22,6 +22,7 @@ The container command allows you to manage containers | exec | [podman-exec(1)](podman-exec.1.md) | Execute a command in a running container. | | exists | [podman-container-exists(1)](podman-container-exists.1.md) | Check if a container exists in local storage | | export | [podman-export(1)](podman-export.1.md) | Export a container's filesystem contents as a tar archive. | +| init | [podman-init(1)](podman-init.1.md) | Initialize a container | | inspect | [podman-inspect(1)](podman-inspect.1.md) | Display a container or image's configuration. | | kill | [podman-kill(1)](podman-kill.1.md) | Kill the main process in one or more containers. | | list | [podman-ps(1)](podman-ps.1.md) | List the containers on the system.(alias ls) | diff --git a/docs/podman-init.1.md b/docs/podman-init.1.md new file mode 100644 index 000000000..f43757f62 --- /dev/null +++ b/docs/podman-init.1.md @@ -0,0 +1,41 @@ +% podman-init(1) + +## NAME +podman\-init - Initialize one or more containers + +## SYNOPSIS +**podman init** [*options*] *container* ... + +## DESCRIPTION +Initialize one or more containers. +You may use container IDs or names as input. +Initializing a container performs all tasks necessary for starting the container (mounting filesystems, creating an OCI spec, initializing the container network) but does not start the container. +If a container is not initialized, the `podman start` and `podman run` commands will do so automatically prior to starting it. +This command is intended to be used for inspecting or modifying the container's filesystem or OCI spec prior to starting it. +This can be used to inspect the container before it runs, or debug why a container is failing to run. + +## OPTIONS + +**--all, -a** + +Initialize all containers. Containers that have already initialized (including containers that have been started and are running) are ignored. + +**--latest, -l** +Instead of providing the container name or ID, use the last created container. If you use methods other than Podman +to run containers such as CRI-O, the last started container could be from either of those methods. + +The latest option is not supported on the remote client. + +## EXAMPLE + +podman init 35480fc9d568 + +podman init test1 + +podman init --latest + +## SEE ALSO +podman(1), podman-start(1) + +## HISTORY +April 2019, Originally compiled by Matthew Heon <mheon@redhat.com> diff --git a/docs/podman.1.md b/docs/podman.1.md index 9c0ca8a7a..ef12cf1cc 100644 --- a/docs/podman.1.md +++ b/docs/podman.1.md @@ -147,6 +147,7 @@ the exit codes follow the `chroot` standard, see below: | [podman-images(1)](podman-images.1.md) | List images in local storage. | | [podman-import(1)](podman-import.1.md) | Import a tarball and save it as a filesystem image. | | [podman-info(1)](podman-info.1.md) | Displays Podman related system information. | +| [podman-init(1)](podman-init.1.md) | Initialize a container | | [podman-inspect(1)](podman-inspect.1.md) | Display a container or image's configuration. | | [podman-kill(1)](podman-kill.1.md) | Kill the main process in one or more containers. | | [podman-load(1)](podman-load.1.md) | Load an image from a container image archive into container storage. | diff --git a/libpod/container_api.go b/libpod/container_api.go index 465b23831..5bfd869b3 100644 --- a/libpod/container_api.go +++ b/libpod/container_api.go @@ -40,7 +40,7 @@ func (c *Container) Init(ctx context.Context) (err error) { if !(c.state.State == ContainerStateConfigured || c.state.State == ContainerStateStopped || c.state.State == ContainerStateExited) { - return errors.Wrapf(ErrCtrExists, "container %s has already been created in runtime", c.ID()) + return errors.Wrapf(ErrCtrStateInvalid, "container %s has already been created in runtime", c.ID()) } // don't recursively start diff --git a/libpod/container_internal.go b/libpod/container_internal.go index 7febf6966..a791df491 100644 --- a/libpod/container_internal.go +++ b/libpod/container_internal.go @@ -811,8 +811,9 @@ func (c *Container) cleanupRuntime(ctx context.Context) error { span.SetTag("struct", "container") defer span.Finish() - // If the container is not ContainerStateStopped, do nothing - if c.state.State != ContainerStateStopped { + // If the container is not ContainerStateStopped or + // ContainerStateCreated, do nothing. + if c.state.State != ContainerStateStopped && c.state.State != ContainerStateCreated { return nil } @@ -825,9 +826,14 @@ func (c *Container) cleanupRuntime(ctx context.Context) error { return err } - // Our state is now Exited, as we've removed ourself from - // the runtime. - c.state.State = ContainerStateExited + // If we were Stopped, we are now Exited, as we've removed ourself + // from the runtime. + // If we were Created, we are now Configured. + if c.state.State == ContainerStateStopped { + c.state.State = ContainerStateExited + } else if c.state.State == ContainerStateCreated { + c.state.State = ContainerStateConfigured + } if c.valid { if err := c.save(); err != nil { diff --git a/pkg/adapter/containers.go b/pkg/adapter/containers.go index 9ec897a60..eb90ab50e 100644 --- a/pkg/adapter/containers.go +++ b/pkg/adapter/containers.go @@ -133,6 +133,43 @@ func (r *LocalRuntime) KillContainers(ctx context.Context, cli *cliconfig.KillVa return pool.Run() } +// InitContainers initializes container(s) based on CLI inputs. +// Returns list of successful id(s), map of failed id(s) to errors, or a general +// error not from the container. +func (r *LocalRuntime) InitContainers(ctx context.Context, cli *cliconfig.InitValues) ([]string, map[string]error, error) { + maxWorkers := shared.DefaultPoolSize("init") + if cli.GlobalIsSet("max-workers") { + maxWorkers = cli.GlobalFlags.MaxWorks + } + logrus.Debugf("Setting maximum init workers to %d", maxWorkers) + + ctrs, err := shortcuts.GetContainersByContext(cli.All, cli.Latest, cli.InputArgs, r.Runtime) + if err != nil { + return nil, nil, err + } + + pool := shared.NewPool("init", maxWorkers, len(ctrs)) + for _, c := range ctrs { + ctr := c + + pool.Add(shared.Job{ + ctr.ID(), + func() error { + err := ctr.Init(ctx) + if err != nil { + // If we're initializing all containers, ignore invalid state errors + if cli.All && errors.Cause(err) == libpod.ErrCtrStateInvalid { + return nil + } + return err + } + return nil + }, + }) + } + return pool.Run() +} + // RemoveContainers removes container(s) based on CLI inputs. func (r *LocalRuntime) RemoveContainers(ctx context.Context, cli *cliconfig.RmValues) ([]string, map[string]error, error) { var ( @@ -876,3 +913,30 @@ func cleanupContainer(ctx context.Context, ctr *libpod.Container, runtime *Local } return nil } + +// Port displays port information about existing containers +func (r *LocalRuntime) Port(c *cliconfig.PortValues) ([]*Container, error) { + var ( + portContainers []*Container + containers []*libpod.Container + err error + ) + + if !c.All { + containers, err = shortcuts.GetContainersByContext(false, c.Latest, c.InputArgs, r.Runtime) + } else { + containers, err = r.Runtime.GetRunningContainers() + } + if err != nil { + return nil, err + } + + //Convert libpod containers to adapter Containers + for _, con := range containers { + if state, _ := con.State(); state != libpod.ContainerStateRunning { + continue + } + portContainers = append(portContainers, &Container{con}) + } + return portContainers, nil +} diff --git a/pkg/adapter/containers_remote.go b/pkg/adapter/containers_remote.go index a3a48a564..b7e353f71 100644 --- a/pkg/adapter/containers_remote.go +++ b/pkg/adapter/containers_remote.go @@ -18,6 +18,7 @@ import ( "github.com/containers/libpod/libpod" "github.com/containers/libpod/pkg/inspect" "github.com/containers/libpod/pkg/varlinkapi/virtwriter" + "github.com/cri-o/ocicni/pkg/ocicni" "github.com/docker/docker/pkg/term" "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" @@ -63,6 +64,19 @@ func (c *Container) Unpause() error { return err } +func (c *Container) PortMappings() ([]ocicni.PortMapping, error) { + // First check if the container belongs to a network namespace (like a pod) + // Taken from libpod portmappings() + if len(c.config.NetNsCtr) > 0 { + netNsCtr, err := c.Runtime.LookupContainer(c.config.NetNsCtr) + if err != nil { + return nil, errors.Wrapf(err, "unable to lookup network namespace for container %s", c.ID()) + } + return netNsCtr.PortMappings() + } + return c.config.PortMappings, nil +} + // Config returns a container config func (r *LocalRuntime) Config(name string) *libpod.ContainerConfig { // TODO the Spec being returned is not populated. Matt and I could not figure out why. Will defer @@ -234,6 +248,40 @@ func (r *LocalRuntime) StopContainers(ctx context.Context, cli *cliconfig.StopVa return ok, failures, nil } +// InitContainers initializes container(s) based on Varlink. +// It returns a list of successful ID(s), a map of failed container ID to error, +// or an error if a more general error occurred. +func (r *LocalRuntime) InitContainers(ctx context.Context, cli *cliconfig.InitValues) ([]string, map[string]error, error) { + var ( + ok = []string{} + failures = map[string]error{} + ) + + ids, err := iopodman.GetContainersByContext().Call(r.Conn, cli.All, cli.Latest, cli.InputArgs) + if err != nil { + return nil, nil, err + } + + for _, id := range ids { + initialized, err := iopodman.InitContainer().Call(r.Conn, id) + if err != nil { + if cli.All { + switch err.(type) { + case *iopodman.InvalidState: + ok = append(ok, initialized) + default: + failures[id] = err + } + } else { + failures[id] = err + } + } else { + ok = append(ok, initialized) + } + } + return ok, failures, nil +} + // KillContainers sends signal to container(s) based on varlink. // Returns list of successful id(s), map of failed id(s) + error, or error not from container func (r *LocalRuntime) KillContainers(ctx context.Context, cli *cliconfig.KillValues, signal syscall.Signal) ([]string, map[string]error, error) { @@ -888,3 +936,23 @@ func (r *LocalRuntime) Prune(ctx context.Context, maxWorkers int, force bool) ([ func (r *LocalRuntime) CleanupContainers(ctx context.Context, cli *cliconfig.CleanupValues) ([]string, map[string]error, error) { return nil, nil, errors.New("container cleanup not supported for remote clients") } + +// Port displays port information about existing containers +func (r *LocalRuntime) Port(c *cliconfig.PortValues) ([]*Container, error) { + var ( + containers []*Container + err error + ) + // This one is a bit odd because when all is used, we only use running containers. + if !c.All { + containers, err = r.GetContainersByContext(false, c.Latest, c.InputArgs) + } else { + // we need to only use running containers if all + filters := []string{libpod.ContainerStateRunning.String()} + containers, err = r.LookupContainersWithStatus(filters) + } + if err != nil { + return nil, err + } + return containers, nil +} diff --git a/pkg/adapter/runtime_remote.go b/pkg/adapter/runtime_remote.go index 6102daccf..4986d16f7 100644 --- a/pkg/adapter/runtime_remote.go +++ b/pkg/adapter/runtime_remote.go @@ -889,3 +889,20 @@ func (r *LocalRuntime) GenerateKube(c *cliconfig.GenerateKubeValues) (*v1.Pod, * err = json.Unmarshal([]byte(reply.Service), &service) return &pod, &service, err } + +// GetContainersByContext looks up containers based on the cli input of all, latest, or a list +func (r *LocalRuntime) GetContainersByContext(all bool, latest bool, namesOrIDs []string) ([]*Container, error) { + var containers []*Container + cids, err := iopodman.GetContainersByContext().Call(r.Conn, all, latest, namesOrIDs) + if err != nil { + return nil, err + } + for _, cid := range cids { + ctr, err := r.LookupContainer(cid) + if err != nil { + return nil, err + } + containers = append(containers, ctr) + } + return containers, nil +} diff --git a/pkg/varlinkapi/containers.go b/pkg/varlinkapi/containers.go index 872c7bc26..c8be41636 100644 --- a/pkg/varlinkapi/containers.go +++ b/pkg/varlinkapi/containers.go @@ -365,6 +365,21 @@ func (i *LibpodAPI) StartContainer(call iopodman.VarlinkCall, name string) error return call.ReplyStartContainer(ctr.ID()) } +// InitContainer initializes the container given by Varlink. +func (i *LibpodAPI) InitContainer(call iopodman.VarlinkCall, name string) error { + ctr, err := i.Runtime.LookupContainer(name) + if err != nil { + return call.ReplyContainerNotFound(name, err.Error()) + } + if err := ctr.Init(getContext()); err != nil { + if errors.Cause(err) == libpod.ErrCtrStateInvalid { + return call.ReplyInvalidState(ctr.ID(), err.Error()) + } + return call.ReplyErrorOccurred(err.Error()) + } + return call.ReplyInitContainer(ctr.ID()) +} + // StopContainer ... func (i *LibpodAPI) StopContainer(call iopodman.VarlinkCall, name string, timeout int64) error { ctr, err := i.Runtime.LookupContainer(name) diff --git a/test/e2e/init_test.go b/test/e2e/init_test.go new file mode 100644 index 000000000..5865930a5 --- /dev/null +++ b/test/e2e/init_test.go @@ -0,0 +1,129 @@ +package integration + +import ( + "os" + + . "github.com/containers/libpod/test/utils" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +var _ = Describe("Podman init", func() { + var ( + tempdir string + err error + podmanTest *PodmanTestIntegration + ) + + BeforeEach(func() { + tempdir, err = CreateTempDirInTempDir() + if err != nil { + os.Exit(1) + } + podmanTest = PodmanTestCreate(tempdir) + podmanTest.Setup() + podmanTest.RestoreAllArtifacts() + }) + + AfterEach(func() { + podmanTest.Cleanup() + f := CurrentGinkgoTestDescription() + processTestResult(f) + + }) + + It("podman init bogus container", func() { + session := podmanTest.Podman([]string{"start", "123456"}) + session.WaitWithDefaultTimeout() + Expect(session.ExitCode()).To(Equal(125)) + }) + + It("podman init with no arguments", func() { + session := podmanTest.Podman([]string{"start"}) + session.WaitWithDefaultTimeout() + Expect(session.ExitCode()).To(Equal(125)) + }) + + It("podman init single container by ID", func() { + session := podmanTest.Podman([]string{"create", "-d", ALPINE, "ls"}) + session.WaitWithDefaultTimeout() + Expect(session.ExitCode()).To(Equal(0)) + cid := session.OutputToString() + init := podmanTest.Podman([]string{"init", cid}) + init.WaitWithDefaultTimeout() + Expect(init.ExitCode()).To(Equal(0)) + result := podmanTest.Podman([]string{"inspect", cid}) + result.WaitWithDefaultTimeout() + Expect(result.ExitCode()).To(Equal(0)) + conData := result.InspectContainerToJSON() + Expect(conData[0].State.Status).To(Equal("created")) + }) + + It("podman init single container by name", func() { + name := "test1" + session := podmanTest.Podman([]string{"create", "--name", name, "-d", ALPINE, "ls"}) + session.WaitWithDefaultTimeout() + Expect(session.ExitCode()).To(Equal(0)) + init := podmanTest.Podman([]string{"init", name}) + init.WaitWithDefaultTimeout() + Expect(init.ExitCode()).To(Equal(0)) + result := podmanTest.Podman([]string{"inspect", name}) + result.WaitWithDefaultTimeout() + Expect(result.ExitCode()).To(Equal(0)) + conData := result.InspectContainerToJSON() + Expect(conData[0].State.Status).To(Equal("created")) + }) + + It("podman init latest container", func() { + session := podmanTest.Podman([]string{"create", "-d", ALPINE, "ls"}) + session.WaitWithDefaultTimeout() + Expect(session.ExitCode()).To(Equal(0)) + init := podmanTest.Podman([]string{"init", "--latest"}) + init.WaitWithDefaultTimeout() + Expect(init.ExitCode()).To(Equal(0)) + result := podmanTest.Podman([]string{"inspect", "--latest"}) + result.WaitWithDefaultTimeout() + Expect(result.ExitCode()).To(Equal(0)) + conData := result.InspectContainerToJSON() + Expect(conData[0].State.Status).To(Equal("created")) + }) + + It("podman init all three containers, one running", func() { + session := podmanTest.Podman([]string{"create", "--name", "test1", "-d", ALPINE, "ls"}) + session.WaitWithDefaultTimeout() + Expect(session.ExitCode()).To(Equal(0)) + session2 := podmanTest.Podman([]string{"create", "--name", "test2", "-d", ALPINE, "ls"}) + session2.WaitWithDefaultTimeout() + Expect(session2.ExitCode()).To(Equal(0)) + session3 := podmanTest.Podman([]string{"run", "--name", "test3", "-d", ALPINE, "top"}) + session3.WaitWithDefaultTimeout() + Expect(session3.ExitCode()).To(Equal(0)) + init := podmanTest.Podman([]string{"init", "--all"}) + init.WaitWithDefaultTimeout() + Expect(init.ExitCode()).To(Equal(0)) + result := podmanTest.Podman([]string{"inspect", "test1"}) + result.WaitWithDefaultTimeout() + Expect(result.ExitCode()).To(Equal(0)) + conData := result.InspectContainerToJSON() + Expect(conData[0].State.Status).To(Equal("created")) + result2 := podmanTest.Podman([]string{"inspect", "test2"}) + result2.WaitWithDefaultTimeout() + Expect(result2.ExitCode()).To(Equal(0)) + conData2 := result2.InspectContainerToJSON() + Expect(conData2[0].State.Status).To(Equal("created")) + result3 := podmanTest.Podman([]string{"inspect", "test3"}) + result3.WaitWithDefaultTimeout() + Expect(result3.ExitCode()).To(Equal(0)) + conData3 := result3.InspectContainerToJSON() + Expect(conData3[0].State.Status).To(Equal("running")) + }) + + It("podman init running container errors", func() { + session := podmanTest.Podman([]string{"run", "-d", ALPINE, "top"}) + session.WaitWithDefaultTimeout() + Expect(session.ExitCode()).To(Equal(0)) + init := podmanTest.Podman([]string{"init", "--latest"}) + init.WaitWithDefaultTimeout() + Expect(init.ExitCode()).To(Equal(125)) + }) +}) diff --git a/vendor.conf b/vendor.conf index 029e6834d..c99b2c1d7 100644 --- a/vendor.conf +++ b/vendor.conf @@ -94,11 +94,11 @@ k8s.io/apimachinery kubernetes-1.10.13-beta.0 https://github.com/kubernetes/apim k8s.io/client-go kubernetes-1.10.13-beta.0 https://github.com/kubernetes/client-go github.com/mrunalp/fileutils 7d4729fb36185a7c1719923406c9d40e54fb93c7 github.com/varlink/go 64e07fabffa33e385817b41971cf2674f692f391 -github.com/containers/buildah 34e7eba408282e890e61395b6d97e58b88e14d25 +github.com/containers/buildah v1.8.1 # TODO: Gotty has not been updated since 2012. Can we find replacement? github.com/Nvveen/Gotty cd527374f1e5bff4938207604a14f2e38a9cf512 github.com/fsouza/go-dockerclient v1.3.0 -github.com/openshift/imagebuilder 705fe9255c57f8505efb9723a9ac4082b67973bc +github.com/openshift/imagebuilder v1.1.0 github.com/ulikunitz/xz v0.5.5 github.com/coreos/go-iptables v0.4.0 github.com/google/shlex c34317bd91bf98fab745d77b03933cf8769299fe diff --git a/vendor/github.com/containers/buildah/buildah.go b/vendor/github.com/containers/buildah/buildah.go index e29e69383..13526057c 100644 --- a/vendor/github.com/containers/buildah/buildah.go +++ b/vendor/github.com/containers/buildah/buildah.go @@ -26,7 +26,7 @@ const ( Package = "buildah" // Version for the Package. Bump version in contrib/rpm/buildah.spec // too. - Version = "1.9.0-dev" + Version = "1.8.1" // The value we use to identify what type of information, currently a // serialized Builder structure, we are using as per-container state. // This should only be changed when we make incompatible changes to diff --git a/vendor/github.com/containers/buildah/imagebuildah/build.go b/vendor/github.com/containers/buildah/imagebuildah/build.go index d9909cdc8..85848e297 100644 --- a/vendor/github.com/containers/buildah/imagebuildah/build.go +++ b/vendor/github.com/containers/buildah/imagebuildah/build.go @@ -1558,6 +1558,9 @@ func (b *Executor) Build(ctx context.Context, stages imagebuilder.Stages) (image // stages. for i := range cleanupImages { removeID := cleanupImages[len(cleanupImages)-i-1] + if removeID == imageID { + continue + } if _, err := b.store.DeleteImage(removeID, true); err != nil { logrus.Debugf("failed to remove intermediate image %q: %v", removeID, err) if b.forceRmIntermediateCtrs || errors.Cause(err) != storage.ErrImageUsedByContainer { @@ -1663,6 +1666,7 @@ func (b *Executor) Build(ctx context.Context, stages imagebuilder.Stages) (image if !b.layers { cleanupImages = append(cleanupImages, imageID) } + imageID = "" } } @@ -1812,9 +1816,10 @@ func (b *Executor) deleteSuccessfulIntermediateCtrs() error { } func (s *StageExecutor) EnsureContainerPath(path string) error { - _, err := os.Stat(filepath.Join(s.mountPoint, path)) + targetPath := filepath.Join(s.mountPoint, path) + _, err := os.Lstat(targetPath) if err != nil && os.IsNotExist(err) { - err = os.MkdirAll(filepath.Join(s.mountPoint, path), 0755) + err = os.MkdirAll(targetPath, 0755) } if err != nil { return errors.Wrapf(err, "error ensuring container path %q", path) diff --git a/vendor/github.com/containers/buildah/pkg/cli/common.go b/vendor/github.com/containers/buildah/pkg/cli/common.go index 7fa0a7777..e7a571db6 100644 --- a/vendor/github.com/containers/buildah/pkg/cli/common.go +++ b/vendor/github.com/containers/buildah/pkg/cli/common.go @@ -96,7 +96,7 @@ type FromAndBudResults struct { SecurityOpt []string ShmSize string Ulimit []string - Volume []string + Volumes []string } // GetUserNSFlags returns the common flags for usernamespace @@ -190,7 +190,7 @@ func GetFromAndBudFlags(flags *FromAndBudResults, usernsResults *UserNSResults, fs.StringArrayVar(&flags.SecurityOpt, "security-opt", []string{}, "security options (default [])") fs.StringVar(&flags.ShmSize, "shm-size", "65536k", "size of '/dev/shm'. The format is `<number><unit>`.") fs.StringSliceVar(&flags.Ulimit, "ulimit", []string{}, "ulimit options (default [])") - fs.StringSliceVarP(&flags.Volume, "volume", "v", []string{}, "bind mount a volume into the container (default [])") + fs.StringSliceVarP(&flags.Volumes, "volume", "v", []string{}, "bind mount a volume into the container (default [])") // Add in the usernamespace and namespaceflags usernsFlags := GetUserNSFlags(usernsResults) diff --git a/vendor/github.com/containers/buildah/pkg/parse/parse.go b/vendor/github.com/containers/buildah/pkg/parse/parse.go index bec41f3ae..e8517eafb 100644 --- a/vendor/github.com/containers/buildah/pkg/parse/parse.go +++ b/vendor/github.com/containers/buildah/pkg/parse/parse.go @@ -149,27 +149,42 @@ func parseSecurityOpts(securityOpts []string, commonOpts *buildah.CommonBuildOpt return nil } +func ParseVolume(volume string) (specs.Mount, error) { + mount := specs.Mount{} + arr := strings.SplitN(volume, ":", 3) + if len(arr) < 2 { + return mount, errors.Errorf("incorrect volume format %q, should be host-dir:ctr-dir[:option]", volume) + } + if err := validateVolumeHostDir(arr[0]); err != nil { + return mount, err + } + if err := validateVolumeCtrDir(arr[1]); err != nil { + return mount, err + } + mountOptions := "" + if len(arr) > 2 { + mountOptions = arr[2] + if err := validateVolumeOpts(arr[2]); err != nil { + return mount, err + } + } + mountOpts := strings.Split(mountOptions, ",") + mount.Source = arr[0] + mount.Destination = arr[1] + mount.Type = "rbind" + mount.Options = mountOpts + return mount, nil +} + // ParseVolumes validates the host and container paths passed in to the --volume flag func ParseVolumes(volumes []string) error { if len(volumes) == 0 { return nil } for _, volume := range volumes { - arr := strings.SplitN(volume, ":", 3) - 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 := ParseVolume(volume); err != nil { return err } - if err := validateVolumeCtrDir(arr[1]); err != nil { - return err - } - if len(arr) > 2 { - if err := validateVolumeOpts(arr[2]); err != nil { - return err - } - } } return nil } diff --git a/vendor/github.com/containers/buildah/run_linux.go b/vendor/github.com/containers/buildah/run_linux.go index 8597e3656..1acf655eb 100644 --- a/vendor/github.com/containers/buildah/run_linux.go +++ b/vendor/github.com/containers/buildah/run_linux.go @@ -142,7 +142,7 @@ func (b *Builder) Run(command []string, options RunOptions) error { g = nil logrus.Debugf("ensuring working directory %q exists", filepath.Join(mountPoint, spec.Process.Cwd)) - if err = os.MkdirAll(filepath.Join(mountPoint, spec.Process.Cwd), 0755); err != nil { + if err = os.MkdirAll(filepath.Join(mountPoint, spec.Process.Cwd), 0755); err != nil && !os.IsExist(err) { return errors.Wrapf(err, "error ensuring working directory %q exists", spec.Process.Cwd) } diff --git a/vendor/github.com/containers/buildah/util/util.go b/vendor/github.com/containers/buildah/util/util.go index 698d79a81..629d9748c 100644 --- a/vendor/github.com/containers/buildah/util/util.go +++ b/vendor/github.com/containers/buildah/util/util.go @@ -197,7 +197,7 @@ func FindImage(store storage.Store, firstRegistry string, systemContext *types.S break } if ref == nil || img == nil { - return nil, nil, errors.Wrapf(err, "error locating image with name %q", image) + return nil, nil, errors.Wrapf(err, "error locating image with name %q (%v)", image, names) } return ref, img, nil } diff --git a/vendor/github.com/openshift/imagebuilder/vendor.conf b/vendor/github.com/openshift/imagebuilder/vendor.conf index 39b216feb..e437b79c3 100644 --- a/vendor/github.com/openshift/imagebuilder/vendor.conf +++ b/vendor/github.com/openshift/imagebuilder/vendor.conf @@ -1,12 +1,11 @@ github.com/Azure/go-ansiterm d6e3b3328b783f23731bc4d058875b0371ff8109 -github.com/containerd/continuity 004b46473808b3e7a4a3049c20e4376c91eb966d +github.com/containers/storage v1.2 github.com/docker/docker b68221c37ee597950364788204546f9c9d0e46a1 github.com/docker/go-connections 97c2040d34dfae1d1b1275fa3a78dbdd2f41cf7e github.com/docker/go-units 2fb04c6466a548a03cb009c5569ee1ab1e35398e github.com/fsouza/go-dockerclient openshift-4.0 https://github.com/openshift/go-dockerclient.git github.com/gogo/protobuf c5a62797aee0054613cc578653a16c6237fef080 github.com/golang/glog 23def4e6c14b4da8ac2ed8007337bc5eb5007998 -github.com/golang/protobuf v1.3.0 github.com/konsorten/go-windows-terminal-sequences f55edac94c9bbba5d6182a4be46d86a2c9b5b50e github.com/Microsoft/go-winio 1a8911d1ed007260465c3bfbbc785ac6915a0bb8 github.com/Nvveen/Gotty cd527374f1e5bff4938207604a14f2e38a9cf512 @@ -14,8 +13,8 @@ github.com/opencontainers/go-digest ac19fd6e7483ff933754af248d80be865e543d22 github.com/opencontainers/image-spec 243ea084a44451d27322fed02b682d99e2af3ba9 github.com/opencontainers/runc 923a8f8a9a07aceada5fc48c4d37e905d9b019b5 github.com/pkg/errors 27936f6d90f9c8e1145f11ed52ffffbfdb9e0af7 +github.com/pquerna/ffjson d49c2bc1aa135aad0c6f4fc2056623ec78f5d5ac github.com/sirupsen/logrus d7b6bf5e4d26448fd977d07d745a2a66097ddecb golang.org/x/crypto ff983b9c42bc9fbf91556e191cc8efb585c16908 golang.org/x/net 45ffb0cd1ba084b73e26dee67e667e1be5acce83 -golang.org/x/sync 37e7f081c4d4c64e13b10787722085407fe5d15f golang.org/x/sys 7fbe1cd0fcc20051e1fcb87fbabec4a1bacaaeba |