18700: Add workbench2 to arvados-boot.
[arvados.git] / sdk / go / health / aggregator.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package health
6
7 import (
8         "context"
9         "crypto/tls"
10         "encoding/json"
11         "fmt"
12         "net/http"
13         "net/url"
14         "sync"
15         "time"
16
17         "git.arvados.org/arvados.git/sdk/go/arvados"
18         "git.arvados.org/arvados.git/sdk/go/auth"
19 )
20
21 const defaultTimeout = arvados.Duration(2 * time.Second)
22
23 // Aggregator implements http.Handler. It handles "GET /_health/all"
24 // by checking the health of all configured services on the cluster
25 // and responding 200 if everything is healthy.
26 type Aggregator struct {
27         setupOnce  sync.Once
28         httpClient *http.Client
29         timeout    arvados.Duration
30
31         Cluster *arvados.Cluster
32
33         // If non-nil, Log is called after handling each request.
34         Log func(*http.Request, error)
35 }
36
37 func (agg *Aggregator) setup() {
38         agg.httpClient = &http.Client{
39                 Transport: &http.Transport{
40                         TLSClientConfig: &tls.Config{
41                                 InsecureSkipVerify: agg.Cluster.TLS.Insecure,
42                         },
43                 },
44         }
45         if agg.timeout == 0 {
46                 // this is always the case, except in the test suite
47                 agg.timeout = defaultTimeout
48         }
49 }
50
51 func (agg *Aggregator) CheckHealth() error {
52         return nil
53 }
54
55 func (agg *Aggregator) Done() <-chan struct{} {
56         return nil
57 }
58
59 func (agg *Aggregator) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
60         agg.setupOnce.Do(agg.setup)
61         sendErr := func(statusCode int, err error) {
62                 resp.WriteHeader(statusCode)
63                 json.NewEncoder(resp).Encode(map[string]string{"error": err.Error()})
64                 if agg.Log != nil {
65                         agg.Log(req, err)
66                 }
67         }
68
69         resp.Header().Set("Content-Type", "application/json")
70
71         if !agg.checkAuth(req) {
72                 sendErr(http.StatusUnauthorized, errUnauthorized)
73                 return
74         }
75         if req.URL.Path == "/_health/all" {
76                 json.NewEncoder(resp).Encode(agg.ClusterHealth())
77         } else if req.URL.Path == "/_health/ping" {
78                 resp.Write(healthyBody)
79         } else {
80                 sendErr(http.StatusNotFound, errNotFound)
81                 return
82         }
83         if agg.Log != nil {
84                 agg.Log(req, nil)
85         }
86 }
87
88 type ClusterHealthResponse struct {
89         // "OK" if all needed services are OK, otherwise "ERROR".
90         Health string `json:"health"`
91
92         // An entry for each known health check of each known instance
93         // of each needed component: "instance of service S on node N
94         // reports health-check C is OK."
95         Checks map[string]CheckResult `json:"checks"`
96
97         // An entry for each service type: "service S is OK." This
98         // exposes problems that can't be expressed in Checks, like
99         // "service S is needed, but isn't configured to run
100         // anywhere."
101         Services map[arvados.ServiceName]ServiceHealth `json:"services"`
102 }
103
104 type CheckResult struct {
105         Health         string                 `json:"health"`
106         Error          string                 `json:"error,omitempty"`
107         HTTPStatusCode int                    `json:",omitempty"`
108         HTTPStatusText string                 `json:",omitempty"`
109         Response       map[string]interface{} `json:"response"`
110         ResponseTime   json.Number            `json:"responseTime"`
111 }
112
113 type ServiceHealth struct {
114         Health string `json:"health"`
115         N      int    `json:"n"`
116 }
117
118 func (agg *Aggregator) ClusterHealth() ClusterHealthResponse {
119         agg.setupOnce.Do(agg.setup)
120         resp := ClusterHealthResponse{
121                 Health:   "OK",
122                 Checks:   make(map[string]CheckResult),
123                 Services: make(map[arvados.ServiceName]ServiceHealth),
124         }
125
126         mtx := sync.Mutex{}
127         wg := sync.WaitGroup{}
128         for svcName, svc := range agg.Cluster.Services.Map() {
129                 // Ensure svc is listed in resp.Services.
130                 mtx.Lock()
131                 if _, ok := resp.Services[svcName]; !ok {
132                         resp.Services[svcName] = ServiceHealth{Health: "ERROR"}
133                 }
134                 mtx.Unlock()
135
136                 for addr := range svc.InternalURLs {
137                         wg.Add(1)
138                         go func(svcName arvados.ServiceName, addr arvados.URL) {
139                                 defer wg.Done()
140                                 var result CheckResult
141                                 pingURL, err := agg.pingURL(addr)
142                                 if err != nil {
143                                         result = CheckResult{
144                                                 Health: "ERROR",
145                                                 Error:  err.Error(),
146                                         }
147                                 } else {
148                                         result = agg.ping(pingURL)
149                                 }
150
151                                 mtx.Lock()
152                                 defer mtx.Unlock()
153                                 resp.Checks[fmt.Sprintf("%s+%s", svcName, pingURL)] = result
154                                 if result.Health == "OK" {
155                                         h := resp.Services[svcName]
156                                         h.N++
157                                         h.Health = "OK"
158                                         resp.Services[svcName] = h
159                                 } else {
160                                         resp.Health = "ERROR"
161                                 }
162                         }(svcName, addr)
163                 }
164         }
165         wg.Wait()
166
167         // Report ERROR if a needed service didn't fail any checks
168         // merely because it isn't configured to run anywhere.
169         for _, sh := range resp.Services {
170                 if sh.Health != "OK" {
171                         resp.Health = "ERROR"
172                         break
173                 }
174         }
175         return resp
176 }
177
178 func (agg *Aggregator) pingURL(svcURL arvados.URL) (*url.URL, error) {
179         base := url.URL(svcURL)
180         return base.Parse("/_health/ping")
181 }
182
183 func (agg *Aggregator) ping(target *url.URL) (result CheckResult) {
184         t0 := time.Now()
185         defer func() {
186                 result.ResponseTime = json.Number(fmt.Sprintf("%.6f", time.Since(t0).Seconds()))
187         }()
188         result.Health = "ERROR"
189
190         req, err := http.NewRequest("GET", target.String(), nil)
191         if err != nil {
192                 result.Error = err.Error()
193                 return
194         }
195         req.Header.Set("Authorization", "Bearer "+agg.Cluster.ManagementToken)
196
197         // Avoid workbench1's redirect-http-to-https feature
198         req.Header.Set("X-Forwarded-Proto", "https")
199
200         ctx, cancel := context.WithTimeout(req.Context(), time.Duration(agg.timeout))
201         defer cancel()
202         req = req.WithContext(ctx)
203         resp, err := agg.httpClient.Do(req)
204         if err != nil {
205                 result.Error = err.Error()
206                 return
207         }
208         result.HTTPStatusCode = resp.StatusCode
209         result.HTTPStatusText = resp.Status
210         err = json.NewDecoder(resp.Body).Decode(&result.Response)
211         if err != nil {
212                 result.Error = fmt.Sprintf("cannot decode response: %s", err)
213         } else if resp.StatusCode != http.StatusOK {
214                 result.Error = fmt.Sprintf("HTTP %d %s", resp.StatusCode, resp.Status)
215         } else if h, _ := result.Response["health"].(string); h != "OK" {
216                 if e, ok := result.Response["error"].(string); ok && e != "" {
217                         result.Error = e
218                         return
219                 } else {
220                         result.Error = fmt.Sprintf("health=%q in ping response", h)
221                         return
222                 }
223         }
224         result.Health = "OK"
225         return
226 }
227
228 func (agg *Aggregator) checkAuth(req *http.Request) bool {
229         creds := auth.CredentialsFromRequest(req)
230         for _, token := range creds.Tokens {
231                 if token != "" && token == agg.Cluster.ManagementToken {
232                         return true
233                 }
234         }
235         return false
236 }