Skip to content

Commit

Permalink
Merge pull request #2301 from vincepri/certwatcher-callback
Browse files Browse the repository at this point in the history
🌱 Add certwatcher callback
  • Loading branch information
k8s-ci-robot committed May 6, 2023
2 parents 62e6867 + aeedfbf commit bc7914c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
22 changes: 22 additions & 0 deletions pkg/certwatcher/certwatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ type CertWatcher struct {

certPath string
keyPath string

// callback is a function to be invoked when the certificate changes.
callback func(tls.Certificate)
}

// New returns a new CertWatcher watching the given certificate and key.
Expand All @@ -68,6 +71,17 @@ func New(certPath, keyPath string) (*CertWatcher, error) {
return cw, nil
}

// RegisterCallback registers a callback to be invoked when the certificate changes.
func (cw *CertWatcher) RegisterCallback(callback func(tls.Certificate)) {
cw.Lock()
defer cw.Unlock()
// If the current certificate is not nil, invoke the callback immediately.
if cw.currentCert != nil {
callback(*cw.currentCert)
}
cw.callback = callback
}

// GetCertificate fetches the currently loaded certificate, which may be nil.
func (cw *CertWatcher) GetCertificate(_ *tls.ClientHelloInfo) (*tls.Certificate, error) {
cw.RLock()
Expand Down Expand Up @@ -146,6 +160,14 @@ func (cw *CertWatcher) ReadCertificate() error {

log.Info("Updated current TLS certificate")

// If a callback is registered, invoke it with the new certificate.
cw.RLock()
defer cw.RUnlock()
if cw.callback != nil {
go func() {
cw.callback(cert)
}()
}
return nil
}

Expand Down
8 changes: 8 additions & 0 deletions pkg/certwatcher/certwatcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@ import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"net"
"os"
"sync/atomic"
"time"

. "github.com/onsi/ginkgo/v2"
Expand Down Expand Up @@ -97,6 +99,11 @@ var _ = Describe("CertWatcher", func() {

It("should reload currentCert when changed", func() {
doneCh := startWatcher()
called := atomic.Int64{}
watcher.RegisterCallback(func(crt tls.Certificate) {
called.Add(1)
Expect(crt.Certificate).ToNot(BeEmpty())
})

firstcert, _ := watcher.GetCertificate(nil)

Expand All @@ -111,6 +118,7 @@ var _ = Describe("CertWatcher", func() {

ctxCancel()
Eventually(doneCh, "4s").Should(BeClosed())
Expect(called.Load()).To(BeNumerically(">=", 1))
})

Context("prometheus metric read_certificate_total", func() {
Expand Down

0 comments on commit bc7914c

Please sign in to comment.