blob: c93889512c110bbbd90186dacfa028df27049f9d [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
jrperrittb1013232016-02-10 19:01:53 -06009 "github.com/jrperritt/gophercloud/openstack/compute/v2/images"
Ash Wilson01626a32014-09-17 10:38:07 -040010 "github.com/rackspace/gophercloud"
Jon Perrittad5f1cb2015-05-20 10:38:13 -060011 "github.com/rackspace/gophercloud/openstack/compute/v2/flavors"
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.
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
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
jrperrittb1013232016-02-10 19:01:53 -0600250 // If ImageRef isn't provided, use ImageName to ascertain the image ID.
251 if opts.ImageRef == "" {
252 if opts.ImageName == "" {
253 return nil, errors.New("One and only one of ImageRef and ImageName must be provided.")
254 }
255 imageID, err := images.IDFromName(client, opts.ImageName)
256 if err != nil {
257 return nil, err
258 }
259 server["imageRef"] = imageID
260 }
261
262 // If FlavorRef isn't provided, use FlavorName to ascertain the flavor ID.
263 if opts.FlavorRef == "" {
264 if opts.FlavorName == "" {
265 return nil, errors.New("One and only one of FlavorRef and FlavorName must be provided.")
266 }
267 flavorID, err := flavors.IDFromName(client, opts.FlavorName)
268 if err != nil {
269 return nil, err
270 }
271 server["flavorRef"] = flavorID
272 }
273
Jon Perritt4149d7c2014-10-23 21:23:46 -0500274 return map[string]interface{}{"server": server}, nil
Ash Wilson6a310e02014-09-29 08:24:02 -0400275}
276
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800277// Create requests a server to be provisioned to the user in the current tenant.
Ash Wilson2206a112014-10-02 10:57:38 -0400278func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult {
Jon Perritt4149d7c2014-10-23 21:23:46 -0500279 var res CreateResult
280
281 reqBody, err := opts.ToServerCreateMap()
282 if err != nil {
283 res.Err = err
284 return res
285 }
286
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100287 _, res.Err = client.Post(listURL(client), reqBody, &res.Body, nil)
Jon Perritt4149d7c2014-10-23 21:23:46 -0500288 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800289}
290
291// Delete requests that a server previously provisioned be removed from your account.
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100292func Delete(client *gophercloud.ServiceClient, id string) DeleteResult {
293 var res DeleteResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100294 _, res.Err = client.Delete(deleteURL(client, id), nil)
Jamie Hannaford34732fe2014-10-27 11:29:36 +0100295 return res
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800296}
297
Ian Duffy370c4302016-01-21 10:44:56 +0000298func ForceDelete(client *gophercloud.ServiceClient, id string) ActionResult {
299 var req struct {
300 ForceDelete string `json:"forceDelete"`
301 }
302
303 var res ActionResult
304 _, res.Err = client.Post(actionURL(client, id), req, nil, nil)
305 return res
306
307}
308
Ash Wilson7ddf0362014-09-17 10:59:09 -0400309// Get requests details on a single server, by ID.
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400310func Get(client *gophercloud.ServiceClient, id string) GetResult {
311 var result GetResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100312 _, result.Err = client.Get(getURL(client, id), &result.Body, &gophercloud.RequestOpts{
313 OkCodes: []int{200, 203},
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800314 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400315 return result
Samuel A. Falvo IIce000732014-02-13 18:53:53 -0800316}
317
Alex Gaynora6d5f9f2014-10-27 10:52:32 -0700318// UpdateOptsBuilder allows extensions to add additional attributes to the Update request.
Jon Perritt82048212014-10-13 22:33:13 -0500319type UpdateOptsBuilder interface {
Ash Wilsone45c9732014-09-29 10:54:12 -0400320 ToServerUpdateMap() map[string]interface{}
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400321}
322
323// UpdateOpts specifies the base attributes that may be updated on an existing server.
324type UpdateOpts struct {
325 // Name [optional] changes the displayed name of the server.
326 // The server host name will *not* change.
327 // Server names are not constrained to be unique, even within the same tenant.
328 Name string
329
330 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
331 AccessIPv4 string
332
333 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
334 AccessIPv6 string
335}
336
Ash Wilsone45c9732014-09-29 10:54:12 -0400337// ToServerUpdateMap formats an UpdateOpts structure into a request body.
338func (opts UpdateOpts) ToServerUpdateMap() map[string]interface{} {
Ash Wilsondcbc8fb2014-09-29 09:05:44 -0400339 server := make(map[string]string)
340 if opts.Name != "" {
341 server["name"] = opts.Name
342 }
343 if opts.AccessIPv4 != "" {
344 server["accessIPv4"] = opts.AccessIPv4
345 }
346 if opts.AccessIPv6 != "" {
347 server["accessIPv6"] = opts.AccessIPv6
348 }
349 return map[string]interface{}{"server": server}
350}
351
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800352// Update requests that various attributes of the indicated server be changed.
Jon Perritt82048212014-10-13 22:33:13 -0500353func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400354 var result UpdateResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100355 reqBody := opts.ToServerUpdateMap()
356 _, result.Err = client.Put(updateURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
357 OkCodes: []int{200},
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800358 })
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400359 return result
Samuel A. Falvo II22d3b772014-02-13 19:27:05 -0800360}
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700361
Ash Wilson01626a32014-09-17 10:38:07 -0400362// ChangeAdminPassword alters the administrator or root password for a specified server.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200363func ChangeAdminPassword(client *gophercloud.ServiceClient, id, newPassword string) ActionResult {
Ash Wilsondc7daa82014-09-23 16:34:42 -0400364 var req struct {
365 ChangePassword struct {
366 AdminPass string `json:"adminPass"`
367 } `json:"changePassword"`
368 }
369
370 req.ChangePassword.AdminPass = newPassword
371
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200372 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100373 _, res.Err = client.Post(actionURL(client, id), req, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200374 return res
Samuel A. Falvo IIca5f9a32014-03-11 17:52:58 -0700375}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700376
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700377// ErrArgument errors occur when an argument supplied to a package function
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700378// fails to fall within acceptable values. For example, the Reboot() function
379// expects the "how" parameter to be one of HardReboot or SoftReboot. These
380// constants are (currently) strings, leading someone to wonder if they can pass
381// other string values instead, perhaps in an effort to break the API of their
382// provider. Reboot() returns this error in this situation.
383//
384// Function identifies which function was called/which function is generating
385// the error.
386// Argument identifies which formal argument was responsible for producing the
387// error.
388// Value provides the value as it was passed into the function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700389type ErrArgument struct {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700390 Function, Argument string
Jon Perritt30558642014-04-14 17:07:12 -0500391 Value interface{}
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700392}
393
394// Error yields a useful diagnostic for debugging purposes.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700395func (e *ErrArgument) Error() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700396 return fmt.Sprintf("Bad argument in call to %s, formal parameter %s, value %#v", e.Function, e.Argument, e.Value)
397}
398
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700399func (e *ErrArgument) String() string {
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700400 return e.Error()
401}
402
Ash Wilson01626a32014-09-17 10:38:07 -0400403// RebootMethod describes the mechanisms by which a server reboot can be requested.
404type RebootMethod string
405
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700406// These constants determine how a server should be rebooted.
407// See the Reboot() function for further details.
408const (
Ash Wilson01626a32014-09-17 10:38:07 -0400409 SoftReboot RebootMethod = "SOFT"
410 HardReboot RebootMethod = "HARD"
411 OSReboot = SoftReboot
412 PowerCycle = HardReboot
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700413)
414
415// Reboot requests that a given server reboot.
416// Two methods exist for rebooting a server:
417//
Ash Wilson01626a32014-09-17 10:38:07 -0400418// HardReboot (aka PowerCycle) restarts the server instance by physically cutting power to the machine, or if a VM,
419// terminating it at the hypervisor level.
420// It's done. Caput. Full stop.
421// Then, after a brief while, power is restored or the VM instance restarted.
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700422//
Ash Wilson01626a32014-09-17 10:38:07 -0400423// SoftReboot (aka OSReboot) simply tells the OS to restart under its own procedures.
424// 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 +0200425func Reboot(client *gophercloud.ServiceClient, id string, how RebootMethod) ActionResult {
426 var res ActionResult
427
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700428 if (how != SoftReboot) && (how != HardReboot) {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200429 res.Err = &ErrArgument{
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700430 Function: "Reboot",
431 Argument: "how",
Jon Perritt30558642014-04-14 17:07:12 -0500432 Value: how,
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700433 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200434 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700435 }
Jon Perritt30558642014-04-14 17:07:12 -0500436
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100437 reqBody := struct {
438 C map[string]string `json:"reboot"`
439 }{
440 map[string]string{"type": string(how)},
441 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200442
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100443 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200444 return res
Samuel A. Falvo II41c9f612014-03-11 19:00:10 -0700445}
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700446
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200447// RebuildOptsBuilder is an interface that allows extensions to override the
448// default behaviour of rebuild options
449type RebuildOptsBuilder interface {
450 ToServerRebuildMap() (map[string]interface{}, error)
451}
452
453// RebuildOpts represents the configuration options used in a server rebuild
454// operation
455type RebuildOpts struct {
456 // Required. The ID of the image you want your server to be provisioned on
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200457 ImageID string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200458
459 // Name to set the server to
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200460 Name string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200461
462 // Required. The server's admin password
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200463 AdminPass string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200464
465 // AccessIPv4 [optional] provides a new IPv4 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200466 AccessIPv4 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200467
468 // AccessIPv6 [optional] provides a new IPv6 address for the instance.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200469 AccessIPv6 string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200470
471 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server.
Jamie Hannaforddcb8c272014-10-16 16:34:41 +0200472 Metadata map[string]string
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200473
Kevin Pike92e10b52015-04-10 15:16:57 -0700474 // Personality [optional] includes files to inject into the server at launch.
475 // Rebuild will base64-encode file contents for you.
476 Personality Personality
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200477}
478
479// ToServerRebuildMap formats a RebuildOpts struct into a map for use in JSON
480func (opts RebuildOpts) ToServerRebuildMap() (map[string]interface{}, error) {
481 var err error
482 server := make(map[string]interface{})
483
484 if opts.AdminPass == "" {
485 err = fmt.Errorf("AdminPass is required")
486 }
487
488 if opts.ImageID == "" {
489 err = fmt.Errorf("ImageID is required")
490 }
491
492 if err != nil {
493 return server, err
494 }
495
496 server["name"] = opts.Name
497 server["adminPass"] = opts.AdminPass
498 server["imageRef"] = opts.ImageID
499
500 if opts.AccessIPv4 != "" {
501 server["accessIPv4"] = opts.AccessIPv4
502 }
503
504 if opts.AccessIPv6 != "" {
505 server["accessIPv6"] = opts.AccessIPv6
506 }
507
508 if opts.Metadata != nil {
509 server["metadata"] = opts.Metadata
510 }
511
Kevin Pike92e10b52015-04-10 15:16:57 -0700512 if len(opts.Personality) > 0 {
Kevin Pikea2bfaea2015-04-21 11:45:59 -0700513 server["personality"] = opts.Personality
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200514 }
515
516 return map[string]interface{}{"rebuild": server}, nil
517}
518
519// Rebuild will reprovision the server according to the configuration options
520// provided in the RebuildOpts struct.
521func Rebuild(client *gophercloud.ServiceClient, id string, opts RebuildOptsBuilder) RebuildResult {
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400522 var result RebuildResult
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700523
524 if id == "" {
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200525 result.Err = fmt.Errorf("ID is required")
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400526 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700527 }
528
Jamie Hannaford6c9eb602014-10-16 16:28:07 +0200529 reqBody, err := opts.ToServerRebuildMap()
530 if err != nil {
531 result.Err = err
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400532 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700533 }
534
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100535 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, nil)
Ash Wilsond27e0ff2014-09-25 11:50:31 -0400536 return result
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700537}
538
Ash Wilson5f7cf182014-10-23 08:35:24 -0400539// ResizeOptsBuilder is an interface that allows extensions to override the default structure of
540// a Resize request.
541type ResizeOptsBuilder interface {
542 ToServerResizeMap() (map[string]interface{}, error)
543}
544
545// ResizeOpts represents the configuration options used to control a Resize operation.
546type ResizeOpts struct {
547 // FlavorRef is the ID of the flavor you wish your server to become.
548 FlavorRef string
549}
550
Alex Gaynor266e9332014-10-28 14:44:04 -0700551// 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 -0400552// Resize request.
553func (opts ResizeOpts) ToServerResizeMap() (map[string]interface{}, error) {
554 resize := map[string]interface{}{
555 "flavorRef": opts.FlavorRef,
556 }
557
558 return map[string]interface{}{"resize": resize}, nil
559}
560
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700561// Resize instructs the provider to change the flavor of the server.
Ash Wilson01626a32014-09-17 10:38:07 -0400562// Note that this implies rebuilding it.
563// Unfortunately, one cannot pass rebuild parameters to the resize function.
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700564// When the resize completes, the server will be in RESIZE_VERIFY state.
565// While in this state, you can explore the use of the new server's configuration.
566// If you like it, call ConfirmResize() to commit the resize permanently.
567// Otherwise, call RevertResize() to restore the old configuration.
Ash Wilson9e87a922014-10-23 14:29:22 -0400568func Resize(client *gophercloud.ServiceClient, id string, opts ResizeOptsBuilder) ActionResult {
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200569 var res ActionResult
Ash Wilson5f7cf182014-10-23 08:35:24 -0400570 reqBody, err := opts.ToServerResizeMap()
571 if err != nil {
572 res.Err = err
573 return res
574 }
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200575
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100576 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200577 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700578}
579
580// ConfirmResize confirms a previous resize operation on a server.
581// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200582func ConfirmResize(client *gophercloud.ServiceClient, id string) ActionResult {
583 var res ActionResult
584
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100585 reqBody := map[string]interface{}{"confirmResize": nil}
586 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, &gophercloud.RequestOpts{
587 OkCodes: []int{201, 202, 204},
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700588 })
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200589 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700590}
591
592// RevertResize cancels a previous resize operation on a server.
593// See Resize() for more details.
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200594func RevertResize(client *gophercloud.ServiceClient, id string) ActionResult {
595 var res ActionResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100596 reqBody := map[string]interface{}{"revertResize": nil}
597 _, res.Err = client.Post(actionURL(client, id), reqBody, nil, nil)
Jamie Hannaford8c072a32014-10-16 14:33:32 +0200598 return res
Samuel A. Falvo II808bb632014-03-12 00:07:50 -0700599}
Alex Gaynor39584a02014-10-28 13:59:21 -0700600
Alex Gaynor266e9332014-10-28 14:44:04 -0700601// RescueOptsBuilder is an interface that allows extensions to override the
602// default structure of a Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700603type RescueOptsBuilder interface {
604 ToServerRescueMap() (map[string]interface{}, error)
605}
606
Alex Gaynor266e9332014-10-28 14:44:04 -0700607// RescueOpts represents the configuration options used to control a Rescue
608// option.
Alex Gaynor39584a02014-10-28 13:59:21 -0700609type RescueOpts struct {
Alex Gaynor266e9332014-10-28 14:44:04 -0700610 // AdminPass is the desired administrative password for the instance in
Alex Gaynorcfec7722014-11-13 13:33:49 -0800611 // RESCUE mode. If it's left blank, the server will generate a password.
Alex Gaynor39584a02014-10-28 13:59:21 -0700612 AdminPass string
613}
614
Jon Perrittcc77da62014-11-16 13:14:21 -0700615// ToServerRescueMap formats a RescueOpts as a map that can be used as a JSON
Alex Gaynor266e9332014-10-28 14:44:04 -0700616// request body for the Rescue request.
Alex Gaynor39584a02014-10-28 13:59:21 -0700617func (opts RescueOpts) ToServerRescueMap() (map[string]interface{}, error) {
618 server := make(map[string]interface{})
619 if opts.AdminPass != "" {
620 server["adminPass"] = opts.AdminPass
621 }
622 return map[string]interface{}{"rescue": server}, nil
623}
624
Alex Gaynor266e9332014-10-28 14:44:04 -0700625// Rescue instructs the provider to place the server into RESCUE mode.
Alex Gaynorfbe61bb2014-11-12 13:35:03 -0800626func Rescue(client *gophercloud.ServiceClient, id string, opts RescueOptsBuilder) RescueResult {
627 var result RescueResult
Alex Gaynor39584a02014-10-28 13:59:21 -0700628
629 if id == "" {
630 result.Err = fmt.Errorf("ID is required")
631 return result
632 }
633 reqBody, err := opts.ToServerRescueMap()
634 if err != nil {
635 result.Err = err
636 return result
637 }
638
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100639 _, result.Err = client.Post(actionURL(client, id), reqBody, &result.Body, &gophercloud.RequestOpts{
640 OkCodes: []int{200},
Alex Gaynor39584a02014-10-28 13:59:21 -0700641 })
642
643 return result
644}
Jon Perrittcc77da62014-11-16 13:14:21 -0700645
Jon Perritt789f8322014-11-21 08:20:04 -0700646// ResetMetadataOptsBuilder allows extensions to add additional parameters to the
647// Reset request.
648type ResetMetadataOptsBuilder interface {
649 ToMetadataResetMap() (map[string]interface{}, error)
Jon Perrittcc77da62014-11-16 13:14:21 -0700650}
651
Jon Perritt78c57ce2014-11-20 11:07:18 -0700652// MetadataOpts is a map that contains key-value pairs.
653type MetadataOpts map[string]string
Jon Perrittcc77da62014-11-16 13:14:21 -0700654
Jon Perritt789f8322014-11-21 08:20:04 -0700655// ToMetadataResetMap assembles a body for a Reset request based on the contents of a MetadataOpts.
656func (opts MetadataOpts) ToMetadataResetMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700657 return map[string]interface{}{"metadata": opts}, nil
658}
659
Jon Perritt78c57ce2014-11-20 11:07:18 -0700660// ToMetadataUpdateMap assembles a body for an Update request based on the contents of a MetadataOpts.
661func (opts MetadataOpts) ToMetadataUpdateMap() (map[string]interface{}, error) {
Jon Perrittcc77da62014-11-16 13:14:21 -0700662 return map[string]interface{}{"metadata": opts}, nil
663}
664
Jon Perritt789f8322014-11-21 08:20:04 -0700665// ResetMetadata will create multiple new key-value pairs for the given server ID.
Jon Perrittcc77da62014-11-16 13:14:21 -0700666// Note: Using this operation will erase any already-existing metadata and create
667// the new metadata provided. To keep any already-existing metadata, use the
668// UpdateMetadatas or UpdateMetadata function.
Jon Perritt789f8322014-11-21 08:20:04 -0700669func ResetMetadata(client *gophercloud.ServiceClient, id string, opts ResetMetadataOptsBuilder) ResetMetadataResult {
670 var res ResetMetadataResult
671 metadata, err := opts.ToMetadataResetMap()
Jon Perrittcc77da62014-11-16 13:14:21 -0700672 if err != nil {
673 res.Err = err
674 return res
675 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100676 _, res.Err = client.Put(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
677 OkCodes: []int{200},
Jon Perrittcc77da62014-11-16 13:14:21 -0700678 })
679 return res
680}
681
Jon Perritt78c57ce2014-11-20 11:07:18 -0700682// Metadata requests all the metadata for the given server ID.
683func Metadata(client *gophercloud.ServiceClient, id string) GetMetadataResult {
Jon Perrittcc77da62014-11-16 13:14:21 -0700684 var res GetMetadataResult
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100685 _, res.Err = client.Get(metadataURL(client, id), &res.Body, nil)
Jon Perrittcc77da62014-11-16 13:14:21 -0700686 return res
687}
688
Jon Perritt78c57ce2014-11-20 11:07:18 -0700689// UpdateMetadataOptsBuilder allows extensions to add additional parameters to the
690// Create request.
691type UpdateMetadataOptsBuilder interface {
692 ToMetadataUpdateMap() (map[string]interface{}, error)
693}
694
695// UpdateMetadata updates (or creates) all the metadata specified by opts for the given server ID.
696// This operation does not affect already-existing metadata that is not specified
697// by opts.
698func UpdateMetadata(client *gophercloud.ServiceClient, id string, opts UpdateMetadataOptsBuilder) UpdateMetadataResult {
699 var res UpdateMetadataResult
700 metadata, err := opts.ToMetadataUpdateMap()
701 if err != nil {
702 res.Err = err
703 return res
704 }
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100705 _, res.Err = client.Post(metadataURL(client, id), metadata, &res.Body, &gophercloud.RequestOpts{
706 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700707 })
708 return res
709}
710
711// MetadatumOptsBuilder allows extensions to add additional parameters to the
712// Create request.
713type MetadatumOptsBuilder interface {
714 ToMetadatumCreateMap() (map[string]interface{}, string, error)
715}
716
717// MetadatumOpts is a map of length one that contains a key-value pair.
718type MetadatumOpts map[string]string
719
720// ToMetadatumCreateMap assembles a body for a Create request based on the contents of a MetadataumOpts.
721func (opts MetadatumOpts) ToMetadatumCreateMap() (map[string]interface{}, string, error) {
722 if len(opts) != 1 {
723 return nil, "", errors.New("CreateMetadatum operation must have 1 and only 1 key-value pair.")
724 }
725 metadatum := map[string]interface{}{"meta": opts}
726 var key string
727 for k := range metadatum["meta"].(MetadatumOpts) {
728 key = k
729 }
730 return metadatum, key, nil
731}
732
733// CreateMetadatum will create or update the key-value pair with the given key for the given server ID.
734func CreateMetadatum(client *gophercloud.ServiceClient, id string, opts MetadatumOptsBuilder) CreateMetadatumResult {
735 var res CreateMetadatumResult
736 metadatum, key, err := opts.ToMetadatumCreateMap()
737 if err != nil {
738 res.Err = err
739 return res
740 }
741
Jamie Hannaford6a3a78f2015-03-24 14:56:12 +0100742 _, res.Err = client.Put(metadatumURL(client, id, key), metadatum, &res.Body, &gophercloud.RequestOpts{
743 OkCodes: []int{200},
Jon Perritt78c57ce2014-11-20 11:07:18 -0700744 })
745 return res
746}
747
748// Metadatum requests the key-value pair with the given key for the given server ID.
749func Metadatum(client *gophercloud.ServiceClient, id, key string) GetMetadatumResult {
750 var res GetMetadatumResult
Ash Wilson59fb6c42015-02-12 16:21:13 -0500751 _, res.Err = client.Request("GET", metadatumURL(client, id, key), gophercloud.RequestOpts{
752 JSONResponse: &res.Body,
Jon Perritt78c57ce2014-11-20 11:07:18 -0700753 })
754 return res
755}
756
757// DeleteMetadatum will delete the key-value pair with the given key for the given server ID.
758func DeleteMetadatum(client *gophercloud.ServiceClient, id, key string) DeleteMetadatumResult {
759 var res DeleteMetadatumResult
Pratik Mallyaee675fd2015-09-14 14:07:30 -0500760 _, res.Err = client.Delete(metadatumURL(client, id, key), nil)
Jon Perrittcc77da62014-11-16 13:14:21 -0700761 return res
762}
Jon Perritt5cb49482015-02-19 12:19:58 -0700763
764// ListAddresses makes a request against the API to list the servers IP addresses.
765func ListAddresses(client *gophercloud.ServiceClient, id string) pagination.Pager {
766 createPageFn := func(r pagination.PageResult) pagination.Page {
767 return AddressPage{pagination.SinglePageBase(r)}
768 }
769 return pagination.NewPager(client, listAddressesURL(client, id), createPageFn)
770}
Jon Perritt04d073c2015-02-19 21:46:23 -0700771
772// ListAddressesByNetwork makes a request against the API to list the servers IP addresses
773// for the given network.
774func ListAddressesByNetwork(client *gophercloud.ServiceClient, id, network string) pagination.Pager {
775 createPageFn := func(r pagination.PageResult) pagination.Page {
776 return NetworkAddressPage{pagination.SinglePageBase(r)}
777 }
778 return pagination.NewPager(client, listAddressesByNetworkURL(client, id, network), createPageFn)
779}
einarf2fc665e2015-04-16 20:16:21 +0000780
einarf4e5fdaf2015-04-16 23:14:59 +0000781type CreateImageOpts struct {
einarf2fc665e2015-04-16 20:16:21 +0000782 // Name [required] of the image/snapshot
783 Name string
784 // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the created image.
785 Metadata map[string]string
786}
787
einarf4e5fdaf2015-04-16 23:14:59 +0000788type CreateImageOptsBuilder interface {
789 ToServerCreateImageMap() (map[string]interface{}, error)
einarf2fc665e2015-04-16 20:16:21 +0000790}
791
einarf4e5fdaf2015-04-16 23:14:59 +0000792// ToServerCreateImageMap formats a CreateImageOpts structure into a request body.
793func (opts CreateImageOpts) ToServerCreateImageMap() (map[string]interface{}, error) {
einarf2fc665e2015-04-16 20:16:21 +0000794 var err error
795 img := make(map[string]interface{})
796 if opts.Name == "" {
einarf4e5fdaf2015-04-16 23:14:59 +0000797 return nil, fmt.Errorf("Cannot create a server image without a name")
einarf2fc665e2015-04-16 20:16:21 +0000798 }
799 img["name"] = opts.Name
800 if opts.Metadata != nil {
801 img["metadata"] = opts.Metadata
802 }
803 createImage := make(map[string]interface{})
804 createImage["createImage"] = img
805 return createImage, err
806}
807
einarf4e5fdaf2015-04-16 23:14:59 +0000808// CreateImage makes a request against the nova API to schedule an image to be created of the server
jrperrittb1013232016-02-10 19:01:53 -0600809func CreateImage(client *gophercloud.ServiceClient, serverID string, opts CreateImageOptsBuilder) CreateImageResult {
einarf4e5fdaf2015-04-16 23:14:59 +0000810 var res CreateImageResult
811 reqBody, err := opts.ToServerCreateImageMap()
einarf2fc665e2015-04-16 20:16:21 +0000812 if err != nil {
813 res.Err = err
814 return res
815 }
jrperrittb1013232016-02-10 19:01:53 -0600816 response, err := client.Post(actionURL(client, serverID), reqBody, nil, &gophercloud.RequestOpts{
einarf2fc665e2015-04-16 20:16:21 +0000817 OkCodes: []int{202},
818 })
819 res.Err = err
einarf4e5fdaf2015-04-16 23:14:59 +0000820 res.Header = response.Header
Kevin Pike9748b7b2015-05-05 07:34:07 -0700821 return res
einarf2fc665e2015-04-16 20:16:21 +0000822}
Jon Perritt6b0a8832015-06-04 14:32:30 -0600823
824// IDFromName is a convienience function that returns a server's ID given its name.
825func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) {
826 serverCount := 0
827 serverID := ""
828 if name == "" {
829 return "", fmt.Errorf("A server name must be provided.")
830 }
831 pager := List(client, nil)
832 pager.EachPage(func(page pagination.Page) (bool, error) {
833 serverList, err := ExtractServers(page)
834 if err != nil {
835 return false, err
836 }
837
838 for _, s := range serverList {
839 if s.Name == name {
840 serverCount++
841 serverID = s.ID
842 }
843 }
844 return true, nil
845 })
846
847 switch serverCount {
848 case 0:
849 return "", fmt.Errorf("Unable to find server: %s", name)
850 case 1:
851 return serverID, nil
852 default:
853 return "", fmt.Errorf("Found %d servers matching %s", serverCount, name)
854 }
855}