gophercloud

package module
v0.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 6, 2014 License: Apache-2.0 Imports: 4 Imported by: 16,429

README

== Gophercloud -- V0.0.0 image:https://secure.travis-ci.org/rackspace/gophercloud.png?branch=master["build status",link="https://travis-ci.org/rackspace/gophercloud"]
The Go ecosystem seems to lack a comprehensive cloud services API (at the time this README was first written). As both Go and cloud services are trending in many businesses, and with Go used increasingly in infrastructure, it seems like an odd omission. To fill this gap, Gophercloud provides a Go binding to OpenStack cloud APIs.  Many providers offer many APIs that are compatible with OpenStack; thus, building your infrastructure automation projects around Openstack is a natural way to avoid vendor lock-in.

WARNING: This library is still in the very early stages of development. Unless you want to contribute, it probably isn't what you want.

=== Getting Started
==== Install the Go Programming Language
Gophercloud provides an Openstack-compatible SDK binding to the Go community.
As such, to either use it or contribute code, you'll need to have Go installed.  Please http://golang.org/doc/install[refer to the Go installation instructions] for detailed steps to install the latest stable release of Go.

==== Familiarize Yourself with Go
To use or contribute to Gophercloud, you'll need some passing familiarity with Go, and how it uses certain concepts.  If you've never worked with Go before, I _strongly_ encourage the interested reader to follow through the excellent online book titled http://golang.org/doc/effective_go.html[Effective Go].

==== Installing Gophercloud in a Workspace

IMPORTANT: *Please* do not just clone this repository expecting it to work like any other Python, Ruby, Java, or C/C++ repo.  Go packages don't work that way!  (You _did_ read Effective Go, right?)

===== Installing Into an Existing Project
Assuming you have a project underway already and its `$GOPATH` environment variable holds the correct path, you can include the Gophercloud package in the usual manner using `go get`:

    go get github.com/rackspace/gophercloud

The remainder of this document, and supporting materials, assumes a correct `$GOPATH` configuration, but further assumes that an environment variable `$GOPHERCLOUD` points to the Gophercloud installation directory as well.  E.g.,

    export GOPHERCLOUD=$GOPATH/src/github.com/rackspace/gophercloud

===== Creating a New Gophercloud Project
If you're just starting out with Go, a convenience script exists which lets you create a new Go workspace preconfigured with Gophercloud for you.

-----------------------------------------------------------------------------------------------------
You can execute the following command to create a brand new Go workspace that is minimally configured for use with Gophercloud.  This should work for any reasonable POSIX-compatible environment.

	source <(curl "https://raw.github.com/rackspace/Gophercloud/master/scripts/create-environment.sh")
-----------------------------------------------------------------------------------------------------

This script will not only install the software, but also create a shell script `env.sh` which, when executed, restores both `$GOPATH` and `$GOPHERCLOUD` to their correct values.  The project will be installed in `$HOME/go/gophercloud`.

==== Make Sure Gophercloud Works For You
You should follow these steps to make sure your local installation works as expected.

-----
export SDK_USERNAME=jack_frost                             <1>
export SDK_PROVIDER=santa-telecom                          <2>
SDK_PASSWORD=c0ldnbr33zy $GOPHERCLOUD/scripts/test-all.sh  <3>
-----
<1> Use your cloud provider's API user name.
<2> Use your provider's unique Gophercloud identifier.  This is how Gophercloud will know which API endpoints to use.
<3> Do not export your password unless you don't care that it may reside in memory after the tests have all run.  You might want to remove it from your shell's history file afterwards too.

If everything goes well, you should only see output indicating the Go commands for each of the acceptance tests being run.  Errors can be caused by several factors:

1. Your provider diverges from established Openstack standards.
2. Gophercloud incorrectly implements the relevant Openstack standards.
3. Mistake in setting up the `SDK_*` environment variables above.

If a problem occurs, https://github.com/rackspace/gophercloud/issues[we'd love to hear about it in the issue tracker!]

==== Using Gophercloud
Simply list Gophercloud in the import section of relevant source listings, and you will be able to issue cloud requests through Gophercloud.  For examples, either refer to the detailed SDK documentation, or https://github.com/rackspace/gophercloud/tree/master/acceptance[take a look at the acceptance-level tests in the `acceptance` subdirectory.]

==== Contributing Features or Bug-Fixes
After using Gophercloud for a while, you might find that it lacks some useful feature, or that existing behavior seems buggy.  We welcome contributions from our users for both missing functionality as well as for bug fixes.

After installing Gophercloud and after running its `env.sh` script (only needed once per shell session), you will find the source files in the `$GOPHERCLOUD` directory.  Feel free to open your favorite editor inside that directory and poke around.

Features and bug-fixes *must* appear on their own *feature branches*, even if you fork the Gophercloud repository.  The name of the branch should be fairly descriptive, but try to avoid verbosity for verbosity's sake.  Examples of good feature branch names include:

.........................
script-environment-setup 
server-creation
issue-43-memory-leak-fix
.........................

Some examples of not-so-good branch names include:

.........................
cloud-server-api-server-creation-endpoint-support   <1>
tk                                                  <2>
anything/with/slashes                               <3>
.........................
<1>  This branch name is lengthy without delivering much value.
<2>  This branch name is too short to be useful to anyone other than the submitter.
<3>  This branch name exacerbates some Git usability issues, where some commands separate origins from branch names using slashes and others do not.  Thus, using these kinds of branch names increases chances for easily preventable errors.

For example, if you're looking to fix a memory leak that is documented in, just to pick a number, issue 42, you might follow a sequence of commands such as the following:

............................................
cd $GOPHERCLOUD
git checkout working
git checkout -b issue-42-fix-memory-leak
# edit edit edit ...
# commits happen here ...
git push -u origin issue-42-fix-memory-leak
............................................

At this point, you may now switch to the GitHub user interface, and open a pull-request for the feature branch.  This pull request should be descriptive.  Basically, you want to give a small code walkthrough in the pull request summary.  You should be able to answer, at a minimum, four basic questions, as appropriate for the nature of the patch:

1.  What is the problem?
2.  Why is it a problem?
3.  What is your solution?
4.  How does your solution actually work?

Here's a made-up example:

......................................................................
Fix memory leak detailed in issue #42.

The Rackspace provider interface tended to leak memory every fifth
Saturday of February.  Over the course of several decades, we find
we run out of memory.  Killing and restarting the process periodically
restores service, but is a burden on the ops team.  This PR fixes this
bug permanently.

The barProvider structure found in
provider/barisp.go defines a FooSet as a slice, as seen on line 314.
Per services/auth/keystone2.go line 628, Keystone authentication
only ever uses the first three	elements of this FooSet.  Line 42 shows
where FooSet is initialized to an empty slice, but on line 512, we see
a function that appends to this slice unconditionally.

I'm not sure where the logic exists to determine where this function is
called; so, I've adjusted the provider/barisp.go file to truncate this
FooSet to only three items, maximum on behalf of the caller.  This seems
to solve the problem in my test cases.  See included tests.
......................................................................

Obviously, please use common sense!  In situations where these questions do not apply, please don't make up filler information.

NOTE: All bug-fix PRs **MUST** reference at least one open issue.  New feature PRs **SHOULD** reference at least one open issue.  This convention helps track *why* certain code is written the way it is, and maintains historical context.  Lengthy design discussions should be moved to the https://groups.google.com/forum/#!forum/gophercloud-dev[gophercloud-dev mailing list] if they occur; links to appropriate discussions should be made in the issue, again to maintain context.

TIP: You may elide answers to the questions above if the answers already appear in the referenced PR(s), issues, or mailing list discussions.  We care that the answers exist and may be easily found, not so much about *where* the answers may be found.

==== Master Branch vs. Working Branch

Many projects will happily let you create a feature branch off the master branch.  However, Go environments place special significance on master branches of packages.  Because the `go get` command *is not* intended to perform complete package management tasks, but merely serve as a convenience for establishing your Go work environment, it will always fetch from the master branch of any repository you specify.  *Therefore, the master branch MUST always represent a customer-installable package.*  Not only that, but interface changes **must** be backward compatible at all times.

To facilitate development efforts, then, we maintain a *working* branch.  New features and bug fixes merge into the `working` branch, where it remains staged for some future release date.  Ideally, every push to github and every merge to `working` should kick off a batch of tests to validate the product still works.  Assuming that `working` tests all pass, *and* your features or bug-fixes are both code- and feature-complete, then and only then should `working` be merged into `master`.

Documentation

Overview

Gophercloud provides a multi-vendor interface to OpenStack-compatible clouds which attempts to follow established Go community coding standards and social norms.

Unless you intend on contributing code to the SDK, you will almost certainly never have to use any Context structures or any of its methods. Contextual methods exist for easier unit testing only. Stick with the global functions unless you know exactly what you're doing, and why.

Index

Constants

View Source
const (
	PublicURL = iota
	InternalURL
)

The choices available for UrlChoice. See the ApiCriteria structure for details.

Variables

View Source
var ErrConfiguration = fmt.Errorf("Missing or incomplete configuration")

ErrConfiguration errors happen when attempting to add a new provider, and the provider added lacks a correct or consistent configuration. For example, all providers must expose at least an Identity V2 API for authentication; if this endpoint isn't specified, you may receive this error when attempting to register it against a context.

View Source
var ErrCredentials = fmt.Errorf("Missing or incomplete credentials")

ErrCredentials errors happen when attempting to authenticate using a set of credentials not recognized by the Authenticate() method. For example, not providing a username or password when attempting to authenticate against an Identity V2 API.

View Source
var ErrEndpoint = fmt.Errorf("Missing endpoint, or insufficient privileges to access endpoint")

ErrEndpoint errors happen when no endpoint with the desired characteristics exists in the service catalog. This can also happen if your tenant lacks adequate permissions to access a given endpoint.

View Source
var ErrError = fmt.Errorf("Attempt to solicit actual HTTP response code from error entity which doesn't know")

ErrError errors happen when you attempt to discover the response code responsible for a previous request bombing with an error, but pass in an error interface which doesn't belong to the web client.

