-
Notifications
You must be signed in to change notification settings - Fork 27
/
main.go
154 lines (126 loc) · 4.96 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
package main
import (
"errors"
"flag"
"fmt"
"net/http"
"regexp"
"strings"
"time"
"github.com/flant/k8s-image-availability-exporter/pkg/cli"
"github.com/flant/k8s-image-availability-exporter/pkg/handlers"
"github.com/flant/k8s-image-availability-exporter/pkg/logging"
"github.com/flant/k8s-image-availability-exporter/pkg/registry"
"github.com/flant/k8s-image-availability-exporter/pkg/version"
"github.com/google/go-containerregistry/pkg/name"
"github.com/sirupsen/logrus"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/sample-controller/pkg/signals"
_ "sigs.k8s.io/controller-runtime/pkg/metrics"
)
func main() {
cp := newCaPaths()
mirrors := newMirrorMap()
forceCheckDisabledControllerKindsParser := cli.NewForceCheckDisabledControllerKindsParser()
imageCheckInterval := flag.Duration("check-interval", time.Minute, "image re-check interval")
ignoredImagesStr := flag.String("ignored-images", "", "tilde-separated image regexes to ignore, each image will be checked against this list of regexes")
bindAddr := flag.String("bind-address", ":8080", "address:port to bind /metrics endpoint to")
namespaceLabels := flag.String("namespace-label", "", "namespace label for checks")
insecureSkipVerify := flag.Bool("skip-registry-cert-verification", false, "whether to skip registries' certificate verification")
plainHTTP := flag.Bool("allow-plain-http", false, "whether to fallback to HTTP scheme for registries that don't support HTTPS") // named after the ctr cli flag
defaultRegistry := flag.String("default-registry", "", fmt.Sprintf("default registry to use in absence of a fully qualified image name, defaults to %q", name.DefaultRegistry))
flag.Var(&cp, "capath", "path to a file that contains CA certificates in the PEM format") // named after the curl cli flag
flag.Var(&mirrors, "image-mirror", "Add a mirror repository (format: original=mirror)")
flag.Func("force-check-disabled-controllers", `comma-separated list of controller kinds for which image is forcibly checked, even when workloads are disabled or suspended. Acceptable values include "Deployment", "StatefulSet", "DaemonSet", "Cronjob" or "*" for all kinds (this option is case-insensitive)`, forceCheckDisabledControllerKindsParser.Parse)
flag.Parse()
logrus.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
})
logrus.AddHook(logging.NewPrometheusHook())
logrus.Infof("Starting k8s-image-availability-exporter %s", version.Version)
// set up signals, so we handle the first shutdown signal gracefully
stopCh := signals.SetupSignalHandler()
cfg, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{}).ClientConfig()
if err != nil {
logrus.Fatalf("Couldn't get Kubernetes default config: %s", err)
}
kubeClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
logrus.Fatalf("Error building kubernetes clientset: %s", err.Error())
}
liveTicksCounter := prometheus.NewCounter(
prometheus.CounterOpts{
Namespace: "k8s_image_availability_exporter",
Name: "completed_rechecks_total",
Help: "Number of image rechecks completed.",
},
)
prometheus.MustRegister(liveTicksCounter)
var regexes []regexp.Regexp
if *ignoredImagesStr != "" {
regexStrings := strings.Split(*ignoredImagesStr, "~")
for _, regexStr := range regexStrings {
regexes = append(regexes, *regexp.MustCompile(regexStr))
}
}
registryChecker := registry.NewChecker(
stopCh.Done(),
kubeClient,
*insecureSkipVerify,
*plainHTTP,
cp,
forceCheckDisabledControllerKindsParser.ParsedKinds,
regexes,
*defaultRegistry,
*namespaceLabels,
mirrors,
)
prometheus.MustRegister(registryChecker)
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/healthz", handlers.Healthz)
go func() {
logrus.Fatal(http.ListenAndServe(*bindAddr, nil))
}()
handlers.UpdateHealth(true)
wait.Until(func() {
registryChecker.Tick()
liveTicksCounter.Inc()
}, *imageCheckInterval, stopCh.Done())
}
/* Custom flag types */
var (
_ flag.Value = (*caPaths)(nil)
_ flag.Value = (*mirrorMap)(nil)
)
// caPaths is a custom flag type for a list of paths to CA certificates
type caPaths []string
func newCaPaths() caPaths {
return caPaths{}
}
func (c *caPaths) String() string {
return fmt.Sprintf("%v", *c)
}
func (c *caPaths) Set(value string) error {
*c = append(*c, value)
return nil
}
// mirrorMap is a custom flag type for a map of original to mirror repository names
type mirrorMap map[string]string
func newMirrorMap() mirrorMap {
return make(mirrorMap)
}
func (m *mirrorMap) String() string {
return fmt.Sprintf("%v", *m)
}
func (m *mirrorMap) Set(value string) error {
result := strings.Split(value, "=")
if len(result) != 2 {
return errors.New("invalid format for mirror, must be original=mirror")
}
(*m)[result[0]] = result[1]
return nil
}