diff options
Diffstat (limited to 'cmd/podman')
44 files changed, 1288 insertions, 1235 deletions
diff --git a/cmd/podman/cliconfig/config.go b/cmd/podman/cliconfig/config.go index 7945cb6cb..ec08eedb5 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,6 +53,15 @@ type ImagesValues struct { Sort string } +type EventValues struct { + PodmanCommand + Filter []string + Format string + Since string + Stream bool + Until string +} + type TagValues struct { PodmanCommand } diff --git a/cmd/podman/create.go b/cmd/podman/create.go index 8a5d0cf73..bceb606f6 100644 --- a/cmd/podman/create.go +++ b/cmd/podman/create.go @@ -1,37 +1,15 @@ package main import ( - "context" - "encoding/json" "fmt" - "io" - "io/ioutil" "os" - "path/filepath" - "strconv" - "strings" - "syscall" - "github.com/containers/image/manifest" "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" ) @@ -53,11 +31,6 @@ 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() { @@ -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,828 +88,3 @@ func createInit(c *cliconfig.PodmanCommand) error { return nil } - -func createContainer(c *cliconfig.PodmanCommand, runtime *libpod.Runtime) (*libpod.Container, *cc.CreateConfig, error) { - var ( - hasHealthCheck bool - healthCheck *manifest.Schema2HealthConfig - ) - 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() - } - - // 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]) - } - if healthCheck != nil { - hasHealthCheck = true - } - } - } - 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.HasHealthCheck = hasHealthCheck - 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 -} - -// 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.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 := 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()) - } - - 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.JoinDirectUserAndMountNS(uint(conmonPid)) - } - } - 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 bd3a985b7..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" diff --git a/cmd/podman/events.go b/cmd/podman/events.go new file mode 100644 index 000000000..dda9a03f9 --- /dev/null +++ b/cmd/podman/events.go @@ -0,0 +1,48 @@ +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 [flags]", + 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 e4cea1f5e..aa81edf56 100644 --- a/cmd/podman/exec.go +++ b/cmd/podman/exec.go @@ -2,16 +2,17 @@ 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 ( @@ -130,7 +131,7 @@ func execCmd(c *cliconfig.ExecValues) error { // 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{} diff --git a/cmd/podman/export.go b/cmd/podman/export.go index 4be2a3c86..e5dc410a7 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" @@ -70,7 +71,7 @@ func exportCmd(c *cliconfig.ExportValues) error { } } - 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/history.go b/cmd/podman/history.go index f6cfe91b6..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" diff --git a/cmd/podman/images.go b/cmd/podman/images.go index f92e5d44d..6133450be 100644 --- a/cmd/podman/images.go +++ b/cmd/podman/images.go @@ -9,8 +9,8 @@ import ( "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" diff --git a/cmd/podman/import.go b/cmd/podman/import.go index c3351ab1b..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" @@ -67,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 de20eb009..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" diff --git a/cmd/podman/inspect.go b/cmd/podman/inspect.go index 0af96088f..e14f25c24 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" 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 3c71e2f61..303c23bc7 100644 --- a/cmd/podman/load.go +++ b/cmd/podman/load.go @@ -7,6 +7,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/pkg/errors" "github.com/spf13/cobra" @@ -91,7 +92,7 @@ func loadCmd(c *cliconfig.LoadValues) error { input = outFile.Name() } } - if err := validateFileName(input); err != nil { + if err := parse.ValidateFileName(input); err != nil { return err } diff --git a/cmd/podman/logs.go b/cmd/podman/logs.go index 9df7281fc..c3416fe57 100644 --- a/cmd/podman/logs.go +++ b/cmd/podman/logs.go @@ -8,6 +8,7 @@ import ( "github.com/containers/libpod/cmd/podman/libpodruntime" "github.com/containers/libpod/libpod" "github.com/containers/libpod/pkg/logs" + "github.com/containers/libpod/pkg/util" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/cobra" @@ -70,7 +71,7 @@ func logsCmd(c *cliconfig.LogsValues) error { 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) } @@ -112,25 +113,3 @@ func logsCmd(c *cliconfig.LogsValues) error { } 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 -} diff --git a/cmd/podman/main.go b/cmd/podman/main.go index 7d4b650a9..669860341 100644 --- a/cmd/podman/main.go +++ b/cmd/podman/main.go @@ -36,6 +36,7 @@ var ( // implemented. var mainCommands = []*cobra.Command{ _buildCommand, + _eventsCommand, _exportCommand, _historyCommand, &_imagesCommand, @@ -65,18 +66,23 @@ 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, + _podStatsCommand: true, + _podStopCommand: true, + _restartCommand: true, + _rmCommand: true, + _runCommand: true, + _unpauseCommand: true, + _searchCommand: true, + _statsCommand: true, + _stopCommand: true, + _topCommand: true, } var rootCmd = &cobra.Command{ @@ -104,6 +110,7 @@ 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") diff --git a/cmd/podman/mount.go b/cmd/podman/mount.go index c5b7e2404..4381074ab 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" diff --git a/cmd/podman/play_kube.go b/cmd/podman/play_kube.go index a9dfee33c..44aa4776b 100644 --- a/cmd/podman/play_kube.go +++ b/cmd/podman/play_kube.go @@ -111,7 +111,7 @@ func playKubeYAMLCmd(c *cliconfig.KubePlayValues) error { 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 } @@ -174,7 +174,7 @@ func playKubeYAMLCmd(c *cliconfig.KubePlayValues) error { return errors.Errorf("Directories are the only supported HostPath type") } } - if err := validateVolumeHostDir(hostPath.Path); err != nil { + if err := shared.ValidateVolumeHostDir(hostPath.Path); err != nil { return errors.Wrapf(err, "Error in parsing HostPath in YAML") } fmt.Println(volume.Name) @@ -190,7 +190,7 @@ func playKubeYAMLCmd(c *cliconfig.KubePlayValues) error { 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 } @@ -286,7 +286,7 @@ func kubeContainerToCreateConfig(containerYAML v1.Container, runtime *libpod.Run if !exists { return nil, errors.Errorf("Volume mount %s specified for container but not configured in volumes", volume.Name) } - if err := validateVolumeCtrDir(volume.MountPath); err != nil { + 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)) diff --git a/cmd/podman/pod.go b/cmd/podman/pod.go index 2d9bca21d..9a9c7a702 100644 --- a/cmd/podman/pod.go +++ b/cmd/podman/pod.go @@ -1,7 +1,12 @@ 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" ) @@ -34,6 +39,48 @@ var podSubCommands = []*cobra.Command{ _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.SetHelpTemplate(HelpTemplate()) diff --git a/cmd/podman/pod_create.go b/cmd/podman/pod_create.go index d2b7da597..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,8 +15,8 @@ import ( var ( // Kernel namespaces shared by default within a pod - DefaultKernelNamespaces = "cgroup,ipc,net,uts" - podCreateCommand cliconfig.PodCreateValues + + podCreateCommand cliconfig.PodCreateValues podCreateDescription = `After creating the pod, the pod ID is printed to stdout. @@ -50,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") } @@ -87,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_ps.go b/cmd/podman/pod_ps.go index e30a03005..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" diff --git a/cmd/podman/pod_rm.go b/cmd/podman/pod_rm.go index a40992818..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" @@ -46,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_stats.go b/cmd/podman/pod_stats.go index 7dbd84525..701051938 100644 --- a/cmd/podman/pod_stats.go +++ b/cmd/podman/pod_stats.go @@ -11,8 +11,8 @@ 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/libpod" "github.com/containers/libpod/pkg/adapter" "github.com/pkg/errors" @@ -53,6 +53,11 @@ func init() { } func podStatsCmd(c *cliconfig.PodStatsValues) error { + + if os.Geteuid() != 0 { + return errors.New("stats is not supported in rootless mode") + } + format := c.Format all := c.All latest := c.Latest diff --git a/cmd/podman/pod_stop.go b/cmd/podman/pod_stop.go index f1b0ac51f..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" @@ -46,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/ps.go b/cmd/podman/ps.go index 6caac2406..de6966c3b 100644 --- a/cmd/podman/ps.go +++ b/cmd/podman/ps.go @@ -12,8 +12,8 @@ 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" diff --git a/cmd/podman/rm.go b/cmd/podman/rm.go index 4230bb396..56aaae9eb 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" @@ -48,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) @@ -61,6 +93,53 @@ 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 { + 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 { + 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(0) + } + } + failureCnt := 0 delContainers, err := getAllOrLatestContainers(&c.PodmanCommand, runtime, -1, "all") if err != nil { diff --git a/cmd/podman/run.go b/cmd/podman/run.go index ff09e670d..130c5a32c 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" @@ -66,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 } 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/save.go b/cmd/podman/save.go index 494496a3d..df016b069 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" @@ -85,7 +86,7 @@ func saveCmd(c *cliconfig.SaveValues) error { return errors.Errorf("refusing to save to terminal. Use -o flag or redirect") } } - if err := validateFileName(output); err != nil { + if err := parse.ValidateFileName(output); err != nil { return err } return runtime.SaveImage(getContext(), c) diff --git a/cmd/podman/search.go b/cmd/podman/search.go index e508c2bcf..25f5a98b7 100644 --- a/cmd/podman/search.go +++ b/cmd/podman/search.go @@ -3,9 +3,9 @@ package main import ( "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" diff --git a/cmd/podman/shared/create.go b/cmd/podman/shared/create.go new file mode 100644 index 000000000..bfd05d53e --- /dev/null +++ b/cmd/podman/shared/create.go @@ -0,0 +1,837 @@ +package shared + +import ( + "context" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + + "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" + 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 ( + hasHealthCheck bool + 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() + } + + // 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]) + } + if healthCheck != nil { + hasHealthCheck = true + } + } + } + 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.HasHealthCheck = hasHealthCheck + 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.StringSlice("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", +} 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/stats.go b/cmd/podman/stats.go index 3e2e114a9..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" diff --git a/cmd/podman/trust_set_show.go b/cmd/podman/trust_set_show.go index 5a70c21cc..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" diff --git a/cmd/podman/varlink/io.podman.varlink b/cmd/podman/varlink/io.podman.varlink index 6109bd290..791790e2e 100644 --- a/cmd/podman/varlink/io.podman.varlink +++ b/cmd/podman/varlink/io.podman.varlink @@ -435,6 +435,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, @@ -656,7 +673,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. @@ -1123,6 +1140,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, stream: bool, 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) @@ -1152,3 +1172,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 b3615ce23..336be892e 100644 --- a/cmd/podman/version.go +++ b/cmd/podman/version.go @@ -6,8 +6,8 @@ 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/libpod" "github.com/pkg/errors" "github.com/spf13/cobra" diff --git a/cmd/podman/volume_create.go b/cmd/podman/volume_create.go index d873f9806..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" @@ -50,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_ls.go b/cmd/podman/volume_ls.go index 5a36f4f7d..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" |