rsapi

package
v8.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2020 License: MIT Imports: 22 Imported by: 16

Documentation

Overview

Package rsapi contains common code to all RightScale API clients This includes common data types and authentication algorithms.

Index

Constants

View Source
const (
	// FileEncodingMime will upload files as multipart mime, which is needed for some older APIs
	FileEncodingMime = iota
	// FileEncodingJSON will cause files to be read from disk then placed inline into JSON
	FileEncodingJSON
)
View Source
const RllSecret = "/var/run/rightlink/secret"

RightLink proxy secret file path

Variables

This section is empty.

Functions

func IdentifyParams

func IdentifyParams(a *metadata.Action, params APIParams) (payloadParams APIParams, queryParams APIParams)

IdentifyParams organizes the given params in two groups: the payload params and the query params.

Types

type API

type API struct {
	Auth                  Authenticator         // Authenticator, signs requests for auth
	Host                  string                // API host, e.g. "us-3.rightscale.com"
	Client                httpclient.HTTPClient // Underlying http client (not used for authentication requests as these necessitate special redirect handling)
	FetchLocationResource bool                  // Whether to fetch resource pointed by Location header
	Metadata              APIMetadata           // Generated API metadata
	VersionHeader         string                // Version header name, defaults to X-Api-Version
	FileEncoding          int                   // Encoding for file uploads. 0 = mime, 1 = json
}

API is the RightScale API client. Instances of this struct should be created through `New`, `NewRL10` or `FromCommandLine`.

func FromCommandLine

func FromCommandLine(cmdLine *cmd.CommandLine) (*API, error)

FromCommandLine builds an API client from the command line.

func New

func New(host string, auth Authenticator) *API

New returns a API client that uses the given authenticator. host may be blank in which case client attempts to resolve it using auth.

func NewRL10

func NewRL10() (*API, error)

NewRL10 returns a API client that uses the information stored in /var/run/rightlink/secret to do auth and configure the host. The client behaves identically to the client returned by New in all other regards.

func (*API) BuildHTTPRequest

func (a *API) BuildHTTPRequest(verb, path, version string, params, payload APIParams) (*http.Request, error)

BuildHTTPRequest creates a http.Request given all its parts. If any member of the Payload field is of type io.Reader then the resulting request has a multipart body where each member of type io.Reader is mapped to a single part and all other members make up the first part.

func (*API) CanAuthenticate

func (a *API) CanAuthenticate() error

CanAuthenticate makes a test authenticated request to the RightScale API and returns an error if it fails.

func (*API) LoadResponse

func (a *API) LoadResponse(resp *http.Response) (interface{}, error)

LoadResponse deserializes the JSON response into a generic object. If the response has a "Location" header then the returned object is a map with one key "Location" containing the value of the header.

func (*API) ParseCommand

func (a *API) ParseCommand(cmd, hrefPrefix string, values ActionCommands) (*ParsedCommand, error)

ParseCommand actually runs a command.

func (*API) ParseCommandAndFlags

func (a *API) ParseCommandAndFlags(cmd, hrefPrefix string, values ActionCommands) (*CommandTarget, []string, error)

ParseCommandAndFlags parses a command flag and infers the resource, action, href and params.

func (*API) PerformRequest

func (a *API) PerformRequest(req *http.Request) (*http.Response, error)

PerformRequest logs the request, dumping its content if required then makes the request and logs and dumps the corresponding response.

func (*API) PerformRequestWithContext

func (a *API) PerformRequestWithContext(ctx context.Context, req *http.Request) (*http.Response, error)

PerformRequestWithContext performs everything the PerformRequest does but is also context-aware.

func (*API) ShowActions

func (a *API) ShowActions(cmd, hrefPrefix string, values ActionCommands) error

ShowActions prints all known actions for an API or the selected resource if any.

func (*API) ShowHelp

func (a *API) ShowHelp(cmd, hrefPrefix string, values ActionCommands) error

ShowHelp displays help for the given command and flags.

type APICommandRegistrar

type APICommandRegistrar interface {
	// Register subcommands for all resource actions
	// Store subcommand parse results into given command line value recipient
	RegisterActionCommands(apiName string, metadata map[string]*metadata.Resource,
		cmdValues ActionCommands)
}

APICommandRegistrar is the interface implemented by registrar used by each API client to register subcommands.

type APIMetadata

type APIMetadata map[string]*metadata.Resource

APIMetadata consists of resource metadata indexed by resource name.

type APIParams

type APIParams map[string]interface{}

APIParams is a generic API parameter type, used to specify optional parameters for example.

func Normalize

func Normalize(payload APIParams, name string, v interface{}) (APIParams, error)

Normalize recursively traverses a query string encoded name and builds up the corresponding structure. "a[b]" produces a map[string]interface{} with key "b" "a[]" produces a []interface{}

