gomaasapi

package module
v0.0.0-...-78d7e6f Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2016 License: GPL-3.0, LGPL-3.0-or-later Imports: 23 Imported by: 0

README

.. -*- mode: rst -*-

******************************
MAAS API client library for Go
******************************

This library serves as a minimal client for communicating with the MAAS web
API in Go programs.

For more information see the `project homepage`_.

.. _project homepage: https://github.com/juju/gomaasapi

Documentation

Index

Constants

View Source
const (
	// Number of retries performed when the server returns a 503
	// response with a 'Retry-after' header.  A request will be issued
	// at most NumberOfRetries + 1 times.
	NumberOfRetries = 4

	RetryAfterHeaderName = "Retry-After"
)
View Source
const (

	// The node has been created and has a system ID assigned to it.
	NodeStatusDeclared = "0"

	//Testing and other commissioning steps are taking place.
	NodeStatusCommissioning = "1"

	// Smoke or burn-in testing has a found a problem.
	NodeStatusFailedTests = "2"

	// The node can’t be contacted.
	NodeStatusMissing = "3"

	// The node is in the general pool ready to be deployed.
	NodeStatusReady = "4"

	// The node is ready for named deployment.
	NodeStatusReserved = "5"

	// The node is powering a service from a charm or is ready for use with a fresh Ubuntu install.
	NodeStatusDeployed = "6"

	// The node has been removed from service manually until an admin overrides the retirement.
	NodeStatusRetired = "7"

	// The node is broken: a step in the node lifecyle failed. More details
	// can be found in the node's event log.
	NodeStatusBroken = "8"

	// The node is being installed.
	NodeStatusDeploying = "9"

	// The node has been allocated to a user and is ready for deployment.
	NodeStatusAllocated = "10"

	// The deployment of the node failed.
	NodeStatusFailedDeployment = "11"

	// The node is powering down after a release request.
	NodeStatusReleasing = "12"

	// The releasing of the node failed.
	NodeStatusFailedReleasing = "13"

	// The node is erasing its disks.
	NodeStatusDiskErasing = "14"

	// The node failed to erase its disks.
	NodeStatusFailedDiskErasing = "15"
)

Variables

View Source
var NotImplemented = errors.New("Not implemented")

Functions

func EnsureTrailingSlash

func EnsureTrailingSlash(URL string) string

