17344: Load alpine docker image for diagnostics.
[arvados.git] / lib / diagnostics / cmd.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package diagnostics
6
7 import (
8         "bytes"
9         "context"
10         "flag"
11         "fmt"
12         "io"
13         "io/ioutil"
14         "net"
15         "net/http"
16         "net/url"
17         "strings"
18         "time"
19
20         "git.arvados.org/arvados.git/lib/cmd"
21         "git.arvados.org/arvados.git/sdk/go/arvados"
22         "git.arvados.org/arvados.git/sdk/go/ctxlog"
23         "github.com/sirupsen/logrus"
24 )
25
26 type Command struct{}
27
28 func (Command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
29         var diag diagnoser
30         f := flag.NewFlagSet(prog, flag.ContinueOnError)
31         f.StringVar(&diag.projectName, "project-name", "scratch area for diagnostics", "name of project to find/create in home project and use for temporary/test objects")
32         f.StringVar(&diag.logLevel, "log-level", "info", "logging level (debug, info, warning, error)")
33         f.StringVar(&diag.dockerImage, "docker-image", "alpine:latest", "image to use when running a test container")
34         f.BoolVar(&diag.checkInternal, "internal-client", false, "check that this host is considered an \"internal\" client")
35         f.BoolVar(&diag.checkExternal, "external-client", false, "check that this host is considered an \"external\" client")
36         f.IntVar(&diag.priority, "priority", 500, "priority for test container (1..1000, or 0 to skip)")
37         f.DurationVar(&diag.timeout, "timeout", 10*time.Second, "timeout for http requests")
38         if ok, code := cmd.ParseFlags(f, prog, args, "", stderr); !ok {
39                 return code
40         }
41         diag.logger = ctxlog.New(stdout, "text", diag.logLevel)
42         diag.logger.SetFormatter(&logrus.TextFormatter{DisableTimestamp: true, DisableLevelTruncation: true, PadLevelText: true})
43         diag.runtests()
44         if len(diag.errors) == 0 {
45                 diag.logger.Info("--- no errors ---")
46                 return 0
47         } else {
48                 if diag.logger.Level > logrus.ErrorLevel {
49                         fmt.Fprint(stdout, "\n--- cut here --- error summary ---\n\n")
50                         for _, e := range diag.errors {
51                                 diag.logger.Error(e)
52                         }
53                 }
54                 return 1
55         }
56 }
57
58 type diagnoser struct {
59         stdout        io.Writer
60         stderr        io.Writer
61         logLevel      string
62         priority      int
63         projectName   string
64         dockerImage   string
65         checkInternal bool
66         checkExternal bool
67         timeout       time.Duration
68         logger        *logrus.Logger
69         errors        []string
70         done          map[int]bool
71 }
72
73 func (diag *diagnoser) debugf(f string, args ...interface{}) {
74         diag.logger.Debugf("  ... "+f, args...)
75 }
76
77 func (diag *diagnoser) infof(f string, args ...interface{}) {
78         diag.logger.Infof("  ... "+f, args...)
79 }
80
81 func (diag *diagnoser) warnf(f string, args ...interface{}) {
82         diag.logger.Warnf("  ... "+f, args...)
83 }
84
85 func (diag *diagnoser) errorf(f string, args ...interface{}) {
86         diag.logger.Errorf(f, args...)
87         diag.errors = append(diag.errors, fmt.Sprintf(f, args...))
88 }
89
90 // Run the given func, logging appropriate messages before and after,
91 // adding timing info, etc.
92 //
93 // The id argument should be unique among tests, and shouldn't change
94 // when other tests are added/removed.
95 func (diag *diagnoser) dotest(id int, title string, fn func() error) {
96         if diag.done == nil {
97                 diag.done = map[int]bool{}
98         } else if diag.done[id] {
99                 diag.errorf("(bug) reused test id %d", id)
100         }
101         diag.done[id] = true
102
103         diag.logger.Infof("%4d: %s", id, title)
104         t0 := time.Now()
105         err := fn()
106         elapsed := fmt.Sprintf("%d ms", time.Now().Sub(t0)/time.Millisecond)
107         if err != nil {
108                 diag.errorf("%4d: %s (%s): %s", id, title, elapsed, err)
109         } else {
110                 diag.logger.Debugf("%4d: %s (%s): ok", id, title, elapsed)
111         }
112 }
113
114 func (diag *diagnoser) runtests() {
115         client := arvados.NewClientFromEnv()
116
117         if client.APIHost == "" || client.AuthToken == "" {
118                 diag.errorf("ARVADOS_API_HOST and ARVADOS_API_TOKEN environment variables are not set -- aborting without running any tests")
119                 return
120         }
121
122         var dd arvados.DiscoveryDocument
123         ddpath := "discovery/v1/apis/arvados/v1/rest"
124         diag.dotest(10, fmt.Sprintf("getting discovery document from https://%s/%s", client.APIHost, ddpath), func() error {
125                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
126                 defer cancel()
127                 err := client.RequestAndDecodeContext(ctx, &dd, "GET", ddpath, nil, nil)
128                 if err != nil {
129                         return err
130                 }
131                 diag.debugf("BlobSignatureTTL = %d", dd.BlobSignatureTTL)
132                 return nil
133         })
134
135         var cluster arvados.Cluster
136         cfgpath := "arvados/v1/config"
137         diag.dotest(20, fmt.Sprintf("getting exported config from https://%s/%s", client.APIHost, cfgpath), func() error {
138                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
139                 defer cancel()
140                 err := client.RequestAndDecodeContext(ctx, &cluster, "GET", cfgpath, nil, nil)
141                 if err != nil {
142                         return err
143                 }
144                 diag.debugf("Collections.BlobSigning = %v", cluster.Collections.BlobSigning)
145                 return nil
146         })
147
148         var user arvados.User
149         diag.dotest(30, "getting current user record", func() error {
150                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
151                 defer cancel()
152                 err := client.RequestAndDecodeContext(ctx, &user, "GET", "arvados/v1/users/current", nil, nil)
153                 if err != nil {
154                         return err
155                 }
156                 diag.debugf("user uuid = %s", user.UUID)
157                 return nil
158         })
159
160         // uncomment to create some spurious errors
161         // cluster.Services.WebDAVDownload.ExternalURL.Host = "0.0.0.0:9"
162
163         // TODO: detect routing errors here, like finding wb2 at the
164         // wb1 address.
165         for i, svc := range []*arvados.Service{
166                 &cluster.Services.Keepproxy,
167                 &cluster.Services.WebDAV,
168                 &cluster.Services.WebDAVDownload,
169                 &cluster.Services.Websocket,
170                 &cluster.Services.Workbench1,
171                 &cluster.Services.Workbench2,
172         } {
173                 diag.dotest(40+i, fmt.Sprintf("connecting to service endpoint %s", svc.ExternalURL), func() error {
174                         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
175                         defer cancel()
176                         u := svc.ExternalURL
177                         if strings.HasPrefix(u.Scheme, "ws") {
178                                 // We can do a real websocket test elsewhere,
179                                 // but for now we'll just check the https
180                                 // connection.
181                                 u.Scheme = "http" + u.Scheme[2:]
182                         }
183                         if svc == &cluster.Services.WebDAV && strings.HasPrefix(u.Host, "*") {
184                                 u.Host = "d41d8cd98f00b204e9800998ecf8427e-0" + u.Host[1:]
185                         }
186                         req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
187                         if err != nil {
188                                 return err
189                         }
190                         resp, err := http.DefaultClient.Do(req)
191                         if err != nil {
192                                 return err
193                         }
194                         resp.Body.Close()
195                         return nil
196                 })
197         }
198
199         for i, url := range []string{
200                 cluster.Services.Controller.ExternalURL.String(),
201                 cluster.Services.Keepproxy.ExternalURL.String() + "d41d8cd98f00b204e9800998ecf8427e+0",
202                 cluster.Services.WebDAVDownload.ExternalURL.String(),
203         } {
204                 diag.dotest(50+i, fmt.Sprintf("checking CORS headers at %s", url), func() error {
205                         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
206                         defer cancel()
207                         req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
208                         if err != nil {
209                                 return err
210                         }
211                         req.Header.Set("Origin", "https://example.com")
212                         resp, err := http.DefaultClient.Do(req)
213                         if err != nil {
214                                 return err
215                         }
216                         if hdr := resp.Header.Get("Access-Control-Allow-Origin"); hdr != "*" {
217                                 return fmt.Errorf("expected \"Access-Control-Allow-Origin: *\", got %q", hdr)
218                         }
219                         return nil
220                 })
221         }
222
223         var keeplist arvados.KeepServiceList
224         diag.dotest(60, "checking internal/external client detection", func() error {
225                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
226                 defer cancel()
227                 err := client.RequestAndDecodeContext(ctx, &keeplist, "GET", "arvados/v1/keep_services/accessible", nil, arvados.ListOptions{Limit: 999999})
228                 if err != nil {
229                         return fmt.Errorf("error getting keep services list: %s", err)
230                 } else if len(keeplist.Items) == 0 {
231                         return fmt.Errorf("controller did not return any keep services")
232                 }
233                 found := map[string]int{}
234                 for _, ks := range keeplist.Items {
235                         found[ks.ServiceType]++
236                 }
237                 isInternal := found["proxy"] == 0 && len(keeplist.Items) > 0
238                 isExternal := found["proxy"] > 0 && found["proxy"] == len(keeplist.Items)
239                 if isExternal {
240                         diag.debugf("controller returned only proxy services, this host is treated as \"external\"")
241                 } else if isInternal {
242                         diag.debugf("controller returned only non-proxy services, this host is treated as \"internal\"")
243                 }
244                 if (diag.checkInternal && !isInternal) || (diag.checkExternal && !isExternal) {
245                         return fmt.Errorf("expecting internal=%v external=%v, but found internal=%v external=%v", diag.checkInternal, diag.checkExternal, isInternal, isExternal)
246                 }
247                 return nil
248         })
249
250         for i, ks := range keeplist.Items {
251                 u := url.URL{
252                         Scheme: "http",
253                         Host:   net.JoinHostPort(ks.ServiceHost, fmt.Sprintf("%d", ks.ServicePort)),
254                         Path:   "/",
255                 }
256                 if ks.ServiceSSLFlag {
257                         u.Scheme = "https"
258                 }
259                 diag.dotest(61+i, fmt.Sprintf("reading+writing via keep service at %s", u.String()), func() error {
260                         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
261                         defer cancel()
262                         req, err := http.NewRequestWithContext(ctx, "PUT", u.String()+"d41d8cd98f00b204e9800998ecf8427e", nil)
263                         if err != nil {
264                                 return err
265                         }
266                         req.Header.Set("Authorization", "Bearer "+client.AuthToken)
267                         resp, err := http.DefaultClient.Do(req)
268                         if err != nil {
269                                 return err
270                         }
271                         defer resp.Body.Close()
272                         body, err := ioutil.ReadAll(resp.Body)
273                         if err != nil {
274                                 return fmt.Errorf("reading response body: %s", err)
275                         }
276                         loc := strings.TrimSpace(string(body))
277                         if !strings.HasPrefix(loc, "d41d8") {
278                                 return fmt.Errorf("unexpected response from write: %q", body)
279                         }
280
281                         req, err = http.NewRequestWithContext(ctx, "GET", u.String()+loc, nil)
282                         if err != nil {
283                                 return err
284                         }
285                         req.Header.Set("Authorization", "Bearer "+client.AuthToken)
286                         resp, err = http.DefaultClient.Do(req)
287                         if err != nil {
288                                 return err
289                         }
290                         defer resp.Body.Close()
291                         body, err = ioutil.ReadAll(resp.Body)
292                         if err != nil {
293                                 return fmt.Errorf("reading response body: %s", err)
294                         }
295                         if len(body) != 0 {
296                                 return fmt.Errorf("unexpected response from read: %q", body)
297                         }
298
299                         return nil
300                 })
301         }
302
303         var project arvados.Group
304         diag.dotest(80, fmt.Sprintf("finding/creating %q project", diag.projectName), func() error {
305                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
306                 defer cancel()
307                 var grplist arvados.GroupList
308                 err := client.RequestAndDecodeContext(ctx, &grplist, "GET", "arvados/v1/groups", nil, arvados.ListOptions{
309                         Filters: []arvados.Filter{
310                                 {"name", "=", diag.projectName},
311                                 {"group_class", "=", "project"},
312                                 {"owner_uuid", "=", user.UUID}},
313                         Limit: 999999})
314                 if err != nil {
315                         return fmt.Errorf("list groups: %s", err)
316                 }
317                 if len(grplist.Items) > 0 {
318                         project = grplist.Items[0]
319                         diag.debugf("using existing project, uuid = %s", project.UUID)
320                         return nil
321                 }
322                 diag.debugf("list groups: ok, no results")
323                 err = client.RequestAndDecodeContext(ctx, &project, "POST", "arvados/v1/groups", nil, map[string]interface{}{"group": map[string]interface{}{
324                         "name":        diag.projectName,
325                         "group_class": "project",
326                 }})
327                 if err != nil {
328                         return fmt.Errorf("create project: %s", err)
329                 }
330                 diag.debugf("created project, uuid = %s", project.UUID)
331                 return nil
332         })
333
334         var collection arvados.Collection
335         diag.dotest(90, "creating temporary collection", func() error {
336                 if project.UUID == "" {
337                         return fmt.Errorf("skipping, no project to work in")
338                 }
339                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
340                 defer cancel()
341                 err := client.RequestAndDecodeContext(ctx, &collection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
342                         "ensure_unique_name": true,
343                         "collection": map[string]interface{}{
344                                 "owner_uuid": project.UUID,
345                                 "name":       "test collection",
346                                 "trash_at":   time.Now().Add(time.Hour)}})
347                 if err != nil {
348                         return err
349                 }
350                 diag.debugf("ok, uuid = %s", collection.UUID)
351                 return nil
352         })
353
354         if collection.UUID != "" {
355                 defer func() {
356                         diag.dotest(9990, "deleting temporary collection", func() error {
357                                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
358                                 defer cancel()
359                                 return client.RequestAndDecodeContext(ctx, nil, "DELETE", "arvados/v1/collections/"+collection.UUID, nil, nil)
360                         })
361                 }()
362         }
363
364         diag.dotest(100, "uploading file via webdav", func() error {
365                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
366                 defer cancel()
367                 if collection.UUID == "" {
368                         return fmt.Errorf("skipping, no test collection")
369                 }
370                 req, err := http.NewRequestWithContext(ctx, "PUT", cluster.Services.WebDAVDownload.ExternalURL.String()+"c="+collection.UUID+"/testfile", bytes.NewBufferString("testfiledata"))
371                 if err != nil {
372                         return fmt.Errorf("BUG? http.NewRequest: %s", err)
373                 }
374                 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
375                 resp, err := http.DefaultClient.Do(req)
376                 if err != nil {
377                         return fmt.Errorf("error performing http request: %s", err)
378                 }
379                 resp.Body.Close()
380                 if resp.StatusCode != http.StatusCreated {
381                         return fmt.Errorf("status %s", resp.Status)
382                 }
383                 diag.debugf("ok, status %s", resp.Status)
384                 err = client.RequestAndDecodeContext(ctx, &collection, "GET", "arvados/v1/collections/"+collection.UUID, nil, nil)
385                 if err != nil {
386                         return fmt.Errorf("get updated collection: %s", err)
387                 }
388                 diag.debugf("ok, pdh %s", collection.PortableDataHash)
389                 return nil
390         })
391
392         davurl := cluster.Services.WebDAV.ExternalURL
393         diag.dotest(110, fmt.Sprintf("checking WebDAV ExternalURL wildcard (%s)", davurl), func() error {
394                 if davurl.Host == "" {
395                         return fmt.Errorf("host missing - content previews will not work")
396                 }
397                 if !strings.HasPrefix(davurl.Host, "*--") && !strings.HasPrefix(davurl.Host, "*.") && !cluster.Collections.TrustAllContent {
398                         diag.warnf("WebDAV ExternalURL has no leading wildcard and TrustAllContent==false - content previews will not work")
399                 }
400                 return nil
401         })
402
403         for i, trial := range []struct {
404                 needcoll bool
405                 status   int
406                 fileurl  string
407         }{
408                 {false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + "foo"},
409                 {false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + "testfile"},
410                 {false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/foo"},
411                 {false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/testfile"},
412                 {true, http.StatusOK, strings.Replace(davurl.String(), "*", strings.Replace(collection.PortableDataHash, "+", "-", -1), 1) + "testfile"},
413                 {true, http.StatusOK, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=" + collection.UUID + "/_/testfile"},
414         } {
415                 diag.dotest(120+i, fmt.Sprintf("downloading from webdav (%s)", trial.fileurl), func() error {
416                         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
417                         defer cancel()
418                         if trial.needcoll && collection.UUID == "" {
419                                 return fmt.Errorf("skipping, no test collection")
420                         }
421                         req, err := http.NewRequestWithContext(ctx, "GET", trial.fileurl, nil)
422                         if err != nil {
423                                 return err
424                         }
425                         req.Header.Set("Authorization", "Bearer "+client.AuthToken)
426                         resp, err := http.DefaultClient.Do(req)
427                         if err != nil {
428                                 return err
429                         }
430                         defer resp.Body.Close()
431                         body, err := ioutil.ReadAll(resp.Body)
432                         if err != nil {
433                                 return fmt.Errorf("reading response: %s", err)
434                         }
435                         if resp.StatusCode != trial.status {
436                                 return fmt.Errorf("unexpected response status: %s", resp.Status)
437                         }
438                         if trial.status == http.StatusOK && string(body) != "testfiledata" {
439                                 return fmt.Errorf("unexpected response content: %q", body)
440                         }
441                         return nil
442                 })
443         }
444
445         var vm arvados.VirtualMachine
446         diag.dotest(130, "getting list of virtual machines", func() error {
447                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
448                 defer cancel()
449                 var vmlist arvados.VirtualMachineList
450                 err := client.RequestAndDecodeContext(ctx, &vmlist, "GET", "arvados/v1/virtual_machines", nil, arvados.ListOptions{Limit: 999999})
451                 if err != nil {
452                         return err
453                 }
454                 if len(vmlist.Items) < 1 {
455                         return fmt.Errorf("no VMs found")
456                 }
457                 vm = vmlist.Items[0]
458                 return nil
459         })
460
461         diag.dotest(140, "getting workbench1 webshell page", func() error {
462                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
463                 defer cancel()
464                 if vm.UUID == "" {
465                         return fmt.Errorf("skipping, no vm available")
466                 }
467                 webshelltermurl := cluster.Services.Workbench1.ExternalURL.String() + "virtual_machines/" + vm.UUID + "/webshell/testusername"
468                 diag.debugf("url %s", webshelltermurl)
469                 req, err := http.NewRequestWithContext(ctx, "GET", webshelltermurl, nil)
470                 if err != nil {
471                         return err
472                 }
473                 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
474                 resp, err := http.DefaultClient.Do(req)
475                 if err != nil {
476                         return err
477                 }
478                 defer resp.Body.Close()
479                 body, err := ioutil.ReadAll(resp.Body)
480                 if err != nil {
481                         return fmt.Errorf("reading response: %s", err)
482                 }
483                 if resp.StatusCode != http.StatusOK {
484                         return fmt.Errorf("unexpected response status: %s %q", resp.Status, body)
485                 }
486                 return nil
487         })
488
489         diag.dotest(150, "connecting to webshell service", func() error {
490                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
491                 defer cancel()
492                 if vm.UUID == "" {
493                         return fmt.Errorf("skipping, no vm available")
494                 }
495                 u := cluster.Services.WebShell.ExternalURL
496                 webshellurl := u.String() + vm.Hostname + "?"
497                 if strings.HasPrefix(u.Host, "*") {
498                         u.Host = vm.Hostname + u.Host[1:]
499                         webshellurl = u.String() + "?"
500                 }
501                 diag.debugf("url %s", webshellurl)
502                 req, err := http.NewRequestWithContext(ctx, "POST", webshellurl, bytes.NewBufferString(url.Values{
503                         "width":   {"80"},
504                         "height":  {"25"},
505                         "session": {"xyzzy"},
506                         "rooturl": {webshellurl},
507                 }.Encode()))
508                 if err != nil {
509                         return err
510                 }
511                 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
512                 resp, err := http.DefaultClient.Do(req)
513                 if err != nil {
514                         return err
515                 }
516                 defer resp.Body.Close()
517                 diag.debugf("response status %s", resp.Status)
518                 body, err := ioutil.ReadAll(resp.Body)
519                 if err != nil {
520                         return fmt.Errorf("reading response: %s", err)
521                 }
522                 diag.debugf("response body %q", body)
523                 // We don't speak the protocol, so we get a 400 error
524                 // from the webshell server even if everything is
525                 // OK. Anything else (404, 502, ???) indicates a
526                 // problem.
527                 if resp.StatusCode != http.StatusBadRequest {
528                         return fmt.Errorf("unexpected response status: %s, %q", resp.Status, body)
529                 }
530                 return nil
531         })
532
533         diag.dotest(160, "running a container", func() error {
534                 if diag.priority < 1 {
535                         diag.infof("skipping (use priority > 0 if you want to run a container)")
536                         return nil
537                 }
538                 if project.UUID == "" {
539                         return fmt.Errorf("skipping, no project to work in")
540                 }
541
542                 var cr arvados.ContainerRequest
543                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
544                 defer cancel()
545
546                 timestamp := time.Now().Format(time.RFC3339)
547                 err := client.RequestAndDecodeContext(ctx, &cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{"container_request": map[string]interface{}{
548                         "owner_uuid":      project.UUID,
549                         "name":            fmt.Sprintf("diagnostics container request %s", timestamp),
550                         "container_image": diag.dockerImage,
551                         "command":         []string{"echo", timestamp},
552                         "use_existing":    false,
553                         "output_path":     "/mnt/output",
554                         "output_name":     fmt.Sprintf("diagnostics output %s", timestamp),
555                         "priority":        diag.priority,
556                         "state":           arvados.ContainerRequestStateCommitted,
557                         "mounts": map[string]map[string]interface{}{
558                                 "/mnt/output": {
559                                         "kind":     "collection",
560                                         "writable": true,
561                                 },
562                         },
563                         "runtime_constraints": arvados.RuntimeConstraints{
564                                 VCPUs:        1,
565                                 RAM:          1 << 26,
566                                 KeepCacheRAM: 1 << 26,
567                         },
568                 }})
569                 if err != nil {
570                         return err
571                 }
572                 diag.debugf("container request uuid = %s", cr.UUID)
573                 diag.debugf("container uuid = %s", cr.ContainerUUID)
574
575                 timeout := 10 * time.Minute
576                 diag.infof("container request submitted, waiting up to %v for container to run", arvados.Duration(timeout))
577                 ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(timeout))
578                 defer cancel()
579
580                 var c arvados.Container
581                 for ; cr.State != arvados.ContainerRequestStateFinal; time.Sleep(2 * time.Second) {
582                         ctx, cancel := context.WithDeadline(ctx, time.Now().Add(diag.timeout))
583                         defer cancel()
584
585                         crStateWas := cr.State
586                         err := client.RequestAndDecodeContext(ctx, &cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
587                         if err != nil {
588                                 return err
589                         }
590                         if cr.State != crStateWas {
591                                 diag.debugf("container request state = %s", cr.State)
592                         }
593
594                         cStateWas := c.State
595                         err = client.RequestAndDecodeContext(ctx, &c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
596                         if err != nil {
597                                 return err
598                         }
599                         if c.State != cStateWas {
600                                 diag.debugf("container state = %s", c.State)
601                         }
602                 }
603
604                 if c.State != arvados.ContainerStateComplete {
605                         return fmt.Errorf("container request %s is final but container %s did not complete: container state = %q", cr.UUID, cr.ContainerUUID, c.State)
606                 } else if c.ExitCode != 0 {
607                         return fmt.Errorf("container exited %d", c.ExitCode)
608                 }
609                 return nil
610         })
611 }