1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
22 "git.arvados.org/arvados.git/lib/cmd"
23 "git.arvados.org/arvados.git/sdk/go/arvados"
24 "git.arvados.org/arvados.git/sdk/go/ctxlog"
25 "github.com/sirupsen/logrus"
30 func (Command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
32 f := flag.NewFlagSet(prog, flag.ContinueOnError)
33 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")
34 f.StringVar(&diag.logLevel, "log-level", "info", "logging level (debug, info, warning, error)")
35 f.StringVar(&diag.dockerImage, "docker-image", "", "image to use when running a test container (default: use embedded hello-world image)")
36 f.BoolVar(&diag.checkInternal, "internal-client", false, "check that this host is considered an \"internal\" client")
37 f.BoolVar(&diag.checkExternal, "external-client", false, "check that this host is considered an \"external\" client")
38 f.IntVar(&diag.priority, "priority", 500, "priority for test container (1..1000, or 0 to skip)")
39 f.DurationVar(&diag.timeout, "timeout", 10*time.Second, "timeout for http requests")
40 if ok, code := cmd.ParseFlags(f, prog, args, "", stderr); !ok {
43 diag.logger = ctxlog.New(stdout, "text", diag.logLevel)
44 diag.logger.SetFormatter(&logrus.TextFormatter{DisableTimestamp: true, DisableLevelTruncation: true, PadLevelText: true})
46 if len(diag.errors) == 0 {
47 diag.logger.Info("--- no errors ---")
50 if diag.logger.Level > logrus.ErrorLevel {
51 fmt.Fprint(stdout, "\n--- cut here --- error summary ---\n\n")
52 for _, e := range diag.errors {
60 // docker save hello-world > hello-world.tar
61 //go:embed hello-world.tar
62 var HelloWorldDockerImage []byte
64 type diagnoser struct {
79 func (diag *diagnoser) debugf(f string, args ...interface{}) {
80 diag.logger.Debugf(" ... "+f, args...)
83 func (diag *diagnoser) infof(f string, args ...interface{}) {
84 diag.logger.Infof(" ... "+f, args...)
87 func (diag *diagnoser) warnf(f string, args ...interface{}) {
88 diag.logger.Warnf(" ... "+f, args...)
91 func (diag *diagnoser) errorf(f string, args ...interface{}) {
92 diag.logger.Errorf(f, args...)
93 diag.errors = append(diag.errors, fmt.Sprintf(f, args...))
96 // Run the given func, logging appropriate messages before and after,
97 // adding timing info, etc.
99 // The id argument should be unique among tests, and shouldn't change
100 // when other tests are added/removed.
101 func (diag *diagnoser) dotest(id int, title string, fn func() error) {
102 if diag.done == nil {
103 diag.done = map[int]bool{}
104 } else if diag.done[id] {
105 diag.errorf("(bug) reused test id %d", id)
109 diag.logger.Infof("%4d: %s", id, title)
112 elapsed := fmt.Sprintf("%d ms", time.Now().Sub(t0)/time.Millisecond)
114 diag.errorf("%4d: %s (%s): %s", id, title, elapsed, err)
116 diag.logger.Debugf("%4d: %s (%s): ok", id, title, elapsed)
120 func (diag *diagnoser) runtests() {
121 client := arvados.NewClientFromEnv()
123 if client.APIHost == "" || client.AuthToken == "" {
124 diag.errorf("ARVADOS_API_HOST and ARVADOS_API_TOKEN environment variables are not set -- aborting without running any tests")
128 var dd arvados.DiscoveryDocument
129 ddpath := "discovery/v1/apis/arvados/v1/rest"
130 diag.dotest(10, fmt.Sprintf("getting discovery document from https://%s/%s", client.APIHost, ddpath), func() error {
131 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
133 err := client.RequestAndDecodeContext(ctx, &dd, "GET", ddpath, nil, nil)
137 diag.debugf("BlobSignatureTTL = %d", dd.BlobSignatureTTL)
141 var cluster arvados.Cluster
142 cfgpath := "arvados/v1/config"
144 diag.dotest(20, fmt.Sprintf("getting exported config from https://%s/%s", client.APIHost, cfgpath), func() error {
145 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
147 err := client.RequestAndDecodeContext(ctx, &cluster, "GET", cfgpath, nil, nil)
151 diag.debugf("Collections.BlobSigning = %v", cluster.Collections.BlobSigning)
156 var user arvados.User
157 diag.dotest(30, "getting current user record", func() error {
158 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
160 err := client.RequestAndDecodeContext(ctx, &user, "GET", "arvados/v1/users/current", nil, nil)
164 diag.debugf("user uuid = %s", user.UUID)
169 diag.errorf("cannot proceed without cluster config -- aborting without running any further tests")
173 // uncomment to create some spurious errors
174 // cluster.Services.WebDAVDownload.ExternalURL.Host = "0.0.0.0:9"
176 // TODO: detect routing errors here, like finding wb2 at the
178 for i, svc := range []*arvados.Service{
179 &cluster.Services.Keepproxy,
180 &cluster.Services.WebDAV,
181 &cluster.Services.WebDAVDownload,
182 &cluster.Services.Websocket,
183 &cluster.Services.Workbench1,
184 &cluster.Services.Workbench2,
186 diag.dotest(40+i, fmt.Sprintf("connecting to service endpoint %s", svc.ExternalURL), func() error {
187 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
190 if strings.HasPrefix(u.Scheme, "ws") {
191 // We can do a real websocket test elsewhere,
192 // but for now we'll just check the https
194 u.Scheme = "http" + u.Scheme[2:]
196 if svc == &cluster.Services.WebDAV && strings.HasPrefix(u.Host, "*") {
197 u.Host = "d41d8cd98f00b204e9800998ecf8427e-0" + u.Host[1:]
199 req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
203 resp, err := http.DefaultClient.Do(req)
212 for i, url := range []string{
213 cluster.Services.Controller.ExternalURL.String(),
214 cluster.Services.Keepproxy.ExternalURL.String() + "d41d8cd98f00b204e9800998ecf8427e+0",
215 cluster.Services.WebDAVDownload.ExternalURL.String(),
217 diag.dotest(50+i, fmt.Sprintf("checking CORS headers at %s", url), func() error {
218 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
220 req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
224 req.Header.Set("Origin", "https://example.com")
225 resp, err := http.DefaultClient.Do(req)
229 if hdr := resp.Header.Get("Access-Control-Allow-Origin"); hdr != "*" {
230 return fmt.Errorf("expected \"Access-Control-Allow-Origin: *\", got %q", hdr)
236 var keeplist arvados.KeepServiceList
237 diag.dotest(60, "checking internal/external client detection", func() error {
238 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
240 err := client.RequestAndDecodeContext(ctx, &keeplist, "GET", "arvados/v1/keep_services/accessible", nil, arvados.ListOptions{Limit: 999999})
242 return fmt.Errorf("error getting keep services list: %s", err)
243 } else if len(keeplist.Items) == 0 {
244 return fmt.Errorf("controller did not return any keep services")
246 found := map[string]int{}
247 for _, ks := range keeplist.Items {
248 found[ks.ServiceType]++
250 isInternal := found["proxy"] == 0 && len(keeplist.Items) > 0
251 isExternal := found["proxy"] > 0 && found["proxy"] == len(keeplist.Items)
253 diag.debugf("controller returned only proxy services, this host is treated as \"external\"")
254 } else if isInternal {
255 diag.debugf("controller returned only non-proxy services, this host is treated as \"internal\"")
257 if (diag.checkInternal && !isInternal) || (diag.checkExternal && !isExternal) {
258 return fmt.Errorf("expecting internal=%v external=%v, but found internal=%v external=%v", diag.checkInternal, diag.checkExternal, isInternal, isExternal)
263 for i, ks := range keeplist.Items {
266 Host: net.JoinHostPort(ks.ServiceHost, fmt.Sprintf("%d", ks.ServicePort)),
269 if ks.ServiceSSLFlag {
272 diag.dotest(61+i, fmt.Sprintf("reading+writing via keep service at %s", u.String()), func() error {
273 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
275 req, err := http.NewRequestWithContext(ctx, "PUT", u.String()+"d41d8cd98f00b204e9800998ecf8427e", nil)
279 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
280 resp, err := http.DefaultClient.Do(req)
284 defer resp.Body.Close()
285 body, err := ioutil.ReadAll(resp.Body)
287 return fmt.Errorf("reading response body: %s", err)
289 loc := strings.TrimSpace(string(body))
290 if !strings.HasPrefix(loc, "d41d8") {
291 return fmt.Errorf("unexpected response from write: %q", body)
294 req, err = http.NewRequestWithContext(ctx, "GET", u.String()+loc, nil)
298 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
299 resp, err = http.DefaultClient.Do(req)
303 defer resp.Body.Close()
304 body, err = ioutil.ReadAll(resp.Body)
306 return fmt.Errorf("reading response body: %s", err)
309 return fmt.Errorf("unexpected response from read: %q", body)
316 var project arvados.Group
317 diag.dotest(80, fmt.Sprintf("finding/creating %q project", diag.projectName), func() error {
318 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
320 var grplist arvados.GroupList
321 err := client.RequestAndDecodeContext(ctx, &grplist, "GET", "arvados/v1/groups", nil, arvados.ListOptions{
322 Filters: []arvados.Filter{
323 {"name", "=", diag.projectName},
324 {"group_class", "=", "project"},
325 {"owner_uuid", "=", user.UUID}},
328 return fmt.Errorf("list groups: %s", err)
330 if len(grplist.Items) > 0 {
331 project = grplist.Items[0]
332 diag.debugf("using existing project, uuid = %s", project.UUID)
335 diag.debugf("list groups: ok, no results")
336 err = client.RequestAndDecodeContext(ctx, &project, "POST", "arvados/v1/groups", nil, map[string]interface{}{"group": map[string]interface{}{
337 "name": diag.projectName,
338 "group_class": "project",
341 return fmt.Errorf("create project: %s", err)
343 diag.debugf("created project, uuid = %s", project.UUID)
347 var collection arvados.Collection
348 diag.dotest(90, "creating temporary collection", func() error {
349 if project.UUID == "" {
350 return fmt.Errorf("skipping, no project to work in")
352 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
354 err := client.RequestAndDecodeContext(ctx, &collection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
355 "ensure_unique_name": true,
356 "collection": map[string]interface{}{
357 "owner_uuid": project.UUID,
358 "name": "test collection",
359 "trash_at": time.Now().Add(time.Hour)}})
363 diag.debugf("ok, uuid = %s", collection.UUID)
367 if collection.UUID != "" {
369 diag.dotest(9990, "deleting temporary collection", func() error {
370 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
372 return client.RequestAndDecodeContext(ctx, nil, "DELETE", "arvados/v1/collections/"+collection.UUID, nil, nil)
377 // Read hello-world.tar to find image ID, so we can upload it
378 // as "sha256:{...}.tar"
381 tr := tar.NewReader(bytes.NewReader(HelloWorldDockerImage))
383 hdr, err := tr.Next()
388 diag.errorf("internal error/bug: cannot read embedded docker image tar file: %s", err)
391 if s := strings.TrimSuffix(hdr.Name, ".json"); len(s) == 64 && s != hdr.Name {
396 diag.errorf("internal error/bug: cannot find {sha256}.json file in embedded docker image tar file")
400 tarfilename := "sha256:" + imageSHA2 + ".tar"
402 diag.dotest(100, "uploading file via webdav", func() error {
403 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
405 if collection.UUID == "" {
406 return fmt.Errorf("skipping, no test collection")
408 req, err := http.NewRequestWithContext(ctx, "PUT", cluster.Services.WebDAVDownload.ExternalURL.String()+"c="+collection.UUID+"/"+tarfilename, bytes.NewReader(HelloWorldDockerImage))
410 return fmt.Errorf("BUG? http.NewRequest: %s", err)
412 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
413 resp, err := http.DefaultClient.Do(req)
415 return fmt.Errorf("error performing http request: %s", err)
418 if resp.StatusCode != http.StatusCreated {
419 return fmt.Errorf("status %s", resp.Status)
421 diag.debugf("ok, status %s", resp.Status)
422 err = client.RequestAndDecodeContext(ctx, &collection, "GET", "arvados/v1/collections/"+collection.UUID, nil, nil)
424 return fmt.Errorf("get updated collection: %s", err)
426 diag.debugf("ok, pdh %s", collection.PortableDataHash)
430 davurl := cluster.Services.WebDAV.ExternalURL
431 davWildcard := strings.HasPrefix(davurl.Host, "*--") || strings.HasPrefix(davurl.Host, "*.")
432 diag.dotest(110, fmt.Sprintf("checking WebDAV ExternalURL wildcard (%s)", davurl), func() error {
433 if davurl.Host == "" {
434 return fmt.Errorf("host missing - content previews will not work")
436 if !davWildcard && !cluster.Collections.TrustAllContent {
437 diag.warnf("WebDAV ExternalURL has no leading wildcard and TrustAllContent==false - content previews will not work")
442 for i, trial := range []struct {
448 {false, false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + "foo"},
449 {false, false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + tarfilename},
450 {false, false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/foo"},
451 {false, false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/" + tarfilename},
452 {true, true, http.StatusOK, strings.Replace(davurl.String(), "*", strings.Replace(collection.PortableDataHash, "+", "-", -1), 1) + tarfilename},
453 {true, false, http.StatusOK, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=" + collection.UUID + "/_/" + tarfilename},
455 diag.dotest(120+i, fmt.Sprintf("downloading from webdav (%s)", trial.fileurl), func() error {
456 if trial.needWildcard && !davWildcard {
457 diag.warnf("skipping collection-id-in-vhost test because WebDAV ExternalURL has no leading wildcard")
460 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
462 if trial.needcoll && collection.UUID == "" {
463 return fmt.Errorf("skipping, no test collection")
465 req, err := http.NewRequestWithContext(ctx, "GET", trial.fileurl, nil)
469 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
470 resp, err := http.DefaultClient.Do(req)
474 defer resp.Body.Close()
475 body, err := ioutil.ReadAll(resp.Body)
477 return fmt.Errorf("reading response: %s", err)
479 if resp.StatusCode != trial.status {
480 return fmt.Errorf("unexpected response status: %s", resp.Status)
482 if trial.status == http.StatusOK && !bytes.Equal(body, HelloWorldDockerImage) {
484 if len(excerpt) > 128 {
485 excerpt = append([]byte(nil), body[:128]...)
486 excerpt = append(excerpt, []byte("[...]")...)
488 return fmt.Errorf("unexpected response content: len %d, %q", len(body), excerpt)
494 var vm arvados.VirtualMachine
495 diag.dotest(130, "getting list of virtual machines", func() error {
496 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
498 var vmlist arvados.VirtualMachineList
499 err := client.RequestAndDecodeContext(ctx, &vmlist, "GET", "arvados/v1/virtual_machines", nil, arvados.ListOptions{Limit: 999999})
503 if len(vmlist.Items) < 1 {
504 diag.warnf("no VMs found")
511 diag.dotest(140, "getting workbench1 webshell page", func() error {
512 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
515 diag.warnf("skipping, no vm available")
518 webshelltermurl := cluster.Services.Workbench1.ExternalURL.String() + "virtual_machines/" + vm.UUID + "/webshell/testusername"
519 diag.debugf("url %s", webshelltermurl)
520 req, err := http.NewRequestWithContext(ctx, "GET", webshelltermurl, nil)
524 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
525 resp, err := http.DefaultClient.Do(req)
529 defer resp.Body.Close()
530 body, err := ioutil.ReadAll(resp.Body)
532 return fmt.Errorf("reading response: %s", err)
534 if resp.StatusCode != http.StatusOK {
535 return fmt.Errorf("unexpected response status: %s %q", resp.Status, body)
540 diag.dotest(150, "connecting to webshell service", func() error {
541 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
544 diag.warnf("skipping, no vm available")
547 u := cluster.Services.WebShell.ExternalURL
548 webshellurl := u.String() + vm.Hostname + "?"
549 if strings.HasPrefix(u.Host, "*") {
550 u.Host = vm.Hostname + u.Host[1:]
551 webshellurl = u.String() + "?"
553 diag.debugf("url %s", webshellurl)
554 req, err := http.NewRequestWithContext(ctx, "POST", webshellurl, bytes.NewBufferString(url.Values{
557 "session": {"xyzzy"},
558 "rooturl": {webshellurl},
563 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
564 resp, err := http.DefaultClient.Do(req)
568 defer resp.Body.Close()
569 diag.debugf("response status %s", resp.Status)
570 body, err := ioutil.ReadAll(resp.Body)
572 return fmt.Errorf("reading response: %s", err)
574 diag.debugf("response body %q", body)
575 // We don't speak the protocol, so we get a 400 error
576 // from the webshell server even if everything is
577 // OK. Anything else (404, 502, ???) indicates a
579 if resp.StatusCode != http.StatusBadRequest {
580 return fmt.Errorf("unexpected response status: %s, %q", resp.Status, body)
585 diag.dotest(160, "running a container", func() error {
586 if diag.priority < 1 {
587 diag.infof("skipping (use priority > 0 if you want to run a container)")
590 if project.UUID == "" {
591 return fmt.Errorf("skipping, no project to work in")
594 timestamp := time.Now().Format(time.RFC3339)
595 ctrCommand := []string{"echo", timestamp}
596 if diag.dockerImage == "" {
597 if collection.UUID == "" {
598 return fmt.Errorf("skipping, no test collection to use as docker image")
600 diag.dockerImage = collection.PortableDataHash
601 ctrCommand = []string{"/hello"}
604 var cr arvados.ContainerRequest
605 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
608 err := client.RequestAndDecodeContext(ctx, &cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{"container_request": map[string]interface{}{
609 "owner_uuid": project.UUID,
610 "name": fmt.Sprintf("diagnostics container request %s", timestamp),
611 "container_image": diag.dockerImage,
612 "command": ctrCommand,
613 "use_existing": false,
614 "output_path": "/mnt/output",
615 "output_name": fmt.Sprintf("diagnostics output %s", timestamp),
616 "priority": diag.priority,
617 "state": arvados.ContainerRequestStateCommitted,
618 "mounts": map[string]map[string]interface{}{
620 "kind": "collection",
624 "runtime_constraints": arvados.RuntimeConstraints{
627 KeepCacheRAM: 1 << 26,
633 diag.debugf("container request uuid = %s", cr.UUID)
634 diag.debugf("container uuid = %s", cr.ContainerUUID)
636 timeout := 10 * time.Minute
637 diag.infof("container request submitted, waiting up to %v for container to run", arvados.Duration(timeout))
638 ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(timeout))
641 var c arvados.Container
642 for ; cr.State != arvados.ContainerRequestStateFinal; time.Sleep(2 * time.Second) {
643 ctx, cancel := context.WithDeadline(ctx, time.Now().Add(diag.timeout))
646 crStateWas := cr.State
647 err := client.RequestAndDecodeContext(ctx, &cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
651 if cr.State != crStateWas {
652 diag.debugf("container request state = %s", cr.State)
656 err = client.RequestAndDecodeContext(ctx, &c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
660 if c.State != cStateWas {
661 diag.debugf("container state = %s", c.State)
665 if c.State != arvados.ContainerStateComplete {
666 return fmt.Errorf("container request %s is final but container %s did not complete: container state = %q", cr.UUID, cr.ContainerUUID, c.State)
667 } else if c.ExitCode != 0 {
668 return fmt.Errorf("container exited %d", c.ExitCode)