manager

package
v0.17.3 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2024 License: Apache-2.0 Imports: 35 Imported by: 8,248

Documentation

Overview

Package manager is required to create Controllers and provides shared dependencies such as clients, caches, schemes, etc. Controllers must be started by calling Manager.Start.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BaseContextFunc added in v0.12.0

type BaseContextFunc func() context.Context

BaseContextFunc is a function used to provide a base Context to Runnables managed by a Manager.

type LeaderElectionRunnable added in v0.2.0

type LeaderElectionRunnable interface {
	// NeedLeaderElection returns true if the Runnable needs to be run in the leader election mode.
	// e.g. controllers need to be run in leader election mode, while webhook server doesn't.
	NeedLeaderElection() bool
}

LeaderElectionRunnable knows if a Runnable needs to be run in the leader election mode.

type Manager

type Manager interface {
	// Cluster holds a variety of methods to interact with a cluster.
	cluster.Cluster

	// Add will set requested dependencies on the component, and cause the component to be
	// started when Start is called.
	// Depending on if a Runnable implements LeaderElectionRunnable interface, a Runnable can be run in either
	// non-leaderelection mode (always running) or leader election mode (managed by leader election if enabled).
	Add(Runnable) error

	// Elected is closed when this manager is elected leader of a group of
	// managers, either because it won a leader election or because no leader
	// election was configured.
	Elected() <-chan struct{}

	// AddHealthzCheck allows you to add Healthz checker
	AddHealthzCheck(name string, check healthz.Checker) error

	// AddReadyzCheck allows you to add Readyz checker
	AddReadyzCheck(name string, check healthz.Checker) error

	// Start starts all registered Controllers and blocks until the context is cancelled.
	// Returns an error if there is an error starting any controller.
	//
	// If LeaderElection is used, the binary must be exited immediately after this returns,
	// otherwise components that need leader election might continue to run after the leader
	// lock was lost.
	Start(ctx context.Context) error

	// GetWebhookServer returns a webhook.Server
	GetWebhookServer() webhook.Server

	// GetLogger returns this manager's logger.
	GetLogger() logr.Logger

	// GetControllerOptions returns controller global configuration options.
	GetControllerOptions() config.Controller
}

Manager initializes shared dependencies such as Caches and Clients, and provides them to Runnables. A Manager is required to create Controllers.

Example (Add)

This example adds a Runnable for the Manager to Start.

package main

import (
	"context"
	"os"

	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/manager"
)

var (
	mgr manager.Manager

	log = logf.Log.WithName("manager-examples")
)

func main() {
	err := mgr.Add(manager.RunnableFunc(func(context.Context) error {
		// Do something
		return nil
	}))
	if err != nil {
		log.Error(err, "unable add a runnable to the manager")
		os.Exit(1)
	}
}
Output:

Example (Start)

This example starts a Manager that has had Runnables added.

package main

import (
	"os"

	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/manager"
	"sigs.k8s.io/controller-runtime/pkg/manager/signals"
)

var (
	mgr manager.Manager
	// NB: don't call SetLogger in init(), or else you'll mess up logging in the main suite.
	log = logf.Log.WithName("manager-examples")
)

func main() {
	if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
		log.Error(err, "unable start the manager")
		os.Exit(1)
	}
}
Output:

func New

func New(config *rest.Config, options Options) (Manager, error)

New returns a new Manager for creating Controllers. Note that if ContentType in the given config is not set, "application/vnd.kubernetes.protobuf" will be used for all built-in resources of Kubernetes, and "application/json" is for other types including all CRD resources.

Example

This example creates a new Manager that can be used with controller.New to create Controllers.

package main

import (
	"os"

	"sigs.k8s.io/controller-runtime/pkg/client/config"

	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/manager"
)

var

// NB: don't call SetLogger in init(), or else you'll mess up logging in the main suite.
log = logf.Log.WithName("manager-examples")

func main() {
	cfg, err := config.GetConfig()
	if err != nil {
		log.Error(err, "unable to get kubeconfig")
		os.Exit(1)
	}

	mgr, err := manager.New(cfg, manager.Options{})
	if err != nil {
		log.Error(err, "unable to set up manager")
		os.Exit(1)
	}
	log.Info("created manager", "manager", mgr)
}
Output:

Example (LimitToNamespaces)

This example creates a new Manager that has a cache scoped to a list of namespaces.

package main

import (
	"os"

	"k8s.io/client-go/rest"
	"sigs.k8s.io/controller-runtime/pkg/cache"
	"sigs.k8s.io/controller-runtime/pkg/client/config"

	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/manager"
)

var

// NB: don't call SetLogger in init(), or else you'll mess up logging in the main suite.
log = logf.Log.WithName("manager-examples")

func main() {
	cfg, err := config.GetConfig()
	if err != nil {
		log.Error(err, "unable to get kubeconfig")
		os.Exit(1)
	}

	mgr, err := manager.New(cfg, manager.Options{
		NewCache: func(config *rest.Config, opts cache.Options) (cache.Cache, error) {
			opts.DefaultNamespaces = map[string]cache.Config{
				"namespace1": {},
				"namespace2": {},
			}
			return cache.New(config, opts)
		}},
	)
	if err != nil {
		log.Error(err, "unable to set up manager")
		os.Exit(1)
	}
	log.Info("created manager", "manager", mgr)
}
Output:

type Options

type Options struct {
	// Scheme is the scheme used to resolve runtime.Objects to GroupVersionKinds / Resources.
	// Defaults to the kubernetes/client-go scheme.Scheme, but it's almost always better
	// to pass your own scheme in. See the documentation in pkg/scheme for more information.
	//
	// If set, the Scheme will be used to create the default Client and Cache.
	Scheme *runtime.Scheme

	// MapperProvider provides the rest mapper used to map go types to Kubernetes APIs.
	//
	// If set, the RESTMapper returned by this function is used to create the RESTMapper
	// used by the Client and Cache.
	MapperProvider func(c *rest.Config, httpClient *http.Client) (meta.RESTMapper, error)

	// Cache is the cache.Options that will be used to create the default Cache.
	// By default, the cache will watch and list requested objects in all namespaces.
	Cache cache.Options

	// NewCache is the function that will create the cache to be used
	// by the manager. If not set this will use the default new cache function.
	//
	// When using a custom NewCache, the Cache options will be passed to the
	// NewCache function.
	//
	// NOTE: LOW LEVEL PRIMITIVE!
	// Only use a custom NewCache if you know what you are doing.
	NewCache cache.NewCacheFunc

	// Client is the client.Options that will be used to create the default Client.
	// By default, the client will use the cache for reads and direct calls for writes.
	Client client.Options

	// NewClient is the func that creates the client to be used by the manager.
	// If not set this will create a Client backed by a Cache for read operations
	// and a direct Client for write operations.
	//
	// When using a custom NewClient, the Client options will be passed to the
	// NewClient function.
	//
	// NOTE: LOW LEVEL PRIMITIVE!
	// Only use a custom NewClient if you know what you are doing.
	NewClient client.NewClientFunc

	// Logger is the logger that should be used by this manager.
	// If none is set, it defaults to log.Log global logger.
	Logger logr.Logger

	// LeaderElection determines whether or not to use leader election when
	// starting the manager.
	LeaderElection bool

	// LeaderElectionResourceLock determines which resource lock to use for leader election,
	// defaults to "leases". Change this value only if you know what you are doing.
	//
	// If you are using `configmaps`/`endpoints` resource lock and want to migrate to "leases",
	// you might do so by migrating to the respective multilock first ("configmapsleases" or "endpointsleases"),
	// which will acquire a leader lock on both resources.
	// After all your users have migrated to the multilock, you can go ahead and migrate to "leases".
	// Please also keep in mind, that users might skip versions of your controller.
	//
	// Note: before controller-runtime version v0.7, it was set to "configmaps".
	// And from v0.7 to v0.11, the default was "configmapsleases", which was
	// used to migrate from configmaps to leases.
	// Since the default was "configmapsleases" for over a year, spanning five minor releases,
	// any actively maintained operators are very likely to have a released version that uses
	// "configmapsleases". Therefore defaulting to "leases" should be safe since v0.12.
	//
	// So, what do you have to do when you are updating your controller-runtime dependency
	// from a lower version to v0.12 or newer?
	// - If your operator matches at least one of these conditions:
	//   - the LeaderElectionResourceLock in your operator has already been explicitly set to "leases"
	//   - the old controller-runtime version is between v0.7.0 and v0.11.x and the
	//     LeaderElectionResourceLock wasn't set or was set to "leases"/"configmapsleases"/"endpointsleases"
	//   feel free to update controller-runtime to v0.12 or newer.
	// - Otherwise, you may have to take these steps:
	//   1. update controller-runtime to v0.12 or newer in your go.mod
	//   2. set LeaderElectionResourceLock to "configmapsleases" (or "endpointsleases")
	//   3. package your operator and upgrade it in all your clusters
	//   4. only if you have finished 3, you can remove the LeaderElectionResourceLock to use the default "leases"
	// Otherwise, your operator might end up with multiple running instances that
	// each acquired leadership through different resource locks during upgrades and thus
	// act on the same resources concurrently.
	LeaderElectionResourceLock string

	// LeaderElectionNamespace determines the namespace in which the leader
	// election resource will be created.
	LeaderElectionNamespace string

	// LeaderElectionID determines the name of the resource that leader election
	// will use for holding the leader lock.
	LeaderElectionID string

	// LeaderElectionConfig can be specified to override the default configuration
	// that is used to build the leader election client.
	LeaderElectionConfig *rest.Config

	// LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily
	// when the Manager ends. This requires the binary to immediately end when the
	// Manager is stopped, otherwise this setting is unsafe. Setting this significantly
	// speeds up voluntary leader transitions as the new leader doesn't have to wait
	// LeaseDuration time first.
	LeaderElectionReleaseOnCancel bool

	// LeaderElectionResourceLockInterface allows to provide a custom resourcelock.Interface that was created outside
	// of the controller-runtime. If this value is set the options LeaderElectionID, LeaderElectionNamespace,
	// LeaderElectionResourceLock, LeaseDuration, RenewDeadline and RetryPeriod will be ignored. This can be useful if you
	// want to use a locking mechanism that is currently not supported, like a MultiLock across two Kubernetes clusters.
	LeaderElectionResourceLockInterface resourcelock.Interface

	// LeaseDuration is the duration that non-leader candidates will
	// wait to force acquire leadership. This is measured against time of
	// last observed ack. Default is 15 seconds.
	LeaseDuration *time.Duration

	// RenewDeadline is the duration that the acting controlplane will retry
	// refreshing leadership before giving up. Default is 10 seconds.
	RenewDeadline *time.Duration

	// RetryPeriod is the duration the LeaderElector clients should wait
	// between tries of actions. Default is 2 seconds.
	RetryPeriod *time.Duration

	// Metrics are the metricsserver.Options that will be used to create the metricsserver.Server.
	Metrics metricsserver.Options

	// HealthProbeBindAddress is the TCP address that the controller should bind to
	// for serving health probes
	// It can be set to "0" or "" to disable serving the health probe.
	HealthProbeBindAddress string

	// Readiness probe endpoint name, defaults to "readyz"
	ReadinessEndpointName string

	// Liveness probe endpoint name, defaults to "healthz"
	LivenessEndpointName string

	// PprofBindAddress is the TCP address that the controller should bind to
	// for serving pprof.
	// It can be set to "" or "0" to disable the pprof serving.
	// Since pprof may contain sensitive information, make sure to protect it
	// before exposing it to public.
	PprofBindAddress string

	// WebhookServer is an externally configured webhook.Server. By default,
	// a Manager will create a server via webhook.NewServer with default settings.
	// If this is set, the Manager will use this server instead.
	WebhookServer webhook.Server

	// BaseContext is the function that provides Context values to Runnables
	// managed by the Manager. If a BaseContext function isn't provided, Runnables
	// will receive a new Background Context instead.
	BaseContext BaseContextFunc

	// EventBroadcaster records Events emitted by the manager and sends them to the Kubernetes API
	// Use this to customize the event correlator and spam filter
	//
	// Deprecated: using this may cause goroutine leaks if the lifetime of your manager or controllers
	// is shorter than the lifetime of your process.
	EventBroadcaster record.EventBroadcaster

	// GracefulShutdownTimeout is the duration given to runnable to stop before the manager actually returns on stop.
	// To disable graceful shutdown, set to time.Duration(0)
	// To use graceful shutdown without timeout, set to a negative duration, e.G. time.Duration(-1)
	// The graceful shutdown is skipped for safety reasons in case the leader election lease is lost.
	GracefulShutdownTimeout *time.Duration

	// Controller contains global configuration options for controllers
	// registered within this manager.
	// +optional
	Controller config.Controller
	// contains filtered or unexported fields
}

