Skip to content

Commit f94c80a

Browse files
stuggiclaude
andcommitted
Wait for webhook certificates before checking endpoints
Operators with ENABLE_WEBHOOKS=true mount certificate secrets as volumes. If these secrets don't exist when the pod starts (cert-manager creates them asynchronously), the pod fails with FailedMount and crash-loops. This was surfaced by the new OLM-based CI flow which deploys operators and immediately proceeds to deploy OpenStackControlPlane, not giving cert-manager enough time to create the certificate secrets. Rather than checking the Secret directly (which would require a new cluster-wide RBAC grant for secrets: get/list/watch, raised as a concern on an earlier version of this change), check the backing cert-manager Certificate's Ready condition instead. The operator already has cluster-wide RBAC for cert-manager.io/certificates, so this needs no new RBAC at all, and Ready only flips true once cert-manager has synced valid data into the Secret, which also covers certificate regeneration/rotation. The disabled-operator check duplicated between checkWebhookCertificates and checkServiceEndpoints is unified into a shared isWebhookOperatorDisabled() helper built on the existing operator.HasOverrides(). Also fixes a related gap: cmd/operator/main.go's manager scheme never registered cert-manager's Certificate type, which would have made every Get on a Certificate fail with a scheme error rather than a usable NotFound. Added a scheme smoke test to guard against this regressing silently. Known follow-ups, left unaddressed as narrow edge cases: - cert-manager does not set an owner reference from the Secret to the Certificate by default, so a Certificate deleted/renamed out-of-band while its Secret survives would block readiness indefinitely even though the Secret is still mountable. - If cert-manager's temporary-certificate issuance were ever enabled for these Certificates, the Secret could become mountable before Ready flips true. Nothing in the current manifests uses it. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: Martin Schuppert <mschuppert@redhat.com>
1 parent 6cc8c4f commit f94c80a

4 files changed

Lines changed: 265 additions & 9 deletions

File tree

