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