Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: add feature gates for patch step status at once #94

Merged
merged 1 commit into from
Dec 6, 2022
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
66 changes: 66 additions & 0 deletions controllers/workflow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -589,6 +589,72 @@ var _ = Describe("Test Workflow", func() {
Expect(checkRun.Status.Steps[1].Phase).Should(BeEquivalentTo(v1alpha1.WorkflowStepPhaseFailed))
})

It("test reconcile with patch status at once", func() {
defer featuregatetesting.SetFeatureGateDuringTest(&testing.T{}, utilfeature.DefaultFeatureGate, features.EnableSuspendOnFailure, true)()
defer featuregatetesting.SetFeatureGateDuringTest(&testing.T{}, utilfeature.DefaultFeatureGate, features.EnablePatchStatusAtOnce, true)()
wr := wrTemplate.DeepCopy()
wr.Name = "wr-failed-after-retries"
wr.Spec.WorkflowSpec.Steps = []v1alpha1.WorkflowStep{
{
WorkflowStepBase: v1alpha1.WorkflowStepBase{
Name: "step1",
Type: "test-apply",
Properties: &runtime.RawExtension{Raw: []byte(`{"cmd":["sleep","1000"],"image":"busybox"}`)},
},
},
{
WorkflowStepBase: v1alpha1.WorkflowStepBase{
Name: "step2-failed",
Type: "apply-object",
Properties: &runtime.RawExtension{Raw: []byte(`{"value":[{"apiVersion":"v1","kind":"invalid","metadata":{"name":"test1"}}]}`)},
},
},
}

Expect(k8sClient.Create(ctx, wr)).Should(BeNil())
wrKey := types.NamespacedName{Namespace: wr.Namespace, Name: wr.Name}
checkRun := &v1alpha1.WorkflowRun{}
Expect(k8sClient.Get(ctx, wrKey, checkRun)).Should(BeNil())

tryReconcile(reconciler, wr.Name, wr.Namespace)

expDeployment := &appsv1.Deployment{}
step1Key := types.NamespacedName{Namespace: wr.Namespace, Name: "step1"}
Expect(k8sClient.Get(ctx, step1Key, expDeployment)).Should(BeNil())

expDeployment.Status.Replicas = 1
expDeployment.Status.ReadyReplicas = 1
Expect(k8sClient.Status().Update(ctx, expDeployment)).Should(BeNil())

By("verify the first ten reconciles")
for i := 0; i < wfTypes.MaxWorkflowStepErrorRetryTimes; i++ {
tryReconcile(reconciler, wr.Name, wr.Namespace)
Expect(k8sClient.Get(ctx, wrKey, checkRun)).Should(BeNil())
Expect(checkRun.Status.Message).Should(BeEquivalentTo(""))
Expect(checkRun.Status.Phase).Should(BeEquivalentTo(v1alpha1.WorkflowStateExecuting))
Expect(checkRun.Status.Steps[1].Phase).Should(BeEquivalentTo(v1alpha1.WorkflowStepPhaseFailed))
}

By("workflowrun should be suspended after failed max reconciles")
tryReconcile(reconciler, wr.Name, wr.Namespace)
Expect(k8sClient.Get(ctx, wrKey, checkRun)).Should(BeNil())
Expect(checkRun.Status.Phase).Should(BeEquivalentTo(v1alpha1.WorkflowStateSuspending))
Expect(checkRun.Status.Message).Should(BeEquivalentTo(wfTypes.MessageSuspendFailedAfterRetries))
Expect(checkRun.Status.Steps[1].Phase).Should(BeEquivalentTo(v1alpha1.WorkflowStepPhaseFailed))
Expect(checkRun.Status.Steps[1].Reason).Should(BeEquivalentTo(wfTypes.StatusReasonFailedAfterRetries))

By("resume the suspended workflow run")
Expect(k8sClient.Get(ctx, wrKey, checkRun)).Should(BeNil())
checkRun.Status.Suspend = false
Expect(k8sClient.Status().Patch(ctx, checkRun, client.Merge)).Should(BeNil())

tryReconcile(reconciler, wr.Name, wr.Namespace)
Expect(k8sClient.Get(ctx, wrKey, checkRun)).Should(BeNil())
Expect(checkRun.Status.Message).Should(BeEquivalentTo(""))
Expect(checkRun.Status.Phase).Should(BeEquivalentTo(v1alpha1.WorkflowStateExecuting))
Expect(checkRun.Status.Steps[1].Phase).Should(BeEquivalentTo(v1alpha1.WorkflowStepPhaseFailed))
})

It("test failed after retries in dag mode with running step and suspend on failure", func() {
defer featuregatetesting.SetFeatureGateDuringTest(&testing.T{}, utilfeature.DefaultFeatureGate, features.EnableSuspendOnFailure, true)()
wr := wrTemplate.DeepCopy()
Expand Down
29 changes: 20 additions & 9 deletions controllers/workflowrun_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ type WorkflowRunReconciler struct {
Args
}

type workflowRunPatcher struct {
client.Client
run *v1alpha1.WorkflowRun
}

var (
// ReconcileTimeout timeout for controller to reconcile
ReconcileTimeout = time.Minute * 3
Expand Down Expand Up @@ -126,7 +131,11 @@ func (r *WorkflowRunReconciler) Reconcile(ctx context.Context, req ctrl.Request)
return r.endWithNegativeCondition(logCtx, run, condition.ErrorCondition(v1alpha1.WorkflowRunConditionType, err))
}

executor := executor.New(instance, r.Client)
patcher := &workflowRunPatcher{
Client: r.Client,
run: run,
}
executor := executor.New(instance, r.Client, patcher.patchStatus)
state, err := executor.ExecuteRunners(logCtx, runners)
if err != nil {
logCtx.Error(err, "[execute runners]")
Expand All @@ -141,28 +150,28 @@ func (r *WorkflowRunReconciler) Reconcile(ctx context.Context, req ctrl.Request)
case v1alpha1.WorkflowStateSuspending:
logCtx.Info("Workflow return state=Suspend")
if duration := executor.GetSuspendBackoffWaitTime(); duration > 0 {
return ctrl.Result{RequeueAfter: duration}, r.patchStatus(logCtx, run, isUpdate)
return ctrl.Result{RequeueAfter: duration}, patcher.patchStatus(logCtx, &run.Status, isUpdate)
}
return ctrl.Result{}, r.patchStatus(logCtx, run, isUpdate)
return ctrl.Result{}, patcher.patchStatus(logCtx, &run.Status, isUpdate)
case v1alpha1.WorkflowStateFailed:
logCtx.Info("Workflow return state=Failed")
r.doWorkflowFinish(run)
r.Recorder.Event(run, event.Normal(v1alpha1.ReasonExecute, v1alpha1.MessageFailed))
return ctrl.Result{}, r.patchStatus(logCtx, run, isUpdate)
return ctrl.Result{}, patcher.patchStatus(logCtx, &run.Status, isUpdate)
case v1alpha1.WorkflowStateTerminated:
logCtx.Info("Workflow return state=Terminated")
r.doWorkflowFinish(run)
r.Recorder.Event(run, event.Normal(v1alpha1.ReasonExecute, v1alpha1.MessageTerminated))
return ctrl.Result{}, r.patchStatus(logCtx, run, isUpdate)
return ctrl.Result{}, patcher.patchStatus(logCtx, &run.Status, isUpdate)
case v1alpha1.WorkflowStateExecuting:
logCtx.Info("Workflow return state=Executing")
return ctrl.Result{RequeueAfter: executor.GetBackoffWaitTime()}, r.patchStatus(logCtx, run, isUpdate)
return ctrl.Result{RequeueAfter: executor.GetBackoffWaitTime()}, patcher.patchStatus(logCtx, &run.Status, isUpdate)
case v1alpha1.WorkflowStateSucceeded:
logCtx.Info("Workflow return state=Succeeded")
r.doWorkflowFinish(run)
run.Status.SetConditions(condition.ReadyCondition(v1alpha1.WorkflowRunConditionType))
r.Recorder.Event(run, event.Normal(v1alpha1.ReasonExecute, v1alpha1.MessageSuccessfully))
return ctrl.Result{}, r.patchStatus(logCtx, run, isUpdate)
return ctrl.Result{}, patcher.patchStatus(logCtx, &run.Status, isUpdate)
case v1alpha1.WorkflowStateSkipped:
logCtx.Info("Skip this reconcile")
return ctrl.Result{}, nil
Expand Down Expand Up @@ -228,13 +237,15 @@ func (r *WorkflowRunReconciler) SetupWithManager(mgr ctrl.Manager) error {

func (r *WorkflowRunReconciler) endWithNegativeCondition(ctx context.Context, wr *v1alpha1.WorkflowRun, condition condition.Condition) (ctrl.Result, error) {
wr.SetConditions(condition)
if err := r.patchStatus(ctx, wr, false); err != nil {
if err := r.Status().Patch(ctx, wr, client.Merge); err != nil {
return ctrl.Result{}, errors.WithMessage(err, "failed to patch workflowrun status")
}
return ctrl.Result{}, fmt.Errorf("reconcile WorkflowRun error, msg: %s", condition.Message)
}

func (r *WorkflowRunReconciler) patchStatus(ctx context.Context, wr *v1alpha1.WorkflowRun, isUpdate bool) error {
func (r *workflowRunPatcher) patchStatus(ctx context.Context, status *v1alpha1.WorkflowRunStatus, isUpdate bool) error {
wr := r.run
r.run.Status = *status
if isUpdate {
if err := r.Status().Update(ctx, wr); err != nil {
executor.StepStatusCache.Store(fmt.Sprintf("%s-%s", wr.Name, wr.Namespace), -1)
Expand Down
9 changes: 7 additions & 2 deletions pkg/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
corev1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"

"github.com/kubevela/pkg/util/rand"
Expand Down Expand Up @@ -217,15 +218,19 @@ func (wf *WorkflowContext) writeToStore() error {

func (wf *WorkflowContext) sync() error {
ctx := context.Background()
store := &corev1.ConfigMap{}
if EnableInMemoryContext {
MemStore.UpdateInMemoryContext(wf.store)
} else if err := wf.cli.Update(ctx, wf.store); err != nil {
} else if err := wf.cli.Get(ctx, types.NamespacedName{
Name: wf.store.Name,
Namespace: wf.store.Namespace,
}, store); err != nil {
if kerrors.IsNotFound(err) {
return wf.cli.Create(ctx, wf.store)
}
return err
}
return nil
return wf.cli.Patch(ctx, wf.store, client.MergeFrom(store))
}

// LoadFromConfigMap recover workflow context from configMap.
Expand Down
2 changes: 1 addition & 1 deletion pkg/context/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ func newCliForTest(t *testing.T, wfCm *corev1.ConfigMap) *test.MockClient {
}
return nil
},
MockUpdate: func(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error {
MockPatch: func(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error {
o, ok := obj.(*corev1.ConfigMap)
if ok {
if wfCm == nil {
Expand Down
Loading