DNS Zones: List / Get (#271)
* Add Zone List / Get Support
* Addressing code review comments
* Adding v2 to DNS client
* List / Get unit tests plus updates to results for unit tests to work.
* DNS v2 List acceptance tests
* add failing unit test for dns v2 allpages
* Changing acceptance test for DNS v2 to use AllPages
* Adding empty zones.go file for package requirements
* Change ttl back to int
* DNS v2 Zones ListOpts
diff --git a/acceptance/clients/clients.go b/acceptance/clients/clients.go
index 8bf4aa3..aa57497 100644
--- a/acceptance/clients/clients.go
+++ b/acceptance/clients/clients.go
@@ -174,6 +174,25 @@
})
}
+// NewDNSV2Client returns a *ServiceClient for making calls
+// to the OpenStack Compute v2 API. An error will be returned
+// if authentication or client creation was not possible.
+func NewDNSV2Client() (*gophercloud.ServiceClient, error) {
+ ao, err := openstack.AuthOptionsFromEnv()
+ if err != nil {
+ return nil, err
+ }
+
+ client, err := openstack.AuthenticatedClient(ao)
+ if err != nil {
+ return nil, err
+ }
+
+ return openstack.NewDNSV2(client, gophercloud.EndpointOpts{
+ Region: os.Getenv("OS_REGION_NAME"),
+ })
+}
+
// NewIdentityV2Client returns a *ServiceClient for making calls
// to the OpenStack Identity v2 API. An error will be returned
// if authentication or client creation was not possible.
diff --git a/acceptance/openstack/dns/v2/zones.go b/acceptance/openstack/dns/v2/zones.go
new file mode 100644
index 0000000..5ec3cc8
--- /dev/null
+++ b/acceptance/openstack/dns/v2/zones.go
@@ -0,0 +1 @@
+package v2
diff --git a/acceptance/openstack/dns/v2/zones_test.go b/acceptance/openstack/dns/v2/zones_test.go
new file mode 100644
index 0000000..add964d
--- /dev/null
+++ b/acceptance/openstack/dns/v2/zones_test.go
@@ -0,0 +1,33 @@
+// +build acceptance dns zones
+
+package v2
+
+import (
+ "testing"
+
+ "github.com/gophercloud/gophercloud/acceptance/clients"
+ "github.com/gophercloud/gophercloud/acceptance/tools"
+ "github.com/gophercloud/gophercloud/openstack/dns/v2/zones"
+)
+
+func TestZonesList(t *testing.T) {
+ client, err := clients.NewDNSV2Client()
+ if err != nil {
+ t.Fatalf("Unable to create a DNS client: %v", err)
+ }
+
+ var allZones []zones.Zone
+ allPages, err := zones.List(client, nil).AllPages()
+ if err != nil {
+ t.Fatalf("Unable to retrieve zones: %v", err)
+ }
+
+ allZones, err = zones.ExtractZones(allPages)
+ if err != nil {
+ t.Fatalf("Unable to extract zones: %v", err)
+ }
+
+ for _, zone := range allZones {
+ tools.PrintResource(t, &zone)
+ }
+}
diff --git a/openstack/client.go b/openstack/client.go
index 6e61944..2d30cc6 100644
--- a/openstack/client.go
+++ b/openstack/client.go
@@ -310,6 +310,19 @@
return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil
}
+// NewDNSV2 creates a ServiceClient that may be used to access the v2 DNS service.
+func NewDNSV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
+ eo.ApplyDefaults("dns")
+ url, err := client.EndpointLocator(eo)
+ if err != nil {
+ return nil, err
+ }
+ return &gophercloud.ServiceClient{
+ ProviderClient: client,
+ Endpoint: url,
+ ResourceBase: url + "v2/"}, nil
+}
+
// NewImageServiceV2 creates a ServiceClient that may be used to access the v2 image service.
func NewImageServiceV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
eo.ApplyDefaults("image")
diff --git a/openstack/dns/v2/zones/doc.go b/openstack/dns/v2/zones/doc.go
new file mode 100644
index 0000000..1302cb9
--- /dev/null
+++ b/openstack/dns/v2/zones/doc.go
@@ -0,0 +1,6 @@
+// Package tokens provides information and interaction with the zone API
+// resource for the OpenStack DNS service.
+//
+// For more information, see:
+// http://developer.openstack.org/api-ref/dns/#zone
+package zones
diff --git a/openstack/dns/v2/zones/requests.go b/openstack/dns/v2/zones/requests.go
new file mode 100644
index 0000000..6db7831
--- /dev/null
+++ b/openstack/dns/v2/zones/requests.go
@@ -0,0 +1,57 @@
+package zones
+
+import (
+ "github.com/gophercloud/gophercloud"
+ "github.com/gophercloud/gophercloud/pagination"
+)
+
+type ListOptsBuilder interface {
+ ToZoneListQuery() (string, error)
+}
+
+// ListOpts allows the filtering and sorting of paginated collections through
+// the API. Filtering is achieved by passing in struct field values that map to
+// the server attributes you want to see returned. Marker and Limit are used
+// for pagination.
+// https://developer.openstack.org/api-ref/dns/
+type ListOpts struct {
+ // Integer value for the limit of values to return.
+ Limit int `q:"limit"`
+
+ // UUID of the zone at which you want to set a marker.
+ Marker string `q:"marker"`
+
+ Description string `q:"description"`
+ Email string `q:"email"`
+ Name string `q:"name"`
+ SortDir string `q:"sort_dir"`
+ SortKey string `q:"sort_key"`
+ Status string `q:"status"`
+ TTL int `q:"ttl"`
+ Type string `q:"type"`
+}
+
+func (opts ListOpts) ToZoneListQuery() (string, error) {
+ q, err := gophercloud.BuildQueryString(opts)
+ return q.String(), err
+}
+
+func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {
+ url := listURL(client)
+ if opts != nil {
+ query, err := opts.ToZoneListQuery()
+ if err != nil {
+ return pagination.Pager{Err: err}
+ }
+ url += query
+ }
+ return pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {
+ return ZonePage{pagination.LinkedPageBase{PageResult: r}}
+ })
+}
+
+// Get returns additional information about a zone, given its ID.
+func Get(client *gophercloud.ServiceClient, zoneID string) (r GetResult) {
+ _, r.Err = client.Get(zoneURL(client, zoneID), &r.Body, nil)
+ return
+}
diff --git a/openstack/dns/v2/zones/results.go b/openstack/dns/v2/zones/results.go
new file mode 100644
index 0000000..4693b09
--- /dev/null
+++ b/openstack/dns/v2/zones/results.go
@@ -0,0 +1,144 @@
+package zones
+
+import (
+ "encoding/json"
+ "strconv"
+ "time"
+
+ "github.com/gophercloud/gophercloud"
+ "github.com/gophercloud/gophercloud/pagination"
+)
+
+type commonResult struct {
+ gophercloud.Result
+}
+
+// Extract interprets a GetResult, CreateResult or UpdateResult as a concrete Zone.
+// An error is returned if the original call or the extraction failed.
+func (r commonResult) Extract() (*Zone, error) {
+ var s *Zone
+ err := r.ExtractInto(&s)
+ return s, err
+}
+
+// GetResult is the deferred result of a Get call.
+type GetResult struct {
+ commonResult
+}
+
+// ZonePage is a single page of Zone results.
+type ZonePage struct {
+ pagination.LinkedPageBase
+}
+
+// IsEmpty returns true if the page contains no results.
+func (r ZonePage) IsEmpty() (bool, error) {
+ s, err := ExtractZones(r)
+ return len(s) == 0, err
+}
+
+// ExtractZones extracts a slice of Services from a Collection acquired from List.
+func ExtractZones(r pagination.Page) ([]Zone, error) {
+ var s struct {
+ Zones []Zone `json:"zones"`
+ }
+ err := (r.(ZonePage)).ExtractInto(&s)
+ return s.Zones, err
+}
+
+// Zone represents a DNS zone.
+type Zone struct {
+ // ID uniquely identifies this zone amongst all other zones, including those not accessible to the current tenant.
+ ID string `json:"id"`
+
+ // PoolID is the ID for the pool hosting this zone.
+ PoolID string `json:"pool_id"`
+
+ // ProjectID identifies the project/tenant owning this resource.
+ ProjectID string `json:"project_id"`
+
+ // Name is the DNS Name for the zone.
+ Name string `json:"name"`
+
+ // Email for the zone. Used in SOA records for the zone.
+ Email string `json:"email"`
+
+ // Description for this zone.
+ Description string `json:"description"`
+
+ // TTL is the Time to Live for the zone.
+ TTL int `json:"ttl"`
+
+ // Serial is the current serial number for the zone.
+ Serial int `json:"-"`
+
+ // Status is the status of the resource.
+ Status string `json:"status"`
+
+ // Action is the current action in progress on the resource.
+ Action string `json:"action"`
+
+ // Version of the resource.
+ Version int `json:"version"`
+
+ // Attributes for the zone.
+ Attributes map[string]string `json:"attributes"`
+
+ // Type of zone. Primary is controlled by Designate.
+ // Secondary zones are slaved from another DNS Server.
+ // Defaults to Primary.
+ Type string `json:"type"`
+
+ // Masters is the servers for slave servers to get DNS information from.
+ Masters []string `json:"masters"`
+
+ // CreatedAt is the date when the zone was created.
+ CreatedAt time.Time `json:"-"`
+
+ // UpdatedAt is the date when the last change was made to the zone.
+ UpdatedAt time.Time `json:"-"`
+
+ // TransferredAt is the last time an update was retrieved from the master servers.
+ TransferredAt time.Time `json:"-"`
+
+ // Links includes HTTP references to the itself, useful for passing along to other APIs that might want a server reference.
+ Links map[string]interface{} `json:"links"`
+}
+
+func (r *Zone) UnmarshalJSON(b []byte) error {
+ type tmp Zone
+ var s struct {
+ tmp
+ CreatedAt gophercloud.JSONRFC3339MilliNoZ `json:"created_at"`
+ UpdatedAt gophercloud.JSONRFC3339MilliNoZ `json:"updated_at"`
+ TransferredAt gophercloud.JSONRFC3339MilliNoZ `json:"transferred_at"`
+ Serial interface{} `json:"serial"`
+ }
+ err := json.Unmarshal(b, &s)
+ if err != nil {
+ return err
+ }
+ *r = Zone(s.tmp)
+
+ r.CreatedAt = time.Time(s.CreatedAt)
+ r.UpdatedAt = time.Time(s.UpdatedAt)
+ r.TransferredAt = time.Time(s.TransferredAt)
+
+ switch t := s.Serial.(type) {
+ case float64:
+ r.Serial = int(t)
+ case string:
+ switch t {
+ case "":
+ r.Serial = 0
+ default:
+ serial, err := strconv.ParseFloat(t, 64)
+ if err != nil {
+ return err
+ }
+ r.Serial = int(serial)
+ }
+ }
+
+ return err
+}
diff --git a/openstack/dns/v2/zones/testing/doc.go b/openstack/dns/v2/zones/testing/doc.go
new file mode 100644
index 0000000..54a0d21
--- /dev/null
+++ b/openstack/dns/v2/zones/testing/doc.go
@@ -0,0 +1,2 @@
+// dns_zones_v2
+package testing
diff --git a/openstack/dns/v2/zones/testing/fixtures.go b/openstack/dns/v2/zones/testing/fixtures.go
new file mode 100644
index 0000000..473ca90
--- /dev/null
+++ b/openstack/dns/v2/zones/testing/fixtures.go
@@ -0,0 +1,165 @@
+package testing
+
+import (
+ "fmt"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/gophercloud/gophercloud"
+ "github.com/gophercloud/gophercloud/openstack/dns/v2/zones"
+ th "github.com/gophercloud/gophercloud/testhelper"
+ "github.com/gophercloud/gophercloud/testhelper/client"
+)
+
+// List Output is a sample response to a List call.
+const ListOutput = `
+{
+ "links": {
+ "self": "http://example.com:9001/v2/zones"
+ },
+ "metadata": {
+ "total_count": 2
+ },
+ "zones": [
+ {
+ "id": "a86dba58-0043-4cc6-a1bb-69d5e86f3ca3",
+ "pool_id": "572ba08c-d929-4c70-8e42-03824bb24ca2",
+ "project_id": "4335d1f0-f793-11e2-b778-0800200c9a66",
+ "name": "example.org.",
+ "email": "joe@example.org",
+ "ttl": 7200,
+ "serial": 1404757531,
+ "status": "ACTIVE",
+ "action": "CREATE",
+ "description": "This is an example zone.",
+ "masters": [],
+ "type": "PRIMARY",
+ "transferred_at": null,
+ "version": 1,
+ "created_at": "2014-07-07T18:25:31.275934",
+ "updated_at": null,
+ "links": {
+ "self": "https://127.0.0.1:9001/v2/zones/a86dba58-0043-4cc6-a1bb-69d5e86f3ca3"
+ }
+ },
+ {
+ "id": "34c4561c-9205-4386-9df5-167436f5a222",
+ "pool_id": "572ba08c-d929-4c70-8e42-03824bb24ca2",
+ "project_id": "4335d1f0-f793-11e2-b778-0800200c9a66",
+ "name": "foo.example.com.",
+ "email": "joe@foo.example.com",
+ "ttl": 7200,
+ "serial": 1488053571,
+ "status": "ACTIVE",
+ "action": "CREATE",
+ "description": "This is another example zone.",
+ "masters": ["example.com."],
+ "type": "PRIMARY",
+ "transferred_at": null,
+ "version": 1,
+ "created_at": "2014-07-07T18:25:31.275934",
+ "updated_at": "2015-02-25T20:23:01.234567",
+ "links": {
+ "self": "https://127.0.0.1:9001/v2/zones/34c4561c-9205-4386-9df5-167436f5a222"
+ }
+ }
+ ]
+}
+`
+
+// GetOutput is a sample response to a Get call.
+const GetOutput = `
+{
+ "id": "a86dba58-0043-4cc6-a1bb-69d5e86f3ca3",
+ "pool_id": "572ba08c-d929-4c70-8e42-03824bb24ca2",
+ "project_id": "4335d1f0-f793-11e2-b778-0800200c9a66",
+ "name": "example.org.",
+ "email": "joe@example.org",
+ "ttl": 7200,
+ "serial": 1404757531,
+ "status": "ACTIVE",
+ "action": "CREATE",
+ "description": "This is an example zone.",
+ "masters": [],
+ "type": "PRIMARY",
+ "transferred_at": null,
+ "version": 1,
+ "created_at": "2014-07-07T18:25:31.275934",
+ "updated_at": null,
+ "links": {
+ "self": "https://127.0.0.1:9001/v2/zones/a86dba58-0043-4cc6-a1bb-69d5e86f3ca3"
+ }
+}
+`
+
+// FirstZone is the first result in ListOutput
+var FirstZoneCreatedAt, _ = time.Parse(gophercloud.RFC3339MilliNoZ, "2014-07-07T18:25:31.275934")
+var FirstZone = zones.Zone{
+ ID: "a86dba58-0043-4cc6-a1bb-69d5e86f3ca3",
+ PoolID: "572ba08c-d929-4c70-8e42-03824bb24ca2",
+ ProjectID: "4335d1f0-f793-11e2-b778-0800200c9a66",
+ Name: "example.org.",
+ Email: "joe@example.org",
+ TTL: 7200,
+ Serial: 1404757531,
+ Status: "ACTIVE",
+ Action: "CREATE",
+ Description: "This is an example zone.",
+ Masters: []string{},
+ Type: "PRIMARY",
+ Version: 1,
+ CreatedAt: FirstZoneCreatedAt,
+ Links: map[string]interface{}{
+ "self": "https://127.0.0.1:9001/v2/zones/a86dba58-0043-4cc6-a1bb-69d5e86f3ca3",
+ },
+}
+
+var SecondZoneCreatedAt, _ = time.Parse(gophercloud.RFC3339MilliNoZ, "2014-07-07T18:25:31.275934")
+var SecondZoneUpdatedAt, _ = time.Parse(gophercloud.RFC3339MilliNoZ, "2015-02-25T20:23:01.234567")
+var SecondZone = zones.Zone{
+ ID: "34c4561c-9205-4386-9df5-167436f5a222",
+ PoolID: "572ba08c-d929-4c70-8e42-03824bb24ca2",
+ ProjectID: "4335d1f0-f793-11e2-b778-0800200c9a66",
+ Name: "foo.example.com.",
+ Email: "joe@foo.example.com",
+ TTL: 7200,
+ Serial: 1488053571,
+ Status: "ACTIVE",
+ Action: "CREATE",
+ Description: "This is another example zone.",
+ Masters: []string{"example.com."},
+ Type: "PRIMARY",
+ Version: 1,
+ CreatedAt: SecondZoneCreatedAt,
+ UpdatedAt: SecondZoneUpdatedAt,
+ Links: map[string]interface{}{
+ "self": "https://127.0.0.1:9001/v2/zones/34c4561c-9205-4386-9df5-167436f5a222",
+ },
+}
+
+// ExpectedZonesSlice is the slice of results that should be parsed
+// from ListOutput, in the expected order.
+var ExpectedZonesSlice = []zones.Zone{FirstZone, SecondZone}
+
+// HandleListSuccessfully configures the test server to respond to a List request.
+func HandleListSuccessfully(t *testing.T) {
+ th.Mux.HandleFunc("/zones", 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 List request.
+func HandleGetSuccessfully(t *testing.T) {
+ th.Mux.HandleFunc("/zones/a86dba58-0043-4cc6-a1bb-69d5e86f3ca3", 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/dns/v2/zones/testing/requests_test.go b/openstack/dns/v2/zones/testing/requests_test.go
new file mode 100644
index 0000000..b7dd667
--- /dev/null
+++ b/openstack/dns/v2/zones/testing/requests_test.go
@@ -0,0 +1,50 @@
+package testing
+
+import (
+ "testing"
+
+ "github.com/gophercloud/gophercloud/openstack/dns/v2/zones"
+ "github.com/gophercloud/gophercloud/pagination"
+ th "github.com/gophercloud/gophercloud/testhelper"
+ "github.com/gophercloud/gophercloud/testhelper/client"
+)
+
+func TestList(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ HandleListSuccessfully(t)
+
+ count := 0
+ err := zones.List(client.ServiceClient(), nil).EachPage(func(page pagination.Page) (bool, error) {
+ count++
+ actual, err := zones.ExtractZones(page)
+ th.AssertNoErr(t, err)
+ th.CheckDeepEquals(t, ExpectedZonesSlice, actual)
+
+ return true, nil
+ })
+ th.AssertNoErr(t, err)
+ th.CheckEquals(t, 1, count)
+}
+
+func TestListAllPages(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ HandleListSuccessfully(t)
+
+ allPages, err := zones.List(client.ServiceClient(), nil).AllPages()
+ th.AssertNoErr(t, err)
+ allZones, err := zones.ExtractZones(allPages)
+ th.AssertNoErr(t, err)
+ th.CheckEquals(t, 2, len(allZones))
+}
+
+func TestGet(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+ HandleGetSuccessfully(t)
+
+ actual, err := zones.Get(client.ServiceClient(), "a86dba58-0043-4cc6-a1bb-69d5e86f3ca3").Extract()
+ th.AssertNoErr(t, err)
+ th.CheckDeepEquals(t, &FirstZone, actual)
+}
diff --git a/openstack/dns/v2/zones/urls.go b/openstack/dns/v2/zones/urls.go
new file mode 100644
index 0000000..0cd4796
--- /dev/null
+++ b/openstack/dns/v2/zones/urls.go
@@ -0,0 +1,11 @@
+package zones
+
+import "github.com/gophercloud/gophercloud"
+
+func listURL(c *gophercloud.ServiceClient) string {
+ return c.ServiceURL("zones")
+}
+
+func zoneURL(c *gophercloud.ServiceClient, zoneID string) string {
+ return c.ServiceURL("zones", zoneID)
+}