1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
5 // package service provides a cmd.Handler that brings up a system service.
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"
27 func Test(t *testing.T) {
31 var _ = check.Suite(&Suite{})
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)
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
55 expectErrorMatch string
56 expectLogsMatch string
61 internalURLs: map[string]string{"http://localhost:" + unusedPort + "/": ""},
62 expectListen: "http://localhost:" + unusedPort + "/",
63 expectInternal: "http://localhost:" + unusedPort + "/",
65 { // implicit port 80 in InternalURLs
66 internalURLs: map[string]string{"http://localhost/": ""},
67 expectErrorMatch: `.*:80: bind: permission denied`,
69 { // implicit port 443 in InternalURLs
70 internalURLs: map[string]string{"https://host.example/": "http://localhost:" + unusedPort + "/"},
71 expectListen: "http://localhost:" + unusedPort + "/",
72 expectInternal: "https://host.example/",
74 { // implicit port 443 in ListenURL
75 internalURLs: map[string]string{"wss://host.example/": "wss://localhost/"},
76 expectErrorMatch: `.*:443: bind: permission denied`,
79 internalURLs: map[string]string{"https://hostname.example/": "http://localhost:8000/"},
80 expectListen: "http://localhost:8000/",
81 expectInternal: "https://hostname.example/",
84 internalURLs: map[string]string{
85 "https://hostname1.example/": "http://localhost:12435/",
86 "https://hostname2.example/": "http://localhost:" + unusedPort + "/",
88 envVar: "https://hostname2.example", // note this works despite missing trailing "/"
89 expectListen: "http://localhost:" + unusedPort + "/",
90 expectInternal: "https://hostname2.example/",
92 { // cannot listen on any of the ListenURLs
93 internalURLs: map[string]string{
94 "https://hostname1.example/": "http://1.2.3.4:" + unusedPort + "/",
95 "https://hostname2.example/": "http://1.2.3.4:" + unusedPort + "/",
97 expectErrorMatch: "configuration does not enable the \"arvados-controller\" service on this host",
99 { // cannot listen on any of the (implied) ListenURLs
100 internalURLs: map[string]string{
101 "https://1.2.3.4/": "",
102 "https://1.2.3.5/": "",
104 expectErrorMatch: "configuration does not enable the \"arvados-controller\" service on this host",
106 { // impossible port number
107 internalURLs: map[string]string{
108 "https://host.example/": "http://0.0.0.0:1234567",
110 expectErrorMatch: `.*:1234567: listen tcp: address 1234567: invalid port`,
113 // env var URL not mentioned in config = obey env var, with warning
114 internalURLs: map[string]string{"https://hostname1.example/": "http://localhost:8000/"},
115 envVar: "https://hostname2.example",
116 expectListen: "https://hostname2.example/",
117 expectInternal: "https://hostname2.example/",
118 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 // env var + empty config = obey env var, with warning
122 envVar: "https://hostname.example",
123 expectListen: "https://hostname.example/",
124 expectInternal: "https://hostname.example/",
125 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 c.Logf("trial %d %+v", idx, trial)
129 os.Setenv("ARVADOS_SERVICE_INTERNAL_URL", trial.envVar)
130 var logbuf bytes.Buffer
131 log := ctxlog.New(&logbuf, "text", "info")
132 services := arvados.Services{Controller: arvados.Service{InternalURLs: map[arvados.URL]arvados.ServiceInstance{}}}
133 for k, v := range trial.internalURLs {
134 u, err := url.Parse(k)
135 c.Assert(err, check.IsNil)
136 si := arvados.ServiceInstance{}
138 u, err := url.Parse(v)
139 c.Assert(err, check.IsNil)
140 si.ListenURL = arvados.URL(*u)
142 services.Controller.InternalURLs[arvados.URL(*u)] = si
144 listenURL, internalURL, err := getListenAddr(services, "arvados-controller", log)
145 if trial.expectLogsMatch != "" {
146 c.Check(logbuf.String(), check.Matches, trial.expectLogsMatch)
148 if trial.expectErrorMatch != "" {
149 c.Check(err, check.ErrorMatches, trial.expectErrorMatch)
152 if !c.Check(err, check.IsNil) {
155 c.Check(listenURL.String(), check.Equals, trial.expectListen)
156 c.Check(internalURL.String(), check.Equals, trial.expectInternal)
160 func (*Suite) TestCommand(c *check.C) {
161 cf, err := ioutil.TempFile("", "cmd_test.")
162 c.Assert(err, check.IsNil)
163 defer os.Remove(cf.Name())
165 fmt.Fprintf(cf, "Clusters:\n zzzzz:\n SystemRootToken: abcde\n NodeProfiles: {\"*\": {\"arvados-controller\": {Listen: \":1234\"}}}")
167 healthCheck := make(chan bool, 1)
168 ctx, cancel := context.WithCancel(context.Background())
171 cmd := Command(arvados.ServiceNameController, func(ctx context.Context, _ *arvados.Cluster, token string, reg *prometheus.Registry) Handler {
172 c.Check(ctx.Value(contextKey), check.Equals, "bar")
173 c.Check(token, check.Equals, "abcde")
174 return &testHandler{ctx: ctx, healthCheck: healthCheck}
176 cmd.(*command).ctx = context.WithValue(ctx, contextKey, "bar")
178 done := make(chan bool)
179 var stdin, stdout, stderr bytes.Buffer
182 cmd.RunCommand("arvados-controller", []string{"-config", cf.Name()}, &stdin, &stdout, &stderr)
188 c.Error("command exited without health check")
191 c.Check(stdout.String(), check.Equals, "")
192 c.Check(stderr.String(), check.Matches, `(?ms).*"msg":"CheckHealth called".*`)
195 func (*Suite) TestTLS(c *check.C) {
196 cwd, err := os.Getwd()
197 c.Assert(err, check.IsNil)
199 stdin := bytes.NewBufferString(`
202 SystemRootToken: abcde
205 ExternalURL: "https://localhost:12345"
206 InternalURLs: {"https://localhost:12345": {}}
208 Key: file://` + cwd + `/../../services/api/tmp/self-signed.key
209 Certificate: file://` + cwd + `/../../services/api/tmp/self-signed.pem
212 called := make(chan bool)
213 cmd := Command(arvados.ServiceNameController, func(ctx context.Context, _ *arvados.Cluster, token string, reg *prometheus.Registry) Handler {
214 return &testHandler{handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
215 w.Write([]byte("ok"))
220 exited := make(chan bool)
221 var stdout, stderr bytes.Buffer
223 cmd.RunCommand("arvados-controller", []string{"-config", "-"}, stdin, &stdout, &stderr)
226 got := make(chan bool)
229 client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
230 for range time.NewTicker(time.Millisecond).C {
231 resp, err := client.Get("https://localhost:12345")
236 body, err := ioutil.ReadAll(resp.Body)
237 c.Check(err, check.IsNil)
238 c.Logf("status %d, body %s", resp.StatusCode, string(body))
239 c.Check(resp.StatusCode, check.Equals, http.StatusOK)
246 c.Error("command exited without calling handler")
247 case <-time.After(time.Second):
253 c.Error("command exited before client received response")
254 case <-time.After(time.Second):
257 c.Log(stderr.String())
260 type testHandler struct {
263 healthCheck chan bool
266 func (th *testHandler) Done() <-chan struct{} { return nil }
267 func (th *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { th.handler.ServeHTTP(w, r) }
268 func (th *testHandler) CheckHealth() error {
269 ctxlog.FromContext(th.ctx).Info("CheckHealth called")
271 case th.healthCheck <- true: