Skip to content

Commit 1a95fa4

Browse files
committed
include changes to satisfy comments
1 parent cb8ffc9 commit 1a95fa4

File tree

4 files changed

+77
-74
lines changed

4 files changed

+77
-74
lines changed

controllers/hcpvaultsecretsapp_controller.go

Lines changed: 37 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"context"
88
"encoding/base64"
99
"encoding/json"
10+
"errors"
1011
"fmt"
1112
"net/http"
1213
"regexp"
@@ -83,16 +84,15 @@ var (
8384
// HCPVaultSecretsAppReconciler reconciles a HCPVaultSecretsApp object
8485
type HCPVaultSecretsAppReconciler struct {
8586
client.Client
86-
Scheme *runtime.Scheme
87-
Recorder record.EventRecorder
88-
SecretDataBuilder *helpers.SecretDataBuilder
89-
HMACValidator helpers.HMACValidator
90-
MinRefreshAfter time.Duration
91-
referenceCache ResourceReferenceCache
92-
GlobalTransformationOptions *helpers.GlobalTransformationOptions
93-
BackOffRegistry *BackOffRegistry
94-
CleanupOrphanedShadowSecretInterval time.Duration
95-
once sync.Once
87+
Scheme *runtime.Scheme
88+
Recorder record.EventRecorder
89+
SecretDataBuilder *helpers.SecretDataBuilder
90+
HMACValidator helpers.HMACValidator
91+
MinRefreshAfter time.Duration
92+
referenceCache ResourceReferenceCache
93+
GlobalTransformationOptions *helpers.GlobalTransformationOptions
94+
BackOffRegistry *BackOffRegistry
95+
once sync.Once
9696
}
9797

9898
// +kubebuilder:rbac:groups=secrets.hashicorp.com,resources=hcpvaultsecretsapps,verbs=get;list;watch;create;update;patch;delete
@@ -293,7 +293,7 @@ func (r *HCPVaultSecretsAppReconciler) Reconcile(ctx context.Context, req ctrl.R
293293
}, nil
294294
}
295295

296-
func (r *HCPVaultSecretsAppReconciler) startOrphanedShadowSecretCleanup(ctx context.Context) error {
296+
func (r *HCPVaultSecretsAppReconciler) startOrphanedShadowSecretCleanup(ctx context.Context, cleanupOrphanedShadowSecretInterval time.Duration) error {
297297
var err error
298298

299299
r.once.Do(func() {
@@ -303,62 +303,66 @@ func (r *HCPVaultSecretsAppReconciler) startOrphanedShadowSecretCleanup(ctx cont
303303
if ctx.Err() != nil {
304304
err = ctx.Err()
305305
}
306+
break
306307
// runs the cleanup process once every hour or as specified by the user
307-
case <-time.After(r.CleanupOrphanedShadowSecretInterval):
308-
err = r.cleanupOrphanedShadowSecrets(ctx)
308+
case <-time.After(cleanupOrphanedShadowSecretInterval):
309+
r.cleanupOrphanedShadowSecrets(ctx)
309310
}
310311
}
311312
})
312313

313-
return fmt.Errorf("shadow secret cleanup error err=%s", err)
314+
return err
314315
}
315316

