diff options
Diffstat (limited to 'pkg')
-rw-r--r-- | pkg/adapter/client.go | 2 | ||||
-rw-r--r-- | pkg/adapter/client_unix.go | 11 | ||||
-rw-r--r-- | pkg/adapter/client_windows.go | 15 | ||||
-rw-r--r-- | pkg/adapter/containers_remote.go | 7 | ||||
-rw-r--r-- | pkg/adapter/pods.go | 7 | ||||
-rw-r--r-- | pkg/netns/netns_linux.go | 46 | ||||
-rw-r--r-- | pkg/rootless/rootless_linux.go | 2 | ||||
-rw-r--r-- | pkg/spec/createconfig.go | 2 | ||||
-rw-r--r-- | pkg/spec/spec.go | 3 | ||||
-rw-r--r-- | pkg/spec/storage.go | 3 | ||||
-rw-r--r-- | pkg/util/utils.go | 85 | ||||
-rw-r--r-- | pkg/util/utils_test.go | 71 | ||||
-rw-r--r-- | pkg/varlinkapi/attach.go | 4 |
13 files changed, 223 insertions, 35 deletions
diff --git a/pkg/adapter/client.go b/pkg/adapter/client.go index 1805c758d..da4670892 100644 --- a/pkg/adapter/client.go +++ b/pkg/adapter/client.go @@ -35,7 +35,7 @@ func (r RemoteRuntime) RemoteEndpoint() (remoteEndpoint *Endpoint, err error) { if len(r.cmd.RemoteUserName) < 1 { return nil, errors.New("you must provide a username when providing a remote host name") } - rc := remoteclientconfig.RemoteConnection{r.cmd.RemoteHost, r.cmd.RemoteUserName, false, r.cmd.Port} + rc := remoteclientconfig.RemoteConnection{r.cmd.RemoteHost, r.cmd.RemoteUserName, false, r.cmd.Port, r.cmd.IdentityFile, r.cmd.IgnoreHosts} remoteEndpoint, err = newBridgeConnection("", &rc, r.cmd.LogLevel) // if the user has a config file with connections in it } else if len(remoteConfigConnections.Connections) > 0 { diff --git a/pkg/adapter/client_unix.go b/pkg/adapter/client_unix.go index a7bc7c1c0..7af8b24c6 100644 --- a/pkg/adapter/client_unix.go +++ b/pkg/adapter/client_unix.go @@ -14,7 +14,14 @@ func formatDefaultBridge(remoteConn *remoteclientconfig.RemoteConnection, logLev if port == 0 { port = 22 } + options := "" + if remoteConn.IdentityFile != "" { + options += " -i " + remoteConn.IdentityFile + } + if remoteConn.IgnoreHosts { + options += " -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" + } return fmt.Sprintf( - `ssh -p %d -T %s@%s -- /usr/bin/varlink -A \'/usr/bin/podman --log-level=%s varlink \\\$VARLINK_ADDRESS\' bridge`, - port, remoteConn.Username, remoteConn.Destination, logLevel) + `ssh -p %d -T%s %s@%s -- varlink -A \'podman --log-level=%s varlink \\\$VARLINK_ADDRESS\' bridge`, + port, options, remoteConn.Username, remoteConn.Destination, logLevel) } diff --git a/pkg/adapter/client_windows.go b/pkg/adapter/client_windows.go index 31e5d9830..32302a600 100644 --- a/pkg/adapter/client_windows.go +++ b/pkg/adapter/client_windows.go @@ -9,7 +9,18 @@ import ( ) func formatDefaultBridge(remoteConn *remoteclientconfig.RemoteConnection, logLevel string) string { + port := remoteConn.Port + if port == 0 { + port = 22 + } + options := "" + if remoteConn.IdentityFile != "" { + options += " -i " + remoteConn.IdentityFile + } + if remoteConn.IgnoreHosts { + options += " -q -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" + } return fmt.Sprintf( - `ssh -T %s@%s -- /usr/bin/varlink -A '/usr/bin/podman --log-level=%s varlink $VARLINK_ADDRESS' bridge`, - remoteConn.Username, remoteConn.Destination, logLevel) + `ssh -p %d -T%s %s@%s -- varlink -A 'podman --log-level=%s varlink $VARLINK_ADDRESS' bridge`, + port, options, remoteConn.Username, remoteConn.Destination, logLevel) } diff --git a/pkg/adapter/containers_remote.go b/pkg/adapter/containers_remote.go index 07ec1f19e..f7cb28b0c 100644 --- a/pkg/adapter/containers_remote.go +++ b/pkg/adapter/containers_remote.go @@ -488,7 +488,12 @@ func (r *LocalRuntime) Run(ctx context.Context, c *cliconfig.RunValues, exitCode fmt.Println(cid) return 0, nil } - exitChan, errChan, err := r.attach(ctx, os.Stdin, os.Stdout, cid, true, c.String("detach-keys")) + inputStream := os.Stdin + // If -i is not set, clear stdin + if !c.Bool("interactive") { + inputStream = nil + } + exitChan, errChan, err := r.attach(ctx, inputStream, os.Stdout, cid, true, c.String("detach-keys")) if err != nil { return exitCode, err } diff --git a/pkg/adapter/pods.go b/pkg/adapter/pods.go index 70293a2c5..c8d57e2a2 100644 --- a/pkg/adapter/pods.go +++ b/pkg/adapter/pods.go @@ -467,8 +467,15 @@ func (r *LocalRuntime) PlayKubeYAML(ctx context.Context, c *cliconfig.KubePlayVa return nil, errors.Wrapf(err, "unable to read %s as YAML", yamlFile) } + if podYAML.Kind != "Pod" { + return nil, errors.Errorf("Invalid YAML kind: %s. Pod is the only supported Kubernetes YAML kind", podYAML.Kind) + } + // check for name collision between pod and container podName := podYAML.ObjectMeta.Name + if podName == "" { + return nil, errors.Errorf("pod does not have a name") + } for _, n := range podYAML.Spec.Containers { if n.Name == podName { fmt.Printf("a container exists with the same name (%s) as the pod in your YAML file; changing pod name to %s_pod\n", podName, podName) diff --git a/pkg/netns/netns_linux.go b/pkg/netns/netns_linux.go index 1d6fb873c..e765bd46f 100644 --- a/pkg/netns/netns_linux.go +++ b/pkg/netns/netns_linux.go @@ -23,23 +23,42 @@ import ( "fmt" "os" "path" + "path/filepath" "runtime" "strings" "sync" "github.com/containernetworking/plugins/pkg/ns" + "github.com/containers/libpod/pkg/rootless" + "github.com/containers/libpod/pkg/util" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" ) -const nsRunDir = "/var/run/netns" +// get NSRunDir returns the dir of where to create the netNS. When running +// rootless, it needs to be at a location writable by user. +func getNSRunDir() (string, error) { + if rootless.IsRootless() { + rootlessDir, err := util.GetRuntimeDir() + if err != nil { + return "", err + } + return filepath.Join(rootlessDir, "netns"), nil + } + return "/var/run/netns", nil +} // NewNS creates a new persistent (bind-mounted) network namespace and returns // an object representing that namespace, without switching to it. func NewNS() (ns.NetNS, error) { + nsRunDir, err := getNSRunDir() + if err != nil { + return nil, err + } + b := make([]byte, 16) - _, err := rand.Reader.Read(b) + _, err = rand.Reader.Read(b) if err != nil { return nil, fmt.Errorf("failed to generate random netns name: %v", err) } @@ -107,9 +126,12 @@ func NewNS() (ns.NetNS, error) { // Don't unlock. By not unlocking, golang will kill the OS thread when the // goroutine is done (for go1.10+) + threadNsPath := getCurrentThreadNetNSPath() + var origNS ns.NetNS - origNS, err = ns.GetNS(getCurrentThreadNetNSPath()) + origNS, err = ns.GetNS(threadNsPath) if err != nil { + logrus.Warnf("cannot open current network namespace %s: %q", threadNsPath, err) return } defer func() { @@ -121,20 +143,27 @@ func NewNS() (ns.NetNS, error) { // create a new netns on the current thread err = unix.Unshare(unix.CLONE_NEWNET) if err != nil { + logrus.Warnf("cannot create a new network namespace: %q", err) return } // Put this thread back to the orig ns, since it might get reused (pre go1.10) defer func() { if err := origNS.Set(); err != nil { - logrus.Errorf("unable to set namespace: %q", err) + if rootless.IsRootless() && strings.Contains(err.Error(), "operation not permitted") { + // When running in rootless mode it will fail to re-join + // the network namespace owned by root on the host. + return + } + logrus.Warnf("unable to reset namespace: %q", err) } }() // bind mount the netns from the current thread (from /proc) onto the // mount point. This causes the namespace to persist, even when there - // are no threads in the ns. - err = unix.Mount(getCurrentThreadNetNSPath(), nsPath, "none", unix.MS_BIND, "") + // are no threads in the ns. Make this a shared mount; it needs to be + // back-propogated to the host + err = unix.Mount(threadNsPath, nsPath, "none", unix.MS_BIND|unix.MS_SHARED|unix.MS_REC, "") if err != nil { err = fmt.Errorf("failed to bind mount ns at %s: %v", nsPath, err) } @@ -150,6 +179,11 @@ func NewNS() (ns.NetNS, error) { // UnmountNS unmounts the NS held by the netns object func UnmountNS(ns ns.NetNS) error { + nsRunDir, err := getNSRunDir() + if err != nil { + return err + } + nsPath := ns.Path() // Only unmount if it's been bind-mounted (don't touch namespaces in /proc...) if strings.HasPrefix(nsPath, nsRunDir) { diff --git a/pkg/rootless/rootless_linux.go b/pkg/rootless/rootless_linux.go index ecb84f6a9..6f6239e5f 100644 --- a/pkg/rootless/rootless_linux.go +++ b/pkg/rootless/rootless_linux.go @@ -365,7 +365,7 @@ func GetConfiguredMappings() ([]idtools.IDMap, []idtools.IDMap, error) { } mappings, err := idtools.NewIDMappings(username, username) if err != nil { - logrus.Warnf("cannot find mappings for user %s: %v", username, err) + logrus.Errorf("cannot find mappings for user %s: %v", username, err) } else { uids = mappings.UIDs() gids = mappings.GIDs() diff --git a/pkg/spec/createconfig.go b/pkg/spec/createconfig.go index c17172016..7c3195be4 100644 --- a/pkg/spec/createconfig.go +++ b/pkg/spec/createconfig.go @@ -275,7 +275,7 @@ func (c *CreateConfig) getContainerCreateOptions(runtime *libpod.Runtime, pod *l options = append(options, libpod.WithNetNSFrom(connectedCtr)) } else if !c.NetMode.IsHost() && !c.NetMode.IsNone() { hasUserns := c.UsernsMode.IsContainer() || c.UsernsMode.IsNS() || len(c.IDMappings.UIDMap) > 0 || len(c.IDMappings.GIDMap) > 0 - postConfigureNetNS := c.NetMode.IsSlirp4netns() || (hasUserns && !c.UsernsMode.IsHost()) + postConfigureNetNS := hasUserns && !c.UsernsMode.IsHost() options = append(options, libpod.WithNetNS(portBindings, postConfigureNetNS, string(c.NetMode), networks)) } diff --git a/pkg/spec/spec.go b/pkg/spec/spec.go index 38f9c7306..c7aa003e8 100644 --- a/pkg/spec/spec.go +++ b/pkg/spec/spec.go @@ -387,6 +387,9 @@ func (config *CreateConfig) createConfigToOCISpec(runtime *libpod.Runtime, userM if err != nil { return nil, err } + if !addedResources { + configSpec.Linux.Resources = &spec.LinuxResources{} + } if addedResources && !cgroup2 { return nil, errors.New("invalid configuration, cannot set resources with rootless containers not using cgroups v2 unified mode") } diff --git a/pkg/spec/storage.go b/pkg/spec/storage.go index 3d59d70d8..93919dd0a 100644 --- a/pkg/spec/storage.go +++ b/pkg/spec/storage.go @@ -168,6 +168,9 @@ func (config *CreateConfig) parseVolumes(runtime *libpod.Runtime) ([]spec.Mount, if _, ok := baseMounts[dest]; ok { continue } + if _, ok := baseVolumes[dest]; ok { + continue + } localOpts := options if dest == "/run" { localOpts = append(localOpts, "noexec", "size=65536k") diff --git a/pkg/util/utils.go b/pkg/util/utils.go index 583bf5d18..edcad1d1b 100644 --- a/pkg/util/utils.go +++ b/pkg/util/utils.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path/filepath" + "regexp" "strings" "sync" "time" @@ -16,7 +17,7 @@ import ( "github.com/containers/libpod/pkg/rootless" "github.com/containers/storage" "github.com/containers/storage/pkg/idtools" - "github.com/opencontainers/image-spec/specs-go/v1" + v1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" "github.com/sirupsen/logrus" "github.com/spf13/pflag" @@ -69,6 +70,50 @@ func StringInSlice(s string, sl []string) bool { return false } +// ParseChanges returns key, value(s) pair for given option. +func ParseChanges(option string) (key string, vals []string, err error) { + // Supported format as below + // 1. key=value + // 2. key value + // 3. key ["value","value1"] + if strings.Contains(option, " ") { + // This handles 2 & 3 conditions. + var val string + tokens := strings.SplitAfterN(option, " ", 2) + if len(tokens) < 2 { + return "", []string{}, fmt.Errorf("invalid key value %s", option) + } + key = strings.Trim(tokens[0], " ") // Need to trim whitespace part of delimeter. + val = tokens[1] + if strings.Contains(tokens[1], "[") && strings.Contains(tokens[1], "]") { + //Trim '[',']' if exist. + val = strings.TrimLeft(strings.TrimRight(tokens[1], "]"), "[") + } + vals = strings.Split(val, ",") + } else if strings.Contains(option, "=") { + // handles condition 1. + tokens := strings.Split(option, "=") + key = tokens[0] + vals = tokens[1:] + } else { + // either ` ` or `=` must be provided after command + return "", []string{}, fmt.Errorf("invalid format %s", option) + } + + if len(vals) == 0 { + return "", []string{}, errors.Errorf("no value given for instruction %q", key) + } + + for _, v := range vals { + //each option must not have ' '., `[`` or `]` & empty strings + whitespaces := regexp.MustCompile(`[\[\s\]]`) + if whitespaces.MatchString(v) || len(v) == 0 { + return "", []string{}, fmt.Errorf("invalid value %s", v) + } + } + return key, vals, nil +} + // GetImageConfig converts the --change flag values in the format "CMD=/bin/bash USER=example" // to a type v1.ImageConfig func GetImageConfig(changes []string) (v1.ImageConfig, error) { @@ -87,40 +132,42 @@ func GetImageConfig(changes []string) (v1.ImageConfig, error) { exposedPorts := make(map[string]struct{}) volumes := make(map[string]struct{}) labels := make(map[string]string) - for _, ch := range changes { - pair := strings.Split(ch, "=") - if len(pair) == 1 { - return v1.ImageConfig{}, errors.Errorf("no value given for instruction %q", ch) + key, vals, err := ParseChanges(ch) + if err != nil { + return v1.ImageConfig{}, err } - switch pair[0] { + + switch key { case "USER": - user = pair[1] + user = vals[0] case "EXPOSE": var st struct{} - exposedPorts[pair[1]] = st + exposedPorts[vals[0]] = st case "ENV": - if len(pair) < 3 { - return v1.ImageConfig{}, errors.Errorf("no value given for environment variable %q", pair[1]) + if len(vals) < 2 { + return v1.ImageConfig{}, errors.Errorf("no value given for environment variable %q", vals[0]) } - env = append(env, strings.Join(pair[1:], "=")) + env = append(env, strings.Join(vals[0:], "=")) case "ENTRYPOINT": - entrypoint = append(entrypoint, pair[1]) + // ENTRYPOINT and CMD can have array of strings + entrypoint = append(entrypoint, vals...) case "CMD": - cmd = append(cmd, pair[1]) + // ENTRYPOINT and CMD can have array of strings + cmd = append(cmd, vals...) case "VOLUME": var st struct{} - volumes[pair[1]] = st + volumes[vals[0]] = st case "WORKDIR": - workingDir = pair[1] + workingDir = vals[0] case "LABEL": - if len(pair) == 3 { - labels[pair[1]] = pair[2] + if len(vals) == 2 { + labels[vals[0]] = vals[1] } else { - labels[pair[1]] = "" + labels[vals[0]] = "" } case "STOPSIGNAL": - stopSignal = pair[1] + stopSignal = vals[0] } } diff --git a/pkg/util/utils_test.go b/pkg/util/utils_test.go index f47c0b7ad..c938dc592 100644 --- a/pkg/util/utils_test.go +++ b/pkg/util/utils_test.go @@ -1,8 +1,9 @@ package util import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) var ( @@ -17,3 +18,71 @@ func TestStringInSlice(t *testing.T) { // string is not in empty slice assert.False(t, StringInSlice("one", []string{})) } + +func TestParseChanges(t *testing.T) { + // CMD=/bin/sh + _, vals, err := ParseChanges("CMD=/bin/sh") + assert.EqualValues(t, []string{"/bin/sh"}, vals) + assert.NoError(t, err) + + // CMD [/bin/sh] + _, vals, err = ParseChanges("CMD [/bin/sh]") + assert.EqualValues(t, []string{"/bin/sh"}, vals) + assert.NoError(t, err) + + // CMD ["/bin/sh"] + _, vals, err = ParseChanges(`CMD ["/bin/sh"]`) + assert.EqualValues(t, []string{`"/bin/sh"`}, vals) + assert.NoError(t, err) + + // CMD ["/bin/sh","-c","ls"] + _, vals, err = ParseChanges(`CMD ["/bin/sh","c","ls"]`) + assert.EqualValues(t, []string{`"/bin/sh"`, `"c"`, `"ls"`}, vals) + assert.NoError(t, err) + + // CMD ["/bin/sh","arg-with,comma"] + _, vals, err = ParseChanges(`CMD ["/bin/sh","arg-with,comma"]`) + assert.EqualValues(t, []string{`"/bin/sh"`, `"arg-with`, `comma"`}, vals) + assert.NoError(t, err) + + // CMD "/bin/sh"] + _, _, err = ParseChanges(`CMD "/bin/sh"]`) + assert.Error(t, err) + assert.Equal(t, `invalid value "/bin/sh"]`, err.Error()) + + // CMD [bin/sh + _, _, err = ParseChanges(`CMD "/bin/sh"]`) + assert.Error(t, err) + assert.Equal(t, `invalid value "/bin/sh"]`, err.Error()) + + // CMD ["/bin /sh"] + _, _, err = ParseChanges(`CMD ["/bin /sh"]`) + assert.Error(t, err) + assert.Equal(t, `invalid value "/bin /sh"`, err.Error()) + + // CMD ["/bin/sh", "-c","ls"] whitespace between values + _, vals, err = ParseChanges(`CMD ["/bin/sh", "c","ls"]`) + assert.Error(t, err) + assert.Equal(t, `invalid value "c"`, err.Error()) + + // CMD? + _, _, err = ParseChanges(`CMD?`) + assert.Error(t, err) + assert.Equal(t, `invalid format CMD?`, err.Error()) + + // empty values for CMD + _, _, err = ParseChanges(`CMD `) + assert.Error(t, err) + assert.Equal(t, `invalid value `, err.Error()) + + // LABEL=blue=image + _, vals, err = ParseChanges(`LABEL=blue=image`) + assert.EqualValues(t, []string{"blue", "image"}, vals) + assert.NoError(t, err) + + // LABEL = blue=image + _, vals, err = ParseChanges(`LABEL = blue=image`) + assert.Error(t, err) + assert.Equal(t, `invalid value = blue=image`, err.Error()) + +} diff --git a/pkg/varlinkapi/attach.go b/pkg/varlinkapi/attach.go index 3bd487849..f8557ae0c 100644 --- a/pkg/varlinkapi/attach.go +++ b/pkg/varlinkapi/attach.go @@ -65,7 +65,9 @@ func (i *LibpodAPI) Attach(call iopodman.VarlinkCall, name string, detachKeys st } // ACK the client upgrade request - call.ReplyAttach() + if err := call.ReplyAttach(); err != nil { + return call.ReplyErrorOccurred(err.Error()) + } reader, writer, _, pw, streams := setupStreams(call) |