17170: Improve error messages and command help text.
[arvados.git] / cmd / arvados-client / container_gateway.go
index 1ed6dc2791aea8a5de2cec80348e4f8c5095b01f..e3b6b9332c23c92c0d62ab9417c3af6d56d0c9c2 100644 (file)
@@ -5,6 +5,7 @@
 package main
 
 import (
+       "bytes"
        "context"
        "flag"
        "fmt"
@@ -12,6 +13,7 @@ import (
        "net/url"
        "os"
        "os/exec"
+       "path/filepath"
        "strings"
        "syscall"
 
@@ -27,7 +29,8 @@ func (shellCommand) RunCommand(prog string, args []string, stdin io.Reader, stdo
        f := flag.NewFlagSet(prog, flag.ContinueOnError)
        f.SetOutput(stderr)
        f.Usage = func() {
-               fmt.Print(stderr, prog+`: open an interactive shell on a running container.
+               _, prog := filepath.Split(prog)
+               fmt.Fprint(stderr, prog+`: open an interactive shell on a running container.
 
 Usage: `+prog+` [options] [username@]container-uuid [ssh-options] [remote-command [args...]]
 
@@ -38,8 +41,7 @@ Options:
        detachKeys := f.String("detach-keys", "ctrl-],ctrl-]", "set detach key sequence, as in docker-attach(1)")
        err := f.Parse(args)
        if err != nil {
-               fmt.Println(stderr, err)
-               f.Usage()
+               fmt.Fprintln(stderr, err)
                return 2
        }
 
@@ -53,32 +55,45 @@ Options:
        }
        sshargs := f.Args()[1:]
 
+       // Try setting up a tunnel, and exit right away if it
+       // fails. This tunnel won't get used -- we'll set up a new
+       // tunnel when running as SSH client's ProxyCommand child --
+       // but in most cases where the real tunnel setup would fail,
+       // we catch the problem earlier here. This makes it less
+       // likely that an error message about tunnel setup will get
+       // hidden behind noisy errors from SSH client like this:
+       //
+       // [useful tunnel setup error message here]
+       // kex_exchange_identification: Connection closed by remote host
+       // Connection closed by UNKNOWN port 65535
+       // exit status 255
+       exitcode := connectSSHCommand{}.RunCommand(
+               "arvados-client connect-ssh",
+               []string{"-detach-keys=" + *detachKeys, "-probe-only=true", target},
+               &bytes.Buffer{}, &bytes.Buffer{}, stderr)
+       if exitcode != 0 {
+               return exitcode
+       }
+
        selfbin, err := os.Readlink("/proc/self/exe")
        if err != nil {
                fmt.Fprintln(stderr, err)
                return 2
        }
        sshargs = append([]string{
+               "ssh",
                "-o", "ProxyCommand " + selfbin + " connect-ssh -detach-keys=" + shellescape(*detachKeys) + " " + shellescape(target),
                "-o", "StrictHostKeyChecking no",
                target},
                sshargs...)
-       cmd := exec.Command("ssh", sshargs...)
-       cmd.Stdin = stdin
-       cmd.Stdout = stdout
-       cmd.Stderr = stderr
-       err = cmd.Run()
-       if err == nil {
-               return 0
-       } else if exiterr, ok := err.(*exec.ExitError); !ok {
-               fmt.Fprintln(stderr, err)
-               return 1
-       } else if status, ok := exiterr.Sys().(syscall.WaitStatus); !ok {
+       sshbin, err := exec.LookPath("ssh")
+       if err != nil {
                fmt.Fprintln(stderr, err)
                return 1
-       } else {
-               return status.ExitStatus()
        }
+       err = syscall.Exec(sshbin, sshargs, os.Environ())
+       fmt.Fprintf(stderr, "exec(%q) failed: %s\n", sshbin, err)
+       return 1
 }
 
 // connectSSHCommand connects stdin/stdout to a container's gateway
@@ -92,18 +107,22 @@ func (connectSSHCommand) RunCommand(prog string, args []string, stdin io.Reader,
        f := flag.NewFlagSet(prog, flag.ContinueOnError)
        f.SetOutput(stderr)
        f.Usage = func() {
+               _, prog := filepath.Split(prog)
                fmt.Fprint(stderr, prog+`: connect to the gateway service for a running container.
 
+NOTE: You almost certainly don't want to use this command directly. It
+is meant to be used internally. Use "arvados-client shell" instead.
+
 Usage: `+prog+` [options] [username@]container-uuid
 
 Options:
 `)
                f.PrintDefaults()
        }
+       probeOnly := f.Bool("probe-only", false, "do not transfer IO, just exit 0 immediately if tunnel setup succeeds")
        detachKeys := f.String("detach-keys", "", "set detach key sequence, as in docker-attach(1)")
        if err := f.Parse(args); err != nil {
                fmt.Fprintln(stderr, err)
-               f.Usage()
                return 2
        } else if f.NArg() != 1 {
                f.Usage()
@@ -115,6 +134,10 @@ Options:
                loginUsername = targetUUID[:i]
                targetUUID = targetUUID[i+1:]
        }
+       if os.Getenv("ARVADOS_API_HOST") == "" || os.Getenv("ARVADOS_API_TOKEN") == "" {
+               fmt.Fprintln(stderr, "fatal: ARVADOS_API_HOST and ARVADOS_API_TOKEN environment variables are not set")
+               return 1
+       }
        insecure := os.Getenv("ARVADOS_API_HOST_INSECURE")
        rpcconn := rpc.NewConn("",
                &url.URL{
@@ -142,6 +165,9 @@ Options:
                }
                targetUUID = cr.ContainerUUID
                fmt.Fprintln(stderr, "connecting to container", targetUUID)
+       } else if !strings.Contains(targetUUID, "-dz642-") {
+               fmt.Fprintf(stderr, "target UUID is not a container or container request UUID: %s\n", targetUUID)
+               return 1
        }
        sshconn, err := rpcconn.ContainerSSH(context.TODO(), arvados.ContainerSSHOptions{
                UUID:          targetUUID,
@@ -154,6 +180,10 @@ Options:
        }
        defer sshconn.Conn.Close()
 
+       if *probeOnly {
+               return 0
+       }
+
        ctx, cancel := context.WithCancel(context.Background())
        go func() {
                defer cancel()