lib

package
v2.5.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2017 License: MIT Imports: 21 Imported by: 55

Documentation

Overview

Package lib provides an API library to integrate your project with Bytemark's self-service hosting.

Index

Constants

View Source
const (
	// Version is the version number the client believes it is
	Version = "2.5.1"
)

Variables

View Source
var DefaultGroup = "default"

DefaultGroup is the default group name (just the group part - don't add dots!). Defaults to "default". Wow.

Functions

func FormatAccount

func FormatAccount(wr io.Writer, a *Account, def *Account, tpl string) error

FormatAccount outputs the given Account to the given Writer. This function is deprecated and will be removed in 3.0. Please use Account.PrettyPrint(io.Writer, prettyprint.Detail) instead.

func FormatImageInstall

func FormatImageInstall(wr io.Writer, ii *brain.ImageInstall, tpl TemplateChoice) error

FormatImageInstall outputs the given ImageInstall to the given Writer. tpl is ignored. This function is deprecated and will be removed in 3.0. Please use brain.ImageInstall.PrettyPrint(io.Writer, prettyprint.Detail) instead.

func FormatOverview

func FormatOverview(wr io.Writer, accounts []*Account, defaultAccount *Account, username string) error

FormatOverview outputs the given overview using the named template to the given writer. defaultAccount does not need to be specified, will be removed in 3.0 TODO(telyn): make template choice not a string TODO(telyn): use an actual Overview object?

func FormatVirtualMachine

func FormatVirtualMachine(wr io.Writer, vm *brain.VirtualMachine, tpl TemplateChoice) error

FormatVirtualMachine outputs the given VM to the given Writer, using the template specified. This function is deprecated and will be removed in 3.0. Please use brain.VirtualMachine.PrettyPrint(io.Writer, prettyprint.Detail) instead.

func FormatVirtualMachineSpec

func FormatVirtualMachineSpec(wr io.Writer, group *GroupName, spec *brain.VirtualMachineSpec, tpl TemplateChoice) error

FormatVirtualMachineSpec outputs the given spec to the given writer. tpl and group are ignored. This function is deprecated and will be removed in 3.0. Please use brain.VirtualMachineSpec.PrettyPrint(io.Writer, prettyprint.Detail) instead.

func ParseAccountName

func ParseAccountName(name string, defaults ...string) (account string)

ParseAccountName parses a group name given in account[.extrabits] format. If there is a blank account name, tries to figure out the best possible account name to use. If authentication has already happened, this also involves asking bmbilling.

Types

type APIError

type APIError struct {
	Method       string
	URL          *url.URL
	StatusCode   int
	RequestBody  string
	ResponseBody string
}

APIError is the basic error type which most errors returned by the client library are subclassed from.

func (APIError) Error

func (e APIError) Error() string

type Account

type Account struct {
	Name             string          `json:"name"`
	Owner            *billing.Person `json:"owner"`
	TechnicalContact *billing.Person `json:"technical_contact"`
	BillingID        int             `json:"billing_id"`
	BrainID          int             `json:"brain_id"`
	CardReference    string          `json:"card_reference"`
	Groups           []*brain.Group  `json:"groups"`
	Suspended        bool            `json:"suspended"`

	IsDefaultAccount bool `json:"-"`
}

Account represents both the BigV and bmbilling parts of an account.

func (Account) CountVirtualMachines

func (a Account) CountVirtualMachines() (servers int)

CountVirtualMachines returns the number of virtual machines across all the Account's Groups.

func (Account) PrettyPrint

func (a Account) PrettyPrint(wr io.Writer, detail prettyprint.DetailLevel) error

PrettyPrint writes an overview of this account out to the given writer.

func (Account) String

func (a Account) String() string

String formats this account as a string - the same format as prettyprint.SingleLine

type AccountCreationDeferredError added in v0.7.0

type AccountCreationDeferredError struct{}

AccountCreationDeferredError is returned when we get a particular response from bmbilling.

func (AccountCreationDeferredError) Error added in v0.7.0

type AmbiguousKeyError

type AmbiguousKeyError struct {
	APIError
}

AmbiguousKeyError is returned when a call to DeleteUserAuthorizedKey has an insufficiently unique

func (AmbiguousKeyError) Error

func (e AmbiguousKeyError) Error() string

type BadNameError

type BadNameError struct {
	APIError
	Type         string
	ProblemField string
	ProblemValue string
}

BadNameError is returned when a VirtualMachineName / GroupName or AccountName is invalid.

func (BadNameError) Error

func (e BadNameError) Error() string

type BadRequestError

type BadRequestError struct {
	APIError
	Problems map[string][]string
}

BadRequestError is returned when a request was malformed.

func (BadRequestError) Error

func (e BadRequestError) Error() string

type Client

type Client interface {

	// GetEndpoint returns the API endpoint currently in use.
	GetEndpoint() string

	// GetSessionFactors returns the factors provided when the current auth session was set up
	GetSessionFactors() []string
	// GetSessionToken returns the token for the current auth session
	GetSessionToken() string

	// GetSessionUser returns the user's name for the current auth session.
	GetSessionUser() string

	// SetDebugLevel sets the debug level / verbosity of the API client. 0 (default) is silent.
	SetDebugLevel(int)

	EnsureVirtualMachineName(vm *VirtualMachineName) error
	EnsureGroupName(group *GroupName) error
	EnsureAccountName(account *string) error

	// AuthWithToken attempts to read sessiondata from auth for the given token. Returns nil on success or an error otherwise.
	AuthWithToken(string) error
	// AuthWithCredentials attempts to authenticate with the given credentials. Returns nil on success or an error otherwise.
	AuthWithCredentials(auth3.Credentials) error

	AllowInsecureRequests()
	BuildRequestNoAuth(method string, endpoint Endpoint, path string, parts ...string) (*Request, error)
	BuildRequest(method string, endpoint Endpoint, path string, parts ...string) (*Request, error)

	CreateCreditCard(*spp.CreditCard) (string, error)
	CreateCreditCardWithToken(*spp.CreditCard, string) (string, error)

	// CreateAccount(*Account) (*Account, error) // TODO(telyn): figure out if CreateAccount is needed/useful
	GetSPPToken(cc spp.CreditCard, owner *billing.Person) (string, error)
	RegisterNewAccount(acc *Account) (*Account, error)

	ParseVirtualMachineName(string, ...*VirtualMachineName) (*VirtualMachineName, error)
	ParseGroupName(string, ...*GroupName) *GroupName
	ParseAccountName(string, ...string) string

	//
	// DEFINITIONS
	//
	ReadDefinitions() (*Definitions, error)

	// GetAccount takes an account name or ID and returns a filled-out Account object
	GetAccount(name string) (account *Account, err error)
	// GetDefaultAccount gets the most-likely default account for the user.
	GetDefaultAccount() (account *Account, err error)
	// GetAccounts gets all the accounts the logged-in user can see.
	GetAccounts() (accounts []*Account, err error)

	CreateDisc(vm *VirtualMachineName, disc brain.Disc) error
	DeleteDisc(vm *VirtualMachineName, idOrLabel string) error
	GetDisc(vm *VirtualMachineName, idOrLabel string) (*brain.Disc, error)
	ResizeDisc(vm *VirtualMachineName, idOrLabel string, size int) error
	SetDiscIopsLimit(vm *VirtualMachineName, idOrLabel string, iopsLimit int) error

	// CreateGroup sends a request to the API server to create a group with the given name.
	CreateGroup(name *GroupName) error
	DeleteGroup(name *GroupName) error
	GetGroup(name *GroupName) (*brain.Group, error)

	AddIP(name *VirtualMachineName, ipcr *brain.IPCreateRequest) (brain.IPs, error)

	//
	// PRIVILEGES
	//
	// username is allowed to be empty
	GetPrivileges(username string) (brain.Privileges, error)
	GetPrivilegesForAccount(account string) (brain.Privileges, error)
	GetPrivilegesForGroup(group GroupName) (brain.Privileges, error)
	GetPrivilegesForVirtualMachine(vm VirtualMachineName) (brain.Privileges, error)
	GrantPrivilege(p brain.Privilege) error
	RevokePrivilege(p brain.Privilege) error

	CreateBackup(server VirtualMachineName, discLabelOrID string) (brain.Backup, error)
	DeleteBackup(server VirtualMachineName, discLabelOrID string, backupLabelOrID string) error
	GetBackups(server VirtualMachineName, discLabelOrID string) (brain.Backups, error)
	RestoreBackup(server VirtualMachineName, discLabelOrID string, backupLabelOrID string) (brain.Backup, error)

	CreateBackupSchedule(server VirtualMachineName, discLabel string, startDate string, intervalSeconds int) (brain.BackupSchedule, error)
	DeleteBackupSchedule(server VirtualMachineName, discLabel string, id int) error

	GetUser(name string) (*brain.User, error)
	AddUserAuthorizedKey(username, key string) error
	DeleteUserAuthorizedKey(username, key string) error

	// CreateVirtualMachine creates a virtual machine with a given specification in the given group.
	// returns nil on success or an error otherwise.
	CreateVirtualMachine(group *GroupName, vm brain.VirtualMachineSpec) (*brain.VirtualMachine, error)

	// DeleteVirtualMachine deletes the named virtual machine.
	// returns nil on success or an error otherwise.
	DeleteVirtualMachine(name *VirtualMachineName, purge bool) error

	// GetVirtualMachine requests an overview of the named VM, regardless of its deletion status.
	GetVirtualMachine(name *VirtualMachineName) (*brain.VirtualMachine, error)

	// MoveVirtualMachine moves a server from one VirtualMachineName to another.
	MoveVirtualMachine(old *VirtualMachineName, new *VirtualMachineName) error

	// ReimageVirtualMachine reimages the named virtual machine. This will wipe everything on the first disk in the vm and install a new OS on top of it.
	// Note that the machine in question must already be powered off. Once complete, according to the API docs, the vm will be powered on but its autoreboot_on will be false.
	ReimageVirtualMachine(name *VirtualMachineName, image *brain.ImageInstall) (err error)

	// ResetVirtualMachine resets the named virtual machine. This is like pressing the reset
	// button on a physical computer. This does not cause a new process to be started, so does not apply any pending hardware changes.
	// returns nil on success or an error otherwise.
	ResetVirtualMachine(name *VirtualMachineName) (err error)

	// RestartVirtualMachine restarts the named virtual machine. This is
	// returns nil on success or an error otherwise.
	RestartVirtualMachine(name *VirtualMachineName) (err error)

	// StartVirtualMachine starts the named virtual machine.
	// returns nil on success or an error otherwise.
	StartVirtualMachine(name *VirtualMachineName) (err error)

	// StopVirtualMachine starts the named virtual machine.
	// returns nil on success or an error otherwise.
	StopVirtualMachine(name *VirtualMachineName) (err error)

	// ShutdownVirtualMachine sends an ACPI shutdown to the VM. This will cause a graceful shutdown of the machine
	// returns nil on success or an error otherwise.
	ShutdownVirtualMachine(name *VirtualMachineName, stayoff bool) (err error)

	// UndeleteVirtualMachine changes the deleted flag on a VM back to false.
	// Return nil on success, an error otherwise.
	UndeleteVirtualMachine(name *VirtualMachineName) error

	// SetVirtualMachineHardwareProfile specifies the hardware profile on a VM. Optionally locks or unlocks h. profile
	// Return nil on success, an error otherwise.
	SetVirtualMachineHardwareProfile(name *VirtualMachineName, profile string, locked ...bool) (err error)

	// SetVirtualMachineHardwareProfileLock locks or unlocks the hardware profile of a VM.
	// Return nil on success, an error otherwise.
	SetVirtualMachineHardwareProfileLock(name *VirtualMachineName, locked bool) (err error)

	// SetVirtualMachineMemory sets the RAM available to a virtual machine in megabytes
	// Return nil on success, an error otherwise.
	SetVirtualMachineMemory(name *VirtualMachineName, memory int) (err error)

	// SetVirtualMachineCores sets the number of CPUs available to a virtual machine
	// Return nil on success, an error otherwise.
	SetVirtualMachineCores(name *VirtualMachineName, cores int) (err error)

	// SetVirtualMachineCDROM sets the URL of a CD to attach to a virtual machine. Set url to "" to remove the CD.
	// Returns nil on success, an error otherwise.
	SetVirtualMachineCDROM(name *VirtualMachineName, url string) (err error)

	GetVLANs() ([]*brain.VLAN, error)
	GetVLAN(num int) (*brain.VLAN, error)
	GetIPRanges() ([]*brain.IPRange, error)
	GetIPRange(idOrCIDR string) (*brain.IPRange, error)
	GetHeads() ([]*brain.Head, error)
	GetHead(idOrLabel string) (*brain.Head, error)
	GetTails() ([]*brain.Tail, error)
	GetTail(idOrLabel string) (*brain.Tail, error)
	GetStoragePools() ([]*brain.StoragePool, error)
	GetStoragePool(idOrLabel string) (*brain.StoragePool, error)
	GetMigratingDiscs() ([]brain.Disc, error)
	GetMigratingVMs() ([]*brain.VirtualMachine, error)
	GetStoppedEligibleVMs() ([]*brain.VirtualMachine, error)
	GetRecentVMs() ([]*brain.VirtualMachine, error)
	MigrateDisc(disc int, newStoragePool string) error
	MigrateVirtualMachine(vmName VirtualMachineName, newHead string) error
	ReapVMs() error
	DeleteVLAN(id int) error
	AdminCreateGroup(name GroupName, vlanNum int) error
	CreateIPRange(ipRange string, vlanNum int) error
	CancelDiscMigration(id int) error
	CancelVMMigration(id int) error
	EmptyStoragePool(idOrLabel string) error
	EmptyHead(idOrLabel string) error
	ReifyDisc(id int) error
	ApproveVM(name VirtualMachineName, powerOn bool) error
	RejectVM(name VirtualMachineName, reason string) error
	RegradeDisc(disc int, newGrade string) error
	UpdateVMMigration(name VirtualMachineName, speed *int64, downtime *int) error
	CreateUser(username string, privilege string) error
	UpdateHead(idOrLabel string, options UpdateHead) error
	UpdateTail(idOrLabel string, options UpdateTail) error
	UpdateStoragePool(idOrLabel string, options UpdateStoragePool) error
}

Client provides the interface which all API clients should implement.

func New

func New(brainEndpoint, billingEndpoint, sppEndpoint string) (c Client, err error)

New creates a new Bytemark API client using the given Bytemark API endpoint and the default Bytemark auth endpoint, and fills the rest in with defaults. This function will be replaced with NewSimple in 3.0

func NewSimple

func NewSimple() (Client, error)

NewSimple creates a new Bytemark API client using the default bytemark endpoints. This function will be renamed to New in 3.0

func NewWithAuth

func NewWithAuth(brainEndpoint, billingEndpoint, sppEndpoint string, auth *auth3.Client) Client

NewWithAuth creates a new Bytemark API client using the given Bytemark API endpoint and github.com/BytemarkHosting/auth-client Client This function is deprecated and will be removed in 3.0

func NewWithURLs

func NewWithURLs(urls EndpointURLs) (c Client, err error)

NewWithURLs creates a new Bytemark API client using the given endpoints.

type Definitions

type Definitions struct {
	Distributions            []string
	StorageGrades            []string
	ZoneNames                []string
	DistributionDescriptions map[string]string
	StorageGradeDescriptions map[string]string
	HardwareProfiles         []string
	Keymaps                  []string
	Sendkeys                 []string
}

Definitions represent all the possible things that can be returned as part of BigV's /definitions endpoint.

func (Definitions) DistributionDefinitions

func (d Definitions) DistributionDefinitions() (dists []brain.DistributionDefinition)

DistributionDefinitions processes DistributionDescriptions into a slice of DistributionDefinitions

func (Definitions) HardwareProfileDefinitions

func (d Definitions) HardwareProfileDefinitions() (profs []brain.HardwareProfileDefinition)

HardwareProfileDefinitions processes HardwareProfiles into a slice of HardwareProfileDefinitions and mixes in some static data since the API doesn't return any more useful information yet.

func (Definitions) StorageGradeDefinitions

func (d Definitions) StorageGradeDefinitions() (grades []brain.StorageGradeDefinition)

StorageGradeDefinitions processes StorageGradeDescriptions into a slice of StorageGradeDefinitions

func (Definitions) ZoneDefinitions

func (d Definitions) ZoneDefinitions() (zones []brain.ZoneDefinition)

ZoneDefinitions processes ZoneNames into a slice of ZoneDefinitions, adding some static data of our own since there's nothing coming from the API about that right now

type Endpoint

type Endpoint int

Endpoint is an enum-style type to avoid people using endpoints like ints

const (
	// AuthEndpoint means "make the connection to auth!"
	AuthEndpoint Endpoint = iota
	// BrainEndpoint means "make the connection to the brain!"
	BrainEndpoint
	// BillingEndpoint means "make the connection to bmbilling!"
	BillingEndpoint
	// SPPEndpoint means "make the connection to SPP!"
	SPPEndpoint
	// APIEndpoint means "make the connection to the general API endpoint!" (api.bytemark.co.uk - atm only used for domains?)
	APIEndpoint
)

type EndpointURLs

type EndpointURLs struct {
	API     string
	Auth    string
	Billing string
	Brain   string
	SPP     string
}

EndpointURLs are the URLs stored by the client for the various API endpoints the client touches. The key endpoints that you may wish to alter are Auth and Brain. When using an auth server and brain that doesn't have a matching bmbilling API, Billing should be set to ""

func DefaultURLs

func DefaultURLs() EndpointURLs

DefaultURLs returns an EndpointURLs for the usual customer-facing Bytemark APIs.

type GroupName

type GroupName struct {
	Group   string
	Account string
}

GroupName is the double-form of the name of a Group, which should be enough to find the group.

func ParseGroupName

func ParseGroupName(name string, defaults ...*GroupName) (group *GroupName)

ParseGroupName parses a group name given in group[.account[.extrabits]] format.

func (GroupName) String

func (g GroupName) String() string

type InsecureConnectionError

type InsecureConnectionError struct {
	Request *Request
}

InsecureConnectionError is returned if the endpoint isn't https but AllowInsecure was not called.

func (InsecureConnectionError) Error

func (e InsecureConnectionError) Error() string

type InternalServerError

type InternalServerError struct {
	APIError
}

InternalServerError is returned when the endpoint responds with an HTTP 500 Internal Server Error.

func (InternalServerError) Error

func (e InternalServerError) Error() string

type JSONDefinition

type JSONDefinition struct {
	ID   string          `json:"id"`
	Data json.RawMessage `json:"data"`
}

JSONDefinition is an intermediate type used for converting BigV's JSON output for /definitions into the beautiful Definitions struct above. It should not be exported.

func (*JSONDefinition) Process

func (d *JSONDefinition) Process(into *Definitions) error

Process unmarshals the data from this JSONDefinition into the right field of the Definitions object.

type JSONDefinitions

type JSONDefinitions []*JSONDefinition

JSONDefinitions should not be exported.

func (JSONDefinitions) Process

func (defs JSONDefinitions) Process() *Definitions

Process processes our intermediate JSONDefinitions into a Definitions object.

type NilAuthError

type NilAuthError struct {
	APIError
}

NilAuthError is returned when a call attempts to add authentication headers to the request, but the Client.AuthSession is nil. This is always a bug as it's an issue with the code and not with anything external.

func (NilAuthError) Error

func (e NilAuthError) Error() string

type NoDefaultAccountError

type NoDefaultAccountError struct {
	InnerErr error
}

NoDefaultAccountError is returned when the library couldn't figure out what account to use as a default.

func (NoDefaultAccountError) Error

func (e NoDefaultAccountError) Error() string

type NotAuthorizedError

type NotAuthorizedError struct {
	APIError
}

NotAuthorizedError is returned when an action was unable to be performed because the caller doesn't have permission. TODO(telyn): rename to ForbiddenError in 3.0

func (NotAuthorizedError) Error

func (e NotAuthorizedError) Error() string

type NotFoundError

type NotFoundError struct {
	APIError
}

NotFoundError is returned when an object was unable to be found - either because the caller doesn't have permission to see them or because they don't exist.

func (NotFoundError) Error

func (e NotFoundError) Error() string

type Overview

type Overview struct {
	DefaultAccount *Account
	Username       string
	Accounts       []*Account
}

Overview is a combination of a user's default account, their username, and all the accounts they have access to see.

type Request

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

Request is the workhorse of the bytemark-client/lib - it builds up a request, then Run can be called to get its results.

func (*Request) AllowInsecure

func (r *Request) AllowInsecure()

AllowInsecure tells the Request that it's ok if the endpoint isn't communicated with over HTTPS.

func (*Request) GetURL

func (r *Request) GetURL() url.URL

GetURL returns the URL that the Request is for.

func (*Request) MarshalAndRun

func (r *Request) MarshalAndRun(in interface{}, out interface{}) (statusCode int, responseBody []byte, err error)

MarshalAndRun marshals the 'in' object and passes that and 'out' to Run as the body and responseObject, respectively.

func (*Request) Run

func (r *Request) Run(body io.Reader, responseObject interface{}) (statusCode int, responseBody []byte, err error)

Run performs the request with the given body, and attempts to unmarshal a successful response into responseObject

type RequestAlreadyRunError

type RequestAlreadyRunError struct {
	Request *Request
}

RequestAlreadyRunError is returned if the Run method was already called for this Request.

func (RequestAlreadyRunError) Error

func (e RequestAlreadyRunError) Error() string

type ServiceUnavailableError

type ServiceUnavailableError struct {
	APIError
}

ServiceUnavailableError is returned by anything that makes an HTTP request resulting in a 503

func (ServiceUnavailableError) Error

func (e ServiceUnavailableError) Error() string

type TemplateChoice

type TemplateChoice string

TemplateChoice is which template to use for a server. This type is deprecated and will be removed in bytemark-client 3.0

type UnauthorizedError

type UnauthorizedError struct {
	APIError
}

UnauthorizedError is returned when an action was unable to be performed because the callers' authentication is bad - they aren't logged in, or their token is invalid

func (UnauthorizedError) Error

func (e UnauthorizedError) Error() string

type UnknownStatusCodeError

type UnknownStatusCodeError struct {
	APIError
}

UnknownStatusCodeError is returned when an action caused API to return a strange status code that the client library wasn't expecting. Perhaps it's a protocol mismatch - try updating to the latest version of the library, otherwise file a bug report.

func (UnknownStatusCodeError) Error

func (e UnknownStatusCodeError) Error() string

type UnsupportedEndpointError

type UnsupportedEndpointError Endpoint

UnsupportedEndpointError is returned when the Endpoint given was not valid.

func (UnsupportedEndpointError) Error

func (e UnsupportedEndpointError) Error() string

type UpdateHead

type UpdateHead struct {
	UsageStrategy   *string
	OvercommitRatio *int
	Label           *string
}

UpdateHead is a struct with all the possible settings that can be updated on a head

type UpdateStoragePool

type UpdateStoragePool struct {
	UsageStrategy   *string
	OvercommitRatio *int
	Label           *string
}

UpdateStoragePool is a struct with all the possible settings that can be updated on a storage pool

type UpdateTail

type UpdateTail struct {
	UsageStrategy   *string
	OvercommitRatio *int
	Label           *string
}

UpdateTail is a struct with all the possible settings that can be updated on a tail

type VirtualMachineName

type VirtualMachineName struct {
	VirtualMachine string
	Group          string
	Account        string
}

VirtualMachineName is the triplet-form of the name of a VirtualMachine, which should be enough to find the VM.

func ParseVirtualMachineName

func ParseVirtualMachineName(name string, defaults ...*VirtualMachineName) (vm *VirtualMachineName, err error)

ParseVirtualMachineName parses a VM name given in vm[.group[.account[.extrabits]]] format

func (VirtualMachineName) GroupName added in v0.6.0

func (vm VirtualMachineName) GroupName() *GroupName

GroupName returns the group and account of this VirtualMachineName as a group.

func (VirtualMachineName) String

func (vm VirtualMachineName) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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