type ActionCommand

type ActionCommand struct {
	Href     string   // Resource or collection href
	Params   []string // Action parameters
	ShowHelp string   // Whether to list flags supported by resource action
}

ActionCommand is a data structure initialized during command line parsing and used by ParseCommand to create the final ParsedCommand struct. Each specific API client registers the action commands under the main command line tool command. kingpin then initializes the values from the command line.

type ActionCommands

type ActionCommands map[string]*ActionCommand

ActionCommands indexes action command values by action name.

type Authenticator

type Authenticator interface {
	// Sign signs the given http Request (adds the auth headers).
	Sign(req *http.Request) error
	// SetHost updates the host used by the authenticator to create sessions.
	// This method is called internally by the various API clients upon creation.
	SetHost(host string)
	// CanAuthenticate returns nil if the authenticator is able to sign requests successfully
	// or an error with additional information otherwise.
	// It makes a test request to CM 1.5 to validate the provided credentials.
	CanAuthenticate(host string) error
}

Authenticator interface

func NewBasicAuthenticator

func NewBasicAuthenticator(username, password string, accountID int) Authenticator

NewBasicAuthenticator returns a authenticator that uses email and password to create sessions. The returned authenticator takes care of refreshing the RightScale session as needed.

func NewInstanceAuthenticator

func NewInstanceAuthenticator(token string, accountID int) Authenticator

NewInstanceAuthenticator returns an authenticator that uses the instance facing API token to create sessions. This is the token found on RightLink instances under the RS_API_TOKEN environment variable. The returned authenticator takes care of refreshing the RightScale session as needed. Note: Use of rsc made from RightLink10 instances can use the RL10 authenticator instead.

func NewOAuthAuthenticator

func NewOAuthAuthenticator(token string, accountID int) Authenticator

NewOAuthAuthenticator returns a authenticator that uses a oauth refresh token to create access tokens. The refresh token can be found in the CM dashboard under Settings > Account Settings > API Credentials. Specifying the accountID is only required if the API requires the "X-Account" header to be set (this is true of CM 1.6 at the moment).

func NewRL10Authenticator

func NewRL10Authenticator(secret string) Authenticator

NewRL10Authenticator returns an authenticator that proxies all requests through the RightLink 10 agent.

func NewSSAuthenticator

func NewSSAuthenticator(auther Authenticator, accountID int) Authenticator

NewSSAuthenticator returns an authenticator that wraps another one and adds the logic needed to create sessions in Self-Service.

func NewTokenAuthenticator

func NewTokenAuthenticator(token string, accountID int) Authenticator

NewTokenAuthenticator returns an authenticator that use an oauth access token to do authentication. This is useful if the oauth handshake has already happened. Use the OAuthAuthenticator to use a refresh token and have the authenticator do the handshake. Specifying the accountID is only required if the API requires the "X-Account" header to be set (this is true of CM 1.6 at the moment).

type CommandTarget

type CommandTarget struct {
	Resource *metadata.Resource   // Resource command applies to
	Action   *metadata.Action     // Action command corresponds to
	Path     *metadata.ActionPath // Action path
	Href     string               // Resource href
}

CommandTarget is the target of a command: resource type and href as well as action details.

type FileUpload

type FileUpload struct {
	Name     string    // Multipart part name
	Filename string    // Uploaded filename
	Reader   io.Reader // Backing reader
}

FileUpload represents payload fields that correspond to multipart file uploads.

func (*FileUpload) MarshalJSON

func (f *FileUpload) MarshalJSON() ([]byte, error)

MarshalJSON just inserts the contents of the file from disk inline into the json

type ParsedCommand

type ParsedCommand struct {
	HTTPMethod    string
	URI           string
	QueryParams   APIParams
	PayloadParams APIParams
}

ParsedCommand is the result of parsing the command line (ParseCommand method). The parser infers the Uri and HTTP method of the request that need to be made and builds the maps of query string and payload parameters. The parameter values are all coerced to the type dictated by the API metadata.

type Registrar

type Registrar struct {
	// Kingpin command under which API subcommands should be registered
	APICmd *kingpin.CmdClause
}

Registrar implements APICommandRegistrar. Create one of these per API client and initialize it with specific API subcommand

func (*Registrar) RegisterActionCommands

func (r *Registrar) RegisterActionCommands(apiName string, res map[string]*metadata.Resource,
	cmds ActionCommands)

RegisterActionCommands implements APICommandRegistrar.

type SourceUpload

type SourceUpload struct {
	Reader io.Reader
}

SourceUpload represents a payload for /api/right_scripts/:id/update_source It's needed as this one API call has unique properties -- it's content type is text/plain only, and body of the HTTP call is the script body rather than a properly formatted form request :(

Jump to

Keyboard shortcuts

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