EnsureTrailingSlash appends a slash at the end of the given string unless there already is one. This is used to create the kind of normalized URLs that Django expects. (to avoid Django's redirection when an URL does not ends with a slash.)

func InternalError

func InternalError(w http.ResponseWriter, r *http.Request, err error)

InternalError replies to the request with an HTTP 500 internal error.

func JoinURLs

func JoinURLs(baseURL, path string) string

JoinURLs joins a base URL and a subpath together. Regardless of whether baseURL ends in a trailing slash (or even multiple trailing slashes), or whether there are any leading slashes at the begining of path, the two will always be joined together by a single slash.

func NameOrIDToID

func NameOrIDToID(v string, nameToID map[string]uint, minID, maxID uint) (ID uint, err error)

NameOrIDToID takes a string that contains eiter an integer ID or the name of a thing. It returns the integer ID contained or mapped to or panics.

func PrettyJsonWriter

func PrettyJsonWriter(thing interface{}, w http.ResponseWriter)

Types

type AddressRange

type AddressRange struct {
	Start string `json:"start"`

	End string `json:"end"`

	Purpose      []string `json:"purpose,omitempty"`
	NumAddresses uint     `json:"num_addresses"`
	// contains filtered or unexported fields
}

AddressRange is used to generate reserved IP address range lists

type AddressRangeList

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

AddressRangeList is a list of AddressRange

func (*AddressRangeList) Append

func (ranges *AddressRangeList) Append(startIP, endIP IP)

Append appends a new AddressRange to an AddressRangeList

type Client

type Client struct {
	APIURL *url.URL
	Signer OAuthSigner
}

Client represents a way to communicating with a MAAS API instance. It is stateless, so it can have concurrent requests in progress.

func NewAnonymousClient

func NewAnonymousClient(BaseURL string, apiVersion string) (*Client, error)

NewAnonymousClient creates a client that issues anonymous requests. BaseURL should refer to the root of the MAAS server path, e.g. http://my.maas.server.example.com/MAAS/ apiVersion should contain the version of the MAAS API that you want to use.

func NewAuthenticatedClient

func NewAuthenticatedClient(BaseURL string, apiKey string, apiVersion string) (*Client, error)

NewAuthenticatedClient parses the given MAAS API key into the individual OAuth tokens and creates an Client that will use these tokens to sign the requests it issues. BaseURL should refer to the root of the MAAS server path, e.g. http://my.maas.server.example.com/MAAS/ apiVersion should contain the version of the MAAS API that you want to use.

func (Client) Delete

func (client Client) Delete(uri *url.URL) error

Delete deletes an object on the API, using an HTTP "DELETE" request.

func (Client) Get

func (client Client) Get(uri *url.URL, operation string, parameters url.Values) ([]byte, error)

Get performs an HTTP "GET" to the API. This may be either an API method invocation (if you pass its name in "operation") or plain resource retrieval (if you leave "operation" blank).

func (Client) GetURL

func (client Client) GetURL(uri *url.URL) *url.URL

GetURL returns the URL to a given resource on the API, based on its URI. The resource URI may be absolute or relative; either way the result is a full absolute URL including the network part.

func (Client) Post

func (client Client) Post(uri *url.URL, operation string, parameters url.Values, files map[string][]byte) ([]byte, error)

Post performs an HTTP "POST" to the API. This may be either an API method invocation (if you pass its name in "operation") or plain resource retrieval (if you leave "operation" blank).

func (Client) Put

func (client Client) Put(uri *url.URL, parameters url.Values) ([]byte, error)

Put updates an object on the API, using an HTTP "PUT" request.

type CreateSpace

type CreateSpace struct {
	Name string `json:"name"`
}

CreateSpace is used to create new spaces on the server.

type CreateSubnet

type CreateSubnet struct {
	DNSServers []string `json:"dns_servers"`
	Name       string   `json:"name"`
	Space      string   `json:"space"`
	GatewayIP  string   `json:"gateway_ip"`
	CIDR       string   `json:"cidr"`

	// VLAN this subnet belongs to. Currently ignored.
	// TODO: Defaults to the default VLAN
	// for the provided fabric or defaults to the default VLAN
	// in the default fabric.
	VLAN *uint `json:"vlan"`

	// Fabric for the subnet. Currently ignored.
	// TODO: Defaults to the fabric the provided
	// VLAN belongs to or defaults to the default fabric.
	Fabric *uint `json:"fabric"`

	// VID of the VLAN this subnet belongs to. Currently ignored.
	// TODO: Only used when vlan
	// is not provided. Picks the VLAN with this VID in the provided
	// fabric or the default fabric if one is not given.
	VID *uint `json:"vid"`

	// This is used for updates (PUT) and is ignored by create (POST)
	ID uint `json:"id"`
}

CreateSubnet is used to receive new subnets via the MAAS API

type IP

type IP struct {
	Purpose []string
	// contains filtered or unexported fields
}

IP is an enhanced net.IP

func IPFromInt64

func IPFromInt64(v uint64) IP

IPFromInt64 creates a new IP from a uint64 IP address representation

func IPFromNetIP

func IPFromNetIP(netIP net.IP) IP

IPFromNetIP creates a IP from a net.IP.

func IPFromString

func IPFromString(v string) IP

IPFromString creates a new IP from a string IP address representation

func (*IP) SetUInt64

func (ip *IP) SetUInt64(v uint64)

SetUInt64 sets the IP value to v

func (IP) String

func (ip IP) String() string

func (IP) To16

func (ip IP) To16() net.IP

To16 converts the IP address ip to a 16-byte representation. If ip is not an IP address (it is the wrong length), To16 returns nil.

func (IP) To4

func (ip IP) To4() net.IP

To4 converts the IPv4 address ip to a 4-byte representation. If ip is not an IPv4 address, To4 returns nil.

func (IP) UInt64

func (ip IP) UInt64() uint64

UInt64 returns a uint64 holding the IP address

type JSONObject

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

JSONObject is a wrapper around a JSON structure which provides methods to extract data from that structure. A JSONObject provides a simple structure consisting of the data types defined in JSON: string, number, object, list, and bool. To get the value you want out of a JSONObject, you must know (or figure out) which kind of value you have, and then call the appropriate Get*() method to get at it. Reading an item as the wrong type will return an error. For instance, if your JSONObject consists of a number, call GetFloat64() to get the value as a float64. If it's a list, call GetArray() to get a slice of JSONObjects. To read any given item from the slice, you'll need to "Get" that as the right type as well. There is one exception: a MAASObject is really a special kind of map, so you can read it as either. Reading a null item is also an error. So before you try obj.Get*(), first check obj.IsNil().

func JSONObjectFromStruct

func JSONObjectFromStruct(client Client, input interface{}) (JSONObject, error)

JSONObjectFromStruct takes a struct and converts it to a JSONObject

func Parse

func Parse(client Client, input []byte) (JSONObject, error)

Parse a JSON blob into a JSONObject.

func (JSONObject) GetArray

func (obj JSONObject) GetArray() (value []JSONObject, err error)

GetArray retrieves the object's value as an array. If the value wasn't a JSON list, that's an error.

func (JSONObject) GetBool

func (obj JSONObject) GetBool() (value bool, err error)

GetBool retrieves the object's value as a bool. If the value wasn't a JSON bool, that's an error.

func (JSONObject) GetBytes

func (obj JSONObject) GetBytes() ([]byte, error)

GetBytes retrieves the object's value as raw bytes. A JSONObject that was parsed from the original input (as opposed to one that's embedded in another JSONObject) can contain both the raw bytes and the parsed JSON value, but either can be the case without the other. If this object wasn't parsed directly from the original input, that's an error. If the object was parsed from an original input that just said "null", then IsNil will return true but the raw bytes are still available from GetBytes.