Options are the arguments for creating a new Manager.

Example (AndFrom)

This example will populate Options from a custom config file using defaults.

package main

import (
	"os"

	"sigs.k8s.io/controller-runtime/pkg/client/config"

	conf "sigs.k8s.io/controller-runtime/pkg/config"

	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/manager"
)

var

// NB: don't call SetLogger in init(), or else you'll mess up logging in the main suite.
log = logf.Log.WithName("manager-examples")

func main() {
	opts := manager.Options{}
	if _, err := opts.AndFrom(conf.File()); err != nil {
		log.Error(err, "unable to load config")
		os.Exit(1)
	}

	cfg, err := config.GetConfig()
	if err != nil {
		log.Error(err, "unable to get kubeconfig")
		os.Exit(1)
	}

	mgr, err := manager.New(cfg, opts)
	if err != nil {
		log.Error(err, "unable to set up manager")
		os.Exit(1)
	}
	log.Info("created manager", "manager", mgr)
}
Output:

Example (AndFromOrDie)

This example will populate Options from a custom config file using defaults and will panic if there are errors.

package main

import (
	"os"

	"sigs.k8s.io/controller-runtime/pkg/client/config"

	conf "sigs.k8s.io/controller-runtime/pkg/config"

	logf "sigs.k8s.io/controller-runtime/pkg/log"
	"sigs.k8s.io/controller-runtime/pkg/manager"
)

