blob: 10280e0d88e91b5f141e4c820c0e0f5c4a53dc56 [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package audit
18
19import (
20 "fmt"
21
22 "github.com/golang/glog"
23 "github.com/prometheus/client_golang/prometheus"
24 auditinternal "k8s.io/apiserver/pkg/apis/audit"
25)
26
27const (
28 subsystem = "apiserver_audit"
29)
30
31var (
32 eventCounter = prometheus.NewCounter(
33 prometheus.CounterOpts{
34 Subsystem: subsystem,
35 Name: "event_total",
36 Help: "Counter of audit events generated and sent to the audit backend.",
37 })
38 errorCounter = prometheus.NewCounterVec(
39 prometheus.CounterOpts{
40 Subsystem: subsystem,
41 Name: "error_total",
42 Help: "Counter of audit events that failed to be audited properly. " +
43 "Plugin identifies the plugin affected by the error.",
44 },
45 []string{"plugin"},
46 )
47 levelCounter = prometheus.NewCounterVec(
48 prometheus.CounterOpts{
49 Subsystem: subsystem,
50 Name: "level_total",
51 Help: "Counter of policy levels for audit events (1 per request).",
52 },
53 []string{"level"},
54 )
55)
56
57func init() {
58 prometheus.MustRegister(eventCounter)
59 prometheus.MustRegister(errorCounter)
60 prometheus.MustRegister(levelCounter)
61}
62
63// ObserveEvent updates the relevant prometheus metrics for the generated audit event.
64func ObserveEvent() {
65 eventCounter.Inc()
66}
67
68// ObservePolicyLevel updates the relevant prometheus metrics with the audit level for a request.
69func ObservePolicyLevel(level auditinternal.Level) {
70 levelCounter.WithLabelValues(string(level)).Inc()
71}
72
73// HandlePluginError handles an error that occurred in an audit plugin. This method should only be
74// used if the error may have prevented the audit event from being properly recorded. The events are
75// logged to the debug log.
76func HandlePluginError(plugin string, err error, impacted ...*auditinternal.Event) {
77 // Count the error.
78 errorCounter.WithLabelValues(plugin).Add(float64(len(impacted)))
79
80 // Log the audit events to the debug log.
81 msg := fmt.Sprintf("Error in audit plugin '%s' affecting %d audit events: %v\nImpacted events:\n",
82 plugin, len(impacted), err)
83 for _, ev := range impacted {
84 msg = msg + EventString(ev) + "\n"
85 }
86 glog.Error(msg)
87}