View Source
var ErrNotImplemented = fmt.Errorf("Not implemented")

ErrNotImplemented should be used only while developing new SDK features. No established function or method will ever produce this error.

View Source
var ErrProvider = fmt.Errorf("Missing or incorrect provider")

ErrProvider errors occur when attempting to reference an unsupported provider. More often than not, this error happens due to a typo in the name.

View Source
var WarnUnauthoritative = fmt.Errorf("Unauthoritative data")

WarnUnauthoritative warnings happen when a service believes its response to be correct, but is not in a position of knowing for sure at the moment. For example, the service could be responding with cached data that has exceeded its time-to-live setting, but which has not yet received an official update from an authoritative source.

Functions

func ActualResponseCode

func ActualResponseCode(e error) (int, error)

ActualResponseCode inspects a returned error, and discovers the actual response actual response code that caused the error to be raised.

Types

type Access

type Access struct {
	Token          Token
	ServiceCatalog []CatalogEntry
	User           User
	// contains filtered or unexported fields
}

Access encapsulates the API token and its relevant fields, as well as the services catalog that Identity API returns once authenticated.

func Authenticate

func Authenticate(provider string, options AuthOptions) (*Access, error)

Authenticate() grants access to the OpenStack-compatible provider API.

Providers are identified through a unique key string. Specifying an unsupported provider will result in an ErrProvider error. However, you may also specify a custom Identity API URL. Any provider name that contains the characters "://", in that order, will be treated as a custom Identity API URL. Custom URLs, important for private cloud deployments, overrides all provider configurations.

The supplied AuthOptions instance allows the client to specify only those credentials relevant for the authentication request. At present, support exists for OpenStack Identity V2 API only; support for V3 will become available as soon as documentation for it becomes readily available.

For Identity V2 API requirements, you must provide at least the Username and Password options. The TenantId field is optional, and defaults to "".

func (*Access) AuthToken

func (a *Access) AuthToken() string

See AccessProvider interface definition for details.

func (*Access) FirstEndpointUrlByCriteria

func (a *Access) FirstEndpointUrlByCriteria(ac ApiCriteria) string

See AccessProvider interface definition for details.

func (*Access) Reauthenticate

func (a *Access) Reauthenticate() error

Reauthenticate attempts to reauthenticate using the configured access credentials, if allowed. This method takes no action unless your AuthOptions has the AllowReauth flag set to true.

func (*Access) Revoke

func (a *Access) Revoke(tok string) error

See AccessProvider interface definition for details.

func (*Access) V2ServiceCatalog

func (a *Access) V2ServiceCatalog() []CatalogEntry

See ServiceCatalogerForIdentityV2 interface definition for details. Note that the raw slice is returend; be careful not to alter the fields of any members, for other components of Gophercloud may depend upon them. If this becomes a problem in the future, a future revision may return a deep-copy of the service catalog instead.

type AccessProvider

type AccessProvider interface {
	// FirstEndpointUrlByCriteria searches through the service catalog for the first
	// matching entry endpoint fulfilling the provided criteria.  If nothing found,
	// return "".  Otherwise, return either the public or internal URL for the
	// endpoint, depending on both its existence and the setting of the ApiCriteria.UrlChoice
	// field.
	FirstEndpointUrlByCriteria(ApiCriteria) string

	// AuthToken provides a copy of the current authentication token for the user's credentials.
	// Note that AuthToken() will not automatically refresh an expired token.
	AuthToken() string

	// Revoke allows you to terminate any program's access to the OpenStack API by token ID.
	Revoke(string) error

	// Reauthenticate attempts to acquire a new authentication token, if the feature is enabled by
	// AuthOptions.AllowReauth.
	Reauthenticate() error
}

AccessProvider instances encapsulate a Keystone authentication interface.

type AddressSet

type AddressSet struct {
	Public  []VersionedAddress `json:"public"`
	Private []VersionedAddress `json:"private"`
}

An AddressSet provides a set of public and private IP addresses for a resource. Each address has a version to identify if IPv4 or IPv6.

type ApiCriteria

type ApiCriteria struct {
	// Name specifies the desired service catalog entry name.
	Name string

	// Type specifies the desired service catalog entry type.
	Type string

	// Region specifies the desired endpoint region.
	Region string

	// VersionId specifies the desired version of the endpoint.
	// Note that this field is matched exactly, and is (at present)
	// opaque to Gophercloud.  Thus, requesting a version 2
	// endpoint will _not_ match a version 3 endpoint.
	VersionId string

	// The UrlChoice field inidicates whether or not gophercloud
	// should use the public or internal endpoint URL if a
	// candidate endpoint is found.
	UrlChoice int
}

ApiCriteria provides one or more criteria for the SDK to look for appropriate endpoints. Fields left unspecified or otherwise set to their zero-values are assumed to not be relevant, and do not participate in the endpoint search.

type ApiKeyCredentials

type ApiKeyCredentials struct {
	Username string `json:"username"`
	ApiKey   string `json:"apiKey"`
}

type Auth

