Skip to content
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
18 changes: 14 additions & 4 deletions internal/k8s/component_jobs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,12 @@ func TestCreateComponentDeploymentUsesConfiguredHealthReadinessProbe(t *testing.
client := &Client{kube: fake.NewSimpleClientset()}

if err := client.CreateComponentDeployment(context.Background(), "test", ComponentDeploymentSpec{
Name: "mediator",
Image: "example/mediator:test",
Port: 7037,
HealthCheckPath: "/mediator/v1/readyz",
Name: "mediator",
Image: "example/mediator:test",
Port: 7037,
ReadinessPath: "/mediator/v1/readyz",
LivenessPath: "/mediator/v1/livez",
StartupPath: "/mediator/v1/livez",
}); err != nil {
t.Fatalf("CreateComponentDeployment() error = %v", err)
}
Expand All @@ -135,6 +137,14 @@ func TestCreateComponentDeploymentUsesConfiguredHealthReadinessProbe(t *testing.
if probe.HTTPGet.Path != "/mediator/v1/readyz" {
t.Fatalf("readiness path = %q, want /mediator/v1/readyz", probe.HTTPGet.Path)
}
liveness := deployment.Spec.Template.Spec.Containers[0].LivenessProbe
if liveness == nil || liveness.HTTPGet == nil || liveness.HTTPGet.Path != "/mediator/v1/livez" {
t.Fatalf("unexpected liveness probe: %+v", liveness)
}
startup := deployment.Spec.Template.Spec.Containers[0].StartupProbe
if startup == nil || startup.HTTPGet == nil || startup.HTTPGet.Path != "/mediator/v1/livez" {
t.Fatalf("unexpected startup probe: %+v", startup)
}
if probe.HTTPGet.Port.IntVal != 7037 {
t.Fatalf("readiness port = %d, want 7037", probe.HTTPGet.Port.IntVal)
}
Expand Down
49 changes: 39 additions & 10 deletions internal/k8s/component_resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,19 @@ type ComponentDeploymentSpec struct {
Labels map[string]string
PlacementMode string
Component string
// HealthCheckPath, if set, wires an HTTP readinessProbe against this path
// on Port. Without it, Kubernetes marks the pod Ready the instant the
// ReadinessPath, if set, wires an HTTP readinessProbe against this path on
// Port. Without it, Kubernetes marks the pod Ready the instant the
// container process starts (no probe = ready-by-default), which is true
// long before the app inside has actually bound its listener — so
// WaitForComponentDeploymentReady's poll of ReadyReplicas was previously
// a near-instant no-op rather than a real "is this serving" check.
HealthCheckPath string
ReadinessPath string
// LivenessPath is process-only: it must not fail merely because a remote
// dependency is unavailable, since restarting the process cannot repair it.
LivenessPath string
// StartupPath suppresses readiness and liveness until the HTTP runtime is
// serving, protecting slow store initialization from premature restarts.
StartupPath string
// Resources sets the container's requests/limits. Memory always carries a
// limit (incompressible); CPU deliberately gets requests only — a CFS quota
// would throttle bursts even when node CPU is idle, while the request alone
Expand Down Expand Up @@ -95,19 +101,40 @@ func (c *Client) CreateComponentDeployment(ctx context.Context, ns string, spec
ports = []corev1.ContainerPort{{ContainerPort: spec.Port, Protocol: corev1.ProtocolTCP}}
}

var readinessProbe *corev1.Probe
if spec.HealthCheckPath != "" {
var readinessProbe, livenessProbe, startupProbe *corev1.Probe
if spec.ReadinessPath != "" {
readinessProbe = &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: spec.HealthCheckPath,
Path: spec.ReadinessPath,
Port: intstr.FromInt32(spec.Port),
},
},
InitialDelaySeconds: 1,
PeriodSeconds: 2,
TimeoutSeconds: 2,
FailureThreshold: 3,
PeriodSeconds: 2,
TimeoutSeconds: 2,
FailureThreshold: 3,
}
}
if spec.LivenessPath != "" {
livenessProbe = &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{HTTPGet: &corev1.HTTPGetAction{
Path: spec.LivenessPath,
Port: intstr.FromInt32(spec.Port),
}},
PeriodSeconds: 10,
TimeoutSeconds: 2,
FailureThreshold: 3,
}
}
if spec.StartupPath != "" {
startupProbe = &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{HTTPGet: &corev1.HTTPGetAction{
Path: spec.StartupPath,
Port: intstr.FromInt32(spec.Port),
}},
PeriodSeconds: 2,
TimeoutSeconds: 2,
FailureThreshold: 60,
}
}

