From 6e406083f2df8ba6aa1aea3a95830a7619f2b226 Mon Sep 17 00:00:00 2001 From: Aliaksandr Valialkin Date: Fri, 2 Jul 2021 13:20:15 +0300 Subject: [PATCH] lib/promauth: cache the client TLS certificate for up to a second This should reduce CPU usage when TLS connections are established at a high rate. --- lib/promauth/config.go | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/lib/promauth/config.go b/lib/promauth/config.go index 32206c7a2..5ac894355 100644 --- a/lib/promauth/config.go +++ b/lib/promauth/config.go @@ -210,7 +210,26 @@ func (ac *Config) NewTLSConfig() *tls.Config { if ac == nil { return tlsCfg } - tlsCfg.GetClientCertificate = ac.getTLSCert + if ac.getTLSCert != nil { + var certLock sync.Mutex + var cert *tls.Certificate + var certDeadline uint64 + tlsCfg.GetClientCertificate = func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) { + // Cache the certificate for up to a second in order to save CPU time + // on certificate parsing when TLS connection are frequently re-established. + certLock.Lock() + defer certLock.Unlock() + if fasttime.UnixTimestamp() > certDeadline { + c, err := ac.getTLSCert(cri) + if err != nil { + return nil, err + } + cert = c + certDeadline = fasttime.UnixTimestamp() + 1 + } + return cert, nil + } + } tlsCfg.RootCAs = ac.TLSRootCA tlsCfg.ServerName = ac.TLSServerName tlsCfg.InsecureSkipVerify = ac.TLSInsecureSkipVerify