forked from kubernetes-sigs/kubebuilder-declarative-pattern
/
applylib.go
99 lines (78 loc) · 2.33 KB
/
applylib.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
package applier
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/dynamic"
"github.com/yuwenma/kubebuilder-declarative-pattern/applylib/applyset"
)
type ApplySetApplier struct {
patchOptions metav1.PatchOptions
}
var _ Applier = &ApplySetApplier{}
func NewApplySetApplier(patchOptions metav1.PatchOptions) *ApplySetApplier {
return &ApplySetApplier{patchOptions: patchOptions}
}
func (a *ApplySetApplier) Apply(ctx context.Context, opt ApplierOptions) error {
patchOptions := a.patchOptions
for _, arg := range opt.ExtraArgs {
switch arg {
case "--force":
opt.Force = true
default:
return fmt.Errorf("extraArg %q is not supported by the ApplySetApplier", arg)
}
}
patchOptions.Force = &opt.Force
dynamicClient, err := dynamic.NewForConfig(opt.RESTConfig)
if err != nil {
return fmt.Errorf("error building dynamic client: %w", err)
}
restMapper := opt.RESTMapper
options := applyset.Options{
PatchOptions: patchOptions,
RESTMapper: restMapper,
Client: dynamicClient,
}
s, err := applyset.New(options)
if err != nil {
return fmt.Errorf("error creating applyset: %w", err)
}
// Populate the namespace on any namespace-scoped objects
if opt.Namespace != "" {
for _, obj := range opt.Objects {
gvk := obj.GroupVersionKind()
restMapping, err := restMapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
return fmt.Errorf("error getting rest mapping for %v: %w", gvk, err)
}
switch restMapping.Scope {
case meta.RESTScopeNamespace:
obj.SetNamespace(opt.Namespace)
case meta.RESTScopeRoot:
// Don't set namespace
default:
return fmt.Errorf("unknown rest mapping scope %v", restMapping.Scope)
}
}
}
var applyableObjects []applyset.ApplyableObject
for _, obj := range opt.Objects {
applyableObject := obj.UnstructuredObject()
applyableObjects = append(applyableObjects, applyableObject)
}
if err := s.SetDesiredObjects(applyableObjects); err != nil {
return fmt.Errorf("error setting desired objects for apply: %w", err)
}
results, err := s.ApplyOnce(ctx)
if err != nil {
// TODO: Aggregate errors?
return fmt.Errorf("error applying objects: %w", err)
}
if !results.AllApplied() {
return fmt.Errorf("not all objects applied")
}
// TODO: Check healthy
return nil
}