Merge branch '12684-pysdk-auto-retry'
[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         "testing"
21         "time"
22
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "git.arvados.org/arvados.git/sdk/go/ctxlog"
25         "github.com/prometheus/client_golang/prometheus"
26         check "gopkg.in/check.v1"
27 )
28
29 func Test(t *testing.T) {
30         check.TestingT(t)
31 }
32
33 var _ = check.Suite(&Suite{})
34
35 type Suite struct{}
36 type key int
37
38 const (
39         contextKey key = iota
40 )
41
42 func (*Suite) TestGetListenAddress(c *check.C) {
43         // Find an available port on the testing host, so the test
44         // cases don't get confused by "already in use" errors.
45         listener, err := net.Listen("tcp", ":")
46         c.Assert(err, check.IsNil)
47         _, unusedPort, err := net.SplitHostPort(listener.Addr().String())
48         c.Assert(err, check.IsNil)
49         listener.Close()
50
51         defer os.Unsetenv("ARVADOS_SERVICE_INTERNAL_URL")
52         for idx, trial := range []struct {
53                 // internalURL => listenURL, both with trailing "/"
54                 // because config loader always adds it
55                 internalURLs     map[string]string
56                 envVar           string
57                 expectErrorMatch string
58                 expectLogsMatch  string
59                 expectListen     string
60                 expectInternal   string
61         }{
62                 {
63                         internalURLs:   map[string]string{"http://localhost:" + unusedPort + "/": ""},
64                         expectListen:   "http://localhost:" + unusedPort + "/",
65                         expectInternal: "http://localhost:" + unusedPort + "/",
66                 },
67                 { // implicit port 80 in InternalURLs
68                         internalURLs:     map[string]string{"http://localhost/": ""},
69                         expectErrorMatch: `.*:80: bind: permission denied`,
70                 },
71                 { // implicit port 443 in InternalURLs
72                         internalURLs:   map[string]string{"https://host.example/": "http://localhost:" + unusedPort + "/"},
73                         expectListen:   "http://localhost:" + unusedPort + "/",
74                         expectInternal: "https://host.example/",
75                 },
76                 { // implicit port 443 in ListenURL
77                         internalURLs:     map[string]string{"wss://host.example/": "wss://localhost/"},
78                         expectErrorMatch: `.*:443: bind: permission denied`,
79                 },
80                 {
81                         internalURLs:   map[string]string{"https://hostname.example/": "http://localhost:8000/"},
82                         expectListen:   "http://localhost:8000/",
83                         expectInternal: "https://hostname.example/",
84                 },
85                 {
86                         internalURLs: map[string]string{
87                                 "https://hostname1.example/": "http://localhost:12435/",
88                                 "https://hostname2.example/": "http://localhost:" + unusedPort + "/",
89                         },
90                         envVar:         "https://hostname2.example", // note this works despite missing trailing "/"
91                         expectListen:   "http://localhost:" + unusedPort + "/",
92                         expectInternal: "https://hostname2.example/",
93                 },
94                 { // cannot listen on any of the ListenURLs
95                         internalURLs: map[string]string{
96                                 "https://hostname1.example/": "http://1.2.3.4:" + unusedPort + "/",
97                                 "https://hostname2.example/": "http://1.2.3.4:" + unusedPort + "/",
98                         },
99                         expectErrorMatch: "configuration does not enable the \"arvados-controller\" service on this host",
100                 },
101                 { // cannot listen on any of the (implied) ListenURLs
102                         internalURLs: map[string]string{
103                                 "https://1.2.3.4/": "",
104                                 "https://1.2.3.5/": "",
105                         },
106                         expectErrorMatch: "configuration does not enable the \"arvados-controller\" service on this host",
107                 },
108                 { // impossible port number
109                         internalURLs: map[string]string{
110                                 "https://host.example/": "http://0.0.0.0:1234567",
111                         },
112                         expectErrorMatch: `.*:1234567: listen tcp: address 1234567: invalid port`,
113                 },
114                 {
115                         // env var URL not mentioned in config = obey env var, with warning
116                         internalURLs:    map[string]string{"https://hostname1.example/": "http://localhost:8000/"},
117                         envVar:          "https://hostname2.example",
118                         expectListen:    "https://hostname2.example/",
119                         expectInternal:  "https://hostname2.example/",
120                         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`,
121                 },
122                 {
123                         // env var + empty config = obey env var, with warning
124                         envVar:          "https://hostname.example",
125                         expectListen:    "https://hostname.example/",
126                         expectInternal:  "https://hostname.example/",
127                         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`,
128                 },
129         } {
130                 c.Logf("trial %d %+v", idx, trial)
131                 os.Setenv("ARVADOS_SERVICE_INTERNAL_URL", trial.envVar)
132                 var logbuf bytes.Buffer
133                 log := ctxlog.New(&logbuf, "text", "info")
134                 services := arvados.Services{Controller: arvados.Service{InternalURLs: map[arvados.URL]arvados.ServiceInstance{}}}
135                 for k, v := range trial.internalURLs {
136                         u, err := url.Parse(k)
137                         c.Assert(err, check.IsNil)
138                         si := arvados.ServiceInstance{}
139                         if v != "" {
140                                 u, err := url.Parse(v)
141                                 c.Assert(err, check.IsNil)
142                                 si.ListenURL = arvados.URL(*u)
143                         }
144                         services.Controller.InternalURLs[arvados.URL(*u)] = si
145                 }
146                 listenURL, internalURL, err := getListenAddr(services, "arvados-controller", log)
147                 if trial.expectLogsMatch != "" {
148                         c.Check(logbuf.String(), check.Matches, trial.expectLogsMatch)
149                 }
150                 if trial.expectErrorMatch != "" {
151                         c.Check(err, check.ErrorMatches, trial.expectErrorMatch)
152                         continue
153                 }
154                 if !c.Check(err, check.IsNil) {
155                         continue
156                 }
157                 c.Check(listenURL.String(), check.Equals, trial.expectListen)
158                 c.Check(internalURL.String(), check.Equals, trial.expectInternal)
159         }
160 }
161
162 func (*Suite) TestCommand(c *check.C) {
163         cf, err := ioutil.TempFile("", "cmd_test.")
164         c.Assert(err, check.IsNil)
165         defer os.Remove(cf.Name())
166         defer cf.Close()
167         fmt.Fprintf(cf, "Clusters:\n zzzzz:\n  SystemRootToken: abcde\n  NodeProfiles: {\"*\": {\"arvados-controller\": {Listen: \":1234\"}}}")
168
169         healthCheck := make(chan bool, 1)
170         ctx, cancel := context.WithCancel(context.Background())
171         defer cancel()
172
173         cmd := Command(arvados.ServiceNameController, func(ctx context.Context, _ *arvados.Cluster, token string, reg *prometheus.Registry) Handler {
174                 c.Check(ctx.Value(contextKey), check.Equals, "bar")
175                 c.Check(token, check.Equals, "abcde")
176                 return &testHandler{ctx: ctx, healthCheck: healthCheck}
177         })
178         cmd.(*command).ctx = context.WithValue(ctx, contextKey, "bar")
179
180         done := make(chan bool)
181         var stdin, stdout, stderr bytes.Buffer
182
183         go func() {
184                 cmd.RunCommand("arvados-controller", []string{"-config", cf.Name()}, &stdin, &stdout, &stderr)
185                 close(done)
186         }()
187         select {
188         case <-healthCheck:
189         case <-done:
190                 c.Error("command exited without health check")
191         }
192         cancel()
193         c.Check(stdout.String(), check.Equals, "")
194         c.Check(stderr.String(), check.Matches, `(?ms).*"msg":"CheckHealth called".*`)
195 }
196
197 func (*Suite) TestDumpRequests(c *check.C) {
198         defer func(orig time.Duration) { requestQueueDumpCheckInterval = orig }(requestQueueDumpCheckInterval)
199         requestQueueDumpCheckInterval = time.Second / 10
200
201         tmpdir := c.MkDir()
202         cf, err := ioutil.TempFile(tmpdir, "cmd_test.")
203         c.Assert(err, check.IsNil)
204         defer os.Remove(cf.Name())
205         defer cf.Close()
206
207         max := 24
208         fmt.Fprintf(cf, `
209 Clusters:
210  zzzzz:
211   SystemRootToken: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
212   ManagementToken: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
213   API: {MaxConcurrentRequests: %d}
214   SystemLogs: {RequestQueueDumpDirectory: %q}
215   Services:
216    Controller:
217     ExternalURL: "http://localhost:12345"
218     InternalURLs: {"http://localhost:12345": {}}
219 `, max, tmpdir)
220
221         started := make(chan bool, max+1)
222         hold := make(chan bool)
223         handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
224                 started <- true
225                 <-hold
226         })
227         healthCheck := make(chan bool, 1)
228         ctx, cancel := context.WithCancel(context.Background())
229         defer cancel()
230
231         cmd := Command(arvados.ServiceNameController, func(ctx context.Context, _ *arvados.Cluster, token string, reg *prometheus.Registry) Handler {
232                 return &testHandler{ctx: ctx, handler: handler, healthCheck: healthCheck}
233         })
234         cmd.(*command).ctx = context.WithValue(ctx, contextKey, "bar")
235
236         exited := make(chan bool)
237         var stdin, stdout, stderr bytes.Buffer
238
239         go func() {
240                 cmd.RunCommand("arvados-controller", []string{"-config", cf.Name()}, &stdin, &stdout, &stderr)
241                 close(exited)
242         }()
243         select {
244         case <-healthCheck:
245         case <-exited:
246                 c.Logf("%s", stderr.String())
247                 c.Error("command exited without health check")
248         }
249         client := http.Client{}
250         deadline := time.Now().Add(time.Second * 2)
251         for i := 0; i < max+1; i++ {
252                 go func() {
253                         resp, err := client.Get("http://localhost:12345/testpath")
254                         for err != nil && strings.Contains(err.Error(), "dial tcp") && deadline.After(time.Now()) {
255                                 time.Sleep(time.Second / 100)
256                                 resp, err = client.Get("http://localhost:12345/testpath")
257                         }
258                         if c.Check(err, check.IsNil) {
259                                 c.Logf("resp StatusCode %d", resp.StatusCode)
260                         }
261                 }()
262         }
263         for i := 0; i < max; i++ {
264                 select {
265                 case <-started:
266                 case <-time.After(time.Second):
267                         c.Logf("%s", stderr.String())
268                         panic("timed out")
269                 }
270         }
271         for {
272                 time.Sleep(time.Second / 100)
273                 j, err := os.ReadFile(tmpdir + "/arvados-controller-requests.json")
274                 if os.IsNotExist(err) && deadline.After(time.Now()) {
275                         continue
276                 }
277                 c.Check(err, check.IsNil)
278                 c.Logf("%s", stderr.String())
279                 c.Logf("%s", string(j))
280
281                 var loaded []struct{ URL string }
282                 err = json.Unmarshal(j, &loaded)
283                 c.Check(err, check.IsNil)
284                 if len(loaded) < max {
285                         // Dumped when #requests was >90% but <100% of
286                         // limit. If we stop now, we won't be able to
287                         // confirm (below) that management endpoints
288                         // are still accessible when normal requests
289                         // are at 100%.
290                         c.Logf("loaded dumped requests, but len %d < max %d -- still waiting", len(loaded), max)
291                         continue
292                 }
293                 c.Check(loaded, check.HasLen, max)
294                 c.Check(loaded[0].URL, check.Equals, "/testpath")
295                 break
296         }
297
298         for _, path := range []string{"/_inspect/requests", "/metrics"} {
299                 req, err := http.NewRequest("GET", "http://localhost:12345"+path, nil)
300                 c.Assert(err, check.IsNil)
301                 req.Header.Set("Authorization", "Bearer bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")
302                 resp, err := client.Do(req)
303                 if !c.Check(err, check.IsNil) {
304                         break
305                 }
306                 c.Logf("got response for %s", path)
307                 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
308                 buf, err := ioutil.ReadAll(resp.Body)
309                 c.Check(err, check.IsNil)
310                 switch path {
311                 case "/metrics":
312                         c.Check(string(buf), check.Matches, `(?ms).*arvados_concurrent_requests `+fmt.Sprintf("%d", max)+`\n.*`)
313                 case "/_inspect/requests":
314                         c.Check(string(buf), check.Matches, `(?ms).*"URL":"/testpath".*`)
315                 default:
316                         c.Error("oops, testing bug")
317                 }
318         }
319         close(hold)
320         cancel()
321
322 }
323
324 func (*Suite) TestTLS(c *check.C) {
325         cwd, err := os.Getwd()
326         c.Assert(err, check.IsNil)
327
328         stdin := bytes.NewBufferString(`
329 Clusters:
330  zzzzz:
331   SystemRootToken: abcde
332   Services:
333    Controller:
334     ExternalURL: "https://localhost:12345"
335     InternalURLs: {"https://localhost:12345": {}}
336   TLS:
337    Key: file://` + cwd + `/../../services/api/tmp/self-signed.key
338    Certificate: file://` + cwd + `/../../services/api/tmp/self-signed.pem
339 `)
340
341         called := make(chan bool)
342         cmd := Command(arvados.ServiceNameController, func(ctx context.Context, _ *arvados.Cluster, token string, reg *prometheus.Registry) Handler {
343                 return &testHandler{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
344                         w.Write([]byte("ok"))
345                         close(called)
346                 })}
347         })
348
349         exited := make(chan bool)
350         var stdout, stderr bytes.Buffer
351         go func() {
352                 cmd.RunCommand("arvados-controller", []string{"-config", "-"}, stdin, &stdout, &stderr)
353                 close(exited)
354         }()
355         got := make(chan bool)
356         go func() {
357                 defer close(got)
358                 client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
359                 for range time.NewTicker(time.Millisecond).C {
360                         resp, err := client.Get("https://localhost:12345")
361                         if err != nil {
362                                 c.Log(err)
363                                 continue
364                         }
365                         body, err := ioutil.ReadAll(resp.Body)
366                         c.Check(err, check.IsNil)
367                         c.Logf("status %d, body %s", resp.StatusCode, string(body))
368                         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
369                         break
370                 }
371         }()
372         select {
373         case <-called:
374         case <-exited:
375                 c.Error("command exited without calling handler")
376         case <-time.After(time.Second):
377                 c.Error("timed out")
378         }
379         select {
380         case <-got:
381         case <-exited:
382                 c.Error("command exited before client received response")
383         case <-time.After(time.Second):
384                 c.Error("timed out")
385         }
386         c.Log(stderr.String())
387 }
388
389 type testHandler struct {
390         ctx         context.Context
391         handler     http.Handler
392         healthCheck chan bool
393 }
394
395 func (th *testHandler) Done() <-chan struct{}                            { return nil }
396 func (th *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { th.handler.ServeHTTP(w, r) }
397 func (th *testHandler) CheckHealth() error {
398         ctxlog.FromContext(th.ctx).Info("CheckHealth called")
399         select {
400         case th.healthCheck <- true:
401         default:
402         }
403         return nil
404 }