k8s

package
v0.15.4 Latest Latest
Warning

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

Go to latest
Published: Apr 25, 2024 License: Apache-2.0 Imports: 34 Imported by: 4

Documentation

Overview

Package k8s contains an implementation of the resource.Client, resource.SchemalessClient, and resource.ClientGenerator interfaces which uses a standard kubernetes API server as its storage system API server.

Instrumentation

This package is instrumented for logs, metrics, and traces.

## Logs

TODO - info here.

## Metrics

TODO - info here.

## Traces

Spans are generated for all interactions with the kubernetes API Server, regardless of the client used. Tracing uses OpenTelemetry, and the Tracer used can be set with k8s.SetTracer (by default, the global Tracer is used). Spans attributes follow the semantic conventions for HTTP spans set by the OpenTelemetry Semantic Conventions for HTTP Spans: https://github.com/open-telemetry/semantic-conventions/blob/098db1ca510da01fe941f6c6308aad5000def910/docs/http/http-spans.md. Currently, the k8s package uses an underlying kubernetes client-go rest.Interface REST client, which does not have tracing instrumentation. This means that retries which are configured in the kubernetes rest.Config used to generate the Client will not be known to spans generated by the k8s.Client, and the entire set of requests will be treated as one HTTP request for the purposes of tracing.

Index

Constants

View Source
const (

	// AnnotationPrefix is the prefix used in annotations which contain grafana kind metadata
	AnnotationPrefix = "grafana.com/"
)
View Source
const (
	// ErrReasonFieldNotAllowed is the "field not allowed" admission error reason string
	ErrReasonFieldNotAllowed = "field_not_allowed"
)

Variables

This section is empty.

Functions

func DeepCopyObject

func DeepCopyObject(in any) runtime.Object

DeepCopyObject is an implementation of the receiver method required for implementing runtime.Object.

func GetTracer added in v0.11.0

func GetTracer() trace.Tracer

GetTracer returns the trace.Tracer set by SetTracer, or a tracer generated from otel.GetTracerProvider().Tracer("k8s") if none has been set.

func SetTracer added in v0.11.0

func SetTracer(t trace.Tracer)

SetTracer sets the tracer used for generating spans for this package

func ValidateNamespace

func ValidateNamespace(namespace string) error

ValidateNamespace validates that `namespace` is a valid Kubernetes namespace name.

Types

type Client

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

Client is a kubernetes-specific implementation of resource.Client, using custom resource definitions. A Client is specific to the Schema it was created with. New Clients should only be created via the ClientRegistry.ClientFor method.

func (*Client) Create

func (c *Client) Create(ctx context.Context, identifier resource.Identifier, obj resource.Object,
	options resource.CreateOptions) (resource.Object, error)

Create creates a new resource, and returns the resulting created resource

func (*Client) CreateInto

func (c *Client) CreateInto(ctx context.Context, identifier resource.Identifier, obj resource.Object,
	_ resource.CreateOptions, into resource.Object) error

CreateInto creates a new resource, and marshals the resulting created resource into `into`

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, identifier resource.Identifier) error

Delete deletes the specified resource

func (*Client) Get

func (c *Client) Get(ctx context.Context, identifier resource.Identifier) (resource.Object, error)

Get gets a resource of the client's internal Schema-derived kind, with the provided identifier

func (*Client) GetInto

func (c *Client) GetInto(ctx context.Context, identifier resource.Identifier, into resource.Object) error

GetInto gets a resource of the client's internal Schema-derived kind, with the provided identifier, and marshals it into `into`

func (*Client) List

func (c *Client) List(ctx context.Context, namespace string, options resource.ListOptions) (
	resource.ListObject, error)

List lists resources in the provided namespace. For resources with a schema.Scope() of ClusterScope, `namespace` must be resource.NamespaceAll

func (*Client) ListInto

func (c *Client) ListInto(ctx context.Context, namespace string, options resource.ListOptions,
	into resource.ListObject) error

ListInto lists resources in the provided namespace, and unmarshals the response into the provided resource.ListObject

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, identifier resource.Identifier, patch resource.PatchRequest,
	options resource.PatchOptions) (resource.Object, error)