func (JSONObject) GetFloat64

func (obj JSONObject) GetFloat64() (value float64, err error)

GetFloat64 retrieves the object's value as a float64. If the value wasn't a JSON number, that's an error.

func (JSONObject) GetMAASObject

func (obj JSONObject) GetMAASObject() (MAASObject, error)

JSONObject getter for a MAAS object. From a decoding perspective, a MAASObject is just like a map except it contains a key "resource_uri", and it keeps track of the Client you got it from so that you can invoke API methods directly on their MAAS objects.

func (JSONObject) GetMap

func (obj JSONObject) GetMap() (value map[string]JSONObject, err error)

GetMap retrieves the object's value as a map. If the value wasn't a JSON object, that's an error.

func (JSONObject) GetString

func (obj JSONObject) GetString() (value string, err error)

GetString retrieves the object's value as a string. If the value wasn't a JSON string, that's an error.

func (JSONObject) IsNil

func (obj JSONObject) IsNil() bool

IsNil tells you whether a JSONObject is a JSON "null." There is one irregularity. If the original JSON blob was actually raw data, not JSON, then its IsNil will return false because the object contains the binary data as a non-nil value. But, if the original JSON blob consisted of a null, then IsNil returns true even though you can still retrieve binary data from it.

func (JSONObject) MarshalJSON

func (obj JSONObject) MarshalJSON() ([]byte, error)

MarshalJSON tells the standard json package how to serialize a JSONObject back to JSON.

type MAASObject

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

