/
prometheus.go
419 lines (371 loc) · 14.2 KB
/
prometheus.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
package prometheus
import (
"bytes"
"context"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"time"
g "github.com/onsi/ginkgo"
o "github.com/onsi/gomega"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
v1 "k8s.io/api/core/v1"
kapierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
clientset "k8s.io/client-go/kubernetes"
watchtools "k8s.io/client-go/tools/watch"
kapi "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/client/conditions"
e2e "k8s.io/kubernetes/test/e2e/framework"
exutil "github.com/openshift/origin/test/extended/util"
)
const waitForPrometheusStartSeconds = 240
var _ = g.Describe("[Feature:Prometheus][Conformance] Prometheus", func() {
defer g.GinkgoRecover()
var (
oc = exutil.NewCLIWithoutNamespace("prometheus")
url, bearerToken string
)
g.BeforeEach(func() {
var ok bool
url, bearerToken, ok = locatePrometheus(oc)
if !ok {
e2e.Skipf("Prometheus could not be located on this cluster, skipping prometheus test")
}
})
g.Describe("when installed on the cluster", func() {
g.It("should report telemetry if a cloud.openshift.com token is present", func() {
if !hasPullSecret(oc.AdminKubeClient(), "cloud.openshift.com") {
e2e.Skipf("Telemetry is disabled")
}
oc.SetupProject()
ns := oc.Namespace()
execPodName := e2e.CreateExecPodOrFail(oc.AdminKubeClient(), ns, "execpod", func(pod *v1.Pod) { pod.Spec.Containers[0].Image = "centos:7" })
defer func() { oc.AdminKubeClient().CoreV1().Pods(ns).Delete(execPodName, metav1.NewDeleteOptions(1)) }()
tests := map[string][]metricTest{
// should have successfully sent at least once to remote
`metricsclient_request_send{client="federate_to",job="telemeter-client",status_code="200"}`: {metricTest{greaterThanEqual: true, value: 1}},
// should have scraped some metrics from prometheus
`federate_samples{job="telemeter-client"}`: {metricTest{greaterThanEqual: true, value: 10}},
}
runQueries(tests, oc, ns, execPodName, url, bearerToken)
e2e.Logf("Telemetry is enabled: %s", bearerToken)
})
g.It("should start and expose a secured proxy and unsecured metrics", func() {
oc.SetupProject()
ns := oc.Namespace()
execPodName := e2e.CreateExecPodOrFail(oc.AdminKubeClient(), ns, "execpod", func(pod *v1.Pod) { pod.Spec.Containers[0].Image = "centos:7" })
defer func() { oc.AdminKubeClient().CoreV1().Pods(ns).Delete(execPodName, metav1.NewDeleteOptions(1)) }()
g.By("checking the unsecured metrics path")
var metrics map[string]*dto.MetricFamily
o.Expect(wait.PollImmediate(10*time.Second, waitForPrometheusStartSeconds*time.Second, func() (bool, error) {
results, err := getInsecureURLViaPod(ns, execPodName, fmt.Sprintf("%s/metrics", url))
if err != nil {
e2e.Logf("unable to get unsecured metrics: %v", err)
return false, nil
}
p := expfmt.TextParser{}
metrics, err = p.TextToMetricFamilies(bytes.NewBufferString(results))
o.Expect(err).NotTo(o.HaveOccurred())
// original field in 2.0.0-beta
counts := findCountersWithLabels(metrics["tsdb_samples_appended_total"], labels{})
if len(counts) != 0 && counts[0] > 0 {
return true, nil
}
// 2.0.0-rc.0
counts = findCountersWithLabels(metrics["tsdb_head_samples_appended_total"], labels{})
if len(counts) != 0 && counts[0] > 0 {
return true, nil
}
// 2.0.0-rc.2
counts = findCountersWithLabels(metrics["prometheus_tsdb_head_samples_appended_total"], labels{})
if len(counts) != 0 && counts[0] > 0 {
return true, nil
}
return false, nil
})).NotTo(o.HaveOccurred(), fmt.Sprintf("Did not find tsdb_samples_appended_total, tsdb_head_samples_appended_total, or prometheus_tsdb_head_samples_appended_total"))
g.By("verifying the oauth-proxy reports a 403 on the root URL")
err := expectURLStatusCodeExec(ns, execPodName, url, 403)
o.Expect(err).NotTo(o.HaveOccurred())
g.By("verifying a service account token is able to authenticate")
err = expectBearerTokenURLStatusCodeExec(ns, execPodName, fmt.Sprintf("%s/graph", url), bearerToken, 200)
o.Expect(err).NotTo(o.HaveOccurred())
g.By("verifying a service account token is able to access the Prometheus API")
// expect all endpoints within 60 seconds
var lastErrs []error
o.Expect(wait.PollImmediate(10*time.Second, 2*time.Minute, func() (bool, error) {
contents, err := getBearerTokenURLViaPod(ns, execPodName, fmt.Sprintf("%s/api/v1/targets", url), bearerToken)
o.Expect(err).NotTo(o.HaveOccurred())
targets := &prometheusTargets{}
err = json.Unmarshal([]byte(contents), targets)
o.Expect(err).NotTo(o.HaveOccurred())
g.By("verifying all expected jobs have a working target")
lastErrs = all(
// The OpenShift control plane
targets.Expect(labels{"job": "api"}, "up", "^https://.*/metrics$"),
targets.Expect(labels{"job": "controller-manager"}, "up", "^https://.*/metrics$"),
// The kube control plane
targets.Expect(labels{"job": "apiserver"}, "up", "^https://.*/metrics$"),
targets.Expect(labels{"job": "kube-controller-manager"}, "up", "^https://.*/metrics$"),
targets.Expect(labels{"job": "scheduler"}, "up", "^https://.*/metrics$"),
targets.Expect(labels{"job": "kube-state-metrics"}, "up", "^https://.*/metrics$"),
// TODO: should probably be https
targets.Expect(labels{"job": "cluster-version-operator"}, "up", "^http://.*/metrics$"),
targets.Expect(labels{"job": "prometheus-k8s", "namespace": "openshift-monitoring", "pod": "prometheus-k8s-0"}, "up", "^https://.*/metrics$"),
targets.Expect(labels{"job": "kubelet"}, "up", "^https://.*/metrics$"),
targets.Expect(labels{"job": "kubelet"}, "up", "^https://.*/metrics/cadvisor$"),
targets.Expect(labels{"job": "node-exporter"}, "up", "^https://.*/metrics$"),
targets.Expect(labels{"job": "prometheus-operator"}, "up", "^http://.*/metrics$"),
targets.Expect(labels{"job": "alertmanager-main"}, "up", "^https://.*/metrics$"),
targets.Expect(labels{"job": "crio"}, "up", "^http://.*/metrics$"),
targets.Expect(labels{"job": "telemeter-client"}, "up", "^https://.*/metrics$"),
)
if len(lastErrs) > 0 {
e2e.Logf("missing some targets: %v", lastErrs)
return false, nil
}
return true, nil
})).NotTo(o.HaveOccurred())
})
g.It("should have a Watchdog alert in firing state", func() {
oc.SetupProject()
ns := oc.Namespace()
execPodName := e2e.CreateExecPodOrFail(oc.AdminKubeClient(), ns, "execpod", func(pod *v1.Pod) { pod.Spec.Containers[0].Image = "centos:7" })
defer func() { oc.AdminKubeClient().CoreV1().Pods(ns).Delete(execPodName, metav1.NewDeleteOptions(1)) }()
tests := map[string][]metricTest{
// should have constantly firing a watchdog alert
`ALERTS{alertstate="firing",alertname="Watchdog"}`: {metricTest{greaterThanEqual: true, value: 1}},
// should be only one watchdog alert (this is a workaround as metricTest doesn't offer equality operator)
`ALERTS{alertstate="firing",alertname="Watchdog",severity="none"}`: {metricTest{greaterThanEqual: false, value: 2}},
}
runQueries(tests, oc, ns, execPodName, url, bearerToken)
e2e.Logf("Watchdog alert is firing: %s", bearerToken)
})
g.It("should have non-Pod host cAdvisor metrics", func() {
oc.SetupProject()
ns := oc.Namespace()
execPodName := e2e.CreateExecPodOrFail(oc.AdminKubeClient(), ns, "execpod", func(pod *v1.Pod) { pod.Spec.Containers[0].Image = "centos:7" })
defer func() { oc.AdminKubeClient().CoreV1().Pods(ns).Delete(execPodName, metav1.NewDeleteOptions(1)) }()
tests := map[string][]metricTest{
// should have constantly firing a watchdog alert
`container_cpu_usage_seconds_total{id!~"/kubepods.slice/.*"}`: {metricTest{greaterThanEqual: true, value: 1}},
}
runQueries(tests, oc, ns, execPodName, url, bearerToken)
})
})
})
func all(errs ...error) []error {
var result []error
for _, err := range errs {
if err != nil {
result = append(result, err)
}
}
return result
}
type prometheusTargets struct {
Data struct {
ActiveTargets []struct {
Labels map[string]string
Health string
ScrapeUrl string
}
}
Status string
}
func (t *prometheusTargets) Expect(l labels, health, scrapeURLPattern string) error {
for _, target := range t.Data.ActiveTargets {
match := true
for k, v := range l {
if target.Labels[k] != v {
match = false
break
}
}
if !match {
continue
}
if health != target.Health {
continue
}
if !regexp.MustCompile(scrapeURLPattern).MatchString(target.ScrapeUrl) {
continue
}
return nil
}
return fmt.Errorf("no match for %v with health %s and scrape URL %s", l, health, scrapeURLPattern)
}
type labels map[string]string
func (l labels) With(name, value string) labels {
n := make(labels)
for k, v := range l {
n[k] = v
}
n[name] = value
return n
}
func findEnvVar(vars []kapi.EnvVar, key string) string {
for _, v := range vars {
if v.Name == key {
return v.Value
}
}
return ""
}
func findMetricsWithLabels(f *dto.MetricFamily, labels map[string]string) []*dto.Metric {
var result []*dto.Metric
if f == nil {
return result
}
for _, m := range f.Metric {
matched := map[string]struct{}{}
for _, l := range m.Label {
if expect, ok := labels[l.GetName()]; ok {
if expect != l.GetValue() {
break
}
matched[l.GetName()] = struct{}{}
}
}
if len(matched) != len(labels) {
continue
}
result = append(result, m)
}
return result
}
func findCountersWithLabels(f *dto.MetricFamily, labels map[string]string) []float64 {
var result []float64
for _, m := range findMetricsWithLabels(f, labels) {
result = append(result, m.Counter.GetValue())
}
return result
}
func findGaugesWithLabels(f *dto.MetricFamily, labels map[string]string) []float64 {
var result []float64
for _, m := range findMetricsWithLabels(f, labels) {
result = append(result, m.Gauge.GetValue())
}
return result
}
func findMetricLabels(f *dto.MetricFamily, labels map[string]string, match string) []string {
var result []string
for _, m := range findMetricsWithLabels(f, labels) {
for _, l := range m.Label {
if l.GetName() == match {
result = append(result, l.GetValue())
break
}
}
}
return result
}
func expectURLStatusCodeExec(ns, execPodName, url string, statusCode int) error {
cmd := fmt.Sprintf("curl -k -s -o /dev/null -w '%%{http_code}' %q", url)
output, err := e2e.RunHostCmd(ns, execPodName, cmd)
if err != nil {
return fmt.Errorf("host command failed: %v\n%s", err, output)
}
if output != strconv.Itoa(statusCode) {
return fmt.Errorf("last response from server was not %d: %s", statusCode, output)
}
return nil
}
func expectBearerTokenURLStatusCodeExec(ns, execPodName, url, bearer string, statusCode int) error {
cmd := fmt.Sprintf("curl -k -s -H 'Authorization: Bearer %s' -o /dev/null -w '%%{http_code}' %q", bearer, url)
output, err := e2e.RunHostCmd(ns, execPodName, cmd)
if err != nil {
return fmt.Errorf("host command failed: %v\n%s", err, output)
}
if output != strconv.Itoa(statusCode) {
return fmt.Errorf("last response from server was not %d: %s", statusCode, output)
}
return nil
}
func getBearerTokenURLViaPod(ns, execPodName, url, bearer string) (string, error) {
cmd := fmt.Sprintf("curl -s -k -H 'Authorization: Bearer %s' %q", bearer, url)
output, err := e2e.RunHostCmd(ns, execPodName, cmd)
if err != nil {
return "", fmt.Errorf("host command failed: %v\n%s", err, output)
}
return output, nil
}
func getAuthenticatedURLViaPod(ns, execPodName, url, user, pass string) (string, error) {
cmd := fmt.Sprintf("curl -s -u %s:%s %q", user, pass, url)
output, err := e2e.RunHostCmd(ns, execPodName, cmd)
if err != nil {
return "", fmt.Errorf("host command failed: %v\n%s", err, output)
}
return output, nil
}
func getInsecureURLViaPod(ns, execPodName, url string) (string, error) {
cmd := fmt.Sprintf("curl -s -k %q", url)
output, err := e2e.RunHostCmd(ns, execPodName, cmd)
if err != nil {
return "", fmt.Errorf("host command failed: %v\n%s", err, output)
}
return output, nil
}
func waitForServiceAccountInNamespace(c clientset.Interface, ns, serviceAccountName string, timeout time.Duration) error {
w, err := c.CoreV1().ServiceAccounts(ns).Watch(metav1.SingleObject(metav1.ObjectMeta{Name: serviceAccountName}))
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
_, err = watchtools.UntilWithoutRetry(ctx, w, conditions.ServiceAccountHasSecrets)
return err
}
func locatePrometheus(oc *exutil.CLI) (url, bearerToken string, ok bool) {
_, err := oc.AdminKubeClient().CoreV1().Services("openshift-monitoring").Get("prometheus-k8s", metav1.GetOptions{})
if kapierrs.IsNotFound(err) {
return "", "", false
}
waitForServiceAccountInNamespace(oc.AdminKubeClient(), "openshift-monitoring", "prometheus-k8s", 2*time.Minute)
for i := 0; i < 30; i++ {
secrets, err := oc.AdminKubeClient().CoreV1().Secrets("openshift-monitoring").List(metav1.ListOptions{})
o.Expect(err).NotTo(o.HaveOccurred())
for _, secret := range secrets.Items {
if secret.Type != v1.SecretTypeServiceAccountToken {
continue
}
if !strings.HasPrefix(secret.Name, "prometheus-") {
continue
}
bearerToken = string(secret.Data[v1.ServiceAccountTokenKey])
break
}
if len(bearerToken) == 0 {
e2e.Logf("Waiting for prometheus service account secret to show up")
time.Sleep(time.Second)
continue
}
}
o.Expect(bearerToken).ToNot(o.BeEmpty())
return "https://prometheus-k8s.openshift-monitoring.svc:9091", bearerToken, true
}
func hasPullSecret(client clientset.Interface, name string) bool {
scrt, err := client.CoreV1().Secrets("openshift-config").Get("pull-secret", metav1.GetOptions{})
if err != nil {
if kapierrs.IsNotFound(err) {
return false
}
e2e.Failf("could not retrieve pull-secret: %v", err)
}
if scrt.Type != v1.SecretTypeDockerConfigJson {
e2e.Failf("error expecting secret type %s got %s", v1.SecretTypeDockerConfigJson, scrt.Type)
}
ps := struct {
Auths map[string]struct {
Auth string `json:"auth"`
} `json:"auths"`
}{}
if err := json.Unmarshal(scrt.Data[v1.DockerConfigJsonKey], &ps); err != nil {
e2e.Failf("could not unmarshal pullSecret from openshift-config/pull-secret: %v", err)
}
return len(ps.Auths[name].Auth) > 0
}