|
| 1 | +// Copyright (c) HashiCorp, Inc. |
| 2 | +// SPDX-License-Identifier: BUSL-1.1 |
| 3 | + |
| 4 | +package remote |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "fmt" |
| 9 | + |
| 10 | + tfe "github.com/hashicorp/go-tfe" |
| 11 | +) |
| 12 | + |
| 13 | +type taskStages map[tfe.Stage]*tfe.TaskStage |
| 14 | + |
| 15 | +const ( |
| 16 | + taskStageBackoffMin = 4000.0 |
| 17 | + taskStageBackoffMax = 12000.0 |
| 18 | +) |
| 19 | + |
| 20 | +// waitTaskStage waits for a task stage to complete, only informs the caller if the stage has failed in some way. |
| 21 | +func (b *Remote) waitTaskStage(stopCtx, cancelCtx context.Context, r *tfe.Run, stageID string) error { |
| 22 | + ctx := &IntegrationContext{ |
| 23 | + StopContext: stopCtx, |
| 24 | + CancelContext: cancelCtx, |
| 25 | + } |
| 26 | + return ctx.Poll(taskStageBackoffMin, taskStageBackoffMax, func(i int) (bool, error) { |
| 27 | + options := tfe.TaskStageReadOptions{ |
| 28 | + Include: []tfe.TaskStageIncludeOpt{tfe.TaskStageTaskResults, tfe.PolicyEvaluationsTaskResults}, |
| 29 | + } |
| 30 | + stage, err := b.client.TaskStages.Read(ctx.StopContext, stageID, &options) |
| 31 | + if err != nil { |
| 32 | + return false, generalError("Failed to retrieve task stage", err) |
| 33 | + } |
| 34 | + |
| 35 | + switch stage.Status { |
| 36 | + case tfe.TaskStagePending: |
| 37 | + // Waiting for it to start |
| 38 | + return true, nil |
| 39 | + case tfe.TaskStageRunning: |
| 40 | + // not a terminal status so we continue to poll |
| 41 | + return true, nil |
| 42 | + case tfe.TaskStagePassed: |
| 43 | + return false, nil |
| 44 | + case tfe.TaskStageCanceled, tfe.TaskStageErrored, tfe.TaskStageFailed: |
| 45 | + return false, fmt.Errorf("Task Stage '%s': %s.", stage.ID, stage.Status) |
| 46 | + case tfe.TaskStageAwaitingOverride: |
| 47 | + return false, fmt.Errorf("Task Stage '%s' awaiting override.", stage.ID) |
| 48 | + case tfe.TaskStageUnreachable: |
| 49 | + return false, nil |
| 50 | + default: |
| 51 | + return false, fmt.Errorf("Task stage '%s' has invalid status: %s", stage.ID, stage.Status) |
| 52 | + } |
| 53 | + }) |
| 54 | +} |
0 commit comments