Skip to content

Commit eb94491

Browse files
authored
Merge pull request kubernetes-sigs#551 from mengqiy/release-0.2
🏃 fast forward release-0.2 branch
2 parents aaddbd9 + 084b73e commit eb94491

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+1053
-474
lines changed

FAQ.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
**A**: Each controller should only reconcile one object type. Other
66
affected objects should be mapped to a single type of root object, using
77
the `EnqueueRequestForOwner` or `EnqueueRequestsFromMapFunc` event
8-
handlers, and potentially indicies. Then, your Reconcile method should
8+
handlers, and potentially indices. Then, your Reconcile method should
99
attempt to reconcile *all* state for that given root objects.
1010

1111
### Q: How do I have different logic in my reconciler for different types of events (e.g. create, update, delete)?

TMP-LOGGING.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ or even write
3030
func (r *Reconciler) Reconcile(req reconcile.Request) (reconcile.Response, error) {
3131
logger := logger.WithValues("pod", req.NamespacedName)
3232
// do some stuff
33-
logger.Info("starting reconcilation")
33+
logger.Info("starting reconciliation")
3434
}
3535
```
3636

@@ -49,7 +49,7 @@ provides some helpers to make it easy to use
4949

5050
You can configure the logging implementation using
5151
`"sigs.k8s.io/controller-runtime/pkg/log".SetLogger`. That
52-
package also contains the convinience functions for setting up Zap.
52+
package also contains the convenience functions for setting up Zap.
5353

5454
You can get a handle to the the "root" logger using
5555
`"sigs.k8s.io/controller-runtime/pkg/log".Log`, and can then call
@@ -58,7 +58,7 @@ repeatedly to chain names together:
5858

5959
```go
6060
logger := log.Log.WithName("controller").WithName("replicaset")
61-
// in reconile...
61+
// in reconcile...
6262
logger = logger.WithValues("replicaset", req.NamespacedName)
6363
// later on in reconcile...
6464
logger.Info("doing things with pods", "pod", newPod)
@@ -86,7 +86,7 @@ Errors should *always* be logged with `log.Error`, which allows logr
8686
implementations to provide special handling of errors (for instance,
8787
providing stack traces in debug mode).
8888

89-
It's acceptible to log call `log.Error` with a nil error object. This
89+
It's acceptable to log call `log.Error` with a nil error object. This
9090
conveys that an error occurred in some capacity, but that no actual
9191
`error` object was involved.
9292

@@ -125,12 +125,12 @@ logic.
125125

126126
### Groups, Versions, and Kinds
127127

