Skip to content

Commit

Permalink
controller refresh certificate
Browse files Browse the repository at this point in the history
  • Loading branch information
ashutosji committed Nov 15, 2023
1 parent 25e0c4a commit 84a072f
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions cmd/controller/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package main

import (
"context"
"crypto/tls"
"io"
"net/http"
"os"
Expand All @@ -35,6 +36,7 @@ import (
"agones.dev/agones/pkg/gameserversets"
"agones.dev/agones/pkg/metrics"
"agones.dev/agones/pkg/util/apiserver"
"agones.dev/agones/pkg/util/fswatch"
"agones.dev/agones/pkg/util/https"
"agones.dev/agones/pkg/util/runtime"
"agones.dev/agones/pkg/util/signals"
Expand All @@ -58,6 +60,10 @@ import (
"k8s.io/client-go/tools/leaderelection/resourcelock"
)

const (
certDir = "/certs/"
)

const (
enableStackdriverMetricsFlag = "stackdriver-exporter"
stackdriverLabels = "stackdriver-labels"
Expand Down Expand Up @@ -167,6 +173,7 @@ func main() {
}
// https server and the items that share the Mux for routing
httpsServer := https.NewServer(ctlConf.CertFile, ctlConf.KeyFile)
watchCertsDirectory(httpsServer, logger)
wh := webhooks.NewWebHook(httpsServer.Mux)
api := apiserver.NewAPIServer(httpsServer.Mux)

Expand Down Expand Up @@ -262,6 +269,48 @@ func main() {
})
}

func watchCertsDirectory(httpsServer *https.Server, logger *logrus.Entry) {
cancel, err := fswatch.Watch(logger, certDir, time.Second*5, func() {
logger.Info("Certificate files changed. Reloading...")

newCert, err := readCertFile()
if err != nil {
logger.WithError(err).Error("Failed to reload certificates")
return
}

// Create a new http.Server with the updated TLS configuration
newHTTPServer := &http.Server{
Addr: ":8081",
Handler: httpsServer.Mux,
}
newHTTPServer.TLSConfig = &tls.Config{
Certificates: []tls.Certificate{*newCert},
}

// Update the TLS configuration
go func() {
if err := newHTTPServer.ListenAndServeTLS("", ""); err != nil {
logger.WithError(err).Error("Failed to update TLS configuration")
}
}()
logger.Info("Certificates reloaded.")
})
defer cancel()

if err != nil {
logger.WithError(err).Error("Failed to set up certificate watch")
}
}

func readCertFile() (*tls.Certificate, error) {
tlsCert, err := tls.LoadX509KeyPair(certDir+"tls.crt", certDir+"tls.key")
if err != nil {
return nil, err
}
return &tlsCert, nil
}

func parseEnvFlags() config {
exec, err := os.Executable()
if err != nil {
Expand Down

0 comments on commit 84a072f

Please sign in to comment.