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.
```

On release-1.6 the WorkloadMonitor status has only operational, with no
reason or message, and adding them is a CRD change a patch release does
not take. Only the rule is ported: a Job in the monitor's namespace that
carries the monitor's selector labels and
workloads.cozystack.io/report-failure: "true" and has Failed=True makes
the monitor not operational, counting only the newest Job per
controller owner, with the Job cache filtered by that label and
stripped by the transform. The application then shows
WorkloadsReady=False with the generic WorkloadMonitorCheck reason
instead of JobFailed; the failed Jobs are named in the controller log.
The JobFailed reason constant, the status precedence against BucketClaim
and DataVolume verdicts (1.6 has neither as a status cause) and the
registry test are not carried over, and the tests assert operational
instead of reason and message.

(cherry picked from commit 23b94d6d1a)
Assisted-By: LLM
Signed-off-by: Andrey Kolkov <androndo@gmail.com>
This commit is contained in:
Aleksei Sviridkin authored and Andrey Kolkov committed 2026-12-01 12:54:21 +07:00
1 parent 590e388b94
commit 3ae890ac4a
4 files changed
+345

No files matched your search

+6
View File
@@ -34,6 +34,12 @@ type WorkloadMonitorSpec struct {
Replicas *int32 `json:"replicas,omitempty"`
}
// 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
+2
View File
@@ -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"
@@ -200,6 +201,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
@@ -13,17 +13,20 @@ import (
"time"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/retry"
"k8s.io/utils/pointer"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
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"
@@ -77,12 +80,114 @@ type WorkloadMonitorReconciler struct {
// +kubebuilder:rbac:groups=core,resources=namespaces,verbs=get
// +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch
// +kubebuilder:rbac:groups=objectstorage.k8s.io,resources=bucketclaims,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 {
return bc.Status.BucketReady
}
// 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
@@ -708,6 +813,27 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ
}
}
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
}
// The status has no field for the cause on this line, so the failed Jobs
// are named in the log only.
jobsMessage := failedJobsMessage(jobList.Items)
if jobsMessage != "" {
logger.Info("WorkloadMonitor is not operational: a Job that reports failure has failed", "monitor", monitor.Name, "jobs", jobsMessage)
}
// Update WorkloadMonitor status based on observed pods
monitor.Status.ObservedReplicas = observedReplicas
monitor.Status.AvailableReplicas = availableReplicas
@@ -728,6 +854,9 @@ func (r *WorkloadMonitorReconciler) Reconcile(ctx context.Context, req ctrl.Requ
if fresh.Spec.MinReplicas != nil && availableReplicas < *fresh.Spec.MinReplicas {
fresh.Status.Operational = pointer.Bool(false)
}
if jobsMessage != "" {
fresh.Status.Operational = pointer.Bool(false)
}
return r.Status().Update(ctx, fresh)
})
if err != nil {
@@ -771,6 +900,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{}).
Complete(r)
@@ -7,8 +7,10 @@ import (
"net/http/httptest"
"strings"
"testing"
"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/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -16,6 +18,7 @@ import (
"k8s.io/apimachinery/pkg/types"
"k8s.io/utils/ptr"
cosiv1alpha1 "sigs.k8s.io/container-object-storage-interface-api/apis/objectstorage/v1alpha1"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
@@ -24,6 +27,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)
@@ -90,6 +94,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)
@@ -219,6 +224,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{
@@ -291,6 +297,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{
@@ -343,6 +350,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{
@@ -387,6 +395,7 @@ func newTestScheme() *runtime.Scheme {
s := runtime.NewScheme()
_ = cozyv1alpha1.AddToScheme(s)
_ = corev1.AddToScheme(s)
_ = batchv1.AddToScheme(s)
_ = cosiv1alpha1.AddToScheme(s)
return s
}
@@ -1300,3 +1309,197 @@ func TestReconcile_PVCStorageClassResourceKey(t *testing.T) {
})
}
}
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}
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
operational bool
}{
{"failed", newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", "Job has reached the specified backoff limit")), false},
{"failed without a reason", newJob("db-repair", selected, jobFailed("", "")), false},
{"succeeded", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobComplete, Status: corev1.ConditionTrue}), true},
{"running", newJob("db-repair", selected), true},
{"Failed condition not true", newJob("db-repair", selected, batchv1.JobCondition{Type: batchv1.JobFailed, Status: corev1.ConditionFalse}), true},
{"outside the selector", newJob("other", map[string]string{"app.kubernetes.io/instance": "other", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"}, jobFailed("BackoffLimitExceeded", "")), true},
{"not opted in", newJob("db-1-initdb", map[string]string{"app.kubernetes.io/instance": "db"}, jobFailed("BackoffLimitExceeded", "")), true},
{"opted out", newJob("db-repair", map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "false"}, jobFailed("BackoffLimitExceeded", "")), true},
}
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.operational {
t.Errorf("Operational = %v, want %v", *got.Status.Operational, tc.operational)
}
})
}
}
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)
if got := reconcileJobMonitor(t, c, s); *got.Status.Operational {
t.Fatal("before: Operational = true, want false")
}
if err := tc.clear(c, job); err != nil {
t.Fatal(err)
}
if got := reconcileJobMonitor(t, c, s); !*got.Status.Operational {
t.Error("after: Operational = false, want true")
}
})
}
}
func TestReconcile_FailedJobWithEnoughReplicas(t *testing.T) {
selected := map[string]string{"app.kubernetes.io/instance": "db", cozyv1alpha1.WorkloadMonitorReportFailureLabel: "true"}
s := newTestScheme()
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{Name: "db-1", Namespace: "default", Labels: map[string]string{"app.kubernetes.io/instance": "db"}},
Status: corev1.PodStatus{
Phase: corev1.PodRunning,
Conditions: []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionTrue}},
},
}
got := reconcileJobMonitor(t, newJobMonitorClient(s, 1, pod, newJob("db-repair", selected, jobFailed("BackoffLimitExceeded", ""))), s)
if got.Status.AvailableReplicas != 1 {
t.Fatalf("AvailableReplicas = %d, want 1", got.Status.AvailableReplicas)
}
if *got.Status.Operational {
t.Error("Operational = true, want false: a failed Job outranks enough ready replicas")
}
}
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)
}
}