7a1f98a8f0af2c3ac188fe15be171f6ca1e26f6b
[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         "fmt"
13         "io/ioutil"
14         "net"
15         "net/http"
16         "net/url"
17         "os"
18         "testing"
19         "time"
20
21         "git.arvados.org/arvados.git/sdk/go/arvados"
22         "git.arvados.org/arvados.git/sdk/go/ctxlog"
23         "github.com/prometheus/client_golang/prometheus"
24         check "gopkg.in/check.v1"
25 )
26
27 func Test(t *testing.T) {
28         check.TestingT(t)
29 }
30
31 var _ = check.Suite(&Suite{})
32
33 type Suite struct{}
34 type key int
35
36 const (
37         contextKey key = iota
38 )
39
40 func (*Suite) TestGetListenAddress(c *check.C) {
41         // Find an available port on the testing host, so the test
42         // cases don't get confused by "already in use" errors.
43         listener, err := net.Listen("tcp", ":")
44         c.Assert(err, check.IsNil)
45         _, unusedPort, err := net.SplitHostPort(listener.Addr().String())
46         c.Assert(err, check.IsNil)
47         listener.Close()
48
49         defer os.Unsetenv("ARVADOS_SERVICE_INTERNAL_URL")
50         for idx, trial := range []struct {
51                 // internalURL => listenURL, both with trailing "/"
52                 // because config loader always adds it
53                 internalURLs     map[string]string
54                 envVar           string
55                 expectErrorMatch string
56                 expectLogsMatch  string
57                 expectListen     string
58                 expectInternal   string
59         }{
60                 {
61                         internalURLs:   map[string]string{"http://localhost:" + unusedPort + "/": ""},
62                         expectListen:   "http://localhost:" + unusedPort + "/",
63                         expectInternal: "http://localhost:" + unusedPort + "/",
64                 },
65                 { // implicit port 80 in InternalURLs
66                         internalURLs:     map[string]string{"http://localhost/": ""},
67                         expectListen:     "http://localhost/",
68                         expectInternal:   "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                 {
77                         internalURLs:   map[string]string{"https://hostname.example/": "http://localhost:8000/"},
78                         expectListen:   "http://localhost:8000/",
79                         expectInternal: "https://hostname.example/",
80                 },
81                 {
82                         internalURLs: map[string]string{
83                                 "https://hostname1.example/": "http://localhost:12435/",
84                                 "https://hostname2.example/": "http://localhost:" + unusedPort + "/",
85                         },
86                         envVar:         "https://hostname2.example", // note this works despite missing trailing "/"
87                         expectListen:   "http://localhost:" + unusedPort + "/",
88                         expectInternal: "https://hostname2.example/",
89                 },
90                 { // cannot listen on any of the ListenURLs
91                         internalURLs: map[string]string{
92                                 "https://hostname1.example/": "http://1.2.3.4:" + unusedPort + "/",
93                                 "https://hostname2.example/": "http://1.2.3.4:" + unusedPort + "/",
94                         },
95                         expectErrorMatch: "configuration does not enable the \"arvados-controller\" service on this host",
96                 },
97                 { // cannot listen on any of the (implied) ListenURLs
98                         internalURLs: map[string]string{
99                                 "https://1.2.3.4/": "",
100                                 "https://1.2.3.5/": "",
101                         },
102                         expectErrorMatch: "configuration does not enable the \"arvados-controller\" service on this host",
103                 },
104                 { // impossible port number
105                         internalURLs: map[string]string{
106                                 "https://host.example/": "http://0.0.0.0:1234567",
107                         },
108                         expectErrorMatch: `.*:1234567: listen tcp: address 1234567: invalid port`,
109                 },
110                 {
111                         // env var URL not mentioned in config = obey env var, with warning
112                         internalURLs:    map[string]string{"https://hostname1.example/": "http://localhost:8000/"},
113                         envVar:          "https://hostname2.example",
114                         expectListen:    "https://hostname2.example/",
115                         expectInternal:  "https://hostname2.example/",
116                         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`,
117                 },
118                 {
119                         // env var + empty config = obey env var, with warning
120                         envVar:          "https://hostname.example",
121                         expectListen:    "https://hostname.example/",
122                         expectInternal:  "https://hostname.example/",
123                         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`,
124                 },
125         } {
126                 c.Logf("trial %d %+v", idx, trial)
127                 os.Setenv("ARVADOS_SERVICE_INTERNAL_URL", trial.envVar)
128                 var logbuf bytes.Buffer
129                 log := ctxlog.New(&logbuf, "text", "info")
130                 services := arvados.Services{Controller: arvados.Service{InternalURLs: map[arvados.URL]arvados.ServiceInstance{}}}
131                 for k, v := range trial.internalURLs {
132                         u, err := url.Parse(k)
133                         c.Assert(err, check.IsNil)
134                         si := arvados.ServiceInstance{}
135                         if v != "" {
136                                 u, err := url.Parse(v)
137                                 c.Assert(err, check.IsNil)
138                                 si.ListenURL = arvados.URL(*u)
139                         }
140                         services.Controller.InternalURLs[arvados.URL(*u)] = si
141                 }
142                 listenURL, internalURL, err := getListenAddr(services, "arvados-controller", log)
143                 if trial.expectLogsMatch != "" {
144                         c.Check(logbuf.String(), check.Matches, trial.expectLogsMatch)
145                 }
146                 if trial.expectErrorMatch != "" {
147                         c.Check(err, check.ErrorMatches, trial.expectErrorMatch)
148                         continue
149                 }
150                 if !c.Check(err, check.IsNil) {
151                         continue
152                 }
153                 c.Check(listenURL.String(), check.Equals, trial.expectListen)
154                 c.Check(internalURL.String(), check.Equals, trial.expectInternal)
155         }
156 }
157
158 func (*Suite) TestCommand(c *check.C) {
159         cf, err := ioutil.TempFile("", "cmd_test.")
160         c.Assert(err, check.IsNil)
161         defer os.Remove(cf.Name())
162         defer cf.Close()
163         fmt.Fprintf(cf, "Clusters:\n zzzzz:\n  SystemRootToken: abcde\n  NodeProfiles: {\"*\": {\"arvados-controller\": {Listen: \":1234\"}}}")
164
165         healthCheck := make(chan bool, 1)
166         ctx, cancel := context.WithCancel(context.Background())
167         defer cancel()
168
169         cmd := Command(arvados.ServiceNameController, func(ctx context.Context, _ *arvados.Cluster, token string, reg *prometheus.Registry) Handler {
170                 c.Check(ctx.Value(contextKey), check.Equals, "bar")
171                 c.Check(token, check.Equals, "abcde")
172                 return &testHandler{ctx: ctx, healthCheck: healthCheck}
173         })
174         cmd.(*command).ctx = context.WithValue(ctx, contextKey, "bar")
175
176         done := make(chan bool)
177         var stdin, stdout, stderr bytes.Buffer
178
179         go func() {
180                 cmd.RunCommand("arvados-controller", []string{"-config", cf.Name()}, &stdin, &stdout, &stderr)
181                 close(done)
182         }()
183         select {
184         case <-healthCheck:
185         case <-done:
186                 c.Error("command exited without health check")
187         }
188         cancel()
189         c.Check(stdout.String(), check.Equals, "")
190         c.Check(stderr.String(), check.Matches, `(?ms).*"msg":"CheckHealth called".*`)
191 }
192
193 func (*Suite) TestTLS(c *check.C) {
194         cwd, err := os.Getwd()
195         c.Assert(err, check.IsNil)
196
197         stdin := bytes.NewBufferString(`
198 Clusters:
199  zzzzz:
200   SystemRootToken: abcde
201   Services:
202    Controller:
203     ExternalURL: "https://localhost:12345"
204     InternalURLs: {"https://localhost:12345": {}}
205   TLS:
206    Key: file://` + cwd + `/../../services/api/tmp/self-signed.key
207    Certificate: file://` + cwd + `/../../services/api/tmp/self-signed.pem
208 `)
209
210         called := make(chan bool)
211         cmd := Command(arvados.ServiceNameController, func(ctx context.Context, _ *arvados.Cluster, token string, reg *prometheus.Registry) Handler {
212                 return &testHandler{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
213                         w.Write([]byte("ok"))
214                         close(called)
215                 })}
216         })
217
218         exited := make(chan bool)
219         var stdout, stderr bytes.Buffer
220         go func() {
221                 cmd.RunCommand("arvados-controller", []string{"-config", "-"}, stdin, &stdout, &stderr)
222                 close(exited)
223         }()
224         got := make(chan bool)
225         go func() {
226                 defer close(got)
227                 client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
228                 for range time.NewTicker(time.Millisecond).C {
229                         resp, err := client.Get("https://localhost:12345")
230                         if err != nil {
231                                 c.Log(err)
232                                 continue
233                         }
234                         body, err := ioutil.ReadAll(resp.Body)
235                         c.Check(err, check.IsNil)
236                         c.Logf("status %d, body %s", resp.StatusCode, string(body))
237                         c.Check(resp.StatusCode, check.Equals, http.StatusOK)
238                         break
239                 }
240         }()
241         select {
242         case <-called:
243         case <-exited:
244                 c.Error("command exited without calling handler")
245         case <-time.After(time.Second):
246                 c.Error("timed out")
247         }
248         select {
249         case <-got:
250         case <-exited:
251                 c.Error("command exited before client received response")
252         case <-time.After(time.Second):
253                 c.Error("timed out")
254         }
255         c.Log(stderr.String())
256 }
257
258 type testHandler struct {
259         ctx         context.Context
260         handler     http.Handler
261         healthCheck chan bool
262 }
263
264 func (th *testHandler) Done() <-chan struct{}                            { return nil }
265 func (th *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { th.handler.ServeHTTP(w, r) }
266 func (th *testHandler) CheckHealth() error {
267         ctxlog.FromContext(th.ctx).Info("CheckHealth called")
268         select {
269         case th.healthCheck <- true:
270         default:
271         }
272         return nil
273 }