This repository has been archived by the owner on Jun 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cert_reloader.go
80 lines (70 loc) · 1.68 KB
/
cert_reloader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"context"
"crypto/tls"
"log"
"os"
"os/signal"
"sync"
"syscall"
)
type CertReloader struct {
mutex *sync.RWMutex
cert *tls.Certificate
certFile string
keyFile string
}
func NewCertReloader(
ctx context.Context,
certFile string, keyFile string,
reloadSignals ...os.Signal,
) (reloader *CertReloader, err error) {
reloader = &CertReloader{
certFile: certFile,
keyFile: keyFile,
}
if err = reloader.tryReload(); err != nil {
return
}
go reloader.listenReloadSignal(ctx, reloadSignals...)
return
}
type GetCertificateFunc func(*tls.ClientHelloInfo) (*tls.Certificate, error)
func (reloader *CertReloader) CreateGetCertificateFunc() GetCertificateFunc {
return func(*tls.ClientHelloInfo) (cert *tls.Certificate, err error) {
reloader.mutex.RLock()
defer reloader.mutex.RUnlock()
cert = reloader.cert
return
}
}
func (reloader *CertReloader) tryReload() (err error) {
var cert tls.Certificate
cert, err = tls.LoadX509KeyPair(reloader.certFile, reloader.keyFile)
if err != nil {
return
}
reloader.mutex.Lock()
defer reloader.mutex.Unlock()
reloader.cert = &cert
return
}
func (reloader *CertReloader) listenReloadSignal(ctx context.Context, reloadSignals ...os.Signal) {
c := make(chan os.Signal, 1)
if len(reloadSignals) == 0 {
reloadSignals = []os.Signal{syscall.SIGUSR1}
}
signal.Notify(c, reloadSignals...)
for {
select {
case <-ctx.Done():
return
case sig := <-c:
log.Printf("Signal Received: '%v', try to reload TLS certificate and key from '%s' and '%s'",
sig, reloader.certFile, reloader.keyFile)
if err := reloader.tryReload(); err != nil {
log.Printf("reload error, ignore: err = %v", err)
}
}
}
}