Merge pull request #475 from feiskyer/neutronports
[rfr] Allow to specify hostid when creating/updating a port
diff --git a/acceptance/openstack/blockstorage/v2/extensions/pkg.go b/acceptance/openstack/blockstorage/v2/extensions/pkg.go
new file mode 100644
index 0000000..89d906d
--- /dev/null
+++ b/acceptance/openstack/blockstorage/v2/extensions/pkg.go
@@ -0,0 +1,3 @@
+// The extensions package contains acceptance tests for the Openstack Cinder V2 extensions service.
+
+package extensions
diff --git a/acceptance/openstack/blockstorage/v2/extensions/volumeactions_test.go b/acceptance/openstack/blockstorage/v2/extensions/volumeactions_test.go
new file mode 100644
index 0000000..e01967b
--- /dev/null
+++ b/acceptance/openstack/blockstorage/v2/extensions/volumeactions_test.go
@@ -0,0 +1,149 @@
+// +build acceptance blockstorage
+
+package extensions
+
+import (
+ "os"
+ "testing"
+
+ "github.com/rackspace/gophercloud"
+ "github.com/rackspace/gophercloud/openstack"
+ "github.com/rackspace/gophercloud/openstack/blockstorage/v2/extensions/volumeactions"
+ "github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes"
+ th "github.com/rackspace/gophercloud/testhelper"
+)
+
+func newClient(t *testing.T) (*gophercloud.ServiceClient, error) {
+ ao, err := openstack.AuthOptionsFromEnv()
+ th.AssertNoErr(t, err)
+
+ client, err := openstack.AuthenticatedClient(ao)
+ th.AssertNoErr(t, err)
+
+ return openstack.NewBlockStorageV2(client, gophercloud.EndpointOpts{
+ Region: os.Getenv("OS_REGION_NAME"),
+ })
+}
+
+func TestVolumeAttach(t *testing.T) {
+ client, err := newClient(t)
+ th.AssertNoErr(t, err)
+
+ t.Logf("Creating volume")
+ cv, err := volumes.Create(client, &volumes.CreateOpts{
+ Size: 1,
+ Name: "blockv2-volume",
+ }).Extract()
+ th.AssertNoErr(t, err)
+
+ defer func() {
+ err = volumes.WaitForStatus(client, cv.ID, "available", 60)
+ th.AssertNoErr(t, err)
+
+ t.Logf("Deleting volume")
+ err = volumes.Delete(client, cv.ID).ExtractErr()
+ th.AssertNoErr(t, err)
+ }()
+
+ err = volumes.WaitForStatus(client, cv.ID, "available", 60)
+ th.AssertNoErr(t, err)
+
+ instanceID := os.Getenv("OS_INSTANCE_ID")
+ if instanceID == "" {
+ t.Fatal("Environment variable OS_INSTANCE_ID is required")
+ }
+
+ t.Logf("Attaching volume")
+ err = volumeactions.Attach(client, cv.ID, &volumeactions.AttachOpts{
+ MountPoint: "/mnt",
+ Mode: "rw",
+ InstanceUUID: instanceID,
+ }).ExtractErr()
+ th.AssertNoErr(t, err)
+
+ err = volumes.WaitForStatus(client, cv.ID, "in-use", 60)
+ th.AssertNoErr(t, err)
+
+ t.Logf("Detaching volume")
+ err = volumeactions.Detach(client, cv.ID).ExtractErr()
+ th.AssertNoErr(t, err)
+}
+
+func TestVolumeReserve(t *testing.T) {
+ client, err := newClient(t)
+ th.AssertNoErr(t, err)
+
+ t.Logf("Creating volume")
+ cv, err := volumes.Create(client, &volumes.CreateOpts{
+ Size: 1,
+ Name: "blockv2-volume",
+ }).Extract()
+ th.AssertNoErr(t, err)
+
+ defer func() {
+ err = volumes.WaitForStatus(client, cv.ID, "available", 60)
+ th.AssertNoErr(t, err)
+
+ t.Logf("Deleting volume")
+ err = volumes.Delete(client, cv.ID).ExtractErr()
+ th.AssertNoErr(t, err)
+ }()
+
+ err = volumes.WaitForStatus(client, cv.ID, "available", 60)
+ th.AssertNoErr(t, err)
+
+ t.Logf("Reserving volume")
+ err = volumeactions.Reserve(client, cv.ID).ExtractErr()
+ th.AssertNoErr(t, err)
+
+ err = volumes.WaitForStatus(client, cv.ID, "attaching", 60)
+ th.AssertNoErr(t, err)
+
+ t.Logf("Unreserving volume")
+ err = volumeactions.Unreserve(client, cv.ID).ExtractErr()
+ th.AssertNoErr(t, err)
+
+ err = volumes.WaitForStatus(client, cv.ID, "available", 60)
+ th.AssertNoErr(t, err)
+}
+
+func TestVolumeConns(t *testing.T) {
+ client, err := newClient(t)
+ th.AssertNoErr(t, err)
+
+ t.Logf("Creating volume")
+ cv, err := volumes.Create(client, &volumes.CreateOpts{
+ Size: 1,
+ Name: "blockv2-volume",
+ }).Extract()
+ th.AssertNoErr(t, err)
+
+ defer func() {
+ err = volumes.WaitForStatus(client, cv.ID, "available", 60)
+ th.AssertNoErr(t, err)
+
+ t.Logf("Deleting volume")
+ err = volumes.Delete(client, cv.ID).ExtractErr()
+ th.AssertNoErr(t, err)
+ }()
+
+ err = volumes.WaitForStatus(client, cv.ID, "available", 60)
+ th.AssertNoErr(t, err)
+
+ connOpts := &volumeactions.ConnectorOpts{
+ IP: "127.0.0.1",
+ Host: "stack",
+ Initiator: "iqn.1994-05.com.redhat:17cf566367d2",
+ Multipath: false,
+ Platform: "x86_64",
+ OSType: "linux2",
+ }
+
+ t.Logf("Initializing connection")
+ _, err = volumeactions.InitializeConnection(client, cv.ID, connOpts).Extract()
+ th.AssertNoErr(t, err)
+
+ t.Logf("Terminating connection")
+ err = volumeactions.TerminateConnection(client, cv.ID, connOpts).ExtractErr()
+ th.AssertNoErr(t, err)
+}
diff --git a/acceptance/openstack/blockstorage/v2/pkg.go b/acceptance/openstack/blockstorage/v2/pkg.go
new file mode 100644
index 0000000..31dd0ff
--- /dev/null
+++ b/acceptance/openstack/blockstorage/v2/pkg.go
@@ -0,0 +1,3 @@
+// The v2 package contains acceptance tests for the Openstack Cinder V2 service.
+
+package v2
diff --git a/acceptance/openstack/blockstorage/v2/volumes_test.go b/acceptance/openstack/blockstorage/v2/volumes_test.go
new file mode 100644
index 0000000..9b82654
--- /dev/null
+++ b/acceptance/openstack/blockstorage/v2/volumes_test.go
@@ -0,0 +1,63 @@
+// +build acceptance blockstorage
+
+package v2
+
+import (
+ "os"
+ "testing"
+
+ "github.com/rackspace/gophercloud"
+ "github.com/rackspace/gophercloud/openstack"
+ "github.com/rackspace/gophercloud/openstack/blockstorage/v2/volumes"
+ "github.com/rackspace/gophercloud/pagination"
+ th "github.com/rackspace/gophercloud/testhelper"
+)
+
+func newClient(t *testing.T) (*gophercloud.ServiceClient, error) {
+ ao, err := openstack.AuthOptionsFromEnv()
+ th.AssertNoErr(t, err)
+
+ client, err := openstack.AuthenticatedClient(ao)
+ th.AssertNoErr(t, err)
+
+ return openstack.NewBlockStorageV2(client, gophercloud.EndpointOpts{
+ Region: os.Getenv("OS_REGION_NAME"),
+ })
+}
+
+func TestVolumes(t *testing.T) {
+ client, err := newClient(t)
+ th.AssertNoErr(t, err)
+
+ cv, err := volumes.Create(client, &volumes.CreateOpts{
+ Size: 1,
+ Name: "blockv2-volume",
+ }).Extract()
+ th.AssertNoErr(t, err)
+ defer func() {
+ err = volumes.WaitForStatus(client, cv.ID, "available", 60)
+ th.AssertNoErr(t, err)
+ err = volumes.Delete(client, cv.ID).ExtractErr()
+ th.AssertNoErr(t, err)
+ }()
+
+ _, err = volumes.Update(client, cv.ID, &volumes.UpdateOpts{
+ Name: "blockv2-updated-volume",
+ }).Extract()
+ th.AssertNoErr(t, err)
+
+ v, err := volumes.Get(client, cv.ID).Extract()
+ th.AssertNoErr(t, err)
+ t.Logf("Got volume: %+v\n", v)
+
+ if v.Name != "blockv2-updated-volume" {
+ t.Errorf("Unable to update volume: Expected name: blockv2-updated-volume\nActual name: %s", v.Name)
+ }
+
+ err = volumes.List(client, &volumes.ListOpts{Name: "blockv2-updated-volume"}).EachPage(func(page pagination.Page) (bool, error) {
+ vols, err := volumes.ExtractVolumes(page)
+ th.CheckEquals(t, 1, len(vols))
+ return true, err
+ })
+ th.AssertNoErr(t, err)
+}
diff --git a/openstack/blockstorage/v2/extensions/volumeactions/doc.go b/openstack/blockstorage/v2/extensions/volumeactions/doc.go
new file mode 100644
index 0000000..0935fdb
--- /dev/null
+++ b/openstack/blockstorage/v2/extensions/volumeactions/doc.go
@@ -0,0 +1,5 @@
+// Package volumeactions provides information and interaction with volumes in the
+// OpenStack Block Storage service. A volume is a detachable block storage
+// device, akin to a USB hard drive. It can only be attached to one instance at
+// a time.
+package volumeactions
diff --git a/openstack/blockstorage/v2/extensions/volumeactions/fixtures.go b/openstack/blockstorage/v2/extensions/volumeactions/fixtures.go
new file mode 100644
index 0000000..905d6df
--- /dev/null
+++ b/openstack/blockstorage/v2/extensions/volumeactions/fixtures.go
@@ -0,0 +1,183 @@
+package volumeactions
+
+import (
+ "fmt"
+ "net/http"
+ "testing"
+
+ th "github.com/rackspace/gophercloud/testhelper"
+ fake "github.com/rackspace/gophercloud/testhelper/client"
+)
+
+func MockAttachResponse(t *testing.T) {
+ th.Mux.HandleFunc("/volumes/cd281d77-8217-4830-be95-9528227c105c/action",
+ func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "POST")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+ th.TestHeader(t, r, "Content-Type", "application/json")
+ th.TestHeader(t, r, "Accept", "application/json")
+ th.TestJSONRequest(t, r, `
+{
+ "os-attach":
+ {
+ "mountpoint": "/mnt",
+ "mode": "rw",
+ "instance_uuid": "50902f4f-a974-46a0-85e9-7efc5e22dfdd"
+ }
+}
+ `)
+
+ w.Header().Add("Content-Type", "application/json")
+ w.WriteHeader(http.StatusAccepted)
+
+ fmt.Fprintf(w, `{}`)
+ })
+}
+
+func MockDetachResponse(t *testing.T) {
+ th.Mux.HandleFunc("/volumes/cd281d77-8217-4830-be95-9528227c105c/action",
+ func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "POST")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+ th.TestHeader(t, r, "Content-Type", "application/json")
+ th.TestHeader(t, r, "Accept", "application/json")
+ th.TestJSONRequest(t, r, `
+{
+ "os-detach": {}
+}
+ `)
+
+ w.Header().Add("Content-Type", "application/json")
+ w.WriteHeader(http.StatusAccepted)
+
+ fmt.Fprintf(w, `{}`)
+ })
+}
+
+func MockReserveResponse(t *testing.T) {
+ th.Mux.HandleFunc("/volumes/cd281d77-8217-4830-be95-9528227c105c/action",
+ func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "POST")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+ th.TestHeader(t, r, "Content-Type", "application/json")
+ th.TestHeader(t, r, "Accept", "application/json")
+ th.TestJSONRequest(t, r, `
+{
+ "os-reserve": {}
+}
+ `)
+
+ w.Header().Add("Content-Type", "application/json")
+ w.WriteHeader(http.StatusAccepted)
+
+ fmt.Fprintf(w, `{}`)
+ })
+}
+
+func MockUnreserveResponse(t *testing.T) {
+ th.Mux.HandleFunc("/volumes/cd281d77-8217-4830-be95-9528227c105c/action",
+ func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "POST")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+ th.TestHeader(t, r, "Content-Type", "application/json")
+ th.TestHeader(t, r, "Accept", "application/json")
+ th.TestJSONRequest(t, r, `
+{
+ "os-unreserve": {}
+}
+ `)
+
+ w.Header().Add("Content-Type", "application/json")
+ w.WriteHeader(http.StatusAccepted)
+
+ fmt.Fprintf(w, `{}`)
+ })
+}
+
+func MockInitializeConnectionResponse(t *testing.T) {
+ th.Mux.HandleFunc("/volumes/cd281d77-8217-4830-be95-9528227c105c/action",
+ func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "POST")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+ th.TestHeader(t, r, "Content-Type", "application/json")
+ th.TestHeader(t, r, "Accept", "application/json")
+ th.TestJSONRequest(t, r, `
+{
+ "os-initialize_connection":
+ {
+ "connector":
+ {
+ "ip":"127.0.0.1",
+ "host":"stack",
+ "initiator":"iqn.1994-05.com.redhat:17cf566367d2",
+ "multipath": false,
+ "platform": "x86_64",
+ "os_type": "linux2"
+ }
+ }
+}
+ `)
+
+ w.Header().Add("Content-Type", "application/json")
+ w.WriteHeader(http.StatusAccepted)
+
+ fmt.Fprintf(w, `{
+"connection_info": {
+ "data": {
+ "target_portals": [
+ "172.31.17.48:3260"
+ ],
+ "auth_method": "CHAP",
+ "auth_username": "5MLtcsTEmNN5jFVcT6ui",
+ "access_mode": "rw",
+ "target_lun": 0,
+ "volume_id": "cd281d77-8217-4830-be95-9528227c105c",
+ "target_luns": [
+ 0
+ ],
+ "target_iqns": [
+ "iqn.2010-10.org.openstack:volume-cd281d77-8217-4830-be95-9528227c105c"
+ ],
+ "auth_password": "x854ZY5Re3aCkdNL",
+ "target_discovered": false,
+ "encrypted": false,
+ "qos_specs": null,
+ "target_iqn": "iqn.2010-10.org.openstack:volume-cd281d77-8217-4830-be95-9528227c105c",
+ "target_portal": "172.31.17.48:3260"
+ },
+ "driver_volume_type": "iscsi"
+ }
+ }`)
+ })
+}
+
+func MockTerminateConnectionResponse(t *testing.T) {
+ th.Mux.HandleFunc("/volumes/cd281d77-8217-4830-be95-9528227c105c/action",
+ func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "POST")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+ th.TestHeader(t, r, "Content-Type", "application/json")
+ th.TestHeader(t, r, "Accept", "application/json")
+ th.TestJSONRequest(t, r, `
+{
+ "os-terminate_connection":
+ {
+ "connector":
+ {
+ "ip":"127.0.0.1",
+ "host":"stack",
+ "initiator":"iqn.1994-05.com.redhat:17cf566367d2",
+ "multipath": false,
+ "platform": "x86_64",
+ "os_type": "linux2"
+ }
+ }
+}
+ `)
+
+ w.Header().Add("Content-Type", "application/json")
+ w.WriteHeader(http.StatusAccepted)
+
+ fmt.Fprintf(w, `{}`)
+ })
+}
diff --git a/openstack/blockstorage/v2/extensions/volumeactions/requests.go b/openstack/blockstorage/v2/extensions/volumeactions/requests.go
new file mode 100644
index 0000000..842a659
--- /dev/null
+++ b/openstack/blockstorage/v2/extensions/volumeactions/requests.go
@@ -0,0 +1,201 @@
+package volumeactions
+
+import (
+ "github.com/rackspace/gophercloud"
+)
+
+// AttachOptsBuilder allows extensions to add additional parameters to the
+// Attach request.
+type AttachOptsBuilder interface {
+ ToVolumeAttachMap() (map[string]interface{}, error)
+}
+
+// AttachMode describes the attachment mode for volumes.
+type AttachMode string
+
+// These constants determine how a volume is attached
+const (
+ ReadOnly AttachMode = "ro"
+ ReadWrite AttachMode = "rw"
+)
+
+// AttachOpts contains options for attaching a Volume.
+type AttachOpts struct {
+ // The mountpoint of this volume
+ MountPoint string
+ // The nova instance ID, can't set simultaneously with HostName
+ InstanceUUID string
+ // The hostname of baremetal host, can't set simultaneously with InstanceUUID
+ HostName string
+ // Mount mode of this volume
+ Mode AttachMode
+}
+
+// ToVolumeAttachMap assembles a request body based on the contents of a
+// AttachOpts.
+func (opts AttachOpts) ToVolumeAttachMap() (map[string]interface{}, error) {
+ v := make(map[string]interface{})
+
+ if opts.MountPoint != "" {
+ v["mountpoint"] = opts.MountPoint
+ }
+ if opts.Mode != "" {
+ v["mode"] = opts.Mode
+ }
+ if opts.InstanceUUID != "" {
+ v["instance_uuid"] = opts.InstanceUUID
+ }
+ if opts.HostName != "" {
+ v["host_name"] = opts.HostName
+ }
+
+ return map[string]interface{}{"os-attach": v}, nil
+}
+
+// Attach will attach a volume based on the values in AttachOpts.
+func Attach(client *gophercloud.ServiceClient, id string, opts AttachOptsBuilder) AttachResult {
+ var res AttachResult
+
+ reqBody, err := opts.ToVolumeAttachMap()
+ if err != nil {
+ res.Err = err
+ return res
+ }
+
+ _, res.Err = client.Post(attachURL(client, id), reqBody, nil, &gophercloud.RequestOpts{
+ OkCodes: []int{202},
+ })
+
+ return res
+}
+
+// Attach will detach a volume based on volume id.
+func Detach(client *gophercloud.ServiceClient, id string) DetachResult {
+ var res DetachResult
+
+ v := make(map[string]interface{})
+ reqBody := map[string]interface{}{"os-detach": v}
+
+ _, res.Err = client.Post(detachURL(client, id), reqBody, nil, &gophercloud.RequestOpts{
+ OkCodes: []int{202},
+ })
+
+ return res
+}
+
+// Reserve will reserve a volume based on volume id.
+func Reserve(client *gophercloud.ServiceClient, id string) ReserveResult {
+ var res ReserveResult
+
+ v := make(map[string]interface{})
+ reqBody := map[string]interface{}{"os-reserve": v}
+
+ _, res.Err = client.Post(reserveURL(client, id), reqBody, nil, &gophercloud.RequestOpts{
+ OkCodes: []int{200, 201, 202},
+ })
+
+ return res
+}
+
+// Unreserve will unreserve a volume based on volume id.
+func Unreserve(client *gophercloud.ServiceClient, id string) UnreserveResult {
+ var res UnreserveResult
+
+ v := make(map[string]interface{})
+ reqBody := map[string]interface{}{"os-unreserve": v}
+
+ _, res.Err = client.Post(unreserveURL(client, id), reqBody, nil, &gophercloud.RequestOpts{
+ OkCodes: []int{200, 201, 202},
+ })
+
+ return res
+}
+
+// ConnectorOptsBuilder allows extensions to add additional parameters to the
+// InitializeConnection request.
+type ConnectorOptsBuilder interface {
+ ToConnectorMap() (map[string]interface{}, error)
+}
+
+// ConnectorOpts hosts options for InitializeConnection.
+type ConnectorOpts struct {
+ IP string
+ Host string
+ Initiator string
+ Wwpns []string
+ Wwnns string
+ Multipath bool
+ Platform string
+ OSType string
+}
+
+// ToConnectorMap assembles a request body based on the contents of a
+// ConnectorOpts.
+func (opts ConnectorOpts) ToConnectorMap() (map[string]interface{}, error) {
+ v := make(map[string]interface{})
+
+ if opts.IP != "" {
+ v["ip"] = opts.IP
+ }
+ if opts.Host != "" {
+ v["host"] = opts.Host
+ }
+ if opts.Initiator != "" {
+ v["initiator"] = opts.Initiator
+ }
+ if opts.Wwpns != nil {
+ v["wwpns"] = opts.Wwpns
+ }
+ if opts.Wwnns != "" {
+ v["wwnns"] = opts.Wwnns
+ }
+
+ v["multipath"] = opts.Multipath
+
+ if opts.Platform != "" {
+ v["platform"] = opts.Platform
+ }
+ if opts.OSType != "" {
+ v["os_type"] = opts.OSType
+ }
+
+ return map[string]interface{}{"connector": v}, nil
+}
+
+// InitializeConnection initializes iscsi connection.
+func InitializeConnection(client *gophercloud.ServiceClient, id string, opts *ConnectorOpts) InitializeConnectionResult {
+ var res InitializeConnectionResult
+
+ connctorMap, err := opts.ToConnectorMap()
+ if err != nil {
+ res.Err = err
+ return res
+ }
+
+ reqBody := map[string]interface{}{"os-initialize_connection": connctorMap}
+
+ _, res.Err = client.Post(initializeConnectionURL(client, id), reqBody, &res.Body, &gophercloud.RequestOpts{
+ OkCodes: []int{200, 201, 202},
+ })
+
+ return res
+}
+
+// TerminateConnection terminates iscsi connection.
+func TerminateConnection(client *gophercloud.ServiceClient, id string, opts *ConnectorOpts) TerminateConnectionResult {
+ var res TerminateConnectionResult
+
+ connctorMap, err := opts.ToConnectorMap()
+ if err != nil {
+ res.Err = err
+ return res
+ }
+
+ reqBody := map[string]interface{}{"os-terminate_connection": connctorMap}
+
+ _, res.Err = client.Post(teminateConnectionURL(client, id), reqBody, nil, &gophercloud.RequestOpts{
+ OkCodes: []int{202},
+ })
+
+ return res
+}
diff --git a/openstack/blockstorage/v2/extensions/volumeactions/requests_test.go b/openstack/blockstorage/v2/extensions/volumeactions/requests_test.go
new file mode 100644
index 0000000..5657287
--- /dev/null
+++ b/openstack/blockstorage/v2/extensions/volumeactions/requests_test.go
@@ -0,0 +1,89 @@
+package volumeactions
+
+import (
+ "testing"
+
+ th "github.com/rackspace/gophercloud/testhelper"
+ "github.com/rackspace/gophercloud/testhelper/client"
+)
+
+func TestAttach(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockAttachResponse(t)
+
+ options := &AttachOpts{
+ MountPoint: "/mnt",
+ Mode: "rw",
+ InstanceUUID: "50902f4f-a974-46a0-85e9-7efc5e22dfdd",
+ }
+ err := Attach(client.ServiceClient(), "cd281d77-8217-4830-be95-9528227c105c", options).ExtractErr()
+ th.AssertNoErr(t, err)
+}
+
+func TestDetach(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockDetachResponse(t)
+
+ err := Detach(client.ServiceClient(), "cd281d77-8217-4830-be95-9528227c105c").ExtractErr()
+ th.AssertNoErr(t, err)
+}
+
+func TestReserve(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockReserveResponse(t)
+
+ err := Reserve(client.ServiceClient(), "cd281d77-8217-4830-be95-9528227c105c").ExtractErr()
+ th.AssertNoErr(t, err)
+}
+
+func TestUnreserve(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockUnreserveResponse(t)
+
+ err := Unreserve(client.ServiceClient(), "cd281d77-8217-4830-be95-9528227c105c").ExtractErr()
+ th.AssertNoErr(t, err)
+}
+
+func TestInitializeConnection(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockInitializeConnectionResponse(t)
+
+ options := &ConnectorOpts{
+ IP: "127.0.0.1",
+ Host: "stack",
+ Initiator: "iqn.1994-05.com.redhat:17cf566367d2",
+ Multipath: false,
+ Platform: "x86_64",
+ OSType: "linux2",
+ }
+ _, err := InitializeConnection(client.ServiceClient(), "cd281d77-8217-4830-be95-9528227c105c", options).Extract()
+ th.AssertNoErr(t, err)
+}
+
+func TestTerminateConnection(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockTerminateConnectionResponse(t)
+
+ options := &ConnectorOpts{
+ IP: "127.0.0.1",
+ Host: "stack",
+ Initiator: "iqn.1994-05.com.redhat:17cf566367d2",
+ Multipath: false,
+ Platform: "x86_64",
+ OSType: "linux2",
+ }
+ err := TerminateConnection(client.ServiceClient(), "cd281d77-8217-4830-be95-9528227c105c", options).ExtractErr()
+ th.AssertNoErr(t, err)
+}
diff --git a/openstack/blockstorage/v2/extensions/volumeactions/results.go b/openstack/blockstorage/v2/extensions/volumeactions/results.go
new file mode 100644
index 0000000..65778e5
--- /dev/null
+++ b/openstack/blockstorage/v2/extensions/volumeactions/results.go
@@ -0,0 +1,52 @@
+package volumeactions
+
+import (
+ "github.com/mitchellh/mapstructure"
+ "github.com/rackspace/gophercloud"
+)
+
+type commonResult struct {
+ gophercloud.Result
+}
+
+// AttachResult contains the response body and error from a Get request.
+type AttachResult struct {
+ gophercloud.ErrResult
+}
+
+// DetachResult contains the response body and error from a Get request.
+type DetachResult struct {
+ gophercloud.ErrResult
+}
+
+// ReserveResult contains the response body and error from a Get request.
+type ReserveResult struct {
+ gophercloud.ErrResult
+}
+
+// UnreserveResult contains the response body and error from a Get request.
+type UnreserveResult struct {
+ gophercloud.ErrResult
+}
+
+// InitializeConnectionResult contains the response body and error from a Get request.
+type InitializeConnectionResult struct {
+ commonResult
+}
+
+// TerminateConnectionResult contains the response body and error from a Get request.
+type TerminateConnectionResult struct {
+ gophercloud.ErrResult
+}
+
+// Extract will get the Volume object out of the commonResult object.
+func (r commonResult) Extract() (map[string]interface{}, error) {
+ if r.Err != nil {
+ return nil, r.Err
+ }
+
+ var res map[string]interface{}
+ err := mapstructure.Decode(r.Body, &res)
+
+ return res, err
+}
diff --git a/openstack/blockstorage/v2/extensions/volumeactions/urls.go b/openstack/blockstorage/v2/extensions/volumeactions/urls.go
new file mode 100644
index 0000000..4b3c5f2
--- /dev/null
+++ b/openstack/blockstorage/v2/extensions/volumeactions/urls.go
@@ -0,0 +1,27 @@
+package volumeactions
+
+import "github.com/rackspace/gophercloud"
+
+func attachURL(c *gophercloud.ServiceClient, id string) string {
+ return c.ServiceURL("volumes", id, "action")
+}
+
+func detachURL(c *gophercloud.ServiceClient, id string) string {
+ return attachURL(c, id)
+}
+
+func reserveURL(c *gophercloud.ServiceClient, id string) string {
+ return attachURL(c, id)
+}
+
+func unreserveURL(c *gophercloud.ServiceClient, id string) string {
+ return attachURL(c, id)
+}
+
+func initializeConnectionURL(c *gophercloud.ServiceClient, id string) string {
+ return attachURL(c, id)
+}
+
+func teminateConnectionURL(c *gophercloud.ServiceClient, id string) string {
+ return attachURL(c, id)
+}
diff --git a/openstack/blockstorage/v2/extensions/volumeactions/urls_test.go b/openstack/blockstorage/v2/extensions/volumeactions/urls_test.go
new file mode 100644
index 0000000..ff4a5d3
--- /dev/null
+++ b/openstack/blockstorage/v2/extensions/volumeactions/urls_test.go
@@ -0,0 +1,50 @@
+package volumeactions
+
+import (
+ "testing"
+
+ "github.com/rackspace/gophercloud"
+ th "github.com/rackspace/gophercloud/testhelper"
+)
+
+const endpoint = "http://localhost:57909"
+
+func endpointClient() *gophercloud.ServiceClient {
+ return &gophercloud.ServiceClient{Endpoint: endpoint}
+}
+
+func TestAttachURL(t *testing.T) {
+ actual := attachURL(endpointClient(), "foo")
+ expected := endpoint + "volumes/foo/action"
+ th.AssertEquals(t, expected, actual)
+}
+
+func TestDettachURL(t *testing.T) {
+ actual := detachURL(endpointClient(), "foo")
+ expected := endpoint + "volumes/foo/action"
+ th.AssertEquals(t, expected, actual)
+}
+
+func TestReserveURL(t *testing.T) {
+ actual := reserveURL(endpointClient(), "foo")
+ expected := endpoint + "volumes/foo/action"
+ th.AssertEquals(t, expected, actual)
+}
+
+func TestUnreserveURL(t *testing.T) {
+ actual := unreserveURL(endpointClient(), "foo")
+ expected := endpoint + "volumes/foo/action"
+ th.AssertEquals(t, expected, actual)
+}
+
+func TestInitializeConnectionURL(t *testing.T) {
+ actual := initializeConnectionURL(endpointClient(), "foo")
+ expected := endpoint + "volumes/foo/action"
+ th.AssertEquals(t, expected, actual)
+}
+
+func TestTeminateConnectionURL(t *testing.T) {
+ actual := teminateConnectionURL(endpointClient(), "foo")
+ expected := endpoint + "volumes/foo/action"
+ th.AssertEquals(t, expected, actual)
+}
diff --git a/openstack/blockstorage/v2/volumes/doc.go b/openstack/blockstorage/v2/volumes/doc.go
new file mode 100644
index 0000000..307b8b1
--- /dev/null
+++ b/openstack/blockstorage/v2/volumes/doc.go
@@ -0,0 +1,5 @@
+// Package volumes provides information and interaction with volumes in the
+// OpenStack Block Storage service. A volume is a detachable block storage
+// device, akin to a USB hard drive. It can only be attached to one instance at
+// a time.
+package volumes
diff --git a/openstack/blockstorage/v2/volumes/fixtures.go b/openstack/blockstorage/v2/volumes/fixtures.go
new file mode 100644
index 0000000..b70e298
--- /dev/null
+++ b/openstack/blockstorage/v2/volumes/fixtures.go
@@ -0,0 +1,204 @@
+package volumes
+
+import (
+ "fmt"
+ "net/http"
+ "testing"
+
+ th "github.com/rackspace/gophercloud/testhelper"
+ fake "github.com/rackspace/gophercloud/testhelper/client"
+)
+
+func MockListResponse(t *testing.T) {
+ th.Mux.HandleFunc("/volumes/detail", func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "GET")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+
+ w.Header().Add("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+
+ fmt.Fprintf(w, `
+ {
+ "volumes": [
+ {
+ "volume_type": "lvmdriver-1",
+ "created_at": "2015-09-17T03:35:03.000000",
+ "bootable": "false",
+ "name": "vol-001",
+ "os-vol-mig-status-attr:name_id": null,
+ "consistencygroup_id": null,
+ "source_volid": null,
+ "os-volume-replication:driver_data": null,
+ "multiattach": false,
+ "snapshot_id": null,
+ "replication_status": "disabled",
+ "os-volume-replication:extended_status": null,
+ "encrypted": false,
+ "os-vol-host-attr:host": null,
+ "availability_zone": "nova",
+ "attachments": [
+ {
+ "attachment_id": "03987cd1-0ad5-40d1-9b2a-7cc48295d4fa",
+ "id": "47e9ecc5-4045-4ee3-9a4b-d859d546a0cf",
+ "volume_id": "289da7f8-6440-407c-9fb4-7db01ec49164",
+ "server_id": "d1c4788b-9435-42e2-9b81-29f3be1cd01f",
+ "host_name": "stack",
+ "device": "/dev/vdc"
+ }
+ ],
+ "id": "289da7f8-6440-407c-9fb4-7db01ec49164",
+ "size": 75,
+ "user_id": "ff1ce52c03ab433aaba9108c2e3ef541",
+ "os-vol-tenant-attr:tenant_id": "304dc00909ac4d0da6c62d816bcb3459",
+ "os-vol-mig-status-attr:migstat": null,
+ "metadata": {"foo": "bar"},
+ "status": "available",
+ "description": null
+ },
+ {
+ "volume_type": "lvmdriver-1",
+ "created_at": "2015-09-17T03:32:29.000000",
+ "bootable": "false",
+ "name": "vol-002",
+ "os-vol-mig-status-attr:name_id": null,
+ "consistencygroup_id": null,
+ "source_volid": null,
+ "os-volume-replication:driver_data": null,
+ "multiattach": false,
+ "snapshot_id": null,
+ "replication_status": "disabled",
+ "os-volume-replication:extended_status": null,
+ "encrypted": false,
+ "os-vol-host-attr:host": null,
+ "availability_zone": "nova",
+ "attachments": [],
+ "id": "96c3bda7-c82a-4f50-be73-ca7621794835",
+ "size": 75,
+ "user_id": "ff1ce52c03ab433aaba9108c2e3ef541",
+ "os-vol-tenant-attr:tenant_id": "304dc00909ac4d0da6c62d816bcb3459",
+ "os-vol-mig-status-attr:migstat": null,
+ "metadata": {},
+ "status": "available",
+ "description": null
+ }
+ ]
+}
+
+ `)
+ })
+}
+
+func MockGetResponse(t *testing.T) {
+ th.Mux.HandleFunc("/volumes/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "GET")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+
+ w.Header().Add("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprintf(w, `
+{
+ "volume": {
+ "volume_type": "lvmdriver-1",
+ "created_at": "2015-09-17T03:32:29.000000",
+ "bootable": "false",
+ "name": "vol-001",
+ "os-vol-mig-status-attr:name_id": null,
+ "consistencygroup_id": null,
+ "source_volid": null,
+ "os-volume-replication:driver_data": null,
+ "multiattach": false,
+ "snapshot_id": null,
+ "replication_status": "disabled",
+ "os-volume-replication:extended_status": null,
+ "encrypted": false,
+ "os-vol-host-attr:host": null,
+ "availability_zone": "nova",
+ "attachments": [{
+ "attachment_id": "dbce64e3-f3b9-4423-a44f-a2b15deffa1b",
+ "id": "3eafc6f5-ed74-456d-90fb-f253f594dbae",
+ "volume_id": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
+ "server_id": "d1c4788b-9435-42e2-9b81-29f3be1cd01f",
+ "host_name": "stack",
+ "device": "/dev/vdd"
+ }],
+ "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
+ "size": 75,
+ "user_id": "ff1ce52c03ab433aaba9108c2e3ef541",
+ "os-vol-tenant-attr:tenant_id": "304dc00909ac4d0da6c62d816bcb3459",
+ "os-vol-mig-status-attr:migstat": null,
+ "metadata": {},
+ "status": "available",
+ "description": null
+ }
+}
+ `)
+ })
+}
+
+func MockCreateResponse(t *testing.T) {
+ th.Mux.HandleFunc("/volumes", func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "POST")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+ th.TestHeader(t, r, "Content-Type", "application/json")
+ th.TestHeader(t, r, "Accept", "application/json")
+ th.TestJSONRequest(t, r, `
+{
+ "volume": {
+ "name": "vol-001",
+ "size": 75
+ }
+}
+ `)
+
+ w.Header().Add("Content-Type", "application/json")
+ w.WriteHeader(http.StatusAccepted)
+
+ fmt.Fprintf(w, `
+{
+ "volume": {
+ "size": 75,
+ "id": "d32019d3-bc6e-4319-9c1d-6722fc136a22",
+ "metadata": {},
+ "created_at": "2015-09-17T03:32:29.044216",
+ "encrypted": false,
+ "bootable": "false",
+ "availability_zone": "nova",
+ "attachments": [],
+ "user_id": "ff1ce52c03ab433aaba9108c2e3ef541",
+ "status": "creating",
+ "description": null,
+ "volume_type": "lvmdriver-1",
+ "name": "vol-001",
+ "replication_status": "disabled",
+ "consistencygroup_id": null,
+ "source_volid": null,
+ "snapshot_id": null,
+ "multiattach": false
+ }
+}
+ `)
+ })
+}
+
+func MockDeleteResponse(t *testing.T) {
+ th.Mux.HandleFunc("/volumes/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "DELETE")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+ w.WriteHeader(http.StatusAccepted)
+ })
+}
+
+func MockUpdateResponse(t *testing.T) {
+ th.Mux.HandleFunc("/volumes/d32019d3-bc6e-4319-9c1d-6722fc136a22", func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "PUT")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprintf(w, `
+{
+ "volume": {
+ "name": "vol-002"
+ }
+}
+ `)
+ })
+}
diff --git a/openstack/blockstorage/v2/volumes/requests.go b/openstack/blockstorage/v2/volumes/requests.go
new file mode 100644
index 0000000..4c60936
--- /dev/null
+++ b/openstack/blockstorage/v2/volumes/requests.go
@@ -0,0 +1,251 @@
+package volumes
+
+import (
+ "fmt"
+
+ "github.com/rackspace/gophercloud"
+ "github.com/rackspace/gophercloud/pagination"
+)
+
+// CreateOptsBuilder allows extensions to add additional parameters to the
+// Create request.
+type CreateOptsBuilder interface {
+ ToVolumeCreateMap() (map[string]interface{}, error)
+}
+
+// CreateOpts contains options for creating a Volume. This object is passed to
+// the volumes.Create function. For more information about these parameters,
+// see the Volume object.
+type CreateOpts struct {
+ // The availability zone [OPTIONAL]
+ AvailabilityZone string
+ // ConsistencyGroupID is the ID of a consistency group [OPTINAL]
+ ConsistencyGroupID string
+ // The volume description [OPTIONAL]
+ Description string
+ // One or more metadata key and value pairs to associate with the volume [OPTIONAL]
+ Metadata map[string]string
+ // The volume name [OPTIONAL]
+ Name string
+ // The size of the volume, in gibibytes (GiB) [REQUIRED]
+ Size int
+ // the ID of the existing volume snapshot [OPTIONAL]
+ SnapshotID string
+ // SourceReplica is a UUID of an existing volume to replicate with [OPTIONAL]
+ SourceReplica string
+ // the ID of the existing volume [OPTIONAL]
+ SourceVolID string
+ // The ID of the image from which you want to create the volume.
+ // Required to create a bootable volume.
+ ImageID string
+ // The associated volume type [OPTIONAL]
+ VolumeType string
+}
+
+// ToVolumeCreateMap assembles a request body based on the contents of a
+// CreateOpts.
+func (opts CreateOpts) ToVolumeCreateMap() (map[string]interface{}, error) {
+ v := make(map[string]interface{})
+
+ if opts.Size == 0 {
+ return nil, fmt.Errorf("Required CreateOpts field 'Size' not set.")
+ }
+ v["size"] = opts.Size
+
+ if opts.AvailabilityZone != "" {
+ v["availability_zone"] = opts.AvailabilityZone
+ }
+ if opts.ConsistencyGroupID != "" {
+ v["consistencygroup_id"] = opts.ConsistencyGroupID
+ }
+ if opts.Description != "" {
+ v["description"] = opts.Description
+ }
+ if opts.ImageID != "" {
+ v["imageRef"] = opts.ImageID
+ }
+ if opts.Metadata != nil {
+ v["metadata"] = opts.Metadata
+ }
+ if opts.Name != "" {
+ v["name"] = opts.Name
+ }
+ if opts.SourceReplica != "" {
+ v["source_replica"] = opts.SourceReplica
+ }
+ if opts.SourceVolID != "" {
+ v["source_volid"] = opts.SourceVolID
+ }
+ if opts.SnapshotID != "" {
+ v["snapshot_id"] = opts.SnapshotID
+ }
+ if opts.VolumeType != "" {
+ v["volume_type"] = opts.VolumeType
+ }
+
+ return map[string]interface{}{"volume": v}, nil
+}
+
+// Create will create a new Volume based on the values in CreateOpts. To extract
+// the Volume object from the response, call the Extract method on the
+// CreateResult.
+func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult {
+ var res CreateResult
+
+ reqBody, err := opts.ToVolumeCreateMap()
+ if err != nil {
+ res.Err = err
+ return res
+ }
+
+ _, res.Err = client.Post(createURL(client), reqBody, &res.Body, &gophercloud.RequestOpts{
+ OkCodes: []int{202},
+ })
+ return res
+}
+
+// Delete will delete the existing Volume with the provided ID.
+func Delete(client *gophercloud.ServiceClient, id string) DeleteResult {
+ var res DeleteResult
+ _, res.Err = client.Delete(deleteURL(client, id), nil)
+ return res
+}
+
+// Get retrieves the Volume with the provided ID. To extract the Volume object
+// from the response, call the Extract method on the GetResult.
+func Get(client *gophercloud.ServiceClient, id string) GetResult {
+ var res GetResult
+ _, res.Err = client.Get(getURL(client, id), &res.Body, nil)
+ return res
+}
+
+// ListOptsBuilder allows extensions to add additional parameters to the List
+// request.
+type ListOptsBuilder interface {
+ ToVolumeListQuery() (string, error)
+}
+
+// ListOpts holds options for listing Volumes. It is passed to the volumes.List
+// function.
+type ListOpts struct {
+ // admin-only option. Set it to true to see all tenant volumes.
+ AllTenants bool `q:"all_tenants"`
+ // List only volumes that contain Metadata.
+ Metadata map[string]string `q:"metadata"`
+ // List only volumes that have Name as the display name.
+ Name string `q:"name"`
+ // List only volumes that have a status of Status.
+ Status string `q:"status"`
+}
+
+// ToVolumeListQuery formats a ListOpts into a query string.
+func (opts ListOpts) ToVolumeListQuery() (string, error) {
+ q, err := gophercloud.BuildQueryString(opts)
+ if err != nil {
+ return "", err
+ }
+ return q.String(), nil
+}
+
+// List returns Volumes optionally limited by the conditions provided in ListOpts.
+func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {
+ url := listURL(client)
+ if opts != nil {
+ query, err := opts.ToVolumeListQuery()
+ if err != nil {
+ return pagination.Pager{Err: err}
+ }
+ url += query
+ }
+ createPage := func(r pagination.PageResult) pagination.Page {
+ return ListResult{pagination.SinglePageBase(r)}
+ }
+
+ return pagination.NewPager(client, url, createPage)
+}
+
+// UpdateOptsBuilder allows extensions to add additional parameters to the
+// Update request.
+type UpdateOptsBuilder interface {
+ ToVolumeUpdateMap() (map[string]interface{}, error)
+}
+
+// UpdateOpts contain options for updating an existing Volume. This object is passed
+// to the volumes.Update function. For more information about the parameters, see
+// the Volume object.
+type UpdateOpts struct {
+ // OPTIONAL
+ Name string
+ // OPTIONAL
+ Description string
+ // OPTIONAL
+ Metadata map[string]string
+}
+
+// ToVolumeUpdateMap assembles a request body based on the contents of an
+// UpdateOpts.
+func (opts UpdateOpts) ToVolumeUpdateMap() (map[string]interface{}, error) {
+ v := make(map[string]interface{})
+
+ if opts.Description != "" {
+ v["description"] = opts.Description
+ }
+ if opts.Metadata != nil {
+ v["metadata"] = opts.Metadata
+ }
+ if opts.Name != "" {
+ v["name"] = opts.Name
+ }
+
+ return map[string]interface{}{"volume": v}, nil
+}
+
+// Update will update the Volume with provided information. To extract the updated
+// Volume from the response, call the Extract method on the UpdateResult.
+func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult {
+ var res UpdateResult
+
+ reqBody, err := opts.ToVolumeUpdateMap()
+ if err != nil {
+ res.Err = err
+ return res
+ }
+
+ _, res.Err = client.Put(updateURL(client, id), reqBody, &res.Body, &gophercloud.RequestOpts{
+ OkCodes: []int{200},
+ })
+ return res
+}
+
+// IDFromName is a convienience function that returns a server's ID given its name.
+func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) {
+ volumeCount := 0
+ volumeID := ""
+ if name == "" {
+ return "", fmt.Errorf("A volume name must be provided.")
+ }
+ pager := List(client, nil)
+ pager.EachPage(func(page pagination.Page) (bool, error) {
+ volumeList, err := ExtractVolumes(page)
+ if err != nil {
+ return false, err
+ }
+
+ for _, s := range volumeList {
+ if s.Name == name {
+ volumeCount++
+ volumeID = s.ID
+ }
+ }
+ return true, nil
+ })
+
+ switch volumeCount {
+ case 0:
+ return "", fmt.Errorf("Unable to find volume: %s", name)
+ case 1:
+ return volumeID, nil
+ default:
+ return "", fmt.Errorf("Found %d volumes matching %s", volumeCount, name)
+ }
+}
diff --git a/openstack/blockstorage/v2/volumes/requests_test.go b/openstack/blockstorage/v2/volumes/requests_test.go
new file mode 100644
index 0000000..962d94b
--- /dev/null
+++ b/openstack/blockstorage/v2/volumes/requests_test.go
@@ -0,0 +1,211 @@
+package volumes
+
+import (
+ "testing"
+
+ "github.com/rackspace/gophercloud/pagination"
+ th "github.com/rackspace/gophercloud/testhelper"
+ "github.com/rackspace/gophercloud/testhelper/client"
+)
+
+func TestList(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockListResponse(t)
+
+ count := 0
+
+ List(client.ServiceClient(), &ListOpts{}).EachPage(func(page pagination.Page) (bool, error) {
+ count++
+ actual, err := ExtractVolumes(page)
+ if err != nil {
+ t.Errorf("Failed to extract volumes: %v", err)
+ return false, err
+ }
+
+ expected := []Volume{
+ {
+ ID: "289da7f8-6440-407c-9fb4-7db01ec49164",
+ Name: "vol-001",
+ Attachments: []map[string]interface{}{{
+ "AttachmentID": "03987cd1-0ad5-40d1-9b2a-7cc48295d4fa",
+ "ID": "47e9ecc5-4045-4ee3-9a4b-d859d546a0cf",
+ "VolumeID": "289da7f8-6440-407c-9fb4-7db01ec49164",
+ "ServerID": "d1c4788b-9435-42e2-9b81-29f3be1cd01f",
+ "HostName": "stack",
+ "Device": "/dev/vdc",
+ }},
+ AvailabilityZone: "nova",
+ Bootable: "false",
+ ConsistencyGroupID: "",
+ CreatedAt: "2015-09-17T03:35:03.000000",
+ Description: "",
+ Encrypted: false,
+ Metadata: map[string]string{"foo": "bar"},
+ Multiattach: false,
+ TenantID: "304dc00909ac4d0da6c62d816bcb3459",
+ ReplicationDriverData: "",
+ ReplicationExtendedStatus: "",
+ ReplicationStatus: "disabled",
+ Size: 75,
+ SnapshotID: "",
+ SourceVolID: "",
+ Status: "available",
+ UserID: "ff1ce52c03ab433aaba9108c2e3ef541",
+ VolumeType: "lvmdriver-1",
+ },
+ {
+ ID: "96c3bda7-c82a-4f50-be73-ca7621794835",
+ Name: "vol-002",
+ Attachments: []map[string]interface{}{},
+ AvailabilityZone: "nova",
+ Bootable: "false",
+ ConsistencyGroupID: "",
+ CreatedAt: "2015-09-17T03:32:29.000000",
+ Description: "",
+ Encrypted: false,
+ Metadata: map[string]string{},
+ Multiattach: false,
+ TenantID: "304dc00909ac4d0da6c62d816bcb3459",
+ ReplicationDriverData: "",
+ ReplicationExtendedStatus: "",
+ ReplicationStatus: "disabled",
+ Size: 75,
+ SnapshotID: "",
+ SourceVolID: "",
+ Status: "available",
+ UserID: "ff1ce52c03ab433aaba9108c2e3ef541",
+ VolumeType: "lvmdriver-1",
+ },
+ }
+
+ th.CheckDeepEquals(t, expected, actual)
+
+ return true, nil
+ })
+
+ if count != 1 {
+ t.Errorf("Expected 1 page, got %d", count)
+ }
+}
+
+func TestListAll(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockListResponse(t)
+
+ allPages, err := List(client.ServiceClient(), &ListOpts{}).AllPages()
+ th.AssertNoErr(t, err)
+ actual, err := ExtractVolumes(allPages)
+ th.AssertNoErr(t, err)
+
+ expected := []Volume{
+ {
+ ID: "289da7f8-6440-407c-9fb4-7db01ec49164",
+ Name: "vol-001",
+ Attachments: []map[string]interface{}{{
+ "AttachmentID": "03987cd1-0ad5-40d1-9b2a-7cc48295d4fa",
+ "ID": "47e9ecc5-4045-4ee3-9a4b-d859d546a0cf",
+ "VolumeID": "289da7f8-6440-407c-9fb4-7db01ec49164",
+ "ServerID": "d1c4788b-9435-42e2-9b81-29f3be1cd01f",
+ "HostName": "stack",
+ "Device": "/dev/vdc",
+ }},
+ AvailabilityZone: "nova",
+ Bootable: "false",
+ ConsistencyGroupID: "",
+ CreatedAt: "2015-09-17T03:35:03.000000",
+ Description: "",
+ Encrypted: false,
+ Metadata: map[string]string{"foo": "bar"},
+ Multiattach: false,
+ TenantID: "304dc00909ac4d0da6c62d816bcb3459",
+ ReplicationDriverData: "",
+ ReplicationExtendedStatus: "",
+ ReplicationStatus: "disabled",
+ Size: 75,
+ SnapshotID: "",
+ SourceVolID: "",
+ Status: "available",
+ UserID: "ff1ce52c03ab433aaba9108c2e3ef541",
+ VolumeType: "lvmdriver-1",
+ },
+ {
+ ID: "96c3bda7-c82a-4f50-be73-ca7621794835",
+ Name: "vol-002",
+ Attachments: []map[string]interface{}{},
+ AvailabilityZone: "nova",
+ Bootable: "false",
+ ConsistencyGroupID: "",
+ CreatedAt: "2015-09-17T03:32:29.000000",
+ Description: "",
+ Encrypted: false,
+ Metadata: map[string]string{},
+ Multiattach: false,
+ TenantID: "304dc00909ac4d0da6c62d816bcb3459",
+ ReplicationDriverData: "",
+ ReplicationExtendedStatus: "",
+ ReplicationStatus: "disabled",
+ Size: 75,
+ SnapshotID: "",
+ SourceVolID: "",
+ Status: "available",
+ UserID: "ff1ce52c03ab433aaba9108c2e3ef541",
+ VolumeType: "lvmdriver-1",
+ },
+ }
+
+ th.CheckDeepEquals(t, expected, actual)
+
+}
+
+func TestGet(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockGetResponse(t)
+
+ v, err := Get(client.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22").Extract()
+ th.AssertNoErr(t, err)
+
+ th.AssertEquals(t, v.Name, "vol-001")
+ th.AssertEquals(t, v.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22")
+}
+
+func TestCreate(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockCreateResponse(t)
+
+ options := &CreateOpts{Size: 75, Name: "vol-001"}
+ n, err := Create(client.ServiceClient(), options).Extract()
+ th.AssertNoErr(t, err)
+
+ th.AssertEquals(t, n.Size, 75)
+ th.AssertEquals(t, n.ID, "d32019d3-bc6e-4319-9c1d-6722fc136a22")
+}
+
+func TestDelete(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockDeleteResponse(t)
+
+ res := Delete(client.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22")
+ th.AssertNoErr(t, res.Err)
+}
+
+func TestUpdate(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ MockUpdateResponse(t)
+
+ options := UpdateOpts{Name: "vol-002"}
+ v, err := Update(client.ServiceClient(), "d32019d3-bc6e-4319-9c1d-6722fc136a22", options).Extract()
+ th.AssertNoErr(t, err)
+ th.CheckEquals(t, "vol-002", v.Name)
+}
diff --git a/openstack/blockstorage/v2/volumes/results.go b/openstack/blockstorage/v2/volumes/results.go
new file mode 100644
index 0000000..59fa530
--- /dev/null
+++ b/openstack/blockstorage/v2/volumes/results.go
@@ -0,0 +1,137 @@
+package volumes
+
+import (
+ "github.com/rackspace/gophercloud"
+ "github.com/rackspace/gophercloud/pagination"
+
+ "github.com/mitchellh/mapstructure"
+)
+
+// Volume contains all the information associated with an OpenStack Volume.
+type Volume struct {
+ // Instances onto which the volume is attached.
+ Attachments []map[string]interface{} `mapstructure:"attachments"`
+
+ // AvailabilityZone is which availability zone the volume is in.
+ AvailabilityZone string `mapstructure:"availability_zone"`
+
+ // Indicates whether this is a bootable volume.
+ Bootable string `mapstructure:"bootable"`
+
+ // ConsistencyGroupID is the consistency group ID.
+ ConsistencyGroupID string `mapstructure:"consistencygroup_id"`
+
+ // The date when this volume was created.
+ CreatedAt string `mapstructure:"created_at"`
+
+ // Human-readable description for the volume.
+ Description string `mapstructure:"description"`
+
+ // Encrypted denotes if the volume is encrypted.
+ Encrypted bool `mapstructure:"encrypted"`
+
+ // Human-readable display name for the volume.
+ Name string `mapstructure:"name"`
+
+ // The type of volume to create, either SATA or SSD.
+ VolumeType string `mapstructure:"volume_type"`
+
+ // ReplicationDriverData contains data about the replication driver.
+ ReplicationDriverData string `mapstructure:"os-volume-replication:driver_data"`
+
+ // ReplicationExtendedStatus contains extended status about replication.
+ ReplicationExtendedStatus string `mapstructure:"os-volume-replication:extended_status"`
+
+ // ReplicationStatus is the status of replication.
+ ReplicationStatus string `mapstructure:"replication_status"`
+
+ // The ID of the snapshot from which the volume was created
+ SnapshotID string `mapstructure:"snapshot_id"`
+
+ // The ID of another block storage volume from which the current volume was created
+ SourceVolID string `mapstructure:"source_volid"`
+
+ // Current status of the volume.
+ Status string `mapstructure:"status"`
+
+ // TenantID is the id of the project that owns the volume.
+ TenantID string `mapstructure:"os-vol-tenant-attr:tenant_id"`
+
+ // Arbitrary key-value pairs defined by the user.
+ Metadata map[string]string `mapstructure:"metadata"`
+
+ // Multiattach denotes if the volume is multi-attach capable.
+ Multiattach bool `mapstructure:"multiattach"`
+
+ // Unique identifier for the volume.
+ ID string `mapstructure:"id"`
+
+ // Size of the volume in GB.
+ Size int `mapstructure:"size"`
+
+ // UserID is the id of the user who created the volume.
+ UserID string `mapstructure:"user_id"`
+}
+
+// CreateResult contains the response body and error from a Create request.
+type CreateResult struct {
+ commonResult
+}
+
+// GetResult contains the response body and error from a Get request.
+type GetResult struct {
+ commonResult
+}
+
+// DeleteResult contains the response body and error from a Delete request.
+type DeleteResult struct {
+ gophercloud.ErrResult
+}
+
+// ListResult is a pagination.pager that is returned from a call to the List function.
+type ListResult struct {
+ pagination.SinglePageBase
+}
+
+// IsEmpty returns true if a ListResult contains no Volumes.
+func (r ListResult) IsEmpty() (bool, error) {
+ volumes, err := ExtractVolumes(r)
+ if err != nil {
+ return true, err
+ }
+ return len(volumes) == 0, nil
+}
+
+// ExtractVolumes extracts and returns Volumes. It is used while iterating over a volumes.List call.
+func ExtractVolumes(page pagination.Page) ([]Volume, error) {
+ var response struct {
+ Volumes []Volume `json:"volumes"`
+ }
+
+ err := mapstructure.Decode(page.(ListResult).Body, &response)
+ return response.Volumes, err
+}
+
+// UpdateResult contains the response body and error from an Update request.
+type UpdateResult struct {
+ commonResult
+}
+
+type commonResult struct {
+ gophercloud.Result
+}
+
+// Extract will get the Volume object out of the commonResult object.
+func (r commonResult) Extract() (*Volume, error) {
+ if r.Err != nil {
+ return nil, r.Err
+ }
+
+ var res struct {
+ Volume *Volume `json:"volume"`
+ }
+
+ err := mapstructure.Decode(r.Body, &res)
+
+ return res.Volume, err
+}
diff --git a/openstack/blockstorage/v2/volumes/urls.go b/openstack/blockstorage/v2/volumes/urls.go
new file mode 100644
index 0000000..2523ec6
--- /dev/null
+++ b/openstack/blockstorage/v2/volumes/urls.go
@@ -0,0 +1,23 @@
+package volumes
+
+import "github.com/rackspace/gophercloud"
+
+func createURL(c *gophercloud.ServiceClient) string {
+ return c.ServiceURL("volumes")
+}
+
+func listURL(c *gophercloud.ServiceClient) string {
+ return c.ServiceURL("volumes", "detail")
+}
+
+func deleteURL(c *gophercloud.ServiceClient, id string) string {
+ return c.ServiceURL("volumes", id)
+}
+
+func getURL(c *gophercloud.ServiceClient, id string) string {
+ return deleteURL(c, id)
+}
+
+func updateURL(c *gophercloud.ServiceClient, id string) string {
+ return deleteURL(c, id)
+}
diff --git a/openstack/blockstorage/v2/volumes/urls_test.go b/openstack/blockstorage/v2/volumes/urls_test.go
new file mode 100644
index 0000000..792b19b
--- /dev/null
+++ b/openstack/blockstorage/v2/volumes/urls_test.go
@@ -0,0 +1,44 @@
+package volumes
+
+import (
+ "testing"
+
+ "github.com/rackspace/gophercloud"
+ th "github.com/rackspace/gophercloud/testhelper"
+)
+
+const endpoint = "http://localhost:57909"
+
+func endpointClient() *gophercloud.ServiceClient {
+ return &gophercloud.ServiceClient{Endpoint: endpoint}
+}
+
+func TestCreateURL(t *testing.T) {
+ actual := createURL(endpointClient())
+ expected := endpoint + "volumes"
+ th.AssertEquals(t, expected, actual)
+}
+
+func TestListURL(t *testing.T) {
+ actual := listURL(endpointClient())
+ expected := endpoint + "volumes/detail"
+ th.AssertEquals(t, expected, actual)
+}
+
+func TestDeleteURL(t *testing.T) {
+ actual := deleteURL(endpointClient(), "foo")
+ expected := endpoint + "volumes/foo"
+ th.AssertEquals(t, expected, actual)
+}
+
+func TestGetURL(t *testing.T) {
+ actual := getURL(endpointClient(), "foo")
+ expected := endpoint + "volumes/foo"
+ th.AssertEquals(t, expected, actual)
+}
+
+func TestUpdateURL(t *testing.T) {
+ actual := updateURL(endpointClient(), "foo")
+ expected := endpoint + "volumes/foo"
+ th.AssertEquals(t, expected, actual)
+}
diff --git a/openstack/blockstorage/v2/volumes/util.go b/openstack/blockstorage/v2/volumes/util.go
new file mode 100644
index 0000000..1dda695
--- /dev/null
+++ b/openstack/blockstorage/v2/volumes/util.go
@@ -0,0 +1,22 @@
+package volumes
+
+import (
+ "github.com/rackspace/gophercloud"
+)
+
+// WaitForStatus will continually poll the resource, checking for a particular
+// status. It will do this for the amount of seconds defined.
+func WaitForStatus(c *gophercloud.ServiceClient, id, status string, secs int) error {
+ return gophercloud.WaitFor(secs, func() (bool, error) {
+ current, err := Get(c, id).Extract()
+ if err != nil {
+ return false, err
+ }
+
+ if current.Status == status {
+ return true, nil
+ }
+
+ return false, nil
+ })
+}
diff --git a/openstack/client.go b/openstack/client.go
index 951f4ed..b533e83 100644
--- a/openstack/client.go
+++ b/openstack/client.go
@@ -281,6 +281,29 @@
return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil
}
+// NewBlockStorageV2 creates a ServiceClient that may be used to access the v2 block storage service.
+func NewBlockStorageV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
+ eo.ApplyDefaults("volume")
+ url, err := client.EndpointLocator(eo)
+ if err != nil {
+ return nil, err
+ }
+
+ // Force using v2 API
+ if strings.Contains(url, "/v1") {
+ url = strings.Replace(url, "/v1", "/v2", -1)
+ }
+ if !strings.Contains(url, "/v2") {
+ return nil, fmt.Errorf("Block Storage v2 endpoint not found")
+ }
+
+ return &gophercloud.ServiceClient{
+ ProviderClient: client,
+ Endpoint: url,
+ ResourceBase: url,
+ }, nil
+}
+
// NewCDNV1 creates a ServiceClient that may be used to access the OpenStack v1
// CDN service.
func NewCDNV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {