1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
24 "git.arvados.org/arvados.git/lib/cmd"
25 "git.arvados.org/arvados.git/lib/controller/rpc"
26 "git.arvados.org/arvados.git/sdk/go/arvados"
29 // logsCommand displays logs from a running container.
30 type logsCommand struct {
34 func (lc logsCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
35 f := flag.NewFlagSet(prog, flag.ContinueOnError)
36 follow := f.Bool("f", false, "follow: poll for new data until the container finishes")
37 pollInterval := f.Duration("poll", time.Second*2, "minimum duration to wait before polling for new data")
38 if ok, code := cmd.ParseFlags(f, prog, args, "container-request-uuid", stderr); !ok {
40 } else if f.NArg() < 1 {
41 fmt.Fprintf(stderr, "missing required argument: container-request-uuid (try -help)\n")
43 } else if f.NArg() > 1 {
44 fmt.Fprintf(stderr, "encountered extra arguments after container-request-uuid (try -help)\n")
49 lc.ac = arvados.NewClientFromEnv()
50 lc.ac.Client = &http.Client{}
52 lc.ac.Client.Transport = &http.Transport{
53 TLSClientConfig: &tls.Config{
54 InsecureSkipVerify: true}}
57 err := lc.tail(target, stdout, stderr, *follow, *pollInterval)
59 fmt.Fprintln(stderr, err)
65 func (lc *logsCommand) tail(crUUID string, stdout, stderr io.Writer, follow bool, pollInterval time.Duration) error {
66 ctx, cancel := context.WithCancel(context.Background())
69 rpcconn, err := rpcFromEnv()
73 err = lc.checkAPISupport(ctx, crUUID)
80 watching = []string{"crunch-run.txt", "stderr.txt"}
81 // fnm => file offset of next byte to display
82 mark = map[string]int64{}
83 // fnm => current size of file reported by api
84 size = map[string]int64{}
85 // has anything worked? (if so, retry after errors)
87 // container UUID whose logs we are displaying
89 // container UUID we last showed in a "connected,
94 cr, err := rpcconn.ContainerRequestGet(ctx, arvados.GetOptions{UUID: crUUID, Select: []string{"uuid", "container_uuid", "state"}})
96 return fmt.Errorf("error retrieving %s: %w", crUUID, err)
98 displayingUUID = cr.ContainerUUID
100 for delay := pollInterval; ; time.Sleep(delay) {
101 if cr.ContainerUUID == "" {
102 return fmt.Errorf("%s has no assigned container (state is %s)", crUUID, cr.State)
104 if delay < pollInterval {
107 // When .../container_requests/{uuid}/log_events is
108 // implemented, we'll wait here for the next
109 // server-sent event to tell us some updated file
110 // sizes. For now, we poll.
111 for _, fnm := range watching {
112 currentsize, _, err := lc.copyRange(ctx, cr.UUID, displayingUUID, fnm, "-0", nil)
117 fmt.Fprintln(stderr, err)
121 if reportedUUID != displayingUUID {
122 fmt.Fprintln(stderr, "connected, polling for log data from container", displayingUUID)
123 reportedUUID = displayingUUID
125 size[fnm] = currentsize
126 if oldsize, seen := mark[fnm]; !seen && currentsize > 10000 {
127 mark[fnm] = currentsize - 10000
130 } else if currentsize < oldsize {
131 // Log collection must have been
132 // emptied and reset.
133 fmt.Fprintln(stderr, "--- log restarted ---")
134 mark = map[string]int64{}
139 newData := map[string]*bytes.Buffer{}
140 for _, fnm := range watching {
141 if size[fnm] > mark[fnm] {
142 newData[fnm] = &bytes.Buffer{}
143 _, n, err := lc.copyRange(ctx, cr.UUID, displayingUUID, fnm, fmt.Sprintf("%d-", mark[fnm]), newData[fnm])
145 fmt.Fprintln(stderr, err)
153 checkState := lc.display(stdout, stderr, watching, newData)
154 if displayingUUID != cr.ContainerUUID {
155 // A different container had already been
156 // assigned when we started fetching the
157 // latest batch of logs. We can now safely
158 // start displaying logs from the new
159 // container, without missing any of the
160 // previous container's logs.
161 displayingUUID = cr.ContainerUUID
164 } else if cr.State == arvados.ContainerRequestStateFinal || !follow {
166 } else if len(newData) > 0 {
170 if delay > pollInterval*5 {
171 delay = pollInterval * 5
176 cr, err = rpcconn.ContainerRequestGet(ctx, arvados.GetOptions{UUID: crUUID, Select: []string{"uuid", "container_uuid", "state"}})
179 return fmt.Errorf("error retrieving %s: %w", crUUID, err)
181 fmt.Fprintln(stderr, err)
190 func (lc *logsCommand) srcURL(crUUID, cUUID, fnm string) string {
194 Path: "/arvados/v1/container_requests/" + crUUID + "/log/" + cUUID + "/" + fnm,
199 // Check whether the API is new enough to support the
200 // .../container_requests/{uuid}/log/ endpoint.
202 // Older versions return 200 for an OPTIONS request at the .../log/
203 // API endpoint, but the response header does not have a "Dav" header.
205 // Note an error response with no "Dav" header is not taken to
206 // indicate lack of API support. It may come from a new server that
207 // has a configuration or networking problem.
208 func (lc *logsCommand) checkAPISupport(ctx context.Context, crUUID string) error {
209 ctx, cancel := context.WithDeadline(ctx, time.Now().Add(20*time.Second))
211 req, err := http.NewRequestWithContext(ctx, "OPTIONS", strings.TrimSuffix(lc.srcURL(crUUID, "", ""), "/"), nil)
215 req.Header.Set("Authorization", "Bearer "+lc.ac.AuthToken)
216 resp, err := lc.ac.Client.Do(req)
220 defer resp.Body.Close()
221 if resp.StatusCode == http.StatusOK && resp.Header.Get("Dav") == "" {
222 return fmt.Errorf("server does not support container logs API (OPTIONS request returned HTTP %s, Dav: %q)", resp.Status, resp.Header.Get("Dav"))
227 // Retrieve specified byte range (e.g., "12-34", "1234-") from given
228 // fnm and write to out.
230 // If range is empty ("-0"), out can be nil.
232 // Return values are current file size, bytes copied, error.
234 // If the file does not exist, return values are 0, 0, nil.
235 func (lc *logsCommand) copyRange(ctx context.Context, crUUID, cUUID, fnm, byterange string, out io.Writer) (int64, int64, error) {
236 ctx, cancel := context.WithDeadline(ctx, time.Now().Add(20*time.Second))
238 req, err := http.NewRequestWithContext(ctx, http.MethodGet, lc.srcURL(crUUID, cUUID, fnm), nil)
242 req.Header.Set("Range", "bytes="+byterange)
243 req.Header.Set("Authorization", "Bearer "+lc.ac.AuthToken)
244 resp, err := lc.ac.Client.Do(req)
248 defer resp.Body.Close()
249 if resp.StatusCode == http.StatusNotFound {
252 if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
253 body, _ := io.ReadAll(io.LimitReader(resp.Body, 10000))
254 return 0, 0, fmt.Errorf("error getting %s: HTTP %s -- %s", fnm, resp.Status, bytes.TrimSuffix(body, []byte{'\n'}))
256 var rstart, rend, rsize int64
257 _, err = fmt.Sscanf(resp.Header.Get("Content-Range"), "bytes %d-%d/%d", &rstart, &rend, &rsize)
259 return 0, 0, fmt.Errorf("error parsing Content-Range header %q: %s", resp.Header.Get("Content-Range"), err)
264 n, err := io.Copy(out, resp.Body)
268 // display some log data, formatted as desired (prefixing each line
269 // with a tag indicating which file it came from, etc.).
271 // Return value is true if the log data contained a hint that it's a
272 // good time to check whether the container is finished so we can
274 func (lc *logsCommand) display(out, stderr io.Writer, watching []string, received map[string]*bytes.Buffer) bool {
277 for _, fnm := range watching {
279 if buf == nil || buf.Len() == 0 {
282 for _, line := range bytes.Split(bytes.TrimSuffix(buf.Bytes(), []byte{'\n'}), []byte{'\n'}) {
283 sorted = append(sorted, fmt.Sprintf("%-14s %s\n", fnm, line))
284 if fnm == "crunch-run.txt" {
285 checkState = checkState ||
286 bytes.HasSuffix(line, []byte("Complete")) ||
287 bytes.HasSuffix(line, []byte("Cancelled")) ||
288 bytes.HasSuffix(line, []byte("Queued"))
292 sort.Slice(sorted, func(i, j int) bool {
293 return sorted[i][15:] < sorted[j][15:]
295 for _, s := range sorted {
296 _, err := fmt.Fprint(out, s)
298 fmt.Fprintln(stderr, err)
304 // shellCommand connects the terminal to an interactive shell on a
305 // running container.
306 type shellCommand struct{}
308 func (shellCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
309 f := flag.NewFlagSet(prog, flag.ContinueOnError)
310 detachKeys := f.String("detach-keys", "ctrl-],ctrl-]", "set detach key sequence, as in docker-attach(1)")
311 if ok, code := cmd.ParseFlags(f, prog, args, "[username@]container-uuid [ssh-options] [remote-command [args...]]", stderr); !ok {
313 } else if f.NArg() < 1 {
314 fmt.Fprintf(stderr, "missing required argument: container-uuid (try -help)\n")
317 target := f.Args()[0]
318 if !strings.Contains(target, "@") {
319 target = "root@" + target
321 sshargs := f.Args()[1:]
323 // Try setting up a tunnel, and exit right away if it
324 // fails. This tunnel won't get used -- we'll set up a new
325 // tunnel when running as SSH client's ProxyCommand child --
326 // but in most cases where the real tunnel setup would fail,
327 // we catch the problem earlier here. This makes it less
328 // likely that an error message about tunnel setup will get
329 // hidden behind noisy errors from SSH client like this:
331 // [useful tunnel setup error message here]
332 // kex_exchange_identification: Connection closed by remote host
333 // Connection closed by UNKNOWN port 65535
336 // In case our target is a container request, the probe also
337 // resolves it to a container, so we don't connect to two
338 // different containers in a race.
339 var probetarget bytes.Buffer
340 exitcode := connectSSHCommand{}.RunCommand(
341 "arvados-client connect-ssh",
342 []string{"-detach-keys=" + *detachKeys, "-probe-only=true", target},
343 &bytes.Buffer{}, &probetarget, stderr)
347 target = strings.Trim(probetarget.String(), "\n")
349 selfbin, err := os.Readlink("/proc/self/exe")
351 fmt.Fprintln(stderr, err)
354 sshargs = append([]string{
356 "-o", "ProxyCommand " + selfbin + " connect-ssh -detach-keys=" + shellescape(*detachKeys) + " " + shellescape(target),
357 "-o", "StrictHostKeyChecking no",
360 sshbin, err := exec.LookPath("ssh")
362 fmt.Fprintln(stderr, err)
365 err = syscall.Exec(sshbin, sshargs, os.Environ())
366 fmt.Fprintf(stderr, "exec(%q) failed: %s\n", sshbin, err)
370 // connectSSHCommand connects stdin/stdout to a container's gateway
371 // server (see lib/crunchrun/ssh.go).
373 // It is intended to be invoked with OpenSSH client's ProxyCommand
375 type connectSSHCommand struct{}
377 func (connectSSHCommand) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
378 f := flag.NewFlagSet(prog, flag.ContinueOnError)
381 _, prog := filepath.Split(prog)
382 fmt.Fprint(stderr, prog+`: connect to the gateway service for a running container.
384 NOTE: You almost certainly don't want to use this command directly. It
385 is meant to be used internally. Use "arvados-client shell" instead.
387 Usage: `+prog+` [options] [username@]container-uuid
393 probeOnly := f.Bool("probe-only", false, "do not transfer IO, just setup tunnel, print target UUID, and exit")
394 detachKeys := f.String("detach-keys", "", "set detach key sequence, as in docker-attach(1)")
395 if ok, code := cmd.ParseFlags(f, prog, args, "[username@]container-uuid", stderr); !ok {
397 } else if f.NArg() != 1 {
398 fmt.Fprintf(stderr, "missing required argument: [username@]container-uuid\n")
401 targetUUID := f.Args()[0]
402 loginUsername := "root"
403 if i := strings.Index(targetUUID, "@"); i >= 0 {
404 loginUsername = targetUUID[:i]
405 targetUUID = targetUUID[i+1:]
407 rpcconn, err := rpcFromEnv()
409 fmt.Fprintln(stderr, err)
412 targetUUID, err = resolveToContainerUUID(rpcconn, targetUUID)
414 fmt.Fprintln(stderr, err)
417 fmt.Fprintln(stderr, "connecting to container", targetUUID)
419 ctx, cancel := context.WithCancel(context.Background())
421 sshconn, err := rpcconn.ContainerSSH(ctx, arvados.ContainerSSHOptions{
423 DetachKeys: *detachKeys,
424 LoginUsername: loginUsername,
427 fmt.Fprintln(stderr, "error setting up tunnel:", err)
430 defer sshconn.Conn.Close()
433 fmt.Fprintln(stdout, targetUUID)
439 _, err := io.Copy(stdout, sshconn.Conn)
440 if err != nil && ctx.Err() == nil {
441 fmt.Fprintf(stderr, "receive: %v\n", err)
446 _, err := io.Copy(sshconn.Conn, stdin)
447 if err != nil && ctx.Err() == nil {
448 fmt.Fprintf(stderr, "send: %v\n", err)
455 func shellescape(s string) string {
456 return "'" + strings.Replace(s, "'", "'\\''", -1) + "'"
459 func rpcFromEnv() (*rpc.Conn, error) {
460 ac := arvados.NewClientFromEnv()
461 if ac.APIHost == "" || ac.AuthToken == "" {
462 return nil, fmt.Errorf("fatal: ARVADOS_API_HOST and ARVADOS_API_TOKEN environment variables are not set, and ~/.config/arvados/settings.conf is not readable")
464 return rpc.NewConn("",
470 func(context.Context) ([]string, error) {
471 return []string{ac.AuthToken}, nil
475 func resolveToContainerUUID(rpcconn *rpc.Conn, targetUUID string) (string, error) {
477 case strings.Contains(targetUUID, "-dz642-") && len(targetUUID) == 27:
478 return targetUUID, nil
479 case strings.Contains(targetUUID, "-xvhdp-") && len(targetUUID) == 27:
480 crs, err := rpcconn.ContainerRequestList(context.TODO(), arvados.ListOptions{Limit: -1, Filters: []arvados.Filter{{"uuid", "=", targetUUID}}})
484 if len(crs.Items) < 1 {
485 return "", fmt.Errorf("container request %q not found", targetUUID)
488 if cr.ContainerUUID == "" {
489 return "", fmt.Errorf("no container assigned, container request state is %s", strings.ToLower(string(cr.State)))
491 return cr.ContainerUUID, nil
493 return "", fmt.Errorf("target UUID is not a container or container request UUID: %s", targetUUID)