-
Notifications
You must be signed in to change notification settings - Fork 292
/
source.go
384 lines (322 loc) · 11.9 KB
/
source.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
package kubernetes
import (
"context"
_ "embed"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/sirupsen/logrus"
"golang.org/x/exp/maps"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic/dynamicinformer"
"k8s.io/client-go/tools/cache"
"github.com/kubeshop/botkube/internal/command"
"github.com/kubeshop/botkube/internal/source/kubernetes/commander"
"github.com/kubeshop/botkube/internal/source/kubernetes/config"
"github.com/kubeshop/botkube/internal/source/kubernetes/event"
"github.com/kubeshop/botkube/internal/source/kubernetes/filterengine"
"github.com/kubeshop/botkube/internal/source/kubernetes/recommendation"
"github.com/kubeshop/botkube/pkg/api"
"github.com/kubeshop/botkube/pkg/api/source"
pkgConfig "github.com/kubeshop/botkube/pkg/config"
"github.com/kubeshop/botkube/pkg/loggerx"
"github.com/kubeshop/botkube/pkg/multierror"
"github.com/kubeshop/botkube/pkg/plugin"
)
var _ source.Source = (*Source)(nil)
var (
// configJSONSchema contains duplications,
// as some UI components (e.g. https://github.com/rjsf-team/react-jsonschema-form) don't support nested defaults for definitions.
//go:embed config_schema.json
configJSONSchema string
)
const (
// PluginName is the name of the Kubernetes Botkube plugin.
PluginName = "kubernetes"
description = "Consume Kubernetes events and get notifications with additional warnings and recommendations."
componentLogFieldKey = "component"
)
type RecommendationFactory interface {
New(cfg config.Config) (recommendation.AggregatedRunner, config.Recommendations)
}
// Source Kubernetes source plugin data structure
type Source struct {
bgProcessor *backgroundProcessor
pluginVersion string
configStore *configurationStore
mu sync.Mutex
source.HandleExternalRequestUnimplemented
}
type SourceConfig struct {
name string
eventCh chan source.Event
cfg config.Config
isInteractivitySupported bool
clusterName string
kubeConfig []byte
*ActiveSourceConfig
}
type ActiveSourceConfig struct {
logger logrus.FieldLogger
messageBuilder *MessageBuilder
filterEngine *filterengine.DefaultFilterEngine
recommFactory *recommendation.Factory
}
// NewSource returns a new instance of Source.
func NewSource(version string) *Source {
return &Source{
pluginVersion: version,
configStore: newConfigurations(),
bgProcessor: newBackgroundProcessor(),
}
}
// Metadata returns metadata of Kubernetes configuration.
func (s *Source) Metadata(_ context.Context) (api.MetadataOutput, error) {
return api.MetadataOutput{
Version: s.pluginVersion,
Description: description,
DocumentationURL: "https://docs.botkube.io/configuration/source/kubernetes",
JSONSchema: api.JSONSchema{
Value: configJSONSchema,
},
Recommended: true,
}, nil
}
// Stream streams Kubernetes events.
// WARNING: This method has to be thread-safe.
func (s *Source) Stream(ctx context.Context, input source.StreamInput) (source.StreamOutput, error) {
s.mu.Lock()
defer s.mu.Unlock()
kubeConfig := input.Context.KubeConfig
if err := plugin.ValidateKubeConfigProvided(PluginName, kubeConfig); err != nil {
return source.StreamOutput{}, err
}
cfg, err := config.MergeConfigs(input.Configs)
if err != nil {
return source.StreamOutput{}, fmt.Errorf("while merging input configs: %w", err)
}
srcName := input.Context.SourceName
eventCh := make(chan source.Event)
s.configStore.Store(srcName, SourceConfig{
name: srcName,
eventCh: eventCh,
cfg: cfg,
isInteractivitySupported: input.Context.IsInteractivitySupported,
clusterName: input.Context.ClusterName,
kubeConfig: kubeConfig,
})
systemSrcCfg, ok := s.configStore.GetSystemConfig()
if !ok {
exitOnError(err, loggerx.New(pkgConfig.Logger{}).WithField("error", "global source configuration not found"))
}
id := s.configStore.Len()
globalLogger := loggerx.NewStderr(pkgConfig.Logger{
Level: systemSrcCfg.cfg.Log.Level,
}).WithField("id", id)
err = s.bgProcessor.StopAndWait(globalLogger)
loggerx.ExitOnError(err, "While stopping background processor") // this should never happen
cfgsByKubeConfig := s.configStore.CloneByKubeconfig()
globalLogger.Infof("Reconfiguring background process with %d different Kubeconfig(s)...", len(cfgsByKubeConfig))
var fns []func(context.Context)
for kubeConfig, srcCfgs := range cfgsByKubeConfig {
fn := s.genFnForKubeconfig(id, []byte(kubeConfig), globalLogger, systemSrcCfg.cfg.InformerResyncPeriod, srcCfgs)
fns = append(fns, fn)
}
s.bgProcessor.Run(ctx, fns)
return source.StreamOutput{
Event: eventCh,
}, nil
}
func (s *Source) configureProcessForSources(ctx context.Context, id int, kubeConfig []byte, globalLogger logrus.FieldLogger, informerResyncPeriod time.Duration, srcCfgs map[string]SourceConfig) error {
client, err := NewClient(kubeConfig)
if err != nil {
return fmt.Errorf("while creating Kubernetes client: %w", err)
}
for _, srcCfg := range srcCfgs {
cfg := srcCfg.cfg
logger := loggerx.NewStderr(pkgConfig.Logger{
Level: cfg.Log.Level,
}).WithField("id", id)
commandGuard := command.NewCommandGuard(logger.WithField(componentLogFieldKey, "Command Guard"), client.discoveryCli)
cmdr := commander.NewCommander(logger.WithField(componentLogFieldKey, "Commander"), commandGuard, cfg.Commands)
recommFactory := recommendation.NewFactory(logger.WithField("component", "Recommendations"), client.dynamicCli)
filterEngine := filterengine.WithAllFilters(logger, client.dynamicCli, client.mapper, cfg.Filters)
messageBuilder := NewMessageBuilder(srcCfg.isInteractivitySupported, logger.WithField(componentLogFieldKey, "Message Builder"), cmdr)
srcCfg.ActiveSourceConfig = &ActiveSourceConfig{
logger: logger,
recommFactory: recommFactory,
filterEngine: filterEngine,
messageBuilder: messageBuilder,
}
s.configStore.Store(srcCfg.name, srcCfg)
}
router := NewRouter(client.mapper, client.dynamicCli, globalLogger)
router.BuildTable(srcCfgs)
globalLogger.Info("Registering informers...")
dynamicKubeInformerFactory := dynamicinformer.NewDynamicSharedInformerFactory(client.dynamicCli, informerResyncPeriod)
err = router.RegisterInformers([]config.EventType{
config.CreateEvent,
config.UpdateEvent,
config.DeleteEvent,
}, func(resource string) (cache.SharedIndexInformer, error) {
gvr, err := parseResourceArg(resource, client.mapper)
if err != nil {
globalLogger.WithError(err).Errorf("Unable to parse resource: %s to register with informer\n", resource)
return nil, err
}
return dynamicKubeInformerFactory.ForResource(gvr).Informer(), nil
})
if err != nil {
exitOnError(err, globalLogger.WithFields(logrus.Fields{
"events": []config.EventType{
config.CreateEvent,
config.UpdateEvent,
config.DeleteEvent,
},
"error": err.Error(),
}))
}
err = router.MapWithEventsInformer(
config.ErrorEvent,
config.WarningEvent,
func(resource string) (cache.SharedIndexInformer, error) {
gvr, err := parseResourceArg(resource, client.mapper)
if err != nil {
globalLogger.WithError(err).Errorf("Unable to parse resource: %s to register with informer\n", resource)
return nil, err
}
return dynamicKubeInformerFactory.ForResource(gvr).Informer(), nil
})
if err != nil {
return fmt.Errorf("while mapping with events informer: %w", err)
}
eventTypes := []config.EventType{
config.CreateEvent,
config.DeleteEvent,
config.UpdateEvent,
}
for _, eventType := range eventTypes {
router.RegisterEventHandler(
ctx,
eventType,
s.handleEventFn(globalLogger),
)
}
router.HandleMappedEvent(
ctx,
config.ErrorEvent,
s.handleEventFn(globalLogger),
)
globalLogger.Info("Starting background process...")
stopCh := ctx.Done()
dynamicKubeInformerFactory.Start(stopCh)
<-stopCh
dynamicKubeInformerFactory.Shutdown()
globalLogger.Info("Stopped background process...")
return nil
}
func (s *Source) handleEventFn(log logrus.FieldLogger) func(ctx context.Context, e event.Event, sources, updateDiffs []string) {
globalLogger := log
return func(ctx context.Context, e event.Event, sources, updateDiffs []string) {
globalLogger.Debugf("Processing %s to %s/%v in %s namespace", e.Type, e.Resource, e.Name, e.Namespace)
// Skip older events
if !e.TimeStamp.IsZero() && e.TimeStamp.Before(s.bgProcessor.StartTime()) {
globalLogger.Debug("Skipping older event...")
return
}
if e.Kind == "" {
globalLogger.Warn("Skipping event without Kind...")
return
}
// Check for significant Update Events in objects
if e.Type == config.UpdateEvent && len(updateDiffs) > 0 {
e.Messages = append(e.Messages, updateDiffs...)
}
errs := multierror.New()
for _, sourceKey := range sources {
eventCopy := e
srcCfg, ok := s.configStore.Get(sourceKey)
if !ok {
errs = multierror.Append(errs, fmt.Errorf("source with key %q not found", sourceKey))
continue
}
if srcCfg.ActiveSourceConfig == nil {
errs = multierror.Append(errs, fmt.Errorf("ActiveSourceConfig not found for source %s. This seems to be a bug", srcCfg.name))
continue
}
eventCopy.Cluster = srcCfg.clusterName
// Filter events
e = srcCfg.filterEngine.Run(ctx, eventCopy)
if e.Skip {
srcCfg.logger.WithField("event", e).Debugf("Skipping event as skip flag is set to true")
continue
}
recRunner, recCfg := srcCfg.recommFactory.New(srcCfg.cfg)
err := recRunner.Do(ctx, &eventCopy)
if err != nil {
errs = multierror.Append(errs, fmt.Errorf("while running recommendation: %w", err))
continue
}
if recommendation.ShouldIgnoreEvent(&recCfg, eventCopy) {
srcCfg.logger.Debugf("Skipping event as it is related to recommendation informers and doesn't have any recommendations: %#v", e)
continue
}
msg, err := srcCfg.messageBuilder.FromEvent(eventCopy, srcCfg.cfg.ExtraButtons)
if err != nil {
errs = multierror.Append(errs, fmt.Errorf("while building message from event: %w", err))
continue
}
message := source.Event{
Message: msg,
RawObject: eventCopy,
AnalyticsLabels: event.AnonymizedEventDetailsFrom(eventCopy),
}
srcCfg.eventCh <- message
}
if errs.ErrorOrNil() != nil {
globalLogger.WithError(errs).Errorf("failed to send event for '%s/%s' resource", e.Namespace, e.Name)
}
}
}
func (s *Source) genFnForKubeconfig(id int, kubeConfig []byte, globalLogger logrus.FieldLogger, informerResyncPeriod time.Duration, srcCfgs map[string]SourceConfig) func(ctx context.Context) {
return func(ctx context.Context) {
err := s.configureProcessForSources(ctx, id, kubeConfig, globalLogger, informerResyncPeriod, srcCfgs)
if err != nil {
exitOnError(fmt.Errorf("while configuring process for sources"), globalLogger.WithError(err).WithField("srcCfgs", maps.Keys(srcCfgs)))
}
}
}
func parseResourceArg(arg string, mapper meta.RESTMapper) (schema.GroupVersionResource, error) {
gvr, err := strToGVR(arg)
if err != nil {
return schema.GroupVersionResource{}, fmt.Errorf("while converting string to GroupVersionReference: %w", err)
}
// Validate the GVR provided
if _, err := mapper.ResourcesFor(gvr); err != nil {
return schema.GroupVersionResource{}, err
}
return gvr, nil
}
func strToGVR(arg string) (schema.GroupVersionResource, error) {
const separator = "/"
gvrStrParts := strings.Split(arg, separator)
switch len(gvrStrParts) {
case 2:
return schema.GroupVersionResource{Group: "", Version: gvrStrParts[0], Resource: gvrStrParts[1]}, nil
case 3:
return schema.GroupVersionResource{Group: gvrStrParts[0], Version: gvrStrParts[1], Resource: gvrStrParts[2]}, nil
default:
return schema.GroupVersionResource{}, fmt.Errorf("invalid string: expected 2 or 3 parts when split by %q", separator)
}
}
func exitOnError(err error, log logrus.FieldLogger) {
if err != nil {
log.Error(err)
// Error message is not propagated to Botkube core without this wait.
time.Sleep(time.Second * 2)
os.Exit(1)
}
}