316-
func (r *HCPVaultSecretsAppReconciler) cleanupOrphanedShadowSecrets(ctx context.Context) error {
317+
func (r *HCPVaultSecretsAppReconciler) cleanupOrphanedShadowSecrets(ctx context.Context) {
317318
logger := log.FromContext(ctx).WithName("cleanupOrphanedShadowSecrets")
319+
var errs error
318320

319-
// filtering only for dynamic secrets
320-
dynamicSecretLabelSelector := client.MatchingLabels{"app.kubernetes.io/component": "hvs-dynamic-secret-cache"}
321+
namespaceLabelKey := hvsaLabelPrefix + "/namespace"
322+
nameLabelKey := hvsaLabelPrefix + "/name"
321323

324+
// filtering only for dynamic secrets, also checking if namespace and name labels are present
322325
secrets := corev1.SecretList{}
323-
if err := r.List(ctx, &secrets, client.InNamespace(common.OperatorNamespace), dynamicSecretLabelSelector); err != nil {
324-
logger.Error(err, "Failed to list shadow secrets")
325-
return err
326+
if err := r.List(ctx, &secrets, client.InNamespace(common.OperatorNamespace),
327+
client.MatchingLabels{"app.kubernetes.io/component": "hvs-dynamic-secret-cache"},
328+
client.HasLabels{namespaceLabelKey, nameLabelKey}); err != nil {
329+
errs = errors.Join(errs, fmt.Errorf("failed to list shadow secrets: %w", err))
326330
}
327331

328332
for _, secret := range secrets.Items {
329-
o := &secretsv1beta1.HCPVaultSecretsApp{}
333+
namespace := secret.Labels[namespaceLabelKey]
334+
name := secret.Labels[nameLabelKey]
335+
objKey := types.NamespacedName{Namespace: namespace, Name: name}
330336

331-
namespace := secret.Labels[hvsaLabelPrefix+"/namespace"]
332-
name := secret.Labels[hvsaLabelPrefix+"/name"]
333-
namespacedName := types.NamespacedName{Namespace: namespace, Name: name}
337+
o := &secretsv1beta1.HCPVaultSecretsApp{}
334338

335-
// get the HCPVaultSecretsApp instance that that the shadow secret belongs to (if applicable)
339+
// get the HCPVaultSecretsApp instance that the shadow secret belongs to (if applicable)
336340
// no errors are returned in the loop because this could block the deletion of other
337341
// orphaned shadow secrets that are further along in the list
338-
err := r.Get(ctx, namespacedName, o)
342+
err := r.Get(ctx, objKey, o)
339343
if err != nil && !apierrors.IsNotFound(err) {
340-
logger.Error(err, "Error getting resource from k8s", "secret", secret.Name)
344+
errs = errors.Join(errs, fmt.Errorf("failed to get HCPVaultSecretsApp: %w", err))
341345
continue
342346
}
343347

344348
// if the HCPVaultSecretsApp has been deleted, and the shadow secret belongs to it, delete both
345349
if o.GetDeletionTimestamp() != nil && o.GetUID() == types.UID(secret.Labels[helpers.LabelOwnerRefUID]) {
346350
if err := r.handleDeletion(ctx, o); err != nil {
347-
logger.Error(err, "Failed to handle deletion of HCPVaultSecretsApp", "app", o.Name)
351+
errs = errors.Join(errs, fmt.Errorf("failed to handle deletion of HCPVaultSecretsApp %s: %w", o.Spec.AppName, err))
348352
}
349353

350354
logger.Info("Deleted orphaned resources associated with HCPVaultSecretsApp", "app", o.Name)
351355
} else if apierrors.IsNotFound(err) || secret.GetDeletionTimestamp() != nil {
352356
// otherwise, delete the single shadow secret if it has a deletion timestamp
353-
if err := helpers.DeleteSecret(ctx, r.Client, namespacedName); err != nil {
354-
logger.Error(err, "Failed to delete shadow secret", "secret", secret.Name)
357+
if err := helpers.DeleteSecret(ctx, r.Client, objKey); err != nil {
358+
errs = errors.Join(errs, fmt.Errorf("failed to delete shadow secret %s: %w", secret.Name, err))
355359
}
356360

357361
logger.Info("Deleted orphaned shadow secret", "secret", secret.Name)
358362
}
359363
}
360364

361-
return nil
365+
logger.Error(errs, "Failed during cleanup of orphaned shadow secrets")
362366
}
363367

364368
func (r *HCPVaultSecretsAppReconciler) updateStatus(ctx context.Context, o *secretsv1beta1.HCPVaultSecretsApp) error {
@@ -373,14 +377,14 @@ func (r *HCPVaultSecretsAppReconciler) updateStatus(ctx context.Context, o *secr
373377
}
374378

375379
// SetupWithManager sets up the controller with the Manager.
376-
func (r *HCPVaultSecretsAppReconciler) SetupWithManager(mgr ctrl.Manager, opts controller.Options) error {
380+
func (r *HCPVaultSecretsAppReconciler) SetupWithManager(mgr ctrl.Manager, opts controller.Options, cleanupOrphanedShadowSecretInterval time.Duration) error {
377381
r.referenceCache = newResourceReferenceCache()
378382
if r.BackOffRegistry == nil {
379383
r.BackOffRegistry = NewBackOffRegistry()
380384
}
381385

382386
mgr.Add(manager.RunnableFunc(func(ctx context.Context) error {
383-
err := r.startOrphanedShadowSecretCleanup(ctx)
387+
err := r.startOrphanedShadowSecretCleanup(ctx, cleanupOrphanedShadowSecretInterval)
384388
return err
385389
}))
386390

internal/options/env.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,8 @@ type VSOEnvOptions struct {
5050
// ClientCacheNumLocks is VSO_CLIENT_CACHE_NUM_LOCKS environment variable option
5151
ClientCacheNumLocks *int `split_words:"true"`
5252

53-
// CleanupOrphanedShadowSecretInterval is VSO_CLEANUP_ORPHANED_SHADOW_SECRETS_INTERVAL environment variable option
54-
CleanupOrphanedShadowSecretInterval time.Duration `split_words:"true"`
53+
// CleanupOrphanedShadowSecretInterval is VSO_HVSA_CLEANUP_ORPHANED_SHADOW_SECRETS_INTERVAL environment variable option
54+
HVSACleanupOrphanedShadowSecretInterval time.Duration `split_words:"true"`
5555
}
5656

5757
// Parse environment variable options, prefixed with "VSO_"

internal/options/env_test.go

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -23,34 +23,34 @@ func TestParse(t *testing.T) {
2323
},
2424
"set all": {
2525
envs: map[string]string{
26-
"VSO_OUTPUT_FORMAT": "json",
27-
"VSO_CLIENT_CACHE_SIZE": "100",
28-
"VSO_CLIENT_CACHE_PERSISTENCE_MODEL": "memory",
29-
"VSO_MAX_CONCURRENT_RECONCILES": "10",
30-
"VSO_BACKOFF_INITIAL_INTERVAL": "1s",
31-
"VSO_BACKOFF_MAX_INTERVAL": "60s",
32-
"VSO_BACKOFF_MAX_ELAPSED_TIME": "24h",
33-
"VSO_BACKOFF_RANDOMIZATION_FACTOR": "0.5",
34-
"VSO_BACKOFF_MULTIPLIER": "2.5",
35-
"VSO_GLOBAL_TRANSFORMATION_OPTIONS": "gOpt1,gOpt2",
36-
"VSO_GLOBAL_VAULT_AUTH_OPTIONS": "vOpt1,vOpt2",
37-
"VSO_CLIENT_CACHE_NUM_LOCKS": "10",
38-
"VSO_CLEANUP_ORPHANED_SHADOW_SECRET_INTERVAL": "1h",
26+
"VSO_OUTPUT_FORMAT": "json",
27+
"VSO_CLIENT_CACHE_SIZE": "100",
28+
"VSO_CLIENT_CACHE_PERSISTENCE_MODEL": "memory",
29+
"VSO_MAX_CONCURRENT_RECONCILES": "10",
30+
"VSO_BACKOFF_INITIAL_INTERVAL": "1s",
31+
"VSO_BACKOFF_MAX_INTERVAL": "60s",
32+
"VSO_BACKOFF_MAX_ELAPSED_TIME": "24h",
33+
"VSO_BACKOFF_RANDOMIZATION_FACTOR": "0.5",
34+
"VSO_BACKOFF_MULTIPLIER": "2.5",
35+
"VSO_GLOBAL_TRANSFORMATION_OPTIONS": "gOpt1,gOpt2",
36+
"VSO_GLOBAL_VAULT_AUTH_OPTIONS": "vOpt1,vOpt2",
37+
"VSO_CLIENT_CACHE_NUM_LOCKS": "10",
38+
"VSO_HVSA_CLEANUP_ORPHANED_SHADOW_SECRET_INTERVAL": "1h",
3939
},
4040
wantOptions: VSOEnvOptions{
41-
OutputFormat: "json",
42-
ClientCacheSize: ptr.To(100),
43-
ClientCachePersistenceModel: "memory",
44-
MaxConcurrentReconciles: ptr.To(10),
45-
BackoffInitialInterval: time.Second * 1,
46-
BackoffMaxInterval: time.Second * 60,
47-
BackoffMaxElapsedTime: time.Hour * 24,
48-
BackoffRandomizationFactor: 0.5,
49-
BackoffMultiplier: 2.5,
50-
GlobalTransformationOptions: []string{"gOpt1", "gOpt2"},
51-
GlobalVaultAuthOptions: []string{"vOpt1", "vOpt2"},
52-
ClientCacheNumLocks: ptr.To(10),
53-
CleanupOrphanedShadowSecretInterval: time.Hour * 1,
41+
OutputFormat: "json",
42+
ClientCacheSize: ptr.To(100),
43+
ClientCachePersistenceModel: "memory",
44+
MaxConcurrentReconciles: ptr.To(10),
45+
BackoffInitialInterval: time.Second * 1,
46+
BackoffMaxInterval: time.Second * 60,
47+
BackoffMaxElapsedTime: time.Hour * 24,
48+
BackoffRandomizationFactor: 0.5,
49+
BackoffMultiplier: 2.5,
50+
GlobalTransformationOptions: []string{"gOpt1", "gOpt2"},
51+
GlobalVaultAuthOptions: []string{"vOpt1", "vOpt2"},
52+
ClientCacheNumLocks: ptr.To(10),
53+
HVSACleanupOrphanedShadowSecretInterval: time.Hour * 1,
5454
},
5555
},
5656
}

main.go

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ func main() {
218218
flag.DurationVar(&cleanupOrphanedShadowSecretInterval, "cleanup-orphaned-shadow-secrets-interval", 1*time.Hour,
219219
"The time interval between each execution of the cleanup process for cached shadow secrets"+
220220
"associated with a deleted HCPVaultSecretsApp. "+
221-
"Also set from environment variable VSO_CLEANUP_ORPHANED_SHADOW_SECRET_INTERVAL.")
221+
"Also set from environment variable VSO_HVSA_CLEANUP_ORPHANED_SHADOW_SECRET_INTERVAL.")
222222

223223
opts := zap.Options{
224224
Development: os.Getenv("VSO_LOGGER_DEVELOPMENT_MODE") != "",
@@ -267,8 +267,8 @@ func main() {
267267
if vsoEnvOptions.BackoffMultiplier != 0 {
268268
backoffMultiplier = vsoEnvOptions.BackoffMultiplier
269269
}
270-
if vsoEnvOptions.CleanupOrphanedShadowSecretInterval != 0 {
271-
cleanupOrphanedShadowSecretInterval = vsoEnvOptions.CleanupOrphanedShadowSecretInterval
270+
if vsoEnvOptions.HVSACleanupOrphanedShadowSecretInterval != 0 {
271+
cleanupOrphanedShadowSecretInterval = vsoEnvOptions.HVSACleanupOrphanedShadowSecretInterval
272272
}
273273
if len(vsoEnvOptions.GlobalVaultAuthOptions) > 0 {
274274
globalVaultAuthOptsSet = vsoEnvOptions.GlobalVaultAuthOptions
@@ -555,16 +555,15 @@ func main() {
555555
os.Exit(1)
556556
}
557557
if err = (&controllers.HCPVaultSecretsAppReconciler{
558-
Client: mgr.GetClient(),
559-
Scheme: mgr.GetScheme(),
560-
Recorder: mgr.GetEventRecorderFor("HCPVaultSecretsApp"),
561-
SecretDataBuilder: secretDataBuilder,
562-
HMACValidator: hmacValidator,
563-
MinRefreshAfter: minRefreshAfterHVSA,
564-
BackOffRegistry: controllers.NewBackOffRegistry(backoffOpts...),
565-
GlobalTransformationOptions: globalTransOptions,
566-
CleanupOrphanedShadowSecretInterval: cleanupOrphanedShadowSecretInterval,
567-
}).SetupWithManager(mgr, controllerOptions); err != nil {
558+
Client: mgr.GetClient(),
559+
Scheme: mgr.GetScheme(),
560+
Recorder: mgr.GetEventRecorderFor("HCPVaultSecretsApp"),
561+
SecretDataBuilder: secretDataBuilder,
562+
HMACValidator: hmacValidator,
563+
MinRefreshAfter: minRefreshAfterHVSA,
564+
BackOffRegistry: controllers.NewBackOffRegistry(backoffOpts...),
565+
GlobalTransformationOptions: globalTransOptions,
566+
}).SetupWithManager(mgr, controllerOptions, cleanupOrphanedShadowSecretInterval); err != nil {
568567
setupLog.Error(err, "unable to create controller", "controller", "HCPVaultSecretsApp")
569568
os.Exit(1)
570569
}

0 commit comments

Comments
 (0)