‎cmd/operator/main.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import (
4242
"sigs.k8s.io/controller-runtime/pkg/metrics/filters"
4343
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
4444

45+
certmgrv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1"
4546
"github.com/openstack-k8s-operators/lib-common/modules/common/operator"
4647
operatorv1beta1 "github.com/openstack-k8s-operators/openstack-operator/api/operator/v1beta1"
4748
operatorcontrollers "github.com/openstack-k8s-operators/openstack-operator/internal/controller/operator"
@@ -55,6 +56,7 @@ var (
5556
func init() {
5657
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
5758
utilruntime.Must(operatorv1beta1.AddToScheme(scheme))
59+
utilruntime.Must(certmgrv1.AddToScheme(scheme))
5860
}
5961

6062
// nolint:gocyclo

‎cmd/operator/main_test.go‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
Copyright 2026.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package main
18+
19+
import (
20+
"testing"
21+
22+
certmgrv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1"
23+
. "github.com/onsi/gomega" //revive:disable:dot-imports
24+
)
25+
26+
// TestSchemeHasCertManagerTypes guards against the manager's client scheme silently losing
27+
// cert-manager types it needs at runtime: OpenStackReconciler.checkWebhookCertificates reads
28+
// certmgrv1.Certificate objects, and a missing scheme registration fails every Get call with a
29+
// scheme error rather than a usable apierrors.IsNotFound, which unit tests built on their own
30+
// fake-client scheme would not catch.
31+
func TestSchemeHasCertManagerTypes(t *testing.T) {
32+
g := NewWithT(t)
33+
g.Expect(scheme.Recognizes(certmgrv1.SchemeGroupVersion.WithKind("Certificate"))).To(BeTrue())
34+
}

‎internal/controller/operator/openstack_controller.go‎

Lines changed: 82 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ import (
3535

3636
"k8s.io/apimachinery/pkg/runtime/schema"
3737

38+
certmgrv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1"
39+
cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1"
3840
"github.com/go-logr/logr"
3941
condition "github.com/openstack-k8s-operators/lib-common/modules/common/condition"
4042
"github.com/openstack-k8s-operators/lib-common/modules/common/helper"
@@ -50,6 +52,7 @@ import (
5052
apierrors "k8s.io/apimachinery/pkg/api/errors"
5153
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
5254
uns "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
55+
"k8s.io/apimachinery/pkg/types"
5356
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
5457
"sigs.k8s.io/controller-runtime/pkg/log"
5558
)
@@ -321,6 +324,23 @@ func (r *OpenStackReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
321324
return ctrl.Result{RequeueAfter: time.Duration(5) * time.Second}, err
322325
}
323326

327+
// Check if webhook certificates are ready before checking deployment status.
328+
// Operators with webhooks enabled mount these certificates and fail to start if
329+
// cert-manager hasn't finished issuing them yet, so check here first to requeue
330+
// with the appropriate delay instead of waiting on deployments that can't come up.
331+
ctrlResult, err := r.checkWebhookCertificates(ctx, instance)
332+
if err != nil {
333+
instance.Status.Conditions.Set(condition.FalseCondition(
334+
operatorv1beta1.OpenStackOperatorReadyCondition,
335+
condition.ErrorReason,
336+
condition.SeverityWarning,
337+
operatorv1beta1.OpenStackOperatorErrorMessage,
338+
err))
339+
return ctrl.Result{}, err
340+
} else if (ctrlResult != ctrl.Result{}) {
341+
return ctrlResult, nil
342+
}
343+
324344
// Check if all deployments are running
325345
deploymentsRunning, deploymentsPending, err := r.countDeployments(ctx, instance)
326346
instance.Status.DeployedOperatorCount = &deploymentsRunning
@@ -349,7 +369,7 @@ func (r *OpenStackReconciler) Reconcile(ctx context.Context, req ctrl.Request) (
349369
operatorv1beta1.OpenStackOperatorDeploymentsReadyMessage)
350370

351371
// Check if Services are running and have an endpoint
352-
ctrlResult, err := r.checkServiceEndpoints(ctx, instance)
372+
ctrlResult, err = r.checkServiceEndpoints(ctx, instance)
353373
if err != nil {
354374
instance.Status.Conditions.Set(condition.FalseCondition(
355375
operatorv1beta1.OpenStackOperatorReadyCondition,
@@ -550,17 +570,72 @@ func containerImageMatch(instance *operatorv1beta1.OpenStack) bool {
550570
return false
551571
}
552572

573+
// webhookOperatorNames is the static list of operators with webhooks enabled. Each backs a
574+
// "<name>-webhook-service" Service and a "<name>-serving-cert" cert-manager Certificate.
575+
var webhookOperatorNames = []string{"openstack-operator", "infra-operator", "openstack-baremetal-operator"}
576+
553577
func isWebhookEndpoint(name string) bool {
554-
// NOTE: this is a static list for all operators with webhooks enabled
555-
endpointNames := []string{"openstack-operator-webhook-service", "infra-operator-webhook-service", "openstack-baremetal-operator-webhook-service"}
556-
for _, prefix := range endpointNames {
557-
if strings.HasPrefix(name, prefix) {
578+
for _, prefix := range webhookOperatorNames {
579+
if strings.HasPrefix(name, prefix+"-webhook-service") {
558580
return true
559581
}
560582
}
561583
return false
562584
}
563585

586+
// isWebhookOperatorDisabled reports whether the operator backing a given webhookOperatorNames
587+
// entry (e.g. "infra-operator") has been scaled to 0 replicas via OperatorOverrides.
588+
func isWebhookOperatorDisabled(overrides []operatorv1beta1.OperatorSpec, webhookName string) bool {
589+
operatorName := strings.TrimSuffix(webhookName, "-operator")
590+
if ovr := operator.HasOverrides(overrides, operatorName); ovr != nil {
591+
return ovr.Replicas != nil && *ovr.Replicas == 0
592+
}
593+
return false
594+
}
595+
596+
// checkWebhookCertificates checks whether the cert-manager Certificate backing each enabled
597+
// operator's webhook server is Ready. Operator pods with ENABLE_WEBHOOKS=true mount the
598+
// Certificate's Secret as a volume and crash-loop if it doesn't exist yet, since cert-manager
599+
// creates it asynchronously. Checking the Certificate's Ready condition rather than the Secret
600+
// directly needs no Secrets RBAC (Certificates are already readable) and also covers
601+
// certificate regeneration/rotation, since cert-manager only flips Ready once the Secret holds
602+
// valid data.
603+
func (r *OpenStackReconciler) checkWebhookCertificates(ctx context.Context, instance *operatorv1beta1.OpenStack) (ctrl.Result, error) {
604+
Log := r.GetLogger(ctx)
605+
606+
for _, name := range webhookOperatorNames {
607+
if isWebhookOperatorDisabled(instance.Spec.OperatorOverrides, name) {
608+
continue
609+
}
610+
611+
certName := name + "-serving-cert"
612+
cert := &certmgrv1.Certificate{}
613+
err := r.Get(ctx, types.NamespacedName{Name: certName, Namespace: instance.Namespace}, cert)
614+
if err != nil {
615+
if apierrors.IsNotFound(err) {
616+
Log.Info("Waiting for webhook certificate to be created. Requeuing...", "name", certName)
617+
return ctrl.Result{RequeueAfter: time.Duration(5) * time.Second}, nil
618+
}
619+
return ctrl.Result{}, err
620+
}
621+
622+
ready := false
623+
for _, cond := range cert.Status.Conditions {
624+
if cond.Type == certmgrv1.CertificateConditionReady && cond.Status == cmmeta.ConditionTrue &&
625+
cond.ObservedGeneration == cert.Generation {
626+
ready = true
627+
break
628+
}
629+
}
630+
if !ready {
631+
Log.Info("Waiting for webhook certificate to become ready. Requeuing...", "name", certName)
632+
return ctrl.Result{RequeueAfter: time.Duration(5) * time.Second}, nil
633+
}
634+
}
635+
636+
return ctrl.Result{}, nil
637+
}
638+
564639
// checkServiceEndpoints -
565640
func (r *OpenStackReconciler) checkServiceEndpoints(ctx context.Context, instance *operatorv1beta1.OpenStack) (ctrl.Result, error) {
566641
Log := r.GetLogger(ctx)
@@ -581,10 +656,8 @@ func (r *OpenStackReconciler) checkServiceEndpoints(ctx context.Context, instanc
581656
if isWebhookEndpoint(endpointSliceName) {
582657
// is deployment disabled ?
583658
disabled := false
584-
for _, op := range instance.Spec.OperatorOverrides {
585-
if strings.HasPrefix(endpointSliceName, op.Name+"-operator") &&
586-
op.Replicas != nil && *op.Replicas == 0 {
587-
659+
for _, name := range webhookOperatorNames {
660+
if strings.HasPrefix(endpointSliceName, name) && isWebhookOperatorDisabled(instance.Spec.OperatorOverrides, name) {
588661
disabled = true
589662
Log.Info(fmt.Sprintf("Webhook %s disabled, skipping endpoint slice check", endpointSliceName), "name", endpointSlice.GetName())
590663
break

‎internal/controller/operator/openstack_controller_test.go‎

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,20 @@ import (
2020
"context"
2121
"testing"
2222

23+
certmgrv1 "github.com/cert-manager/cert-manager/pkg/apis/certmanager/v1"
24+
cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1"
2325
. "github.com/onsi/gomega" //revive:disable:dot-imports
2426

2527
operatorv1beta1 "github.com/openstack-k8s-operators/openstack-operator/api/operator/v1beta1"
2628
corev1 "k8s.io/api/core/v1"
29+
apierrors "k8s.io/apimachinery/pkg/api/errors"
2730
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2831
"k8s.io/apimachinery/pkg/runtime"
32+
"k8s.io/utils/ptr"
33+
ctrl "sigs.k8s.io/controller-runtime"
2934
"sigs.k8s.io/controller-runtime/pkg/client"
3035
fakeclient "sigs.k8s.io/controller-runtime/pkg/client/fake"
36+
"sigs.k8s.io/controller-runtime/pkg/client/interceptor"
3137
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
3238
)
3339

@@ -37,9 +43,150 @@ func newTestScheme(t *testing.T) *runtime.Scheme {
3743
g := NewWithT(t)
3844
g.Expect(corev1.AddToScheme(s)).To(Succeed())
3945
g.Expect(operatorv1beta1.AddToScheme(s)).To(Succeed())
46+
g.Expect(certmgrv1.AddToScheme(s)).To(Succeed())
4047
return s
4148
}
4249

50+
func readyCertificate(name, namespace string) *certmgrv1.Certificate {
51+
return &certmgrv1.Certificate{
52+
ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace, Generation: 1},
53+
Status: certmgrv1.CertificateStatus{
54+
Conditions: []certmgrv1.CertificateCondition{
55+
{Type: certmgrv1.CertificateConditionReady, Status: cmmeta.ConditionTrue, ObservedGeneration: 1},
56+
},
57+
},
58+
}
59+
}
60+
61+
// TestCheckWebhookCertificates covers the cert-manager Certificate readiness gate that
62+
// prevents the operator from waiting on deployments that can't start because their webhook
63+
// certificate Secret hasn't been issued yet.
64+
func TestCheckWebhookCertificates(t *testing.T) {
65+
ctx := context.Background()
66+
instance := &operatorv1beta1.OpenStack{
67+
ObjectMeta: metav1.ObjectMeta{Name: "openstack", Namespace: "openstack-operators"},
68+
}
69+
70+
t.Run("requeues when a certificate is missing", func(t *testing.T) {
71+
g := NewWithT(t)
72+
s := newTestScheme(t)
73+
fakeClient := fakeclient.NewClientBuilder().WithScheme(s).WithObjects(instance).Build()
74+
r := &OpenStackReconciler{Client: fakeClient, Scheme: s}
75+
76+
result, err := r.checkWebhookCertificates(ctx, instance)
77+
g.Expect(err).NotTo(HaveOccurred())
78+
g.Expect(result.RequeueAfter).NotTo(BeZero())
79+
})
80+
81+
t.Run("requeues when a certificate exists but isn't ready", func(t *testing.T) {
82+
g := NewWithT(t)
83+
s := newTestScheme(t)
84+
notReady := &certmgrv1.Certificate{
85+
ObjectMeta: metav1.ObjectMeta{Name: "openstack-operator-serving-cert", Namespace: "openstack-operators"},
86+
}
87+
objs := []client.Object{
88+
instance, notReady,
89+
readyCertificate("infra-operator-serving-cert", "openstack-operators"),
90+
readyCertificate("openstack-baremetal-operator-serving-cert", "openstack-operators"),
91+
}
92+
fakeClient := fakeclient.NewClientBuilder().WithScheme(s).WithObjects(objs...).Build()
93+
r := &OpenStackReconciler{Client: fakeClient, Scheme: s}
94+
95+
result, err := r.checkWebhookCertificates(ctx, instance)
96+
g.Expect(err).NotTo(HaveOccurred())
97+
g.Expect(result.RequeueAfter).NotTo(BeZero())
98+
})
99+
100+
t.Run("requeues when Ready is stale from a previous generation", func(t *testing.T) {
101+
g := NewWithT(t)
102+
s := newTestScheme(t)
103+
// Certificate spec changed (Generation bumped to 2) but status still reflects the old
104+
// generation's Ready condition - cert-manager hasn't reconciled the new spec yet.
105+
stale := &certmgrv1.Certificate{
106+
ObjectMeta: metav1.ObjectMeta{Name: "openstack-operator-serving-cert", Namespace: "openstack-operators", Generation: 2},
107+
Status: certmgrv1.CertificateStatus{
108+
Conditions: []certmgrv1.CertificateCondition{
109+
{Type: certmgrv1.CertificateConditionReady, Status: cmmeta.ConditionTrue, ObservedGeneration: 1},
110+
},
111+
},
112+
}
113+
objs := []client.Object{
114+
instance, stale,
115+
readyCertificate("infra-operator-serving-cert", "openstack-operators"),
116+
readyCertificate("openstack-baremetal-operator-serving-cert", "openstack-operators"),
117+
}
118+
fakeClient := fakeclient.NewClientBuilder().WithScheme(s).WithObjects(objs...).Build()
119+
r := &OpenStackReconciler{Client: fakeClient, Scheme: s}
120+
121+
result, err := r.checkWebhookCertificates(ctx, instance)
122+
g.Expect(err).NotTo(HaveOccurred())
123+
g.Expect(result.RequeueAfter).NotTo(BeZero(), "a Ready condition from a stale generation must not be treated as current")
124+
})
125+
126+
t.Run("proceeds when all certificates are ready", func(t *testing.T) {
127+
g := NewWithT(t)
128+
s := newTestScheme(t)
129+
objs := []client.Object{
130+
instance,
131+
readyCertificate("openstack-operator-serving-cert", "openstack-operators"),
132+
readyCertificate("infra-operator-serving-cert", "openstack-operators"),
133+
readyCertificate("openstack-baremetal-operator-serving-cert", "openstack-operators"),
134+
}
135+
fakeClient := fakeclient.NewClientBuilder().WithScheme(s).WithObjects(objs...).Build()
136+
r := &OpenStackReconciler{Client: fakeClient, Scheme: s}
137+
138+
result, err := r.checkWebhookCertificates(ctx, instance)
139+
g.Expect(err).NotTo(HaveOccurred())
140+
g.Expect(result.RequeueAfter).To(BeZero())
141+
})
142+
143+
t.Run("propagates a non-NotFound error from the API server", func(t *testing.T) {
144+
g := NewWithT(t)
145+
s := newTestScheme(t)
146+
fakeClient := fakeclient.NewClientBuilder().
147+
WithScheme(s).
148+
WithObjects(instance).
149+
WithInterceptorFuncs(interceptor.Funcs{
150+
Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error {
151+
if _, ok := obj.(*certmgrv1.Certificate); ok {
152+
return apierrors.NewServiceUnavailable("etcd unavailable")
153+
}
154+
return c.Get(ctx, key, obj, opts...)
155+
},
156+
}).
157+
Build()
158+
r := &OpenStackReconciler{Client: fakeClient, Scheme: s}
159+
160+
result, err := r.checkWebhookCertificates(ctx, instance)
161+
g.Expect(err).To(HaveOccurred())
162+
g.Expect(result).To(Equal(ctrl.Result{}))
163+
})
164+
165+
t.Run("skips disabled operators even if their certificate is missing", func(t *testing.T) {
166+
g := NewWithT(t)
167+
s := newTestScheme(t)
168+
disabledInstance := &operatorv1beta1.OpenStack{
169+
ObjectMeta: metav1.ObjectMeta{Name: "openstack", Namespace: "openstack-operators"},
170+
Spec: operatorv1beta1.OpenStackSpec{
171+
OperatorOverrides: []operatorv1beta1.OperatorSpec{
172+
{Name: "infra", Replicas: ptr.To(int32(0))},
173+
{Name: "openstack-baremetal", Replicas: ptr.To(int32(0))},
174+
},
175+
},
176+
}
177+
objs := []client.Object{
178+
disabledInstance,
179+
readyCertificate("openstack-operator-serving-cert", "openstack-operators"),
180+
}
181+
fakeClient := fakeclient.NewClientBuilder().WithScheme(s).WithObjects(objs...).Build()
182+
r := &OpenStackReconciler{Client: fakeClient, Scheme: s}
183+
184+
result, err := r.checkWebhookCertificates(ctx, disabledInstance)
185+
g.Expect(err).NotTo(HaveOccurred())
186+
g.Expect(result.RequeueAfter).To(BeZero(), "disabled operators' missing certificates should not block")
187+
})
188+
}
189+
43190
// TestAdoptAwayServiceAccounts covers the ownership-migration logic: sub-operator
44191
// ServiceAccounts left over from before openstack-operator#2109 are still
45192
// controlled by the OpenStack instance, but this controller no longer manages them

0 commit comments

Comments
 (0)