rest

package
v0.0.0-...-a134451 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2024 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultQPS   float32 = 5.0
	DefaultBurst int     = 10
)

Variables

This section is empty.

Functions

func DefaultServerURL

func DefaultServerURL(host, apiPath string, groupVersion schema.GroupVersion, defaultTLS bool) (*url.URL, string, error)

DefaultServerURL converts a host, host:port, or URL string to the default base server API path to use with a Client at a given API version following the standard conventions for a Kubernetes API.

func DefaultUserAgent

func DefaultUserAgent() string

DefaultUserAgent returns a User-Agent string built from static global vars.

func DefaultVersionedAPIPath

func DefaultVersionedAPIPath(apiPath string, groupVersion schema.GroupVersion) string

DefaultVersionedAPIPath constructs the default path for the given group version, assuming the given API path, following the standard conventions of the Kubernetes API.

func HTTPClientFor

func HTTPClientFor(config *Config) (*http.Client, error)

HTTPClientFor returns an http.Client that will provide the authentication or transport level security defined by the provided Config. Will return the default http.DefaultClient if no special case behavior is needed.

Types

type BackoffManager

type BackoffManager interface {
	UpdateBackoff(actualUrl *url.URL, err error, responseCode int)
	CalculateBackoff(actualUrl *url.URL) time.Duration
	Sleep(d time.Duration)
}

type ClientContentConfig

type ClientContentConfig struct {
	// AcceptContentTypes specifies the types the client will accept and is optional.
	// If not set, ContentType will be used to define the Accept header
	AcceptContentTypes string
	// ContentType specifies the wire format used to communicate with the server.
	// This value will be set as the Accept header on requests made to the server if
	// AcceptContentTypes is not set, and as the default content type on any object
	// sent to the server. If not set, "application/json" is used.
	ContentType string
	// GroupVersion is the API version to talk to. Must be provided when initializing
	// a RESTClient directly. When initializing a Client, will be set with the default
	// code version. This is used as the default group version for VersionedParams.
	GroupVersion schema.GroupVersion
	// Negotiator is used for obtaining encoders and decoders for multiple
	// supported media types.
	Negotiator runtime.ClientNegotiator
	// BearerToken
	BearerToken string
}

type Config

type Config struct {
	// Host must be a host string, a host:port pair, or a URL to the base of the apiserver.
	// If a URL is given then the (optional) Path of that URL represents a prefix that must
	// be appended to all request URIs used to access the apiserver. This allows a frontend
	// proxy to easily relocate all of the apiserver endpoints.
	Host string
	// APIPath is a sub-path that points to an API root.
	APIPath string

	// ContentConfig contains settings that affect how objects are transformed when
	// sent to the server.
	ContentConfig

	// Server requires Basic authentication
	Username string
	Password string `datapolicy:"password"`

	// Server requires Bearer authentication. This client will not attempt to use
	// refresh tokens for an OAuth2 flow.
	BearerToken string `datapolicy:"token"`

	// Path to a file containing a BearerToken.
	// If set, the contents are periodically read.
	// The last successfully read value takes precedence over BearerToken.
	BearerTokenFile string

	// Impersonate is the configuration that RESTClient will use for impersonation.
	Impersonate ImpersonationConfig

	// UserAgent is an optional field that specifies the caller of this request.
	UserAgent string

	// DisableCompression bypasses automatic GZip compression requests to the
	// server.
	DisableCompression bool

	// Transport may be used for custom HTTP behavior. This attribute may not
	// be specified with the TLS client certificate options. Use WrapTransport
	// to provide additional per-server middleware behavior.
	Transport http.RoundTripper

	// QPS indicates the maximum QPS to the master from this client.
	// If it's zero, the created RESTClient will use DefaultQPS: 5
	QPS float32

	// Maximum burst for throttle.
	// If it's zero, the created RESTClient will use DefaultBurst: 10.
	Burst int

	// Rate limiter for limiting connections to the master from this client. If present overwrites QPS/Burst
	RateLimiter flowcontrol.RateLimiter

	// The maximum length of time to wait before giving up on a server request. A value of zero means no timeout.
	Timeout time.Duration

	// Dial specifies the dial function for creating unencrypted TCP connections.
	Dial func(ctx context.Context, network, address string) (net.Conn, error)

	// Proxy is the proxy func to be used for all requests made by this
	// transport. If Proxy is nil, http.ProxyFromEnvironment is used. If Proxy
	// returns a nil *URL, no proxy is used.
	//
	// socks5 proxying does not currently support spdy streaming endpoints.
	Proxy func(*http.Request) (*url.URL, error)
}

