8000 feat(metrics): adding `certmanager_certificate_challenge_status` metric by hjoshi123 · Pull Request #7736 · cert-manager/cert-manager · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat(metrics): adding certmanager_certificate_challenge_status metric #7736

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions internal/apis/config/controller/v1alpha1/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/cert-manager/cert-manager/pkg/apis/config/controller/v1alpha1"
sharedv1alpha1 "github.com/cert-manager/cert-manager/pkg/apis/config/shared/v1alpha1"
challengescontroller "github.com/cert-manager/cert-manager/pkg/controller/acmechallenges"
acmechallengesmetricscontroller "github.com/cert-manager/cert-manager/pkg/controller/acmechallenges/metrics"
orderscontroller "github.com/cert-manager/cert-manager/pkg/controller/acmeorders"
shimgatewaycontroller "github.com/cert-manager/cert-manager/pkg/controller/certificate-shim/gateways"
shimingresscontroller "github.com/cert-manager/cert-manager/pkg/controller/certificate-shim/ingresses"
Expand Down Expand Up @@ -128,6 +129,7 @@ var (
csrselfsignedcontroller.CSRControllerName,
csrvenaficontroller.CSRControllerName,
csrvaultcontroller.CSRControllerName,
acmechallengesmetricscontroller.ControllerName,
}

DefaultEnabledControllers = []string{
Expand All @@ -150,6 +152,7 @@ var (
requestmanager.ControllerName,
readiness.ControllerName,
revisionmanager.ControllerName,
acmechallengesmetricscontroller.ControllerName,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs adding to AllControllers as well

}

ExperimentalCertificateSigningRequestControllers = []string{
Expand Down
113 changes: 113 additions & 0 deletions pkg/controller/acmechallenges/metrics/controller.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
Copyright 2025 The cert-manager 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 metrics

impo 10000 rt (
"context"
"fmt"

apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"

cmacmelisters "github.com/cert-manager/cert-manager/pkg/client/listers/acme/v1"
controllerpkg "github.com/cert-manager/cert-manager/pkg/controller"
"github.com/cert-manager/cert-manager/pkg/metrics"
)

const (
// ControllerName is the string used to refer to this controller
// when enabling or disabling it from command line flags.
ControllerName = "certificate-challenges-metrics"
)

// controllerWrapper wraps the `controller` structure to make it implement
// the controllerpkg.queueingController interface
type controllerWrapper struct {
*controller
}

// This controller is synced on all Certificate 'create', 'update', and
// 'delete' events which will update the metrics for that Certificate.
type controller struct {
certificateChallengeListers cmacmelisters.ChallengeLister

metrics *metrics.Metrics
}

func NewController(ctx *controllerpkg.Context) (*controller, workqueue.TypedRateLimitingInterface[types.NamespacedName], []cache.InformerSynced, error) {
// create a queue used to queue up items to be processed
queue := workqueue.NewTypedRateLimitingQueueWithConfig(
controllerpkg.DefaultCertificateRateLimiter(),
workqueue.TypedRateLimitingQueueConfig[types.NamespacedName]{
Name: ControllerName,
},
)

certificateChallengeInformer := ctx.SharedInformerFactory.Acme().V1().Challenges()

// handle all events when challenge is created, updated, or deleted. Delete shouldn't matter for challenges
// but leaving the behavior of the default queueing event handler.
if _, err := certificateChallengeInformer.Informer().AddEventHandler(&controllerpkg.QueuingEventHandler{
Queue: queue,
}); err != nil {
return nil, nil, nil, fmt.Errorf("error setting up event handler: %v", err)
}

// build a list of InformerSynced functions that will be returned by the
// Register method. the controller will only begin processing items once all
// of these informers have synced.
mustSync := []cache.InformerSynced{
certificateChallengeInformer.Informer().HasSynced,
}

return &controller{
certificateChallengeListers: certificateChallengeInformer.Lister(),
metrics: ctx.Metrics,
}, queue, mustSync, nil
}

func (c *controller) ProcessItem(ctx context.Context, namespace types.NamespacedName) error {
ns, name := namespace.Namespace, namespace.Name

challenge, err := c.certificateChallengeListers.Challenges(ns).Get(name)
if apierrors.IsNotFound(err) {
c.metrics.RemoveChallengeStatus(challenge)
return nil
}
if err != nil {
return err
}

c.metrics.UpdateChallengeStatus(challenge)
return nil
}

func (c *controllerWrapper) Register(ctx *controllerpkg.Context) (workqueue.TypedRateLimitingInterface[types.NamespacedName], []cache.InformerSynced, error) {
ctrl, queue, mustSync, err := NewController(ctx)
c.controller = ctrl
return queue, mustSync, err
}

func init() {
controllerpkg.Register(ControllerName, func(ctx *controllerpkg.ContextFactory) (controllerpkg.Interface, error) {
return controllerpkg.NewBuilder(ctx, ControllerName).
For(&controllerWrapper{}).
Complete()
})
}
29 changes: 29 additions & 0 deletions pkg/metrics/acme.go
8000
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@ limitations under the License.
package metrics

import (
"fmt"
"time"

"github.com/prometheus/client_golang/prometheus"

acmev1 "github.com/cert-manager/cert-manager/pkg/apis/acme/v1"
)

// ObserveACMERequestDuration increases bucket counters for that ACME client duration.
Expand All @@ -29,3 +34,27 @@ func (m *Metrics) ObserveACMERequestDuration(duration time.Duration, labels ...s
func (m *Metrics) IncrementACMERequestCount(labels ...string) {
m.acmeClientRequestCount.WithLabelValues(labels...).Inc()
}

func (m *Metrics) UpdateChallengeStatus(challenge *acmev1.Challenge) {
for _, status := range challengeValidStatuses {
value := 0.0
if string(challenge.Status.State) == string(status) {
value = 1.0
}

m.certificateChallengeStatus.With(prometheus.Labels{
"status": string(status),
"reason": challenge.Status.Reason,
"domain": challenge.Spec.DNSName,
"type": string(challenge.Spec.Type),
"id": string(challenge.GetUID()),
"processing": fmt.Sprint(challenge.Status.Processing),
}).Set(value)
}
}

func (m *Metrics) RemoveChallengeStatus(challenge *acmev1.Challenge) {
m.certificateChallengeStatus.DeletePartialMatch(prometheus.Labels{
"id": string(challenge.GetUID()),
})
}
88 changes: 88 additions & 0 deletions pkg/metrics/acme_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
Copyright 2025 The cert-manager 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 metrics

import (
"strings"
"testing"

"github.com/go-logr/logr/testr"
"github.com/prometheus/client_golang/prometheus/testutil"
"k8s.io/utils/clock"

cmacme "github.com/cert-manager/cert-manager/pkg/apis/acme/v1"
"github.com/cert-manager/cert-manager/test/unit/gen"
)

const certificateChallengeStatusMetadata = `
# HELP certmanager_certificate_challenge_status The status of certificate challenges.
# TYPE certmanager_certificate_challenge_status gauge
`

func TestCertificateChallengeStatusMetrics(t *testing.T) {
type TestChallenge struct {
challenges []*cmacme.Challenge
expectedMetric string
}

pendingToValidChallenges := make([]*cmacme.Challenge, 0)
pendingToValidChallenges = append(pendingToValidChallenges, gen.Challenge("test-challenge-status",
gen.SetChallengeDNSName("example.com"),
gen.SetChallengeProcessing(false),
gen.SetChallengeType(cmacme.ACMEChallengeTypeDNS01),
gen.SetChallengeState(cmacme.Pending),
gen.SetChallengeUID("test-challenge-uid"),
), gen.Challenge("test-challenge-status-2",
gen.SetChallengeDNSName("example.com"),
gen.SetChallengeProcessing(false),
gen.SetChallengeType(cmacme.ACMEChallengeTypeDNS01),
gen.SetChallengeState(cmacme.Ready),
gen.SetChallengeUID("test-challenge-uid"),
))
testCases := map[string]TestChallenge{
"challenge-metric-active-state-valid": {
challenges: pendingToValidChallenges,
expectedMetric: `
certmanager_certificate_challenge_status{domain="example.com",id="test-challenge-uid",processing="false",reason="",status="",type="DNS-01"} 0
certmanager_certificate_challenge_status{domain="example.com",id="test-challenge-uid",processing="false",reason="",status="errored",type="DNS-01"} 0
certmanager_certificate_challenge_status{domain="example.com",id="test-challenge-uid",processing="false",reason="",status="expired",type="DNS-01"} 0
certmanager_certificate_challenge_status{domain="example.com",id="test-challenge-uid",processing="false",reason="",status="invalid",type="DNS-01"} 0
certmanager_certificate_challenge_status{domain="example.com",id="test-challenge-uid",processing="false",reason="",status="processing",type="DNS-01"} 0
certmanager_certificate_challenge_status{domain="example.com",id="test-challenge-uid",processing="false",reason="",status="pending",type="DNS-01"} 0
certmanager_certificate_challenge_status{domain="example.com",id="test-challenge-uid",processing="false",reason="",status="ready",type="DNS-01"} 1
certmanager_certificate_challenge_status{domain="example.com",id="test-challenge-uid",processing="false",reason="",status="valid",type="DNS-01"} 0
`,
},
}

for testName, test := range testCases {
t.Run(testName, func(t *testing.T) {
m := New(testr.New(t), clock.RealClock{})

for _, challenge := range test.challenges {
m.UpdateChallengeStatus(challenge)
}

if err := testutil.CollectAndCompare(m.certificateChallengeStatus,
strings.NewReader(certificateChallengeStatusMetadata+test.expectedMetric),
"certmanager_certificate_challenge_status",
); err != nil {
t.Errorf("unexpected collecting result:\n%s", err)
}
})
}
}
16 changes: 15 additions & 1 deletion pkg/metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ limitations under the License.
// certificate_expiration_timestamp_seconds{name, namespace, issuer_name, issuer_kind, issuer_group}
// certificate_renewal_timestamp_seconds{name, namespace, issuer_name, issuer_kind, issuer_group}
// certificate_ready_status{name, namespace, condition, issuer_name, issuer_kind, issuer_group}
// certificate_challenge_status{status, domain, reason, processing, id, type}
// acme_client_request_count{"scheme", "host", "path", "method", "status"}
// acme_client_request_duration_seconds{"scheme", "host", "path", "method", "status"}
// venafi_client_request_duration_seconds{"scheme", "host", "path", "method", "status"}
Expand All @@ -36,6 +37,7 @@ import (
"github.com/prometheus/client_golang/prometheus/promhttp"
"k8s.io/utils/clock"

acmemeta "github.com/cert-manager/cert-manager/pkg/apis/acme/v1"
cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1"
)

Expand Down Expand Up @@ -65,9 +67,13 @@ type Metrics struct {
venafiClientRequestDurationSeconds *prometheus.SummaryVec
controllerSyncCallCount *prometheus.CounterVec
controllerSyncErrorCount *prometheus.CounterVec
certificateChallengeStatus *prometheus.GaugeVec
}

var readyConditionStatuses = [...]cmmeta.ConditionStatus{cmmeta.ConditionTrue, cmmeta.ConditionFalse, cmmeta.ConditionUnknown}
var (
readyConditionStatuses = [...]cmmeta.ConditionStatus{cmmeta.ConditionTrue, cmmeta.ConditionFalse, cmmeta.ConditionUnknown}
challengeValidStatuses = [...]acmemeta.State{acmemeta.Ready, acmemeta.Valid, acmemeta.Errored, acmemeta.Expired, acmemeta.Invalid, acmemeta.Processing, acmemeta.Unknown, acmemeta.Pending}
)

// New creates a Metrics struct and populates it with prometheus metric types.
func New(log logr.Logger, c clock.Clock) *Metrics {
Expand Down Expand Up @@ -205,6 +211,12 @@ func New(log logr.Logger, c clock.Clock) *Metrics {
},
[]string{"controller"},
)

certificateChallengeStatus = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace,
Name: "certificate_challenge_status",
Help: "The status of certificate challenges.",
}, []string{"status", "domain", "reason", "processing", "id", "type"})
)

// Create Registry and register the recommended collectors
Expand All @@ -230,6 +242,7 @@ func New(log logr.Logger, c clock.Clock) *Metrics {
venafiClientRequestDurationSeconds: venafiClientRequestDurationSeconds,
controllerSyncCallCount: controllerSyncCallCount,
controllerSyncErrorCount: controllerSyncErrorCount,
certificateChallengeStatus: certificateChallengeStatus,
}

return m
Expand All @@ -249,6 +262,7 @@ func (m *Metrics) NewServer(ln net.Listener) *http.Server {
m.registry.MustRegister(m.acmeClientRequestCount)
m.registry.MustRegister(m.controllerSyncCallCount)
m.registry.MustRegister(m.controllerSyncErrorCount)
m.registry.MustRegister(m.certificateChallengeStatus)

mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.HandlerFor(m.registry, promhttp.HandlerOpts{}))
Expand Down
7 changes: 7 additions & 0 deletions test/unit/gen/challenge.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package gen

import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"

cmacme "github.com/cert-manager/cert-manager/pkg/apis/acme/v1"
cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1"
Expand Down Expand Up @@ -128,6 +129,12 @@ func SetChallengeDeletionTimestamp(ts metav1.Time) ChallengeModifier {
}
}

func SetChallengeUID(uid string) ChallengeModifier {
return func(ch *cmacme.Challenge) {
ch.UID = types.UID(uid)
}
}

func ResetChallengeStatus() ChallengeModifier {
return func(ch *cmacme.Challenge) {
ch.Status = cmacme.ChallengeStatus{}
Expand Down
0