controller

package
v0.32.0-rc1 Latest Latest
Warning

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

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

Documentation

Index

Constants

View Source
const (
	// InProgressStateMessageFormat represents the message when resource is in progress state.
	InProgressStateMessageFormat = "The target resource is in progress state: %s."
)

Variables

View Source
var (
	// ContentTypeHeaderKey is the header key of Content-Type
	ContentTypeHeaderKey = http.CanonicalHeaderKey("Content-Type")

	// DefaultScheme is the default scheme used if there is no scheme in the URL.
	DefaultSheme = "http"
)
View Source
var (
	// ErrUnsupportedContentType represents the error of unsupported content-type.
	ErrUnsupportedContentType = errors.New("unsupported Content-Type")
	// ErrRequestedResourceDoesNotExist represents the error of resource that is requested not existing.
	ErrRequestedResourceDoesNotExist = errors.New("requested resource does not exist")
	// ErrETagsDoNotMatch represents the error of the eTag of the resource and the requested etag not matching.
	ErrETagsDoNotMatch = errors.New("etags do not match")
	// ErrResourceAlreadyExists represents the error of the resource being already existent at the moment.
	ErrResourceAlreadyExists = errors.New("resource already exists")
)

Functions

func BuildTrackedResource

func BuildTrackedResource(ctx context.Context) v1.TrackedResource

BuildTrackedResource takes in a context and returns a v1.TrackedResource object with the ID, Name, Type and Location fields populated from the context.

func GetNextLinkURL

func GetNextLinkURL(ctx context.Context, req *http.Request, paginationToken string) string

GetNextLinkUrl function returns the URL string by building a URL from the request and the pagination token.

func GetURLFromReqWithQueryParameters

func GetURLFromReqWithQueryParameters(req *http.Request, qps url.Values) *url.URL

GetURLFromReqWithQueryParameters function builds a URL from the request and query parameters

func ReadJSONBody

func ReadJSONBody(r *http.Request) ([]byte, error)

ReadJSONBody extracts the content from request - it reads the body of the request if the content type is "application/json". It returns the body as a byte array or an error if the content type is not supported or an error occurs while reading the body.

func UpdateSystemData

func UpdateSystemData(old v1.SystemData, new v1.SystemData) v1.SystemData

UpdateSystemData updates the system data fields in the old object with the new object's fields, backfilling the created fields if necessary.

func ValidateETag

func ValidateETag(armRequestContext v1.ARMRequestContext, etag string) error

ValidateETag checks the If-Match and If-None-Match headers of the ARMRequestContext against the provided etag, and returns an error if the etag does not match either header.

Types

type BaseController

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

BaseController is the base operation controller.

func NewBaseController

func NewBaseController(options Options) BaseController

NewBaseController creates BaseController instance.

func (*BaseController) DataProvider

DataProvider gets data storage provider for this controller.

func (*BaseController) GetResource

func (c *BaseController) GetResource(ctx context.Context, id string, out any) (etag string, err error)

GetResource gets a resource from data store for id, set the retrieved resource to out argument and returns the ETag of the resource and an error if one occurs.

func (*BaseController) KubeClient

func (b *BaseController) KubeClient() runtimeclient.Client

KubeClient gets Kubernetes client for this controller.

func (*BaseController) ResourceType

func (b *BaseController) ResourceType() string

ResourceType gets the resource type for this controller.

func (*BaseController) SaveResource

func (c *BaseController) SaveResource(ctx context.Context, id string, in any, etag string) (*store.Object, error)

SaveResource saves a resource to the data store with an ETag and returns a store object or an error if the save fails.

func (*BaseController) StatusManager

func (b *BaseController) StatusManager() sm.StatusManager

StatusManager gets the StatusManager of this controller.

func (*BaseController) StorageClient

func (b *BaseController) StorageClient() store.StorageClient

StorageClient gets storage client for this controller.

type Controller

type Controller interface {
	// Run executes the operation.
	Run(ctx context.Context, w http.ResponseWriter, req *http.Request) (rest.Response, error)
}

TODO: Remove Controller when all controller uses Operation Controller is an interface of each operation controller.

type DeleteFilter

type DeleteFilter[T any] func(ctx context.Context, oldResource *T, options *Options) (rest.Response, error)

DeleteFilter is a function that is executed as part of the controller lifecycle. DeleteFilters can be used to:

- Block deletion of a resource based on some arbitrary condition.

DeleteFilters should return a rest.Response to handle the request without allowing deletion to occur. Any errors returned will be treated as "unhandled" and logged before sending back an HTTP 500.

type Operation

type Operation[P interface {
	*T
	v1.ResourceDataModel
}, T any] struct {
	// contains filtered or unexported fields
}

Operation is the base operation controller.

func NewOperation

func NewOperation[P interface {
	*T
	v1.ResourceDataModel
}, T any](options Options, resourceOptions ResourceOptions[T]) Operation[P, T]

NewOperation creates BaseController instance.

func (*Operation[P, T]) AsyncOperationTimeout

func (b *Operation[P, T]) AsyncOperationTimeout() time.Duration

AsyncOperationTimeout returns the timeput for the operation.

func (*Operation[P, T]) ConstructAsyncResponse

func (c *Operation[P, T]) ConstructAsyncResponse(ctx context.Context, method, etag string, resource *T) (rest.Response, error)

ConstructAsyncResponse creates an asynchronous response for a given resource, method and etag. It converts the resource to the appropriate version and sets the response code to either Accepted or Created depending on the method. It also sets the RetryAfter value if it is specified in the resourceOptions. If an error occurs, it is returned to the caller.

func (*Operation[P, T]) ConstructSyncResponse

func (c *Operation[P, T]) ConstructSyncResponse(ctx context.Context, method, etag string, resource *T) (rest.Response, error)

ConstructSyncResponse constructs synchronous API response.

func (*Operation[P, T]) DataProvider

func (b *Operation[P, T]) DataProvider() dataprovider.DataStorageProvider

DataProvider gets the DataStorageProvider.

func (*Operation[P, T]) DeleteFilters

func (b *Operation[P, T]) DeleteFilters() []DeleteFilter[T]

DeleteFilters returns the set of filters to execute on delete operations.

func (*Operation[P, T]) GetResource

func (c *Operation[P, T]) GetResource(ctx context.Context, id resources.ID) (out *T, etag string, err error)

GetResource is the helper to get the resource via storage client.

func (*Operation[P, T]) GetResourceFromRequest

func (c *Operation[P, T]) GetResourceFromRequest(ctx context.Context, req *http.Request) (*T, error)

GetResourceFromRequest extracts and deserializes from HTTP request body to datamodel.

func (*Operation[P, T]) Options

func (b *Operation[P, T]) Options() *Options

Options gets the options for this controller.

func (*Operation[P, T]) PrepareAsyncOperation

func (c *Operation[P, T]) PrepareAsyncOperation(ctx context.Context, newResource *T, initialState v1.ProvisioningState, asyncTimeout time.Duration, etag *string) (rest.Response, error)

PrepareAsyncOperation saves the initial state and queue the async operation.

func (*Operation[P, T]) PrepareResource

func (c *Operation[P, T]) PrepareResource(ctx context.Context, req *http.Request, newResource *T, oldResource *T, etag string) (rest.Response, error)

PrepareResource validates incoming request and populate the metadata to new resource.

func (*Operation[P, T]) RequestConverter

func (b *Operation[P, T]) RequestConverter() v1.ConvertToDataModel[T]

RequestConverter returns the request converter function for this controller.

func (*Operation[P, T]) ResourceType

func (b *Operation[P, T]) ResourceType() string

ResourceType gets the resource type for this controller.

func (*Operation[P, T]) ResponseConverter

func (b *Operation[P, T]) ResponseConverter() v1.ConvertToAPIModel[T]

