gophercloud

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2014 License: Apache-2.0 Imports: 9 Imported by: 5

README

Gophercloud: the OpenStack SDK for Go

Build Status

Gophercloud is a flexible SDK that allows you to consume and work with OpenStack clouds in a simple and idiomatic way using golang. Many services are supported, including Compute, Block Storage, Object Storage, Networking, and Identity. Each service API is backed with getting started guides, code samples, reference documentation, unit tests and acceptance tests.

How to install

Before installing, you need to ensure that your GOPATH environment variable is pointing to an appropriate directory where you want to install Gophercloud:

mkdir $HOME/go
export GOPATH=$HOME/go

To protect yourself against changes in your dependencies, we highly recommend choosing a dependency management solution for your projects, such as godep. Once this is set up, you can install Gophercloud as a dependency like so:

go get github.com/rackspace/gophercloud

# Edit your code to import relevant packages from "github.com/rackspace/gophercloud"

godep save ./...

This will install all the source files you need into a Godeps/_workspace directory, which is referenceable from your own source files when you use the godep go command.

Getting started

Credentials

Because you'll be hitting an API, you will need to retrieve your OpenStack credentials and either store them as environment variables or in your local Go files. The first method is recommended because it decouples credential information from source code, allowing you to push the latter to your version control system without any security risk.

You will need to retrieve the following:

  • username
  • password
  • tenant name or tenant ID
  • a valid Keystone identity URL

For users that have the OpenStack dashboard installed, there's a shortcut. If you visit the project/access_and_security path in Horizon and click on the "Download OpenStack RC File" button at the top right hand corner, you will download a bash file that exports all of your access details to environment variables. To execute the file, run source admin-openrc.sh and you will be prompted for your password.

Authentication

Once you have access to your credentials, you can begin plugging them into Gophercloud. The next step is authentication, and this is handled by a base "Provider" struct. To get one, you can either pass in your credentials explicitly, or tell Gophercloud to use environment variables:

import (
  "github.com/rackspace/gophercloud"
  "github.com/rackspace/gophercloud/openstack"
  "github.com/rackspace/gophercloud/openstack/utils"
)

// Option 1: Pass in the values yourself
opts := gophercloud.AuthOptions{
  IdentityEndpoint: "https://my-openstack.com:5000/v2.0",
  Username: "{username}",
  Password: "{password}",
  TenantID: "{tenant_id}",
}

// Option 2: Use a utility function to retrieve all your environment variables
opts, err := openstack.AuthOptionsFromEnv()

Once you have the opts variable, you can pass it in and get back a ProviderClient struct:

provider, err := openstack.AuthenticatedClient(opts)

The ProviderClient is the top-level client that all of your OpenStack services derive from. The provider contains all of the authentication details that allow your Go code to access the API - such as the base URL and token ID.

Provision a server

Once we have a base Provider, we inject it as a dependency into each OpenStack service. In order to work with the Compute API, we need a Compute service client; which can be created like so:

client, err := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{
  Region: os.Getenv("OS_REGION_NAME"),
})

We then use this client for any Compute API operation we want. In our case, we want to provision a new server - so we invoke the Create method and pass in the flavor ID (hardware specification) and image ID (operating system) we're interested in:

import "github.com/rackspace/gophercloud/openstack/compute/v2/servers"

server, err := servers.Create(client, servers.CreateOpts{
  Name:      "My new server!",
  FlavorRef: "flavor_id",
  ImageRef:  "image_id",
}).Extract()

If you are unsure about what images and flavors are, you can read our Compute Getting Started guide. The above code sample creates a new server with the parameters, and embodies the new resource in the server variable (a servers.Server struct).

Next steps

Cool! You've handled authentication, got your ProviderClient and provisioned a new server. You're now ready to use more OpenStack services.

Contributing

Engaging the community and lowering barriers for contributors is something we care a lot about. For this reason, we've taken the time to write a contributing guide for folks interested in getting involved in our project. If you're not sure how you can get involved, feel free to submit an issue or e-mail us privately. You don't need to be a Go expert - all members of the community are welcome!

Help and feedback

If you're struggling with something or have spotted a potential bug, feel free to submit an issue to our bug tracker or e-mail us directly at sdk-support@rackspace.com.

Documentation

Overview

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: "https://my-openstack.com:5000/v2.0",
  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.

Index

Constants

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

RFC3339Milli describes a time format used by API responses.

Variables

View Source
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.")
)

Functions

func BuildHeaders added in v1.0.0

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 added in v1.0.0

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 added in v1.0.0

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 added in v1.0.0

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 added in v1.0.0

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 added in v1.0.0

func NormalizeURL(url string) string

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

func WaitFor added in v1.0.0

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.

Types

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 added in v1.0.0

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 added in v1.0.0

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 added in v1.0.0

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 added in v1.0.0

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 added in v1.0.0

