api

package
v1.2.30 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2024 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Package api provides an way to interact with Elastic Cloud APIs, including ESS, ECE and ESSP.

The preferred way to interact with the Elastic Cloud APIs is by creating a new API pointer by using the "api.NewAPI()" constructor. To do so, you'll need to pass an "auth.Writer" as the API.Config parameter, and an "http.Client", optionally the API endpoint (Host), if not specified it defaults to ESS API.

To create a new "auth.Writer", you can use one of (APIKey or UserLogin) from the auth package ("github.com/elastic/cloud-sdk-go/auth").

Optionally, "auth.NewAuthWriter()" can be used in applications where the credentials are specified by the user via environment variables or flags.

 ess, err := api.NewAPI(api.Config{
	 Client:        new(http.Client),
	 AuthWriter:    auth.APIKey("some-apikey"),
 })
 if err != nil {
	 panic(err)
 }

List the user's deployments via the `deploymentapi` package (Recommended).

 res, err := deploymentapi.List(deploymentapi.ListParams{API: ess.V1API})
 if err != nil {
	 panic(err)
 }

 var encoder = json.NewEncoder(os.Stdout)
 if err := encoder.Encode(res); err != nil {
	 panic(err)
 }

List the user's deployments using the autogenerated APIs.

 res, err = ess.V1API.Deployments.ListDeployments(
	 deployments.NewListDeploymentsParams(),
	 ess.AuthWriter,
 )
 if err != nil {
	 // Errors returned by the auto-generated API should be unpacked
	 // with `api.UnwrapError`.
	 panic(api.UnwrapError(err))
 }

 if err := encoder.Encode(res.Payload); err != nil {
	 panic(err)
 }

APIs which are region-bound, need that region to be specified as a `context.Context` in the API operation when using the auto-generated APIs directly.

 res, err := ess.V1API.Stack.GetVersionStacks(
	stack.NewGetVersionStacksParams().
	 	WithContext(api.WithRegion(context.Background(), "us-east-1")),
  	ess.AuthWriter,
 )
 if err != nil {
	 panic(api.UnwrapError(err))
 }
 if err := encoder.Encode(res.Payload); err != nil {
	 panic(err)
 }

Index

Constants

View Source
const ESSEndpoint = "https://api.elastic-cloud.com"

ESSEndpoint is the Elasticsearch Service endpoint.

View Source
const (
	// RegionBasePath is for /platform operations which require a Region to be
	// passed as of an API call context.Context. Previously used to create a
	// global client per API instance, now used on a per-operation basis.
	RegionBasePath = "/api/v1/regions/%s"
)
View Source
const Version = "3.7.0"

Version contains the ECE API version compatibility for the current auto-generated client and models. This needs to be updated every time a new "api/apidocs.json" file added and the client and models are re-generated. Even though the Bugfix version is specified, the general support statement is on the minor version, i.e: 2.4.2 means that all the 2.4 branch is supported, expecting some potentially unfixed bugs when ECE version is the same feature version bug higher bugfix version.

Variables

View Source
var (
	// DefaultWriteMockHeaders can be used for test assertions.
	DefaultWriteMockHeaders = map[string][]string{
		"Accept":        {"application/json"},
		"Authorization": {"ApiKey dummy"},
		"Content-Type":  {"application/json"},
		"User-Agent":    {fmt.Sprint("cloud-sdk-go/", Version)},
	}

	// DefaultReadMockHeaders can be used for test assertions.
	DefaultReadMockHeaders = map[string][]string{
		"Accept":        {"application/json"},
		"Authorization": {"ApiKey dummy"},
		"User-Agent":    {fmt.Sprint("cloud-sdk-go/", Version)},
	}

	// DefaultMockHost can be used for test assertions
	DefaultMockHost = "mock.elastic.co"
)
View Source
var DefaultBasePath = client.DefaultBasePath

DefaultBasePath is used as the base prefix for the API.

View Source
var (
	// DefaultTimeout is used when TransportConfig.Transport is not specified.
	DefaultTimeout = 30 * time.Second
)
View Source
var DefaultTransport = new(ErrCatchTransport)

DefaultTransport can be used by clients which rely on the apierror.Unwrap Can obtain the underlying http.Response is returned with a StatusCode not defined within the swagger spec from which the models have been generated. Meaning this is a small hack which allows http.Response.Body to be accessed. See pkg/api/apierror for details on how apierror.Unwrap works. Note that using this variable directly won't allow any of the http.Transport settings to be overridden. To customize the transport further, please use NewTransport()

View Source
var DefaultUserAgent = "cloud-sdk-go/" + Version

DefaultUserAgent is used in UserAgentTransport when the agent is not set. It defaults to the project name + the current committed version.

Functions

func AddTypeConsumers

func AddTypeConsumers(rtime *client.Runtime) *client.Runtime

AddTypeConsumers adds the missing consumers and producers to the client.Runtime. Even though a pointer is passed it is returned too.

func GetContextRegion

func GetContextRegion(ctx context.Context) (string, bool)

GetContextRegion returns the region from a specified context, if any.

func LoginUser

func LoginUser(instance *API, writer io.Writer) error

LoginUser logs in a user when its AuthWriter is of type *auth.UserLogin. Additionally, calls the RefreshToken pethod in *auth.UserLogin launching a background Go routine which will keep the JWT token always valid.

func NewTransport

func NewTransport(rt http.RoundTripper, cfg TransportConfig) (http.RoundTripper, error)

NewTransport constructs a new http.RoundTripper from its config.

func ReturnErrOnly

func ReturnErrOnly(_ interface{}, err error) error

ReturnErrOnly is used to strip the first return argument of a function call

func UnwrapError

func UnwrapError(err error) error

UnwrapError Deprecated: unpacks an error message returned from a client API call. Deprecated: in favour of apierror.Wrap().

func WithRegion

func WithRegion(ctx context.Context, region string) context.Context

WithRegion creates a new context with a region value. This needs to be used when calling any auto-generated platform APIs directly. client..Stack.GetVersionStacks(stack.NewGetVersionStacksParams().

WithContext(api.WithRegion(context.Background(), "us-east-1")), nil)

Types

type API

type API struct {
	V1API      *client.Rest
	AuthWriter auth.Writer
}

API contains all of the API clients and authentication objects necessary for the EC API

func NewAPI

func NewAPI(c Config) (*API, error)

NewAPI initializes the API clients from an API config that it receives

func NewDebugMock

func NewDebugMock(o io.Writer, res ...mock.Response) *API

NewDebugMock creates a new api.API from a list of Responses. Defaults to a dummy APIKey for authentication, which is not checked. Additionally adds the DebugTransport so that the responses go to the configured io.Writer.

func NewMock

func NewMock(res ...mock.Response) *API

NewMock creates a new api.API from a list of Responses. Defaults to a dummy APIKey for authentication, which is not checked

type AuthWriter

type AuthWriter auth.Writer

AuthWriter wraps the runtime.ClientAuthInfoWriter interface adding a method to Auth generic http.Request. This type alias is used to maintain API compatibility.

type CloudClientRuntime

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

CloudClientRuntime wraps runtimeclient.Runtime to allow operations to use a transport depending on the operation which is being performed.

func NewCloudClientRuntime

func NewCloudClientRuntime(c Config) (*CloudClientRuntime, error)

NewCloudClientRuntime creates a CloudClientRuntime from the config. Using the configured region (if any) to instantiate two different client.Runtime. If there's no region specified in the config then both are regionless.

func (*CloudClientRuntime) Submit

func (r *CloudClientRuntime) Submit(op *runtime.ClientOperation) (interface{}, error)

Submit calls either the regionRuntime or the regionless runtime depending on which operation is being performed. Any API call to /deployments will use a regionless runtime while all others will use a region (if specified).

type Config

type Config struct {
	Client     *http.Client
	AuthWriter auth.Writer
	Host       string

	// SkipTLSVerify will not perform any TLS/SSL verification.
	SkipTLSVerify bool

	// SkipLogin skips validating the user / password with the instanced API
	// when AuthWriter equals *auth.UserLogin.
	SkipLogin bool

	// ErrorDevice is used to send errors to prevent cluttering the output.
	ErrorDevice io.Writer

	VerboseSettings

	// Timeout for all of the API calls performed through the API structure.
	Timeout time.Duration

	// UserAgent if specified, it sets the user agent on all outgoing requests.
	UserAgent string

	// Number of retries to perform on request timeout.
	Retries int

	// Cooldown time between retries.
	RetryBackoff time.Duration
}

Config contains the API config

func (*Config) Validate

func (c *Config) Validate() error

Validate returns an error if the config is invalid

type CustomTransport

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

CustomTransport is the cloud-sdk-go custom transport which handles all the add-ons for http request and responses. It supports: * Adding a custom UserAgent header to all outgoing requests. * Writing a trail of the request / response flow to a device (verbose). * Adding support for request retries on timeout with a backoff period.

func NewCustomTransport

func NewCustomTransport(cfg CustomTransportCfg) (*CustomTransport, error)

NewCustomTransport creates a new CustomTransport. See the structure's Goddoc to learn about what it does.

func (*CustomTransport) RoundTrip

func (t *CustomTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip wraps http.DefaultTransport.RoundTrip to keep track of the current request.

type CustomTransportCfg

type CustomTransportCfg struct {
	// RoundTripper to use for http calls.
	RoundTripper http.RoundTripper

	// UserAgent if specified, it sets the user agent on all outgoing requests.
	UserAgent string

	// Number of retries to perform on request timeout.
	Retries int

	// Cooldown time between retried requests.
	Backoff time.Duration

	// Verbose settings
	Verbose    bool
	RedactAuth bool
	Writer     io.Writer
}

CustomTransportCfg is used to configure a CustomTransport.

type DebugTransport

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

DebugTransport Deprecated: is an http.RoundTripper that keeps track of the in-flight request and implements hooks to report HTTP tracing events.

func NewDebugTransport

func NewDebugTransport(transport http.RoundTripper, o io.Writer, obscure bool) *DebugTransport

NewDebugTransport Deprecated: factory for DebugTransport.

func (*DebugTransport) RoundTrip

func (t *DebugTransport) RoundTrip(req *http.Request) (res *http.Response, err error)

RoundTrip Deprecated: wraps http.DefaultTransport.RoundTrip to keep track of the current request.

type ErrCatchTransport

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

ErrCatchTransport Deprecated: is an http.RoundTripper that which allows the http.Response to be accessed in certain types of wrapped errors returned by autogenerated code. See pkg/api/apierror for details on how apierror.Unwrap works.

func NewErrCatchTransport

func NewErrCatchTransport(rt http.RoundTripper) *ErrCatchTransport

NewErrCatchTransport Deprecated: initializes an ErrCatchTransport. See GoDoc for more help on this type.

func (*ErrCatchTransport) RoundTrip

func (e *ErrCatchTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip Deprecated: wraps http.DefaultTransport.RoundTrip to keep track of the current request.

type TransportConfig

type TransportConfig struct {
	// When SkipTLSVerify the TLS verification is completely skipped.
	SkipTLSVerify bool

	// ErrorDevice where any error or notices will be sent.
	ErrorDevice io.Writer

	// Can enable a debug RoundTripper which dumps the request and responses to
	// the configured device.
	VerboseSettings

	// Timeout for the Transport net.Dialer.
	Timeout time.Duration

	// UserAgent if specified, it sets the user agent on all outgoing requests.
	UserAgent string

	// Number of retries to perform on request timeout.
	Retries int

	// Cooldown time between retries.
	RetryBackoff time.Duration
}

TransportConfig is meant to be used so an http.RoundTripper is constructed with the appropriate settings.

type UserAgentTransport

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

UserAgentTransport Deprecated: wraps an http.RoundTripper and adds an User -Agent header to all requests which are processed through the structure.

func NewUserAgentTransport

func NewUserAgentTransport(rt http.RoundTripper, agent string) *UserAgentTransport

NewUserAgentTransport Deprecated: initializes a new UserAgentTransport

func (*UserAgentTransport) RoundTrip

func (ua *UserAgentTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip Deprecated: wraps http.DefaultTransport.RoundTrip to keep track of the current request.

type VerboseSettings

type VerboseSettings struct {
	Device  io.Writer
	Verbose bool

	// RedactAuth replaces the contents of the Authorization header with:
	// "[REDACTED]".
	RedactAuth bool
}

VerboseSettings define the behaviour of verbosity.

func (VerboseSettings) Validate

func (settings VerboseSettings) Validate() error

Validate ensures the settings are usable.

Directories

Path Synopsis
Package deploymentapi contains curated functions which iteract with the deployments API, exposing an API which its usage is preferred over the direct client calls.
Package deploymentapi contains curated functions which iteract with the deployments API, exposing an API which its usage is preferred over the direct client calls.
depresourceapi
Package depresourceapi contains curated functions which iteract with the deployment resources API, exposing an API which its usage is preferred over the direct client calls.
Package depresourceapi contains curated functions which iteract with the deployment resources API, exposing an API which its usage is preferred over the direct client calls.
noteapi
Package noteapi contains curated functions which iteract with the deployment notes API, exposing an API which its usage is preferred over the direct client calls.
Package noteapi contains curated functions which iteract with the deployment notes API, exposing an API which its usage is preferred over the direct client calls.
Package mock provides functions and types to help test and stub external calls that the API structures would otherwise perform causing external calls through the network.
Package mock provides functions and types to help test and stub external calls that the API structures would otherwise perform causing external calls through the network.
snaprepoapi
Package snaprepoapi contains the a set of functions to interact with the platform repositories
Package snaprepoapi contains the a set of functions to interact with the platform repositories
Package userapi contains the methods required to manage platform users.
Package userapi contains the methods required to manage platform users.
authapi
Package userauthapi contains the self service logic required to manage a user's authentication settings, such as API keys.
Package userauthapi contains the self service logic required to manage a user's authentication settings, such as API keys.
authapi/adminapi
Package userauthadminapi contains the logic required to manage a user's authentication settings, such as API keys.
Package userauthadminapi contains the logic required to manage a user's authentication settings, such as API keys.

Jump to

Keyboard shortcuts

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