blob: 93a340abc4a084534dac1ae2b2292e5d8a0d13cc [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"
Kevin Pikea2bfaea2015-04-21 11:45:59 -07005 "encoding/json"
Jon Perrittcc77da62014-11-16 13:14:21 -07006 "errors"
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -07007 "fmt"
Ash Wilson01626a32014-09-17 10:38:07 -04008
Ash Wilson01626a32014-09-17 10:38:07 -04009 "github.com/rackspace/gophercloud"
10 "github.com/rackspace/gophercloud/pagination"
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080011)
12
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020013// ListOptsBuilder allows extensions to add additional parameters to the
14// List request.
15type ListOptsBuilder interface {
16 ToServerListQuery() (string, error)
17}
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020018// 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.
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700100type Personality []*File
Kevin Pike92e10b52015-04-10 15:16:57 -0700101
102// File is used within CreateOpts and RebuildOpts to inject a file into the server at launch.
103type File struct {
104 // Path of the file
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700105 Path string
Kevin Pike92e10b52015-04-10 15:16:57 -0700106 // Contents of the file. Maximum content size is 255 bytes.
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700107 Contents []byte
Kevin Pike92e10b52015-04-10 15:16:57 -0700108}
109
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700110// MarshalJSON marshals the escaped file, base64 encoding the contents.
111func (f *File) MarshalJSON() ([]byte, error) {
112 file := struct {
113 Path string `json:"path"`
114 Contents string `json:"contents"`
115 }{
116 Path: f.Path,
117 Contents: base64.StdEncoding.EncodeToString(f.Contents),
Kevin Pike92e10b52015-04-10 15:16:57 -0700118 }
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700119 return json.Marshal(file)
Kevin Pike92e10b52015-04-10 15:16:57 -0700120}
121
Ash Wilson6a310e02014-09-29 08:24:02 -0400122// CreateOpts specifies server creation parameters.
123type CreateOpts struct {
124 // Name [required] is the name to assign to the newly launched server.
125 Name string
126
127 // ImageRef [required] is the ID or full URL to the image that contains the server's OS and initial state.
128 // Optional if using the boot-from-volume extension.
129 ImageRef string
130
131 // FlavorRef [required] is the ID or full URL to the flavor that describes the server's specs.
132 FlavorRef string
133
134 // SecurityGroups [optional] lists the names of the security groups to which this server should belong.
135 SecurityGroups []string
136
137 // UserData [optional] contains configuration information or scripts to use upon launch.
138 // Create will base64-encode it for you.
139 UserData []byte
140
141 // AvailabilityZone [optional] in which to launch the server.
142 AvailabilityZone string
143
144 // Networks [optional] dictates how this server will be attached to available networks.
145 // By default, the server will be attached to all isolated networks for the tenant.
146 Networks []Network
147
148 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server.
149 Metadata map[string]string
150
Kevin Pike92e10b52015-04-10 15:16:57 -0700151 // Personality [optional] includes files to inject into the server at launch.
152 // Create will base64-encode file contents for you.
153 Personality Personality
Ash Wilson6a310e02014-09-29 08:24:02 -0400154
155 // ConfigDrive [optional] enables metadata injection through a configuration drive.
156 ConfigDrive bool
Jon Perrittf3b2e142014-11-04 16:00:19 -0600157
158 // AdminPass [optional] sets the root user password. If not set, a randomly-generated
159 // password will be created and returned in the response.
160 AdminPass string
Jon Perritt7b9671c2015-02-01 22:03:14 -0700161
162 // AccessIPv4 [optional] specifies an IPv4 address for the instance.
163 AccessIPv4 string
164
165 // AccessIPv6 [optional] specifies an IPv6 address for the instance.
166 AccessIPv6 string
Ash Wilson6a310e02014-09-29 08:24:02 -0400167}
168
Ash Wilsone45c9732014-09-29 10:54:12 -0400169// ToServerCreateMap assembles a request body based on the contents of a CreateOpts.
Jon Perritt4149d7c2014-10-23 21:23:46 -0500170func (opts CreateOpts) ToServerCreateMap() (map[string]interface{}, error) {
Ash Wilson6a310e02014-09-29 08:24:02 -0400171 server := make(map[string]interface{})
172
173 server["name"] = opts.Name
174 server["imageRef"] = opts.ImageRef
175 server["flavorRef"] = opts.FlavorRef
176
177 if opts.UserData != nil {
178 encoded := base64.StdEncoding.EncodeToString(opts.UserData)
179 server["user_data"] = &encoded
180 }
Ash Wilson6a310e02014-09-29 08:24:02 -0400181 if opts.ConfigDrive {
182 server["config_drive"] = "true"
183 }
184 if opts.AvailabilityZone != "" {
185 server["availability_zone"] = opts.AvailabilityZone
186 }
187 if opts.Metadata != nil {
188 server["metadata"] = opts.Metadata
189 }
Jon Perrittf3b2e142014-11-04 16:00:19 -0600190 if opts.AdminPass != "" {
191 server["adminPass"] = opts.AdminPass
192 }
Jon Perritt7b9671c2015-02-01 22:03:14 -0700193 if opts.AccessIPv4 != "" {
194 server["accessIPv4"] = opts.AccessIPv4
195 }
196 if opts.AccessIPv6 != "" {
197 server["accessIPv6"] = opts.AccessIPv6
198 }
Ash Wilson6a310e02014-09-29 08:24:02 -0400199
200 if len(opts.SecurityGroups) > 0 {
201 securityGroups := make([]map[string]interface{}, len(opts.SecurityGroups))
202 for i, groupName := range opts.SecurityGroups {
203 securityGroups[i] = map[string]interface{}{"name": groupName}
204 }
eselldf709942014-11-13 21:07:11 -0700205 server["security_groups"] = securityGroups
Ash Wilson6a310e02014-09-29 08:24:02 -0400206 }
Jon Perritt2a7797d2014-10-21 15:08:43 -0500207
Ash Wilson6a310e02014-09-29 08:24:02 -0400208 if len(opts.Networks) > 0 {
209 networks := make([]map[string]interface{}, len(opts.Networks))
210 for i, net := range opts.Networks {
211 networks[i] = make(map[string]interface{})
212 if net.UUID != "" {
213 networks[i]["uuid"] = net.UUID
214 }
215 if net.Port != "" {
216 networks[i]["port"] = net.Port
217 }
218 if net.FixedIP != "" {
219 networks[i]["fixed_ip"] = net.FixedIP
220 }
221 }
Jon Perritt2a7797d2014-10-21 15:08:43 -0500222 server["networks"] = networks
Ash Wilson6a310e02014-09-29 08:24:02 -0400223 }
224
Kevin Pike92e10b52015-04-10 15:16:57 -0700225 if len(opts.Personality) > 0 {
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700226 server["personality"] = opts.Personality
Kevin Pike92e10b52015-04-10 15:16:57 -0700227 }
228
Jon Perritt4149d7c2014-10-23 21:23:46 -0500229 return map[string]interface{}{"server": server}, nil
Ash Wilson6a310e02014-09-29 08:24:02 -0400230}
231
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800232// Create requests a server to be provisioned to the user in the current tenant.
Ash Wilson2206a112014-10-02 10:57:38 -0400233func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult {
Jon Perritt4149d7c2014-10-23 21:23:46 -0500234 var res CreateResult
235
236 reqBody, err := opts.ToServerCreateMap()
237 if err != nil {
238 res.Err = err
239 return res
240 }
241
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100242 _, res.Err = client.Post(listURL(client), reqBody, &res.Body, nil)
Jon Perritt4149d7c2014-10-23 21:23:46 -0500243 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800244}
245
246// Delete requests that a server previously provisioned be removed from your account.
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100247func Delete(client *gophercloud.ServiceClient, id string) DeleteResult {
248 var res DeleteResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100249 _, res.Err = client.Delete(deleteURL(client, id), nil)
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100250 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800251}
252
Ash Wilson7ddf0362014-09-17 10:59:09 -0400253// Get requests details on a single server, by ID.
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400254func Get(client *gophercloud.ServiceClient, id string) GetResult {
255 var result GetResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100256 _, result.Err = client.Get(getURL(client, id), &result.Body, &gophercloud.RequestOpts{
257 OkCodes: []int{200, 203},
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800258 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400259 return result
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800260}
261
Alex Gaynora6d5f9f2014-10-27 10:52:32 -0700262// UpdateOptsBuilder allows extensions to add additional attributes to the Update request.
Jon Perritt82048212014-10-13 22:33:13 -0500263type UpdateOptsBuilder interface {
Ash Wilsone45c9732014-09-29 10:54:12 -0400264 ToServerUpdateMap() map[string]interface{}
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400265}
266
267// UpdateOpts specifies the base attributes that may be updated on an existing server.
268type UpdateOpts struct {
269 // Name [optional] changes the displayed name of the server.
270 // The server host name will *not* change.
271 // Server names are not constrained to be unique, even within the same tenant.
272 Name string
273
274 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
275 AccessIPv4 string
276
277 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
278 AccessIPv6 string
279}
280
Ash Wilsone45c9732014-09-29 10:54:12 -0400281// ToServerUpdateMap formats an UpdateOpts structure into a request body.
282func (opts UpdateOpts) ToServerUpdateMap() map[string]interface{} {
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400283 server := make(map[string]string)
284 if opts.Name != "" {
285 server["name"] = opts.Name
286 }
287 if opts.AccessIPv4 != "" {
288 server["accessIPv4"] = opts.AccessIPv4
289 }
290 if opts.AccessIPv6 != "" {
291 server["accessIPv6"] = opts.AccessIPv6
292 }
293 return map[string]interface{}{"server": server}
294}
295
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800296// Update requests that various attributes of the indicated server be changed.
Jon Perritt82048212014-10-13 22:33:13 -0500297func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400298 var result UpdateResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100299 reqBody := opts.ToServerUpdateMap()
300 _, result.Err = client.Put(updateURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
301 OkCodes: []int{200},
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800302 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400303 return result
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800304}
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700305
Ash Wilson01626a32014-09-17 10:38:07 -0400306// ChangeAdminPassword alters the administrator or root password for a specified server.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200307func ChangeAdminPassword(client *gophercloud.ServiceClient, id, newPassword string) ActionResult {
Ash Wilsondc7daa82014-09-23 16:34:42 -0400308 var req struct {
309 ChangePassword struct {
310 AdminPass string `json:"adminPass"`
311 } `json:"changePassword"`
312 }
313
314 req.ChangePassword.AdminPass = newPassword
315
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200316 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100317 _, res.Err = client.Post(actionURL(client, id), req, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200318 return res
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700319}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700320
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700321// ErrArgument errors occur when an argument supplied to a package function
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700322// fails to fall within acceptable values. For example, the Reboot() function
323// expects the "how" parameter to be one of HardReboot or SoftReboot. These
324// constants are (currently) strings, leading someone to wonder if they can pass
325// other string values instead, perhaps in an effort to break the API of their
326// provider. Reboot() returns this error in this situation.
327//
328// Function identifies which function was called/which function is generating
329// the error.
330// Argument identifies which formal argument was responsible for producing the
331// error.
332// Value provides the value as it was passed into the function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700333type ErrArgument struct {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700334 Function, Argument string
Jon Perritt30558642014-04-14 17:07:12 -0500335 Value interface{}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700336}
337
338// Error yields a useful diagnostic for debugging purposes.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700339func (e *ErrArgument) Error() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700340 return fmt.Sprintf("Bad argument in call to %s, formal parameter %s, value %#v", e.Function, e.Argument, e.Value)
341}
342
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700343func (e *ErrArgument) String() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700344 return e.Error()
345}
346
Ash Wilson01626a32014-09-17 10:38:07 -0400347// RebootMethod describes the mechanisms by which a server reboot can be requested.
348type RebootMethod string
349
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700350// These constants determine how a server should be rebooted.
351// See the Reboot() function for further details.
352const (
Ash Wilson01626a32014-09-17 10:38:07 -0400353 SoftReboot RebootMethod = "SOFT"
354 HardReboot RebootMethod = "HARD"
355 OSReboot = SoftReboot
356 PowerCycle = HardReboot
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700357)
358
359// Reboot requests that a given server reboot.
360// Two methods exist for rebooting a server:
361//
Ash Wilson01626a32014-09-17 10:38:07 -0400362// HardReboot (aka PowerCycle) restarts the server instance by physically cutting power to the machine, or if a VM,
363// terminating it at the hypervisor level.
364// It's done. Caput. Full stop.
365// Then, after a brief while, power is restored or the VM instance restarted.
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700366//
Ash Wilson01626a32014-09-17 10:38:07 -0400367// SoftReboot (aka OSReboot) simply tells the OS to restart under its own procedures.
368// 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 +0200369func Reboot(client *gophercloud.ServiceClient, id string, how RebootMethod) ActionResult {
370 var res ActionResult
371
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700372 if (how != SoftReboot) && (how != HardReboot) {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200373 res.Err = &ErrArgument{
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700374 Function: "Reboot",
375 Argument: "how",
Jon Perritt30558642014-04-14 17:07:12 -0500376 Value: how,
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700377 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200378 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700379 }
Jon Perritt30558642014-04-14 17:07:12 -0500380
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100381 reqBody := struct {
382 C map[string]string `json:"reboot"`
383 }{
384 map[string]string{"type": string(how)},
385 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200386
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100387 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200388 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700389}
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700390
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200391// RebuildOptsBuilder is an interface that allows extensions to override the
392// default behaviour of rebuild options
393type RebuildOptsBuilder interface {
394 ToServerRebuildMap() (map[string]interface{}, error)
395}
396
397// RebuildOpts represents the configuration options used in a server rebuild
398// operation
399type RebuildOpts struct {
400 // Required. The ID of the image you want your server to be provisioned on
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200401 ImageID string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200402
403 // Name to set the server to
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200404 Name string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200405
406 // Required. The server's admin password
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200407 AdminPass string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200408
409 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200410 AccessIPv4 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200411
412 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200413 AccessIPv6 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200414
415 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200416 Metadata map[string]string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200417
Kevin Pike92e10b52015-04-10 15:16:57 -0700418 // Personality [optional] includes files to inject into the server at launch.
419 // Rebuild will base64-encode file contents for you.
420 Personality Personality
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200421}
422
423// ToServerRebuildMap formats a RebuildOpts struct into a map for use in JSON
424func (opts RebuildOpts) ToServerRebuildMap() (map[string]interface{}, error) {
425 var err error
426 server := make(map[string]interface{})
427
428 if opts.AdminPass == "" {
429 err = fmt.Errorf("AdminPass is required")
430 }
431
432 if opts.ImageID == "" {
433 err = fmt.Errorf("ImageID is required")
434 }
435
436 if err != nil {
437 return server, err
438 }
439
440 server["name"] = opts.Name
441 server["adminPass"] = opts.AdminPass
442 server["imageRef"] = opts.ImageID
443
444 if opts.AccessIPv4 != "" {
445 server["accessIPv4"] = opts.AccessIPv4
446 }
447
448 if opts.AccessIPv6 != "" {
449 server["accessIPv6"] = opts.AccessIPv6
450 }
451
452 if opts.Metadata != nil {
453 server["metadata"] = opts.Metadata
454 }
455
Kevin Pike92e10b52015-04-10 15:16:57 -0700456 if len(opts.Personality) > 0 {
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700457 server["personality"] = opts.Personality
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200458 }
459
460 return map[string]interface{}{"rebuild": server}, nil
461}
462
463// Rebuild will reprovision the server according to the configuration options
464// provided in the RebuildOpts struct.
465func Rebuild(client *gophercloud.ServiceClient, id string, opts RebuildOptsBuilder) RebuildResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400466 var result RebuildResult
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700467
468 if id == "" {
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200469 result.Err = fmt.Errorf("ID is required")
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400470 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700471 }
472
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200473 reqBody, err := opts.ToServerRebuildMap()
474 if err != nil {
475 result.Err = err
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400476 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700477 }
478
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100479 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, nil)
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400480 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700481}
482
Ash Wilson5f7cf182014-10-23 08:35:24 -0400483// ResizeOptsBuilder is an interface that allows extensions to override the default structure of
484// a Resize request.
485type ResizeOptsBuilder interface {
486 ToServerResizeMap() (map[string]interface{}, error)
487}
488
489// ResizeOpts represents the configuration options used to control a Resize operation.
490type ResizeOpts struct {
491 // FlavorRef is the ID of the flavor you wish your server to become.
492 FlavorRef string
493}
494
Alex Gaynor266e9332014-10-28 14:44:04 -0700495// 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 -0400496// Resize request.
497func (opts ResizeOpts) ToServerResizeMap() (map[string]interface{}, error) {
498 resize := map[string]interface{}{
499 "flavorRef": opts.FlavorRef,
500 }
501
502 return map[string]interface{}{"resize": resize}, nil
503}
504
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700505// Resize instructs the provider to change the flavor of the server.
Ash Wilson01626a32014-09-17 10:38:07 -0400506// Note that this implies rebuilding it.
507// Unfortunately, one cannot pass rebuild parameters to the resize function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700508// When the resize completes, the server will be in RESIZE_VERIFY state.
509// While in this state, you can explore the use of the new server's configuration.
510// If you like it, call ConfirmResize() to commit the resize permanently.
511// Otherwise, call RevertResize() to restore the old configuration.
Ash Wilson9e87a922014-10-23 14:29:22 -0400512func Resize(client *gophercloud.ServiceClient, id string, opts ResizeOptsBuilder) ActionResult {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200513 var res ActionResult
Ash Wilson5f7cf182014-10-23 08:35:24 -0400514 reqBody, err := opts.ToServerResizeMap()
515 if err != nil {
516 res.Err = err
517 return res
518 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200519
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100520 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200521 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700522}
523
524// ConfirmResize confirms a previous resize operation on a server.
525// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200526func ConfirmResize(client *gophercloud.ServiceClient, id string) ActionResult {
527 var res ActionResult
528
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100529 reqBody := map[string]interface{}{"confirmResize": nil}
530 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, &gophercloud.RequestOpts{
531 OkCodes: []int{201, 202, 204},
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700532 })
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200533 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700534}
535
536// RevertResize cancels a previous resize operation on a server.
537// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200538func RevertResize(client *gophercloud.ServiceClient, id string) ActionResult {
539 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100540 reqBody := map[string]interface{}{"revertResize": nil}
541 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200542 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700543}
Alex Gaynor39584a02014-10-28 13:59:21 -0700544
Alex Gaynor266e9332014-10-28 14:44:04 -0700545// RescueOptsBuilder is an interface that allows extensions to override the
546// default structure of a Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700547type RescueOptsBuilder interface {
548 ToServerRescueMap() (map[string]interface{}, error)
549}
550
Alex Gaynor266e9332014-10-28 14:44:04 -0700551// RescueOpts represents the configuration options used to control a Rescue
552// option.
Alex Gaynor39584a02014-10-28 13:59:21 -0700553type RescueOpts struct {
Alex Gaynor266e9332014-10-28 14:44:04 -0700554 // AdminPass is the desired administrative password for the instance in
Alex Gaynorcfec7722014-11-13 13:33:49 -0800555 // RESCUE mode. If it's left blank, the server will generate a password.
Alex Gaynor39584a02014-10-28 13:59:21 -0700556 AdminPass string
557}
558
Jon Perrittcc77da62014-11-16 13:14:21 -0700559// ToServerRescueMap formats a RescueOpts as a map that can be used as a JSON
Alex Gaynor266e9332014-10-28 14:44:04 -0700560// request body for the Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700561func (opts RescueOpts) ToServerRescueMap() (map[string]interface{}, error) {
562 server := make(map[string]interface{})
563 if opts.AdminPass != "" {
564 server["adminPass"] = opts.AdminPass
565 }
566 return map[string]interface{}{"rescue": server}, nil
567}
568
Alex Gaynor266e9332014-10-28 14:44:04 -0700569// Rescue instructs the provider to place the server into RESCUE mode.
Alex Gaynorfbe61bb2014-11-12 13:35:03 -0800570func Rescue(client *gophercloud.ServiceClient, id string, opts RescueOptsBuilder) RescueResult {
571 var result RescueResult
Alex Gaynor39584a02014-10-28 13:59:21 -0700572
573 if id == "" {
574 result.Err = fmt.Errorf("ID is required")
575 return result
576 }
577 reqBody, err := opts.ToServerRescueMap()
578 if err != nil {
579 result.Err = err
580 return result
581 }
582
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100583 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
584 OkCodes: []int{200},
Alex Gaynor39584a02014-10-28 13:59:21 -0700585 })
586
587 return result
588}
Jon Perrittcc77da62014-11-16 13:14:21 -0700589
Jon Perritt789f8322014-11-21 08:20:04 -0700590// ResetMetadataOptsBuilder allows extensions to add additional parameters to the
591// Reset request.
592type ResetMetadataOptsBuilder interface {
593 ToMetadataResetMap() (map[string]interface{}, error)
Jon Perrittcc77da62014-11-16 13:14:21 -0700594}
595
Jon Perritt78c57ce2014-11-20 11:07:18 -0700596// MetadataOpts is a map that contains key-value pairs.
597type MetadataOpts map[string]string
Jon Perrittcc77da62014-11-16 13:14:21 -0700598
Jon Perritt789f8322014-11-21 08:20:04 -0700599// ToMetadataResetMap assembles a body for a Reset request based on the contents of a MetadataOpts.
600func (opts MetadataOpts) ToMetadataResetMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700601 return map[string]interface{}{"metadata": opts}, nil
602}
603
Jon Perritt78c57ce2014-11-20 11:07:18 -0700604// ToMetadataUpdateMap assembles a body for an Update request based on the contents of a MetadataOpts.
605func (opts MetadataOpts) ToMetadataUpdateMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700606 return map[string]interface{}{"metadata": opts}, nil
607}
608
Jon Perritt789f8322014-11-21 08:20:04 -0700609// ResetMetadata will create multiple new key-value pairs for the given server ID.
Jon Perrittcc77da62014-11-16 13:14:21 -0700610// Note: Using this operation will erase any already-existing metadata and create
611// the new metadata provided. To keep any already-existing metadata, use the
612// UpdateMetadatas or UpdateMetadata function.
Jon Perritt789f8322014-11-21 08:20:04 -0700613func ResetMetadata(client *gophercloud.ServiceClient, id string, opts ResetMetadataOptsBuilder) ResetMetadataResult {
614 var res ResetMetadataResult
615 metadata, err := opts.ToMetadataResetMap()
Jon Perrittcc77da62014-11-16 13:14:21 -0700616 if err != nil {
617 res.Err = err
618 return res
619 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100620 _, res.Err = client.Put(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
621 OkCodes: []int{200},
Jon Perrittcc77da62014-11-16 13:14:21 -0700622 })
623 return res
624}
625
Jon Perritt78c57ce2014-11-20 11:07:18 -0700626// Metadata requests all the metadata for the given server ID.
627func Metadata(client *gophercloud.ServiceClient, id string) GetMetadataResult {
Jon Perrittcc77da62014-11-16 13:14:21 -0700628 var res GetMetadataResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100629 _, res.Err = client.Get(metadataURL(client, id), &res.Body, nil)
Jon Perrittcc77da62014-11-16 13:14:21 -0700630 return res
631}
632
Jon Perritt78c57ce2014-11-20 11:07:18 -0700633// UpdateMetadataOptsBuilder allows extensions to add additional parameters to the
634// Create request.
635type UpdateMetadataOptsBuilder interface {
636 ToMetadataUpdateMap() (map[string]interface{}, error)
637}
638
639// UpdateMetadata updates (or creates) all the metadata specified by opts for the given server ID.
640// This operation does not affect already-existing metadata that is not specified
641// by opts.
642func UpdateMetadata(client *gophercloud.ServiceClient, id string, opts UpdateMetadataOptsBuilder) UpdateMetadataResult {
643 var res UpdateMetadataResult
644 metadata, err := opts.ToMetadataUpdateMap()
645 if err != nil {
646 res.Err = err
647 return res
648 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100649 _, res.Err = client.Post(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
650 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700651 })
652 return res
653}
654
655// MetadatumOptsBuilder allows extensions to add additional parameters to the
656// Create request.
657type MetadatumOptsBuilder interface {
658 ToMetadatumCreateMap() (map[string]interface{}, string, error)
659}
660
661// MetadatumOpts is a map of length one that contains a key-value pair.
662type MetadatumOpts map[string]string
663
664// ToMetadatumCreateMap assembles a body for a Create request based on the contents of a MetadataumOpts.
665func (opts MetadatumOpts) ToMetadatumCreateMap() (map[string]interface{}, string, error) {
666 if len(opts) != 1 {
667 return nil, "", errors.New("CreateMetadatum operation must have 1 and only 1 key-value pair.")
668 }
669 metadatum := map[string]interface{}{"meta": opts}
670 var key string
671 for k := range metadatum["meta"].(MetadatumOpts) {
672 key = k
673 }
674 return metadatum, key, nil
675}
676
677// CreateMetadatum will create or update the key-value pair with the given key for the given server ID.
678func CreateMetadatum(client *gophercloud.ServiceClient, id string, opts MetadatumOptsBuilder) CreateMetadatumResult {
679 var res CreateMetadatumResult
680 metadatum, key, err := opts.ToMetadatumCreateMap()
681 if err != nil {
682 res.Err = err
683 return res
684 }
685
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100686 _, res.Err = client.Put(metadatumURL(client, id, key), metadatum, &res.Body, &gophercloud.RequestOpts{
687 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700688 })
689 return res
690}
691
692// Metadatum requests the key-value pair with the given key for the given server ID.
693func Metadatum(client *gophercloud.ServiceClient, id, key string) GetMetadatumResult {
694 var res GetMetadatumResult
Ash Wilson59fb6c42015-02-12 16:21:13 -0500695 _, res.Err = client.Request("GET", metadatumURL(client, id, key), gophercloud.RequestOpts{
696 JSONResponse: &res.Body,
Jon Perritt78c57ce2014-11-20 11:07:18 -0700697 })
698 return res
699}
700
701// DeleteMetadatum will delete the key-value pair with the given key for the given server ID.
702func DeleteMetadatum(client *gophercloud.ServiceClient, id, key string) DeleteMetadatumResult {
703 var res DeleteMetadatumResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100704 _, res.Err = client.Delete(metadatumURL(client, id, key), &gophercloud.RequestOpts{
Ash Wilson59fb6c42015-02-12 16:21:13 -0500705 JSONResponse: &res.Body,
Jon Perrittcc77da62014-11-16 13:14:21 -0700706 })
707 return res
708}
Jon Perritt5cb49482015-02-19 12:19:58 -0700709
710// ListAddresses makes a request against the API to list the servers IP addresses.
711func ListAddresses(client *gophercloud.ServiceClient, id string) pagination.Pager {
712 createPageFn := func(r pagination.PageResult) pagination.Page {
713 return AddressPage{pagination.SinglePageBase(r)}
714 }
715 return pagination.NewPager(client, listAddressesURL(client, id), createPageFn)
716}
Jon Perritt04d073c2015-02-19 21:46:23 -0700717
718// ListAddressesByNetwork makes a request against the API to list the servers IP addresses
719// for the given network.
720func ListAddressesByNetwork(client *gophercloud.ServiceClient, id, network string) pagination.Pager {
721 createPageFn := func(r pagination.PageResult) pagination.Page {
722 return NetworkAddressPage{pagination.SinglePageBase(r)}
723 }
724 return pagination.NewPager(client, listAddressesByNetworkURL(client, id, network), createPageFn)
725}
einarf2fc665e2015-04-16 20:16:21 +0000726
einarf4e5fdaf2015-04-16 23:14:59 +0000727type CreateImageOpts struct {
einarf2fc665e2015-04-16 20:16:21 +0000728 // Name [required] of the image/snapshot
729 Name string
730 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the created image.
731 Metadata map[string]string
732}
733
einarf4e5fdaf2015-04-16 23:14:59 +0000734type CreateImageOptsBuilder interface {
735 ToServerCreateImageMap() (map[string]interface{}, error)
einarf2fc665e2015-04-16 20:16:21 +0000736}
737
einarf4e5fdaf2015-04-16 23:14:59 +0000738// ToServerCreateImageMap formats a CreateImageOpts structure into a request body.
739func (opts CreateImageOpts) ToServerCreateImageMap() (map[string]interface{}, error) {
einarf2fc665e2015-04-16 20:16:21 +0000740 var err error
741 img := make(map[string]interface{})
742 if opts.Name == "" {
einarf4e5fdaf2015-04-16 23:14:59 +0000743 return nil, fmt.Errorf("Cannot create a server image without a name")
einarf2fc665e2015-04-16 20:16:21 +0000744 }
745 img["name"] = opts.Name
746 if opts.Metadata != nil {
747 img["metadata"] = opts.Metadata
748 }
749 createImage := make(map[string]interface{})
750 createImage["createImage"] = img
751 return createImage, err
752}
753
einarf4e5fdaf2015-04-16 23:14:59 +0000754// CreateImage makes a request against the nova API to schedule an image to be created of the server
755func CreateImage(client *gophercloud.ServiceClient, serverId string, opts CreateImageOptsBuilder) CreateImageResult {
756 var res CreateImageResult
757 reqBody, err := opts.ToServerCreateImageMap()
einarf2fc665e2015-04-16 20:16:21 +0000758 if err != nil {
759 res.Err = err
760 return res
761 }
762 response, err := client.Post(actionURL(client, serverId), reqBody, nil, &gophercloud.RequestOpts{
763 OkCodes: []int{202},
764 })
765 res.Err = err
einarf4e5fdaf2015-04-16 23:14:59 +0000766 res.Header = response.Header
einarf2fc665e2015-04-16 20:16:21 +0000767 return res
768}