-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
245 lines (203 loc) · 6.76 KB
/
main.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package main
import (
"compress/gzip"
"flag"
"fmt"
"io"
"log"
"log/slog"
"net/http"
"os"
"strings"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type Metrics struct {
PolicyRequestsTotal prometheus.Counter
ReportRequestsTotal prometheus.Counter
ReportErrorsTotal *prometheus.CounterVec
SuccessfulSessionsTotal *prometheus.CounterVec
FailureSessionsTotal *prometheus.CounterVec
}
func createMetrics() Metrics {
namespace := "mta_sts"
return Metrics{
PolicyRequestsTotal: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "policy_requests_total",
Help: "Total number of policy requests.",
}),
ReportRequestsTotal: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace,
Name: "report_requests_total",
Help: "Total number of report requests.",
}),
ReportErrorsTotal: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace,
Name: "report_errors_total",
Help: "Total number of report errors.",
}, []string{"cause"}),
SuccessfulSessionsTotal: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace,
Name: "successful_sessions_total",
Help: "Total number of successful sessions.",
}, []string{"organization"}),
FailureSessionsTotal: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace,
Name: "failure_sessions_total",
Help: "Total number of failure sessions.",
}, []string{"organization"}),
}
}
func createRegistry(config Config, metrics Metrics) *prometheus.Registry {
registry := prometheus.NewRegistry()
registry.MustRegister(
metrics.PolicyRequestsTotal,
metrics.ReportRequestsTotal,
metrics.ReportErrorsTotal,
metrics.SuccessfulSessionsTotal,
metrics.FailureSessionsTotal)
if config.Metrics.Collectors.Go {
registry.MustRegister(
collectors.NewGoCollector(),
)
}
if config.Metrics.Collectors.Process {
registry.MustRegister(
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
}
return registry
}
func healthCheck(config Config) int {
res, err := http.Get(fmt.Sprintf("http://localhost:%d/healthz", config.Port))
if err != nil || res.StatusCode != http.StatusOK {
slog.Error("Healthcheck failed", "error", err, "statusCode", res.StatusCode)
return 1
}
return 0
}
func policyResponse(policy Policy) string {
var sb strings.Builder
sb.WriteString(fmt.Sprintf("version: %s\n", policy.Version))
sb.WriteString(fmt.Sprintf("mode: %s\n", policy.Mode))
for _, mx := range policy.Mx {
sb.WriteString(fmt.Sprintf("mx: %s\n", mx))
}
sb.WriteString(fmt.Sprintf("max_age: %d\n", policy.MaxAge))
return sb.String()
}
func handlePolicy(config Config, metrics Metrics) http.HandlerFunc {
response := policyResponse(config.Policy)
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
metrics.PolicyRequestsTotal.Inc()
fmt.Fprint(w, response)
}
}
func handleReport(config Config, metrics Metrics) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
metrics.ReportRequestsTotal.Inc()
bodyReader := io.LimitReader(r.Body, config.Reports.Max.Body)
defer r.Body.Close()
gzipReader, err := gzip.NewReader(bodyReader)
if err != nil {
slog.Warn("Gzip error", "remote", r.RemoteAddr, "error", err)
metrics.ReportErrorsTotal.With(prometheus.Labels{"cause": "gzip"}).Inc()
w.WriteHeader(http.StatusBadRequest)
return
}
defer gzipReader.Close()
jsonReader := io.LimitReader(gzipReader, config.Reports.Max.Json)
if config.Reports.Save.Enabled {
saveReader, file, err := saveReport(config, jsonReader)
if err != nil {
slog.Warn("Save failed")
metrics.ReportErrorsTotal.With(prometheus.Labels{"cause": "save"}).Inc()
} else {
defer file.Close()
jsonReader = saveReader
}
}
report, err := parseReport(jsonReader)
if err != nil {
if err == io.ErrUnexpectedEOF {
slog.Warn("Request too large", "remote", r.RemoteAddr)
metrics.ReportErrorsTotal.With(prometheus.Labels{"cause": "request_too_large"}).Inc()
w.WriteHeader(http.StatusRequestEntityTooLarge)
return
}
slog.Warn("Report error", "remote", r.RemoteAddr, "error", err)
metrics.ReportErrorsTotal.With(prometheus.Labels{"cause": "parse"}).Inc()
w.WriteHeader(http.StatusBadRequest)
return
}
for _, policy := range report.Policies {
if policy.Summary.TotalSuccessfulSessionCount > 0 {
labels := prometheus.Labels{"organization": report.OrganizationName}
value := float64(policy.Summary.TotalSuccessfulSessionCount)
metrics.SuccessfulSessionsTotal.With(labels).Add(value)
}
if policy.Summary.TotalFailureSessionCount > 0 {
labels := prometheus.Labels{"organization": report.OrganizationName}
value := float64(policy.Summary.TotalFailureSessionCount)
metrics.FailureSessionsTotal.With(labels).Add(value)
}
if len(policy.FailureDetails) > 0 {
slog.Warn("Policy contains failure details", "details", policy.FailureDetails)
}
}
}
}
func start(config Config) {
slog.Info("Config", "config", config)
metrics := createMetrics()
registry := createRegistry(config, metrics)
var handlerOpts promhttp.HandlerOpts
if config.Metrics.Collectors.Exporter {
handlerOpts = promhttp.HandlerOpts{Registry: registry}
} else {
handlerOpts = promhttp.HandlerOpts{}
}
metricsHandler := promhttp.HandlerFor(registry, handlerOpts)
metricsHttp := http.NewServeMux()
metricsHttp.Handle(config.Metrics.Path, metricsHandler)
http.HandleFunc("/healthz", func(http.ResponseWriter, *http.Request) {})
if config.Metrics.Enabled {
go func() {
slog.Info("Serving metrics", "port", config.Metrics.Port, "path", config.Metrics.Path)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.Metrics.Port), metricsHttp))
}()
}
if config.Reports.Enabled {
slog.Info("Listening for reports", "port", config.Port, "path", config.Reports.Path)
http.HandleFunc(config.Reports.Path, handleReport(config, metrics))
}
if config.Policy.Enabled {
slog.Info("Serving policy", "port", config.Port, "path", config.Policy.Path)
http.HandleFunc(config.Policy.Path, handlePolicy(config, metrics))
}
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", config.Port), nil))
}
func main() {
config := createConfig()
if config.Log.Json {
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
slog.SetDefault(logger)
}
healthCheckFlag := flag.Bool("health", false, "run health check")
flag.Parse()
if *healthCheckFlag {
os.Exit(healthCheck(config))
} else {
start(config)
}
}