github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/openstack/resource_openstack_blockstorage_volume_v1.go (about) 1 package openstack 2 3 import ( 4 "bytes" 5 "fmt" 6 "log" 7 "time" 8 9 "github.com/gophercloud/gophercloud" 10 "github.com/gophercloud/gophercloud/openstack/blockstorage/v1/volumes" 11 "github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/volumeattach" 12 "github.com/hashicorp/terraform/helper/hashcode" 13 "github.com/hashicorp/terraform/helper/resource" 14 "github.com/hashicorp/terraform/helper/schema" 15 ) 16 17 func resourceBlockStorageVolumeV1() *schema.Resource { 18 return &schema.Resource{ 19 Create: resourceBlockStorageVolumeV1Create, 20 Read: resourceBlockStorageVolumeV1Read, 21 Update: resourceBlockStorageVolumeV1Update, 22 Delete: resourceBlockStorageVolumeV1Delete, 23 Importer: &schema.ResourceImporter{ 24 State: schema.ImportStatePassthrough, 25 }, 26 27 Schema: map[string]*schema.Schema{ 28 "region": &schema.Schema{ 29 Type: schema.TypeString, 30 Required: true, 31 ForceNew: true, 32 DefaultFunc: schema.EnvDefaultFunc("OS_REGION_NAME", ""), 33 }, 34 "size": &schema.Schema{ 35 Type: schema.TypeInt, 36 Required: true, 37 ForceNew: true, 38 }, 39 "name": &schema.Schema{ 40 Type: schema.TypeString, 41 Optional: true, 42 ForceNew: false, 43 }, 44 "description": &schema.Schema{ 45 Type: schema.TypeString, 46 Optional: true, 47 ForceNew: false, 48 }, 49 "availability_zone": &schema.Schema{ 50 Type: schema.TypeString, 51 Optional: true, 52 ForceNew: true, 53 Computed: true, 54 }, 55 "metadata": &schema.Schema{ 56 Type: schema.TypeMap, 57 Optional: true, 58 ForceNew: false, 59 Computed: true, 60 }, 61 "snapshot_id": &schema.Schema{ 62 Type: schema.TypeString, 63 Optional: true, 64 ForceNew: true, 65 }, 66 "source_vol_id": &schema.Schema{ 67 Type: schema.TypeString, 68 Optional: true, 69 ForceNew: true, 70 }, 71 "image_id": &schema.Schema{ 72 Type: schema.TypeString, 73 Optional: true, 74 ForceNew: true, 75 }, 76 "volume_type": &schema.Schema{ 77 Type: schema.TypeString, 78 Optional: true, 79 ForceNew: true, 80 Computed: true, 81 }, 82 "attachment": &schema.Schema{ 83 Type: schema.TypeSet, 84 Computed: true, 85 Elem: &schema.Resource{ 86 Schema: map[string]*schema.Schema{ 87 "id": &schema.Schema{ 88 Type: schema.TypeString, 89 Computed: true, 90 }, 91 "instance_id": &schema.Schema{ 92 Type: schema.TypeString, 93 Computed: true, 94 }, 95 "device": &schema.Schema{ 96 Type: schema.TypeString, 97 Computed: true, 98 }, 99 }, 100 }, 101 Set: resourceVolumeAttachmentHash, 102 }, 103 }, 104 } 105 } 106 107 func resourceBlockStorageVolumeV1Create(d *schema.ResourceData, meta interface{}) error { 108 config := meta.(*Config) 109 blockStorageClient, err := config.blockStorageV1Client(d.Get("region").(string)) 110 if err != nil { 111 return fmt.Errorf("Error creating OpenStack block storage client: %s", err) 112 } 113 114 createOpts := &volumes.CreateOpts{ 115 Description: d.Get("description").(string), 116 Availability: d.Get("availability_zone").(string), 117 Name: d.Get("name").(string), 118 Size: d.Get("size").(int), 119 SnapshotID: d.Get("snapshot_id").(string), 120 SourceVolID: d.Get("source_vol_id").(string), 121 ImageID: d.Get("image_id").(string), 122 VolumeType: d.Get("volume_type").(string), 123 Metadata: resourceContainerMetadataV2(d), 124 } 125 126 log.Printf("[DEBUG] Create Options: %#v", createOpts) 127 v, err := volumes.Create(blockStorageClient, createOpts).Extract() 128 if err != nil { 129 return fmt.Errorf("Error creating OpenStack volume: %s", err) 130 } 131 log.Printf("[INFO] Volume ID: %s", v.ID) 132 133 // Store the ID now 134 d.SetId(v.ID) 135 136 // Wait for the volume to become available. 137 log.Printf( 138 "[DEBUG] Waiting for volume (%s) to become available", 139 v.ID) 140 141 stateConf := &resource.StateChangeConf{ 142 Pending: []string{"downloading", "creating"}, 143 Target: []string{"available"}, 144 Refresh: VolumeV1StateRefreshFunc(blockStorageClient, v.ID), 145 Timeout: 10 * time.Minute, 146 Delay: 10 * time.Second, 147 MinTimeout: 3 * time.Second, 148 } 149 150 _, err = stateConf.WaitForState() 151 if err != nil { 152 return fmt.Errorf( 153 "Error waiting for volume (%s) to become ready: %s", 154 v.ID, err) 155 } 156 157 return resourceBlockStorageVolumeV1Read(d, meta) 158 } 159 160 func resourceBlockStorageVolumeV1Read(d *schema.ResourceData, meta interface{}) error { 161 config := meta.(*Config) 162 blockStorageClient, err := config.blockStorageV1Client(d.Get("region").(string)) 163 if err != nil { 164 return fmt.Errorf("Error creating OpenStack block storage client: %s", err) 165 } 166 167 v, err := volumes.Get(blockStorageClient, d.Id()).Extract() 168 if err != nil { 169 return CheckDeleted(d, err, "volume") 170 } 171 172 log.Printf("[DEBUG] Retrieved volume %s: %+v", d.Id(), v) 173 174 d.Set("size", v.Size) 175 d.Set("description", v.Description) 176 d.Set("availability_zone", v.AvailabilityZone) 177 d.Set("name", v.Name) 178 d.Set("snapshot_id", v.SnapshotID) 179 d.Set("source_vol_id", v.SourceVolID) 180 d.Set("volume_type", v.VolumeType) 181 d.Set("metadata", v.Metadata) 182 183 attachments := make([]map[string]interface{}, len(v.Attachments)) 184 for i, attachment := range v.Attachments { 185 attachments[i] = make(map[string]interface{}) 186 attachments[i]["id"] = attachment["id"] 187 attachments[i]["instance_id"] = attachment["server_id"] 188 attachments[i]["device"] = attachment["device"] 189 log.Printf("[DEBUG] attachment: %v", attachment) 190 } 191 d.Set("attachment", attachments) 192 193 return nil 194 } 195 196 func resourceBlockStorageVolumeV1Update(d *schema.ResourceData, meta interface{}) error { 197 config := meta.(*Config) 198 blockStorageClient, err := config.blockStorageV1Client(d.Get("region").(string)) 199 if err != nil { 200 return fmt.Errorf("Error creating OpenStack block storage client: %s", err) 201 } 202 203 updateOpts := volumes.UpdateOpts{ 204 Name: d.Get("name").(string), 205 Description: d.Get("description").(string), 206 } 207 208 if d.HasChange("metadata") { 209 updateOpts.Metadata = resourceVolumeMetadataV1(d) 210 } 211 212 _, err = volumes.Update(blockStorageClient, d.Id(), updateOpts).Extract() 213 if err != nil { 214 return fmt.Errorf("Error updating OpenStack volume: %s", err) 215 } 216 217 return resourceBlockStorageVolumeV1Read(d, meta) 218 } 219 220 func resourceBlockStorageVolumeV1Delete(d *schema.ResourceData, meta interface{}) error { 221 config := meta.(*Config) 222 blockStorageClient, err := config.blockStorageV1Client(d.Get("region").(string)) 223 if err != nil { 224 return fmt.Errorf("Error creating OpenStack block storage client: %s", err) 225 } 226 227 v, err := volumes.Get(blockStorageClient, d.Id()).Extract() 228 if err != nil { 229 return CheckDeleted(d, err, "volume") 230 } 231 232 // make sure this volume is detached from all instances before deleting 233 if len(v.Attachments) > 0 { 234 log.Printf("[DEBUG] detaching volumes") 235 if computeClient, err := config.computeV2Client(d.Get("region").(string)); err != nil { 236 return err 237 } else { 238 for _, volumeAttachment := range v.Attachments { 239 log.Printf("[DEBUG] Attachment: %v", volumeAttachment) 240 if err := volumeattach.Delete(computeClient, volumeAttachment["server_id"].(string), volumeAttachment["id"].(string)).ExtractErr(); err != nil { 241 return err 242 } 243 } 244 245 stateConf := &resource.StateChangeConf{ 246 Pending: []string{"in-use", "attaching", "detaching"}, 247 Target: []string{"available"}, 248 Refresh: VolumeV1StateRefreshFunc(blockStorageClient, d.Id()), 249 Timeout: 10 * time.Minute, 250 Delay: 10 * time.Second, 251 MinTimeout: 3 * time.Second, 252 } 253 254 _, err = stateConf.WaitForState() 255 if err != nil { 256 return fmt.Errorf( 257 "Error waiting for volume (%s) to become available: %s", 258 d.Id(), err) 259 } 260 } 261 } 262 263 // It's possible that this volume was used as a boot device and is currently 264 // in a "deleting" state from when the instance was terminated. 265 // If this is true, just move on. It'll eventually delete. 266 if v.Status != "deleting" { 267 if err := volumes.Delete(blockStorageClient, d.Id()).ExtractErr(); err != nil { 268 return CheckDeleted(d, err, "volume") 269 } 270 } 271 272 // Wait for the volume to delete before moving on. 273 log.Printf("[DEBUG] Waiting for volume (%s) to delete", d.Id()) 274 275 stateConf := &resource.StateChangeConf{ 276 Pending: []string{"deleting", "downloading", "available"}, 277 Target: []string{"deleted"}, 278 Refresh: VolumeV1StateRefreshFunc(blockStorageClient, d.Id()), 279 Timeout: 10 * time.Minute, 280 Delay: 10 * time.Second, 281 MinTimeout: 3 * time.Second, 282 } 283 284 _, err = stateConf.WaitForState() 285 if err != nil { 286 return fmt.Errorf( 287 "Error waiting for volume (%s) to delete: %s", 288 d.Id(), err) 289 } 290 291 d.SetId("") 292 return nil 293 } 294 295 func resourceVolumeMetadataV1(d *schema.ResourceData) map[string]string { 296 m := make(map[string]string) 297 for key, val := range d.Get("metadata").(map[string]interface{}) { 298 m[key] = val.(string) 299 } 300 return m 301 } 302 303 // VolumeV1StateRefreshFunc returns a resource.StateRefreshFunc that is used to watch 304 // an OpenStack volume. 305 func VolumeV1StateRefreshFunc(client *gophercloud.ServiceClient, volumeID string) resource.StateRefreshFunc { 306 return func() (interface{}, string, error) { 307 v, err := volumes.Get(client, volumeID).Extract() 308 if err != nil { 309 if _, ok := err.(gophercloud.ErrDefault404); ok { 310 return v, "deleted", nil 311 } 312 return nil, "", err 313 } 314 315 return v, v.Status, nil 316 } 317 } 318 319 func resourceVolumeAttachmentHash(v interface{}) int { 320 var buf bytes.Buffer 321 m := v.(map[string]interface{}) 322 if m["instance_id"] != nil { 323 buf.WriteString(fmt.Sprintf("%s-", m["instance_id"].(string))) 324 } 325 return hashcode.String(buf.String()) 326 }