forked from containerd/nri
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnri-differ.go
438 lines (354 loc) · 11.2 KB
/
nri-differ.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
/*
Copyright The containerd Authors.
Licensed 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 main
import (
"container/list"
"context"
"flag"
"fmt"
"os"
"strconv"
"strings"
"sync"
"github.com/r3labs/diff/v3"
"github.com/sirupsen/logrus"
"github.com/sters/yaml-diff/yamldiff"
"sigs.k8s.io/yaml"
"github.com/containerd/nri/pkg/api"
"github.com/containerd/nri/pkg/stub"
)
type config struct {
Indices string `json:"indices"`
LogFile string `json:"logFile"`
VerboseLevel int `json:"verboseLevel"`
Yaml bool `json:"yaml"`
}
type pluginIndex struct {
prevIndex int
nextIndex int
prevValues *list.List // Contains changedValue list from previous index
}
type changedValue struct {
podSet bool
pod api.PodSandbox
containerSet bool
container api.Container
}
type plugin struct {
stub stub.Stub
mask stub.EventMask
name string
idx int
}
var (
cfg config
log *logrus.Logger
indices map[int]pluginIndex
)
func (p *plugin) Configure(_ context.Context, nriCfg string) (stub.EventMask, error) {
log.Infof("got configuration data: %q", nriCfg)
if nriCfg == "" {
return p.mask, nil
}
oldCfg := cfg
err := yaml.Unmarshal([]byte(nriCfg), &cfg)
if err != nil {
return 0, fmt.Errorf("failed to parse provided configuration: %w", err)
}
p.mask, err = api.ParseEventMask("all")
if err != nil {
return 0, fmt.Errorf("failed to parse events in configuration: %w", err)
}
if cfg.LogFile != oldCfg.LogFile {
f, err := os.OpenFile(cfg.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Errorf("failed to open log file %q: %v", cfg.LogFile, err)
return 0, fmt.Errorf("failed to open log file %q: %w", cfg.LogFile, err)
}
log.SetOutput(f)
}
return p.mask, nil
}
func setValue(newValue *changedValue, pod *api.PodSandbox, container *api.Container) {
if pod != nil {
newValue.podSet = true
newValue.pod = *pod
}
if container != nil {
newValue.containerSet = true
newValue.container = *container
}
}
func (p *plugin) saveValue(pod *api.PodSandbox, container *api.Container) {
newValue := &changedValue{}
setValue(newValue, pod, container)
indices[p.idx].prevValues.PushBack(newValue)
}
func (p *plugin) differ(apifunc string, pod *api.PodSandbox, container *api.Container) {
// If we are the first plugin, then no need to diff
if indices[p.idx].prevIndex < 0 {
if cfg.VerboseLevel > 0 {
if container != nil {
p.dump(apifunc, "pod", pod, "container", container)
} else {
p.dump(apifunc, "pod", pod)
}
}
p.saveValue(pod, container)
} else {
element := indices[indices[p.idx].prevIndex].prevValues.Front()
initialValue := element.Value.(*changedValue)
indices[indices[p.idx].prevIndex].prevValues.Remove(element)
if pod != nil {
if initialValue.podSet {
podChanged := *pod
if cfg.Yaml {
p.printYamlDiff(apifunc, "pod", initialValue.pod, podChanged)
} else {
changelog, err := diff.Diff(initialValue.pod, podChanged)
if err != nil {
log.Errorf("%v", err)
return
}
p.printDiff(apifunc, &changelog, "pod", initialValue.pod, podChanged)
}
}
}
if container != nil {
if initialValue.containerSet {
containerChanged := *container
if cfg.Yaml {
p.printYamlDiff(apifunc, "container", initialValue.container, containerChanged)
} else {
changelog, err := diff.Diff(initialValue.container, containerChanged)
if err != nil {
log.Errorf("%v", err)
return
}
p.printDiff(apifunc, &changelog, "container", initialValue.container, containerChanged)
}
}
}
// Push to next index so it can diff things too
if indices[p.idx].nextIndex > 0 {
p.saveValue(pod, container)
}
}
}
func (p *plugin) Synchronize(_ context.Context, pods []*api.PodSandbox, containers []*api.Container) ([]*api.ContainerUpdate, error) {
if cfg.VerboseLevel > 2 {
p.dump("Synchronize", "pods", pods, "containers", containers)
}
return nil, nil
}
func (p *plugin) Shutdown(_ context.Context) {
p.dump("Shutdown")
}
func (p *plugin) RunPodSandbox(_ context.Context, pod *api.PodSandbox) error {
p.differ("RunPodSandbox", pod, nil)
return nil
}
func (p *plugin) StopPodSandbox(_ context.Context, pod *api.PodSandbox) error {
p.differ("StopPodSandbox", pod, nil)
return nil
}
func (p *plugin) RemovePodSandbox(_ context.Context, pod *api.PodSandbox) error {
p.differ("RemovePodSandbox", pod, nil)
return nil
}
func (p *plugin) CreateContainer(_ context.Context, pod *api.PodSandbox, container *api.Container) (*api.ContainerAdjustment, []*api.ContainerUpdate, error) {
p.differ("CreateContainer", pod, container)
adjust := &api.ContainerAdjustment{}
return adjust, nil, nil
}
func (p *plugin) PostCreateContainer(_ context.Context, pod *api.PodSandbox, container *api.Container) error {
p.differ("PostCreateContainer", pod, container)
return nil
}
func (p *plugin) StartContainer(_ context.Context, pod *api.PodSandbox, container *api.Container) error {
p.differ("StartContainer", pod, container)
return nil
}
func (p *plugin) PostStartContainer(_ context.Context, pod *api.PodSandbox, container *api.Container) error {
p.differ("PostStartContainer", pod, container)
return nil
}
func (p *plugin) UpdateContainer(_ context.Context, pod *api.PodSandbox, container *api.Container, r *api.LinuxResources) ([]*api.ContainerUpdate, error) {
p.differ("UpdateContainer", pod, container)
return nil, nil
}
func (p *plugin) PostUpdateContainer(_ context.Context, pod *api.PodSandbox, container *api.Container) error {
p.differ("PostUpdateContainer", pod, container)
return nil
}
func (p *plugin) StopContainer(_ context.Context, pod *api.PodSandbox, container *api.Container) ([]*api.ContainerUpdate, error) {
p.differ("StopContainer", pod, container)
return nil, nil
}
func (p *plugin) RemoveContainer(_ context.Context, pod *api.PodSandbox, container *api.Container) error {
p.differ("RemoveContainer", pod, container)
return nil
}
func (p *plugin) onClose() {
log.Infof("stopped")
os.Exit(0)
}
// Dump one or more objects, with an optional global prefix and per-object tags.
func (p *plugin) dump(args ...interface{}) {
var (
prefix string
idx int
)
if len(args)&0x1 == 1 {
prefix = args[0].(string)
idx++
}
for ; idx < len(args)-1; idx += 2 {
tag, obj := args[idx], args[idx+1]
msg, err := yaml.Marshal(obj)
if err != nil {
log.Infof("%s: %s: failed to dump object: %v", prefix, tag, err)
continue
}
if prefix != "" {
log.Infof("%s %s: %s:", p.name, prefix, tag)
for _, line := range strings.Split(strings.TrimSpace(string(msg)), "\n") {
log.Infof("%s %s: %s", p.name, prefix, line)
}
} else {
log.Infof("%s %s:", p.name, tag)
for _, line := range strings.Split(strings.TrimSpace(string(msg)), "\n") {
log.Infof("%s %s", p.name, line)
}
}
}
}
func (p *plugin) printDiff(apifunc string, changelog *diff.Changelog, obj string, origValue interface{}, changedValue interface{}) {
if cfg.VerboseLevel > 1 {
log.Infof("[%d] Original values for %s", p.idx, obj)
p.dump(apifunc, obj, origValue)
}
if len(*changelog) == 0 {
log.Infof("[%d] %s: %s: %s", p.idx, apifunc, obj, "<no changes>")
return
}
for _, item := range *changelog {
log.Infof("[%d] %s: %s: %s: %v: From: %v -> To: %v", p.idx, apifunc, obj, item.Type, item.Path, item.From, item.To)
}
if cfg.VerboseLevel > 1 {
log.Infof("[%d] Values after changes for %s", p.idx, obj)
p.dump(apifunc, obj, changedValue)
}
}
func (p *plugin) printYamlDiff(apifunc string, obj string, origValue interface{}, changedValue interface{}) {
msg, err := yaml.Marshal(origValue)
if err != nil {
return
}
yamlOrig := yamldiff.Load(string(msg[:]))
msg, err = yaml.Marshal(changedValue)
if err != nil {
return
}
yamlChanged := yamldiff.Load(string(msg[:]))
for _, diff := range yamldiff.Do(yamlOrig, yamlChanged) {
if diff.Status == yamldiff.DiffStatusSame {
log.Infof("[%d] %s: %s: %s", p.idx, apifunc, obj, "<no changes>")
break
}
log.Infof("[%d] %s: %s: %v", p.idx, apifunc, obj, diff.Diff)
}
}
func startPlugin(wg *sync.WaitGroup, pluginName string, pluginIdx int) {
var (
opts []stub.Option
err error
)
defer wg.Done()
idxStr := fmt.Sprintf("%02d", pluginIdx)
if pluginName != "" {
opts = append(opts, stub.WithPluginName(pluginName))
}
if idxStr != "" {
opts = append(opts, stub.WithPluginIdx(idxStr))
}
p := &plugin{}
if p.mask, err = api.ParseEventMask("all"); err != nil {
log.Fatalf("Failed to parse events: %v", err)
}
p.name = fmt.Sprintf("[%s]", idxStr)
p.idx = pluginIdx
if p.stub, err = stub.New(p, append(opts, stub.WithOnClose(p.onClose))...); err != nil {
log.Fatalf("Failed to create plugin stub: %v", err)
}
err = p.stub.Run(context.Background())
if err != nil {
log.Errorf("Plugin exited with error %v", err)
os.Exit(1)
}
}
func main() {
log = logrus.StandardLogger()
log.SetFormatter(&logrus.TextFormatter{
PadLevelText: true,
})
flag.StringVar(&cfg.LogFile, "log-file", "", "logfile name, if logging to a file")
flag.IntVar(&cfg.VerboseLevel, "verbose-level", 0,
"Print extra information,\n"+
"level 0 (default) prints only the changes done by plugins,\n"+
"level 1 prints original data for the first invocation of this plugin,\n"+
"level 2 prints original and changed data together with the difference,\n"+
"level 3 prints all the data received (prints lot of data).")
flag.StringVar(&cfg.Indices, "indices", "0,99",
"Comma separated list of indices where to install the differ plugin to monitor the changes.\n"+
"Example: \"-indices 45,50,80\" will print the changes generated by plugins in\n"+
"indices 45, 50 and 80. Note that this plugin will install itself to index 0 and 99\n"+
"if this parameter is not given.")
flag.BoolVar(&cfg.Yaml, "yaml", false, "Print the diff in yaml")
flag.Parse()
if cfg.LogFile != "" {
f, err := os.OpenFile(cfg.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatalf("failed to open log file %q: %v", cfg.LogFile, err)
}
log.SetOutput(f)
}
wg := new(sync.WaitGroup)
indexCount := strings.Count(cfg.Indices, ",")
if indexCount == 0 {
log.Fatalf("There must be at least two index given.")
return
}
indices = make(map[int]pluginIndex)
prevIndex := -1
for _, idxStr := range strings.Split(cfg.Indices, ",") {
idx, _ := strconv.Atoi(idxStr)
entry := indices[idx]
entry.prevIndex = prevIndex
entry.prevValues = list.New()
indices[idx] = entry
if prevIndex >= 0 {
if prevEntry, ok := indices[prevIndex]; ok {
prevEntry.nextIndex = idx
indices[prevIndex] = prevEntry
}
}
prevIndex = idx
wg.Add(1)
go startPlugin(wg, "Differ", idx)
}
entry := indices[prevIndex]
entry.nextIndex = -1
indices[prevIndex] = entry
wg.Wait()
}