Patch performs a JSON Patch on the provided resource, and returns the updated object

func (*Client) PatchInto

func (c *Client) PatchInto(ctx context.Context, identifier resource.Identifier, patch resource.PatchRequest,
	options resource.PatchOptions, into resource.Object) error

PatchInto performs a JSON Patch on the provided resource, and marshals the updated version into the `into` field

func (*Client) PrometheusCollectors added in v0.12.0

func (c *Client) PrometheusCollectors() []prometheus.Collector

Metrics returns the prometheus collectors used by this Client for registration with a prometheus exporter

func (*Client) RESTClient

func (c *Client) RESTClient() rest.Interface

RESTClient returns the underlying rest.Interface used to communicate with kubernetes

func (*Client) Update

func (c *Client) Update(ctx context.Context, identifier resource.Identifier, obj resource.Object,
	options resource.UpdateOptions) (resource.Object, error)

Update updates the provided resource, and returns the updated resource from kubernetes

func (*Client) UpdateInto

func (c *Client) UpdateInto(ctx context.Context, identifier resource.Identifier, obj resource.Object,
	options resource.UpdateOptions, into resource.Object) error

UpdateInto updates the provided resource, and marshals the updated resource from kubernetes into `into`

func (*Client) Watch

func (c *Client) Watch(ctx context.Context, namespace string, options resource.WatchOptions) (
	resource.WatchResponse, error)

Watch makes a watch request for the namespace, and returns a WatchResponse which wraps a kubernetes watch.Interface. The underlying watch.Interface can be accessed using KubernetesWatch()

type ClientConfig

type ClientConfig struct {
	// CustomMetadataIsAnyType tells the Client if the custom metadata of an object can be of any type, or is limited to only strings.
	// By default, this is false, with which the client will assume custom metadata is only a string type,
	// and not invoke reflection to turn the type into a string when encoding to the underlying kubernetes annotation storage.
	// If set to true, the client will use reflection to get the type of each custom metadata field,
	// and convert it into a string (structs and lists will be converted into stringified JSON).
	// Keep in mind that the metadata bytes blob used in unmarshaling will always have custom metadata as string types,
	// regardless of how this value is set, so make sure your resource.Object implementations can handle
	// turning strings into non-string types when unmarshaling if you plan to have custom metadata keys which have non-string values.
	CustomMetadataIsAnyType bool

	MetricsConfig metrics.Config
}

ClientConfig is the configuration object for creating Clients.

func DefaultClientConfig

func DefaultClientConfig() ClientConfig

DefaultClientConfig returns a ClientConfig using defaults that assume you have used the SDK codegen tooling

type ClientRegistry

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

ClientRegistry implements resource.ClientGenerator, and keeps a cache of kubernetes clients based on GroupVersion (the largest unit a kubernetes rest.RESTClient can work with).

func NewClientRegistry

func NewClientRegistry(kubeCconfig rest.Config, clientConfig ClientConfig) *ClientRegistry

NewClientRegistry returns a new ClientRegistry which will make Client structs using the provided rest.Config

func (*ClientRegistry) ClientFor

func (c *ClientRegistry) ClientFor(sch resource.Kind) (resource.Client, error)

ClientFor returns a Client with the underlying rest.Interface being a cached one for the Schema's GroupVersion. If no such client is cached, it creates a new one with the stored config.

func (*ClientRegistry) PrometheusCollectors added in v0.12.0

func (c *ClientRegistry) PrometheusCollectors() []prometheus.Collector

PrometheusCollectors returns the prometheus metric collectors used by all clients generated by this ClientRegistry to allow for registration

type CodecDecoder added in v0.15.0

type CodecDecoder struct {
	SampleObject resource.Object
	Codec        resource.Codec
	Decoder      func([]byte, any) error
}

CodecDecoder implements runtime.Serializer and works with Untyped* objects to implement runtime.Object

func (*CodecDecoder) Decode added in v0.15.0

Decode decodes the provided data into UntypedWatchObject or UntypedObjectWrapper

func (*CodecDecoder) Encode added in v0.15.0

func (c *CodecDecoder) Encode(obj runtime.Object, w io.Writer) error

Encode json-encodes the provided object

