Back to

Package gophercloud

Latest Go to latest

The latest major version is .

Published: Oct 28, 2014 | License: Apache-2.0 | Module:


Package gophercloud provides a multi-vendor interface to OpenStack-compatible clouds. The library has a three-level hierarchy: providers, services, and resources.

Provider structs represent the service providers that offer and manage a collection of services. Examples of providers include: OpenStack, Rackspace, HP. These are defined like so:

opts := gophercloud.AuthOptions{
  IdentityEndpoint: "",
  Username: "{username}",
  Password: "{password}",
  TenantID: "{tenant_id}",

provider, err := openstack.AuthenticatedClient(opts)

Service structs are specific to a provider and handle all of the logic and operations for a particular OpenStack service. Examples of services include: Compute, Object Storage, Block Storage. In order to define one, you need to pass in the parent provider, like so:

opts := gophercloud.EndpointOpts{Region: "RegionOne"}

client := openstack.NewComputeV2(provider, opts)

Resource structs are the domain models that services make use of in order to work with and represent the state of API resources:

server, err := servers.Get(client, "{serverId}").Extract()

Another convention is to return Result structs for API operations, which allow you to access the HTTP headers, response body, and associated errors with the network transaction. To get a resource struct, you then call the Extract method which is chained to the response.



const RFC3339Milli = "2006-01-02T15:04:05.999999Z"

RFC3339Milli describes a time format used by API responses.


var (
	// ErrServiceNotFound is returned when no service matches the EndpointOpts.
	ErrServiceNotFound = errors.New("No suitable service could be found in the service catalog.")

	// ErrEndpointNotFound is returned when no available endpoints match the provided EndpointOpts.
	ErrEndpointNotFound = errors.New("No suitable endpoint could be found in the service catalog.")

func BuildHeaders

func BuildHeaders(opts interface{}) (map[string]string, error)

BuildHeaders accepts a generic structure and parses it into a string map. It converts field names into header names based on "h" tags, and field values into header values by a simple one-to-one mapping.

func BuildQueryString

func BuildQueryString(opts interface{}) (*url.URL, error)

BuildQueryString accepts a generic structure and parses it URL struct. It converts field names into query names based on "q" tags. So for example, this type:

struct {
   Bar string `q:"x_bar"`
   Baz int    `q:"lorem_ipsum"`
   Bar: "XXX",
   Baz: "YYY",

will be converted into ?x_bar=XXX&lorem_ipsum=YYYY

func ExtractNextURL

func ExtractNextURL(links []Link) (string, error)

ExtractNextURL attempts to extract the next URL from a JSON structure. It follows the common convention of nesting back and next URLs in a "links" JSON array.

func MaybeInt

func MaybeInt(original int) *int

MaybeInt takes an int that might be a zero-value, and either returns a pointer to its address or a nil value (i.e. empty pointer).

func MaybeString

func MaybeString(original string) *string

MaybeString takes a string that might be a zero-value, and either returns a pointer to its address or a nil value (i.e. empty pointer). This is useful for converting zero values in options structs when the end-user hasn't defined values. Those zero values need to be nil in order for the JSON serialization to ignore them.

func NormalizeURL

func NormalizeURL(url string) string

NormalizeURL ensures that each endpoint URL has a closing `/`, as expected by ServiceClient.

func WaitFor

func WaitFor(timeout int, predicate func() (bool, error)) error

WaitFor polls a predicate function, once per second, up to a timeout limit. It usually does this to wait for the resource to transition to a certain state.

type AuthOptions

type AuthOptions struct {
	// IdentityEndpoint specifies the HTTP endpoint that is required to work with
	// the Identity API of the appropriate version. Required by the identity
	// services, but often populated by a provider Client.
	IdentityEndpoint string

	// Username is required if using Identity V2 API. Consult with your provider's
	// control panel to discover your account's username. In Identity V3, either
	// UserID or a combination of Username and DomainID or DomainName.
	Username, UserID string

	// Exactly one of Password or ApiKey is required for the Identity V2 and V3
	// APIs. Consult with your provider's control panel to discover your account's
	// preferred method of authentication.
	Password, APIKey string

	// At most one of DomainID and DomainName must be provided if using Username
	// with Identity V3. Otherwise, either are optional.
	DomainID, DomainName string

	// The TenantID and TenantName fields are optional for the Identity V2 API.
	// Some providers allow you to specify a TenantName instead of the TenantId.
	// Some require both.  Your provider's authentication policies will determine
	// how these fields influence authentication.
	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 allows anyone calling Authenticate to supply the required access credentials. Its fields are the union of those recognized by each identity implementation and provider.

type AuthResults

type AuthResults interface {
	// TokenID returns the token's ID value from the authentication response.
	TokenID() (string, error)

	// ExpiresAt retrieves the token's expiration time.
	ExpiresAt() (time.Time, error)

AuthResults encapsulates the raw results from an authentication request. As OpenStack allows extensions to influence the structure returned in ways that Gophercloud cannot predict at compile-time, you should use type-safe accessors to work with the data represented by this type, such as ServiceCatalog and TokenID.

type Availability

type Availability string

Availability indicates whether a specific service endpoint is accessible. Identity v2 lists these as different kinds of URLs ("adminURL", "internalURL", and "publicURL"), while v3 lists them as "Interfaces".

const (
	// AvailabilityAdmin makes an endpoint only available to administrators.
	AvailabilityAdmin Availability = "admin"

	// AvailabilityPublic makes an endpoint available to everyone.
	AvailabilityPublic Availability = "public"

	// AvailabilityInternal makes an endpoint only available within the cluster.
	AvailabilityInternal Availability = "internal"

type EndpointLocator

type EndpointLocator func(EndpointOpts) (string, error)

EndpointLocator is a function that describes how to locate a single endpoint from a service catalog for a specific ProviderClient. It should be set during ProviderClient authentication and used to discover related ServiceClients.

type EndpointOpts

type EndpointOpts struct {
	// Type is the service type for the client (e.g., "compute", "object-store").
	// Required.
	Type string

	// Name is the service name for the client (e.g., "nova") as it appears in
	// the service catalog. Services can have the same Type but a different Name,
	// which is why both Type and Name are sometimes needed. Optional.
	Name string

	// Region is the geographic region in which the service resides. Required only
	// for services that span multiple regions.
	Region string

	// Availability is the visibility of the endpoint to be returned. Valid types
	// are: AvailabilityPublic, AvailabilityInternal, or AvailabilityAdmin.
	// Availability is not required, and defaults to AvailabilityPublic.
	// Not all providers or services offer all Availability options.
	Availability Availability

EndpointOpts contains options for finding an endpoint for an Openstack client.

func (*EndpointOpts) ApplyDefaults

func (eo *EndpointOpts) ApplyDefaults(t string)

ApplyDefaults sets EndpointOpts fields if not already set. Currently, EndpointOpts.Availability defaults to the public endpoint.

type ErrResult

type ErrResult struct {

ErrResult represents results that only contain a potential error and nothing else. Usually if the operation executed successfully, the Err field will be nil; otherwise it will be stocked with a relevant error.

func (ErrResult) ExtractErr

func (r ErrResult) ExtractErr() error

ExtractErr is a function that extracts error information from a result.

type HeaderResult

type HeaderResult struct {

HeaderResult represents a result that only contains an `error` (possibly nil) and an http.Header. This is used, for example, by the `objectstorage` packages in `openstack`, because most of the operations don't return response bodies.

func (HeaderResult) ExtractHeader

func (hr HeaderResult) ExtractHeader() (http.Header, error)

ExtractHeader will return the http.Header and error from the HeaderResult. Usage: header, err := objects.Create(client, "my_container", objects.CreateOpts{}).ExtractHeader()

type Link struct {
	Href string `mapstructure:"href"`
	Rel  string `mapstructure:"rel"`

Link represents a structure that enables paginated collections how to traverse backward or forward. The "Rel" field is usually either "next".

type ProviderClient

type ProviderClient struct {
	// IdentityBase is the base URL used for a particular provider's identity
	// service - it will be used when issuing authenticatation requests. It
	// should point to the root resource of the identity service, not a specific
	// identity version.
	IdentityBase string

	// IdentityEndpoint is the identity endpoint. This may be a specific version
	// of the identity service. If this is the case, this endpoint is used rather
	// than querying versions first.
	IdentityEndpoint string

	// TokenID is the ID of the most recently issued valid token.
	TokenID string

	// EndpointLocator describes how this provider discovers the endpoints for
	// its constituent services.
	EndpointLocator EndpointLocator

ProviderClient stores details that are required to interact with any services within a specific provider's API.

Generally, you acquire a ProviderClient by calling the NewClient method in the appropriate provider's child package, providing whatever authentication credentials are required.

func (*ProviderClient) AuthenticatedHeaders

func (client *ProviderClient) AuthenticatedHeaders() map[string]string

AuthenticatedHeaders returns a map of HTTP headers that are common for all authenticated service requests.

type Result

type Result struct {
	// Body is the payload of the HTTP response from the server. In most cases, this will be the
	// deserialized JSON structure.
	Body interface{}

	// Header contains the HTTP header structure from the original response.
	Header http.Header

	// Err is an error that occurred during the operation. It's deferred until extraction to make
	// it easier to chain operations.
	Err error

Result acts as a base struct that other results can embed.

func (Result) PrettyPrintJSON

func (r Result) PrettyPrintJSON() string

PrettyPrintJSON creates a string containing the full response body as pretty-printed JSON.

type ServiceClient

type ServiceClient struct {
	// ProviderClient is a reference to the provider that implements this service.

	// Endpoint is the base URL of the service's API, acquired from a service catalog.
	// It MUST end with a /.
	Endpoint string

	// ResourceBase is the base URL shared by the resources within a service's API. It should include
	// the API version and, like Endpoint, MUST end with a / if set. If not set, the Endpoint is used
	// as-is, instead.
	ResourceBase string

ServiceClient stores details required to interact with a specific service API implemented by a provider. Generally, you'll acquire these by calling the appropriate `New` method on a ProviderClient.

func (*ServiceClient) ResourceBaseURL

func (client *ServiceClient) ResourceBaseURL() string

ResourceBaseURL returns the base URL of any resources used by this service. It MUST end with a /.

func (*ServiceClient) ServiceURL

func (client *ServiceClient) ServiceURL(parts ...string) string

ServiceURL constructs a URL for a resource belonging to this provider.

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier