1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.arvados.org/arvados.git/sdk/go/arvados"
21 "git.arvados.org/arvados.git/sdk/go/ctxlog"
22 "github.com/sirupsen/logrus"
27 func (cmd Command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
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")
37 if err == flag.ErrHelp {
39 } else if err != nil {
40 fmt.Fprintln(stderr, err)
42 } else if f.NArg() != 0 {
43 fmt.Fprintf(stderr, "unrecognized command line arguments: %v\n", f.Args())
46 diag.logger = ctxlog.New(stdout, "text", diag.logLevel)
47 diag.logger.SetFormatter(&logrus.TextFormatter{DisableTimestamp: true, DisableLevelTruncation: true, PadLevelText: true})
49 if len(diag.errors) == 0 {
50 diag.logger.Info("--- no errors ---")
53 if diag.logger.Level > logrus.ErrorLevel {
54 fmt.Fprint(stdout, "\n--- cut here --- error summary ---\n\n")
55 for _, e := range diag.errors {
63 type diagnoser struct {
77 func (diag *diagnoser) debugf(f string, args ...interface{}) {
78 diag.logger.Debugf(" ... "+f, args...)
81 func (diag *diagnoser) infof(f string, args ...interface{}) {
82 diag.logger.Infof(" ... "+f, args...)
85 func (diag *diagnoser) warnf(f string, args ...interface{}) {
86 diag.logger.Warnf(" ... "+f, args...)
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...))
94 // Run the given func, logging appropriate messages before and after,
95 // adding timing info, etc.
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)
107 diag.logger.Infof("%4d: %s", id, title)
110 elapsed := fmt.Sprintf("%d ms", time.Now().Sub(t0)/time.Millisecond)
112 diag.errorf("%4d: %s (%s): %s", id, title, elapsed, err)
114 diag.logger.Debugf("%4d: %s (%s): ok", id, title, elapsed)
118 func (diag *diagnoser) runtests() {
119 client := arvados.NewClientFromEnv()
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")
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))
131 err := client.RequestAndDecodeContext(ctx, &dd, "GET", ddpath, nil, nil)
135 diag.debugf("BlobSignatureTTL = %d", dd.BlobSignatureTTL)
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))
144 err := client.RequestAndDecodeContext(ctx, &cluster, "GET", cfgpath, nil, nil)
148 diag.debugf("Collections.BlobSigning = %v", cluster.Collections.BlobSigning)
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))
156 err := client.RequestAndDecodeContext(ctx, &user, "GET", "arvados/v1/users/current", nil, nil)
160 diag.debugf("user uuid = %s", user.UUID)
164 // uncomment to create some spurious errors
165 // cluster.Services.WebDAVDownload.ExternalURL.Host = "0.0.0.0:9"
167 // TODO: detect routing errors here, like finding wb2 at the
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,
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))
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
185 u.Scheme = "http" + u.Scheme[2:]
187 if svc == &cluster.Services.WebDAV && strings.HasPrefix(u.Host, "*") {
188 u.Host = "d41d8cd98f00b204e9800998ecf8427e-0" + u.Host[1:]
190 req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
194 resp, err := http.DefaultClient.Do(req)
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(),
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))
211 req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
215 req.Header.Set("Origin", "https://example.com")
216 resp, err := http.DefaultClient.Do(req)
220 if hdr := resp.Header.Get("Access-Control-Allow-Origin"); hdr != "*" {
221 return fmt.Errorf("expected \"Access-Control-Allow-Origin: *\", got %q", hdr)
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))
231 err := client.RequestAndDecodeContext(ctx, &keeplist, "GET", "arvados/v1/keep_services/accessible", nil, arvados.ListOptions{Limit: 999999})
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")
237 found := map[string]int{}
238 for _, ks := range keeplist.Items {
239 found[ks.ServiceType]++
241 isInternal := found["proxy"] == 0 && len(keeplist.Items) > 0
242 isExternal := found["proxy"] > 0 && found["proxy"] == len(keeplist.Items)
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\"")
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)
254 for i, ks := range keeplist.Items {
257 Host: net.JoinHostPort(ks.ServiceHost, fmt.Sprintf("%d", ks.ServicePort)),
260 if ks.ServiceSSLFlag {
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))
266 req, err := http.NewRequestWithContext(ctx, "PUT", u.String()+"d41d8cd98f00b204e9800998ecf8427e", nil)
270 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
271 resp, err := http.DefaultClient.Do(req)
275 defer resp.Body.Close()
276 body, err := ioutil.ReadAll(resp.Body)
278 return fmt.Errorf("reading response body: %s", err)
280 loc := strings.TrimSpace(string(body))
281 if !strings.HasPrefix(loc, "d41d8") {
282 return fmt.Errorf("unexpected response from write: %q", body)
285 req, err = http.NewRequestWithContext(ctx, "GET", u.String()+loc, nil)
289 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
290 resp, err = http.DefaultClient.Do(req)
294 defer resp.Body.Close()
295 body, err = ioutil.ReadAll(resp.Body)
297 return fmt.Errorf("reading response body: %s", err)
300 return fmt.Errorf("unexpected response from read: %q", body)
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))
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}},
319 return fmt.Errorf("list groups: %s", err)
321 if len(grplist.Items) > 0 {
322 project = grplist.Items[0]
323 diag.debugf("using existing project, uuid = %s", project.UUID)
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",
332 return fmt.Errorf("create project: %s", err)
334 diag.debugf("created project, uuid = %s", project.UUID)
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")
343 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
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)}})
354 diag.debugf("ok, uuid = %s", collection.UUID)
358 if collection.UUID != "" {
360 diag.dotest(9990, "deleting temporary collection", func() error {
361 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
363 return client.RequestAndDecodeContext(ctx, nil, "DELETE", "arvados/v1/collections/"+collection.UUID, nil, nil)
368 diag.dotest(100, "uploading file via webdav", func() error {
369 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
371 if collection.UUID == "" {
372 return fmt.Errorf("skipping, no test collection")
374 req, err := http.NewRequestWithContext(ctx, "PUT", cluster.Services.WebDAVDownload.ExternalURL.String()+"c="+collection.UUID+"/testfile", bytes.NewBufferString("testfiledata"))
376 return fmt.Errorf("BUG? http.NewRequest: %s", err)
378 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
379 resp, err := http.DefaultClient.Do(req)
381 return fmt.Errorf("error performing http request: %s", err)
384 if resp.StatusCode != http.StatusCreated {
385 return fmt.Errorf("status %s", resp.Status)
387 diag.debugf("ok, status %s", resp.Status)
388 err = client.RequestAndDecodeContext(ctx, &collection, "GET", "arvados/v1/collections/"+collection.UUID, nil, nil)
390 return fmt.Errorf("get updated collection: %s", err)
392 diag.debugf("ok, pdh %s", collection.PortableDataHash)
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")
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")
407 for i, trial := range []struct {
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"},
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))
422 if trial.needcoll && collection.UUID == "" {
423 return fmt.Errorf("skipping, no test collection")
425 req, err := http.NewRequestWithContext(ctx, "GET", trial.fileurl, nil)
429 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
430 resp, err := http.DefaultClient.Do(req)
434 defer resp.Body.Close()
435 body, err := ioutil.ReadAll(resp.Body)
437 return fmt.Errorf("reading response: %s", err)
439 if resp.StatusCode != trial.status {
440 return fmt.Errorf("unexpected response status: %s", resp.Status)
442 if trial.status == http.StatusOK && string(body) != "testfiledata" {
443 return fmt.Errorf("unexpected response content: %q", body)
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))
453 var vmlist arvados.VirtualMachineList
454 err := client.RequestAndDecodeContext(ctx, &vmlist, "GET", "arvados/v1/virtual_machines", nil, arvados.ListOptions{Limit: 999999})
458 if len(vmlist.Items) < 1 {
459 return fmt.Errorf("no VMs found")
465 diag.dotest(140, "getting workbench1 webshell page", func() error {
466 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
469 return fmt.Errorf("skipping, no vm available")
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)
477 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
478 resp, err := http.DefaultClient.Do(req)
482 defer resp.Body.Close()
483 body, err := ioutil.ReadAll(resp.Body)
485 return fmt.Errorf("reading response: %s", err)
487 if resp.StatusCode != http.StatusOK {
488 return fmt.Errorf("unexpected response status: %s %q", resp.Status, body)
493 diag.dotest(150, "connecting to webshell service", func() error {
494 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
497 return fmt.Errorf("skipping, no vm available")
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() + "?"
505 diag.debugf("url %s", webshellurl)
506 req, err := http.NewRequestWithContext(ctx, "POST", webshellurl, bytes.NewBufferString(url.Values{
509 "session": {"xyzzy"},
510 "rooturl": {webshellurl},
515 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
516 resp, err := http.DefaultClient.Do(req)
520 defer resp.Body.Close()
521 diag.debugf("response status %s", resp.Status)
522 body, err := ioutil.ReadAll(resp.Body)
524 return fmt.Errorf("reading response: %s", err)
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
531 if resp.StatusCode != http.StatusBadRequest {
532 return fmt.Errorf("unexpected response status: %s, %q", resp.Status, body)
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)")
542 if project.UUID == "" {
543 return fmt.Errorf("skipping, no project to work in")
546 var cr arvados.ContainerRequest
547 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
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{}{
563 "kind": "collection",
567 "runtime_constraints": arvados.RuntimeConstraints{
570 KeepCacheRAM: 1 << 26,
576 diag.debugf("container request uuid = %s", cr.UUID)
577 diag.debugf("container uuid = %s", cr.ContainerUUID)
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))
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))
589 crStateWas := cr.State
590 err := client.RequestAndDecodeContext(ctx, &cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
594 if cr.State != crStateWas {
595 diag.debugf("container request state = %s", cr.State)
599 err = client.RequestAndDecodeContext(ctx, &c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
603 if c.State != cStateWas {
604 diag.debugf("container state = %s", c.State)
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)