func (*CodecDecoder) Identifier added in v0.15.0

func (*CodecDecoder) Identifier() runtime.Identifier

Identifier returns "generic-json-decoder"

type Converter added in v0.13.0

type Converter interface {
	// Convert converts a raw kubernetes kind into the target APIVersion.
	// The RawKind argument will contain kind information and the raw kubernetes object,
	// and the returned bytes are expected to be a raw kubernetes object of the same kind and targetAPIVersion
	// APIVersion. The returned kubernetes object MUST have an apiVersion that matches targetAPIVersion.
	Convert(obj RawKind, targetAPIVersion string) ([]byte, error)
}

Converter describes a type which can convert a kubernetes kind from one API version to another. Typically there is one converter per-kind, but a single converter can also handle multiple kinds.

type CustomResourceDefinition

type CustomResourceDefinition struct {
	metav1.TypeMeta   `json:",inline" yaml:",inline"`
	metav1.ObjectMeta `json:"metadata,omitempty" yaml:"metadata,omitempty"`
	Spec              CustomResourceDefinitionSpec `json:"spec"`
}

CustomResourceDefinition is the kubernetes-API-compliant representation of a Custom Resource Definition

func (*CustomResourceDefinition) DeepCopyObject

func (crd *CustomResourceDefinition) DeepCopyObject() runtime.Object

DeepCopyObject implements runtime.Object.

type CustomResourceDefinitionSpec

type CustomResourceDefinitionSpec struct {
	Group    string                                `json:"group" yaml:"group"`
	Versions []CustomResourceDefinitionSpecVersion `json:"versions" yaml:"versions"`
	Names    CustomResourceDefinitionSpecNames     `json:"names" yaml:"names"`
	Scope    string                                `json:"scope" yaml:"scope"`
}

CustomResourceDefinitionSpec is the body or spec of a kubernetes Custom Resource Definition

type CustomResourceDefinitionSpecNames

type CustomResourceDefinitionSpecNames struct {
	Kind   string `json:"kind" yaml:"kind"`
	Plural string `json:"plural" yaml:"plural"`
}

CustomResourceDefinitionSpecNames is the struct representing the names (kind and plural) of a kubernetes CRD

type CustomResourceDefinitionSpecVersion

type CustomResourceDefinitionSpecVersion struct {
	Name         string         `json:"name" yaml:"name"`
	Served       bool           `json:"served" yaml:"served"`
	Storage      bool           `json:"storage" yaml:"storage"`
	Schema       map[string]any `json:"schema" yaml:"schema"`
	Subresources map[string]any `json:"subresources,omitempty" yaml:"subresources,omitempty"`
}

CustomResourceDefinitionSpecVersion is the representation of a specific version of a CRD, as part of the overall spec

type GenericJSONDecoder

type GenericJSONDecoder struct {
}

GenericJSONDecoder implements runtime.Serializer and works with Untyped* objects to implement runtime.Object

func (*GenericJSONDecoder) Decode

Decode decodes the provided data into UntypedWatchObject or UntypedObjectWrapper

func (*GenericJSONDecoder) Encode

func (*GenericJSONDecoder) Encode(obj runtime.Object, w io.Writer) error

Encode json-encodes the provided object

func (*GenericJSONDecoder) Identifier

func (*GenericJSONDecoder) Identifier() runtime.Identifier

Identifier returns "generic-json-decoder"

type GenericNegotiatedSerializer

type GenericNegotiatedSerializer struct {
}

GenericNegotiatedSerializer implements runtime.NegotiatedSerializer and allows for JSON serialization and deserialization of resource.Object. Since it is generic, and has no schema information, wrapped objects are returned which require a call to `Into` to marshal into an actual resource.Object.

func (*GenericNegotiatedSerializer) DecoderToVersion

DecoderToVersion returns a GenericJSONDecoder

func (*GenericNegotiatedSerializer) EncoderForVersion

EncoderForVersion returns the `serializer` input

func (*GenericNegotiatedSerializer) SupportedMediaTypes