128-
- Kinds should not be logged alone (they're meanless alone). Use
128+
- Kinds should not be logged alone (they're meaningless alone). Use
129129
a `GroupKind` object to log them instead, or a `GroupVersionKind` when
130130
version is relevant.
131131

132132
- If you need to log an API version string, use `api version` as the key
133-
(formatted as with a `GroupVersion`, or as recieved directly from API
133+
(formatted as with a `GroupVersion`, or as received directly from API
134134
discovery).
135135

136136
### Objects and Types

VERSIONING.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ greatest code, including breaking changes, happens on master.
6666
The *release-X* branches contain stable, backwards compatible code. Every
6767
major (X) release, a new such branch is created. It is from these
6868
branches that minor and patch releases are tagged. If some cases, it may
69-
be neccessary open PRs for bugfixes directly against stable branches, but
69+
be necessary open PRs for bugfixes directly against stable branches, but
7070
this should generally not be the case.
7171

7272
The maintainers are responsible for updating the contents of this branch;
@@ -131,7 +131,7 @@ branch, except in exceptional circumstances. Patches will be backported
131131
to maintained stable versions, as needed.
132132

133133
Major releases are done shortly after a breaking change is merged -- once
134-
a breaking change is merged, the next release *must* be a major revison.
134+
a breaking change is merged, the next release *must* be a major revision.
135135
We don't intend to have a lot of these, so we may put off merging breaking
136136
PRs until a later date.
137137

@@ -172,9 +172,9 @@ have to rewrite their code when they eventually upgrade, and for
172172
maintainers/contributors, who have to deal with differences between master
173173
and stable branches.
174174

175-
That being said, we'll occaisonally want to make breaking changes. They'll
175+
That being said, we'll occasionally want to make breaking changes. They'll
176176
be merged onto master, and will then trigger a major release (see [Release
177-
Proccess](#release-process)). Because breaking changes induce a major
177+
Process](#release-process)). Because breaking changes induce a major
178178
revision, the maintainers may delay a particular breaking change until
179179
a later date when they are ready to make a major revision with a few
180180
breaking changes.
@@ -187,7 +187,7 @@ Maintainers should treat breaking changes with caution, and evaluate
187187
potential non-breaking solutions (see below).
188188

189189
Note that API breakage in public APIs due to dependencies will trigger
190-
a major revision, so you may occaisonally need to have a major release
190+
a major revision, so you may occasionally need to have a major release
191191
anyway, due to changes in libraries like `k8s.io/client-go` or
192192
`k8s.io/apimachinery`.
193193

doc.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ limitations under the License.
6464
// sources (pkg/source), like Kubernetes API object changes, to event handlers
6565
// (pkg/handler), like "enqueue a reconcile request for the object owner".
6666
// Predicates (pkg/predicate) can be used to filter which events actually
67-
// trigger reconciles. There are pre-written utilies for the common cases, and
67+
// trigger reconciles. There are pre-written utilities for the common cases, and
6868
// interfaces and helpers for advanced cases.
6969
//
7070
// Reconcilers

examples/README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Examples
2+
3+
These two examples represent the usage of `controller-runtime` libraries for built-in Kubernetes resources as well as custom resources.
4+
5+
### builtins/
6+
7+
This example implements a custom controller and webhooks for the *existing* ReplicaSet resource.
8+
9+
* `controller.go`: implements a reconciler for ReplicaSets
10+
* `mutatingwebhook.go`: implements a mutating webhook that adds an annotation to every incoming Pod ("example-mutating-admission-webhook" = "foo")
11+
* `validatingwebhook.go`: implements a validating webhook that checks to see if a Pod has the aforementioned annotation
12+
* `main.go`
13+
1. Creates a new manager
14+
2. Creates a new controller that watches both ReplicaSets and Pods and reconciles the objects with the implemented reconciler
15+
3. Registers the mutating and validating webhooks with the manager
16+
4. Starts the manager
17+
18+
### crd/
19+
20+
This example implements a *new* Kubernetes resource, ChaosPod, and creates a custom controller that watches it and webhooks that mutate and validate.
21+
22+
* `pkg/`
23+
* `resource.go`: defines the schema for the ChaosPod API and implements validate and mutate webhooks
24+
* `groupversion_info.go`: specifies the Group and Version for the ChaosPod API
25+
* `zz_generated.deepcopy.go`: deep copy functions generated by kubebuilder
26+
* `main.go`
27+
1. Creates a new manager
28+
2. Adds ChaosPod resource to the manager's schema
29+
3. Implements a reconciler to execute the desired behavior of the ChaosPod API
30+
4. Creates a new controller that watches ChaosPods and reconciles the objects with the implemented reconciler
31+
5. Adds ChaosPod webhooks to manager
32+
6. Starts the manager
33+
34+
## Deploying and Running
35+
36+
To install and run the provided examples, see the Kubebuilder [Quick Start](https://book.kubebuilder.io/quick-start.html).

examples/builtins/controller.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ type reconcileReplicaSet struct {
3838
var _ reconcile.Reconciler = &reconcileReplicaSet{}
3939

4040
func (r *reconcileReplicaSet) Reconcile(request reconcile.Request) (reconcile.Result, error) {
41-
// set up a convinient log object so we don't have to type request over and over again
41+
// set up a convenient log object so we don't have to type request over and over again
4242
log := r.log.WithValues("request", request)
4343

4444
// Fetch the ReplicaSet from the cache

examples/builtins/main.go

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ limitations under the License.
1717
package main
1818

1919
import (
20-
"flag"
2120
"os"
2221

2322
appsv1 "k8s.io/api/apps/v1"
@@ -37,11 +36,6 @@ import (
3736
var log = logf.Log.WithName("example-controller")
3837

3938
func main() {
40-
var disableWebhookConfigInstaller bool
41-
flag.BoolVar(&disableWebhookConfigInstaller, "disable-webhook-config-installer", false,
42-
"disable the installer in the webhook server, so it won't install webhook configuration resources during bootstrapping")
43-
44-
flag.Parse()
4539
logf.SetLogger(zap.Logger(false))
4640
entryLog := log.WithName("entrypoint")
4741

examples/crd/pkg/resource.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,16 @@ func (c *ChaosPod) ValidateUpdate(old runtime.Object) error {
9393
return nil
9494
}
9595

96+
// ValidateDelete implements webhookutil.validator so a webhook will be registered for the type
97+
func (c *ChaosPod) ValidateDelete() error {
98+
log.Info("validate delete", "name", c.Name)
99+
100+
if c.Spec.NextStop.Before(&metav1.Time{Time: time.Now()}) {
101+
return fmt.Errorf(".spec.nextStop must be later than current time")
102+
}
103+
return nil
104+
}
105+
96106
// +kubebuilder:webhook:path=/mutate-chaosapps-metamagical-io-v1-chaospod,mutating=true,failurePolicy=fail,groups=chaosapps.metamagical.io,resources=chaospods,verbs=create;update,versions=v1,name=mchaospod.kb.io
97107

98108
var _ webhook.Defaulter = &ChaosPod{}

hack/check-everything.sh

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ function fetch_kb_tools {
6060
}
6161

6262
function is_installed {
63-
if [ command -v $1 &>/dev/null ]; then
63+
if command -v "$1" &>/dev/null; then
6464
return 0
6565
fi
6666
return 1

pkg/builder/builder_suite_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ var _ = AfterSuite(func() {
7777

7878
func addCRDToEnvironment(env *envtest.Environment, gvks ...schema.GroupVersionKind) {
7979
for _, gvk := range gvks {
80-
plural, singlar := meta.UnsafeGuessKindToResource(gvk)
80+
plural, singular := meta.UnsafeGuessKindToResource(gvk)
8181
crd := &apiextensionsv1beta1.CustomResourceDefinition{
8282
TypeMeta: metav1.TypeMeta{
8383
APIVersion: "apiextensions.k8s.io",
@@ -91,7 +91,7 @@ func addCRDToEnvironment(env *envtest.Environment, gvks ...schema.GroupVersionKi
9191
Version: gvk.Version,
9292
Names: apiextensionsv1beta1.CustomResourceDefinitionNames{
9393
Plural: plural.Resource,
94-
Singular: singlar.Resource,
94+
Singular: singular.Resource,
9595
Kind: gvk.Kind,
9696
},
9797
Versions: []apiextensionsv1beta1.CustomResourceDefinitionVersion{

pkg/builder/controller.go

Lines changed: 20 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import (
2323
"k8s.io/apimachinery/pkg/runtime"
2424
"k8s.io/client-go/rest"
2525
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
26-
"sigs.k8s.io/controller-runtime/pkg/client/config"
2726
"sigs.k8s.io/controller-runtime/pkg/controller"
2827
"sigs.k8s.io/controller-runtime/pkg/handler"
2928
"sigs.k8s.io/controller-runtime/pkg/manager"
@@ -33,9 +32,7 @@ import (
3332
)
3433

3534
// Supporting mocking out functions for testing
36-
var getConfig = config.GetConfig
3735
var newController = controller.New
38-
var newManager = manager.New
3936
var getGvk = apiutil.GVKForObject
4037

4138
// Builder builds a Controller.
@@ -47,19 +44,13 @@ type Builder struct {
4744
watchRequest []watchRequest
4845
config *rest.Config
4946
ctrl controller.Controller
47+
ctrlOptions controller.Options
5048
name string
5149
}
5250

53-
// SimpleController returns a new Builder.
54-
//
55-
// Deprecated: Use ControllerManagedBy(Manager) instead.
56-
func SimpleController() *Builder {
57-
return &Builder{}
58-
}
59-
6051
// ControllerManagedBy returns a new controller builder that will be started by the provided Manager
6152
func ControllerManagedBy(m manager.Manager) *Builder {
62-
return SimpleController().WithManager(m)
53+
return &Builder{mgr: m}
6354
}
6455

6556
// ForType defines the type of Object being *reconciled*, and configures the ControllerManagedBy to respond to create / delete /
@@ -109,14 +100,6 @@ func (blder *Builder) WithConfig(config *rest.Config) *Builder {
109100
return blder
110101
}
111102

112-
// WithManager sets the Manager to use for registering the ControllerManagedBy. Defaults to a new manager.Manager.
113-
//
114-
// Deprecated: Use ControllerManagedBy(Manager) and this isn't needed.
115-
func (blder *Builder) WithManager(m manager.Manager) *Builder {
116-
blder.mgr = m
117-
return blder
118-
}
119-
120103
// WithEventFilter sets the event filters, to filter which create/update/delete/generic events eventually
121104
// trigger reconciliations. For example, filtering on whether the resource version has changed.
122105
// Defaults to the empty list.
@@ -125,6 +108,12 @@ func (blder *Builder) WithEventFilter(p predicate.Predicate) *Builder {
125108
return blder
126109
}
127110

111+
// WithOptions overrides the controller options use in doController. Defaults to empty.
112+
func (blder *Builder) WithOptions(options controller.Options) *Builder {
113+
blder.ctrlOptions = options
114+
return blder
115+
}
116+
128117
// Named sets the name of the controller to the given name. The name shows up
129118
// in metrics, among other things, and thus should be a prometheus compatible name
130119
// (underscores and alphanumeric characters only).
@@ -141,23 +130,17 @@ func (blder *Builder) Complete(r reconcile.Reconciler) error {
141130
return err
142131
}
143132

144-
// Build builds the Application ControllerManagedBy and returns the Manager used to start it.
145-
//
146-
// Deprecated: Use Complete
147-
func (blder *Builder) Build(r reconcile.Reconciler) (manager.Manager, error) {
133+
// Build builds the Application ControllerManagedBy and returns the Controller it created.
134+
func (blder *Builder) Build(r reconcile.Reconciler) (controller.Controller, error) {
148135
if r == nil {
149136
return nil, fmt.Errorf("must provide a non-nil Reconciler")
150137
}
151-
152-
// Set the Config
153-
if err := blder.loadRestConfig(); err != nil {
154-
return nil, err
138+
if blder.mgr == nil {
139+
return nil, fmt.Errorf("must provide a non-nil Manager")
155140
}
156141

157-
// Set the Manager
158-
if err := blder.doManager(); err != nil {
159-
return nil, err
160-
}
142+
// Set the Config
143+
blder.loadRestConfig()
161144

162145
// Set the ControllerManagedBy
163146
if err := blder.doController(r); err != nil {
@@ -169,7 +152,7 @@ func (blder *Builder) Build(r reconcile.Reconciler) (manager.Manager, error) {
169152
return nil, err
170153
}
171154

172-
return blder.mgr, nil
155+
return blder.ctrl, nil
173156
}
174157

175158
func (blder *Builder) doWatch() error {
@@ -203,26 +186,10 @@ func (blder *Builder) doWatch() error {
203186
return nil
204187
}
205188

206-
func (blder *Builder) loadRestConfig() error {
207-
if blder.config != nil {
208-
return nil
209-
}
210-
if blder.mgr != nil {
189+
func (blder *Builder) loadRestConfig() {
190+
if blder.config == nil {
211191
blder.config = blder.mgr.GetConfig()
212-
return nil
213-
}
214-
var err error
215-
blder.config, err = getConfig()
216-
return err
217-
}
218-
219-
func (blder *Builder) doManager() error {
220-
if blder.mgr != nil {
221-
return nil
222192
}
223-
var err error
224-
blder.mgr, err = newManager(blder.config, manager.Options{})
225-
return err
226193
}
227194

228195
func (blder *Builder) getControllerName() (string, error) {
@@ -241,6 +208,8 @@ func (blder *Builder) doController(r reconcile.Reconciler) error {
241208
if err != nil {
242209
return err
243210
}
244-
blder.ctrl, err = newController(name, blder.mgr, controller.Options{Reconciler: r})
211+
ctrlOptions := blder.ctrlOptions
212+
ctrlOptions.Reconciler = r
213+
blder.ctrl, err = newController(name, blder.mgr, ctrlOptions)
245214
return err
246215
}

0 commit comments

Comments
 (0)