Documentation ¶
Index ¶
- Constants
- Variables
- func DefaultFinalizerSupplier(sch resource.Schema) string
- func GetTracer() trace.Tracer
- func LoadOperatorRestConfig(path string, opts RestConfigOptions, dst *RestConfig) error
- func NewListerWatcher(client ListWatchClient, sch resource.Schema, filterOptions ListWatchOptions) cache.ListerWatcher
- func SetTracer(t trace.Tracer)
- type CannotCastError
- type Controller
- type ConvertableIntoResourceObject
- type CustomCacheInformer
- func NewCustomCacheInformer(store cache.Store, lw cache.ListerWatcher, kind resource.Kind) *CustomCacheInformer
- func NewMemcachedInformer(kind resource.Kind, client ListWatchClient, namespace string, addrs ...string) (*CustomCacheInformer, error)
- func NewMemcachedInformerWithFilters(kind resource.Kind, client ListWatchClient, filterOptions ListWatchOptions, ...) (*CustomCacheInformer, error)
- func (c *CustomCacheInformer) AddEventHandler(handler ResourceWatcher) error
- func (c *CustomCacheInformer) HasStarted() bool
- func (c *CustomCacheInformer) HasSynced() bool
- func (c *CustomCacheInformer) LastSyncResourceVersion() string
- func (c *CustomCacheInformer) OnAdd(obj any, isInInitialList bool)
- func (c *CustomCacheInformer) OnDelete(obj any)
- func (c *CustomCacheInformer) OnUpdate(oldObj any, newObj any)
- func (c *CustomCacheInformer) PrometheusCollectors() []prometheus.Collector
- func (c *CustomCacheInformer) Run(stopCh <-chan struct{}) error
- type FinalizerSupplier
- type Informer
- type InformerController
- func (c *InformerController) AddInformer(informer Informer, resourceKind string) error
- func (c *InformerController) AddReconciler(reconciler Reconciler, resourceKind string) error
- func (c *InformerController) AddWatcher(watcher ResourceWatcher, resourceKind string) error
- func (c *InformerController) PrometheusCollectors() []prometheus.Collector
- func (c *InformerController) RemoveAllReconcilersForResource(resourceKind string)
- func (c *InformerController) RemoveAllWatchersForResource(resourceKind string)
- func (c *InformerController) RemoveReconciler(reconciler Reconciler, resourceKind string)
- func (c *InformerController) RemoveWatcher(watcher ResourceWatcher, resourceKind string)
- func (c *InformerController) Run(stopCh <-chan struct{}) error
- type InformerControllerConfig
- type KubernetesBasedIformerOptions
- type KubernetesBasedInformer
- type KubernetesCompatibleWatch
- type ListMap
- func (l *ListMap[K, V]) AddItem(key K, items ...V)
- func (l *ListMap[K, V]) ItemAt(key K, index int) (V, bool)
- func (l *ListMap[K, V]) KeySize(key K) int
- func (l *ListMap[K, V]) Keys() []K
- func (l *ListMap[K, V]) Range(key K, rangeFunc func(index int, value V))
- func (l *ListMap[K, V]) RangeAll(rangeFunc func(key K, index int, value V))
- func (l *ListMap[K, V]) RemoveItem(key K, match func(V) bool) bool
- func (l *ListMap[K, V]) RemoveItemAt(key K, index int)
- func (l *ListMap[K, V]) RemoveItems(key K, match func(V) bool, limit int) int
- func (l *ListMap[K, V]) RemoveKey(key K)
- func (l *ListMap[K, V]) Size() int
- type ListWatchClient
- type ListWatchOptions
- type MemcachedStore
- func (m *MemcachedStore) Add(obj any) error
- func (m *MemcachedStore) Delete(obj any) error
- func (m *MemcachedStore) Get(obj any) (item any, exists bool, err error)
- func (m *MemcachedStore) GetByKey(key string) (item any, exists bool, err error)
- func (m *MemcachedStore) List() []any
- func (m *MemcachedStore) ListKeys() []string
- func (m *MemcachedStore) PrometheusCollectors() []prometheus.Collector
- func (*MemcachedStore) Replace([]any, string) error
- func (*MemcachedStore) Resync() error
- func (m *MemcachedStore) Update(obj any) error
- type MemcachedStoreConfig
- type Operator
- type OpinionatedReconciler
- type OpinionatedWatcher
- func (o *OpinionatedWatcher) Add(ctx context.Context, object resource.Object) error
- func (*OpinionatedWatcher) Delete(context.Context, resource.Object) error
- func (o *OpinionatedWatcher) Update(ctx context.Context, old resource.Object, new resource.Object) error
- func (o *OpinionatedWatcher) Wrap(watcher ResourceWatcher, syncToAdd bool)
- type PatchClient
- type ReconcileAction
- type ReconcileRequest
- type ReconcileResult
- type Reconciler
- type ResourceAction
- type ResourceObjectWrapper
- type ResourceWatcher
- type RestConfig
- type RestConfigOptions
- type RetryDequeuePolicy
- type RetryPolicy
- type Runner
- type RunnerConfig
- type RunnerMetricsConfig
- type RunnerWebhookConfig
- type SimpleReconciler
- type SimpleWatcher
- type TypedReconcileRequest
- type TypedReconciler
Constants ¶
const ( ResourceActionCreate = ResourceAction("CREATE") ResourceActionUpdate = ResourceAction("UPDATE") ResourceActionDelete = ResourceAction("DELETE") )
const (
// MemcachedStoreDefaultPageSize is the default page size for MemcachedStore.List() operations
MemcachedStoreDefaultPageSize = 500
)
Variables ¶
var DefaultErrorHandler = func(ctx context.Context, err error) { logging.FromContext(ctx).Error(err.Error(), "component", "InformerController", "error", err) }
DefaultErrorHandler is an error handler function which simply logs the error with the logger in the context
var DefaultRetryPolicy = ExponentialBackoffRetryPolicy(5*time.Second, 5)
DefaultRetryPolicy is an Exponential Backoff RetryPolicy with an initial 5-second delay and a max of 5 attempts
var ErrInformerAlreadyAdded = errors.New("informer for resource kind already added")
ErrInformerAlreadyAdded indicates that there is already an informer for the resource kind mapped
var ErrNilObject = errors.New("object cannot be nil")
ErrNilObject indicates that a provided resource.Object is nil, and cannot be processed
var OpinionatedRetryDequeuePolicy = func(newAction ResourceAction, newObject resource.Object, retryAction ResourceAction, retryObject resource.Object, _ error) bool { if newAction == ResourceActionDelete { return true } if newAction != retryAction { return false } if newObject.GetGeneration() == retryObject.GetGeneration() { return false } return true }
OpinionatedRetryDequeuePolicy is a RetryDequeuePolicy which has the following logic: 1. If the newAction is a delete, dequeue the retry 2. If the newAction and retryAction are different, keep the retry (for example, a queued create retry, and a received update action) 3. If the generation of newObject and retryObject is the same, keep the retry 4. Otherwise, dequeue the retry
Functions ¶
func DefaultFinalizerSupplier ¶
DefaultFinalizerSupplier crates finalizer following to pattern `operator.{version}.{kind}.{group}`.
func GetTracer ¶ added in v0.11.0
GetTracer returns the trace.Tracer set by SetTracer, or a tracer generated from otel.GetTracerProvider().Tracer("k8s") if none has been set.
func LoadOperatorRestConfig ¶ added in v0.17.6
func LoadOperatorRestConfig(path string, opts RestConfigOptions, dst *RestConfig) error
LoadOperatorRestConfig loads an operator rest config from given path.
func NewListerWatcher ¶ added in v0.18.0
func NewListerWatcher(client ListWatchClient, sch resource.Schema, filterOptions ListWatchOptions) cache.ListerWatcher
NewListerWatcher returns a cache.ListerWatcher for the provided resource.Schema that uses the given ListWatchClient. The List and Watch requests will always use the provided namespace and labelFilters.
Types ¶
type CannotCastError ¶ added in v0.10.0
type CannotCastError struct { Namespace string Name string Group string Kind string // contains filtered or unexported fields }
CannotCastError is an error that is returned by a Typed object if it cannot cast the resource.Object provided into the type the Typed object was created for.
func NewCannotCastError ¶ added in v0.10.0
func NewCannotCastError(meta resource.StaticMetadata) *CannotCastError
NewCannotCastError returns a new CannotCastError with data filled out from the provided resource.StaticMetadata
func (*CannotCastError) Error ¶ added in v0.10.0
func (c *CannotCastError) Error() string
Error returns the error message
type Controller ¶
type Controller interface {
Run(<-chan struct{}) error
}
Controller is an interface that describes a controller which can be run as part of an operator
type ConvertableIntoResourceObject ¶
type ConvertableIntoResourceObject interface {
Into(object resource.Object, codec resource.Codec) error
}
ConvertableIntoResourceObject describes any object which can be marshaled into a resource.Object. This is specifically useful for objects which may wrap underlying data which can be marshaled into a resource.Object, but need the exact implementation provided to them (by `into`).
type CustomCacheInformer ¶ added in v0.18.0
type CustomCacheInformer struct { // CacheResyncInterval is the interval at which the informer will emit CacheResync events for all resources in the cache. // This is distinct from a full resync, as no information is fetched from the API server. // Changes to this value after run() is called will not take effect. CacheResyncInterval time.Duration // ErrorHandler is called if the informer encounters an error which does not stop the informer from running, // but may stop it from processing a given event. ErrorHandler func(context.Context, error) // contains filtered or unexported fields }
func NewCustomCacheInformer ¶ added in v0.18.0
func NewCustomCacheInformer(store cache.Store, lw cache.ListerWatcher, kind resource.Kind) *CustomCacheInformer
NewCustomCacheInformer returns a new CustomCacheInformer using the provided cache.Store and cache.ListerWatcher.
func NewMemcachedInformer ¶ added in v0.18.0
func NewMemcachedInformer(kind resource.Kind, client ListWatchClient, namespace string, addrs ...string) (*CustomCacheInformer, error)
NewMemcachedInformer creates a new CustomCacheInformer which uses memcached as its custom cache. This is analogous to calling NewCustomCacheInformer with a MemcachedStore as the store.
func NewMemcachedInformerWithFilters ¶ added in v0.19.0
func NewMemcachedInformerWithFilters(kind resource.Kind, client ListWatchClient, filterOptions ListWatchOptions, addrs ...string) (*CustomCacheInformer, error)
NewMemcachedInformerWithFilters creates a new CustomCacheInformer which uses memcached as its custom cache. This is analogous to calling NewCustomCacheInformer with a MemcachedStore as the store.
func (*CustomCacheInformer) AddEventHandler ¶ added in v0.18.0
func (c *CustomCacheInformer) AddEventHandler(handler ResourceWatcher) error
AddEventHandler adds the provided ResourceWatcher to the list of handlers to have events reported to.
func (*CustomCacheInformer) HasStarted ¶ added in v0.18.0
func (c *CustomCacheInformer) HasStarted() bool
HasStarted returns true if the informer is already running
func (*CustomCacheInformer) HasSynced ¶ added in v0.18.0
func (c *CustomCacheInformer) HasSynced() bool
HasSynced returns true if the informer has synced all events from the initial list request.
func (*CustomCacheInformer) LastSyncResourceVersion ¶ added in v0.18.0
func (c *CustomCacheInformer) LastSyncResourceVersion() string
LastSyncResourceVersion delegates to the underlying cache.Reflector's method, if the informer has started. Otherwise, it returns an empty string.
func (*CustomCacheInformer) OnAdd ¶ added in v0.18.0
func (c *CustomCacheInformer) OnAdd(obj any, isInInitialList bool)
OnAdd implements cache.ResourceEventHandler, and distributes the add event to all registered ResourceWatcher handlers.
func (*CustomCacheInformer) OnDelete ¶ added in v0.18.0
func (c *CustomCacheInformer) OnDelete(obj any)
OnDelete implements cache.ResourceEventHandler, and distributes the delete event to all registered ResourceWatcher handlers.
func (*CustomCacheInformer) OnUpdate ¶ added in v0.18.0
func (c *CustomCacheInformer) OnUpdate(oldObj any, newObj any)
OnUpdate implements cache.ResourceEventHandler, and distributes the update event to all registered ResourceWatcher handlers.
func (*CustomCacheInformer) PrometheusCollectors ¶ added in v0.18.0
func (c *CustomCacheInformer) PrometheusCollectors() []prometheus.Collector
PrometheusCollectors returns a list of prometheus collectors used by the informer and its objects (such as the cache).
func (*CustomCacheInformer) Run ¶ added in v0.18.0
func (c *CustomCacheInformer) Run(stopCh <-chan struct{}) error
Run runs the informer until stopCh is closed or receives a message. While running, events from the ListerWatcher will be propagated to all registered ResourceWatcher handlers, and current state of all resources will be stored in the custom cache.Store.
type FinalizerSupplier ¶
FinalizerSupplier represents a function that creates string finalizer from provider schema.
type Informer ¶
type Informer interface { AddEventHandler(handler ResourceWatcher) error Run(stopCh <-chan struct{}) error }
Informer is an interface describing an informer which can be managed by InformerController
type InformerController ¶
type InformerController struct { // ErrorHandler is a user-specified error handling function. This is typically for logging/metrics use, // as retry logic is covered by the RetryPolicy. ErrorHandler func(context.Context, error) // RetryPolicy is a user-specified retry logic function which will be used when ResourceWatcher function calls fail. RetryPolicy RetryPolicy // RetryDequeuePolicy is a user-specified retry dequeue logic function which will be used for new informer actions // when one or more retries for the object are still pending. If not present, existing retries are always dequeued. RetryDequeuePolicy RetryDequeuePolicy // contains filtered or unexported fields }
InformerController is an object that handles coordinating informers and observers. Unlike adding a Watcher directly to an Informer with AddEventHandler, the InformerController guarantees sequential execution of watchers, based on add order.
func NewInformerController ¶
func NewInformerController(cfg InformerControllerConfig) *InformerController
NewInformerController creates a new controller
func (*InformerController) AddInformer ¶
func (c *InformerController) AddInformer(informer Informer, resourceKind string) error
AddInformer adds an informer for a specific resourceKind. The `resourceKind` string is used for internal tracking and correlation to observers, and does not necessarily need to match the informer's type.
Multiple informers may be added for the same resource kind, and each will trigger all watchers for that resource kind. The most common usage of this is to have informers partitioned by namespace or labels for the same resource kind, which share a watcher.
func (*InformerController) AddReconciler ¶ added in v0.10.0
func (c *InformerController) AddReconciler(reconciler Reconciler, resourceKind string) error
AddReconciler adds a reconciler to an informer with a matching `resourceKind`. Any time the informer sees an add, update, or delete, it will call reconciler.Reconcile. Multiple reconcilers can exist for the same resource kind. If multiple reconcilers exist, they will be run in the order they were added to the informer.
func (*InformerController) AddWatcher ¶
func (c *InformerController) AddWatcher(watcher ResourceWatcher, resourceKind string) error
AddWatcher adds an observer to an informer with a matching `resourceKind`. Any time the informer sees an add, update, or delete, it will call the observer's corresponding method. Multiple watchers can exist for the same resource kind. They will be run in the order they were added to the informer.
func (*InformerController) PrometheusCollectors ¶ added in v0.12.0
func (c *InformerController) PrometheusCollectors() []prometheus.Collector
PrometheusCollectors returns the prometheus metric collectors used by this informer, as well as collectors used by any registered informer or watcher which implements metrics.Provider, to allow for registration
func (*InformerController) RemoveAllReconcilersForResource ¶ added in v0.10.0
func (c *InformerController) RemoveAllReconcilersForResource(resourceKind string)
RemoveAllReconcilersForResource removes all Reconcilers for a specific resourceKind
func (*InformerController) RemoveAllWatchersForResource ¶
func (c *InformerController) RemoveAllWatchersForResource(resourceKind string)
RemoveAllWatchersForResource removes all watchers for a specific resourceKind
func (*InformerController) RemoveReconciler ¶ added in v0.10.0
func (c *InformerController) RemoveReconciler(reconciler Reconciler, resourceKind string)
RemoveReconciler removes the given Reconciler from the list for the resourceKind, provided it exists in the list.
func (*InformerController) RemoveWatcher ¶
func (c *InformerController) RemoveWatcher(watcher ResourceWatcher, resourceKind string)
RemoveWatcher removes the given ResourceWatcher from the list for the resourceKind, provided it exists in the list.
func (*InformerController) Run ¶
func (c *InformerController) Run(stopCh <-chan struct{}) error
Run runs the controller, which starts all informers, until stopCh is closed
type InformerControllerConfig ¶ added in v0.12.0
InformerControllerConfig contains configuration options for an InformerController
func DefaultInformerControllerConfig ¶ added in v0.12.0
func DefaultInformerControllerConfig() InformerControllerConfig
DefaultInformerControllerConfig returns an InformerControllerConfig with default values
type KubernetesBasedIformerOptions ¶ added in v0.22.0
type KubernetesBasedIformerOptions struct { ListWatchOptions ListWatchOptions // CacheResyncInterval is the interval at which the informer will emit CacheResync events for all resources in the cache. // This is distinct from a full resync, as no information is fetched from the API server. // An empty value will disable cache resyncs. CacheResyncInterval time.Duration }
type KubernetesBasedInformer ¶
type KubernetesBasedInformer struct { ErrorHandler func(context.Context, error) // contains filtered or unexported fields }
KubernetesBasedInformer is a k8s apimachinery-based informer. It wraps a k8s cache.SharedIndexInformer, and works most optimally with a client that has a Watch response that implements KubernetesCompatibleWatch.
func NewKubernetesBasedInformer ¶
func NewKubernetesBasedInformer(sch resource.Kind, client ListWatchClient, namespace string) ( *KubernetesBasedInformer, error)
NewKubernetesBasedInformer creates a new KubernetesBasedInformer for the provided schema and namespace, using the ListWatchClient provided to do its List and Watch requests.
func NewKubernetesBasedInformerWithFilters ¶
func NewKubernetesBasedInformerWithFilters(sch resource.Kind, client ListWatchClient, options KubernetesBasedIformerOptions) ( *KubernetesBasedInformer, error)
NewKubernetesBasedInformerWithFilters creates a new KubernetesBasedInformer for the provided schema and namespace, using the ListWatchClient provided to do its List and Watch requests applying provided labelFilters if it is not empty.
func (*KubernetesBasedInformer) AddEventHandler ¶
func (k *KubernetesBasedInformer) AddEventHandler(handler ResourceWatcher) error
AddEventHandler adds a ResourceWatcher as an event handler for watch events from the informer. Event handlers are not guaranteed to be executed in parallel or in any particular order by the underlying kubernetes apimachinery code. If you want to coordinate ResourceWatchers, use am InformerController. nolint:dupl
func (*KubernetesBasedInformer) Run ¶
func (k *KubernetesBasedInformer) Run(stopCh <-chan struct{}) error
Run starts the informer and blocks until stopCh receives a message
func (*KubernetesBasedInformer) Schema ¶
func (k *KubernetesBasedInformer) Schema() resource.Schema
Schema returns the resource.Schema this informer is set up for
type KubernetesCompatibleWatch ¶
KubernetesCompatibleWatch describes a watch response that either is wrapping a kubernetes watch.Interface, or can return a compatibility layer that implements watch.Interface.
type ListMap ¶
type ListMap[K comparable, V any] struct { // contains filtered or unexported fields }
ListMap is a map of lists which is thread-safe, with read and write distinction. The underlying map and slice(s) are not directly accessible, as it would prevent the read/write safety.
func NewListMap ¶
NewListMap returns a pointer to a new properly-initialized ListMap. The type parameter is the type of elements in the lists
func (*ListMap[K, V]) AddItem ¶
func (l *ListMap[K, V]) AddItem(key K, items ...V)
AddItem adds one or more items to the list for a key. If the key does not exist, it will be added. AddItem locks the particular list for writing, so simultaneous AddItem calls for the same key will be sequential, and simultaneous AddItem calls for different keys will not impact each other.
func (*ListMap[K, V]) ItemAt ¶
ItemAt returns the item at index `index` in the list for the map key `key`. If the index or key do not exist, it will return an empty value, and a false.
func (*ListMap[K, V]) Keys ¶
func (l *ListMap[K, V]) Keys() []K
Keys returns a list of all keys in the map at the time of the call. It does not lock the map for writing, so new keys may be added during this call which may not be present in the result.
func (*ListMap[K, V]) Range ¶
Range performs a range operation for a given key's list. It consumes a rangeFunc, which takes arguments identical to a traditional go `range` function: `index` is the index within the list of the current item, and `value` is the list item at that index. `value` is safe to use beyond the list iteration as it is not a re-used pointer like in a typical `range` operation.
func (*ListMap[K, V]) RangeAll ¶
RangeAll ranges through all keys in the map, and all items in each key's list. It calls rangeFunc for each item in all lists. `key` is the list's map key, `index` is the index within the list, and `value` is the value pointer, as in a normal `range` operation.
func (*ListMap[K, V]) RemoveItem ¶
RemoveItem removes the first item in the list for a key which satisfies the `match` function. If the key does not exist, or no item in the list satisfies the `match` function, it is a no-op. The function returns `true` if an item was deleted, and `false` otherwise. The delete preserves list order after delete, meaning that all items subsequent to the index are left-shifted.
func (*ListMap[K, V]) RemoveItemAt ¶
RemoveItemAt removes a specific index from the list for a key. If the key or index does not exist, it is a no-op. The delete preserves list order after delete, meaning that all items subsequent to the index are left-shifted.
func (*ListMap[K, V]) RemoveItems ¶ added in v0.9.9
RemoveItems removes the first N (`limit`) items in the list for a key which satisfies the `match` function. If `limit` is less than 1, there is no limit to the number of items which can be removed. If the key does not exist, or no item in the list satisfies the `match` function, it is a no-op. The function returns the number of removed items. The delete preserves list order after delete, meaning that all items subsequent to the index are left-shifted.
type ListWatchClient ¶
type ListWatchClient interface { ListInto(ctx context.Context, namespace string, options resource.ListOptions, into resource.ListObject) error Watch(ctx context.Context, namespace string, options resource.WatchOptions) (resource.WatchResponse, error) }
ListWatchClient describes a client which can do ListInto and Watch requests.
type ListWatchOptions ¶ added in v0.19.0
ListWatchOptions are namespace, label selectors, and field selectors for filtering resources in ListWatch requests and Informers.
type MemcachedStore ¶ added in v0.18.0
type MemcachedStore struct {
// contains filtered or unexported fields
}
MemcachedStore implements cache.Store using memcached as the store for objects. It should be instantiated with NewMemcachedStore.
func NewMemcachedStore ¶ added in v0.18.0
func NewMemcachedStore(kind resource.Kind, cfg MemcachedStoreConfig) (*MemcachedStore, error)
NewMemcachedStore returns a new MemcachedStore for the specified Kind using the provided config.
func (*MemcachedStore) Add ¶ added in v0.18.0
func (m *MemcachedStore) Add(obj any) error
func (*MemcachedStore) Delete ¶ added in v0.18.0
func (m *MemcachedStore) Delete(obj any) error
func (*MemcachedStore) Get ¶ added in v0.18.0
func (m *MemcachedStore) Get(obj any) (item any, exists bool, err error)
func (*MemcachedStore) GetByKey ¶ added in v0.18.0
func (m *MemcachedStore) GetByKey(key string) (item any, exists bool, err error)
func (*MemcachedStore) List ¶ added in v0.18.0
func (m *MemcachedStore) List() []any
func (*MemcachedStore) ListKeys ¶ added in v0.18.0
func (m *MemcachedStore) ListKeys() []string
func (*MemcachedStore) PrometheusCollectors ¶ added in v0.18.0
func (m *MemcachedStore) PrometheusCollectors() []prometheus.Collector
PrometheusCollectors returns a list of prometheus collectors used by the MemcachedStore
func (*MemcachedStore) Replace ¶ added in v0.18.0
func (*MemcachedStore) Replace([]any, string) error
func (*MemcachedStore) Resync ¶ added in v0.18.0
func (*MemcachedStore) Resync() error
func (*MemcachedStore) Update ¶ added in v0.18.0
func (m *MemcachedStore) Update(obj any) error
type MemcachedStoreConfig ¶ added in v0.18.0
type MemcachedStoreConfig struct { // KeyFunc is the function used to determine the key for an object KeyFunc func(any) (string, error) // Addrs is a list of addresses (including ports) to connect to Addrs []string // Metrics is metrics configuration Metrics metrics.Config // KeySyncInterval is the interval at which keys stored in the in-memory map will be pushed to memcached. // Set to 0 to disable key tracking. It is advisable to disable this functionality unless you need ListKeys() and/or // List() functionality in MemcachedStore (this is required by an informer if you set the CacheResyncInterval). // If disabled (0), ListKeys() and List() will return nil. // Since a key list cannot be exported from memcached, the keys are tracked in-memory (from Add, Delete, and successful // Get operations), and periodically written to a known key in memcached. NewMemcachedStore loads the existing // value from the "known keys" key in memcached into the in-memory key tracking, and then will run a process // to push this list of keys to memcached every KeySyncInterval. If the data in memcached is cleared, // The in-memory list of keys will also be cleared, though this can result in some state synchronization errors, // as any Add operations that happen between the time the memcached was cleared and the next sync run will not // be known by the key tracker anymore. KeySyncInterval time.Duration // Timeout is the timeout on memcached connections. Leave 0 to default. Timeout time.Duration // MaxIdleConns is the max number of idle memcached connections. Leave 0 to default. MaxIdleConns int // PageSize is the page size to use for List requests on the store. If 0, it defaults to MemcachedStoreDefaultPageSize. PageSize int // ShardKey is a unique identifier for this MemcachedStore instance if you are using multiple. // If present, each shard will track the keys they manage in the underlying memcached separately. // To take advantage of this behavior, a shard key should be non-random and identical each run. ShardKey string }
MemcachedStoreConfig is a collection of config values for a MemcachedStore
type Operator ¶
type Operator struct {
// contains filtered or unexported fields
}
Operator is the highest-level construct of the `operator` package, and contains one or more controllers which can be run. Operator handles scaling and error propagation for its underlying controllers
func (*Operator) AddController ¶
func (o *Operator) AddController(c Controller)
AddController adds a new controller to the operator. If called after `Run`, it will not be added to the currently-running controllers.
func (*Operator) PrometheusCollectors ¶ added in v0.12.0
func (o *Operator) PrometheusCollectors() []prometheus.Collector
PrometheusCollectors returns the prometheus metric collectors for all controllers which implement metrics.Provider
type OpinionatedReconciler ¶ added in v0.10.0
type OpinionatedReconciler struct { Reconciler Reconciler // contains filtered or unexported fields }
OpinionatedReconciler wraps an ordinary Reconciler with finalizer-based logic to convert "Created" events into "resync" events on start-up when the reconciler has handled the "created" event on a previous run, and ensures that "delete" events are not missed during reconciler down-time by using the finalizer.
func NewOpinionatedReconciler ¶ added in v0.10.0
func NewOpinionatedReconciler(client PatchClient, finalizer string) (*OpinionatedReconciler, error)
NewOpinionatedReconciler creates a new OpinionatedReconciler. To have the new OpinionatedReconciler wrap an existing reconciler, set the `OpinionatedReconciler.Reconciler` value or use `OpinionatedReconciler.Wrap()`
func (*OpinionatedReconciler) Reconcile ¶ added in v0.10.0
func (o *OpinionatedReconciler) Reconcile(ctx context.Context, request ReconcileRequest) (ReconcileResult, error)
Reconcile consumes a ReconcileRequest and passes it off to the underlying ReconcileFunc, using the following criteria to modify or drop the request if needed:
- If the action is a Create, and the OpinionatedReconciler's finalizer is in the finalizer list, update the action to a Resync
- If the action is a Create, and the OpinionatedReconciler's finalizer is missing, add the finalizer after the delegated Reconcile request returns successfully
- If the action is an Update, and the DeletionTimestamp is non-nil, remove the OpinionatedReconciler's finalizer, and do not delegate (the subsequent Delete will be delegated)
- If the action is an Update, and the OpinionatedReconciler's finalizer is missing (and DeletionTimestamp is nil), add the finalizer, and do not delegate (the subsequent update action will delegate)
func (*OpinionatedReconciler) Wrap ¶ added in v0.10.0
func (o *OpinionatedReconciler) Wrap(reconciler Reconciler)
Wrap wraps the provided Reconciler's Reconcile function with this OpinionatedReconciler
type OpinionatedWatcher ¶
type OpinionatedWatcher struct { AddFunc func(ctx context.Context, object resource.Object) error UpdateFunc func(ctx context.Context, old resource.Object, new resource.Object) error DeleteFunc func(ctx context.Context, object resource.Object) error SyncFunc func(ctx context.Context, object resource.Object) error // contains filtered or unexported fields }
OpinionatedWatcher is a ResourceWatcher implementation that handles extra state logic, ensuring that downtime and restarts will not result in missed events. It does this via a few mechanisms is transparently handles for the user:
It adds a finalizer for all newly-created resources. This ensures that deletes cannot complete until the finalizer is removed, so the event will not be missed if the operator is down.
It only removes the finalizer after a successful call to `DeleteFunc`, which ensures that the resource is only deleted once the handler has succeeded.
On startup, it is able to differentiate between `Add` events, which are newly-created resources the operator has not yet handled, and `Add` events which are previously-created resources that have already been handled by the operator. Fully new resources call the `AddFunc` handler, and previously-created call the `SyncFunc` handler.
`Update` events which do not update anything in the spec or significant parts of the metadata are ignored.
OpinionatedWatcher contains unexported fields, and must be created with NewOpinionatedWatcher
func NewOpinionatedWatcher ¶
func NewOpinionatedWatcher(sch resource.Schema, client PatchClient) (*OpinionatedWatcher, error)
NewOpinionatedWatcher sets up a new OpinionatedWatcher and returns a pointer to it.
func NewOpinionatedWatcherWithFinalizer ¶
func NewOpinionatedWatcherWithFinalizer(sch resource.Schema, client PatchClient, supplier FinalizerSupplier) (*OpinionatedWatcher, error)
NewOpinionatedWatcherWithFinalizer sets up a new OpinionatedWatcher with finalizer from provided supplier and returns a pointer to it.
func (*OpinionatedWatcher) Add ¶
Add is part of implementing ResourceWatcher, and calls the underlying AddFunc, SyncFunc, or DeleteFunc based upon internal logic. When the object is first added, AddFunc is called and a finalizer is attached to it. Subsequent calls to Add will check the finalizer list and call SyncFunc if the finalizer is already attached, or if ObjectMetadata.DeletionTimestamp is non-nil, they will call DeleteFunc and remove the finalizer (the finalizer prevents the resource from being hard deleted until it is removed).
func (*OpinionatedWatcher) Delete ¶
Delete exists to implement ResourceWatcher, but, due to deletes only happening after the finalizer is removed, this function does nothing.
func (*OpinionatedWatcher) Update ¶
func (o *OpinionatedWatcher) Update(ctx context.Context, old resource.Object, new resource.Object) error
Update is part of implementing ResourceWatcher and calls the underlying UpdateFunc or DeleteFunc based on internal logic. If the new object has a non-nil ObjectMetadata.DeletionTimestamp in its metadata, DeleteFunc will be called, and the object's finalizer will be removed to allow kubernetes to hard delete it. Otherwise, UpdateFunc is called, provided the update is non-trivial (that is, the metadata.Generation has changed).
func (*OpinionatedWatcher) Wrap ¶
func (o *OpinionatedWatcher) Wrap(watcher ResourceWatcher, syncToAdd bool)
Wrap wraps the Add, Update, and Delete calls in another ResourceWatcher by having the AddFunc call watcher. Add, UpdateFunc call watcher.Update, and DeleteFunc call watcher.Delete. If syncToAdd is true, SyncFunc will also call resource.Add. If it is false, SyncFunc will not be assigned.
type PatchClient ¶
type PatchClient interface {
PatchInto(context.Context, resource.Identifier, resource.PatchRequest, resource.PatchOptions, resource.Object) error
}
PatchClient is a Client capable of making PatchInto requests. This is used by OpinionatedWatch to update finalizers.
type ReconcileAction ¶ added in v0.10.0
type ReconcileAction int
ReconcileAction describes the action that triggered reconciliation.
const ( // ReconcileActionUnknown represents an Unknown ReconcileAction ReconcileActionUnknown ReconcileAction = iota // ReconcileActionCreated indicates that the resource to reconcile has been created. // Note that this action may also be used on initial start-up of some informer-based implementations, // such as the KubernetesBasedInformer. To instead receive Resync actions for these events, // use the OpinionatedReconciler. ReconcileActionCreated // ReconcileActionUpdated indicates that the resource to reconcile has been updated. ReconcileActionUpdated // ReconcileActionDeleted indicates that the resource to reconcile has been deleted. // Note that if the resource has Finalizers attached to it, a ReconcileActionUpdated will be used to indicate // "tombstoning" of the resource where DeletionTimestamp is non-nil and Finalizers may only be removed. // On completion of the actual delete from the API server once the Finalizers list is empty, // a Delete reconcile action will be triggered. ReconcileActionDeleted // ReconcileActionResynced indicates a periodic or initial re-sync of existing resources in the API server. // Note that not all implementations support this action (KubernetesBasedInformer will only trigger Created, // Updated, and Deleted actions. You can use OpinionatedReconciler to introduce Resync events on start instead // of Add events). ReconcileActionResynced )
func ReconcileActionFromResourceAction ¶ added in v0.10.0
func ReconcileActionFromResourceAction(action ResourceAction) ReconcileAction
ReconcileActionFromResourceAction returns the equivalent ReconcileAction from a provided ResourceAction. If there is no equivalent, it returns ReconcileActionUnknown.
type ReconcileRequest ¶ added in v0.10.0
type ReconcileRequest struct { // Action is the action that triggered this ReconcileRequest Action ReconcileAction // Object is the object at the time of the received action Object resource.Object // State is a user-defined map of state values that can be provided on retried ReconcileRequests. // See State in ReconcileResult. It will always be nil on an initial Reconcile call, // and will only be non-nil if a prior Reconcile call with this ReconcileRequest returned a State // in its ReconcileResult alongside either a RequeueAfter or an error. State map[string]any }
ReconcileRequest contains the action which took place, and a snapshot of the object at that point in time. The Object in the ReconcileRequest is not guaranteed to be the current state of the object in-storage, as other actions may have taken place subsequently.
Controllers such as InformerController contain logic to dequeue ReconcileRequests if subsequent actions are received for the same object.
type ReconcileResult ¶ added in v0.10.0
type ReconcileResult struct { // RequeueAfter is a duration after which the Reconcile action which returned this result should be retried. // If nil, the Reconcile action will not be requeued. RequeueAfter *time.Duration // State can be used alongside RequeueAfter to add the provided state map to the ReconcileRequest supplied in the // future Reconcile call. This allows a Reconcile to "partially complete" and not have to re-do tasks // if it needs to wait on an additional bit of information or if a particular call results in a transient failure. State map[string]any }
ReconcileResult is the status of a successful Reconcile action. "Success" in this case simply indicates that unexpected errors did not occur, as the ReconcileResult can specify that the Reconcile action should be re-queued to run again after a period of time has elapsed.
type Reconciler ¶ added in v0.10.0
type Reconciler interface { // Reconcile should be called whenever any action is received for a relevant object. // The action and object at the time the action was received are contained within the ReconcileRequest. // If the returned ReconcileResult has a non-nil RequeueAfter, the managing controller should requeue // the Reconcile action, with the same ReconcileRequest and context, after that duration has elapsed. // If the call returns an error, the Reconcile action should be requeued according to the retry policy // of the controller. Reconcile(ctx context.Context, req ReconcileRequest) (ReconcileResult, error) }
Reconciler is an interface which describes an object which implements simple Reconciliation behavior.
type ResourceAction ¶ added in v0.9.9
type ResourceAction string
func ResourceActionFromReconcileAction ¶ added in v0.10.0
func ResourceActionFromReconcileAction(action ReconcileAction) ResourceAction
ResourceActionFromReconcileAction returns the equivalent ResourceAction from a provided ReconcileAction. If there is no equivalent, it returns an empty ResourceAction.
type ResourceObjectWrapper ¶
ResourceObjectWrapper describes anything which wraps a resource.Object, such that it can be extracted.
type ResourceWatcher ¶
type ResourceWatcher interface { Add(context.Context, resource.Object) error Update(ctx context.Context, old, new resource.Object) error Delete(context.Context, resource.Object) error }
ResourceWatcher describes an object which handles Add/Update/Delete actions for a resource
type RestConfig ¶ added in v0.17.6
type RestConfigOptions ¶ added in v0.17.6
type RestConfigOptions struct { // QPS indicates the maximum QPS to the master from this client. // If it's zero, the created RESTClient will use DefaultQPS: 50 QPS float64 // Maximum burst for throttle. // If it's zero, the created RESTClient will use DefaultBurst: 300. Burst int // NoLimit removes client-side request throttling completely. NoLimit bool }
RestConfigOptions are options which are applied when loading RestConfigs.
type RetryDequeuePolicy ¶ added in v0.9.9
type RetryDequeuePolicy func(newAction ResourceAction, newObject resource.Object, retryAction ResourceAction, retryObject resource.Object, retryError error) bool
RetryDequeuePolicy is a function that defines when a retry should be dequeued when a new action is taken on a resource. It accepts information about the new action being taken, and information about the current queued retry, and returns `true` if the retry should be dequeued. A RetryDequeuePolicy may be called multiple times for the same action, depending on the number of pending retries for the object.
type RetryPolicy ¶
RetryPolicy is a function that defines whether an event should be retried, based on the error and number of attempts. It returns a boolean indicating whether another attempt should be made, and a time.Duration after which that attempt should be made again.
func ExponentialBackoffRetryPolicy ¶
func ExponentialBackoffRetryPolicy(initialDelay time.Duration, maxAttempts int) RetryPolicy
ExponentialBackoffRetryPolicy returns an Exponential Backoff RetryPolicy function, which follows the following formula: retry time = initialDelay * (2^attempt). If maxAttempts is exceeded, it will return false for the retry.
type Runner ¶ added in v0.22.0
type Runner struct {
// contains filtered or unexported fields
}
Runner runs an app.App as a standalone operator, capable of exposing admission (validation, mutation) and conversion as webhooks, and running a main control loop with reconcilers and watchers. It relies on the Kinds managed by the app.App already existing in the API server it talks to, either as CRD's or another type. It does not support certain advanced app.App functionality which is not natively supported by CRDs, such as arbitrary subresources (app.App.CallSubresource). It should be instantiated with NewRunner.
func NewRunner ¶ added in v0.22.0
func NewRunner(cfg RunnerConfig) (*Runner, error)
NewRunner creates a new, properly-initialized instance of a Runner
func (*Runner) Run ¶ added in v0.22.0
Run runs the Runner for the app built from the provided app.AppProvider, until the provided context.Context is closed, or an unrecoverable error occurs. If an app.App cannot be instantiated from the app.AppProvider, an error will be returned. Webserver components of Run (such as webhooks and the prometheus exporter) will remain running so long as at least one Run() call is still active.
type RunnerConfig ¶ added in v0.22.0
type RunnerConfig struct { // WebhookConfig contains configuration information for exposing k8s webhooks. // This can be empty if your App does not implement ValidatorApp, MutatorApp, or ConversionApp WebhookConfig RunnerWebhookConfig // MetricsConfig contains the configuration for exposing prometheus metrics, if desired MetricsConfig RunnerMetricsConfig // KubeConfig is the kubernetes rest.Config to use when communicating with the API server KubeConfig rest.Config // Filesystem is an fs.FS that can be used in lieu of the OS filesystem. // if empty, it defaults to os.DirFS(".") Filesystem fs.FS }
type RunnerMetricsConfig ¶ added in v0.22.0
type RunnerMetricsConfig struct { metrics.ExporterConfig Enabled bool Namespace string }
RunnerMetricsConfig contains configuration information for exposing prometheus metrics
type RunnerWebhookConfig ¶ added in v0.22.0
type SimpleReconciler ¶ added in v0.10.0
type SimpleReconciler struct {
ReconcileFunc func(context.Context, ReconcileRequest) (ReconcileResult, error)
}
SimpleReconciler is a simple Reconciler implementation that calls ReconcileFunc if non-nil on Reconcile requests.
func (*SimpleReconciler) Reconcile ¶ added in v0.10.0
func (s *SimpleReconciler) Reconcile(ctx context.Context, req ReconcileRequest) (ReconcileResult, error)
Reconcile calls ReconcileFunc if non-nil and returns the response, or returns an empty ReconcileResult and nil error if ReconcileFunc is nil.
type SimpleWatcher ¶
type SimpleWatcher struct { AddFunc func(context.Context, resource.Object) error UpdateFunc func(context.Context, resource.Object, resource.Object) error DeleteFunc func(context.Context, resource.Object) error }
SimpleWatcher is a struct that implements ResourceWatcher, but takes no action on its own. For each method in (Add, Update, Delete) the corresponding exported function field is called, if non-nil.
type TypedReconcileRequest ¶ added in v0.10.0
type TypedReconcileRequest[T resource.Object] struct { // Action is the actions which triggered this TypedReconcileRequest Action ReconcileAction // Object is the object on which the Action was performed, at the point in time of that Action Object T // State is a user-defined map of state values that can be provided on retried ReconcileRequests. // See State in ReconcileResult. It will always be nil on an initial Reconcile call, // and will only be non-nil if a prior Reconcile call with this TypedReconcileRequest returned a State // in its ReconcileResult alongside either a RequeueAfter or an error. State map[string]any }
TypedReconcileRequest is a variation of ReconcileRequest which uses a concretely-typed Object, rather than the interface resource.Object. It is used by TypedReconciler in its ReconcileFunc.
type TypedReconciler ¶ added in v0.10.0
type TypedReconciler[T resource.Object] struct { // ReconcileFunc is called by TypedReconciler.Reconcile using the T-typed Object instead of a resource.Object. ReconcileFunc func(context.Context, TypedReconcileRequest[T]) (ReconcileResult, error) }
TypedReconciler is a variant of SimpleReconciler in which a user can specify the underlying type of the resource.Object which is in the provided ReconcileRequest. Reconcile() will then attempt to cast the resource.Object in the ReconcileRequest into the provided T type and produce a TypedReconcileRequest, which will be passed to ReconcileFunc.
func (*TypedReconciler[T]) Reconcile ¶ added in v0.10.0
func (t *TypedReconciler[T]) Reconcile(ctx context.Context, request ReconcileRequest) (ReconcileResult, error)
Reconcile tries to cast the Object in ReconcileRequest into the T-typed resource.Object, then creates a TypedReconcileRequest with the cast object and the same Action and State, which is passed to ReconcileFunc. If the Object cannot be cast, it returns an empty ReconcileResult with an error of type *CannotCastError. If ReconcileFunc is nil, it returns an empty ReconcileResult with a nil error.