Merge pull request #378 from jrperritt/list-server-addresses
List Server Addresses; Closes #286
diff --git a/acceptance/openstack/compute/v2/tenantnetworks_test.go b/acceptance/openstack/compute/v2/tenantnetworks_test.go
new file mode 100644
index 0000000..a92e8bf
--- /dev/null
+++ b/acceptance/openstack/compute/v2/tenantnetworks_test.go
@@ -0,0 +1,109 @@
+// +build acceptance compute servers
+
+package v2
+
+import (
+ "os"
+ "testing"
+
+ "github.com/rackspace/gophercloud"
+ "github.com/rackspace/gophercloud/acceptance/tools"
+ "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/tenantnetworks"
+ "github.com/rackspace/gophercloud/openstack/compute/v2/servers"
+ th "github.com/rackspace/gophercloud/testhelper"
+)
+
+func getNetworkID(t *testing.T, client *gophercloud.ServiceClient, networkName string) (string, error) {
+ allPages, err := tenantnetworks.List(client).AllPages()
+ if err != nil {
+ t.Fatalf("Unable to list networks: %v", err)
+ }
+
+ networkList, err := tenantnetworks.ExtractNetworks(allPages)
+ if err != nil {
+ t.Fatalf("Unable to list networks: %v", err)
+ }
+
+ networkID := ""
+ for _, network := range networkList {
+ t.Logf("Network: %v", network)
+ if network.Name == networkName {
+ networkID = network.ID
+ }
+ }
+
+ t.Logf("Found network ID for %s: %s\n", networkName, networkID)
+
+ return networkID, nil
+}
+
+func createNetworkServer(t *testing.T, client *gophercloud.ServiceClient, choices *ComputeChoices, networkID string) (*servers.Server, error) {
+ if testing.Short() {
+ t.Skip("Skipping test that requires server creation in short mode.")
+ }
+
+ name := tools.RandomString("ACPTTEST", 16)
+ t.Logf("Attempting to create server: %s\n", name)
+
+ pwd := tools.MakeNewPassword("")
+
+ networks := make([]servers.Network, 1)
+ networks[0] = servers.Network{
+ UUID: networkID,
+ }
+
+ server, err := servers.Create(client, servers.CreateOpts{
+ Name: name,
+ FlavorRef: choices.FlavorID,
+ ImageRef: choices.ImageID,
+ AdminPass: pwd,
+ Networks: networks,
+ }).Extract()
+ if err != nil {
+ t.Fatalf("Unable to create server: %v", err)
+ }
+
+ th.AssertEquals(t, pwd, server.AdminPass)
+
+ return server, err
+}
+
+func TestTenantNetworks(t *testing.T) {
+ networkName := os.Getenv("OS_NETWORK_NAME")
+ if networkName == "" {
+ t.Fatalf("OS_NETWORK_NAME must be set")
+ }
+
+ choices, err := ComputeChoicesFromEnv()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ client, err := newClient()
+ if err != nil {
+ t.Fatalf("Unable to create a compute client: %v", err)
+ }
+
+ networkID, err := getNetworkID(t, client, networkName)
+ if err != nil {
+ t.Fatalf("Unable to get network ID: %v", err)
+ }
+
+ server, err := createNetworkServer(t, client, choices, networkID)
+ if err != nil {
+ t.Fatalf("Unable to create server: %v", err)
+ }
+ defer func() {
+ servers.Delete(client, server.ID)
+ t.Logf("Server deleted.")
+ }()
+
+ if err = waitForStatus(client, server, "ACTIVE"); err != nil {
+ t.Fatalf("Unable to wait for server: %v", err)
+ }
+
+ allPages, err := tenantnetworks.List(client).AllPages()
+ allNetworks, err := tenantnetworks.ExtractNetworks(allPages)
+ th.AssertNoErr(t, err)
+ t.Logf("Retrieved all %d networks: %+v", len(allNetworks), allNetworks)
+}
diff --git a/acceptance/openstack/objectstorage/v1/containers_test.go b/acceptance/openstack/objectstorage/v1/containers_test.go
index d6832f1..8328a4f 100644
--- a/acceptance/openstack/objectstorage/v1/containers_test.go
+++ b/acceptance/openstack/objectstorage/v1/containers_test.go
@@ -87,3 +87,51 @@
}
}
}
+
+func TestListAllContainers(t *testing.T) {
+ // Create a new client to execute the HTTP requests. See common.go for newClient body.
+ client := newClient(t)
+
+ numContainers := 20
+
+ // Create a slice of random container names.
+ cNames := make([]string, numContainers)
+ for i := 0; i < numContainers; i++ {
+ cNames[i] = tools.RandomString("gophercloud-test-container-", 8)
+ }
+
+ // Create numContainers containers.
+ for i := 0; i < len(cNames); i++ {
+ res := containers.Create(client, cNames[i], nil)
+ th.AssertNoErr(t, res.Err)
+ }
+ // Delete the numContainers containers after function completion.
+ defer func() {
+ for i := 0; i < len(cNames); i++ {
+ res := containers.Delete(client, cNames[i])
+ th.AssertNoErr(t, res.Err)
+ }
+ }()
+
+ // List all the numContainer names that were just created. To just list those,
+ // the 'prefix' parameter is used.
+ allPages, err := containers.List(client, &containers.ListOpts{Full: true, Limit: 5, Prefix: "gophercloud-test-container-"}).AllPages()
+ th.AssertNoErr(t, err)
+ containerInfoList, err := containers.ExtractInfo(allPages)
+ th.AssertNoErr(t, err)
+ for _, n := range containerInfoList {
+ t.Logf("Container: Name [%s] Count [%d] Bytes [%d]",
+ n.Name, n.Count, n.Bytes)
+ }
+ th.AssertEquals(t, numContainers, len(containerInfoList))
+
+ // List the info for all the numContainer containers that were created.
+ allPages, err = containers.List(client, &containers.ListOpts{Full: false, Limit: 2, Prefix: "gophercloud-test-container-"}).AllPages()
+ th.AssertNoErr(t, err)
+ containerNamesList, err := containers.ExtractNames(allPages)
+ th.AssertNoErr(t, err)
+ for _, n := range containerNamesList {
+ t.Logf("Container: Name [%s]", n)
+ }
+ th.AssertEquals(t, numContainers, len(containerNamesList))
+}
diff --git a/acceptance/rackspace/compute/v2/volumeattach_test.go b/acceptance/rackspace/compute/v2/volumeattach_test.go
new file mode 100644
index 0000000..9848e2e
--- /dev/null
+++ b/acceptance/rackspace/compute/v2/volumeattach_test.go
@@ -0,0 +1,130 @@
+// +build acceptance compute servers
+
+package v2
+
+import (
+ "os"
+ "testing"
+
+ "github.com/rackspace/gophercloud"
+ "github.com/rackspace/gophercloud/acceptance/tools"
+ "github.com/rackspace/gophercloud/openstack"
+ osVolumes "github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes"
+ osVolumeAttach "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach"
+ osServers "github.com/rackspace/gophercloud/openstack/compute/v2/servers"
+ "github.com/rackspace/gophercloud/rackspace"
+ "github.com/rackspace/gophercloud/rackspace/blockstorage/v1/volumes"
+ "github.com/rackspace/gophercloud/rackspace/compute/v2/servers"
+ "github.com/rackspace/gophercloud/rackspace/compute/v2/volumeattach"
+ th "github.com/rackspace/gophercloud/testhelper"
+)
+
+func newBlockClient(t *testing.T) (*gophercloud.ServiceClient, error) {
+ ao, err := rackspace.AuthOptionsFromEnv()
+ th.AssertNoErr(t, err)
+
+ client, err := rackspace.AuthenticatedClient(ao)
+ th.AssertNoErr(t, err)
+
+ return openstack.NewBlockStorageV1(client, gophercloud.EndpointOpts{
+ Region: os.Getenv("RS_REGION_NAME"),
+ })
+}
+
+func createVAServer(t *testing.T, computeClient *gophercloud.ServiceClient, choices *serverOpts) (*osServers.Server, error) {
+ if testing.Short() {
+ t.Skip("Skipping test that requires server creation in short mode.")
+ }
+
+ name := tools.RandomString("ACPTTEST", 16)
+ t.Logf("Attempting to create server: %s\n", name)
+
+ pwd := tools.MakeNewPassword("")
+
+ server, err := servers.Create(computeClient, osServers.CreateOpts{
+ Name: name,
+ FlavorRef: choices.flavorID,
+ ImageRef: choices.imageID,
+ AdminPass: pwd,
+ }).Extract()
+ if err != nil {
+ t.Fatalf("Unable to create server: %v", err)
+ }
+
+ th.AssertEquals(t, pwd, server.AdminPass)
+
+ return server, err
+}
+
+func createVAVolume(t *testing.T, blockClient *gophercloud.ServiceClient) (*volumes.Volume, error) {
+ volume, err := volumes.Create(blockClient, &osVolumes.CreateOpts{
+ Size: 80,
+ Name: "gophercloud-test-volume",
+ }).Extract()
+ th.AssertNoErr(t, err)
+ defer func() {
+ err = osVolumes.WaitForStatus(blockClient, volume.ID, "available", 60)
+ th.AssertNoErr(t, err)
+ }()
+
+ return volume, err
+}
+
+func createVolumeAttachment(t *testing.T, computeClient *gophercloud.ServiceClient, blockClient *gophercloud.ServiceClient, serverID string, volumeID string) {
+ va, err := volumeattach.Create(computeClient, serverID, &osVolumeAttach.CreateOpts{
+ VolumeID: volumeID,
+ }).Extract()
+ th.AssertNoErr(t, err)
+ defer func() {
+ err = osVolumes.WaitForStatus(blockClient, volumeID, "in-use", 60)
+ th.AssertNoErr(t, err)
+ err = volumeattach.Delete(computeClient, serverID, va.ID).ExtractErr()
+ th.AssertNoErr(t, err)
+ err = osVolumes.WaitForStatus(blockClient, volumeID, "available", 60)
+ th.AssertNoErr(t, err)
+ }()
+ t.Logf("Attached volume to server: %+v", va)
+}
+
+func TestAttachVolume(t *testing.T) {
+ choices, err := optionsFromEnv()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ computeClient, err := newClient()
+ if err != nil {
+ t.Fatalf("Unable to create a compute client: %v", err)
+ }
+
+ blockClient, err := newBlockClient(t)
+ if err != nil {
+ t.Fatalf("Unable to create a blockstorage client: %v", err)
+ }
+
+ server, err := createVAServer(t, computeClient, choices)
+ if err != nil {
+ t.Fatalf("Unable to create server: %v", err)
+ }
+ defer func() {
+ servers.Delete(computeClient, server.ID)
+ t.Logf("Server deleted.")
+ }()
+
+ if err = osServers.WaitForStatus(computeClient, server.ID, "ACTIVE", 300); err != nil {
+ t.Fatalf("Unable to wait for server: %v", err)
+ }
+
+ volume, err := createVAVolume(t, blockClient)
+ if err != nil {
+ t.Fatalf("Unable to create volume: %v", err)
+ }
+ defer func() {
+ err = volumes.Delete(blockClient, volume.ID).ExtractErr()
+ th.AssertNoErr(t, err)
+ t.Logf("Volume deleted.")
+ }()
+
+ createVolumeAttachment(t, computeClient, blockClient, server.ID, volume.ID)
+
+}
diff --git a/openstack/blockstorage/v1/volumes/requests.go b/openstack/blockstorage/v1/volumes/requests.go
index e620ca6..e67ba10 100644
--- a/openstack/blockstorage/v1/volumes/requests.go
+++ b/openstack/blockstorage/v1/volumes/requests.go
@@ -152,6 +152,7 @@
createPage := func(r pagination.PageResult) pagination.Page {
return ListResult{pagination.SinglePageBase(r)}
}
+
return pagination.NewPager(client, url, createPage)
}
diff --git a/openstack/blockstorage/v1/volumes/requests_test.go b/openstack/blockstorage/v1/volumes/requests_test.go
index 7643375..c484cf0 100644
--- a/openstack/blockstorage/v1/volumes/requests_test.go
+++ b/openstack/blockstorage/v1/volumes/requests_test.go
@@ -45,6 +45,32 @@
}
}
+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{
+ Volume{
+ ID: "289da7f8-6440-407c-9fb4-7db01ec49164",
+ Name: "vol-001",
+ },
+ Volume{
+ ID: "96c3bda7-c82a-4f50-be73-ca7621794835",
+ Name: "vol-002",
+ },
+ }
+
+ th.CheckDeepEquals(t, expected, actual)
+
+}
+
func TestGet(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
diff --git a/openstack/compute/v2/extensions/tenantnetworks/doc.go b/openstack/compute/v2/extensions/tenantnetworks/doc.go
new file mode 100644
index 0000000..65c46ff
--- /dev/null
+++ b/openstack/compute/v2/extensions/tenantnetworks/doc.go
@@ -0,0 +1,2 @@
+// Package tenantnetworks provides the ability for tenants to see information about the networks they have access to
+package tenantnetworks
diff --git a/openstack/compute/v2/extensions/tenantnetworks/fixtures.go b/openstack/compute/v2/extensions/tenantnetworks/fixtures.go
new file mode 100644
index 0000000..0cfa72a
--- /dev/null
+++ b/openstack/compute/v2/extensions/tenantnetworks/fixtures.go
@@ -0,0 +1,84 @@
+// +build fixtures
+
+package tenantnetworks
+
+import (
+ "fmt"
+ "net/http"
+ "testing"
+ "time"
+
+ th "github.com/rackspace/gophercloud/testhelper"
+ "github.com/rackspace/gophercloud/testhelper/client"
+)
+
+// ListOutput is a sample response to a List call.
+const ListOutput = `
+{
+ "networks": [
+ {
+ "cidr": "10.0.0.0/29",
+ "id": "20c8acc0-f747-4d71-a389-46d078ebf047",
+ "label": "mynet_0"
+ },
+ {
+ "cidr": "10.0.0.10/29",
+ "id": "20c8acc0-f747-4d71-a389-46d078ebf000",
+ "label": "mynet_1"
+ }
+ ]
+}
+`
+
+// GetOutput is a sample response to a Get call.
+const GetOutput = `
+{
+ "network": {
+ "cidr": "10.0.0.10/29",
+ "id": "20c8acc0-f747-4d71-a389-46d078ebf000",
+ "label": "mynet_1"
+ }
+}
+`
+
+// FirstNetwork is the first result in ListOutput.
+var nilTime time.Time
+var FirstNetwork = Network{
+ CIDR: "10.0.0.0/29",
+ ID: "20c8acc0-f747-4d71-a389-46d078ebf047",
+ Name: "mynet_0",
+}
+
+// SecondNetwork is the second result in ListOutput.
+var SecondNetwork = Network{
+ CIDR: "10.0.0.10/29",
+ ID: "20c8acc0-f747-4d71-a389-46d078ebf000",
+ Name: "mynet_1",
+}
+
+// ExpectedNetworkSlice is the slice of results that should be parsed
+// from ListOutput, in the expected order.
+var ExpectedNetworkSlice = []Network{FirstNetwork, SecondNetwork}
+
+// HandleListSuccessfully configures the test server to respond to a List request.
+func HandleListSuccessfully(t *testing.T) {
+ th.Mux.HandleFunc("/os-tenant-networks", func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "GET")
+ th.TestHeader(t, r, "X-Auth-Token", client.TokenID)
+
+ w.Header().Add("Content-Type", "application/json")
+ fmt.Fprintf(w, ListOutput)
+ })
+}
+
+// HandleGetSuccessfully configures the test server to respond to a Get request
+// for an existing network.
+func HandleGetSuccessfully(t *testing.T) {
+ th.Mux.HandleFunc("/os-tenant-networks/20c8acc0-f747-4d71-a389-46d078ebf000", func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "GET")
+ th.TestHeader(t, r, "X-Auth-Token", client.TokenID)
+
+ w.Header().Add("Content-Type", "application/json")
+ fmt.Fprintf(w, GetOutput)
+ })
+}
diff --git a/openstack/compute/v2/extensions/tenantnetworks/requests.go b/openstack/compute/v2/extensions/tenantnetworks/requests.go
new file mode 100644
index 0000000..cd73479
--- /dev/null
+++ b/openstack/compute/v2/extensions/tenantnetworks/requests.go
@@ -0,0 +1,25 @@
+package tenantnetworks
+
+import (
+ "github.com/rackspace/gophercloud"
+ "github.com/rackspace/gophercloud/pagination"
+)
+
+// List returns a Pager that allows you to iterate over a collection of Network.
+func List(client *gophercloud.ServiceClient) pagination.Pager {
+ url := listURL(client)
+ createPage := func(r pagination.PageResult) pagination.Page {
+ return NetworkPage{pagination.SinglePageBase(r)}
+ }
+ return pagination.NewPager(client, url, createPage)
+}
+
+// Get returns data about a previously created Network.
+func Get(client *gophercloud.ServiceClient, id string) GetResult {
+ var res GetResult
+ _, res.Err = client.Request("GET", getURL(client, id), gophercloud.RequestOpts{
+ JSONResponse: &res.Body,
+ OkCodes: []int{200},
+ })
+ return res
+}
diff --git a/openstack/compute/v2/extensions/tenantnetworks/requests_test.go b/openstack/compute/v2/extensions/tenantnetworks/requests_test.go
new file mode 100644
index 0000000..fc4ee4f
--- /dev/null
+++ b/openstack/compute/v2/extensions/tenantnetworks/requests_test.go
@@ -0,0 +1,37 @@
+package tenantnetworks
+
+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()
+ HandleListSuccessfully(t)
+
+ count := 0
+ err := List(client.ServiceClient()).EachPage(func(page pagination.Page) (bool, error) {
+ count++
+ actual, err := ExtractNetworks(page)
+ th.AssertNoErr(t, err)
+ th.CheckDeepEquals(t, ExpectedNetworkSlice, actual)
+
+ return true, nil
+ })
+ th.AssertNoErr(t, err)
+ th.CheckEquals(t, 1, count)
+}
+
+func TestGet(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ HandleGetSuccessfully(t)
+
+ actual, err := Get(client.ServiceClient(), "20c8acc0-f747-4d71-a389-46d078ebf000").Extract()
+ th.AssertNoErr(t, err)
+ th.CheckDeepEquals(t, &SecondNetwork, actual)
+}
diff --git a/openstack/compute/v2/extensions/tenantnetworks/results.go b/openstack/compute/v2/extensions/tenantnetworks/results.go
new file mode 100644
index 0000000..8050092
--- /dev/null
+++ b/openstack/compute/v2/extensions/tenantnetworks/results.go
@@ -0,0 +1,68 @@
+package tenantnetworks
+
+import (
+ "github.com/mitchellh/mapstructure"
+ "github.com/rackspace/gophercloud"
+ "github.com/rackspace/gophercloud/pagination"
+)
+
+// A Network represents a nova-network that an instance communicates on
+type Network struct {
+ // CIDR is the IPv4 subnet.
+ CIDR string `mapstructure:"cidr"`
+
+ // ID is the UUID of the network.
+ ID string `mapstructure:"id"`
+
+ // Name is the common name that the network has.
+ Name string `mapstructure:"label"`
+}
+
+// NetworkPage stores a single, only page of Networks
+// results from a List call.
+type NetworkPage struct {
+ pagination.SinglePageBase
+}
+
+// IsEmpty determines whether or not a NetworkPage is empty.
+func (page NetworkPage) IsEmpty() (bool, error) {
+ va, err := ExtractNetworks(page)
+ return len(va) == 0, err
+}
+
+// ExtractNetworks interprets a page of results as a slice of Networks
+func ExtractNetworks(page pagination.Page) ([]Network, error) {
+ networks := page.(NetworkPage).Body
+ var res struct {
+ Networks []Network `mapstructure:"networks"`
+ }
+
+ err := mapstructure.WeakDecode(networks, &res)
+
+ return res.Networks, err
+}
+
+type NetworkResult struct {
+ gophercloud.Result
+}
+
+// Extract is a method that attempts to interpret any Network resource
+// response as a Network struct.
+func (r NetworkResult) Extract() (*Network, error) {
+ if r.Err != nil {
+ return nil, r.Err
+ }
+
+ var res struct {
+ Network *Network `json:"network" mapstructure:"network"`
+ }
+
+ err := mapstructure.Decode(r.Body, &res)
+ return res.Network, err
+}
+
+// GetResult is the response from a Get operation. Call its Extract method to interpret it
+// as a Network.
+type GetResult struct {
+ NetworkResult
+}
diff --git a/openstack/compute/v2/extensions/tenantnetworks/urls.go b/openstack/compute/v2/extensions/tenantnetworks/urls.go
new file mode 100644
index 0000000..2401a5d
--- /dev/null
+++ b/openstack/compute/v2/extensions/tenantnetworks/urls.go
@@ -0,0 +1,17 @@
+package tenantnetworks
+
+import "github.com/rackspace/gophercloud"
+
+const resourcePath = "os-tenant-networks"
+
+func resourceURL(c *gophercloud.ServiceClient) string {
+ return c.ServiceURL(resourcePath)
+}
+
+func listURL(c *gophercloud.ServiceClient) string {
+ return resourceURL(c)
+}
+
+func getURL(c *gophercloud.ServiceClient, id string) string {
+ return c.ServiceURL(resourcePath, id)
+}
diff --git a/openstack/compute/v2/extensions/tenantnetworks/urls_test.go b/openstack/compute/v2/extensions/tenantnetworks/urls_test.go
new file mode 100644
index 0000000..39c464e
--- /dev/null
+++ b/openstack/compute/v2/extensions/tenantnetworks/urls_test.go
@@ -0,0 +1,25 @@
+package tenantnetworks
+
+import (
+ "testing"
+
+ th "github.com/rackspace/gophercloud/testhelper"
+ "github.com/rackspace/gophercloud/testhelper/client"
+)
+
+func TestListURL(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ c := client.ServiceClient()
+
+ th.CheckEquals(t, c.Endpoint+"os-tenant-networks", listURL(c))
+}
+
+func TestGetURL(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ c := client.ServiceClient()
+ id := "1"
+
+ th.CheckEquals(t, c.Endpoint+"os-tenant-networks/"+id, getURL(c, id))
+}
diff --git a/openstack/compute/v2/servers/requests_test.go b/openstack/compute/v2/servers/requests_test.go
index 3527428..62b89e0 100644
--- a/openstack/compute/v2/servers/requests_test.go
+++ b/openstack/compute/v2/servers/requests_test.go
@@ -39,6 +39,19 @@
}
}
+func TestListAllServers(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ HandleServerListSuccessfully(t)
+
+ allPages, err := List(client.ServiceClient(), ListOpts{}).AllPages()
+ th.AssertNoErr(t, err)
+ actual, err := ExtractServers(allPages)
+ th.AssertNoErr(t, err)
+ th.CheckDeepEquals(t, ServerHerp, actual[0])
+ th.CheckDeepEquals(t, ServerDerp, actual[1])
+}
+
func TestCreateServer(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
diff --git a/openstack/networking/v2/extensions/external/requests.go b/openstack/networking/v2/extensions/external/requests.go
index 2f04593..097ae37 100644
--- a/openstack/networking/v2/extensions/external/requests.go
+++ b/openstack/networking/v2/extensions/external/requests.go
@@ -1,6 +1,10 @@
package external
-import "github.com/rackspace/gophercloud/openstack/networking/v2/networks"
+import (
+ "time"
+
+ "github.com/rackspace/gophercloud/openstack/networking/v2/networks"
+)
// AdminState gives users a solid type to work with for create and update
// operations. It is recommended that users use the `Up` and `Down` enums.
@@ -25,6 +29,15 @@
// ToNetworkCreateMap casts a CreateOpts struct to a map.
func (o CreateOpts) ToNetworkCreateMap() (map[string]interface{}, error) {
+
+ // DO NOT REMOVE. Though this line seemingly does nothing of value, it is a
+ // splint to prevent the unit test from failing on Go Tip. We suspect it is a
+ // compiler issue that will hopefully be worked out prior to our next release.
+ // Again, for all the unit tests to pass, this line is necessary and sufficient
+ // at the moment. We should reassess after the Go 1.5 release to determine
+ // if this line is still needed.
+ time.Sleep(0 * time.Millisecond)
+
outer, err := o.Parent.ToNetworkCreateMap()
if err != nil {
return nil, err
diff --git a/openstack/objectstorage/v1/containers/fixtures.go b/openstack/objectstorage/v1/containers/fixtures.go
index 9c84bce..e607352 100644
--- a/openstack/objectstorage/v1/containers/fixtures.go
+++ b/openstack/objectstorage/v1/containers/fixtures.go
@@ -55,6 +55,14 @@
"name": "marktwain"
}
]`)
+ case "janeausten":
+ fmt.Fprintf(w, `[
+ {
+ "count": 1,
+ "bytes": 14,
+ "name": "marktwain"
+ }
+ ]`)
case "marktwain":
fmt.Fprintf(w, `[]`)
default:
@@ -77,6 +85,8 @@
switch marker {
case "":
fmt.Fprintf(w, "janeausten\nmarktwain\n")
+ case "janeausten":
+ fmt.Fprintf(w, "marktwain\n")
case "marktwain":
fmt.Fprintf(w, ``)
default:
diff --git a/openstack/objectstorage/v1/containers/requests_test.go b/openstack/objectstorage/v1/containers/requests_test.go
index f650696..0ccd5a7 100644
--- a/openstack/objectstorage/v1/containers/requests_test.go
+++ b/openstack/objectstorage/v1/containers/requests_test.go
@@ -29,6 +29,18 @@
th.CheckEquals(t, count, 1)
}
+func TestListAllContainerInfo(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ HandleListContainerInfoSuccessfully(t)
+
+ allPages, err := List(fake.ServiceClient(), &ListOpts{Full: true}).AllPages()
+ th.AssertNoErr(t, err)
+ actual, err := ExtractInfo(allPages)
+ th.AssertNoErr(t, err)
+ th.CheckDeepEquals(t, ExpectedListInfo, actual)
+}
+
func TestListContainerNames(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
@@ -51,6 +63,18 @@
th.CheckEquals(t, count, 1)
}
+func TestListAllContainerNames(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ HandleListContainerNamesSuccessfully(t)
+
+ allPages, err := List(fake.ServiceClient(), &ListOpts{Full: false}).AllPages()
+ th.AssertNoErr(t, err)
+ actual, err := ExtractNames(allPages)
+ th.AssertNoErr(t, err)
+ th.CheckDeepEquals(t, ExpectedListNames, actual)
+}
+
func TestCreateContainer(t *testing.T) {
th.SetupHTTP()
defer th.TeardownHTTP()
diff --git a/openstack/orchestration/v1/stackevents/results.go b/openstack/orchestration/v1/stackevents/results.go
index bf233ae..3c8f1da 100644
--- a/openstack/orchestration/v1/stackevents/results.go
+++ b/openstack/orchestration/v1/stackevents/results.go
@@ -1,6 +1,8 @@
package stackevents
import (
+ "fmt"
+ "reflect"
"time"
"github.com/mitchellh/mapstructure"
@@ -106,7 +108,15 @@
return nil, err
}
- events := casted.(map[string]interface{})["events"].([]interface{})
+ var events []interface{}
+ switch casted.(type) {
+ case map[string]interface{}:
+ events = casted.(map[string]interface{})["events"].([]interface{})
+ case map[string][]interface{}:
+ events = casted.(map[string][]interface{})["events"]
+ default:
+ return res.Res, fmt.Errorf("Unknown type: %v", reflect.TypeOf(casted))
+ }
for i, eventRaw := range events {
event := eventRaw.(map[string]interface{})
diff --git a/openstack/orchestration/v1/stackresources/results.go b/openstack/orchestration/v1/stackresources/results.go
index 13f5dd2..69f21da 100644
--- a/openstack/orchestration/v1/stackresources/results.go
+++ b/openstack/orchestration/v1/stackresources/results.go
@@ -1,6 +1,8 @@
package stackresources
import (
+ "fmt"
+ "reflect"
"time"
"github.com/mitchellh/mapstructure"
@@ -94,7 +96,15 @@
}
err := mapstructure.Decode(casted, &response)
- resources := casted.(map[string]interface{})["resources"].([]interface{})
+ var resources []interface{}
+ switch casted.(type) {
+ case map[string]interface{}:
+ resources = casted.(map[string]interface{})["resources"].([]interface{})
+ case map[string][]interface{}:
+ resources = casted.(map[string][]interface{})["resources"]
+ default:
+ return response.Resources, fmt.Errorf("Unknown type: %v", reflect.TypeOf(casted))
+ }
for i, resourceRaw := range resources {
resource := resourceRaw.(map[string]interface{})
diff --git a/openstack/orchestration/v1/stacks/results.go b/openstack/orchestration/v1/stacks/results.go
index ff971e8..04d3f8e 100644
--- a/openstack/orchestration/v1/stacks/results.go
+++ b/openstack/orchestration/v1/stacks/results.go
@@ -2,6 +2,8 @@
import (
"encoding/json"
+ "fmt"
+ "reflect"
"time"
"github.com/mitchellh/mapstructure"
@@ -73,6 +75,8 @@
// ExtractStacks extracts and returns a slice of ListedStack. It is used while iterating
// over a stacks.List call.
func ExtractStacks(page pagination.Page) ([]ListedStack, error) {
+ casted := page.(StackPage).Body
+
var res struct {
Stacks []ListedStack `mapstructure:"stacks"`
}
@@ -82,7 +86,16 @@
return nil, err
}
- rawStacks := (((page.(StackPage).Body).(map[string]interface{}))["stacks"]).([]interface{})
+ var rawStacks []interface{}
+ switch casted.(type) {
+ case map[string]interface{}:
+ rawStacks = casted.(map[string]interface{})["stacks"].([]interface{})
+ case map[string][]interface{}:
+ rawStacks = casted.(map[string][]interface{})["stacks"]
+ default:
+ return res.Stacks, fmt.Errorf("Unknown type: %v", reflect.TypeOf(casted))
+ }
+
for i := range rawStacks {
thisStack := (rawStacks[i]).(map[string]interface{})
diff --git a/pagination/linked.go b/pagination/linked.go
index 461fa49..e9bd8de 100644
--- a/pagination/linked.go
+++ b/pagination/linked.go
@@ -59,3 +59,9 @@
}
}
}
+
+// GetBody returns the linked page's body. This method is needed to satisfy the
+// Page interface.
+func (current LinkedPageBase) GetBody() interface{} {
+ return current.Body
+}
diff --git a/pagination/linked_test.go b/pagination/linked_test.go
index 4d3248e..1ac0f73 100644
--- a/pagination/linked_test.go
+++ b/pagination/linked_test.go
@@ -105,3 +105,16 @@
t.Errorf("Expected 3 calls, but was %d", callCount)
}
}
+
+func TestAllPagesLinked(t *testing.T) {
+ pager := createLinked(t)
+ defer testhelper.TeardownHTTP()
+
+ page, err := pager.AllPages()
+ testhelper.AssertNoErr(t, err)
+
+ expected := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
+ actual, err := ExtractLinkedInts(page)
+ testhelper.AssertNoErr(t, err)
+ testhelper.CheckDeepEquals(t, expected, actual)
+}
diff --git a/pagination/marker.go b/pagination/marker.go
index e7688c2..f355afc 100644
--- a/pagination/marker.go
+++ b/pagination/marker.go
@@ -32,3 +32,9 @@
return currentURL.String(), nil
}
+
+// GetBody returns the linked page's body. This method is needed to satisfy the
+// Page interface.
+func (current MarkerPageBase) GetBody() interface{} {
+ return current.Body
+}
diff --git a/pagination/marker_test.go b/pagination/marker_test.go
index 3b1df1d..f4d55be 100644
--- a/pagination/marker_test.go
+++ b/pagination/marker_test.go
@@ -111,3 +111,16 @@
testhelper.AssertNoErr(t, err)
testhelper.AssertEquals(t, callCount, 3)
}
+
+func TestAllPagesMarker(t *testing.T) {
+ pager := createMarkerPaged(t)
+ defer testhelper.TeardownHTTP()
+
+ page, err := pager.AllPages()
+ testhelper.AssertNoErr(t, err)
+
+ expected := []string{"aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii"}
+ actual, err := ExtractMarkerStrings(page)
+ testhelper.AssertNoErr(t, err)
+ testhelper.CheckDeepEquals(t, expected, actual)
+}
diff --git a/pagination/pager.go b/pagination/pager.go
index 5c20e16..ea47c69 100644
--- a/pagination/pager.go
+++ b/pagination/pager.go
@@ -2,6 +2,10 @@
import (
"errors"
+ "fmt"
+ "net/http"
+ "reflect"
+ "strings"
"github.com/rackspace/gophercloud"
)
@@ -25,6 +29,9 @@
// IsEmpty returns true if this Page has no items in it.
IsEmpty() (bool, error)
+
+ // GetBody returns the Page Body. This is used in the `AllPages` method.
+ GetBody() interface{}
}
// Pager knows how to advance through a specific resource collection, one page at a time.
@@ -113,3 +120,105 @@
}
}
}
+
+// AllPages returns all the pages from a `List` operation in a single page,
+// allowing the user to retrieve all the pages at once.
+func (p Pager) AllPages() (Page, error) {
+ // pagesSlice holds all the pages until they get converted into as Page Body.
+ var pagesSlice []interface{}
+ // body will contain the final concatenated Page body.
+ var body reflect.Value
+
+ // Grab a test page to ascertain the page body type.
+ testPage, err := p.fetchNextPage(p.initialURL)
+ if err != nil {
+ return nil, err
+ }
+ // Store the page type so we can use reflection to create a new mega-page of
+ // that type.
+ pageType := reflect.TypeOf(testPage)
+
+ // Switch on the page body type. Recognized types are `map[string]interface{}`,
+ // `[]byte`, and `[]interface{}`.
+ switch testPage.GetBody().(type) {
+ case map[string]interface{}:
+ // key is the map key for the page body if the body type is `map[string]interface{}`.
+ var key string
+ // Iterate over the pages to concatenate the bodies.
+ err := p.EachPage(func(page Page) (bool, error) {
+ b := page.GetBody().(map[string]interface{})
+ for k := range b {
+ // If it's a linked page, we don't want the `links`, we want the other one.
+ if !strings.HasSuffix(k, "links") {
+ key = k
+ }
+ }
+ pagesSlice = append(pagesSlice, b[key].([]interface{})...)
+ return true, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ // Set body to value of type `map[string]interface{}`
+ body = reflect.MakeMap(reflect.MapOf(reflect.TypeOf(key), reflect.TypeOf(pagesSlice)))
+ body.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(pagesSlice))
+ case []byte:
+ // Iterate over the pages to concatenate the bodies.
+ err := p.EachPage(func(page Page) (bool, error) {
+ b := page.GetBody().([]byte)
+ pagesSlice = append(pagesSlice, b)
+ // seperate pages with a comma
+ pagesSlice = append(pagesSlice, []byte{10})
+ return true, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ // Remove the trailing comma.
+ pagesSlice = pagesSlice[:len(pagesSlice)-1]
+ var b []byte
+ // Combine the slice of slices in to a single slice.
+ for _, slice := range pagesSlice {
+ b = append(b, slice.([]byte)...)
+ }
+ // Set body to value of type `bytes`.
+ body = reflect.New(reflect.TypeOf(b)).Elem()
+ body.SetBytes(b)
+ case []interface{}:
+ // Iterate over the pages to concatenate the bodies.
+ err := p.EachPage(func(page Page) (bool, error) {
+ b := page.GetBody().([]interface{})
+ pagesSlice = append(pagesSlice, b...)
+ return true, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ // Set body to value of type `[]interface{}`
+ body = reflect.MakeSlice(reflect.TypeOf(pagesSlice), len(pagesSlice), len(pagesSlice))
+ for i, s := range pagesSlice {
+ body.Index(i).Set(reflect.ValueOf(s))
+ }
+ default:
+ return nil, fmt.Errorf("Page body has unrecognized type.")
+ }
+
+ // Each `Extract*` function is expecting a specific type of page coming back,
+ // otherwise the type assertion in those functions will fail. pageType is needed
+ // to create a type in this method that has the same type that the `Extract*`
+ // function is expecting and set the Body of that object to the concatenated
+ // pages.
+ page := reflect.New(pageType)
+ // Set the page body to be the concatenated pages.
+ page.Elem().FieldByName("Body").Set(body)
+ // Set any additional headers that were pass along. The `objectstorage` pacakge,
+ // for example, passes a Content-Type header.
+ h := make(http.Header)
+ for k, v := range p.Headers {
+ h.Add(k, v)
+ }
+ page.Elem().FieldByName("Header").Set(reflect.ValueOf(h))
+ // Type assert the page to a Page interface so that the type assertion in the
+ // `Extract*` methods will work.
+ return page.Elem().Interface().(Page), err
+}
diff --git a/pagination/single.go b/pagination/single.go
index 4dd3c5c..f78d4ab 100644
--- a/pagination/single.go
+++ b/pagination/single.go
@@ -7,3 +7,9 @@
func (current SinglePageBase) NextPageURL() (string, error) {
return "", nil
}
+
+// GetBody returns the single page's body. This method is needed to satisfy the
+// Page interface.
+func (current SinglePageBase) GetBody() interface{} {
+ return current.Body
+}
diff --git a/pagination/single_test.go b/pagination/single_test.go
index 8817d57..4af0fee 100644
--- a/pagination/single_test.go
+++ b/pagination/single_test.go
@@ -69,3 +69,16 @@
testhelper.CheckNoErr(t, err)
testhelper.CheckEquals(t, 1, callCount)
}
+
+func TestAllPagesSingle(t *testing.T) {
+ pager := setupSinglePaged()
+ defer testhelper.TeardownHTTP()
+
+ page, err := pager.AllPages()
+ testhelper.AssertNoErr(t, err)
+
+ expected := []int{1, 2, 3}
+ actual, err := ExtractSingleInts(page)
+ testhelper.AssertNoErr(t, err)
+ testhelper.CheckDeepEquals(t, expected, actual)
+}
diff --git a/provider_client.go b/provider_client.go
index 200ee0b..f342a5e 100644
--- a/provider_client.go
+++ b/provider_client.go
@@ -169,7 +169,6 @@
if options.MoreHeaders != nil {
for k, v := range options.MoreHeaders {
- fmt.Printf("Applying header [%s: %v]\n", k, v)
if v != "" {
req.Header.Set(k, v)
} else {
diff --git a/rackspace/compute/v2/volumeattach/delegate.go b/rackspace/compute/v2/volumeattach/delegate.go
new file mode 100644
index 0000000..c6003e0
--- /dev/null
+++ b/rackspace/compute/v2/volumeattach/delegate.go
@@ -0,0 +1,27 @@
+package volumeattach
+
+import (
+ "github.com/rackspace/gophercloud"
+ os "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach"
+ "github.com/rackspace/gophercloud/pagination"
+)
+
+// List returns a Pager that allows you to iterate over a collection of VolumeAttachments.
+func List(client *gophercloud.ServiceClient, serverID string) pagination.Pager {
+ return os.List(client, serverID)
+}
+
+// Create requests the creation of a new volume attachment on the server
+func Create(client *gophercloud.ServiceClient, serverID string, opts os.CreateOptsBuilder) os.CreateResult {
+ return os.Create(client, serverID, opts)
+}
+
+// Get returns public data about a previously created VolumeAttachment.
+func Get(client *gophercloud.ServiceClient, serverID, aID string) os.GetResult {
+ return os.Get(client, serverID, aID)
+}
+
+// Delete requests the deletion of a previous stored VolumeAttachment from the server.
+func Delete(client *gophercloud.ServiceClient, serverID, aID string) os.DeleteResult {
+ return os.Delete(client, serverID, aID)
+}
diff --git a/rackspace/compute/v2/volumeattach/delegate_test.go b/rackspace/compute/v2/volumeattach/delegate_test.go
new file mode 100644
index 0000000..e26416c
--- /dev/null
+++ b/rackspace/compute/v2/volumeattach/delegate_test.go
@@ -0,0 +1,66 @@
+package volumeattach
+
+import (
+ "testing"
+
+ os "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach"
+ "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()
+ os.HandleListSuccessfully(t)
+ serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0"
+
+ count := 0
+ err := List(client.ServiceClient(), serverId).EachPage(func(page pagination.Page) (bool, error) {
+ count++
+ actual, err := os.ExtractVolumeAttachments(page)
+ th.AssertNoErr(t, err)
+ th.CheckDeepEquals(t, os.ExpectedVolumeAttachmentSlice, actual)
+
+ return true, nil
+ })
+ th.AssertNoErr(t, err)
+ th.CheckEquals(t, 1, count)
+}
+
+func TestCreate(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ os.HandleCreateSuccessfully(t)
+ serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0"
+
+ actual, err := Create(client.ServiceClient(), serverId, os.CreateOpts{
+ Device: "/dev/vdc",
+ VolumeID: "a26887c6-c47b-4654-abb5-dfadf7d3f804",
+ }).Extract()
+ th.AssertNoErr(t, err)
+ th.CheckDeepEquals(t, &os.CreatedVolumeAttachment, actual)
+}
+
+func TestGet(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ os.HandleGetSuccessfully(t)
+ aId := "a26887c6-c47b-4654-abb5-dfadf7d3f804"
+ serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0"
+
+ actual, err := Get(client.ServiceClient(), serverId, aId).Extract()
+ th.AssertNoErr(t, err)
+ th.CheckDeepEquals(t, &os.SecondVolumeAttachment, actual)
+}
+
+func TestDelete(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ os.HandleDeleteSuccessfully(t)
+ aId := "a26887c6-c47b-4654-abb5-dfadf7d3f804"
+ serverId := "4d8c3732-a248-40ed-bebc-539a6ffd25c0"
+
+ err := Delete(client.ServiceClient(), serverId, aId).ExtractErr()
+ th.AssertNoErr(t, err)
+}
diff --git a/rackspace/compute/v2/volumeattach/doc.go b/rackspace/compute/v2/volumeattach/doc.go
new file mode 100644
index 0000000..2164908
--- /dev/null
+++ b/rackspace/compute/v2/volumeattach/doc.go
@@ -0,0 +1,3 @@
+// Package volumeattach provides the ability to attach and detach volume
+// to instances to Rackspace servers
+package volumeattach