type Auth struct {
	PasswordCredentials *PasswordCredentials `json:"passwordCredentials,omitempty"`
	ApiKeyCredentials   *ApiKeyCredentials   `json:"RAX-KSKEY:apiKeyCredentials,omitempty"`
	TenantId            string               `json:"tenantId,omitempty"`
	TenantName          string               `json:"tenantName,omitempty"`
}

Auth provides a JSON encoding wrapper for passing credentials to the Identity service. You will not work with this structure directly.

type AuthContainer

type AuthContainer struct {
	Auth Auth `json:"auth"`
}

AuthContainer provides a JSON encoding wrapper for passing credentials to the Identity service. You will not work with this structure directly.

type AuthOptions

type AuthOptions struct {
	// Username and Password are required if using Identity V2 API.
	// Consult with your provider's control panel to discover your
	// account's username and password.
	Username, Password string

	// ApiKey used for providers that support Api Key authentication
	ApiKey string

	// The TenantId field is optional for the Identity V2 API.
	TenantId string

	// The TenantName can be specified instead of the TenantId
	TenantName string

	// AllowReauth should be set to true if you grant permission for Gophercloud to cache
	// your credentials in memory, and to allow Gophercloud to attempt to re-authenticate
	// automatically if/when your token expires.  If you set it to false, it will not cache
	// these settings, but re-authentication will not be possible.  This setting defaults
	// to false.
	AllowReauth bool
}

AuthOptions lets anyone calling Authenticate() supply the required access credentials. At present, only Identity V2 API support exists; therefore, only Username, Password, and optionally, TenantId are provided. If future Identity API versions become available, alternative fields unique to those versions may appear here.

type CatalogEntry

type CatalogEntry struct {
	Name, Type string
	Endpoints  []EntryEndpoint
}

CatalogEntry encapsulates a service catalog record.

type CloudServersProvider

type CloudServersProvider interface {

	// ListServers provides a complete list of servers hosted by the user
	// in a given region.  This function differs from ListServersLinksOnly()
	// in that it returns all available details for each server returned.
	ListServers() ([]Server, error)

	// ListServers provides a complete list of servers hosted by the user
	// in a given region.  This function differs from ListServers() in that
	// it returns only IDs and links to each server returned.
	//
	// This function should be used only under certain circumstances.
	// It's most useful for checking to see if a server with a given ID exists,
	// or that you have permission to work with that server.  It's also useful
	// when the cost of retrieving the server link list plus the overhead of manually
	// invoking ServerById() for each of the servers you're interested in is less than
	// just calling ListServers() to begin with.  This may be a consideration, for
	// example, with mobile applications.
	//
	// In other cases, you probably should just call ListServers() and cache the
	// results to conserve overall bandwidth and reduce your access rate on the API.
	ListServersLinksOnly() ([]Server, error)

	// ServerById will retrieve a detailed server description given the unique ID
	// of a server.  The ID can be returned by either ListServers() or by ListServersLinksOnly().
	ServerById(id string) (*Server, error)

	// CreateServer requests a new server to be created by the cloud server provider.
	// The user must pass in a pointer to an initialized NewServerContainer structure.
	// Please refer to the NewServerContainer documentation for more details.
	//
	// If the NewServer structure's AdminPass is empty (""), a password will be
	// automatically generated by your OpenStack provider, and returned through the
	// AdminPass field of the result.  Take care, however; this will be the only time
	// this happens.  No other means exists in the public API to acquire a password
	// for a pre-existing server.  If you lose it, you'll need to call SetAdminPassword()
	// to set a new one.
	CreateServer(ns NewServer) (*NewServer, error)

	// DeleteServerById requests that the server with the assigned ID be removed
	// from your account.  The delete happens asynchronously.
	DeleteServerById(id string) error

	// SetAdminPassword requests that the server with the specified ID have its
	// administrative password changed.  For Linux, BSD, or other POSIX-like
	// system, this password corresponds to the root user.  For Windows machines,
	// the Administrator password will be affected instead.
	SetAdminPassword(id string, pw string) error

	// ResizeServer can be a short-hand for RebuildServer where only the size of the server
	// changes.  Note that after the resize operation is requested, you will need to confirm
	// the resize has completed for changes to take effect permanently.  Changes will assume
	// to be confirmed even without an explicit confirmation after 24 hours from the initial
	// request.
	ResizeServer(id, newName, newFlavor, newDiskConfig string) error

	// RevertResize will reject a server's resized configuration, thus
	// rolling back to the original server.
	RevertResize(id string) error

	// ConfirmResizeServer will acknowledge a server's resized configuration.
	ConfirmResize(id string) error

	// RebootServer requests that the server with the specified ID be rebooted.
	// Two reboot mechanisms exist.
	//
	// - Hard.  This will physically power-cycle the unit.
	// - Soft.  This will attempt to use the server's software-based mechanisms to restart
	//           the machine.  E.g., "shutdown -r now" on Linux.
	RebootServer(id string, hard bool) error

	// RescueServer requests that the server with the specified ID be placed into
	// a state of maintenance.  The server instance is replaced with a new instance,
	// of the same flavor and image.  This new image will have the boot volume of the
	// original machine mounted as a secondary device, so that repair and administration
	// may occur.  Use UnrescueServer() to restore the server to its previous state.
	// Note also that many providers will impose a time limit for how long a server may
	// exist in rescue mode!  Consult the API documentation for your provider for
	// details.
	RescueServer(id string) (string, error)

	// UnrescueServer requests that a server in rescue state be placed into its nominal
	// operating state.
	UnrescueServer(id string) error

	// UpdateServer alters one or more fields of the identified server's Server record.
	// However, not all fields may be altered.  Presently, only Name, AccessIPv4, and
	// AccessIPv6 fields may be altered.   If unspecified, or set to an empty or zero
	// value, the corresponding field remains unaltered.
	//
	// This function returns the new set of server details if successful.
	UpdateServer(id string, newValues NewServerSettings) (*Server, error)

	// RebuildServer reprovisions a server to the specifications given by the
	// NewServer structure.  The following fields are guaranteed to be recognized:
	//
	//		Name (required)				AccessIPv4
	//		imageRef (required)			AccessIPv6
	//		AdminPass (required)		Metadata
	//		Personality
	//
	// Other providers may reserve the right to act on additional fields.
	RebuildServer(id string, ns NewServer) (*Server, error)

	// CreateImage will create a new image from the specified server id returning the id of the new image.
	CreateImage(id string, ci CreateImage) (string, error)

	// ListAddresses yields the list of available addresses for the server.
	// This information is also returned by ServerById() in the Server.Addresses
	// field.  However, if you have a lot of servers and all you need are addresses,
	// this function might be more efficient.
	ListAddresses(id string) (AddressSet, error)

	// ListAddressesByNetwork yields the list of available addresses for a given server id and networkLabel.
	// Example: ListAddressesByNetwork("234-4353-4jfrj-43j2s", "private")
	ListAddressesByNetwork(id, networkLabel string) (NetworkAddress, error)

	// ListImages yields the list of available operating system images.  This function
	// returns full details for each image, if available.
	ListImages() ([]Image, error)

	// ImageById yields details about a specific image.
	ImageById(id string) (*Image, error)

	// DeleteImageById will delete the specific image.
	DeleteImageById(id string) error

	// ListFlavors yields the list of available system flavors.  This function
	// returns full details for each flavor, if available.
	ListFlavors() ([]Flavor, error)

	// ListKeyPairs yields the list of available keypairs.
	ListKeyPairs() ([]KeyPair, error)

	// CreateKeyPairs will create or generate a new keypair.
	CreateKeyPair(nkp NewKeyPair) (KeyPair, error)

	// DeleteKeyPair wil delete a keypair.
	DeleteKeyPair(name string) error

	// ShowKeyPair will yield the named keypair.
	ShowKeyPair(name string) (KeyPair, error)
}

