sdk

package
v0.0.0-...-ae22146 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2024 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const (
	OvhEU        = "https://eu.api.ovh.com/1.0"
	OvhCA        = "https://ca.api.ovh.com/1.0"
	OvhUS        = "https://api.us.ovhcloud.com/1.0"
	KimsufiEU    = "https://eu.api.kimsufi.com/1.0"
	KimsufiCA    = "https://ca.api.kimsufi.com/1.0"
	SoyoustartEU = "https://eu.api.soyoustart.com/1.0"
	SoyoustartCA = "https://ca.api.soyoustart.com/1.0"
	RunaboveCA   = "https://api.runabove.com/1.0"
)

Endpoints

View Source
const DefaultExpirationTime = 23 * time.Hour

DefaultExpirationTime is the maximum time to be alive of an OpenStack keystone token.

View Source
const DefaultTimeout = 180 * time.Second

DefaultTimeout api requests after 180s

Variables

View Source
var (
	ReadOnly      = []string{"GET"}
	ReadWrite     = []string{"GET", "POST", "PUT", "DELETE"}
	ReadWriteSafe = []string{"GET", "POST", "PUT"}
)

Map user friendly access level names to corresponding HTTP verbs

View Source
var Endpoints = map[string]string{
	"ovh-eu":        OvhEU,
	"ovh-ca":        OvhCA,
	"ovh-us":        OvhUS,
	"kimsufi-eu":    KimsufiEU,
	"kimsufi-ca":    KimsufiCA,
	"soyoustart-eu": SoyoustartEU,
	"soyoustart-ca": SoyoustartCA,
	"runabove-ca":   RunaboveCA,
}

Endpoints conveniently maps endpoints names to their URI for external configuration

View Source
var (
	ErrAPIDown = errors.New("go-vh: the OVH API is down, it does't respond to /time anymore")
)

Errors

Functions

func IsPossiblyCanadianTenantSyncError

func IsPossiblyCanadianTenantSyncError(err error, url string) bool

IsPossiblyCanadianTenantSyncError returns whether the given error and URL could be due to the tenant being canadian and too recent. This is a temporary fix until the issue is correctly handled

Types

type APIError

type APIError struct {
	// Error message.
	Message string
	// HTTP code.
	Code int
	// ID of the request
	QueryID string
}

APIError represents an error that can occurred while calling the API.

func (*APIError) Error

func (err *APIError) Error() string

type AccessRule

type AccessRule struct {
	// Allowed HTTP Method for the requested AccessRule.
	// Can be set to GET/POST/PUT/DELETE.
	Method string `json:"method"`
	// Allowed path.
	// Can be an exact string or a string with '*' char.
	// Example :
	// 		/me : only /me is authorized
	//		/* : all calls are authorized
	Path string `json:"path"`
}

AccessRule represents a method allowed for a path

type CkRequest

type CkRequest struct {
	AccessRules []AccessRule `json:"accessRules"`
	Redirection string       `json:"redirection,omitempty"`
	// contains filtered or unexported fields
}

CkRequest represents the parameters to fill in order to ask a new consumerKey.

func (*CkRequest) AddRecursiveRules

func (ck *CkRequest) AddRecursiveRules(methods []string, path string)

AddRecursiveRules adds grant requests on "path" and "path/*", for all methods "ReadOnly", "ReadWrite" and "ReadWriteSafe" should be used for "methods" unless specific access are required.

func (*CkRequest) AddRule

func (ck *CkRequest) AddRule(method, path string)

AddRule adds a new rule to the ckRequest

func (*CkRequest) AddRules

func (ck *CkRequest) AddRules(methods []string, path string)

AddRules adds grant requests on "path" for all methods. "ReadOnly", "ReadWrite" and "ReadWriteSafe" should be used for "methods" unless specific access are required.

func (*CkRequest) Do

func (ck *CkRequest) Do() (*CkValidationState, error)

Do executes the request. On success, set the consumer key in the client and return the URL the user needs to visit to validate the key

type CkValidationState

