-
Notifications
You must be signed in to change notification settings - Fork 0
/
prometheus.go
146 lines (112 loc) · 3.25 KB
/
prometheus.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// Package prometheus provides suppoert for sending metrics to prometheus.
package prometheus
import (
"context"
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/dimfeld/httptreemux/v5"
"github.com/nhaancs/bhms/foundation/logger"
)
// Exporter implements the prometheus exporter support.
type Exporter struct {
log *logger.Logger
server http.Server
data map[string]any
mu sync.Mutex
}
// New constructs an Exporter for use.
func New(log *logger.Logger, host string, route string, readTimeout, writeTimeout time.Duration, idleTimeout time.Duration) *Exporter {
mux := httptreemux.NewContextMux()
exp := Exporter{
log: log,
server: http.Server{
Addr: host,
Handler: mux,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
IdleTimeout: idleTimeout,
ErrorLog: logger.NewStdLogger(log, logger.LevelError),
},
}
mux.Handle(http.MethodGet, route, exp.handler)
go func() {
ctx := context.Background()
log.Info(ctx, "prometheus", "status", "API listening", "host", host)
if err := exp.server.ListenAndServe(); err != nil {
log.Error(ctx, "prometheus", "msg", err)
}
}()
return &exp
}
// Publish stores a deep copy of the data for publishing.
func (exp *Exporter) Publish(data map[string]any) {
exp.mu.Lock()
defer exp.mu.Unlock()
exp.data = deepCopyMap(data)
}
// Stop turns off all the prometheus support.
func (exp *Exporter) Stop(shutdownTimeout time.Duration) {
ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
defer cancel()
exp.log.Info(ctx, "prometheus", "status", "start shutdown...")
defer exp.log.Info(ctx, "prometheus: Completed")
if err := exp.server.Shutdown(ctx); err != nil {
exp.log.Error(ctx, "prometheus", "status", "graceful shutdown did not complete", "msg", err, "shutdownTimeout", shutdownTimeout)
if err := exp.server.Close(); err != nil {
exp.log.Error(ctx, "prometheus", "status", "could not stop http server", "msg", err)
}
}
}
// =============================================================================
func (exp *Exporter) handler(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
w.Header().Set("Content-Type", "text/plain; version=0.0.4")
w.WriteHeader(http.StatusOK)
var data map[string]any
exp.mu.Lock()
{
data = deepCopyMap(exp.data)
}
exp.mu.Unlock()
out(w, "", data)
exp.log.Info(ctx, "prometheus", "metrics", fmt.Sprintf("expvar : (%d) : %s %s -> %s", http.StatusOK, r.Method, r.URL.Path, r.RemoteAddr))
}
// =============================================================================
func deepCopyMap(source map[string]any) map[string]any {
result := make(map[string]any)
for k, v := range source {
switch vm := v.(type) {
case map[string]any:
result[k] = deepCopyMap(vm)
case int64:
result[k] = float64(vm)
case float64:
result[k] = vm
case bool:
result[k] = 0.0
if vm {
result[k] = 1.0
}
}
}
return result
}
func out(w io.Writer, prefix string, data map[string]any) {
if prefix != "" {
prefix += "_"
}
for k, v := range data {
writeKey := fmt.Sprintf("%s%s", prefix, k)
switch vm := v.(type) {
case float64:
fmt.Fprintf(w, "%s %.f\n", writeKey, vm)
case map[string]any:
out(w, writeKey, vm)
default:
// Discard this value.
}
}
}