Skip to content

Commit 50f7cd0

Browse files
committed
handle race condition when creating namespaces in the service cluster
On-behalf-of: @SAP [email protected]
1 parent 73ad15e commit 50f7cd0

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

internal/sync/object_syncer.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,10 @@ func (s *objectSyncer) ensureNamespace(ctx context.Context, log *zap.SugaredLogg
349349
return nil
350350
}
351351

352+
// Use a get-then-create approach to benefit from having a cache; otherwise if we always
353+
// send a create request, we're needlessly spamming the kube apiserver. Yes, this approach
354+
// is a race condition and we have to check for AlreadyExists later down the line, but that
355+
// only occurs on cold caches. During normal operations this should be more efficient.
352356
ns := &corev1.Namespace{}
353357
if err := client.Get(ctx, types.NamespacedName{Name: namespace}, ns); ctrlruntimeclient.IgnoreNotFound(err) != nil {
354358
return fmt.Errorf("failed to check: %w", err)
@@ -358,7 +362,7 @@ func (s *objectSyncer) ensureNamespace(ctx context.Context, log *zap.SugaredLogg
358362
ns.Name = namespace
359363

360364
log.Debugw("Creating namespace…", "namespace", namespace)
361-
if err := client.Create(ctx, ns); err != nil {
365+
if err := client.Create(ctx, ns); err != nil && !apierrors.IsAlreadyExists(err) {
362366
return fmt.Errorf("failed to create: %w", err)
363367
}
364368
}

0 commit comments

Comments
 (0)