MAASObject represents a MAAS object as returned by the MAAS API, such as a Node or a Tag. You can extract a MAASObject out of a JSONObject using JSONObject.GetMAASObject. A MAAS API call will usually return either a MAASObject or a list of MAASObjects. The list itself would be wrapped in a JSONObject, so if an API call returns a list of objects "l," you first obtain the array using l.GetArray(). Then, for each item "i" in the array, obtain the matching MAASObject using i.GetMAASObject().

func NewMAAS

func NewMAAS(client Client) *MAASObject

NewMAAS returns an interface to the MAAS API as a *MAASObject.

func (MAASObject) CallGet

func (obj MAASObject) CallGet(operation string, params url.Values) (JSONObject, error)

CallGet invokes an idempotent API method on this object.

func (MAASObject) CallPost

func (obj MAASObject) CallPost(operation string, params url.Values) (JSONObject, error)

CallPost invokes a non-idempotent API method on this object.

func (MAASObject) CallPostFiles

func (obj MAASObject) CallPostFiles(operation string, params url.Values, files map[string][]byte) (JSONObject, error)

CallPostFiles invokes a non-idempotent API method on this object. It is similar to CallPost but has an extra parameter, 'files', which should contain the files that will be uploaded to the API.

func (MAASObject) Delete

func (obj MAASObject) Delete() error

Delete removes this object on the API.

func (MAASObject) Get

func (obj MAASObject) Get() (MAASObject, error)

Get retrieves a fresh copy of this MAAS object from the API.

func (MAASObject) GetField

func (obj MAASObject) GetField(name string) (string, error)

GetField extracts a string field from this MAAS object.

func (MAASObject) GetMap

func (obj MAASObject) GetMap() map[string]JSONObject

GetMap returns all of the object's attributes in the form of a map.

func (MAASObject) GetSubObject

func (obj MAASObject) GetSubObject(name string) MAASObject

GetSubObject returns a new MAASObject representing the API resource found at a given sub-path of the current object's resource URI.

func (MAASObject) MarshalJSON

func (obj MAASObject) MarshalJSON() ([]byte, error)

MarshalJSON tells the standard json package how to serialize a MAASObject.

func (MAASObject) Post

func (obj MAASObject) Post(params url.Values) (JSONObject, error)

Post overwrites this object's existing value on the API with those given in "params." It returns the object's new value as received from the API.

func (MAASObject) URI

func (obj MAASObject) URI() *url.URL

URI is the resource URI for this MAAS object. It is an absolute path, but without a network part.

func (MAASObject) URL

func (obj MAASObject) URL() *url.URL

URL returns a full absolute URL (including network part) for this MAAS object on the API.

func (MAASObject) Update

func (obj MAASObject) Update(params url.Values) (MAASObject, error)

Update modifies this object on the API, based on the values given in "params." It returns the object's new value as received from the API.

type NetworkLink struct {
	ID     uint    `json:"id"`
	Mode   string  `json:"mode"`
	Subnet *Subnet `json:"subnet"`
}

NetworkLink represents a MAAS network link

type Node

type Node struct {
	SystemID   string                 `json:"system_id"`
	Interfaces []NodeNetworkInterface `json:"interface_set"`
}

Node represents a node

type NodeNetworkInterface

type NodeNetworkInterface struct {
	Name  string        `json:"name"`
	Links []NetworkLink `json:"links"`
}

NodeNetworkInterface represents a network interface attached to a node

type OAuthSigner

type OAuthSigner interface {
	OAuthSign(request *http.Request) error
}

func NewPlainTestOAuthSigner

func NewPlainTestOAuthSigner(token *OAuthToken, realm string) (OAuthSigner, error)

type OAuthToken

type OAuthToken struct {
	ConsumerKey    string
	ConsumerSecret string
	TokenKey       string
	TokenSecret    string
}

type PostedVLAN

type PostedVLAN struct {
	Name string `json:"name"`
	VID  uint   `json:"vid"`
}

PostedVLAN is the MAAS API posted VLAN representation

type ServerError

type ServerError struct {
	StatusCode int
	Header     http.Header
	// contains filtered or unexported fields
}

