Skip to content

Commit

Permalink
PR review improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
ReToCode committed Aug 7, 2023
1 parent fdbb4c0 commit 99ae0c1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
23 changes: 14 additions & 9 deletions pkg/queue/certificate/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package certificate
import (
"crypto/sha256"
"crypto/tls"
"fmt"
"os"
"path"
"sync"
Expand Down Expand Up @@ -62,7 +63,9 @@ func NewCertWatcher(certPath, keyPath string, reloadInterval time.Duration, logg
zap.String("certDir", certDir), zap.String("keyDir", keyDir))

// initial load
cw.loadCert()
if err := cw.loadCert(); err != nil {
return nil, err
}

go cw.watch()

Expand Down Expand Up @@ -90,22 +93,23 @@ func (cw *CertWatcher) watch() {
return

case <-cw.ticker.C:
cw.loadCert()
// On error, we do not want to stop trying
if err := cw.loadCert(); err != nil {
cw.logger.Error(err)
}
}
}
}

func (cw *CertWatcher) loadCert() {
func (cw *CertWatcher) loadCert() error {
var err error
certFile, err := os.ReadFile(cw.certPath)
if err != nil {
cw.logger.Error("failed to load certificate file", zap.String("certPath", cw.certPath), zap.Error(err))
return
return fmt.Errorf("failed to load certificate file in %s: %w", cw.certPath, err)
}
keyFile, err := os.ReadFile(cw.keyPath)
if err != nil {
cw.logger.Error("failed to load key file", zap.String("keyPath", cw.keyPath), zap.Error(err))
return
return fmt.Errorf("failed to load key file in %s: %w", cw.keyPath, err)
}

certChecksum := sha256.Sum256(certFile)
Expand All @@ -114,8 +118,7 @@ func (cw *CertWatcher) loadCert() {
if certChecksum != cw.certChecksum || keyChecksum != cw.keyChecksum {
keyPair, err := tls.LoadX509KeyPair(cw.certPath, cw.keyPath)
if err != nil {
cw.logger.Error("failed to load and parse certificate", zap.Error(err))
return
return fmt.Errorf("failed to parse certificate: %w", err)
}

cw.mux.Lock()
Expand All @@ -127,4 +130,6 @@ func (cw *CertWatcher) loadCert() {

cw.logger.Info("Certificate and/or key have changed on disk and were reloaded.")
}

return nil
}
5 changes: 5 additions & 0 deletions pkg/queue/sharedmain/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,11 @@ func Main(opts ...Option) error {
logger.Errorw("Failed to shutdown server", zap.String("server", name), zap.Error(err))
}
}

if certWatcher != nil {
certWatcher.Stop()
}

logger.Info("Shutdown complete, exiting...")
}
return nil
Expand Down

0 comments on commit 99ae0c1

Please sign in to comment.