/
resource_ibm_pi_snapshot.go
327 lines (269 loc) · 8.9 KB
/
resource_ibm_pi_snapshot.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
package ibm
import (
"fmt"
"log"
"time"
"github.com/IBM-Cloud/power-go-client/power/client/p_cloud_p_vm_instances"
"github.com/IBM-Cloud/power-go-client/power/models"
"github.com/IBM-Cloud/bluemix-go/bmxerror"
st "github.com/IBM-Cloud/power-go-client/clients/instance"
"github.com/IBM-Cloud/power-go-client/helpers"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)
func resourceIBMPISnapshot() *schema.Resource {
return &schema.Resource{
Create: resourceIBMPISnapshotCreate,
Read: resourceIBMPISnapshotRead,
Update: resourceIBMPISnapshotUpdate,
Delete: resourceIBMPISnapshotDelete,
Exists: resourceIBMPISnapshotExists,
Importer: &schema.ResourceImporter{},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(60 * time.Minute),
Update: schema.DefaultTimeout(60 * time.Minute),
Delete: schema.DefaultTimeout(60 * time.Minute),
},
Schema: map[string]*schema.Schema{
//Snapshots are created at the pvm instance level
helpers.PISnapshotName: {
Type: schema.TypeString,
Required: true,
Description: "Unique name of the snapshot",
},
helpers.PIInstanceName: {
Type: schema.TypeString,
Required: true,
Description: "Instance name / id of the pvm",
},
helpers.PIInstanceVolumeIds: {
Type: schema.TypeSet,
Optional: true,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
DiffSuppressFunc: applyOnce,
Description: "List of PI volumes",
},
helpers.PICloudInstanceId: {
Type: schema.TypeString,
Required: true,
Description: " Cloud Instance ID - This is the service_instance_id.",
},
"description": {
Type: schema.TypeString,
Optional: true,
Description: "Snapshot description",
},
// Computed Attributes
helpers.PISnapshot: {
Type: schema.TypeString,
Computed: true,
Description: "Id of the snapshot",
},
"status": {
Type: schema.TypeString,
Computed: true,
},
"creation_date": {
Type: schema.TypeString,
Computed: true,
},
"last_updated_date": {
Type: schema.TypeString,
Computed: true,
},
"volume_snapshots": {
Type: schema.TypeMap,
Computed: true,
},
},
}
}
func resourceIBMPISnapshotCreate(d *schema.ResourceData, meta interface{}) error {
sess, err := meta.(ClientSession).IBMPISession()
if err != nil {
return err
}
powerinstanceid := d.Get(helpers.PICloudInstanceId).(string)
instanceid := d.Get(helpers.PIInstanceName).(string)
volids := expandStringList((d.Get(helpers.PIInstanceVolumeIds).(*schema.Set)).List())
name := d.Get(helpers.PISnapshotName).(string)
description := d.Get("description").(string)
if d.Get(description) == "" {
description = "Testing from Terraform"
}
client := st.NewIBMPIInstanceClient(sess, powerinstanceid)
snapshotBody := &models.SnapshotCreate{Name: &name, Description: description}
if len(volids) > 0 {
snapshotBody.VolumeIds = volids
}
snapshotResponse, err := client.CreatePvmSnapShot(&p_cloud_p_vm_instances.PcloudPvminstancesSnapshotsPostParams{
Body: snapshotBody,
}, instanceid, powerinstanceid, createTimeOut)
if err != nil {
log.Printf("[DEBUG] err %s", err)
return err
}
d.SetId(fmt.Sprintf("%s/%s", powerinstanceid, *snapshotResponse.SnapshotID))
if err != nil {
log.Printf("[DEBUG] err %s", err)
return err
}
//return nil
return resourceIBMPISnapshotRead(d, meta)
}
func resourceIBMPISnapshotRead(d *schema.ResourceData, meta interface{}) error {
log.Printf("Calling the Snapshot Read function post create")
sess, err := meta.(ClientSession).IBMPISession()
if err != nil {
return err
}
parts, err := idParts(d.Id())
if err != nil {
return err
}
powerinstanceid := parts[0]
snapshot := st.NewIBMPISnapshotClient(sess, powerinstanceid)
snapshotdata, err := snapshot.Get(parts[1], powerinstanceid, getTimeOut)
if err != nil {
return err
}
d.Set(helpers.PISnapshotName, snapshotdata.Name)
d.Set(helpers.PISnapshot, *snapshotdata.SnapshotID)
d.Set("status", snapshotdata.Status)
d.Set("creation_date", snapshotdata.CreationDate.String())
d.Set("volume_snapshots", snapshotdata.VolumeSnapshots)
d.Set("last_update_date", snapshotdata.LastUpdateDate.String())
return nil
}
func resourceIBMPISnapshotUpdate(d *schema.ResourceData, meta interface{}) error {
log.Printf("Calling the IBM Power Volume update call")
sess, _ := meta.(ClientSession).IBMPISession()
parts, err := idParts(d.Id())
if err != nil {
return err
}
powerinstanceid := parts[0]
client := st.NewIBMPIVolumeClient(sess, powerinstanceid)
//name := ""
//if d.HasChange(helpers.PIVolumeName) {
name := d.Get(helpers.PIVolumeName).(string)
//}
size := float64(d.Get(helpers.PIVolumeSize).(float64))
shareable := bool(d.Get(helpers.PIVolumeShareable).(bool))
volrequest, err := client.Update(parts[1], name, size, shareable, powerinstanceid, postTimeOut)
if err != nil {
return err
}
_, err = isWaitForIBMPIVolumeAvailable(client, *volrequest.VolumeID, powerinstanceid, d.Timeout(schema.TimeoutUpdate))
if err != nil {
return err
}
return resourceIBMPIVolumeRead(d, meta)
}
func resourceIBMPISnapshotDelete(d *schema.ResourceData, meta interface{}) error {
sess, _ := meta.(ClientSession).IBMPISession()
parts, err := idParts(d.Id())
if err != nil {
return err
}
powerinstanceid := parts[0]
client := st.NewIBMPISnapshotClient(sess, powerinstanceid)
snapshot, err := client.Get(parts[1], powerinstanceid, getTimeOut)
if err != nil {
return err
}
log.Printf("The snapshot to be deleted is in the following state .. %s", snapshot.Status)
//_, err = isWaitForIBMPIVolumeAvailable(client, parts[1], powerinstanceid, d.Timeout(schema.TimeoutDelete))
//if err != nil {
// return err
//}
snapshotdel_err := client.Delete(parts[1], powerinstanceid, deleteTimeOut)
if snapshotdel_err != nil {
return snapshotdel_err
}
d.SetId("")
return nil
}
func resourceIBMPISnapshotExists(d *schema.ResourceData, meta interface{}) (bool, error) {
sess, err := meta.(ClientSession).IBMPISession()
if err != nil {
return false, err
}
parts, err := idParts(d.Id())
if err != nil {
return false, err
}
powerinstanceid := parts[0]
client := st.NewIBMPISnapshotClient(sess, powerinstanceid)
snapshotdelete, err := client.Get(parts[1], powerinstanceid, getTimeOut)
if err != nil {
if apiErr, ok := err.(bmxerror.RequestFailure); ok {
if apiErr.StatusCode() == 404 {
return false, nil
}
}
return false, fmt.Errorf("Error communicating with the API: %s", err)
}
log.Printf("Calling the existing function.. %s", *(snapshotdelete.SnapshotID))
volumeid := *snapshotdelete.SnapshotID
return volumeid == parts[1], nil
}
/*
func isWaitForIBMPIVolumeDeleted(vol *st.IBMPIVolumeClient, id string, timeout time.Duration) (interface{}, error) {
log.Printf("Waiting for (%s) to be deleted.", id)
stateConf := &resource.StateChangeConf{
Pending: []string{"retry", isVolumeDeleting},
Target: []string{},
Refresh: isIBMPIVolumeDeleteRefreshFunc(vol, id),
Timeout: timeout,
Delay: 10 * time.Second,
MinTimeout: 10 * time.Second,
}
return stateConf.WaitForState()
}*/
/*func isIBMPIVolumeDeleteRefreshFunc(vol *st.IBMPIVolumeClient, id string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
vol, err := vol.Get(id)
if err == nil {
return vol, isVolumeDeleting, nil
}
iserror, ok := err.(iserrors.Power)
if ok {
log.Printf("[DEBUG] %s", iserror.Error())
if len(iserror.Payload.Errors) == 1 &&
iserror.Payload.Errors[0].Code == "volume_not_found" {
return nil, isVolumeDeleted, nil
}
}
return nil, isVolumeDeleting, err
}
}
*/
func isWaitForPIInstanceSnapshotAvailable(client *st.IBMPISnapshotClient, id string, timeout time.Duration, powerinstanceid string) (interface{}, error) {
log.Printf("Waiting for PIInstance Snapshot (%s) to be available and active ", id)
stateConf := &resource.StateChangeConf{
Pending: []string{"creating_snapshot", "BUILD"},
Target: []string{"available", "ACTIVE"},
Refresh: isPIInstanceSnapshotRefreshFunc(client, id, powerinstanceid),
Delay: 30 * time.Second,
MinTimeout: 2 * time.Minute,
Timeout: 60 * time.Minute,
}
return stateConf.WaitForState()
}
func isPIInstanceSnapshotRefreshFunc(client *st.IBMPISnapshotClient, id, powerinstanceid string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
snapshotInfo, err := client.Get(id, powerinstanceid, getTimeOut)
if err != nil {
return nil, "", err
}
//if pvm.Health.Status == helpers.PIInstanceHealthOk {
if snapshotInfo.Status == "available" && snapshotInfo.PercentComplete == 100 {
log.Printf("The snapshot is now available")
return snapshotInfo, "available", nil
}
return snapshotInfo, "in_progress", nil
}
}