ServerError is an http error (or at least, a non-2xx result) received from the server. It contains the numerical HTTP status code as well as an error string and the response's headers.

type Space

type Space struct {
	Name        string   `json:"name"`
	Subnets     []Subnet `json:"subnets"`
	ResourceURI string   `json:"resource_uri"`
	ID          uint     `json:"id"`
}

Space is the MAAS API space representation

type Subnet

type Subnet struct {
	DNSServers []string `json:"dns_servers"`
	Name       string   `json:"name"`
	Space      string   `json:"space"`
	VLAN       VLAN     `json:"vlan"`
	GatewayIP  string   `json:"gateway_ip"`
	CIDR       string   `json:"cidr"`

	ResourceURI        string         `json:"resource_uri"`
	ID                 uint           `json:"id"`
	InUseIPAddresses   []IP           `json:"-"`
	FixedAddressRanges []AddressRange `json:"-"`
}

Subnet is the MAAS API subnet representation

type SubnetStats

type SubnetStats struct {
	NumAvailable     uint           `json:"num_available"`
	LargestAvailable uint           `json:"largest_available"`
	NumUnavailable   uint           `json:"num_unavailable"`
	TotalAddresses   uint           `json:"total_addresses"`
	Usage            float32        `json:"usage"`
	UsageString      string         `json:"usage_string"`
	Ranges           []AddressRange `json:"ranges"`
}

SubnetStats holds statistics about a subnet

type TestMAASObject

type TestMAASObject struct {
	MAASObject
	TestServer *TestServer
}

TestMAASObject is a fake MAAS server MAASObject.

func NewTestMAAS

func NewTestMAAS(version string) *TestMAASObject

NewTestMAAS returns a TestMAASObject that implements the MAASObject interface and thus can be used as a test object instead of the one returned by gomaasapi.NewMAAS().

func (*TestMAASObject) Close

func (testMAASObject *TestMAASObject) Close()

Close shuts down the test server.

type TestServer

type TestServer struct {
	*httptest.Server
	// contains filtered or unexported fields
}

A TestServer is an HTTP server listening on a system-chosen port on the local loopback interface, which simulates the behavior of a MAAS server. It is intendend for use in end-to-end HTTP tests using the gomaasapi library.

func NewTestServer

func NewTestServer(version string) *TestServer

NewTestServer starts and returns a new MAAS test server. The caller should call Close when finished, to shut it down.

func (*TestServer) AddBootImage

func (server *TestServer) AddBootImage(nodegroupUUID string, jsonText string)

AddBootImage adds a boot-image object to the specified nodegroup.

func (*TestServer) AddFixedAddressRange

func (server *TestServer) AddFixedAddressRange(subnetID uint, ar AddressRange)

AddFixedAddressRange adds an AddressRange to the list of fixed address ranges that subnet stores.

func (*TestServer) AddNodeDetails

func (server *TestServer) AddNodeDetails(systemId, xmlText string)

AddNodeDetails stores node details, expected in XML format.

func (*TestServer) AddZone

func (server *TestServer) AddZone(name, description string)

AddZone adds a physical zone to the server.

func (*TestServer) ChangeNode

func (server *TestServer) ChangeNode(systemId, key, value string)

ChangeNode updates a node with the given key/value.

func (*TestServer) Clear

func (server *TestServer) Clear()

Clear clears all the fake data stored and recorded by the test server (nodes, recorded operations, etc.).

func (*TestServer) ConnectNodeToNetwork

func (server *TestServer) ConnectNodeToNetwork(systemId, name string)

func (*TestServer) ConnectNodeToNetworkWithMACAddress

func (server *TestServer) ConnectNodeToNetworkWithMACAddress(systemId, networkName, macAddress string)

func (*TestServer) Files

func (server *TestServer) Files() map[string]MAASObject

func (*TestServer) IPAddresses

func (server *TestServer) IPAddresses() map[string][]string

