|
| 1 | +package util |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" |
| 7 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 8 | + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 9 | + "k8s.io/apimachinery/pkg/runtime" |
| 10 | + kscheme "k8s.io/client-go/kubernetes/scheme" |
| 11 | + apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" |
| 12 | + "reflect" |
| 13 | + controllerclient "sigs.k8s.io/controller-runtime/pkg/client" |
| 14 | +) |
| 15 | + |
| 16 | +const ( |
| 17 | + defaultOwner = "operator-lifecycle-manager" |
| 18 | +) |
| 19 | + |
| 20 | +var ( |
| 21 | + localSchemeBuilder = runtime.NewSchemeBuilder( |
| 22 | + kscheme.AddToScheme, |
| 23 | + apiextensionsv1.AddToScheme, |
| 24 | + apiregistrationv1.AddToScheme, |
| 25 | + ) |
| 26 | +) |
| 27 | + |
| 28 | +type Object interface { |
| 29 | + runtime.Object |
| 30 | + metav1.Object |
| 31 | +} |
| 32 | + |
| 33 | +func SetDefaultGroupVersionKind(obj Object, s *runtime.Scheme) { |
| 34 | + gvk := obj.GetObjectKind().GroupVersionKind() |
| 35 | + if s == nil { |
| 36 | + s = runtime.NewScheme() |
| 37 | + _ = localSchemeBuilder.AddToScheme(s) |
| 38 | + } |
| 39 | + if gvk.Empty() && s != nil { |
| 40 | + // Best-effort guess the GVK |
| 41 | + gvks, _, err := s.ObjectKinds(obj) |
| 42 | + if err != nil { |
| 43 | + panic(fmt.Sprintf("unable to get gvks for object %T: %s", obj, err)) |
| 44 | + } |
| 45 | + if len(gvks) == 0 || gvks[0].Empty() { |
| 46 | + panic(fmt.Sprintf("unexpected gvks registered for object %T: %v", obj, gvks)) |
| 47 | + } |
| 48 | + // TODO: The same object can be registered for multiple group versions |
| 49 | + // (although in practise this doesn't seem to be used). |
| 50 | + // In such case, the version set may not be correct. |
| 51 | + gvk = gvks[0] |
| 52 | + } |
| 53 | + obj.GetObjectKind().SetGroupVersionKind(gvk) |
| 54 | +} |
| 55 | + |
| 56 | +type ServerSideApplier struct { |
| 57 | + controllerclient.Client |
| 58 | + Scheme *runtime.Scheme |
| 59 | + // Owner becomes the Field Manager for whatever field the Server-Side apply acts on |
| 60 | + Owner controllerclient.FieldOwner |
| 61 | +} |
| 62 | + |
| 63 | +// Apply returns a function that invokes a change func on an object and performs a server-side apply patch with the result and its status subresource. |
| 64 | +// The given resource must be a pointer to a struct that specifies its Name, Namespace, APIVersion, and Kind at minimum. |
| 65 | +// The given change function must be unary, matching the signature: "func(<obj type>) error". |
| 66 | +// The returned function is suitable for use w/ asyncronous assertions. |
| 67 | +// The underlying value of the given resource pointer is updated to reflect the latest cluster state each time the closure is successfully invoked. |
| 68 | +// Ex. Change the spec of an existing InstallPlan |
| 69 | +// |
| 70 | +// plan := &InstallPlan{} |
| 71 | +// plan.SetNamespace("ns") |
| 72 | +// plan.SetName("install-123def") |
| 73 | +// plan.GetObjectKind().SetGroupVersionKind(schema.GroupVersionKind{ |
| 74 | +// Group: GroupName, |
| 75 | +// Version: GroupVersion, |
| 76 | +// Kind: InstallPlanKind, |
| 77 | +// }) |
| 78 | +// Eventually(c.Apply(plan, func(p *v1alpha1.InstallPlan) error { |
| 79 | +// p.Spec.Approved = true |
| 80 | +// return nil |
| 81 | +// })).Should(Succeed()) |
| 82 | +func (client *ServerSideApplier) Apply(obj Object, changeFunc interface{}) func() error { |
| 83 | + // Ensure given object is a pointer |
| 84 | + objType := reflect.TypeOf(obj) |
| 85 | + if objType.Kind() != reflect.Ptr { |
| 86 | + panic(fmt.Sprintf("argument object must be a pointer")) |
| 87 | + } |
| 88 | + |
| 89 | + // Ensure given function matches expected signature |
| 90 | + var ( |
| 91 | + change = reflect.ValueOf(changeFunc) |
| 92 | + changeType = change.Type() |
| 93 | + ) |
| 94 | + if n := changeType.NumIn(); n != 1 { |
| 95 | + panic(fmt.Sprintf("unexpected number of formal parameters in change function signature: expected 1, present %d", n)) |
| 96 | + } |
| 97 | + if pt := changeType.In(0); pt.Kind() != reflect.Interface { |
| 98 | + if objType != pt { |
| 99 | + panic(fmt.Sprintf("argument object type does not match the change function parameter type: argument %s, parameter: %s", objType, pt)) |
| 100 | + } |
| 101 | + } else if !objType.Implements(pt) { |
| 102 | + panic(fmt.Sprintf("argument object type does not implement the change function parameter type: argument %s, parameter: %s", objType, pt)) |
| 103 | + } |
| 104 | + if n := changeType.NumOut(); n != 1 { |
| 105 | + panic(fmt.Sprintf("unexpected number of return values in change function signature: expected 1, present %d", n)) |
| 106 | + } |
| 107 | + var err error |
| 108 | + if rt := changeType.Out(0); !rt.Implements(reflect.TypeOf((*error)(nil)).Elem()) { |
| 109 | + panic(fmt.Sprintf("unexpected return type in change function signature: expected %t, present %s", err, rt)) |
| 110 | + } |
| 111 | + |
| 112 | + // Determine if we need to apply a status subresource |
| 113 | + _, applyStatus := objType.Elem().FieldByName("Status") |
| 114 | + |
| 115 | + if unstructuredObj, ok := obj.(*unstructured.Unstructured); ok { |
| 116 | + _, applyStatus = unstructuredObj.Object["status"] |
| 117 | + } else { |
| 118 | + _, applyStatus = objType.Elem().FieldByName("Status") |
| 119 | + } |
| 120 | + |
| 121 | + var ( |
| 122 | + bg = context.Background() |
| 123 | + ) |
| 124 | + key, err := controllerclient.ObjectKeyFromObject(obj) |
| 125 | + if err != nil { |
| 126 | + panic(fmt.Sprintf("unable to extract key from resource: %s", err)) |
| 127 | + } |
| 128 | + |
| 129 | + // Ensure the GVK is set before patching |
| 130 | + SetDefaultGroupVersionKind(obj, client.Scheme) |
| 131 | + |
| 132 | + return func() error { |
| 133 | + changed := func(obj Object) (Object, error) { |
| 134 | + cp := obj.DeepCopyObject().(Object) |
| 135 | + if err := client.Get(bg, key, cp); err != nil { |
| 136 | + return nil, err |
| 137 | + } |
| 138 | + // Reset the GVK after the client call strips it |
| 139 | + SetDefaultGroupVersionKind(cp, client.Scheme) |
| 140 | + cp.SetManagedFields(nil) |
| 141 | + |
| 142 | + out := change.Call([]reflect.Value{reflect.ValueOf(cp)}) |
| 143 | + if len(out) != 1 { |
| 144 | + panic(fmt.Sprintf("unexpected number of return values from apply mutation func: expected 1, returned %d", len(out))) |
| 145 | + } |
| 146 | + |
| 147 | + if err := out[0].Interface(); err != nil { |
| 148 | + return nil, err.(error) |
| 149 | + } |
| 150 | + |
| 151 | + return cp, nil |
| 152 | + } |
| 153 | + |
| 154 | + cp, err := changed(obj) |
| 155 | + if err != nil { |
| 156 | + return err |
| 157 | + } |
| 158 | + |
| 159 | + if len(client.Owner) == 0 { |
| 160 | + client.Owner = defaultOwner |
| 161 | + } |
| 162 | + |
| 163 | + if err := client.Patch(bg, cp, controllerclient.Apply, controllerclient.ForceOwnership, client.Owner); err != nil { |
| 164 | + fmt.Printf("first patch error: %s\n", err) |
| 165 | + return err |
| 166 | + } |
| 167 | + |
| 168 | + if !applyStatus { |
| 169 | + reflect.ValueOf(obj).Elem().Set(reflect.ValueOf(cp).Elem()) |
| 170 | + return nil |
| 171 | + } |
| 172 | + |
| 173 | + cp, err = changed(cp) |
| 174 | + if err != nil { |
| 175 | + return err |
| 176 | + } |
| 177 | + |
| 178 | + if err := client.Status().Patch(bg, cp, controllerclient.Apply, controllerclient.ForceOwnership, client.Owner); err != nil { |
| 179 | + fmt.Printf("second patch error: %s\n", err) |
| 180 | + return err |
| 181 | + } |
| 182 | + |
| 183 | + reflect.ValueOf(obj).Elem().Set(reflect.ValueOf(cp).Elem()) |
| 184 | + |
| 185 | + return nil |
| 186 | + } |
| 187 | +} |
0 commit comments