-
Notifications
You must be signed in to change notification settings - Fork 165
/
certificateRefresher.go
101 lines (84 loc) · 2.3 KB
/
certificateRefresher.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package env
// Copyright (c) Microsoft Corporation.
// Licensed under the Apache License 2.0.
import (
"context"
"crypto/rsa"
"crypto/x509"
"sync"
"time"
"github.com/sirupsen/logrus"
"github.com/Azure/ARO-RP/pkg/util/keyvault"
)
type CertificateRefresher interface {
Start(context.Context) error
GetCertificates() (*rsa.PrivateKey, []*x509.Certificate)
}
type refreshingCertificate struct {
lock sync.RWMutex
certs []*x509.Certificate
key *rsa.PrivateKey
logger *logrus.Entry
kv keyvault.Manager
certName string
newTicker func() (tick <-chan time.Time, stop func())
}
func newCertificateRefresher(logger *logrus.Entry, interval time.Duration, kv keyvault.Manager, certificateName string) CertificateRefresher {
return &refreshingCertificate{
logger: logger,
kv: kv,
certName: certificateName,
newTicker: func() (tick <-chan time.Time, stop func()) {
ticker := time.NewTicker(interval)
return ticker.C, func() { ticker.Stop() }
},
}
}
func (r *refreshingCertificate) Start(ctx context.Context) error {
// initial pull to get the certificate start
err := r.fetchCertificateOnce(ctx)
if err != nil {
return err
}
r.fetchCertificate(ctx)
return nil
}
// GetCertificates loads the certificate from the synced store safe to use concurently
func (r *refreshingCertificate) GetCertificates() (*rsa.PrivateKey, []*x509.Certificate) {
r.lock.RLock()
defer r.lock.RUnlock()
return r.key, r.certs
}
// fetchCertificateOnce access keyvault via preset getter and download new set
// of certificates.
// in case of failure error is returned and old certificate is left in the
// synced store
func (r *refreshingCertificate) fetchCertificateOnce(ctx context.Context) error {
key, certs, err := r.kv.GetCertificateSecret(ctx, r.certName)
if err != nil {
return err
}
r.lock.Lock()
defer r.lock.Unlock()
r.key = key
r.certs = certs
return nil
}
// fetchCertificate starts goroutine to poll certificates
func (r *refreshingCertificate) fetchCertificate(ctx context.Context) {
tick, stop := r.newTicker()
go func() {
defer stop()
for {
select {
case <-ctx.Done():
return
case <-tick:
err := r.fetchCertificateOnce(ctx)
if err != nil {
r.logger.Errorf("cannot pull certificate leaving old one, %s", err.Error())
}
}
}
}()
}