controller-runtime
Repo for the controller-runtime subproject of kubebuilder (sig-apimachinery)
Top Related Projects
Go client for Kubernetes.
SDK for building Kubernetes applications. Provides high level APIs, useful abstractions, and project scaffolding.
Production-Grade Container Scheduling and Management
Kubebuilder - SDK for building Kubernetes APIs using CRDs
Customization of kubernetes YAML configurations
Quick Overview
Kubernetes controller-runtime is a set of Go libraries for building Kubernetes APIs and controllers using CustomResourceDefinitions (CRDs). It simplifies the process of creating custom controllers and operators for Kubernetes, providing high-level abstractions and utilities to streamline development.
Pros
- Simplifies the development of Kubernetes controllers and operators
- Provides a well-structured framework for handling Kubernetes resources
- Offers built-in support for leader election, metrics, and health probes
- Integrates seamlessly with other Kubernetes-related tools and libraries
Cons
- Steep learning curve for developers new to Kubernetes concepts
- Limited documentation for advanced use cases
- May introduce additional complexity for simple controller implementations
- Requires keeping up with Kubernetes API changes and versioning
Code Examples
- Creating a basic controller:
import (
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
)
func NewController(mgr manager.Manager) error {
return builder.ControllerManagedBy(mgr).
For(&myv1.MyCustomResource{}).
Complete(&MyReconciler{client: mgr.GetClient()})
}
- Implementing a Reconciler:
type MyReconciler struct {
client client.Client
}
func (r *MyReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var cr myv1.MyCustomResource
if err := r.client.Get(ctx, req.NamespacedName, &cr); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
// Implement reconciliation logic here
return ctrl.Result{}, nil
}
- Setting up the manager and starting the controller:
import (
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/manager/signals"
)
func main() {
mgr, err := manager.New(config, manager.Options{})
if err != nil {
// Handle error
}
if err := NewController(mgr); err != nil {
// Handle error
}
if err := mgr.Start(signals.SetupSignalHandler()); err != nil {
// Handle error
}
}
Getting Started
To start using controller-runtime, follow these steps:
-
Install the library:
go get sigs.k8s.io/controller-runtime
-
Import the necessary packages in your Go code:
import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/builder" )
-
Create a new manager and implement your controller logic as shown in the code examples above.
-
Build and run your controller, ensuring it has the necessary RBAC permissions to interact with the Kubernetes API server.
Competitor Comparisons
Go client for Kubernetes.
Pros of client-go
- Lower-level API offering more fine-grained control over Kubernetes interactions
- Broader scope, covering more Kubernetes resources and operations
- More suitable for applications that need direct access to Kubernetes API
Cons of client-go
- Requires more boilerplate code for common operations
- Steeper learning curve, especially for developers new to Kubernetes
- Less abstraction for handling common controller patterns
Code Comparison
controller-runtime example:
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{})
err = (&MyReconciler{
Client: mgr.GetClient(),
Log: ctrl.Log.WithName("controllers").WithName("My"),
}).SetupWithManager(mgr)
client-go example:
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
clientset, err := kubernetes.NewForConfig(config)
pod, err := clientset.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{})
Summary
controller-runtime is built on top of client-go and provides higher-level abstractions for building Kubernetes controllers. It simplifies common patterns and reduces boilerplate code. client-go offers more flexibility and control but requires more detailed implementation. Choose based on your project's specific needs and complexity.
SDK for building Kubernetes applications. Provides high level APIs, useful abstractions, and project scaffolding.
Pros of operator-sdk
- Provides a higher-level abstraction for building Kubernetes operators
- Includes scaffolding tools for quick project setup and code generation
- Offers built-in support for metrics, leader election, and versioning
Cons of operator-sdk
- Steeper learning curve due to additional abstractions and concepts
- Less flexibility in customizing the underlying controller logic
- Potentially larger binary size due to included dependencies
Code Comparison
operator-sdk:
import (
"github.com/operator-framework/operator-sdk/pkg/k8sutil"
"github.com/operator-framework/operator-sdk/pkg/leader"
"github.com/operator-framework/operator-sdk/pkg/ready"
)
controller-runtime:
import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
The operator-sdk code snippet shows imports specific to the SDK, including leader election and readiness checks. The controller-runtime code demonstrates core components for building controllers, such as client, manager, and reconciler interfaces.
While operator-sdk provides a more opinionated approach with additional features, controller-runtime offers a lower-level library for building custom controllers with greater flexibility. The choice between the two depends on the project's requirements and the developer's preference for abstraction level and control.
Production-Grade Container Scheduling and Management
Pros of kubernetes
- Comprehensive platform for container orchestration
- Extensive ecosystem with wide community support
- Offers a complete set of features for managing containerized applications
Cons of kubernetes
- Steep learning curve and complex setup
- Resource-intensive, requiring significant infrastructure
- Can be overkill for smaller projects or simpler deployments
Code comparison
kubernetes:
type Pod struct {
metav1.TypeMeta
metav1.ObjectMeta
Spec PodSpec
Status PodStatus
}
controller-runtime:
type Controller interface {
Reconcile(Request) (Result, error)
Watch(src source.Source, eventhandler handler.EventHandler, predicates ...predicate.Predicate) error
}
Key differences
- kubernetes is the core Kubernetes project, while controller-runtime is a library for building Kubernetes controllers and operators
- kubernetes provides the full container orchestration platform, whereas controller-runtime focuses on simplifying custom controller development
- controller-runtime offers a higher-level abstraction for interacting with Kubernetes resources, making it easier to build custom controllers
- kubernetes requires more setup and resources, while controller-runtime can be integrated into existing projects more easily
- controller-runtime is better suited for developing specific, custom functionality on top of Kubernetes, while kubernetes provides the underlying infrastructure
Kubebuilder - SDK for building Kubernetes APIs using CRDs
Pros of kubebuilder
- Provides a higher-level abstraction for creating Kubernetes operators
- Includes scaffolding tools for quickly generating project structure and boilerplate code
- Offers built-in support for webhooks and conversion between API versions
Cons of kubebuilder
- Less flexibility compared to controller-runtime for custom implementations
- Steeper learning curve for developers new to Kubernetes concepts
- May generate unnecessary code for simpler use cases
Code Comparison
kubebuilder:
type MyCustomResource struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec MyCustomResourceSpec `json:"spec,omitempty"`
Status MyCustomResourceStatus `json:"status,omitempty"`
}
controller-runtime:
type MyCustomResource struct {
metav1.TypeMeta
metav1.ObjectMeta
Spec MyCustomResourceSpec
Status MyCustomResourceStatus
}
The code comparison shows that kubebuilder generates more opinionated struct tags for JSON serialization, while controller-runtime leaves this customization to the developer.
Customization of kubernetes YAML configurations
Pros of Kustomize
- Focused on declarative configuration management for Kubernetes resources
- Provides a simpler, template-free way to customize Kubernetes manifests
- Integrated into kubectl, making it easily accessible for users
Cons of Kustomize
- Limited to Kubernetes resource management, less versatile for general controller development
- May require additional tools for complex scenarios or advanced reconciliation logic
- Less suitable for building custom controllers or operators
Code Comparison
Kustomize example:
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml
- service.yaml
Controller-runtime example:
import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
func (r *Reconciler) Reconcile(ctx context.Context, req reconcile.Request) (reconcile.Result, error) {
// Reconciliation logic here
}
Summary
Kustomize is ideal for managing Kubernetes manifests and configurations, offering a straightforward approach to customization. Controller-runtime, on the other hand, provides a framework for building custom controllers and operators, offering more flexibility for complex Kubernetes-native applications. The choice between the two depends on the specific requirements of your project and the level of control you need over Kubernetes resources.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Kubernetes controller-runtime Project
The Kubernetes controller-runtime Project is a set of go libraries for building Controllers. It is leveraged by Kubebuilder and Operator SDK. Both are a great place to start for new projects. See Kubebuilder's Quick Start to see how it can be used.
Documentation:
- Package overview
- Basic controller using builder
- Creating a manager
- Creating a controller
- Examples
- Designs
Versioning, Maintenance, and Compatibility
The full documentation can be found at VERSIONING.md, but TL;DR:
Users:
- We follow Semantic Versioning (semver)
- Use releases with your dependency management to ensure that you get compatible code
- The main branch contains all the latest code, some of which may break compatibility (so "normal"
go get
is not recommended)
Contributors:
- All code PR must be labeled with :bug: (patch fixes), :sparkles: (backwards-compatible features), or :warning: (breaking changes)
- Breaking changes will find their way into the next major release, other changes will go into an semi-immediate patch or minor release
- For a quick PR template suggesting the right information, use one of these PR templates:
Compatibility
Every minor version of controller-runtime has been tested with a specific minor version of client-go. A controller-runtime minor version may be compatible with other client-go minor versions, but this is by chance and neither supported nor tested. In general, we create one minor version of controller-runtime for each minor version of client-go and other k8s.io/* dependencies.
The minimum Go version of controller-runtime is the highest minimum Go version of our Go dependencies. Usually, this will be identical to the minimum Go version of the corresponding k8s.io/* dependencies.
Compatible k8s.io/*, client-go and minimum Go versions can be looked up in our go.mod file.
k8s.io/*, client-go | minimum Go version | |
---|---|---|
CR v0.20 | v0.32 | 1.23 |
CR v0.19 | v0.31 | 1.22 |
CR v0.18 | v0.30 | 1.22 |
CR v0.17 | v0.29 | 1.21 |
CR v0.16 | v0.28 | 1.20 |
CR v0.15 | v0.27 | 1.20 |
FAQ
See FAQ.md
Community, discussion, contribution, and support
Learn how to engage with the Kubernetes community on the community page.
controller-runtime is a subproject of the kubebuilder project in sig apimachinery.
You can reach the maintainers of this project at:
- Slack channel: #controller-runtime
- Google Group: kubebuilder@googlegroups.com
Contributing
Contributions are greatly appreciated. The maintainers actively manage the issues list, and try to highlight issues suitable for newcomers. The project follows the typical GitHub pull request model. See CONTRIBUTING.md for more details. Before starting any work, please either comment on an existing issue, or file a new one.
Code of conduct
Participation in the Kubernetes community is governed by the Kubernetes Code of Conduct.
Top Related Projects
Go client for Kubernetes.
SDK for building Kubernetes applications. Provides high level APIs, useful abstractions, and project scaffolding.
Production-Grade Container Scheduling and Management
Kubebuilder - SDK for building Kubernetes APIs using CRDs
Customization of kubernetes YAML configurations
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot