Now I understand the issue clearly. Let me trace through what happens:
-
Commit 4dd3be7f9 moved the wait for log uploads logic into the pipeline runtime. It added an uploadWait WaitGroup and made sure runDetachedStep adds to it before launching the goroutine.
-
This introduced a bug: for unbounded services (infinitely running), the WaitStep call in completeStep blocks until the container exits. But with Kubernetes, when DestroyWorkflow is called (after all stages complete), it destroys all pods including service pods. The service pod being destroyed should cause WaitStep to detect this and return.
-
Commit 60df1c618 was supposed to fix this by adding an explicit destroyWorkflowFunc() call AFTER all stages complete (before waiting for uploadWait), so that DestroyWorkflow is called and service pods are destroyed.
Looking at the current code in workflow.go:
func (r *Runtime) Run(runnerCtx context.Context) error {
...
destroyWorkflowFunc := sync.OnceFunc(func() {
...
if err := r.engine.DestroyWorkflow(ctx, r.spec, r.taskUUID); err != nil {
...
}
})
defer destroyWorkflowFunc()
...
for _, stage := range r.spec.Stages {
...
}
// Now we can shutdown the workflow
destroyWorkflowFunc()
// Ensure all logs/traces are uploaded before finishing
logger.Debug().Msg("waiting for logs and traces upload")
r.uploadWait.Wait()
logger.Debug().Msg("logs and traces uploaded")
return r.err.Get()
}
Wait, this looks correct! The fix commit 60df1c618 is already applied. Let me check if there's still an issue...
Actually, let me re-read the issue description more carefully:
"with newer releases (3.14.x), With kubernetes backend and pipelines defining services, the services are not cleaned properly. The pods from kubernetes backend are destroyed properly, but the woodpecker API still show these steps as state=running."
So the pods ARE destroyed (DestroyWorkflow is called), but the API still shows them as running. This means the issue is NOT about the workflow hanging, but about the service steps not being properly traced with their final "stopped" state.
Let me think about the flow again:
DestroyWorkflow is called, which destroys all pods including service pods
- Service step goroutines are in
completeStep, which is waiting on WaitStep
- When the pod is destroyed, the Kubernetes informer should detect this and close the
finished channel
WaitStep should return
completeStep calls DestroyStep (which might be a no-op since pod is already destroyed)
completeStep calls traceStep to report the final state
r.uploadWait.Done() is called
But there's a potential issue: what happens if WaitStep doesn't detect that the pod was destroyed?
Looking at the WaitStep implementation in kubernetes.go:
func (e *kube) WaitStep(ctx context.Context, step *types.Step, taskUUID string) (*types.State, error) {
...
podUpdated := func(_, newPod any) {
pod, ok := newPod.(*kube_core_v1.Pod)
if !ok {
...
return
}
if pod.Name == podName {
if isImagePullBackOffState(pod) || isInvalidImageName(pod) {
finishedOnce.Do(func() { close(finished) })
}
switch pod.Status.Phase {
case kube_core_v1.PodSucceeded, kube_core_v1.PodFailed, kube_core_v1.PodUnknown:
finishedOnce.Do(func() { close(finished) })
}
}
}
...
}
The informer only receives UpdateFunc events. When a pod is DELETED, the informer might not trigger an update event for the deleted pod. It would trigger a deletion event, but the informer's UpdateFunc handler is not called for deletions.
Actually, wait - when you delete a pod, the informer should first trigger an update (setting the pod's deletion timestamp, etc.), and then trigger a deletion event. But since we only added an UpdateFunc handler, the deletion event won't trigger the handler.
So the question is: when a pod is deleted, does the informer trigger an UpdateFunc event for the last state of the pod before deletion?
Actually, looking at the Kubernetes informer documentation, when a resource is deleted:
- The informer receives a DELETE event
- The cached object is removed
- If there's a
DeleteFunc handler, it's called
But we're only using UpdateFunc. So when a pod is deleted, the informer won't call our UpdateFunc handler, and the finished channel will never be closed!
Wait, but there's another mechanism. Let me look at the informer more carefully.
Actually, I think the issue is different. When a pod is deleted with a foreground propagation policy, the pod's phase might change to "Terminating" before it's actually deleted. But with the background propagation policy (which is what we're using based on newDefaultDeleteOptions()), the pod is deleted immediately.
Let me look at the informer setup more carefully:
si := informers.NewSharedInformerFactoryWithOptions(e.client, defaultResyncDuration, informers.WithNamespace(e.config.GetNamespace(step.OrgID)))
if _, err := si.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: podUpdated,
},
); err != nil {
return nil, err
}
stop := make(chan struct{})
si.Start(stop)
defer close(stop)
The informer is started, but there's no DeleteFunc handler. So when a pod is deleted, our handler won't be called.
Actually wait, let me think about this more carefully. When a pod is being deleted (before it's actually removed from etcd), the informer should receive the update. Let me check what happens when you delete a pod with DeletePropagationBackground:
With DeletePropagationBackground:
- The pod is deleted from etcd
- The controller-manager immediately removes the finalizers (if any)
- The pod object is removed
So the informer should receive the deletion event. But we're only listening to UpdateFunc, not DeleteFunc.
But wait, there's another mechanism: the informer's resync. The informer is configured with defaultResyncDuration = 5 * time.Second. This means the informer will periodically resync all objects. When a pod is deleted, the next resync should detect that it's no longer in the cache.
But our UpdateFunc handler only checks the newPod object. If the pod is deleted, the informer won't call the UpdateFunc handler with the deleted pod.
Actually, I think I need to understand this better. Let me look at how the Kubernetes informer works:
When a resource is deleted:
- The informer receives a
cache.DeletionHandlingMetaNamespaceKeyFunc event with cache.DeletedFinalStateUnknown if the handler is not fast enough to receive the delete event, or
- If the handler is fast enough, it receives a
DeleteFunc event
But we're not setting up a DeleteFunc handler. So when a pod is deleted, our handler is NOT called.
However, the informer does maintain a cache. When a pod is deleted, the cache is updated to remove the pod. But the UpdateFunc handler is not called.
So if we delete a pod, and we only have an UpdateFunc handler, the handler is never called for the deletion.
This means that when DestroyWorkflow deletes a service pod, the WaitStep function is still waiting on the finished channel. The pod is gone, but our handler doesn't know about it.
After defaultResyncDuration (5 seconds), the informer will resync, and it will call the UpdateFunc handler for all objects in the cache. But at this point, the pod is no longer in the cache, so the handler won't be called for it.
Actually, I think the issue is simpler. Let me look at the informer's behavior again.
When a pod is deleted, the informer calls:
OnDelete(obj) if there's a DeleteFunc handler, OR
OnUpdate(oldObj, newObj) if there's an UpdateFunc handler
But when a pod is deleted, there's no "new" version of the pod. The informer just removes it from the cache.
Actually, I think the informer might call the UpdateFunc handler with the old object as both old and new before the delete. Let me check...
Actually, I think the informer calls OnUpdate(oldObj, newObj) when an object is modified, and OnDelete(obj) when an object is deleted. Since we're not setting up a DeleteFunc handler, we won't be notified when a pod is deleted.
But wait, the informer's cache is updated when an object is deleted. So when we do e.client.CoreV1().Pods(namespace).Get(ctx, podName, ...), we'll get an error saying the pod is not found.
So the issue is that WaitStep is waiting for the informer to tell it that the pod is done. When the pod is deleted, the informer doesn't call our handler, so we keep waiting.
Actually, let me look at the informer's behavior more carefully. When you have a shared informer and you add a handler with UpdateFunc, the informer will call the UpdateFunc for every update to any object in the cache. When an object is deleted, the informer:
- Calls
OnDelete(obj) if there's a DeleteFunc handler
- Removes the object from the cache
If there's no DeleteFunc handler, the informer just removes the object from the cache. The UpdateFunc is NOT called for deletions.
So when DestroyWorkflow deletes a service pod, the WaitStep function is still waiting on the finished channel. The informer doesn't call our handler, so we keep waiting.
But wait, after the informer resyncs (5 seconds), it will re-list all objects. At this point, the pod is gone, so the informer will notice that the pod was deleted. But the informer will call OnDelete for the deleted object, not OnUpdate. So our UpdateFunc handler won't be called.
So the issue is that when a pod is deleted, our WaitStep function never knows about it.
But wait, the issue description says "The pods from kubernetes backend are destroyed properly". So the pods ARE being destroyed. And the issue says "API still show these steps as state=running". This suggests that the service steps are not being properly traced with their final "stopped" state.
Let me think about this again...
Actually, I think I was on the right track earlier. The issue is that:
DestroyWorkflow deletes all service pods
- Service step goroutines are blocked in
WaitStep, waiting for the informer to tell them the pod is done
- Since we only have an
UpdateFunc handler and not a DeleteFunc handler, the informer doesn't call our handler when the pod is deleted
- The goroutines keep waiting
uploadWait.Wait() hangs until the informer resyncs (5 seconds)
- After the resync, the informer might finally detect that the pod is gone and call our handler
But the issue description says "These are only cleaned after the pipeline times out." This suggests that the goroutines never complete until the pipeline times out.
Wait, but the pipeline has a timeout. If the service goroutines don't complete, the workflow will hang forever (or until the context is canceled).
Actually, looking at the code again:
// Now we can shutdown the workflow
destroyWorkflowFunc()
// Ensure all logs/traces are uploaded before finishing
logger.Debug().Msg("waiting for logs and traces upload")
r.uploadWait.Wait()
If WaitStep never returns because the informer doesn't call our handler, then uploadWait.Wait() will hang forever. But the issue description says "These are only cleaned after the pipeline times out." This suggests that the workflow does eventually complete, but it takes a long time.
Let me re-read the issue description again:
"once wait-for-postgres step completes, the pods are destroyed, but API still shows the service as running, also visible on Web UI."
"Expected behavior: Pipeline services are stopped once the pipeline steps complete, the pipeline completes."
"These are only cleaned after the pipeline times out."
OK so the issue is:
- The main step (wait-for-postgres) completes
- The pipeline proceeds to call
DestroyWorkflow, which destroys all pods
- But the service step goroutines don't complete their
WaitStep calls because the informer doesn't call their UpdateFunc handler when the pods are deleted
- The service steps are stuck in "running" state in the API/UI
- Eventually, the pipeline times out and the goroutines complete (when the context is canceled)
So the fix should be to ensure that when a pod is deleted, the informer calls our handler. We need to add a DeleteFunc handler.
Let me check if there's a DeleteFunc handler in the informer:
Looking at the kubernetes.go code:
if _, err := si.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: podUpdated,
},
); err != nil {
return nil, err
}
There's no DeleteFunc handler! This is the bug.
The fix should be to add a DeleteFunc handler that also triggers the finished channel:
if _, err := si.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: podUpdated,
DeleteFunc: func(obj any) {
pod, ok := obj.(*kube_core_v1.Pod)
if !ok {
return
}
if pod.Name == podName {
finishedOnce.Do(func() { close(finished) })
}
},
},
); err != nil {
return nil, err
}
But wait, when a pod is deleted, the informer might call the DeleteFunc handler with a cache.DeletedFinalStateUnknown object if the handler is not fast enough to receive the delete event. So we need to handle that case too.
Actually, let me look at the cache.DeletedFinalStateUnknown type:
type DeletedFinalStateUnknown struct {
Key string
Obj interface{}
}
If the informer calls DeleteFunc with a DeletedFinalStateUnknown object, we need to extract the pod from it.
But actually, looking at the informer's code, if the handler is fast enough to receive the delete event, it will be called with the actual pod object. The DeletedFinalStateUnknown is only used when the handler is too slow to receive the delete event.
Since we're running the informer synchronously (we start the informer and then wait for the event), we should be fast enough to receive the delete event. So we can just handle the *kube_core_v1.Pod case.
Actually, wait. The issue is even simpler. Looking at the informer's behavior:
When a pod is deleted, the informer will call the DeleteFunc handler with the deleted pod object. This is because the informer is running in the same goroutine and processing events synchronously.
But we're not setting up a DeleteFunc handler. So when a pod is deleted, the informer doesn't call any handler.
So the fix is to add a DeleteFunc handler.
But actually, there's another issue. Looking at the informer setup:
si := informers.NewSharedInformerFactoryWithOptions(e.client, defaultResyncDuration, informers.WithNamespace(e.config.GetNamespace(step.OrgID)))
if _, err := si.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: podUpdated,
},
); err != nil {
return nil, err
}
stop := make(chan struct{})
si.Start(stop)
defer close(stop)
The informer is started, but it's stopped immediately after the function returns (defer close(stop)). But we're waiting for the informer to call our handler. So the informer needs to be running while we're waiting.
Actually, the informer is started in a separate goroutine, and we're waiting on the finished channel. When the informer receives an event (e.g., the pod is deleted), it calls our handler, which closes the finished channel. Then WaitStep returns.
But if we're not setting up a DeleteFunc handler, the informer won't call our handler when the pod is deleted. So we keep waiting.
OK so I'm pretty confident now that the issue is the missing DeleteFunc handler.
Let me also check if there's a similar issue in the TailStep function:
func (e *kube) TailStep(ctx context.Context, step *types.Step, taskUUID string) (io.ReadCloser, error) {
...
podUpdated := func(_, newPod any) {
...
if pod.Name == podName {
if isImagePullBackOffState(pod) || isInvalidImageName(pod) {
upOnce.Do(func() { close(up) })
}
switch pod.Status.Phase {
case kube_core_v1.PodRunning, kube_core_v1.PodSucceeded, kube_core_v1.PodFailed:
upOnce.Do(func() { close(up) })
}
}
}
if _, err := si.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: podUpdated,
},
); err != nil {
return nil, err
}
...
}
Same issue - no DeleteFunc handler. But for TailStep, we're waiting for the pod to be in a running/succeeded/failed state. If the pod is deleted, we might not know about it. But actually, for TailStep, we're only using it to wait for the pod to be in a terminal state before starting to stream logs. So if the pod is deleted, we'll try to get the logs and get an error. But we should also handle the case where the pod is deleted before we can start streaming logs.
Actually, looking at the code more carefully, I see that TailStep is called BEFORE WaitStep. So the sequence is:
StartStep - starts the pod
TailStep - waits for the pod to be running, then starts streaming logs
WaitStep - waits for the pod to complete
DestroyStep - stops the pod
So for TailStep, the pod should be running before we call WaitStep. And for WaitStep, the pod might be deleted while we're waiting.
But actually, DestroyStep is called after WaitStep returns. So the sequence is:
StartStep - starts the pod
TailStep - waits for the pod to be running, then starts streaming logs
WaitStep - waits for the pod to complete
DestroyStep - stops the pod
But in completeStep, the sequence is:
waitForLogs() - drains the log stream
WaitStep - waits for the pod to complete
DestroyStep - stops the pod
So WaitStep is called AFTER the pod is running and logs are streaming. And DestroyStep is called AFTER WaitStep returns.
But in DestroyWorkflow, we're calling stopPod for all steps. If DestroyWorkflow is called while WaitStep is waiting, the pod will be deleted. And WaitStep won't know about it because we don't have a DeleteFunc handler.
So the fix is to add a DeleteFunc handler.
Actually, let me also think about the TailStep function. If the pod is deleted before we can start streaming logs, we should handle that case. But actually, the pod should be running before we call TailStep (since StartStep should have started it). So if the pod is deleted, it's because DestroyWorkflow was called.
But actually, for services, the goroutine is started in the background. So the sequence for a service is:
StartStep - starts the pod
TailStep - waits for the pod to be running, then starts streaming logs
- Return immediately (since it's a detached step)
- Goroutine calls
completeStep:
a. waitForLogs() - drains the log stream
b. WaitStep - waits for the pod to complete
c. DestroyStep - stops the pod
So for services, TailStep is called BEFORE the goroutine is started. And the goroutine is started after TailStep returns. So by the time the goroutine calls WaitStep, the pod should be running.
But if DestroyWorkflow is called while the goroutine is in WaitStep, the pod will be deleted. And WaitStep won't know about it.
So the fix is to add a DeleteFunc handler to WaitStep.
Let me also check if there are any tests that cover this case.
Looking at the test file, I see:
// TestWorkflowUnboundedServiceDoesNotHang asserts that when all normal steps
// have finished, a long-running service does NOT keep the workflow blocked
// forever.
This test uses the dummy backend, which has a different implementation of WaitStep. Let me check how the dummy backend handles this.
Looking at the dummy backend in commit 60df1c618:
func (e *dummy) WaitStep(ctx context.Context, step *types.Step, taskUUID string) (*types.State, error) {
...
rawWC, exist := e.kv.Load(workflowKey(taskUUID))
if !exist {
...
}
wc, ok := rawWC.(chan struct{})
if !ok {
return nil, fmt.Errorf("workflow stop chan not found")
}
key := stepKey(taskUUID, step.UUID)
...
} else if step.Type == backend_types.StepTypeService {
if sleepWithContext(ctx, wc, testServiceTimeout) {
// context for service closed — we can move forward
} else {
...
}
}
...
}
So for services, the dummy backend uses a sleepWithContext that waits on the context OR the workflow stop channel. When the workflow is destroyed, the stop channel is closed, and WaitStep returns.
This is the pattern that the Kubernetes backend should also follow. But the Kubernetes backend uses an informer to detect pod completion. And the informer doesn't call our handler when the pod is deleted.
So the fix for the Kubernetes backend should be to add a DeleteFunc handler.
Actually, wait. Let me re-check the informer's behavior. When a pod is deleted, does the informer call the UpdateFunc handler with the deleted pod?
Looking at the Kubernetes informer documentation:
- When an object is updated, the
UpdateFunc handler is called with (oldObj, newObj)
- When an object is deleted, the
DeleteFunc handler is called with the deleted object
So the UpdateFunc handler is NOT called when an object is deleted. We need to add a DeleteFunc handler.
But wait, when an object is being deleted, the informer might call the UpdateFunc handler with the last update before the delete. But with DeletePropagationBackground, the pod is deleted immediately without a finalizer. So the informer might not see any update before the delete.
Actually, let me think about this more carefully. When you call Delete() with DeletePropagationBackground:
- The Kubernetes API server immediately deletes the pod object
- The informer receives a delete event
So the informer receives a delete event, but we're not setting up a DeleteFunc handler. So we don't know about it.
But wait, the informer's cache is updated when an object is deleted. So when we do e.client.CoreV1().Pods(namespace).Get(ctx, podName, ...), we'll get an error saying the pod is not found.
So the issue is that WaitStep is waiting for the informer to call our handler. But we're not setting up a DeleteFunc handler, so we don't know when the pod is deleted.
So the fix is to add a DeleteFunc handler.
But actually, there's another approach. Instead of relying on the informer to tell us when the pod is deleted, we can check if the pod exists after the informer calls our handler. If the pod doesn't exist, we can assume it was deleted.
But this approach doesn't help because the informer doesn't call our handler when the pod is deleted.
So the fix is definitely to add a DeleteFunc handler.
Let me now think about the exact fix. The DeleteFunc handler should:
- Check if the deleted pod is the pod we're waiting for
- If so, close the
finished channel
But we also need to handle the case where the DeleteFunc handler is called with a cache.DeletedFinalStateUnknown object. In this case, we need to extract the pod from the object.
Let me write the fix:
DeleteFunc: func(obj any) {
pod, ok := obj.(*kube_core_v1.Pod)
if !ok {
// Handle DeletedFinalStateUnknown case
if tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok {
pod, ok = tombstone.Obj.(*kube_core_v1.Pod)
if !ok {
return
}
} else {
return
}
}
if pod.Name == podName {
finishedOnce.Do(func() { close(finished) })
}
},
Actually, looking at the code more carefully, I see that the informer's UpdateFunc handler checks pod.Name == podName. So we should do the same in the DeleteFunc handler.
But wait, there's another issue. When the informer calls the UpdateFunc handler, it's because the pod was updated (e.g., the pod's phase changed). But when the pod is deleted, the informer calls the DeleteFunc handler with the deleted pod.
So the fix is correct: we need to add a DeleteFunc handler.
But actually, I just realized something. When a pod is being deleted, the Kubernetes API server might call the UpdateFunc handler with the pod's last state before it's deleted. This is because the pod has a deletionTimestamp before it's actually deleted.
But with DeletePropagationBackground, the pod is deleted immediately without a finalizer. So the informer might not see any update before the delete.
Actually, I'm not sure about this. Let me check the Kubernetes documentation.
According to the Kubernetes documentation:
- When a resource is deleted, the API server sets the
deletionTimestamp field on the object
- The object remains in etcd until the finalizers are cleared
- When the finalizers are cleared, the object is deleted
But with DeletePropagationBackground, the propagation policy is "Background", which means the API server deletes the object immediately without waiting for the garbage collector to clean up dependent objects.
So when you delete a pod with DeletePropagationBackground:
- The API server deletes the pod object immediately
- The informer receives a delete event
But wait, before the pod is deleted, the API server sets the deletionTimestamp field. So the pod is updated with the deletionTimestamp, and the informer receives an update event. Then the pod is deleted, and the informer receives a delete event.
So the informer should call the UpdateFunc handler with the pod's last state (including the deletionTimestamp), and then call the DeleteFunc handler with the deleted pod.
But we're not setting up a DeleteFunc handler. So we only see the update event, not the delete event.
But the update event might not set the pod's phase to a terminal state. The pod might still have Phase: PodRunning even after the deletionTimestamp is set.
So we need to add a DeleteFunc handler to detect when the pod is deleted.
Actually, I just realized something else. When the deletionTimestamp is set on the pod, the pod is in a "Terminating" state. But the pod's Status.Phase is still PodRunning. The pod's Status.Reason might be Evicted or NodeLost, but not always.
So we need to check for the deletionTimestamp field. But that's a separate issue.
Let me focus on the DeleteFunc handler. The fix is:
if _, err := si.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: podUpdated,
DeleteFunc: func(obj any) {
pod, ok := obj.(*kube_core_v1.Pod)
if !ok {
if tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok {
if pod, ok = tombstone.Obj.(*kube_core_v1.Pod); !ok {
return
}
} else {
return
}
}
if pod.Name == podName {
finishedOnce.Do(func() { close(finished) })
}
},
},
); err != nil {
return nil, err
}
OK let me now write the actual fix.
Wait, let me double-check the issue. The problem is:
DestroyWorkflow calls stopPod for all service pods
- The informer doesn't call our handler when the pod is deleted (because we don't have a
DeleteFunc handler)
- The
WaitStep function keeps waiting
- The goroutine doesn't call
traceStep to report the final state
- The API shows the service as running
But actually, there's another issue. Even if we add a DeleteFunc handler, the WaitStep function needs to return a proper state. Let me check what the WaitStep function returns:
func (e *kube) WaitStep(ctx context.Context, step *types.Step, taskUUID string) (*types.State, error) {
...
select {
case <-finished:
case <-ctx.Done():
return nil, ctx.Err()
}
pod, err := e.client.CoreV1().Pods(e.config.GetNamespace(step.OrgID)).Get(ctx, podName, kube_meta_v1.GetOptions{})
if err != nil {
return nil, err
}
...
}
If the pod is deleted, the Get call will fail with a "not found" error. So we need to handle this case.
But actually, if the DeleteFunc handler is called, the finished channel will be closed. So we'll exit the select block. Then we try to Get the pod, which will fail. So we'll return an error.
But that's not what we want. We want to return a proper state for the service step.
Actually, looking at the code more carefully, I see that the WaitStep function returns:
- A
State with Exited=true and ExitCode from the terminated container
- An error if the pod is not found
But if the pod is deleted, we don't know the exit code. So we need to handle this case differently.
Actually, let me look at the completeStep function:
func (r *Runtime) completeStep(runnerCtx context.Context, step *backend_types.Step, waitForLogs func(), startTime int64) (*backend_types.State, error) {
waitForLogs()
waitState, err := r.engine.WaitStep(r.ctx, step, r.taskUUID)
if err != nil {
if errors.Is(err, context.Canceled) {
if waitState == nil {
waitState = &backend_types.State{}
}
waitState.Error = pipeline_errors.ErrCancel
} else {
return nil, err
}
}
...
}
So if WaitStep returns an error, completeStep checks if it's a context cancellation. If so, it uses a default state with the error set. Otherwise, it returns the error.
But if the pod is deleted, the error is not a context cancellation. So completeStep will return an error.
But wait, the issue is that the service goroutine is stuck in WaitStep. It never returns. So the error never happens.
But if we add a DeleteFunc handler, the finished channel will be closed. So WaitStep will exit the select block. Then it tries to Get the pod, which fails. So it returns an error.
But the error is not a context cancellation. So completeStep will return an error.
And then the goroutine will log the error but not propagate it:
func (r *Runtime) runDetachedStep(runnerCtx context.Context, step *backend_types.Step) error {
...
r.uploadWait.Add(1)
go func() {
defer r.uploadWait.Done()
logger := r.makeLogger()
processState, err := r.completeStep(runnerCtx, step, waitForLogs, startTime)
...
if err != nil {
logger.Error().Err(err).Str("step", step.Name).Msg("detached step failed while running")
}
if traceErr := r.traceStep(processState, err, step); traceErr != nil {
...
}
}()
return nil
}
So if completeStep returns an error, the goroutine logs it and calls traceStep. But processState might be nil if completeStep returns before setting it.
Actually, looking at completeStep:
func (r *Runtime) completeStep(runnerCtx context.Context, step *backend_types.Step, waitForLogs func(), startTime int64) (*backend_types.State, error) {
waitForLogs()
waitState, err := r.engine.WaitStep(r.ctx, step, r.taskUUID)
if err != nil {
if errors.Is(err, context.Canceled) {
if waitState == nil {
waitState = &backend_types.State{}
}
waitState.Error = pipeline_errors.ErrCancel
} else {
return nil, err
}
}
...
return waitState, nil
}
If WaitStep returns an error that's not a context cancellation, completeStep returns nil, err. So processState is nil.
And in runDetachedStep:
processState, err := r.completeStep(runnerCtx, step, waitForLogs, startTime)
...
if err != nil {
logger.Error().Err(err).Str("step", step.Name).Msg("detached step failed while running")
}
if traceErr := r.traceStep(processState, err, step); traceErr != nil {
...
}
So if processState is nil and err is not nil, traceStep will be called with processState=nil, err!=nil. And traceStep will create a dummy state:
func (r *Runtime) traceStep(processState *backend_types.State, err error, step *backend_types.Step) error {
...
switch {
case processState == nil && err != nil:
s.CurrStepState = backend_types.State{
Error: err,
Exited: true,
OOMKilled: false,
}
...
}
...
}
So traceStep will create a state with Exited=true and Error=err. And then it will call the tracer to report this state.
So the fix (adding a DeleteFunc handler) should work. When the pod is deleted:
- The
DeleteFunc handler is called
- The
finished channel is closed
WaitStep exits the select block
WaitStep tries to Get the pod, which fails
WaitStep returns an error
completeStep returns nil, err
- The goroutine logs the error and calls
traceStep
traceStep creates a state with Exited=true and Error=err
- The tracer reports this state
- The API shows the service as stopped (with an error)
But wait, the issue description says the service should be stopped, not failed. So maybe we need to handle the "pod not found" case differently.
Actually, looking at the issue description again:
"Expected behavior: Pipeline services are stopped once the pipeline steps complete, the pipeline completes."
So the service should be stopped, not failed. But the service is infinitely running (like a PostgreSQL container). So it never completes on its own. The service is stopped by DestroyWorkflow deleting the pod.
So when WaitStep detects that the pod is deleted, it should return a state indicating that the service was stopped (not failed).
Let me modify the WaitStep function to handle this case:
pod, err := e.client.CoreV1().Pods(e.config.GetNamespace(step.OrgID)).Get(ctx, podName, kube_meta_v1.GetOptions{})
if errors.IsNotFound(err) {
// Pod was deleted (e.g., by DestroyWorkflow). This is expected for services.
return &backend_types.State{
Exited: true,
Error: pipeline_errors.ErrCancel,
}, nil
}
if err != nil {
return nil, err
}
But wait, we don't want to return an error. We want to indicate that the service was stopped. But the State struct doesn't have a field for "stopped by user".
Actually, looking at the issue more carefully, I think the key issue is that the service step is not being traced with its final state. The traceStep function is called with the processState, which includes the Exited field. If Exited=true, the API should show the service as stopped.
So even if the service was stopped by DestroyWorkflow, the API should show it as stopped (with Exited=true).
Let me re-read the issue description:
"The pods from kubernetes backend are destroyed properly, but the woodpecker API still show these steps as state=running."
So the pods are destroyed (which is correct), but the API shows them as running (which is incorrect). This confirms that the issue is with the state reporting, not with the pod cleanup.
So the fix should ensure that:
- When
DestroyWorkflow deletes the service pod, WaitStep detects it
WaitStep returns a state indicating that the service was stopped
completeStep calls traceStep with this state
- The tracer reports the state to the server
- The API shows the service as stopped
The current issue is that WaitStep never returns because it's waiting for the informer to call the handler. And we're not setting up a DeleteFunc handler.
So the fix is to add a DeleteFunc handler.
But actually, let me also consider another approach. Instead of adding a DeleteFunc handler, we can check if the pod exists after the informer calls our handler. If the pod doesn't exist, we can assume it was deleted.
But this approach requires the informer to call our handler at least once before the pod is deleted. If the informer never calls our handler, we keep waiting.
So adding a DeleteFunc handler is the correct approach.
Let me also consider if there are any race conditions. If the pod is deleted before the informer is started, the informer might not call the DeleteFunc handler. In this case, we might hang forever.
But this race condition is unlikely because the pod is created by StartStep, and then we start the informer and wait. So the pod exists when we start the informer.
And if the pod is deleted while we're waiting, the informer should call the DeleteFunc handler.
OK I'm confident that the fix is to add a DeleteFunc handler.
Actually wait, let me re-check the issue description one more time to make sure I understand it correctly.
"With kubernetes backend and pipelines defining services, the services are not cleaned properly. The pods from kubernetes backend are destroyed properly, but the woodpecker API still show these steps as state=running."
OK so the pods ARE destroyed (correct), but the API still shows them as running (incorrect).
"These are only cleaned after the pipeline times out."
So the services are only cleaned up (in the API) after the pipeline times out. This confirms that the service goroutines are stuck in WaitStep and never complete until the context is canceled.
And the context is canceled when the pipeline times out. So when the context is canceled, the WaitStep function returns with context.Canceled error. And completeStep handles this by setting the error to pipeline_errors.ErrCancel.
But before the context is canceled, the DeleteFunc handler is not called, so the finished channel is never closed, so WaitStep never returns.
So the fix is to add a DeleteFunc handler.
Now let me think about what happens if the DeleteFunc handler is called. When the handler is called, the finished channel is closed. And WaitStep returns.
But then WaitStep tries to Get the pod, which fails with "not found". And WaitStep returns an error.
And completeStep handles the error. If the error is not a context cancellation, completeStep returns nil, err.
And the goroutine logs the error and calls traceStep. And traceStep creates a state with Exited=true and Error=err.
So the API will show the service as stopped (with an error).
But the issue says "Pipeline services are stopped once the pipeline steps complete, the pipeline completes." So the service should be stopped without an error.
Hmm, but actually, the service was stopped by DestroyWorkflow, which is expected. So maybe we should treat this as a successful stop, not an error.
Let me modify the WaitStep function to handle the "pod not found" case:
pod, err := e.client.CoreV1().Pods(e.config.GetNamespace(step.OrgID)).Get(ctx, podName, kube_meta_v1.GetOptions{})
if errors.IsNotFound(err) {
// Pod was deleted (e.g., by DestroyWorkflow). This is expected for services.
return &backend_types.State{
Exited: true,
Error: pipeline_errors.ErrCancel,
}, nil
}
Actually, I think we should return ExitCode: 0 or some other indicator that the service was stopped intentionally.
But looking at the issue description, the service is infinitely running. So it never exits on its own. And it's stopped by DestroyWorkflow. So the exit code doesn't really make sense.
But the API shows the service as running. So the issue is that the API doesn't know the service was stopped.
So the fix is to ensure that the service is traced with Exited=true. This is done by completeStep calling traceStep.
And traceStep creates a state with Exited=true and Error=err (if there's an error).
So the API will show the service as stopped (with an error if WaitStep returned an error).
But the issue description says "Pipeline services are stopped once the pipeline steps complete, the pipeline completes." So maybe we should treat this as a successful stop, not an error.
Actually, let me look at the issue description again:
"Expected behavior: Pipeline services are stopped once the pipeline steps complete, the pipeline completes."
So the expected behavior is that the service is stopped. The issue is that the service is NOT stopped (in the API). So the fix is to ensure that the service is stopped.
And the way to stop a service is to call traceStep with Exited=true. This is done by completeStep when WaitStep returns.
So the fix is to ensure that WaitStep returns when the pod is deleted. This is done by adding a DeleteFunc handler.
And WaitStep returns with an error if the pod is not found. And completeStep handles this by creating a state with Exited=true and Error=err.
So the API will show the service as stopped (with an error).
But the issue description says the service should be stopped. It doesn't say anything about the error.
Actually, looking at the issue description again:
"this prevents timely deploys as pipeline executions are not getting green status (although, as a mitigation, the pipeline waiting services can be cancelled, after which the deploy can be made)."
So the pipeline is not getting a green status because the services are shown as running. And the mitigation is to cancel the services.
So the fix should ensure that the services are shown as stopped. And the way to do this is to add a DeleteFunc handler.
OK I think I've analyzed this enough. Let me now write the fix.
Actually, wait. I also need to handle the TailStep function. If the pod is deleted before we can start streaming logs, the informer doesn't call our handler, and we keep waiting.
But actually, for services, TailStep is called BEFORE the goroutine is started. So by the time the goroutine calls WaitStep, TailStep has already started streaming logs.
So the issue is only with WaitStep, not with TailStep.
But actually, TailStep also waits for the pod to be running. If the pod is deleted before it's running, TailStep might hang.
But this is unlikely because the pod should be running before WaitStep is called.
OK let me focus on WaitStep.
Actually, I realize I also need to handle the TailStep function. Let me check if there's a similar issue.
Looking at TailStep:
func (e *kube) TailStep(ctx context.Context, step *types.Step, taskUUID string) (io.ReadCloser, error) {
...
podUpdated := func(_, newPod any) {
...
if pod.Name == podName {
if isImagePullBackOffState(pod) || isInvalidImageName(pod) {
upOnce.Do(func() { close(up) })
}
switch pod.Status.Phase {
case kube_core_v1.PodRunning, kube_core_v1.PodSucceeded, kube_core_v1.PodFailed:
upOnce.Do(func() { close(up) })
}
}
}
if _, err := si.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: podUpdated,
},
); err != nil {
return nil, err
}
...
}
TailStep waits for the pod to be in a terminal state (running, succeeded, failed). If the pod is deleted before it reaches a terminal state, TailStep might hang.
But actually, the pod should be running before TailStep returns. And TailStep waits for the pod to be running. So if the pod is deleted, TailStep will try to get the logs and get an error.
But TailStep is waiting for the informer to call the handler. If the handler is not called, TailStep hangs.
So we should also add a DeleteFunc handler to TailStep.
OK so the fix is to add a DeleteFunc handler to both WaitStep and TailStep.
But actually, for TailStep, we might want to handle the "pod deleted" case differently. If the pod is deleted, we should return an error so that the caller knows the pod doesn't exist.
And for WaitStep, if the pod is deleted, we should return a state indicating that the pod was deleted.
Let me now write the fix.
Actually, I think I should focus on the main issue first, which is WaitStep. Let me add a DeleteFunc handler to WaitStep and see if that fixes the issue.
Let me also check if there are any tests that cover this case.
Actually, looking at the test file, I see that the tests use the dummy backend, not the Kubernetes backend. So the tests don't cover this case.
But the commit 60df1c618 added tests for the dummy backend:
// TestWorkflowUnboundedServiceDoesNotHang asserts that when all normal steps
// have finished, a long-running service does NOT keep the workflow blocked
// forever.
This test uses the dummy backend, which has a different implementation of WaitStep. So this test doesn't cover the Kubernetes backend.
So we need to write a test for the Kubernetes backend. But since we can't actually test against a Kubernetes cluster, we might need to mock the Kubernetes client.
But for now, let me focus on the fix.
Let me also check the TailStep function more carefully:
func (e *kube) TailStep(ctx context.Context, step *types.Step, taskUUID string) (io.ReadCloser, error) {
...
switch pod.Status.Phase {
case kube_core_v1.PodRunning, kube_core_v1.PodSucceeded, kube_core_v1.PodFailed:
upOnce.Do(func() { close(up) })
}
...
}
So TailStep waits for the pod to be running, succeeded, or failed. If the pod is deleted, the informer doesn't call the handler, and TailStep hangs.
But actually, TailStep also waits for image pull back off or invalid image name states. So the handler is called for those states as well.
So if the pod is deleted, TailStep might hang forever.
But actually, looking at the code more carefully:
func (e *kube) TailStep(ctx context.Context, step *types.Step, taskUUID string) (io.ReadCloser, error) {
...
select {
case <-up:
case <-ctx.Done():
return nil, ctx.Err()
}
...
}
So TailStep waits on the up channel or the context. If the context is canceled, TailStep returns with ctx.Err().
But if the context is not canceled, TailStep hangs forever.
So we need to add a DeleteFunc handler to TailStep as well.
But actually, for services, TailStep is called BEFORE the goroutine is started. So by the time the goroutine calls WaitStep, TailStep has already returned.
So the issue is only with WaitStep.
OK let me focus on WaitStep.
Actually, I realize I should also check the StartStep function to see if there are any similar issues.
Looking at StartStep:
func (e *kube) StartStep(ctx context.Context, step *types.Step, taskUUID string) error {
...
log.Trace().Str("taskUUID", taskUUID).Msgf("starting step: %s", step.Name)
_, err = startPod(ctx, e, step, options, taskUUID)
return err
}
StartStep just starts the pod. It doesn't wait for the pod to be ready. So there's no issue here.
And StopStep is called by DestroyWorkflow:
func (e *kube) DestroyStep(ctx context.Context, step *types.Step, taskUUID string) error {
...
err := stopPod(ctx, e, step, e.config.newDefaultDeleteOptions())
...
}
DestroyStep just stops the pod. It doesn't wait for the pod to be stopped. So there's no issue here.
OK so the only issue is with WaitStep. Let me write the fix.
Now, the DeleteFunc handler for WaitStep should:
- Check if the deleted pod is the pod we're waiting for
- If so, close the
finished channel
But we also need to handle the case where the DeleteFunc handler is called with a cache.DeletedFinalStateUnknown object.
Let me write the fix:
DeleteFunc: func(obj any) {
var pod *kube_core_v1.Pod
if p, ok := obj.(*kube_core_v1.Pod); ok {
pod = p
} else if tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok {
if p, ok := tombstone.Obj.(*kube_core_v1.Pod); ok {
pod = p
}
}
if pod != nil && pod.Name == podName {
finishedOnce.Do(func() { close(finished) })
}
},
And then in the Get call, we need to handle the "pod not found" case:
pod, err := e.client.CoreV1().Pods(e.config.GetNamespace(step.OrgID)).Get(ctx, podName, kube_meta_v1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
// Pod was deleted (e.g., by DestroyWorkflow).
return &backend_types.State{
Exited: true,
Error: pipeline_errors.ErrCancel,
}, nil
}
return nil, err
}
Actually, I think we should also check if the pod's deletion timestamp is set. If so, the pod is being deleted. But this might be handled by the informer calling the DeleteFunc handler.
But actually, if the pod is being deleted (has a deletion timestamp), the informer might call the UpdateFunc handler with the pod's last state. And the pod's phase might still be PodRunning. So we need to check for the deletion timestamp.
But actually, with DeletePropagationBackground, the pod is deleted immediately without a finalizer. So the informer might not see the pod with a deletion timestamp.
Let me think about this more carefully. When you delete a pod with DeletePropagationBackground:
- The API server sets the deletion timestamp
- The API server deletes the pod immediately (because there's no finalizer and the propagation policy is Background)
- The informer receives a delete event
But wait, if the API server deletes the pod immediately, the informer might not see the pod with a deletion timestamp. It might just see the delete event.
So the DeleteFunc handler should be called. And we should close the finished channel.
But what if the API server doesn't delete the pod immediately? For example, if there are finalizers on the pod. In this case, the API server sets the deletion timestamp, and the pod is marked for deletion. But the pod is not deleted until the finalizers are cleared.
And during this time, the pod might still have Phase: PodRunning. So the informer calls the UpdateFunc handler with the pod's last state. And the pod's phase is still PodRunning.
So the UpdateFunc handler doesn't close the finished channel.
And when the finalizers are cleared and the pod is deleted, the informer calls the DeleteFunc handler. And the handler closes the finished channel.
So the DeleteFunc handler should handle this case.
OK so the fix is:
- Add a
DeleteFunc handler that closes the finished channel
- In the
Get call, handle the "pod not found" case by returning a state with Exited=true
Let me now write the actual fix.
Actually, I should also check if there's a race condition between the UpdateFunc handler and the DeleteFunc handler. If the UpdateFunc handler is called with the pod's last state, and then the DeleteFunc handler is called, the finishedOnce.Do will only close the channel once. So there's no race condition.
OK let me write the fix now.
Actually, I want to double-check one more thing. Looking at the WaitStep function:
func (e *kube) WaitStep(ctx context.Context, step *types.Step, taskUUID string) (*types.State, error) {
podName, err := stepToPodName(step)
if err != nil {
return nil, err
}
finished := make(chan struct{})
var finishedOnce sync.Once
podUpdated := func(_, newPod any) {
pod, ok := newPod.(*kube_core_v1.Pod)
if !ok {
log.Error().Msgf("could not parse pod: %v", newPod)
return
}
if pod.Name == podName {
if isImagePullBackOffState(pod) || isInvalidImageName(pod) {
finishedOnce.Do(func() { close(finished) })
}
switch pod.Status.Phase {
case kube_core_v1.PodSucceeded, kube_core_v1.PodFailed, kube_core_v1.PodUnknown:
finishedOnce.Do(func() { close(finished) })
}
}
}
si := informers.NewSharedInformerFactoryWithOptions(e.client, defaultResyncDuration, informers.WithNamespace(e.config.GetNamespace(step.OrgID)))
if _, err := si.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: podUpdated,
},
); err != nil {
return nil, err
}
stop := make(chan struct{})
si.Start(stop)
defer close(stop)
select {
case <-finished:
case <-ctx.Done():
return nil, ctx.Err()
}
pod, err := e.client.CoreV1().Pods(e.config.GetNamespace(step.OrgID)).Get(ctx, podName, kube_meta_v1.GetOptions{})
if err != nil {
return nil, err
}
...
}
So the WaitStep function:
- Creates a
finished channel
- Creates a
finishedOnce to ensure the channel is only closed once
- Sets up an informer with an
UpdateFunc handler
- Starts the informer
- Waits for the
finished channel to be closed (or the context to be canceled)
- Gets the pod's current state
- Returns the pod's state
The fix is to add a DeleteFunc handler that also closes the finished channel.
And then in step 6, we need to handle the "pod not found" case.
Let me write the fix.
Actually, I also want to think about what happens if the DeleteFunc handler is called after the UpdateFunc handler. In this case, the UpdateFunc handler might close the finished channel, and then the DeleteFunc handler calls finishedOnce.Do, which does nothing because the channel is already closed.
So there's no race condition.
OK let me write the fix now.
Actually, I realize I should also check if the informer is started before the UpdateFunc handler is added. If not, the informer might miss the first update event.
Looking at the code:
if _, err := si.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: podUpdated,
},
); err != nil {
return nil, err
}
stop := make(chan struct{})
si.Start(stop)
So the handler is added BEFORE the informer is started. This is correct.
OK let me write the fix now.
Wait, I should also handle the TailStep function. But actually, for TailStep, if the pod is deleted, the caller should be notified. So we should return an error if the pod is deleted.
But actually, for TailStep, we're waiting for the pod to be in a terminal state (running, succeeded, failed). If the pod is deleted before reaching a terminal state, the caller should know.
So we should add a DeleteFunc handler to TailStep as well. And if the DeleteFunc handler is called, we should close the up channel.
And then the caller should handle the case where TailStep returns early.
But actually, looking at the TailStep function:
select {
case <-up:
case <-ctx.Done():
return nil, ctx.Err()
}
So if the up channel is closed, TailStep returns. And then the caller tries to get the logs. If the pod is deleted, the Get call will fail.
So the caller should handle the error.
But actually, for services, TailStep is called BEFORE the goroutine is started. So if TailStep returns an error, the goroutine is not started.
But for regular steps, TailStep is called as part of startStep, which is called from runBlockingStep. And runBlockingStep returns an error if TailStep fails.
So for regular steps, if the pod is deleted, TailStep will return an error. And the step will fail.
But for services, if the pod is deleted, TailStep will return... what?
Actually, looking at startStep:
func (r *Runtime) startStep(step *backend_types.Step) (func(), int64, error) {
if err := r.engine.StartStep(r.ctx, step, r.taskUUID); err != nil {
return nil, 0, err
}
startTime := time.Now().Unix()
rc, err := r.engine.TailStep(r.ctx, step, r.taskUUID)
if err != nil {
return nil, 0, err
}
...
}
So startStep returns an error if TailStep fails. And runBlockingStep returns this error.
But for services, TailStep is called from startStep, which is called from runDetachedStep. And runDetachedStep returns an error if startStep fails.
So for services, if the pod is deleted, TailStep will return... an error? Or will it block forever?
Actually, looking at the code, TailStep blocks until the pod is in a terminal state. If the pod is deleted, the informer doesn't call the handler, and TailStep blocks forever.
So for services, if the pod is deleted, TailStep will block forever. And the goroutine is never started.
So we need to add a DeleteFunc handler to TailStep as well.
OK so the fix is to add a DeleteFunc handler to both WaitStep and TailStep.
For WaitStep, the DeleteFunc handler should close the finished channel.
For TailStep, the DeleteFunc handler should close the up channel.
And then the callers should handle the case where the pod is not found.
Let me now write the fix.
Actually, wait. I want to make sure I understand the issue correctly. Let me re-read the issue description.
"once wait-for-postgres step completes, the pods are destroyed, but API still shows the service as running"
So the wait-for-postgres step (the main step) completes. And then the pods are destroyed (by DestroyWorkflow). But the API shows the service as running.
So the issue is that the service goroutines are stuck in WaitStep. And DestroyWorkflow deletes the pod, but the goroutine doesn't know about it.
So the fix is to add a DeleteFunc handler to WaitStep.
OK let me write the fix now.
Let me think about what should happen when DeleteFunc is called for WaitStep:
- The
finished channel is closed
WaitStep exits the select block
WaitStep tries to Get the pod
- The
Get call fails with "not found"
WaitStep returns... what?
Currently, WaitStep returns nil, err. And completeStep handles the error. If the error is not a context cancellation, completeStep returns nil, err.
But actually, if the pod is deleted by DestroyWorkflow, this is expected. So we should treat this as a successful stop, not an error.
So we should return a state with Exited=true and no error (or with a specific error indicating that the pod was deleted).
Let me modify the WaitStep function:
pod, err := e.client.CoreV1().Pods(e.config.GetNamespace(step.OrgID)).Get(ctx, podName, kube_meta_v1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
// Pod was deleted (e.g., by DestroyWorkflow). Return a state indicating the step exited.
return &backend_types.State{
Exited: true,
Error: pipeline_errors.ErrCancel,
}, nil
}
return nil, err
}
Actually, I think we should use a different error message. pipeline_errors.ErrCancel is for context cancellation. But the pod was deleted by DestroyWorkflow, not canceled.
But actually, looking at completeStep:
waitState, err := r.engine.WaitStep(r.ctx, step, r.taskUUID)
if err != nil {
if errors.Is(err, context.Canceled) {
if waitState == nil {
waitState = &backend_types.State{}
}
waitState.Error = pipeline_errors.ErrCancel
} else {
return nil, err
}
}
So completeStep checks if the error is a context cancellation. If so, it uses a default state with the error set. Otherwise, it returns the error.
So if we return a state with Error=pipeline_errors.ErrCancel, completeStep won't handle it correctly because it only checks for context.Canceled, not pipeline_errors.ErrCancel.
Let me check what pipeline_errors.ErrCancel is:
Actually, let me look at the pipeline_errors package to see what errors are defined there.
But for now, let me just return a state with Exited=true and no error. Or with a specific error that's not context.Canceled.
Actually, looking at the code, I think the cleanest approach is to return a state with Exited=true and Error=pipeline_errors.ErrCancel. And then modify completeStep to handle this case.
But actually, pipeline_errors.ErrCancel is errors.New("canceled"). And completeStep checks for context.Canceled, which is context.Canceled = errors.New("context canceled").
So we should check for pipeline_errors.ErrCancel as well.
Actually, let me just look at the code again:
waitState, err := r.engine.WaitStep(r.ctx, step, r.taskUUID)
if err != nil {
if errors.Is(err, context.Canceled) {
if waitState == nil {
waitState = &backend_types.State{}
}
waitState.Error = pipeline_errors.ErrCancel
} else {
return nil, err
}
}
So WaitStep returns nil, err if there's an error. And completeStep checks if the error is context.Canceled. If so, it creates a default state with the error set.
But if WaitStep returns a state with Error=pipeline_errors.ErrCancel and err=nil, completeStep won't do anything special.
So let me just return a state with Exited=true and Error=pipeline_errors.ErrCancel:
if err != nil {
if errors.IsNotFound(err) {
// Pod was deleted (e.g., by DestroyWorkflow).
return &backend_types.State{
Exited: true,
Error: pipeline_errors.ErrCancel,
}, nil
}
return nil, err
}
And then completeStep will use this state as-is.
But actually, pipeline_errors.ErrCancel is for context cancellation. And the pod was deleted by DestroyWorkflow, not canceled.
So maybe we should return a state with Exited=true and no error:
if err != nil {
if errors.IsNotFound(err) {
// Pod was deleted (e.g., by DestroyWorkflow).
return &backend_types.State{
Exited: true,
}, nil
}
return nil, err
}
But this might be confusing because the service was deleted by DestroyWorkflow, not because it exited normally.
Actually, I think the cleanest approach is to return a state with Exited=true and Error=... to indicate that the service was deleted.
But let me just keep it simple and return a state with Exited=true and Error=.... The exact error doesn't matter as much as the Exited=true flag.
Actually, let me look at what the traceStep function does with the state:
func (r *Runtime) traceStep(processState *backend_types.State, err error, step *backend_types.Step) error {
...
switch {
case processState == nil && err != nil:
s.CurrStepState = backend_types.State{
Error: err,
Exited: true,
OOMKilled: false,
}
case processState != nil:
s.CurrStepState = *processState
...
}
...
}
So if processState != nil, traceStep uses the state as-is. So if we return a state with Exited=true, traceStep will report the step as exited.
So the fix is:
- Add a
DeleteFunc handler to WaitStep
- In the
Get call, handle the "pod not found" case by returning a state with Exited=true
Let me now write the fix.
Actually, I also want to check if there are any other places where the informer is used. Let me search for AddEventHandler in the codebase:
<tool_call>
<function=bash_terminal>
<parameter=command>
cd /woodpecker && grep -r "AddEventHandler" --include="*.go"
</tool_call>