func (*GenericNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo

SupportedMediaTypes returns the JSON supported media type with a GenericJSONDecoder and kubernetes JSON Framer.

type KindNegotiatedSerializer added in v0.15.0

type KindNegotiatedSerializer struct {
	Kind resource.Kind
}

func (*KindNegotiatedSerializer) DecoderToVersion added in v0.15.0

DecoderToVersion returns a GenericJSONDecoder

func (*KindNegotiatedSerializer) EncoderForVersion added in v0.15.0

func (*KindNegotiatedSerializer) EncoderForVersion(serializer runtime.Encoder,
	_ runtime.GroupVersioner) runtime.Encoder

EncoderForVersion returns the `serializer` input

func (*KindNegotiatedSerializer) SupportedMediaTypes added in v0.15.0

func (k *KindNegotiatedSerializer) SupportedMediaTypes() []runtime.SerializerInfo

SupportedMediaTypes returns the JSON supported media type with a GenericJSONDecoder and kubernetes JSON Framer.

type OpinionatedMutatingAdmissionController added in v0.9.11

type OpinionatedMutatingAdmissionController struct {
	Underlying resource.MutatingAdmissionController
}

OpinionatedMutatingAdmissionController is a MutatingAdmissionController which wraps an optional user-defined MutatingAdmissionController with a set of additional changes to the response's UpdatedObject which set metadata and label properties.

func NewOpinionatedMutatingAdmissionController added in v0.9.11

func NewOpinionatedMutatingAdmissionController(wrap resource.MutatingAdmissionController) *OpinionatedMutatingAdmissionController

NewOpinionatedMutatingAdmissionController creates a pointer to a new OpinionatedMutatingAdmissionController wrapping the provided MutatingAdmissionController. If `wrap` is nil, it will not be used in the Mutate call.

func (*OpinionatedMutatingAdmissionController) Mutate added in v0.9.11

Mutate runs the Mutate function of the Underlying MutatingAdmissionController (if non-nil), and if that returns successfully, appends additional patch operations to the MutatingResponse for CommonMetadata fields not in kubernetes standard metadata, and labels internally used by the SDK, such as the stored version.

type OpinionatedValidatingAdmissionController added in v0.9.11

type OpinionatedValidatingAdmissionController struct {
	Underlying resource.ValidatingAdmissionController
}

OpinionatedValidatingAdmissionController implements resource.ValidatingAdmissionController and performs initial validation on reserved metadata fields which are stores as annotations in kubernetes, ensuring that if any changes are made, they are allowed, before calling the underlying admission validate function.

func NewOpinionatedValidatingAdmissionController added in v0.9.11

func NewOpinionatedValidatingAdmissionController(wrap resource.ValidatingAdmissionController) *OpinionatedValidatingAdmissionController

NewOpinionatedValidatingAdmissionController returns a new OpinionatedValidatingAdmissionController which wraps the provided ValidatingAdmissionController. If `wrap` is nil, no extra validation after the opinionated initial validation will be performed.

func (*OpinionatedValidatingAdmissionController) Validate added in v0.9.11

Validate performs validation on metadata-as-annotations fields before calling Validate on Underlying, if non-nil. If the Opinionated validation fails, Validate is never called on Underlying.

type RawKind added in v0.13.0

type RawKind struct {
	// Kind is the parsed kind string
	Kind string
	// APIVersion is the parsed API version string
	APIVersion string
	// Group is the group parsed from the API version string
	Group string
	// Version is the version parsed from the API version string
	Version string
	// Raw contains the entire kubernetes object in []byte form
	Raw []byte
}

RawKind represents a raw kubernetes object with basic kind information parsed out of it

type ResourceManager

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

ResourceManager is a struct that implements resource.Manager, allowing a user to manage Schemas as Custom Resource Definitions in kubernetes.

func NewManager

func NewManager(cfg rest.Config) (*ResourceManager, error)

NewManager creates a new ResourceManager

func (*ResourceManager) RegisterSchema

func (m *ResourceManager) RegisterSchema(ctx context.Context, schema resource.Schema,
	options resource.RegisterSchemaOptions) error

RegisterSchema converts a Schema to a Custom Resource Definition, then attempts to create it in kubernetes. If a CRD already exists for the name, it checks to see if this is a new version and attempts to update the CRD with the new version.

func (*ResourceManager) WaitForAvailability

func (m *ResourceManager) WaitForAvailability(ctx context.Context, schema resource.Schema) error

WaitForAvailability polls the kubernetes API server every second until it gets a successful response for the Schema's CRD name

type SchemalessClient

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

SchemalessClient implements resource.SchemalessClient and allows for working with Schemas as kubernetes Custom Resource Definitions without being tied to a particular Schema (or GroupVerson). Since the largest unit a kubernetes rest.Interface can work with is a GroupVersion, SchemalessClient is actually an arbitrary number of kubernetes REST clients under-the-hood.

func NewSchemalessClient added in v0.9.9

func NewSchemalessClient(kubeConfig rest.Config, clientConfig ClientConfig) *SchemalessClient

NewSchemalessClient creates a new SchemalessClient using the provided rest.Config and ClientConfig.

func NewSchemalessClientWithCodec added in v0.15.0

func NewSchemalessClientWithCodec(kubeConfig rest.Config, clientConfig ClientConfig, jsonCodec resource.Codec) *SchemalessClient

func (*SchemalessClient) Create

Create creates a new resource, and marshals the storage response (the created object) into the `into` field.

func (*SchemalessClient) Delete

func (s *SchemalessClient) Delete(ctx context.Context, identifier resource.FullIdentifier) error

Delete deletes a resource identified by identifier

func (*SchemalessClient) Get

Get gets a resource from kubernetes with the Kind and GroupVersion determined from the FullIdentifier, using the namespace and name in FullIdentifier. If identifier.Plural is present, it will use that, otherwise, LOWER(identifier.Kind) + s is used for the resource. The returned resource is marshaled into `into`.

func (*SchemalessClient) List

func (s *SchemalessClient) List(ctx context.Context, identifier resource.FullIdentifier,
	options resource.ListOptions, into resource.ListObject, exampleListItem resource.Object) error

List lists all resources that satisfy identifier, ignoring `Name`. The response is marshaled into `into`

func (*SchemalessClient) Patch

Patch performs a JSON Patch on the provided resource, and marshals the updated version into the `into` field

func (*SchemalessClient) PrometheusCollectors added in v0.12.0

func (s *SchemalessClient) PrometheusCollectors() []prometheus.Collector

PrometheusCollectors returns the prometheus metric collectors used by this client to allow for registration

func (*SchemalessClient) Update

Update updates an existing resource, and marshals the updated version into the `into` field

func (*SchemalessClient) Watch

Watch watches all resources that satisfy the identifier, ignoring `Name`. The WatchResponse's WatchEvent Objects are created by unmarshaling into an object created by calling example.Copy().

type ServerResponseError

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

ServerResponseError represents an HTTP error from the kubernetes control plane. It contains the underlying error returned by the kubernetes go client, and the status code returned from the API.

func NewServerResponseError

func NewServerResponseError(err error, statusCode int) *ServerResponseError

NewServerResponseError creates a new instance of ServerResponseError

func (*ServerResponseError) Error

func (s *ServerResponseError) Error() string

Error returns the Error() of the underlying kubernetes client error

func (*ServerResponseError) StatusCode

func (s *ServerResponseError) StatusCode() int

StatusCode returns the status code returned by the kubernetes API associated with this error

func (*ServerResponseError) Unwrap

func (s *ServerResponseError) Unwrap() error

Unwrap returns the underlying kubernetes go client error

type SimpleAdmissionError added in v0.9.11

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

SimpleAdmissionError implements resource.AdmissionError

func NewAdmissionError added in v0.9.11

func NewAdmissionError(err error, statusCode int, reason string) *SimpleAdmissionError

NewAdmissionError returns a new SimpleAdmissionError, which implements resource.AdmissionError

func (*SimpleAdmissionError) Reason added in v0.9.11

func (s *SimpleAdmissionError) Reason() string

Reason returns a machine-readable reason for the error

func (*SimpleAdmissionError) StatusCode added in v0.9.11

func (s *SimpleAdmissionError) StatusCode() int

StatusCode returns the error's HTTP status code

type TLSConfig added in v0.9.11

type TLSConfig struct {
	// CertPath is the path to the on-disk cert file
	CertPath string
	// KeyPath is the path to the on-disk key file for the cert
	KeyPath string
}

TLSConfig describes a set of TLS files

type TypedObjectWrapper

type TypedObjectWrapper struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata"`
	// contains filtered or unexported fields
}

