-
Notifications
You must be signed in to change notification settings - Fork 26
/
resource_run.go
291 lines (262 loc) · 8.97 KB
/
resource_run.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package spacelift
import (
"context"
"fmt"
"slices"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/pkg/errors"
"github.com/shurcooL/graphql"
"github.com/spacelift-io/terraform-provider-spacelift/spacelift/internal"
"github.com/spacelift-io/terraform-provider-spacelift/spacelift/internal/validations"
)
func resourceRun() *schema.Resource {
return &schema.Resource{
Description: "" +
"`spacelift_run` allows programmatically triggering runs in response " +
"to arbitrary changes in the keepers section.",
CreateContext: resourceRunCreate,
ReadContext: schema.NoopContext,
Delete: schema.RemoveFromState,
UpdateContext: schema.NoopContext,
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"stack_id": {
Type: schema.TypeString,
Description: "ID of the stack on which the run is to be triggered.",
Required: true,
ForceNew: true,
ValidateDiagFunc: validations.DisallowEmptyString,
},
"commit_sha": {
Description: "The commit SHA for which to trigger a run.",
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"keepers": {
Description: "" +
"Arbitrary map of values that, when changed, will trigger " +
"recreation of the resource.",
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},
"proposed": {
Type: schema.TypeBool,
Description: "Whether the run is a proposed run. Defaults to `false`.",
Optional: true,
ForceNew: true,
Default: false,
},
"id": {
Description: "The ID of the triggered run.",
Type: schema.TypeString,
Computed: true,
},
"wait": {
Type: schema.TypeList,
Optional: true,
Description: "Wait for the run to finish",
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"disabled": {
Type: schema.TypeBool,
Description: "Whether waiting for a job is disabled or not. Default: `false`",
Optional: true,
Default: false,
},
"continue_on_state": {
Type: schema.TypeSet,
Elem: &schema.Schema{
Type: schema.TypeString,
},
Description: "Continue on the specified states of a finished run. If not specified, the default is `[ 'finished' ]`. You can use following states: `applying`, `canceled`, `confirmed`, `destroying`, `discarded`, `failed`, `finished`, `initializing`, `pending_review`, `performing`, `planning`, `preparing_apply`, `preparing_replan`, `preparing`, `queued`, `ready`, `replan_requested`, `skipped`, `stopped`, `unconfirmed`.",
Optional: true,
},
"continue_on_timeout": {
Type: schema.TypeBool,
Description: "Continue if run timed out, i.e. did not reach any defined end state in time. Default: `false`",
Optional: true,
Default: false,
},
},
},
},
},
}
}
type waitConfiguration struct {
disabled bool
continueOnState []string
continueOnTimeout bool
}
func expandWaitConfiguration(input []interface{}) *waitConfiguration {
if len(input) == 0 {
return nil
}
v := input[0].(map[string]interface{})
cfg := &waitConfiguration{
disabled: v["disabled"].(bool),
continueOnState: []string{},
continueOnTimeout: v["continue_on_timeout"].(bool),
}
if v, ok := v["continue_on_state"]; ok {
for _, item := range v.(*schema.Set).List() {
str, ok := item.(string)
if !ok {
panic(fmt.Sprintf("continue_on_state contains a non-string element %+v", str))
}
cfg.continueOnState = append(cfg.continueOnState, str)
}
}
if len(cfg.continueOnState) == 0 {
cfg.continueOnState = append(cfg.continueOnState, "finished")
}
return cfg
}
func (wait *waitConfiguration) Wait(ctx context.Context, d *schema.ResourceData, client *internal.Client, stackID, mutationID string) diag.Diagnostics {
if wait.disabled {
return nil
}
stateConf := &retry.StateChangeConf{
ContinuousTargetOccurence: 1,
Delay: 10 * time.Second,
MinTimeout: 10 * time.Second,
Pending: []string{
"running",
},
Target: []string{
"finished",
"unconfirmed", // Let's treat unconfirmed as the target state.
// It's not finished, but we don't want to wait for it because it requires confirmation from someone.
},
Refresh: checkStackStatusFunc(ctx, client, stackID, mutationID),
Timeout: d.Timeout(schema.TimeoutCreate),
}
finalState, err := stateConf.WaitForStateContext(ctx)
if err != nil {
if timeoutErr, ok := internal.AsError[*retry.TimeoutError](err); ok {
tflog.Debug(ctx, "received retry.TimeoutError from WaitForStateContext", map[string]any{
"stackID": stackID,
"runID": mutationID,
"lastState": timeoutErr.LastState,
"expectedState": timeoutErr.ExpectedState,
})
finalState = "__timeout__"
} else if err == context.DeadlineExceeded {
tflog.Debug(ctx, "received context.DeadlineExceeded from WaitForStateContext", map[string]any{
"stackID": stackID,
"runID": mutationID,
})
finalState = "__timeout__"
} else {
return diag.Errorf("failed waiting for run %s on stack %s to finish. error(%T): %+v ", mutationID, stackID, err, err)
}
}
switch finalState.(string) {
case "__timeout__":
if !wait.continueOnTimeout {
return diag.Errorf("run %s on stack %s has timed out", mutationID, stackID)
}
tflog.Info(ctx, "run timed out but continue_on_timeout=true",
map[string]any{
"stackID": stackID,
"runID": mutationID,
})
default:
if !slices.Contains[[]string](wait.continueOnState, finalState.(string)) {
return diag.Errorf("run %s on stack %s has ended with status %s. expected %v", mutationID, stackID, finalState, wait.continueOnState)
}
tflog.Debug(ctx, "run finished", map[string]any{
"stackID": stackID,
"runID": mutationID,
"finalState": finalState,
})
}
return nil
}
func resourceRunCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
var mutation struct {
ID string `graphql:"runResourceCreate(stack: $stack, commitSha: $sha, proposed: $proposed)"`
}
stackID := d.Get("stack_id").(string)
variables := map[string]interface{}{
"stack": toID(stackID),
"sha": (*graphql.String)(nil),
"proposed": (*graphql.Boolean)(nil),
}
if sha, ok := d.GetOk("commit_sha"); ok {
variables["sha"] = graphql.NewString(graphql.String(sha.(string)))
}
if proposed, ok := d.GetOk("proposed"); ok {
variables["proposed"] = graphql.NewBoolean(graphql.Boolean(proposed.(bool)))
}
client := meta.(*internal.Client)
if err := client.Mutate(ctx, "ResourceRunCreate", &mutation, variables); err != nil {
return diag.Errorf("could not trigger run for stack %s: %v", stackID, internal.FromSpaceliftError(err))
}
if waitRaw, ok := d.GetOk("wait"); ok {
wait := expandWaitConfiguration(waitRaw.([]interface{}))
if diag := wait.Wait(ctx, d, client, stackID, mutation.ID); len(diag) > 0 {
return diag
}
}
d.SetId(mutation.ID)
return nil
}
func checkStackStatusFunc(ctx context.Context, client *internal.Client, stackID string, runID string) retry.StateRefreshFunc {
return func() (result any, state string, err error) {
// instead of a resource handle we return the current state as result
// Makes it easier to detect which end state has been reached.
// Otherwise we would need another GraphQL query
result, finished, err := getStackRunStateByID(ctx, client, stackID, runID)
if err != nil {
return
}
state = "running"
if finished {
state = "finished"
}
// Let's treat unconfirmed as the target state.
// It's not finished, but we don't want to wait for it because it requires confirmation from someone.
if result == "unconfirmed" {
state = "unconfirmed"
}
return
}
}
func getStackRunStateByID(ctx context.Context, client *internal.Client, stackID string, runID string) (string, bool, error) {
var query struct {
Stack struct {
RunResourceState struct {
ID graphql.String
State graphql.String
Finished graphql.Boolean
} `graphql:"runResourceState(id: $runId)"`
} `graphql:"stack(id: $stackId)"`
}
variables := map[string]interface{}{
"stackId": graphql.ID(stackID),
"runId": graphql.ID(runID),
}
if err := client.Query(ctx, "StackRunRead", &query, variables); err != nil {
return "", false, errors.Wrap(err, fmt.Sprintf("could not query for run %s of stack %s", runID, stackID))
}
rrs := query.Stack.RunResourceState
currentState := strings.ToLower(string(rrs.State))
tflog.Debug(ctx, "current state of run", map[string]interface{}{
"stackID": stackID,
"runID": runID,
"currentState": currentState,
"finished": rrs.Finished,
})
return currentState, bool(rrs.Finished), nil
}