lib

package
v3.0.0-...-c77a060 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2019 License: MIT Imports: 23 Imported by: 0

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 = "3.4"
)

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 FormatOverview

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

FormatOverview outputs the given overview using the named template to the given writer. TODO(telyn): make template choice not a string TODO(telyn): use an actual Overview object?

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.

func TokenType

func TokenType(ep Endpoint) string

TokenType returns what kind of token is used for the given endpoint. token for endpoints which expect an authorization header like "Token token=blah" bearer for endpoints which expect one like "Bearer blah"

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.Groups   `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) DefaultFields

func (a Account) DefaultFields(f output.Format) string

DefaultFields returns the list of default fields to feed to github.com/BytemarkHosting/row.From for this type.

func (Account) IsValid

func (a Account) IsValid() bool

IsValid returns true if this account has been populated with data from the brain or billing endpoints.

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

type AccountCreationDeferredError struct{}

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

func (AccountCreationDeferredError) Error

type Accounts

type Accounts []Account

Accounts represents more than one account in output.Outputtable form.

func (Accounts) DefaultFields

func (as Accounts) DefaultFields(f output.Format) string

DefaultFields returns the list of default fields to feed to github.com/BytemarkHosting/row.From for this type.

func (Accounts) PrettyPrint

func (as Accounts) PrettyPrint(wr io.Writer, detail prettyprint.DetailLevel) error

PrettyPrint writes a human-readable summary of the accounts to writer at the given detail level.

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 BillingAccountNotFound

type BillingAccountNotFound string

BillingAccountNotFound is returned when the named billing account could not be found. It's not an APIError or a 404 because we find billing accounts by getting the full list and searching it. Also, having a billing account as part of an Account isn't necessary for all uses of the API, so we return the error and the Account and let the consumer decide what to do.

func (BillingAccountNotFound) Error

func (e BillingAccountNotFound) 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
	// Impersonate requests impersonation of a given user. Authentication must have already occurred.
	Impersonate(user string) 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)

	//
	// 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 Accounts, err error)

	CreateDisc(vm VirtualMachineName, disc brain.Disc) error
	DeleteDisc(vm VirtualMachineName, idOrLabel string) error
	GetDisc(vm VirtualMachineName, idOrLabel string) (brain.Disc, error)
	GetDiscByID(id int) (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)

	// 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.VLANs, error)
	GetVLAN(num int) (brain.VLAN, error)
	GetIPRanges() (brain.IPRanges, error)
	GetIPRange(idOrCIDR string) (brain.IPRange, error)
	GetHeads() (brain.Heads, error)
	GetHead(idOrLabel string) (brain.Head, error)
	GetTails() (brain.Tails, error)
	GetTail(idOrLabel string) (brain.Tail, error)
	GetStoragePools() (brain.StoragePools, error)
	GetStoragePool(idOrLabel string) (brain.StoragePool, error)
	GetMigratingDiscs() (brain.Discs, error)
	GetMigratingVMs() (brain.VirtualMachines, error)
	GetStoppedEligibleVMs() (brain.VirtualMachines, error)
	GetRecentVMs() (brain.VirtualMachines, error)
	MigrateDisc(disc int, newStoragePool string) error
	MigrateVirtualMachine(vmName VirtualMachineName, newHead string) 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
	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 brain.StoragePool) error
}

Client provides the interface which all API clients should implement.

func New

func New() (Client, error)

New creates a new Bytemark API client using the default bytemark endpoints. This function will be renamed to New 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.DistributionDefinitions)

DistributionDefinitions processes DistributionDescriptions into a slice of DistributionDefinitions

func (Definitions) HardwareProfileDefinitions

func (d Definitions) HardwareProfileDefinitions() (profs brain.HardwareProfileDefinitions)

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.StorageGradeDefinitions)

StorageGradeDefinitions processes StorageGradeDescriptions into a slice of StorageGradeDefinitions

func (Definitions) ZoneDefinitions

func (d Definitions) ZoneDefinitions() (zones brain.ZoneDefinitions)

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 ForbiddenError

type ForbiddenError struct {
	APIError
}

ForbiddenError is returned when an action was unable to be performed because the user you're logged in as doesn't have permission.

func (ForbiddenError) Error

func (e ForbiddenError) Error() string

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() (out 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 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.

func (Overview) DefaultFields

func (o Overview) DefaultFields(f output.Format) string

DefaultFields returns the list of default fields to feed to github.com/BytemarkHosting/row.From for this type.

func (Overview) PrettyPrint

func (o Overview) PrettyPrint(wr io.Writer, detail prettyprint.DetailLevel) error

PrettyPrint writes this overview out to the given writer. TODO(telyn): rewrite without FormatOverview

type Request

type Request interface {
	// GetURL gets the URL this request will be / has been made to
	GetURL() url.URL
	// AllowInsecure allows the Request to be made over http instead of https
	AllowInsecure()
	// JSON-marshals the input and runs the request, unmarshalling the response to out if it's not nil
	MarshalAndRun(in interface{}, out interface{}) (statusCode int, responseBody []byte, err error)
	// Runs the request, reading the request body to reader and unmarshalling the response to responseObject (if not nil)
	Run(body io.Reader, responseObject interface{}) (statusCode int, responseBody []byte, err error)
}

Request is the lower-level type that makes HTTP calls

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 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 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

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
requests

Jump to

Keyboard shortcuts

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