|
| 1 | +package resourceapply |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + networkingv1 "k8s.io/api/networking/v1" |
| 7 | + "k8s.io/apimachinery/pkg/api/equality" |
| 8 | + apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 9 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 10 | + networkingclientv1 "k8s.io/client-go/kubernetes/typed/networking/v1" |
| 11 | + "k8s.io/klog/v2" |
| 12 | + |
| 13 | + "github.com/openshift/library-go/pkg/operator/events" |
| 14 | + "github.com/openshift/library-go/pkg/operator/resource/resourcehelper" |
| 15 | + "github.com/openshift/library-go/pkg/operator/resource/resourcemerge" |
| 16 | +) |
| 17 | + |
| 18 | +// ApplyClusterRole merges objectmeta, does not worry about anything else |
| 19 | +func ApplyNetworkPolicy(ctx context.Context, client networkingclientv1.NetworkPoliciesGetter, recorder events.Recorder, required *networkingv1.NetworkPolicy) (*networkingv1.NetworkPolicy, bool, error) { |
| 20 | + existing, err := client.NetworkPolicies(required.Namespace).Get(ctx, required.Name, metav1.GetOptions{}) |
| 21 | + if apierrors.IsNotFound(err) { |
| 22 | + requiredCopy := required.DeepCopy() |
| 23 | + actual, err := client.NetworkPolicies(required.Namespace).Create( |
| 24 | + ctx, resourcemerge.WithCleanLabelsAndAnnotations(requiredCopy).(*networkingv1.NetworkPolicy), metav1.CreateOptions{}) |
| 25 | + resourcehelper.ReportCreateEvent(recorder, required, err) |
| 26 | + return actual, true, err |
| 27 | + } |
| 28 | + if err != nil { |
| 29 | + return nil, false, err |
| 30 | + } |
| 31 | + |
| 32 | + modified := false |
| 33 | + existingCopy := existing.DeepCopy() |
| 34 | + |
| 35 | + resourcemerge.EnsureObjectMeta(&modified, &existingCopy.ObjectMeta, required.ObjectMeta) |
| 36 | + if equality.Semantic.DeepEqual(existingCopy.Spec, required.Spec) && !modified { |
| 37 | + return existingCopy, false, nil |
| 38 | + } |
| 39 | + |
| 40 | + if klog.V(2).Enabled() { |
| 41 | + klog.Infof("NetworkPolicy %q changes: %v", required.Name, JSONPatchNoError(existing, existingCopy)) |
| 42 | + } |
| 43 | + |
| 44 | + actual, err := client.NetworkPolicies(existingCopy.Namespace).Update(ctx, existingCopy, metav1.UpdateOptions{}) |
| 45 | + resourcehelper.ReportUpdateEvent(recorder, required, err) |
| 46 | + return actual, true, err |
| 47 | +} |
| 48 | + |
| 49 | +func DeleteNetworkPolicy(ctx context.Context, client networkingclientv1.NetworkPoliciesGetter, recorder events.Recorder, required *networkingv1.NetworkPolicy) (*networkingv1.NetworkPolicy, bool, error) { |
| 50 | + err := client.NetworkPolicies(required.Namespace).Delete(ctx, required.Name, metav1.DeleteOptions{}) |
| 51 | + if err != nil && apierrors.IsNotFound(err) { |
| 52 | + return nil, false, nil |
| 53 | + } |
| 54 | + if err != nil { |
| 55 | + return nil, false, err |
| 56 | + } |
| 57 | + resourcehelper.ReportDeleteEvent(recorder, required, err) |
| 58 | + return nil, true, nil |
| 59 | +} |
0 commit comments