-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathmain.go
186 lines (163 loc) · 6.22 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
package main
import (
"context"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"syscall"
"time"
"github.com/muxinc/certificate-expiry-monitor/monitor"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)
var (
kubeconfigPath = flag.String("kubeconfig", "", "Path to kubeconfig file if running outside the Kubernetes cluster")
kubeContext = flag.String("context", "", "The name of the kubeconfig context to use if running outside the Kubernetes cluster")
pollingFrequency = flag.Duration("frequency", time.Minute, "Frequency at which the certificate expiry times are polled")
namespaces = flag.String("namespaces", "default", "Comma-separated Kubernetes namespaces to query")
labels = flag.String("labels", "", "Label selector that identifies pods to query")
ingressNamespaces = flag.String("ingressNamespaces", "", "If provided, a comma-separated list of namespaces that will be searched for ingresses with domains to automatically query")
domains = flag.String("domains", "", "Comma-separated SNI domains to query")
ignoredDomains = flag.String("ignoredDomains", "", "Comma-separated list of domains to exclude from the discovered set. This can be a regex if the string is wrapped in forward-slashes like /.*\\.domain\\.com$/ which would exclude all domain.com subdomains.")
hostIP = flag.Bool("hostIP", false, "If true, then connect to the host that the pod is running on rather than to the pod itself.")
port = flag.Int("port", 443, "TCP port to connect to each pod on")
loglevel = flag.String("loglevel", "error", "Log-level threshold for logging messages (debug, info, warn, error, fatal, or panic)")
logFormat = flag.String("logformat", "text", "Log format (text or json)")
metricsPort = flag.Int("metricsPort", 8888, "TCP port that the Prometheus metrics listener should use")
insecureSkipVerify = flag.Bool("insecure", true, "If true, then the InsecureSkipVerify option will be used with the TLS connection, and the remote certificate and hostname will be trusted without verification")
ingressAPIVersion = flag.String("ingressAPIVersion", "extensions/v1beta1", "Version of the Ingress API to use, can be either `extensions/v1beta1` or `networking/v1`")
)
func main() {
// parse input flags
flag.Parse()
// create logging instance
logger := newLogger(*loglevel, *logFormat)
// start HTTP listener with Prometheus metrics and healthcheck endpoints
hh := &healthHandler{healthy: false}
runHTTPListener(logger, hh)
// create Kubernetes client
kubeClient, err := newClientSet(*kubeconfigPath, *kubeContext)
if err != nil {
log.Fatalf("Error creating Kubernetes client, exiting: %v", err)
}
// start monitor
monitor := &monitor.CertExpiryMonitor{
Logger: logger,
KubernetesClient: kubeClient,
PollingFrequency: *pollingFrequency,
Namespaces: strings.Split(*namespaces, ","),
Labels: *labels,
IngressNamespaces: strings.Split(*ingressNamespaces, ","),
Domains: strings.Split(*domains, ","),
IgnoredDomains: strings.Split(*ignoredDomains, ","),
HostIP: *hostIP,
Port: *port,
InsecureSkipVerify: *insecureSkipVerify,
IngressAPIVersion: *ingressAPIVersion,
}
ctx, cancel := context.WithCancel(context.Background())
wg := &sync.WaitGroup{}
wg.Add(1)
go monitor.Run(ctx, wg)
// switch to healthy
hh.healthy = true
// trap signals to terminate
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
logger.Info("Received termination signal, shutting down")
cancel()
wg.Wait()
logger.Info("Shutdown finished, exiting")
}
func runHTTPListener(logger *logrus.Logger, hh *healthHandler) {
m := http.NewServeMux()
m.Handle("/healthz", hh)
m.Handle("/metrics", promhttp.Handler())
logger.Infof("Starting Prometheus metrics endpoint on :%d", *metricsPort)
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *metricsPort))
if err != nil {
logger.Fatalf("Failed to start Prometheus metrics endpoint: %v", err)
}
go http.Serve(lis, m)
}
func newLogger(level, format string) *logrus.Logger {
var logger = logrus.New()
logger.Out = os.Stderr
switch strings.ToLower(format) {
case "text":
textFormatter := new(logrus.TextFormatter)
textFormatter.TimestampFormat = time.RFC3339Nano
logger.Formatter = textFormatter
case "json":
jsonFormatter := new(logrus.JSONFormatter)
jsonFormatter.TimestampFormat = time.RFC3339Nano
logger.Formatter = jsonFormatter
default:
log.Fatalf("Unrecognized log format, exiting: %s", format)
}
switch strings.ToLower(level) {
case "debug":
logger.Level = logrus.DebugLevel
case "info":
logger.Level = logrus.InfoLevel
case "error":
logger.Level = logrus.ErrorLevel
case "warn":
logger.Level = logrus.WarnLevel
case "fatal":
logger.Level = logrus.FatalLevel
case "panic":
logger.Level = logrus.PanicLevel
default:
log.Fatalf("Unrecognized log level, exiting: %s", level)
}
return logger
}
// Create new Kubernetes's clientSet.
// When configured env.KubeconfigPath, read config from env.KubeconfigPath.
// When not configured env.KubeconfigPath, read internal cluster config.
func newClientSet(kubeconfigPath string, kubeContext string) (*kubernetes.Clientset, error) {
var err error
var config *rest.Config
if kubeconfigPath == "" {
config, err = rest.InClusterConfig()
} else {
configOverrides := &clientcmd.ConfigOverrides{}
if kubeContext != "" {
configOverrides.CurrentContext = kubeContext
}
config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfigPath},
configOverrides).ClientConfig()
}
if err != nil {
return nil, err
}
clientSet, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
return clientSet, nil
}
type healthHandler struct {
healthy bool
}
func (hh *healthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if hh.healthy {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Healthy"))
return
}
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Unhealthy"))
}