forked from quay/registry-monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonitor.go
596 lines (490 loc) · 13.9 KB
/
monitor.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/coreos/pkg/flagutil"
"github.com/fsouza/go-dockerclient"
"github.com/prometheus/client_golang/prometheus"
log "github.com/sirupsen/logrus"
)
var listen = flag.String("listen", ":8000", "")
var level = flag.String("loglevel", "info", "default log level: debug, info, warn, error, fatal, panic")
var dockerUsername = flag.String("username", "", "Registry username for pulling and pushing")
var dockerPassword = flag.String("password", "", "Registry password for pulling and pushing")
var registryHost = flag.String("registry-host", "", "Hostname of the registry being monitored")
var repository = flag.String("repository", "", "Repository on the registry to pull and push")
var baseImage = flag.String("base-image", "", "Repository to use as base image for push image; instead of base-layer-id")
var publicBase = flag.Bool("public-base", false, "Is the base image public or private (default: false)")
var baseLayer = flag.String("base-layer-id", "", "Docker V1 ID of the base layer in the repository; instead of base-image")
var testInterval = flag.String("run-test-every", "2m", "the time between test in minutes")
var (
base string
dockerClient *docker.Client
healthy bool
status bool
)
var (
promNamespace = os.Getenv("PROMETHEUS_NAMESPACE")
promSuccessMetric = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: promNamespace,
Subsystem: "",
Name: "monitor_success",
Help: "The registry monitor successfully completed a pull and push operation",
}, []string{})
promFailureMetric = prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: promNamespace,
Subsystem: "",
Name: "monitor_failure",
Help: "The registry monitor failed to complete a pull and push operation",
}, []string{})
promPushMetric = prometheus.NewSummary(prometheus.SummaryOpts{
Namespace: promNamespace,
Subsystem: "",
Name: "monitor_push",
Help: "The time for the monitor push operation",
})
promPullMetric = prometheus.NewSummary(prometheus.SummaryOpts{
Namespace: promNamespace,
Subsystem: "",
Name: "monitor_pull",
Help: "The time for the monitor pull operation",
})
)
var prometheusMetrics = []prometheus.Collector{promSuccessMetric, promFailureMetric, promPullMetric, promPushMetric}
type LoggingWriter struct{}
func (w *LoggingWriter) Write(p []byte) (n int, err error) {
s := string(p)
log.Infof("%s", s)
return len(s), nil
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
if !healthy {
w.WriteHeader(503)
}
fmt.Fprintf(w, "%t", healthy)
}
func statusHandler(w http.ResponseWriter, r *http.Request) {
if !status {
w.WriteHeader(400)
}
fmt.Fprintf(w, "%t", status)
}
func buildTLSTransport(basePath string) (*http.Transport, error) {
roots := x509.NewCertPool()
pemData, err := ioutil.ReadFile(filepath.Join(basePath, "ca.pem"))
if err != nil {
return nil, err
}
// Add the certification to the pool.
roots.AppendCertsFromPEM(pemData)
// Create the certificate.
crt, err := tls.LoadX509KeyPair(filepath.Join(basePath, "/cert.pem"), filepath.Join(basePath, "/key.pem"))
if err != nil {
return nil, err
}
// Create the new tls configuration using both the authority and certificate.
conf := &tls.Config{
RootCAs: roots,
Certificates: []tls.Certificate{crt},
}
// Create our own transport and return it.
return &http.Transport{
TLSClientConfig: conf,
}, nil
}
func newDockerClient(dockerHost string) (*docker.Client, error) {
if os.Getenv("DOCKER_CERT_PATH") == "" {
return docker.NewClient(dockerHost)
}
cert_path := os.Getenv("DOCKER_CERT_PATH")
ca := fmt.Sprintf("%s/ca.pem", cert_path)
cert := fmt.Sprintf("%s/cert.pem", cert_path)
key := fmt.Sprintf("%s/key.pem", cert_path)
return docker.NewTLSClient(dockerHost, cert, key, ca)
}
func stringInSlice(value string, list []string) bool {
for _, current := range list {
if current == value {
return true
}
}
return false
}
func verifyDockerClient(dockerClient *docker.Client) bool {
log.Infof("Trying to connect to Docker client")
if err := dockerClient.Ping(); err != nil {
log.Errorf("Error connecting to Docker client: %s", err)
healthy = false
return false
}
log.Infof("Docker client valid")
return true
}
func clearAllContainers(dockerClient *docker.Client) bool {
listOptions := docker.ListContainersOptions{
All: true,
}
log.Infof("Listing all containers")
containers, err := dockerClient.ListContainers(listOptions)
if err != nil {
log.Errorf("Error listing containers: %s", err)
healthy = false
return false
}
for _, container := range containers {
if stringInSlice("monitor", container.Names) {
continue
}
log.Infof("Removing container: %s", container.ID)
removeOptions := docker.RemoveContainerOptions{
ID: container.ID,
RemoveVolumes: true,
Force: true,
}
if err = dockerClient.RemoveContainer(removeOptions); err != nil {
log.Errorf("Error removing container: %s", err)
healthy = false
return false
}
}
return healthy
}
func clearAllImages(dockerClient *docker.Client) bool {
// Note: We delete in a loop like this because deleting one
// image can lead to others being deleted. Therefore, we just
// loop until the images list are empty.
skipImages := map[string]bool{}
for {
// List all Docker images.
listOptions := docker.ListImagesOptions{
All: true,
}
log.Infof("Listing docker images")
images, err := dockerClient.ListImages(listOptions)
if err != nil {
log.Errorf("Could not list images: %s", err)
healthy = false
return false
}
// Determine if we need to remove any images.
imagesFound := false
for _, image := range images {
if _, toSkip := skipImages[image.ID]; toSkip {
continue
}
imagesFound = true
}
if !imagesFound {
return healthy
}
// Remove images.
removedImages := false
for _, image := range images[:1] {
if _, toSkip := skipImages[image.ID]; toSkip {
continue
}
log.Infof("Clearing image %s", image.ID)
if err = dockerClient.RemoveImage(image.ID); err != nil {
if strings.ToLower(os.Getenv("UNDER_DOCKER")) != "true" {
log.Errorf("%s", err)
healthy = false
return false
} else {
log.Warningf("Skipping deleting image %v", image.ID)
skipImages[image.ID] = true
continue
}
}
removedImages = true
}
if !removedImages {
break
}
}
return true
}
func pullTestImage(dockerClient *docker.Client) bool {
pullOptions := docker.PullImageOptions{
Repository: *repository,
Registry: "quay.io",
Tag: "latest",
OutputStream: &LoggingWriter{},
}
pullAuth := docker.AuthConfiguration{
Username: *dockerUsername,
Password: *dockerPassword,
}
if err := dockerClient.PullImage(pullOptions, pullAuth); err != nil {
log.Errorf("Pull Error: %s", err)
status = false
return false
}
return true
}
func pullBaseImage(dockerClient *docker.Client) bool {
pullOptions := docker.PullImageOptions{
Repository: *baseImage,
Tag: "latest",
OutputStream: &LoggingWriter{},
}
var pullAuth docker.AuthConfiguration
if *publicBase {
pullAuth = docker.AuthConfiguration{}
} else {
pullAuth = docker.AuthConfiguration{
Username: *dockerUsername,
Password: *dockerPassword,
}
}
if err := dockerClient.PullImage(pullOptions, pullAuth); err != nil {
log.Errorf("Pull Error: %s", err)
status = false
return false
}
return true
}
func deleteTopLayer(dockerClient *docker.Client) bool {
imageHistory, err := dockerClient.ImageHistory(*repository)
if err != nil && err.Error() != "no such image" {
log.Errorf("%s", err)
healthy = false
return false
}
for _, image := range imageHistory {
if stringInSlice("latest", image.Tags) {
log.Infof("Deleting image %s", image.ID)
if err = dockerClient.RemoveImage(image.ID); err != nil {
log.Errorf("%s", err)
healthy = false
return false
}
break
}
}
return healthy
}
func createTagLayer(dockerClient *docker.Client) bool {
t := time.Now().Local()
timestamp := t.Format("2006-01-02 15:04:05 -0700")
config := &docker.Config{
Image: base,
Cmd: []string{"sh", "echo", "\"" + timestamp + "\" > foo"},
}
container_name := fmt.Sprintf("updatedcontainer%v", time.Now().Unix())
log.Infof("Creating new image via container %v", container_name)
options := docker.CreateContainerOptions{
Name: container_name,
Config: config,
}
if _, err := dockerClient.CreateContainer(options); err != nil {
log.Errorf("Error creating container: %s", err)
healthy = false
return false
}
commitOptions := docker.CommitContainerOptions{
Container: container_name,
Repository: *repository,
Tag: "latest",
Message: "Updated at " + timestamp,
}
if _, err := dockerClient.CommitContainer(commitOptions); err != nil {
log.Errorf("Error committing Container: %s", err)
healthy = false
return false
}
log.Infof("Removing container: %s", container_name)
removeOptions := docker.RemoveContainerOptions{
ID: container_name,
RemoveVolumes: true,
Force: true,
}
if err := dockerClient.RemoveContainer(removeOptions); err != nil {
log.Errorf("Error removing container: %s", err)
healthy = false
return false
}
return healthy
}
func pushTestImage(dockerClient *docker.Client) bool {
pushOptions := docker.PushImageOptions{
Name: *repository,
Registry: *registryHost,
Tag: "latest",
OutputStream: &LoggingWriter{},
}
pushAuth := docker.AuthConfiguration{
Username: *dockerUsername,
Password: *dockerPassword,
}
if err := dockerClient.PushImage(pushOptions, pushAuth); err != nil {
log.Errorf("Push Error: %s", err)
status = false
return false
}
status = true
return true
}
func main() {
// Parse the command line flags.
if err := flag.CommandLine.Parse(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
if err := flagutil.SetFlagsFromEnv(flag.CommandLine, "REGISTRY_MONITOR"); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
lvl, err := log.ParseLevel(*level)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
log.SetLevel(lvl)
// Ensure we have proper values.
if *dockerUsername == "" {
log.Fatalln("Missing username flag")
}
if *dockerPassword == "" {
log.Fatalln("Missing password flag")
}
if *registryHost == "" {
log.Fatalln("Missing registry-host flag")
}
if *repository == "" {
log.Fatalln("Missing repository flag")
}
if *baseImage == "" && *baseLayer == "" {
log.Infof("Missing base-image and base-layer-id flag; Dynamically assinging base-layer-id")
grabID, err := dockerClient.ImageHistory(*repository)
if err != nil {
log.Fatalln("Failed grab image ID: %v", err)
}
log.Infof("Assigning base-layer-id to %s", grabID[0])
*baseLayer = grabID[0].ID
} else if *baseImage != "" && *baseLayer != "" {
log.Fatalln("Both base-image and base-layer-id flag; only one of required")
}
// Register the metrics.
for _, metric := range prometheusMetrics {
err := prometheus.Register(metric)
if err != nil {
log.Fatalf("Failed to register metric: %v", err)
}
}
// Setup the HTTP server.
http.Handle("/metrics", prometheus.Handler())
http.HandleFunc("/health", healthHandler)
http.HandleFunc("/status", statusHandler)
log.Infoln("Listening on", *listen)
// Run the monitor routine.
runMonitor()
// Listen and serve.
log.Fatal(http.ListenAndServe(*listen, nil))
}
func runMonitor() {
dockerHost := os.Getenv("DOCKER_HOST")
if dockerHost == "" {
dockerHost = "unix:///var/run/docker.sock"
}
firstLoop := true
healthy = true
mainLoop := func() {
duration, err := time.ParseDuration(*testInterval)
if err != nil {
log.Fatalf("Failed to parse time interval: %v", err)
}
for {
if !firstLoop {
log.Infof("Sleeping for %v", duration)
time.Sleep(duration)
}
log.Infof("Starting test")
firstLoop = false
status = true
if dockerClient == nil || !verifyDockerClient(dockerClient) {
log.Infof("Trying docker host: %s", dockerHost)
dockerClient, err = newDockerClient(dockerHost)
if err != nil {
log.Errorf("%s", err)
healthy = false
return
}
}
if !verifyDockerClient(dockerClient) {
return
}
if strings.ToLower(os.Getenv("UNDER_DOCKER")) != "true" {
log.Infof("Clearing all containers")
if !clearAllContainers(dockerClient) {
return
}
}
log.Infof("Clearing all images")
if !clearAllImages(dockerClient) {
return
}
log.Infof("Pulling test image")
pullStartTime := time.Now()
if !pullTestImage(dockerClient) {
duration = 30 * time.Second
// Write the failure metric.
m, err := promFailureMetric.GetMetricWithLabelValues()
if err != nil {
panic(err)
}
m.Inc()
continue
}
// Write the pull time metric.
promPullMetric.Observe(time.Since(pullStartTime).Seconds())
if *baseImage != "" {
log.Infof("Pulling specified base image")
if !pullBaseImage(dockerClient) {
return
}
base = *baseImage
} else {
base = *baseLayer
}
log.Infof("Deleting top layer")
if !deleteTopLayer(dockerClient) {
return
}
log.Infof("Creating new top layer")
if !createTagLayer(dockerClient) {
return
}
log.Infof("Pushing test image")
pushStartTime := time.Now()
if !pushTestImage(dockerClient) {
duration = 30 * time.Second
// Write the failure metric.
m, err := promFailureMetric.GetMetricWithLabelValues()
if err != nil {
panic(err)
}
m.Inc()
continue
}
// Write the push time metric.
promPushMetric.Observe(time.Since(pushStartTime).Seconds())
log.Infof("Test successful")
duration = 2 * time.Minute
// Write the success metric.
m, err := promSuccessMetric.GetMetricWithLabelValues()
if err != nil {
panic(err)
}
m.Inc()
}
}
go mainLoop()
}