blob: 18a2237fbb8c19bb63de0134a39d0d5eb7145341 [file] [log] [blame]
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -08001package servers
2
3import (
Ash Wilson6a310e02014-09-29 08:24:02 -04004 "encoding/base64"
Jon Perrittcc77da62014-11-16 13:14:21 -07005 "errors"
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -07006 "fmt"
Ash Wilson01626a32014-09-17 10:38:07 -04007
Ash Wilson01626a32014-09-17 10:38:07 -04008 "github.com/rackspace/gophercloud"
9 "github.com/rackspace/gophercloud/pagination"
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080010)
11
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020012// ListOptsBuilder allows extensions to add additional parameters to the
13// List request.
14type ListOptsBuilder interface {
15 ToServerListQuery() (string, error)
16}
17
18// ListOpts allows the filtering and sorting of paginated collections through
19// the API. Filtering is achieved by passing in struct field values that map to
20// the server attributes you want to see returned. Marker and Limit are used
21// for pagination.
22type ListOpts struct {
23 // A time/date stamp for when the server last changed status.
24 ChangesSince string `q:"changes-since"`
25
26 // Name of the image in URL format.
27 Image string `q:"image"`
28
29 // Name of the flavor in URL format.
30 Flavor string `q:"flavor"`
31
32 // Name of the server as a string; can be queried with regular expressions.
33 // Realize that ?name=bob returns both bob and bobb. If you need to match bob
34 // only, you can use a regular expression matching the syntax of the
35 // underlying database server implemented for Compute.
36 Name string `q:"name"`
37
38 // Value of the status of the server so that you can filter on "ACTIVE" for example.
39 Status string `q:"status"`
40
41 // Name of the host as a string.
42 Host string `q:"host"`
43
44 // UUID of the server at which you want to set a marker.
45 Marker string `q:"marker"`
46
47 // Integer value for the limit of values to return.
48 Limit int `q:"limit"`
49}
50
51// ToServerListQuery formats a ListOpts into a query string.
52func (opts ListOpts) ToServerListQuery() (string, error) {
53 q, err := gophercloud.BuildQueryString(opts)
54 if err != nil {
55 return "", err
56 }
57 return q.String(), nil
58}
59
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080060// List makes a request against the API to list servers accessible to you.
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020061func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {
62 url := listDetailURL(client)
63
64 if opts != nil {
65 query, err := opts.ToServerListQuery()
66 if err != nil {
67 return pagination.Pager{Err: err}
68 }
69 url += query
70 }
71
Ash Wilsonb8b16f82014-10-20 10:19:49 -040072 createPageFn := func(r pagination.PageResult) pagination.Page {
73 return ServerPage{pagination.LinkedPageBase{PageResult: r}}
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080074 }
75
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020076 return pagination.NewPager(client, url, createPageFn)
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080077}
78
Ash Wilson2206a112014-10-02 10:57:38 -040079// CreateOptsBuilder describes struct types that can be accepted by the Create call.
Ash Wilson6a310e02014-09-29 08:24:02 -040080// The CreateOpts struct in this package does.
Ash Wilson2206a112014-10-02 10:57:38 -040081type CreateOptsBuilder interface {
Jon Perritt4149d7c2014-10-23 21:23:46 -050082 ToServerCreateMap() (map[string]interface{}, error)
Ash Wilson6a310e02014-09-29 08:24:02 -040083}
84
85// Network is used within CreateOpts to control a new server's network attachments.
86type Network struct {
87 // UUID of a nova-network to attach to the newly provisioned server.
88 // Required unless Port is provided.
89 UUID string
90
91 // Port of a neutron network to attach to the newly provisioned server.
92 // Required unless UUID is provided.
93 Port string
94
95 // FixedIP [optional] specifies a fixed IPv4 address to be used on this network.
96 FixedIP string
97}
98
Kevin Pike92e10b52015-04-10 15:16:57 -070099// Personality is an array of files that are injected into the server at launch.
100type Personality []File
101
102// Marshal marshals the personality, marshalling each of the files.
103func (p Personality) Marshal() []map[string]string {
104 personality := make([]map[string]string, len(p))
105 for i, file := range p {
106 personality[i] = file.Marshal()
107 }
108
109 return personality
110}
111
112// File is used within CreateOpts and RebuildOpts to inject a file into the server at launch.
113type File struct {
114 // Path of the file
115 Path string `json:"path"`
116 // Contents of the file. Maximum content size is 255 bytes.
117 Contents []byte `json:"contents"`
118}
119
120// Marshal marshals the file, base64 encoding the contents.
121func (f File) Marshal() map[string]string {
122 return map[string]string{
123 "path": f.Path,
124 "contents": base64.StdEncoding.EncodeToString(f.Contents),
125 }
126}
127
Ash Wilson6a310e02014-09-29 08:24:02 -0400128// CreateOpts specifies server creation parameters.
129type CreateOpts struct {
130 // Name [required] is the name to assign to the newly launched server.
131 Name string
132
133 // ImageRef [required] is the ID or full URL to the image that contains the server's OS and initial state.
134 // Optional if using the boot-from-volume extension.
135 ImageRef string
136
137 // FlavorRef [required] is the ID or full URL to the flavor that describes the server's specs.
138 FlavorRef string
139
140 // SecurityGroups [optional] lists the names of the security groups to which this server should belong.
141 SecurityGroups []string
142
143 // UserData [optional] contains configuration information or scripts to use upon launch.
144 // Create will base64-encode it for you.
145 UserData []byte
146
147 // AvailabilityZone [optional] in which to launch the server.
148 AvailabilityZone string
149
150 // Networks [optional] dictates how this server will be attached to available networks.
151 // By default, the server will be attached to all isolated networks for the tenant.
152 Networks []Network
153
154 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server.
155 Metadata map[string]string
156
Kevin Pike92e10b52015-04-10 15:16:57 -0700157 // Personality [optional] includes files to inject into the server at launch.
158 // Create will base64-encode file contents for you.
159 Personality Personality
Ash Wilson6a310e02014-09-29 08:24:02 -0400160
161 // ConfigDrive [optional] enables metadata injection through a configuration drive.
162 ConfigDrive bool
Jon Perrittf3b2e142014-11-04 16:00:19 -0600163
164 // AdminPass [optional] sets the root user password. If not set, a randomly-generated
165 // password will be created and returned in the response.
166 AdminPass string
Jon Perritt7b9671c2015-02-01 22:03:14 -0700167
168 // AccessIPv4 [optional] specifies an IPv4 address for the instance.
169 AccessIPv4 string
170
171 // AccessIPv6 [optional] specifies an IPv6 address for the instance.
172 AccessIPv6 string
Ash Wilson6a310e02014-09-29 08:24:02 -0400173}
174
Ash Wilsone45c9732014-09-29 10:54:12 -0400175// ToServerCreateMap assembles a request body based on the contents of a CreateOpts.
Jon Perritt4149d7c2014-10-23 21:23:46 -0500176func (opts CreateOpts) ToServerCreateMap() (map[string]interface{}, error) {
Ash Wilson6a310e02014-09-29 08:24:02 -0400177 server := make(map[string]interface{})
178
179 server["name"] = opts.Name
180 server["imageRef"] = opts.ImageRef
181 server["flavorRef"] = opts.FlavorRef
182
183 if opts.UserData != nil {
184 encoded := base64.StdEncoding.EncodeToString(opts.UserData)
185 server["user_data"] = &encoded
186 }
Ash Wilson6a310e02014-09-29 08:24:02 -0400187 if opts.ConfigDrive {
188 server["config_drive"] = "true"
189 }
190 if opts.AvailabilityZone != "" {
191 server["availability_zone"] = opts.AvailabilityZone
192 }
193 if opts.Metadata != nil {
194 server["metadata"] = opts.Metadata
195 }
Jon Perrittf3b2e142014-11-04 16:00:19 -0600196 if opts.AdminPass != "" {
197 server["adminPass"] = opts.AdminPass
198 }
Jon Perritt7b9671c2015-02-01 22:03:14 -0700199 if opts.AccessIPv4 != "" {
200 server["accessIPv4"] = opts.AccessIPv4
201 }
202 if opts.AccessIPv6 != "" {
203 server["accessIPv6"] = opts.AccessIPv6
204 }
Ash Wilson6a310e02014-09-29 08:24:02 -0400205
206 if len(opts.SecurityGroups) > 0 {
207 securityGroups := make([]map[string]interface{}, len(opts.SecurityGroups))
208 for i, groupName := range opts.SecurityGroups {
209 securityGroups[i] = map[string]interface{}{"name": groupName}
210 }
eselldf709942014-11-13 21:07:11 -0700211 server["security_groups"] = securityGroups
Ash Wilson6a310e02014-09-29 08:24:02 -0400212 }
Jon Perritt2a7797d2014-10-21 15:08:43 -0500213
Ash Wilson6a310e02014-09-29 08:24:02 -0400214 if len(opts.Networks) > 0 {
215 networks := make([]map[string]interface{}, len(opts.Networks))
216 for i, net := range opts.Networks {
217 networks[i] = make(map[string]interface{})
218 if net.UUID != "" {
219 networks[i]["uuid"] = net.UUID
220 }
221 if net.Port != "" {
222 networks[i]["port"] = net.Port
223 }
224 if net.FixedIP != "" {
225 networks[i]["fixed_ip"] = net.FixedIP
226 }
227 }
Jon Perritt2a7797d2014-10-21 15:08:43 -0500228 server["networks"] = networks
Ash Wilson6a310e02014-09-29 08:24:02 -0400229 }
230
Kevin Pike92e10b52015-04-10 15:16:57 -0700231 if len(opts.Personality) > 0 {
232 server["personality"] = opts.Personality.Marshal()
233 }
234
Jon Perritt4149d7c2014-10-23 21:23:46 -0500235 return map[string]interface{}{"server": server}, nil
Ash Wilson6a310e02014-09-29 08:24:02 -0400236}
237
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800238// Create requests a server to be provisioned to the user in the current tenant.
Ash Wilson2206a112014-10-02 10:57:38 -0400239func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult {
Jon Perritt4149d7c2014-10-23 21:23:46 -0500240 var res CreateResult
241
242 reqBody, err := opts.ToServerCreateMap()
243 if err != nil {
244 res.Err = err
245 return res
246 }
247
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100248 _, res.Err = client.Post(listURL(client), reqBody, &res.Body, nil)
Jon Perritt4149d7c2014-10-23 21:23:46 -0500249 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800250}
251
252// Delete requests that a server previously provisioned be removed from your account.
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100253func Delete(client *gophercloud.ServiceClient, id string) DeleteResult {
254 var res DeleteResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100255 _, res.Err = client.Delete(deleteURL(client, id), nil)
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100256 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800257}
258
Ash Wilson7ddf0362014-09-17 10:59:09 -0400259// Get requests details on a single server, by ID.
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400260func Get(client *gophercloud.ServiceClient, id string) GetResult {
261 var result GetResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100262 _, result.Err = client.Get(getURL(client, id), &result.Body, &gophercloud.RequestOpts{
263 OkCodes: []int{200, 203},
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800264 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400265 return result
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800266}
267
Alex Gaynora6d5f9f2014-10-27 10:52:32 -0700268// UpdateOptsBuilder allows extensions to add additional attributes to the Update request.
Jon Perritt82048212014-10-13 22:33:13 -0500269type UpdateOptsBuilder interface {
Ash Wilsone45c9732014-09-29 10:54:12 -0400270 ToServerUpdateMap() map[string]interface{}
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400271}
272
273// UpdateOpts specifies the base attributes that may be updated on an existing server.
274type UpdateOpts struct {
275 // Name [optional] changes the displayed name of the server.
276 // The server host name will *not* change.
277 // Server names are not constrained to be unique, even within the same tenant.
278 Name string
279
280 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
281 AccessIPv4 string
282
283 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
284 AccessIPv6 string
285}
286
Ash Wilsone45c9732014-09-29 10:54:12 -0400287// ToServerUpdateMap formats an UpdateOpts structure into a request body.
288func (opts UpdateOpts) ToServerUpdateMap() map[string]interface{} {
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400289 server := make(map[string]string)
290 if opts.Name != "" {
291 server["name"] = opts.Name
292 }
293 if opts.AccessIPv4 != "" {
294 server["accessIPv4"] = opts.AccessIPv4
295 }
296 if opts.AccessIPv6 != "" {
297 server["accessIPv6"] = opts.AccessIPv6
298 }
299 return map[string]interface{}{"server": server}
300}
301
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800302// Update requests that various attributes of the indicated server be changed.
Jon Perritt82048212014-10-13 22:33:13 -0500303func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400304 var result UpdateResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100305 reqBody := opts.ToServerUpdateMap()
306 _, result.Err = client.Put(updateURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
307 OkCodes: []int{200},
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800308 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400309 return result
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800310}
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700311
Ash Wilson01626a32014-09-17 10:38:07 -0400312// ChangeAdminPassword alters the administrator or root password for a specified server.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200313func ChangeAdminPassword(client *gophercloud.ServiceClient, id, newPassword string) ActionResult {
Ash Wilsondc7daa82014-09-23 16:34:42 -0400314 var req struct {
315 ChangePassword struct {
316 AdminPass string `json:"adminPass"`
317 } `json:"changePassword"`
318 }
319
320 req.ChangePassword.AdminPass = newPassword
321
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200322 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100323 _, res.Err = client.Post(actionURL(client, id), req, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200324 return res
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700325}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700326
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700327// ErrArgument errors occur when an argument supplied to a package function
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700328// fails to fall within acceptable values. For example, the Reboot() function
329// expects the "how" parameter to be one of HardReboot or SoftReboot. These
330// constants are (currently) strings, leading someone to wonder if they can pass
331// other string values instead, perhaps in an effort to break the API of their
332// provider. Reboot() returns this error in this situation.
333//
334// Function identifies which function was called/which function is generating
335// the error.
336// Argument identifies which formal argument was responsible for producing the
337// error.
338// Value provides the value as it was passed into the function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700339type ErrArgument struct {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700340 Function, Argument string
Jon Perritt30558642014-04-14 17:07:12 -0500341 Value interface{}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700342}
343
344// Error yields a useful diagnostic for debugging purposes.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700345func (e *ErrArgument) Error() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700346 return fmt.Sprintf("Bad argument in call to %s, formal parameter %s, value %#v", e.Function, e.Argument, e.Value)
347}
348
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700349func (e *ErrArgument) String() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700350 return e.Error()
351}
352
Ash Wilson01626a32014-09-17 10:38:07 -0400353// RebootMethod describes the mechanisms by which a server reboot can be requested.
354type RebootMethod string
355
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700356// These constants determine how a server should be rebooted.
357// See the Reboot() function for further details.
358const (
Ash Wilson01626a32014-09-17 10:38:07 -0400359 SoftReboot RebootMethod = "SOFT"
360 HardReboot RebootMethod = "HARD"
361 OSReboot = SoftReboot
362 PowerCycle = HardReboot
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700363)
364
365// Reboot requests that a given server reboot.
366// Two methods exist for rebooting a server:
367//
Ash Wilson01626a32014-09-17 10:38:07 -0400368// HardReboot (aka PowerCycle) restarts the server instance by physically cutting power to the machine, or if a VM,
369// terminating it at the hypervisor level.
370// It's done. Caput. Full stop.
371// Then, after a brief while, power is restored or the VM instance restarted.
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700372//
Ash Wilson01626a32014-09-17 10:38:07 -0400373// SoftReboot (aka OSReboot) simply tells the OS to restart under its own procedures.
374// E.g., in Linux, asking it to enter runlevel 6, or executing "sudo shutdown -r now", or by asking Windows to restart the machine.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200375func Reboot(client *gophercloud.ServiceClient, id string, how RebootMethod) ActionResult {
376 var res ActionResult
377
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700378 if (how != SoftReboot) && (how != HardReboot) {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200379 res.Err = &ErrArgument{
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700380 Function: "Reboot",
381 Argument: "how",
Jon Perritt30558642014-04-14 17:07:12 -0500382 Value: how,
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700383 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200384 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700385 }
Jon Perritt30558642014-04-14 17:07:12 -0500386
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100387 reqBody := struct {
388 C map[string]string `json:"reboot"`
389 }{
390 map[string]string{"type": string(how)},
391 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200392
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100393 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200394 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700395}
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700396
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200397// RebuildOptsBuilder is an interface that allows extensions to override the
398// default behaviour of rebuild options
399type RebuildOptsBuilder interface {
400 ToServerRebuildMap() (map[string]interface{}, error)
401}
402
403// RebuildOpts represents the configuration options used in a server rebuild
404// operation
405type RebuildOpts struct {
406 // Required. The ID of the image you want your server to be provisioned on
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200407 ImageID string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200408
409 // Name to set the server to
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200410 Name string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200411
412 // Required. The server's admin password
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200413 AdminPass string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200414
415 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200416 AccessIPv4 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200417
418 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200419 AccessIPv6 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200420
421 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200422 Metadata map[string]string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200423
Kevin Pike92e10b52015-04-10 15:16:57 -0700424 // Personality [optional] includes files to inject into the server at launch.
425 // Rebuild will base64-encode file contents for you.
426 Personality Personality
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200427}
428
429// ToServerRebuildMap formats a RebuildOpts struct into a map for use in JSON
430func (opts RebuildOpts) ToServerRebuildMap() (map[string]interface{}, error) {
431 var err error
432 server := make(map[string]interface{})
433
434 if opts.AdminPass == "" {
435 err = fmt.Errorf("AdminPass is required")
436 }
437
438 if opts.ImageID == "" {
439 err = fmt.Errorf("ImageID is required")
440 }
441
442 if err != nil {
443 return server, err
444 }
445
446 server["name"] = opts.Name
447 server["adminPass"] = opts.AdminPass
448 server["imageRef"] = opts.ImageID
449
450 if opts.AccessIPv4 != "" {
451 server["accessIPv4"] = opts.AccessIPv4
452 }
453
454 if opts.AccessIPv6 != "" {
455 server["accessIPv6"] = opts.AccessIPv6
456 }
457
458 if opts.Metadata != nil {
459 server["metadata"] = opts.Metadata
460 }
461
Kevin Pike92e10b52015-04-10 15:16:57 -0700462 if len(opts.Personality) > 0 {
463 server["personality"] = opts.Personality.Marshal()
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200464 }
465
466 return map[string]interface{}{"rebuild": server}, nil
467}
468
469// Rebuild will reprovision the server according to the configuration options
470// provided in the RebuildOpts struct.
471func Rebuild(client *gophercloud.ServiceClient, id string, opts RebuildOptsBuilder) RebuildResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400472 var result RebuildResult
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700473
474 if id == "" {
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200475 result.Err = fmt.Errorf("ID is required")
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400476 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700477 }
478
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200479 reqBody, err := opts.ToServerRebuildMap()
480 if err != nil {
481 result.Err = err
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400482 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700483 }
484
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100485 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, nil)
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400486 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700487}
488
Ash Wilson5f7cf182014-10-23 08:35:24 -0400489// ResizeOptsBuilder is an interface that allows extensions to override the default structure of
490// a Resize request.
491type ResizeOptsBuilder interface {
492 ToServerResizeMap() (map[string]interface{}, error)
493}
494
495// ResizeOpts represents the configuration options used to control a Resize operation.
496type ResizeOpts struct {
497 // FlavorRef is the ID of the flavor you wish your server to become.
498 FlavorRef string
499}
500
Alex Gaynor266e9332014-10-28 14:44:04 -0700501// ToServerResizeMap formats a ResizeOpts as a map that can be used as a JSON request body for the
Ash Wilson5f7cf182014-10-23 08:35:24 -0400502// Resize request.
503func (opts ResizeOpts) ToServerResizeMap() (map[string]interface{}, error) {
504 resize := map[string]interface{}{
505 "flavorRef": opts.FlavorRef,
506 }
507
508 return map[string]interface{}{"resize": resize}, nil
509}
510
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700511// Resize instructs the provider to change the flavor of the server.
Ash Wilson01626a32014-09-17 10:38:07 -0400512// Note that this implies rebuilding it.
513// Unfortunately, one cannot pass rebuild parameters to the resize function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700514// When the resize completes, the server will be in RESIZE_VERIFY state.
515// While in this state, you can explore the use of the new server's configuration.
516// If you like it, call ConfirmResize() to commit the resize permanently.
517// Otherwise, call RevertResize() to restore the old configuration.
Ash Wilson9e87a922014-10-23 14:29:22 -0400518func Resize(client *gophercloud.ServiceClient, id string, opts ResizeOptsBuilder) ActionResult {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200519 var res ActionResult
Ash Wilson5f7cf182014-10-23 08:35:24 -0400520 reqBody, err := opts.ToServerResizeMap()
521 if err != nil {
522 res.Err = err
523 return res
524 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200525
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100526 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200527 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700528}
529
530// ConfirmResize confirms a previous resize operation on a server.
531// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200532func ConfirmResize(client *gophercloud.ServiceClient, id string) ActionResult {
533 var res ActionResult
534
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100535 reqBody := map[string]interface{}{"confirmResize": nil}
536 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, &gophercloud.RequestOpts{
537 OkCodes: []int{201, 202, 204},
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700538 })
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200539 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700540}
541
542// RevertResize cancels a previous resize operation on a server.
543// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200544func RevertResize(client *gophercloud.ServiceClient, id string) ActionResult {
545 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100546 reqBody := map[string]interface{}{"revertResize": nil}
547 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200548 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700549}
Alex Gaynor39584a02014-10-28 13:59:21 -0700550
Alex Gaynor266e9332014-10-28 14:44:04 -0700551// RescueOptsBuilder is an interface that allows extensions to override the
552// default structure of a Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700553type RescueOptsBuilder interface {
554 ToServerRescueMap() (map[string]interface{}, error)
555}
556
Alex Gaynor266e9332014-10-28 14:44:04 -0700557// RescueOpts represents the configuration options used to control a Rescue
558// option.
Alex Gaynor39584a02014-10-28 13:59:21 -0700559type RescueOpts struct {
Alex Gaynor266e9332014-10-28 14:44:04 -0700560 // AdminPass is the desired administrative password for the instance in
Alex Gaynorcfec7722014-11-13 13:33:49 -0800561 // RESCUE mode. If it's left blank, the server will generate a password.
Alex Gaynor39584a02014-10-28 13:59:21 -0700562 AdminPass string
563}
564
Jon Perrittcc77da62014-11-16 13:14:21 -0700565// ToServerRescueMap formats a RescueOpts as a map that can be used as a JSON
Alex Gaynor266e9332014-10-28 14:44:04 -0700566// request body for the Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700567func (opts RescueOpts) ToServerRescueMap() (map[string]interface{}, error) {
568 server := make(map[string]interface{})
569 if opts.AdminPass != "" {
570 server["adminPass"] = opts.AdminPass
571 }
572 return map[string]interface{}{"rescue": server}, nil
573}
574
Alex Gaynor266e9332014-10-28 14:44:04 -0700575// Rescue instructs the provider to place the server into RESCUE mode.
Alex Gaynorfbe61bb2014-11-12 13:35:03 -0800576func Rescue(client *gophercloud.ServiceClient, id string, opts RescueOptsBuilder) RescueResult {
577 var result RescueResult
Alex Gaynor39584a02014-10-28 13:59:21 -0700578
579 if id == "" {
580 result.Err = fmt.Errorf("ID is required")
581 return result
582 }
583 reqBody, err := opts.ToServerRescueMap()
584 if err != nil {
585 result.Err = err
586 return result
587 }
588
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100589 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
590 OkCodes: []int{200},
Alex Gaynor39584a02014-10-28 13:59:21 -0700591 })
592
593 return result
594}
Jon Perrittcc77da62014-11-16 13:14:21 -0700595
Jon Perritt789f8322014-11-21 08:20:04 -0700596// ResetMetadataOptsBuilder allows extensions to add additional parameters to the
597// Reset request.
598type ResetMetadataOptsBuilder interface {
599 ToMetadataResetMap() (map[string]interface{}, error)
Jon Perrittcc77da62014-11-16 13:14:21 -0700600}
601
Jon Perritt78c57ce2014-11-20 11:07:18 -0700602// MetadataOpts is a map that contains key-value pairs.
603type MetadataOpts map[string]string
Jon Perrittcc77da62014-11-16 13:14:21 -0700604
Jon Perritt789f8322014-11-21 08:20:04 -0700605// ToMetadataResetMap assembles a body for a Reset request based on the contents of a MetadataOpts.
606func (opts MetadataOpts) ToMetadataResetMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700607 return map[string]interface{}{"metadata": opts}, nil
608}
609
Jon Perritt78c57ce2014-11-20 11:07:18 -0700610// ToMetadataUpdateMap assembles a body for an Update request based on the contents of a MetadataOpts.
611func (opts MetadataOpts) ToMetadataUpdateMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700612 return map[string]interface{}{"metadata": opts}, nil
613}
614
Jon Perritt789f8322014-11-21 08:20:04 -0700615// ResetMetadata will create multiple new key-value pairs for the given server ID.
Jon Perrittcc77da62014-11-16 13:14:21 -0700616// Note: Using this operation will erase any already-existing metadata and create
617// the new metadata provided. To keep any already-existing metadata, use the
618// UpdateMetadatas or UpdateMetadata function.
Jon Perritt789f8322014-11-21 08:20:04 -0700619func ResetMetadata(client *gophercloud.ServiceClient, id string, opts ResetMetadataOptsBuilder) ResetMetadataResult {
620 var res ResetMetadataResult
621 metadata, err := opts.ToMetadataResetMap()
Jon Perrittcc77da62014-11-16 13:14:21 -0700622 if err != nil {
623 res.Err = err
624 return res
625 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100626 _, res.Err = client.Put(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
627 OkCodes: []int{200},
Jon Perrittcc77da62014-11-16 13:14:21 -0700628 })
629 return res
630}
631
Jon Perritt78c57ce2014-11-20 11:07:18 -0700632// Metadata requests all the metadata for the given server ID.
633func Metadata(client *gophercloud.ServiceClient, id string) GetMetadataResult {
Jon Perrittcc77da62014-11-16 13:14:21 -0700634 var res GetMetadataResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100635 _, res.Err = client.Get(metadataURL(client, id), &res.Body, nil)
Jon Perrittcc77da62014-11-16 13:14:21 -0700636 return res
637}
638
Jon Perritt78c57ce2014-11-20 11:07:18 -0700639// UpdateMetadataOptsBuilder allows extensions to add additional parameters to the
640// Create request.
641type UpdateMetadataOptsBuilder interface {
642 ToMetadataUpdateMap() (map[string]interface{}, error)
643}
644
645// UpdateMetadata updates (or creates) all the metadata specified by opts for the given server ID.
646// This operation does not affect already-existing metadata that is not specified
647// by opts.
648func UpdateMetadata(client *gophercloud.ServiceClient, id string, opts UpdateMetadataOptsBuilder) UpdateMetadataResult {
649 var res UpdateMetadataResult
650 metadata, err := opts.ToMetadataUpdateMap()
651 if err != nil {
652 res.Err = err
653 return res
654 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100655 _, res.Err = client.Post(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
656 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700657 })
658 return res
659}
660
661// MetadatumOptsBuilder allows extensions to add additional parameters to the
662// Create request.
663type MetadatumOptsBuilder interface {
664 ToMetadatumCreateMap() (map[string]interface{}, string, error)
665}
666
667// MetadatumOpts is a map of length one that contains a key-value pair.
668type MetadatumOpts map[string]string
669
670// ToMetadatumCreateMap assembles a body for a Create request based on the contents of a MetadataumOpts.
671func (opts MetadatumOpts) ToMetadatumCreateMap() (map[string]interface{}, string, error) {
672 if len(opts) != 1 {
673 return nil, "", errors.New("CreateMetadatum operation must have 1 and only 1 key-value pair.")
674 }
675 metadatum := map[string]interface{}{"meta": opts}
676 var key string
677 for k := range metadatum["meta"].(MetadatumOpts) {
678 key = k
679 }
680 return metadatum, key, nil
681}
682
683// CreateMetadatum will create or update the key-value pair with the given key for the given server ID.
684func CreateMetadatum(client *gophercloud.ServiceClient, id string, opts MetadatumOptsBuilder) CreateMetadatumResult {
685 var res CreateMetadatumResult
686 metadatum, key, err := opts.ToMetadatumCreateMap()
687 if err != nil {
688 res.Err = err
689 return res
690 }
691
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100692 _, res.Err = client.Put(metadatumURL(client, id, key), metadatum, &res.Body, &gophercloud.RequestOpts{
693 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700694 })
695 return res
696}
697
698// Metadatum requests the key-value pair with the given key for the given server ID.
699func Metadatum(client *gophercloud.ServiceClient, id, key string) GetMetadatumResult {
700 var res GetMetadatumResult
Ash Wilson59fb6c42015-02-12 16:21:13 -0500701 _, res.Err = client.Request("GET", metadatumURL(client, id, key), gophercloud.RequestOpts{
702 JSONResponse: &res.Body,
Jon Perritt78c57ce2014-11-20 11:07:18 -0700703 })
704 return res
705}
706
707// DeleteMetadatum will delete the key-value pair with the given key for the given server ID.
708func DeleteMetadatum(client *gophercloud.ServiceClient, id, key string) DeleteMetadatumResult {
709 var res DeleteMetadatumResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100710 _, res.Err = client.Delete(metadatumURL(client, id, key), &gophercloud.RequestOpts{
Ash Wilson59fb6c42015-02-12 16:21:13 -0500711 JSONResponse: &res.Body,
Jon Perrittcc77da62014-11-16 13:14:21 -0700712 })
713 return res
714}
Jon Perritt5cb49482015-02-19 12:19:58 -0700715
716// ListAddresses makes a request against the API to list the servers IP addresses.
717func ListAddresses(client *gophercloud.ServiceClient, id string) pagination.Pager {
718 createPageFn := func(r pagination.PageResult) pagination.Page {
719 return AddressPage{pagination.SinglePageBase(r)}
720 }
721 return pagination.NewPager(client, listAddressesURL(client, id), createPageFn)
722}
Jon Perritt04d073c2015-02-19 21:46:23 -0700723
724// ListAddressesByNetwork makes a request against the API to list the servers IP addresses
725// for the given network.
726func ListAddressesByNetwork(client *gophercloud.ServiceClient, id, network string) pagination.Pager {
727 createPageFn := func(r pagination.PageResult) pagination.Page {
728 return NetworkAddressPage{pagination.SinglePageBase(r)}
729 }
730 return pagination.NewPager(client, listAddressesByNetworkURL(client, id, network), createPageFn)
731}