1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
27 "git.arvados.org/arvados.git/lib/cmd"
28 "git.arvados.org/arvados.git/lib/config"
29 "git.arvados.org/arvados.git/sdk/go/arvados"
30 "git.arvados.org/arvados.git/sdk/go/ctxlog"
31 "git.arvados.org/arvados.git/sdk/go/health"
32 "github.com/sirupsen/logrus"
37 func (Command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
39 f := flag.NewFlagSet(prog, flag.ContinueOnError)
40 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")
41 f.StringVar(&diag.logLevel, "log-level", "info", "logging `level` (debug, info, warning, error)")
42 f.StringVar(&diag.dockerImage, "docker-image", "", "`image` (tag or portable data hash) to use when running a test container, or \"hello-world\" to use embedded hello-world image (default: build a custom image containing this executable, and run diagnostics inside the container too)")
43 f.StringVar(&diag.dockerImageFrom, "docker-image-from", "debian:stable-slim", "`base` image to use when building a custom image (see https://doc.arvados.org/main/admin/diagnostics.html#container-options)")
44 f.BoolVar(&diag.checkInternal, "internal-client", false, "check that this host is considered an \"internal\" client")
45 f.BoolVar(&diag.checkExternal, "external-client", false, "check that this host is considered an \"external\" client")
46 f.BoolVar(&diag.verbose, "v", false, "verbose: include more information in report")
47 f.IntVar(&diag.priority, "priority", 500, "priority for test container (1..1000, or 0 to skip)")
48 f.DurationVar(&diag.timeout, "timeout", 10*time.Second, "timeout for http requests")
49 if ok, code := cmd.ParseFlags(f, prog, args, "", stderr); !ok {
54 diag.logger = ctxlog.New(stdout, "text", diag.logLevel)
55 diag.logger.SetFormatter(&logrus.TextFormatter{DisableTimestamp: true, DisableLevelTruncation: true, PadLevelText: true})
57 if len(diag.errors) == 0 {
58 diag.logger.Info("--- no errors ---")
61 if diag.logger.Level > logrus.ErrorLevel {
62 fmt.Fprint(stdout, "\n--- cut here --- error summary ---\n\n")
63 for _, e := range diag.errors {
71 // docker save hello-world > hello-world.tar
73 //go:embed hello-world.tar
74 var HelloWorldDockerImage []byte
76 type diagnoser struct {
83 dockerImageFrom string
93 func (diag *diagnoser) debugf(f string, args ...interface{}) {
94 diag.logger.Debugf(" ... "+f, args...)
97 func (diag *diagnoser) infof(f string, args ...interface{}) {
98 diag.logger.Infof(" ... "+f, args...)
101 func (diag *diagnoser) verbosef(f string, args ...interface{}) {
103 diag.logger.Infof(" ... "+f, args...)
107 func (diag *diagnoser) warnf(f string, args ...interface{}) {
108 diag.logger.Warnf(" ... "+f, args...)
111 func (diag *diagnoser) errorf(f string, args ...interface{}) {
112 diag.logger.Errorf(f, args...)
113 diag.errors = append(diag.errors, fmt.Sprintf(f, args...))
116 // Run the given func, logging appropriate messages before and after,
117 // adding timing info, etc.
119 // The id argument should be unique among tests, and shouldn't change
120 // when other tests are added/removed.
121 func (diag *diagnoser) dotest(id int, title string, fn func() error) {
122 if diag.done == nil {
123 diag.done = map[int]bool{}
124 } else if diag.done[id] {
125 diag.errorf("(bug) reused test id %d", id)
129 diag.logger.Infof("%4d: %s", id, title)
132 elapsed := fmt.Sprintf("%d ms", time.Now().Sub(t0)/time.Millisecond)
134 diag.errorf("%4d: %s (%s): %s", id, title, elapsed, err)
136 diag.logger.Debugf("%4d: %s (%s): ok", id, title, elapsed)
140 func (diag *diagnoser) runtests() {
141 client := arvados.NewClientFromEnv()
142 // Disable auto-retry, use context instead
145 if client.APIHost == "" || client.AuthToken == "" {
146 diag.errorf("ARVADOS_API_HOST and ARVADOS_API_TOKEN environment variables are not set -- aborting without running any tests")
150 hostname, err := os.Hostname()
152 diag.warnf("error getting hostname: %s")
154 diag.verbosef("hostname = %s", hostname)
157 diag.dotest(5, "running health check (same as `arvados-server check`)", func() error {
158 ldr := config.NewLoader(&bytes.Buffer{}, ctxlog.New(&bytes.Buffer{}, "text", "info"))
159 ldr.SetupFlags(flag.NewFlagSet("diagnostics", flag.ContinueOnError))
160 cfg, err := ldr.Load()
162 diag.infof("skipping because config could not be loaded: %s", err)
165 cluster, err := cfg.GetCluster("")
169 if cluster.SystemRootToken != os.Getenv("ARVADOS_API_TOKEN") {
170 return fmt.Errorf("diagnostics usage error: %s is readable but SystemRootToken does not match $ARVADOS_API_TOKEN (to fix, either run 'arvados-client sudo diagnostics' to load everything from config file, or set ARVADOS_CONFIG=- to load nothing from config file)", ldr.Path)
172 agg := &health.Aggregator{Cluster: cluster}
173 resp := agg.ClusterHealth()
174 for _, e := range resp.Errors {
175 diag.errorf("health check: %s", e)
177 if len(resp.Errors) > 0 {
178 diag.infof("consider running `arvados-server check -yaml` for a comprehensive report")
180 diag.verbosef("reported clock skew = %v", resp.ClockSkew)
181 reported := map[string]bool{}
182 for _, result := range resp.Checks {
183 version := strings.SplitN(result.Metrics.Version, " (go", 2)[0]
184 if version != "" && !reported[version] {
185 diag.verbosef("arvados version = %s", version)
186 reported[version] = true
189 reported = map[string]bool{}
190 for _, result := range resp.Checks {
191 if result.Server != "" && !reported[result.Server] {
192 diag.verbosef("http frontend version = %s", result.Server)
193 reported[result.Server] = true
196 reported = map[string]bool{}
197 for _, result := range resp.Checks {
198 if sha := result.ConfigSourceSHA256; sha != "" && !reported[sha] {
199 diag.verbosef("config file sha256 = %s", sha)
206 var dd arvados.DiscoveryDocument
207 ddpath := "discovery/v1/apis/arvados/v1/rest"
208 diag.dotest(10, fmt.Sprintf("getting discovery document from https://%s/%s", client.APIHost, ddpath), func() error {
209 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
211 err := client.RequestAndDecodeContext(ctx, &dd, "GET", ddpath, nil, nil)
215 diag.verbosef("BlobSignatureTTL = %d", dd.BlobSignatureTTL)
219 var cluster arvados.Cluster
220 cfgpath := "arvados/v1/config"
222 diag.dotest(20, fmt.Sprintf("getting exported config from https://%s/%s", client.APIHost, cfgpath), func() error {
223 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
225 err := client.RequestAndDecodeContext(ctx, &cluster, "GET", cfgpath, nil, nil)
229 diag.verbosef("Collections.BlobSigning = %v", cluster.Collections.BlobSigning)
234 var user arvados.User
235 diag.dotest(30, "getting current user record", func() error {
236 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
238 err := client.RequestAndDecodeContext(ctx, &user, "GET", "arvados/v1/users/current", nil, nil)
242 diag.verbosef("user uuid = %s", user.UUID)
247 diag.errorf("cannot proceed without cluster config -- aborting without running any further tests")
251 // uncomment to create some spurious errors
252 // cluster.Services.WebDAVDownload.ExternalURL.Host = "0.0.0.0:9"
254 // TODO: detect routing errors here, like finding wb2 at the
256 for i, svc := range []struct {
258 config *arvados.Service
260 {"Keepproxy", &cluster.Services.Keepproxy},
261 {"WebDAV", &cluster.Services.WebDAV},
262 {"WebDAVDownload", &cluster.Services.WebDAVDownload},
263 {"Websocket", &cluster.Services.Websocket},
264 {"Workbench1", &cluster.Services.Workbench1},
265 {"Workbench2", &cluster.Services.Workbench2},
267 u := url.URL(svc.config.ExternalURL)
268 diag.dotest(40+i, fmt.Sprintf("connecting to %s endpoint %s", svc.name, u.String()), func() error {
269 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
271 if strings.HasPrefix(u.Scheme, "ws") {
272 // We can do a real websocket test elsewhere,
273 // but for now we'll just check the https
275 u.Scheme = "http" + u.Scheme[2:]
277 if svc.config == &cluster.Services.WebDAV && strings.HasPrefix(u.Host, "*") {
278 u.Host = "d41d8cd98f00b204e9800998ecf8427e-0" + u.Host[1:]
280 req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
284 resp, err := http.DefaultClient.Do(req)
293 for i, url := range []string{
294 cluster.Services.Controller.ExternalURL.String(),
295 cluster.Services.Keepproxy.ExternalURL.String() + "d41d8cd98f00b204e9800998ecf8427e+0",
296 cluster.Services.WebDAVDownload.ExternalURL.String(),
298 diag.dotest(50+i, fmt.Sprintf("checking CORS headers at %s", url), func() error {
299 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
301 req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
305 req.Header.Set("Origin", "https://example.com")
306 resp, err := http.DefaultClient.Do(req)
310 if hdr := resp.Header.Get("Access-Control-Allow-Origin"); hdr != "*" {
311 return fmt.Errorf("expected \"Access-Control-Allow-Origin: *\", got %q", hdr)
317 var keeplist arvados.KeepServiceList
318 diag.dotest(60, "checking internal/external client detection", func() error {
319 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
321 err := client.RequestAndDecodeContext(ctx, &keeplist, "GET", "arvados/v1/keep_services/accessible", nil, arvados.ListOptions{Limit: 999999})
323 return fmt.Errorf("error getting keep services list: %s", err)
324 } else if len(keeplist.Items) == 0 {
325 return fmt.Errorf("controller did not return any keep services")
327 found := map[string]int{}
328 for _, ks := range keeplist.Items {
329 found[ks.ServiceType]++
331 isInternal := found["proxy"] == 0 && len(keeplist.Items) > 0
332 isExternal := found["proxy"] > 0 && found["proxy"] == len(keeplist.Items)
334 diag.infof("controller returned only proxy services, this host is treated as \"external\"")
335 } else if isInternal {
336 diag.infof("controller returned only non-proxy services, this host is treated as \"internal\"")
338 if (diag.checkInternal && !isInternal) || (diag.checkExternal && !isExternal) {
339 return fmt.Errorf("expecting internal=%v external=%v, but found internal=%v external=%v", diag.checkInternal, diag.checkExternal, isInternal, isExternal)
344 for i, ks := range keeplist.Items {
347 Host: net.JoinHostPort(ks.ServiceHost, fmt.Sprintf("%d", ks.ServicePort)),
350 if ks.ServiceSSLFlag {
353 diag.dotest(61+i, fmt.Sprintf("reading+writing via keep service at %s", u.String()), func() error {
354 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
356 req, err := http.NewRequestWithContext(ctx, "PUT", u.String()+"d41d8cd98f00b204e9800998ecf8427e", nil)
360 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
361 resp, err := http.DefaultClient.Do(req)
365 defer resp.Body.Close()
366 body, err := ioutil.ReadAll(resp.Body)
368 return fmt.Errorf("reading response body: %s", err)
370 loc := strings.TrimSpace(string(body))
371 if !strings.HasPrefix(loc, "d41d8") {
372 return fmt.Errorf("unexpected response from write: %q", body)
375 req, err = http.NewRequestWithContext(ctx, "GET", u.String()+loc, nil)
379 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
380 resp, err = http.DefaultClient.Do(req)
384 defer resp.Body.Close()
385 body, err = ioutil.ReadAll(resp.Body)
387 return fmt.Errorf("reading response body: %s", err)
390 return fmt.Errorf("unexpected response from read: %q", body)
397 var project arvados.Group
398 diag.dotest(80, fmt.Sprintf("finding/creating %q project", diag.projectName), func() error {
399 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
401 var grplist arvados.GroupList
402 err := client.RequestAndDecodeContext(ctx, &grplist, "GET", "arvados/v1/groups", nil, arvados.ListOptions{
403 Filters: []arvados.Filter{
404 {"name", "=", diag.projectName},
405 {"group_class", "=", "project"},
406 {"owner_uuid", "=", user.UUID}},
409 return fmt.Errorf("list groups: %s", err)
411 if len(grplist.Items) > 0 {
412 project = grplist.Items[0]
413 diag.verbosef("using existing project, uuid = %s", project.UUID)
416 diag.debugf("list groups: ok, no results")
417 err = client.RequestAndDecodeContext(ctx, &project, "POST", "arvados/v1/groups", nil, map[string]interface{}{"group": map[string]interface{}{
418 "name": diag.projectName,
419 "group_class": "project",
422 return fmt.Errorf("create project: %s", err)
424 diag.verbosef("created project, uuid = %s", project.UUID)
428 var collection arvados.Collection
429 diag.dotest(90, "creating temporary collection", func() error {
430 if project.UUID == "" {
431 return fmt.Errorf("skipping, no project to work in")
433 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
435 err := client.RequestAndDecodeContext(ctx, &collection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
436 "ensure_unique_name": true,
437 "collection": map[string]interface{}{
438 "owner_uuid": project.UUID,
439 "name": "test collection",
440 "trash_at": time.Now().Add(time.Hour)}})
444 diag.verbosef("ok, uuid = %s", collection.UUID)
448 if collection.UUID != "" {
450 diag.dotest(9990, "deleting temporary collection", func() error {
451 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
453 return client.RequestAndDecodeContext(ctx, nil, "DELETE", "arvados/v1/collections/"+collection.UUID, nil, nil)
458 tempdir, err := ioutil.TempDir("", "arvados-diagnostics")
460 diag.errorf("error creating temp dir: %s", err)
463 defer os.RemoveAll(tempdir)
466 var dockerImageData []byte
467 if diag.dockerImage != "" || diag.priority < 1 {
468 // We won't be using the self-built docker image, so
469 // don't build it. But we will write the embedded
470 // "hello-world" image to our test collection to test
471 // upload/download, whether or not we're using it as a
473 dockerImageData = HelloWorldDockerImage
475 if diag.priority > 0 {
476 imageSHA2, err = getSHA2FromImageData(dockerImageData)
478 diag.errorf("internal error/bug: %s", err)
482 } else if selfbin, err := os.Readlink("/proc/self/exe"); err != nil {
483 diag.errorf("readlink /proc/self/exe: %s", err)
485 } else if selfbindata, err := os.ReadFile(selfbin); err != nil {
486 diag.errorf("error reading %s: %s", selfbin, err)
489 selfbinSha := fmt.Sprintf("%x", sha256.Sum256(selfbindata))
490 tag := "arvados-client-diagnostics:" + selfbinSha[:9]
491 err := os.WriteFile(tempdir+"/arvados-client", selfbindata, 0777)
493 diag.errorf("error writing %s: %s", tempdir+"/arvados-client", err)
497 dockerfile := "FROM " + diag.dockerImageFrom + "\n"
498 dockerfile += "RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends libfuse2 ca-certificates && apt-get clean\n"
499 dockerfile += "COPY /arvados-client /arvados-client\n"
500 cmd := exec.Command("docker", "build", "--tag", tag, "-f", "-", tempdir)
501 cmd.Stdin = strings.NewReader(dockerfile)
502 cmd.Stdout = diag.stderr
503 cmd.Stderr = diag.stderr
506 diag.errorf("error building docker image: %s", err)
509 checkversion, err := exec.Command("docker", "run", tag, "/arvados-client", "version").CombinedOutput()
511 diag.errorf("docker image does not seem to work: %s", err)
514 diag.infof("arvados-client version: %s", checkversion)
516 buf, err := exec.Command("docker", "inspect", "--format={{.Id}}", tag).Output()
518 diag.errorf("docker inspect --format={{.Id}} %s: %s", tag, err)
521 imageSHA2 = min64HexDigits.FindString(string(buf))
522 if len(imageSHA2) != 64 {
523 diag.errorf("docker inspect --format={{.Id}} output %q does not seem to contain sha256 digest", buf)
527 buf, err = exec.Command("docker", "save", tag).Output()
529 diag.errorf("docker save %s: %s", tag, err)
532 diag.infof("docker image size is %d", len(buf))
533 dockerImageData = buf
536 tarfilename := "sha256:" + imageSHA2 + ".tar"
538 diag.dotest(100, "uploading file via webdav", func() error {
539 timeout := diag.timeout
540 if len(dockerImageData) > 10<<20 && timeout < time.Minute {
541 // Extend the normal http timeout if we're
542 // uploading a substantial docker image.
543 timeout = time.Minute
545 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(timeout))
547 if collection.UUID == "" {
548 return fmt.Errorf("skipping, no test collection")
551 req, err := http.NewRequestWithContext(ctx, "PUT", cluster.Services.WebDAVDownload.ExternalURL.String()+"c="+collection.UUID+"/"+tarfilename, bytes.NewReader(dockerImageData))
553 return fmt.Errorf("BUG? http.NewRequest: %s", err)
555 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
556 resp, err := http.DefaultClient.Do(req)
558 return fmt.Errorf("error performing http request: %s", err)
561 if resp.StatusCode != http.StatusCreated {
562 return fmt.Errorf("status %s", resp.Status)
564 diag.verbosef("upload ok, status %s, %f MB/s", resp.Status, float64(len(dockerImageData))/time.Since(t0).Seconds()/1000000)
565 err = client.RequestAndDecodeContext(ctx, &collection, "GET", "arvados/v1/collections/"+collection.UUID, nil, nil)
567 return fmt.Errorf("get updated collection: %s", err)
569 diag.verbosef("upload pdh %s", collection.PortableDataHash)
573 davurl := cluster.Services.WebDAV.ExternalURL
574 davWildcard := strings.HasPrefix(davurl.Host, "*--") || strings.HasPrefix(davurl.Host, "*.")
575 diag.dotest(110, fmt.Sprintf("checking WebDAV ExternalURL wildcard (%s)", davurl), func() error {
576 if davurl.Host == "" {
577 return fmt.Errorf("host missing - content previews will not work")
579 if !davWildcard && !cluster.Collections.TrustAllContent {
580 diag.warnf("WebDAV ExternalURL has no leading wildcard and TrustAllContent==false - content previews will not work")
585 for i, trial := range []struct {
591 {false, false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + "foo"},
592 {false, false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + tarfilename},
593 {false, false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/foo"},
594 {false, false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/" + tarfilename},
595 {true, true, http.StatusOK, strings.Replace(davurl.String(), "*", strings.Replace(collection.PortableDataHash, "+", "-", -1), 1) + tarfilename},
596 {true, false, http.StatusOK, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=" + collection.UUID + "/_/" + tarfilename},
598 diag.dotest(120+i, fmt.Sprintf("downloading from webdav (%s)", trial.fileurl), func() error {
599 if trial.needWildcard && !davWildcard {
600 diag.warnf("skipping collection-id-in-vhost test because WebDAV ExternalURL has no leading wildcard")
603 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
605 if trial.needcoll && collection.UUID == "" {
606 return fmt.Errorf("skipping, no test collection")
608 req, err := http.NewRequestWithContext(ctx, "GET", trial.fileurl, nil)
612 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
613 resp, err := http.DefaultClient.Do(req)
617 defer resp.Body.Close()
618 body, err := ioutil.ReadAll(resp.Body)
620 return fmt.Errorf("reading response: %s", err)
622 if resp.StatusCode != trial.status {
623 return fmt.Errorf("unexpected response status: %s", resp.Status)
625 if trial.status == http.StatusOK && !bytes.Equal(body, dockerImageData) {
627 if len(excerpt) > 128 {
628 excerpt = append([]byte(nil), body[:128]...)
629 excerpt = append(excerpt, []byte("[...]")...)
631 return fmt.Errorf("unexpected response content: len %d, %q", len(body), excerpt)
637 var vm arvados.VirtualMachine
638 diag.dotest(130, "getting list of virtual machines", func() error {
639 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
641 var vmlist arvados.VirtualMachineList
642 err := client.RequestAndDecodeContext(ctx, &vmlist, "GET", "arvados/v1/virtual_machines", nil, arvados.ListOptions{Limit: 999999})
646 if len(vmlist.Items) < 1 {
647 diag.warnf("no VMs found")
654 diag.dotest(150, "connecting to webshell service", func() error {
655 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
657 u := cluster.Services.WebShell.ExternalURL
658 if u == (arvados.URL{}) {
659 diag.infof("skipping, webshell not configured")
663 diag.warnf("skipping, no vm available")
666 webshellurl := u.String() + vm.Hostname + "?"
667 if strings.HasPrefix(u.Host, "*") {
668 u.Host = vm.Hostname + u.Host[1:]
669 webshellurl = u.String() + "?"
671 diag.debugf("url %s", webshellurl)
672 req, err := http.NewRequestWithContext(ctx, "POST", webshellurl, bytes.NewBufferString(url.Values{
675 "session": {"xyzzy"},
676 "rooturl": {webshellurl},
681 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
682 resp, err := http.DefaultClient.Do(req)
686 defer resp.Body.Close()
687 diag.debugf("response status %s", resp.Status)
688 body, err := ioutil.ReadAll(resp.Body)
690 return fmt.Errorf("reading response: %s", err)
692 diag.debugf("response body %q", body)
693 // We don't speak the protocol, so we get a 400 error
694 // from the webshell server even if everything is
695 // OK. Anything else (404, 502, ???) indicates a
697 if resp.StatusCode != http.StatusBadRequest {
698 return fmt.Errorf("unexpected response status: %s, %q", resp.Status, body)
703 diag.dotest(160, "running a container", func() error {
704 if diag.priority < 1 {
705 diag.infof("skipping (use priority > 0 if you want to run a container)")
708 if project.UUID == "" {
709 return fmt.Errorf("skipping, no project to work in")
712 timestamp := time.Now().Format(time.RFC3339)
714 var ctrCommand []string
715 switch diag.dockerImage {
717 if collection.UUID == "" {
718 return fmt.Errorf("skipping, no test collection to use as docker image")
720 diag.dockerImage = collection.PortableDataHash
721 ctrCommand = []string{"/arvados-client", "diagnostics",
722 "-priority=0", // don't run a container
723 "-log-level=" + diag.logLevel,
724 "-internal-client=true"}
726 if collection.UUID == "" {
727 return fmt.Errorf("skipping, no test collection to use as docker image")
729 diag.dockerImage = collection.PortableDataHash
730 ctrCommand = []string{"/hello"}
732 ctrCommand = []string{"echo", timestamp}
735 var cr arvados.ContainerRequest
736 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
739 err := client.RequestAndDecodeContext(ctx, &cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{"container_request": map[string]interface{}{
740 "owner_uuid": project.UUID,
741 "name": fmt.Sprintf("diagnostics container request %s", timestamp),
742 "container_image": diag.dockerImage,
743 "command": ctrCommand,
744 "use_existing": false,
745 "output_path": "/mnt/output",
746 "output_name": fmt.Sprintf("diagnostics output %s", timestamp),
747 "priority": diag.priority,
748 "state": arvados.ContainerRequestStateCommitted,
749 "mounts": map[string]map[string]interface{}{
751 "kind": "collection",
755 "runtime_constraints": arvados.RuntimeConstraints{
759 KeepCacheRAM: 64 << 20,
765 diag.infof("container request uuid = %s", cr.UUID)
766 diag.verbosef("container uuid = %s", cr.ContainerUUID)
768 timeout := 10 * time.Minute
769 diag.infof("container request submitted, waiting up to %v for container to run", arvados.Duration(timeout))
770 deadline := time.Now().Add(timeout)
772 var c arvados.Container
773 for ; cr.State != arvados.ContainerRequestStateFinal && time.Now().Before(deadline); time.Sleep(2 * time.Second) {
774 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
777 crStateWas := cr.State
778 err := client.RequestAndDecodeContext(ctx, &cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
782 if cr.State != crStateWas {
783 diag.debugf("container request state = %s", cr.State)
787 err = client.RequestAndDecodeContext(ctx, &c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
791 if c.State != cStateWas {
792 diag.debugf("container state = %s", c.State)
798 if cr.State != arvados.ContainerRequestStateFinal {
799 err := client.RequestAndDecodeContext(context.Background(), &cr, "PATCH", "arvados/v1/container_requests/"+cr.UUID, nil, map[string]interface{}{
800 "container_request": map[string]interface{}{
804 diag.infof("error canceling container request %s: %s", cr.UUID, err)
806 diag.debugf("canceled container request %s", cr.UUID)
808 return fmt.Errorf("timed out waiting for container to finish; container request %s state was %q, container %s state was %q", cr.UUID, cr.State, c.UUID, c.State)
810 if c.State != arvados.ContainerStateComplete {
811 return fmt.Errorf("container request %s is final but container %s did not complete: container state = %q", cr.UUID, cr.ContainerUUID, c.State)
814 return fmt.Errorf("container exited %d", c.ExitCode)
820 func getSHA2FromImageData(dockerImageData []byte) (string, error) {
821 tr := tar.NewReader(bytes.NewReader(dockerImageData))
823 hdr, err := tr.Next()
825 return "", fmt.Errorf("cannot find manifest.json in docker image tar file")
828 return "", fmt.Errorf("cannot read docker image tar file: %s", err)
830 if hdr.Name != "manifest.json" {
833 var manifest []struct {
836 err = json.NewDecoder(tr).Decode(&manifest)
838 return "", fmt.Errorf("cannot read manifest.json from docker image tar file: %s", err)
840 if len(manifest) == 0 {
841 return "", fmt.Errorf("manifest.json is empty")
843 s := min64HexDigits.FindString(manifest[0].Config)
845 return "", fmt.Errorf("found manifest.json but .[0].Config %q does not seem to contain sha256 digest", manifest[0].Config)
851 var min64HexDigits = regexp.MustCompile(`[0-9a-f]{64,}`)