func (eo *EndpointOpts) ApplyDefaults(t string)

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

type ErrResult added in v1.0.0

type ErrResult struct {
	Result
}

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 added in v1.0.0

func (r ErrResult) ExtractErr() error

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

type HeaderResult added in v1.0.0

type HeaderResult struct {
	Result
}

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 added in v1.0.0

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 added in v1.0.0

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 added in v1.0.0

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

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

type Result added in v1.0.0

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 added in v1.0.0

func (r Result) PrettyPrintJSON() string

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

type ServiceClient added in v1.0.0

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

	// 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 added in v1.0.0

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 added in v1.0.0

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

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

Directories

Path Synopsis
acceptance
blockstorage/v1/apiversions
Package apiversions provides information and interaction with the different API versions for the OpenStack Block Storage service, code-named Cinder.
Package apiversions provides information and interaction with the different API versions for the OpenStack Block Storage service, code-named Cinder.
blockstorage/v1/snapshots
Package snapshots provides information and interaction with snapshots in the OpenStack Block Storage service.
Package snapshots provides information and interaction with snapshots in the OpenStack Block Storage service.
blockstorage/v1/volumes
Package volumes provides information and interaction with volumes in the OpenStack Block Storage service.
Package volumes provides information and interaction with volumes in the OpenStack Block Storage service.
blockstorage/v1/volumetypes
Package volumetypes provides information and interaction with volume types in the OpenStack Block Storage service.
Package volumetypes provides information and interaction with volume types in the OpenStack Block Storage service.
common/extensions
Package extensions provides information and interaction with the different extensions available for an OpenStack service.
Package extensions provides information and interaction with the different extensions available for an OpenStack service.
compute/v2/extensions
Package extensions provides information and interaction with the different extensions available for the OpenStack Compute service.
Package extensions provides information and interaction with the different extensions available for the OpenStack Compute service.
compute/v2/extensions/diskconfig
Package diskconfig provides information and interaction with the Disk Config extension that works with the OpenStack Compute service.
Package diskconfig provides information and interaction with the Disk Config extension that works with the OpenStack Compute service.
compute/v2/extensions/keypairs
Package keypairs provides information and interaction with the Keypairs extension for the OpenStack Compute service.
Package keypairs provides information and interaction with the Keypairs extension for the OpenStack Compute service.
compute/v2/flavors
Package flavors provides information and interaction with the flavor API resource in the OpenStack Compute service.
Package flavors provides information and interaction with the flavor API resource in the OpenStack Compute service.
compute/v2/images
Package images provides information and interaction with the image API resource in the OpenStack Compute service.
Package images provides information and interaction with the image API resource in the OpenStack Compute service.
compute/v2/servers
Package servers provides information and interaction with the server API resource in the OpenStack Compute service.
Package servers provides information and interaction with the server API resource in the OpenStack Compute service.
identity/v2/extensions
Package extensions provides information and interaction with the different extensions available for the OpenStack Identity service.
Package extensions provides information and interaction with the different extensions available for the OpenStack Identity service.
identity/v2/tenants
Package tenants provides information and interaction with the tenants API resource for the OpenStack Identity service.
Package tenants provides information and interaction with the tenants API resource for the OpenStack Identity service.
identity/v2/tokens
Package tokens provides information and interaction with the token API resource for the OpenStack Identity service.
Package tokens provides information and interaction with the token API resource for the OpenStack Identity service.
identity/v3/endpoints
Package endpoints provides information and interaction with the service endpoints API resource in the OpenStack Identity service.
Package endpoints provides information and interaction with the service endpoints API resource in the OpenStack Identity service.
identity/v3/services
Package services provides information and interaction with the services API resource for the OpenStack Identity service.
Package services provides information and interaction with the services API resource for the OpenStack Identity service.
identity/v3/tokens
Package tokens provides information and interaction with the token API resource for the OpenStack Identity service.
Package tokens provides information and interaction with the token API resource for the OpenStack Identity service.
networking/v2/apiversions
Package apiversions provides information and interaction with the different API versions for the OpenStack Neutron service.
Package apiversions provides information and interaction with the different API versions for the OpenStack Neutron service.
networking/v2/extensions/external
Package external provides information and interaction with the external extension for the OpenStack Networking service.
Package external provides information and interaction with the external extension for the OpenStack Networking service.
networking/v2/extensions/layer3
Package layer3 provides access to the Layer-3 networking extension for the OpenStack Neutron service.
Package layer3 provides access to the Layer-3 networking extension for the OpenStack Neutron service.
networking/v2/extensions/lbaas
Package lbaas provides information and interaction with the Load Balancer as a Service extension for the OpenStack Networking service.
Package lbaas provides information and interaction with the Load Balancer as a Service extension for the OpenStack Networking service.
networking/v2/extensions/provider
Package provider gives access to the provider Neutron plugin, allowing network extended attributes.
Package provider gives access to the provider Neutron plugin, allowing network extended attributes.
networking/v2/extensions/security
Package security contains functionality to work with security group and security group rules Neutron resources.
Package security contains functionality to work with security group and security group rules Neutron resources.
networking/v2/networks
Package networks contains functionality for working with Neutron network resources.
Package networks contains functionality for working with Neutron network resources.
networking/v2/ports
Package ports contains functionality for working with Neutron port resources.
Package ports contains functionality for working with Neutron port resources.
networking/v2/subnets
Package subnets contains functionality for working with Neutron subnet resources.
Package subnets contains functionality for working with Neutron subnet resources.
objectstorage/v1/accounts
Package accounts contains functionality for working with Object Storage account resources.
Package accounts contains functionality for working with Object Storage account resources.
objectstorage/v1/containers
Package containers contains functionality for working with Object Storage container resources.
Package containers contains functionality for working with Object Storage container resources.
objectstorage/v1/objects
Package objects contains functionality for working with Object Storage object resources.
Package objects contains functionality for working with Object Storage object resources.
Package pagination contains utilities and convenience structs that implement common pagination idioms within OpenStack APIs.
Package pagination contains utilities and convenience structs that implement common pagination idioms within OpenStack APIs.
blockstorage/v1/snapshots
Package snapshots provides information and interaction with the snapshot API resource for the Rackspace Block Storage service.
Package snapshots provides information and interaction with the snapshot API resource for the Rackspace Block Storage service.
blockstorage/v1/volumes
Package volumes provides information and interaction with the volume API resource for the Rackspace Block Storage service.
Package volumes provides information and interaction with the volume API resource for the Rackspace Block Storage service.
blockstorage/v1/volumetypes
Package volumetypes provides information and interaction with the volume type API resource for the Rackspace Block Storage service.
Package volumetypes provides information and interaction with the volume type API resource for the Rackspace Block Storage service.
compute/v2/flavors
Package flavors provides information and interaction with the flavor API resource for the Rackspace Cloud Servers service.
Package flavors provides information and interaction with the flavor API resource for the Rackspace Cloud Servers service.
compute/v2/images
Package images provides information and interaction with the image API resource for the Rackspace Cloud Servers service.
Package images provides information and interaction with the image API resource for the Rackspace Cloud Servers service.
compute/v2/keypairs
Package keypairs provides information and interaction with the keypair API resource for the Rackspace Cloud Servers service.
Package keypairs provides information and interaction with the keypair API resource for the Rackspace Cloud Servers service.
compute/v2/networks
Package networks provides information and interaction with the network API resource for the Rackspace Cloud Servers service.
Package networks provides information and interaction with the network API resource for the Rackspace Cloud Servers service.
compute/v2/servers
Package servers provides information and interaction with the server API resource for the Rackspace Cloud Servers service.
Package servers provides information and interaction with the server API resource for the Rackspace Cloud Servers service.
identity/v2/extensions
Package extensions provides information and interaction with the all the extensions available for the Rackspace Identity service.
Package extensions provides information and interaction with the all the extensions available for the Rackspace Identity service.
identity/v2/tenants
Package tenants provides information and interaction with the tenant API resource for the Rackspace Identity service.
Package tenants provides information and interaction with the tenant API resource for the Rackspace Identity service.
identity/v2/tokens
Package tokens provides information and interaction with the token API resource for the Rackspace Identity service.
Package tokens provides information and interaction with the token API resource for the Rackspace Identity service.
objectstorage/v1/accounts
Package accounts provides information and interaction with the account API resource for the Rackspace Cloud Files service.
Package accounts provides information and interaction with the account API resource for the Rackspace Cloud Files service.
objectstorage/v1/bulk
Package bulk provides functionality for working with bulk operations in the Rackspace Cloud Files service.
Package bulk provides functionality for working with bulk operations in the Rackspace Cloud Files service.
objectstorage/v1/cdncontainers
Package cdncontainers provides information and interaction with the CDN Container API resource for the Rackspace Cloud Files service.
Package cdncontainers provides information and interaction with the CDN Container API resource for the Rackspace Cloud Files service.
objectstorage/v1/cdnobjects
Package cdnobjects provides information and interaction with the CDN Object API resource for the Rackspace Cloud Files service.
Package cdnobjects provides information and interaction with the CDN Object API resource for the Rackspace Cloud Files service.
objectstorage/v1/containers
Package containers provides information and interaction with the Container API resource for the Rackspace Cloud Files service.
Package containers provides information and interaction with the Container API resource for the Rackspace Cloud Files service.
objectstorage/v1/objects
Package objects provides information and interaction with the Object API resource for the Rackspace Cloud Files service.
Package objects provides information and interaction with the Object API resource for the Rackspace Cloud Files service.
Package testhelper container methods that are useful for writing unit tests.
Package testhelper container methods that are useful for writing unit tests.

Jump to

Keyboard shortcuts

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