21285: Use separate request limit/queue for gateway tunnel requests.
[arvados.git] / lib / service / cmd_test.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 // package service provides a cmd.Handler that brings up a system service.
6 package service
7
8 import (
9         "bytes"
10         "context"
11         "crypto/tls"
12         "encoding/json"
13         "fmt"
14         "io/ioutil"
15         "net"
16         "net/http"
17         "net/url"
18         "os"
19         "strings"
20         "sync"
21         "sync/atomic"
22         "testing"
23         "time"
24
25         "git.arvados.org/arvados.git/sdk/go/arvados"
26         "git.arvados.org/arvados.git/sdk/go/ctxlog"
27         "github.com/prometheus/client_golang/prometheus"
28         check "gopkg.in/check.v1"
29 )
30
31 func Test(t *testing.T) {
32         check.TestingT(t)
33 }
34
35 var _ = check.Suite(&Suite{})
36
37 type Suite struct{}
38 type key int
39
40 const (
41         contextKey key = iota
42 )
43
44 func unusedPort(c *check.C) string {
45         // Find an available port on the testing host, so the test
46         // cases don't get confused by "already in use" errors.
47         listener, err := net.Listen("tcp", ":")
48         c.Assert(err, check.IsNil)
49         listener.Close()
50         _, port, err := net.SplitHostPort(listener.Addr().String())
51         c.Assert(err, check.IsNil)
52         return port
53 }
54
55 func (*Suite) TestGetListenAddress(c *check.C) {
56         port := unusedPort(c)
57         defer os.Unsetenv("ARVADOS_SERVICE_INTERNAL_URL")
58         for idx, trial := range []struct {
59                 // internalURL => listenURL, both with trailing "/"
60                 // because config loader always adds it
61                 internalURLs     map[string]string
62                 envVar           string
63                 expectErrorMatch string
64                 expectLogsMatch  string
65                 expectListen     string
66                 expectInternal   string
67         }{
68                 {
69                         internalURLs:   map[string]string{"http://localhost:" + port + "/": ""},
70                         expectListen:   "http://localhost:" + port + "/",
71                         expectInternal: "http://localhost:" + port + "/",
72                 },
73                 { // implicit port 80 in InternalURLs
74                         internalURLs:     map[string]string{"http://localhost/": ""},
75                         expectErrorMatch: `.*:80: bind: permission denied`,
76                 },
77                 { // implicit port 443 in InternalURLs
78                         internalURLs:   map[string]string{"https://host.example/": "http://localhost:" + port + "/"},
79                         expectListen:   "http://localhost:" + port + "/",
80                         expectInternal: "https://host.example/",
81                 },
82                 { // implicit port 443 in ListenURL
83                         internalURLs:     map[string]string{"wss://host.example/": "wss://localhost/"},
84                         expectErrorMatch: `.*:443: bind: permission denied`,
85                 },
86                 {
87                         internalURLs:   map[string]string{"https://hostname.example/": "http://localhost:8000/"},
88                         expectListen:   "http://localhost:8000/",
89                         expectInternal: "https://hostname.example/",
90                 },
91                 {
92                         internalURLs: map[string]string{
93                                 "https://hostname1.example/": "http://localhost:12435/",
94                                 "https://hostname2.example/": "http://localhost:" + port + "/",
95                         },
96                         envVar:         "https://hostname2.example", // note this works despite missing trailing "/"
97                         expectListen:   "http://localhost:" + port + "/",
98                         expectInternal: "https://hostname2.example/",
99                 },
100                 { // cannot listen on any of the ListenURLs
101                         internalURLs: map[string]string{
102                                 "https://hostname1.example/": "http://1.2.3.4:" + port + "/",
103                                 "https://hostname2.example/": "http://1.2.3.4:" + port + "/",
104                         },
105                         expectErrorMatch: "configuration does not enable the \"arvados-controller\" service on this host",
106                 },
107                 { // cannot listen on any of the (implied) ListenURLs
108                         internalURLs: map[string]string{
109                                 "https://1.2.3.4/": "",
110                                 "https://1.2.3.5/": "",
111                         },
112                         expectErrorMatch: "configuration does not enable the \"arvados-controller\" service on this host",
113                 },
114                 { // impossible port number
115                         internalURLs: map[string]string{
116                                 "https://host.example/": "http://0.0.0.0:1234567",
117                         },
118                         expectErrorMatch: `.*:1234567: listen tcp: address 1234567: invalid port`,
119                 },
120                 {
121                         // env var URL not mentioned in config = obey env var, with warning
122                         internalURLs:    map[string]string{"https://hostname1.example/": "http://localhost:8000/"},
123                         envVar:          "https://hostname2.example",
124                         expectListen:    "https://hostname2.example/",
125                         expectInternal:  "https://hostname2.example/",
126                         expectLogsMatch: `.*\Qpossible configuration error: listening on https://hostname2.example/ (from $ARVADOS_SERVICE_INTERNAL_URL) even though configuration does not have a matching InternalURLs entry\E.*\n`,
127                 },
128                 {
129                         // env var + empty config = obey env var, with warning
130                         envVar:          "https://hostname.example",
131                         expectListen:    "https://hostname.example/",
132                         expectInternal:  "https://hostname.example/",
133                         expectLogsMatch: `.*\Qpossible configuration error: listening on https://hostname.example/ (from $ARVADOS_SERVICE_INTERNAL_URL) even though configuration does not have a matching InternalURLs entry\E.*\n`,
134                 },
135         } {
136                 c.Logf("trial %d %+v", idx, trial)
137                 os.Setenv("ARVADOS_SERVICE_INTERNAL_URL", trial.envVar)
138                 var logbuf bytes.Buffer
139                 log := ctxlog.New(&logbuf, "text", "info")
140                 services := arvados.Services{Controller: arvados.Service{InternalURLs: map[arvados.URL]arvados.ServiceInstance{}}}
141                 for k, v := range trial.internalURLs {
142                         u, err := url.Parse(k)
143                         c.Assert(err, check.IsNil)
144                         si := arvados.ServiceInstance{}
145                         if v != "" {
146                                 u, err := url.Parse(v)
147                                 c.Assert(err, check.IsNil)
148                                 si.ListenURL = arvados.URL(*u)
149                         }
150                         services.Controller.InternalURLs[arvados.URL(*u)] = si
151                 }
152                 listenURL, internalURL, err := getListenAddr(services, "arvados-controller", log)
153                 if trial.expectLogsMatch != "" {
154                         c.Check(logbuf.String(), check.Matches, trial.expectLogsMatch)
155                 }
156                 if trial.expectErrorMatch != "" {
157                         c.Check(err, check.ErrorMatches, trial.expectErrorMatch)
158                         continue
159                 }
160                 if !c.Check(err, check.IsNil) {
161                         continue
162                 }
163                 c.Check(listenURL.String(), check.Equals, trial.expectListen)
164                 c.Check(internalURL.String(), check.Equals, trial.expectInternal)
165         }
166 }
167
168 func (*Suite) TestCommand(c *check.C) {
169         cf, err := ioutil.TempFile("", "cmd_test.")
170         c.Assert(err, check.IsNil)
171         defer os.Remove(cf.Name())
172         defer cf.Close()
173         fmt.Fprintf(cf, "Clusters:\n zzzzz:\n  SystemRootToken: abcde\n  NodeProfiles: {\"*\": {\"arvados-controller\": {Listen: \":1234\"}}}")
174
175         healthCheck := make(chan bool, 1)
176         ctx, cancel := context.WithCancel(context.Background())
177         defer cancel()
178
179         cmd := Command(arvados.ServiceNameController, func(ctx context.Context, _ *arvados.Cluster, token string, reg *prometheus.Registry) Handler {
180                 c.Check(ctx.Value(contextKey), check.Equals, "bar")
181                 c.Check(token, check.Equals, "abcde")
182                 return &testHandler{ctx: ctx, healthCheck: healthCheck}
183         })
184         cmd.(*command).ctx = context.WithValue(ctx, contextKey, "bar")
185
186         done := make(chan bool)
187         var stdin, stdout, stderr bytes.Buffer
188
189         go func() {
190                 cmd.RunCommand("arvados-controller", []string{"-config", cf.Name()}, &stdin, &stdout, &stderr)
191                 close(done)
192         }()
193         select {
194         case <-healthCheck:
195         case <-done:
196                 c.Error("command exited without health check")
197         }
198         cancel()
199         c.Check(stdout.String(), check.Equals, "")
200         c.Check(stderr.String(), check.Matches, `(?ms).*"msg":"CheckHealth called".*`)
201 }
202
203 func (s *Suite) TestRequestLimitsAndDumpRequests_Keepweb(c *check.C) {
204         s.testRequestLimitAndDumpRequests(c, arvados.ServiceNameKeepweb, "MaxConcurrentRequests")
205 }
206
207 func (s *Suite) TestRequestLimitsAndDumpRequests_Controller(c *check.C) {
208         s.testRequestLimitAndDumpRequests(c, arvados.ServiceNameController, "MaxConcurrentRailsRequests")
209 }
210
211 func (*Suite) testRequestLimitAndDumpRequests(c *check.C, serviceName arvados.ServiceName, maxReqsConfigKey string) {
212         defer func(orig time.Duration) { requestQueueDumpCheckInterval = orig }(requestQueueDumpCheckInterval)
213         requestQueueDumpCheckInterval = time.Second / 10
214
215         port := unusedPort(c)
216         tmpdir := c.MkDir()
217         cf, err := ioutil.TempFile(tmpdir, "cmd_test.")
218         c.Assert(err, check.IsNil)
219         defer os.Remove(cf.Name())
220         defer cf.Close()
221
222         max := 24
223         maxTunnels := 30
224         fmt.Fprintf(cf, `
225 Clusters:
226  zzzzz:
227   SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
228   ManagementToken: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
229   API:
230    `+maxReqsConfigKey+`: %d
231    MaxQueuedRequests: 1
232    MaxGatewayTunnels: %d
233   SystemLogs: {RequestQueueDumpDirectory: %q}
234   Services:
235    Controller:
236     ExternalURL: "http://localhost:`+port+`"
237     InternalURLs: {"http://localhost:`+port+`": {}}
238    WebDAV:
239     ExternalURL: "http://localhost:`+port+`"
240     InternalURLs: {"http://localhost:`+port+`": {}}
241 `, max, maxTunnels, tmpdir)
242         cf.Close()
243
244         started := make(chan bool, max+1)
245         hold := make(chan bool)
246         handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
247                 if strings.HasPrefix(r.URL.Path, "/arvados/v1/connect") {
248                         <-hold
249                 } else {
250                         started <- true
251                         <-hold
252                 }
253         })
254         healthCheck := make(chan bool, 1)
255         ctx, cancel := context.WithCancel(context.Background())
256         defer cancel()
257
258         cmd := Command(serviceName, func(ctx context.Context, _ *arvados.Cluster, token string, reg *prometheus.Registry) Handler {
259                 return &testHandler{ctx: ctx, handler: handler, healthCheck: healthCheck}
260         })
261         cmd.(*command).ctx = context.WithValue(ctx, contextKey, "bar")
262
263         exited := make(chan bool)
264         var stdin, stdout, stderr bytes.Buffer
265
266         go func() {
267                 cmd.RunCommand(string(serviceName), []string{"-config", cf.Name()}, &stdin, &stdout, &stderr)
268                 close(exited)
269         }()
270         select {
271         case <-healthCheck:
272         case <-exited:
273                 c.Logf("%s", stderr.String())
274                 c.Error("command exited without health check")
275         }
276         client := http.Client{}
277         deadline := time.Now().Add(time.Second * 2)
278         var activeReqs sync.WaitGroup
279
280         // Start some API reqs
281         var apiResp200, apiResp503 int64
282         for i := 0; i < max+1; i++ {
283                 activeReqs.Add(1)
284                 go func() {
285                         defer activeReqs.Done()
286                         resp, err := client.Get("http://localhost:" + port + "/testpath")
287                         for err != nil && strings.Contains(err.Error(), "dial tcp") && deadline.After(time.Now()) {
288                                 time.Sleep(time.Second / 100)
289                                 resp, err = client.Get("http://localhost:" + port + "/testpath")
290                         }
291                         if c.Check(err, check.IsNil) {
292                                 if resp.StatusCode == http.StatusOK {
293                                         atomic.AddInt64(&apiResp200, 1)
294                                 } else if resp.StatusCode == http.StatusServiceUnavailable {
295                                         atomic.AddInt64(&apiResp503, 1)
296                                 }
297                         }
298                 }()
299         }
300
301         // Start some gateway tunnel reqs that don't count toward our
302         // API req limit
303         extraTunnelReqs := 20
304         var tunnelResp200, tunnelResp503 int64
305         for i := 0; i < maxTunnels+extraTunnelReqs; i++ {
306                 activeReqs.Add(1)
307                 go func() {
308                         defer activeReqs.Done()
309                         resp, err := client.Get("http://localhost:" + port + "/arvados/v1/connect/...")
310                         for err != nil && strings.Contains(err.Error(), "dial tcp") && deadline.After(time.Now()) {
311                                 time.Sleep(time.Second / 100)
312                                 resp, err = client.Get("http://localhost:" + port + "/arvados/v1/connect/...")
313                         }
314                         if c.Check(err, check.IsNil) {
315                                 if resp.StatusCode == http.StatusOK {
316                                         atomic.AddInt64(&tunnelResp200, 1)
317                                 } else if resp.StatusCode == http.StatusServiceUnavailable {
318                                         atomic.AddInt64(&tunnelResp503, 1)
319                                 } else {
320                                         c.Errorf("tunnel response code %d", resp.StatusCode)
321                                 }
322                         }
323                 }()
324         }
325         for i := 0; i < max; i++ {
326                 select {
327                 case <-started:
328                 case <-time.After(time.Second):
329                         c.Logf("%s", stderr.String())
330                         c.Fatal("timed out")
331                 }
332         }
333         for delay := time.Second / 100; ; delay = delay * 2 {
334                 time.Sleep(delay)
335                 j, err := os.ReadFile(tmpdir + "/" + string(serviceName) + "-requests.json")
336                 if os.IsNotExist(err) && deadline.After(time.Now()) {
337                         continue
338                 }
339                 c.Assert(err, check.IsNil)
340                 c.Logf("stderr:\n%s", stderr.String())
341                 c.Logf("json:\n%s", string(j))
342
343                 var loaded []struct{ URL string }
344                 err = json.Unmarshal(j, &loaded)
345                 c.Check(err, check.IsNil)
346
347                 for i := 0; i < len(loaded); i++ {
348                         if strings.HasPrefix(loaded[i].URL, "/arvados/v1/connect/") {
349                                 // Filter out a gateway tunnel req
350                                 // that doesn't count toward our API
351                                 // req limit
352                                 if i < len(loaded)-1 {
353                                         copy(loaded[i:], loaded[i+1:])
354                                         i--
355                                 }
356                                 loaded = loaded[:len(loaded)-1]
357                         }
358                 }
359
360                 if len(loaded) < max {
361                         // Dumped when #requests was >90% but <100% of
362                         // limit. If we stop now, we won't be able to
363                         // confirm (below) that management endpoints
364                         // are still accessible when normal requests
365                         // are at 100%.
366                         c.Logf("loaded dumped requests, but len %d < max %d -- still waiting", len(loaded), max)
367                         continue
368                 }
369                 c.Check(loaded, check.HasLen, max+1)
370                 c.Check(loaded[0].URL, check.Equals, "/testpath")
371                 break
372         }
373
374         for _, path := range []string{"/_inspect/requests", "/metrics"} {
375                 req, err := http.NewRequest("GET", "http://localhost:"+port+""+path, nil)
376                 c.Assert(err, check.IsNil)
377                 req.Header.Set("Authorization", "Bearer bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
378                 resp, err := client.Do(req)
379                 if !c.Check(err, check.IsNil) {
380                         break
381                 }
382                 c.Logf("got response for %s", path)
383                 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
384                 buf, err := ioutil.ReadAll(resp.Body)
385                 c.Check(err, check.IsNil)
386                 switch path {
387                 case "/metrics":
388                         c.Check(string(buf), check.Matches, `(?ms).*arvados_concurrent_requests{queue="api"} `+fmt.Sprintf("%d", max)+`\n.*`)
389                         c.Check(string(buf), check.Matches, `(?ms).*arvados_queued_requests{priority="normal",queue="api"} 1\n.*`)
390                 case "/_inspect/requests":
391                         c.Check(string(buf), check.Matches, `(?ms).*"URL":"/testpath".*`)
392                 default:
393                         c.Error("oops, testing bug")
394                 }
395         }
396         close(hold)
397         activeReqs.Wait()
398         c.Check(int(apiResp200), check.Equals, max+1)
399         c.Check(int(apiResp503), check.Equals, 0)
400         c.Check(int(tunnelResp200), check.Equals, maxTunnels)
401         c.Check(int(tunnelResp503), check.Equals, extraTunnelReqs)
402         cancel()
403 }
404
405 func (*Suite) TestTLS(c *check.C) {
406         port := unusedPort(c)
407         cwd, err := os.Getwd()
408         c.Assert(err, check.IsNil)
409
410         stdin := bytes.NewBufferString(`
411 Clusters:
412  zzzzz:
413   SystemRootToken: abcde
414   Services:
415    Controller:
416     ExternalURL: "https://localhost:` + port + `"
417     InternalURLs: {"https://localhost:` + port + `": {}}
418   TLS:
419    Key: file://` + cwd + `/../../services/api/tmp/self-signed.key
420    Certificate: file://` + cwd + `/../../services/api/tmp/self-signed.pem
421 `)
422
423         called := make(chan bool)
424         cmd := Command(arvados.ServiceNameController, func(ctx context.Context, _ *arvados.Cluster, token string, reg *prometheus.Registry) Handler {
425                 return &testHandler{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
426                         w.Write([]byte("ok"))
427                         close(called)
428                 })}
429         })
430
431         exited := make(chan bool)
432         var stdout, stderr bytes.Buffer
433         go func() {
434                 cmd.RunCommand("arvados-controller", []string{"-config", "-"}, stdin, &stdout, &stderr)
435                 close(exited)
436         }()
437         got := make(chan bool)
438         go func() {
439                 defer close(got)
440                 client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
441                 for range time.NewTicker(time.Millisecond).C {
442                         resp, err := client.Get("https://localhost:" + port)
443                         if err != nil {
444                                 c.Log(err)
445                                 continue
446                         }
447                         body, err := ioutil.ReadAll(resp.Body)
448                         c.Check(err, check.IsNil)
449                         c.Logf("status %d, body %s", resp.StatusCode, string(body))
450                         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
451                         break
452                 }
453         }()
454         select {
455         case <-called:
456         case <-exited:
457                 c.Error("command exited without calling handler")
458         case <-time.After(time.Second):
459                 c.Error("timed out")
460         }
461         select {
462         case <-got:
463         case <-exited:
464                 c.Error("command exited before client received response")
465         case <-time.After(time.Second):
466                 c.Error("timed out")
467         }
468         c.Log(stderr.String())
469 }
470
471 type testHandler struct {
472         ctx         context.Context
473         handler     http.Handler
474         healthCheck chan bool
475 }
476
477 func (th *testHandler) Done() <-chan struct{}                            { return nil }
478 func (th *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { th.handler.ServeHTTP(w, r) }
479 func (th *testHandler) CheckHealth() error {
480         ctxlog.FromContext(th.ctx).Info("CheckHealth called")
481         select {
482         case th.healthCheck <- true:
483         default:
484         }
485         return nil
486 }