Expand Down Expand Up @@ -135,6 +162,8 @@ func (c *Client) CreateComponentDeployment(ctx context.Context, ns string, spec
Ports: ports,
VolumeMounts: mounts,
ReadinessProbe: readinessProbe,
LivenessProbe: livenessProbe,
StartupProbe: startupProbe,
Resources: spec.Resources,
}},
Volumes: volumes,
Expand Down
2 changes: 1 addition & 1 deletion internal/k8s/trust_registry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func TestRegistryJobRetryRetainsIdentityAndActiveJobs(t *testing.T) {
func TestRegistryDeploymentKeepsCredentialInMemoryAndOutOfExports(t *testing.T) {
kube := fake.NewSimpleClientset()
client := &Client{kube: kube}
spec := ComponentDeploymentSpec{Name: "registry", Labels: map[string]string{"app": "registry"}, Image: "registry:image", ServiceAccount: VtaServiceAccount, Command: []string{"trust-registry"}, Port: 3232, HealthCheckPath: "/health", Recreate: true,
spec := ComponentDeploymentSpec{Name: "registry", Labels: map[string]string{"app": "registry"}, Image: "registry:image", ServiceAccount: VtaServiceAccount, Command: []string{"trust-registry"}, Port: 3232, ReadinessPath: "/readyz", LivenessPath: "/livez", StartupPath: "/livez", Recreate: true,
Env: []corev1.EnvVar{{Name: "MEDIATOR_DID", Value: "did:webvh:mediator"}, {Name: "TR_VTA_CONTEXT_ID", Value: "registry-7"}, {Name: "TR_SECRETS_SEED", Value: "test-only-secret"}},
ExtraVolumes: []corev1.Volume{{Name: "credential", VolumeSource: corev1.VolumeSource{EmptyDir: &corev1.EmptyDirVolumeSource{Medium: corev1.StorageMediumMemory}}}},
ExtraMounts: []corev1.VolumeMount{{Name: "credential", MountPath: "/run/trust-registry", ReadOnly: true}},
Expand Down
137 changes: 131 additions & 6 deletions internal/k8s/upgrade.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,122 @@ import (
"time"

appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/util/retry"
)

const recoveryRestartAnnotation = "vtafarm.ic3software.com/recovery-restarted-at"

type upgradeProbePaths struct {
readiness string
liveness string
startup string
}

func currentProbePathsFor(app string) (upgradeProbePaths, bool) {
switch app {
case "vta", "fs-vta", "fs-vtc", "fs-trust-registry", "fs-dids":
return upgradeProbePaths{readiness: "/readyz", liveness: "/livez", startup: "/livez"}, true
case "fs-mediator":
return upgradeProbePaths{
readiness: "/mediator/v1/readyz",
liveness: "/mediator/v1/livez",
startup: "/mediator/v1/livez",
}, true
default:
return upgradeProbePaths{}, false
}
}

// rollbackProbePathsFor uses only endpoints available before the dedicated
// probes landed, so a failed new image can still roll back cleanly.
func rollbackProbePathsFor(app string) (upgradeProbePaths, bool) {
switch app {
case "vta", "fs-vta", "fs-vtc", "fs-trust-registry":
return upgradeProbePaths{readiness: "/health", liveness: "/health", startup: "/health"}, true
case "fs-dids":
return upgradeProbePaths{readiness: "/health"}, true
case "fs-mediator":
return upgradeProbePaths{readiness: "/mediator/v1/readyz"}, true
default:
return upgradeProbePaths{}, false
}
}

func upgradeHTTPProbe(path string, port int32, period, failures int32) *corev1.Probe {
if path == "" {
return nil
}
return &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{HTTPGet: &corev1.HTTPGetAction{
Path: path,
Port: intstr.FromInt32(port),
}},
PeriodSeconds: period,
TimeoutSeconds: 2,
FailureThreshold: failures,
}
}

func isManagedHTTPProbe(probe *corev1.Probe, port, period, failures int32, paths ...string) bool {
if probe == nil || probe.HTTPGet == nil || probe.HTTPGet.Port.IntVal != port ||
probe.PeriodSeconds != period || probe.TimeoutSeconds != 2 ||
probe.FailureThreshold != failures {
return false
}
for _, path := range paths {
if path != "" && probe.HTTPGet.Path == path {
return true
}
}
return false
}

func reconcileProbe(
probe **corev1.Probe,
desiredPath string,
port, period, failures int32,
managedPaths ...string,
) {
if *probe != nil && !isManagedHTTPProbe(*probe, port, period, failures, managedPaths...) {
return
}
*probe = upgradeHTTPProbe(desiredPath, port, period, failures)
}

func reconcileHealthProbes(deployment *appsv1.Deployment, rollback bool) {
current, ok := currentProbePathsFor(deployment.Labels["app"])
if !ok || len(deployment.Spec.Template.Spec.Containers) == 0 {
return
}
legacy, _ := rollbackProbePathsFor(deployment.Labels["app"])
desired := current
if rollback {
desired = legacy
}
container := &deployment.Spec.Template.Spec.Containers[0]
if len(container.Ports) == 0 {
return
}
port := container.Ports[0].ContainerPort
reconcileProbe(&container.ReadinessProbe, desired.readiness, port, 2, 3, current.readiness, legacy.readiness)
reconcileProbe(&container.LivenessProbe, desired.liveness, port, 10, 3, current.liveness, legacy.liveness)
reconcileProbe(&container.StartupProbe, desired.startup, port, 2, 60, current.startup, legacy.startup)
}

// reconcileUpgradeHealthProbes fills missing probes and migrates probes from
// the Farm's former `/health` policy. Other operator-supplied probes remain.
func reconcileUpgradeHealthProbes(deployment *appsv1.Deployment) {
reconcileHealthProbes(deployment, false)
}

func reconcileRollbackHealthProbes(deployment *appsv1.Deployment) {
reconcileHealthProbes(deployment, true)
}

// VtaDeploymentName exposes vta_only's Deployment name (vta-<sessionID>) to
// the upgrade runner, which patches Deployments created by CreateVtaDeployment.
// full_stack components use the exported FS*Name funcs directly.
Expand All @@ -21,13 +130,24 @@ func VtaDeploymentName(sessionID uint) string {
}

// SetDeploymentImage points every container in the Deployment at image and
// forces the Recreate strategy. The same rollout reconciles component tuning and an
// existing mediator's persisted Vault CA configuration. Recreate matters: these Deployments mount RWO
// PVCs, so the default RollingUpdate would start the new pod while the old
// one still holds the volume and deadlock the rollout. Replacing the whole
// Strategy struct also clears any rollingUpdate params, which the API server
// rejects alongside type Recreate.
// forces the Recreate strategy. The same rollout reconciles component tuning,
// missing health probes, and an existing mediator's persisted Vault CA
// configuration. Recreate matters: these Deployments mount RWO PVCs, so the
// default RollingUpdate would start the new pod while the old one still holds
// the volume and deadlock the rollout. Replacing the whole Strategy struct also
// clears any rollingUpdate params, which the API server rejects alongside type
// Recreate.
func (c *Client) SetDeploymentImage(ctx context.Context, ns, name, image string) error {
return c.setDeploymentImage(ctx, ns, name, image, false)
}

// RollbackDeploymentImage restores an older image with the legacy probe paths
// that image is guaranteed to expose.
func (c *Client) RollbackDeploymentImage(ctx context.Context, ns, name, image string) error {
return c.setDeploymentImage(ctx, ns, name, image, true)
}

func (c *Client) setDeploymentImage(ctx context.Context, ns, name, image string, rollback bool) error {
return retry.RetryOnConflict(retry.DefaultRetry, func() error {
deploy, err := c.kube.AppsV1().Deployments(ns).Get(ctx, name, metav1.GetOptions{})
if err != nil {
Expand All @@ -38,6 +158,11 @@ func (c *Client) SetDeploymentImage(ctx context.Context, ns, name, image string)
deploy.Spec.Template.Spec.Containers[i].Image = image
}
reconcileTuningEnv(deploy)
if rollback {
reconcileRollbackHealthProbes(deploy)
} else {
reconcileUpgradeHealthProbes(deploy)
}
ensureMediatorVaultCA(deploy, image)
_, err = c.kube.AppsV1().Deployments(ns).Update(ctx, deploy, metav1.UpdateOptions{})
return err
Expand Down
94 changes: 94 additions & 0 deletions internal/k8s/upgrade_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,100 @@ func deploymentEnv(t *testing.T, client *Client, name string) map[string]string
return env
}

func TestImageUpgradeAndRollbackReconcileHealthProbes(t *testing.T) {
cases := []struct {
app string
port int32
legacyReadiness, legacyLiveness string
legacyStartup string
currentReadiness, currentLiveness string
currentStartup string
}{
{app: "vta", port: 8100, legacyReadiness: "/health", legacyLiveness: "/health", legacyStartup: "/health", currentReadiness: "/readyz", currentLiveness: "/livez", currentStartup: "/livez"},
{app: "fs-vta", port: 8100, legacyReadiness: "/health", legacyLiveness: "/health", legacyStartup: "/health", currentReadiness: "/readyz", currentLiveness: "/livez", currentStartup: "/livez"},
{app: "fs-vtc", port: 8200, legacyReadiness: "/health", legacyLiveness: "/health", legacyStartup: "/health", currentReadiness: "/readyz", currentLiveness: "/livez", currentStartup: "/livez"},
{app: "fs-trust-registry", port: 3232, legacyReadiness: "/health", legacyLiveness: "/health", legacyStartup: "/health", currentReadiness: "/readyz", currentLiveness: "/livez", currentStartup: "/livez"},
{app: "fs-mediator", port: 7037, legacyReadiness: "/mediator/v1/readyz", currentReadiness: "/mediator/v1/readyz", currentLiveness: "/mediator/v1/livez", currentStartup: "/mediator/v1/livez"},
{app: "fs-dids", port: 8534, legacyReadiness: "/health", currentReadiness: "/readyz", currentLiveness: "/livez", currentStartup: "/livez"},
}
for _, tc := range cases {
for _, initial := range []string{"missing", "legacy"} {
t.Run(tc.app+"/"+initial, func(t *testing.T) {
deployment := tuningTestDeployment("workload", tc.app)
container := &deployment.Spec.Template.Spec.Containers[0]
container.Ports = []corev1.ContainerPort{{ContainerPort: tc.port}}
if initial == "legacy" {
container.ReadinessProbe = upgradeHTTPProbe(tc.legacyReadiness, tc.port, 2, 3)
container.LivenessProbe = upgradeHTTPProbe(tc.legacyLiveness, tc.port, 10, 3)
container.StartupProbe = upgradeHTTPProbe(tc.legacyStartup, tc.port, 2, 60)
}
client := &Client{kube: fake.NewSimpleClientset(deployment)}

if err := client.SetDeploymentImage(context.Background(), "test", "workload", "example/new:image"); err != nil {
t.Fatalf("SetDeploymentImage() error = %v", err)
}
got, err := client.kube.AppsV1().Deployments("test").Get(context.Background(), "workload", metav1.GetOptions{})
if err != nil {
t.Fatalf("get Deployment: %v", err)
}
container = &got.Spec.Template.Spec.Containers[0]
assertHTTPProbe(t, "readiness", container.ReadinessProbe, tc.currentReadiness, tc.port)
assertHTTPProbe(t, "liveness", container.LivenessProbe, tc.currentLiveness, tc.port)
assertHTTPProbe(t, "startup", container.StartupProbe, tc.currentStartup, tc.port)

if err := client.RollbackDeploymentImage(context.Background(), "test", "workload", "example/old:image"); err != nil {
t.Fatalf("RollbackDeploymentImage() error = %v", err)
}
got, err = client.kube.AppsV1().Deployments("test").Get(context.Background(), "workload", metav1.GetOptions{})
if err != nil {
t.Fatalf("get rolled-back Deployment: %v", err)
}
container = &got.Spec.Template.Spec.Containers[0]
assertHTTPProbe(t, "rollback readiness", container.ReadinessProbe, tc.legacyReadiness, tc.port)
assertHTTPProbe(t, "rollback liveness", container.LivenessProbe, tc.legacyLiveness, tc.port)
assertHTTPProbe(t, "rollback startup", container.StartupProbe, tc.legacyStartup, tc.port)
})
}
}
}

func TestSetDeploymentImagePreservesOperatorHealthProbes(t *testing.T) {
deployment := tuningTestDeployment("vta-7", "vta")
container := &deployment.Spec.Template.Spec.Containers[0]
container.Ports = []corev1.ContainerPort{{ContainerPort: 8100}}
container.ReadinessProbe = upgradeHTTPProbe("/operator-ready", 8100, 7, 4)
client := &Client{kube: fake.NewSimpleClientset(deployment)}

if err := client.SetDeploymentImage(context.Background(), "test", "vta-7", "example/vta:new"); err != nil {
t.Fatalf("SetDeploymentImage() error = %v", err)
}
got, err := client.kube.AppsV1().Deployments("test").Get(context.Background(), "vta-7", metav1.GetOptions{})
if err != nil {
t.Fatalf("get Deployment: %v", err)
}
probe := got.Spec.Template.Spec.Containers[0].ReadinessProbe
assertHTTPProbe(t, "readiness", probe, "/operator-ready", 8100)
if probe.PeriodSeconds != 7 || probe.FailureThreshold != 4 {
t.Fatalf("operator readiness timing changed: %+v", probe)
}
}

func assertHTTPProbe(t *testing.T, name string, probe *corev1.Probe, path string, port int32) {
t.Helper()
if path == "" {
if probe != nil {
t.Fatalf("%s probe = %+v, want nil", name, probe)
}
return
}
if probe == nil || probe.HTTPGet == nil {
t.Fatalf("%s probe = %+v, want HTTP probe", name, probe)
}
if probe.HTTPGet.Path != path || probe.HTTPGet.Port.IntVal != port {
t.Fatalf("%s probe = %+v, want %s:%d", name, probe.HTTPGet, path, port)
}
}

func TestSetDeploymentImageAddsMissingVtaTuningEnv(t *testing.T) {
for _, app := range []string{"vta", "fs-vta"} {
t.Run(app, func(t *testing.T) {
Expand Down
Loading