-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhealthz.go
68 lines (58 loc) · 1.68 KB
/
healthz.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
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
kmsapi "k8s.io/kms/apis/v2" // The Kubernetes KMS API
)
type HealthCheckService struct {
path string
port int
pluginUnixPath string
timeout time.Duration
}
func (h *HealthCheckService) Start() chan error {
host := fmt.Sprintf("0.0.0.0:%d", *healthzPort)
errorCh := make(chan error)
mux := http.NewServeMux()
mux.HandleFunc(h.path, h.HandlerFunc)
log.Println("Starting up health check server...")
go func() {
defer close(errorCh)
select {
case errorCh <- http.ListenAndServe(host, mux):
default:
}
}()
return errorCh
}
func (h *HealthCheckService) HandlerFunc(w http.ResponseWriter, r *http.Request) {
_, cancel := context.WithTimeout(r.Context(), h.timeout)
defer cancel()
conn, err := grpc.NewClient(fmt.Sprintf("unix://%s", h.pluginUnixPath), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
defer conn.Close()
client := kmsapi.NewKeyManagementServiceClient(conn)
status, err := client.Status(context.Background(), &kmsapi.StatusRequest{})
if err != nil {
log.Printf("Health check failed: %v", err)
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
log.Printf("Health check: %+v", status)
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}
func NewHealthCheckService(path string, port int, timeout time.Duration, pluginUnixPath string) *HealthCheckService {
return &HealthCheckService{
path: path,
port: port,
timeout: timeout,
pluginUnixPath: pluginUnixPath,
}
}