controller-runtime: Index | Examples | Files | Directories

package manager

import ""

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.



Package Files

doc.go internal.go manager.go

func DefaultNewClient Uses

func DefaultNewClient(cache cache.Cache, config *rest.Config, options client.Options) (client.Client, error)

DefaultNewClient creates the default caching client

type LeaderElectionRunnable Uses

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 Uses

type Manager interface {
    // Add will set requested dependencies on the component, and cause the component to be
    // started when Start is called.  Add will inject any dependencies for which the argument
    // implements the inject interface - e.g. inject.Client.
    // 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{}

    // SetFields will set any dependencies on an object for which the object has implemented the inject
    // interface - e.g. inject.Client.
    SetFields(interface{}) error

    // AddMetricsExtraHandler adds an extra handler served on path to the http server that serves metrics.
    // Might be useful to register some diagnostic endpoints e.g. pprof. Note that these endpoints meant to be
    // sensitive and shouldn't be exposed publicly.
    // If the simple path -> handler mapping offered here is not enough, a new http server/listener should be added as
    // Runnable to the manager via Add method.
    AddMetricsExtraHandler(path string, handler http.Handler) error

    // 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 Stop channel is closed.
    // 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(<-chan struct{}) error

    // GetConfig returns an initialized Config
    GetConfig() *rest.Config

    // GetScheme returns an initialized Scheme
    GetScheme() *runtime.Scheme

    // GetClient returns a client configured with the Config. This client may
    // not be a fully "direct" client -- it may read from a cache, for
    // instance.  See Options.NewClient for more information on how the default
    // implementation works.
    GetClient() client.Client

    // GetFieldIndexer returns a client.FieldIndexer configured with the client
    GetFieldIndexer() client.FieldIndexer

    // GetCache returns a cache.Cache
    GetCache() cache.Cache

    // GetEventRecorderFor returns a new EventRecorder for the provided name
    GetEventRecorderFor(name string) record.EventRecorder

    // GetRESTMapper returns a RESTMapper
    GetRESTMapper() meta.RESTMapper

    // GetAPIReader returns a reader that will be configured to use the API server.
    // This should be used sparingly and only when the client does not fit your
    // use case.
    GetAPIReader() client.Reader

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

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

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

This example adds a Runnable for the Manager to Start.


err := mgr.Add(manager.RunnableFunc(func(<-chan struct{}) error {
    // Do something
    return nil
if err != nil {
    log.Error(err, "unable add a runnable to the manager")

This example starts a Manager that has had Runnables added.


err := mgr.Start(signals.SetupSignalHandler())
if err != nil {
    log.Error(err, "unable start the manager")

func New Uses

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

New returns a new Manager for creating Controllers.

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


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

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

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


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

mgr, err := manager.New(cfg, manager.Options{
    NewCache: cache.MultiNamespacedCacheBuilder([]string{"namespace1", "namespace2"}),
if err != nil {
    log.Error(err, "unable to set up manager")
log.Info("created manager", "manager", mgr)

type NewClientFunc Uses

type NewClientFunc func(cache cache.Cache, config *rest.Config, options client.Options) (client.Client, error)

NewClientFunc allows a user to define how to create a client

type Options Uses

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
    // idea to pass your own scheme in.  See the documentation in pkg/scheme for more information.
    Scheme *runtime.Scheme

    // MapperProvider provides the rest mapper used to map go types to Kubernetes APIs
    MapperProvider func(c *rest.Config) (meta.RESTMapper, error)

    // SyncPeriod determines the minimum frequency at which watched resources are
    // reconciled. A lower period will correct entropy more quickly, but reduce
    // responsiveness to change if there are many watched resources. Change this
    // value only if you know what you are doing. Defaults to 10 hours if unset.
    // there will a 10 percent jitter between the SyncPeriod of all controllers
    // so that all controllers will not send list requests simultaneously.
    SyncPeriod *time.Duration

    // 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 "configmapsleases". Change this value only if you know what you are doing.
    // Otherwise, users of your controller 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.
    // If you want to migrate to the "leases" resource lock, 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, the resource lock was set to "configmaps".
    // Please keep this in mind, when planning a proper migration path for your controller.
    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

    // 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

    // Namespace if specified restricts the manager's cache to watch objects in
    // the desired namespace Defaults to all namespaces
    // Note: If a namespace is specified, controllers can still Watch for a
    // cluster-scoped resource (e.g Node).  For namespaced resources the cache
    // will only hold objects from the desired namespace.
    Namespace string

    // MetricsBindAddress is the TCP address that the controller should bind to
    // for serving prometheus metrics.
    // It can be set to "0" to disable the metrics serving.
    MetricsBindAddress string

    // HealthProbeBindAddress is the TCP address that the controller should bind to
    // for serving health probes
    HealthProbeBindAddress string

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

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

    // Port is the port that the webhook server serves at.
    // It is used to set webhook.Server.Port.
    Port int
    // Host is the hostname that the webhook server binds to.
    // It is used to set webhook.Server.Host.
    Host string

    // CertDir is the directory that contains the server key and certificate.
    // if not set, webhook server would look up the server key and certificate in
    // {TempDir}/k8s-webhook-server/serving-certs. The server key and certificate
    // must be named tls.key and tls.crt, respectively.
    CertDir string

    // 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.
    NewCache cache.NewCacheFunc

    // NewClient will create the client to be used by the manager.
    // If not set this will create the default DelegatingClient that will
    // use the cache for reads and the client for writes.
    NewClient NewClientFunc

    // DryRunClient specifies whether the client should be configured to enforce
    // dryRun mode.
    DryRunClient bool

    // 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 leadere election lease is lost.
    GracefulShutdownTimeout *time.Duration
    // contains filtered or unexported fields

Options are the arguments for creating a new Manager

type Runnable Uses

type Runnable interface {
    // Start starts running the component.  The component will stop running
    // when the channel is closed.  Start blocks until the channel is closed or
    // an error occurs.
    Start(<-chan struct{}) error

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

type RunnableFunc Uses

type RunnableFunc func(<-chan struct{}) error

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

func (RunnableFunc) Start Uses

func (r RunnableFunc) Start(s <-chan struct{}) error

Start implements Runnable


signalsPackage signals contains libraries for handling signals to gracefully shutdown the manager in combination with Kubernetes pod graceful termination policy.

Package manager imports 29 packages (graph) and is imported by 1179 packages. Updated 2020-09-22. Refresh now. Tools for package owners.