-
Notifications
You must be signed in to change notification settings - Fork 9.5k
/
resource_openstack_blockstorage_volume_attach_v2.go
255 lines (210 loc) · 6.69 KB
/
resource_openstack_blockstorage_volume_attach_v2.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
package openstack
import (
"fmt"
"log"
"strings"
"time"
"github.com/gophercloud/gophercloud/openstack/blockstorage/extensions/volumeactions"
"github.com/gophercloud/gophercloud/openstack/blockstorage/v2/volumes"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
func resourceBlockStorageVolumeAttachV2() *schema.Resource {
return &schema.Resource{
Create: resourceBlockStorageVolumeAttachV2Create,
Read: resourceBlockStorageVolumeAttachV2Read,
Delete: resourceBlockStorageVolumeAttachV2Delete,
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", ""),
},
"volume_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"instance_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"host_name"},
},
"host_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ConflictsWith: []string{"instance_id"},
},
"device": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"attach_mode": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: func(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if value != "ro" && value != "rw" {
errors = append(errors, fmt.Errorf(
"Only 'ro' and 'rw' are supported values for 'attach_mode'"))
}
return
},
},
},
}
}
func resourceBlockStorageVolumeAttachV2Create(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
client, err := config.blockStorageV2Client(GetRegion(d))
if err != nil {
return fmt.Errorf("Error creating OpenStack block storage client: %s", err)
}
// Check if either instance_id or host_name was set.
instanceId := d.Get("instance_id").(string)
hostName := d.Get("host_name").(string)
if instanceId == "" && hostName == "" {
return fmt.Errorf("One of 'instance_id' or 'host_name' must be set.")
}
volumeId := d.Get("volume_id").(string)
attachMode, err := blockStorageVolumeAttachV2AttachMode(d.Get("attach_mode").(string))
if err != nil {
return nil
}
attachOpts := &volumeactions.AttachOpts{
InstanceUUID: d.Get("instance_id").(string),
HostName: d.Get("host_name").(string),
MountPoint: d.Get("device").(string),
Mode: attachMode,
}
log.Printf("[DEBUG] Attachment Options: %#v", attachOpts)
if err := volumeactions.Attach(client, volumeId, attachOpts).ExtractErr(); err != nil {
return err
}
// Wait for the volume to become available.
log.Printf("[DEBUG] Waiting for volume (%s) to become available", volumeId)
stateConf := &resource.StateChangeConf{
Pending: []string{"available", "attaching"},
Target: []string{"in-use"},
Refresh: VolumeV2StateRefreshFunc(client, volumeId),
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", volumeId, err)
}
volume, err := volumes.Get(client, volumeId).Extract()
if err != nil {
return err
}
var attachmentId string
for _, attachment := range volume.Attachments {
if instanceId != "" && instanceId == attachment.ServerID {
attachmentId = attachment.AttachmentID
}
if hostName != "" && hostName == attachment.HostName {
attachmentId = attachment.AttachmentID
}
}
if attachmentId == "" {
return fmt.Errorf("Unable to determine attachment ID.")
}
// The ID must be a combination of the volume and attachment ID
// in order to import attachments.
id := fmt.Sprintf("%s/%s", volumeId, attachmentId)
d.SetId(id)
return resourceBlockStorageVolumeAttachV2Read(d, meta)
}
func resourceBlockStorageVolumeAttachV2Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
client, err := config.blockStorageV2Client(GetRegion(d))
if err != nil {
return fmt.Errorf("Error creating OpenStack block storage client: %s", err)
}
volumeId, attachmentId, err := blockStorageVolumeAttachV2ParseId(d.Id())
if err != nil {
return err
}
volume, err := volumes.Get(client, volumeId).Extract()
if err != nil {
return err
}
log.Printf("[DEBUG] Retrieved volume %s: %#v", d.Id(), volume)
var attachment volumes.Attachment
for _, v := range volume.Attachments {
if attachmentId == v.AttachmentID {
attachment = v
}
}
log.Printf("[DEBUG] Retrieved volume attachment: %#v", attachment)
d.Set("volume_id", volumeId)
d.Set("attachment_id", attachmentId)
d.Set("device", attachment.Device)
d.Set("instance_id", attachment.ServerID)
d.Set("host_name", attachment.HostName)
d.Set("region", GetRegion(d))
return nil
}
func resourceBlockStorageVolumeAttachV2Delete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
client, err := config.blockStorageV2Client(GetRegion(d))
if err != nil {
return fmt.Errorf("Error creating OpenStack block storage client: %s", err)
}
volumeId, attachmentId, err := blockStorageVolumeAttachV2ParseId(d.Id())
if err != nil {
return err
}
detachOpts := volumeactions.DetachOpts{
AttachmentID: attachmentId,
}
log.Printf("[DEBUG] Detachment Options: %#v", detachOpts)
if err := volumeactions.Detach(client, volumeId, detachOpts).ExtractErr(); err != nil {
return err
}
stateConf := &resource.StateChangeConf{
Pending: []string{"in-use", "attaching", "detaching"},
Target: []string{"available"},
Refresh: VolumeV2StateRefreshFunc(client, volumeId),
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", volumeId, err)
}
return nil
}
func blockStorageVolumeAttachV2AttachMode(v string) (volumeactions.AttachMode, error) {
var attachMode volumeactions.AttachMode
var attachError error
switch v {
case "":
attachMode = ""
case "ro":
attachMode = volumeactions.ReadOnly
case "rw":
attachMode = volumeactions.ReadWrite
default:
attachError = fmt.Errorf("Invalid attach_mode specified")
}
return attachMode, attachError
}
func blockStorageVolumeAttachV2ParseId(id string) (string, string, error) {
parts := strings.Split(id, "/")
if len(parts) < 2 {
return "", "", fmt.Errorf("Unable to determine attachment ID")
}
return parts[0], parts[1], nil
}