-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathbasic.go
1113 lines (918 loc) · 33.8 KB
/
basic.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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package modules
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/deckhouse/deckhouse/pkg/log"
"github.com/gofrs/uuid/v5"
"github.com/hashicorp/go-multierror"
"github.com/kennygrant/sanitize"
"github.com/flant/addon-operator/pkg/app"
"github.com/flant/addon-operator/pkg/hook/types"
"github.com/flant/addon-operator/pkg/module_manager/models/hooks"
"github.com/flant/addon-operator/pkg/module_manager/models/hooks/kind"
"github.com/flant/addon-operator/pkg/utils"
"github.com/flant/addon-operator/pkg/values/validation"
"github.com/flant/addon-operator/sdk"
shapp "github.com/flant/shell-operator/pkg/app"
"github.com/flant/shell-operator/pkg/executor"
bindingcontext "github.com/flant/shell-operator/pkg/hook/binding_context"
sh_op_types "github.com/flant/shell-operator/pkg/hook/types"
utils_file "github.com/flant/shell-operator/pkg/utils/file"
"github.com/flant/shell-operator/pkg/utils/measure"
)
// BasicModule is a basic representation of the Module, which addon-operator works with
// any Module has the next parameters:
// - name of the module
// - order of the module execution
// - path of the module on a filesystem
// - values storage - config and calculated values for the module
// - hooks of the module
// - current module state
type BasicModule struct {
// required
Name string
// required
Order uint32
// required
Path string
crdsExist bool
crdFilesPaths []string
valuesStorage *ValuesStorage
state *moduleState
hooks *HooksStorage
// dependency
dc *hooks.HookExecutionDependencyContainer
keepTemporaryHookFiles bool
logger *log.Logger
}
// TODO: add options WithLogger
// NewBasicModule creates new BasicModule
// staticValues - are values from modules/values.yaml and /modules/<module-name>/values.yaml, they could not be changed during the runtime
func NewBasicModule(name, path string, order uint32, staticValues utils.Values, configBytes, valuesBytes []byte, logger *log.Logger) (*BasicModule, error) {
valuesStorage, err := NewValuesStorage(name, staticValues, configBytes, valuesBytes)
if err != nil {
return nil, fmt.Errorf("new values storage: %w", err)
}
crdsFromPath := getCRDsFromPath(path, app.CRDsFilters)
return &BasicModule{
Name: name,
Order: order,
Path: path,
crdsExist: len(crdsFromPath) > 0,
crdFilesPaths: crdsFromPath,
valuesStorage: valuesStorage,
state: &moduleState{
Phase: Startup,
hookErrors: make(map[string]error),
synchronizationState: NewSynchronizationState(),
},
hooks: newHooksStorage(),
keepTemporaryHookFiles: shapp.DebugKeepTmpFiles,
logger: logger,
}, nil
}
// getCRDsFromPath scan path/crds directory and store yaml file in slice
// if file name do not start with `_` or `doc-` prefix
func getCRDsFromPath(path string, crdsFilters string) []string {
var crdFilesPaths []string
err := filepath.Walk(
filepath.Join(path, "crds"),
func(path string, _ os.FileInfo, err error) error {
if err != nil {
return err
}
if !matchPrefix(path, crdsFilters) && filepath.Ext(path) == ".yaml" {
crdFilesPaths = append(crdFilesPaths, path)
}
return nil
})
if err != nil {
return nil
}
return crdFilesPaths
}
func matchPrefix(path string, crdsFilters string) bool {
filters := strings.Split(crdsFilters, ",")
for _, filter := range filters {
if strings.HasPrefix(filepath.Base(path), strings.TrimSpace(filter)) {
return true
}
}
return false
}
// WithDependencies inject module dependencies
func (bm *BasicModule) WithDependencies(dep *hooks.HookExecutionDependencyContainer) {
bm.dc = dep
}
// GetOrder returns the module order
func (bm *BasicModule) GetOrder() uint32 {
return bm.Order
}
// GetName returns the module name
func (bm *BasicModule) GetName() string {
return bm.Name
}
// GetPath returns the module path on a filesystem
func (bm *BasicModule) GetPath() string {
return bm.Path
}
// GetHooks returns module hooks, they could be filtered by BindingType optionally
func (bm *BasicModule) GetHooks(bt ...sh_op_types.BindingType) []*hooks.ModuleHook {
return bm.hooks.getHooks(bt...)
}
// DeregisterHooks clean up all module hooks
func (bm *BasicModule) DeregisterHooks() {
bm.hooks.clean()
}
// HooksControllersReady returns controllersReady status of the hook storage
func (bm *BasicModule) HooksControllersReady() bool {
return bm.hooks.controllersReady
}
// SetHooksControllersReady sets controllersReady status of the hook storage to true
func (bm *BasicModule) SetHooksControllersReady() {
bm.hooks.controllersReady = true
}
// ResetState drops the module state
func (bm *BasicModule) ResetState() {
bm.state = &moduleState{
Phase: Startup,
hookErrors: make(map[string]error),
synchronizationState: NewSynchronizationState(),
}
}
// RegisterHooks find and registers all module hooks from a filesystem or GoHook Registry
func (bm *BasicModule) RegisterHooks(logger *log.Logger) ([]*hooks.ModuleHook, error) {
if bm.hooks.registered {
logger.Debugf("Module hooks already registered")
return nil, nil
}
logger.Debugf("Search and register hooks")
hks, err := bm.searchAndRegisterHooks(logger)
if err != nil {
return nil, fmt.Errorf("search and register hooks: %w", err)
}
bm.hooks.registered = true
return hks, nil
}
func (bm *BasicModule) searchModuleHooks() ([]*hooks.ModuleHook, error) {
shellHooks, err := bm.searchModuleShellHooks()
if err != nil {
return nil, fmt.Errorf("search module shell hooks: %w", err)
}
goHooks := bm.searchModuleGoHooks()
batchHooks, err := bm.searchModuleBatchHooks()
if err != nil {
return nil, fmt.Errorf("search module batch hooks: %w", err)
}
mHooks := make([]*hooks.ModuleHook, 0, len(shellHooks)+len(goHooks))
for _, sh := range shellHooks {
mh := hooks.NewModuleHook(sh)
mHooks = append(mHooks, mh)
}
for _, gh := range goHooks {
mh := hooks.NewModuleHook(gh)
mHooks = append(mHooks, mh)
}
for _, bh := range batchHooks {
mh := hooks.NewModuleHook(bh)
mHooks = append(mHooks, mh)
}
sort.SliceStable(mHooks, func(i, j int) bool {
return mHooks[i].GetPath() < mHooks[j].GetPath()
})
return mHooks, nil
}
func (bm *BasicModule) searchModuleShellHooks() (hks []*kind.ShellHook, err error) {
hooksDir := filepath.Join(bm.Path, "hooks")
if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
return nil, nil
}
hooksRelativePaths, err := utils_file.RecursiveGetExecutablePaths(hooksDir)
if err != nil {
return nil, err
}
hks = make([]*kind.ShellHook, 0)
// sort hooks by path
sort.Strings(hooksRelativePaths)
bm.logger.Debugf("Hook paths: %+v", hooksRelativePaths)
for _, hookPath := range hooksRelativePaths {
hookName, err := filepath.Rel(filepath.Dir(bm.Path), hookPath)
if err != nil {
return nil, err
}
if filepath.Ext(hookPath) == "" {
_, err := kind.GetBatchHookConfig(hookPath)
if err == nil {
continue
}
bm.logger.Warn("get batch hook config", slog.String("hook_file_path", hookPath), slog.String("error", err.Error()))
}
shHook := kind.NewShellHook(hookName, hookPath, bm.keepTemporaryHookFiles, shapp.LogProxyHookJSON, bm.logger.Named("shell-hook"))
hks = append(hks, shHook)
}
return
}
func (bm *BasicModule) searchModuleBatchHooks() (hks []*kind.BatchHook, err error) {
hooksDir := filepath.Join(bm.Path, "hooks")
if _, err := os.Stat(hooksDir); os.IsNotExist(err) {
return nil, nil
}
hooksRelativePaths, err := RecursiveGetBatchHookExecutablePaths(hooksDir, bm.logger)
if err != nil {
return nil, err
}
hks = make([]*kind.BatchHook, 0)
// sort hooks by path
sort.Strings(hooksRelativePaths)
bm.logger.Debug("sorted paths", slog.Any("paths", hooksRelativePaths))
for _, hookPath := range hooksRelativePaths {
hookName, err := filepath.Rel(filepath.Dir(bm.Path), hookPath)
if err != nil {
return nil, err
}
sdkcfgs, err := kind.GetBatchHookConfig(hookPath)
if err != nil {
return nil, fmt.Errorf("getting sdk config for '%s': %w", hookName, err)
}
for idx, cfg := range sdkcfgs {
nestedHookName := fmt.Sprintf("%s:%s:%d", hookName, cfg.Metadata.Name, idx)
shHook := kind.NewBatchHook(nestedHookName, hookPath, uint(idx), bm.keepTemporaryHookFiles, shapp.LogProxyHookJSON, bm.logger.Named("batch-hook"))
hks = append(hks, shHook)
}
}
return
}
func RecursiveGetBatchHookExecutablePaths(dir string, logger *log.Logger) ([]string, error) {
paths := make([]string, 0)
err := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
if err != nil {
return err
}
if f.IsDir() {
// Skip hidden and lib directories inside initial directory
if strings.HasPrefix(f.Name(), ".") || f.Name() == "lib" {
return filepath.SkipDir
}
return nil
}
if err := isExecutableBatchHookFile(path, f); err != nil {
logger.Warn("file is skipped", slog.String("path", path), slog.String("error", err.Error()))
return nil
}
paths = append(paths, path)
return nil
})
if err != nil {
return nil, err
}
return paths, nil
}
var (
ErrFileHasNotMetRequirements = errors.New("file has not met requirements")
ErrFileHasWrongExtension = errors.New("file has wrong extension")
ErrFileIsNotBatchHook = errors.New("file is not batch hook")
ErrFileNoExecutablePermissions = errors.New("no executable permissions, chmod +x is required to run this hook")
)
func isExecutableBatchHookFile(path string, f os.FileInfo) error {
switch filepath.Ext(f.Name()) {
// ignore any extension and hidden files
case "":
return IsFileBatchHook(path, f)
// ignore all with extensions
default:
return ErrFileHasWrongExtension
}
}
var compiledHooksFound = regexp.MustCompile(`Found ([1-9]|[1-9]\d|[1-9]\d\d|[1-9]\d\d\d) items`)
func IsFileBatchHook(path string, f os.FileInfo) error {
if f.Mode()&0o111 == 0 {
return ErrFileNoExecutablePermissions
}
// TODO: check binary another way
args := []string{"hook", "list"}
o, err := exec.Command(path, args...).Output()
if err != nil {
return fmt.Errorf("exec file '%s': %w", path, err)
}
if compiledHooksFound.Match(o) {
return nil
}
return ErrFileIsNotBatchHook
}
func (bm *BasicModule) searchModuleGoHooks() (hks []*kind.GoHook) {
// find module hooks in go hooks registry
return sdk.Registry().GetModuleHooks(bm.Name)
}
func (bm *BasicModule) searchAndRegisterHooks(logger *log.Logger) ([]*hooks.ModuleHook, error) {
hks, err := bm.searchModuleHooks()
if err != nil {
return nil, fmt.Errorf("search module hooks failed: %w", err)
}
logger.Debugf("Found %d hooks", len(hks))
if logger.GetLevel() == log.LevelDebug {
for _, h := range hks {
logger.Debugf("ModuleHook: Name=%s, Path=%s", h.GetName(), h.GetPath())
}
}
for _, moduleHook := range hks {
hookLogEntry := logger.With("hook", moduleHook.GetName()).
With("hook.type", "module")
// TODO: we could make multierr here and return all config errors at once
err := moduleHook.InitializeHookConfig()
if err != nil {
return nil, fmt.Errorf("module hook --config invalid: %w", err)
}
bm.logger.Debug("module hook config print", slog.String("module_name", bm.Name), slog.String("hook_name", moduleHook.GetName()), slog.Any("config", moduleHook.GetHookConfig().V1))
// Add hook info as log labels
for _, kubeCfg := range moduleHook.GetHookConfig().OnKubernetesEvents {
kubeCfg.Monitor.Metadata.LogLabels["module"] = bm.Name
kubeCfg.Monitor.Metadata.LogLabels["hook"] = moduleHook.GetName()
kubeCfg.Monitor.Metadata.LogLabels["hook.type"] = "module"
kubeCfg.Monitor.Metadata.MetricLabels = map[string]string{
"hook": moduleHook.GetName(),
"binding": kubeCfg.BindingName,
"module": bm.Name,
"queue": kubeCfg.Queue,
"kind": kubeCfg.Monitor.Kind,
}
}
// register module hook in indexes
bm.hooks.AddHook(moduleHook)
hookLogEntry.Debugf("Module hook from '%s'. Bindings: %s", moduleHook.GetPath(), moduleHook.GetConfigDescription())
}
return hks, nil
}
// GetPhase ...
func (bm *BasicModule) GetPhase() ModuleRunPhase {
return bm.state.Phase
}
// SetPhase ...
func (bm *BasicModule) SetPhase(phase ModuleRunPhase) {
bm.state.Phase = phase
}
// SetError ...
func (bm *BasicModule) SetError(err error) {
bm.state.lastModuleErr = err
}
// SetStateEnabled ...
func (bm *BasicModule) SetStateEnabled(e bool) {
bm.state.Enabled = e
}
// SaveHookError ...
func (bm *BasicModule) SaveHookError(hookName string, err error) {
bm.state.hookErrorsLock.Lock()
defer bm.state.hookErrorsLock.Unlock()
bm.state.hookErrors[hookName] = err
}
// RunHooksByBinding gets all hooks for binding, for each hook it creates a BindingContext,
// sets KubernetesSnapshots and runs the hook.
func (bm *BasicModule) RunHooksByBinding(binding sh_op_types.BindingType, logLabels map[string]string) error {
var err error
moduleHooks := bm.GetHooks(binding)
for _, moduleHook := range moduleHooks {
// TODO: This looks like a bug. It will block all hooks of the module
err = moduleHook.RateLimitWait(context.Background())
if err != nil {
// This could happen when the Context is
// canceled, or the expected wait time exceeds the Context's Deadline.
// The best we can do without proper context usage is to repeat the task.
return fmt.Errorf("rate limit wait: %w", err)
}
bc := bindingcontext.BindingContext{
Binding: string(binding),
}
// Update kubernetes snapshots just before execute a hook
if binding == types.BeforeHelm || binding == types.AfterHelm || binding == types.AfterDeleteHelm {
bc.Snapshots = moduleHook.GetHookController().KubernetesSnapshots()
bc.Metadata.IncludeAllSnapshots = true
}
bc.Metadata.BindingType = binding
metricLabels := map[string]string{
"module": bm.Name,
"hook": moduleHook.GetName(),
"binding": string(binding),
"queue": "main", // AfterHelm,BeforeHelm hooks always handle in main queue
"activation": logLabels["event.type"],
}
func() {
defer measure.Duration(func(d time.Duration) {
bm.dc.MetricStorage.HistogramObserve("{PREFIX}module_hook_run_seconds", d.Seconds(), metricLabels, nil)
})()
err = bm.executeHook(moduleHook, binding, []bindingcontext.BindingContext{bc}, logLabels, metricLabels)
}()
if err != nil {
return fmt.Errorf("execute hook: %w", err)
}
}
return nil
}
// RunHookByName runs some specified hook by its name
func (bm *BasicModule) RunHookByName(hookName string, binding sh_op_types.BindingType, bindingContext []bindingcontext.BindingContext, logLabels map[string]string) (string, string, error) {
values := bm.valuesStorage.GetValues(false)
valuesChecksum := values.Checksum()
moduleHook := bm.hooks.getHookByName(hookName)
// Update kubernetes snapshots just before execute a hook
// Note: BeforeHelm and AfterHelm are run by RunHookByBinding
if binding == sh_op_types.OnKubernetesEvent || binding == sh_op_types.Schedule {
bindingContext = moduleHook.GetHookController().UpdateSnapshots(bindingContext)
}
metricLabels := map[string]string{
"module": bm.Name,
"hook": hookName,
"binding": string(binding),
"queue": logLabels["queue"],
"activation": logLabels["event.type"],
}
err := bm.executeHook(moduleHook, binding, bindingContext, logLabels, metricLabels)
if err != nil {
return "", "", err
}
newValuesChecksum := bm.valuesStorage.GetValues(false).Checksum()
return valuesChecksum, newValuesChecksum, nil
}
// RunEnabledScript execute enabled script
func (bm *BasicModule) RunEnabledScript(tmpDir string, precedingEnabledModules []string, logLabels map[string]string) (bool, error) {
// Copy labels and set 'module' label.
logLabels = utils.MergeLabels(logLabels)
logLabels["module"] = bm.Name
logEntry := utils.EnrichLoggerWithLabels(bm.logger, logLabels)
enabledScriptPath := filepath.Join(bm.Path, "enabled")
configValuesPath, err := bm.prepareConfigValuesJsonFile(tmpDir)
if err != nil {
logEntry.Errorf("Prepare CONFIG_VALUES_PATH file for '%s': %s", enabledScriptPath, err)
return false, err
}
defer func() {
if bm.keepTemporaryHookFiles {
return
}
err := os.Remove(configValuesPath)
if err != nil {
bm.logger.With("module", bm.Name).
Errorf("Remove tmp file '%s': %s", configValuesPath, err)
}
}()
valuesPath, err := bm.prepareValuesJsonFileForEnabledScript(tmpDir, precedingEnabledModules)
if err != nil {
logEntry.Errorf("Prepare VALUES_PATH file for '%s': %s", enabledScriptPath, err)
return false, err
}
defer func() {
if bm.keepTemporaryHookFiles {
return
}
err := os.Remove(valuesPath)
if err != nil {
bm.logger.With("module", bm.Name).
Errorf("Remove tmp file '%s': %s", configValuesPath, err)
}
}()
enabledResultFilePath, err := bm.prepareModuleEnabledResultFile(tmpDir)
if err != nil {
logEntry.Errorf("Prepare MODULE_ENABLED_RESULT file for '%s': %s", enabledScriptPath, err)
return false, err
}
defer func() {
if bm.keepTemporaryHookFiles {
return
}
err := os.Remove(enabledResultFilePath)
if err != nil {
bm.logger.With("module", bm.Name).
Errorf("Remove tmp file '%s': %s", configValuesPath, err)
}
}()
logEntry.Debugf("Execute enabled script '%s', preceding modules: %v", enabledScriptPath, precedingEnabledModules)
envs := make([]string, 0)
envs = append(envs, os.Environ()...)
envs = append(envs, fmt.Sprintf("CONFIG_VALUES_PATH=%s", configValuesPath))
envs = append(envs, fmt.Sprintf("VALUES_PATH=%s", valuesPath))
envs = append(envs, fmt.Sprintf("MODULE_ENABLED_RESULT=%s", enabledResultFilePath))
cmd := executor.NewExecutor(
"",
enabledScriptPath,
[]string{},
envs).
WithLogger(bm.logger.Named("executor")).
WithCMDStdout(nil)
usage, err := cmd.RunAndLogLines(logLabels)
if usage != nil {
// usage metrics
metricLabels := map[string]string{
"module": bm.Name,
"hook": "enabled",
"binding": "enabled",
"queue": logLabels["queue"],
"activation": logLabels["event.type"],
}
bm.dc.MetricStorage.HistogramObserve("{PREFIX}module_hook_run_sys_cpu_seconds", usage.Sys.Seconds(), metricLabels, nil)
bm.dc.MetricStorage.HistogramObserve("{PREFIX}module_hook_run_user_cpu_seconds", usage.User.Seconds(), metricLabels, nil)
bm.dc.MetricStorage.GaugeSet("{PREFIX}module_hook_run_max_rss_bytes", float64(usage.MaxRss)*1024, metricLabels)
}
if err != nil {
logEntry.Errorf("Fail to run enabled script '%s': %s", enabledScriptPath, err)
return false, err
}
moduleEnabled, err := bm.readModuleEnabledResult(enabledResultFilePath)
if err != nil {
logEntry.Errorf("Read enabled result from '%s': %s", enabledScriptPath, err)
return false, fmt.Errorf("bad enabled result")
}
result := "Disabled"
if moduleEnabled {
result = "Enabled"
}
logEntry.Infof("Enabled script run successful, result '%v', module '%s'", moduleEnabled, result)
bm.state.enabledScriptResult = &moduleEnabled
return moduleEnabled, nil
}
func (bm *BasicModule) prepareValuesJsonFileForEnabledScript(tmpdir string, precedingEnabledModules []string) (string, error) {
values := bm.valuesForEnabledScript(precedingEnabledModules)
return bm.prepareValuesJsonFileWith(tmpdir, values)
}
func (bm *BasicModule) prepareModuleEnabledResultFile(tmpdir string) (string, error) {
path := filepath.Join(tmpdir, fmt.Sprintf("%s.module-enabled-result", bm.Name))
if err := utils.CreateEmptyWritableFile(path); err != nil {
return "", err
}
return path, nil
}
func (bm *BasicModule) readModuleEnabledResult(filePath string) (bool, error) {
data, err := os.ReadFile(filePath)
if err != nil {
return false, fmt.Errorf("cannot read %s: %s", filePath, err)
}
value := strings.TrimSpace(string(data))
if value == "true" {
return true, nil
} else if value == "false" {
return false, nil
}
return false, fmt.Errorf("expected 'true' or 'false', got '%s'", value)
}
// VALUES_PATH
func (bm *BasicModule) prepareValuesJsonFileWith(tmpdir string, values utils.Values) (string, error) {
data, err := values.JsonBytes()
if err != nil {
return "", err
}
path := filepath.Join(tmpdir, fmt.Sprintf("%s.module-values-%s.json", bm.safeName(), uuid.Must(uuid.NewV4()).String()))
err = utils.DumpData(path, data)
if err != nil {
return "", err
}
bm.logger.Debugf("Prepared module %s hook values:\n%s", bm.Name, values.DebugString())
return path, nil
}
// ValuesForEnabledScript returns effective values for enabled script.
// There is enabledModules key in global section with previously enabled modules.
func (bm *BasicModule) valuesForEnabledScript(precedingEnabledModules []string) utils.Values {
res := bm.valuesStorage.GetValues(true)
res = mergeLayers(
utils.Values{},
res,
bm.dc.GlobalValuesGetter.GetValues(true),
utils.Values{
"global": map[string]interface{}{
"enabledModules": precedingEnabledModules,
},
},
)
return res
}
func (bm *BasicModule) safeName() string {
return sanitize.BaseName(bm.Name)
}
// CONFIG_VALUES_PATH
func (bm *BasicModule) prepareConfigValuesJsonFile(tmpDir string) (string, error) {
v := utils.Values{
"global": bm.dc.GlobalValuesGetter.GetConfigValues(false),
bm.moduleNameForValues(): bm.GetConfigValues(false),
}
data, err := v.JsonBytes()
if err != nil {
return "", err
}
path := filepath.Join(tmpDir, fmt.Sprintf("%s.module-config-values-%s.json", bm.safeName(), uuid.Must(uuid.NewV4()).String()))
err = utils.DumpData(path, data)
if err != nil {
return "", err
}
bm.logger.Debugf("Prepared module %s hook config values:\n%s", bm.Name, v.DebugString())
return path, nil
}
// instead on ModuleHook.Run
func (bm *BasicModule) executeHook(h *hooks.ModuleHook, bindingType sh_op_types.BindingType, bctx []bindingcontext.BindingContext, logLabels map[string]string, metricLabels map[string]string) error {
logLabels = utils.MergeLabels(logLabels, map[string]string{
"hook": h.GetName(),
"hook.type": "module",
"binding": string(bindingType),
})
logEntry := utils.EnrichLoggerWithLabels(bm.logger, logLabels)
logStartLevel := log.LevelInfo
// Use Debug when run as a separate task for Kubernetes or Schedule hooks, as task start is already logged.
// TODO log this message by callers.
if bindingType == sh_op_types.OnKubernetesEvent || bindingType == sh_op_types.Schedule {
logStartLevel = log.LevelDebug
}
logEntry.Log(context.Background(), logStartLevel.Level(), "Module hook start", slog.String(bm.Name, h.GetName()))
for _, info := range h.GetHookController().SnapshotsInfo() {
logEntry.Debugf("snapshot info: %s", info)
}
prefixedConfigValues := bm.valuesStorage.GetConfigValues(true)
prefixedValues := bm.valuesStorage.GetValues(true)
valuesModuleName := bm.moduleNameForValues()
configValues := prefixedConfigValues.GetKeySection(valuesModuleName)
values := prefixedValues.GetKeySection(valuesModuleName)
// we have to add a module name key at top level
// because all hooks are living with an old scheme
hookConfigValues := utils.Values{
utils.GlobalValuesKey: bm.dc.GlobalValuesGetter.GetConfigValues(false),
bm.moduleNameForValues(): configValues,
}
hookValues := utils.Values{
utils.GlobalValuesKey: bm.dc.GlobalValuesGetter.GetValues(false),
bm.moduleNameForValues(): values,
}
hookResult, err := h.Execute(h.GetConfigVersion(), bctx, bm.safeName(), hookConfigValues, hookValues, logLabels)
if hookResult != nil && hookResult.Usage != nil {
bm.dc.MetricStorage.HistogramObserve("{PREFIX}module_hook_run_sys_cpu_seconds", hookResult.Usage.Sys.Seconds(), metricLabels, nil)
bm.dc.MetricStorage.HistogramObserve("{PREFIX}module_hook_run_user_cpu_seconds", hookResult.Usage.User.Seconds(), metricLabels, nil)
bm.dc.MetricStorage.GaugeSet("{PREFIX}module_hook_run_max_rss_bytes", float64(hookResult.Usage.MaxRss)*1024, metricLabels)
}
if err != nil {
// we have to check if there are some status patches to apply
if hookResult != nil && len(hookResult.ObjectPatcherOperations) > 0 {
statusPatchesErr := bm.dc.KubeObjectPatcher.ExecuteOperations(hookResult.ObjectPatcherOperations)
if statusPatchesErr != nil {
return fmt.Errorf("module hook '%s' failed: %s, update status operation failed: %s", h.GetName(), err, statusPatchesErr)
}
}
return fmt.Errorf("module hook '%s' failed: %s", h.GetName(), err)
}
if len(hookResult.ObjectPatcherOperations) > 0 {
err = bm.dc.KubeObjectPatcher.ExecuteOperations(hookResult.ObjectPatcherOperations)
if err != nil {
return fmt.Errorf("execute operations: %w", err)
}
}
// Apply metric operations
err = bm.dc.HookMetricsStorage.SendBatch(hookResult.Metrics, map[string]string{
"hook": h.GetName(),
"module": bm.Name,
})
if err != nil {
return fmt.Errorf("metric storage send batch: %w", err)
}
// Apply binding actions. (Only Go hook for now).
if h.GetKind() == kind.HookKindGo {
err = h.ApplyBindingActions(hookResult.BindingActions)
if err != nil {
return fmt.Errorf("apply binding actions: %w", err)
}
}
configValuesPatch, has := hookResult.Patches[utils.ConfigMapPatch]
if has && configValuesPatch != nil {
// Apply patch to get intermediate updated values.
configValuesPatchResult, err := bm.handleModuleValuesPatch(prefixedConfigValues, *configValuesPatch)
if err != nil {
return fmt.Errorf("module hook '%s': kube module config values update error: %s", h.GetName(), err)
}
if configValuesPatchResult.ValuesChanged {
logEntry.Debugf("Module hook '%s': validate module config values before update", h.GetName())
// Validate merged static and new values.
newValues, validationErr := bm.valuesStorage.GenerateNewConfigValues(configValuesPatchResult.Values, true)
if validationErr != nil {
return multierror.Append(
fmt.Errorf("cannot apply config values patch for module values"),
validationErr,
)
}
err := bm.dc.KubeConfigManager.SaveConfigValues(bm.Name, configValuesPatchResult.Values)
if err != nil {
logEntry.Debugf("Module hook '%s' kube module config values stay unchanged:\n%s", h.GetName(), bm.valuesStorage.GetConfigValues(false).DebugString())
return fmt.Errorf("module hook '%s': set kube module config failed: %s", h.GetName(), err)
}
bm.valuesStorage.SaveConfigValues(newValues)
logEntry.Debugf("Module hook '%s': kube module '%s' config values updated:\n%s", h.GetName(), bm.Name, bm.valuesStorage.GetConfigValues(false).DebugString())
}
}
valuesPatch, has := hookResult.Patches[utils.MemoryValuesPatch]
if has && valuesPatch != nil {
// Apply patch to get intermediate updated values.
valuesPatchResult, err := bm.handleModuleValuesPatch(prefixedValues, *valuesPatch)
if err != nil {
return fmt.Errorf("module hook '%s': dynamic module values update error: %s", h.GetName(), err)
}
if valuesPatchResult.ValuesChanged {
logEntry.Debugf("Module hook '%s': validate module values before update", h.GetName())
// Validate schema for updated module values
validationErr := bm.valuesStorage.validateValues(valuesPatchResult.Values)
if validationErr != nil {
return multierror.Append(
fmt.Errorf("cannot apply values patch for module values"),
validationErr,
)
}
// Save patch set if everything is ok.
bm.valuesStorage.appendValuesPatch(valuesPatchResult.ValuesPatch)
err = bm.valuesStorage.CommitValues()
if err != nil {
return fmt.Errorf("error on commit values: %w", err)
}
logEntry.Debugf("Module hook '%s': dynamic module '%s' values updated:\n%s", h.GetName(), bm.Name, bm.valuesStorage.GetValues(false).DebugString())
}
}
logEntry.Debugf("Module hook success %s/%s", bm.Name, h.GetName())
return nil
}
type moduleValuesMergeResult struct {
// global values with root ModuleValuesKey key
Values utils.Values
ModuleValuesKey string
ValuesPatch utils.ValuesPatch
ValuesChanged bool
}
// moduleNameForValues returns module name as camelCase
// Example:
//
// my-super-module -> mySuperModule
func (bm *BasicModule) moduleNameForValues() string {
return utils.ModuleNameToValuesKey(bm.Name)
}
func (bm *BasicModule) handleModuleValuesPatch(currentValues utils.Values, valuesPatch utils.ValuesPatch) (*moduleValuesMergeResult, error) {
moduleValuesKey := bm.moduleNameForValues()
if err := utils.ValidateHookValuesPatch(valuesPatch, moduleValuesKey); err != nil {
return nil, fmt.Errorf("merge module '%s' values failed: %s", bm.Name, err)
}
// Apply new patches in Strict mode. Hook should not return 'remove' with nonexistent path.
newValues, valuesChanged, err := utils.ApplyValuesPatch(currentValues, valuesPatch, utils.Strict)
if err != nil {
return nil, fmt.Errorf("merge module '%s' values failed: %s", bm.Name, err)
}
switch v := newValues[moduleValuesKey].(type) {
case utils.Values:
newValues = v
case map[string]interface{}:
newValues = v
default:
return nil, fmt.Errorf("unknown module values type: %T", v)
}
result := &moduleValuesMergeResult{
ModuleValuesKey: moduleValuesKey,
Values: newValues,
ValuesChanged: valuesChanged,
ValuesPatch: valuesPatch,
}
return result, nil
}
func (bm *BasicModule) GenerateNewConfigValues(kubeConfigValues utils.Values, validate bool) (utils.Values, error) {
return bm.valuesStorage.GenerateNewConfigValues(kubeConfigValues, validate)
}
func (bm *BasicModule) SaveConfigValues(configV utils.Values) {
bm.valuesStorage.SaveConfigValues(configV)
}
func (bm *BasicModule) GetValues(withPrefix bool) utils.Values {
return bm.valuesStorage.GetValues(withPrefix)
}
func (bm *BasicModule) GetConfigValues(withPrefix bool) utils.Values {
return bm.valuesStorage.GetConfigValues(withPrefix)
}
// Synchronization xxx
// TODO: don't like this honestly, i think we can remake it
func (bm *BasicModule) Synchronization() *SynchronizationState {
return bm.state.synchronizationState
}
// SynchronizationNeeded is true if module has at least one kubernetes hook
// with executeHookOnSynchronization.
// TODO: dont skip
func (bm *BasicModule) SynchronizationNeeded() bool {
for _, modHook := range bm.hooks.byName {
if modHook.SynchronizationNeeded() {
return true
}
}
return false
}
// HasKubernetesHooks is true if module has at least one kubernetes hook.
func (bm *BasicModule) HasKubernetesHooks() bool {
hks := bm.hooks.getHooks(sh_op_types.OnKubernetesEvent)
return len(hks) > 0
}
// GetHookByName returns hook by its name
func (bm *BasicModule) GetHookByName(name string) *hooks.ModuleHook {
return bm.hooks.getHookByName(name)
}
// GetValuesPatches returns patches for debug output
func (bm *BasicModule) GetValuesPatches() []utils.ValuesPatch {
return bm.valuesStorage.getValuesPatches()
}
// GetHookErrorsSummary get hooks errors summary report
func (bm *BasicModule) GetHookErrorsSummary() string {
bm.state.hookErrorsLock.RLock()
defer bm.state.hookErrorsLock.RUnlock()
hooksState := make([]string, 0, len(bm.state.hookErrors))
for name, err := range bm.state.hookErrors {
errorMsg := fmt.Sprint(err)
if err == nil {
errorMsg = "ok"