1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
25 "git.arvados.org/arvados.git/lib/config"
26 "git.arvados.org/arvados.git/sdk/go/arvados"
27 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
28 "git.arvados.org/arvados.git/sdk/go/arvadostest"
29 "git.arvados.org/arvados.git/sdk/go/ctxlog"
30 "git.arvados.org/arvados.git/sdk/go/httpserver"
31 "git.arvados.org/arvados.git/sdk/go/keepclient"
32 "github.com/prometheus/client_golang/prometheus"
33 check "gopkg.in/check.v1"
36 var testAPIHost = os.Getenv("ARVADOS_API_HOST")
38 var _ = check.Suite(&IntegrationSuite{})
40 // IntegrationSuite tests need an API server and a keep-web server
41 type IntegrationSuite struct {
42 testServer *httptest.Server
46 func (s *IntegrationSuite) TestNoToken(c *check.C) {
47 for _, token := range []string{
51 hdr, body, _ := s.runCurl(c, token, "collections.example.com", "/collections/"+arvadostest.FooCollection+"/foo")
52 c.Check(hdr, check.Matches, `(?s)HTTP/1.1 404 Not Found\r\n.*`)
53 c.Check(strings.TrimSpace(body), check.Equals, notFoundMessage)
56 hdr, body, _ = s.runCurl(c, token, "collections.example.com", "/collections/download/"+arvadostest.FooCollection+"/"+token+"/foo")
57 c.Check(hdr, check.Matches, `(?s)HTTP/1.1 404 Not Found\r\n.*`)
58 c.Check(strings.TrimSpace(body), check.Equals, notFoundMessage)
61 hdr, body, _ = s.runCurl(c, token, "collections.example.com", "/bad-route")
62 c.Check(hdr, check.Matches, `(?s)HTTP/1.1 404 Not Found\r\n.*`)
63 c.Check(strings.TrimSpace(body), check.Equals, notFoundMessage)
67 // TODO: Move most cases to functional tests -- at least use Go's own
68 // http client instead of forking curl. Just leave enough of an
69 // integration test to assure that the documented way of invoking curl
70 // really works against the server.
71 func (s *IntegrationSuite) Test404(c *check.C) {
72 for _, uri := range []string{
73 // Routing errors (always 404 regardless of what's stored in Keep)
78 // Implicit/generated index is not implemented yet;
79 // until then, return 404.
80 "/collections/" + arvadostest.FooCollection,
81 "/collections/" + arvadostest.FooCollection + "/",
82 "/collections/" + arvadostest.FooBarDirCollection + "/dir1",
83 "/collections/" + arvadostest.FooBarDirCollection + "/dir1/",
84 // Non-existent file in collection
85 "/collections/" + arvadostest.FooCollection + "/theperthcountyconspiracy",
86 "/collections/download/" + arvadostest.FooCollection + "/" + arvadostest.ActiveToken + "/theperthcountyconspiracy",
87 // Non-existent collection
88 "/collections/" + arvadostest.NonexistentCollection,
89 "/collections/" + arvadostest.NonexistentCollection + "/",
90 "/collections/" + arvadostest.NonexistentCollection + "/theperthcountyconspiracy",
91 "/collections/download/" + arvadostest.NonexistentCollection + "/" + arvadostest.ActiveToken + "/theperthcountyconspiracy",
93 hdr, body, _ := s.runCurl(c, arvadostest.ActiveToken, "collections.example.com", uri)
94 c.Check(hdr, check.Matches, "(?s)HTTP/1.1 404 Not Found\r\n.*")
96 c.Check(strings.TrimSpace(body), check.Equals, notFoundMessage)
101 func (s *IntegrationSuite) Test1GBFile(c *check.C) {
103 c.Skip("skipping 1GB integration test in short mode")
105 s.test100BlockFile(c, 10000000)
108 func (s *IntegrationSuite) Test100BlockFile(c *check.C) {
111 s.test100BlockFile(c, 30000)
114 s.test100BlockFile(c, 3000000)
118 func (s *IntegrationSuite) test100BlockFile(c *check.C, blocksize int) {
119 testdata := make([]byte, blocksize)
120 for i := 0; i < blocksize; i++ {
121 testdata[i] = byte(' ')
123 arv, err := arvadosclient.MakeArvadosClient()
124 c.Assert(err, check.Equals, nil)
125 arv.ApiToken = arvadostest.ActiveToken
126 kc, err := keepclient.MakeKeepClient(arv)
127 c.Assert(err, check.Equals, nil)
128 loc, _, err := kc.PutB(testdata[:])
129 c.Assert(err, check.Equals, nil)
131 for i := 0; i < 100; i++ {
132 mtext = mtext + " " + loc
134 mtext = mtext + fmt.Sprintf(" 0:%d00:testdata.bin\n", blocksize)
135 coll := map[string]interface{}{}
136 err = arv.Create("collections",
137 map[string]interface{}{
138 "collection": map[string]interface{}{
139 "name": fmt.Sprintf("testdata blocksize=%d", blocksize),
140 "manifest_text": mtext,
143 c.Assert(err, check.Equals, nil)
144 uuid := coll["uuid"].(string)
146 hdr, body, size := s.runCurl(c, arv.ApiToken, uuid+".collections.example.com", "/testdata.bin")
147 c.Check(hdr, check.Matches, `(?s)HTTP/1.1 200 OK\r\n.*`)
148 c.Check(hdr, check.Matches, `(?si).*Content-length: `+fmt.Sprintf("%d00", blocksize)+`\r\n.*`)
149 c.Check([]byte(body)[:1234], check.DeepEquals, testdata[:1234])
150 c.Check(size, check.Equals, int64(blocksize)*100)
153 type curlCase struct {
160 func (s *IntegrationSuite) Test200(c *check.C) {
161 s.handler.Cluster.Users.AnonymousUserToken = arvadostest.AnonymousToken
162 for _, spec := range []curlCase{
165 auth: arvadostest.ActiveToken,
166 host: arvadostest.FooCollection + "--collections.example.com",
168 dataMD5: "acbd18db4cc2f85cedef654fccc4a4d8",
171 auth: arvadostest.ActiveToken,
172 host: arvadostest.FooCollection + ".collections.example.com",
174 dataMD5: "acbd18db4cc2f85cedef654fccc4a4d8",
177 host: strings.Replace(arvadostest.FooCollectionPDH, "+", "-", 1) + ".collections.example.com",
178 path: "/t=" + arvadostest.ActiveToken + "/foo",
179 dataMD5: "acbd18db4cc2f85cedef654fccc4a4d8",
182 path: "/c=" + arvadostest.FooCollectionPDH + "/t=" + arvadostest.ActiveToken + "/foo",
183 dataMD5: "acbd18db4cc2f85cedef654fccc4a4d8",
186 path: "/c=" + strings.Replace(arvadostest.FooCollectionPDH, "+", "-", 1) + "/t=" + arvadostest.ActiveToken + "/_/foo",
187 dataMD5: "acbd18db4cc2f85cedef654fccc4a4d8",
190 path: "/collections/download/" + arvadostest.FooCollection + "/" + arvadostest.ActiveToken + "/foo",
191 dataMD5: "acbd18db4cc2f85cedef654fccc4a4d8",
194 auth: "tokensobogus",
195 path: "/collections/download/" + arvadostest.FooCollection + "/" + arvadostest.ActiveToken + "/foo",
196 dataMD5: "acbd18db4cc2f85cedef654fccc4a4d8",
199 auth: arvadostest.ActiveToken,
200 path: "/collections/download/" + arvadostest.FooCollection + "/" + arvadostest.ActiveToken + "/foo",
201 dataMD5: "acbd18db4cc2f85cedef654fccc4a4d8",
204 auth: arvadostest.AnonymousToken,
205 path: "/collections/download/" + arvadostest.FooCollection + "/" + arvadostest.ActiveToken + "/foo",
206 dataMD5: "acbd18db4cc2f85cedef654fccc4a4d8",
209 // Anonymously accessible data
211 path: "/c=" + arvadostest.HelloWorldCollection + "/Hello%20world.txt",
212 dataMD5: "f0ef7081e1539ac00ef5b761b4fb01b3",
215 host: arvadostest.HelloWorldCollection + ".collections.example.com",
216 path: "/Hello%20world.txt",
217 dataMD5: "f0ef7081e1539ac00ef5b761b4fb01b3",
220 host: arvadostest.HelloWorldCollection + ".collections.example.com",
221 path: "/_/Hello%20world.txt",
222 dataMD5: "f0ef7081e1539ac00ef5b761b4fb01b3",
225 path: "/collections/" + arvadostest.HelloWorldCollection + "/Hello%20world.txt",
226 dataMD5: "f0ef7081e1539ac00ef5b761b4fb01b3",
229 auth: arvadostest.ActiveToken,
230 path: "/collections/" + arvadostest.HelloWorldCollection + "/Hello%20world.txt",
231 dataMD5: "f0ef7081e1539ac00ef5b761b4fb01b3",
234 auth: arvadostest.SpectatorToken,
235 path: "/collections/" + arvadostest.HelloWorldCollection + "/Hello%20world.txt",
236 dataMD5: "f0ef7081e1539ac00ef5b761b4fb01b3",
239 auth: arvadostest.SpectatorToken,
240 host: arvadostest.HelloWorldCollection + "--collections.example.com",
241 path: "/Hello%20world.txt",
242 dataMD5: "f0ef7081e1539ac00ef5b761b4fb01b3",
245 auth: arvadostest.SpectatorToken,
246 path: "/collections/download/" + arvadostest.HelloWorldCollection + "/" + arvadostest.SpectatorToken + "/Hello%20world.txt",
247 dataMD5: "f0ef7081e1539ac00ef5b761b4fb01b3",
252 host = "collections.example.com"
254 hdr, body, _ := s.runCurl(c, spec.auth, host, spec.path)
255 c.Check(hdr, check.Matches, `(?s)HTTP/1.1 200 OK\r\n.*`)
256 if strings.HasSuffix(spec.path, ".txt") {
257 c.Check(hdr, check.Matches, `(?s).*\r\nContent-Type: text/plain.*`)
258 // TODO: Check some types that aren't
259 // automatically detected by Go's http server
260 // by sniffing the content.
262 c.Check(fmt.Sprintf("%x", md5.Sum([]byte(body))), check.Equals, spec.dataMD5)
266 // Return header block and body.
267 func (s *IntegrationSuite) runCurl(c *check.C, auth, host, uri string, args ...string) (hdr, bodyPart string, bodySize int64) {
268 curlArgs := []string{"--silent", "--show-error", "--include"}
269 testHost, testPort, _ := net.SplitHostPort(s.testServer.URL[7:])
270 curlArgs = append(curlArgs, "--resolve", host+":"+testPort+":"+testHost)
271 if strings.Contains(auth, " ") {
272 // caller supplied entire Authorization header value
273 curlArgs = append(curlArgs, "-H", "Authorization: "+auth)
274 } else if auth != "" {
275 // caller supplied Arvados token
276 curlArgs = append(curlArgs, "-H", "Authorization: Bearer "+auth)
278 curlArgs = append(curlArgs, args...)
279 curlArgs = append(curlArgs, "http://"+host+":"+testPort+uri)
280 c.Log(fmt.Sprintf("curlArgs == %#v", curlArgs))
281 cmd := exec.Command("curl", curlArgs...)
282 stdout, err := cmd.StdoutPipe()
283 c.Assert(err, check.IsNil)
284 cmd.Stderr = os.Stderr
286 c.Assert(err, check.IsNil)
287 buf := make([]byte, 2<<27)
288 n, err := io.ReadFull(stdout, buf)
289 // Discard (but measure size of) anything past 128 MiB.
291 if err == io.ErrUnexpectedEOF {
294 c.Assert(err, check.IsNil)
295 discarded, err = io.Copy(ioutil.Discard, stdout)
296 c.Assert(err, check.IsNil)
299 // Without "-f", curl exits 0 as long as it gets a valid HTTP
300 // response from the server, even if the response status
301 // indicates that the request failed. In our test suite, we
302 // always expect a valid HTTP response, and we parse the
303 // headers ourselves. If curl exits non-zero, our testing
304 // environment is broken.
305 c.Assert(err, check.Equals, nil)
306 hdrsAndBody := strings.SplitN(string(buf), "\r\n\r\n", 2)
307 c.Assert(len(hdrsAndBody), check.Equals, 2)
309 bodyPart = hdrsAndBody[1]
310 bodySize = int64(len(bodyPart)) + discarded
314 // Run a full-featured server, including the metrics/health routes
315 // that are added by service.Command.
316 func (s *IntegrationSuite) runServer(c *check.C) (cluster arvados.Cluster, srvaddr string, logbuf *bytes.Buffer) {
317 logbuf = &bytes.Buffer{}
318 cluster = *s.handler.Cluster
319 cluster.Services.WebDAV.InternalURLs = map[arvados.URL]arvados.ServiceInstance{{Scheme: "http", Host: "0.0.0.0:0"}: {}}
320 cluster.Services.WebDAVDownload.InternalURLs = map[arvados.URL]arvados.ServiceInstance{{Scheme: "http", Host: "0.0.0.0:0"}: {}}
322 var configjson bytes.Buffer
323 json.NewEncoder(&configjson).Encode(arvados.Config{Clusters: map[string]arvados.Cluster{"zzzzz": cluster}})
324 go Command.RunCommand("keep-web", []string{"-config=-"}, &configjson, os.Stderr, io.MultiWriter(os.Stderr, logbuf))
325 for deadline := time.Now().Add(time.Second); deadline.After(time.Now()); time.Sleep(time.Second / 100) {
326 if m := regexp.MustCompile(`"Listen":"(.*?)"`).FindStringSubmatch(logbuf.String()); m != nil {
327 srvaddr = "http://" + m[1]
337 // Ensure uploads can take longer than API.RequestTimeout.
339 // Currently, this works only by accident: service.Command cancels the
340 // request context as usual (there is no exemption), but
341 // webdav.Handler doesn't notice if the request context is cancelled
342 // while waiting to send or receive file data.
343 func (s *IntegrationSuite) TestRequestTimeoutExemption(c *check.C) {
344 s.handler.Cluster.API.RequestTimeout = arvados.Duration(time.Second / 2)
345 _, srvaddr, _ := s.runServer(c)
347 var coll arvados.Collection
348 arv, err := arvadosclient.MakeArvadosClient()
349 c.Assert(err, check.IsNil)
350 arv.ApiToken = arvadostest.ActiveTokenV2
351 err = arv.Create("collections", map[string]interface{}{"ensure_unique_name": true}, &coll)
352 c.Assert(err, check.IsNil)
356 time.Sleep(time.Second)
357 pw.Write(make([]byte, 10000000))
360 req, _ := http.NewRequest("PUT", srvaddr+"/testfile", pr)
361 req.Host = coll.UUID + ".example"
362 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveTokenV2)
363 resp, err := http.DefaultClient.Do(req)
364 c.Assert(err, check.IsNil)
365 c.Check(resp.StatusCode, check.Equals, http.StatusCreated)
367 req, _ = http.NewRequest("GET", srvaddr+"/testfile", nil)
368 req.Host = coll.UUID + ".example"
369 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveTokenV2)
370 resp, err = http.DefaultClient.Do(req)
371 c.Assert(err, check.IsNil)
372 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
373 time.Sleep(time.Second)
374 body, err := ioutil.ReadAll(resp.Body)
375 c.Check(err, check.IsNil)
376 c.Check(len(body), check.Equals, 10000000)
379 func (s *IntegrationSuite) TestHealthCheckPing(c *check.C) {
380 cluster, srvaddr, _ := s.runServer(c)
381 req, _ := http.NewRequest("GET", srvaddr+"/_health/ping", nil)
382 req.Header.Set("Authorization", "Bearer "+cluster.ManagementToken)
383 resp, err := http.DefaultClient.Do(req)
384 c.Assert(err, check.IsNil)
385 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
386 body, _ := ioutil.ReadAll(resp.Body)
387 c.Check(string(body), check.Matches, `{"health":"OK"}\n`)
390 func (s *IntegrationSuite) TestMetrics(c *check.C) {
391 cluster, srvaddr, _ := s.runServer(c)
393 req, _ := http.NewRequest("GET", srvaddr+"/notfound", nil)
394 req.Host = cluster.Services.WebDAVDownload.ExternalURL.Host
395 _, err := http.DefaultClient.Do(req)
396 c.Assert(err, check.IsNil)
397 req, _ = http.NewRequest("GET", srvaddr+"/by_id/", nil)
398 req.Host = cluster.Services.WebDAVDownload.ExternalURL.Host
399 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
400 resp, err := http.DefaultClient.Do(req)
401 c.Assert(err, check.IsNil)
402 c.Assert(resp.StatusCode, check.Equals, http.StatusOK)
403 for i := 0; i < 2; i++ {
404 req, _ = http.NewRequest("GET", srvaddr+"/foo", nil)
405 req.Host = arvadostest.FooCollection + ".example.com"
406 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
407 resp, err = http.DefaultClient.Do(req)
408 c.Assert(err, check.IsNil)
409 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
410 buf, _ := ioutil.ReadAll(resp.Body)
411 c.Check(buf, check.DeepEquals, []byte("foo"))
415 time.Sleep(metricsUpdateInterval * 2)
417 req, _ = http.NewRequest("GET", srvaddr+"/metrics.json", nil)
418 req.Host = cluster.Services.WebDAVDownload.ExternalURL.Host
419 resp, err = http.DefaultClient.Do(req)
420 c.Assert(err, check.IsNil)
421 c.Check(resp.StatusCode, check.Equals, http.StatusUnauthorized)
423 req, _ = http.NewRequest("GET", srvaddr+"/metrics.json", nil)
424 req.Host = cluster.Services.WebDAVDownload.ExternalURL.Host
425 req.Header.Set("Authorization", "Bearer badtoken")
426 resp, err = http.DefaultClient.Do(req)
427 c.Assert(err, check.IsNil)
428 c.Check(resp.StatusCode, check.Equals, http.StatusForbidden)
430 req, _ = http.NewRequest("GET", srvaddr+"/metrics.json", nil)
431 req.Host = cluster.Services.WebDAVDownload.ExternalURL.Host
432 req.Header.Set("Authorization", "Bearer "+arvadostest.ManagementToken)
433 resp, err = http.DefaultClient.Do(req)
434 c.Assert(err, check.IsNil)
435 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
436 type summary struct {
440 type counter struct {
460 json.NewDecoder(resp.Body).Decode(&ents)
461 summaries := map[string]summary{}
462 gauges := map[string]gauge{}
463 counters := map[string]counter{}
464 for _, e := range ents {
465 for _, m := range e.Metric {
466 labels := map[string]string{}
467 for _, lbl := range m.Label {
468 labels[lbl.Name] = lbl.Value
470 summaries[e.Name+"/"+labels["method"]+"/"+labels["code"]] = m.Summary
471 counters[e.Name+"/"+labels["method"]+"/"+labels["code"]] = m.Counter
472 gauges[e.Name+"/"+labels["method"]+"/"+labels["code"]] = m.Gauge
475 c.Check(summaries["request_duration_seconds/get/200"].SampleSum, check.Not(check.Equals), 0)
476 c.Check(summaries["request_duration_seconds/get/200"].SampleCount, check.Equals, "3")
477 c.Check(summaries["request_duration_seconds/get/404"].SampleCount, check.Equals, "1")
478 c.Check(summaries["time_to_status_seconds/get/404"].SampleCount, check.Equals, "1")
479 c.Check(gauges["arvados_keepweb_sessions_cached_session_bytes//"].Value, check.Equals, float64(469))
481 // If the Host header indicates a collection, /metrics.json
482 // refers to a file in the collection -- the metrics handler
483 // must not intercept that route. Ditto health check paths.
484 for _, path := range []string{"/metrics.json", "/_health/ping"} {
485 c.Logf("path: %q", path)
486 req, _ = http.NewRequest("GET", srvaddr+path, nil)
487 req.Host = strings.Replace(arvadostest.FooCollectionPDH, "+", "-", -1) + ".example.com"
488 req.Header.Set("Authorization", "Bearer "+arvadostest.ActiveToken)
489 resp, err = http.DefaultClient.Do(req)
490 c.Assert(err, check.IsNil)
491 c.Check(resp.StatusCode, check.Equals, http.StatusNotFound)
495 func (s *IntegrationSuite) SetUpSuite(c *check.C) {
496 arvadostest.ResetDB(c)
497 arvadostest.StartKeep(2, true)
499 arv, err := arvadosclient.MakeArvadosClient()
500 c.Assert(err, check.Equals, nil)
501 arv.ApiToken = arvadostest.ActiveToken
502 kc, err := keepclient.MakeKeepClient(arv)
503 c.Assert(err, check.Equals, nil)
504 kc.PutB([]byte("Hello world\n"))
505 kc.PutB([]byte("foo"))
506 kc.PutB([]byte("foobar"))
507 kc.PutB([]byte("waz"))
510 func (s *IntegrationSuite) TearDownSuite(c *check.C) {
511 arvadostest.StopKeep(2)
514 func (s *IntegrationSuite) SetUpTest(c *check.C) {
515 arvadostest.ResetEnv()
516 logger := ctxlog.TestLogger(c)
517 ldr := config.NewLoader(&bytes.Buffer{}, logger)
518 cfg, err := ldr.Load()
519 c.Assert(err, check.IsNil)
520 cluster, err := cfg.GetCluster("")
521 c.Assert(err, check.IsNil)
523 ctx := ctxlog.Context(context.Background(), logger)
525 s.handler = newHandlerOrErrorHandler(ctx, cluster, cluster.SystemRootToken, prometheus.NewRegistry()).(*handler)
526 s.testServer = httptest.NewUnstartedServer(
527 httpserver.AddRequestIDs(
528 httpserver.LogRequests(
530 s.testServer.Config.BaseContext = func(net.Listener) context.Context { return ctx }
533 cluster.Services.WebDAV.InternalURLs = map[arvados.URL]arvados.ServiceInstance{{Host: s.testServer.URL[7:]}: {}}
534 cluster.Services.WebDAVDownload.InternalURLs = map[arvados.URL]arvados.ServiceInstance{{Host: s.testServer.URL[7:]}: {}}
537 func (s *IntegrationSuite) TearDownTest(c *check.C) {
538 if s.testServer != nil {
543 // Gocheck boilerplate
544 func Test(t *testing.T) {