TypedObjectWrapper wraps a resource.Object in a runtime.Object interface, and exposes a ResourceObject() method to get the wrapped object.

func (*TypedObjectWrapper) DeepCopyObject

func (o *TypedObjectWrapper) DeepCopyObject() runtime.Object

DeepCopyObject copies the object

func (*TypedObjectWrapper) ResourceObject

func (o *TypedObjectWrapper) ResourceObject() resource.Object

ResourceObject returns the wrapped resource.Object

type UntypedObjectWrapper

type UntypedObjectWrapper struct {
	metav1.TypeMeta   `json:",inline"`
	metav1.ObjectMeta `json:"metadata"`
	// contains filtered or unexported fields
}

UntypedObjectWrapper wraps bytes which can be marshaled into a resource.Object, but only if provided an example object to marshal into. It implements runtime.Object, and exposes Into() to marshal the bytes into a concrete type.

func (*UntypedObjectWrapper) DeepCopyObject

func (o *UntypedObjectWrapper) DeepCopyObject() runtime.Object

DeepCopyObject copies the object

func (*UntypedObjectWrapper) Into

func (o *UntypedObjectWrapper) Into(into resource.Object, codec resource.Codec) error

Into unmarshals the wrapped object bytes into the provided resource.Object, using the same unmarshal logic that Client and SchemalessClient use

