/
main.go
222 lines (196 loc) · 6.63 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
/******************************************************************************
*
* Copyright 2020 SAP SE
*
* 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 healthmonitorcmd
import (
"bytes"
"context"
"encoding/json"
"net/http"
"strings"
"sync"
"time"
"github.com/docker/distribution/manifest/schema2"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sapcc/go-bits/httpext"
"github.com/sapcc/go-bits/logg"
"github.com/sapcc/go-bits/must"
"github.com/spf13/cobra"
"github.com/sapcc/keppel/internal/client"
"github.com/sapcc/keppel/internal/keppel"
"github.com/sapcc/keppel/internal/models"
)
var longDesc = strings.TrimSpace(`
Monitors the health of a Keppel instance. This sets up a Keppel account with
the given name containing a single image, and pulls the image at regular
intervals. The health check result will be published as a Prometheus metric.
The environment variables must contain credentials for authenticating with the
authentication method used by the target Keppel API.
`)
var listenAddress string
var healthmonitorResultGauge = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "keppel_healthmonitor_result",
Help: "Result from the keppel healthmonitor check.",
},
)
// AddCommandTo mounts this command into the command hierarchy.
func AddCommandTo(parent *cobra.Command) {
cmd := &cobra.Command{
Use: "healthmonitor <account>",
Short: "Monitors the health of a Keppel instance.",
Long: longDesc,
Args: cobra.ExactArgs(1),
Run: run,
}
cmd.PersistentFlags().StringVarP(&listenAddress, "listen", "l", ":8080", "Listen address for Prometheus metrics endpoint")
parent.AddCommand(cmd)
}
type healthMonitorJob struct {
AuthDriver client.AuthDriver
AccountName string
RepoClient *client.RepoClient
LastResultLock *sync.RWMutex
LastResult *bool // nil during initialization, non-nil indicates result of last healthcheck
}
func run(cmd *cobra.Command, args []string) {
keppel.SetTaskName("health-monitor")
prometheus.MustRegister(healthmonitorResultGauge)
ad, err := client.NewAuthDriver()
if err != nil {
logg.Fatal("while setting up auth driver: %s", err.Error())
}
apiUser, apiPassword := ad.CredentialsForRegistryAPI()
job := &healthMonitorJob{
AuthDriver: ad,
AccountName: args[0],
RepoClient: &client.RepoClient{
Scheme: ad.ServerScheme(),
Host: ad.ServerHost(),
RepoName: args[0] + "/healthcheck",
UserName: apiUser,
Password: apiPassword,
},
LastResultLock: &sync.RWMutex{},
}
ctx := httpext.ContextWithSIGINT(context.Background(), 1*time.Second)
// run one-time preparations
err = job.PrepareKeppelAccount(ctx)
if err != nil {
logg.Fatal("while preparing Keppel account: %s", err.Error())
}
manifestRef, err := job.UploadImage(ctx)
if err != nil {
logg.Fatal("while uploading test image: %s", err.Error())
}
// expose metrics endpoint
mux := http.NewServeMux()
mux.HandleFunc("/healthcheck", job.ReportHealthcheckResult)
mux.Handle("/metrics", promhttp.Handler())
go func() {
must.Succeed(httpext.ListenAndServeContext(ctx, listenAddress, mux))
}()
// enter long-running check loop
job.ValidateImage(ctx, manifestRef) // once immediately to initialize the metric
tick := time.Tick(30 * time.Second)
for {
select {
case <-ctx.Done():
return
case <-tick:
job.ValidateImage(ctx, manifestRef)
}
}
}
// Creates the Keppel account for this job if it does not exist yet.
func (j *healthMonitorJob) PrepareKeppelAccount(ctx context.Context) error {
reqBody := map[string]any{
"account": map[string]any{
"auth_tenant_id": j.AuthDriver.CurrentAuthTenantID(),
// anonymous pull access is needed for `keppel server anycastmonitor`
"rbac_policies": []map[string]any{{
"match_repository": "healthcheck",
"permissions": []string{"anonymous_pull"},
}},
},
}
reqBodyBytes, _ := json.Marshal(reqBody)
req, err := http.NewRequestWithContext(ctx, http.MethodPut, "/keppel/v1/accounts/"+j.AccountName, bytes.NewReader(reqBodyBytes))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := j.AuthDriver.SendHTTPRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
// Uploads a minimal complete image (one config blob, one layer blob and one manifest) for testing.
func (j *healthMonitorJob) UploadImage(ctx context.Context) (models.ManifestReference, error) {
_, err := j.RepoClient.UploadMonolithicBlob(ctx, []byte(minimalImageConfiguration))
if err != nil {
return models.ManifestReference{}, err
}
_, err = j.RepoClient.UploadMonolithicBlob(ctx, minimalImageLayer())
if err != nil {
return models.ManifestReference{}, err
}
digest, err := j.RepoClient.UploadManifest(ctx, []byte(minimalManifest), schema2.MediaTypeManifest, "latest")
return models.ManifestReference{Digest: digest}, err
}
// Validates the uploaded image and emits the keppel_healthmonitor_result metric accordingly.
func (j *healthMonitorJob) ValidateImage(ctx context.Context, manifestRef models.ManifestReference) {
err := j.RepoClient.ValidateManifest(ctx, manifestRef, nil, nil)
if err == nil {
j.recordHealthcheckResult(true)
} else {
j.recordHealthcheckResult(false)
imageRef := models.ImageReference{
Host: j.RepoClient.Host,
RepoName: j.RepoClient.RepoName,
Reference: manifestRef,
}
logg.Error("validation of %s failed: %s", imageRef, err.Error())
}
}
func (j *healthMonitorJob) recordHealthcheckResult(ok bool) {
if ok {
healthmonitorResultGauge.Set(1)
} else {
healthmonitorResultGauge.Set(0)
}
j.LastResultLock.Lock()
j.LastResult = &ok
j.LastResultLock.Unlock()
}
// Provides the GET /healthcheck endpoint.
func (j *healthMonitorJob) ReportHealthcheckResult(w http.ResponseWriter, r *http.Request) {
j.LastResultLock.RLock()
lastResult := j.LastResult
j.LastResultLock.RUnlock()
switch {
case lastResult == nil:
http.Error(w, "still starting up", http.StatusServiceUnavailable)
case *lastResult:
w.WriteHeader(http.StatusNoContent)
default:
http.Error(w, "healthcheck failed", http.StatusInternalServerError)
}
}