-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
434 lines (391 loc) · 16.6 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"net/http"
"os"
"time"
"github.com/golang/glog"
"github.com/gorilla/mux"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/status"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type ProbeConfig struct {
flGrpcServerAddr string
flRunCli bool
flHTTPListenAddr string
flMetricsHTTPListenAddr string
flMetricsHTTPPath string
flHTTPListenPath string
flServiceName string
flUserAgent string
flConnTimeout time.Duration
flRPCTimeout time.Duration
flGrpcTLS bool
flGrpcTLSNoVerify bool
flGrpcTLSCACert string
flGrpcTLSClientCert string
flGrpcTLSClientKey string
flGrpcSNIServerName string
flHTTPSTLSServerCert string
flHTTPSTLSServerKey string
flHTTPSTLSVerifyCA string
flHTTPSTLSVerifyClient bool
}
var (
cfg = &ProbeConfig{}
opts = []grpc.DialOption{}
httpDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "grpc_health_check_seconds",
Help: "Duration of HTTP requests.",
}, []string{"path"})
serviceDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "grpc_health_check_service_duration_seconds",
Help: "Duration of HTTP requests per service.",
}, []string{"service_name"})
grpcReqs = promauto.NewCounterVec(
prometheus.CounterOpts{
Name: "grpc_health_check_service_requests",
Help: "backend status, partitioned by status code and service_name.",
},
[]string{"code", "service_name"},
)
)
type GrpcProbeError struct {
Code int
Message string
}
func NewGrpcProbeError(code int, message string) *GrpcProbeError {
return &GrpcProbeError{
Code: code,
Message: message,
}
}
func (e *GrpcProbeError) Error() string {
return e.Message
}
const (
StatusConnectionFailure = 1
StatusRPCFailure = 2
StatusServiceNotFound = 3
StatusUnimplemented = 4
StatusUnhealthy = 5
)
func prometheusMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
timer := prometheus.NewTimer(httpDuration.WithLabelValues(path))
next.ServeHTTP(w, r)
timer.ObserveDuration()
})
}
func init() {
flag.StringVar(&cfg.flGrpcServerAddr, "grpcaddr", "", "(required) tcp host:port to connect")
flag.StringVar(&cfg.flServiceName, "service-name", "", "service name to check. If specified, server will ignore ?serviceName= request parameter")
flag.StringVar(&cfg.flUserAgent, "user-agent", "grpc_health_proxy", "user-agent header value of health check requests")
flag.BoolVar(&cfg.flRunCli, "runcli", false, "execute healthCheck via CLI; will not start webserver")
// settings for HTTPS listener
flag.StringVar(&cfg.flHTTPListenAddr, "http-listen-addr", "localhost:8080", "(required) http host:port to listen (default: localhost:8080")
flag.StringVar(&cfg.flMetricsHTTPListenAddr, "metrics-http-listen-addr", "localhost:9000", "http host:port for metrics endpoint (default: localhost:9000")
flag.StringVar(&cfg.flMetricsHTTPPath, "metrics-http-path", "/metrics", "http path metrics endpoint (default: /metrics")
flag.StringVar(&cfg.flHTTPListenPath, "http-listen-path", "/", "path to listen for healthcheck traffic (default '/')")
flag.StringVar(&cfg.flHTTPSTLSServerCert, "https-listen-cert", "", "TLS Server certificate to for HTTP listner")
flag.StringVar(&cfg.flHTTPSTLSServerKey, "https-listen-key", "", "TLS Server certificate key to for HTTP listner")
flag.StringVar(&cfg.flHTTPSTLSVerifyCA, "https-listen-ca", "", "Use CA to verify client requests against CA")
flag.BoolVar(&cfg.flHTTPSTLSVerifyClient, "https-listen-verify", false, "Verify client certificate provided to the HTTP listner")
// timeouts
flag.DurationVar(&cfg.flConnTimeout, "connect-timeout", time.Second, "timeout for establishing connection")
flag.DurationVar(&cfg.flRPCTimeout, "rpc-timeout", time.Second, "timeout for health check rpc")
// tls settings
flag.BoolVar(&cfg.flGrpcTLS, "grpctls", false, "use TLS for upstream gRPC(default: false, INSECURE plaintext transport)")
flag.BoolVar(&cfg.flGrpcTLSNoVerify, "grpc-tls-no-verify", false, "(with -tls) don't verify the certificate (INSECURE) presented by the server (default: false)")
flag.StringVar(&cfg.flGrpcTLSCACert, "grpc-ca-cert", "", "(with -tls, optional) file containing trusted certificates for verifying server")
flag.StringVar(&cfg.flGrpcTLSClientCert, "grpc-client-cert", "", "(with -grpctls, optional) client certificate for authenticating to the server (requires -tls-client-key)")
flag.StringVar(&cfg.flGrpcTLSClientKey, "grpc-client-key", "", "(with -grpctls) client private key for authenticating to the server (requires -tls-client-cert)")
flag.StringVar(&cfg.flGrpcSNIServerName, "grpc-sni-server-name", "", "(with -grpctls) override the hostname used to verify the gRPC server certificate")
flag.Parse()
argError := func(s string, v ...interface{}) {
//flag.PrintDefaults()
glog.Errorf("Invalid Argument error: "+s, v...)
os.Exit(-1)
}
if cfg.flGrpcServerAddr == "" {
argError("-grpcaddr not specified")
}
if !cfg.flRunCli && cfg.flHTTPListenAddr == "" {
argError("-http-listen-addr not specified")
}
if cfg.flConnTimeout <= 0 {
argError("-connect-timeout must be greater than zero (specified: %v)", cfg.flConnTimeout)
}
if cfg.flRPCTimeout <= 0 {
argError("-rpc-timeout must be greater than zero (specified: %v)", cfg.flRPCTimeout)
}
if !cfg.flGrpcTLS && cfg.flGrpcTLSNoVerify {
argError("specified -grpc-tls-no-verify without specifying -grpctls")
}
if !cfg.flGrpcTLS && cfg.flGrpcTLSCACert != "" {
argError("specified -grpc-ca-cert without specifying -grpctls")
}
if !cfg.flGrpcTLS && cfg.flGrpcTLSClientCert != "" {
argError("specified -grpc-client-cert without specifying -grpctls")
}
if !cfg.flGrpcTLS && cfg.flGrpcSNIServerName != "" {
argError("specified -grpc-sni-server-name without specifying -grpctls")
}
if cfg.flGrpcTLSClientCert != "" && cfg.flGrpcTLSClientKey == "" {
argError("specified -grpc-client-cert without specifying -grpc-client-key")
}
if cfg.flGrpcTLSClientCert == "" && cfg.flGrpcTLSClientKey != "" {
argError("specified -grpc-client-key without specifying -grpc-client-cert")
}
if cfg.flGrpcTLSNoVerify && cfg.flGrpcTLSCACert != "" {
argError("cannot specify -grpc-ca-cert with -grpc-tls-no-verify (CA cert would not be used)")
}
if cfg.flGrpcTLSNoVerify && cfg.flGrpcSNIServerName != "" {
argError("cannot specify -grpc-sni-server-name with -grpc-tls-no-verify (server name would not be used)")
}
if (cfg.flHTTPSTLSServerCert == "" && cfg.flHTTPSTLSServerKey != "") || (cfg.flHTTPSTLSServerCert != "" && cfg.flHTTPSTLSServerKey == "") {
argError("must specify both -https-listen-cert and -https-listen-key")
}
if cfg.flHTTPSTLSVerifyCA == "" && cfg.flHTTPSTLSVerifyClient {
argError("cannot specify -https-listen-ca if https-listen-verify is set (you need a trust CA for client certificate https auth)")
}
glog.V(10).Infof("parsed options:")
glog.V(10).Infof("> addr=%s conn_timeout=%s rpc_timeout=%s", cfg.flGrpcServerAddr, cfg.flConnTimeout, cfg.flRPCTimeout)
glog.V(10).Infof("> grpctls=%v", cfg.flGrpcTLS)
glog.V(10).Infof(" http-listen-addr=%s ", cfg.flHTTPListenAddr)
glog.V(10).Infof(" http-listen-path=%s ", cfg.flHTTPListenPath)
glog.V(10).Infof(" https-listen-cert=%s ", cfg.flHTTPSTLSServerCert)
glog.V(10).Infof(" https-listen-key=%s ", cfg.flHTTPSTLSServerKey)
glog.V(10).Infof(" https-listen-verify=%v ", cfg.flHTTPSTLSVerifyClient)
glog.V(10).Infof(" https-listen-ca=%s ", cfg.flHTTPSTLSVerifyCA)
glog.V(10).Infof(" > grpc-tls-no-verify=%v ", cfg.flGrpcTLSNoVerify)
glog.V(10).Infof(" > grpc-ca-cert=%s", cfg.flGrpcTLSCACert)
glog.V(10).Infof(" > grpc-client-cert=%s", cfg.flGrpcTLSClientCert)
glog.V(10).Infof(" > grpc-client-key=%s", cfg.flGrpcTLSClientKey)
glog.V(10).Infof(" > grpc-sni-server-name=%s", cfg.flGrpcSNIServerName)
}
func buildGrpcCredentials() (credentials.TransportCredentials, error) {
var tlsCfg tls.Config
if cfg.flGrpcTLSClientCert != "" && cfg.flGrpcTLSClientKey != "" {
keyPair, err := tls.LoadX509KeyPair(cfg.flGrpcTLSClientCert, cfg.flGrpcTLSClientKey)
if err != nil {
return nil, fmt.Errorf("failed to load tls client cert/key pair. error=%v", err)
}
tlsCfg.Certificates = []tls.Certificate{keyPair}
}
if cfg.flGrpcTLSNoVerify {
tlsCfg.InsecureSkipVerify = true
} else if cfg.flGrpcTLSCACert != "" {
rootCAs := x509.NewCertPool()
pem, err := os.ReadFile(cfg.flGrpcTLSCACert)
if err != nil {
return nil, fmt.Errorf("failed to load root CA certificates from file (%s) error=%v", cfg.flGrpcTLSCACert, err)
}
if !rootCAs.AppendCertsFromPEM(pem) {
return nil, fmt.Errorf("no root CA certs parsed from file %s", cfg.flGrpcTLSCACert)
}
tlsCfg.RootCAs = rootCAs
}
if cfg.flGrpcSNIServerName != "" {
tlsCfg.ServerName = cfg.flGrpcSNIServerName
}
return credentials.NewTLS(&tlsCfg), nil
}
func checkService(ctx context.Context, serviceName string) (healthpb.HealthCheckResponse_ServingStatus, error) {
timer := prometheus.NewTimer(serviceDuration.WithLabelValues(serviceName))
defer timer.ObserveDuration()
glog.V(10).Infof("establishing connection")
connStart := time.Now()
dialCtx, dialCancel := context.WithTimeout(ctx, cfg.flConnTimeout)
defer dialCancel()
conn, err := grpc.DialContext(dialCtx, cfg.flGrpcServerAddr, opts...)
if err != nil {
if err == context.DeadlineExceeded {
glog.Warningf("timeout: failed to connect service %s within %s", cfg.flGrpcServerAddr, cfg.flConnTimeout)
} else {
glog.Warningf("error: failed to connect service at %s: %+v", cfg.flGrpcServerAddr, err)
}
return healthpb.HealthCheckResponse_UNKNOWN, NewGrpcProbeError(StatusConnectionFailure, "StatusConnectionFailure")
}
connDuration := time.Since(connStart)
defer conn.Close()
glog.V(10).Infof("connection established %v", connDuration)
rpcStart := time.Now()
rpcCtx, rpcCancel := context.WithTimeout(ctx, cfg.flRPCTimeout)
defer rpcCancel()
glog.V(10).Infoln("Running HealthCheck for service: ", serviceName)
resp, err := healthpb.NewHealthClient(conn).Check(rpcCtx, &healthpb.HealthCheckRequest{Service: serviceName})
if err != nil {
// first handle and return gRPC-level errors
if stat, ok := status.FromError(err); ok && stat.Code() == codes.Unimplemented {
defer grpcReqs.WithLabelValues(codes.Unimplemented.String(), serviceName).Inc()
glog.Warningf("error: this server does not implement the grpc health protocol (grpc.health.v1.Health)")
return healthpb.HealthCheckResponse_UNKNOWN, NewGrpcProbeError(StatusUnimplemented, "StatusUnimplemented")
} else if stat, ok := status.FromError(err); ok && stat.Code() == codes.DeadlineExceeded {
defer grpcReqs.WithLabelValues(codes.DeadlineExceeded.String(), serviceName).Inc()
glog.Warningf("error timeout: health rpc did not complete within ", cfg.flRPCTimeout)
return healthpb.HealthCheckResponse_UNKNOWN, NewGrpcProbeError(StatusRPCFailure, "StatusRPCFailure")
} else if stat, ok := status.FromError(err); ok && stat.Code() == codes.NotFound {
defer grpcReqs.WithLabelValues(codes.NotFound.String(), serviceName).Inc()
// wrap a grpC NOT_FOUND as grpcProbeError.
// https://github.com/grpc/grpc/blob/master/doc/health-checking.md
// if the service name is not registerered, the server returns a NOT_FOUND GPRPC status.
// the Check for a not found should "return nil, status.Error(codes.NotFound, "unknown service")"
glog.Warningf("error Service Not Found %v", err)
return healthpb.HealthCheckResponse_SERVICE_UNKNOWN, NewGrpcProbeError(StatusServiceNotFound, "StatusServiceNotFound")
} else {
defer grpcReqs.WithLabelValues(codes.Unknown.String(), serviceName).Inc()
glog.Warningf("error: health rpc failed: ", err)
}
} else {
defer grpcReqs.WithLabelValues(resp.GetStatus().String(), serviceName).Inc()
}
rpcDuration := time.Since(rpcStart)
// otherwise, retrurn gRPC-HC status
glog.V(10).Infof("time elapsed: connect=%s rpc=%s", connDuration, rpcDuration)
return resp.GetStatus(), nil
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
var serviceName string
if cfg.flServiceName != "" {
serviceName = cfg.flServiceName
}
keys, ok := r.URL.Query()["serviceName"]
if ok && len(keys[0]) > 0 {
serviceName = keys[0]
}
resp, err := checkService(r.Context(), serviceName)
// first handle errors derived from gRPC-codes
if err != nil {
if pe, ok := err.(*GrpcProbeError); ok {
glog.Errorf("HealtCheck Probe Error: %v", pe.Error())
switch pe.Code {
case StatusConnectionFailure:
http.Error(w, err.Error(), http.StatusBadGateway)
case StatusRPCFailure:
http.Error(w, err.Error(), http.StatusBadGateway)
case StatusUnimplemented:
http.Error(w, err.Error(), http.StatusNotImplemented)
case StatusServiceNotFound:
http.Error(w, fmt.Sprintf("%s ServiceNotFound", cfg.flServiceName), http.StatusNotFound)
default:
http.Error(w, err.Error(), http.StatusBadGateway)
}
return
}
}
// then grpc-hc codes
glog.Infof("%s %v", cfg.flServiceName, resp.String())
switch resp {
case healthpb.HealthCheckResponse_SERVING:
fmt.Fprintf(w, "%s %v", cfg.flServiceName, resp)
case healthpb.HealthCheckResponse_NOT_SERVING:
http.Error(w, fmt.Sprintf("%s %v", cfg.flServiceName, resp.String()), http.StatusBadGateway)
case healthpb.HealthCheckResponse_UNKNOWN:
http.Error(w, fmt.Sprintf("%s %v", cfg.flServiceName, resp.String()), http.StatusBadGateway)
case healthpb.HealthCheckResponse_SERVICE_UNKNOWN:
http.Error(w, fmt.Sprintf("%s %v", cfg.flServiceName, resp.String()), http.StatusNotFound)
}
}
func main() {
opts = append(opts, grpc.WithUserAgent(cfg.flUserAgent))
opts = append(opts, grpc.WithBlock())
if cfg.flGrpcTLS {
creds, err := buildGrpcCredentials()
if err != nil {
glog.Fatalf("failed to initialize tls credentials. error=%v", err)
}
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
if cfg.flRunCli {
resp, err := checkService(context.Background(), cfg.flServiceName)
if err != nil {
if pe, ok := err.(*GrpcProbeError); ok {
glog.Errorf("HealtCheck Probe Error: %v", pe.Error())
switch pe.Code {
case StatusConnectionFailure:
os.Exit(StatusConnectionFailure)
case StatusRPCFailure:
os.Exit(StatusRPCFailure)
case StatusUnimplemented:
os.Exit(StatusUnimplemented)
case StatusServiceNotFound:
os.Exit(StatusServiceNotFound)
default:
os.Exit(StatusUnhealthy)
}
}
}
if resp != healthpb.HealthCheckResponse_SERVING {
glog.Errorf("HealtCheck Probe Error: service %s failed with reason: %v", cfg.flServiceName, resp.String())
os.Exit(StatusUnhealthy)
} else {
glog.Infof("%s %v", cfg.flServiceName, resp.String())
}
} else {
tlsConfig := &tls.Config{}
if cfg.flHTTPSTLSVerifyClient {
caCert, err := os.ReadFile(cfg.flHTTPSTLSVerifyCA)
if err != nil {
glog.Fatal(err)
}
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(caCert) {
glog.Fatal("Unable to add https server root CA certs")
}
tlsConfig = &tls.Config{
ClientCAs: caCertPool,
ClientAuth: tls.RequireAndVerifyClientCert,
}
}
r := mux.NewRouter()
r.Use(prometheusMiddleware)
r.Path(cfg.flHTTPListenPath).HandlerFunc(healthHandler)
go func() {
http.Handle(cfg.flMetricsHTTPPath, promhttp.Handler())
glog.Error(http.ListenAndServe(cfg.flMetricsHTTPListenAddr, nil))
}()
srv := &http.Server{
Addr: cfg.flHTTPListenAddr,
TLSConfig: tlsConfig,
Handler: r,
}
var err error
if cfg.flHTTPSTLSServerCert != "" && cfg.flHTTPSTLSServerKey != "" {
err = srv.ListenAndServeTLS(cfg.flHTTPSTLSServerCert, cfg.flHTTPSTLSServerKey)
} else {
err = srv.ListenAndServe()
}
if err != nil {
glog.Fatalf("ListenAndServe Error: ", err)
}
}
}