Config holds the common attributes that can be passed to a Kubernetes client on initialization.

type ContentConfig

type ContentConfig struct {
	// AcceptContentTypes specifies the types the client will accept and is optional.
	// If not set, ContentType will be used to define the Accept header
	AcceptContentTypes string
	// ContentType specifies the wire format used to communicate with the server.
	// This value will be set as the Accept header on requests made to the server, and
	// as the default content type on any object sent to the server. If not set,
	// "application/json" is used.
	ContentType string
	// GroupVersion is the API version to talk to. Must be provided when initializing
	// a RESTClient directly. When initializing a Client, will be set with the default
	// code version.
	GroupVersion *schema.GroupVersion
	// NegotiatedSerializer is used for obtaining encoders and decoders for multiple
	// supported media types.
	NegotiatedSerializer runtime.NegotiatedSerializer
}

type ErrorReporter

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

ErrorReporter converts generic errors into runtime.Object errors without requiring the caller to take a dependency on meta/v1 (where Status lives). This prevents circular dependencies in core watch code.

func NewClientErrorReporter

func NewClientErrorReporter(code int, verb string, reason string) *ErrorReporter

NewClientErrorReporter will respond with valid v1.Status objects that report unexpected server responses. Primarily used by watch to report errors when we attempt to decode a response from the server and it is not in the form we expect. Because watch is a dependency of the core api, we can't return meta/v1.Status in that package and so much inject this interface to convert a generic error as appropriate. The reason is passed as a unique status cause on the returned status, otherwise the generic "ClientError" is returned.

func (*ErrorReporter) AsObject

func (r *ErrorReporter) AsObject(err error) runtime.Object

AsObject returns a valid error runtime.Object (a v1.Status) for the given error, using the code and verb of the reporter type. The error is set to indicate that this was an unexpected server response.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient is an interface for testing a request object.

type ImpersonationConfig

type ImpersonationConfig struct {
	// UserName is the username to impersonate on each request.
	UserName string
	// UID is a unique value that identifies the user.
	UID string
	// Groups are the groups to impersonate on each request.
	Groups []string
	// Extra is a free-form field which can be used to link some authentication information
	// to authorization information.  This field allows you to impersonate it.
	Extra map[string][]string
}

ImpersonationConfig has all the available impersonation options

type Interface

type Interface interface {
	GetRateLimiter() flowcontrol.RateLimiter
	Verb(verb string) *Request
	Post() *Request
	Put() *Request
	Patch(pt string) *Request
	Get() *Request
	Delete() *Request
	APIVersion() schema.GroupVersion
}

type IsRetryableErrorFunc

type IsRetryableErrorFunc func(request *http.Request, err error) bool

IsRetryableErrorFunc allows the client to provide its own function that determines whether the specified err from the server is retryable.

request: the original request sent to the server err: the server sent this error to us

The function returns true if the error is retryable and the request can be retried, otherwise it returns false. We have four mode of communications - 'Stream', 'Watch', 'Do' and 'DoRaw', this function allows us to customize the retryability aspect of each.

func (IsRetryableErrorFunc) IsErrorRetryable

func (r IsRetryableErrorFunc) IsErrorRetryable(request *http.Request, err error) bool

type NoBackoff

type NoBackoff struct {
}

NoBackoff is a stub implementation, can be used for mocking or else as a default.

func (*NoBackoff) CalculateBackoff

func (n *NoBackoff) CalculateBackoff(_ *url.URL) time.Duration

func (*NoBackoff) Sleep

func (n *NoBackoff) Sleep(d time.Duration)

