-
Notifications
You must be signed in to change notification settings - Fork 8
/
credhub_exporter.go
242 lines (202 loc) · 7.99 KB
/
credhub_exporter.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
package main
import (
"code.cloudfoundry.org/credhub-cli/credhub"
"code.cloudfoundry.org/credhub-cli/credhub/auth"
"encoding/json"
"github.com/alecthomas/kingpin/v2"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/version"
log "github.com/sirupsen/logrus"
"net/http"
"os"
"regexp"
)
var (
apiURL = kingpin.Flag(
"credhub.api-url", "Credhub API URL ($CREDHUB_EXPORTER_API_URL)",
).Envar("CREDHUB_EXPORTER_API_URL").Required().String()
clientID = kingpin.Flag(
"credhub.client-id", "Credhub Client ID ($CREDHUB_EXPORTER_CLIENT_ID)",
).Envar("CREDHUB_EXPORTER_CLIENT_ID").String()
clientSecret = kingpin.Flag(
"credhub.client-secret", "Credhub Client Secret ($CREDHUB_EXPORTER_CLIENT_SECRET)",
).Envar("CREDHUB_EXPORTER_CLIENT_SECRET").Required().String()
caCertPath = kingpin.Flag(
"credhub.ca-certs-path", "Credhub Client CA certificates path ($CREDHUB_EXPORTER_CA_CERTS_PATH)",
).Envar("CREDHUB_EXPORTER_CA_CERTS_PATH").String()
credhubProxy = kingpin.Flag(
"credhub.proxy", "Credhub Client Secret ($CREDHUB_EXPORTER_CLIENT_SECRET)",
).Envar("CREDHUB_EXPORTER_PROXY").Default("").String()
filterNameLike = kingpin.Flag(
"filters.name-like", "Fetch credentials whose name contains the query string (fetch all credentials when empty)",
).Envar("CREDHUB_EXPORTER_FILTER_NAMELIKE").Default("").String()
filterPath = kingpin.Flag(
"filters.path", "Fetch credentials that exist under the provided path (ignored when --filters.name-like is not empty)",
).Envar("CREDHUB_EXPORTER_FILTER_PATH").Default("").String()
genericCertificateFilter = kingpin.Flag(
"filters.generic-certificates", "Json list of <regexp> to match generic credentials paths that may contains certificates",
).Envar("CREDHUB_EXPORTER_GENERIC_CERTIFICATES").Default("[]").String()
metricsNamespace = kingpin.Flag(
"metrics.namespace", "Metrics Namespace ($CREDHUB_EXPORTER_METRICS_NAMESPACE)",
).Envar("CREDHUB_EXPORTER_METRICS_NAMESPACE").Default("credhub").String()
metricsEnvironment = kingpin.Flag(
"metrics.environment", "Credhub environment label to be attached to metrics ($CREDHUB_EXPORTER_METRICS_ENVIRONMENT)",
).Envar("CREDHUB_EXPORTER_METRICS_ENVIRONMENT").Required().String()
metricsDeployment = kingpin.Flag(
"metrics.deployment-name", "Credhub Bosh Deployment Name to be reported as the deployment metric label ($CREDHUB_EXPORTER_METRICS_DEPLOYMENT)",
).Envar("CREDHUB_EXPORTER_METRICS_DEPLOYMENT").Required().String()
metricsUpdateInterval = kingpin.Flag(
"metrics.udpate-interval", "Metrics update interval given as golang duration format ($CREDHUB_EXPORTER_METRICS_UPDATE_INTERVAL)",
).Envar("CREDHUB_EXPORTER_METRICS_UPDATE_INTERVAL").Default("6h").Duration()
skipSSLValidation = kingpin.Flag(
"skip-ssl-verify", "Disable SSL Verify ($CREDHUB_EXPORTER_SKIP_SSL_VERIFY)",
).Envar("CREDHUB_EXPORTER_SKIP_SSL_VERIFY").Default("false").Bool()
listenAddress = kingpin.Flag(
"web.listen-address", "Address to listen on for web interface and telemetry ($CREDHUB_EXPORTER_WEB_LISTEN_ADDRESS)",
).Envar("CREDHUB_EXPORTER_WEB_LISTEN_ADDRESS").Default(":9358").String()
metricsPath = kingpin.Flag(
"web.telemetry-path", "Path under which to expose Prometheus metrics ($CREDHUB_EXPORTER_WEB_TELEMETRY_PATH)",
).Envar("CREDHUB_EXPORTER_WEB_TELEMETRY_PATH").Default("/metrics").String()
authUsername = kingpin.Flag(
"web.auth.username", "Username for web interface basic auth ($CREDHUB_EXPORTER_WEB_AUTH_USERNAME)",
).Envar("CREDHUB_EXPORTER_WEB_AUTH_USERNAME").String()
authPassword = kingpin.Flag(
"web.auth.password", "Password for web interface basic auth ($CREDHUB_EXPORTER_WEB_AUTH_PASSWORD)",
).Envar("CREDHUB_EXPORTER_WEB_AUTH_PASSWORD").String()
tlsCertFile = kingpin.Flag(
"web.tls.cert_file", "Path to a file that contains the TLS certificate (PEM format). If the certificate is signed by a certificate authority, the file should be the concatenation of the server's certificate, any intermediates, and the CA's certificate ($CREDHUB_EXPORTER_WEB_TLS_CERTFILE)",
).Envar("CREDHUB_EXPORTER_WEB_TLS_KEYFILE").ExistingFile()
tlsKeyFile = kingpin.Flag(
"web.tls.key_file", "Path to a file that contains the TLS private key (PEM format) ($CREDHUB_EXPORTER_WEB_TLS_KEYFILE)",
).Envar("CREDHUB_EXPORTER_WEB_TLS_KEYFILE").ExistingFile()
logLevel = kingpin.Flag(
"log.level", "Only log messages with the given severity or above. Valid levels: [debug, info, warn, error, fatal]",
).Default("info").String()
logStream = kingpin.Flag(
"log.stream", "Write log to given stream. Valid streams: [stdout, stderr]",
).Default("stderr").String()
logJson = kingpin.Flag(
"log.json", "When given, write log in json format",
).Bool()
)
type basicAuthHandler struct {
handler http.HandlerFunc
username string
password string
}
func (h *basicAuthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
username, password, ok := r.BasicAuth()
if !ok || username != h.username || password != h.password {
log.Errorf("Invalid HTTP auth from `%s`", r.RemoteAddr)
w.Header().Set("WWW-Authenticate", "Basic realm=\"metrics\"")
http.Error(w, "Invalid username or password", http.StatusUnauthorized)
return
}
h.handler(w, r)
}
func prometheusHandler() http.Handler {
handler := promhttp.Handler()
if *authUsername != "" && *authPassword != "" {
handler = &basicAuthHandler{
handler: promhttp.Handler().ServeHTTP,
username: *authUsername,
password: *authPassword,
}
}
return handler
}
var (
credentialMetrics *prometheus.GaugeVec
certificateExpiresMetrics *prometheus.GaugeVec
)
func main() {
kingpin.Version(version.Print("credhub_exporter"))
kingpin.HelpFlag.Short('h')
kingpin.Parse()
log.SetLevel(log.ErrorLevel)
if lvl, err := log.ParseLevel(*logLevel); err == nil {
log.SetLevel(lvl)
}
log.SetOutput(os.Stderr)
if *logStream == "stdout" {
log.SetOutput(os.Stdout)
}
if *logJson {
log.SetFormatter(&log.JSONFormatter{})
}
log.Infoln("Starting credhub_exporter", version.Info())
log.Infoln("Build context", version.BuildContext())
if len(*credhubProxy) != 0 {
_ = os.Setenv("CREDHUB_PROXY", *credhubProxy)
}
credhubCli, err := credhub.New(*apiURL,
credhub.SkipTLSValidation(*skipSSLValidation),
credhub.Auth(auth.Uaa(
*clientID,
*clientSecret,
"",
"",
"",
"",
true,
)))
if err != nil {
log.Errorf("Error creating Credhub client: %s", err.Error())
os.Exit(1)
}
if len(*caCertPath) != 0 {
b, err := os.ReadFile(*caCertPath)
if err != nil {
log.Errorf("unable to read file '%s' : %s", *caCertPath, err.Error())
os.Exit(1)
}
credhub.CaCerts(string(b))(credhubCli)
}
regexps := []string{}
if err = json.Unmarshal([]byte(*genericCertificateFilter), ®exps); err != nil {
log.Errorf("invalid json in --filters.generic-certificates parameter : %s", err.Error())
os.Exit(1)
}
filters := []*regexp.Regexp{}
for _, r := range regexps {
exp, err := regexp.Compile(r)
if err != nil {
log.Errorf("could not compile given regexp '%s' : %s", r, err.Error())
os.Exit(1)
}
filters = append(filters, exp)
}
credhubCollector := NewCredhubCollector(
*metricsDeployment,
*metricsEnvironment,
filters,
credhubCli,
)
credhubCollector.filterNameLike(*filterNameLike)
credhubCollector.filterPath(*filterPath)
credhubCollector.run(*metricsUpdateInterval)
http.Handle(*metricsPath, prometheusHandler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`
<html>
<head>
<title>Credhub Exporter</title>
</head>
<body>
<h1>Credhub Exporter</h1>
<p><a href='` + *metricsPath + `'>Metrics</a></p>
</body>
</html>`))
})
if *tlsCertFile != "" && *tlsKeyFile != "" {
log.Infoln("Listening TLS on", *listenAddress)
log.Fatal(http.ListenAndServeTLS(*listenAddress, *tlsCertFile, *tlsKeyFile, nil))
} else {
log.Infoln("Listening on", *listenAddress)
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}
}
// Local Variables:
// ispell-local-dictionary: "american"
// End: