-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
195 lines (173 loc) · 6.06 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
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
compute "cloud.google.com/go/compute/apiv1"
md "cloud.google.com/go/compute/metadata"
"github.com/gorilla/websocket"
"github.com/m-lab/go/flagx"
"github.com/m-lab/go/memoryless"
"github.com/m-lab/go/prometheusx"
"github.com/m-lab/go/rtx"
v2 "github.com/m-lab/locate/api/v2"
"github.com/m-lab/locate/cmd/heartbeat/health"
"github.com/m-lab/locate/cmd/heartbeat/metadata"
"github.com/m-lab/locate/cmd/heartbeat/registration"
"github.com/m-lab/locate/connection"
"github.com/m-lab/locate/metrics"
"github.com/m-lab/locate/static"
)
var (
heartbeatURL string
hostname string
hostnameFile flagx.FileBytes
experiment string
pod string
node string
namespace string
kubernetesAuth = "/var/run/secrets/kubernetes.io/serviceaccount/"
kubernetesURL = flagx.URL{}
registrationURL = flagx.URL{}
services = flagx.KeyValueArray{}
heartbeatPeriod = static.HeartbeatPeriod
mainCtx, mainCancel = context.WithCancel(context.Background())
lbPath = "/metadata/loadbalanced"
)
// Checker generates a health score for the heartbeat instance (0, 1).
type Checker interface {
GetHealth(ctx context.Context) float64 // Health score.
}
func init() {
flag.StringVar(&heartbeatURL, "heartbeat-url", "ws://localhost:8080/v2/platform/heartbeat",
"URL for locate service")
flag.StringVar(&hostname, "hostname", "", "The service hostname (takes precedence over -hostname-file)")
flag.Var(&hostnameFile, "hostname-file", "A file containing the service hostname")
flag.StringVar(&experiment, "experiment", "", "Experiment name")
flag.StringVar(&pod, "pod", "", "Kubernetes pod name")
flag.StringVar(&node, "node", "", "Kubernetes node name")
flag.StringVar(&namespace, "namespace", "", "Kubernetes namespace")
flag.Var(&kubernetesURL, "kubernetes-url", "URL for Kubernetes API")
flag.Var(®istrationURL, "registration-url", "URL for site registration")
flag.Var(&services, "services", "Maps experiment target names to their set of services")
}
func main() {
flag.Parse()
rtx.Must(flagx.ArgsFromEnvWithLog(flag.CommandLine, false), "failed to read args from env")
// If -hostname-file was set, use it instead of -hostname.
if hostnameFile.String() != "" {
hostname = hostnameFile.String()
}
// Start metrics server.
prom := prometheusx.MustServeMetrics()
defer prom.Close()
// Load registration data.
ldrConfig := memoryless.Config{
Min: static.RegistrationLoadMin,
Expected: static.RegistrationLoadExpected,
Max: static.RegistrationLoadMax,
}
svcs := services.Get()
ldr, err := registration.NewLoader(mainCtx, registrationURL.URL, hostname, experiment, svcs, ldrConfig)
rtx.Must(err, "could not initialize registration loader")
r, err := ldr.GetRegistration(mainCtx)
rtx.Must(err, "could not load registration data")
hbm := v2.HeartbeatMessage{Registration: r}
// Establish a connection.
conn := connection.NewConn()
err = conn.Dial(heartbeatURL, http.Header{}, hbm)
rtx.Must(err, "failed to establish a websocket connection with %s", heartbeatURL)
_, lberr := os.ReadFile(lbPath)
probe := health.NewPortProbe(svcs)
ec := health.NewEndpointClient(static.HealthEndpointTimeout)
var hc Checker
// If the "loadbalanced" file exists, then the instance is a load balanced VM.
// If not, then it is a standalone instance.
if lberr == nil {
gcpmd, err := metadata.NewGCPMetadata(md.NewClient(http.DefaultClient), hostname)
rtx.Must(err, "failed to get VM metadata")
gceClient, err := compute.NewRegionBackendServicesRESTClient(mainCtx)
rtx.Must(err, "failed to create GCE client")
hc = health.NewGCPChecker(gceClient, gcpmd)
} else if kubernetesURL.URL == nil {
hc = health.NewChecker(probe, ec)
} else {
k8s := health.MustNewKubernetesClient(kubernetesURL.URL, pod, node, namespace, kubernetesAuth)
hc = health.NewCheckerK8S(probe, k8s, ec)
}
write(conn, hc, ldr)
}
// write starts a write loop to send health messages every
// HeartbeatPeriod.
func write(ws *connection.Conn, hc Checker, ldr *registration.Loader) {
defer ws.Close()
hbTicker := *time.NewTicker(heartbeatPeriod)
defer hbTicker.Stop()
// Register the channel to receive SIGTERM events.
sigterm := make(chan os.Signal, 1)
defer close(sigterm)
signal.Notify(sigterm, syscall.SIGTERM)
defer ldr.Ticker.Stop()
for {
select {
case <-mainCtx.Done():
log.Println("context cancelled")
sendExitMessage(ws)
return
case <-sigterm:
log.Println("received SIGTERM")
sendExitMessage(ws)
mainCancel()
return
case <-ldr.Ticker.C:
reg, err := ldr.GetRegistration(mainCtx)
if err != nil {
log.Printf("could not load registration data, err: %v", err)
}
if reg != nil {
sendMessage(ws, v2.HeartbeatMessage{Registration: reg}, "registration")
log.Printf("updated registration to %v", reg)
}
case <-hbTicker.C:
t := time.Now()
score := getHealth(hc)
healthMsg := v2.Health{Score: score}
hbm := v2.HeartbeatMessage{Health: &healthMsg}
sendMessage(ws, hbm, "health")
// Record duration metric.
fmtScore := fmt.Sprintf("%.1f", score)
metrics.HealthTransmissionDuration.WithLabelValues(fmtScore).Observe(time.Since(t).Seconds())
}
}
}
func getHealth(hc Checker) float64 {
ctx, cancel := context.WithTimeout(mainCtx, heartbeatPeriod)
defer cancel()
return hc.GetHealth(ctx)
}
func sendMessage(ws *connection.Conn, hbm v2.HeartbeatMessage, msgType string) {
// If a new registration message was found, update the websocket's dial message.
// The message is sent whenever the connection is restarted (i.e., once per hour in App Engine).
if msgType == "registration" {
ws.DialMessage = hbm
}
err := ws.WriteMessage(websocket.TextMessage, hbm)
if err != nil {
log.Printf("failed to write %s message, err: %v", msgType, err)
}
}
func sendExitMessage(ws *connection.Conn) {
// Notify the receiver that the health score should now be 0.
hbm := v2.HeartbeatMessage{
Health: &v2.Health{
Score: 0,
},
}
sendMessage(ws, hbm, "final health")
}