func (*NoBackoff) UpdateBackoff

func (n *NoBackoff) UpdateBackoff(_ *url.URL, _ error, _ int)

type RESTClient

type RESTClient struct {

	// Set specific behavior of the client.  If not set http.DefaultClient will be used.
	Client *http.Client
	// contains filtered or unexported fields
}

func NewRESTClient

func NewRESTClient(baseURL *url.URL, versionedAPIPath string, config ClientContentConfig, rateLimiter flowcontrol.RateLimiter, client *http.Client) (*RESTClient, error)

NewRESTClient creates a new RESTClient. This client performs generic REST functions such as Get, Put, Post, and Delete on specified paths.

func RESTClientFor

func RESTClientFor(config *Config) (*RESTClient, error)

func RESTClientForConfigAndClient

func RESTClientForConfigAndClient(config *Config, httpClient *http.Client) (*RESTClient, error)

RESTClientForConfigAndClient returns a RESTClient that satisfies the requested attributes on a client Config object. Unlike RESTClientFor, RESTClientForConfigAndClient allows to pass an http.Client that is shared between all the API Groups and Versions. Note that the http client takes precedence over the transport values configured. The http client defaults to the `http.DefaultClient` if nil.

func (*RESTClient) APIVersion

func (c *RESTClient) APIVersion() schema.GroupVersion

func (*RESTClient) Delete

func (c *RESTClient) Delete() *Request

func (*RESTClient) Get

func (c *RESTClient) Get() *Request

func (*RESTClient) GetRateLimiter

func (c *RESTClient) GetRateLimiter() flowcontrol.RateLimiter

func (*RESTClient) Patch

func (c *RESTClient) Patch(pt string) *Request

func (*RESTClient) Post

func (c *RESTClient) Post() *Request

func (*RESTClient) Put

func (c *RESTClient) Put() *Request

func (*RESTClient) Verb

func (c *RESTClient) Verb(verb string) *Request

type Request

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

func NewRequest

func NewRequest(c *RESTClient) *Request

func NewRequestWithClient

func NewRequestWithClient(base *url.URL, versionedAPIPath string, content ClientContentConfig, client *http.Client) *Request

NewRequestWithClient creates a Request with an embedded RESTClient for use in test scenarios.

func (*Request) AbsPath

func (r *Request) AbsPath(segments ...string) *Request

AbsPath overwrites an existing path with the segments provided. Trailing slashes are preserved when a single segment is passed.

func (*Request) BackOff

func (r *Request) BackOff(manager BackoffManager) *Request

BackOff sets the request's backoff manager to the one specified, or defaults to the stub implementation if nil is provided

func (*Request) Body

func (r *Request) Body(obj interface{}) *Request

Body makes the request use obj as the body. Optional. If obj is a string, try to read a file of that name. If obj is a []byte, send it directly. If obj is an io.Reader, use it directly. If obj is a runtime.Object, marshal it correctly, and set Content-Type header. If obj is a runtime.Object and nil, do nothing. Otherwise, set an error.

func (*Request) Do

func (r *Request) Do(ctx context.Context) Result

Do formats and executes the request. Returns a Result object for easy response processing.

Error type:

  • If the server responds with a status: *errors.StatusError or *errors.UnexpectedObjectError
  • http.Client.Do errors are returned directly.

func (*Request) DoRaw

func (r *Request) DoRaw(ctx context.Context) ([]byte, error)

DoRaw executes the request but does not process the response body.

func (*Request) MaxRetries

func (r *Request) MaxRetries(maxRetries int) *Request

MaxRetries makes the request use the given integer as a ceiling of retrying upon receiving "Retry-After" headers and 429 status-code in the response. The default is 10 unless this function is specifically called with a different value. A zero maxRetries prevent it from doing retires and return an error immediately.

func (*Request) Name

func (r *Request) Name(resourceName string) *Request

Name sets the name of a resource to access (<resource>/[ns/<namespace>/]<name>)

func (*Request) Param

func (r *Request) Param(paramName, s string) *Request

Param creates a query parameter with the given string value.

func (*Request) Prefix

func (r *Request) Prefix(segments ...string) *Request

Prefix adds segments to the relative beginning to the request path. These items will be placed before the optional Namespace, Resource, or Name sections. Setting AbsPath will clear any previously set Prefix segments

func (*Request) RequestURI

func (r *Request) RequestURI(uri string) *Request

RequestURI overwrites existing path and parameters with the value of the provided server relative URI.

func (*Request) Resource

func (r *Request) Resource(resource string) *Request

Resource sets the resource to access (<resource>/[ns/<namespace>/]<name>)

func (*Request) SetHeader

func (r *Request) SetHeader(key string, values ...string) *Request

func (*Request) SpecificallyVersionedParams

func (r *Request) SpecificallyVersionedParams(obj runtime.Object, codec runtime.ParameterCodec, version schema.GroupVersion) *Request

func (*Request) Stream

func (r *Request) Stream(ctx context.Context) (io.ReadCloser, error)

Stream formats and executes the request, and offers streaming of the response. Returns io.ReadCloser which could be used for streaming of the response, or an error Any non-2xx http status code causes an error. If we get a non-2xx code, we try to convert the body into an APIStatus object. If we can, we return that as an error. Otherwise, we create an error that lists the http status and the content of the response.

func (*Request) SubResource

func (r *Request) SubResource(subresources ...string) *Request

SubResource sets a sub-resource path which can be multiple segments after the resource name but before the suffix.

func (*Request) Suffix

func (r *Request) Suffix(segments ...string) *Request

Suffix appends segments to the end of the path. These items will be placed after the prefix and optional Namespace, Resource, or Name sections.

func (*Request) Throttle

func (r *Request) Throttle(limiter flowcontrol.RateLimiter) *Request

Throttle receives a rate-limiter and sets or replaces an existing request limiter

func (*Request) Timeout

func (r *Request) Timeout(d time.Duration) *Request

Timeout makes the request use the given duration as an overall timeout for the request. Additionally, if set passes the value as "timeout" parameter in URL.

func (*Request) URL

func (r *Request) URL() *url.URL

URL returns the current working URL.

func (*Request) Verb

func (r *Request) Verb(verb string) *Request

Verb sets the verb this request will use.

func (*Request) VersionedParams

func (r *Request) VersionedParams(obj runtime.Object, codec runtime.ParameterCodec) *Request

VersionedParams will take the provided object, serialize it to a map[string][]string using the implicit RESTClient API version and the default parameter codec, and then add those as parameters to the request. Use this to provide versioned query parameters from client libraries. VersionedParams will not write query parameters that have omitempty set and are empty. If a parameter has already been set it is appended to (Params and VersionedParams are additive).

func (*Request) Watch

func (r *Request) Watch(ctx context.Context) (watch.Interface, error)

Watch attempts to begin watching the requested location. Returns a watch.Interface, or an error.

type ResponseWrapper

type ResponseWrapper interface {
	DoRaw(context.Context) ([]byte, error)
	Stream(context.Context) (io.ReadCloser, error)
}

ResponseWrapper is an interface for getting a response. The response may be either accessed as a raw data (the whole output is put into memory) or as a stream.

type Result

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

Result contains the result of calling Request.Do().

func (Result) Error

func (r Result) Error() error

Error returns the error executing the request, nil if no error occurred. If the returned object is of type Status and has Status != StatusSuccess, the additional information in Status will be used to enrich the error. See the Request.Do() comment for what errors you might get.

func (Result) Get

func (r Result) Get() (runtime.Object, error)

Get returns the result as an object, which means it passes through the decoder. If the returned object is of type Status and has .Status != StatusSuccess, the additional information in Status will be used to enrich the error.

func (Result) Into

func (r Result) Into(obj runtime.Object) error

Into stores the result into obj, if possible. If obj is nil it is ignored. If the returned object is of type Status and has .Status != StatusSuccess, the additional information in Status will be used to enrich the error.

func (Result) Raw

func (r Result) Raw() ([]byte, error)

Raw returns the raw result.

func (Result) StatusCode

func (r Result) StatusCode(statusCode *int) Result

StatusCode returns the HTTP status code of the request. (Only valid if no error was returned.)

func (Result) WasCreated

func (r Result) WasCreated(wasCreated *bool) Result

WasCreated updates the provided bool pointer to whether the server returned 201 created or a different response.

type RetryAfter

type RetryAfter struct {
	// Wait is the duration the server has asked us to wait before
	// the next retry is initiated.
	// This is the value of the 'Retry-After' response header in seconds.
	Wait time.Duration

	// Attempt is the Nth attempt after which we have received a retryable
	// error or a 'Retry-After' response header from the server.
	Attempt int

	// Reason describes why we are retrying the request
	Reason string
}

RetryAfter holds information associated with the next retry.

type URLBackoff

type URLBackoff struct {
	// Uses backoff as underlying implementation.
	Backoff *flowcontrol.Backoff
}

URLBackoff struct implements the semantics on top of Backoff which we need for URL specific exponential backoff.

func (*URLBackoff) CalculateBackoff

func (b *URLBackoff) CalculateBackoff(actualUrl *url.URL) time.Duration

CalculateBackoff takes a url and back's off exponentially, based on its knowledge of existing failures.

func (*URLBackoff) Disable

func (b *URLBackoff) Disable()

Disable makes the backoff trivial, i.e., sets it to zero. This might be used by tests which want to run 1000s of mock requests without slowing down.

func (*URLBackoff) Sleep

func (b *URLBackoff) Sleep(d time.Duration)

func (*URLBackoff) UpdateBackoff

func (b *URLBackoff) UpdateBackoff(actualUrl *url.URL, err error, responseCode int)

UpdateBackoff updates backoff metadata

type WithRetry

type WithRetry interface {
	// IsNextRetry advances the retry counter appropriately
	// and returns true if the request should be retried,
	// otherwise it returns false, if:
	//  - we have already reached the maximum retry threshold.
	//  - the error does not fall into the retryable category.
	//  - the server has not sent us a 429, or 5xx status code and the
	//    'Retry-After' response header is not set with a value.
	//  - we need to seek to the beginning of the request body before we
	//    initiate the next retry, the function should log an error and
	//    return false if it fails to do so.
	//
	// restReq: the associated rest.Request
	// httpReq: the HTTP Request sent to the server
	// resp: the response sent from the server, it is set if err is nil
	// err: the server sent this error to us, if err is set then resp is nil.
	// f: a IsRetryableErrorFunc function provided by the client that determines
	//    if to err sent by the server is retryable.
	IsNextRetry(ctx context.Context, restReq *Request, httpReq *http.Request, resp *http.Response, err error, f IsRetryableErrorFunc) bool

	// Before should be invoked prior to each attempt, including
	// the first one. If an error is returned, the request should
	// be aborted immediately.
	//
	// Before may also be additionally responsible for preparing
	// the request for the next retry, namely in terms of resetting
	// the request body in case it has been read.
	Before(ctx context.Context, r *Request) error

	// After should be invoked immediately after an attempt is made.
	After(ctx context.Context, r *Request, resp *http.Response, err error)

	// WrapPreviousError wraps the error from any previous attempt into
	// the final error specified in 'finalErr', so the user has more
	// context why the request failed.
	// For example, if a request times out after multiple retries then
	// we see a generic context.Canceled or context.DeadlineExceeded
	// error which is not very useful in debugging. This function can
	// wrap any error from previous attempt(s) to provide more context to
	// the user. The error returned in 'err' must satisfy the
	// following conditions:
	//  a: errors.Unwrap(err) = errors.Unwrap(finalErr) if finalErr
	//     implements Unwrap
	//  b: errors.Unwrap(err) = finalErr if finalErr does not
	//     implements Unwrap
	//  c: errors.Is(err, otherErr) = errors.Is(finalErr, otherErr)
	WrapPreviousError(finalErr error) (err error)
}

WithRetry allows the client to retry a request up to a certain number of times Note that WithRetry is not safe for concurrent use by multiple goroutines without additional locking or coordination.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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