17417: Add arm64 packages for our Golang components.
[arvados.git] / cmd / arvados-client / container_gateway.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package main
6
7 import (
8         "bytes"
9         "context"
10         "flag"
11         "fmt"
12         "io"
13         "net/url"
14         "os"
15         "os/exec"
16         "path/filepath"
17         "strings"
18         "syscall"
19
20         "git.arvados.org/arvados.git/lib/controller/rpc"
21         "git.arvados.org/arvados.git/sdk/go/arvados"
22 )
23
24 // shellCommand connects the terminal to an interactive shell on a
25 // running container.
26 type shellCommand struct{}
27
28 func (shellCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
29         f := flag.NewFlagSet(prog, flag.ContinueOnError)
30         f.SetOutput(stderr)
31         f.Usage = func() {
32                 _, prog := filepath.Split(prog)
33                 fmt.Fprint(stderr, prog+`: open an interactive shell on a running container.
34
35 Usage: `+prog+` [options] [username@]container-uuid [ssh-options] [remote-command [args...]]
36
37 Options:
38 `)
39                 f.PrintDefaults()
40         }
41         detachKeys := f.String("detach-keys", "ctrl-],ctrl-]", "set detach key sequence, as in docker-attach(1)")
42         err := f.Parse(args)
43         if err != nil {
44                 fmt.Fprintln(stderr, err)
45                 return 2
46         }
47
48         if f.NArg() < 1 {
49                 f.Usage()
50                 return 2
51         }
52         target := f.Args()[0]
53         if !strings.Contains(target, "@") {
54                 target = "root@" + target
55         }
56         sshargs := f.Args()[1:]
57
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:
65         //
66         // [useful tunnel setup error message here]
67         // kex_exchange_identification: Connection closed by remote host
68         // Connection closed by UNKNOWN port 65535
69         // exit status 255
70         exitcode := connectSSHCommand{}.RunCommand(
71                 "arvados-client connect-ssh",
72                 []string{"-detach-keys=" + *detachKeys, "-probe-only=true", target},
73                 &bytes.Buffer{}, &bytes.Buffer{}, stderr)
74         if exitcode != 0 {
75                 return exitcode
76         }
77
78         selfbin, err := os.Readlink("/proc/self/exe")
79         if err != nil {
80                 fmt.Fprintln(stderr, err)
81                 return 2
82         }
83         sshargs = append([]string{
84                 "ssh",
85                 "-o", "ProxyCommand " + selfbin + " connect-ssh -detach-keys=" + shellescape(*detachKeys) + " " + shellescape(target),
86                 "-o", "StrictHostKeyChecking no",
87                 target},
88                 sshargs...)
89         sshbin, err := exec.LookPath("ssh")
90         if err != nil {
91                 fmt.Fprintln(stderr, err)
92                 return 1
93         }
94         err = syscall.Exec(sshbin, sshargs, os.Environ())
95         fmt.Fprintf(stderr, "exec(%q) failed: %s\n", sshbin, err)
96         return 1
97 }
98
99 // connectSSHCommand connects stdin/stdout to a container's gateway
100 // server (see lib/crunchrun/ssh.go).
101 //
102 // It is intended to be invoked with OpenSSH client's ProxyCommand
103 // config.
104 type connectSSHCommand struct{}
105
106 func (connectSSHCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
107         f := flag.NewFlagSet(prog, flag.ContinueOnError)
108         f.SetOutput(stderr)
109         f.Usage = func() {
110                 _, prog := filepath.Split(prog)
111                 fmt.Fprint(stderr, prog+`: connect to the gateway service for a running container.
112
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.
115
116 Usage: `+prog+` [options] [username@]container-uuid
117
118 Options:
119 `)
120                 f.PrintDefaults()
121         }
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)
126                 return 2
127         } else if f.NArg() != 1 {
128                 f.Usage()
129                 return 2
130         }
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:]
136         }
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")
139                 return 1
140         }
141         insecure := os.Getenv("ARVADOS_API_HOST_INSECURE")
142         rpcconn := rpc.NewConn("",
143                 &url.URL{
144                         Scheme: "https",
145                         Host:   os.Getenv("ARVADOS_API_HOST"),
146                 },
147                 insecure == "1" || insecure == "yes" || insecure == "true",
148                 func(context.Context) ([]string, error) {
149                         return []string{os.Getenv("ARVADOS_API_TOKEN")}, nil
150                 })
151         if strings.Contains(targetUUID, "-xvhdp-") {
152                 crs, err := rpcconn.ContainerRequestList(context.TODO(), arvados.ListOptions{Limit: -1, Filters: []arvados.Filter{{"uuid", "=", targetUUID}}})
153                 if err != nil {
154                         fmt.Fprintln(stderr, err)
155                         return 1
156                 }
157                 if len(crs.Items) < 1 {
158                         fmt.Fprintf(stderr, "container request %q not found\n", targetUUID)
159                         return 1
160                 }
161                 cr := crs.Items[0]
162                 if cr.ContainerUUID == "" {
163                         fmt.Fprintf(stderr, "no container assigned, container request state is %s\n", strings.ToLower(string(cr.State)))
164                         return 1
165                 }
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)
170                 return 1
171         }
172         sshconn, err := rpcconn.ContainerSSH(context.TODO(), arvados.ContainerSSHOptions{
173                 UUID:          targetUUID,
174                 DetachKeys:    *detachKeys,
175                 LoginUsername: loginUsername,
176         })
177         if err != nil {
178                 fmt.Fprintln(stderr, "error setting up tunnel:", err)
179                 return 1
180         }
181         defer sshconn.Conn.Close()
182
183         if *probeOnly {
184                 return 0
185         }
186
187         ctx, cancel := context.WithCancel(context.Background())
188         go func() {
189                 defer cancel()
190                 _, err := io.Copy(stdout, sshconn.Conn)
191                 if err != nil && ctx.Err() == nil {
192                         fmt.Fprintf(stderr, "receive: %v\n", err)
193                 }
194         }()
195         go func() {
196                 defer cancel()
197                 _, err := io.Copy(sshconn.Conn, stdin)
198                 if err != nil && ctx.Err() == nil {
199                         fmt.Fprintf(stderr, "send: %v\n", err)
200                 }
201         }()
202         <-ctx.Done()
203         return 0
204 }
205
206 func shellescape(s string) string {
207         return "'" + strings.Replace(s, "'", "'\\''", -1) + "'"
208 }