summaryrefslogtreecommitdiff
path: root/cmd
diff options
context:
space:
mode:
authorJhon Honce <jhonce@redhat.com>2020-06-04 11:51:29 -0700
committerJhon Honce <jhonce@redhat.com>2020-06-23 08:18:53 -0700
commit7377e578a9402a416579be92cee44c3b3786f81a (patch)
treec1424a43cc606ed11c8b0b5fb5f9f199ab0d83c5 /cmd
parentb2c42a0993d2129c910036d4054ec25129d09f18 (diff)
downloadpodman-7377e578a9402a416579be92cee44c3b3786f81a.tar.gz
podman-7377e578a9402a416579be92cee44c3b3786f81a.tar.bz2
podman-7377e578a9402a416579be92cee44c3b3786f81a.zip
V2 podman system connection
* Implement command * Refactor podman-remote to pull from containers.conf by default * podman-remote defaults to --remote being true * Write podman-system-connection.1.md Signed-off-by: Jhon Honce <jhonce@redhat.com>
Diffstat (limited to 'cmd')
-rw-r--r--cmd/podman/main.go2
-rw-r--r--cmd/podman/registry/config.go3
-rw-r--r--cmd/podman/registry/config_tunnel.go7
-rw-r--r--cmd/podman/root.go17
-rw-r--r--cmd/podman/system/connection.go221
5 files changed, 208 insertions, 42 deletions
diff --git a/cmd/podman/main.go b/cmd/podman/main.go
index 76ec7bc8e..f502e7a67 100644
--- a/cmd/podman/main.go
+++ b/cmd/podman/main.go
@@ -35,7 +35,7 @@ func main() {
_, found := c.Command.Annotations[registry.ParentNSRequired]
if rootless.IsRootless() && found {
c.Command.RunE = func(cmd *cobra.Command, args []string) error {
- return fmt.Errorf("cannot `%s` in rootless mode", cmd.CommandPath())
+ return fmt.Errorf("cannot run command %q in rootless mode", cmd.CommandPath())
}
}
diff --git a/cmd/podman/registry/config.go b/cmd/podman/registry/config.go
index 49d5bca74..a67568d73 100644
--- a/cmd/podman/registry/config.go
+++ b/cmd/podman/registry/config.go
@@ -68,7 +68,6 @@ func newPodmanConfig() {
}
}
- // FIXME: for rootless, add flag to get the path to override configuration
cfg, err := config.NewConfig("")
if err != nil {
fmt.Fprint(os.Stderr, "Failed to obtain podman configuration: "+err.Error())
@@ -83,7 +82,7 @@ func newPodmanConfig() {
podmanOptions = entities.PodmanConfig{Config: cfg, EngineMode: mode}
}
-// SetXdgDirs ensures the XDG_RUNTIME_DIR env and XDG_CONFIG_HOME variables are set.
+// setXdgDirs ensures the XDG_RUNTIME_DIR env and XDG_CONFIG_HOME variables are set.
// containers/image uses XDG_RUNTIME_DIR to locate the auth file, XDG_CONFIG_HOME is
// use for the libpod.conf configuration file.
func setXdgDirs() error {
diff --git a/cmd/podman/registry/config_tunnel.go b/cmd/podman/registry/config_tunnel.go
index bb3da947e..4f9f51163 100644
--- a/cmd/podman/registry/config_tunnel.go
+++ b/cmd/podman/registry/config_tunnel.go
@@ -2,6 +2,13 @@
package registry
+import (
+ "os"
+)
+
func init() {
abiSupport = false
+
+ // Enforce that podman-remote == podman --remote
+ os.Args = append(os.Args, "--remote")
}
diff --git a/cmd/podman/root.go b/cmd/podman/root.go
index 4f834e87d..25e53cbee 100644
--- a/cmd/podman/root.go
+++ b/cmd/podman/root.go
@@ -8,6 +8,7 @@ import (
"runtime/pprof"
"strings"
+ "github.com/containers/common/pkg/config"
"github.com/containers/libpod/cmd/podman/registry"
"github.com/containers/libpod/cmd/podman/validate"
"github.com/containers/libpod/pkg/domain/entities"
@@ -103,13 +104,13 @@ func persistentPreRunE(cmd *cobra.Command, args []string) error {
// TODO: Remove trace statement in podman V2.1
logrus.Debugf("Called %s.PersistentPreRunE(%s)", cmd.Name(), strings.Join(os.Args, " "))
- cfg := registry.PodmanConfig()
-
// Help is a special case, no need for more setup
if cmd.Name() == "help" {
return nil
}
+ cfg := registry.PodmanConfig()
+
// Prep the engines
if _, err := registry.NewImageEngine(cmd, args); err != nil {
return err
@@ -211,10 +212,14 @@ func loggingHook() {
func rootFlags(opts *entities.PodmanConfig, flags *pflag.FlagSet) {
// V2 flags
flags.BoolVarP(&opts.Remote, "remote", "r", false, "Access remote Podman service (default false)")
- // TODO Read uri from containers.config when available
- flags.StringVar(&opts.URI, "url", registry.DefaultAPIAddress(), "URL to access Podman service (CONTAINER_HOST)")
- flags.StringSliceVar(&opts.Identities, "identity", []string{}, "path to SSH identity file, (CONTAINER_SSHKEY)")
- flags.StringVar(&opts.PassPhrase, "passphrase", "", "passphrase for identity file (not secure, CONTAINER_PASSPHRASE), ssh-agent always supported")
+
+ custom, _ := config.ReadCustomConfig()
+ defaultURI := custom.Engine.RemoteURI
+ if defaultURI == "" {
+ defaultURI = registry.DefaultAPIAddress()
+ }
+ flags.StringVar(&opts.URI, "url", defaultURI, "URL to access Podman service (CONTAINER_HOST)")
+ flags.StringVar(&opts.Identity, "identity", custom.Engine.RemoteIdentity, "path to SSH identity file, (CONTAINER_SSHKEY)")
cfg := opts.Config
flags.StringVar(&cfg.Engine.CgroupManager, "cgroup-manager", cfg.Engine.CgroupManager, "Cgroup manager to use (\"cgroupfs\"|\"systemd\")")
diff --git a/cmd/podman/system/connection.go b/cmd/podman/system/connection.go
index 3af905fad..d8c709d6e 100644
--- a/cmd/podman/system/connection.go
+++ b/cmd/podman/system/connection.go
@@ -1,54 +1,209 @@
-// +build !remote
-
package system
import (
+ "bytes"
+ "fmt"
+ "net"
+ "net/url"
+ "os"
+ "os/user"
+ "regexp"
+
+ "github.com/containers/common/pkg/config"
"github.com/containers/libpod/cmd/podman/registry"
+ "github.com/containers/libpod/libpod/define"
"github.com/containers/libpod/pkg/domain/entities"
+ "github.com/containers/libpod/pkg/terminal"
+ "github.com/pkg/errors"
+ "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
+ "golang.org/x/crypto/ssh"
+ "golang.org/x/crypto/ssh/agent"
)
+const schemaPattern = "^[A-Za-z][A-Za-z0-9+.-]*:"
+
var (
- connectionDescription = `TBD
-`
- connectionCommand = &cobra.Command{
- Use: "connection",
- //Args: validate.NoArgs,
- Long: connectionDescription,
- Short: "Add remote ssh connection",
- RunE: connection,
- Example: `podman system connection server.foobar.com
-podman system connection --identity ~/.ssh/dev_rsa --default root@server.foobar.com:222`,
+ // Skip creating engines since this command will obtain connection information to engine
+ noOp = func(cmd *cobra.Command, args []string) error {
+ return nil
+ }
+ connectionCmd = &cobra.Command{
+ Use: "connection [flags] destination",
+ Args: cobra.ExactArgs(1),
+ Long: `Store ssh destination information in podman configuration.
+ "destination" is of the form [user@]hostname or
+ an URI of the form ssh://[user@]hostname[:port]
+`,
+ Short: "Record remote ssh destination",
+ PersistentPreRunE: noOp,
+ PersistentPostRunE: noOp,
+ TraverseChildren: false,
+ RunE: connection,
+ Example: `podman system connection server.fubar.com
+ podman system connection --identity ~/.ssh/dev_rsa ssh://root@server.fubar.com:2222
+ podman system connection --identity ~/.ssh/dev_rsa -port 22 root@server.fubar.com`,
}
-)
-var connectionOptions = struct {
- Alias string
- Default bool
- Identity string
- SocketPath string
- User string
-}{}
+ cOpts = struct {
+ Identity string
+ Port int
+ UDSPath string
+ }{}
+)
func init() {
registry.Commands = append(registry.Commands, registry.CliCommand{
- Mode: []entities.EngineMode{entities.ABIMode},
- Command: connectionCommand,
+ Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
+ Command: connectionCmd,
Parent: systemCmd,
})
- flags := connectionCommand.Flags()
- flags.StringVar(&connectionOptions.Alias, "alias", "", "alias name for connection")
- flags.BoolVar(&connectionOptions.Default, "default", false, "set as the default connection")
- flags.StringVar(&connectionOptions.Identity, "identity", "", "path to ssh identity file")
- //flags.StringVar(&connectionOptions.User, "user", "", "remote username")
- flags.StringVar(&connectionOptions.SocketPath, "socket-path", "", "path to podman socket on remote host")
+
+ flags := connectionCmd.Flags()
+ flags.StringVar(&cOpts.Identity, "identity", "", "path to ssh identity file")
+ flags.IntVarP(&cOpts.Port, "port", "p", 22, "port number for destination")
+ flags.StringVar(&cOpts.UDSPath, "socket-path", "", "path to podman socket on remote host. (default '/run/podman/podman.sock' or '/run/user/{uid}/podman/podman.sock)")
}
func connection(cmd *cobra.Command, args []string) error {
- // if no user is provided, assume local user name
- // if no socket is provided, then do an ssh to look for it
- // default connection, if exists, is then assumed with podman remote
- // if no identity exists, should we be prompting for password?
+ // Default to ssh: schema if none given
+ dest := []byte(args[0])
+ if match, err := regexp.Match(schemaPattern, dest); err != nil {
+ return errors.Wrapf(err, "internal regex error %q", schemaPattern)
+ } else if !match {
+ dest = append([]byte("ssh://"), dest...)
+ }
+
+ uri, err := url.Parse(string(dest))
+ if err != nil {
+ return errors.Wrapf(err, "failed to parse %q", string(dest))
+ }
+
+ if uri.User.Username() == "" {
+ if uri.User, err = getUserInfo(uri); err != nil {
+ return err
+ }
+ }
+
+ if cmd.Flag("socket-path").Changed {
+ uri.Path = cmd.Flag("socket-path").Value.String()
+ }
+
+ if cmd.Flag("port").Changed {
+ uri.Host = net.JoinHostPort(uri.Hostname(), cmd.Flag("port").Value.String())
+ }
+
+ if uri.Port() == "" {
+ uri.Host = net.JoinHostPort(uri.Hostname(), cmd.Flag("port").DefValue)
+ }
+
+ if uri.Path == "" {
+ if uri.Path, err = getUDS(cmd, uri); err != nil {
+ return errors.Wrapf(err, "failed to connect to %q", uri.String())
+ }
+ }
+
+ custom, err := config.ReadCustomConfig()
+ if err != nil {
+ return err
+ }
+
+ if cmd.Flag("identity").Changed {
+ custom.Engine.RemoteIdentity = cOpts.Identity
+ }
+
+ custom.Engine.RemoteURI = uri.String()
+ return custom.Write()
+}
+
+func getUserInfo(uri *url.URL) (*url.Userinfo, error) {
+ var (
+ usr *user.User
+ err error
+ )
+ if u, found := os.LookupEnv("_CONTAINERS_ROOTLESS_UID"); found {
+ usr, err = user.LookupId(u)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to find user %q", u)
+ }
+ } else {
+ usr, err = user.Current()
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to obtain current user")
+ }
+ }
+
+ pw, set := uri.User.Password()
+ if set {
+ return url.UserPassword(usr.Username, pw), nil
+ }
+ return url.User(usr.Username), nil
+}
+
+func getUDS(cmd *cobra.Command, uri *url.URL) (string, error) {
+ var authMethods []ssh.AuthMethod
+ passwd, set := uri.User.Password()
+ if set {
+ authMethods = append(authMethods, ssh.Password(passwd))
+ }
+
+ ident := cmd.Flag("identity")
+ if ident.Changed {
+ auth, err := terminal.PublicKey(ident.Value.String(), []byte(passwd))
+ if err != nil {
+ return "", errors.Wrapf(err, "Failed to read identity %q", ident.Value.String())
+ }
+ authMethods = append(authMethods, auth)
+ }
+
+ if sock, found := os.LookupEnv("SSH_AUTH_SOCK"); found {
+ logrus.Debugf("Found SSH_AUTH_SOCK %q, ssh-agent signer enabled", sock)
+
+ c, err := net.Dial("unix", sock)
+ if err != nil {
+ return "", err
+ }
+ a := agent.NewClient(c)
+ authMethods = append(authMethods, ssh.PublicKeysCallback(a.Signers))
+ }
- return nil
+ config := &ssh.ClientConfig{
+ User: uri.User.Username(),
+ Auth: authMethods,
+ HostKeyCallback: ssh.InsecureIgnoreHostKey(),
+ }
+ dial, err := ssh.Dial("tcp", uri.Host, config)
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to connect to %q", uri.Host)
+ }
+ defer dial.Close()
+
+ session, err := dial.NewSession()
+ if err != nil {
+ return "", errors.Wrapf(err, "failed to create new ssh session on %q", uri.Host)
+ }
+ defer session.Close()
+
+ // Override podman binary for testing etc
+ podman := "podman"
+ if v, found := os.LookupEnv("PODMAN_BINARY"); found {
+ podman = v
+ }
+ run := podman + " info --format=json"
+
+ var buffer bytes.Buffer
+ session.Stdout = &buffer
+ if err := session.Run(run); err != nil {
+ return "", errors.Wrapf(err, "failed to run %q", run)
+ }
+
+ var info define.Info
+ if err := json.Unmarshal(buffer.Bytes(), &info); err != nil {
+ return "", errors.Wrapf(err, "failed to parse 'podman info' results")
+ }
+
+ if info.Host.RemoteSocket == nil || !info.Host.RemoteSocket.Exists {
+ return "", fmt.Errorf("remote podman %q failed to report its UDS socket", uri.Host)
+ }
+ return info.Host.RemoteSocket.Path, nil
}