type UntypedWatchObject

type UntypedWatchObject struct {
	metav1.TypeMeta
	Type   string          `json:"type"`
	Object json.RawMessage `json:"object"`
}

UntypedWatchObject implements runtime.Object, and keeps the Object part of a kubernetes watch event as bytes when unmarshaled, so that it can later be marshaled into a concrete type with Into().

func (*UntypedWatchObject) DeepCopyObject

func (w *UntypedWatchObject) DeepCopyObject() runtime.Object

DeepCopyObject copies the object

func (*UntypedWatchObject) Into

func (w *UntypedWatchObject) Into(into resource.Object, codec resource.Codec) error

Into unmarshals the wrapped object bytes into the provided resource.Object, using the same unmarshal logic that Client and SchemalessClient use

type WatchResponse

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

WatchResponse wraps a kubernetes watch.Interface in order to implement resource.WatchResponse. The underlying watch.Interface can be accessed with KubernetesWatch().

func (*WatchResponse) KubernetesWatch

func (w *WatchResponse) KubernetesWatch() watch.Interface

KubernetesWatch returns the underlying watch.Interface. Calling this method will shut down the translation channel between the watch.Interface and ResultChan(). Using both KubernetesWatch() and ResultChan() simultaneously is not supported, and may result in undefined behavior.

func (*WatchResponse) Stop

func (w *WatchResponse) Stop()

Stop stops the translation channel between the kubernetes watch.Interface, and stops the continued watch request encapsulated by the watch.Interface.

func (*WatchResponse) WatchEvents

func (w *WatchResponse) WatchEvents() <-chan resource.WatchEvent

WatchEvents returns a channel that receives watch events. All calls to this method will return the same channel. This channel will stop receiving events if KubernetesWatch() is called, as that halts the event translation process. If Stop() is called, ths channel is closed.

type WebhookServer added in v0.9.11

type WebhookServer struct {
	// DefaultValidatingController is the default ValidatingAdmissionController to use if one is not defined for the schema in the request.
	// If this is empty, the request will be rejected.
	DefaultValidatingController resource.ValidatingAdmissionController
	// DefaultMutatingController is the default MutatingAdmissionController to use if one is not defined for the schema in the request.
	// If this is empty, the request will be rejected.
	DefaultMutatingController resource.MutatingAdmissionController
	// contains filtered or unexported fields
}

WebhookServer is a kubernetes webhook server, which exposes /validate and /mutate HTTPS endpoints. It implements operator.Controller and can be run as a controller in an operator, or as a standalone process.

func NewWebhookServer added in v0.9.11

