blob: 7c964d2d6cac27a8414c192e44b95efd0e2fa329 [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
Jon Perritt27249f42016-02-18 10:35:59 -06009 "github.com/gophercloud/gophercloud"
10 "github.com/gophercloud/gophercloud/openstack/compute/v2/flavors"
Jon Perritt994370e2016-02-18 15:23:34 -060011 "github.com/gophercloud/gophercloud/openstack/compute/v2/images"
Jon Perritt27249f42016-02-18 10:35:59 -060012 "github.com/gophercloud/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.
jrperrittb1013232016-02-10 19:01:53 -0600133 Name string `b:"name,required"`
Ash Wilson6a310e02014-09-29 08:24:02 -0400134
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
Jon Perritt994370e2016-02-18 15:23:34 -0600186
187 // ServiceClient [optional] will allow calls to be made to retrieve an image or
188 // flavor ID by name.
189 ServiceClient *gophercloud.ServiceClient
Ash Wilson6a310e02014-09-29 08:24:02 -0400190}
191
Ash Wilsone45c9732014-09-29 10:54:12 -0400192// ToServerCreateMap assembles a request body based on the contents of a CreateOpts.
Jon Perritt4149d7c2014-10-23 21:23:46 -0500193func (opts CreateOpts) ToServerCreateMap() (map[string]interface{}, error) {
Ash Wilson6a310e02014-09-29 08:24:02 -0400194 server := make(map[string]interface{})
195
196 server["name"] = opts.Name
197 server["imageRef"] = opts.ImageRef
Jon Perrittad5f1cb2015-05-20 10:38:13 -0600198 server["imageName"] = opts.ImageName
Ash Wilson6a310e02014-09-29 08:24:02 -0400199 server["flavorRef"] = opts.FlavorRef
Jon Perrittad5f1cb2015-05-20 10:38:13 -0600200 server["flavorName"] = opts.FlavorName
Ash Wilson6a310e02014-09-29 08:24:02 -0400201
202 if opts.UserData != nil {
203 encoded := base64.StdEncoding.EncodeToString(opts.UserData)
204 server["user_data"] = &encoded
205 }
Ash Wilson6a310e02014-09-29 08:24:02 -0400206 if opts.ConfigDrive {
207 server["config_drive"] = "true"
208 }
209 if opts.AvailabilityZone != "" {
210 server["availability_zone"] = opts.AvailabilityZone
211 }
212 if opts.Metadata != nil {
213 server["metadata"] = opts.Metadata
214 }
Jon Perrittf3b2e142014-11-04 16:00:19 -0600215 if opts.AdminPass != "" {
216 server["adminPass"] = opts.AdminPass
217 }
Jon Perritt7b9671c2015-02-01 22:03:14 -0700218 if opts.AccessIPv4 != "" {
219 server["accessIPv4"] = opts.AccessIPv4
220 }
221 if opts.AccessIPv6 != "" {
222 server["accessIPv6"] = opts.AccessIPv6
223 }
Ash Wilson6a310e02014-09-29 08:24:02 -0400224
225 if len(opts.SecurityGroups) > 0 {
226 securityGroups := make([]map[string]interface{}, len(opts.SecurityGroups))
227 for i, groupName := range opts.SecurityGroups {
228 securityGroups[i] = map[string]interface{}{"name": groupName}
229 }
eselldf709942014-11-13 21:07:11 -0700230 server["security_groups"] = securityGroups
Ash Wilson6a310e02014-09-29 08:24:02 -0400231 }
Jon Perritt2a7797d2014-10-21 15:08:43 -0500232
Ash Wilson6a310e02014-09-29 08:24:02 -0400233 if len(opts.Networks) > 0 {
234 networks := make([]map[string]interface{}, len(opts.Networks))
235 for i, net := range opts.Networks {
236 networks[i] = make(map[string]interface{})
237 if net.UUID != "" {
238 networks[i]["uuid"] = net.UUID
239 }
240 if net.Port != "" {
241 networks[i]["port"] = net.Port
242 }
243 if net.FixedIP != "" {
244 networks[i]["fixed_ip"] = net.FixedIP
245 }
246 }
Jon Perritt2a7797d2014-10-21 15:08:43 -0500247 server["networks"] = networks
Ash Wilson6a310e02014-09-29 08:24:02 -0400248 }
249
Kevin Pike92e10b52015-04-10 15:16:57 -0700250 if len(opts.Personality) > 0 {
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700251 server["personality"] = opts.Personality
Kevin Pike92e10b52015-04-10 15:16:57 -0700252 }
253
jrperrittb1013232016-02-10 19:01:53 -0600254 // If ImageRef isn't provided, use ImageName to ascertain the image ID.
255 if opts.ImageRef == "" {
256 if opts.ImageName == "" {
257 return nil, errors.New("One and only one of ImageRef and ImageName must be provided.")
258 }
Jon Perritt994370e2016-02-18 15:23:34 -0600259 if opts.ServiceClient == nil {
260 return nil, errors.New("A service client must be provided to find an image ID by name.")
261 }
262 imageID, err := images.IDFromName(opts.ServiceClient, opts.ImageName)
jrperrittb1013232016-02-10 19:01:53 -0600263 if err != nil {
264 return nil, err
265 }
266 server["imageRef"] = imageID
267 }
268
269 // If FlavorRef isn't provided, use FlavorName to ascertain the flavor ID.
270 if opts.FlavorRef == "" {
271 if opts.FlavorName == "" {
272 return nil, errors.New("One and only one of FlavorRef and FlavorName must be provided.")
273 }
Jon Perritt994370e2016-02-18 15:23:34 -0600274 if opts.ServiceClient == nil {
275 return nil, errors.New("A service client must be provided to find a flavor ID by name.")
276 }
277 flavorID, err := flavors.IDFromName(opts.ServiceClient, opts.FlavorName)
jrperrittb1013232016-02-10 19:01:53 -0600278 if err != nil {
279 return nil, err
280 }
281 server["flavorRef"] = flavorID
282 }
283
Jon Perritt4149d7c2014-10-23 21:23:46 -0500284 return map[string]interface{}{"server": server}, nil
Ash Wilson6a310e02014-09-29 08:24:02 -0400285}
286
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800287// Create requests a server to be provisioned to the user in the current tenant.
Ash Wilson2206a112014-10-02 10:57:38 -0400288func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult {
Jon Perritt4149d7c2014-10-23 21:23:46 -0500289 var res CreateResult
290
291 reqBody, err := opts.ToServerCreateMap()
292 if err != nil {
293 res.Err = err
294 return res
295 }
296
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100297 _, res.Err = client.Post(listURL(client), reqBody, &res.Body, nil)
Jon Perritt4149d7c2014-10-23 21:23:46 -0500298 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800299}
300
301// Delete requests that a server previously provisioned be removed from your account.
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100302func Delete(client *gophercloud.ServiceClient, id string) DeleteResult {
303 var res DeleteResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100304 _, res.Err = client.Delete(deleteURL(client, id), nil)
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100305 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800306}
307
Ian Duffy370c4302016-01-21 10:44:56 +0000308func ForceDelete(client *gophercloud.ServiceClient, id string) ActionResult {
309 var req struct {
310 ForceDelete string `json:"forceDelete"`
311 }
312
313 var res ActionResult
314 _, res.Err = client.Post(actionURL(client, id), req, nil, nil)
315 return res
316
317}
318
Ash Wilson7ddf0362014-09-17 10:59:09 -0400319// Get requests details on a single server, by ID.
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400320func Get(client *gophercloud.ServiceClient, id string) GetResult {
321 var result GetResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100322 _, result.Err = client.Get(getURL(client, id), &result.Body, &gophercloud.RequestOpts{
323 OkCodes: []int{200, 203},
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800324 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400325 return result
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800326}
327
Alex Gaynora6d5f9f2014-10-27 10:52:32 -0700328// UpdateOptsBuilder allows extensions to add additional attributes to the Update request.
Jon Perritt82048212014-10-13 22:33:13 -0500329type UpdateOptsBuilder interface {
Ash Wilsone45c9732014-09-29 10:54:12 -0400330 ToServerUpdateMap() map[string]interface{}
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400331}
332
333// UpdateOpts specifies the base attributes that may be updated on an existing server.
334type UpdateOpts struct {
335 // Name [optional] changes the displayed name of the server.
336 // The server host name will *not* change.
337 // Server names are not constrained to be unique, even within the same tenant.
338 Name string
339
340 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
341 AccessIPv4 string
342
343 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
344 AccessIPv6 string
345}
346
Ash Wilsone45c9732014-09-29 10:54:12 -0400347// ToServerUpdateMap formats an UpdateOpts structure into a request body.
348func (opts UpdateOpts) ToServerUpdateMap() map[string]interface{} {
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400349 server := make(map[string]string)
350 if opts.Name != "" {
351 server["name"] = opts.Name
352 }
353 if opts.AccessIPv4 != "" {
354 server["accessIPv4"] = opts.AccessIPv4
355 }
356 if opts.AccessIPv6 != "" {
357 server["accessIPv6"] = opts.AccessIPv6
358 }
359 return map[string]interface{}{"server": server}
360}
361
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800362// Update requests that various attributes of the indicated server be changed.
Jon Perritt82048212014-10-13 22:33:13 -0500363func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400364 var result UpdateResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100365 reqBody := opts.ToServerUpdateMap()
366 _, result.Err = client.Put(updateURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
367 OkCodes: []int{200},
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800368 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400369 return result
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800370}
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700371
Ash Wilson01626a32014-09-17 10:38:07 -0400372// ChangeAdminPassword alters the administrator or root password for a specified server.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200373func ChangeAdminPassword(client *gophercloud.ServiceClient, id, newPassword string) ActionResult {
Ash Wilsondc7daa82014-09-23 16:34:42 -0400374 var req struct {
375 ChangePassword struct {
376 AdminPass string `json:"adminPass"`
377 } `json:"changePassword"`
378 }
379
380 req.ChangePassword.AdminPass = newPassword
381
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200382 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100383 _, res.Err = client.Post(actionURL(client, id), req, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200384 return res
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700385}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700386
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700387// ErrArgument errors occur when an argument supplied to a package function
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700388// fails to fall within acceptable values. For example, the Reboot() function
389// expects the "how" parameter to be one of HardReboot or SoftReboot. These
390// constants are (currently) strings, leading someone to wonder if they can pass
391// other string values instead, perhaps in an effort to break the API of their
392// provider. Reboot() returns this error in this situation.
393//
394// Function identifies which function was called/which function is generating
395// the error.
396// Argument identifies which formal argument was responsible for producing the
397// error.
398// Value provides the value as it was passed into the function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700399type ErrArgument struct {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700400 Function, Argument string
Jon Perritt30558642014-04-14 17:07:12 -0500401 Value interface{}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700402}
403
404// Error yields a useful diagnostic for debugging purposes.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700405func (e *ErrArgument) Error() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700406 return fmt.Sprintf("Bad argument in call to %s, formal parameter %s, value %#v", e.Function, e.Argument, e.Value)
407}
408
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700409func (e *ErrArgument) String() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700410 return e.Error()
411}
412
Ash Wilson01626a32014-09-17 10:38:07 -0400413// RebootMethod describes the mechanisms by which a server reboot can be requested.
414type RebootMethod string
415
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700416// These constants determine how a server should be rebooted.
417// See the Reboot() function for further details.
418const (
Ash Wilson01626a32014-09-17 10:38:07 -0400419 SoftReboot RebootMethod = "SOFT"
420 HardReboot RebootMethod = "HARD"
421 OSReboot = SoftReboot
422 PowerCycle = HardReboot
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700423)
424
425// Reboot requests that a given server reboot.
426// Two methods exist for rebooting a server:
427//
Ash Wilson01626a32014-09-17 10:38:07 -0400428// HardReboot (aka PowerCycle) restarts the server instance by physically cutting power to the machine, or if a VM,
429// terminating it at the hypervisor level.
430// It's done. Caput. Full stop.
431// Then, after a brief while, power is restored or the VM instance restarted.
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700432//
Ash Wilson01626a32014-09-17 10:38:07 -0400433// SoftReboot (aka OSReboot) simply tells the OS to restart under its own procedures.
434// 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 +0200435func Reboot(client *gophercloud.ServiceClient, id string, how RebootMethod) ActionResult {
436 var res ActionResult
437
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700438 if (how != SoftReboot) && (how != HardReboot) {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200439 res.Err = &ErrArgument{
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700440 Function: "Reboot",
441 Argument: "how",
Jon Perritt30558642014-04-14 17:07:12 -0500442 Value: how,
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700443 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200444 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700445 }
Jon Perritt30558642014-04-14 17:07:12 -0500446
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100447 reqBody := struct {
448 C map[string]string `json:"reboot"`
449 }{
450 map[string]string{"type": string(how)},
451 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200452
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100453 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200454 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700455}
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700456
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200457// RebuildOptsBuilder is an interface that allows extensions to override the
458// default behaviour of rebuild options
459type RebuildOptsBuilder interface {
460 ToServerRebuildMap() (map[string]interface{}, error)
461}
462
463// RebuildOpts represents the configuration options used in a server rebuild
464// operation
465type RebuildOpts struct {
466 // Required. The ID of the image you want your server to be provisioned on
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200467 ImageID string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200468
469 // Name to set the server to
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200470 Name string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200471
472 // Required. The server's admin password
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200473 AdminPass string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200474
475 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200476 AccessIPv4 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200477
478 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200479 AccessIPv6 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200480
481 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200482 Metadata map[string]string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200483
Kevin Pike92e10b52015-04-10 15:16:57 -0700484 // Personality [optional] includes files to inject into the server at launch.
485 // Rebuild will base64-encode file contents for you.
486 Personality Personality
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200487}
488
489// ToServerRebuildMap formats a RebuildOpts struct into a map for use in JSON
490func (opts RebuildOpts) ToServerRebuildMap() (map[string]interface{}, error) {
491 var err error
492 server := make(map[string]interface{})
493
494 if opts.AdminPass == "" {
495 err = fmt.Errorf("AdminPass is required")
496 }
497
498 if opts.ImageID == "" {
499 err = fmt.Errorf("ImageID is required")
500 }
501
502 if err != nil {
503 return server, err
504 }
505
506 server["name"] = opts.Name
507 server["adminPass"] = opts.AdminPass
508 server["imageRef"] = opts.ImageID
509
510 if opts.AccessIPv4 != "" {
511 server["accessIPv4"] = opts.AccessIPv4
512 }
513
514 if opts.AccessIPv6 != "" {
515 server["accessIPv6"] = opts.AccessIPv6
516 }
517
518 if opts.Metadata != nil {
519 server["metadata"] = opts.Metadata
520 }
521
Kevin Pike92e10b52015-04-10 15:16:57 -0700522 if len(opts.Personality) > 0 {
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700523 server["personality"] = opts.Personality
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200524 }
525
526 return map[string]interface{}{"rebuild": server}, nil
527}
528
529// Rebuild will reprovision the server according to the configuration options
530// provided in the RebuildOpts struct.
531func Rebuild(client *gophercloud.ServiceClient, id string, opts RebuildOptsBuilder) RebuildResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400532 var result RebuildResult
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700533
534 if id == "" {
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200535 result.Err = fmt.Errorf("ID is required")
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400536 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700537 }
538
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200539 reqBody, err := opts.ToServerRebuildMap()
540 if err != nil {
541 result.Err = err
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400542 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700543 }
544
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100545 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, nil)
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400546 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700547}
548
Ash Wilson5f7cf182014-10-23 08:35:24 -0400549// ResizeOptsBuilder is an interface that allows extensions to override the default structure of
550// a Resize request.
551type ResizeOptsBuilder interface {
552 ToServerResizeMap() (map[string]interface{}, error)
553}
554
555// ResizeOpts represents the configuration options used to control a Resize operation.
556type ResizeOpts struct {
557 // FlavorRef is the ID of the flavor you wish your server to become.
558 FlavorRef string
559}
560
Alex Gaynor266e9332014-10-28 14:44:04 -0700561// 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 -0400562// Resize request.
563func (opts ResizeOpts) ToServerResizeMap() (map[string]interface{}, error) {
564 resize := map[string]interface{}{
565 "flavorRef": opts.FlavorRef,
566 }
567
568 return map[string]interface{}{"resize": resize}, nil
569}
570
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700571// Resize instructs the provider to change the flavor of the server.
Ash Wilson01626a32014-09-17 10:38:07 -0400572// Note that this implies rebuilding it.
573// Unfortunately, one cannot pass rebuild parameters to the resize function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700574// When the resize completes, the server will be in RESIZE_VERIFY state.
575// While in this state, you can explore the use of the new server's configuration.
576// If you like it, call ConfirmResize() to commit the resize permanently.
577// Otherwise, call RevertResize() to restore the old configuration.
Ash Wilson9e87a922014-10-23 14:29:22 -0400578func Resize(client *gophercloud.ServiceClient, id string, opts ResizeOptsBuilder) ActionResult {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200579 var res ActionResult
Ash Wilson5f7cf182014-10-23 08:35:24 -0400580 reqBody, err := opts.ToServerResizeMap()
581 if err != nil {
582 res.Err = err
583 return res
584 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200585
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100586 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200587 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700588}
589
590// ConfirmResize confirms a previous resize operation on a server.
591// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200592func ConfirmResize(client *gophercloud.ServiceClient, id string) ActionResult {
593 var res ActionResult
594
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100595 reqBody := map[string]interface{}{"confirmResize": nil}
596 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, &gophercloud.RequestOpts{
597 OkCodes: []int{201, 202, 204},
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700598 })
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200599 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700600}
601
602// RevertResize cancels a previous resize operation on a server.
603// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200604func RevertResize(client *gophercloud.ServiceClient, id string) ActionResult {
605 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100606 reqBody := map[string]interface{}{"revertResize": nil}
607 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200608 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700609}
Alex Gaynor39584a02014-10-28 13:59:21 -0700610
Alex Gaynor266e9332014-10-28 14:44:04 -0700611// RescueOptsBuilder is an interface that allows extensions to override the
612// default structure of a Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700613type RescueOptsBuilder interface {
614 ToServerRescueMap() (map[string]interface{}, error)
615}
616
Alex Gaynor266e9332014-10-28 14:44:04 -0700617// RescueOpts represents the configuration options used to control a Rescue
618// option.
Alex Gaynor39584a02014-10-28 13:59:21 -0700619type RescueOpts struct {
Alex Gaynor266e9332014-10-28 14:44:04 -0700620 // AdminPass is the desired administrative password for the instance in
Alex Gaynorcfec7722014-11-13 13:33:49 -0800621 // RESCUE mode. If it's left blank, the server will generate a password.
Alex Gaynor39584a02014-10-28 13:59:21 -0700622 AdminPass string
623}
624
Jon Perrittcc77da62014-11-16 13:14:21 -0700625// ToServerRescueMap formats a RescueOpts as a map that can be used as a JSON
Alex Gaynor266e9332014-10-28 14:44:04 -0700626// request body for the Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700627func (opts RescueOpts) ToServerRescueMap() (map[string]interface{}, error) {
628 server := make(map[string]interface{})
629 if opts.AdminPass != "" {
630 server["adminPass"] = opts.AdminPass
631 }
632 return map[string]interface{}{"rescue": server}, nil
633}
634
Alex Gaynor266e9332014-10-28 14:44:04 -0700635// Rescue instructs the provider to place the server into RESCUE mode.
Alex Gaynorfbe61bb2014-11-12 13:35:03 -0800636func Rescue(client *gophercloud.ServiceClient, id string, opts RescueOptsBuilder) RescueResult {
637 var result RescueResult
Alex Gaynor39584a02014-10-28 13:59:21 -0700638
639 if id == "" {
640 result.Err = fmt.Errorf("ID is required")
641 return result
642 }
643 reqBody, err := opts.ToServerRescueMap()
644 if err != nil {
645 result.Err = err
646 return result
647 }
648
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100649 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
650 OkCodes: []int{200},
Alex Gaynor39584a02014-10-28 13:59:21 -0700651 })
652
653 return result
654}
Jon Perrittcc77da62014-11-16 13:14:21 -0700655
Jon Perritt789f8322014-11-21 08:20:04 -0700656// ResetMetadataOptsBuilder allows extensions to add additional parameters to the
657// Reset request.
658type ResetMetadataOptsBuilder interface {
659 ToMetadataResetMap() (map[string]interface{}, error)
Jon Perrittcc77da62014-11-16 13:14:21 -0700660}
661
Jon Perritt78c57ce2014-11-20 11:07:18 -0700662// MetadataOpts is a map that contains key-value pairs.
663type MetadataOpts map[string]string
Jon Perrittcc77da62014-11-16 13:14:21 -0700664
Jon Perritt789f8322014-11-21 08:20:04 -0700665// ToMetadataResetMap assembles a body for a Reset request based on the contents of a MetadataOpts.
666func (opts MetadataOpts) ToMetadataResetMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700667 return map[string]interface{}{"metadata": opts}, nil
668}
669
Jon Perritt78c57ce2014-11-20 11:07:18 -0700670// ToMetadataUpdateMap assembles a body for an Update request based on the contents of a MetadataOpts.
671func (opts MetadataOpts) ToMetadataUpdateMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700672 return map[string]interface{}{"metadata": opts}, nil
673}
674
Jon Perritt789f8322014-11-21 08:20:04 -0700675// ResetMetadata will create multiple new key-value pairs for the given server ID.
Jon Perrittcc77da62014-11-16 13:14:21 -0700676// Note: Using this operation will erase any already-existing metadata and create
677// the new metadata provided. To keep any already-existing metadata, use the
678// UpdateMetadatas or UpdateMetadata function.
Jon Perritt789f8322014-11-21 08:20:04 -0700679func ResetMetadata(client *gophercloud.ServiceClient, id string, opts ResetMetadataOptsBuilder) ResetMetadataResult {
680 var res ResetMetadataResult
681 metadata, err := opts.ToMetadataResetMap()
Jon Perrittcc77da62014-11-16 13:14:21 -0700682 if err != nil {
683 res.Err = err
684 return res
685 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100686 _, res.Err = client.Put(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
687 OkCodes: []int{200},
Jon Perrittcc77da62014-11-16 13:14:21 -0700688 })
689 return res
690}
691
Jon Perritt78c57ce2014-11-20 11:07:18 -0700692// Metadata requests all the metadata for the given server ID.
693func Metadata(client *gophercloud.ServiceClient, id string) GetMetadataResult {
Jon Perrittcc77da62014-11-16 13:14:21 -0700694 var res GetMetadataResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100695 _, res.Err = client.Get(metadataURL(client, id), &res.Body, nil)
Jon Perrittcc77da62014-11-16 13:14:21 -0700696 return res
697}
698
Jon Perritt78c57ce2014-11-20 11:07:18 -0700699// UpdateMetadataOptsBuilder allows extensions to add additional parameters to the
700// Create request.
701type UpdateMetadataOptsBuilder interface {
702 ToMetadataUpdateMap() (map[string]interface{}, error)
703}
704
705// UpdateMetadata updates (or creates) all the metadata specified by opts for the given server ID.
706// This operation does not affect already-existing metadata that is not specified
707// by opts.
708func UpdateMetadata(client *gophercloud.ServiceClient, id string, opts UpdateMetadataOptsBuilder) UpdateMetadataResult {
709 var res UpdateMetadataResult
710 metadata, err := opts.ToMetadataUpdateMap()
711 if err != nil {
712 res.Err = err
713 return res
714 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100715 _, res.Err = client.Post(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
716 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700717 })
718 return res
719}
720
721// MetadatumOptsBuilder allows extensions to add additional parameters to the
722// Create request.
723type MetadatumOptsBuilder interface {
724 ToMetadatumCreateMap() (map[string]interface{}, string, error)
725}
726
727// MetadatumOpts is a map of length one that contains a key-value pair.
728type MetadatumOpts map[string]string
729
730// ToMetadatumCreateMap assembles a body for a Create request based on the contents of a MetadataumOpts.
731func (opts MetadatumOpts) ToMetadatumCreateMap() (map[string]interface{}, string, error) {
732 if len(opts) != 1 {
733 return nil, "", errors.New("CreateMetadatum operation must have 1 and only 1 key-value pair.")
734 }
735 metadatum := map[string]interface{}{"meta": opts}
736 var key string
737 for k := range metadatum["meta"].(MetadatumOpts) {
738 key = k
739 }
740 return metadatum, key, nil
741}
742
743// CreateMetadatum will create or update the key-value pair with the given key for the given server ID.
744func CreateMetadatum(client *gophercloud.ServiceClient, id string, opts MetadatumOptsBuilder) CreateMetadatumResult {
745 var res CreateMetadatumResult
746 metadatum, key, err := opts.ToMetadatumCreateMap()
747 if err != nil {
748 res.Err = err
749 return res
750 }
751
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100752 _, res.Err = client.Put(metadatumURL(client, id, key), metadatum, &res.Body, &gophercloud.RequestOpts{
753 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700754 })
755 return res
756}
757
758// Metadatum requests the key-value pair with the given key for the given server ID.
759func Metadatum(client *gophercloud.ServiceClient, id, key string) GetMetadatumResult {
760 var res GetMetadatumResult
Ash Wilson59fb6c42015-02-12 16:21:13 -0500761 _, res.Err = client.Request("GET", metadatumURL(client, id, key), gophercloud.RequestOpts{
762 JSONResponse: &res.Body,
Jon Perritt78c57ce2014-11-20 11:07:18 -0700763 })
764 return res
765}
766
767// DeleteMetadatum will delete the key-value pair with the given key for the given server ID.
768func DeleteMetadatum(client *gophercloud.ServiceClient, id, key string) DeleteMetadatumResult {
769 var res DeleteMetadatumResult
Pratik Mallyaee675fd2015-09-14 14:07:30 -0500770 _, res.Err = client.Delete(metadatumURL(client, id, key), nil)
Jon Perrittcc77da62014-11-16 13:14:21 -0700771 return res
772}
Jon Perritt5cb49482015-02-19 12:19:58 -0700773
774// ListAddresses makes a request against the API to list the servers IP addresses.
775func ListAddresses(client *gophercloud.ServiceClient, id string) pagination.Pager {
776 createPageFn := func(r pagination.PageResult) pagination.Page {
777 return AddressPage{pagination.SinglePageBase(r)}
778 }
779 return pagination.NewPager(client, listAddressesURL(client, id), createPageFn)
780}
Jon Perritt04d073c2015-02-19 21:46:23 -0700781
782// ListAddressesByNetwork makes a request against the API to list the servers IP addresses
783// for the given network.
784func ListAddressesByNetwork(client *gophercloud.ServiceClient, id, network string) pagination.Pager {
785 createPageFn := func(r pagination.PageResult) pagination.Page {
786 return NetworkAddressPage{pagination.SinglePageBase(r)}
787 }
788 return pagination.NewPager(client, listAddressesByNetworkURL(client, id, network), createPageFn)
789}
einarf2fc665e2015-04-16 20:16:21 +0000790
einarf4e5fdaf2015-04-16 23:14:59 +0000791type CreateImageOpts struct {
einarf2fc665e2015-04-16 20:16:21 +0000792 // Name [required] of the image/snapshot
793 Name string
794 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the created image.
795 Metadata map[string]string
796}
797
einarf4e5fdaf2015-04-16 23:14:59 +0000798type CreateImageOptsBuilder interface {
799 ToServerCreateImageMap() (map[string]interface{}, error)
einarf2fc665e2015-04-16 20:16:21 +0000800}
801
einarf4e5fdaf2015-04-16 23:14:59 +0000802// ToServerCreateImageMap formats a CreateImageOpts structure into a request body.
803func (opts CreateImageOpts) ToServerCreateImageMap() (map[string]interface{}, error) {
einarf2fc665e2015-04-16 20:16:21 +0000804 var err error
805 img := make(map[string]interface{})
806 if opts.Name == "" {
einarf4e5fdaf2015-04-16 23:14:59 +0000807 return nil, fmt.Errorf("Cannot create a server image without a name")
einarf2fc665e2015-04-16 20:16:21 +0000808 }
809 img["name"] = opts.Name
810 if opts.Metadata != nil {
811 img["metadata"] = opts.Metadata
812 }
813 createImage := make(map[string]interface{})
814 createImage["createImage"] = img
815 return createImage, err
816}
817
einarf4e5fdaf2015-04-16 23:14:59 +0000818// CreateImage makes a request against the nova API to schedule an image to be created of the server
jrperrittb1013232016-02-10 19:01:53 -0600819func CreateImage(client *gophercloud.ServiceClient, serverID string, opts CreateImageOptsBuilder) CreateImageResult {
einarf4e5fdaf2015-04-16 23:14:59 +0000820 var res CreateImageResult
821 reqBody, err := opts.ToServerCreateImageMap()
einarf2fc665e2015-04-16 20:16:21 +0000822 if err != nil {
823 res.Err = err
824 return res
825 }
jrperrittb1013232016-02-10 19:01:53 -0600826 response, err := client.Post(actionURL(client, serverID), reqBody, nil, &gophercloud.RequestOpts{
einarf2fc665e2015-04-16 20:16:21 +0000827 OkCodes: []int{202},
828 })
829 res.Err = err
einarf4e5fdaf2015-04-16 23:14:59 +0000830 res.Header = response.Header
Kevin Pike9748b7b2015-05-05 07:34:07 -0700831 return res
einarf2fc665e2015-04-16 20:16:21 +0000832}
Jon Perritt6b0a8832015-06-04 14:32:30 -0600833
834// IDFromName is a convienience function that returns a server's ID given its name.
835func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) {
836 serverCount := 0
837 serverID := ""
838 if name == "" {
839 return "", fmt.Errorf("A server name must be provided.")
840 }
841 pager := List(client, nil)
842 pager.EachPage(func(page pagination.Page) (bool, error) {
843 serverList, err := ExtractServers(page)
844 if err != nil {
845 return false, err
846 }
847
848 for _, s := range serverList {
849 if s.Name == name {
850 serverCount++
851 serverID = s.ID
852 }
853 }
854 return true, nil
855 })
856
857 switch serverCount {
858 case 0:
859 return "", fmt.Errorf("Unable to find server: %s", name)
860 case 1:
861 return serverID, nil
862 default:
863 return "", fmt.Errorf("Found %d servers matching %s", serverCount, name)
864 }
865}