-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
event.go
196 lines (172 loc) · 5.92 KB
/
event.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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package event
import (
"fmt"
"time"
"github.com/elastic/beats/v7/libbeat/common"
"github.com/elastic/beats/v7/libbeat/common/kubernetes"
"github.com/elastic/beats/v7/libbeat/common/safemapstr"
"github.com/elastic/beats/v7/metricbeat/mb"
)
// init registers the MetricSet with the central registry.
// The New method will be called after the setup of the module and before starting to fetch data
func init() {
if err := mb.Registry.AddMetricSet("kubernetes", "event", New); err != nil {
panic(err)
}
}
// MetricSet type defines all fields of the MetricSet
// The event MetricSet listens to events from Kubernetes API server and streams them to the output.
// MetricSet implements the mb.PushMetricSet interface, and therefore does not rely on polling.
type MetricSet struct {
mb.BaseMetricSet
watcher kubernetes.Watcher
watchOptions kubernetes.WatchOptions
dedotConfig dedotConfig
}
// dedotConfig defines LabelsDedot and AnnotationsDedot.
// If set to true, replace dots in labels with `_`.
// Default to be true.
type dedotConfig struct {
LabelsDedot bool `config:"labels.dedot"`
AnnotationsDedot bool `config:"annotations.dedot"`
}
// New create a new instance of the MetricSet
// Part of new is also setting up the configuration by processing additional
// configuration entries if needed.
func New(base mb.BaseMetricSet) (mb.MetricSet, error) {
config := defaultKubernetesEventsConfig()
err := base.Module().UnpackConfig(&config)
if err != nil {
return nil, fmt.Errorf("fail to unpack the kubernetes event configuration: %s", err)
}
client, err := kubernetes.GetKubernetesClient(config.KubeConfig)
if err != nil {
return nil, fmt.Errorf("fail to get kubernetes client: %s", err.Error())
}
watchOptions := kubernetes.WatchOptions{
SyncTimeout: config.SyncPeriod,
Namespace: config.Namespace,
}
watcher, err := kubernetes.NewWatcher(client, &kubernetes.Event{}, watchOptions, nil)
if err != nil {
return nil, fmt.Errorf("fail to init kubernetes watcher: %s", err.Error())
}
dedotConfig := dedotConfig{
LabelsDedot: config.LabelsDedot,
AnnotationsDedot: config.AnnotationsDedot,
}
return &MetricSet{
BaseMetricSet: base,
dedotConfig: dedotConfig,
watcher: watcher,
watchOptions: watchOptions,
}, nil
}
// Run method provides the Kubernetes event watcher with a reporter with which events can be reported.
func (m *MetricSet) Run(reporter mb.PushReporter) {
now := time.Now()
handler := kubernetes.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
reporter.Event(generateMapStrFromEvent(obj.(*kubernetes.Event), m.dedotConfig))
},
UpdateFunc: func(obj interface{}) {
reporter.Event(generateMapStrFromEvent(obj.(*kubernetes.Event), m.dedotConfig))
},
// ignore events that are deleted
DeleteFunc: nil,
}
m.watcher.AddEventHandler(kubernetes.FilteringResourceEventHandler{
// skip events happened before watch
FilterFunc: func(obj interface{}) bool {
eve := obj.(*kubernetes.Event)
if kubernetes.Time(&eve.LastTimestamp).Before(now) {
return false
}
return true
},
Handler: handler,
})
// start event watcher
m.watcher.Start()
<-reporter.Done()
m.watcher.Stop()
return
}
func generateMapStrFromEvent(eve *kubernetes.Event, dedotConfig dedotConfig) common.MapStr {
eventMeta := common.MapStr{
"timestamp": common.MapStr{
"created": kubernetes.Time(&eve.ObjectMeta.CreationTimestamp).UTC(),
},
"name": eve.ObjectMeta.GetName(),
"namespace": eve.ObjectMeta.GetNamespace(),
"self_link": eve.ObjectMeta.GetSelfLink(),
"generate_name": eve.ObjectMeta.GetGenerateName(),
"uid": eve.ObjectMeta.GetUID(),
"resource_version": eve.ObjectMeta.GetResourceVersion(),
}
if len(eve.ObjectMeta.Labels) != 0 {
labels := make(common.MapStr, len(eve.ObjectMeta.Labels))
for k, v := range eve.ObjectMeta.Labels {
if dedotConfig.LabelsDedot {
label := common.DeDot(k)
labels.Put(label, v)
} else {
safemapstr.Put(labels, k, v)
}
}
eventMeta["labels"] = labels
}
if len(eve.ObjectMeta.Annotations) != 0 {
annotations := make(common.MapStr, len(eve.ObjectMeta.Annotations))
for k, v := range eve.ObjectMeta.Annotations {
if dedotConfig.AnnotationsDedot {
annotation := common.DeDot(k)
annotations.Put(annotation, v)
} else {
safemapstr.Put(annotations, k, v)
}
}
eventMeta["annotations"] = annotations
}
output := common.MapStr{
"message": eve.Message,
"reason": eve.Reason,
"type": eve.Type,
"count": eve.Count,
"source": common.MapStr{
"host": eve.Source.Host,
"component": eve.Source.Component,
},
"involved_object": common.MapStr{
"api_version": eve.InvolvedObject.APIVersion,
"resource_version": eve.InvolvedObject.ResourceVersion,
"name": eve.InvolvedObject.Name,
"kind": eve.InvolvedObject.Kind,
"uid": eve.InvolvedObject.UID,
},
"metadata": eventMeta,
}
tsMap := make(common.MapStr)
tsMap["first_occurrence"] = kubernetes.Time(&eve.FirstTimestamp).UTC()
tsMap["last_occurrence"] = kubernetes.Time(&eve.LastTimestamp).UTC()
if len(tsMap) != 0 {
output["timestamp"] = tsMap
}
return output
}