Jamie Hannaford | 2aaf1a6 | 2014-10-16 12:55:50 +0200 | [diff] [blame] | 1 | package servers |
| 2 | |
| 3 | import ( |
| 4 | "encoding/base64" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/racker/perigee" |
| 8 | "github.com/rackspace/gophercloud" |
| 9 | "github.com/rackspace/gophercloud/pagination" |
| 10 | ) |
| 11 | |
| 12 | // ListOptsBuilder allows extensions to add additional parameters to the |
| 13 | // List request. |
| 14 | type ListOptsBuilder interface { |
| 15 | ToServerListQuery() (string, error) |
| 16 | } |
| 17 | |
| 18 | // ListOpts allows the filtering and sorting of paginated collections through |
| 19 | // the API. Filtering is achieved by passing in struct field values that map to |
| 20 | // the server attributes you want to see returned. Marker and Limit are used |
| 21 | // for pagination. |
| 22 | type ListOpts struct { |
| 23 | // A time/date stamp for when the server last changed status. |
| 24 | ChangesSince string `q:"changes-since"` |
| 25 | |
| 26 | // Name of the image in URL format. |
| 27 | Image string `q:"image"` |
| 28 | |
| 29 | // Name of the flavor in URL format. |
| 30 | Flavor string `q:"flavor"` |
| 31 | |
| 32 | // Name of the server as a string; can be queried with regular expressions. |
| 33 | // Realize that ?name=bob returns both bob and bobb. If you need to match bob |
| 34 | // only, you can use a regular expression matching the syntax of the |
| 35 | // underlying database server implemented for Compute. |
| 36 | Name string `q:"name"` |
| 37 | |
| 38 | // Value of the status of the server so that you can filter on "ACTIVE" for example. |
| 39 | Status string `q:"status"` |
| 40 | |
| 41 | // Name of the host as a string. |
| 42 | Host string `q:"host"` |
| 43 | |
| 44 | // UUID of the server at which you want to set a marker. |
| 45 | Marker string `q:"marker"` |
| 46 | |
| 47 | // Integer value for the limit of values to return. |
| 48 | Limit int `q:"limit"` |
| 49 | } |
| 50 | |
| 51 | // ToServerListQuery formats a ListOpts into a query string. |
| 52 | func (opts ListOpts) ToServerListQuery() (string, error) { |
| 53 | q, err := gophercloud.BuildQueryString(opts) |
| 54 | if err != nil { |
| 55 | return "", err |
| 56 | } |
| 57 | return q.String(), nil |
| 58 | } |
| 59 | |
| 60 | // List makes a request against the API to list servers accessible to you. |
| 61 | func List(client *gophercloud.ServiceClient, opts ListOptsBuilder) pagination.Pager { |
| 62 | url := listDetailURL(client) |
| 63 | |
| 64 | if opts != nil { |
| 65 | query, err := opts.ToServerListQuery() |
| 66 | if err != nil { |
| 67 | return pagination.Pager{Err: err} |
| 68 | } |
| 69 | url += query |
| 70 | } |
| 71 | |
| 72 | createPageFn := func(r pagination.LastHTTPResponse) pagination.Page { |
| 73 | return ServerPage{pagination.LinkedPageBase{LastHTTPResponse: r}} |
| 74 | } |
| 75 | |
| 76 | return pagination.NewPager(client, url, createPageFn) |
| 77 | } |
| 78 | |
| 79 | // CreateOptsBuilder describes struct types that can be accepted by the Create call. |
| 80 | // The CreateOpts struct in this package does. |
| 81 | type CreateOptsBuilder interface { |
| 82 | ToServerCreateMap() map[string]interface{} |
| 83 | } |
| 84 | |
| 85 | // Network is used within CreateOpts to control a new server's network attachments. |
| 86 | type Network struct { |
| 87 | // UUID of a nova-network to attach to the newly provisioned server. |
| 88 | // Required unless Port is provided. |
| 89 | UUID string |
| 90 | |
| 91 | // Port of a neutron network to attach to the newly provisioned server. |
| 92 | // Required unless UUID is provided. |
| 93 | Port string |
| 94 | |
| 95 | // FixedIP [optional] specifies a fixed IPv4 address to be used on this network. |
| 96 | FixedIP string |
| 97 | } |
| 98 | |
| 99 | // CreateOpts specifies server creation parameters. |
| 100 | type CreateOpts struct { |
| 101 | // Name [required] is the name to assign to the newly launched server. |
| 102 | Name string |
| 103 | |
| 104 | // ImageRef [required] is the ID or full URL to the image that contains the server's OS and initial state. |
| 105 | // Optional if using the boot-from-volume extension. |
| 106 | ImageRef string |
| 107 | |
| 108 | // FlavorRef [required] is the ID or full URL to the flavor that describes the server's specs. |
| 109 | FlavorRef string |
| 110 | |
| 111 | // SecurityGroups [optional] lists the names of the security groups to which this server should belong. |
| 112 | SecurityGroups []string |
| 113 | |
| 114 | // UserData [optional] contains configuration information or scripts to use upon launch. |
| 115 | // Create will base64-encode it for you. |
| 116 | UserData []byte |
| 117 | |
| 118 | // AvailabilityZone [optional] in which to launch the server. |
| 119 | AvailabilityZone string |
| 120 | |
| 121 | // Networks [optional] dictates how this server will be attached to available networks. |
| 122 | // By default, the server will be attached to all isolated networks for the tenant. |
| 123 | Networks []Network |
| 124 | |
| 125 | // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server. |
| 126 | Metadata map[string]string |
| 127 | |
| 128 | // Personality [optional] includes the path and contents of a file to inject into the server at launch. |
| 129 | // The maximum size of the file is 255 bytes (decoded). |
| 130 | Personality []byte |
| 131 | |
| 132 | // ConfigDrive [optional] enables metadata injection through a configuration drive. |
| 133 | ConfigDrive bool |
| 134 | } |
| 135 | |
| 136 | // ToServerCreateMap assembles a request body based on the contents of a CreateOpts. |
| 137 | func (opts CreateOpts) ToServerCreateMap() map[string]interface{} { |
| 138 | server := make(map[string]interface{}) |
| 139 | |
| 140 | server["name"] = opts.Name |
| 141 | server["imageRef"] = opts.ImageRef |
| 142 | server["flavorRef"] = opts.FlavorRef |
| 143 | |
| 144 | if opts.UserData != nil { |
| 145 | encoded := base64.StdEncoding.EncodeToString(opts.UserData) |
| 146 | server["user_data"] = &encoded |
| 147 | } |
| 148 | if opts.Personality != nil { |
| 149 | encoded := base64.StdEncoding.EncodeToString(opts.Personality) |
| 150 | server["personality"] = &encoded |
| 151 | } |
| 152 | if opts.ConfigDrive { |
| 153 | server["config_drive"] = "true" |
| 154 | } |
| 155 | if opts.AvailabilityZone != "" { |
| 156 | server["availability_zone"] = opts.AvailabilityZone |
| 157 | } |
| 158 | if opts.Metadata != nil { |
| 159 | server["metadata"] = opts.Metadata |
| 160 | } |
| 161 | |
| 162 | if len(opts.SecurityGroups) > 0 { |
| 163 | securityGroups := make([]map[string]interface{}, len(opts.SecurityGroups)) |
| 164 | for i, groupName := range opts.SecurityGroups { |
| 165 | securityGroups[i] = map[string]interface{}{"name": groupName} |
| 166 | } |
| 167 | } |
| 168 | if len(opts.Networks) > 0 { |
| 169 | networks := make([]map[string]interface{}, len(opts.Networks)) |
| 170 | for i, net := range opts.Networks { |
| 171 | networks[i] = make(map[string]interface{}) |
| 172 | if net.UUID != "" { |
| 173 | networks[i]["uuid"] = net.UUID |
| 174 | } |
| 175 | if net.Port != "" { |
| 176 | networks[i]["port"] = net.Port |
| 177 | } |
| 178 | if net.FixedIP != "" { |
| 179 | networks[i]["fixed_ip"] = net.FixedIP |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | return map[string]interface{}{"server": server} |
| 185 | } |
| 186 | |
| 187 | // Create requests a server to be provisioned to the user in the current tenant. |
| 188 | func Create(client *gophercloud.ServiceClient, opts CreateOptsBuilder) CreateResult { |
| 189 | var result CreateResult |
| 190 | _, result.Err = perigee.Request("POST", listURL(client), perigee.Options{ |
| 191 | Results: &result.Resp, |
| 192 | ReqBody: opts.ToServerCreateMap(), |
| 193 | MoreHeaders: client.Provider.AuthenticatedHeaders(), |
| 194 | OkCodes: []int{202}, |
| 195 | }) |
| 196 | return result |
| 197 | } |
| 198 | |
| 199 | // Delete requests that a server previously provisioned be removed from your account. |
| 200 | func Delete(client *gophercloud.ServiceClient, id string) error { |
| 201 | _, err := perigee.Request("DELETE", deleteURL(client, id), perigee.Options{ |
| 202 | MoreHeaders: client.Provider.AuthenticatedHeaders(), |
| 203 | OkCodes: []int{204}, |
| 204 | }) |
| 205 | return err |
| 206 | } |
| 207 | |
| 208 | // Get requests details on a single server, by ID. |
| 209 | func Get(client *gophercloud.ServiceClient, id string) GetResult { |
| 210 | var result GetResult |
| 211 | _, result.Err = perigee.Request("GET", getURL(client, id), perigee.Options{ |
| 212 | Results: &result.Resp, |
| 213 | MoreHeaders: client.Provider.AuthenticatedHeaders(), |
| 214 | }) |
| 215 | return result |
| 216 | } |
| 217 | |
| 218 | // UpdateOptsBuilder allows extentions to add additional attributes to the Update request. |
| 219 | type UpdateOptsBuilder interface { |
| 220 | ToServerUpdateMap() map[string]interface{} |
| 221 | } |
| 222 | |
| 223 | // UpdateOpts specifies the base attributes that may be updated on an existing server. |
| 224 | type UpdateOpts struct { |
| 225 | // Name [optional] changes the displayed name of the server. |
| 226 | // The server host name will *not* change. |
| 227 | // Server names are not constrained to be unique, even within the same tenant. |
| 228 | Name string |
| 229 | |
| 230 | // AccessIPv4 [optional] provides a new IPv4 address for the instance. |
| 231 | AccessIPv4 string |
| 232 | |
| 233 | // AccessIPv6 [optional] provides a new IPv6 address for the instance. |
| 234 | AccessIPv6 string |
| 235 | } |
| 236 | |
| 237 | // ToServerUpdateMap formats an UpdateOpts structure into a request body. |
| 238 | func (opts UpdateOpts) ToServerUpdateMap() map[string]interface{} { |
| 239 | server := make(map[string]string) |
| 240 | if opts.Name != "" { |
| 241 | server["name"] = opts.Name |
| 242 | } |
| 243 | if opts.AccessIPv4 != "" { |
| 244 | server["accessIPv4"] = opts.AccessIPv4 |
| 245 | } |
| 246 | if opts.AccessIPv6 != "" { |
| 247 | server["accessIPv6"] = opts.AccessIPv6 |
| 248 | } |
| 249 | return map[string]interface{}{"server": server} |
| 250 | } |
| 251 | |
| 252 | // Update requests that various attributes of the indicated server be changed. |
| 253 | func Update(client *gophercloud.ServiceClient, id string, opts UpdateOptsBuilder) UpdateResult { |
| 254 | var result UpdateResult |
| 255 | _, result.Err = perigee.Request("PUT", updateURL(client, id), perigee.Options{ |
| 256 | Results: &result.Resp, |
| 257 | ReqBody: opts.ToServerUpdateMap(), |
| 258 | MoreHeaders: client.Provider.AuthenticatedHeaders(), |
| 259 | }) |
| 260 | return result |
| 261 | } |
| 262 | |
| 263 | // ChangeAdminPassword alters the administrator or root password for a specified server. |
| 264 | func ChangeAdminPassword(client *gophercloud.ServiceClient, id, newPassword string) error { |
| 265 | var req struct { |
| 266 | ChangePassword struct { |
| 267 | AdminPass string `json:"adminPass"` |
| 268 | } `json:"changePassword"` |
| 269 | } |
| 270 | |
| 271 | req.ChangePassword.AdminPass = newPassword |
| 272 | |
| 273 | _, err := perigee.Request("POST", actionURL(client, id), perigee.Options{ |
| 274 | ReqBody: req, |
| 275 | MoreHeaders: client.Provider.AuthenticatedHeaders(), |
| 276 | OkCodes: []int{202}, |
| 277 | }) |
| 278 | return err |
| 279 | } |
| 280 | |
| 281 | // ErrArgument errors occur when an argument supplied to a package function |
| 282 | // fails to fall within acceptable values. For example, the Reboot() function |
| 283 | // expects the "how" parameter to be one of HardReboot or SoftReboot. These |
| 284 | // constants are (currently) strings, leading someone to wonder if they can pass |
| 285 | // other string values instead, perhaps in an effort to break the API of their |
| 286 | // provider. Reboot() returns this error in this situation. |
| 287 | // |
| 288 | // Function identifies which function was called/which function is generating |
| 289 | // the error. |
| 290 | // Argument identifies which formal argument was responsible for producing the |
| 291 | // error. |
| 292 | // Value provides the value as it was passed into the function. |
| 293 | type ErrArgument struct { |
| 294 | Function, Argument string |
| 295 | Value interface{} |
| 296 | } |
| 297 | |
| 298 | // Error yields a useful diagnostic for debugging purposes. |
| 299 | func (e *ErrArgument) Error() string { |
| 300 | return fmt.Sprintf("Bad argument in call to %s, formal parameter %s, value %#v", e.Function, e.Argument, e.Value) |
| 301 | } |
| 302 | |
| 303 | func (e *ErrArgument) String() string { |
| 304 | return e.Error() |
| 305 | } |
| 306 | |
| 307 | // RebootMethod describes the mechanisms by which a server reboot can be requested. |
| 308 | type RebootMethod string |
| 309 | |
| 310 | // These constants determine how a server should be rebooted. |
| 311 | // See the Reboot() function for further details. |
| 312 | const ( |
| 313 | SoftReboot RebootMethod = "SOFT" |
| 314 | HardReboot RebootMethod = "HARD" |
| 315 | OSReboot = SoftReboot |
| 316 | PowerCycle = HardReboot |
| 317 | ) |
| 318 | |
| 319 | // Reboot requests that a given server reboot. |
| 320 | // Two methods exist for rebooting a server: |
| 321 | // |
| 322 | // HardReboot (aka PowerCycle) restarts the server instance by physically cutting power to the machine, or if a VM, |
| 323 | // terminating it at the hypervisor level. |
| 324 | // It's done. Caput. Full stop. |
| 325 | // Then, after a brief while, power is restored or the VM instance restarted. |
| 326 | // |
| 327 | // SoftReboot (aka OSReboot) simply tells the OS to restart under its own procedures. |
| 328 | // E.g., in Linux, asking it to enter runlevel 6, or executing "sudo shutdown -r now", or by asking Windows to restart the machine. |
| 329 | func Reboot(client *gophercloud.ServiceClient, id string, how RebootMethod) error { |
| 330 | if (how != SoftReboot) && (how != HardReboot) { |
| 331 | return &ErrArgument{ |
| 332 | Function: "Reboot", |
| 333 | Argument: "how", |
| 334 | Value: how, |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | _, err := perigee.Request("POST", actionURL(client, id), perigee.Options{ |
| 339 | ReqBody: struct { |
| 340 | C map[string]string `json:"reboot"` |
| 341 | }{ |
| 342 | map[string]string{"type": string(how)}, |
| 343 | }, |
| 344 | MoreHeaders: client.Provider.AuthenticatedHeaders(), |
| 345 | OkCodes: []int{202}, |
| 346 | }) |
| 347 | return err |
| 348 | } |
| 349 | |
| 350 | // RebuildOptsBuilder is an interface that allows extensions to override the |
| 351 | // default behaviour of rebuild options |
| 352 | type RebuildOptsBuilder interface { |
| 353 | ToServerRebuildMap() (map[string]interface{}, error) |
| 354 | } |
| 355 | |
| 356 | // RebuildOpts represents the configuration options used in a server rebuild |
| 357 | // operation |
| 358 | type RebuildOpts struct { |
| 359 | // Required. The ID of the image you want your server to be provisioned on |
| 360 | ImageID string |
| 361 | |
| 362 | // Name to set the server to |
| 363 | Name string |
| 364 | |
| 365 | // Required. The server's admin password |
| 366 | AdminPass string |
| 367 | |
| 368 | // AccessIPv4 [optional] provides a new IPv4 address for the instance. |
| 369 | AccessIPv4 string |
| 370 | |
| 371 | // AccessIPv6 [optional] provides a new IPv6 address for the instance. |
| 372 | AccessIPv6 string |
| 373 | |
| 374 | // Metadata [optional] contains key-value pairs (up to 255 bytes each) to attach to the server. |
| 375 | Metadata map[string]string |
| 376 | |
| 377 | // Personality [optional] includes the path and contents of a file to inject into the server at launch. |
| 378 | // The maximum size of the file is 255 bytes (decoded). |
| 379 | Personality []byte |
| 380 | } |
| 381 | |
| 382 | // ToServerRebuildMap formats a RebuildOpts struct into a map for use in JSON |
| 383 | func (opts RebuildOpts) ToServerRebuildMap() (map[string]interface{}, error) { |
| 384 | var err error |
| 385 | server := make(map[string]interface{}) |
| 386 | |
| 387 | if opts.AdminPass == "" { |
| 388 | err = fmt.Errorf("AdminPass is required") |
| 389 | } |
| 390 | |
| 391 | if opts.ImageID == "" { |
| 392 | err = fmt.Errorf("ImageID is required") |
| 393 | } |
| 394 | |
| 395 | if err != nil { |
| 396 | return server, err |
| 397 | } |
| 398 | |
| 399 | server["name"] = opts.Name |
| 400 | server["adminPass"] = opts.AdminPass |
| 401 | server["imageRef"] = opts.ImageID |
| 402 | |
| 403 | if opts.AccessIPv4 != "" { |
| 404 | server["accessIPv4"] = opts.AccessIPv4 |
| 405 | } |
| 406 | |
| 407 | if opts.AccessIPv6 != "" { |
| 408 | server["accessIPv6"] = opts.AccessIPv6 |
| 409 | } |
| 410 | |
| 411 | if opts.Metadata != nil { |
| 412 | server["metadata"] = opts.Metadata |
| 413 | } |
| 414 | |
| 415 | if opts.Personality != nil { |
| 416 | encoded := base64.StdEncoding.EncodeToString(opts.Personality) |
| 417 | server["personality"] = &encoded |
| 418 | } |
| 419 | |
| 420 | return map[string]interface{}{"rebuild": server}, nil |
| 421 | } |
| 422 | |
| 423 | // Rebuild will reprovision the server according to the configuration options |
| 424 | // provided in the RebuildOpts struct. |
| 425 | func Rebuild(client *gophercloud.ServiceClient, id string, opts RebuildOptsBuilder) RebuildResult { |
| 426 | var result RebuildResult |
| 427 | |
| 428 | if id == "" { |
| 429 | result.Err = fmt.Errorf("ID is required") |
| 430 | return result |
| 431 | } |
| 432 | |
| 433 | reqBody, err := opts.ToServerRebuildMap() |
| 434 | if err != nil { |
| 435 | result.Err = err |
| 436 | return result |
| 437 | } |
| 438 | |
| 439 | _, result.Err = perigee.Request("POST", actionURL(client, id), perigee.Options{ |
| 440 | ReqBody: &reqBody, |
| 441 | Results: &result.Resp, |
| 442 | MoreHeaders: client.Provider.AuthenticatedHeaders(), |
| 443 | OkCodes: []int{202}, |
| 444 | }) |
| 445 | |
| 446 | return result |
| 447 | } |
| 448 | |
| 449 | // Resize instructs the provider to change the flavor of the server. |
| 450 | // Note that this implies rebuilding it. |
| 451 | // Unfortunately, one cannot pass rebuild parameters to the resize function. |
| 452 | // When the resize completes, the server will be in RESIZE_VERIFY state. |
| 453 | // While in this state, you can explore the use of the new server's configuration. |
| 454 | // If you like it, call ConfirmResize() to commit the resize permanently. |
| 455 | // Otherwise, call RevertResize() to restore the old configuration. |
| 456 | func Resize(client *gophercloud.ServiceClient, id, flavorRef string) error { |
| 457 | _, err := perigee.Request("POST", actionURL(client, id), perigee.Options{ |
| 458 | ReqBody: struct { |
| 459 | R map[string]interface{} `json:"resize"` |
| 460 | }{ |
| 461 | map[string]interface{}{"flavorRef": flavorRef}, |
| 462 | }, |
| 463 | MoreHeaders: client.Provider.AuthenticatedHeaders(), |
| 464 | OkCodes: []int{202}, |
| 465 | }) |
| 466 | return err |
| 467 | } |
| 468 | |
| 469 | // ConfirmResize confirms a previous resize operation on a server. |
| 470 | // See Resize() for more details. |
| 471 | func ConfirmResize(client *gophercloud.ServiceClient, id string) error { |
| 472 | _, err := perigee.Request("POST", actionURL(client, id), perigee.Options{ |
| 473 | ReqBody: map[string]interface{}{"confirmResize": nil}, |
| 474 | MoreHeaders: client.Provider.AuthenticatedHeaders(), |
| 475 | OkCodes: []int{204}, |
| 476 | }) |
| 477 | return err |
| 478 | } |
| 479 | |
| 480 | // RevertResize cancels a previous resize operation on a server. |
| 481 | // See Resize() for more details. |
| 482 | func RevertResize(client *gophercloud.ServiceClient, id string) error { |
| 483 | _, err := perigee.Request("POST", actionURL(client, id), perigee.Options{ |
| 484 | ReqBody: map[string]interface{}{"revertResize": nil}, |
| 485 | MoreHeaders: client.Provider.AuthenticatedHeaders(), |
| 486 | OkCodes: []int{202}, |
| 487 | }) |
| 488 | return err |
| 489 | } |