type CkValidationState struct {
	// Consumer key, which need to be validated by customer.
	ConsumerKey string `json:"consumerKey"`
	// Current status, should be always "pendingValidation".
	State string `json:"state"`
	// URL to redirect user in order to log in.
	ValidationURL string `json:"validationUrl"`
}

CkValidationState represents the response when asking a new consumerKey.

func (*CkValidationState) String

func (ck *CkValidationState) String() string

type Client

type Client struct {
	// Self generated tokens. Create one by visiting
	// https://eu.api.ovh.com/createApp/
	// AppKey holds the Application key
	AppKey string

	// AppSecret holds the Application secret key
	AppSecret string

	// ConsumerKey holds the user/app specific token. It must have been validated before use.
	ConsumerKey string

	// Client is the underlying HTTP client used to run the requests. It may be overloaded but a default one is instanciated in “NewClient“ by default.
	Client *http.Client

	// Logger is used to log HTTP requests and responses.
	Logger Logger

	Timeout time.Duration
	// contains filtered or unexported fields
}

Client represents a client to call the OVH API

func NewClient

func NewClient(endpoint, appKey, appSecret, consumerKey string) (*Client, error)

NewClient represents a new client to call the API

func NewDefaultClient

func NewDefaultClient() (*Client, error)

NewDefaultClient will load all it's parameter from environment or configuration files

func NewDefaultClientWithToken

func NewDefaultClientWithToken(authUrl, token string) (*Client, error)

NewDefaultClientWithToken will load all it's parameter from environment or configuration files using an OpenStack keystone token

func NewEndpointClient

func NewEndpointClient(endpoint string) (*Client, error)

NewEndpointClient will create an API client for specified endpoint and load all credentials from environment or configuration files

func (*Client) CallAPI

func (c *Client) CallAPI(method, path string, reqBody, result interface{}, queryParams url.Values, needAuth bool) error

CallAPI is the lowest level call helper. If needAuth is true, inject authentication headers and sign the request.

Request signature is a sha1 hash on following fields, joined by '+': - applicationSecret (from Client instance) - consumerKey (from Client instance) - capitalized method (from arguments) - full request url, including any query string argument - full serialized request body - server current time (takes time delta into account)

Call will automatically assemble the target url from the endpoint configured in the client instance and the path argument. If the reqBody argument is not nil, it will also serialize it as json and inject the required Content-Type header.

If everything went fine, unmarshall response into result and return nil otherwise, return the error

func (*Client) CallAPIWithContext

func (c *Client) CallAPIWithContext(ctx context.Context, method, path string, reqBody, result interface{}, queryParams url.Values, headers map[string]interface{}, needAuth bool) error

CallAPIWithContext is the lowest level call helper. If needAuth is true, inject authentication headers and sign the request.

Request signature is a sha1 hash on following fields, joined by '+': - applicationSecret (from Client instance) - consumerKey (from Client instance) - capitalized method (from arguments) - full request url, including any query string argument - full serialized request body - server current time (takes time delta into account)

Context is used by http.Client to handle context cancelation

Call will automatically assemble the target url from the endpoint configured in the client instance and the path argument. If the reqBody argument is not nil, it will also serialize it as json and inject the required Content-Type header.

If everything went fine, unmarshall response into result and return nil otherwise, return the error

func (*Client) CreateNodePool

func (c *Client) CreateNodePool(ctx context.Context, projectID string, clusterID string, opts *CreateNodePoolOpts) (*NodePool, error)

CreateNodePool allows to creates a node pool in a cluster

func (*Client) Delete

func (c *Client) Delete(url string, result interface{}, queryParams url.Values) error

Delete is a wrapper for the DELETE method

func (*Client) DeleteNodePool

func (c *Client) DeleteNodePool(ctx context.Context, projectID string, clusterID string, poolID string) (*NodePool, error)

DeleteNodePool allows to delete a specific node pool

func (*Client) DeleteUnAuth

func (c *Client) DeleteUnAuth(url string, result interface{}, queryParams url.Values) error

DeleteUnAuth is a wrapper for the unauthenticated DELETE method

func (*Client) DeleteUnAuthWithContext

func (c *Client) DeleteUnAuthWithContext(ctx context.Context, url string, result interface{}, queryParams url.Values) error