ResponseConverter returns the response converter function for this controller.

func (*Operation[P, T]) SaveResource

func (c *Operation[P, T]) SaveResource(ctx context.Context, id string, in *T, etag string) (string, error)

SaveResource is the helper to save the resource via storage client.

func (*Operation[P, T]) StatusManager

func (b *Operation[P, T]) StatusManager() sm.StatusManager

DeploymentProcessor gets the deployment processor for this controller.

func (*Operation[P, T]) StorageClient

func (b *Operation[P, T]) StorageClient() store.StorageClient

StorageClient gets storage client for this controller.

func (*Operation[P, T]) UpdateFilters

func (b *Operation[P, T]) UpdateFilters() []UpdateFilter[T]

DeleteFilters returns the set of filters to execute on update (PUT/PATCH) operations.

type Options

type Options struct {
	// Address is the listening address where the controller is running, including the hostname and port.
	//
	// For example: "localhost:8080".
	//
	// The listening address is provided so that it can be used when constructing URLs.
	Address string

	// PathBase is a URL path prefix that is applied to all requests and should not be considered part of request path
	// for determining routing or parsing of IDs. It must start with a slash or be empty.
	//
	// For example consider the following examples that match the resource ID "/planes/radius/local":
	//
	// - base path: "/apis/api.ucp.dev/v1alpha3" and URL path: "/apis/api.ucp.dev/planes/radius/local".
	// - base path: "" (empty) and request path: "/planes/radius/local".
	//
	// Code that needs to process the URL path should ignore the base path prefix when parsing the URL path.
	// Code that needs to construct a URL path should use the base path prefix when constructing the URL path.
	PathBase string

	// StorageClient is the data storage client.
	StorageClient store.StorageClient

	// DataProvider is the data storage provider.
	DataProvider dataprovider.DataStorageProvider

	// KubeClient is the Kubernetes controller runtime client.
	KubeClient runtimeclient.Client

	// ResourceType is the string that represents the resource type. May be empty if the controller
	// does not represent a single type of resource.
	ResourceType string

	// StatusManager is the async operation status manager.
	StatusManager sm.StatusManager
}

Options represents controller options.

type ResourceOptions

type ResourceOptions[T any] struct {
	// RequestConverter is the request converter.
	RequestConverter v1.ConvertToDataModel[T]

	// ResponseConverter is the response converter.
	ResponseConverter v1.ConvertToAPIModel[T]

	// DeleteFilters is a slice of filters that execute prior to deleting a resource.
	DeleteFilters []DeleteFilter[T]

	// UpdateFilters is a slice of filters that execute prior to updating a resource.
	UpdateFilters []UpdateFilter[T]

	// AsyncOperationTimeout is the default timeout duration of async put operation.
	AsyncOperationTimeout time.Duration

	// AsyncOperationRetryAfter is the value of the Retry-After header that will be used for async operations.
	// If this is 0 then the default value of v1.DefaultRetryAfter will be used. Consider setting this to a smaller
	// value like 5 seconds if your operations will complete quickly.
	AsyncOperationRetryAfter time.Duration

	// ListRecursiveQuery specifies whether store query should be recursive or not. This should be set to true when the
	// scope of the list operation does not match the scope of the underlying resource type.
	//
	// This is ignored by non-list controllers.
	ListRecursiveQuery bool
}

ResourceOptions represents the options and filters for resource.

type UpdateFilter

type UpdateFilter[T any] func(ctx context.Context, newResource *T, oldResource *T, options *Options) (rest.Response, error)

UpdateFilter is a function that is executed as part of the controller lifecycle. UpdateFilters can be used to:

- Set internal state of a resource data model prior to saving. - Perform semantic validation based on the old state of a resource. - Perform semantic validation based on external state.

UpdateFilters should return a rest.Response to handle the request without allowing updates to occur. Any errors returned will be treated as "unhandled" and logged before sending back an HTTP 500.

Jump to

Keyboard shortcuts

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