Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Ignore field should not be honored when creating the resource #784

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 19 additions & 10 deletions pkg/work/spoke/apply/server_side_apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func NewServerSideApply(client dynamic.Interface) *ServerSideApply {
func (c *ServerSideApply) Apply(
ctx context.Context,
gvr schema.GroupVersionResource,
required *unstructured.Unstructured,
requiredOriginal *unstructured.Unstructured,
owner metav1.OwnerReference,
applyOption *workapiv1.ManifestConfigOption,
recorder events.Recorder) (runtime.Object, error) {
Expand All @@ -52,12 +52,14 @@ func (c *ServerSideApply) Apply(
// https://github.com/kubernetes/kubernetes/issues/67610
//
// TODO Remove this after the above issue fixed in Kubernetes
removeCreationTimeFromMetadata(required.Object, logger)
removeCreationTimeFromMetadata(requiredOriginal.Object, logger)

force := false
fieldManager := workapiv1.DefaultFieldManager
var requiredHash string

required := requiredOriginal.DeepCopy()

if applyOption.UpdateStrategy.ServerSideApply != nil {
force = applyOption.UpdateStrategy.ServerSideApply.Force
if len(applyOption.UpdateStrategy.ServerSideApply.FieldManager) > 0 {
Expand All @@ -83,22 +85,29 @@ func (c *ServerSideApply) Apply(
}
annotation[workapiv1.ManifestConfigSpecHashAnnotationKey] = requiredHash
required.SetAnnotations(annotation)
requiredOriginal.SetAnnotations(annotation)
}
}

// only get existing resource and compare hash if the hash is computed.
if len(requiredHash) > 0 {
existing, err := c.client.Resource(gvr).Namespace(required.GetNamespace()).Get(
ctx, required.GetName(), metav1.GetOptions{})
if err != nil && !errors.IsNotFound(err) {
switch {
case errors.IsNotFound(err):
// if object is not found, directly apply without removing ignore fields in the object.
obj, createErr := c.client.
Resource(gvr).
Namespace(required.GetNamespace()).
Apply(ctx, required.GetName(), requiredOriginal, metav1.ApplyOptions{FieldManager: fieldManager, Force: force})
return obj, createErr
case err != nil:
return nil, err
} else if err == nil {
if len(existing.GetAnnotations()) > 0 {
// skip the apply operation when the hash of the existing resource does match the required hash
existingHash := existing.GetAnnotations()[workapiv1.ManifestConfigSpecHashAnnotationKey]
if requiredHash == existingHash {
return existing, nil
}
case len(existing.GetAnnotations()) > 0:
// skip the apply operation when the hash of the existing resource matches the required hash
existingHash := existing.GetAnnotations()[workapiv1.ManifestConfigSpecHashAnnotationKey]
if requiredHash == existingHash {
return existing, nil
}
}
}
Expand Down
32 changes: 32 additions & 0 deletions pkg/work/spoke/apply/server_side_apply_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,38 @@ func TestServerSideApplyWithIgnoreFields(t *testing.T) {
condition: workapiv1.IgnoreFieldsConditionOnSpokePresent,
jsonPath: ".spec.replicas",
},
{
name: "server side apply should not ignore when create",
required: testingcommon.NewUnstructuredWithContent(
"apps/v1", "Deployment", "default", "deploy1",
map[string]interface{}{
"spec": map[string]interface{}{
"replicas": int64(2),
},
}),
gvr: schema.GroupVersionResource{Version: "v1", Group: "apps", Resource: "deployments"},
validateActions: func(t *testing.T, actions []clienttesting.Action) {
testingcommon.AssertActions(t, actions, "get", "patch")
p := actions[1].(clienttesting.PatchActionImpl).Patch
actual := &unstructured.Unstructured{}
err := actual.UnmarshalJSON(p)
if err != nil {
t.Fatal(err)
}
actualReplicas, exist, err := unstructured.NestedInt64(actual.Object, "spec", "replicas")
if err != nil {
t.Fatal(err)
}
if !exist {
t.Errorf("expected replicas to exist in the patch")
}
if actualReplicas != int64(2) {
t.Errorf("expected replicas to be 2 but got %d", actualReplicas)
}
},
condition: workapiv1.IgnoreFieldsConditionOnSpokePresent,
jsonPath: ".spec.replicas",
},
{
name: "server side apply ignore update",
existing: func() *unstructured.Unstructured {
Expand Down
97 changes: 97 additions & 0 deletions test/e2e/work_workload_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -766,6 +766,103 @@ var _ = ginkgo.Describe("Work agent", ginkgo.Label("work-agent", "sanity-check")
gomega.Expect(err).ToNot(gomega.HaveOccurred())
})
})

ginkgo.Context("ManifestWork server side apply", func() {
ginkgo.It("should ignore fields with certain field", func() {
deployment := newDeployment("busybox-ssa")
deployment.Spec.Replicas = pointer.Int32(2)
objects := []runtime.Object{deployment}
work := newManifestWork(universalClusterName, workName, objects...)
work.Spec.ManifestConfigs = []workapiv1.ManifestConfigOption{
{
ResourceIdentifier: workapiv1.ResourceIdentifier{
Group: "apps",
Resource: "deployments",
Name: "busybox-ssa",
Namespace: "default",
},
UpdateStrategy: &workapiv1.UpdateStrategy{
Type: workapiv1.UpdateStrategyTypeServerSideApply,
ServerSideApply: &workapiv1.ServerSideApplyConfig{
IgnoreFields: []workapiv1.IgnoreField{
{
Condition: workapiv1.IgnoreFieldsConditionOnSpokeChange,
JSONPaths: []string{"spec.replicas"},
},
},
},
},
},
}
_, err = hub.WorkClient.WorkV1().ManifestWorks(universalClusterName).Create(context.Background(), work, metav1.CreateOptions{})
gomega.Expect(err).ToNot(gomega.HaveOccurred())

// Check deployment status
gomega.Eventually(func() error {
deploy, err := spoke.KubeClient.AppsV1().Deployments(deployment.Namespace).Get(context.Background(), deployment.Name, metav1.GetOptions{})
if err != nil {
return err
}
if *deploy.Spec.Replicas != int32(2) {
return fmt.Errorf("expected 2 replicas, got %d", *deploy.Spec.Replicas)
}
return nil
}).ShouldNot(gomega.HaveOccurred())

ginkgo.By("update replicas in the manifestwork")
gomega.Eventually(func() error {
actualWork, err := hub.WorkClient.WorkV1().ManifestWorks(universalClusterName).Get(context.Background(), workName, metav1.GetOptions{})
if err != nil {
return err
}
deployment.Spec.Replicas = pointer.Int32(3)
objects := []runtime.Object{deployment}
newWork := newManifestWork(universalClusterName, workName, objects...)
actualWork.Spec.Workload = newWork.Spec.Workload
_, err = hub.WorkClient.WorkV1().ManifestWorks(universalClusterName).Update(context.Background(), actualWork, metav1.UpdateOptions{})
return err
}).ShouldNot(gomega.HaveOccurred())

// Check deployment status
gomega.Eventually(func() error {
deploy, err := spoke.KubeClient.AppsV1().Deployments(deployment.Namespace).Get(context.Background(), deployment.Name, metav1.GetOptions{})
if err != nil {
return err
}
if *deploy.Spec.Replicas != int32(3) {
return fmt.Errorf("expected 3 replicas, got %d", *deploy.Spec.Replicas)
}
return nil
}).ShouldNot(gomega.HaveOccurred())

ginkgo.By("update work with new replicas and type to onSpokePresent")
gomega.Eventually(func() error {
actualWork, err := hub.WorkClient.WorkV1().ManifestWorks(universalClusterName).Get(context.Background(), workName, metav1.GetOptions{})
if err != nil {
return err
}
deployment.Spec.Replicas = pointer.Int32(4)
objects := []runtime.Object{deployment}
newWork := newManifestWork(universalClusterName, workName, objects...)
actualWork.Spec.Workload = newWork.Spec.Workload
actualWork.Spec.ManifestConfigs[0].UpdateStrategy.ServerSideApply.IgnoreFields[0].Condition = workapiv1.IgnoreFieldsConditionOnSpokePresent
_, err = hub.WorkClient.WorkV1().ManifestWorks(universalClusterName).Update(context.Background(), actualWork, metav1.UpdateOptions{})
return err
}).ShouldNot(gomega.HaveOccurred())

// Check deployment status, it should not be changed
gomega.Eventually(func() error {
deploy, err := spoke.KubeClient.AppsV1().Deployments(deployment.Namespace).Get(context.Background(), deployment.Name, metav1.GetOptions{})
if err != nil {
return err
}
if *deploy.Spec.Replicas != int32(3) {
return fmt.Errorf("expected 3 replicas, got %d", *deploy.Spec.Replicas)
}
return nil
}).ShouldNot(gomega.HaveOccurred())
})
})
})

func assertManifestWorkAppliedSuccessfully(workNamespace, workName string,
Expand Down
Loading