forked from tomcz/openldap_exporter
-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.go
105 lines (95 loc) · 2.26 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package openldap_exporter
import (
"context"
"errors"
"fmt"
"net/http"
"time"
kitlog "github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/exporter-toolkit/web"
log "github.com/sirupsen/logrus"
)
var commit string
var tag string
func GetVersion() string {
return fmt.Sprintf("%s (%s)", tag, commit)
}
type Server struct {
server *http.Server
logger log.FieldLogger
cfgPath string
}
func NewMetricsServer(bindAddr, metricsPath, tlsConfigPath string) *Server {
mux := http.NewServeMux()
mux.Handle(metricsPath, promhttp.Handler())
mux.HandleFunc("/version", showVersion)
return &Server{
server: &http.Server{Addr: bindAddr, Handler: mux},
logger: log.WithField("component", "server"),
cfgPath: tlsConfigPath,
}
}
func showVersion(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
fmt.Fprintln(w, GetVersion())
}
func (s *Server) Start() error {
s.logger.WithField("addr", s.server.Addr).Info("starting http listener")
serverAddress := []string{s.server.Addr}
useSystemdSocket := false
var flags web.FlagConfig = web.FlagConfig{
WebListenAddresses: &serverAddress,
WebSystemdSocket: &useSystemdSocket,
WebConfigFile: &s.cfgPath,
}
err := web.ListenAndServe(s.server, &flags, kitlog.LoggerFunc(s.adaptor))
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
}
func (s *Server) Stop() {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
s.server.Shutdown(ctx)
cancel()
}
func (s *Server) adaptor(kvs ...interface{}) error {
if len(kvs) == 0 {
return nil
}
if len(kvs)%2 != 0 {
kvs = append(kvs, nil)
}
fields := log.Fields{}
for i := 0; i < len(kvs); i += 2 {
key := fmt.Sprint(kvs[i])
fields[key] = kvs[i+1]
}
var msg string
if val, ok := fields["msg"]; ok {
delete(fields, "msg")
msg = fmt.Sprint(val)
}
var level string
if val, ok := fields["level"]; ok {
delete(fields, "level")
level = fmt.Sprint(val)
}
ll := s.logger.WithFields(fields)
switch level {
case "error":
ll.Error(msg)
case "warn":
ll.Warn(msg)
case "debug":
ll.Debug(msg)
default:
ll.Info(msg)
}
return nil
}