DeleteUnAuthWithContext is a wrapper for the unauthenticated DELETE method

func (*Client) DeleteWithContext

func (c *Client) DeleteWithContext(ctx context.Context, url string, result interface{}, queryParams url.Values) error

DeleteWithContext is a wrapper for the DELETE method

func (*Client) Do

func (c *Client) Do(req *http.Request) (*http.Response, error)

Do sends an HTTP request and returns an HTTP response

func (*Client) Get

func (c *Client) Get(url string, result interface{}, queryParams url.Values) error

Get is a wrapper for the GET method

func (*Client) GetNodePool

func (c *Client) GetNodePool(ctx context.Context, projectID string, clusterID string, poolID string) (*NodePool, error)

GetNodePool allows to display information for a specific node pool

func (*Client) GetUnAuth

func (c *Client) GetUnAuth(url string, result interface{}, queryParams url.Values) error

GetUnAuth is a wrapper for the unauthenticated GET method

func (*Client) GetUnAuthWithContext

func (c *Client) GetUnAuthWithContext(ctx context.Context, url string, result interface{}, queryParams url.Values) error

GetUnAuthWithContext is a wrapper for the unauthenticated GET method

func (*Client) GetWithContext

func (c *Client) GetWithContext(ctx context.Context, url string, result interface{}, queryParams url.Values) error

GetWithContext is a wrapper for the GET method

func (*Client) ListClusterFlavors

func (c *Client) ListClusterFlavors(ctx context.Context, projectID string, clusterID string) ([]Flavor, error)

ListClusterFlavors allows to display flavors available for nodes templates

func (*Client) ListNodePoolNodes

func (c *Client) ListNodePoolNodes(ctx context.Context, projectID string, clusterID string, poolID string) ([]Node, error)

ListNodePoolNodes allows to display nodes contained in a parent node pool

func (*Client) ListNodePools

func (c *Client) ListNodePools(ctx context.Context, projectID, clusterID string) ([]NodePool, error)

ListNodePools allows to list all node pools available in a cluster

func (*Client) NewCkRequest

func (c *Client) NewCkRequest() *CkRequest

NewCkRequest helps create a new ck request

func (*Client) NewCkRequestWithRedirection

func (c *Client) NewCkRequestWithRedirection(redirection string) *CkRequest

NewCkRequestWithRedirection helps create a new ck request with a redirect URL

func (*Client) NewRequest

func (c *Client) NewRequest(method, path string, reqBody interface{}, queryParams url.Values, headers map[string]interface{}, needAuth bool) (*http.Request, error)

NewRequest returns a new HTTP request

func (*Client) Ping

func (c *Client) Ping() error

Ping performs a ping to OVH API. In fact, ping is just a /auth/time call, in order to check if API is up.

func (*Client) Post

func (c *Client) Post(url string, reqBody, result interface{}, queryParams url.Values) error

Post is a wrapper for the POST method

func (*Client) PostUnAuth

func (c *Client) PostUnAuth(url string, reqBody, result interface{}, queryParams url.Values) error

PostUnAuth is a wrapper for the unauthenticated POST method

func (*Client) PostUnAuthWithContext

func (c *Client) PostUnAuthWithContext(ctx context.Context, url string, reqBody, result interface{}, queryParams url.Values) error

PostUnAuthWithContext is a wrapper for the unauthenticated POST method

func (*Client) PostWithContext

func (c *Client) PostWithContext(ctx context.Context, url string, reqBody, result interface{}, queryParams url.Values) error

PostWithContext is a wrapper for the POST method

func (*Client) Put

func (c *Client) Put(url string, reqBody, result interface{}, queryParams url.Values) error

Put is a wrapper for the PUT method

func (*Client) PutUnAuth

func (c *Client) PutUnAuth(url string, reqBody, result interface{}, queryParams url.Values) error

PutUnAuth is a wrapper for the unauthenticated PUT method

func (*Client) PutUnAuthWithContext

func (c *Client) PutUnAuthWithContext(ctx context.Context, url string, reqBody, result interface{}, queryParams url.Values) error

