/
reconciler.go
229 lines (190 loc) · 8.34 KB
/
reconciler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/*
Copyright 2019 The Crossplane Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package target
import (
"context"
"strings"
"time"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/crossplane/crossplane-runtime/apis/core/v1alpha1"
"github.com/crossplane/crossplane-runtime/pkg/event"
"github.com/crossplane/crossplane-runtime/pkg/logging"
"github.com/crossplane/crossplane-runtime/pkg/meta"
"github.com/crossplane/crossplane-runtime/pkg/resource"
)
const (
targetReconcileTimeout = 1 * time.Minute
aShortWait = 30 * time.Second
)
// Error strings
const (
errGetTarget = "unable to get Target"
errUpdateTarget = "unable to update Target"
)
// Event reasons.
const (
reasonSetSecretRef event.Reason = "SetSecretRef"
reasonCannotGetManaged event.Reason = "CannotGetManaged"
reasonCannotPropagateSecret event.Reason = "CannotPropagateSecret"
reasonPropagatedSecret event.Reason = "PropagatedSecret"
)
// TypeSecretPropagated resources have had connection information
// propagated to their secret reference.
const TypeSecretPropagated v1alpha1.ConditionType = "ConnectionSecretPropagated"
// NOTE(negz): This reconciler exists to service KubernetesApplications, which
// are deprecated per https://github.com/crossplane/crossplane/issues/1595. It
// had a PropagationSuccess condition but did not use it. I elected not to fix
// this due to its impending removal.
// ReasonSecretPropagationError indicates that secret propagation failed.
const ReasonSecretPropagationError v1alpha1.ConditionReason = "PropagationError"
// ControllerName returns the recommended name for controllers that use this
// package to reconcile a particular kind of target.
func ControllerName(kind string) string {
return "target/" + strings.ToLower(kind)
}
// A Reconciler reconciles targets by propagating the secret of the
// referenced managed resource.
type Reconciler struct {
client client.Client
newTarget func() resource.Target
newManaged func() resource.Managed
propagator resource.ManagedConnectionPropagator
log logging.Logger
record event.Recorder
}
// A ReconcilerOption configures a Reconciler.
type ReconcilerOption func(*Reconciler)
// WithManagedConnectionPropagator specifies which ManagedConnectionPropagator
// should be used to propagate resource connection details to their target.
func WithManagedConnectionPropagator(p resource.ManagedConnectionPropagator) ReconcilerOption {
return func(r *Reconciler) {
r.propagator = p
}
}
// WithLogger specifies how the Reconciler should log messages.
func WithLogger(l logging.Logger) ReconcilerOption {
return func(r *Reconciler) {
r.log = l
}
}
// WithRecorder specifies how the Reconciler should record events.
func WithRecorder(er event.Recorder) ReconcilerOption {
return func(r *Reconciler) {
r.record = er
}
}
// NewReconciler returns a Reconciler that reconciles KubernetesTargets by
// propagating the referenced Kubernetes cluster's connection Secret to the
// namespace of the KubernetesTarget.
func NewReconciler(m manager.Manager, of resource.TargetKind, with resource.ManagedKind, o ...ReconcilerOption) *Reconciler {
nt := func() resource.Target {
return resource.MustCreateObject(schema.GroupVersionKind(of), m.GetScheme()).(resource.Target)
}
nr := func() resource.Managed {
return resource.MustCreateObject(schema.GroupVersionKind(with), m.GetScheme()).(resource.Managed)
}
// Panic early if we've been asked to reconcile a target or resource kind
// that has not been registered with our controller manager's scheme.
_, _ = nt(), nr()
r := &Reconciler{
client: m.GetClient(),
newTarget: nt,
newManaged: nr,
// TODO(negz): Switch to resource.ConnectionPropagator after this has
// been deprecated for a release or two.
//nolint:staticcheck
propagator: resource.NewAPIManagedConnectionPropagator(m.GetClient(), m.GetScheme()),
log: logging.NewNopLogger(),
record: event.NewNopRecorder(),
}
for _, ro := range o {
ro(r)
}
return r
}
// TODO(negz): Could we use a regular ReconcileError instead of a bespoke
// SecretPropagationError for this controller?
// Reconcile a target with a concrete managed resource.
func (r *Reconciler) Reconcile(req reconcile.Request) (reconcile.Result, error) {
log := r.log.WithValues("request", req)
log.Debug("Reconciling")
ctx, cancel := context.WithTimeout(context.Background(), targetReconcileTimeout)
defer cancel()
target := r.newTarget()
if err := r.client.Get(ctx, req.NamespacedName, target); err != nil {
// There's no need to requeue if we no longer exist. Otherwise we'll be
// requeued implicitly because we return an error.
log.Debug("Cannot get target", "error", err)
return reconcile.Result{}, errors.Wrap(resource.IgnoreNotFound(err), errGetTarget)
}
// Our watch predicates ensure we only reconcile targets with a non-nil
// resource reference.
record := r.record.WithAnnotations("managed-name", target.GetResourceReference().Name)
log = log.WithValues(
"uid", target.GetUID(),
"version", target.GetResourceVersion(),
"managed-name", target.GetResourceReference().Name,
)
if target.GetWriteConnectionSecretToReference() == nil {
// If the ConnectionSecretRef is not set on this Target, we generate a
// Secret name that matches the UID of the Target. We are implicitly
// requeued because of the Target update.
log.Debug("Set secret reference to target UID")
record.Event(target, event.Normal(reasonSetSecretRef, "Set secret reference to target UID"))
target.SetWriteConnectionSecretToReference(&v1alpha1.LocalSecretReference{Name: string(target.GetUID())})
return reconcile.Result{}, errors.Wrap(r.client.Update(ctx, target), errUpdateTarget)
}
// TODO(negz): Move this above the secret ref check. Is this needed at all?
if meta.WasDeleted(target) {
// If the Target was deleted, there is nothing left for us to do.
return reconcile.Result{Requeue: false}, nil
}
managed := r.newManaged()
if err := r.client.Get(ctx, meta.NamespacedNameOf(target.GetResourceReference()), managed); err != nil {
log.Debug("Cannot get referenced managed resource", "error", err, "requeue-after", time.Now().Add(aShortWait))
record.Event(target, event.Warning(reasonCannotGetManaged, err))
target.SetConditions(SecretPropagationError(err))
return reconcile.Result{RequeueAfter: aShortWait}, errors.Wrap(r.client.Status().Update(ctx, target), errUpdateTarget)
}
if err := r.propagator.PropagateConnection(ctx, target, managed); err != nil {
// If we fail to propagate the connection secret of a bound managed
// resource, we try again after a short wait.
log.Debug("Cannot propagate connection secret", "error", err, "requeue-after", time.Now().Add(aShortWait))
record.Event(target, event.Warning(reasonCannotPropagateSecret, err))
target.SetConditions(SecretPropagationError(err))
return reconcile.Result{RequeueAfter: aShortWait}, errors.Wrap(r.client.Status().Update(ctx, target), errUpdateTarget)
}
// No need to requeue.
log.Debug("Successfully propagated connection secret")
record.Event(target, event.Normal(reasonPropagatedSecret, "Successfully propagated connection secret"))
return reconcile.Result{Requeue: false}, nil
}
// SecretPropagationError returns a condition indicating that Crossplane was
// unable to propagate connection data to the referenced secret. This could be
// because it was unable to find the managed resource that owns the secret to be
// propagated.
func SecretPropagationError(err error) v1alpha1.Condition {
return v1alpha1.Condition{
Type: TypeSecretPropagated,
Status: corev1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: ReasonSecretPropagationError,
Message: err.Error(),
}
}