Skip to content
Open
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
137 changes: 137 additions & 0 deletions integration_tests/apply_replace.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
local user = User.new()
local team = Team.new("apply-replace-team", "Apply field removal testing", "#apply-replace-team")
team:addMember(user)

Test.rest("create resources with fields that will be omitted", function(t)
t.addHeader("x-user-email", user:email())
t.send("POST", "/api/v1/teams/apply-replace-team/environments/dev/apply", [[
{"resources": [
{
"apiVersion": "nais.io/v1alpha1",
"kind": "Application",
"metadata": {
"name": "my-app",
"labels": {"kept": "same", "removed": "old"},
"annotations": {"removed": "old"}
},
"spec": {
"image": "example.com/my-app:v1",
"resources": {
"limits": {"cpu": "1", "memory": "512Mi"},
"requests": {"cpu": "100m", "memory": "256Mi"}
}
}
},
{
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": {"name": "my-config"},
"data": {"kept": "old", "removed": "old"},
"binaryData": {"removed": "b2xk"}
}
]}
]])
t.check(200, {
results = {
{ resource = "Application/my-app", environmentName = "dev", status = "created" },
{ resource = "ConfigMap/my-config", environmentName = "dev", status = "created" },
},
})
end)

local replacement = [[
{"resources": [
{
"apiVersion": "nais.io/v1alpha1",
"kind": "Application",
"metadata": {
"name": "my-app",
"labels": {"kept": "same"}
},
"spec": {
"image": "example.com/my-app:v1",
"resources": {
"limits": {"memory": "512Mi"},
"requests": {"cpu": "100m", "memory": "256Mi"}
}
}
},
{
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": {"name": "my-config"},
"data": {"kept": "new"}
}
]}
]]

Test.rest("apply replaces omitted fields and reports changes", function(t)
t.addHeader("x-user-email", user:email())
t.send("POST", "/api/v1/teams/apply-replace-team/environments/dev/apply", replacement)
t.check(200, {
results = {
{
resource = "Application/my-app",
environmentName = "dev",
status = "applied",
changedFields = {
{ field = "metadata.annotations.removed", oldValue = "old" },
{ field = "metadata.labels.removed", oldValue = "old" },
{ field = "spec.resources.limits.cpu", oldValue = "1" },
},
},
{
resource = "ConfigMap/my-config",
environmentName = "dev",
status = "applied",
changedFields = {
{ field = "binaryData.removed", oldValue = "b2xk" },
{ field = "data.kept", oldValue = "old", newValue = "new" },
{ field = "data.removed", oldValue = "old" },
},
},
},
})
end)

Test.k8s("omitted CPU limit and metadata are removed from the stored Application", function(t)
t.check("nais.io/v1alpha1", "applications", "dev", team:slug(), "my-app", {
apiVersion = "nais.io/v1alpha1",
kind = "Application",
metadata = {
name = "my-app",
namespace = team:slug(),
labels = { kept = "same" },
},
spec = {
image = "example.com/my-app:v1",
resources = {
limits = { memory = "512Mi" },
requests = { cpu = "100m", memory = "256Mi" },
},
},
})
end)

Test.k8s("omitted data keys and top-level fields are removed from the stored ConfigMap", function(t)
t.check("v1", "configmaps", "dev", team:slug(), "my-config", {
apiVersion = "v1",
kind = "ConfigMap",
metadata = {
name = "my-config",
namespace = team:slug(),
},
data = { kept = "new" },
})
end)

Test.rest("reapplying the replacement has no changes", function(t)
t.addHeader("x-user-email", user:email())
t.send("POST", "/api/v1/teams/apply-replace-team/environments/dev/apply", replacement)
t.check(200, {
results = {
{ resource = "Application/my-app", environmentName = "dev", status = "applied" },
{ resource = "ConfigMap/my-config", environmentName = "dev", status = "applied" },
},
})
end)
52 changes: 28 additions & 24 deletions internal/apply/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,18 @@ package apply

import (
"context"
"encoding/json"
"fmt"

apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/dynamic"
)

const fieldManager = "nais-api"

// ApplyResult holds the before and after states of a server-side apply operation.
// ApplyResult holds the before and after states of an apply operation.
type ApplyResult struct {
// Before is the state of the object before the apply. Nil if the object did not exist.
Before *unstructured.Unstructured
Expand All @@ -25,9 +23,8 @@ type ApplyResult struct {
Created bool
}

// ApplyResource performs a Kubernetes server-side apply for a single resource.
// It fetches the current state (before), applies the resource, and returns both
// before and after states so the caller can diff them.
// ApplyResource creates missing resources and replaces existing resources.
// It returns both before and after states so the caller can diff them.
func ApplyResource(
ctx context.Context,
client dynamic.Interface,
Expand All @@ -46,7 +43,6 @@ func ApplyResource(

resourceClient := client.Resource(gvr).Namespace(namespace)

// Step 1: Get the current state of the object (before-state).
before, err := resourceClient.Get(ctx, name, metav1.GetOptions{})
if err != nil {
if !apierrors.IsNotFound(err) {
Expand All @@ -55,26 +51,34 @@ func ApplyResource(
before = nil
}

// Step 2: Marshal the object to JSON for the apply patch.
data, err := json.Marshal(obj.Object)
if err != nil {
return nil, fmt.Errorf("marshaling resource to JSON: %w", err)
submittedVersion := obj.GetResourceVersion()
if submittedVersion != "" {
if before == nil {
return nil, apierrors.NewConflict(gvr.GroupResource(), name, fmt.Errorf("resourceVersion %q refers to a resource that no longer exists", submittedVersion))
}
if submittedVersion != before.GetResourceVersion() {
return nil, apierrors.NewConflict(gvr.GroupResource(), name, fmt.Errorf("requested resourceVersion %q does not match current version %q", submittedVersion, before.GetResourceVersion()))
}
}

// Step 3: Server-side apply using PATCH with ApplyPatchType.
after, err := resourceClient.Patch(
ctx,
name,
types.ApplyPatchType,
data,
metav1.PatchOptions{
desired := obj.DeepCopy()
var after *unstructured.Unstructured
if before != nil {
desired.SetResourceVersion(before.GetResourceVersion())
after, err = resourceClient.Update(ctx, desired, metav1.UpdateOptions{
FieldManager: fieldManager,
Force: new(true),
FieldValidation: metav1.FieldValidationStrict,
},
)
if err != nil {
return nil, fmt.Errorf("applying %s/%s: %w", namespace, name, err)
})
if err != nil {
return nil, fmt.Errorf("updating %s/%s: %w", namespace, name, err)
}
} else {
after, err = resourceClient.Create(ctx, desired, metav1.CreateOptions{
FieldManager: fieldManager,
FieldValidation: metav1.FieldValidationStrict,
})
if err != nil {
return nil, fmt.Errorf("creating %s/%s: %w", namespace, name, err)
}
}

return &ApplyResult{
Expand Down
Loading
Loading