blob: af77546e5cbdb9f11d01e45f97983646b5a8e6a1 [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}
Kevin Pike9748b7b2015-05-05 07:34:07 -070018
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020019// ListOpts allows the filtering and sorting of paginated collections through
20// the API. Filtering is achieved by passing in struct field values that map to
21// the server attributes you want to see returned. Marker and Limit are used
22// for pagination.
23type ListOpts struct {
24 // A time/date stamp for when the server last changed status.
25 ChangesSince string `q:"changes-since"`
26
27 // Name of the image in URL format.
28 Image string `q:"image"`
29
30 // Name of the flavor in URL format.
31 Flavor string `q:"flavor"`
32
33 // Name of the server as a string; can be queried with regular expressions.
34 // Realize that ?name=bob returns both bob and bobb. If you need to match bob
35 // only, you can use a regular expression matching the syntax of the
36 // underlying database server implemented for Compute.
37 Name string `q:"name"`
38
39 // Value of the status of the server so that you can filter on "ACTIVE" for example.
40 Status string `q:"status"`
41
42 // Name of the host as a string.
43 Host string `q:"host"`
44
45 // UUID of the server at which you want to set a marker.
46 Marker string `q:"marker"`
47
48 // Integer value for the limit of values to return.
49 Limit int `q:"limit"`
50}
51
52// ToServerListQuery formats a ListOpts into a query string.
53func (opts ListOpts) ToServerListQuery() (string, error) {
54 q, err := gophercloud.BuildQueryString(opts)
55 if err != nil {
56 return "", err
57 }
58 return q.String(), nil
59}
60
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080061// List makes a request against the API to list servers accessible to you.
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020062func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {
63 url := listDetailURL(client)
64
65 if opts != nil {
66 query, err := opts.ToServerListQuery()
67 if err != nil {
68 return pagination.Pager{Err: err}
69 }
70 url += query
71 }
72
Ash Wilsonb8b16f82014-10-20 10:19:49 -040073 createPageFn := func(r pagination.PageResult) pagination.Page {
74 return ServerPage{pagination.LinkedPageBase{PageResult: r}}
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080075 }
76
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020077 return pagination.NewPager(client, url, createPageFn)
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080078}
79
Ash Wilson2206a112014-10-02 10:57:38 -040080// CreateOptsBuilder describes struct types that can be accepted by the Create call.
Ash Wilson6a310e02014-09-29 08:24:02 -040081// The CreateOpts struct in this package does.
Ash Wilson2206a112014-10-02 10:57:38 -040082type CreateOptsBuilder interface {
Jon Perritt4149d7c2014-10-23 21:23:46 -050083 ToServerCreateMap() (map[string]interface{}, error)
Ash Wilson6a310e02014-09-29 08:24:02 -040084}
85
86// Network is used within CreateOpts to control a new server's network attachments.
87type Network struct {
88 // UUID of a nova-network to attach to the newly provisioned server.
89 // Required unless Port is provided.
90 UUID string
91
92 // Port of a neutron network to attach to the newly provisioned server.
93 // Required unless UUID is provided.
94 Port string
95
96 // FixedIP [optional] specifies a fixed IPv4 address to be used on this network.
97 FixedIP string
98}
99
Kevin Pike92e10b52015-04-10 15:16:57 -0700100// Personality is an array of files that are injected into the server at launch.
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700101type Personality []*File
Kevin Pike92e10b52015-04-10 15:16:57 -0700102
103// File is used within CreateOpts and RebuildOpts to inject a file into the server at launch.
Kevin Pike9748b7b2015-05-05 07:34:07 -0700104// File implements the json.Marshaler interface, so when a Create or Rebuild operation is requested,
105// json.Marshal will call File's MarshalJSON method.
Kevin Pike92e10b52015-04-10 15:16:57 -0700106type File struct {
107 // Path of the file
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700108 Path string
Kevin Pike92e10b52015-04-10 15:16:57 -0700109 // Contents of the file. Maximum content size is 255 bytes.
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700110 Contents []byte
Kevin Pike92e10b52015-04-10 15:16:57 -0700111}
112
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700113// MarshalJSON marshals the escaped file, base64 encoding the contents.
114func (f *File) MarshalJSON() ([]byte, error) {
115 file := struct {
116 Path string `json:"path"`
117 Contents string `json:"contents"`
118 }{
119 Path: f.Path,
120 Contents: base64.StdEncoding.EncodeToString(f.Contents),
Kevin Pike92e10b52015-04-10 15:16:57 -0700121 }
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700122 return json.Marshal(file)
Kevin Pike92e10b52015-04-10 15:16:57 -0700123}
124
Ash Wilson6a310e02014-09-29 08:24:02 -0400125// CreateOpts specifies server creation parameters.
126type CreateOpts struct {
127 // Name [required] is the name to assign to the newly launched server.
128 Name string
129
130 // ImageRef [required] is the ID or full URL to the image that contains the server's OS and initial state.
131 // Optional if using the boot-from-volume extension.
132 ImageRef string
133
134 // FlavorRef [required] is the ID or full URL to the flavor that describes the server's specs.
135 FlavorRef string
136
137 // SecurityGroups [optional] lists the names of the security groups to which this server should belong.
138 SecurityGroups []string
139
140 // UserData [optional] contains configuration information or scripts to use upon launch.
141 // Create will base64-encode it for you.
142 UserData []byte
143
144 // AvailabilityZone [optional] in which to launch the server.
145 AvailabilityZone string
146
147 // Networks [optional] dictates how this server will be attached to available networks.
148 // By default, the server will be attached to all isolated networks for the tenant.
149 Networks []Network
150
151 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server.
152 Metadata map[string]string
153
Kevin Pike92e10b52015-04-10 15:16:57 -0700154 // Personality [optional] includes files to inject into the server at launch.
155 // Create will base64-encode file contents for you.
156 Personality Personality
Ash Wilson6a310e02014-09-29 08:24:02 -0400157
158 // ConfigDrive [optional] enables metadata injection through a configuration drive.
159 ConfigDrive bool
Jon Perrittf3b2e142014-11-04 16:00:19 -0600160
161 // AdminPass [optional] sets the root user password. If not set, a randomly-generated
162 // password will be created and returned in the response.
163 AdminPass string
Jon Perritt7b9671c2015-02-01 22:03:14 -0700164
165 // AccessIPv4 [optional] specifies an IPv4 address for the instance.
166 AccessIPv4 string
167
168 // AccessIPv6 [optional] specifies an IPv6 address for the instance.
169 AccessIPv6 string
Ash Wilson6a310e02014-09-29 08:24:02 -0400170}
171
Ash Wilsone45c9732014-09-29 10:54:12 -0400172// ToServerCreateMap assembles a request body based on the contents of a CreateOpts.
Jon Perritt4149d7c2014-10-23 21:23:46 -0500173func (opts CreateOpts) ToServerCreateMap() (map[string]interface{}, error) {
Ash Wilson6a310e02014-09-29 08:24:02 -0400174 server := make(map[string]interface{})
175
176 server["name"] = opts.Name
177 server["imageRef"] = opts.ImageRef
178 server["flavorRef"] = opts.FlavorRef
179
180 if opts.UserData != nil {
181 encoded := base64.StdEncoding.EncodeToString(opts.UserData)
182 server["user_data"] = &encoded
183 }
Ash Wilson6a310e02014-09-29 08:24:02 -0400184 if opts.ConfigDrive {
185 server["config_drive"] = "true"
186 }
187 if opts.AvailabilityZone != "" {
188 server["availability_zone"] = opts.AvailabilityZone
189 }
190 if opts.Metadata != nil {
191 server["metadata"] = opts.Metadata
192 }
Jon Perrittf3b2e142014-11-04 16:00:19 -0600193 if opts.AdminPass != "" {
194 server["adminPass"] = opts.AdminPass
195 }
Jon Perritt7b9671c2015-02-01 22:03:14 -0700196 if opts.AccessIPv4 != "" {
197 server["accessIPv4"] = opts.AccessIPv4
198 }
199 if opts.AccessIPv6 != "" {
200 server["accessIPv6"] = opts.AccessIPv6
201 }
Ash Wilson6a310e02014-09-29 08:24:02 -0400202
203 if len(opts.SecurityGroups) > 0 {
204 securityGroups := make([]map[string]interface{}, len(opts.SecurityGroups))
205 for i, groupName := range opts.SecurityGroups {
206 securityGroups[i] = map[string]interface{}{"name": groupName}
207 }
eselldf709942014-11-13 21:07:11 -0700208 server["security_groups"] = securityGroups
Ash Wilson6a310e02014-09-29 08:24:02 -0400209 }
Jon Perritt2a7797d2014-10-21 15:08:43 -0500210
Ash Wilson6a310e02014-09-29 08:24:02 -0400211 if len(opts.Networks) > 0 {
212 networks := make([]map[string]interface{}, len(opts.Networks))
213 for i, net := range opts.Networks {
214 networks[i] = make(map[string]interface{})
215 if net.UUID != "" {
216 networks[i]["uuid"] = net.UUID
217 }
218 if net.Port != "" {
219 networks[i]["port"] = net.Port
220 }
221 if net.FixedIP != "" {
222 networks[i]["fixed_ip"] = net.FixedIP
223 }
224 }
Jon Perritt2a7797d2014-10-21 15:08:43 -0500225 server["networks"] = networks
Ash Wilson6a310e02014-09-29 08:24:02 -0400226 }
227
Kevin Pike92e10b52015-04-10 15:16:57 -0700228 if len(opts.Personality) > 0 {
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700229 server["personality"] = opts.Personality
Kevin Pike92e10b52015-04-10 15:16:57 -0700230 }
231
Jon Perritt4149d7c2014-10-23 21:23:46 -0500232 return map[string]interface{}{"server": server}, nil
Ash Wilson6a310e02014-09-29 08:24:02 -0400233}
234
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800235// Create requests a server to be provisioned to the user in the current tenant.
Ash Wilson2206a112014-10-02 10:57:38 -0400236func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult {
Jon Perritt4149d7c2014-10-23 21:23:46 -0500237 var res CreateResult
238
239 reqBody, err := opts.ToServerCreateMap()
240 if err != nil {
241 res.Err = err
242 return res
243 }
244
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100245 _, res.Err = client.Post(listURL(client), reqBody, &res.Body, nil)
Jon Perritt4149d7c2014-10-23 21:23:46 -0500246 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800247}
248
249// Delete requests that a server previously provisioned be removed from your account.
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100250func Delete(client *gophercloud.ServiceClient, id string) DeleteResult {
251 var res DeleteResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100252 _, res.Err = client.Delete(deleteURL(client, id), nil)
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100253 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800254}
255
Ash Wilson7ddf0362014-09-17 10:59:09 -0400256// Get requests details on a single server, by ID.
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400257func Get(client *gophercloud.ServiceClient, id string) GetResult {
258 var result GetResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100259 _, result.Err = client.Get(getURL(client, id), &result.Body, &gophercloud.RequestOpts{
260 OkCodes: []int{200, 203},
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800261 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400262 return result
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800263}
264
Alex Gaynora6d5f9f2014-10-27 10:52:32 -0700265// UpdateOptsBuilder allows extensions to add additional attributes to the Update request.
Jon Perritt82048212014-10-13 22:33:13 -0500266type UpdateOptsBuilder interface {
Ash Wilsone45c9732014-09-29 10:54:12 -0400267 ToServerUpdateMap() map[string]interface{}
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400268}
269
270// UpdateOpts specifies the base attributes that may be updated on an existing server.
271type UpdateOpts struct {
272 // Name [optional] changes the displayed name of the server.
273 // The server host name will *not* change.
274 // Server names are not constrained to be unique, even within the same tenant.
275 Name string
276
277 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
278 AccessIPv4 string
279
280 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
281 AccessIPv6 string
282}
283
Ash Wilsone45c9732014-09-29 10:54:12 -0400284// ToServerUpdateMap formats an UpdateOpts structure into a request body.
285func (opts UpdateOpts) ToServerUpdateMap() map[string]interface{} {
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400286 server := make(map[string]string)
287 if opts.Name != "" {
288 server["name"] = opts.Name
289 }
290 if opts.AccessIPv4 != "" {
291 server["accessIPv4"] = opts.AccessIPv4
292 }
293 if opts.AccessIPv6 != "" {
294 server["accessIPv6"] = opts.AccessIPv6
295 }
296 return map[string]interface{}{"server": server}
297}
298
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800299// Update requests that various attributes of the indicated server be changed.
Jon Perritt82048212014-10-13 22:33:13 -0500300func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400301 var result UpdateResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100302 reqBody := opts.ToServerUpdateMap()
303 _, result.Err = client.Put(updateURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
304 OkCodes: []int{200},
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800305 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400306 return result
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800307}
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700308
Ash Wilson01626a32014-09-17 10:38:07 -0400309// ChangeAdminPassword alters the administrator or root password for a specified server.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200310func ChangeAdminPassword(client *gophercloud.ServiceClient, id, newPassword string) ActionResult {
Ash Wilsondc7daa82014-09-23 16:34:42 -0400311 var req struct {
312 ChangePassword struct {
313 AdminPass string `json:"adminPass"`
314 } `json:"changePassword"`
315 }
316
317 req.ChangePassword.AdminPass = newPassword
318
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200319 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100320 _, res.Err = client.Post(actionURL(client, id), req, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200321 return res
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700322}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700323
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700324// ErrArgument errors occur when an argument supplied to a package function
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700325// fails to fall within acceptable values. For example, the Reboot() function
326// expects the "how" parameter to be one of HardReboot or SoftReboot. These
327// constants are (currently) strings, leading someone to wonder if they can pass
328// other string values instead, perhaps in an effort to break the API of their
329// provider. Reboot() returns this error in this situation.
330//
331// Function identifies which function was called/which function is generating
332// the error.
333// Argument identifies which formal argument was responsible for producing the
334// error.
335// Value provides the value as it was passed into the function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700336type ErrArgument struct {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700337 Function, Argument string
Jon Perritt30558642014-04-14 17:07:12 -0500338 Value interface{}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700339}
340
341// Error yields a useful diagnostic for debugging purposes.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700342func (e *ErrArgument) Error() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700343 return fmt.Sprintf("Bad argument in call to %s, formal parameter %s, value %#v", e.Function, e.Argument, e.Value)
344}
345
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700346func (e *ErrArgument) String() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700347 return e.Error()
348}
349
Ash Wilson01626a32014-09-17 10:38:07 -0400350// RebootMethod describes the mechanisms by which a server reboot can be requested.
351type RebootMethod string
352
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700353// These constants determine how a server should be rebooted.
354// See the Reboot() function for further details.
355const (
Ash Wilson01626a32014-09-17 10:38:07 -0400356 SoftReboot RebootMethod = "SOFT"
357 HardReboot RebootMethod = "HARD"
358 OSReboot = SoftReboot
359 PowerCycle = HardReboot
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700360)
361
362// Reboot requests that a given server reboot.
363// Two methods exist for rebooting a server:
364//
Ash Wilson01626a32014-09-17 10:38:07 -0400365// HardReboot (aka PowerCycle) restarts the server instance by physically cutting power to the machine, or if a VM,
366// terminating it at the hypervisor level.
367// It's done. Caput. Full stop.
368// Then, after a brief while, power is restored or the VM instance restarted.
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700369//
Ash Wilson01626a32014-09-17 10:38:07 -0400370// SoftReboot (aka OSReboot) simply tells the OS to restart under its own procedures.
371// 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 +0200372func Reboot(client *gophercloud.ServiceClient, id string, how RebootMethod) ActionResult {
373 var res ActionResult
374
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700375 if (how != SoftReboot) && (how != HardReboot) {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200376 res.Err = &ErrArgument{
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700377 Function: "Reboot",
378 Argument: "how",
Jon Perritt30558642014-04-14 17:07:12 -0500379 Value: how,
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700380 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200381 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700382 }
Jon Perritt30558642014-04-14 17:07:12 -0500383
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100384 reqBody := struct {
385 C map[string]string `json:"reboot"`
386 }{
387 map[string]string{"type": string(how)},
388 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200389
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100390 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200391 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700392}
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700393
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200394// RebuildOptsBuilder is an interface that allows extensions to override the
395// default behaviour of rebuild options
396type RebuildOptsBuilder interface {
397 ToServerRebuildMap() (map[string]interface{}, error)
398}
399
400// RebuildOpts represents the configuration options used in a server rebuild
401// operation
402type RebuildOpts struct {
403 // Required. The ID of the image you want your server to be provisioned on
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200404 ImageID string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200405
406 // Name to set the server to
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200407 Name string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200408
409 // Required. The server's admin password
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200410 AdminPass string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200411
412 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200413 AccessIPv4 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200414
415 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200416 AccessIPv6 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200417
418 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200419 Metadata map[string]string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200420
Kevin Pike92e10b52015-04-10 15:16:57 -0700421 // Personality [optional] includes files to inject into the server at launch.
422 // Rebuild will base64-encode file contents for you.
423 Personality Personality
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200424}
425
426// ToServerRebuildMap formats a RebuildOpts struct into a map for use in JSON
427func (opts RebuildOpts) ToServerRebuildMap() (map[string]interface{}, error) {
428 var err error
429 server := make(map[string]interface{})
430
431 if opts.AdminPass == "" {
432 err = fmt.Errorf("AdminPass is required")
433 }
434
435 if opts.ImageID == "" {
436 err = fmt.Errorf("ImageID is required")
437 }
438
439 if err != nil {
440 return server, err
441 }
442
443 server["name"] = opts.Name
444 server["adminPass"] = opts.AdminPass
445 server["imageRef"] = opts.ImageID
446
447 if opts.AccessIPv4 != "" {
448 server["accessIPv4"] = opts.AccessIPv4
449 }
450
451 if opts.AccessIPv6 != "" {
452 server["accessIPv6"] = opts.AccessIPv6
453 }
454
455 if opts.Metadata != nil {
456 server["metadata"] = opts.Metadata
457 }
458
Kevin Pike92e10b52015-04-10 15:16:57 -0700459 if len(opts.Personality) > 0 {
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700460 server["personality"] = opts.Personality
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200461 }
462
463 return map[string]interface{}{"rebuild": server}, nil
464}
465
466// Rebuild will reprovision the server according to the configuration options
467// provided in the RebuildOpts struct.
468func Rebuild(client *gophercloud.ServiceClient, id string, opts RebuildOptsBuilder) RebuildResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400469 var result RebuildResult
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700470
471 if id == "" {
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200472 result.Err = fmt.Errorf("ID is required")
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400473 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700474 }
475
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200476 reqBody, err := opts.ToServerRebuildMap()
477 if err != nil {
478 result.Err = err
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400479 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700480 }
481
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100482 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, nil)
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400483 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700484}
485
Ash Wilson5f7cf182014-10-23 08:35:24 -0400486// ResizeOptsBuilder is an interface that allows extensions to override the default structure of
487// a Resize request.
488type ResizeOptsBuilder interface {
489 ToServerResizeMap() (map[string]interface{}, error)
490}
491
492// ResizeOpts represents the configuration options used to control a Resize operation.
493type ResizeOpts struct {
494 // FlavorRef is the ID of the flavor you wish your server to become.
495 FlavorRef string
496}
497
Alex Gaynor266e9332014-10-28 14:44:04 -0700498// 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 -0400499// Resize request.
500func (opts ResizeOpts) ToServerResizeMap() (map[string]interface{}, error) {
501 resize := map[string]interface{}{
502 "flavorRef": opts.FlavorRef,
503 }
504
505 return map[string]interface{}{"resize": resize}, nil
506}
507
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700508// Resize instructs the provider to change the flavor of the server.
Ash Wilson01626a32014-09-17 10:38:07 -0400509// Note that this implies rebuilding it.
510// Unfortunately, one cannot pass rebuild parameters to the resize function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700511// When the resize completes, the server will be in RESIZE_VERIFY state.
512// While in this state, you can explore the use of the new server's configuration.
513// If you like it, call ConfirmResize() to commit the resize permanently.
514// Otherwise, call RevertResize() to restore the old configuration.
Ash Wilson9e87a922014-10-23 14:29:22 -0400515func Resize(client *gophercloud.ServiceClient, id string, opts ResizeOptsBuilder) ActionResult {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200516 var res ActionResult
Ash Wilson5f7cf182014-10-23 08:35:24 -0400517 reqBody, err := opts.ToServerResizeMap()
518 if err != nil {
519 res.Err = err
520 return res
521 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200522
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100523 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200524 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700525}
526
527// ConfirmResize confirms a previous resize operation on a server.
528// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200529func ConfirmResize(client *gophercloud.ServiceClient, id string) ActionResult {
530 var res ActionResult
531
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100532 reqBody := map[string]interface{}{"confirmResize": nil}
533 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, &gophercloud.RequestOpts{
534 OkCodes: []int{201, 202, 204},
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700535 })
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200536 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700537}
538
539// RevertResize cancels a previous resize operation on a server.
540// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200541func RevertResize(client *gophercloud.ServiceClient, id string) ActionResult {
542 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100543 reqBody := map[string]interface{}{"revertResize": nil}
544 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200545 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700546}
Alex Gaynor39584a02014-10-28 13:59:21 -0700547
Alex Gaynor266e9332014-10-28 14:44:04 -0700548// RescueOptsBuilder is an interface that allows extensions to override the
549// default structure of a Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700550type RescueOptsBuilder interface {
551 ToServerRescueMap() (map[string]interface{}, error)
552}
553
Alex Gaynor266e9332014-10-28 14:44:04 -0700554// RescueOpts represents the configuration options used to control a Rescue
555// option.
Alex Gaynor39584a02014-10-28 13:59:21 -0700556type RescueOpts struct {
Alex Gaynor266e9332014-10-28 14:44:04 -0700557 // AdminPass is the desired administrative password for the instance in
Alex Gaynorcfec7722014-11-13 13:33:49 -0800558 // RESCUE mode. If it's left blank, the server will generate a password.
Alex Gaynor39584a02014-10-28 13:59:21 -0700559 AdminPass string
560}
561
Jon Perrittcc77da62014-11-16 13:14:21 -0700562// ToServerRescueMap formats a RescueOpts as a map that can be used as a JSON
Alex Gaynor266e9332014-10-28 14:44:04 -0700563// request body for the Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700564func (opts RescueOpts) ToServerRescueMap() (map[string]interface{}, error) {
565 server := make(map[string]interface{})
566 if opts.AdminPass != "" {
567 server["adminPass"] = opts.AdminPass
568 }
569 return map[string]interface{}{"rescue": server}, nil
570}
571
Alex Gaynor266e9332014-10-28 14:44:04 -0700572// Rescue instructs the provider to place the server into RESCUE mode.
Alex Gaynorfbe61bb2014-11-12 13:35:03 -0800573func Rescue(client *gophercloud.ServiceClient, id string, opts RescueOptsBuilder) RescueResult {
574 var result RescueResult
Alex Gaynor39584a02014-10-28 13:59:21 -0700575
576 if id == "" {
577 result.Err = fmt.Errorf("ID is required")
578 return result
579 }
580 reqBody, err := opts.ToServerRescueMap()
581 if err != nil {
582 result.Err = err
583 return result
584 }
585
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100586 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
587 OkCodes: []int{200},
Alex Gaynor39584a02014-10-28 13:59:21 -0700588 })
589
590 return result
591}
Jon Perrittcc77da62014-11-16 13:14:21 -0700592
Jon Perritt789f8322014-11-21 08:20:04 -0700593// ResetMetadataOptsBuilder allows extensions to add additional parameters to the
594// Reset request.
595type ResetMetadataOptsBuilder interface {
596 ToMetadataResetMap() (map[string]interface{}, error)
Jon Perrittcc77da62014-11-16 13:14:21 -0700597}
598
Jon Perritt78c57ce2014-11-20 11:07:18 -0700599// MetadataOpts is a map that contains key-value pairs.
600type MetadataOpts map[string]string
Jon Perrittcc77da62014-11-16 13:14:21 -0700601
Jon Perritt789f8322014-11-21 08:20:04 -0700602// ToMetadataResetMap assembles a body for a Reset request based on the contents of a MetadataOpts.
603func (opts MetadataOpts) ToMetadataResetMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700604 return map[string]interface{}{"metadata": opts}, nil
605}
606
Jon Perritt78c57ce2014-11-20 11:07:18 -0700607// ToMetadataUpdateMap assembles a body for an Update request based on the contents of a MetadataOpts.
608func (opts MetadataOpts) ToMetadataUpdateMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700609 return map[string]interface{}{"metadata": opts}, nil
610}
611
Jon Perritt789f8322014-11-21 08:20:04 -0700612// ResetMetadata will create multiple new key-value pairs for the given server ID.
Jon Perrittcc77da62014-11-16 13:14:21 -0700613// Note: Using this operation will erase any already-existing metadata and create
614// the new metadata provided. To keep any already-existing metadata, use the
615// UpdateMetadatas or UpdateMetadata function.
Jon Perritt789f8322014-11-21 08:20:04 -0700616func ResetMetadata(client *gophercloud.ServiceClient, id string, opts ResetMetadataOptsBuilder) ResetMetadataResult {
617 var res ResetMetadataResult
618 metadata, err := opts.ToMetadataResetMap()
Jon Perrittcc77da62014-11-16 13:14:21 -0700619 if err != nil {
620 res.Err = err
621 return res
622 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100623 _, res.Err = client.Put(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
624 OkCodes: []int{200},
Jon Perrittcc77da62014-11-16 13:14:21 -0700625 })
626 return res
627}
628
Jon Perritt78c57ce2014-11-20 11:07:18 -0700629// Metadata requests all the metadata for the given server ID.
630func Metadata(client *gophercloud.ServiceClient, id string) GetMetadataResult {
Jon Perrittcc77da62014-11-16 13:14:21 -0700631 var res GetMetadataResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100632 _, res.Err = client.Get(metadataURL(client, id), &res.Body, nil)
Jon Perrittcc77da62014-11-16 13:14:21 -0700633 return res
634}
635
Jon Perritt78c57ce2014-11-20 11:07:18 -0700636// UpdateMetadataOptsBuilder allows extensions to add additional parameters to the
637// Create request.
638type UpdateMetadataOptsBuilder interface {
639 ToMetadataUpdateMap() (map[string]interface{}, error)
640}
641
642// UpdateMetadata updates (or creates) all the metadata specified by opts for the given server ID.
643// This operation does not affect already-existing metadata that is not specified
644// by opts.
645func UpdateMetadata(client *gophercloud.ServiceClient, id string, opts UpdateMetadataOptsBuilder) UpdateMetadataResult {
646 var res UpdateMetadataResult
647 metadata, err := opts.ToMetadataUpdateMap()
648 if err != nil {
649 res.Err = err
650 return res
651 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100652 _, res.Err = client.Post(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
653 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700654 })
655 return res
656}
657
658// MetadatumOptsBuilder allows extensions to add additional parameters to the
659// Create request.
660type MetadatumOptsBuilder interface {
661 ToMetadatumCreateMap() (map[string]interface{}, string, error)
662}
663
664// MetadatumOpts is a map of length one that contains a key-value pair.
665type MetadatumOpts map[string]string
666
667// ToMetadatumCreateMap assembles a body for a Create request based on the contents of a MetadataumOpts.
668func (opts MetadatumOpts) ToMetadatumCreateMap() (map[string]interface{}, string, error) {
669 if len(opts) != 1 {
670 return nil, "", errors.New("CreateMetadatum operation must have 1 and only 1 key-value pair.")
671 }
672 metadatum := map[string]interface{}{"meta": opts}
673 var key string
674 for k := range metadatum["meta"].(MetadatumOpts) {
675 key = k
676 }
677 return metadatum, key, nil
678}
679
680// CreateMetadatum will create or update the key-value pair with the given key for the given server ID.
681func CreateMetadatum(client *gophercloud.ServiceClient, id string, opts MetadatumOptsBuilder) CreateMetadatumResult {
682 var res CreateMetadatumResult
683 metadatum, key, err := opts.ToMetadatumCreateMap()
684 if err != nil {
685 res.Err = err
686 return res
687 }
688
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100689 _, res.Err = client.Put(metadatumURL(client, id, key), metadatum, &res.Body, &gophercloud.RequestOpts{
690 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700691 })
692 return res
693}
694
695// Metadatum requests the key-value pair with the given key for the given server ID.
696func Metadatum(client *gophercloud.ServiceClient, id, key string) GetMetadatumResult {
697 var res GetMetadatumResult
Ash Wilson59fb6c42015-02-12 16:21:13 -0500698 _, res.Err = client.Request("GET", metadatumURL(client, id, key), gophercloud.RequestOpts{
699 JSONResponse: &res.Body,
Jon Perritt78c57ce2014-11-20 11:07:18 -0700700 })
701 return res
702}
703
704// DeleteMetadatum will delete the key-value pair with the given key for the given server ID.
705func DeleteMetadatum(client *gophercloud.ServiceClient, id, key string) DeleteMetadatumResult {
706 var res DeleteMetadatumResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100707 _, res.Err = client.Delete(metadatumURL(client, id, key), &gophercloud.RequestOpts{
Ash Wilson59fb6c42015-02-12 16:21:13 -0500708 JSONResponse: &res.Body,
Jon Perrittcc77da62014-11-16 13:14:21 -0700709 })
710 return res
711}
Jon Perritt5cb49482015-02-19 12:19:58 -0700712
713// ListAddresses makes a request against the API to list the servers IP addresses.
714func ListAddresses(client *gophercloud.ServiceClient, id string) pagination.Pager {
715 createPageFn := func(r pagination.PageResult) pagination.Page {
716 return AddressPage{pagination.SinglePageBase(r)}
717 }
718 return pagination.NewPager(client, listAddressesURL(client, id), createPageFn)
719}
Jon Perritt04d073c2015-02-19 21:46:23 -0700720
721// ListAddressesByNetwork makes a request against the API to list the servers IP addresses
722// for the given network.
723func ListAddressesByNetwork(client *gophercloud.ServiceClient, id, network string) pagination.Pager {
724 createPageFn := func(r pagination.PageResult) pagination.Page {
725 return NetworkAddressPage{pagination.SinglePageBase(r)}
726 }
727 return pagination.NewPager(client, listAddressesByNetworkURL(client, id, network), createPageFn)
728}
einarf2fc665e2015-04-16 20:16:21 +0000729
einarf4e5fdaf2015-04-16 23:14:59 +0000730type CreateImageOpts struct {
einarf2fc665e2015-04-16 20:16:21 +0000731 // Name [required] of the image/snapshot
732 Name string
733 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the created image.
734 Metadata map[string]string
735}
736
einarf4e5fdaf2015-04-16 23:14:59 +0000737type CreateImageOptsBuilder interface {
738 ToServerCreateImageMap() (map[string]interface{}, error)
einarf2fc665e2015-04-16 20:16:21 +0000739}
740
einarf4e5fdaf2015-04-16 23:14:59 +0000741// ToServerCreateImageMap formats a CreateImageOpts structure into a request body.
742func (opts CreateImageOpts) ToServerCreateImageMap() (map[string]interface{}, error) {
einarf2fc665e2015-04-16 20:16:21 +0000743 var err error
744 img := make(map[string]interface{})
745 if opts.Name == "" {
einarf4e5fdaf2015-04-16 23:14:59 +0000746 return nil, fmt.Errorf("Cannot create a server image without a name")
einarf2fc665e2015-04-16 20:16:21 +0000747 }
748 img["name"] = opts.Name
749 if opts.Metadata != nil {
750 img["metadata"] = opts.Metadata
751 }
752 createImage := make(map[string]interface{})
753 createImage["createImage"] = img
754 return createImage, err
755}
756
einarf4e5fdaf2015-04-16 23:14:59 +0000757// CreateImage makes a request against the nova API to schedule an image to be created of the server
758func CreateImage(client *gophercloud.ServiceClient, serverId string, opts CreateImageOptsBuilder) CreateImageResult {
759 var res CreateImageResult
760 reqBody, err := opts.ToServerCreateImageMap()
einarf2fc665e2015-04-16 20:16:21 +0000761 if err != nil {
762 res.Err = err
763 return res
764 }
765 response, err := client.Post(actionURL(client, serverId), reqBody, nil, &gophercloud.RequestOpts{
766 OkCodes: []int{202},
767 })
768 res.Err = err
einarf4e5fdaf2015-04-16 23:14:59 +0000769 res.Header = response.Header
Kevin Pike9748b7b2015-05-05 07:34:07 -0700770 return res
einarf2fc665e2015-04-16 20:16:21 +0000771}