do not panic if metrics initialization fails

This commit is contained in:
aler9 2020-08-30 13:44:15 +02:00
parent e27e807813
commit 833ce34838
2 changed files with 22 additions and 11 deletions

View File

@ -210,7 +210,7 @@ func newProgram(args []string, stdin io.Reader) (*program, error) {
if _, ok := p.conf.logDestinationsParsed[logDestinationFile]; ok {
p.logFile, err = os.OpenFile(p.conf.LogFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal("ERR:", err)
return nil, err
}
}
@ -231,7 +231,10 @@ func newProgram(args []string, stdin io.Reader) (*program, error) {
}
if conf.Metrics {
p.metrics = newMetrics(p)
p.metrics, err = newMetrics(p)
if err != nil {
return nil, err
}
}
if conf.Pprof {

View File

@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"net"
"net/http"
"time"
)
@ -19,25 +20,32 @@ type metricsData struct {
}
type metrics struct {
p *program
mux *http.ServeMux
server *http.Server
p *program
mux *http.ServeMux
server *http.Server
listener net.Listener
}
func newMetrics(p *program) *metrics {
func newMetrics(p *program) (*metrics, error) {
listener, err := net.Listen("tcp", metricsAddress)
if err != nil {
return nil, err
}
m := &metrics{
p: p,
p: p,
listener: listener,
}
m.mux = http.NewServeMux()
m.mux.HandleFunc("/metrics", m.onMetrics)
m.server = &http.Server{
Addr: metricsAddress,
Handler: m.mux,
}
m.log("opened on " + metricsAddress)
return m
m.log("opened on " + metricsAddress)
return m, nil
}
func (m *metrics) log(format string, args ...interface{}) {
@ -45,7 +53,7 @@ func (m *metrics) log(format string, args ...interface{}) {
}
func (m *metrics) run() {
err := m.server.ListenAndServe()
err := m.server.Serve(m.listener)
if err != http.ErrServerClosed {
panic(err)
}