ProvisionerJob renders a provisioner job with interactive cancellation.
(ctx context.Context, wr io.Writer, opts ProvisionerJobOptions)
| 61 | |
| 62 | // ProvisionerJob renders a provisioner job with interactive cancellation. |
| 63 | func ProvisionerJob(ctx context.Context, wr io.Writer, opts ProvisionerJobOptions) error { |
| 64 | if opts.FetchInterval == 0 { |
| 65 | opts.FetchInterval = time.Second |
| 66 | } |
| 67 | ctx, cancelFunc := context.WithCancel(ctx) |
| 68 | defer cancelFunc() |
| 69 | |
| 70 | var ( |
| 71 | currentStage = ProvisioningStateQueued |
| 72 | currentStageStartedAt = time.Now().UTC() |
| 73 | currentQueuePos = -1 |
| 74 | |
| 75 | errChan = make(chan error, 1) |
| 76 | job codersdk.ProvisionerJob |
| 77 | jobMutex sync.Mutex |
| 78 | ) |
| 79 | |
| 80 | sw := &stageWriter{w: wr, verbose: opts.Verbose, silentLogs: opts.Silent} |
| 81 | |
| 82 | printStage := func() { |
| 83 | out := currentStage |
| 84 | |
| 85 | if currentStage == ProvisioningStateQueued && currentQueuePos > 0 { |
| 86 | var queuePos string |
| 87 | if currentQueuePos == 1 { |
| 88 | queuePos = "next" |
| 89 | } else { |
| 90 | queuePos = fmt.Sprintf("position: %d", currentQueuePos) |
| 91 | } |
| 92 | |
| 93 | out = pretty.Sprintf(DefaultStyles.Warn, "%s (%s)", currentStage, queuePos) |
| 94 | } |
| 95 | |
| 96 | sw.Start(out) |
| 97 | } |
| 98 | |
| 99 | updateStage := func(stage string, startedAt time.Time) { |
| 100 | if currentStage != "" { |
| 101 | duration := startedAt.Sub(currentStageStartedAt) |
| 102 | if job.CompletedAt != nil && job.Status != codersdk.ProvisionerJobSucceeded { |
| 103 | sw.Fail(currentStage, duration) |
| 104 | } else { |
| 105 | sw.Complete(currentStage, duration) |
| 106 | } |
| 107 | } |
| 108 | if stage == "" { |
| 109 | return |
| 110 | } |
| 111 | currentStage = stage |
| 112 | currentStageStartedAt = startedAt |
| 113 | printStage() |
| 114 | } |
| 115 | |
| 116 | updateJob := func() { |
| 117 | var err error |
| 118 | jobMutex.Lock() |
| 119 | defer jobMutex.Unlock() |
| 120 | job, err = opts.Fetch() |