fix(metrics): release listener on TLS startup failure (#8527)

This commit is contained in:
Paco Cartones
2026-09-14 02:57:30 +02:00
committed by GitHub
parent 5bd1701376
commit 22351a0d3c
2 changed files with 78 additions and 11 deletions

View File

@@ -40,15 +40,17 @@ type Metrics struct {
plugins map[string]struct{} // all available plugins, used to determine which plugin made the client write
tlsConfigPath string
serveTLS func(net.Listener, *http.Server, *web.FlagConfig, *slog.Logger) error
}
// New returns a new instance of Metrics with the given address.
func New(addr string) *Metrics {
met := &Metrics{
Addr: addr,
Reg: prometheus.DefaultRegisterer.(*prometheus.Registry),
zoneMap: make(map[string]struct{}),
plugins: pluginList(caddy.ListPlugins()),
Addr: addr,
Reg: prometheus.DefaultRegisterer.(*prometheus.Registry),
zoneMap: make(map[string]struct{}),
plugins: pluginList(caddy.ListPlugins()),
serveTLS: web.Serve,
}
return met
@@ -117,6 +119,13 @@ func (sl *startupListener) Ready() <-chan struct{} {
// OnStartup sets up the metrics on startup.
func (m *Metrics) OnStartup() error {
if m.tlsConfigPath != "" {
if err := web.Validate(m.tlsConfigPath); err != nil {
log.Errorf("Invalid TLS config: %s", err)
return err
}
}
ln, err := reuseport.Listen("tcp", m.Addr)
if err != nil {
log.Errorf("Failed to start metrics handler: %s", err)
@@ -151,12 +160,6 @@ func (m *Metrics) OnStartup() error {
return nil
}
// Check TLS config file existence
if _, err := os.Stat(m.tlsConfigPath); os.IsNotExist(err) {
log.Errorf("TLS config file does not exist: %s", m.tlsConfigPath)
return err
}
// Create web config for ListenAndServe
webConfig := &web.FlagConfig{
WebListenAddresses: &[]string{m.Addr},
@@ -173,7 +176,7 @@ func (m *Metrics) OnStartup() error {
// web.Serve() never returns nil, it always returns a non-nil error and
// it doesn't retun anything if server starts successfully.
// startupListener handles capturing succesful startup.
err := web.Serve(m.ln, server, webConfig, logger)
err := m.serveTLS(m.ln, server, webConfig, logger)
if err != nil && err != http.ErrServerClosed {
log.Errorf("Failed to start HTTPS metrics server: %v", err)
startUpErr <- err
@@ -183,6 +186,10 @@ func (m *Metrics) OnStartup() error {
// Wait for startup errors
select {
case err := <-startUpErr:
if closeErr := ln.Close(); closeErr != nil {
log.Errorf("Failed to close metrics listener after startup error: %s", closeErr)
}
m.lnSetup = false
return err
case <-startupListener.Ready():
log.Infof("Server is ready and accepting connections")