Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Add functionality to dynamically reload the VPA certs #3462

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions vertical-pod-autoscaler/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require (
github.com/prometheus/common v0.4.1
github.com/prometheus/procfs v0.0.5 // indirect
github.com/stretchr/testify v1.4.0
github.com/fsnotify/fsnotify v1.4.9
golang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d // indirect
golang.org/x/time v0.0.0-20191024005414-555d28b269f0
k8s.io/api v0.18.3
Expand Down
3 changes: 3 additions & 0 deletions vertical-pod-autoscaler/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ github.com/evanphx/json-patch v4.2.0+incompatible h1:fUDGZCv/7iAN7u0puUVhvKCcsR6
github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
Expand Down Expand Up @@ -203,6 +205,7 @@ golang.org/x/sys v0.0.0-20190209173611-3b5209105503/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190616124812-15dcb6c0061f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7 h1:HmbHVPwrPEKPGLAcHSrMe6+hqSUlvZU0rab6x5EXfGU=
golang.org/x/sys v0.0.0-20191022100944-742c48ecaeb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
Expand Down
90 changes: 84 additions & 6 deletions vertical-pod-autoscaler/pkg/admission-controller/certs.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,24 @@ limitations under the License.
package main

import (
"crypto/tls"
"io/ioutil"
"sync"

"github.com/fsnotify/fsnotify"
"k8s.io/klog"
)

// KeypairReloader structs holds cert path and certs
type KeypairReloader struct {
certMu sync.RWMutex
cert *tls.Certificate
caCert []byte
certPath string
keyPath string
caPath string
}

type certsContainer struct {
caCert, serverKey, serverCert []byte
}
Expand All @@ -41,10 +54,75 @@ func readFile(filePath string) []byte {
return res
}

func initCerts(config certsConfig) certsContainer {
res := certsContainer{}
res.caCert = readFile(*config.clientCaFile)
res.serverCert = readFile(*config.tlsCertFile)
res.serverKey = readFile(*config.tlsPrivateKey)
return res
// NewKeypairReloader will load certs on first run and trigger a goroutine for fsnotify watcher
func NewKeypairReloader(config certsConfig) (*KeypairReloader, error) {
result := &KeypairReloader{
certPath: *config.tlsCertFile,
keyPath: *config.tlsPrivateKey,
caCert: readFile(*config.clientCaFile),
}
cert, err := tls.LoadX509KeyPair(*config.tlsCertFile, *config.tlsPrivateKey)
if err != nil {
return nil, err
}
result.cert = &cert

// creates a new file watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}

defer func() {
if err != nil {
watcher.Close()
}
}()

if err := watcher.Add("/etc/tls-certs"); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You probably don't want this hardcoded. You should get the directories of both the cert and key and set watches on them.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1 I think you want those as flags passed in to the KeyPairReloader

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure, I will update it 👍

return nil, err
}

go func() {
for {
select {
// watch for events
case event := <-watcher.Events:
// fsnotify.create events will tell us if there are new certs
if event.Op&fsnotify.Create == fsnotify.Create {
klog.Info("Reloading certs")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add verbosity level to the log? And the log could be "New certificate found, reloading certs"

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure 👍

if err := result.reload(); err != nil {
klog.Infof("Could not load new certs: %v", err)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably be Warning

}
}

// watch for errors
case err := <-watcher.Errors:
klog.Infof("error: %v", err)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need more descriptive log here. Probably also warning or error level.
Is there any action to be taken on observing errors from the watcher?

}
}
}()

return result, nil
}

// reload loads updated cert and key whenever they are updated
func (kpr *KeypairReloader) reload() error {
newCert, err := tls.LoadX509KeyPair(kpr.certPath, kpr.keyPath)
if err != nil {
return err
}
kpr.certMu.Lock()
defer kpr.certMu.Unlock()
kpr.cert = &newCert
return nil
}

// GetCertificateFunc will return function which will be used as tls.Config.GetCertificate
func (kpr *KeypairReloader) GetCertificateFunc() func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
return func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since clientHello is unused, you can replace it with underscore

kpr.certMu.RLock()
defer kpr.certMu.RUnlock()
return kpr.cert, nil
}
}
11 changes: 0 additions & 11 deletions vertical-pod-autoscaler/pkg/admission-controller/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package main

import (
"context"
"crypto/tls"
"time"

admissionregistration "k8s.io/api/admissionregistration/v1"
Expand All @@ -45,16 +44,6 @@ func getClient() *kubernetes.Clientset {
return clientset
}

func configTLS(clientset *kubernetes.Clientset, serverCert, serverKey []byte) *tls.Config {
sCert, err := tls.X509KeyPair(serverCert, serverKey)
if err != nil {
klog.Fatal(err)
}
return &tls.Config{
Certificates: []tls.Certificate{sCert},
}
}

// register this webhook admission controller with the kube-apiserver
// by creating MutatingWebhookConfiguration.
func selfRegistration(clientset *kubernetes.Clientset, caCert []byte, namespace, serviceName, url string, registerByURL bool, timeoutSeconds int32) {
Expand Down
16 changes: 12 additions & 4 deletions vertical-pod-autoscaler/pkg/admission-controller/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package main

import (
"crypto/tls"
"flag"
"fmt"

Expand Down Expand Up @@ -78,7 +79,11 @@ func main() {
metrics.Initialize(*address, healthCheck)
metrics_admission.Register()

certs := initCerts(*certsConfiguration)
// load certs
kpr, err := NewKeypairReloader(*certsConfiguration)
if err != nil {
klog.Fatal(err)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

More info in the log needed, like "Failed to load certificate on startup: %v", err

}

config, err := rest.InClusterConfig()
if err != nil {
Expand Down Expand Up @@ -128,13 +133,16 @@ func main() {
})
clientset := getClient()
server := &http.Server{
Addr: fmt.Sprintf(":%d", *port),
TLSConfig: configTLS(clientset, certs.serverCert, certs.serverKey),
Addr: fmt.Sprintf(":%d", *port),
}
// this will check if there are new certs before every tls handshake
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, this will return up-to-date cert before every handshake, right?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, that's correct, I've updated the comment :)

t := &tls.Config{GetCertificate: kpr.GetCertificateFunc()}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

server.TLSConfig = &tls.Config{GetCertificate: kpr.GetCertificateFunc()}

you can also do it above:
server := &http.Server{
Addr: fmt.Sprintf(":%d", *port),
TLSConfig: &tls.Config{GetCertificate: kpr.GetCertificateFunc()},
}

One more thing is that the KeypairReloader could have a GetTLSConfig function and then we could simply have:

server := &http.Server{
Addr: fmt.Sprintf(":%d", *port),
TLSConfig: kpr.GetTLSConfig(),
}

server.TLSConfig = t

url := fmt.Sprintf("%v:%v", *webhookAddress, *webhookPort)
go func() {
if *registerWebhook {
selfRegistration(clientset, certs.caCert, namespace, *serviceName, url, *registerByURL, int32(*webhookTimeout))
selfRegistration(clientset, kpr.caCert, namespace, *serviceName, url, *registerByURL, int32(*webhookTimeout))
}
// Start status updates after the webhook is initialized.
statusUpdater.Run(stopCh)
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading