Skip to content

Commit

Permalink
pref: update log msg (#195)
Browse files Browse the repository at this point in the history
* pref: update log msg

* pref: fix lint code mess

---------

Co-authored-by: wanghuagang <[email protected]>
  • Loading branch information
whg517 and wanghuagang authored Jan 9, 2025
1 parent 2466ed4 commit 5bf5470
Show file tree
Hide file tree
Showing 10 changed files with 187 additions and 161 deletions.
16 changes: 8 additions & 8 deletions internal/csi/backend/autotls.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,17 +78,17 @@ func (a *AutoTlsBackend) getCertLife() (time.Duration, error) {

certLife := a.volumeContext.AutoTlsCertLifetime
if certLife == 0 {
logger.Info("Certificate lifetime is not set, using default certificate lifetime", "defaultCertLifeTime", DefaultCertLifeTime)
logger.V(1).Info("certificate lifetime is not set, using default certificate lifetime", "defaultCertLifeTime", DefaultCertLifeTime)
certLife = DefaultCertLifeTime
}
restarterBuffer := a.volumeContext.AutoTlsCertRestartBuffer
if restarterBuffer == 0 {
logger.Info("Certificate restart buffer is not set, using default certificate restart buffer", "defaultCertBuffer", DefaultCertBuffer)
logger.V(1).Info("certificate restart buffer is not set, using default certificate restart buffer", "defaultCertBuffer", DefaultCertBuffer)
restarterBuffer = DefaultCertBuffer
}

if certLife > a.maxCertificateLifeTime {
logger.Info("Certificate lifetime is greater than the maximum certificate lifetime, using the maximum certificate lifetime",
logger.V(1).Info("certificate lifetime is greater than the maximum certificate lifetime, using the maximum certificate lifetime",
"certLife", certLife,
"maxCertificateLifeTime", a.maxCertificateLifeTime,
)
Expand All @@ -99,15 +99,15 @@ func (a *AutoTlsBackend) getCertLife() (time.Duration, error) {

jitterFactorAllowedRange := 0.0 < jitterFactor && jitterFactor < 1.0
if !jitterFactorAllowedRange {
logger.Info("Invalid jitter factor, using default value", "jitterFactor", jitterFactor)
logger.V(1).Info("invalid jitter factor, using default value", "jitterFactor", jitterFactor)
jitterFactor = DefaultCertJitter
}

randomJitterFactor := rand.Float64() * jitterFactor
jitterLife := time.Duration(float64(certLife) * jitterFactor)
jitteredCertLife := certLife - jitterLife

logger.Info("Jittered certificate lifetime",
logger.V(1).Info("jittered certificate lifetime",
"certLife", certLife,
"jitteredCertLife", jitteredCertLife,
"jitterLife", jitterLife,
Expand Down Expand Up @@ -139,7 +139,7 @@ func (a *AutoTlsBackend) certificateConvert(cert *ca.Certificate) (map[string]st
trustAnchors := a.certManager.GetTrustAnchors()

if format == volume.SecretFormatTLSP12 {
logger.Info("Converting certificate to PKCS12 format")
logger.V(1).Info("Converting certificate to PKCS12 format")
password := a.volumeContext.TlsPKCS12Password

caCerts := make([]*x509.Certificate, 0, len(trustAnchors))
Expand Down Expand Up @@ -167,7 +167,7 @@ func (a *AutoTlsBackend) certificateConvert(cert *ca.Certificate) (map[string]st
pemCACerts = append(pemCACerts, string(caCert.CertificatePEM()))
}

logger.Info("Converting certificate to PEM format")
logger.V(1).Info("converting certificate to PEM format")
return map[string]string{
PEMTlsCertFileName: string(cert.CertificatePEM()),
PEMTlsKeyFileName: string(cert.PrivateKeyPEM()),
Expand Down Expand Up @@ -204,7 +204,7 @@ func (a *AutoTlsBackend) GetSecretData(ctx context.Context) (*util.SecretContent
return nil, err
}

logger.Info("Signed certificate", "notAfter", notAfter, "addresses", addresses, "certLife", certLife, "certSerialNumber", cert.SerialNumber())
logger.V(1).Info("signed certificate", "notAfter", notAfter, "addresses", addresses, "certLife", certLife, "certSerialNumber", cert.SerialNumber())

data, err := a.certificateConvert(cert)
if err != nil {
Expand Down
52 changes: 25 additions & 27 deletions internal/csi/backend/ca/ca.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,15 @@ func NewCertificateAuthorityFromData(
}

// NewCertificateAuthorityFromSecret creates a new CertificateAuthority from a secret
func NewCertificateAuthority(root *Certificate) (*CertificateAuthority, error) {
func NewCertificateAuthority(ca *Certificate) (*CertificateAuthority, error) {
// check cert is a CA
if !root.Certificate.IsCA {
if !ca.Certificate.IsCA {
return nil, errors.New("root certificate is not a CA")
}

return &CertificateAuthority{
Certificate: root.Certificate,
privateKey: root.privateKey,
Certificate: ca.Certificate,
privateKey: ca.privateKey,
}, nil
}

Expand All @@ -128,7 +128,8 @@ func (c *CertificateAuthority) CertificatePEM() []byte {
func (c *CertificateAuthority) SignCertificate(
addresses []pod_info.Address,
extKeyUsage []x509.ExtKeyUsage,
notAfter time.Time) (*Certificate, error) {
notAfter time.Time,
) (*Certificate, error) {
// Generate a new private key
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
Expand Down Expand Up @@ -166,33 +167,15 @@ func (c *CertificateAuthority) SignCertificate(
template.ExtKeyUsage = extKeyUsage
}

var dnsNames []string
var ipAddresses []net.IP
for _, address := range addresses {
if address.IP != nil {
template.IPAddresses = append(template.IPAddresses, address.IP)
ipAddresses = append(ipAddresses, address.IP)
}
if address.Hostname != "" {
template.DNSNames = append(template.DNSNames, address.Hostname)
dnsNames = append(dnsNames, address.Hostname)
}
}

sanExt := &SubjectAltName{
DNSNames: dnsNames,
IPAddresses: ipAddresses,
}

ext, err := sanExt.ToExtension()
sanExt, err := c.getSANExt(addresses)
if err != nil {
return nil, err
}
// From RFC 5280, Section 4.2.1.6:
// "If the subject field contains an empty sequence, then the issuer field MUST also contain an empty sequence and the subjectAltName extension MUST be marked as critical."
// golang x509 library automatically sets the critical flag if the subject field is empty.
// But we pass a invalid subject to the template, so we need to set the critical flag manually.
template.ExtraExtensions = append(template.ExtraExtensions, ext)
template.ExtraExtensions = append(template.ExtraExtensions, sanExt)

certBytes, err := x509.CreateCertificate(rand.Reader, template, c.Certificate, &privateKey.PublicKey, c.privateKey)
if err != nil {
Expand All @@ -205,13 +188,28 @@ func (c *CertificateAuthority) SignCertificate(
return nil, err
}

logger.V(0).Info("Signed certificate", "subject", cert.Subject, "serialNumber", formatSerialNumber(cert.SerialNumber), "notAfter", cert.NotAfter, "sanDns", cert.DNSNames, "sanIp", cert.IPAddresses)
logger.V(1).Info("signed certificate", "subject", cert.Subject, "serialNumber", formatSerialNumber(cert.SerialNumber), "notAfter", cert.NotAfter, "sanDns", cert.DNSNames, "sanIp", cert.IPAddresses)
return &Certificate{
Certificate: cert,
privateKey: privateKey,
}, nil
}

func (c *CertificateAuthority) getSANExt(addresses []pod_info.Address) (pkix.Extension, error) {
var dnsNames []string
var ipAddresses []net.IP
for _, address := range addresses {
if address.IP != nil {
ipAddresses = append(ipAddresses, address.IP)
}
if address.Hostname != "" {
dnsNames = append(dnsNames, address.Hostname)
}
}
san := &SubjectAltName{DNSNames: dnsNames, IPAddresses: ipAddresses}
return san.ToExtension()
}

func (c *CertificateAuthority) SignServerCertificate(
addresses []pod_info.Address,
notAfter time.Time,
Expand All @@ -232,7 +230,7 @@ func (c *CertificateAuthority) Rotate(notAfter time.Time) (*CertificateAuthority
return nil, err
}

logger.V(0).Info("Rotated certificate authority", "notAfter", newCA.Certificate.NotAfter, "newSerialNumber", newCA.SerialNumber(), "currentSerialNumber", c.SerialNumber())
logger.V(1).Info("rotated certificate authority", "notAfter", newCA.Certificate.NotAfter, "newSerialNumber", newCA.SerialNumber(), "currentSerialNumber", c.SerialNumber())
return newCA, nil
}

Expand Down
29 changes: 17 additions & 12 deletions internal/csi/backend/ca/ca_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@ func (c *CertificateManager) getSecret(ctx context.Context) error {
if client.IgnoreNotFound(err) != nil {
return err
}
logger.V(1).Info("Could not find secret", "name", c.name, "namespace", c.namespace)
logger.V(1).Info("could not find secret", "name", c.name, "namespace", c.namespace)
return nil
}
logger.V(5).Info("Found secret", "name", c.name, "namespace", c.namespace)
logger.V(5).Info("found secret", "name", c.name, "namespace", c.namespace)
return nil
}

Expand All @@ -81,7 +81,7 @@ func (c *CertificateManager) updateSecret(ctx context.Context, data map[string][
if err := c.client.Update(ctx, c.secret); err != nil {
return err
}
logger.V(0).Info("Saved certificate authorities PEM key pairs to secret", "name", c.name, "namespace", c.namespace)
logger.V(1).Info("saved certificate authorities PEM key pairs to secret", "name", c.name, "namespace", c.namespace)
return nil
}

Expand All @@ -90,7 +90,7 @@ func (c *CertificateManager) secretCreateIfDoesNotExist(ctx context.Context) err
return nil
}

logger.V(1).Info("Could not find secret, create a new secret", "name", c.name, "namespace", c.namespace, "auto", c.auto)
logger.V(1).Info("could not find secret, create a new secret", "name", c.name, "namespace", c.namespace, "auto", c.auto)
if err := c.client.Create(ctx, c.secret); err != nil {
return err
}
Expand All @@ -115,7 +115,7 @@ func (c CertificateManager) getPEMKeyPairsFromSecret(ctx context.Context) ([]PEM
}
}

logger.V(0).Info("got certificate authorities PEM key pairs from secret", "name", c.name, "namespace", c.namespace, "len", len(keyPairs))
logger.V(1).Info("got certificate authorities PEM key pairs from secret", "name", c.name, "namespace", c.namespace, "len", len(keyPairs))
return keyPairs, nil
}

Expand Down Expand Up @@ -171,7 +171,7 @@ func (c *CertificateManager) getCertificateAuthorities(pemKeyPairs []PEMkeyPair)
return nil, err
}
if ca.Certificate.NotAfter.Before(time.Now()) {
logger.V(0).Info("certificate authority is expired, skip it.", "serialNumber", ca.SerialNumber(), "notAfter", ca.Certificate.NotAfter)
logger.V(1).Info("certificate authority is expired, skip it.", "serialNumber", ca.SerialNumber(), "notAfter", ca.Certificate.NotAfter)
continue
}
cas = append(cas, ca)
Expand All @@ -187,7 +187,9 @@ func (c *CertificateManager) getCertificateAuthorities(pemKeyPairs []PEMkeyPair)
)
}

logger.V(0).Info("could not find any certificate authorities, created a new self-signed certificate authority", "name", c.name, "namespace", c.namespace, "auto", c.auto)
logger.V(1).Info("could not find any valid certificate authorities, created a new self-signed certificate authority",
"name", c.name, "namespace", c.namespace, "auto", c.auto,
)
ca, err := c.createSelfSignedCertificateAuthority()
if err != nil {
return nil, err
Expand All @@ -213,7 +215,7 @@ func (c *CertificateManager) createSelfSignedCertificateAuthority() (*Certificat
if err != nil {
return nil, err
}
logger.V(0).Info("created new self-signed certificate authority", "serialNumber", ca.SerialNumber(), "notAfter", ca.Certificate.NotAfter)
logger.V(1).Info("created new self-signed certificate authority", "serialNumber", ca.SerialNumber(), "notAfter", ca.Certificate.NotAfter)
return ca, nil
}

Expand All @@ -240,6 +242,9 @@ func (c *CertificateManager) rotateCertificateAuthority(cas []*CertificateAuthor
return nil, errors.New("certificate authorities is empty")
}

// sort certificate authority as ascending
c.sort(cas)

newestCA := cas[len(cas)-1]

if time.Now().Add(c.caCertificateLifetime / 2).After(newestCA.Certificate.NotAfter) {
Expand All @@ -248,19 +253,19 @@ func (c *CertificateManager) rotateCertificateAuthority(cas []*CertificateAuthor
if err != nil {
return nil, err
}
logger.V(0).Info("rotated certificate authority, because the old ca is about to expire",
logger.V(1).Info("rotated certificate authority, because the old ca is about to expire",
"serialNumber", newestCA.SerialNumber(),
"notAfter", newCA.Certificate.NotAfter,
)
cas = append(cas, newCA)
} else {
logger.V(0).Info("certificate authority is about to expire, but auto-generate is disabled, please rotate manually.",
logger.V(1).Info("certificate authority is about to expire, but auto-generate is disabled, please rotate manually.",
"serialNumber", newestCA.SerialNumber(),
"notAfter", newestCA.Certificate.NotAfter,
)
}
} else {
logger.V(0).Info("certificate authority is still valid, no need to rotate",
logger.V(1).Info("certificate authority is still valid, no need to rotate",
"serialNumber", newestCA.SerialNumber(),
"notAfter", newestCA.Certificate.NotAfter,
)
Expand All @@ -283,7 +288,7 @@ func (c *CertificateManager) getAliveCertificateAuthority(atAfter time.Time, cas
}
return 0
})
logger.V(0).Info("got alive certificate authority", "serialNumber", oldestCA.SerialNumber(), "notAfter", oldestCA.Certificate.NotAfter)
logger.V(1).Info("got alive certificate authority", "serialNumber", oldestCA.SerialNumber(), "notAfter", oldestCA.Certificate.NotAfter)

return oldestCA
}
Expand Down
10 changes: 6 additions & 4 deletions internal/csi/backend/k8s_search.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ func (k *K8sSearchBackend) getSecretList(ctx context.Context, matchingLabels map
return nil, err
}

logger.V(1).Info("searching secrets", "namespace", namespace, "matchingLabels", matchingLabels)
objs := &corev1.SecretList{}
if err := k.client.List(ctx, objs, client.InNamespace(namespace), client.MatchingLabels(matchingLabels)); err != nil {
return nil, err
Expand All @@ -79,7 +80,7 @@ func (k *K8sSearchBackend) getSecretList(ctx context.Context, matchingLabels map
for _, obj := range objs.Items {
secretNames = append(secretNames, obj.GetName())
}
logger.V(1).Info("Found secrets", "total", len(secretNames), "secrets", secretNames)
logger.V(1).Info("found secrets", "total", len(secretNames), "secrets", secretNames, "namespace", namespace, "matchingLabels", matchingLabels)

return objs, nil
}
Expand All @@ -104,7 +105,7 @@ func (k *K8sSearchBackend) matchingLabels(ctx context.Context, hasListenerNodeSc
labels[constants.LabelSecretsNode] = pod.Spec.NodeName
}

listenerVolumesToListenerName, err := k.podInfo.GetListenerVolumeNamesToListenerName(ctx)
listenerVolumesToListenerName, err := k.podInfo.GetScopedListenerVolumeNamesToListenerName(ctx)
if err != nil {
return nil, err
}
Expand All @@ -127,6 +128,7 @@ func (k *K8sSearchBackend) GetQualifiedNodeNames(ctx context.Context) ([]string,
}

if !hasListenerNodeScope {
logger.V(1).Info("no listeners in node scope")
return nil, nil
}

Expand Down Expand Up @@ -156,7 +158,7 @@ func (k *K8sSearchBackend) GetQualifiedNodeNames(ctx context.Context) ([]string,
if err != nil {
return nil, err
}
logger.V(1).Info("Found nodes from secrets with labels when listener node scope is enabled",
logger.V(1).Info("found nodes from secrets with labels when listener node scope is enabled",
"total", len(ndoes), "nodes", ndoes, "namespace", namespace, "matchingLabels", matchingLabels,
)
return ndoes, nil
Expand Down Expand Up @@ -189,7 +191,7 @@ func (k *K8sSearchBackend) GetSecretData(ctx context.Context) (*util.SecretConte
}

secret := objs.Items[0]
logger.V(1).Info("Found secret", "name", secret.GetName())
logger.V(1).Info("found secret", "name", secret.GetName(), "namespace", secret.GetNamespace())

decoded, err := DecodeSecretData(secret.Data)
if err != nil {
Expand Down
Loading

0 comments on commit 5bf5470

Please sign in to comment.