Rename lb dir to lbs
diff --git a/rackspace/lb/lbs/doc.go b/rackspace/lb/lbs/doc.go
new file mode 100644
index 0000000..185ebbf
--- /dev/null
+++ b/rackspace/lb/lbs/doc.go
@@ -0,0 +1,6 @@
+/*
+A load balancer is a logical device which belongs to a cloud account. It is
+used to distribute workloads between multiple back-end systems or services,
+based on the criteria defined as part of its configuration.
+*/
+package lbs
diff --git a/rackspace/lb/lbs/fixtures.go b/rackspace/lb/lbs/fixtures.go
new file mode 100644
index 0000000..5178eee
--- /dev/null
+++ b/rackspace/lb/lbs/fixtures.go
@@ -0,0 +1,258 @@
+package lbs
+
+import (
+ "fmt"
+ "net/http"
+ "strconv"
+ "testing"
+
+ th "github.com/rackspace/gophercloud/testhelper"
+ fake "github.com/rackspace/gophercloud/testhelper/client"
+)
+
+func mockListLBResponse(t *testing.T) {
+ th.Mux.HandleFunc("/loadbalancers", 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, `
+{
+ "loadBalancers": [
+ {
+ "name": "lb-site1",
+ "id": 71,
+ "protocol": "HTTP",
+ "port": 80,
+ "algorithm": "RANDOM",
+ "status": "ACTIVE",
+ "nodeCount": 3,
+ "virtualIps": [
+ {
+ "id": 403,
+ "address": "206.55.130.1",
+ "type": "PUBLIC",
+ "ipVersion": "IPV4"
+ }
+ ],
+ "created": {
+ "time": "2010-11-30T03:23:42Z"
+ },
+ "updated": {
+ "time": "2010-11-30T03:23:44Z"
+ }
+ }
+ ]
+}
+ `)
+ })
+}
+
+func mockCreateLBResponse(t *testing.T) {
+ th.Mux.HandleFunc("/loadbalancers", func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "POST")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+
+ th.TestJSONRequest(t, r, `
+{
+ "loadBalancer": {
+ "name": "a-new-loadbalancer",
+ "port": 80,
+ "protocol": "HTTP",
+ "virtualIps": [
+ {
+ "id": 2341
+ },
+ {
+ "id": 900001
+ }
+ ],
+ "nodes": [
+ {
+ "address": "10.1.1.1",
+ "port": 80,
+ "condition": "ENABLED"
+ }
+ ]
+ }
+}
+ `)
+
+ w.Header().Add("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+
+ fmt.Fprintf(w, `
+{
+ "loadBalancer": {
+ "name": "a-new-loadbalancer",
+ "id": 144,
+ "protocol": "HTTP",
+ "halfClosed": false,
+ "port": 83,
+ "algorithm": "RANDOM",
+ "status": "BUILD",
+ "timeout": 30,
+ "cluster": {
+ "name": "ztm-n01.staging1.lbaas.rackspace.net"
+ },
+ "nodes": [
+ {
+ "address": "10.1.1.1",
+ "id": 653,
+ "port": 80,
+ "status": "ONLINE",
+ "condition": "ENABLED",
+ "weight": 1
+ }
+ ],
+ "virtualIps": [
+ {
+ "address": "206.10.10.210",
+ "id": 39,
+ "type": "PUBLIC",
+ "ipVersion": "IPV4"
+ },
+ {
+ "address": "2001:4801:79f1:0002:711b:be4c:0000:0021",
+ "id": 900001,
+ "type": "PUBLIC",
+ "ipVersion": "IPV6"
+ }
+ ],
+ "created": {
+ "time": "2011-04-13T14:18:07Z"
+ },
+ "updated": {
+ "time": "2011-04-13T14:18:07Z"
+ },
+ "connectionLogging": {
+ "enabled": false
+ }
+ }
+}
+ `)
+ })
+}
+
+func mockBatchDeleteLBResponse(t *testing.T, ids []int) {
+ th.Mux.HandleFunc("/loadbalancers", func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "DELETE")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+
+ r.ParseForm()
+
+ for k, v := range ids {
+ fids := r.Form["id"]
+ th.AssertEquals(t, strconv.Itoa(v), fids[k])
+ }
+
+ w.WriteHeader(http.StatusAccepted)
+ })
+}
+
+func mockDeleteLBResponse(t *testing.T, id int) {
+ th.Mux.HandleFunc("/loadbalancers/"+strconv.Itoa(id), 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 mockGetLBResponse(t *testing.T, id int) {
+ th.Mux.HandleFunc("/loadbalancers/"+strconv.Itoa(id), 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, `
+{
+ "loadBalancer": {
+ "id": 2000,
+ "name": "sample-loadbalancer",
+ "protocol": "HTTP",
+ "port": 80,
+ "algorithm": "RANDOM",
+ "status": "ACTIVE",
+ "timeout": 30,
+ "connectionLogging": {
+ "enabled": true
+ },
+ "virtualIps": [
+ {
+ "id": 1000,
+ "address": "206.10.10.210",
+ "type": "PUBLIC",
+ "ipVersion": "IPV4"
+ }
+ ],
+ "nodes": [
+ {
+ "id": 1041,
+ "address": "10.1.1.1",
+ "port": 80,
+ "condition": "ENABLED",
+ "status": "ONLINE"
+ },
+ {
+ "id": 1411,
+ "address": "10.1.1.2",
+ "port": 80,
+ "condition": "ENABLED",
+ "status": "ONLINE"
+ }
+ ],
+ "sessionPersistence": {
+ "persistenceType": "HTTP_COOKIE"
+ },
+ "connectionThrottle": {
+ "minConnections": 10,
+ "maxConnections": 100,
+ "maxConnectionRate": 50,
+ "rateInterval": 60
+ },
+ "cluster": {
+ "name": "c1.dfw1"
+ },
+ "created": {
+ "time": "2010-11-30T03:23:42Z"
+ },
+ "updated": {
+ "time": "2010-11-30T03:23:44Z"
+ },
+ "sourceAddresses": {
+ "ipv6Public": "2001:4801:79f1:1::1/64",
+ "ipv4Servicenet": "10.0.0.0",
+ "ipv4Public": "10.12.99.28"
+ }
+ }
+}
+ `)
+ })
+}
+
+func mockUpdateLBResponse(t *testing.T, id int) {
+ th.Mux.HandleFunc("/loadbalancers/"+strconv.Itoa(id), func(w http.ResponseWriter, r *http.Request) {
+ th.TestMethod(t, r, "PUT")
+ th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
+
+ th.TestJSONRequest(t, r, `
+{
+ "loadBalancer": {
+ "name": "a-new-loadbalancer",
+ "protocol": "TCP",
+ "halfClosed": true,
+ "algorithm": "RANDOM",
+ "port": 8080,
+ "timeout": 100,
+ "httpsRedirect": false
+ }
+}
+ `)
+
+ w.WriteHeader(http.StatusOK)
+ })
+}
diff --git a/rackspace/lb/lbs/requests.go b/rackspace/lb/lbs/requests.go
new file mode 100644
index 0000000..98484e9
--- /dev/null
+++ b/rackspace/lb/lbs/requests.go
@@ -0,0 +1,339 @@
+package lbs
+
+import (
+ "errors"
+ "strconv"
+
+ "github.com/racker/perigee"
+
+ "github.com/rackspace/gophercloud"
+ "github.com/rackspace/gophercloud/pagination"
+)
+
+// ListOptsBuilder allows extensions to add additional parameters to the
+// List request.
+type ListOptsBuilder interface {
+ ToLBListQuery() (string, error)
+}
+
+// ListOpts allows the filtering and sorting of paginated collections through
+// the API.
+type ListOpts struct {
+ ChangesSince string `q:"changes-since"`
+ Status Status `q:"status"`
+ NodeAddr string `q:"nodeaddress"`
+ Marker string `q:"marker"`
+ Limit int `q:"limit"`
+}
+
+// ToLBListQuery formats a ListOpts into a query string.
+func (opts ListOpts) ToLBListQuery() (string, error) {
+ q, err := gophercloud.BuildQueryString(opts)
+ if err != nil {
+ return "", err
+ }
+ return q.String(), nil
+}
+
+func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {
+ url := rootURL(client)
+ if opts != nil {
+ query, err := opts.ToLBListQuery()
+ if err != nil {
+ return pagination.Pager{Err: err}
+ }
+ url += query
+ }
+
+ return pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {
+ return LBPage{pagination.LinkedPageBase{PageResult: r}}
+ })
+}
+
+type enabledState *bool
+
+var (
+ iTrue = true
+ iFalse = false
+
+ Enabled enabledState = &iTrue
+ Disabled enabledState = &iFalse
+)
+
+// CreateOptsBuilder is the interface options structs have to satisfy in order
+// to be used in the main Create operation in this package. Since many
+// extensions decorate or modify the common logic, it is useful for them to
+// satisfy a basic interface in order for them to be used.
+type CreateOptsBuilder interface {
+ ToLBCreateMap() (map[string]interface{}, error)
+}
+
+// CreateOpts is the common options struct used in this package's Create
+// operation.
+type CreateOpts struct {
+ // Required - name of the load balancer to create. The name must be 128
+ // characters or fewer in length, and all UTF-8 characters are valid.
+ Name string
+
+ // Optional - nodes to be added.
+ Nodes []Node
+
+ // Required - protocol of the service that is being load balanced.
+ Protocol Protocol
+
+ // Optional - enables or disables Half-Closed support for the load balancer.
+ // Half-Closed support provides the ability for one end of the connection to
+ // terminate its output, while still receiving data from the other end. Only
+ // available for TCP/TCP_CLIENT_FIRST protocols.
+ HalfClosed enabledState
+
+ // Optional - the type of virtual IPs you want associated with the load
+ // balancer.
+ VIPs []VIP
+
+ // Optional - the access list management feature allows fine-grained network
+ // access controls to be applied to the load balancer virtual IP address.
+ AccessList string
+
+ // Optional - algorithm that defines how traffic should be directed between
+ // back-end nodes.
+ Algorithm Algorithm
+
+ // Optional - current connection logging configuration.
+ ConnectionLogging *ConnectionLogging
+
+ // Optional - specifies a limit on the number of connections per IP address
+ // to help mitigate malicious or abusive traffic to your applications.
+ //??? ConnThrottle string
+
+ //??? HealthMonitor string
+
+ // Optional - arbitrary information that can be associated with each LB.
+ Metadata map[string]interface{}
+
+ // Optional - port number for the service you are load balancing.
+ Port int
+
+ // Optional - the timeout value for the load balancer and communications with
+ // its nodes. Defaults to 30 seconds with a maximum of 120 seconds.
+ Timeout int
+
+ // Optional - specifies whether multiple requests from clients are directed
+ // to the same node.
+ //??? SessionPersistence
+
+ // Optional - enables or disables HTTP to HTTPS redirection for the load
+ // balancer. When enabled, any HTTP request returns status code 301 (Moved
+ // Permanently), and the requester is redirected to the requested URL via the
+ // HTTPS protocol on port 443. For example, http://example.com/page.html
+ // would be redirected to https://example.com/page.html. Only available for
+ // HTTPS protocol (port=443), or HTTP protocol with a properly configured SSL
+ // termination (secureTrafficOnly=true, securePort=443).
+ HTTPSRedirect enabledState
+}
+
+var (
+ errNameRequired = errors.New("Name is a required attribute")
+ errTimeoutExceeded = errors.New("Timeout must be less than 120")
+)
+
+// ToLBCreateMap casts a CreateOpts struct to a map.
+func (opts CreateOpts) ToLBCreateMap() (map[string]interface{}, error) {
+ lb := make(map[string]interface{})
+
+ if opts.Name == "" {
+ return lb, errNameRequired
+ }
+ if opts.Timeout > 120 {
+ return lb, errTimeoutExceeded
+ }
+
+ lb["name"] = opts.Name
+
+ if len(opts.Nodes) > 0 {
+ nodes := []map[string]interface{}{}
+ for _, n := range opts.Nodes {
+ nodes = append(nodes, map[string]interface{}{
+ "address": n.Address,
+ "port": n.Port,
+ "condition": n.Condition,
+ })
+ }
+ lb["nodes"] = nodes
+ }
+
+ if opts.Protocol != "" {
+ lb["protocol"] = opts.Protocol
+ }
+ if opts.HalfClosed != nil {
+ lb["halfClosed"] = opts.HalfClosed
+ }
+
+ if len(opts.VIPs) > 0 {
+
+ lb["virtualIps"] = opts.VIPs
+ }
+
+ // if opts.AccessList != "" {
+ // lb["accessList"] = opts.AccessList
+ // }
+ if opts.Algorithm != "" {
+ lb["algorithm"] = opts.Algorithm
+ }
+ if opts.ConnectionLogging != nil {
+ lb["connectionLogging"] = &opts.ConnectionLogging
+ }
+ // if opts.ConnThrottle != "" {
+ // lb["connectionThrottle"] = opts.ConnThrottle
+ // }
+ // if opts.HealthMonitor != "" {
+ // lb["healthMonitor"] = opts.HealthMonitor
+ // }
+ if len(opts.Metadata) != 0 {
+ lb["metadata"] = opts.Metadata
+ }
+ if opts.Port > 0 {
+ lb["port"] = opts.Port
+ }
+ if opts.Timeout > 0 {
+ lb["timeout"] = opts.Timeout
+ }
+ // if opts.SessionPersistence != "" {
+ // lb["sessionPersistence"] = opts.SessionPersistence
+ // }
+ if opts.HTTPSRedirect != nil {
+ lb["httpsRedirect"] = &opts.HTTPSRedirect
+ }
+
+ return map[string]interface{}{"loadBalancer": lb}, nil
+}
+
+func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult {
+ var res CreateResult
+
+ reqBody, err := opts.ToLBCreateMap()
+ if err != nil {
+ res.Err = err
+ return res
+ }
+
+ _, res.Err = perigee.Request("POST", rootURL(c), perigee.Options{
+ MoreHeaders: c.AuthenticatedHeaders(),
+ ReqBody: &reqBody,
+ Results: &res.Body,
+ OkCodes: []int{200},
+ })
+
+ return res
+}
+
+func Get(c *gophercloud.ServiceClient, id int) GetResult {
+ var res GetResult
+
+ _, res.Err = perigee.Request("GET", resourceURL(c, id), perigee.Options{
+ MoreHeaders: c.AuthenticatedHeaders(),
+ Results: &res.Body,
+ OkCodes: []int{200},
+ })
+
+ return res
+}
+
+func BulkDelete(c *gophercloud.ServiceClient, ids []int) DeleteResult {
+ var res DeleteResult
+
+ url := rootURL(c)
+ for k, v := range ids {
+ if k == 0 {
+ url += "?"
+ } else {
+ url += "&"
+ }
+ url += "id=" + strconv.Itoa(v)
+ }
+
+ _, res.Err = perigee.Request("DELETE", url, perigee.Options{
+ MoreHeaders: c.AuthenticatedHeaders(),
+ OkCodes: []int{202},
+ })
+
+ return res
+}
+
+func Delete(c *gophercloud.ServiceClient, id int) DeleteResult {
+ var res DeleteResult
+
+ _, res.Err = perigee.Request("DELETE", resourceURL(c, id), perigee.Options{
+ MoreHeaders: c.AuthenticatedHeaders(),
+ OkCodes: []int{202},
+ })
+
+ return res
+}
+
+type UpdateOptsBuilder interface {
+ ToLBUpdateMap() (map[string]interface{}, error)
+}
+
+type UpdateOpts struct {
+ Name string
+
+ Protocol Protocol
+
+ HalfClosed enabledState
+
+ Algorithm Algorithm
+
+ Port int
+
+ Timeout int
+
+ HTTPSRedirect enabledState
+}
+
+// ToLBUpdateMap casts a CreateOpts struct to a map.
+func (opts UpdateOpts) ToLBUpdateMap() (map[string]interface{}, error) {
+ lb := make(map[string]interface{})
+
+ if opts.Name != "" {
+ lb["name"] = opts.Name
+ }
+ if opts.Protocol != "" {
+ lb["protocol"] = opts.Protocol
+ }
+ if opts.HalfClosed != nil {
+ lb["halfClosed"] = opts.HalfClosed
+ }
+ if opts.Algorithm != "" {
+ lb["algorithm"] = opts.Algorithm
+ }
+ if opts.Port > 0 {
+ lb["port"] = opts.Port
+ }
+ if opts.Timeout > 0 {
+ lb["timeout"] = opts.Timeout
+ }
+ if opts.HTTPSRedirect != nil {
+ lb["httpsRedirect"] = &opts.HTTPSRedirect
+ }
+
+ return map[string]interface{}{"loadBalancer": lb}, nil
+}
+
+func Update(c *gophercloud.ServiceClient, id int, opts UpdateOptsBuilder) UpdateResult {
+ var res UpdateResult
+
+ reqBody, err := opts.ToLBUpdateMap()
+ if err != nil {
+ res.Err = err
+ return res
+ }
+
+ _, res.Err = perigee.Request("PUT", resourceURL(c, id), perigee.Options{
+ MoreHeaders: c.AuthenticatedHeaders(),
+ ReqBody: &reqBody,
+ OkCodes: []int{200},
+ })
+
+ return res
+}
diff --git a/rackspace/lb/lbs/requests_test.go b/rackspace/lb/lbs/requests_test.go
new file mode 100644
index 0000000..8c912ae
--- /dev/null
+++ b/rackspace/lb/lbs/requests_test.go
@@ -0,0 +1,226 @@
+package lbs
+
+import (
+ "testing"
+
+ "github.com/rackspace/gophercloud/pagination"
+ th "github.com/rackspace/gophercloud/testhelper"
+ "github.com/rackspace/gophercloud/testhelper/client"
+)
+
+const (
+ id1 = 12345
+ id2 = 67890
+)
+
+func TestList(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ mockListLBResponse(t)
+
+ count := 0
+
+ err := List(client.ServiceClient(), ListOpts{}).EachPage(func(page pagination.Page) (bool, error) {
+ count++
+ actual, err := ExtractLBs(page)
+ th.AssertNoErr(t, err)
+
+ expected := []LoadBalancer{
+ LoadBalancer{
+ Name: "lb-site1",
+ ID: 71,
+ Protocol: "HTTP",
+ Port: 80,
+ Algorithm: RAND,
+ Status: ACTIVE,
+ NodeCount: 3,
+ VIPs: []VIP{
+ VIP{
+ ID: 403,
+ Address: "206.55.130.1",
+ Type: "PUBLIC",
+ Version: "IPV4",
+ },
+ },
+ Created: Datetime{Time: "2010-11-30T03:23:42Z"},
+ Updated: Datetime{Time: "2010-11-30T03:23:44Z"},
+ },
+ }
+
+ th.CheckDeepEquals(t, expected, actual)
+
+ return true, nil
+ })
+
+ th.AssertNoErr(t, err)
+ th.AssertEquals(t, 1, count)
+}
+
+func TestCreate(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ mockCreateLBResponse(t)
+
+ opts := CreateOpts{
+ Name: "a-new-loadbalancer",
+ Port: 80,
+ Protocol: "HTTP",
+ VIPs: []VIP{
+ VIP{ID: 2341},
+ VIP{ID: 900001},
+ },
+ Nodes: []Node{
+ Node{Address: "10.1.1.1", Port: 80, Condition: "ENABLED"},
+ },
+ }
+
+ lb, err := Create(client.ServiceClient(), opts).Extract()
+ th.AssertNoErr(t, err)
+
+ expected := &LoadBalancer{
+ Name: "a-new-loadbalancer",
+ ID: 144,
+ Protocol: "HTTP",
+ HalfClosed: false,
+ Port: 83,
+ Algorithm: RAND,
+ Status: BUILD,
+ Timeout: 30,
+ Cluster: Cluster{Name: "ztm-n01.staging1.lbaas.rackspace.net"},
+ Nodes: []Node{
+ Node{
+ Address: "10.1.1.1",
+ ID: 653,
+ Port: 80,
+ Status: "ONLINE",
+ Condition: "ENABLED",
+ Weight: 1,
+ },
+ },
+ VIPs: []VIP{
+ VIP{
+ ID: 39,
+ Address: "206.10.10.210",
+ Type: "PUBLIC",
+ Version: "IPV4",
+ },
+ VIP{
+ ID: 900001,
+ Address: "2001:4801:79f1:0002:711b:be4c:0000:0021",
+ Type: "PUBLIC",
+ Version: "IPV6",
+ },
+ },
+ Created: Datetime{Time: "2011-04-13T14:18:07Z"},
+ Updated: Datetime{Time: "2011-04-13T14:18:07Z"},
+ ConnectionLogging: ConnectionLogging{Enabled: false},
+ }
+
+ th.AssertDeepEquals(t, expected, lb)
+}
+
+func TestBulkDelete(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ ids := []int{id1, id2}
+
+ mockBatchDeleteLBResponse(t, ids)
+
+ err := BulkDelete(client.ServiceClient(), ids).ExtractErr()
+ th.AssertNoErr(t, err)
+}
+
+func TestDelete(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ mockDeleteLBResponse(t, id1)
+
+ err := Delete(client.ServiceClient(), id1).ExtractErr()
+ th.AssertNoErr(t, err)
+}
+
+func TestGet(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ mockGetLBResponse(t, id1)
+
+ lb, err := Get(client.ServiceClient(), id1).Extract()
+
+ expected := &LoadBalancer{
+ Name: "sample-loadbalancer",
+ ID: 2000,
+ Protocol: "HTTP",
+ Port: 80,
+ Algorithm: RAND,
+ Status: ACTIVE,
+ Timeout: 30,
+ ConnectionLogging: ConnectionLogging{Enabled: true},
+ VIPs: []VIP{
+ VIP{
+ ID: 1000,
+ Address: "206.10.10.210",
+ Type: "PUBLIC",
+ Version: "IPV4",
+ },
+ },
+ Nodes: []Node{
+ Node{
+ Address: "10.1.1.1",
+ ID: 1041,
+ Port: 80,
+ Status: "ONLINE",
+ Condition: "ENABLED",
+ },
+ Node{
+ Address: "10.1.1.2",
+ ID: 1411,
+ Port: 80,
+ Status: "ONLINE",
+ Condition: "ENABLED",
+ },
+ },
+ SessionPersistence: SessionPersistence{Type: "HTTP_COOKIE"},
+ ConnectionThrottle: ConnectionThrottle{
+ MinConns: 10,
+ MaxConns: 100,
+ MaxConnRate: 50,
+ RateInterval: 60,
+ },
+ Cluster: Cluster{Name: "c1.dfw1"},
+ Created: Datetime{Time: "2010-11-30T03:23:42Z"},
+ Updated: Datetime{Time: "2010-11-30T03:23:44Z"},
+ SourceAddrs: SourceAddrs{
+ IPv4Public: "10.12.99.28",
+ IPv4Private: "10.0.0.0",
+ IPv6Public: "2001:4801:79f1:1::1/64",
+ },
+ }
+
+ th.AssertDeepEquals(t, expected, lb)
+ th.AssertNoErr(t, err)
+}
+
+func TestUpdate(t *testing.T) {
+ th.SetupHTTP()
+ defer th.TeardownHTTP()
+
+ mockUpdateLBResponse(t, id1)
+
+ opts := UpdateOpts{
+ Name: "a-new-loadbalancer",
+ Protocol: "TCP",
+ HalfClosed: Enabled,
+ Algorithm: RAND,
+ Port: 8080,
+ Timeout: 100,
+ HTTPSRedirect: Disabled,
+ }
+
+ err := Update(client.ServiceClient(), id1, opts).ExtractErr()
+ th.AssertNoErr(t, err)
+}
diff --git a/rackspace/lb/lbs/results.go b/rackspace/lb/lbs/results.go
new file mode 100644
index 0000000..384a1fc
--- /dev/null
+++ b/rackspace/lb/lbs/results.go
@@ -0,0 +1,251 @@
+package lbs
+
+import (
+ "github.com/mitchellh/mapstructure"
+
+ "github.com/rackspace/gophercloud"
+ "github.com/rackspace/gophercloud/pagination"
+)
+
+type Protocol string
+
+// The constants below represent all the compatible load balancer protocols.
+const (
+ // DNSTCP is a protocol that works with IPv6 and allows your DNS server to
+ // receive traffic using TCP port 53.
+ DNSTCP = "DNS_TCP"
+
+ // DNSUDP is a protocol that works with IPv6 and allows your DNS server to
+ // receive traffic using UDP port 53.
+ DNSUDP = "DNS_UDP"
+
+ // TCP is one of the core protocols of the Internet Protocol Suite. It
+ // provides a reliable, ordered delivery of a stream of bytes from one
+ // program on a computer to another program on another computer. Applications
+ // that require an ordered and reliable delivery of packets use this protocol.
+ TCP = "TCP"
+
+ // TCPCLIENTFIRST is a protocol similar to TCP, but is more efficient when a
+ // client is expected to write the data first.
+ TCPCLIENTFIRST = "TCP_CLIENT_FIRST"
+
+ // UDP provides a datagram service that emphasizes speed over reliability. It
+ // works well with applications that provide security through other measures.
+ UDP = "UDP"
+
+ // UDPSTREAM is a protocol designed to stream media over networks and is
+ // built on top of UDP.
+ UDPSTREAM = "UDP_STREAM"
+)
+
+// Algorithm defines how traffic should be directed between back-end nodes.
+type Algorithm string
+
+const (
+ // LC directs traffic to the node with the lowest number of connections.
+ LC = "LEAST_CONNECTIONS"
+
+ // RAND directs traffic to nodes at random.
+ RAND = "RANDOM"
+
+ // RR directs traffic to each of the nodes in turn.
+ RR = "ROUND_ROBIN"
+
+ // WLC directs traffic to a node based on the number of concurrent
+ // connections and its weight.
+ WLC = "WEIGHTED_LEAST_CONNECTIONS"
+
+ // WRR directs traffic to a node according to the RR algorithm, but with
+ // different proportions of traffic being directed to the back-end nodes.
+ // Weights must be defined as part of the node configuration.
+ WRR = "WEIGHTED_ROUND_ROBIN"
+)
+
+type Status string
+
+const (
+ // ACTIVE indicates that the LB is configured properly and ready to serve
+ // traffic to incoming requests via the configured virtual IPs.
+ ACTIVE = "ACTIVE"
+
+ // BUILD indicates that the LB is being provisioned for the first time and
+ // configuration is being applied to bring the service online. The service
+ // cannot yet serve incoming requests.
+ BUILD = "BUILD"
+
+ // PENDINGUPDATE indicates that the LB is online but configuration changes
+ // are being applied to update the service based on a previous request.
+ PENDINGUPDATE = "PENDING_UPDATE"
+
+ // PENDINGDELETE indicates that the LB is online but configuration changes
+ // are being applied to begin deletion of the service based on a previous
+ // request.
+ PENDINGDELETE = "PENDING_DELETE"
+
+ // SUSPENDED indicates that the LB has been taken offline and disabled.
+ SUSPENDED = "SUSPENDED"
+
+ // ERROR indicates that the system encountered an error when attempting to
+ // configure the load balancer.
+ ERROR = "ERROR"
+
+ // DELETED indicates that the LB has been deleted.
+ DELETED = "DELETED"
+)
+
+type Datetime struct {
+ Time string
+}
+
+type VIP struct {
+ Address string `json:"address,omitempty"`
+ ID int `json:"id,omitempty"`
+ Type string `json:"type,omitempty"`
+ Version string `json:"ipVersion,omitempty" mapstructure:"ipVersion"`
+}
+
+type LoadBalancer struct {
+ // Human-readable name for the load balancer.
+ Name string
+
+ // The unique ID for the load balancer.
+ ID int
+
+ // Represents the service protocol being load balanced.
+ Protocol Protocol
+
+ // Defines how traffic should be directed between back-end nodes. The default
+ // algorithm is RANDOM.
+ Algorithm Algorithm
+
+ // The current status of the load balancer.
+ Status Status
+
+ // The number of load balancer nodes.
+ NodeCount int `mapstructure:"nodeCount"`
+
+ // Slice of virtual IPs associated with this load balancer.
+ VIPs []VIP `mapstructure:"virtualIps"`
+
+ // Datetime when the LB was created.
+ Created Datetime
+
+ // Datetime when the LB was created.
+ Updated Datetime
+
+ Port int
+
+ HalfClosed bool
+
+ Timeout int
+
+ Cluster Cluster
+
+ Nodes []Node
+
+ ConnectionLogging ConnectionLogging
+
+ SessionPersistence SessionPersistence
+
+ ConnectionThrottle ConnectionThrottle
+
+ SourceAddrs SourceAddrs `mapstructure:"sourceAddresses"`
+}
+
+type SourceAddrs struct {
+ IPv4Public string `json:"ipv4Public" mapstructure:"ipv4Public"`
+ IPv4Private string `json:"ipv4Servicenet" mapstructure:"ipv4Servicenet"`
+ IPv6Public string `json:"ipv6Public" mapstructure:"ipv6Public"`
+ IPv6Private string `json:"ipv6Servicenet" mapstructure:"ipv6Servicenet"`
+}
+
+type SessionPersistence struct {
+ Type string `json:"persistenceType" mapstructure:"persistenceType"`
+}
+
+type ConnectionThrottle struct {
+ MinConns int `json:"minConnections" mapstructure:"minConnections"`
+ MaxConns int `json:"maxConnections" mapstructure:"maxConnections"`
+ MaxConnRate int `json:"maxConnectionRate" mapstructure:"maxConnectionRate"`
+ RateInterval int `json:"rateInterval" mapstructure:"rateInterval"`
+}
+
+type ConnectionLogging struct {
+ Enabled bool
+}
+
+type Cluster struct {
+ Name string
+}
+
+type Node struct {
+ Address string
+ ID int
+ Port int
+ Status Status
+ Condition string
+ Weight int
+}
+
+// LBPage is the page returned by a pager when traversing over a collection of
+// LBs.
+type LBPage struct {
+ pagination.LinkedPageBase
+}
+
+// IsEmpty checks whether a NetworkPage struct is empty.
+func (p LBPage) IsEmpty() (bool, error) {
+ is, err := ExtractLBs(p)
+ if err != nil {
+ return true, nil
+ }
+ return len(is) == 0, nil
+}
+
+// ExtractLBs accepts a Page struct, specifically a LBPage struct, and extracts
+// the elements into a slice of LoadBalancer structs. In other words, a generic
+// collection is mapped into a relevant slice.
+func ExtractLBs(page pagination.Page) ([]LoadBalancer, error) {
+ var resp struct {
+ LBs []LoadBalancer `mapstructure:"loadBalancers" json:"loadBalancers"`
+ }
+
+ err := mapstructure.Decode(page.(LBPage).Body, &resp)
+
+ return resp.LBs, err
+}
+
+type commonResult struct {
+ gophercloud.Result
+}
+
+// Extract interprets any commonResult as a LB, if possible.
+func (r commonResult) Extract() (*LoadBalancer, error) {
+ if r.Err != nil {
+ return nil, r.Err
+ }
+
+ var response struct {
+ LB LoadBalancer `mapstructure:"loadBalancer"`
+ }
+
+ err := mapstructure.Decode(r.Body, &response)
+
+ return &response.LB, err
+}
+
+type CreateResult struct {
+ commonResult
+}
+
+type DeleteResult struct {
+ gophercloud.ErrResult
+}
+
+type UpdateResult struct {
+ gophercloud.ErrResult
+}
+
+type GetResult struct {
+ commonResult
+}
diff --git a/rackspace/lb/lbs/urls.go b/rackspace/lb/lbs/urls.go
new file mode 100644
index 0000000..3df99ab
--- /dev/null
+++ b/rackspace/lb/lbs/urls.go
@@ -0,0 +1,17 @@
+package lbs
+
+import (
+ "strconv"
+
+ "github.com/rackspace/gophercloud"
+)
+
+const path = "loadbalancers"
+
+func resourceURL(c *gophercloud.ServiceClient, id int) string {
+ return c.ServiceURL(path, strconv.Itoa(id))
+}
+
+func rootURL(c *gophercloud.ServiceClient) string {
+ return c.ServiceURL(path)
+}