PutUnAuthWithContext is a wrapper for the unauthenticated PUT method

func (*Client) PutWithContext

func (c *Client) PutWithContext(ctx context.Context, url string, reqBody, result interface{}, queryParams url.Values) error

PutWithContext is a wrapper for the PUT method

func (*Client) Time

func (c *Client) Time() (*time.Time, error)

Time returns time from the OVH API, by asking GET /auth/time.

func (*Client) TimeDelta

func (c *Client) TimeDelta() (time.Duration, error)

TimeDelta represents the delay between the machine that runs the code and the OVH API. The delay shouldn't change, let's do it only once.

func (*Client) UnmarshalResponse

func (c *Client) UnmarshalResponse(response *http.Response, result interface{}) error

UnmarshalResponse checks the response and unmarshals it into the response type if needed Helper function, called from CallAPI

func (*Client) UpdateNodePool

func (c *Client) UpdateNodePool(ctx context.Context, projectID string, clusterID string, poolID string, opts *UpdateNodePoolOpts) (*NodePool, error)

UpdateNodePool allows to update a specific node pool properties (this call is used for resize)

type ClientMock

type ClientMock struct {
	mock.Mock
}

ClientMock mocks the API client

func (*ClientMock) CreateNodePool

func (m *ClientMock) CreateNodePool(ctx context.Context, projectID string, clusterID string, opts *CreateNodePoolOpts) (*NodePool, error)

CreateNodePool mocks API call for creating a new pool

func (*ClientMock) DeleteNodePool

func (m *ClientMock) DeleteNodePool(ctx context.Context, projectID string, clusterID string, poolID string) (*NodePool, error)

DeleteNodePool mocks API call to delete an existing pool

func (*ClientMock) ListClusterFlavors

func (m *ClientMock) ListClusterFlavors(ctx context.Context, projectID string, clusterID string) ([]Flavor, error)

ListClusterFlavors mocks API call for listing available flavors in cluster

func (*ClientMock) ListNodePoolNodes

func (m *ClientMock) ListNodePoolNodes(ctx context.Context, projectID string, clusterID string, poolID string) ([]Node, error)

ListNodePoolNodes mocks API call for listing node in a pool

func (*ClientMock) ListNodePools

func (m *ClientMock) ListNodePools(ctx context.Context, projectID string, clusterID string) ([]NodePool, error)

ListNodePools mocks API call for listing node pool in cluster

func (*ClientMock) UpdateNodePool

func (m *ClientMock) UpdateNodePool(ctx context.Context, projectID string, clusterID string, poolID string, opts *UpdateNodePoolOpts) (*NodePool, error)

UpdateNodePool mocks API call to update size of a pool

type CreateNodePoolOpts

type CreateNodePoolOpts struct {
	Name       *string `json:"name,omitempty"`
	FlavorName string  `json:"flavorName"`

	Autoscale     bool `json:"autoscale"`
	MonthlyBilled bool `json:"monthlyBilled"`
	AntiAffinity  bool `json:"antiAffinity"`

	DesiredNodes *uint32 `json:"desiredNodes,omitempty"`
	MinNodes     *uint32 `json:"minNodes,omitempty"`
	MaxNodes     *uint32 `json:"maxNodes,omitempty"`
}

CreateNodePoolOpts defines required fields to create a node pool

type Error

type Error struct {
	StatusCode int
	Method     string
	Path       string
	Type       string
	Message    string
}

Error struct

func (Error) Error

func (e Error) Error() string

type Flavor

type Flavor struct {
	Name     string `json:"name"`
	Category string `json:"category"`
	State    string `json:"state"`
	VCPUs    int    `json:"vCPUs"`
	GPUs     int    `json:"gpus"`
	RAM      int    `json:"ram"`
}

Flavor defines instances types available on OVHcloud

type Logger

type Logger interface {
	// LogRequest logs an HTTP request.
	LogRequest(*http.Request)

	// LogResponse logs an HTTP response.
	LogResponse(*http.Response)
}

Logger is the interface that should be implemented for loggers that wish to log HTTP requests and HTTP responses.

type Node

type Node struct {
	ID         string `json:"id"`
	InstanceID string `json:"instanceId"`
	NodePoolID string `json:"nodePoolId"`
	ProjectID  string `json:"projectId"`

	Name     string `json:"name"`
	Flavor   string `json:"flavor"`
	Version  string `json:"version"`
	UpToDate bool   `json:"isUpToDate"`
	Status   string `json:"status"`

	IP        *string `json:"ip,omitempty"`
	PrivateIP *string `json:"privateIp,omitempty"`

	CreatedAt  time.Time `json:"createdAt"`
	DeployedAt time.Time `json:"deployedAt"`
	UpdatedAt  time.Time `json:"updatedAt"`
}

Node defines the instance deployed on OVHcloud

type NodePool

type NodePool struct {
	ID        string `json:"id"`
	ProjectID string `json:"projectId"`

	Name       string `json:"name"`
	Flavor     string `json:"flavor"`
	Status     string `json:"status"`
	SizeStatus string `json:"sizeStatus"`

	Autoscale     bool `json:"autoscale"`
	MonthlyBilled bool `json:"monthlyBilled"`
	AntiAffinity  bool `json:"antiAffinity"`

	DesiredNodes   uint32 `json:"desiredNodes"`
	MinNodes       uint32 `json:"minNodes"`
	MaxNodes       uint32 `json:"maxNodes"`
	CurrentNodes   uint32 `json:"currentNodes"`
	AvailableNodes uint32 `json:"availableNodes"`
	UpToDateNodes  uint32 `json:"upToDateNodes"`

	Autoscaling *NodePoolAutoscaling `json:"autoscaling,omitempty"`

	Template struct {
		Metadata struct {
			Labels      map[string]string `json:"labels"`
			Annotations map[string]string `json:"annotations"`
			Finalizers  []string          `json:"finalizers"`
		} `json:"metadata"`

		Spec struct {
			Unschedulable bool       `json:"unschedulable"`
			Taints        []v1.Taint `json:"taints"`
		} `json:"spec"`
	} `json:"template"`

	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

NodePool defines the nodes group deployed on OVHcloud

type NodePoolAutoscaling

type NodePoolAutoscaling struct {
	CpuMin float32 `json:"cpuMin"`
	CpuMax float32 `json:"cpuMax"`

	MemoryMin float32 `json:"memoryMin"`
	MemoryMax float32 `json:"memoryMax"`

	ScaleDownUtilizationThreshold float32 `json:"scaleDownUtilizationThreshold"`

	ScaleDownUnneededTimeSeconds int32 `json:"scaleDownUnneededTimeSeconds"`
	ScaleDownUnreadyTimeSeconds  int32 `json:"scaleDownUnreadyTimeSeconds"`
}

NodePoolAutoscaling defines the node group autoscaling options from OVHcloud API

type OpenStackProvider

type OpenStackProvider struct {
	AuthUrl string
	Token   string
	// contains filtered or unexported fields
}

OpenStackProvider defines a custom OpenStack provider with a token to re-authenticate

func NewOpenStackProvider

func NewOpenStackProvider(authUrl string, username string, password string, domain string, tenant string) (*OpenStackProvider, error)

NewOpenStackProvider initializes a client/token pair to interact with OpenStack

func (*OpenStackProvider) IsTokenExpired

func (p *OpenStackProvider) IsTokenExpired() bool

IsTokenExpired checks if the current token is expired

func (*OpenStackProvider) ReauthenticateToken

func (p *OpenStackProvider) ReauthenticateToken() error

ReauthenticateToken revoke the current provider token and re-create a new one

type UpdateNodePoolOpts

type UpdateNodePoolOpts struct {
	DesiredNodes *uint32 `json:"desiredNodes,omitempty"`
	MinNodes     *uint32 `json:"minNodes,omitempty"`
	MaxNodes     *uint32 `json:"maxNodes,omitempty"`

	Autoscale *bool `json:"autoscale,omitempty"`

	NodesToRemove []string `json:"nodesToRemove,omitempty"`
}

UpdateNodePoolOpts defines required fields to update a node pool

Jump to

Keyboard shortcuts

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