-
Notifications
You must be signed in to change notification settings - Fork 142
Expand file tree
/
Copy pathcommon.go
More file actions
383 lines (338 loc) · 12.8 KB
/
Copy pathcommon.go
File metadata and controls
383 lines (338 loc) · 12.8 KB
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package controllers
import (
"context"
"fmt"
"math/rand"
"time"
"github.com/go-logr/logr"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/log"
secretsv1beta1 "github.com/hashicorp/vault-secrets-operator/api/v1beta1"
"github.com/hashicorp/vault-secrets-operator/common"
"github.com/hashicorp/vault-secrets-operator/consts"
)
var (
_ error = (*LeaseTruncatedError)(nil)
// random is not cryptographically secure, should not be used in any crypto
// type of operations.
random = rand.New(rand.NewSource(int64(time.Now().Nanosecond())))
requeueDurationOnError = time.Second * 5
// used by monkey patching unit tests
nowFunc = time.Now
)
const renewalPercentCap = 90
type empty struct{}
// LeaseTruncatedError indicates that the requested lease renewal duration is
// less than expected
type LeaseTruncatedError struct {
Expected int
Actual int
}
func (l *LeaseTruncatedError) Error() string {
return fmt.Sprintf("lease renewal duration was truncated from %ds to %ds",
l.Expected, l.Actual)
}
// computeMaxJitter with max as 10% of the duration, and jitter a random amount
// between 0-10%
func computeMaxJitter(duration time.Duration) (maxHorizon float64, jitter uint64) {
return computeMaxJitterWithPercent(duration, 0.10)
}
// computeMaxJitterDuration with max as 10% of the duration, and jitter a random amount
// between 0-10% as time.Duration.
func computeMaxJitterDuration(duration time.Duration) (maxHorizon float64, jitter time.Duration) {
var j uint64
maxHorizon, j = computeMaxJitterWithPercent(duration, 0.10)
jitter = time.Duration(j)
return
}
// computeMaxJitter with max as a percentage (percent) of the duration, and
// jitter a random amount between 0 up to percent
func computeMaxJitterWithPercent(duration time.Duration, percent float64) (maxHorizon float64, jitter uint64) {
nanos := duration.Nanoseconds()
maxHorizon = percent * float64(nanos)
u := uint64(maxHorizon)
if u == 0 {
jitter = 0
} else {
jitter = uint64(random.Int63()) % u
}
return maxHorizon, jitter
}
// computeMaxJitterDurationWithPercent with max as a percentage (percent) of the duration, and
// jitter a random amount between 0 up to percent
func computeMaxJitterDurationWithPercent(duration time.Duration, percent float64) (float64, time.Duration) {
maxDuration, jitter := computeMaxJitterWithPercent(duration, percent)
return maxDuration, time.Duration(jitter)
}
// computeHorizonWithJitter returns a time.Duration minus a random offset, with an
// additional random jitter added to reduce pressure on the Reconciler.
// based https://github.com/hashicorp/vault/blob/03d2be4cb943115af1bcddacf5b8d79f3ec7c210/api/lifetime_watcher.go#L381
func computeHorizonWithJitter(minDuration time.Duration) time.Duration {
maxHorizon, jitter := computeMaxJitter(minDuration)
return minDuration - (time.Duration(maxHorizon) + time.Duration(jitter))
}
// capRenewalPercent returns a renewalPercent capped between 0 and 90
// inclusively
func capRenewalPercent(renewalPercent int) (rp int) {
switch {
case renewalPercent > renewalPercentCap:
rp = renewalPercentCap
case renewalPercent < 0:
rp = 0
default:
rp = renewalPercent
}
return rp
}
// computeDynamicHorizonWithJitter returns a time.Duration that is the specified
// percentage of the lease duration, minus some random jitter (up to 10% of
// leaseDuration), to ensure the horizon falls within the specified renewal window
func computeDynamicHorizonWithJitter(leaseDuration time.Duration, renewalPercent int) time.Duration {
maxHorizon, jitter := computeMaxJitter(leaseDuration)
return computeStartRenewingAt(leaseDuration, renewalPercent) + time.Duration(maxHorizon) - time.Duration(jitter)
}
// computeStartRenewingAt returns a time.Duration that is the specified
// percentage of the lease duration.
func computeStartRenewingAt(leaseDuration time.Duration, renewalPercent int) time.Duration {
return time.Duration(float64(leaseDuration.Nanoseconds()) * float64(capRenewalPercent(renewalPercent)) / 100)
}
// RemoveAllFinalizers is responsible for removing all finalizers added by the controller to prevent
// finalizers from going stale when the controller is being deleted.
func RemoveAllFinalizers(ctx context.Context, c client.Client, log logr.Logger) error {
// To support allNamespaces, do not add the common.OperatorNamespace filter, aka opts := client.ListOptions{}
opts := []client.ListOption{
client.InNamespace(common.OperatorNamespace),
}
// Fetch all custom resources managed by the controller and remove any finalizers that we control.
// Do this for each resource type:
// * VaultAuthMethod
// * VaultConnection
// * VaultDynamicSecret
// * VaultStaticSecret <- not currently implemented
// * VaultPKISecret
vamList := &secretsv1beta1.VaultAuthList{}
err := c.List(ctx, vamList, opts...)
if err != nil {
log.Error(err, "Unable to list VaultAuth resources")
}
removeFinalizers(ctx, c, log, vamList)
vcList := &secretsv1beta1.VaultConnectionList{}
err = c.List(ctx, vcList, opts...)
if err != nil {
log.Error(err, "Unable to list VaultConnection resources")
}
removeFinalizers(ctx, c, log, vcList)
vdsList := &secretsv1beta1.VaultDynamicSecretList{}
err = c.List(ctx, vdsList, opts...)
if err != nil {
log.Error(err, "Unable to list VaultDynamicSecret resources")
}
removeFinalizers(ctx, c, log, vdsList)
vpkiList := &secretsv1beta1.VaultPKISecretList{}
err = c.List(ctx, vpkiList, opts...)
if err != nil {
log.Error(err, "Unable to list VaultPKISecret resources")
}
removeFinalizers(ctx, c, log, vpkiList)
return nil
}
// removeFinalizers removes specific finalizers from each CR type and updates the resource if necessary.
// Errors are ignored in this case so that we can do the best effort attempt to remove *all* finalizers, even
// if one or two have problems.
func removeFinalizers(ctx context.Context, c client.Client, log logr.Logger, objs client.ObjectList) {
cnt := 0
switch t := objs.(type) {
case *secretsv1beta1.VaultAuthList:
for _, x := range t.Items {
cnt++
if controllerutil.RemoveFinalizer(&x, vaultAuthFinalizer) {
log.Info(fmt.Sprintf("Updating finalizer for Auth %s", x.Name))
if err := c.Update(ctx, &x, &client.UpdateOptions{}); err != nil {
log.Error(err, fmt.Sprintf("Unable to update finalizer for %s: %s", vaultAuthFinalizer, x.Name))
}
}
}
case *secretsv1beta1.VaultPKISecretList:
for _, x := range t.Items {
cnt++
if controllerutil.RemoveFinalizer(&x, vaultPKIFinalizer) {
log.Info(fmt.Sprintf("Updating finalizer for PKI %s", x.Name))
if err := c.Update(ctx, &x, &client.UpdateOptions{}); err != nil {
log.Error(err, fmt.Sprintf("Unable to update finalizer for %s: %s", vaultPKIFinalizer, x.Name))
}
}
}
case *secretsv1beta1.VaultConnectionList:
for _, x := range t.Items {
cnt++
if controllerutil.RemoveFinalizer(&x, vaultConnectionFinalizer) {
log.Info(fmt.Sprintf("Updating finalizer for Connection %s", x.Name))
if err := c.Update(ctx, &x, &client.UpdateOptions{}); err != nil {
log.Error(err, fmt.Sprintf("Unable to update finalizer for %s: %s", vaultConnectionFinalizer, x.Name))
}
}
}
case *secretsv1beta1.VaultDynamicSecretList:
for _, x := range t.Items {
cnt++
if controllerutil.RemoveFinalizer(&x, vaultDynamicSecretFinalizer) {
log.Info(fmt.Sprintf("Updating finalizer for DynamicSecret %s", x.Name))
if err := c.Update(ctx, &x, &client.UpdateOptions{}); err != nil {
log.Error(err, fmt.Sprintf("Unable to update finalizer for %s: %s", vaultDynamicSecretFinalizer, x.Name))
}
}
}
}
log.Info(fmt.Sprintf("Removed %d finalizers", cnt))
}
func parseDurationString(duration, path string, min time.Duration) (time.Duration, error) {
var err error
var d time.Duration
if duration != "" {
d, err = time.ParseDuration(duration)
if err != nil {
return 0, fmt.Errorf(
"invalid value %q for %s, %w",
duration, path, err)
}
if d < min {
return 0, fmt.Errorf(
"invalid value %q for %s, below the minimum allowed value %s",
duration, path, min)
}
}
return d, nil
}
func isInWindow(t1, t2 time.Time) bool {
return t1.After(t2) || t1.Equal(t2)
}
// maybeAddFinalizer updates client.Object with finalizer if it is not already
// set. Return true if the object was updated, in which case the object's
// ResourceVersion will have changed. This update should be handled by in the
// caller.
func maybeAddFinalizer(ctx context.Context, c client.Client, o client.Object, finalizer string) (bool, error) {
if o.GetDeletionTimestamp() == nil && !controllerutil.ContainsFinalizer(o, finalizer) {
// always call maybeAddFinalizer() after client.Client.Status.Update() to avoid
// API validation errors due to changes to the status schema.
logger := log.FromContext(ctx).WithValues("finalizer", finalizer)
logger.V(consts.LogLevelTrace).Info("Adding finalizer",
"finalizer", finalizer)
controllerutil.AddFinalizer(o, finalizer)
if err := c.Update(ctx, o); err != nil {
logger.Error(err, "Failed to add finalizer")
controllerutil.RemoveFinalizer(o, finalizer)
return false, err
}
return true, nil
}
return false, nil
}
func waitForStoppedCh(ctx context.Context, stoppedCh chan struct{}) error {
select {
case <-stoppedCh:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// updateConditions updates the current conditions with updates, returning a new
// set of metav1.Condition(s). It will update the LastTransitionTime if the condition has
// changed. It will also append new conditions to the existing conditions. All
// updates are deduplicated based on their type and reason.
func updateConditions(current []metav1.Condition, updates ...metav1.Condition) []metav1.Condition {
if len(updates) == 0 {
return current
}
seen := make(map[string]bool)
var ret []metav1.Condition
for _, newCond := range updates {
key := newCond.Type
if seen[key] {
// drop duplicate conditions
continue
}
seen[key] = true
var updated bool
for _, cond := range current {
if cond.Type == newCond.Type && cond.Reason == newCond.Reason {
if cond.Status != newCond.Status {
newCond.LastTransitionTime = metav1.NewTime(nowFunc())
}
if newCond.LastTransitionTime.IsZero() {
if cond.LastTransitionTime.IsZero() {
newCond.LastTransitionTime = metav1.NewTime(nowFunc())
} else {
newCond.LastTransitionTime = cond.LastTransitionTime
}
}
ret = append(ret, newCond)
updated = true
break
}
}
if !updated {
if newCond.LastTransitionTime.IsZero() {
newCond.LastTransitionTime = metav1.NewTime(nowFunc())
}
ret = append(ret, newCond)
}
}
var orig []metav1.Condition
for _, cond := range current {
if _, ok := seen[cond.Type]; ok {
continue
}
orig = append(orig, cond)
}
return append(orig, ret...)
}
func newConditionNow(o client.Object, typ, reason string, status metav1.ConditionStatus,
msgFmt string, msgArgs ...any,
) metav1.Condition {
return newCondition(o, typ, reason, status, time.Now(), msgFmt, msgArgs...)
}
func newCondition(o client.Object, typ, reason string, status metav1.ConditionStatus,
t time.Time, msgFmt string, msgArgs ...any,
) metav1.Condition {
return metav1.Condition{
ObservedGeneration: o.GetGeneration(),
LastTransitionTime: metav1.NewTime(t),
Type: typ,
Reason: reason,
Status: status,
Message: fmt.Sprintf(msgFmt, msgArgs...),
}
}
func newSyncCondition(o client.Object, status metav1.ConditionStatus, msgFmt string, msgArgs ...any) metav1.Condition {
return newConditionNow(o, consts.TypeSecretSynced, "Synced", status, msgFmt, msgArgs...)
}
// newUpToDateCondition returns a SecretSynced=True condition with a distinct
// Reason ("SecretUpToDate") to clearly distinguish "verified up-to-date, no
// write needed" from "data changed and was written to Kubernetes".
func newUpToDateCondition(o client.Object, msgFmt string, msgArgs ...any) metav1.Condition {
return newConditionNow(o, consts.TypeSecretSynced, consts.ReasonSecretUpToDate, metav1.ConditionTrue, msgFmt, msgArgs...)
}
func newHealthyCondition(o client.Object, healthy bool, objType string) metav1.Condition {
var reason string
var conditionStatus metav1.ConditionStatus
if healthy {
conditionStatus = metav1.ConditionTrue
reason = consts.ReasonHealthy
} else {
conditionStatus = metav1.ConditionFalse
reason = consts.ReasonUnhealthy
}
return newConditionNow(o, consts.TypeHealthy, reason, conditionStatus, "%s%s", objType, reason)
}
func newReadyCondition(o client.Object, ready bool, objType string) metav1.Condition {
reason := consts.ReasonReady
conditionStatus := metav1.ConditionTrue
if !ready {
conditionStatus = metav1.ConditionFalse
}
return newConditionNow(o, consts.TypeReady, reason, conditionStatus, "%s%s", objType, reason)
}