15954: Add ping check for health aggregator.
[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         "encoding/json"
10         "errors"
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.DefaultClient
39         if agg.timeout == 0 {
40                 // this is always the case, except in the test suite
41                 agg.timeout = defaultTimeout
42         }
43 }
44
45 func (agg *Aggregator) CheckHealth() error {
46         return nil
47 }
48
49 func (agg *Aggregator) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
50         agg.setupOnce.Do(agg.setup)
51         sendErr := func(statusCode int, err error) {
52                 resp.WriteHeader(statusCode)
53                 json.NewEncoder(resp).Encode(map[string]string{"error": err.Error()})
54                 if agg.Log != nil {
55                         agg.Log(req, err)
56                 }
57         }
58
59         resp.Header().Set("Content-Type", "application/json")
60
61         if !agg.checkAuth(req) {
62                 sendErr(http.StatusUnauthorized, errUnauthorized)
63                 return
64         }
65         if req.URL.Path == "/_health/all" {
66                 json.NewEncoder(resp).Encode(agg.ClusterHealth())
67         } else if req.URL.Path == "/_health/ping" {
68                 resp.Write(healthyBody)
69         } else {
70                 sendErr(http.StatusNotFound, errNotFound)
71                 return
72         }
73         if agg.Log != nil {
74                 agg.Log(req, nil)
75         }
76 }
77
78 type ClusterHealthResponse struct {
79         // "OK" if all needed services are OK, otherwise "ERROR".
80         Health string `json:"health"`
81
82         // An entry for each known health check of each known instance
83         // of each needed component: "instance of service S on node N
84         // reports health-check C is OK."
85         Checks map[string]CheckResult `json:"checks"`
86
87         // An entry for each service type: "service S is OK." This
88         // exposes problems that can't be expressed in Checks, like
89         // "service S is needed, but isn't configured to run
90         // anywhere."
91         Services map[arvados.ServiceName]ServiceHealth `json:"services"`
92 }
93
94 type CheckResult struct {
95         Health         string                 `json:"health"`
96         Error          string                 `json:"error,omitempty"`
97         HTTPStatusCode int                    `json:",omitempty"`
98         HTTPStatusText string                 `json:",omitempty"`
99         Response       map[string]interface{} `json:"response"`
100         ResponseTime   json.Number            `json:"responseTime"`
101 }
102
103 type ServiceHealth struct {
104         Health string `json:"health"`
105         N      int    `json:"n"`
106 }
107
108 func (agg *Aggregator) ClusterHealth() ClusterHealthResponse {
109         resp := ClusterHealthResponse{
110                 Health:   "OK",
111                 Checks:   make(map[string]CheckResult),
112                 Services: make(map[arvados.ServiceName]ServiceHealth),
113         }
114
115         mtx := sync.Mutex{}
116         wg := sync.WaitGroup{}
117         for svcName, svc := range agg.Cluster.Services.Map() {
118                 // Ensure svc is listed in resp.Services.
119                 mtx.Lock()
120                 if _, ok := resp.Services[svcName]; !ok {
121                         resp.Services[svcName] = ServiceHealth{Health: "ERROR"}
122                 }
123                 mtx.Unlock()
124
125                 for addr := range svc.InternalURLs {
126                         wg.Add(1)
127                         go func(svcName arvados.ServiceName, addr arvados.URL) {
128                                 defer wg.Done()
129                                 var result CheckResult
130                                 pingURL, err := agg.pingURL(addr)
131                                 if err != nil {
132                                         result = CheckResult{
133                                                 Health: "ERROR",
134                                                 Error:  err.Error(),
135                                         }
136                                 } else {
137                                         result = agg.ping(pingURL)
138                                 }
139
140                                 mtx.Lock()
141                                 defer mtx.Unlock()
142                                 resp.Checks[fmt.Sprintf("%s+%s", svcName, pingURL)] = result
143                                 if result.Health == "OK" {
144                                         h := resp.Services[svcName]
145                                         h.N++
146                                         h.Health = "OK"
147                                         resp.Services[svcName] = h
148                                 } else {
149                                         resp.Health = "ERROR"
150                                 }
151                         }(svcName, addr)
152                 }
153         }
154         wg.Wait()
155
156         // Report ERROR if a needed service didn't fail any checks
157         // merely because it isn't configured to run anywhere.
158         for _, sh := range resp.Services {
159                 if sh.Health != "OK" {
160                         resp.Health = "ERROR"
161                         break
162                 }
163         }
164         return resp
165 }
166
167 func (agg *Aggregator) pingURL(svcURL arvados.URL) (*url.URL, error) {
168         base := url.URL(svcURL)
169         return base.Parse("/_health/ping")
170 }
171
172 func (agg *Aggregator) ping(target *url.URL) (result CheckResult) {
173         t0 := time.Now()
174
175         var err error
176         defer func() {
177                 result.ResponseTime = json.Number(fmt.Sprintf("%.6f", time.Since(t0).Seconds()))
178                 if err != nil {
179                         result.Health, result.Error = "ERROR", err.Error()
180                 } else {
181                         result.Health = "OK"
182                 }
183         }()
184
185         req, err := http.NewRequest("GET", target.String(), nil)
186         if err != nil {
187                 return
188         }
189         req.Header.Set("Authorization", "Bearer "+agg.Cluster.ManagementToken)
190
191         ctx, cancel := context.WithTimeout(req.Context(), time.Duration(agg.timeout))
192         defer cancel()
193         req = req.WithContext(ctx)
194         resp, err := agg.httpClient.Do(req)
195         if err != nil {
196                 return
197         }
198         result.HTTPStatusCode = resp.StatusCode
199         result.HTTPStatusText = resp.Status
200         err = json.NewDecoder(resp.Body).Decode(&result.Response)
201         if err != nil {
202                 err = fmt.Errorf("cannot decode response: %s", err)
203         } else if resp.StatusCode != http.StatusOK {
204                 err = fmt.Errorf("HTTP %d %s", resp.StatusCode, resp.Status)
205         } else if h, _ := result.Response["health"].(string); h != "OK" {
206                 if e, ok := result.Response["error"].(string); ok && e != "" {
207                         err = errors.New(e)
208                 } else {
209                         err = fmt.Errorf("health=%q in ping response", h)
210                 }
211         }
212         return
213 }
214
215 func (agg *Aggregator) checkAuth(req *http.Request) bool {
216         creds := auth.CredentialsFromRequest(req)
217         for _, token := range creds.Tokens {
218                 if token != "" && token == agg.Cluster.ManagementToken {
219                         return true
220                 }
221         }
222         return false
223 }