forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_openstack_blockstorage_volume_v1.go
326 lines (289 loc) · 9.23 KB
/
resource_openstack_blockstorage_volume_v1.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
package openstack
import (
"bytes"
"fmt"
"log"
"time"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack/blockstorage/v1/volumes"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/volumeattach"
"github.com/hashicorp/terraform/helper/hashcode"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceBlockStorageVolumeV1() *schema.Resource {
return &schema.Resource{
Create: resourceBlockStorageVolumeV1Create,
Read: resourceBlockStorageVolumeV1Read,
Update: resourceBlockStorageVolumeV1Update,
Delete: resourceBlockStorageVolumeV1Delete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"region": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""),
},
"size": &schema.Schema{
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
"name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
},
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: false,
},
"availability_zone": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"metadata": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
ForceNew: false,
Computed: true,
},
"snapshot_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"source_vol_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"image_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"volume_type": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"attachment": &schema.Schema{
Type: schema.TypeSet,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"instance_id": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"device": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
},
Set: resourceVolumeAttachmentHash,
},
},
}
}
func resourceBlockStorageVolumeV1Create(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
blockStorageClient, err := config.blockStorageV1Client(d.Get("region").(string))
if err != nil {
return fmt.Errorf("Error creating OpenStack block storage client: %s", err)
}
createOpts := &volumes.CreateOpts{
Description: d.Get("description").(string),
Availability: d.Get("availability_zone").(string),
Name: d.Get("name").(string),
Size: d.Get("size").(int),
SnapshotID: d.Get("snapshot_id").(string),
SourceVolID: d.Get("source_vol_id").(string),
ImageID: d.Get("image_id").(string),
VolumeType: d.Get("volume_type").(string),
Metadata: resourceContainerMetadataV2(d),
}
log.Printf("[DEBUG] Create Options: %#v", createOpts)
v, err := volumes.Create(blockStorageClient, createOpts).Extract()
if err != nil {
return fmt.Errorf("Error creating OpenStack volume: %s", err)
}
log.Printf("[INFO] Volume ID: %s", v.ID)
// Store the ID now
d.SetId(v.ID)
// Wait for the volume to become available.
log.Printf(
"[DEBUG] Waiting for volume (%s) to become available",
v.ID)
stateConf := &resource.StateChangeConf{
Pending: []string{"downloading", "creating"},
Target: []string{"available"},
Refresh: VolumeV1StateRefreshFunc(blockStorageClient, v.ID),
Timeout: 10 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for volume (%s) to become ready: %s",
v.ID, err)
}
return resourceBlockStorageVolumeV1Read(d, meta)
}
func resourceBlockStorageVolumeV1Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
blockStorageClient, err := config.blockStorageV1Client(d.Get("region").(string))
if err != nil {
return fmt.Errorf("Error creating OpenStack block storage client: %s", err)
}
v, err := volumes.Get(blockStorageClient, d.Id()).Extract()
if err != nil {
return CheckDeleted(d, err, "volume")
}
log.Printf("[DEBUG] Retrieved volume %s: %+v", d.Id(), v)
d.Set("size", v.Size)
d.Set("description", v.Description)
d.Set("availability_zone", v.AvailabilityZone)
d.Set("name", v.Name)
d.Set("snapshot_id", v.SnapshotID)
d.Set("source_vol_id", v.SourceVolID)
d.Set("volume_type", v.VolumeType)
d.Set("metadata", v.Metadata)
attachments := make([]map[string]interface{}, len(v.Attachments))
for i, attachment := range v.Attachments {
attachments[i] = make(map[string]interface{})
attachments[i]["id"] = attachment["id"]
attachments[i]["instance_id"] = attachment["server_id"]
attachments[i]["device"] = attachment["device"]
log.Printf("[DEBUG] attachment: %v", attachment)
}
d.Set("attachment", attachments)
return nil
}
func resourceBlockStorageVolumeV1Update(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
blockStorageClient, err := config.blockStorageV1Client(d.Get("region").(string))
if err != nil {
return fmt.Errorf("Error creating OpenStack block storage client: %s", err)
}
updateOpts := volumes.UpdateOpts{
Name: d.Get("name").(string),
Description: d.Get("description").(string),
}
if d.HasChange("metadata") {
updateOpts.Metadata = resourceVolumeMetadataV1(d)
}
_, err = volumes.Update(blockStorageClient, d.Id(), updateOpts).Extract()
if err != nil {
return fmt.Errorf("Error updating OpenStack volume: %s", err)
}
return resourceBlockStorageVolumeV1Read(d, meta)
}
func resourceBlockStorageVolumeV1Delete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
blockStorageClient, err := config.blockStorageV1Client(d.Get("region").(string))
if err != nil {
return fmt.Errorf("Error creating OpenStack block storage client: %s", err)
}
v, err := volumes.Get(blockStorageClient, d.Id()).Extract()
if err != nil {
return CheckDeleted(d, err, "volume")
}
// make sure this volume is detached from all instances before deleting
if len(v.Attachments) > 0 {
log.Printf("[DEBUG] detaching volumes")
if computeClient, err := config.computeV2Client(d.Get("region").(string)); err != nil {
return err
} else {
for _, volumeAttachment := range v.Attachments {
log.Printf("[DEBUG] Attachment: %v", volumeAttachment)
if err := volumeattach.Delete(computeClient, volumeAttachment["server_id"].(string), volumeAttachment["id"].(string)).ExtractErr(); err != nil {
return err
}
}
stateConf := &resource.StateChangeConf{
Pending: []string{"in-use", "attaching", "detaching"},
Target: []string{"available"},
Refresh: VolumeV1StateRefreshFunc(blockStorageClient, d.Id()),
Timeout: 10 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for volume (%s) to become available: %s",
d.Id(), err)
}
}
}
// It's possible that this volume was used as a boot device and is currently
// in a "deleting" state from when the instance was terminated.
// If this is true, just move on. It'll eventually delete.
if v.Status != "deleting" {
if err := volumes.Delete(blockStorageClient, d.Id()).ExtractErr(); err != nil {
return CheckDeleted(d, err, "volume")
}
}
// Wait for the volume to delete before moving on.
log.Printf("[DEBUG] Waiting for volume (%s) to delete", d.Id())
stateConf := &resource.StateChangeConf{
Pending: []string{"deleting", "downloading", "available"},
Target: []string{"deleted"},
Refresh: VolumeV1StateRefreshFunc(blockStorageClient, d.Id()),
Timeout: 10 * time.Minute,
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for volume (%s) to delete: %s",
d.Id(), err)
}
d.SetId("")
return nil
}
func resourceVolumeMetadataV1(d *schema.ResourceData) map[string]string {
m := make(map[string]string)
for key, val := range d.Get("metadata").(map[string]interface{}) {
m[key] = val.(string)
}
return m
}
// VolumeV1StateRefreshFunc returns a resource.StateRefreshFunc that is used to watch
// an OpenStack volume.
func VolumeV1StateRefreshFunc(client *gophercloud.ServiceClient, volumeID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
v, err := volumes.Get(client, volumeID).Extract()
if err != nil {
if _, ok := err.(gophercloud.ErrDefault404); ok {
return v, "deleted", nil
}
return nil, "", err
}
return v, v.Status, nil
}
}
func resourceVolumeAttachmentHash(v interface{}) int {
var buf bytes.Buffer
m := v.(map[string]interface{})
if m["instance_id"] != nil {
buf.WriteString(fmt.Sprintf("%s-", m["instance_id"].(string)))
}
return hashcode.String(buf.String())
}