CloudServersProvider instances encapsulate a Cloud Servers API, should one exist in the service catalog for your provider.

func ServersApi

func ServersApi(acc AccessProvider, criteria ApiCriteria) (CloudServersProvider, error)

Instantiates a Cloud Servers object for the provider given.

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context structures encapsulate Gophercloud-global state in a manner which facilitates easier unit testing. As a user of this SDK, you'll never have to use this structure, except when contributing new code to the SDK.

func TestContext

func TestContext() *Context

TestContext yields a new Context instance, pre-initialized with a barren state suitable for per-unit-test customization. This configuration consists of:

* An empty provider map.

* An HTTP client built by the net/http package (see http://godoc.org/net/http#Client).

func (*Context) Authenticate

func (c *Context) Authenticate(provider string, options AuthOptions) (*Access, error)

Authenticate() grants access to the OpenStack-compatible provider API.

Providers are identified through a unique key string. See the RegisterProvider() method for more details.

The supplied AuthOptions instance allows the client to specify only those credentials relevant for the authentication request. At present, support exists for OpenStack Identity V2 API only; support for V3 will become available as soon as documentation for it becomes readily available.

For Identity V2 API requirements, you must provide at least the Username and Password options. The TenantId field is optional, and defaults to "".

func (*Context) ProviderByName

func (c *Context) ProviderByName(name string) (p Provider, err error)

ProviderByName will locate a provider amongst those previously registered, if it exists. If the named provider has not been registered, an ErrProvider error will result.

You may also specify a custom Identity API URL. Any provider name that contains the characters "://", in that order, will be treated as a custom Identity API URL. Custom URLs, important for private cloud deployments, overrides all provider configurations.

func (*Context) RegisterProvider

func (c *Context) RegisterProvider(name string, p Provider) error

RegisterProvider allows a unit test to register a mythical provider convenient for testing. If the provider structure lacks adequate configuration, or the configuration given has some detectable error, an ErrConfiguration error will result.

func (*Context) ResponseWithReauth

func (c *Context) ResponseWithReauth(ap AccessProvider, f func() (*perigee.Response, error)) (*perigee.Response, error)

This is like WithReauth above but returns a perigee Response object

func (*Context) ServersApi

func (c *Context) ServersApi(acc AccessProvider, criteria ApiCriteria) (CloudServersProvider, error)

Instantiates a Cloud Servers API for the provider given.

func (*Context) UseCustomClient

func (c *Context) UseCustomClient(hc *http.Client) *Context

UseCustomClient configures the context to use a customized HTTP client instance. By default, TestContext() will return a Context which uses the net/http package's default client instance.

func (*Context) WithProvider

func (c *Context) WithProvider(name string, p Provider) *Context

WithProvider offers convenience for unit tests.

func (*Context) WithReauth

func (c *Context) WithReauth(ap AccessProvider, f func() error) error

WithReauth wraps a Perigee request fragment with logic to perform re-authentication if it's deemed necessary.

Do not confuse this function with WithReauth()! Although they work together to support reauthentication, WithReauth() actually contains the decision-making logic to determine when to perform a reauth, while WithReauthHandler() is used to configure what a reauth actually entails.

func (*Context) WithReauthHandler

func (c *Context) WithReauthHandler(f ReauthHandlerFunc) *Context

WithReauthHandler configures the context to handle reauthentication attempts using the supplied funtion. By default, reauthentication happens by invoking Authenticate(), which is unlikely to be useful in a unit test.

Do not confuse this function with WithReauth()! Although they work together to support reauthentication, WithReauth() actually contains the decision-making logic to determine when to perform a reauth, while WithReauthHandler() is used to configure what a reauth actually entails.

type CreateImage

type CreateImage struct {
	Name     string            `json:"name"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

type EntryEndpoint

type EntryEndpoint struct {
	Region, TenantId                    string
	PublicURL, InternalURL              string
	VersionId, VersionInfo, VersionList string
}

EntryEndpoint encapsulates how to get to the API of some service.

func FindFirstEndpointByCriteria

func FindFirstEndpointByCriteria(entries []CatalogEntry, ac ApiCriteria) EntryEndpoint

Given a set of criteria to match on, locate the first candidate endpoint in the provided service catalog.

If nothing found, the result will be a zero-valued EntryEndpoint (all URLs set to "").

type FileConfig

type FileConfig struct {
	Path     string `json:"path"`
	Contents string `json:"contents"`
}

FileConfig structures represent a blob of data which must appear at a a specific location in a server's filesystem. The file contents are base-64 encoded.

type Flavor

type Flavor struct {
	OsFlvDisabled bool    `json:"OS-FLV-DISABLED:disabled"`
	Disk          int     `json:"disk"`
	Id            string  `json:"id"`
	Links         []Link  `json:"links"`
	Name          string  `json:"name"`
	Ram           int     `json:"ram"`
	RxTxFactor    float64 `json:"rxtx_factor"`
	Swap          int     `json:"swap"`
	VCpus         int     `json:"vcpus"`
}

Flavor records represent (virtual) hardware configurations for server resources in a region.

The Id field contains the flavor's unique identifier. For example, this identifier will be useful when specifying which hardware configuration to use for a new server instance.

The Disk and Ram fields provide a measure of storage space offered by the flavor, in GB and MB, respectively.

The Name field provides a human-readable moniker for the flavor.

Swap indicates how much space is reserved for swap. If not provided, this field will be set to 0.

VCpus indicates how many (virtual) CPUs are available for this flavor.

type FlavorLink struct {
	Id    string `json:"id"`
	Links []Link `json:"links"`
}

FlavorLink provides a reference to a flavor by either ID or by direct URL. Some services use just the ID, others use just the URL. This structure provides a common means of expressing both in a single field.

type Image

type Image struct {
	Created         string `json:"created"`
	Id              string `json:"id"`
	Links           []Link `json:"links"`
	MinDisk         int    `json:"minDisk"`
	MinRam          int    `json:"minRam"`
	Name            string `json:"name"`
	Progress        int    `json:"progress"`
	Status          string `json:"status"`
	Updated         string `json:"updated"`
	OsDcfDiskConfig string `json:"OS-DCF:diskConfig"`
}

Image is used for JSON (un)marshalling. It provides a description of an OS image.

The Id field contains the image's unique identifier. For example, this identifier will be useful for specifying which operating system to install on a new server instance.

The MinDisk and MinRam fields specify the minimum resources a server must provide to be able to install the image.

The Name field provides a human-readable moniker for the OS image.

The Progress and Status fields indicate image-creation status. Any usable image will have 100% progress.

The Updated field indicates the last time this image was changed.

OsDcfDiskConfig indicates the server's boot volume configuration. Valid values are:

AUTO
----
The server is built with a single partition the size of the target flavor disk.
The file system is automatically adjusted to fit the entire partition.
This keeps things simple and automated.
AUTO is valid only for images and servers with a single partition that use the EXT3 file system.
This is the default setting for applicable Rackspace base images.

MANUAL
------
The server is built using whatever partition scheme and file system is in the source image.
If the target flavor disk is larger,
the remaining disk space is left unpartitioned.
This enables images to have non-EXT3 file systems, multiple partitions, and so on,
and enables you to manage the disk configuration.
type ImageLink struct {
	Id    string `json:"id"`
	Links []Link `json:"links"`
}

ImageLink provides a reference to a image by either ID or by direct URL. Some services use just the ID, others use just the URL. This structure provides a common means of expressing both in a single field.

type KeyPair

type KeyPair struct {
	FingerPrint string `json:"fingerprint"`
	Name        string `json:"name"`
	PrivateKey  string `json:"private_key,omitempty"`
	PublicKey   string `json:"public_key"`
	UserID      string `json:"user_id,omitempty"`
}
type Link struct {
	Href string `json:"href"`
	Rel  string `json:"rel"`
	Type string `json:"type"`
}

Link is used for JSON (un)marshalling. It provides RESTful links to a resource.

type NetworkAddress

type NetworkAddress map[string][]VersionedAddress

type NetworkConfig

type NetworkConfig struct {
	Uuid string `json:"uuid"`
}

NetworkConfig structures represent an affinity between a server and a specific, uniquely identified network. Networks are identified through universally unique IDs.

type NewKeyPair

type NewKeyPair struct {
	Name      string `json:"name"`
	PublicKey string `json:"public_key,omitempty"`
}

type NewServer

type NewServer struct {
	Name            string            `json:"name,omitempty"`
	ImageRef        string            `json:"imageRef,omitempty"`
	FlavorRef       string            `json:"flavorRef,omitempty"`
	Metadata        map[string]string `json:"metadata,omitempty"`
	Personality     []FileConfig      `json:"personality,omitempty"`
	Networks        []NetworkConfig   `json:"networks,omitempty"`
	AdminPass       string            `json:"adminPass,omitempty"`
	KeyPairName     string            `json:"key_name,omitempty"`
	Id              string            `json:"id,omitempty"`
	Links           []Link            `json:"links,omitempty"`
	OsDcfDiskConfig string            `json:"OS-DCF:diskConfig,omitempty"`
}

NewServer structures are used for both requests and responses. The fields discussed below are relevent for server-creation purposes.

The Name field contains the desired name of the server. Note that (at present) Rackspace permits more than one server with the same name; however, software should not depend on this. Not only will Rackspace support thank you, so will your own devops engineers. A name is required.

The ImageRef field contains the ID of the desired software image to place on the server. This ID must be found in the image slice returned by the Images() function. This field is required.

The FlavorRef field contains the ID of the server configuration desired for deployment. This ID must be found in the flavor slice returned by the Flavors() function. This field is required.

For OsDcfDiskConfig, refer to the Image or Server structure documentation. This field defaults to "AUTO" if not explicitly provided.

Metadata contains a small key/value association of arbitrary data. Neither Rackspace nor OpenStack places significance on this field in any way. This field defaults to an empty map if not provided.

Personality specifies the contents of certain files in the server's filesystem. The files and their contents are mapped through a slice of FileConfig structures. If not provided, all filesystem entities retain their image-specific configuration.

Networks specifies an affinity for the server's various networks and interfaces. Networks are identified through UUIDs; see NetworkConfig structure documentation for more details. If not provided, network affinity is determined automatically.

The AdminPass field may be used to provide a root- or administrator-password during the server provisioning process. If not provided, a random password will be automatically generated and returned in this field.

The following fields are intended to be used to communicate certain results about the server being provisioned. When attempting to create a new server, these fields MUST not be provided. They'll be filled in by the response received from the Rackspace APIs.

The Id field contains the server's unique identifier. The identifier's scope is best assumed to be bound by the user's account, unless other arrangements have been made with Rackspace.

Any Links provided are used to refer to the server specifically by URL. These links are useful for making additional REST calls not explicitly supported by Gorax.

type NewServerSettings

type NewServerSettings struct {
	Name       string `json:"name,omitempty"`
	AccessIPv4 string `json:"accessIPv4,omitempty"`
	AccessIPv6 string `json:"accessIPv6,omitempty"`
}

NewServerSettings structures record those fields of the Server structure to change when updating a server (see UpdateServer method).

type PasswordCredentials

type PasswordCredentials struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

PasswordCredentials provides a JSON encoding wrapper for passing credentials to the Identity service. You will not work with this structure directly.

type Provider

type Provider struct {
	AuthEndpoint string
}

Provider structures exist for each tangible provider of OpenStack service. For example, Rackspace, Hewlett-Packard, and NASA might have their own instance of this structure.

At a minimum, a provider must expose an authentication endpoint.

type RaxBandwidth

type RaxBandwidth struct {
	AuditPeriodEnd    string `json:"audit_period_end"`
	AuditPeriodStart  string `json:"audit_period_start"`
	BandwidthInbound  int64  `json:"bandwidth_inbound"`
	BandwidthOutbound int64  `json:"bandwidth_outbound"`
	Interface         string `json:"interface"`
}

RaxBandwidth provides measurement of server bandwidth consumed over a given audit interval.

type ReauthHandlerFunc

type ReauthHandlerFunc func(AccessProvider) error

ReauthHandlerFunc functions are responsible for somehow performing the task of reauthentication.

type ResizeRequest

type ResizeRequest struct {
	Name       string `json:"name,omitempty"`
	FlavorRef  string `json:"flavorRef"`
	DiskConfig string `json:"OS-DCF:diskConfig,omitempty"`
}

ResizeRequest structures are used internally to encode to JSON the parameters required to resize a server instance. Client applications will not use this structure (no API accepts an instance of this structure). See the Region method ResizeServer() for more details on how to resize a server.

type Role

type Role struct {
	Description, Id, Name string
}

Role encapsulates a permission that a user can rely on.

type Server

type Server struct {
	AccessIPv4         string            `json:"accessIPv4"`
	AccessIPv6         string            `json:"accessIPv6"`
	Addresses          AddressSet        `json:"addresses"`
	Created            string            `json:"created"`
	Flavor             FlavorLink        `json:"flavor"`
	HostId             string            `json:"hostId"`
	Id                 string            `json:"id"`
	Image              ImageLink         `json:"image"`
	Links              []Link            `json:"links"`
	Metadata           map[string]string `json:"metadata"`
	Name               string            `json:"name"`
	Progress           int               `json:"progress"`
	Status             string            `json:"status"`
	TenantId           string            `json:"tenant_id"`
	Updated            string            `json:"updated"`
	UserId             string            `json:"user_id"`
	OsDcfDiskConfig    string            `json:"OS-DCF:diskConfig"`
	RaxBandwidth       []RaxBandwidth    `json:"rax-bandwidth:bandwidth"`
	OsExtStsPowerState int               `json:"OS-EXT-STS:power_state"`
	OsExtStsTaskState  string            `json:"OS-EXT-STS:task_state"`
	OsExtStsVmState    string            `json:"OS-EXT-STS:vm_state"`
}

Server records represent (virtual) hardware instances (not configurations) accessible by the user.

The AccessIPv4 / AccessIPv6 fields provides IP addresses for the server in the IPv4 or IPv6 format, respectively.

Addresses provides addresses for any attached isolated networks. The version field indicates whether the IP address is version 4 or 6.

Created tells when the server entity was created.

The Flavor field includes the flavor ID and flavor links.

The compute provisioning algorithm has an anti-affinity property that attempts to spread customer VMs across hosts. Under certain situations, VMs from the same customer might be placed on the same host. The HostId field represents the host your server runs on and can be used to determine this scenario if it is relevant to your application. Note that HostId is unique only per account; it is not globally unique.

Id provides the server's unique identifier. This field must be treated opaquely.

Image indicates which image is installed on the server.

Links provides one or more means of accessing the server.

Metadata provides a small key-value store for application-specific information.

Name provides a human-readable name for the server.

Progress indicates how far along it is towards being provisioned. 100 represents complete, while 0 represents just beginning.

Status provides an indication of what the server's doing at the moment. A server will be in ACTIVE state if it's ready for use.

OsDcfDiskConfig indicates the server's boot volume configuration. Valid values are:

AUTO
----
The server is built with a single partition the size of the target flavor disk.
The file system is automatically adjusted to fit the entire partition.
This keeps things simple and automated.
AUTO is valid only for images and servers with a single partition that use the EXT3 file system.
This is the default setting for applicable Rackspace base images.

MANUAL
------
The server is built using whatever partition scheme and file system is in the source image.
If the target flavor disk is larger,
the remaining disk space is left unpartitioned.
This enables images to have non-EXT3 file systems, multiple partitions, and so on,
and enables you to manage the disk configuration.

RaxBandwidth provides measures of the server's inbound and outbound bandwidth per interface.

OsExtStsPowerState provides an indication of the server's power. This field appears to be a set of flag bits:

  ... 4  3   2   1   0
+--//--+---+---+---+---+
| .... | 0 | S | 0 | I |
+--//--+---+---+---+---+
             |       |
             |       +---  0=Instance is down.
             |             1=Instance is up.
             |
             +-----------  0=Server is switched ON.
                           1=Server is switched OFF.
                           (note reverse logic.)

Unused bits should be ignored when read, and written as 0 for future compatibility.

OsExtStsTaskState and OsExtStsVmState work together to provide visibility in the provisioning process for the instance. Consult Rackspace documentation at http://docs.rackspace.com/servers/api/v2/cs-devguide/content/ch_extensions.html#ext_status for more details. It's too lengthy to include here.

type ServiceCatalogerForIdentityV2

type ServiceCatalogerForIdentityV2 interface {
	V2ServiceCatalog() []CatalogEntry
}

ServiceCatalogerIdentityV2 interface provides direct access to the service catalog as offered by the Identity V2 API. We regret we need to fracture the namespace of what should otherwise be a simple concept; however, the OpenStack community saw fit to render V3's service catalog completely incompatible with V2.

type Tenant

type Tenant struct {
	Id, Name string
}

Tenant encapsulates tenant authentication information. If, after authentication, no tenant information is supplied, both Id and Name will be "".

type Token

type Token struct {
	Id, Expires string
	Tenant      Tenant
}

Token encapsulates an authentication token and when it expires. It also includes tenant information if available.

type User

type User struct {
	Id, Name          string
	XRaxDefaultRegion string `json:"RAX-AUTH:defaultRegion"`
	Roles             []Role
}

User encapsulates the user credentials, and provides visibility in what the user can do through its role assignments.

type VersionedAddress

type VersionedAddress struct {
	Addr    string `json:"addr"`
	Version int    `json:"version"`
}

A VersionedAddress denotes either an IPv4 or IPv6 (depending on version indicated) address.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL