From fc618c1dcb086886eee591424b4ebaa98116f835 Mon Sep 17 00:00:00 2001 From: Aleksei Sviridkin Date: Mon, 30 Nov 2026 14:04:15 +0300 Subject: [PATCH] feat(workloadmonitor): report failed Jobs that opt in as not operational (#5505) ## What this PR does Refs #5459 A chart that runs workload-critical work in a Job outside its Helm release has no way to report a failed run on the Application today: `Ready` mirrors the HelmRelease, which is already applied, and `WorkloadsReady` only looks at pods, PVCs, Services, BucketClaims and DataVolumes. The immediate case is #5479, where the postgres collation repair and PostGIS update move out of a blocking hook into a Job started outside the release. If that Job fails (duplicates under a UNIQUE index, a PostGIS update that does not go through), the indexes stay wrong while the Application shows `Ready=True` and `WorkloadsReady=True`. This PR implements the proposal in https://github.com/cozystack/cozystack/issues/5459#issuecomment-7268007229 by adding a generic rule to the WorkloadMonitor controller: a `batch/v1` Job in the monitor's namespace that carries the monitor's selector labels plus `workloads.cozystack.io/report-failure: "true"`, and has `Failed=True`, makes the monitor not operational, with reason `JobFailed` and a message such as `Job postgres-x-collation-repair failed: BackoffLimitExceeded: Job has reached the specified backoff limit`. cozystack-api passes it through unchanged as `WorkloadsReady=False` with that reason and message. The rule knows nothing about postgres: a chart opts a Job in explicitly with that label. A Job with only the selector labels, which every chart and every operator inheriting labels from the workload may carry, never affects the monitor. The postgres side (the labels on the repair Job, no `ttlSecondsAfterFinished`) lands on #5479. Behaviour: - A Job that is deleted, or replaced by a run that does not fail, clears the verdict. Of the Jobs one controller owns, only the newest counts, so a CronJob's failed run that stays in its history after a later success does not keep the monitor down. - The message lists failed Jobs sorted by name, at most three, then `N more Jobs failed`. - Precedence: a DataVolume verdict comes first (unchanged; its stored value is kept while DataVolumes cannot be read), then `JobFailed`, then `BucketClaimNotReady`. `minReplicas` still sets `Operational=false` without a reason, so a failed Job beside too few replicas reports `JobFailed`. - Jobs are watched and mapped to monitors the same way pods are. The manager caches only Jobs that carry the opt-in label, with a transform that keeps only metadata (labels, owners, timestamps) and conditions. - RBAC: a `+kubebuilder:rbac` marker for `jobs.batch` get/list/watch documents the need. The markers under `internal/controller` do not generate YAML, and the cozystack-controller ClusterRole in `packages/system/cozystack-controller/templates/rbac.yaml` already grants get/list/watch on every resource, as it does for pods, PVCs, BucketClaims and DataVolumes, so the chart needs no change. No chart sets the opt-in label yet, so nothing reports until a chart adopts it. The postgres chart sets the selector labels in the Cluster's `inheritedMetadata`, so CNPG's initdb and join Jobs carry them; without the opt-in they are ignored, as are backup CronJob runs and any other labelled Job. ### Testing - `go build ./...`, `go vet` on `./internal/controller/`, `./cmd/cozystack-controller/`, `./api/v1alpha1/`: clean. - `go test ./internal/controller/... ./pkg/registry/apps/application/... ./api/...`: pass. - New unit tests (fake client): a failed Job sets `Operational=false`, reason `JobFailed` and the message; a succeeded, running, `Failed=False` or other-selector Job, and a failed Job without the opt-in label or with it set to anything but `"true"`, has no effect; a failed Job deleted or replaced by a successful run clears the verdict; a stale `JobFailed` is cleared before the DataVolume reader is installed; precedence against `minReplicas`, an unprovisioned BucketClaim and a DataVolume verdict; message sorting, the three-Job bound, newest-run-per-controller and Jobs being deleted; the cache transform keeps what the rule reads. cozystack-api: a monitor with `JobFailed` yields `WorkloadsReady=False` with that reason and message. - `make generate`: no changes. - Not run against a cluster: the Job watch and the transformed cache were not exercised end to end. ### Downstream repositories Walked the trigger map against the diff (`api/v1alpha1/workloadmonitor_types.go` constant only, no CRD schema change; `internal/controller`; `cmd/cozystack-controller`; tests). No package, platform values, ApplicationDefinition, installer, hack tooling, telemetry or commit-convention change. - [x] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: ### Release note ```release-note feat(workloadmonitor): a failed Job that carries a WorkloadMonitor's selector labels and `workloads.cozystack.io/report-failure: "true"` now makes the workload not operational, so the Application reports `WorkloadsReady=False` with reason `JobFailed` and a message naming the Job and its failure. Deleting the Job, or a later run that does not fail, clears it. ``` (cherry picked from commit 23b94d6d1a42f052dbcbbeb773c7497cc2220491) Signed-off-by: Andrey Kolkov --- api/v1alpha1/workloadmonitor_types.go | 11 + cmd/cozystack-controller/main.go | 2 + .../controller/workloadmonitor_controller.go | 139 +++++++++- .../workloadmonitor_controller_test.go | 254 ++++++++++++++++++ .../apps/application/rest_workloads_test.go | 8 + 5 files changed, 411 insertions(+), 3 deletions(-) diff --git a/api/v1alpha1/workloadmonitor_types.go b/api/v1alpha1/workloadmonitor_types.go index b5089652a..0ffc33e7a 100644 --- a/api/v1alpha1/workloadmonitor_types.go +++ b/api/v1alpha1/workloadmonitor_types.go @@ -43,6 +43,17 @@ const WorkloadMonitorReasonDataVolumeNotReady = "DataVolumeNotReady" // that is not operational because a BucketClaim it selects is not provisioned. const WorkloadMonitorReasonBucketClaimNotReady = "BucketClaimNotReady" +// WorkloadMonitorReasonJobFailed is the status Reason of a monitor that is not +// operational because a Job it selects, opted in with +// WorkloadMonitorReportFailureLabel, has failed. +const WorkloadMonitorReasonJobFailed = "JobFailed" + +// WorkloadMonitorReportFailureLabel set to "true" on a Job that also carries a +// monitor's selector labels makes a failure of that Job a failure of the +// workload. Other Jobs, such as those an operator labels by inheritance from +// the workload, never affect the monitor. +const WorkloadMonitorReportFailureLabel = "workloads.cozystack.io/report-failure" + // WorkloadMonitorStatus defines the observed state of WorkloadMonitor type WorkloadMonitorStatus struct { // Operational indicates if the workload meets all operational requirements diff --git a/cmd/cozystack-controller/main.go b/cmd/cozystack-controller/main.go index 59ba3b515..7cac159ae 100644 --- a/cmd/cozystack-controller/main.go +++ b/cmd/cozystack-controller/main.go @@ -26,6 +26,7 @@ import ( // to ensure that exec-entrypoint and run can make use of them. _ "k8s.io/client-go/plugin/pkg/client/auth" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" @@ -216,6 +217,7 @@ func main() { Cache: cache.Options{ ByObject: map[client.Object]cache.ByObject{ &corev1.Secret{}: wildcardsecret.SecretCacheByObject(), + &batchv1.Job{}: controller.JobCacheByObject(), }, }, // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily diff --git a/internal/controller/workloadmonitor_controller.go b/internal/controller/workloadmonitor_controller.go index 53677a544..d0daf47f6 100644 --- a/internal/controller/workloadmonitor_controller.go +++ b/internal/controller/workloadmonitor_controller.go @@ -19,6 +19,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" @@ -38,6 +39,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -368,6 +370,7 @@ func (r *WorkloadMonitorReconciler) dataVolumesMessage(ctx context.Context, moni // +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch // +kubebuilder:rbac:groups=objectstorage.k8s.io,resources=bucketclaims,verbs=get;list;watch // +kubebuilder:rbac:groups=cdi.kubevirt.io,resources=datavolumes,verbs=get;list;watch +// +kubebuilder:rbac:groups=batch,resources=jobs,verbs=get;list;watch // isBucketClaimReady checks if the BucketClaim has been provisioned. func (r *WorkloadMonitorReconciler) isBucketClaimReady(bc *cosiv1alpha1.BucketClaim) bool { @@ -393,6 +396,107 @@ func (r *WorkloadMonitorReconciler) bucketClaimsMessage(claims []cosiv1alpha1.Bu return strings.Join(pending, "; ") } +// maxFailedJobsInMessage bounds how many failed Jobs a monitor's message names. +const maxFailedJobsInMessage = 3 + +// jobFailedCondition returns the Failed=True condition of a Job, or nil. +func jobFailedCondition(job *batchv1.Job) *batchv1.JobCondition { + for i := range job.Status.Conditions { + c := &job.Status.Conditions[i] + if c.Type == batchv1.JobFailed && c.Status == corev1.ConditionTrue { + return c + } + } + return nil +} + +func jobIsNewer(a, b *batchv1.Job) bool { + if !a.CreationTimestamp.Equal(&b.CreationTimestamp) { + return b.CreationTimestamp.Before(&a.CreationTimestamp) + } + return a.Name > b.Name +} + +// failedJobsMessage names the failed Jobs with the reason and message of their +// Failed condition, and is empty when there is none. Of the Jobs one controller +// owns, only the newest counts: a CronJob keeps failed runs in its history +// after a later run succeeds. +func failedJobsMessage(jobs []batchv1.Job) string { + var current []*batchv1.Job + newestByOwner := map[types.UID]*batchv1.Job{} + for i := range jobs { + job := &jobs[i] + if job.DeletionTimestamp != nil { + continue + } + owner := metav1.GetControllerOfNoCopy(job) + if owner == nil { + current = append(current, job) + continue + } + if prev, ok := newestByOwner[owner.UID]; !ok || jobIsNewer(job, prev) { + newestByOwner[owner.UID] = job + } + } + for _, job := range newestByOwner { + current = append(current, job) + } + sort.Slice(current, func(i, j int) bool { return current[i].Name < current[j].Name }) + + var failed []string + for _, job := range current { + cond := jobFailedCondition(job) + if cond == nil { + continue + } + entry := fmt.Sprintf("Job %s failed", job.Name) + if cond.Reason != "" { + entry += ": " + cond.Reason + } + if cond.Message != "" { + entry += ": " + cond.Message + } + failed = append(failed, entry) + } + if extra := len(failed) - maxFailedJobsInMessage; extra > 0 { + failed = append(failed[:maxFailedJobsInMessage], fmt.Sprintf("%d more Jobs failed", extra)) + } + return strings.Join(failed, "; ") +} + +// JobCacheByObject returns the cache options the cozystack-controller manager +// applies to Jobs. The WorkloadMonitor reconciler, their only reader there, +// reads only Jobs that opted in with WorkloadMonitorReportFailureLabel, and of +// them only labels, owners and conditions. +func JobCacheByObject() cache.ByObject { + return cache.ByObject{ + Label: labels.SelectorFromSet(labels.Set{cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"}), + Transform: stripJob, + } +} + +func stripJob(obj any) (any, error) { + job, ok := obj.(*batchv1.Job) + if !ok { + return obj, nil + } + return &batchv1.Job{ + TypeMeta: job.TypeMeta, + ObjectMeta: metav1.ObjectMeta{ + Name: job.Name, + Namespace: job.Namespace, + UID: job.UID, + ResourceVersion: job.ResourceVersion, + Generation: job.Generation, + CreationTimestamp: job.CreationTimestamp, + DeletionTimestamp: job.DeletionTimestamp, + Labels: job.Labels, + OwnerReferences: job.OwnerReferences, + }, + Status: batchv1.JobStatus{Conditions: job.Status.Conditions}, + }, nil +} + // isServiceReady checks if the service has an external IP bound func (r *WorkloadMonitorReconciler) isServiceReady(svc *corev1.Service) bool { return len(svc.Status.LoadBalancer.Ingress) > 0 @@ -1044,6 +1148,22 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ bucketsMessage := r.bucketClaimsMessage(bucketClaimList.Items) + reportedJobs := client.MatchingLabels{cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + for k, v := range monitor.Spec.Selector { + reportedJobs[k] = v + } + jobList := &batchv1.JobList{} + if err := r.List( + ctx, + jobList, + client.InNamespace(monitor.Namespace), + reportedJobs, + ); err != nil { + logger.Error(err, "Unable to list Jobs for WorkloadMonitor", "monitor", monitor.Name) + return ctrl.Result{}, err + } + jobsMessage := failedJobsMessage(jobList.Items) + // Update WorkloadMonitor status based on observed pods monitor.Status.ObservedReplicas = observedReplicas monitor.Status.AvailableReplicas = availableReplicas @@ -1067,18 +1187,26 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ } // A stored DataVolume verdict is the last one: kept while no reader is // installed yet, so a controller restart does not report a stuck disk as - // ready. BucketClaims are listed on every pass, so their verdict is - // recomputed and only fills fields no DataVolume verdict holds. + // ready. Jobs and BucketClaims are listed on every pass, so their + // verdicts are recomputed and only fill fields no DataVolume verdict + // holds. A failed Job outranks an unprovisioned BucketClaim: it stays + // failed until something replaces it, while a claim is usually still + // being provisioned. if dataVolumesRead { fresh.Status.Message = dataVolumesMessage fresh.Status.Reason = "" if dataVolumesMessage != "" { fresh.Status.Reason = cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady } - } else if fresh.Status.Reason == cozyv1alpha1.WorkloadMonitorReasonBucketClaimNotReady { + } else if fresh.Status.Reason == cozyv1alpha1.WorkloadMonitorReasonBucketClaimNotReady || + fresh.Status.Reason == cozyv1alpha1.WorkloadMonitorReasonJobFailed { fresh.Status.Message = "" fresh.Status.Reason = "" } + if fresh.Status.Message == "" && jobsMessage != "" { + fresh.Status.Message = jobsMessage + fresh.Status.Reason = cozyv1alpha1.WorkloadMonitorReasonJobFailed + } if fresh.Status.Message == "" && bucketsMessage != "" { fresh.Status.Message = bucketsMessage fresh.Status.Reason = cozyv1alpha1.WorkloadMonitorReasonBucketClaimNotReady @@ -1136,6 +1264,11 @@ func (r *WorkloadMonitorReconciler) SetupWithManager(mgr ctrl.Manager) error { &cosiv1alpha1.BucketClaim{}, handler.EnqueueRequestsFromMapFunc(mapObjectToMonitor(&cosiv1alpha1.BucketClaim{}, r.Client)), ). + // Cached Jobs carry only what JobCacheByObject keeps. + Watches( + &batchv1.Job{}, + handler.EnqueueRequestsFromMapFunc(mapObjectToMonitor(&batchv1.Job{}, r.Client)), + ). // Watch for changes to Workload objects we create (owned by WorkloadMonitor) Owns(&cozyv1alpha1.Workload{}) c, err := builder.Build(r) diff --git a/internal/controller/workloadmonitor_controller_test.go b/internal/controller/workloadmonitor_controller_test.go index 10a6c3eeb..151a832bc 100644 --- a/internal/controller/workloadmonitor_controller_test.go +++ b/internal/controller/workloadmonitor_controller_test.go @@ -13,6 +13,7 @@ import ( "time" cozyv1alpha1 "github.com/cozystack/cozystack/api/v1alpha1" + batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/api/resource" @@ -40,6 +41,7 @@ func TestReconcile_OperationalStatusPersisted(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) minReplicas := int32(2) @@ -106,6 +108,7 @@ func TestReconcile_OperationalTrue_WhenEnoughReplicas(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) minReplicas := int32(1) @@ -235,6 +238,7 @@ func TestReconcile_MonitorLabelsPropagatedToPodWorkload(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -307,6 +311,7 @@ func TestReconcile_BackwardCompat_NoMonitorLabels(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -359,6 +364,7 @@ func TestReconcile_OperationalTrue_WhenNoMinReplicas(t *testing.T) { scheme := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) + _ = batchv1.AddToScheme(scheme) _ = cosiv1alpha1.AddToScheme(scheme) monitor := &cozyv1alpha1.WorkloadMonitor{ @@ -403,6 +409,7 @@ func newTestScheme() *runtime.Scheme { s := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(s) _ = corev1.AddToScheme(s) + _ = batchv1.AddToScheme(s) _ = cosiv1alpha1.AddToScheme(s) return s } @@ -2565,3 +2572,250 @@ func TestReconcile_DataVolumeVerdictOutranksBucketClaim(t *testing.T) { t.Errorf("Message = %q", got.Status.Message) } } + +func newJob(name string, labels map[string]string, conditions ...batchv1.JobCondition) *batchv1.Job { + return &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", Labels: labels}, + Status: batchv1.JobStatus{Conditions: conditions}, + } +} + +func jobFailed(reason, message string) batchv1.JobCondition { + return batchv1.JobCondition{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: reason, Message: message} +} + +func newJobMonitorClient(s *runtime.Scheme, minReplicas int32, objs ...client.Object) client.Client { + monitor := &cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{Name: "db", Namespace: "default"}, + Spec: cozyv1alpha1.WorkloadMonitorSpec{ + Selector: map[string]string{"app.kubernetes.io/instance": "db"}, + MinReplicas: ptr.To(minReplicas), + }, + } + return fake.NewClientBuilder(). + WithScheme(s). + WithObjects(append([]client.Object{monitor}, objs...)...). + WithStatusSubresource(monitor). + Build() +} + +func reconcileJobMonitor(t *testing.T, c client.Client, s *runtime.Scheme) *cozyv1alpha1.WorkloadMonitor { + t.Helper() + reconciler := &WorkloadMonitorReconciler{Client: c, Scheme: s, DataVolumeReader: c} + req := reconcile.Request{NamespacedName: types.NamespacedName{Name: "db", Namespace: "default"}} + if _, err := reconciler.Reconcile(context.TODO(), req); err != nil { + t.Fatalf("Reconcile returned error: %v", err) + } + updated := &cozyv1alpha1.WorkloadMonitor{} + if err := c.Get(context.TODO(), req.NamespacedName, updated); err != nil { + t.Fatalf("Failed to get updated WorkloadMonitor: %v", err) + } + if updated.Status.Operational == nil { + t.Fatal("Expected Operational to be set, got nil") + } + return updated +} + +func TestReconcile_FailedJobDecidesOperational(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + cases := []struct { + name string + job *batchv1.Job + message string + }{ + { + "failed", + newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "Job has reached the specified backoff limit")), + "Job db-repair failed: BackoffLimitExceeded: Job has reached the specified backoff limit", + }, + {"failed without a message", newJob("db-repair", selected, jobFailed("DeadlineExceeded", "")), "Job db-repair failed: DeadlineExceeded"}, + {"failed without a reason", newJob("db-repair", selected, jobFailed("", "")), "Job db-repair failed"}, + {"succeeded", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}), ""}, + {"running", newJob("db-repair", selected), ""}, + {"Failed condition not true", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobFailed, Status: corev1.ConditionFalse}), ""}, + {"outside the selector", newJob("other", map[string]string{"app.kubernetes.io/instance": "other", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"}, jobFailed("BackoffLimitExceeded", "")), ""}, + {"not opted in", newJob("db-1-initdb", map[string]string{"app.kubernetes.io/instance": "db"}, jobFailed("BackoffLimitExceeded", "")), ""}, + {"opted out", newJob("db-repair", map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "false"}, jobFailed("BackoffLimitExceeded", "")), ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := newTestScheme() + got := reconcileJobMonitor(t, newJobMonitorClient(s, 0, tc.job), s) + if *got.Status.Operational != (tc.message == "") { + t.Errorf("Operational = %v, want %v", *got.Status.Operational, tc.message == "") + } + if got.Status.Message != tc.message { + t.Errorf("Message = %q, want %q", got.Status.Message, tc.message) + } + wantReason := "" + if tc.message != "" { + wantReason = cozyv1alpha1.WorkloadMonitorReasonJobFailed + } + if got.Status.Reason != wantReason { + t.Errorf("Reason = %q, want %q", got.Status.Reason, wantReason) + } + }) + } +} + +func TestReconcile_FailedJobVerdictClears(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + for _, tc := range []struct { + name string + clear func(c client.Client, job *batchv1.Job) error + }{ + {"deleted", func(c client.Client, job *batchv1.Job) error { return c.Delete(context.TODO(), job) }}, + {"replaced by a run that succeeded", func(c client.Client, job *batchv1.Job) error { + if err := c.Delete(context.TODO(), job); err != nil { + return err + } + return c.Create(context.TODO(), newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue})) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + s := newTestScheme() + job := newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "")) + c := newJobMonitorClient(s, 0, job) + got := reconcileJobMonitor(t, c, s) + if *got.Status.Operational || got.Status.Reason != cozyv1alpha1.WorkloadMonitorReasonJobFailed { + t.Fatalf("before: Operational = %v, Reason = %q", *got.Status.Operational, got.Status.Reason) + } + if err := tc.clear(c, job); err != nil { + t.Fatal(err) + } + got = reconcileJobMonitor(t, c, s) + if !*got.Status.Operational || got.Status.Message != "" || got.Status.Reason != "" { + t.Errorf("after: Operational = %v, Message = %q, Reason = %q", *got.Status.Operational, got.Status.Message, got.Status.Reason) + } + }) + } +} + +func TestReconcile_StaleFailedJobVerdictClearsWithoutDataVolumeReader(t *testing.T) { + s := newTestScheme() + monitor := &cozyv1alpha1.WorkloadMonitor{ + ObjectMeta: metav1.ObjectMeta{Name: "db", Namespace: "default"}, + Spec: cozyv1alpha1.WorkloadMonitorSpec{Selector: map[string]string{"app.kubernetes.io/instance": "db"}}, + Status: cozyv1alpha1.WorkloadMonitorStatus{ + Operational: ptr.To(false), + Message: "Job db-repair failed: BackoffLimitExceeded", + Reason: cozyv1alpha1.WorkloadMonitorReasonJobFailed, + }, + } + c := fake.NewClientBuilder().WithScheme(s).WithObjects(monitor).WithStatusSubresource(monitor).Build() + reconciler := &WorkloadMonitorReconciler{Client: c, Scheme: s} + req := reconcile.Request{NamespacedName: types.NamespacedName{Name: "db", Namespace: "default"}} + if _, err := reconciler.Reconcile(context.TODO(), req); err != nil { + t.Fatalf("Reconcile returned error: %v", err) + } + got := &cozyv1alpha1.WorkloadMonitor{} + if err := c.Get(context.TODO(), req.NamespacedName, got); err != nil { + t.Fatal(err) + } + if got.Status.Operational == nil || !*got.Status.Operational || got.Status.Message != "" || got.Status.Reason != "" { + t.Errorf("Operational = %v, Message = %q, Reason = %q, want true and both cleared", got.Status.Operational, got.Status.Message, got.Status.Reason) + } +} + +func TestReconcile_FailedJobPrecedence(t *testing.T) { + selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"} + failed := newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "")) + importing := "ImportInProgress" + cases := []struct { + name string + minReplicas int32 + objs []client.Object + reason string + message string + }{ + {"below minReplicas", 1, []client.Object{failed}, cozyv1alpha1.WorkloadMonitorReasonJobFailed, "Job db-repair failed: BackoffLimitExceeded"}, + {"outranks an unprovisioned BucketClaim", 0, []client.Object{failed, newBucketClaim("db", selected, "", false)}, cozyv1alpha1.WorkloadMonitorReasonJobFailed, "Job db-repair failed: BackoffLimitExceeded"}, + {"outranked by a DataVolume verdict", 0, []client.Object{failed, newDataVolume("db", selected, &importing)}, cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady, "DataVolume db is ImportInProgress"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := newTestScheme() + got := reconcileJobMonitor(t, newJobMonitorClient(s, tc.minReplicas, tc.objs...), s) + if *got.Status.Operational { + t.Error("Operational = true, want false") + } + if got.Status.Reason != tc.reason || got.Status.Message != tc.message { + t.Errorf("Reason = %q, Message = %q, want %q, %q", got.Status.Reason, got.Status.Message, tc.reason, tc.message) + } + }) + } +} + +func TestFailedJobsMessage(t *testing.T) { + failed := jobFailed("BackoffLimitExceeded", "") + complete := batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue} + ownedBy := func(job *batchv1.Job, uid types.UID, created time.Time) batchv1.Job { + job.OwnerReferences = []metav1.OwnerReference{{APIVersion: "batch/v1", Kind: "CronJob", Name: "backup", UID: uid, Controller: ptr.To(true)}} + job.CreationTimestamp = metav1.NewTime(created) + return *job + } + now := time.Now() + cases := []struct { + name string + jobs []batchv1.Job + want string + }{ + { + "sorted by name", + []batchv1.Job{*newJob("b", nil, failed), *newJob("a", nil, failed)}, + "Job a failed: BackoffLimitExceeded; Job b failed: BackoffLimitExceeded", + }, + { + "bounded", + []batchv1.Job{*newJob("e", nil, failed), *newJob("d", nil, failed), *newJob("c", nil, failed), *newJob("b", nil, failed), *newJob("a", nil, failed)}, + "Job a failed: BackoffLimitExceeded; Job b failed: BackoffLimitExceeded; Job c failed: BackoffLimitExceeded; 2 more Jobs failed", + }, + { + "a later run of the same controller succeeded", + []batchv1.Job{ownedBy(newJob("backup-1", nil, failed), "cron", now.Add(-time.Hour)), ownedBy(newJob("backup-2", nil, complete), "cron", now)}, + "", + }, + { + "the latest run of the controller failed", + []batchv1.Job{ownedBy(newJob("backup-1", nil, complete), "cron", now.Add(-time.Hour)), ownedBy(newJob("backup-2", nil, failed), "cron", now)}, + "Job backup-2 failed: BackoffLimitExceeded", + }, + { + "being deleted", + []batchv1.Job{func() batchv1.Job { + j := newJob("a", nil, failed) + j.DeletionTimestamp = ptr.To(metav1.NewTime(now)) + return *j + }()}, + "", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := failedJobsMessage(tc.jobs); got != tc.want { + t.Errorf("failedJobsMessage = %q, want %q", got, tc.want) + } + }) + } +} + +func TestStripJobKeepsWhatTheMonitorReads(t *testing.T) { + job := newJob("db-repair", map[string]string{"app.kubernetes.io/instance": "db"}, jobFailed("BackoffLimitExceeded", "limit")) + job.OwnerReferences = []metav1.OwnerReference{{Name: "owner", UID: "u", Controller: ptr.To(true)}} + job.ResourceVersion = "7" + job.ManagedFields = []metav1.ManagedFieldsEntry{{Manager: "kube-controller-manager"}} + job.Spec.Template.Spec.Containers = []corev1.Container{{Name: "repair", Image: "postgres"}} + + out, err := stripJob(job) + if err != nil { + t.Fatal(err) + } + got := out.(*batchv1.Job) + if got.Name != job.Name || got.Namespace != job.Namespace || got.ResourceVersion != "7" || + len(got.Labels) != 1 || len(got.OwnerReferences) != 1 || failedJobsMessage([]batchv1.Job{*got}) != "Job db-repair failed: BackoffLimitExceeded: limit" { + t.Errorf("stripped Job lost what the monitor reads: %+v", got) + } + if len(got.ManagedFields) != 0 || len(got.Spec.Template.Spec.Containers) != 0 { + t.Errorf("stripped Job kept its spec or managed fields: %+v", got) + } +} diff --git a/pkg/registry/apps/application/rest_workloads_test.go b/pkg/registry/apps/application/rest_workloads_test.go index 1143e9c1d..5be5ee428 100644 --- a/pkg/registry/apps/application/rest_workloads_test.go +++ b/pkg/registry/apps/application/rest_workloads_test.go @@ -394,6 +394,14 @@ func TestConvertConditions_WorkloadsReadyCarriesMonitorMessages(t *testing.T) { "DataVolume b is Failed", cozyv1alpha1.WorkloadMonitorReasonDataVolumeNotReady, }, + { + "a failed Job", + []runtime.Object{ + monitor("mon-a", false, "Job mydb-repair failed: BackoffLimitExceeded: Job has reached the specified backoff limit", cozyv1alpha1.WorkloadMonitorReasonJobFailed), + }, + "Job mydb-repair failed: BackoffLimitExceeded: Job has reached the specified backoff limit", + cozyv1alpha1.WorkloadMonitorReasonJobFailed, + }, { "generic message when no monitor names a cause", []runtime.Object{monitor("mon-a", false, "", "")},