blob: 3a9fc251bb74920f760206107f15696f1a4ce2b9 [file] [log] [blame]
Jamie Hannafordfba65af2014-11-03 10:32:37 +01001package lbs
Jamie Hannaford186d4e22014-10-31 12:26:11 +01002
3import (
Jamie Hannaforde09b6822014-10-31 15:33:57 +01004 "errors"
5
6 "github.com/racker/perigee"
7
Jamie Hannaford186d4e22014-10-31 12:26:11 +01008 "github.com/rackspace/gophercloud"
9 "github.com/rackspace/gophercloud/pagination"
Jamie Hannaford940159d2014-11-03 13:04:08 +010010 "github.com/rackspace/gophercloud/rackspace/lb/v1"
Jamie Hannaford0a9a6be2014-11-03 12:55:38 +010011 "github.com/rackspace/gophercloud/rackspace/lb/v1/nodes"
Jamie Hannaford1c817312014-11-04 10:56:58 +010012 "github.com/rackspace/gophercloud/rackspace/lb/v1/vips"
Jamie Hannaford186d4e22014-10-31 12:26:11 +010013)
14
15// ListOptsBuilder allows extensions to add additional parameters to the
16// List request.
17type ListOptsBuilder interface {
18 ToLBListQuery() (string, error)
19}
20
21// ListOpts allows the filtering and sorting of paginated collections through
22// the API.
23type ListOpts struct {
24 ChangesSince string `q:"changes-since"`
25 Status Status `q:"status"`
26 NodeAddr string `q:"nodeaddress"`
27 Marker string `q:"marker"`
28 Limit int `q:"limit"`
29}
30
31// ToLBListQuery formats a ListOpts into a query string.
32func (opts ListOpts) ToLBListQuery() (string, error) {
33 q, err := gophercloud.BuildQueryString(opts)
34 if err != nil {
35 return "", err
36 }
37 return q.String(), nil
38}
39
Jamie Hannafordb2007ee2014-11-03 16:24:43 +010040// List is the operation responsible for returning a paginated collection of
41// load balancers. You may pass in a ListOpts struct to filter results.
Jamie Hannaford186d4e22014-10-31 12:26:11 +010042func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {
43 url := rootURL(client)
44 if opts != nil {
45 query, err := opts.ToLBListQuery()
46 if err != nil {
47 return pagination.Pager{Err: err}
48 }
49 url += query
50 }
51
52 return pagination.NewPager(client, url, func(r pagination.PageResult) pagination.Page {
53 return LBPage{pagination.LinkedPageBase{PageResult: r}}
54 })
55}
Jamie Hannaforde09b6822014-10-31 15:33:57 +010056
57type enabledState *bool
58
Jamie Hannafordb2007ee2014-11-03 16:24:43 +010059// Convenience vars to help setting enabled state.
Jamie Hannaforde09b6822014-10-31 15:33:57 +010060var (
61 iTrue = true
62 iFalse = false
63
64 Enabled enabledState = &iTrue
65 Disabled enabledState = &iFalse
66)
67
68// CreateOptsBuilder is the interface options structs have to satisfy in order
69// to be used in the main Create operation in this package. Since many
70// extensions decorate or modify the common logic, it is useful for them to
71// satisfy a basic interface in order for them to be used.
72type CreateOptsBuilder interface {
73 ToLBCreateMap() (map[string]interface{}, error)
74}
75
76// CreateOpts is the common options struct used in this package's Create
77// operation.
78type CreateOpts struct {
79 // Required - name of the load balancer to create. The name must be 128
80 // characters or fewer in length, and all UTF-8 characters are valid.
81 Name string
82
83 // Optional - nodes to be added.
Jamie Hannaford0a9a6be2014-11-03 12:55:38 +010084 Nodes []nodes.Node
Jamie Hannaforde09b6822014-10-31 15:33:57 +010085
86 // Required - protocol of the service that is being load balanced.
87 Protocol Protocol
88
89 // Optional - enables or disables Half-Closed support for the load balancer.
90 // Half-Closed support provides the ability for one end of the connection to
91 // terminate its output, while still receiving data from the other end. Only
92 // available for TCP/TCP_CLIENT_FIRST protocols.
93 HalfClosed enabledState
94
95 // Optional - the type of virtual IPs you want associated with the load
96 // balancer.
Jamie Hannaford1c817312014-11-04 10:56:58 +010097 VIPs []vips.VIP
Jamie Hannaforde09b6822014-10-31 15:33:57 +010098
99 // Optional - the access list management feature allows fine-grained network
100 // access controls to be applied to the load balancer virtual IP address.
101 AccessList string
102
103 // Optional - algorithm that defines how traffic should be directed between
104 // back-end nodes.
105 Algorithm Algorithm
106
107 // Optional - current connection logging configuration.
108 ConnectionLogging *ConnectionLogging
109
110 // Optional - specifies a limit on the number of connections per IP address
111 // to help mitigate malicious or abusive traffic to your applications.
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100112 ConnThrottle *ConnectionThrottle
Jamie Hannaforde09b6822014-10-31 15:33:57 +0100113
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100114 // Optional -
115 //HealthMonitor string
Jamie Hannaforde09b6822014-10-31 15:33:57 +0100116
117 // Optional - arbitrary information that can be associated with each LB.
118 Metadata map[string]interface{}
119
120 // Optional - port number for the service you are load balancing.
121 Port int
122
123 // Optional - the timeout value for the load balancer and communications with
124 // its nodes. Defaults to 30 seconds with a maximum of 120 seconds.
125 Timeout int
126
127 // Optional - specifies whether multiple requests from clients are directed
128 // to the same node.
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100129 SessionPersistence *SessionPersistence
Jamie Hannaforde09b6822014-10-31 15:33:57 +0100130
131 // Optional - enables or disables HTTP to HTTPS redirection for the load
132 // balancer. When enabled, any HTTP request returns status code 301 (Moved
133 // Permanently), and the requester is redirected to the requested URL via the
134 // HTTPS protocol on port 443. For example, http://example.com/page.html
135 // would be redirected to https://example.com/page.html. Only available for
136 // HTTPS protocol (port=443), or HTTP protocol with a properly configured SSL
137 // termination (secureTrafficOnly=true, securePort=443).
138 HTTPSRedirect enabledState
139}
140
141var (
142 errNameRequired = errors.New("Name is a required attribute")
143 errTimeoutExceeded = errors.New("Timeout must be less than 120")
144)
145
146// ToLBCreateMap casts a CreateOpts struct to a map.
147func (opts CreateOpts) ToLBCreateMap() (map[string]interface{}, error) {
148 lb := make(map[string]interface{})
149
150 if opts.Name == "" {
151 return lb, errNameRequired
152 }
153 if opts.Timeout > 120 {
154 return lb, errTimeoutExceeded
155 }
156
157 lb["name"] = opts.Name
158
159 if len(opts.Nodes) > 0 {
160 nodes := []map[string]interface{}{}
161 for _, n := range opts.Nodes {
162 nodes = append(nodes, map[string]interface{}{
163 "address": n.Address,
164 "port": n.Port,
165 "condition": n.Condition,
166 })
167 }
168 lb["nodes"] = nodes
169 }
170
171 if opts.Protocol != "" {
172 lb["protocol"] = opts.Protocol
173 }
174 if opts.HalfClosed != nil {
175 lb["halfClosed"] = opts.HalfClosed
176 }
177
178 if len(opts.VIPs) > 0 {
Jamie Hannaforde09b6822014-10-31 15:33:57 +0100179 lb["virtualIps"] = opts.VIPs
180 }
181
182 // if opts.AccessList != "" {
183 // lb["accessList"] = opts.AccessList
184 // }
185 if opts.Algorithm != "" {
186 lb["algorithm"] = opts.Algorithm
187 }
188 if opts.ConnectionLogging != nil {
189 lb["connectionLogging"] = &opts.ConnectionLogging
190 }
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100191 if opts.ConnThrottle != nil {
192 lb["connectionThrottle"] = &opts.ConnThrottle
193 }
Jamie Hannaforde09b6822014-10-31 15:33:57 +0100194 // if opts.HealthMonitor != "" {
195 // lb["healthMonitor"] = opts.HealthMonitor
196 // }
197 if len(opts.Metadata) != 0 {
198 lb["metadata"] = opts.Metadata
199 }
200 if opts.Port > 0 {
201 lb["port"] = opts.Port
202 }
203 if opts.Timeout > 0 {
204 lb["timeout"] = opts.Timeout
205 }
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100206 if opts.SessionPersistence != nil {
207 lb["sessionPersistence"] = &opts.SessionPersistence
208 }
Jamie Hannaforde09b6822014-10-31 15:33:57 +0100209 if opts.HTTPSRedirect != nil {
210 lb["httpsRedirect"] = &opts.HTTPSRedirect
211 }
212
213 return map[string]interface{}{"loadBalancer": lb}, nil
214}
215
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100216// Create is the operation responsible for asynchronously provisioning a new
217// load balancer based on the configuration defined in CreateOpts. Once the
218// request is validated and progress has started on the provisioning process, a
219// response struct is returned. When extracted (with Extract()), you have
220// to the load balancer's unique ID and status.
221//
222// Once an ID is attained, you can check on the progress of the operation by
223// calling Get and passing in the ID. If the corresponding request cannot be
224// fulfilled due to insufficient or invalid data, a HTTP 400 (Bad Request)
225// error response is returned with information regarding the nature of the
226// failure in the body of the response. Failures in the validation process are
227// non-recoverable and require the caller to correct the cause of the failure.
Jamie Hannaforde09b6822014-10-31 15:33:57 +0100228func Create(c *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult {
229 var res CreateResult
230
231 reqBody, err := opts.ToLBCreateMap()
232 if err != nil {
233 res.Err = err
234 return res
235 }
236
237 _, res.Err = perigee.Request("POST", rootURL(c), perigee.Options{
238 MoreHeaders: c.AuthenticatedHeaders(),
239 ReqBody: &reqBody,
240 Results: &res.Body,
241 OkCodes: []int{200},
242 })
243
244 return res
245}
Jamie Hannaford1c260332014-10-31 15:57:22 +0100246
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100247// Get is the operation responsible for providing detailed information
248// regarding a specific load balancer which is configured and associated with
249// your account. This operation is not capable of returning details for a load
250// balancer which has been deleted.
Jamie Hannaford07c06962014-10-31 16:42:03 +0100251func Get(c *gophercloud.ServiceClient, id int) GetResult {
252 var res GetResult
253
254 _, res.Err = perigee.Request("GET", resourceURL(c, id), perigee.Options{
255 MoreHeaders: c.AuthenticatedHeaders(),
256 Results: &res.Body,
257 OkCodes: []int{200},
258 })
259
260 return res
261}
262
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100263// BulkDelete removes all the load balancers referenced in the slice of IDs.
264// Any and all configuration data associated with these load balancers are
265// immediately purged and is not recoverable.
266//
267// If one of the items in the list cannot be removed due to its current status,
268// a 400 Bad Request error is returned along with the IDs of the ones the
269// system identified as potential failures for this request.
Jamie Hannaford1c260332014-10-31 15:57:22 +0100270func BulkDelete(c *gophercloud.ServiceClient, ids []int) DeleteResult {
271 var res DeleteResult
272
Jamie Hannaford0a9a6be2014-11-03 12:55:38 +0100273 if len(ids) > 10 || len(ids) == 0 {
274 res.Err = errors.New("You must provide a minimum of 1 and a maximum of 10 LB IDs")
275 return res
276 }
277
Jamie Hannaford1c260332014-10-31 15:57:22 +0100278 url := rootURL(c)
Jamie Hannaford940159d2014-11-03 13:04:08 +0100279 url += v1.IDSliceToQueryString("id", ids)
Jamie Hannaford1c260332014-10-31 15:57:22 +0100280
281 _, res.Err = perigee.Request("DELETE", url, perigee.Options{
282 MoreHeaders: c.AuthenticatedHeaders(),
283 OkCodes: []int{202},
284 })
285
286 return res
287}
Jamie Hannaford5f95e6a2014-10-31 16:13:44 +0100288
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100289// Delete removes a single load balancer.
Jamie Hannaford5f95e6a2014-10-31 16:13:44 +0100290func Delete(c *gophercloud.ServiceClient, id int) DeleteResult {
291 var res DeleteResult
292
293 _, res.Err = perigee.Request("DELETE", resourceURL(c, id), perigee.Options{
294 MoreHeaders: c.AuthenticatedHeaders(),
295 OkCodes: []int{202},
296 })
297
298 return res
299}
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100300
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100301// UpdateOptsBuilder represents a type that can be converted into a JSON-like
302// map structure.
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100303type UpdateOptsBuilder interface {
304 ToLBUpdateMap() (map[string]interface{}, error)
305}
306
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100307// UpdateOpts represent the options for updating an existing load balancer.
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100308type UpdateOpts struct {
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100309 // Optional - new name of the load balancer.
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100310 Name string
311
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100312 // Optional - the new protocol you want your load balancer to have.
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100313 Protocol Protocol
314
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100315 // Optional - see the HalfClosed field in CreateOpts for more information.
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100316 HalfClosed enabledState
317
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100318 // Optional - see the Algorithm field in CreateOpts for more information.
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100319 Algorithm Algorithm
320
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100321 // Optional - see the Port field in CreateOpts for more information.
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100322 Port int
323
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100324 // Optional - see the Timeout field in CreateOpts for more information.
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100325 Timeout int
326
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100327 // Optional - see the HTTPSRedirect field in CreateOpts for more information.
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100328 HTTPSRedirect enabledState
329}
330
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100331// ToLBUpdateMap casts an UpdateOpts struct to a map.
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100332func (opts UpdateOpts) ToLBUpdateMap() (map[string]interface{}, error) {
333 lb := make(map[string]interface{})
334
335 if opts.Name != "" {
336 lb["name"] = opts.Name
337 }
338 if opts.Protocol != "" {
339 lb["protocol"] = opts.Protocol
340 }
341 if opts.HalfClosed != nil {
342 lb["halfClosed"] = opts.HalfClosed
343 }
344 if opts.Algorithm != "" {
345 lb["algorithm"] = opts.Algorithm
346 }
347 if opts.Port > 0 {
348 lb["port"] = opts.Port
349 }
350 if opts.Timeout > 0 {
351 lb["timeout"] = opts.Timeout
352 }
353 if opts.HTTPSRedirect != nil {
354 lb["httpsRedirect"] = &opts.HTTPSRedirect
355 }
356
357 return map[string]interface{}{"loadBalancer": lb}, nil
358}
359
Jamie Hannafordb2007ee2014-11-03 16:24:43 +0100360// Update is the operation responsible for asynchronously updating the
361// attributes of a specific load balancer. Upon successful validation of the
362// request, the service returns a 202 Accepted response and the load balancer
363// enters a PENDING_UPDATE state. A user can poll the load balancer with Get to
364// wait for the changes to be applied. When this happens, the load balancer will
365// return to an ACTIVE state.
Jamie Hannaford76fcc832014-10-31 16:56:50 +0100366func Update(c *gophercloud.ServiceClient, id int, opts UpdateOptsBuilder) UpdateResult {
367 var res UpdateResult
368
369 reqBody, err := opts.ToLBUpdateMap()
370 if err != nil {
371 res.Err = err
372 return res
373 }
374
375 _, res.Err = perigee.Request("PUT", resourceURL(c, id), perigee.Options{
376 MoreHeaders: c.AuthenticatedHeaders(),
377 ReqBody: &reqBody,
378 OkCodes: []int{200},
379 })
380
381 return res
382}