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