-
Notifications
You must be signed in to change notification settings - Fork 658
/
resource_ibm_is_bare_metal_server_action.go
352 lines (315 loc) · 11.3 KB
/
resource_ibm_is_bare_metal_server_action.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright IBM Corp. 2017, 2021 All Rights Reserved.
// Licensed under the Mozilla Public License v2.0
package vpc
import (
"context"
"fmt"
"log"
"time"
"github.com/IBM-Cloud/terraform-provider-ibm/ibm/validate"
"github.com/IBM/vpc-go-sdk/vpcv1"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
const (
isBareMetalServerActionAvailable = "available"
isBareMetalServerActionPending = "pending"
isBareMetalServerActionFailed = "failed"
isBareMetalServerStopType = "stop_type"
)
func ResourceIBMIsBareMetalServerAction() *schema.Resource {
return &schema.Resource{
CreateContext: resourceIBMISBareMetalServerActionCreate,
ReadContext: resourceIBMISBareMetalServerActionRead,
UpdateContext: resourceIBMISBareMetalServerActionUpdate,
DeleteContext: resourceIBMISBareMetalServerActionDelete,
Importer: &schema.ResourceImporter{},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
isBareMetalServerID: {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Bare metal server identifier",
},
isBareMetalServerStopType: {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Default: "hard",
Description: "The type of stop operation",
},
isBareMetalServerAction: {
Type: schema.TypeString,
Required: true,
ValidateFunc: validate.InvokeValidator("ibm_is_bare_metal_server", isBareMetalServerAction),
Description: "This restart/start/stops a bare metal server.",
},
isBareMetalServerStatus: {
Type: schema.TypeString,
Computed: true,
Description: "Bare metal server status",
},
isBareMetalServerStatusReasons: {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
isBareMetalServerStatusReasonsCode: {
Type: schema.TypeString,
Computed: true,
Description: "A snake case string succinctly identifying the status reason",
},
isBareMetalServerStatusReasonsMessage: {
Type: schema.TypeString,
Computed: true,
Description: "An explanation of the status reason",
},
isBareMetalServerStatusReasonsMoreInfo: {
Type: schema.TypeString,
Computed: true,
Description: "Link to documentation about this status reason",
},
},
},
},
},
}
}
func ResourceIBMISBareMetalServerActionValidator() *validate.ResourceValidator {
bareMetalServerStopTypes := "soft, hard"
bareMetalServerActions := "start, restart, stop"
validateSchema := make([]validate.ValidateSchema, 0)
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: isBareMetalServerAction,
ValidateFunctionIdentifier: validate.ValidateAllowedStringValue,
Type: validate.TypeString,
Required: true,
AllowedValues: bareMetalServerActions})
validateSchema = append(validateSchema,
validate.ValidateSchema{
Identifier: isBareMetalServerStopType,
ValidateFunctionIdentifier: validate.ValidateAllowedStringValue,
Type: validate.TypeString,
Optional: true,
AllowedValues: bareMetalServerStopTypes})
ibmISBareMetalServerActionResourceValidator := validate.ResourceValidator{ResourceName: "ibm_is_bare_metal_server_action", Schema: validateSchema}
return &ibmISBareMetalServerActionResourceValidator
}
func resourceIBMISBareMetalServerActionCreate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
sess, err := vpcClient(meta)
if err != nil {
return diag.FromErr(err)
}
bareMetalServerId := ""
if bmsId, ok := d.GetOk(isBareMetalServerID); ok {
bareMetalServerId = bmsId.(string)
}
bareMetalServerAction := ""
if bmsAction, ok := d.GetOk(isBareMetalServerAction); ok {
bareMetalServerAction = bmsAction.(string)
}
if bareMetalServerAction == "stop" {
bareMetalServerStopType := "hard"
if stopType, ok := d.GetOk(isBareMetalServerStopType); ok {
bareMetalServerStopType = stopType.(string)
}
createBareMetalServerStopOptions := &vpcv1.StopBareMetalServerOptions{
ID: &bareMetalServerId,
Type: &bareMetalServerStopType,
}
_, err = sess.StopBareMetalServerWithContext(context, createBareMetalServerStopOptions)
if err != nil {
return diag.FromErr(err)
}
_, waitErr := isWaitForBareMetalServerActionStop(sess, d.Timeout(schema.TimeoutCreate), bareMetalServerId, d)
if waitErr != nil {
return diag.FromErr(waitErr)
}
} else if bareMetalServerAction == "start" {
createBareMetalServerStartOptions := &vpcv1.StartBareMetalServerOptions{
ID: &bareMetalServerId,
}
_, err := sess.StartBareMetalServerWithContext(context, createBareMetalServerStartOptions)
if err != nil {
return diag.FromErr(err)
}
_, waitErr := isWaitForBareMetalServerActionAvailable(sess, bareMetalServerId, d.Timeout(schema.TimeoutDelete), d)
if waitErr != nil {
return diag.FromErr(waitErr)
}
} else if bareMetalServerAction == "restart" {
createBareMetalServerRestartOptions := &vpcv1.RestartBareMetalServerOptions{
ID: &bareMetalServerId,
}
_, err := sess.RestartBareMetalServerWithContext(context, createBareMetalServerRestartOptions)
if err != nil {
return diag.FromErr(err)
}
_, waitErr := isWaitForBareMetalServerActionAvailable(sess, bareMetalServerId, d.Timeout(schema.TimeoutDelete), d)
if waitErr != nil {
return diag.FromErr(waitErr)
}
}
d.SetId(bareMetalServerId)
err = bareMetalServerActionGet(context, sess, bareMetalServerId, d)
if err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceIBMISBareMetalServerActionRead(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
sess, err := vpcClient(meta)
if err != nil {
return diag.FromErr(err)
}
id := d.Id()
err = bareMetalServerActionGet(context, sess, id, d)
if err != nil {
return diag.FromErr(err)
}
return nil
}
func bareMetalServerActionGet(context context.Context, sess *vpcv1.VpcV1, id string, d *schema.ResourceData) error {
options := &vpcv1.GetBareMetalServerOptions{
ID: &id,
}
bms, response, err := sess.GetBareMetalServerWithContext(context, options)
if err != nil {
if response != nil && response.StatusCode == 404 {
d.SetId("")
return nil
}
return fmt.Errorf("[ERROR] Error getting Bare Metal Server (%s): %s\n%s", id, err, response)
}
d.SetId(*bms.ID)
d.Set(isBareMetalServerStatus, *bms.Status)
statusReasonsList := make([]map[string]interface{}, 0)
if bms.StatusReasons != nil {
for _, sr := range bms.StatusReasons {
currentSR := map[string]interface{}{}
if sr.Code != nil && sr.Message != nil {
currentSR[isBareMetalServerStatusReasonsCode] = *sr.Code
currentSR[isBareMetalServerStatusReasonsMessage] = *sr.Message
if sr.MoreInfo != nil {
currentSR[isBareMetalServerStatusReasonsMoreInfo] = *sr.MoreInfo
}
statusReasonsList = append(statusReasonsList, currentSR)
}
}
}
d.Set(isBareMetalServerStatusReasons, statusReasonsList)
return nil
}
func resourceIBMISBareMetalServerActionUpdate(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
if d.HasChange(isBareMetalServerAction) {
sess, err := vpcClient(meta)
if err != nil {
return diag.FromErr(err)
}
bareMetalServerId := d.Id()
bareMetalServerAction := ""
if bmsAction, ok := d.GetOk(isBareMetalServerAction); ok {
bareMetalServerAction = bmsAction.(string)
}
if bareMetalServerAction == "stop" {
bareMetalServerStopType := "soft"
if stopType, ok := d.GetOk(isBareMetalServerStopType); ok {
bareMetalServerStopType = stopType.(string)
}
createBareMetalServerStopOptions := &vpcv1.StopBareMetalServerOptions{
ID: &bareMetalServerId,
Type: &bareMetalServerStopType,
}
_, err := sess.StopBareMetalServerWithContext(context, createBareMetalServerStopOptions)
if err != nil {
return diag.FromErr(err)
}
_, waitErr := isWaitForBareMetalServerActionStop(sess, d.Timeout(schema.TimeoutUpdate), bareMetalServerId, d)
if waitErr != nil {
return diag.FromErr(waitErr)
}
} else if bareMetalServerAction == "start" {
createBareMetalServerStartOptions := &vpcv1.StartBareMetalServerOptions{
ID: &bareMetalServerId,
}
_, err := sess.StartBareMetalServerWithContext(context, createBareMetalServerStartOptions)
if err != nil {
return diag.FromErr(err)
}
_, waitErr := isWaitForBareMetalServerActionAvailable(sess, bareMetalServerId, d.Timeout(schema.TimeoutDelete), d)
if waitErr != nil {
return diag.FromErr(waitErr)
}
} else if bareMetalServerAction == "restart" {
createBareMetalServerRestartOptions := &vpcv1.RestartBareMetalServerOptions{
ID: &bareMetalServerId,
}
_, err := sess.RestartBareMetalServerWithContext(context, createBareMetalServerRestartOptions)
if err != nil {
return diag.FromErr(err)
}
_, waitErr := isWaitForBareMetalServerActionAvailable(sess, bareMetalServerId, d.Timeout(schema.TimeoutDelete), d)
if waitErr != nil {
return diag.FromErr(waitErr)
}
}
err = bareMetalServerActionGet(context, sess, bareMetalServerId, d)
if err != nil {
return diag.FromErr(err)
}
}
return nil
}
func resourceIBMISBareMetalServerActionDelete(context context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
d.SetId("")
return nil
}
func isWaitForBareMetalServerActionAvailable(client *vpcv1.VpcV1, id string, timeout time.Duration, d *schema.ResourceData) (interface{}, error) {
log.Printf("Waiting for Bare Metal Server (%s) to be running.", id)
communicator := make(chan interface{})
stateConf := &resource.StateChangeConf{
Pending: []string{isBareMetalServerStatusPending, isBareMetalServerActionStatusStarting},
Target: []string{isBareMetalServerStatusRunning, isBareMetalServerStatusFailed},
Refresh: isBareMetalServerActionRefreshFunc(client, id, d, communicator),
Timeout: timeout,
Delay: 10 * time.Second,
MinTimeout: 10 * time.Second,
}
return stateConf.WaitForState()
}
func isBareMetalServerActionRefreshFunc(client *vpcv1.VpcV1, id string, d *schema.ResourceData, communicator chan interface{}) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
bmsgetoptions := &vpcv1.GetBareMetalServerOptions{
ID: &id,
}
bms, response, err := client.GetBareMetalServer(bmsgetoptions)
if err != nil {
return nil, "", fmt.Errorf("[ERROR] Error getting Bare Metal Server: %s\n%s", err, response)
}
d.Set(isBareMetalServerStatus, *bms.Status)
select {
case data := <-communicator:
return nil, "", data.(error)
default:
fmt.Println("no message sent")
}
if *bms.Status == "running" {
// let know the isRestartStartAction() to stop
close(communicator)
return bms, *bms.Status, nil
}
if *bms.Status == "failed" {
// let know the isRestartStartAction() to stop
close(communicator)
return bms, *bms.Status, fmt.Errorf("[ERROR] Error Bare Metal Server is in failed state")
}
return bms, isBareMetalServerStatusPending, nil
}
}