-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathbatch_hook.go
321 lines (268 loc) · 9.5 KB
/
batch_hook.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
package kind
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"github.com/deckhouse/deckhouse/pkg/log"
sdkhook "github.com/deckhouse/module-sdk/pkg/hook"
"github.com/gofrs/uuid/v5"
"github.com/flant/addon-operator/pkg/utils"
"github.com/flant/shell-operator/pkg/executor"
sh_hook "github.com/flant/shell-operator/pkg/hook"
bindingcontext "github.com/flant/shell-operator/pkg/hook/binding_context"
"github.com/flant/shell-operator/pkg/hook/config"
"github.com/flant/shell-operator/pkg/hook/controller"
objectpatch "github.com/flant/shell-operator/pkg/kube/object_patch"
metricoperation "github.com/flant/shell-operator/pkg/metric_storage/operation"
)
type BatchHook struct {
sh_hook.Hook
// hook ID in batch
ID uint
}
// NewBatchHook new hook, which runs via the OS interpreter like bash/python/etc
func NewBatchHook(name, path string, id uint, keepTemporaryHookFiles bool, logProxyHookJSON bool, logger *log.Logger) *BatchHook {
return &BatchHook{
Hook: sh_hook.Hook{
Name: name,
Path: path,
KeepTemporaryHookFiles: keepTemporaryHookFiles,
LogProxyHookJSON: logProxyHookJSON,
Logger: logger,
},
ID: id,
}
}
// BackportHookConfig for shell-operator to make HookController and GetConfigDescription workable.
func (sh *BatchHook) BackportHookConfig(cfg *config.HookConfig) {
sh.Config = cfg
sh.RateLimiter = sh_hook.CreateRateLimiter(cfg)
}
// WithHookController sets dependency "hook controller" for shell-operator
func (sh *BatchHook) WithHookController(hookController *controller.HookController) {
sh.HookController = hookController
}
// WithTmpDir injects temp directory from operator
func (sh *BatchHook) WithTmpDir(tmpDir string) {
sh.TmpDir = tmpDir
}
// GetPath returns hook's path on the filesystem
func (sh *BatchHook) GetPath() string {
return sh.Path
}
// GetHookController returns HookController
func (sh *BatchHook) GetHookController() *controller.HookController {
return sh.HookController
}
// GetName returns the hook's name
func (sh *BatchHook) GetName() string {
return sh.Name
}
// GetKind returns kind of the hook
func (sh *BatchHook) GetKind() HookKind {
return HookKindShell
}
// GetHookConfigDescription get part of hook config for logging/debugging
func (sh *BatchHook) GetHookConfigDescription() string {
return sh.Hook.GetConfigDescription()
}
// Execute runs the hook via the OS interpreter and returns the result of the execution
func (sh *BatchHook) Execute(configVersion string, bContext []bindingcontext.BindingContext, moduleSafeName string, configValues, values utils.Values, logLabels map[string]string) (result *HookResult, err error) {
result = &HookResult{
Patches: make(map[utils.ValuesPatchType]*utils.ValuesPatch),
}
versionedContextList := bindingcontext.ConvertBindingContextList(configVersion, bContext)
bindingContextBytes, err := versionedContextList.Json()
if err != nil {
return nil, err
}
// tmp files has uuid in name and create only in tmp folder (because of RO filesystem)
tmpFiles, err := sh.prepareTmpFilesForHookRun(bindingContextBytes, moduleSafeName, configValues, values)
if err != nil {
return nil, err
}
// Remove tmp files after execution
defer func() {
if sh.KeepTemporaryHookFiles {
return
}
for _, f := range tmpFiles {
err := os.Remove(f)
if err != nil {
sh.Hook.Logger.With("hook", sh.GetName()).
Errorf("Remove tmp file '%s': %s", f, err)
}
}
}()
configValuesPatchPath := tmpFiles["CONFIG_VALUES_JSON_PATCH_PATH"]
valuesPatchPath := tmpFiles["VALUES_JSON_PATCH_PATH"]
metricsPath := tmpFiles["METRICS_PATH"]
kubernetesPatchPath := tmpFiles["KUBERNETES_PATCH_PATH"]
envs := make([]string, 0)
args := make([]string, 0)
args = append(args, "hook", "run", strconv.Itoa(int(sh.ID)))
envs = append(envs, os.Environ()...)
for envName, filePath := range tmpFiles {
envs = append(envs, fmt.Sprintf("%s=%s", envName, filePath))
}
cmd := executor.NewExecutor(
"",
sh.GetPath(),
args,
envs).
WithLogProxyHookJSON(sh.LogProxyHookJSON).
WithLogProxyHookJSONKey(sh.LogProxyHookJSONKey).
WithLogger(sh.Logger.Named("executor"))
usage, err := cmd.RunAndLogLines(logLabels)
result.Usage = usage
if err != nil {
return result, err
}
result.Patches[utils.ConfigMapPatch], err = utils.ValuesPatchFromFile(configValuesPatchPath)
if err != nil {
return result, fmt.Errorf("got bad json patch for config values: %s", err)
}
result.Patches[utils.MemoryValuesPatch], err = utils.ValuesPatchFromFile(valuesPatchPath)
if err != nil {
return result, fmt.Errorf("got bad json patch for values: %s", err)
}
result.Metrics, err = metricoperation.MetricOperationsFromFile(metricsPath)
if err != nil {
return result, fmt.Errorf("got bad metrics: %s", err)
}
kubernetesPatchBytes, err := os.ReadFile(kubernetesPatchPath)
if err != nil {
return result, fmt.Errorf("can't read kubernetes patch file: %s", err)
}
result.ObjectPatcherOperations, err = objectpatch.ParseOperations(kubernetesPatchBytes)
if err != nil {
return nil, err
}
return result, nil
}
func (sh *BatchHook) getConfig() ([]sdkhook.HookConfig, error) {
return GetBatchHookConfig(sh.Path)
}
func GetBatchHookConfig(hookPath string) ([]sdkhook.HookConfig, error) {
args := []string{"hook", "config"}
o, err := exec.Command(hookPath, args...).Output()
if err != nil {
return nil, fmt.Errorf("exec file '%s': %w", hookPath, err)
}
cfgs := make([]sdkhook.HookConfig, 0)
buf := bytes.NewReader(o)
err = json.NewDecoder(buf).Decode(&cfgs)
if err != nil {
return nil, fmt.Errorf("decode: %w", err)
}
return cfgs, nil
}
// GetConfig returns config via executing the hook with `--config` param
func (sh *BatchHook) GetConfig() ([]sdkhook.HookConfig, error) {
return sh.getConfig()
}
// PrepareTmpFilesForHookRun creates temporary files for hook and returns environment variables with paths
func (sh *BatchHook) prepareTmpFilesForHookRun(bindingContext []byte, moduleSafeName string, configValues, values utils.Values) (tmpFiles map[string]string, err error) {
tmpFiles = make(map[string]string)
tmpFiles["CONFIG_VALUES_PATH"], err = sh.prepareConfigValuesJsonFile(moduleSafeName, configValues)
if err != nil {
return
}
tmpFiles["VALUES_PATH"], err = sh.prepareValuesJsonFile(moduleSafeName, values)
if err != nil {
return
}
tmpFiles["BINDING_CONTEXT_PATH"], err = sh.prepareBindingContextJsonFile(moduleSafeName, bindingContext)
if err != nil {
return
}
tmpFiles["CONFIG_VALUES_JSON_PATCH_PATH"], err = sh.prepareConfigValuesJsonPatchFile()
if err != nil {
return
}
tmpFiles["VALUES_JSON_PATCH_PATH"], err = sh.prepareValuesJsonPatchFile()
if err != nil {
return
}
tmpFiles["METRICS_PATH"], err = sh.prepareMetricsFile()
if err != nil {
return
}
tmpFiles["KUBERNETES_PATCH_PATH"], err = sh.prepareKubernetesPatchFile()
if err != nil {
return
}
return
}
// METRICS_PATH
func (sh *BatchHook) prepareMetricsFile() (string, error) {
path := filepath.Join(sh.TmpDir, fmt.Sprintf("%s.module-hook-metrics-%s.json", sh.SafeName(), uuid.Must(uuid.NewV4()).String()))
if err := utils.CreateEmptyWritableFile(path); err != nil {
return "", err
}
return path, nil
}
// BINDING_CONTEXT_PATH
func (sh *BatchHook) prepareBindingContextJsonFile(moduleSafeName string, bindingContext []byte) (string, error) {
path := filepath.Join(sh.TmpDir, fmt.Sprintf("%s.module-hook-%s-binding-context-%s.json", moduleSafeName, sh.SafeName(), uuid.Must(uuid.NewV4()).String()))
err := utils.DumpData(path, bindingContext)
if err != nil {
return "", err
}
return path, nil
}
// CONFIG_VALUES_JSON_PATCH_PATH
func (sh *BatchHook) prepareConfigValuesJsonPatchFile() (string, error) {
path := filepath.Join(sh.TmpDir, fmt.Sprintf("%s.module-hook-config-values-%s.json-patch", sh.SafeName(), uuid.Must(uuid.NewV4()).String()))
if err := utils.CreateEmptyWritableFile(path); err != nil {
return "", err
}
return path, nil
}
// VALUES_JSON_PATCH_PATH
func (sh *BatchHook) prepareValuesJsonPatchFile() (string, error) {
path := filepath.Join(sh.TmpDir, fmt.Sprintf("%s.module-hook-values-%s.json-patch", sh.SafeName(), uuid.Must(uuid.NewV4()).String()))
if err := utils.CreateEmptyWritableFile(path); err != nil {
return "", err
}
return path, nil
}
// KUBERNETES PATCH PATH
func (sh *BatchHook) prepareKubernetesPatchFile() (string, error) {
path := filepath.Join(sh.TmpDir, fmt.Sprintf("%s-object-patch-%s", sh.SafeName(), uuid.Must(uuid.NewV4()).String()))
if err := utils.CreateEmptyWritableFile(path); err != nil {
return "", err
}
return path, nil
}
// CONFIG_VALUES_PATH
func (sh *BatchHook) prepareConfigValuesJsonFile(moduleSafeName string, configValues utils.Values) (string, error) {
data, err := configValues.JsonBytes()
if err != nil {
return "", err
}
path := filepath.Join(sh.TmpDir, fmt.Sprintf("%s.module-config-values-%s.json", moduleSafeName, uuid.Must(uuid.NewV4()).String()))
err = utils.DumpData(path, data)
if err != nil {
return "", err
}
sh.Hook.Logger.Debugf("Prepared module %s hook config values:\n%s", moduleSafeName, configValues.DebugString())
return path, nil
}
func (sh *BatchHook) prepareValuesJsonFile(moduleSafeName string, values utils.Values) (string, error) {
data, err := values.JsonBytes()
if err != nil {
return "", err
}
path := filepath.Join(sh.TmpDir, fmt.Sprintf("%s.module-values-%s.json", moduleSafeName, uuid.Must(uuid.NewV4()).String()))
err = utils.DumpData(path, data)
if err != nil {
return "", err
}
sh.Hook.Logger.Debugf("Prepared module %s hook values:\n%s", moduleSafeName, values.DebugString())
return path, nil
}