func NewWebhookServer(config WebhookServerConfig) (*WebhookServer, error)

NewWebhookServer creates a new WebhookServer using the provided configuration. The only required parts of the config are the Port and TLSConfig, as all other parts (default controllers, schema-specific controllers) can be set post-initialization.

func (*WebhookServer) AddConverter added in v0.13.0

func (w *WebhookServer) AddConverter(converter Converter, groupKind metav1.GroupKind)

AddConverter adds a Converter to the WebhookServer, associated with the given group and kind.

func (*WebhookServer) AddMutatingAdmissionController added in v0.9.11

func (w *WebhookServer) AddMutatingAdmissionController(controller resource.MutatingAdmissionController, kind resource.Kind)

AddMutatingAdmissionController adds a resource.MutatingAdmissionController to the WebhookServer, associated with a given schema. The schema association associates all incoming requests of the same group and kind of the schema to the schema's ZeroValue object. If a MutatingAdmissionController already exists for the provided schema, the one provided in this call will be used instead of the extant one.

func (*WebhookServer) AddValidatingAdmissionController added in v0.9.11

func (w *WebhookServer) AddValidatingAdmissionController(controller resource.ValidatingAdmissionController, kind resource.Kind)

AddValidatingAdmissionController adds a resource.ValidatingAdmissionController to the WebhookServer, associated with a given schema. The schema association associates all incoming requests of the same group and kind of the schema to the schema's ZeroValue object. If a ValidatingAdmissionController already exists for the provided schema, the one provided in this call will be used instead of the extant one.

func (*WebhookServer) HandleConvertHTTP added in v0.13.0

func (w *WebhookServer) HandleConvertHTTP(writer http.ResponseWriter, req *http.Request)

HandleConvertHTTP is the HTTP HandlerFunc for a kubernetes CRD conversion webhook call nolint:errcheck,revive,funlen

func (*WebhookServer) HandleMutateHTTP added in v0.9.11

func (w *WebhookServer) HandleMutateHTTP(writer http.ResponseWriter, req *http.Request)

HandleMutateHTTP is the HTTP HandlerFunc for a kubernetes mutating webhook call nolint:errcheck,revive,funlen

func (*WebhookServer) HandleValidateHTTP added in v0.9.11

func (w *WebhookServer) HandleValidateHTTP(writer http.ResponseWriter, req *http.Request)

HandleValidateHTTP is the HTTP HandlerFunc for a kubernetes validating webhook call nolint:errcheck,revive,funlen

func (*WebhookServer) Run added in v0.9.11

func (w *WebhookServer) Run(closeChan <-chan struct{}) error

Run establishes an HTTPS server on the configured port and exposes `/validate` and `/mutate` paths for kubernetes validating and mutating webhooks, respectively. It will block until either closeChan is closed (in which case it returns nil), or the server encounters an unrecoverable error (in which case it returns the error).

type WebhookServerConfig added in v0.9.11

type WebhookServerConfig struct {
	// The Port to run the HTTPS server on
	Port int
	// TLSConfig contains cert information for running the HTTPS server
	TLSConfig TLSConfig
	// ValidatingControllers is a map of schemas to their corresponding ValidatingAdmissionController.
	ValidatingControllers map[*resource.Kind]resource.ValidatingAdmissionController
	// MutatingControllers is a map of schemas to their corresponding MutatingAdmissionController.
	MutatingControllers map[*resource.Kind]resource.MutatingAdmissionController
	// KindConverters is a map of GroupKind to a Converter which can parse any valid version of the kind
	// and return any valid version of the kind.
	KindConverters map[metav1.GroupKind]Converter
	// DefaultValidatingController is called for any /validate requests received which don't have an entry in ValidatingControllers.
	// If left nil, an error will be returned to the caller instead.
	DefaultValidatingController resource.ValidatingAdmissionController
	// DefaultMutatingController is called for any /validate requests received which don't have an entry in MutatingControllers.
	// If left nil, an error will be returned to the caller instead.
	DefaultMutatingController resource.MutatingAdmissionController
}

WebhookServerConfig is the configuration object for a WebhookServer, used with NewWebhookServer.

Jump to

Keyboard shortcuts

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