From 5795b5f658549ec8aa8f55b47692d51c5775afc8 Mon Sep 17 00:00:00 2001 From: Andrey Kolkov Date: Mon, 30 Nov 2026 13:42:03 +0700 Subject: [PATCH] feat(workloadmonitor): report failed Jobs that opt in as not operational Some charts run work that matters to the workload in a Job outside the Helm release, such as an index repair after an image upgrade. Once the release has applied, Ready stays True whatever that Job does, so a failed run was visible only to someone who went looking for the Job. A Job that carries a monitor's selector labels and workloads.cozystack.io/report-failure set to "true", and has Failed=True, now makes the monitor not operational with reason JobFailed and a message naming the Job and its failure, which the Application surfaces as WorkloadsReady=False. The opt-in is explicit because the selector labels alone are carried by Jobs that say nothing about the workload's health: Jobs an operator labels by inheritance from the workload, such as CloudNativePG's initdb and join Jobs under the postgres chart, and backup runs. Of the Jobs one controller owns only the newest counts, because a CronJob keeps failed runs in its history after a later run succeeds; a Job that is deleted or replaced by a successful run clears the verdict. A DataVolume verdict still comes first, since its stored value is kept across restarts until the DataVolumes can be read again. A failed Job outranks an unprovisioned BucketClaim: it stays failed until something replaces it, while a claim is usually still being provisioned. The manager caches only Jobs that carry the opt-in label, and of them only their metadata and conditions. The controller's ClusterRole already grants read on every resource. Refs: #5459 Assisted-By: LLM 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 20611eb1c..c296496a9 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" @@ -226,6 +227,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 d50f1d6e0..b77331da4 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 @@ -1178,6 +1282,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 @@ -1201,18 +1321,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 @@ -1270,6 +1398,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 70bf5aa0f..656fc3c50 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" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" @@ -41,6 +42,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) @@ -107,6 +109,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) @@ -236,6 +239,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{ @@ -308,6 +312,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{ @@ -360,6 +365,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{ @@ -404,6 +410,7 @@ func newTestScheme() *runtime.Scheme { s := runtime.NewScheme() _ = cozyv1alpha1.AddToScheme(s) _ = corev1.AddToScheme(s) + _ = batchv1.AddToScheme(s) _ = cosiv1alpha1.AddToScheme(s) return s } @@ -3107,3 +3114,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 176d7b18c..5ff65c78c 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, "", "")},