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
1 change: 1 addition & 0 deletions MILAB.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ release line: an upstream release plus the changes below.
|---|---|---|
| Confirm a missing component with an uncached read before failing | The controller can read a Job it has just created from a stale cache and fail the workload at once (`MissingComponent: Only found 0 deployed components`) | PR project-codeflare/appwrapper#417 (open) |
| `appwrapper.maxConcurrentReconciles` in the operator config | One reconcile worker can fall behind during a burst of submissions and create Jobs late; the delay counts against the admission grace period | not proposed yet |
| Status patches carry the AppWrapper's `resourceVersion` (optimistic lock) | A reconcile can read a stale AppWrapper from the cache and write over a newer status; parallel reconciles make this more frequent. The API server now rejects such a patch with a Conflict, and the controller requeues the AppWrapper | not proposed yet |

## Configuration

Expand Down
58 changes: 42 additions & 16 deletions internal/controller/appwrapper/appwrapper_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,23 @@ type componentStatusSummary struct {
// Reconcile reconciles an appwrapper
// Please see [aw-states] for documentation of this method.
//
// [aw-states]: https://project-codeflare.github.io/appwrapper/arch-controller/#framework-controller
// A Conflict error means that this reconcile read a stale copy of the AppWrapper:
// the API server has a newer version, and the write that used the stale copy was rejected.
// This is not a failure. Reconcile requeues the AppWrapper without an error, so that
// the next reconcile reads the newer version.
//
//gocyclo:ignore
// [aw-states]: https://project-codeflare.github.io/appwrapper/arch-controller/#framework-controller
func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
result, err := r.reconcile(ctx, req)
if apierrors.IsConflict(err) {
log.FromContext(ctx).V(2).Info("Stale AppWrapper; write rejected with Conflict, requeueing", "error", err.Error())
return ctrl.Result{RequeueAfter: time.Second}, nil
}
return result, err
}

//gocyclo:ignore
func (r *AppWrapperReconciler) reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
aw := &awv1beta2.AppWrapper{}
if err := r.Get(ctx, req.NamespacedName, aw); err != nil {
return ctrl.Result{}, nil
Expand All @@ -128,7 +141,7 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)
if aw.Status.Phase != awv1beta2.AppWrapperTerminating {
// Set Phase for better UX, but ignore errors. We still want to requeue after 5 seconds (not immediately)
aw.Status.Phase = awv1beta2.AppWrapperTerminating
_ = r.Status().Patch(ctx, aw, client.MergeFrom(orig))
_ = r.Status().Patch(ctx, aw, statusPatch(orig))
}
return ctrl.Result{RequeueAfter: 5 * time.Second}, nil // check after a short while
}
Expand All @@ -151,7 +164,7 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)
statusUpdated = true
}
if statusUpdated {
if err := r.Status().Patch(ctx, aw, client.MergeFrom(orig)); err != nil {
if err := r.Status().Patch(ctx, aw, statusPatch(orig)); err != nil {
return ctrl.Result{}, err
}
}
Expand Down Expand Up @@ -225,6 +238,10 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)
err, fatal := r.createComponents(ctx, aw) // NOTE: createComponents applies patches to aw.Status incrementally as resources are created
orig := copyForStatusPatch(aw)
if err != nil {
if apierrors.IsConflict(err) {
// A status patch used a stale copy of the AppWrapper. This is not a create failure.
return ctrl.Result{}, err
}
if !fatal {
startTime := meta.FindStatusCondition(aw.Status.Conditions, string(awv1beta2.ResourcesDeployed)).LastTransitionTime
graceDuration := r.admissionGraceDuration(ctx, aw)
Expand Down Expand Up @@ -349,7 +366,7 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)
now := time.Now()
deadline := whenDetected.Add(gracePeriod)
if now.Before(deadline) {
return requeueAfter(deadline.Sub(now), r.Status().Patch(ctx, aw, client.MergeFrom(orig)))
return requeueAfter(deadline.Sub(now), r.Status().Patch(ctx, aw, statusPatch(orig)))
} else {
r.Recorder.Eventf(aw, nil, v1.EventTypeNormal, "FoundFailedPods", string(awv1beta2.Unhealthy), "%v failed pods", podStatus.failed)
return ctrl.Result{}, r.resetOrFail(ctx, orig, aw, podStatus.terminalFailure, 1)
Expand Down Expand Up @@ -378,7 +395,7 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)
Reason: "SufficientPodsReady",
Message: fmt.Sprintf("%v pods running; %v pods succeeded", podStatus.running, podStatus.succeeded),
})
return requeueAfter(time.Minute, r.Status().Patch(ctx, aw, client.MergeFrom(orig)))
return requeueAfter(time.Minute, r.Status().Patch(ctx, aw, statusPatch(orig)))
}

