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 []*arvados.Service{
257 &cluster.Services.Keepproxy,
258 &cluster.Services.WebDAV,
259 &cluster.Services.WebDAVDownload,
260 &cluster.Services.Websocket,
261 &cluster.Services.Workbench1,
262 &cluster.Services.Workbench2,
264 diag.dotest(40+i, fmt.Sprintf("connecting to service endpoint %s", svc.ExternalURL), func() error {
265 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
268 if strings.HasPrefix(u.Scheme, "ws") {
269 // We can do a real websocket test elsewhere,
270 // but for now we'll just check the https
272 u.Scheme = "http" + u.Scheme[2:]
274 if svc == &cluster.Services.WebDAV && strings.HasPrefix(u.Host, "*") {
275 u.Host = "d41d8cd98f00b204e9800998ecf8427e-0" + u.Host[1:]
277 req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
281 resp, err := http.DefaultClient.Do(req)
290 for i, url := range []string{
291 cluster.Services.Controller.ExternalURL.String(),
292 cluster.Services.Keepproxy.ExternalURL.String() + "d41d8cd98f00b204e9800998ecf8427e+0",
293 cluster.Services.WebDAVDownload.ExternalURL.String(),
295 diag.dotest(50+i, fmt.Sprintf("checking CORS headers at %s", url), func() error {
296 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
298 req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
302 req.Header.Set("Origin", "https://example.com")
303 resp, err := http.DefaultClient.Do(req)
307 if hdr := resp.Header.Get("Access-Control-Allow-Origin"); hdr != "*" {
308 return fmt.Errorf("expected \"Access-Control-Allow-Origin: *\", got %q", hdr)
314 var keeplist arvados.KeepServiceList
315 diag.dotest(60, "checking internal/external client detection", func() error {
316 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
318 err := client.RequestAndDecodeContext(ctx, &keeplist, "GET", "arvados/v1/keep_services/accessible", nil, arvados.ListOptions{Limit: 999999})
320 return fmt.Errorf("error getting keep services list: %s", err)
321 } else if len(keeplist.Items) == 0 {
322 return fmt.Errorf("controller did not return any keep services")
324 found := map[string]int{}
325 for _, ks := range keeplist.Items {
326 found[ks.ServiceType]++
328 isInternal := found["proxy"] == 0 && len(keeplist.Items) > 0
329 isExternal := found["proxy"] > 0 && found["proxy"] == len(keeplist.Items)
331 diag.infof("controller returned only proxy services, this host is treated as \"external\"")
332 } else if isInternal {
333 diag.infof("controller returned only non-proxy services, this host is treated as \"internal\"")
335 if (diag.checkInternal && !isInternal) || (diag.checkExternal && !isExternal) {
336 return fmt.Errorf("expecting internal=%v external=%v, but found internal=%v external=%v", diag.checkInternal, diag.checkExternal, isInternal, isExternal)
341 for i, ks := range keeplist.Items {
344 Host: net.JoinHostPort(ks.ServiceHost, fmt.Sprintf("%d", ks.ServicePort)),
347 if ks.ServiceSSLFlag {
350 diag.dotest(61+i, fmt.Sprintf("reading+writing via keep service at %s", u.String()), func() error {
351 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
353 req, err := http.NewRequestWithContext(ctx, "PUT", u.String()+"d41d8cd98f00b204e9800998ecf8427e", nil)
357 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
358 resp, err := http.DefaultClient.Do(req)
362 defer resp.Body.Close()
363 body, err := ioutil.ReadAll(resp.Body)
365 return fmt.Errorf("reading response body: %s", err)
367 loc := strings.TrimSpace(string(body))
368 if !strings.HasPrefix(loc, "d41d8") {
369 return fmt.Errorf("unexpected response from write: %q", body)
372 req, err = http.NewRequestWithContext(ctx, "GET", u.String()+loc, nil)
376 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
377 resp, err = http.DefaultClient.Do(req)
381 defer resp.Body.Close()
382 body, err = ioutil.ReadAll(resp.Body)
384 return fmt.Errorf("reading response body: %s", err)
387 return fmt.Errorf("unexpected response from read: %q", body)
394 var project arvados.Group
395 diag.dotest(80, fmt.Sprintf("finding/creating %q project", diag.projectName), func() error {
396 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
398 var grplist arvados.GroupList
399 err := client.RequestAndDecodeContext(ctx, &grplist, "GET", "arvados/v1/groups", nil, arvados.ListOptions{
400 Filters: []arvados.Filter{
401 {"name", "=", diag.projectName},
402 {"group_class", "=", "project"},
403 {"owner_uuid", "=", user.UUID}},
406 return fmt.Errorf("list groups: %s", err)
408 if len(grplist.Items) > 0 {
409 project = grplist.Items[0]
410 diag.verbosef("using existing project, uuid = %s", project.UUID)
413 diag.debugf("list groups: ok, no results")
414 err = client.RequestAndDecodeContext(ctx, &project, "POST", "arvados/v1/groups", nil, map[string]interface{}{"group": map[string]interface{}{
415 "name": diag.projectName,
416 "group_class": "project",
419 return fmt.Errorf("create project: %s", err)
421 diag.verbosef("created project, uuid = %s", project.UUID)
425 var collection arvados.Collection
426 diag.dotest(90, "creating temporary collection", func() error {
427 if project.UUID == "" {
428 return fmt.Errorf("skipping, no project to work in")
430 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
432 err := client.RequestAndDecodeContext(ctx, &collection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
433 "ensure_unique_name": true,
434 "collection": map[string]interface{}{
435 "owner_uuid": project.UUID,
436 "name": "test collection",
437 "trash_at": time.Now().Add(time.Hour)}})
441 diag.verbosef("ok, uuid = %s", collection.UUID)
445 if collection.UUID != "" {
447 diag.dotest(9990, "deleting temporary collection", func() error {
448 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
450 return client.RequestAndDecodeContext(ctx, nil, "DELETE", "arvados/v1/collections/"+collection.UUID, nil, nil)
455 tempdir, err := ioutil.TempDir("", "arvados-diagnostics")
457 diag.errorf("error creating temp dir: %s", err)
460 defer os.RemoveAll(tempdir)
463 var dockerImageData []byte
464 if diag.dockerImage != "" || diag.priority < 1 {
465 // We won't be using the self-built docker image, so
466 // don't build it. But we will write the embedded
467 // "hello-world" image to our test collection to test
468 // upload/download, whether or not we're using it as a
470 dockerImageData = HelloWorldDockerImage
472 if diag.priority > 0 {
473 imageSHA2, err = getSHA2FromImageData(dockerImageData)
475 diag.errorf("internal error/bug: %s", err)
479 } else if selfbin, err := os.Readlink("/proc/self/exe"); err != nil {
480 diag.errorf("readlink /proc/self/exe: %s", err)
482 } else if selfbindata, err := os.ReadFile(selfbin); err != nil {
483 diag.errorf("error reading %s: %s", selfbin, err)
486 selfbinSha := fmt.Sprintf("%x", sha256.Sum256(selfbindata))
487 tag := "arvados-client-diagnostics:" + selfbinSha[:9]
488 err := os.WriteFile(tempdir+"/arvados-client", selfbindata, 0777)
490 diag.errorf("error writing %s: %s", tempdir+"/arvados-client", err)
494 dockerfile := "FROM " + diag.dockerImageFrom + "\n"
495 dockerfile += "RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install --yes --no-install-recommends libfuse2 ca-certificates && apt-get clean\n"
496 dockerfile += "COPY /arvados-client /arvados-client\n"
497 cmd := exec.Command("docker", "build", "--tag", tag, "-f", "-", tempdir)
498 cmd.Stdin = strings.NewReader(dockerfile)
499 cmd.Stdout = diag.stderr
500 cmd.Stderr = diag.stderr
503 diag.errorf("error building docker image: %s", err)
506 checkversion, err := exec.Command("docker", "run", tag, "/arvados-client", "version").CombinedOutput()
508 diag.errorf("docker image does not seem to work: %s", err)
511 diag.infof("arvados-client version: %s", checkversion)
513 buf, err := exec.Command("docker", "inspect", "--format={{.Id}}", tag).Output()
515 diag.errorf("docker inspect --format={{.Id}} %s: %s", tag, err)
518 imageSHA2 = min64HexDigits.FindString(string(buf))
519 if len(imageSHA2) != 64 {
520 diag.errorf("docker inspect --format={{.Id}} output %q does not seem to contain sha256 digest", buf)
524 buf, err = exec.Command("docker", "save", tag).Output()
526 diag.errorf("docker save %s: %s", tag, err)
529 diag.infof("docker image size is %d", len(buf))
530 dockerImageData = buf
533 tarfilename := "sha256:" + imageSHA2 + ".tar"
535 diag.dotest(100, "uploading file via webdav", func() error {
536 timeout := diag.timeout
537 if len(dockerImageData) > 10<<20 && timeout < time.Minute {
538 // Extend the normal http timeout if we're
539 // uploading a substantial docker image.
540 timeout = time.Minute
542 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(timeout))
544 if collection.UUID == "" {
545 return fmt.Errorf("skipping, no test collection")
548 req, err := http.NewRequestWithContext(ctx, "PUT", cluster.Services.WebDAVDownload.ExternalURL.String()+"c="+collection.UUID+"/"+tarfilename, bytes.NewReader(dockerImageData))
550 return fmt.Errorf("BUG? http.NewRequest: %s", err)
552 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
553 resp, err := http.DefaultClient.Do(req)
555 return fmt.Errorf("error performing http request: %s", err)
558 if resp.StatusCode != http.StatusCreated {
559 return fmt.Errorf("status %s", resp.Status)
561 diag.verbosef("upload ok, status %s, %f MB/s", resp.Status, float64(len(dockerImageData))/time.Since(t0).Seconds()/1000000)
562 err = client.RequestAndDecodeContext(ctx, &collection, "GET", "arvados/v1/collections/"+collection.UUID, nil, nil)
564 return fmt.Errorf("get updated collection: %s", err)
566 diag.verbosef("upload pdh %s", collection.PortableDataHash)
570 davurl := cluster.Services.WebDAV.ExternalURL
571 davWildcard := strings.HasPrefix(davurl.Host, "*--") || strings.HasPrefix(davurl.Host, "*.")
572 diag.dotest(110, fmt.Sprintf("checking WebDAV ExternalURL wildcard (%s)", davurl), func() error {
573 if davurl.Host == "" {
574 return fmt.Errorf("host missing - content previews will not work")
576 if !davWildcard && !cluster.Collections.TrustAllContent {
577 diag.warnf("WebDAV ExternalURL has no leading wildcard and TrustAllContent==false - content previews will not work")
582 for i, trial := range []struct {
588 {false, false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + "foo"},
589 {false, false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + tarfilename},
590 {false, false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/foo"},
591 {false, false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/" + tarfilename},
592 {true, true, http.StatusOK, strings.Replace(davurl.String(), "*", strings.Replace(collection.PortableDataHash, "+", "-", -1), 1) + tarfilename},
593 {true, false, http.StatusOK, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=" + collection.UUID + "/_/" + tarfilename},
595 diag.dotest(120+i, fmt.Sprintf("downloading from webdav (%s)", trial.fileurl), func() error {
596 if trial.needWildcard && !davWildcard {
597 diag.warnf("skipping collection-id-in-vhost test because WebDAV ExternalURL has no leading wildcard")
600 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
602 if trial.needcoll && collection.UUID == "" {
603 return fmt.Errorf("skipping, no test collection")
605 req, err := http.NewRequestWithContext(ctx, "GET", trial.fileurl, nil)
609 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
610 resp, err := http.DefaultClient.Do(req)
614 defer resp.Body.Close()
615 body, err := ioutil.ReadAll(resp.Body)
617 return fmt.Errorf("reading response: %s", err)
619 if resp.StatusCode != trial.status {
620 return fmt.Errorf("unexpected response status: %s", resp.Status)
622 if trial.status == http.StatusOK && !bytes.Equal(body, dockerImageData) {
624 if len(excerpt) > 128 {
625 excerpt = append([]byte(nil), body[:128]...)
626 excerpt = append(excerpt, []byte("[...]")...)
628 return fmt.Errorf("unexpected response content: len %d, %q", len(body), excerpt)
634 var vm arvados.VirtualMachine
635 diag.dotest(130, "getting list of virtual machines", func() error {
636 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
638 var vmlist arvados.VirtualMachineList
639 err := client.RequestAndDecodeContext(ctx, &vmlist, "GET", "arvados/v1/virtual_machines", nil, arvados.ListOptions{Limit: 999999})
643 if len(vmlist.Items) < 1 {
644 diag.warnf("no VMs found")
651 diag.dotest(150, "connecting to webshell service", func() error {
652 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
655 diag.warnf("skipping, no vm available")
658 u := cluster.Services.WebShell.ExternalURL
659 webshellurl := u.String() + vm.Hostname + "?"
660 if strings.HasPrefix(u.Host, "*") {
661 u.Host = vm.Hostname + u.Host[1:]
662 webshellurl = u.String() + "?"
664 diag.debugf("url %s", webshellurl)
665 req, err := http.NewRequestWithContext(ctx, "POST", webshellurl, bytes.NewBufferString(url.Values{
668 "session": {"xyzzy"},
669 "rooturl": {webshellurl},
674 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
675 resp, err := http.DefaultClient.Do(req)
679 defer resp.Body.Close()
680 diag.debugf("response status %s", resp.Status)
681 body, err := ioutil.ReadAll(resp.Body)
683 return fmt.Errorf("reading response: %s", err)
685 diag.debugf("response body %q", body)
686 // We don't speak the protocol, so we get a 400 error
687 // from the webshell server even if everything is
688 // OK. Anything else (404, 502, ???) indicates a
690 if resp.StatusCode != http.StatusBadRequest {
691 return fmt.Errorf("unexpected response status: %s, %q", resp.Status, body)
696 diag.dotest(160, "running a container", func() error {
697 if diag.priority < 1 {
698 diag.infof("skipping (use priority > 0 if you want to run a container)")
701 if project.UUID == "" {
702 return fmt.Errorf("skipping, no project to work in")
705 timestamp := time.Now().Format(time.RFC3339)
707 var ctrCommand []string
708 switch diag.dockerImage {
710 if collection.UUID == "" {
711 return fmt.Errorf("skipping, no test collection to use as docker image")
713 diag.dockerImage = collection.PortableDataHash
714 ctrCommand = []string{"/arvados-client", "diagnostics",
715 "-priority=0", // don't run a container
716 "-log-level=" + diag.logLevel,
717 "-internal-client=true"}
719 if collection.UUID == "" {
720 return fmt.Errorf("skipping, no test collection to use as docker image")
722 diag.dockerImage = collection.PortableDataHash
723 ctrCommand = []string{"/hello"}
725 ctrCommand = []string{"echo", timestamp}
728 var cr arvados.ContainerRequest
729 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
732 err := client.RequestAndDecodeContext(ctx, &cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{"container_request": map[string]interface{}{
733 "owner_uuid": project.UUID,
734 "name": fmt.Sprintf("diagnostics container request %s", timestamp),
735 "container_image": diag.dockerImage,
736 "command": ctrCommand,
737 "use_existing": false,
738 "output_path": "/mnt/output",
739 "output_name": fmt.Sprintf("diagnostics output %s", timestamp),
740 "priority": diag.priority,
741 "state": arvados.ContainerRequestStateCommitted,
742 "mounts": map[string]map[string]interface{}{
744 "kind": "collection",
748 "runtime_constraints": arvados.RuntimeConstraints{
752 KeepCacheRAM: 64 << 20,
758 diag.infof("container request uuid = %s", cr.UUID)
759 diag.verbosef("container uuid = %s", cr.ContainerUUID)
761 timeout := 10 * time.Minute
762 diag.infof("container request submitted, waiting up to %v for container to run", arvados.Duration(timeout))
763 deadline := time.Now().Add(timeout)
765 var c arvados.Container
766 for ; cr.State != arvados.ContainerRequestStateFinal && time.Now().Before(deadline); time.Sleep(2 * time.Second) {
767 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
770 crStateWas := cr.State
771 err := client.RequestAndDecodeContext(ctx, &cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
775 if cr.State != crStateWas {
776 diag.debugf("container request state = %s", cr.State)
780 err = client.RequestAndDecodeContext(ctx, &c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
784 if c.State != cStateWas {
785 diag.debugf("container state = %s", c.State)
791 if cr.State != arvados.ContainerRequestStateFinal {
792 err := client.RequestAndDecodeContext(context.Background(), &cr, "PATCH", "arvados/v1/container_requests/"+cr.UUID, nil, map[string]interface{}{
793 "container_request": map[string]interface{}{
797 diag.infof("error canceling container request %s: %s", cr.UUID, err)
799 diag.debugf("canceled container request %s", cr.UUID)
801 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)
803 if c.State != arvados.ContainerStateComplete {
804 return fmt.Errorf("container request %s is final but container %s did not complete: container state = %q", cr.UUID, cr.ContainerUUID, c.State)
807 return fmt.Errorf("container exited %d", c.ExitCode)
813 func getSHA2FromImageData(dockerImageData []byte) (string, error) {
814 tr := tar.NewReader(bytes.NewReader(dockerImageData))
816 hdr, err := tr.Next()
818 return "", fmt.Errorf("cannot find manifest.json in docker image tar file")
821 return "", fmt.Errorf("cannot read docker image tar file: %s", err)
823 if hdr.Name != "manifest.json" {
826 var manifest []struct {
829 err = json.NewDecoder(tr).Decode(&manifest)
831 return "", fmt.Errorf("cannot read manifest.json from docker image tar file: %s", err)
833 if len(manifest) == 0 {
834 return "", fmt.Errorf("manifest.json is empty")
836 s := min64HexDigits.FindString(manifest[0].Config)
838 return "", fmt.Errorf("found manifest.json but .[0].Config %q does not seem to contain sha256 digest", manifest[0].Config)
844 var min64HexDigits = regexp.MustCompile(`[0-9a-f]{64,}`)