1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.arvados.org/arvados.git/lib/cmd"
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "git.arvados.org/arvados.git/sdk/go/ctxlog"
23 "github.com/sirupsen/logrus"
28 func (Command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
30 f := flag.NewFlagSet(prog, flag.ContinueOnError)
31 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")
32 f.StringVar(&diag.logLevel, "log-level", "info", "logging level (debug, info, warning, error)")
33 f.BoolVar(&diag.checkInternal, "internal-client", false, "check that this host is considered an \"internal\" client")
34 f.BoolVar(&diag.checkExternal, "external-client", false, "check that this host is considered an \"external\" client")
35 f.IntVar(&diag.priority, "priority", 500, "priority for test container (1..1000, or 0 to skip)")
36 f.DurationVar(&diag.timeout, "timeout", 10*time.Second, "timeout for http requests")
37 if ok, code := cmd.ParseFlags(f, prog, args, "", stderr); !ok {
40 diag.logger = ctxlog.New(stdout, "text", diag.logLevel)
41 diag.logger.SetFormatter(&logrus.TextFormatter{DisableTimestamp: true, DisableLevelTruncation: true, PadLevelText: true})
43 if len(diag.errors) == 0 {
44 diag.logger.Info("--- no errors ---")
47 if diag.logger.Level > logrus.ErrorLevel {
48 fmt.Fprint(stdout, "\n--- cut here --- error summary ---\n\n")
49 for _, e := range diag.errors {
57 type diagnoser struct {
71 func (diag *diagnoser) debugf(f string, args ...interface{}) {
72 diag.logger.Debugf(" ... "+f, args...)
75 func (diag *diagnoser) infof(f string, args ...interface{}) {
76 diag.logger.Infof(" ... "+f, args...)
79 func (diag *diagnoser) warnf(f string, args ...interface{}) {
80 diag.logger.Warnf(" ... "+f, args...)
83 func (diag *diagnoser) errorf(f string, args ...interface{}) {
84 diag.logger.Errorf(f, args...)
85 diag.errors = append(diag.errors, fmt.Sprintf(f, args...))
88 // Run the given func, logging appropriate messages before and after,
89 // adding timing info, etc.
91 // The id argument should be unique among tests, and shouldn't change
92 // when other tests are added/removed.
93 func (diag *diagnoser) dotest(id int, title string, fn func() error) {
95 diag.done = map[int]bool{}
96 } else if diag.done[id] {
97 diag.errorf("(bug) reused test id %d", id)
101 diag.logger.Infof("%4d: %s", id, title)
104 elapsed := fmt.Sprintf("%d ms", time.Now().Sub(t0)/time.Millisecond)
106 diag.errorf("%4d: %s (%s): %s", id, title, elapsed, err)
108 diag.logger.Debugf("%4d: %s (%s): ok", id, title, elapsed)
112 func (diag *diagnoser) runtests() {
113 client := arvados.NewClientFromEnv()
115 if client.APIHost == "" || client.AuthToken == "" {
116 diag.errorf("ARVADOS_API_HOST and ARVADOS_API_TOKEN environment variables are not set -- aborting without running any tests")
120 var dd arvados.DiscoveryDocument
121 ddpath := "discovery/v1/apis/arvados/v1/rest"
122 diag.dotest(10, fmt.Sprintf("getting discovery document from https://%s/%s", client.APIHost, ddpath), func() error {
123 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
125 err := client.RequestAndDecodeContext(ctx, &dd, "GET", ddpath, nil, nil)
129 diag.debugf("BlobSignatureTTL = %d", dd.BlobSignatureTTL)
133 var cluster arvados.Cluster
134 cfgpath := "arvados/v1/config"
135 diag.dotest(20, fmt.Sprintf("getting exported config from https://%s/%s", client.APIHost, cfgpath), func() error {
136 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
138 err := client.RequestAndDecodeContext(ctx, &cluster, "GET", cfgpath, nil, nil)
142 diag.debugf("Collections.BlobSigning = %v", cluster.Collections.BlobSigning)
146 var user arvados.User
147 diag.dotest(30, "getting current user record", func() error {
148 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
150 err := client.RequestAndDecodeContext(ctx, &user, "GET", "arvados/v1/users/current", nil, nil)
154 diag.debugf("user uuid = %s", user.UUID)
158 // uncomment to create some spurious errors
159 // cluster.Services.WebDAVDownload.ExternalURL.Host = "0.0.0.0:9"
161 // TODO: detect routing errors here, like finding wb2 at the
163 for i, svc := range []*arvados.Service{
164 &cluster.Services.Keepproxy,
165 &cluster.Services.WebDAV,
166 &cluster.Services.WebDAVDownload,
167 &cluster.Services.Websocket,
168 &cluster.Services.Workbench1,
169 &cluster.Services.Workbench2,
171 diag.dotest(40+i, fmt.Sprintf("connecting to service endpoint %s", svc.ExternalURL), func() error {
172 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
175 if strings.HasPrefix(u.Scheme, "ws") {
176 // We can do a real websocket test elsewhere,
177 // but for now we'll just check the https
179 u.Scheme = "http" + u.Scheme[2:]
181 if svc == &cluster.Services.WebDAV && strings.HasPrefix(u.Host, "*") {
182 u.Host = "d41d8cd98f00b204e9800998ecf8427e-0" + u.Host[1:]
184 req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
188 resp, err := http.DefaultClient.Do(req)
197 for i, url := range []string{
198 cluster.Services.Controller.ExternalURL.String(),
199 cluster.Services.Keepproxy.ExternalURL.String() + "d41d8cd98f00b204e9800998ecf8427e+0",
200 cluster.Services.WebDAVDownload.ExternalURL.String(),
202 diag.dotest(50+i, fmt.Sprintf("checking CORS headers at %s", url), func() error {
203 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
205 req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
209 req.Header.Set("Origin", "https://example.com")
210 resp, err := http.DefaultClient.Do(req)
214 if hdr := resp.Header.Get("Access-Control-Allow-Origin"); hdr != "*" {
215 return fmt.Errorf("expected \"Access-Control-Allow-Origin: *\", got %q", hdr)
221 var keeplist arvados.KeepServiceList
222 diag.dotest(60, "checking internal/external client detection", func() error {
223 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
225 err := client.RequestAndDecodeContext(ctx, &keeplist, "GET", "arvados/v1/keep_services/accessible", nil, arvados.ListOptions{Limit: 999999})
227 return fmt.Errorf("error getting keep services list: %s", err)
228 } else if len(keeplist.Items) == 0 {
229 return fmt.Errorf("controller did not return any keep services")
231 found := map[string]int{}
232 for _, ks := range keeplist.Items {
233 found[ks.ServiceType]++
235 isInternal := found["proxy"] == 0 && len(keeplist.Items) > 0
236 isExternal := found["proxy"] > 0 && found["proxy"] == len(keeplist.Items)
238 diag.debugf("controller returned only proxy services, this host is treated as \"external\"")
239 } else if isInternal {
240 diag.debugf("controller returned only non-proxy services, this host is treated as \"internal\"")
242 if (diag.checkInternal && !isInternal) || (diag.checkExternal && !isExternal) {
243 return fmt.Errorf("expecting internal=%v external=%v, but found internal=%v external=%v", diag.checkInternal, diag.checkExternal, isInternal, isExternal)
248 for i, ks := range keeplist.Items {
251 Host: net.JoinHostPort(ks.ServiceHost, fmt.Sprintf("%d", ks.ServicePort)),
254 if ks.ServiceSSLFlag {
257 diag.dotest(61+i, fmt.Sprintf("reading+writing via keep service at %s", u.String()), func() error {
258 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
260 req, err := http.NewRequestWithContext(ctx, "PUT", u.String()+"d41d8cd98f00b204e9800998ecf8427e", nil)
264 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
265 resp, err := http.DefaultClient.Do(req)
269 defer resp.Body.Close()
270 body, err := ioutil.ReadAll(resp.Body)
272 return fmt.Errorf("reading response body: %s", err)
274 loc := strings.TrimSpace(string(body))
275 if !strings.HasPrefix(loc, "d41d8") {
276 return fmt.Errorf("unexpected response from write: %q", body)
279 req, err = http.NewRequestWithContext(ctx, "GET", u.String()+loc, nil)
283 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
284 resp, err = http.DefaultClient.Do(req)
288 defer resp.Body.Close()
289 body, err = ioutil.ReadAll(resp.Body)
291 return fmt.Errorf("reading response body: %s", err)
294 return fmt.Errorf("unexpected response from read: %q", body)
301 var project arvados.Group
302 diag.dotest(80, fmt.Sprintf("finding/creating %q project", diag.projectName), func() error {
303 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
305 var grplist arvados.GroupList
306 err := client.RequestAndDecodeContext(ctx, &grplist, "GET", "arvados/v1/groups", nil, arvados.ListOptions{
307 Filters: []arvados.Filter{
308 {"name", "=", diag.projectName},
309 {"group_class", "=", "project"},
310 {"owner_uuid", "=", user.UUID}},
313 return fmt.Errorf("list groups: %s", err)
315 if len(grplist.Items) > 0 {
316 project = grplist.Items[0]
317 diag.debugf("using existing project, uuid = %s", project.UUID)
320 diag.debugf("list groups: ok, no results")
321 err = client.RequestAndDecodeContext(ctx, &project, "POST", "arvados/v1/groups", nil, map[string]interface{}{"group": map[string]interface{}{
322 "name": diag.projectName,
323 "group_class": "project",
326 return fmt.Errorf("create project: %s", err)
328 diag.debugf("created project, uuid = %s", project.UUID)
332 var collection arvados.Collection
333 diag.dotest(90, "creating temporary collection", func() error {
334 if project.UUID == "" {
335 return fmt.Errorf("skipping, no project to work in")
337 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
339 err := client.RequestAndDecodeContext(ctx, &collection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
340 "ensure_unique_name": true,
341 "collection": map[string]interface{}{
342 "owner_uuid": project.UUID,
343 "name": "test collection",
344 "trash_at": time.Now().Add(time.Hour)}})
348 diag.debugf("ok, uuid = %s", collection.UUID)
352 if collection.UUID != "" {
354 diag.dotest(9990, "deleting temporary collection", func() error {
355 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
357 return client.RequestAndDecodeContext(ctx, nil, "DELETE", "arvados/v1/collections/"+collection.UUID, nil, nil)
362 diag.dotest(100, "uploading file via webdav", func() error {
363 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
365 if collection.UUID == "" {
366 return fmt.Errorf("skipping, no test collection")
368 req, err := http.NewRequestWithContext(ctx, "PUT", cluster.Services.WebDAVDownload.ExternalURL.String()+"c="+collection.UUID+"/testfile", bytes.NewBufferString("testfiledata"))
370 return fmt.Errorf("BUG? http.NewRequest: %s", err)
372 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
373 resp, err := http.DefaultClient.Do(req)
375 return fmt.Errorf("error performing http request: %s", err)
378 if resp.StatusCode != http.StatusCreated {
379 return fmt.Errorf("status %s", resp.Status)
381 diag.debugf("ok, status %s", resp.Status)
382 err = client.RequestAndDecodeContext(ctx, &collection, "GET", "arvados/v1/collections/"+collection.UUID, nil, nil)
384 return fmt.Errorf("get updated collection: %s", err)
386 diag.debugf("ok, pdh %s", collection.PortableDataHash)
390 davurl := cluster.Services.WebDAV.ExternalURL
391 diag.dotest(110, fmt.Sprintf("checking WebDAV ExternalURL wildcard (%s)", davurl), func() error {
392 if davurl.Host == "" {
393 return fmt.Errorf("host missing - content previews will not work")
395 if !strings.HasPrefix(davurl.Host, "*--") && !strings.HasPrefix(davurl.Host, "*.") && !cluster.Collections.TrustAllContent {
396 diag.warnf("WebDAV ExternalURL has no leading wildcard and TrustAllContent==false - content previews will not work")
401 for i, trial := range []struct {
406 {false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + "foo"},
407 {false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + "testfile"},
408 {false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/foo"},
409 {false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/testfile"},
410 {true, http.StatusOK, strings.Replace(davurl.String(), "*", strings.Replace(collection.PortableDataHash, "+", "-", -1), 1) + "testfile"},
411 {true, http.StatusOK, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=" + collection.UUID + "/_/testfile"},
413 diag.dotest(120+i, fmt.Sprintf("downloading from webdav (%s)", trial.fileurl), func() error {
414 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
416 if trial.needcoll && collection.UUID == "" {
417 return fmt.Errorf("skipping, no test collection")
419 req, err := http.NewRequestWithContext(ctx, "GET", trial.fileurl, nil)
423 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
424 resp, err := http.DefaultClient.Do(req)
428 defer resp.Body.Close()
429 body, err := ioutil.ReadAll(resp.Body)
431 return fmt.Errorf("reading response: %s", err)
433 if resp.StatusCode != trial.status {
434 return fmt.Errorf("unexpected response status: %s", resp.Status)
436 if trial.status == http.StatusOK && string(body) != "testfiledata" {
437 return fmt.Errorf("unexpected response content: %q", body)
443 var vm arvados.VirtualMachine
444 diag.dotest(130, "getting list of virtual machines", func() error {
445 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
447 var vmlist arvados.VirtualMachineList
448 err := client.RequestAndDecodeContext(ctx, &vmlist, "GET", "arvados/v1/virtual_machines", nil, arvados.ListOptions{Limit: 999999})
452 if len(vmlist.Items) < 1 {
453 return fmt.Errorf("no VMs found")
459 diag.dotest(140, "getting workbench1 webshell page", func() error {
460 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
463 return fmt.Errorf("skipping, no vm available")
465 webshelltermurl := cluster.Services.Workbench1.ExternalURL.String() + "virtual_machines/" + vm.UUID + "/webshell/testusername"
466 diag.debugf("url %s", webshelltermurl)
467 req, err := http.NewRequestWithContext(ctx, "GET", webshelltermurl, nil)
471 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
472 resp, err := http.DefaultClient.Do(req)
476 defer resp.Body.Close()
477 body, err := ioutil.ReadAll(resp.Body)
479 return fmt.Errorf("reading response: %s", err)
481 if resp.StatusCode != http.StatusOK {
482 return fmt.Errorf("unexpected response status: %s %q", resp.Status, body)
487 diag.dotest(150, "connecting to webshell service", func() error {
488 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
491 return fmt.Errorf("skipping, no vm available")
493 u := cluster.Services.WebShell.ExternalURL
494 webshellurl := u.String() + vm.Hostname + "?"
495 if strings.HasPrefix(u.Host, "*") {
496 u.Host = vm.Hostname + u.Host[1:]
497 webshellurl = u.String() + "?"
499 diag.debugf("url %s", webshellurl)
500 req, err := http.NewRequestWithContext(ctx, "POST", webshellurl, bytes.NewBufferString(url.Values{
503 "session": {"xyzzy"},
504 "rooturl": {webshellurl},
509 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
510 resp, err := http.DefaultClient.Do(req)
514 defer resp.Body.Close()
515 diag.debugf("response status %s", resp.Status)
516 body, err := ioutil.ReadAll(resp.Body)
518 return fmt.Errorf("reading response: %s", err)
520 diag.debugf("response body %q", body)
521 // We don't speak the protocol, so we get a 400 error
522 // from the webshell server even if everything is
523 // OK. Anything else (404, 502, ???) indicates a
525 if resp.StatusCode != http.StatusBadRequest {
526 return fmt.Errorf("unexpected response status: %s, %q", resp.Status, body)
531 diag.dotest(160, "running a container", func() error {
532 if diag.priority < 1 {
533 diag.infof("skipping (use priority > 0 if you want to run a container)")
536 if project.UUID == "" {
537 return fmt.Errorf("skipping, no project to work in")
540 var cr arvados.ContainerRequest
541 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
544 timestamp := time.Now().Format(time.RFC3339)
545 err := client.RequestAndDecodeContext(ctx, &cr, "POST", "arvados/v1/container_requests", nil, map[string]interface{}{"container_request": map[string]interface{}{
546 "owner_uuid": project.UUID,
547 "name": fmt.Sprintf("diagnostics container request %s", timestamp),
548 "container_image": "arvados/jobs",
549 "command": []string{"echo", timestamp},
550 "use_existing": false,
551 "output_path": "/mnt/output",
552 "output_name": fmt.Sprintf("diagnostics output %s", timestamp),
553 "priority": diag.priority,
554 "state": arvados.ContainerRequestStateCommitted,
555 "mounts": map[string]map[string]interface{}{
557 "kind": "collection",
561 "runtime_constraints": arvados.RuntimeConstraints{
564 KeepCacheRAM: 1 << 26,
570 diag.debugf("container request uuid = %s", cr.UUID)
571 diag.debugf("container uuid = %s", cr.ContainerUUID)
573 timeout := 10 * time.Minute
574 diag.infof("container request submitted, waiting up to %v for container to run", arvados.Duration(timeout))
575 ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(timeout))
578 var c arvados.Container
579 for ; cr.State != arvados.ContainerRequestStateFinal; time.Sleep(2 * time.Second) {
580 ctx, cancel := context.WithDeadline(ctx, time.Now().Add(diag.timeout))
583 crStateWas := cr.State
584 err := client.RequestAndDecodeContext(ctx, &cr, "GET", "arvados/v1/container_requests/"+cr.UUID, nil, nil)
588 if cr.State != crStateWas {
589 diag.debugf("container request state = %s", cr.State)
593 err = client.RequestAndDecodeContext(ctx, &c, "GET", "arvados/v1/containers/"+cr.ContainerUUID, nil, nil)
597 if c.State != cStateWas {
598 diag.debugf("container state = %s", c.State)
602 if c.State != arvados.ContainerStateComplete {
603 return fmt.Errorf("container request %s is final but container %s did not complete: container state = %q", cr.UUID, cr.ContainerUUID, c.State)
604 } else if c.ExitCode != 0 {
605 return fmt.Errorf("container exited %d", c.ExitCode)