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