// Not ready yet; either continue to wait or giveup if the warmup period has expired
Expand All @@ -392,7 +409,7 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)
graceDuration = r.admissionGraceDuration(ctx, aw)
}
if time.Now().Before(whenDeployed.Add(graceDuration)) {
return requeueAfter(5*time.Second, r.Status().Patch(ctx, aw, client.MergeFrom(orig)))
return requeueAfter(5*time.Second, r.Status().Patch(ctx, aw, statusPatch(orig)))
} else {
meta.SetStatusCondition(&aw.Status.Conditions, metav1.Condition{
Type: string(awv1beta2.Unhealthy),
Expand All @@ -409,7 +426,7 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)
// finish undeploying components irrespective of desired state (suspend bit)
if meta.IsStatusConditionTrue(aw.Status.Conditions, string(awv1beta2.ResourcesDeployed)) {
if !r.deleteComponents(ctx, aw) {
return requeueAfter(5*time.Second, r.Status().Patch(ctx, aw, client.MergeFrom(orig)))
return requeueAfter(5*time.Second, r.Status().Patch(ctx, aw, statusPatch(orig)))
}
meta.SetStatusCondition(&aw.Status.Conditions, metav1.Condition{
Type: string(awv1beta2.ResourcesDeployed),
Expand Down Expand Up @@ -438,7 +455,7 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)
clearCondition(aw, awv1beta2.PodsReady, string(awv1beta2.AppWrapperResetting), "")
if meta.IsStatusConditionTrue(aw.Status.Conditions, string(awv1beta2.ResourcesDeployed)) {
if !r.deleteComponents(ctx, aw) {
return requeueAfter(5*time.Second, r.Status().Patch(ctx, aw, client.MergeFrom(orig)))
return requeueAfter(5*time.Second, r.Status().Patch(ctx, aw, statusPatch(orig)))
}
meta.SetStatusCondition(&aw.Status.Conditions, metav1.Condition{
Type: string(awv1beta2.ResourcesDeployed),
Expand All @@ -454,7 +471,7 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)
now := time.Now()
deadline := whenReset.Add(pauseDuration)
if now.Before(deadline) {
return requeueAfter(deadline.Sub(now), r.Status().Patch(ctx, aw, client.MergeFrom(orig)))
return requeueAfter(deadline.Sub(now), r.Status().Patch(ctx, aw, statusPatch(orig)))
}

meta.SetStatusCondition(&aw.Status.Conditions, metav1.Condition{
Expand Down Expand Up @@ -485,13 +502,13 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)
now := time.Now()
deadline := whenDelayed.Add(deletionDelay)
if now.Before(deadline) {
return requeueAfter(deadline.Sub(now), r.Status().Patch(ctx, aw, client.MergeFrom(orig)))
return requeueAfter(deadline.Sub(now), r.Status().Patch(ctx, aw, statusPatch(orig)))
}
}

if meta.IsStatusConditionTrue(aw.Status.Conditions, string(awv1beta2.ResourcesDeployed)) {
if !r.deleteComponents(ctx, aw) {
return requeueAfter(5*time.Second, r.Status().Patch(ctx, aw, client.MergeFrom(orig)))
return requeueAfter(5*time.Second, r.Status().Patch(ctx, aw, statusPatch(orig)))
}
msg := "Resources deleted for failed AppWrapper"
if deletionDelay > 0 && aw.Spec.Suspend {
Expand All @@ -510,7 +527,7 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)
Reason: string(awv1beta2.AppWrapperFailed),
Message: "No resources deployed",
})
return ctrl.Result{}, r.Status().Patch(ctx, aw, client.MergeFrom(orig))
return ctrl.Result{}, r.Status().Patch(ctx, aw, statusPatch(orig))

case awv1beta2.AppWrapperSucceeded:
if meta.IsStatusConditionTrue(aw.Status.Conditions, string(awv1beta2.ResourcesDeployed)) {
Expand All @@ -524,15 +541,15 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)

orig := copyForStatusPatch(aw)
if !r.deleteComponents(ctx, aw) {
return requeueAfter(5*time.Second, r.Status().Patch(ctx, aw, client.MergeFrom(orig)))
return requeueAfter(5*time.Second, r.Status().Patch(ctx, aw, statusPatch(orig)))
}
meta.SetStatusCondition(&aw.Status.Conditions, metav1.Condition{
Type: string(awv1beta2.ResourcesDeployed),
Status: metav1.ConditionFalse,
Reason: string(awv1beta2.AppWrapperSucceeded),
Message: fmt.Sprintf("Time to live after success of %v expired", deletionDelay),
})
return ctrl.Result{}, r.Status().Patch(ctx, aw, client.MergeFrom(orig))
return ctrl.Result{}, r.Status().Patch(ctx, aw, statusPatch(orig))
}
return ctrl.Result{}, nil
}
Expand All @@ -542,7 +559,7 @@ func (r *AppWrapperReconciler) Reconcile(ctx context.Context, req ctrl.Request)

func (r *AppWrapperReconciler) transitionToPhase(ctx context.Context, orig *awv1beta2.AppWrapper, modified *awv1beta2.AppWrapper, phase awv1beta2.AppWrapperPhase) error {
modified.Status.Phase = phase
if err := r.Status().Patch(ctx, modified, client.MergeFrom(orig)); err != nil {
if err := r.Status().Patch(ctx, modified, statusPatch(orig)); err != nil {
return err
}
log.FromContext(ctx).Info(string(phase), "phase", phase)
Expand Down Expand Up @@ -1003,6 +1020,15 @@ func (r *AppWrapperReconciler) apiReader() client.Reader {
return r.Client
}

// statusPatch returns the patch for a Status().Patch(...) call that uses orig as its base.
// The patch carries the resourceVersion of orig. If the AppWrapper changed on the API server
// after orig was read, the API server rejects the patch with a Conflict error. Without this
// check, a reconcile that read a stale copy from the cache can write over a newer status.
// The risk increases when more than one reconcile runs in parallel (maxConcurrentReconciles > 1).
func statusPatch(orig *awv1beta2.AppWrapper) client.Patch {
return client.MergeFromWithOptions(orig, client.MergeFromWithOptimisticLock{})
}

// copyForStatusPatch returns an AppWrapper with an empty Spec and a DeepCopy of orig's Status for use in a subsequent Status().Patch(...) call
func copyForStatusPatch(orig *awv1beta2.AppWrapper) *awv1beta2.AppWrapper {
copy := awv1beta2.AppWrapper{
Expand Down
37 changes: 37 additions & 0 deletions internal/controller/appwrapper/appwrapper_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,43 @@ var _ = Describe("AppWrapper Controller", func() {
Expect(meta.IsStatusConditionTrue(aw.Status.Conditions, string(awv1beta2.Unhealthy))).Should(BeTrue())
})

It("A status patch that uses a stale AppWrapper is rejected and requeued", func() {
advanceToResuming(pod(100, 1, true), pod(100, 0, false))
beginRunning()

By("Keeping a copy of the AppWrapper that becomes stale")
stale := getAppWrapper(awName)

By("Changing the AppWrapper on the API server after the copy was read")
aw := getAppWrapper(awName)
if aw.Annotations == nil {
aw.Annotations = map[string]string{}
}
aw.Annotations["test.appwrapper/stale-copy"] = "true"
Expect(k8sClient.Update(ctx, aw)).To(Succeed())

By("Deleting a component, so that the reconcile writes a new status")
cs := stale.Status.ComponentStatus[0]
victim := &metav1.PartialObjectMetadata{TypeMeta: metav1.TypeMeta{Kind: cs.Kind, APIVersion: cs.APIVersion}}
victim.Name = cs.Name
victim.Namespace = stale.Namespace
Expect(k8sClient.Delete(ctx, victim)).To(Succeed())

By("Reconciling with a cache that still holds the stale copy: the status patch is rejected")
awReconciler.Client = &staleAppWrapperClient{Client: k8sClient, stale: stale}
defer func() { awReconciler.Client = k8sClient }()
result, err := awReconciler.Reconcile(ctx, reconcile.Request{NamespacedName: awName})
Expect(err).NotTo(HaveOccurred())
Expect(result.RequeueAfter).Should(BeNumerically(">", 0))
Expect(getAppWrapper(awName).Status.Phase).Should(Equal(awv1beta2.AppWrapperRunning))

By("Reconciling with a current copy: Running -> Failed")
awReconciler.Client = k8sClient
_, err = awReconciler.Reconcile(ctx, reconcile.Request{NamespacedName: awName})
Expect(err).NotTo(HaveOccurred())
Expect(getAppWrapper(awName).Status.Phase).Should(Equal(awv1beta2.AppWrapperFailed))
})

It("Happy Path Lifecycle", func() {
advanceToResuming(pod(100, 1, true), pod(100, 0, false))
beginRunning()
Expand Down
17 changes: 17 additions & 0 deletions internal/controller/appwrapper/fixtures_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -295,3 +295,20 @@ func (c *cacheBlindToPods) Get(ctx context.Context, key client.ObjectKey, obj cl
}
return c.Client.Get(ctx, key, obj, opts...)
}

// staleAppWrapperClient simulates a controller-runtime cache that lags behind the API server:
// Get returns an old copy of one AppWrapper, while every other operation (including status
// patches) goes to the real client. This reproduces a reconcile that starts before the cache
// has observed the latest change to the AppWrapper.
type staleAppWrapperClient struct {
client.Client
stale *awv1beta2.AppWrapper
}

func (c *staleAppWrapperClient) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
if aw, ok := obj.(*awv1beta2.AppWrapper); ok && key == client.ObjectKeyFromObject(c.stale) {
c.stale.DeepCopyInto(aw)
return nil
}
return c.Client.Get(ctx, key, obj, opts...)
}
6 changes: 3 additions & 3 deletions internal/controller/appwrapper/resource_management.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ func (r *AppWrapperReconciler) createComponent(ctx context.Context, aw *awv1beta
Status: metav1.ConditionUnknown,
Reason: "ComponentCreationInitiated",
})
if err := r.Status().Patch(ctx, aw, client.MergeFrom(orig)); err != nil {
if err := r.Status().Patch(ctx, aw, statusPatch(orig)); err != nil {
return err, false
}
}
Expand All @@ -382,7 +382,7 @@ func (r *AppWrapperReconciler) createComponent(ctx context.Context, aw *awv1beta
Status: metav1.ConditionFalse,
Reason: "ComponentCreationErrored",
})
if patchErr := r.Status().Patch(ctx, aw, client.MergeFrom(orig)); patchErr != nil {
if patchErr := r.Status().Patch(ctx, aw, statusPatch(orig)); patchErr != nil {
// ugh. Patch failed, so retry the create so we can get to a consistient state
return patchErr, false
}
Expand All @@ -398,7 +398,7 @@ func (r *AppWrapperReconciler) createComponent(ctx context.Context, aw *awv1beta
Status: metav1.ConditionTrue,
Reason: "ComponentCreatedSuccessfully",
})
if err := r.Status().Patch(ctx, aw, client.MergeFrom(orig)); err != nil {
if err := r.Status().Patch(ctx, aw, statusPatch(orig)); err != nil {
return err, false
}

Expand Down