1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
20 "git.arvados.org/arvados.git/lib/controller/rpc"
21 "git.arvados.org/arvados.git/sdk/go/arvados"
24 // shellCommand connects the terminal to an interactive shell on a
26 type shellCommand struct{}
28 func (shellCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
29 f := flag.NewFlagSet(prog, flag.ContinueOnError)
32 _, prog := filepath.Split(prog)
33 fmt.Fprint(stderr, prog+`: open an interactive shell on a running container.
35 Usage: `+prog+` [options] [username@]container-uuid [ssh-options] [remote-command [args...]]
41 detachKeys := f.String("detach-keys", "ctrl-],ctrl-]", "set detach key sequence, as in docker-attach(1)")
44 fmt.Fprintln(stderr, err)
53 if !strings.Contains(target, "@") {
54 target = "root@" + target
56 sshargs := f.Args()[1:]
58 // Try setting up a tunnel, and exit right away if it
59 // fails. This tunnel won't get used -- we'll set up a new
60 // tunnel when running as SSH client's ProxyCommand child --
61 // but in most cases where the real tunnel setup would fail,
62 // we catch the problem earlier here. This makes it less
63 // likely that an error message about tunnel setup will get
64 // hidden behind noisy errors from SSH client like this:
66 // [useful tunnel setup error message here]
67 // kex_exchange_identification: Connection closed by remote host
68 // Connection closed by UNKNOWN port 65535
70 exitcode := connectSSHCommand{}.RunCommand(
71 "arvados-client connect-ssh",
72 []string{"-detach-keys=" + *detachKeys, "-probe-only=true", target},
73 &bytes.Buffer{}, &bytes.Buffer{}, stderr)
78 selfbin, err := os.Readlink("/proc/self/exe")
80 fmt.Fprintln(stderr, err)
83 sshargs = append([]string{
85 "-o", "ProxyCommand " + selfbin + " connect-ssh -detach-keys=" + shellescape(*detachKeys) + " " + shellescape(target),
86 "-o", "StrictHostKeyChecking no",
89 sshbin, err := exec.LookPath("ssh")
91 fmt.Fprintln(stderr, err)
94 err = syscall.Exec(sshbin, sshargs, os.Environ())
95 fmt.Fprintf(stderr, "exec(%q) failed: %s\n", sshbin, err)
99 // connectSSHCommand connects stdin/stdout to a container's gateway
100 // server (see lib/crunchrun/ssh.go).
102 // It is intended to be invoked with OpenSSH client's ProxyCommand
104 type connectSSHCommand struct{}
106 func (connectSSHCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
107 f := flag.NewFlagSet(prog, flag.ContinueOnError)
110 _, prog := filepath.Split(prog)
111 fmt.Fprint(stderr, prog+`: connect to the gateway service for a running container.
113 NOTE: You almost certainly don't want to use this command directly. It
114 is meant to be used internally. Use "arvados-client shell" instead.
116 Usage: `+prog+` [options] [username@]container-uuid
122 probeOnly := f.Bool("probe-only", false, "do not transfer IO, just exit 0 immediately if tunnel setup succeeds")
123 detachKeys := f.String("detach-keys", "", "set detach key sequence, as in docker-attach(1)")
124 if err := f.Parse(args); err != nil {
125 fmt.Fprintln(stderr, err)
127 } else if f.NArg() != 1 {
131 targetUUID := f.Args()[0]
132 loginUsername := "root"
133 if i := strings.Index(targetUUID, "@"); i >= 0 {
134 loginUsername = targetUUID[:i]
135 targetUUID = targetUUID[i+1:]
137 if os.Getenv("ARVADOS_API_HOST") == "" || os.Getenv("ARVADOS_API_TOKEN") == "" {
138 fmt.Fprintln(stderr, "fatal: ARVADOS_API_HOST and ARVADOS_API_TOKEN environment variables are not set")
141 insecure := os.Getenv("ARVADOS_API_HOST_INSECURE")
142 rpcconn := rpc.NewConn("",
145 Host: os.Getenv("ARVADOS_API_HOST"),
147 insecure == "1" || insecure == "yes" || insecure == "true",
148 func(context.Context) ([]string, error) {
149 return []string{os.Getenv("ARVADOS_API_TOKEN")}, nil
151 if strings.Contains(targetUUID, "-xvhdp-") {
152 crs, err := rpcconn.ContainerRequestList(context.TODO(), arvados.ListOptions{Limit: -1, Filters: []arvados.Filter{{"uuid", "=", targetUUID}}})
154 fmt.Fprintln(stderr, err)
157 if len(crs.Items) < 1 {
158 fmt.Fprintf(stderr, "container request %q not found\n", targetUUID)
162 if cr.ContainerUUID == "" {
163 fmt.Fprintf(stderr, "no container assigned, container request state is %s\n", strings.ToLower(string(cr.State)))
166 targetUUID = cr.ContainerUUID
167 fmt.Fprintln(stderr, "connecting to container", targetUUID)
168 } else if !strings.Contains(targetUUID, "-dz642-") {
169 fmt.Fprintf(stderr, "target UUID is not a container or container request UUID: %s\n", targetUUID)
172 sshconn, err := rpcconn.ContainerSSH(context.TODO(), arvados.ContainerSSHOptions{
174 DetachKeys: *detachKeys,
175 LoginUsername: loginUsername,
178 fmt.Fprintln(stderr, "error setting up tunnel:", err)
181 defer sshconn.Conn.Close()
187 ctx, cancel := context.WithCancel(context.Background())
190 _, err := io.Copy(stdout, sshconn.Conn)
191 if err != nil && ctx.Err() == nil {
192 fmt.Fprintf(stderr, "receive: %v\n", err)
197 _, err := io.Copy(sshconn.Conn, stdin)
198 if err != nil && ctx.Err() == nil {
199 fmt.Fprintf(stderr, "send: %v\n", err)
206 func shellescape(s string) string {
207 return "'" + strings.Replace(s, "'", "'\\''", -1) + "'"