var

// NB: don't call SetLogger in init(), or else you'll mess up logging in the main suite.
log = logf.Log.WithName("manager-examples")

func main() {
	cfg, err := config.GetConfig()
	if err != nil {
		log.Error(err, "unable to get kubeconfig")
		os.Exit(1)
	}

	mgr, err := manager.New(cfg, manager.Options{}.AndFromOrDie(conf.File()))
	if err != nil {
		log.Error(err, "unable to set up manager")
		os.Exit(1)
	}
	log.Info("created manager", "manager", mgr)
}
Output:

func (Options) AndFrom deprecated added in v0.7.0

AndFrom will use a supplied type and convert to Options any options already set on Options will be ignored, this is used to allow cli flags to override anything specified in the config file.

Deprecated: This function has been deprecated and will be removed in a future release, The Component Configuration package has been unmaintained for over a year and is no longer actively developed. Users should migrate to their own configuration format and configure Manager.Options directly. See https://github.com/kubernetes-sigs/controller-runtime/issues/895 for more information, feedback, and comments.

func (Options) AndFromOrDie deprecated added in v0.7.0

func (o Options) AndFromOrDie(loader config.ControllerManagerConfiguration) Options

AndFromOrDie will use options.AndFrom() and will panic if there are errors.

Deprecated: This function has been deprecated and will be removed in a future release, The Component Configuration package has been unmaintained for over a year and is no longer actively developed. Users should migrate to their own configuration format and configure Manager.Options directly. See https://github.com/kubernetes-sigs/controller-runtime/issues/895 for more information, feedback, and comments.

type Runnable

type Runnable interface {
	// Start starts running the component.  The component will stop running
	// when the context is closed. Start blocks until the context is closed or
	// an error occurs.
	Start(context.Context) error
}

Runnable allows a component to be started. It's very important that Start blocks until it's done running.

type RunnableFunc

type RunnableFunc func(context.Context) error

RunnableFunc implements Runnable using a function. It's very important that the given function block until it's done running.

func (RunnableFunc) Start

func (r RunnableFunc) Start(ctx context.Context) error

Start implements Runnable.

Directories

Path Synopsis
internal
Package signals contains libraries for handling signals to gracefully shutdown the manager in combination with Kubernetes pod graceful termination policy.
Package signals contains libraries for handling signals to gracefully shutdown the manager in combination with Kubernetes pod graceful termination policy.

Jump to

Keyboard shortcuts

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