IPAddresses returns the map with network names as keys and slices of IP addresses belonging to each network as values.

func (*TestServer) NewFile

func (server *TestServer) NewFile(filename string, filecontent []byte) MAASObject

NewFile creates a file in the test MAAS server.

func (*TestServer) NewIPAddress

func (server *TestServer) NewIPAddress(ipAddress, networkOrSubnet string)

NewIPAddress creates a new static IP address reservation for the given network/subnet and ipAddress. While networks is being deprecated try the given name as both a netowrk and a subnet.

func (*TestServer) NewNetwork

func (server *TestServer) NewNetwork(jsonText string) MAASObject

NewNetwork creates a network in the test MAAS server

func (*TestServer) NewNode

func (server *TestServer) NewNode(jsonText string) MAASObject

NewNode creates a MAAS node. The provided string should be a valid json string representing a map and contain a string value for the key 'system_id'. e.g. `{"system_id": "mysystemid"}`. If one of these conditions is not met, NewNode panics.

func (*TestServer) NewNodegroupInterface

func (server *TestServer) NewNodegroupInterface(uuid, jsonText string) JSONObject

NewNodegroupInterface adds a nodegroup-interface, for the specified nodegroup, in the test MAAS server.

func (*TestServer) NewSpace

func (server *TestServer) NewSpace(spaceJSON io.Reader) *Space

NewSpace creates a space in the test server

func (*TestServer) NewSubnet

func (server *TestServer) NewSubnet(subnetJSON io.Reader) *Subnet

NewSubnet creates a subnet in the test server

func (*TestServer) NodeOperationRequestValues

func (server *TestServer) NodeOperationRequestValues() map[string][]url.Values

NodeOperationRequestValues returns the map containing the list of the url.Values extracted from the request used when performing operations on nodes.

func (*TestServer) NodeOperations

func (server *TestServer) NodeOperations() map[string][]string

NodeOperations returns the map containing the list of the operations performed for each node.

func (*TestServer) Nodes

func (server *TestServer) Nodes() map[string]MAASObject

Nodes returns a map associating all the nodes' system ids with the nodes' objects.

func (*TestServer) NodesOperationRequestValues

func (server *TestServer) NodesOperationRequestValues() []url.Values

NodesOperationRequestValues returns the list of url.Values extracted from the request used when performing operations at the /nodes/ level.

func (*TestServer) NodesOperations

func (server *TestServer) NodesOperations() []string

NodesOperations returns the list of operations performed at the /nodes/ level.

func (*TestServer) OwnedNodes

func (server *TestServer) OwnedNodes() map[string]bool

OwnedNodes returns a map whose keys represent the nodes that are currently allocated.

func (*TestServer) RemoveIPAddress

func (server *TestServer) RemoveIPAddress(ipAddress string) bool

RemoveIPAddress removes the given existing ipAddress and returns whether it was actually removed.

func (server *TestServer) SetNodeNetworkLink(SystemID string, nodeNetworkInterface NodeNetworkInterface)

SetNodeNetworkLink records that the given node + interface are in subnet

func (*TestServer) SetVersionJSON

func (server *TestServer) SetVersionJSON(json string)

SetVersionJSON sets the JSON response (capabilities) returned from the /version/ endpoint.

func (*TestServer) UpdateSubnet

func (server *TestServer) UpdateSubnet(subnetJSON io.Reader) Subnet

UpdateSubnet creates a subnet in the test server

type VLAN

type VLAN struct {
	Name   string `json:"name"`
	Fabric string `json:"fabric"`
	VID    uint   `json:"vid"`

	ResourceURI string `json:"resource_uri"`
	ID          uint   `json:"id"`
}

VLAN is the MAAS API VLAN representation

Directories

Path Synopsis
This is an example on how the Go library gomaasapi can be used to interact with a real MAAS server.
This is an example on how the Go library gomaasapi can be used to interact with a real MAAS server.

Jump to

Keyboard shortcuts

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