-
Notifications
You must be signed in to change notification settings - Fork 266
/
resource_ops.go
499 lines (456 loc) · 16.8 KB
/
resource_ops.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
package kube
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"github.com/go-logr/logr"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/cli-runtime/pkg/printers"
"k8s.io/cli-runtime/pkg/resource"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/kubectl/pkg/cmd/apply"
"k8s.io/kubectl/pkg/cmd/auth"
"k8s.io/kubectl/pkg/cmd/create"
"k8s.io/kubectl/pkg/cmd/delete"
"k8s.io/kubectl/pkg/cmd/replace"
cmdutil "k8s.io/kubectl/pkg/cmd/util"
"k8s.io/kubectl/pkg/scheme"
"k8s.io/kubectl/pkg/util/openapi"
"github.com/argoproj/gitops-engine/pkg/diff"
"github.com/argoproj/gitops-engine/pkg/utils/io"
"github.com/argoproj/gitops-engine/pkg/utils/tracing"
)
// ResourceOperations provides methods to manage k8s resources
type ResourceOperations interface {
ApplyResource(ctx context.Context, obj *unstructured.Unstructured, dryRunStrategy cmdutil.DryRunStrategy, force, validate, serverSideApply bool, manager string, serverSideDiff bool) (string, error)
ReplaceResource(ctx context.Context, obj *unstructured.Unstructured, dryRunStrategy cmdutil.DryRunStrategy, force bool) (string, error)
CreateResource(ctx context.Context, obj *unstructured.Unstructured, dryRunStrategy cmdutil.DryRunStrategy, validate bool) (string, error)
UpdateResource(ctx context.Context, obj *unstructured.Unstructured, dryRunStrategy cmdutil.DryRunStrategy) (*unstructured.Unstructured, error)
}
type kubectlResourceOperations struct {
config *rest.Config
log logr.Logger
tracer tracing.Tracer
onKubectlRun OnKubectlRunFunc
fact cmdutil.Factory
openAPISchema openapi.Resources
}
type commandExecutor func(f cmdutil.Factory, ioStreams genericclioptions.IOStreams, fileName string) error
func (k *kubectlResourceOperations) runResourceCommand(ctx context.Context, obj *unstructured.Unstructured, dryRunStrategy cmdutil.DryRunStrategy, executor commandExecutor) (string, error) {
manifestBytes, err := json.Marshal(obj)
if err != nil {
return "", err
}
manifestFile, err := os.CreateTemp(io.TempDir, "")
if err != nil {
return "", fmt.Errorf("Failed to generate temp file for manifest: %v", err)
}
if _, err = manifestFile.Write(manifestBytes); err != nil {
return "", fmt.Errorf("Failed to write manifest: %v", err)
}
if err = manifestFile.Close(); err != nil {
return "", fmt.Errorf("Failed to close manifest: %v", err)
}
defer io.DeleteFile(manifestFile.Name())
// log manifest
if k.log.V(1).Enabled() {
var obj unstructured.Unstructured
err := json.Unmarshal(manifestBytes, &obj)
if err != nil {
return "", err
}
redacted, _, err := diff.HideSecretData(&obj, nil)
if err != nil {
return "", err
}
redactedBytes, err := json.Marshal(redacted)
if err != nil {
return "", err
}
k.log.V(1).Info(string(redactedBytes))
}
var out []string
if obj.GetAPIVersion() == "rbac.authorization.k8s.io/v1" {
// If it is an RBAC resource, run `kubectl auth reconcile`. This is preferred over
// `kubectl apply`, which cannot tolerate changes in roleRef, which is an immutable field.
// See: https://github.com/kubernetes/kubernetes/issues/66353
// `auth reconcile` will delete and recreate the resource if necessary
outReconcile, err := func() (string, error) {
cleanup, err := k.processKubectlRun("auth")
if err != nil {
return "", err
}
defer cleanup()
return k.authReconcile(ctx, obj, manifestFile.Name(), dryRunStrategy)
}()
if err != nil {
return "", err
}
out = append(out, outReconcile)
// We still want to fallthrough and run `kubectl apply` in order set the
// last-applied-configuration annotation in the object.
}
// Run kubectl apply
ioStreams := genericclioptions.IOStreams{
In: &bytes.Buffer{},
Out: &bytes.Buffer{},
ErrOut: &bytes.Buffer{},
}
err = executor(k.fact, ioStreams, manifestFile.Name())
if err != nil {
return "", errors.New(cleanKubectlOutput(err.Error()))
}
if buf := strings.TrimSpace(ioStreams.Out.(*bytes.Buffer).String()); len(buf) > 0 {
out = append(out, buf)
}
if buf := strings.TrimSpace(ioStreams.ErrOut.(*bytes.Buffer).String()); len(buf) > 0 {
out = append(out, buf)
}
return strings.Join(out, ". "), nil
}
func kubeCmdFactory(kubeconfig, ns string, config *rest.Config) cmdutil.Factory {
kubeConfigFlags := genericclioptions.NewConfigFlags(true)
if ns != "" {
kubeConfigFlags.Namespace = &ns
}
kubeConfigFlags.KubeConfig = &kubeconfig
kubeConfigFlags.WithDiscoveryBurst(config.Burst)
kubeConfigFlags.WithDiscoveryQPS(config.QPS)
matchVersionKubeConfigFlags := cmdutil.NewMatchVersionFlags(kubeConfigFlags)
return cmdutil.NewFactory(matchVersionKubeConfigFlags)
}
func (k *kubectlResourceOperations) ReplaceResource(ctx context.Context, obj *unstructured.Unstructured, dryRunStrategy cmdutil.DryRunStrategy, force bool) (string, error) {
span := k.tracer.StartSpan("ReplaceResource")
span.SetBaggageItem("kind", obj.GetKind())
span.SetBaggageItem("name", obj.GetName())
defer span.Finish()
k.log.Info(fmt.Sprintf("Replacing resource %s/%s in cluster: %s, namespace: %s", obj.GetKind(), obj.GetName(), k.config.Host, obj.GetNamespace()))
return k.runResourceCommand(ctx, obj, dryRunStrategy, func(f cmdutil.Factory, ioStreams genericclioptions.IOStreams, fileName string) error {
cleanup, err := k.processKubectlRun("replace")
if err != nil {
return err
}
defer cleanup()
replaceOptions, err := k.newReplaceOptions(k.config, f, ioStreams, fileName, obj.GetNamespace(), force, dryRunStrategy)
if err != nil {
return err
}
return replaceOptions.Run(f)
})
}
func (k *kubectlResourceOperations) CreateResource(ctx context.Context, obj *unstructured.Unstructured, dryRunStrategy cmdutil.DryRunStrategy, validate bool) (string, error) {
gvk := obj.GroupVersionKind()
span := k.tracer.StartSpan("CreateResource")
span.SetBaggageItem("kind", gvk.Kind)
span.SetBaggageItem("name", obj.GetName())
defer span.Finish()
return k.runResourceCommand(ctx, obj, dryRunStrategy, func(f cmdutil.Factory, ioStreams genericclioptions.IOStreams, fileName string) error {
cleanup, err := k.processKubectlRun("create")
if err != nil {
return err
}
defer cleanup()
createOptions, err := k.newCreateOptions(k.config, ioStreams, fileName, dryRunStrategy)
if err != nil {
return err
}
command := &cobra.Command{}
saveConfig := false
command.Flags().BoolVar(&saveConfig, "save-config", false, "")
val := false
command.Flags().BoolVar(&val, "validate", false, "")
if validate {
_ = command.Flags().Set("validate", "true")
}
return createOptions.RunCreate(f, command)
})
}
func (k *kubectlResourceOperations) UpdateResource(ctx context.Context, obj *unstructured.Unstructured, dryRunStrategy cmdutil.DryRunStrategy) (*unstructured.Unstructured, error) {
gvk := obj.GroupVersionKind()
span := k.tracer.StartSpan("UpdateResource")
span.SetBaggageItem("kind", gvk.Kind)
span.SetBaggageItem("name", obj.GetName())
defer span.Finish()
dynamicIf, err := dynamic.NewForConfig(k.config)
if err != nil {
return nil, err
}
disco, err := discovery.NewDiscoveryClientForConfig(k.config)
if err != nil {
return nil, err
}
apiResource, err := ServerResourceForGroupVersionKind(disco, gvk, "update")
if err != nil {
return nil, err
}
resource := gvk.GroupVersion().WithResource(apiResource.Name)
resourceIf := ToResourceInterface(dynamicIf, apiResource, resource, obj.GetNamespace())
updateOptions := metav1.UpdateOptions{}
switch dryRunStrategy {
case cmdutil.DryRunClient, cmdutil.DryRunServer:
updateOptions.DryRun = []string{metav1.DryRunAll}
}
return resourceIf.Update(ctx, obj, updateOptions)
}
// ApplyResource performs an apply of a unstructured resource
func (k *kubectlResourceOperations) ApplyResource(ctx context.Context, obj *unstructured.Unstructured, dryRunStrategy cmdutil.DryRunStrategy, force, validate, serverSideApply bool, manager string, serverSideDiff bool) (string, error) {
span := k.tracer.StartSpan("ApplyResource")
span.SetBaggageItem("kind", obj.GetKind())
span.SetBaggageItem("name", obj.GetName())
defer span.Finish()
k.log.Info(fmt.Sprintf("Applying resource %s/%s in cluster: %s, namespace: %s", obj.GetKind(), obj.GetName(), k.config.Host, obj.GetNamespace()))
return k.runResourceCommand(ctx, obj, dryRunStrategy, func(f cmdutil.Factory, ioStreams genericclioptions.IOStreams, fileName string) error {
cleanup, err := k.processKubectlRun("apply")
if err != nil {
return err
}
defer cleanup()
applyOpts, err := k.newApplyOptions(ioStreams, obj, fileName, validate, force, serverSideApply, dryRunStrategy, manager, serverSideDiff)
if err != nil {
return err
}
return applyOpts.Run()
})
}
func (k *kubectlResourceOperations) newApplyOptions(ioStreams genericclioptions.IOStreams, obj *unstructured.Unstructured, fileName string, validate bool, force, serverSideApply bool, dryRunStrategy cmdutil.DryRunStrategy, manager string, serverSideDiff bool) (*apply.ApplyOptions, error) {
flags := apply.NewApplyFlags(k.fact, ioStreams)
o := &apply.ApplyOptions{
IOStreams: ioStreams,
VisitedUids: sets.NewString(),
VisitedNamespaces: sets.NewString(),
Recorder: genericclioptions.NoopRecorder{},
PrintFlags: flags.PrintFlags,
Overwrite: true,
OpenAPIPatch: true,
ServerSideApply: serverSideApply,
}
dynamicClient, err := dynamic.NewForConfig(k.config)
if err != nil {
return nil, err
}
o.DynamicClient = dynamicClient
o.DeleteOptions, err = delete.NewDeleteFlags("").ToOptions(dynamicClient, ioStreams)
if err != nil {
return nil, err
}
o.OpenAPISchema = k.openAPISchema
o.DryRunVerifier = resource.NewQueryParamVerifier(dynamicClient, k.fact.OpenAPIGetter(), resource.QueryParamDryRun)
o.FieldValidationVerifier = resource.NewQueryParamVerifier(dynamicClient, k.fact.OpenAPIGetter(), resource.QueryParamFieldValidation)
validateDirective := metav1.FieldValidationIgnore
if validate {
validateDirective = metav1.FieldValidationStrict
}
o.Validator, err = k.fact.Validator(validateDirective, o.DryRunVerifier)
if err != nil {
return nil, err
}
o.Builder = k.fact.NewBuilder()
o.Mapper, err = k.fact.ToRESTMapper()
if err != nil {
return nil, err
}
o.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {
o.PrintFlags.NamePrintFlags.Operation = operation
switch o.DryRunStrategy {
case cmdutil.DryRunClient:
err = o.PrintFlags.Complete("%s (dry run)")
if err != nil {
return nil, err
}
case cmdutil.DryRunServer:
if serverSideDiff {
// managedFields are required by server-side diff to identify
// changes made by mutation webhooks.
o.PrintFlags.JSONYamlPrintFlags.ShowManagedFields = true
p, err := o.PrintFlags.JSONYamlPrintFlags.ToPrinter("json")
if err != nil {
return nil, fmt.Errorf("error configuring server-side diff printer: %w", err)
}
return p, nil
} else {
err = o.PrintFlags.Complete("%s (server dry run)")
if err != nil {
return nil, fmt.Errorf("error configuring server dryrun printer: %w", err)
}
}
}
return o.PrintFlags.ToPrinter()
}
o.DeleteOptions.FilenameOptions.Filenames = []string{fileName}
o.Namespace = obj.GetNamespace()
o.DeleteOptions.ForceDeletion = force
o.DryRunStrategy = dryRunStrategy
if manager != "" {
o.FieldManager = manager
}
if serverSideApply {
o.ForceConflicts = true
}
return o, nil
}
func (k *kubectlResourceOperations) newCreateOptions(config *rest.Config, ioStreams genericclioptions.IOStreams, fileName string, dryRunStrategy cmdutil.DryRunStrategy) (*create.CreateOptions, error) {
o := create.NewCreateOptions(ioStreams)
recorder, err := o.RecordFlags.ToRecorder()
if err != nil {
return nil, err
}
o.Recorder = recorder
dynamicClient, err := dynamic.NewForConfig(config)
if err != nil {
return nil, err
}
o.DryRunVerifier = resource.NewQueryParamVerifier(dynamicClient, k.fact.OpenAPIGetter(), resource.QueryParamDryRun)
o.FieldValidationVerifier = resource.NewQueryParamVerifier(dynamicClient, k.fact.OpenAPIGetter(), resource.QueryParamFieldValidation)
switch dryRunStrategy {
case cmdutil.DryRunClient:
err = o.PrintFlags.Complete("%s (dry run)")
if err != nil {
return nil, err
}
case cmdutil.DryRunServer:
err = o.PrintFlags.Complete("%s (server dry run)")
if err != nil {
return nil, err
}
}
o.DryRunStrategy = dryRunStrategy
printer, err := o.PrintFlags.ToPrinter()
if err != nil {
return nil, err
}
o.PrintObj = func(obj runtime.Object) error {
return printer.PrintObj(obj, o.Out)
}
o.FilenameOptions.Filenames = []string{fileName}
return o, nil
}
func (k *kubectlResourceOperations) newReplaceOptions(config *rest.Config, f cmdutil.Factory, ioStreams genericclioptions.IOStreams, fileName string, namespace string, force bool, dryRunStrategy cmdutil.DryRunStrategy) (*replace.ReplaceOptions, error) {
o := replace.NewReplaceOptions(ioStreams)
recorder, err := o.RecordFlags.ToRecorder()
if err != nil {
return nil, err
}
o.Recorder = recorder
dynamicClient, err := dynamic.NewForConfig(config)
if err != nil {
return nil, err
}
o.DeleteOptions, err = o.DeleteFlags.ToOptions(dynamicClient, o.IOStreams)
if err != nil {
return nil, err
}
o.DryRunVerifier = resource.NewQueryParamVerifier(dynamicClient, k.fact.OpenAPIGetter(), resource.QueryParamDryRun)
o.FieldValidationVerifier = resource.NewQueryParamVerifier(dynamicClient, k.fact.OpenAPIGetter(), resource.QueryParamFieldValidation)
o.Builder = func() *resource.Builder {
return f.NewBuilder()
}
switch dryRunStrategy {
case cmdutil.DryRunClient:
err = o.PrintFlags.Complete("%s (dry run)")
if err != nil {
return nil, err
}
case cmdutil.DryRunServer:
err = o.PrintFlags.Complete("%s (server dry run)")
if err != nil {
return nil, err
}
}
o.DryRunStrategy = dryRunStrategy
printer, err := o.PrintFlags.ToPrinter()
if err != nil {
return nil, err
}
o.PrintObj = func(obj runtime.Object) error {
return printer.PrintObj(obj, o.Out)
}
o.DeleteOptions.FilenameOptions.Filenames = []string{fileName}
o.Namespace = namespace
o.DeleteOptions.ForceDeletion = force
return o, nil
}
func newReconcileOptions(f cmdutil.Factory, kubeClient *kubernetes.Clientset, fileName string, ioStreams genericclioptions.IOStreams, namespace string, dryRunStrategy cmdutil.DryRunStrategy) (*auth.ReconcileOptions, error) {
o := auth.NewReconcileOptions(ioStreams)
o.RBACClient = kubeClient.RbacV1()
o.NamespaceClient = kubeClient.CoreV1()
o.FilenameOptions.Filenames = []string{fileName}
o.DryRun = dryRunStrategy != cmdutil.DryRunNone
r := f.NewBuilder().
WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
NamespaceParam(namespace).DefaultNamespace().
FilenameParam(false, o.FilenameOptions).
Flatten().
Do()
o.Visitor = r
if o.DryRun {
err := o.PrintFlags.Complete("%s (dry run)")
if err != nil {
return nil, err
}
}
printer, err := o.PrintFlags.ToPrinter()
if err != nil {
return nil, err
}
o.PrintObject = printer.PrintObj
return o, nil
}
func (k *kubectlResourceOperations) authReconcile(ctx context.Context, obj *unstructured.Unstructured, manifestFile string, dryRunStrategy cmdutil.DryRunStrategy) (string, error) {
kubeClient, err := kubernetes.NewForConfig(k.config)
if err != nil {
return "", err
}
// `kubectl auth reconcile` has a side effect of auto-creating namespaces if it doesn't exist.
// See: https://github.com/kubernetes/kubernetes/issues/71185. This is behavior which we do
// not want. We need to check if the namespace exists, before know if it is safe to run this
// command. Skip this for dryRuns.
if dryRunStrategy == cmdutil.DryRunNone && obj.GetNamespace() != "" {
_, err = kubeClient.CoreV1().Namespaces().Get(ctx, obj.GetNamespace(), metav1.GetOptions{})
if err != nil {
return "", err
}
}
ioStreams := genericclioptions.IOStreams{
In: &bytes.Buffer{},
Out: &bytes.Buffer{},
ErrOut: &bytes.Buffer{},
}
reconcileOpts, err := newReconcileOptions(k.fact, kubeClient, manifestFile, ioStreams, obj.GetNamespace(), dryRunStrategy)
if err != nil {
return "", err
}
err = reconcileOpts.Validate()
if err != nil {
return "", errors.New(cleanKubectlOutput(err.Error()))
}
err = reconcileOpts.RunReconcile()
if err != nil {
return "", errors.New(cleanKubectlOutput(err.Error()))
}
var out []string
if buf := strings.TrimSpace(ioStreams.Out.(*bytes.Buffer).String()); len(buf) > 0 {
out = append(out, buf)
}
if buf := strings.TrimSpace(ioStreams.ErrOut.(*bytes.Buffer).String()); len(buf) > 0 {
out = append(out, buf)
}
return strings.Join(out, ". "), nil
}
func (k *kubectlResourceOperations) processKubectlRun(cmd string) (CleanupFunc, error) {
if k.onKubectlRun != nil {
return k.onKubectlRun(cmd)
}
return func() {}, nil
}