blob: e6490539ce3e8bb148db8e8fe2434a7747b783e7 [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"
Jon Perrittad5f1cb2015-05-20 10:38:13 -060010 "github.com/rackspace/gophercloud/openstack/compute/v2/flavors"
11 "github.com/rackspace/gophercloud/openstack/compute/v2/images"
Ash Wilson01626a32014-09-17 10:38:07 -040012 "github.com/rackspace/gophercloud/pagination"
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080013)
14
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020015// ListOptsBuilder allows extensions to add additional parameters to the
16// List request.
17type ListOptsBuilder interface {
18 ToServerListQuery() (string, error)
19}
Kevin Pike9748b7b2015-05-05 07:34:07 -070020
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020021// ListOpts allows the filtering and sorting of paginated collections through
22// the API. Filtering is achieved by passing in struct field values that map to
23// the server attributes you want to see returned. Marker and Limit are used
24// for pagination.
25type ListOpts struct {
26 // A time/date stamp for when the server last changed status.
27 ChangesSince string `q:"changes-since"`
28
29 // Name of the image in URL format.
30 Image string `q:"image"`
31
32 // Name of the flavor in URL format.
33 Flavor string `q:"flavor"`
34
35 // Name of the server as a string; can be queried with regular expressions.
36 // Realize that ?name=bob returns both bob and bobb. If you need to match bob
37 // only, you can use a regular expression matching the syntax of the
38 // underlying database server implemented for Compute.
39 Name string `q:"name"`
40
41 // Value of the status of the server so that you can filter on "ACTIVE" for example.
42 Status string `q:"status"`
43
44 // Name of the host as a string.
45 Host string `q:"host"`
46
47 // UUID of the server at which you want to set a marker.
48 Marker string `q:"marker"`
49
50 // Integer value for the limit of values to return.
51 Limit int `q:"limit"`
Daniel Speichert9342e522015-06-05 10:31:52 -040052
53 // Bool to show all tenants
54 AllTenants bool `q:"all_tenants"`
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020055}
56
57// ToServerListQuery formats a ListOpts into a query string.
58func (opts ListOpts) ToServerListQuery() (string, error) {
59 q, err := gophercloud.BuildQueryString(opts)
60 if err != nil {
61 return "", err
62 }
63 return q.String(), nil
64}
65
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080066// List makes a request against the API to list servers accessible to you.
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020067func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager {
68 url := listDetailURL(client)
69
70 if opts != nil {
71 query, err := opts.ToServerListQuery()
72 if err != nil {
73 return pagination.Pager{Err: err}
74 }
75 url += query
76 }
77
Ash Wilsonb8b16f82014-10-20 10:19:49 -040078 createPageFn := func(r pagination.PageResult) pagination.Page {
79 return ServerPage{pagination.LinkedPageBase{PageResult: r}}
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080080 }
81
Jamie Hannafordbfe33b22014-10-16 12:45:40 +020082 return pagination.NewPager(client, url, createPageFn)
Samuel A. Falvo IIc007c272014-02-10 20:49:26 -080083}
84
Ash Wilson2206a112014-10-02 10:57:38 -040085// CreateOptsBuilder describes struct types that can be accepted by the Create call.
Ash Wilson6a310e02014-09-29 08:24:02 -040086// The CreateOpts struct in this package does.
Ash Wilson2206a112014-10-02 10:57:38 -040087type CreateOptsBuilder interface {
Jon Perritt4149d7c2014-10-23 21:23:46 -050088 ToServerCreateMap() (map[string]interface{}, error)
Ash Wilson6a310e02014-09-29 08:24:02 -040089}
90
91// Network is used within CreateOpts to control a new server's network attachments.
92type Network struct {
93 // UUID of a nova-network to attach to the newly provisioned server.
94 // Required unless Port is provided.
95 UUID string
96
97 // Port of a neutron network to attach to the newly provisioned server.
98 // Required unless UUID is provided.
99 Port string
100
101 // FixedIP [optional] specifies a fixed IPv4 address to be used on this network.
102 FixedIP string
103}
104
Kevin Pike92e10b52015-04-10 15:16:57 -0700105// Personality is an array of files that are injected into the server at launch.
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700106type Personality []*File
Kevin Pike92e10b52015-04-10 15:16:57 -0700107
108// File is used within CreateOpts and RebuildOpts to inject a file into the server at launch.
Kevin Pike9748b7b2015-05-05 07:34:07 -0700109// File implements the json.Marshaler interface, so when a Create or Rebuild operation is requested,
110// json.Marshal will call File's MarshalJSON method.
Kevin Pike92e10b52015-04-10 15:16:57 -0700111type File struct {
112 // Path of the file
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700113 Path string
Kevin Pike92e10b52015-04-10 15:16:57 -0700114 // Contents of the file. Maximum content size is 255 bytes.
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700115 Contents []byte
Kevin Pike92e10b52015-04-10 15:16:57 -0700116}
117
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700118// MarshalJSON marshals the escaped file, base64 encoding the contents.
119func (f *File) MarshalJSON() ([]byte, error) {
120 file := struct {
121 Path string `json:"path"`
122 Contents string `json:"contents"`
123 }{
124 Path: f.Path,
125 Contents: base64.StdEncoding.EncodeToString(f.Contents),
Kevin Pike92e10b52015-04-10 15:16:57 -0700126 }
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700127 return json.Marshal(file)
Kevin Pike92e10b52015-04-10 15:16:57 -0700128}
129
Ash Wilson6a310e02014-09-29 08:24:02 -0400130// CreateOpts specifies server creation parameters.
131type CreateOpts struct {
132 // Name [required] is the name to assign to the newly launched server.
133 Name string
134
Jon Perrittad5f1cb2015-05-20 10:38:13 -0600135 // ImageRef [optional; required if ImageName is not provided] is the ID or full
136 // URL to the image that contains the server's OS and initial state.
137 // Also optional if using the boot-from-volume extension.
Ash Wilson6a310e02014-09-29 08:24:02 -0400138 ImageRef string
139
Jon Perrittad5f1cb2015-05-20 10:38:13 -0600140 // ImageName [optional; required if ImageRef is not provided] is the name of the
141 // image that contains the server's OS and initial state.
142 // Also optional if using the boot-from-volume extension.
143 ImageName string
144
145 // FlavorRef [optional; required if FlavorName is not provided] is the ID or
146 // full URL to the flavor that describes the server's specs.
Ash Wilson6a310e02014-09-29 08:24:02 -0400147 FlavorRef string
148
Jon Perrittad5f1cb2015-05-20 10:38:13 -0600149 // FlavorName [optional; required if FlavorRef is not provided] is the name of
150 // the flavor that describes the server's specs.
151 FlavorName string
152
Ash Wilson6a310e02014-09-29 08:24:02 -0400153 // SecurityGroups [optional] lists the names of the security groups to which this server should belong.
154 SecurityGroups []string
155
156 // UserData [optional] contains configuration information or scripts to use upon launch.
157 // Create will base64-encode it for you.
158 UserData []byte
159
160 // AvailabilityZone [optional] in which to launch the server.
161 AvailabilityZone string
162
163 // Networks [optional] dictates how this server will be attached to available networks.
164 // By default, the server will be attached to all isolated networks for the tenant.
165 Networks []Network
166
167 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server.
168 Metadata map[string]string
169
Kevin Pike92e10b52015-04-10 15:16:57 -0700170 // Personality [optional] includes files to inject into the server at launch.
171 // Create will base64-encode file contents for you.
172 Personality Personality
Ash Wilson6a310e02014-09-29 08:24:02 -0400173
174 // ConfigDrive [optional] enables metadata injection through a configuration drive.
175 ConfigDrive bool
Jon Perrittf3b2e142014-11-04 16:00:19 -0600176
177 // AdminPass [optional] sets the root user password. If not set, a randomly-generated
178 // password will be created and returned in the response.
179 AdminPass string
Jon Perritt7b9671c2015-02-01 22:03:14 -0700180
181 // AccessIPv4 [optional] specifies an IPv4 address for the instance.
182 AccessIPv4 string
183
184 // AccessIPv6 [optional] specifies an IPv6 address for the instance.
185 AccessIPv6 string
Ash Wilson6a310e02014-09-29 08:24:02 -0400186}
187
Ash Wilsone45c9732014-09-29 10:54:12 -0400188// ToServerCreateMap assembles a request body based on the contents of a CreateOpts.
Jon Perritt4149d7c2014-10-23 21:23:46 -0500189func (opts CreateOpts) ToServerCreateMap() (map[string]interface{}, error) {
Ash Wilson6a310e02014-09-29 08:24:02 -0400190 server := make(map[string]interface{})
191
192 server["name"] = opts.Name
193 server["imageRef"] = opts.ImageRef
Jon Perrittad5f1cb2015-05-20 10:38:13 -0600194 server["imageName"] = opts.ImageName
Ash Wilson6a310e02014-09-29 08:24:02 -0400195 server["flavorRef"] = opts.FlavorRef
Jon Perrittad5f1cb2015-05-20 10:38:13 -0600196 server["flavorName"] = opts.FlavorName
Ash Wilson6a310e02014-09-29 08:24:02 -0400197
198 if opts.UserData != nil {
199 encoded := base64.StdEncoding.EncodeToString(opts.UserData)
200 server["user_data"] = &encoded
201 }
Ash Wilson6a310e02014-09-29 08:24:02 -0400202 if opts.ConfigDrive {
203 server["config_drive"] = "true"
204 }
205 if opts.AvailabilityZone != "" {
206 server["availability_zone"] = opts.AvailabilityZone
207 }
208 if opts.Metadata != nil {
209 server["metadata"] = opts.Metadata
210 }
Jon Perrittf3b2e142014-11-04 16:00:19 -0600211 if opts.AdminPass != "" {
212 server["adminPass"] = opts.AdminPass
213 }
Jon Perritt7b9671c2015-02-01 22:03:14 -0700214 if opts.AccessIPv4 != "" {
215 server["accessIPv4"] = opts.AccessIPv4
216 }
217 if opts.AccessIPv6 != "" {
218 server["accessIPv6"] = opts.AccessIPv6
219 }
Ash Wilson6a310e02014-09-29 08:24:02 -0400220
221 if len(opts.SecurityGroups) > 0 {
222 securityGroups := make([]map[string]interface{}, len(opts.SecurityGroups))
223 for i, groupName := range opts.SecurityGroups {
224 securityGroups[i] = map[string]interface{}{"name": groupName}
225 }
eselldf709942014-11-13 21:07:11 -0700226 server["security_groups"] = securityGroups
Ash Wilson6a310e02014-09-29 08:24:02 -0400227 }
Jon Perritt2a7797d2014-10-21 15:08:43 -0500228
Ash Wilson6a310e02014-09-29 08:24:02 -0400229 if len(opts.Networks) > 0 {
230 networks := make([]map[string]interface{}, len(opts.Networks))
231 for i, net := range opts.Networks {
232 networks[i] = make(map[string]interface{})
233 if net.UUID != "" {
234 networks[i]["uuid"] = net.UUID
235 }
236 if net.Port != "" {
237 networks[i]["port"] = net.Port
238 }
239 if net.FixedIP != "" {
240 networks[i]["fixed_ip"] = net.FixedIP
241 }
242 }
Jon Perritt2a7797d2014-10-21 15:08:43 -0500243 server["networks"] = networks
Ash Wilson6a310e02014-09-29 08:24:02 -0400244 }
245
Kevin Pike92e10b52015-04-10 15:16:57 -0700246 if len(opts.Personality) > 0 {
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700247 server["personality"] = opts.Personality
Kevin Pike92e10b52015-04-10 15:16:57 -0700248 }
249
Jon Perritt4149d7c2014-10-23 21:23:46 -0500250 return map[string]interface{}{"server": server}, nil
Ash Wilson6a310e02014-09-29 08:24:02 -0400251}
252
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800253// Create requests a server to be provisioned to the user in the current tenant.
Ash Wilson2206a112014-10-02 10:57:38 -0400254func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult {
Jon Perritt4149d7c2014-10-23 21:23:46 -0500255 var res CreateResult
256
257 reqBody, err := opts.ToServerCreateMap()
258 if err != nil {
259 res.Err = err
260 return res
261 }
262
Jon Perrittad5f1cb2015-05-20 10:38:13 -0600263 // If ImageRef isn't provided, use ImageName to ascertain the image ID.
264 if reqBody["server"].(map[string]interface{})["imageRef"].(string) == "" {
265 imageName := reqBody["server"].(map[string]interface{})["imageName"].(string)
266 if imageName == "" {
267 res.Err = errors.New("One and only one of ImageRef and ImageName must be provided.")
268 return res
269 }
270 imageID, err := images.IDFromName(client, imageName)
271 if err != nil {
272 res.Err = err
273 return res
274 }
275 reqBody["server"].(map[string]interface{})["imageRef"] = imageID
276 }
277 delete(reqBody["server"].(map[string]interface{}), "imageName")
278
279 // If FlavorRef isn't provided, use FlavorName to ascertain the flavor ID.
280 if reqBody["server"].(map[string]interface{})["flavorRef"].(string) == "" {
281 flavorName := reqBody["server"].(map[string]interface{})["flavorName"].(string)
282 if flavorName == "" {
283 res.Err = errors.New("One and only one of FlavorRef and FlavorName must be provided.")
284 return res
285 }
286 flavorID, err := flavors.IDFromName(client, flavorName)
287 if err != nil {
288 res.Err = err
289 return res
290 }
291 reqBody["server"].(map[string]interface{})["flavorRef"] = flavorID
292 }
293 delete(reqBody["server"].(map[string]interface{}), "flavorName")
294
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100295 _, res.Err = client.Post(listURL(client), reqBody, &res.Body, nil)
Jon Perritt4149d7c2014-10-23 21:23:46 -0500296 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800297}
298
299// Delete requests that a server previously provisioned be removed from your account.
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100300func Delete(client *gophercloud.ServiceClient, id string) DeleteResult {
301 var res DeleteResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100302 _, res.Err = client.Delete(deleteURL(client, id), nil)
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100303 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800304}
305
Ian Duffy370c4302016-01-21 10:44:56 +0000306func ForceDelete(client *gophercloud.ServiceClient, id string) ActionResult {
307 var req struct {
308 ForceDelete string `json:"forceDelete"`
309 }
310
311 var res ActionResult
312 _, res.Err = client.Post(actionURL(client, id), req, nil, nil)
313 return res
314
315}
316
Ash Wilson7ddf0362014-09-17 10:59:09 -0400317// Get requests details on a single server, by ID.
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400318func Get(client *gophercloud.ServiceClient, id string) GetResult {
319 var result GetResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100320 _, result.Err = client.Get(getURL(client, id), &result.Body, &gophercloud.RequestOpts{
321 OkCodes: []int{200, 203},
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800322 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400323 return result
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800324}
325
Alex Gaynora6d5f9f2014-10-27 10:52:32 -0700326// UpdateOptsBuilder allows extensions to add additional attributes to the Update request.
Jon Perritt82048212014-10-13 22:33:13 -0500327type UpdateOptsBuilder interface {
Ash Wilsone45c9732014-09-29 10:54:12 -0400328 ToServerUpdateMap() map[string]interface{}
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400329}
330
331// UpdateOpts specifies the base attributes that may be updated on an existing server.
332type UpdateOpts struct {
333 // Name [optional] changes the displayed name of the server.
334 // The server host name will *not* change.
335 // Server names are not constrained to be unique, even within the same tenant.
336 Name string
337
338 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
339 AccessIPv4 string
340
341 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
342 AccessIPv6 string
343}
344
Ash Wilsone45c9732014-09-29 10:54:12 -0400345// ToServerUpdateMap formats an UpdateOpts structure into a request body.
346func (opts UpdateOpts) ToServerUpdateMap() map[string]interface{} {
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400347 server := make(map[string]string)
348 if opts.Name != "" {
349 server["name"] = opts.Name
350 }
351 if opts.AccessIPv4 != "" {
352 server["accessIPv4"] = opts.AccessIPv4
353 }
354 if opts.AccessIPv6 != "" {
355 server["accessIPv6"] = opts.AccessIPv6
356 }
357 return map[string]interface{}{"server": server}
358}
359
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800360// Update requests that various attributes of the indicated server be changed.
Jon Perritt82048212014-10-13 22:33:13 -0500361func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400362 var result UpdateResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100363 reqBody := opts.ToServerUpdateMap()
364 _, result.Err = client.Put(updateURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
365 OkCodes: []int{200},
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800366 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400367 return result
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800368}
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700369
Ash Wilson01626a32014-09-17 10:38:07 -0400370// ChangeAdminPassword alters the administrator or root password for a specified server.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200371func ChangeAdminPassword(client *gophercloud.ServiceClient, id, newPassword string) ActionResult {
Ash Wilsondc7daa82014-09-23 16:34:42 -0400372 var req struct {
373 ChangePassword struct {
374 AdminPass string `json:"adminPass"`
375 } `json:"changePassword"`
376 }
377
378 req.ChangePassword.AdminPass = newPassword
379
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200380 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100381 _, res.Err = client.Post(actionURL(client, id), req, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200382 return res
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700383}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700384
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700385// ErrArgument errors occur when an argument supplied to a package function
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700386// fails to fall within acceptable values. For example, the Reboot() function
387// expects the "how" parameter to be one of HardReboot or SoftReboot. These
388// constants are (currently) strings, leading someone to wonder if they can pass
389// other string values instead, perhaps in an effort to break the API of their
390// provider. Reboot() returns this error in this situation.
391//
392// Function identifies which function was called/which function is generating
393// the error.
394// Argument identifies which formal argument was responsible for producing the
395// error.
396// Value provides the value as it was passed into the function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700397type ErrArgument struct {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700398 Function, Argument string
Jon Perritt30558642014-04-14 17:07:12 -0500399 Value interface{}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700400}
401
402// Error yields a useful diagnostic for debugging purposes.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700403func (e *ErrArgument) Error() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700404 return fmt.Sprintf("Bad argument in call to %s, formal parameter %s, value %#v", e.Function, e.Argument, e.Value)
405}
406
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700407func (e *ErrArgument) String() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700408 return e.Error()
409}
410
Ash Wilson01626a32014-09-17 10:38:07 -0400411// RebootMethod describes the mechanisms by which a server reboot can be requested.
412type RebootMethod string
413
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700414// These constants determine how a server should be rebooted.
415// See the Reboot() function for further details.
416const (
Ash Wilson01626a32014-09-17 10:38:07 -0400417 SoftReboot RebootMethod = "SOFT"
418 HardReboot RebootMethod = "HARD"
419 OSReboot = SoftReboot
420 PowerCycle = HardReboot
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700421)
422
423// Reboot requests that a given server reboot.
424// Two methods exist for rebooting a server:
425//
Ash Wilson01626a32014-09-17 10:38:07 -0400426// HardReboot (aka PowerCycle) restarts the server instance by physically cutting power to the machine, or if a VM,
427// terminating it at the hypervisor level.
428// It's done. Caput. Full stop.
429// Then, after a brief while, power is restored or the VM instance restarted.
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700430//
Ash Wilson01626a32014-09-17 10:38:07 -0400431// SoftReboot (aka OSReboot) simply tells the OS to restart under its own procedures.
432// 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 +0200433func Reboot(client *gophercloud.ServiceClient, id string, how RebootMethod) ActionResult {
434 var res ActionResult
435
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700436 if (how != SoftReboot) && (how != HardReboot) {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200437 res.Err = &ErrArgument{
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700438 Function: "Reboot",
439 Argument: "how",
Jon Perritt30558642014-04-14 17:07:12 -0500440 Value: how,
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700441 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200442 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700443 }
Jon Perritt30558642014-04-14 17:07:12 -0500444
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100445 reqBody := struct {
446 C map[string]string `json:"reboot"`
447 }{
448 map[string]string{"type": string(how)},
449 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200450
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100451 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200452 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700453}
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700454
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200455// RebuildOptsBuilder is an interface that allows extensions to override the
456// default behaviour of rebuild options
457type RebuildOptsBuilder interface {
458 ToServerRebuildMap() (map[string]interface{}, error)
459}
460
461// RebuildOpts represents the configuration options used in a server rebuild
462// operation
463type RebuildOpts struct {
464 // Required. The ID of the image you want your server to be provisioned on
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200465 ImageID string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200466
467 // Name to set the server to
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200468 Name string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200469
470 // Required. The server's admin password
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200471 AdminPass string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200472
473 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200474 AccessIPv4 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200475
476 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200477 AccessIPv6 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200478
479 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200480 Metadata map[string]string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200481
Kevin Pike92e10b52015-04-10 15:16:57 -0700482 // Personality [optional] includes files to inject into the server at launch.
483 // Rebuild will base64-encode file contents for you.
484 Personality Personality
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200485}
486
487// ToServerRebuildMap formats a RebuildOpts struct into a map for use in JSON
488func (opts RebuildOpts) ToServerRebuildMap() (map[string]interface{}, error) {
489 var err error
490 server := make(map[string]interface{})
491
492 if opts.AdminPass == "" {
493 err = fmt.Errorf("AdminPass is required")
494 }
495
496 if opts.ImageID == "" {
497 err = fmt.Errorf("ImageID is required")
498 }
499
500 if err != nil {
501 return server, err
502 }
503
504 server["name"] = opts.Name
505 server["adminPass"] = opts.AdminPass
506 server["imageRef"] = opts.ImageID
507
508 if opts.AccessIPv4 != "" {
509 server["accessIPv4"] = opts.AccessIPv4
510 }
511
512 if opts.AccessIPv6 != "" {
513 server["accessIPv6"] = opts.AccessIPv6
514 }
515
516 if opts.Metadata != nil {
517 server["metadata"] = opts.Metadata
518 }
519
Kevin Pike92e10b52015-04-10 15:16:57 -0700520 if len(opts.Personality) > 0 {
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700521 server["personality"] = opts.Personality
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200522 }
523
524 return map[string]interface{}{"rebuild": server}, nil
525}
526
527// Rebuild will reprovision the server according to the configuration options
528// provided in the RebuildOpts struct.
529func Rebuild(client *gophercloud.ServiceClient, id string, opts RebuildOptsBuilder) RebuildResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400530 var result RebuildResult
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700531
532 if id == "" {
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200533 result.Err = fmt.Errorf("ID is required")
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400534 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700535 }
536
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200537 reqBody, err := opts.ToServerRebuildMap()
538 if err != nil {
539 result.Err = err
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400540 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700541 }
542
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100543 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, nil)
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400544 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700545}
546
Ash Wilson5f7cf182014-10-23 08:35:24 -0400547// ResizeOptsBuilder is an interface that allows extensions to override the default structure of
548// a Resize request.
549type ResizeOptsBuilder interface {
550 ToServerResizeMap() (map[string]interface{}, error)
551}
552
553// ResizeOpts represents the configuration options used to control a Resize operation.
554type ResizeOpts struct {
555 // FlavorRef is the ID of the flavor you wish your server to become.
556 FlavorRef string
557}
558
Alex Gaynor266e9332014-10-28 14:44:04 -0700559// 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 -0400560// Resize request.
561func (opts ResizeOpts) ToServerResizeMap() (map[string]interface{}, error) {
562 resize := map[string]interface{}{
563 "flavorRef": opts.FlavorRef,
564 }
565
566 return map[string]interface{}{"resize": resize}, nil
567}
568
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700569// Resize instructs the provider to change the flavor of the server.
Ash Wilson01626a32014-09-17 10:38:07 -0400570// Note that this implies rebuilding it.
571// Unfortunately, one cannot pass rebuild parameters to the resize function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700572// When the resize completes, the server will be in RESIZE_VERIFY state.
573// While in this state, you can explore the use of the new server's configuration.
574// If you like it, call ConfirmResize() to commit the resize permanently.
575// Otherwise, call RevertResize() to restore the old configuration.
Ash Wilson9e87a922014-10-23 14:29:22 -0400576func Resize(client *gophercloud.ServiceClient, id string, opts ResizeOptsBuilder) ActionResult {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200577 var res ActionResult
Ash Wilson5f7cf182014-10-23 08:35:24 -0400578 reqBody, err := opts.ToServerResizeMap()
579 if err != nil {
580 res.Err = err
581 return res
582 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200583
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100584 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200585 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700586}
587
588// ConfirmResize confirms a previous resize operation on a server.
589// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200590func ConfirmResize(client *gophercloud.ServiceClient, id string) ActionResult {
591 var res ActionResult
592
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100593 reqBody := map[string]interface{}{"confirmResize": nil}
594 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, &gophercloud.RequestOpts{
595 OkCodes: []int{201, 202, 204},
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700596 })
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200597 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700598}
599
600// RevertResize cancels a previous resize operation on a server.
601// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200602func RevertResize(client *gophercloud.ServiceClient, id string) ActionResult {
603 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100604 reqBody := map[string]interface{}{"revertResize": nil}
605 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200606 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700607}
Alex Gaynor39584a02014-10-28 13:59:21 -0700608
Alex Gaynor266e9332014-10-28 14:44:04 -0700609// RescueOptsBuilder is an interface that allows extensions to override the
610// default structure of a Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700611type RescueOptsBuilder interface {
612 ToServerRescueMap() (map[string]interface{}, error)
613}
614
Alex Gaynor266e9332014-10-28 14:44:04 -0700615// RescueOpts represents the configuration options used to control a Rescue
616// option.
Alex Gaynor39584a02014-10-28 13:59:21 -0700617type RescueOpts struct {
Alex Gaynor266e9332014-10-28 14:44:04 -0700618 // AdminPass is the desired administrative password for the instance in
Alex Gaynorcfec7722014-11-13 13:33:49 -0800619 // RESCUE mode. If it's left blank, the server will generate a password.
Alex Gaynor39584a02014-10-28 13:59:21 -0700620 AdminPass string
621}
622
Jon Perrittcc77da62014-11-16 13:14:21 -0700623// ToServerRescueMap formats a RescueOpts as a map that can be used as a JSON
Alex Gaynor266e9332014-10-28 14:44:04 -0700624// request body for the Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700625func (opts RescueOpts) ToServerRescueMap() (map[string]interface{}, error) {
626 server := make(map[string]interface{})
627 if opts.AdminPass != "" {
628 server["adminPass"] = opts.AdminPass
629 }
630 return map[string]interface{}{"rescue": server}, nil
631}
632
Alex Gaynor266e9332014-10-28 14:44:04 -0700633// Rescue instructs the provider to place the server into RESCUE mode.
Alex Gaynorfbe61bb2014-11-12 13:35:03 -0800634func Rescue(client *gophercloud.ServiceClient, id string, opts RescueOptsBuilder) RescueResult {
635 var result RescueResult
Alex Gaynor39584a02014-10-28 13:59:21 -0700636
637 if id == "" {
638 result.Err = fmt.Errorf("ID is required")
639 return result
640 }
641 reqBody, err := opts.ToServerRescueMap()
642 if err != nil {
643 result.Err = err
644 return result
645 }
646
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100647 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
648 OkCodes: []int{200},
Alex Gaynor39584a02014-10-28 13:59:21 -0700649 })
650
651 return result
652}
Jon Perrittcc77da62014-11-16 13:14:21 -0700653
Jon Perritt789f8322014-11-21 08:20:04 -0700654// ResetMetadataOptsBuilder allows extensions to add additional parameters to the
655// Reset request.
656type ResetMetadataOptsBuilder interface {
657 ToMetadataResetMap() (map[string]interface{}, error)
Jon Perrittcc77da62014-11-16 13:14:21 -0700658}
659
Jon Perritt78c57ce2014-11-20 11:07:18 -0700660// MetadataOpts is a map that contains key-value pairs.
661type MetadataOpts map[string]string
Jon Perrittcc77da62014-11-16 13:14:21 -0700662
Jon Perritt789f8322014-11-21 08:20:04 -0700663// ToMetadataResetMap assembles a body for a Reset request based on the contents of a MetadataOpts.
664func (opts MetadataOpts) ToMetadataResetMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700665 return map[string]interface{}{"metadata": opts}, nil
666}
667
Jon Perritt78c57ce2014-11-20 11:07:18 -0700668// ToMetadataUpdateMap assembles a body for an Update request based on the contents of a MetadataOpts.
669func (opts MetadataOpts) ToMetadataUpdateMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700670 return map[string]interface{}{"metadata": opts}, nil
671}
672
Jon Perritt789f8322014-11-21 08:20:04 -0700673// ResetMetadata will create multiple new key-value pairs for the given server ID.
Jon Perrittcc77da62014-11-16 13:14:21 -0700674// Note: Using this operation will erase any already-existing metadata and create
675// the new metadata provided. To keep any already-existing metadata, use the
676// UpdateMetadatas or UpdateMetadata function.
Jon Perritt789f8322014-11-21 08:20:04 -0700677func ResetMetadata(client *gophercloud.ServiceClient, id string, opts ResetMetadataOptsBuilder) ResetMetadataResult {
678 var res ResetMetadataResult
679 metadata, err := opts.ToMetadataResetMap()
Jon Perrittcc77da62014-11-16 13:14:21 -0700680 if err != nil {
681 res.Err = err
682 return res
683 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100684 _, res.Err = client.Put(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
685 OkCodes: []int{200},
Jon Perrittcc77da62014-11-16 13:14:21 -0700686 })
687 return res
688}
689
Jon Perritt78c57ce2014-11-20 11:07:18 -0700690// Metadata requests all the metadata for the given server ID.
691func Metadata(client *gophercloud.ServiceClient, id string) GetMetadataResult {
Jon Perrittcc77da62014-11-16 13:14:21 -0700692 var res GetMetadataResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100693 _, res.Err = client.Get(metadataURL(client, id), &res.Body, nil)
Jon Perrittcc77da62014-11-16 13:14:21 -0700694 return res
695}
696
Jon Perritt78c57ce2014-11-20 11:07:18 -0700697// UpdateMetadataOptsBuilder allows extensions to add additional parameters to the
698// Create request.
699type UpdateMetadataOptsBuilder interface {
700 ToMetadataUpdateMap() (map[string]interface{}, error)
701}
702
703// UpdateMetadata updates (or creates) all the metadata specified by opts for the given server ID.
704// This operation does not affect already-existing metadata that is not specified
705// by opts.
706func UpdateMetadata(client *gophercloud.ServiceClient, id string, opts UpdateMetadataOptsBuilder) UpdateMetadataResult {
707 var res UpdateMetadataResult
708 metadata, err := opts.ToMetadataUpdateMap()
709 if err != nil {
710 res.Err = err
711 return res
712 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100713 _, res.Err = client.Post(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
714 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700715 })
716 return res
717}
718
719// MetadatumOptsBuilder allows extensions to add additional parameters to the
720// Create request.
721type MetadatumOptsBuilder interface {
722 ToMetadatumCreateMap() (map[string]interface{}, string, error)
723}
724
725// MetadatumOpts is a map of length one that contains a key-value pair.
726type MetadatumOpts map[string]string
727
728// ToMetadatumCreateMap assembles a body for a Create request based on the contents of a MetadataumOpts.
729func (opts MetadatumOpts) ToMetadatumCreateMap() (map[string]interface{}, string, error) {
730 if len(opts) != 1 {
731 return nil, "", errors.New("CreateMetadatum operation must have 1 and only 1 key-value pair.")
732 }
733 metadatum := map[string]interface{}{"meta": opts}
734 var key string
735 for k := range metadatum["meta"].(MetadatumOpts) {
736 key = k
737 }
738 return metadatum, key, nil
739}
740
741// CreateMetadatum will create or update the key-value pair with the given key for the given server ID.
742func CreateMetadatum(client *gophercloud.ServiceClient, id string, opts MetadatumOptsBuilder) CreateMetadatumResult {
743 var res CreateMetadatumResult
744 metadatum, key, err := opts.ToMetadatumCreateMap()
745 if err != nil {
746 res.Err = err
747 return res
748 }
749
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100750 _, res.Err = client.Put(metadatumURL(client, id, key), metadatum, &res.Body, &gophercloud.RequestOpts{
751 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700752 })
753 return res
754}
755
756// Metadatum requests the key-value pair with the given key for the given server ID.
757func Metadatum(client *gophercloud.ServiceClient, id, key string) GetMetadatumResult {
758 var res GetMetadatumResult
Ash Wilson59fb6c42015-02-12 16:21:13 -0500759 _, res.Err = client.Request("GET", metadatumURL(client, id, key), gophercloud.RequestOpts{
760 JSONResponse: &res.Body,
Jon Perritt78c57ce2014-11-20 11:07:18 -0700761 })
762 return res
763}
764
765// DeleteMetadatum will delete the key-value pair with the given key for the given server ID.
766func DeleteMetadatum(client *gophercloud.ServiceClient, id, key string) DeleteMetadatumResult {
767 var res DeleteMetadatumResult
Pratik Mallyaee675fd2015-09-14 14:07:30 -0500768 _, res.Err = client.Delete(metadatumURL(client, id, key), nil)
Jon Perrittcc77da62014-11-16 13:14:21 -0700769 return res
770}
Jon Perritt5cb49482015-02-19 12:19:58 -0700771
772// ListAddresses makes a request against the API to list the servers IP addresses.
773func ListAddresses(client *gophercloud.ServiceClient, id string) pagination.Pager {
774 createPageFn := func(r pagination.PageResult) pagination.Page {
775 return AddressPage{pagination.SinglePageBase(r)}
776 }
777 return pagination.NewPager(client, listAddressesURL(client, id), createPageFn)
778}
Jon Perritt04d073c2015-02-19 21:46:23 -0700779
780// ListAddressesByNetwork makes a request against the API to list the servers IP addresses
781// for the given network.
782func ListAddressesByNetwork(client *gophercloud.ServiceClient, id, network string) pagination.Pager {
783 createPageFn := func(r pagination.PageResult) pagination.Page {
784 return NetworkAddressPage{pagination.SinglePageBase(r)}
785 }
786 return pagination.NewPager(client, listAddressesByNetworkURL(client, id, network), createPageFn)
787}
einarf2fc665e2015-04-16 20:16:21 +0000788
einarf4e5fdaf2015-04-16 23:14:59 +0000789type CreateImageOpts struct {
einarf2fc665e2015-04-16 20:16:21 +0000790 // Name [required] of the image/snapshot
791 Name string
792 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the created image.
793 Metadata map[string]string
794}
795
einarf4e5fdaf2015-04-16 23:14:59 +0000796type CreateImageOptsBuilder interface {
797 ToServerCreateImageMap() (map[string]interface{}, error)
einarf2fc665e2015-04-16 20:16:21 +0000798}
799
einarf4e5fdaf2015-04-16 23:14:59 +0000800// ToServerCreateImageMap formats a CreateImageOpts structure into a request body.
801func (opts CreateImageOpts) ToServerCreateImageMap() (map[string]interface{}, error) {
einarf2fc665e2015-04-16 20:16:21 +0000802 var err error
803 img := make(map[string]interface{})
804 if opts.Name == "" {
einarf4e5fdaf2015-04-16 23:14:59 +0000805 return nil, fmt.Errorf("Cannot create a server image without a name")
einarf2fc665e2015-04-16 20:16:21 +0000806 }
807 img["name"] = opts.Name
808 if opts.Metadata != nil {
809 img["metadata"] = opts.Metadata
810 }
811 createImage := make(map[string]interface{})
812 createImage["createImage"] = img
813 return createImage, err
814}
815
einarf4e5fdaf2015-04-16 23:14:59 +0000816// CreateImage makes a request against the nova API to schedule an image to be created of the server
817func CreateImage(client *gophercloud.ServiceClient, serverId string, opts CreateImageOptsBuilder) CreateImageResult {
818 var res CreateImageResult
819 reqBody, err := opts.ToServerCreateImageMap()
einarf2fc665e2015-04-16 20:16:21 +0000820 if err != nil {
821 res.Err = err
822 return res
823 }
824 response, err := client.Post(actionURL(client, serverId), reqBody, nil, &gophercloud.RequestOpts{
825 OkCodes: []int{202},
826 })
827 res.Err = err
einarf4e5fdaf2015-04-16 23:14:59 +0000828 res.Header = response.Header
Kevin Pike9748b7b2015-05-05 07:34:07 -0700829 return res
einarf2fc665e2015-04-16 20:16:21 +0000830}
Jon Perritt6b0a8832015-06-04 14:32:30 -0600831
832// IDFromName is a convienience function that returns a server's ID given its name.
833func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) {
834 serverCount := 0
835 serverID := ""
836 if name == "" {
837 return "", fmt.Errorf("A server name must be provided.")
838 }
839 pager := List(client, nil)
840 pager.EachPage(func(page pagination.Page) (bool, error) {
841 serverList, err := ExtractServers(page)
842 if err != nil {
843 return false, err
844 }
845
846 for _, s := range serverList {
847 if s.Name == name {
848 serverCount++
849 serverID = s.ID
850 }
851 }
852 return true, nil
853 })
854
855 switch serverCount {
856 case 0:
857 return "", fmt.Errorf("Unable to find server: %s", name)
858 case 1:
859 return serverID, nil
860 default:
861 return "", fmt.Errorf("Found %d servers matching %s", serverCount, name)
862 }
863}
Rickard von Essen5b8bbff2016-02-16 07:48:20 +0100864
Rickard von Essenc3d49b72016-02-16 20:59:18 +0100865// GetPassword makes a request against the nova API to get the encrypted administrative password.
Rickard von Essen5b8bbff2016-02-16 07:48:20 +0100866func GetPassword(client *gophercloud.ServiceClient, serverId string) GetPasswordResult {
867 var res GetPasswordResult
868 _, res.Err = client.Request("GET", passwordURL(client, serverId), gophercloud.RequestOpts{
869 JSONResponse: &res.Body,
870 })
871 return res
872}