Apply sends an apply patch with force=true using cc and updates object with any returned content. The client is responsible for setting fieldManager; see [client.WithFieldOwner]. - https://docs.k8s.io/reference/using-api/server-side-apply#managers - https://docs.k8s.io/reference/using-api/server-si
(ctx context.Context, cc ClientPatch, object T)
| 18 | // - https://docs.k8s.io/reference/using-api/server-side-apply#managers |
| 19 | // - https://docs.k8s.io/reference/using-api/server-side-apply#conflicts |
| 20 | func Apply[ |
| 21 | // NOTE: This interface can go away following https://go.dev/issue/47487. |
| 22 | ClientPatch interface { |
| 23 | Patch(context.Context, client.Object, client.Patch, ...client.PatchOption) error |
| 24 | }, |
| 25 | T interface{ client.Object }, |
| 26 | ](ctx context.Context, cc ClientPatch, object T) error { |
| 27 | // Generate an apply-patch by comparing the object to its zero value. |
| 28 | data, err := client.MergeFrom(*new(T)).Data(object) |
| 29 | apply := client.RawPatch(client.Apply.Type(), data) |
| 30 | |
| 31 | // Keep a copy of the object before any API calls. |
| 32 | intent := object.DeepCopyObject() |
| 33 | |
| 34 | // Send the apply-patch with force=true. |
| 35 | if err == nil { |
| 36 | err = cc.Patch(ctx, object, apply, client.ForceOwnership) |
| 37 | } |
| 38 | |
| 39 | // Some fields cannot be server-side applied correctly. |
| 40 | // When their outcome does not match the intent, send a json-patch to get really specific. |
| 41 | patch := NewJSONPatch() |
| 42 | |
| 43 | switch actual := any(object).(type) { |
| 44 | case *corev1.Service: |
| 45 | intent := intent.(*corev1.Service) |
| 46 | |
| 47 | // Service.Spec.Selector cannot be unset; perhaps https://issue.k8s.io/117447 |
| 48 | if !equality.Semantic.DeepEqual(actual.Spec.Selector, intent.Spec.Selector) { |
| 49 | patch.Replace("spec", "selector")(intent.Spec.Selector) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | // Send the json-patch when necessary. |
| 54 | if err == nil && !patch.IsEmpty() { |
| 55 | err = cc.Patch(ctx, object, patch) |
| 56 | } |
| 57 | return err |
| 58 | } |