blob: 80b4842fd2973aa6e7e66add3ab008ac0fbe5d98 [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
17// Package webhook implements the audit.Backend interface using HTTP webhooks.
18package webhook
19
20import (
21 "time"
22
23 "k8s.io/apimachinery/pkg/runtime/schema"
24 auditinternal "k8s.io/apiserver/pkg/apis/audit"
25 "k8s.io/apiserver/pkg/apis/audit/install"
26 "k8s.io/apiserver/pkg/audit"
27 "k8s.io/apiserver/pkg/util/webhook"
28 "k8s.io/client-go/rest"
29)
30
31const (
32 // PluginName is the name of this plugin, to be used in help and logs.
33 PluginName = "webhook"
34
35 // DefaultInitialBackoff is the default amount of time to wait before
36 // retrying sending audit events through a webhook.
37 DefaultInitialBackoff = 10 * time.Second
38)
39
40func init() {
41 install.Install(audit.Scheme)
42}
43
44func loadWebhook(configFile string, groupVersion schema.GroupVersion, initialBackoff time.Duration) (*webhook.GenericWebhook, error) {
45 return webhook.NewGenericWebhook(audit.Scheme, audit.Codecs, configFile,
46 []schema.GroupVersion{groupVersion}, initialBackoff)
47}
48
49type backend struct {
50 w *webhook.GenericWebhook
51}
52
53// NewBackend returns an audit backend that sends events over HTTP to an external service.
54func NewBackend(kubeConfigFile string, groupVersion schema.GroupVersion, initialBackoff time.Duration) (audit.Backend, error) {
55 w, err := loadWebhook(kubeConfigFile, groupVersion, initialBackoff)
56 if err != nil {
57 return nil, err
58 }
59 return &backend{w}, nil
60}
61
62func (b *backend) Run(stopCh <-chan struct{}) error {
63 return nil
64}
65
66func (b *backend) Shutdown() {
67 // nothing to do here
68}
69
70func (b *backend) ProcessEvents(ev ...*auditinternal.Event) {
71 if err := b.processEvents(ev...); err != nil {
72 audit.HandlePluginError(PluginName, err, ev...)
73 }
74}
75
76func (b *backend) processEvents(ev ...*auditinternal.Event) error {
77 var list auditinternal.EventList
78 for _, e := range ev {
79 list.Items = append(list.Items, *e)
80 }
81 return b.w.WithExponentialBackoff(func() rest.Result {
82 return b.w.RestClient.Post().Body(&list).Do()
83 }).Error()
84}
85
86func (b *backend) String() string {
87 return PluginName
88}