-
Notifications
You must be signed in to change notification settings - Fork 15
/
resource_ecl_storage_virtualstorage_v1.go
455 lines (397 loc) · 13.5 KB
/
resource_ecl_storage_virtualstorage_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
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package ecl
import (
"fmt"
"log"
"regexp"
"time"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/helper/validation"
"github.com/nttcom/eclcloud"
"github.com/nttcom/eclcloud/ecl/storage/v1/virtualstorages"
"github.com/nttcom/eclcloud/ecl/storage/v1/volumetypes"
)
func resourceStorageVirtualStorageV1() *schema.Resource {
return &schema.Resource{
Create: resourceStorageVirtualStorageV1Create,
Read: resourceStorageVirtualStorageV1Read,
Update: resourceStorageVirtualStorageV1Update,
Delete: resourceStorageVirtualStorageV1Delete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Update: schema.DefaultTimeout(30 * time.Minute),
Delete: schema.DefaultTimeout(30 * time.Minute),
},
Schema: map[string]*schema.Schema{
"name": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"description": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"network_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"subnet_id": &schema.Schema{
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"volume_type_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
ConflictsWith: []string{"volume_type_name"},
},
"volume_type_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{
"piops_iscsi_na", "pre_nfs_na", "standard_nfs_na",
}, false),
ConflictsWith: []string{"volume_type_id"},
},
"ip_addr_pool": &schema.Schema{
Type: schema.TypeMap,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"start": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"end": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
},
},
},
"host_routes": &schema.Schema{
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"destination": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"nexthop": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
},
},
},
"error_message": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
}
}
func resourceVirtualStorageIPAddrPool(d *schema.ResourceData) virtualstorages.IPAddressPool {
log.Printf("resourceVirtualStorageIPAddrPool")
log.Printf("[DEBUG] d: %+v", d)
log.Printf("[DEBUG] ip_addr_pool: %+v", d.Get("ip_addr_pool"))
result := virtualstorages.IPAddressPool{}
poolInfo := d.Get("ip_addr_pool").(map[string]interface{})
result.Start = poolInfo["start"].(string)
result.End = poolInfo["end"].(string)
return result
}
func resourceVirtualStorageHostRoutes(d *schema.ResourceData) []virtualstorages.HostRoute {
log.Printf("resourceVirtualStorageHostRoutes")
log.Printf("[DEBUG] d: %+v", d)
log.Printf("[DEBUG] host_routes: %+v", d.Get("host_routes"))
routeList := d.Get("host_routes").([]interface{})
result := make([]virtualstorages.HostRoute, 0)
for _, hostRoute := range routeList {
hr := virtualstorages.HostRoute{}
dest := hostRoute.(map[string]interface{})["destination"]
nexthop := hostRoute.(map[string]interface{})["nexthop"]
hr.Destination = dest.(string)
hr.Nexthop = nexthop.(string)
result = append(result, hr)
}
return result
}
func avoidTenantBusyForVirtualStorageCreate(
client *eclcloud.ServiceClient,
createOpts *virtualstorages.CreateOpts) (*virtualstorages.VirtualStorage, error) {
for i := 0; i < StorageRetryMaxCount; i++ {
v, err := virtualstorages.Create(client, createOpts).Extract()
if err != nil {
_, ok := err.(eclcloud.ErrDefault409)
if ok {
log.Printf("[DEBUG] Sleeping for retry creation")
time.Sleep(time.Minute * time.Duration(StorageRetryWaitMinute))
continue
} else {
return nil, fmt.Errorf("Failed in virtual storage creation with options %v . Error: %s",
createOpts,
err)
}
}
log.Printf("[DEBUG] End of for block")
return v, nil
}
log.Printf("[DEBUG] Reached maximun retry count of creation")
return nil, nil
}
func avoidTenantBusyForVirtualStorageUpdate(
client *eclcloud.ServiceClient,
id string,
updateOpts *virtualstorages.UpdateOpts) (*virtualstorages.VirtualStorage, error) {
for i := 0; i < StorageRetryMaxCount; i++ {
v, err := virtualstorages.Update(client, id, updateOpts).Extract()
log.Printf("%d th updating try: result is %#v, %#v", i, v, err)
if err != nil {
_, ok := err.(eclcloud.ErrDefault409)
if ok {
log.Printf("[DEBUG] Sleeping for retry updating")
time.Sleep(time.Minute * time.Duration(StorageRetryWaitMinute))
continue
} else {
return nil, fmt.Errorf("Failed in virtual storage updating with options %v . Error: %s",
updateOpts,
err)
}
}
return v, nil
}
log.Printf("[DEBUG] Reached maximun retry count of updating")
return nil, nil
}
func avoidTenantBusyForVirtualStorageDelete(client *eclcloud.ServiceClient, id string) error {
for i := 0; i < StorageRetryMaxCount; i++ {
err := virtualstorages.Delete(client, id).ExtractErr()
log.Printf("%d th deletion try: result is %#v", i, err)
if err != nil {
_, ok := err.(eclcloud.ErrDefault409)
if ok {
log.Printf("[DEBUG] Sleeping for retry deletion")
time.Sleep(time.Minute * time.Duration(StorageRetryWaitMinute))
continue
} else {
return fmt.Errorf("Failed in virtual storage deleting")
}
}
return nil
}
log.Printf("[DEBUG] Reached maximun retry count of deletion")
return nil
}
func resourceStorageVirtualStorageV1Create(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
client, err := config.storageV1Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating ECL storage client: %s", err)
}
createOpts := &virtualstorages.CreateOpts{
Name: d.Get("name").(string),
Description: d.Get("description").(string),
NetworkID: d.Get("network_id").(string),
SubnetID: d.Get("subnet_id").(string),
VolumeTypeID: d.Get("volume_type_id").(string),
IPAddrPool: resourceVirtualStorageIPAddrPool(d),
HostRoutes: resourceVirtualStorageHostRoutes(d),
}
if volumeTypeID := d.Get("volume_type_id").(string); volumeTypeID != "" {
createOpts.VolumeTypeID = volumeTypeID
} else if volumeTypeName := d.Get("volume_type_name").(string); volumeTypeName != "" {
volumeTypeID, err := volumetypes.IDFromName(client, volumeTypeName)
if err != nil {
return fmt.Errorf("No volume type, named %s is found", volumeTypeName)
}
createOpts.VolumeTypeID = volumeTypeID
}
log.Printf("[DEBUG] Create Options: %#v", createOpts)
// Loop until tenant busy is cleared.
v, err := avoidTenantBusyForVirtualStorageCreate(client, createOpts)
if err != nil {
return fmt.Errorf("Virtual storage creation loop returns error: %s", err)
}
// Store the ID now
d.SetId(v.ID)
log.Printf("[DEBUG] VirtualStorage creation loop result %#v", v)
log.Printf("[INFO] VirtualStorage ID: %s", v.ID)
// Wait for the volume to become available.
log.Printf("[DEBUG] Waiting for virtual storage (%s) to become available", v.ID)
stateConf := &resource.StateChangeConf{
Pending: []string{"creating"},
Target: []string{"available"},
Refresh: VirtualStorageV1RefreshFunc(client, v.ID),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 10 * time.Second,
PollInterval: 30 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for virtual storage (%s) to become ready: %s",
v.ID, err)
}
return resourceStorageVirtualStorageV1Read(d, meta)
}
func getHostRoutesFromVirtualStorage(v *virtualstorages.VirtualStorage) []map[string]string {
hostRoutes := make([]map[string]string, len(v.HostRoutes))
for i, hostRoute := range v.HostRoutes {
hostRoutes[i] = make(map[string]string)
hostRoutes[i]["destination"] = hostRoute.Destination
hostRoutes[i]["nexthop"] = hostRoute.Nexthop
log.Printf("[DEBUG] route: %v", hostRoute)
}
return hostRoutes
}
func getIPAddrPoolFromVirtualStorage(v *virtualstorages.VirtualStorage) map[string]string {
ipAddrPool := make(map[string]string)
ipAddrPool["start"] = v.IPAddrPool.Start
ipAddrPool["end"] = v.IPAddrPool.End
return ipAddrPool
}
func resourceStorageVirtualStorageV1Read(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
client, err := config.storageV1Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating ECL storage client: %s", err)
}
v, err := virtualstorages.Get(client, d.Id()).Extract()
if err != nil {
return CheckDeleted(d, err, "virtual_storage")
}
log.Printf("[DEBUG] Retrieved virtual storage %s: %+v", d.Id(), v)
d.Set("api_error_message", v.APIErrorMessage)
d.Set("network_id", v.NetworkID)
d.Set("subnet_id", v.SubnetID)
d.Set("ip_addr_pool", v.IPAddrPool)
d.Set("host_routes", v.HostRoutes)
d.Set("name", v.Name)
d.Set("description", v.Description)
d.Set("volume_type_id", v.VolumeTypeID)
d.Set("host_routes", getHostRoutesFromVirtualStorage(v))
d.Set("ip_addr_pool", getIPAddrPoolFromVirtualStorage(v))
return nil
}
func resourceStorageVirtualStorageV1Update(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
client, err := config.storageV1Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating ECL storage client: %s", err)
}
var updateOpts virtualstorages.UpdateOpts
if d.HasChange("name") {
name := d.Get("name").(string)
updateOpts.Name = &name
}
if d.HasChange("description") {
description := d.Get("description").(string)
updateOpts.Description = &description
}
if d.HasChange("ip_addr_pool") {
ipAddrPool := resourceVirtualStorageIPAddrPool(d)
updateOpts.IPAddrPool = &ipAddrPool
}
if d.HasChange("host_routes") {
hostRoutes := resourceVirtualStorageHostRoutes(d)
updateOpts.HostRoutes = &hostRoutes
}
// Loop until tenant busy is cleared.
v, err := avoidTenantBusyForVirtualStorageUpdate(client, d.Id(), &updateOpts)
if err != nil {
return fmt.Errorf("VirtualStorage updating loop returns error: %s", err)
}
log.Printf("[DEBUG] VirtualStorage updating loop result %#v", v)
log.Printf("[INFO] VirtualStorage ID: %s", v.ID)
// Wait for the volume to become available.
log.Printf("[DEBUG] Waiting for virtual storage (%s) to become available", v.ID)
stateConf := &resource.StateChangeConf{
Pending: []string{"updating"},
Target: []string{"available"},
Refresh: VirtualStorageV1RefreshFunc(client, v.ID),
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: 10 * time.Second,
PollInterval: 30 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf("Error waiting for virtual storage (%s) to become ready: %s", v.ID, err)
}
return resourceStorageVirtualStorageV1Read(d, meta)
}
func resourceStorageVirtualStorageV1Delete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
client, err := config.storageV1Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating ECL storage client: %s", err)
}
v, err := virtualstorages.Get(client, d.Id()).Extract()
if err != nil {
return CheckDeleted(d, err, "virtual_storage")
}
// 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" {
err := avoidTenantBusyForVirtualStorageDelete(client, d.Id())
if err != nil {
return CheckDeleted(d, err, "virtual_storage")
}
}
// Wait for the volume to delete before moving on.
log.Printf("[DEBUG] Waiting for virtual storage (%s) to delete", d.Id())
stateConf := &resource.StateChangeConf{
Pending: []string{"deleting", "available"},
Target: []string{"deleted"},
Refresh: VirtualStorageV1RefreshFunc(client, d.Id()),
Timeout: d.Timeout(schema.TimeoutDelete),
Delay: 10 * time.Second,
MinTimeout: 3 * time.Second,
}
_, err = stateConf.WaitForState()
if err != nil {
return fmt.Errorf(
"Error waiting for virtual storage (%s) to delete: %s",
d.Id(), err)
}
d.SetId("")
return nil
}
// VirtualStorageV1RefreshFunc returns a resource.StateRefreshFunc that is used to watch
// an ECL virtual storage.
func VirtualStorageV1RefreshFunc(client *eclcloud.ServiceClient, virtualStorageID string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
v, err := virtualstorages.Get(client, virtualStorageID).Extract()
if err != nil {
if _, ok := err.(eclcloud.ErrDefault404); ok {
return v, "deleted", nil
}
return nil, "", err
}
if err == nil && v.ErrorMessage != "" && v.ErrorMessage != " " {
return nil, "", fmt.Errorf(
"Error message from storage service is: %s",
v.ErrorMessage)
}
pattern := regexp.MustCompile("^error_") // error_creating, _updating, _deleting
if pattern.MatchString(v.Status) {
return v, v.Status, fmt.Errorf(
"There was an error creating the virtual storage. " +
"Please check with your cloud admin.")
}
log.Printf("[DEBUG] VirtualStorage state refresh func, status is: %s", v.Status)
return v, v.Status, nil
}
}