Skip to content

Commit 5ebe291

Browse files
committed
Use TLS for the prometheus http server
The HTTP server used to export metrics with prometheus is now using TLS thanks to the spire SDK. Signed-off-by: Lionel Jouin <[email protected]>
1 parent 92ab2ad commit 5ebe291

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

main.go

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ import (
3131
"github.com/kelseyhightower/envconfig"
3232
"github.com/prometheus/client_golang/prometheus/promhttp"
3333
"github.com/sirupsen/logrus"
34+
"github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig"
35+
"github.com/spiffe/go-spiffe/v2/workloadapi"
3436
"go.opentelemetry.io/otel/sdk/metric"
3537
"go.opentelemetry.io/otel/sdk/trace"
3638

@@ -124,12 +126,27 @@ func main() {
124126
}
125127

126128
// https://github.com/open-telemetry/opentelemetry-go/blob/v1.17.0/example/prometheus/main.go
129+
// https://github.com/spiffe/go-spiffe/blob/v1.1.0/v2/examples/spiffe-http/server/main.go
127130
func serveMetrics(ctx context.Context, port int) {
128131
log.FromContext(ctx).Infof(fmt.Sprintf("serving metrics at localhost:%d/metrics", port))
129-
http.Handle("/metrics", promhttp.Handler())
130-
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
132+
133+
source, err := workloadapi.NewX509Source(ctx, workloadapi.WithClientOptions())
131134
if err != nil {
132-
fmt.Printf("error serving http: %v", err)
135+
log.FromContext(ctx).Errorf("Unable to create X509Source: %v", err)
136+
return
137+
}
138+
defer source.Close()
139+
140+
tlsConfig := tlsconfig.TLSServerConfig(source)
141+
server := &http.Server{
142+
Addr: fmt.Sprintf(":%d", port),
143+
TLSConfig: tlsConfig,
144+
}
145+
146+
http.Handle("/metrics", promhttp.Handler())
147+
148+
if err := server.ListenAndServeTLS("", ""); err != nil {
149+
log.FromContext(ctx).Errorf("error serving http: %v", err)
133150
return
134151
}
135152
}

0 commit comments

Comments
 (0)