17609: Improve log text alignment.
[arvados.git] / lib / diagnostics / cmd.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package diagnostics
6
7 import (
8         "bytes"
9         "context"
10         "flag"
11         "fmt"
12         "io"
13         "io/ioutil"
14         "net"
15         "net/http"
16         "net/url"
17         "strings"
18         "time"
19
20         "git.arvados.org/arvados.git/sdk/go/arvados"
21         "git.arvados.org/arvados.git/sdk/go/ctxlog"
22         "github.com/sirupsen/logrus"
23 )
24
25 type Command struct{}
26
27 func (cmd Command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
28         var diag diagnoser
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.DurationVar(&diag.timeout, "timeout", 10*time.Second, "timeout for http requests")
35         err := f.Parse(args)
36         if err == flag.ErrHelp {
37                 return 0
38         } else if err != nil {
39                 fmt.Fprintln(stderr, err)
40                 return 2
41         }
42         diag.logger = ctxlog.New(stdout, "text", diag.logLevel)
43         diag.logger.SetFormatter(&logrus.TextFormatter{DisableTimestamp: true, DisableLevelTruncation: true})
44         diag.runtests()
45         if len(diag.errors) == 0 {
46                 diag.logger.Info("--- no errors ---")
47                 return 0
48         } else {
49                 if diag.logger.Level > logrus.ErrorLevel {
50                         fmt.Fprint(stdout, "\n--- cut here --- error summary ---\n\n")
51                         for _, e := range diag.errors {
52                                 diag.logger.Error(e)
53                         }
54                 }
55                 return 1
56         }
57 }
58
59 type diagnoser struct {
60         stdout        io.Writer
61         stderr        io.Writer
62         logLevel      string
63         projectName   string
64         checkInternal bool
65         checkExternal bool
66         timeout       time.Duration
67         logger        *logrus.Logger
68         errors        []string
69         done          map[int]bool
70 }
71
72 func (diag *diagnoser) debugf(f string, args ...interface{}) {
73         diag.logger.Debugf(f, args...)
74 }
75
76 func (diag *diagnoser) infof(f string, args ...interface{}) {
77         diag.logger.Infof(f, args...)
78 }
79
80 func (diag *diagnoser) warnf(f string, args ...interface{}) {
81         diag.logger.Warnf(f, args...)
82 }
83
84 func (diag *diagnoser) errorf(f string, args ...interface{}) {
85         diag.logger.Errorf(f, args...)
86         diag.errors = append(diag.errors, fmt.Sprintf(f, args...))
87 }
88
89 // Run the given func, logging appropriate messages before and after,
90 // adding timing info, etc.
91 //
92 // The id argument should be unique among tests, and shouldn't change
93 // when other tests are added/removed.
94 func (diag *diagnoser) dotest(id int, title string, fn func() error) {
95         if diag.done == nil {
96                 diag.done = map[int]bool{}
97         } else if diag.done[id] {
98                 diag.errorf("(bug) reused test id %d", id)
99         }
100         diag.done[id] = true
101
102         diag.infof("%4d %s", id, title)
103         t0 := time.Now()
104         err := fn()
105         elapsed := fmt.Sprintf("%.0dms", time.Now().Sub(t0)/time.Millisecond)
106         if err != nil {
107                 diag.errorf("%s (%s): %s", title, elapsed, err)
108         }
109         diag.debugf("%4d %s (%s): ok", id, title, elapsed)
110 }
111
112 func (diag *diagnoser) runtests() {
113         client := arvados.NewClientFromEnv()
114
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")
117                 return
118         }
119
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))
124                 defer cancel()
125                 err := client.RequestAndDecodeContext(ctx, &dd, "GET", ddpath, nil, nil)
126                 if err != nil {
127                         return err
128                 }
129                 diag.debugf("BlobSignatureTTL = %d", dd.BlobSignatureTTL)
130                 return nil
131         })
132
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))
137                 defer cancel()
138                 err := client.RequestAndDecodeContext(ctx, &cluster, "GET", cfgpath, nil, nil)
139                 if err != nil {
140                         return err
141                 }
142                 diag.debugf("Collections.BlobSigning = %v", cluster.Collections.BlobSigning)
143                 return nil
144         })
145
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))
149                 defer cancel()
150                 err := client.RequestAndDecodeContext(ctx, &user, "GET", "arvados/v1/users/current", nil, nil)
151                 if err != nil {
152                         return err
153                 }
154                 diag.debugf("user uuid = %s", user.UUID)
155                 return nil
156         })
157
158         // uncomment to create some spurious errors
159         // cluster.Services.WebDAVDownload.ExternalURL.Host = "0.0.0.0:9"
160
161         // TODO: detect routing errors here, like finding wb2 at the
162         // wb1 address.
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,
170         } {
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))
173                         defer cancel()
174                         u := svc.ExternalURL
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
178                                 // connection.
179                                 u.Scheme = "http" + u.Scheme[2:]
180                         }
181                         if svc == &cluster.Services.WebDAV && strings.HasPrefix(u.Host, "*") {
182                                 u.Host = "d41d8cd98f00b204e9800998ecf8427e-0" + u.Host[1:]
183                         }
184                         req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
185                         if err != nil {
186                                 return err
187                         }
188                         resp, err := http.DefaultClient.Do(req)
189                         if err != nil {
190                                 return err
191                         }
192                         resp.Body.Close()
193                         return nil
194                 })
195         }
196
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(),
201         } {
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))
204                         defer cancel()
205                         req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
206                         if err != nil {
207                                 return err
208                         }
209                         req.Header.Set("Origin", "https://example.com")
210                         resp, err := http.DefaultClient.Do(req)
211                         if err != nil {
212                                 return err
213                         }
214                         if hdr := resp.Header.Get("Access-Control-Allow-Origin"); hdr != "*" {
215                                 return fmt.Errorf("expected \"Access-Control-Allow-Origin: *\", got %q", hdr)
216                         }
217                         return nil
218                 })
219         }
220
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))
224                 defer cancel()
225                 err := client.RequestAndDecodeContext(ctx, &keeplist, "GET", "arvados/v1/keep_services/accessible", nil, arvados.ListOptions{Limit: 999999})
226                 if err != nil {
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")
230                 }
231                 found := map[string]int{}
232                 for _, ks := range keeplist.Items {
233                         found[ks.ServiceType]++
234                 }
235                 isInternal := found["proxy"] == 0 && len(keeplist.Items) > 0
236                 isExternal := found["proxy"] > 0 && found["proxy"] == len(keeplist.Items)
237                 if isExternal {
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\"")
241                 }
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)
244                 }
245                 return nil
246         })
247
248         for i, ks := range keeplist.Items {
249                 u := url.URL{
250                         Scheme: "http",
251                         Host:   net.JoinHostPort(ks.ServiceHost, fmt.Sprintf("%d", ks.ServicePort)),
252                         Path:   "/",
253                 }
254                 if ks.ServiceSSLFlag {
255                         u.Scheme = "https"
256                 }
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))
259                         defer cancel()
260                         req, err := http.NewRequestWithContext(ctx, "PUT", u.String()+"d41d8cd98f00b204e9800998ecf8427e", nil)
261                         if err != nil {
262                                 return err
263                         }
264                         req.Header.Set("Authorization", "Bearer "+client.AuthToken)
265                         resp, err := http.DefaultClient.Do(req)
266                         if err != nil {
267                                 return err
268                         }
269                         defer resp.Body.Close()
270                         body, err := ioutil.ReadAll(resp.Body)
271                         if err != nil {
272                                 return fmt.Errorf("reading response body: %s", err)
273                         }
274                         loc := strings.TrimSpace(string(body))
275                         if !strings.HasPrefix(loc, "d41d8") {
276                                 return fmt.Errorf("unexpected response from write: %q", body)
277                         }
278
279                         req, err = http.NewRequestWithContext(ctx, "GET", u.String()+loc, nil)
280                         if err != nil {
281                                 return err
282                         }
283                         req.Header.Set("Authorization", "Bearer "+client.AuthToken)
284                         resp, err = http.DefaultClient.Do(req)
285                         if err != nil {
286                                 return err
287                         }
288                         defer resp.Body.Close()
289                         body, err = ioutil.ReadAll(resp.Body)
290                         if err != nil {
291                                 return fmt.Errorf("reading response body: %s", err)
292                         }
293                         if len(body) != 0 {
294                                 return fmt.Errorf("unexpected response from read: %q", body)
295                         }
296
297                         return nil
298                 })
299         }
300
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))
304                 defer cancel()
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}},
311                         Limit: 999999})
312                 if err != nil {
313                         return fmt.Errorf("list groups: %s", err)
314                 }
315                 if len(grplist.Items) > 0 {
316                         project = grplist.Items[0]
317                         diag.debugf("using existing project, uuid = %s", project.UUID)
318                         return nil
319                 }
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",
324                 }})
325                 if err != nil {
326                         return fmt.Errorf("create project: %s", err)
327                 }
328                 diag.debugf("created project, uuid = %s", project.UUID)
329                 return nil
330         })
331
332         var collection arvados.Collection
333         diag.dotest(90, "creating temporary collection", func() error {
334                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
335                 defer cancel()
336                 err := client.RequestAndDecodeContext(ctx, &collection, "POST", "arvados/v1/collections", nil, map[string]interface{}{
337                         "ensure_unique_name": true,
338                         "collection": map[string]interface{}{
339                                 "name":     "test collection",
340                                 "trash_at": time.Now().Add(time.Hour)}})
341                 if err != nil {
342                         return err
343                 }
344                 diag.debugf("ok, uuid = %s", collection.UUID)
345                 return nil
346         })
347
348         if collection.UUID != "" {
349                 defer func() {
350                         diag.dotest(9990, "deleting temporary collection", func() error {
351                                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
352                                 defer cancel()
353                                 return client.RequestAndDecodeContext(ctx, nil, "DELETE", "arvados/v1/collections/"+collection.UUID, nil, nil)
354                         })
355                 }()
356         }
357
358         diag.dotest(100, "uploading file via webdav", func() error {
359                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
360                 defer cancel()
361                 if collection.UUID == "" {
362                         return fmt.Errorf("skipping, no test collection")
363                 }
364                 req, err := http.NewRequestWithContext(ctx, "PUT", cluster.Services.WebDAVDownload.ExternalURL.String()+"c="+collection.UUID+"/testfile", bytes.NewBufferString("testfiledata"))
365                 if err != nil {
366                         return fmt.Errorf("BUG? http.NewRequest: %s", err)
367                 }
368                 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
369                 resp, err := http.DefaultClient.Do(req)
370                 if err != nil {
371                         return fmt.Errorf("error performing http request: %s", err)
372                 }
373                 resp.Body.Close()
374                 if resp.StatusCode != http.StatusCreated {
375                         return fmt.Errorf("status %s", resp.Status)
376                 }
377                 diag.debugf("ok, status %s", resp.Status)
378                 err = client.RequestAndDecodeContext(ctx, &collection, "GET", "arvados/v1/collections/"+collection.UUID, nil, nil)
379                 if err != nil {
380                         return fmt.Errorf("get updated collection: %s", err)
381                 }
382                 diag.debugf("ok, pdh %s", collection.PortableDataHash)
383                 return nil
384         })
385
386         davurl := cluster.Services.WebDAV.ExternalURL
387         diag.dotest(110, fmt.Sprintf("checking WebDAV ExternalURL wildcard (%s)", davurl), func() error {
388                 if davurl.Host == "" {
389                         return fmt.Errorf("host missing - content previews will not work")
390                 }
391                 if !strings.HasPrefix(davurl.Host, "*--") && !strings.HasPrefix(davurl.Host, "*.") && !cluster.Collections.TrustAllContent {
392                         diag.warnf("WebDAV ExternalURL has no leading wildcard and TrustAllContent==false - content previews will not work")
393                 }
394                 return nil
395         })
396
397         for i, trial := range []struct {
398                 needcoll bool
399                 status   int
400                 fileurl  string
401         }{
402                 {false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + "foo"},
403                 {false, http.StatusNotFound, strings.Replace(davurl.String(), "*", "d41d8cd98f00b204e9800998ecf8427e-0", 1) + "testfile"},
404                 {false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/foo"},
405                 {false, http.StatusNotFound, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=d41d8cd98f00b204e9800998ecf8427e+0/_/testfile"},
406                 {true, http.StatusOK, strings.Replace(davurl.String(), "*", strings.Replace(collection.PortableDataHash, "+", "-", -1), 1) + "testfile"},
407                 {true, http.StatusOK, cluster.Services.WebDAVDownload.ExternalURL.String() + "c=" + collection.UUID + "/_/testfile"},
408         } {
409                 diag.dotest(120+i, fmt.Sprintf("downloading from webdav (%s)", trial.fileurl), func() error {
410                         ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
411                         defer cancel()
412                         if trial.needcoll && collection.UUID == "" {
413                                 return fmt.Errorf("skipping, no test collection")
414                         }
415                         req, err := http.NewRequestWithContext(ctx, "GET", trial.fileurl, nil)
416                         if err != nil {
417                                 return err
418                         }
419                         req.Header.Set("Authorization", "Bearer "+client.AuthToken)
420                         resp, err := http.DefaultClient.Do(req)
421                         if err != nil {
422                                 return err
423                         }
424                         defer resp.Body.Close()
425                         body, err := ioutil.ReadAll(resp.Body)
426                         if err != nil {
427                                 return fmt.Errorf("reading response: %s", err)
428                         }
429                         if resp.StatusCode != trial.status {
430                                 return fmt.Errorf("unexpected response status: %s", resp.Status)
431                         }
432                         if trial.status == http.StatusOK && string(body) != "testfiledata" {
433                                 return fmt.Errorf("unexpected response content: %q", body)
434                         }
435                         return nil
436                 })
437         }
438
439         var vm arvados.VirtualMachine
440         diag.dotest(130, "getting list of virtual machines", func() error {
441                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
442                 defer cancel()
443                 var vmlist arvados.VirtualMachineList
444                 err := client.RequestAndDecodeContext(ctx, &vmlist, "GET", "arvados/v1/virtual_machines", nil, arvados.ListOptions{Limit: 999999})
445                 if err != nil {
446                         return err
447                 }
448                 if len(vmlist.Items) < 1 {
449                         return fmt.Errorf("no VMs found")
450                 }
451                 vm = vmlist.Items[0]
452                 return nil
453         })
454
455         diag.dotest(140, "getting workbench1 webshell page", func() error {
456                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
457                 defer cancel()
458                 if vm.UUID == "" {
459                         return fmt.Errorf("skipping, no vm available")
460                 }
461                 webshelltermurl := cluster.Services.Workbench1.ExternalURL.String() + "virtual_machines/" + vm.UUID + "/webshell/testusername"
462                 diag.debugf("url %s", webshelltermurl)
463                 req, err := http.NewRequestWithContext(ctx, "GET", webshelltermurl, nil)
464                 if err != nil {
465                         return err
466                 }
467                 req.Header.Set("Authorization", "Bearer "+client.AuthToken)
468                 resp, err := http.DefaultClient.Do(req)
469                 if err != nil {
470                         return err
471                 }
472                 defer resp.Body.Close()
473                 body, err := ioutil.ReadAll(resp.Body)
474                 if err != nil {
475                         return fmt.Errorf("reading response: %s", err)
476                 }
477                 if resp.StatusCode != http.StatusOK {
478                         return fmt.Errorf("unexpected response status: %s %q", resp.Status, body)
479                 }
480                 return nil
481         })
482
483         diag.dotest(150, "connecting to webshell service", func() error {
484                 ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(diag.timeout))
485                 defer cancel()
486                 if vm.UUID == "" {
487                         return fmt.Errorf("skipping, no vm available")
488                 }
489                 u := cluster.Services.WebShell.ExternalURL
490                 webshellurl := u.String() + vm.Hostname + "?"
491                 if strings.HasPrefix(u.Host, "*") {
492                         u.Host = vm.Hostname + u.Host[1:]
493                         webshellurl = u.String() + "?"
494                 }
495                 diag.debugf("url %s", webshellurl)
496                 req, err := http.NewRequestWithContext(ctx, "POST", webshellurl, bytes.NewBufferString(url.Values{
497                         "width":   {"80"},
498                         "height":  {"25"},
499                         "session": {"xyzzy"},
500                         "rooturl": {webshellurl},
501                 }.Encode()))
502                 if err != nil {
503                         return err
504                 }
505                 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
506                 resp, err := http.DefaultClient.Do(req)
507                 if err != nil {
508                         return err
509                 }
510                 defer resp.Body.Close()
511                 diag.debugf("response status %s", resp.Status)
512                 body, err := ioutil.ReadAll(resp.Body)
513                 if err != nil {
514                         return fmt.Errorf("reading response: %s", err)
515                 }
516                 diag.debugf("response body %q", body)
517                 // We don't speak the protocol, so we get a 400 error
518                 // from the webshell server even if everything is
519                 // OK. Anything else (404, 502, ???) indicates a
520                 // problem.
521                 if resp.StatusCode != http.StatusBadRequest {
522                         return fmt.Errorf("unexpected response status: %s, %q", resp.Status, body)
523                 }
524                 return nil
525         })
526 }