-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
413 lines (385 loc) · 11.3 KB
/
app.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package prepalert
import (
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"strconv"
"sync"
"github.com/hashicorp/hcl/v2"
"github.com/kayac/go-katsubushi"
"github.com/mackerelio/mackerel-client-go"
"github.com/mashiike/canyon"
"github.com/mashiike/hclutil"
"github.com/mashiike/prepalert/provider"
"github.com/mashiike/slogutils"
)
type App struct {
mkrSvc *MackerelService
backend Backend
rules []*Rule
queueName string
webhookClientID string
webhookClientSecret string
providerParameters provider.ProviderParameters
providers map[string]provider.Provider
queries map[string]provider.Query
diagWriter *hclutil.DiagnosticsWriter
evalCtx *hcl.EvalContext
loadingConfig bool
workerPrepared bool
webhookServerPrepared bool
cleanupFuncs []func() error
retryPolicy *RetryPolicy `hcl:"retry_policy,block"`
}
func New(apikey string) *App {
app := &App{
backend: NewDiscardBackend(),
}
return app.SetMackerelClient(mackerel.NewClient(apikey))
}
func (app *App) Close() error {
var errs []error
if c, ok := app.backend.(io.Closer); ok {
if err := c.Close(); err != nil {
errs = append(errs, err)
}
}
for _, provider := range app.providers {
if c, ok := provider.(io.Closer); ok {
if err := c.Close(); err != nil {
errs = append(errs, err)
}
}
}
for _, query := range app.queries {
if c, ok := query.(io.Closer); ok {
if err := c.Close(); err != nil {
errs = append(errs, err)
}
}
}
for _, cleanup := range app.cleanupFuncs {
if err := cleanup(); err != nil {
errs = append(errs, err)
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
func (app *App) WorkerIsReady() bool {
return app.workerPrepared
}
func (app *App) WebhookServerIsReady() bool {
return app.webhookServerPrepared
}
func (app *App) EnableWebhookServer() bool {
return app.SQSQueueName() != ""
}
func (app *App) SetMackerelClient(client MackerelClient) *App {
app.mkrSvc = NewMackerelService(client)
return app
}
func (app *App) SQSQueueName() string {
return app.queueName
}
func (app *App) MackerelService() *MackerelService {
return app.mkrSvc
}
func (app *App) Rules() []*Rule {
return app.rules
}
func (app *App) Backend() Backend {
return app.backend
}
func (app *App) RetryPolicy() *RetryPolicy {
return app.retryPolicy
}
func (app *App) ProviderList() []string {
providers := make([]string, 0, len(app.providers))
for name := range app.providers {
providers = append(providers, name)
}
return providers
}
func (app *App) QueryList() []string {
queries := make([]string, 0, len(app.queries))
for name := range app.queries {
queries = append(queries, name)
}
return queries
}
func must[T any](t T, err error) T {
if err != nil {
panic(err)
}
return t
}
type RequestIDGenerator interface {
NextID() (uint64, error)
}
const (
HeaderRequestID = "Prepalert-Request-ID"
)
var DefaultRequestIDGeneartor RequestIDGenerator = must(katsubushi.NewGenerator(1))
func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
ctx := r.Context()
ctx = slogutils.With(
ctx,
"x_amzn_trace_id", r.Header.Get("X-Amzn-Trace-Id"),
"x_amz_cf_id", r.Header.Get("X-Amz-Cf-Id"),
)
if canyon.IsWorker(r) {
if reqIDstr := r.Header.Get(HeaderRequestID); reqIDstr != "" {
reqID, err := strconv.ParseUint(reqIDstr, 10, 64)
if err != nil {
canyon.Logger(r).WarnContext(
ctx,
"can not parse request id",
"status", http.StatusBadRequest,
"method", r.Method,
"path", r.URL.Path,
)
} else {
ctx = slogutils.With(ctx, "request_id", reqID)
}
}
app.serveHTTPAsWorker(w, r.WithContext(ctx))
return
}
reqID, err := DefaultRequestIDGeneartor.NextID()
if err != nil {
canyon.Logger(r).ErrorContext(
ctx,
"can not generate request id",
"status", http.StatusInternalServerError,
"method", r.Method,
"path", r.URL.Path,
)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
w.Header().Set(HeaderRequestID, fmt.Sprintf("%d", reqID))
r.Header.Set(HeaderRequestID, fmt.Sprintf("%d", reqID)) // set for worker
ctx = slogutils.With(ctx, "request_id", reqID)
app.serveHTTPAsWebhookServer(w, r.WithContext(ctx))
}
func (app *App) serveHTTPAsWebhookServer(w http.ResponseWriter, r *http.Request) {
logger := canyon.Logger(r)
ctx := r.Context()
logger.InfoContext(ctx, "accept Webhook Server HTTP request", "method", r.Method, "path", r.URL.Path)
if r.Method == http.MethodGet {
app.backend.ServeHTTP(w, r)
return
}
if app.EnableBasicAuth() && !app.CheckBasicAuth(r) {
logger.InfoContext(ctx, "basic auth failed, request BasicAuth challenge", "status", http.StatusUnauthorized)
w.Header().Add("WWW-Authenticate", `Basic realm="SECRET AREA"`)
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return
}
if r.Method != http.MethodPost {
logger.InfoContext(ctx, "method not allowed", "status", http.StatusMethodNotAllowed)
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
messageId, err := canyon.SendToWorker(r, nil)
if err != nil {
logger.InfoContext(ctx, "can not send to worker", "status", http.StatusInternalServerError, "error", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
logger.InfoContext(ctx, "send to worker", "status", http.StatusOK, "sqs_message_id", messageId)
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, http.StatusText(http.StatusOK))
}
func (app *App) serveHTTPAsWorker(w http.ResponseWriter, r *http.Request) {
logger := canyon.Logger(r)
ctx := r.Context()
logger.InfoContext(
ctx, "accept Worker request",
"method", r.Method,
"path", r.URL.Path,
"sqs_message_id", r.Header.Get(canyon.HeaderSQSMessageID),
)
decoder := json.NewDecoder(r.Body)
var body WebhookBody
if err := decoder.Decode(&body); err != nil {
logger.ErrorContext(ctx, "can not parse request body as Mackerel webhook body", "error", err.Error())
app.retryPolicy.SetRetryAfter(w, r)
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
if body.Alert == nil {
logger.WarnContext(ctx, "not found alert in request body, maybe not webhook request", "text", body.Text, "org_name", body.OrgName, "event", body.Event)
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, http.StatusText(http.StatusOK))
return
}
ctx = slogutils.With(
ctx,
"alert_id", body.Alert.ID,
"alsert_status", body.Alert.Status,
"monitor", body.Alert.MonitorName,
)
logger.InfoContext(ctx, "parse request body as Mackerel webhook body")
if err := app.ExecuteRules(ctx, &body); err != nil {
logger.ErrorContext(ctx, "failed process Mackerel webhook body", "error", err.Error())
app.retryPolicy.SetRetryAfter(w, r)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
logger.InfoContext(ctx, "finish process Mackerel webhook body")
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, http.StatusText(http.StatusOK))
}
func (app *App) ExecuteRules(ctx context.Context, body *WebhookBody) error {
slog.InfoContext(ctx, "start process rules")
matchCount := 0
evalCtx, err := app.NewEvalContext(body)
if err != nil {
return fmt.Errorf("failed build eval context: %w", err)
}
matchedRules := make([]*Rule, 0, len(app.rules))
dependsOnQueries := make(map[string]struct{})
for _, rule := range app.rules {
if !rule.Match(evalCtx) {
continue
}
slog.InfoContext(ctx, "match rule", "rule", rule.Name())
matchCount++
matchedRules = append(matchedRules, rule)
for _, queryFQN := range rule.DependsOnQueries() {
dependsOnQueries[queryFQN] = struct{}{}
}
}
u := app.mkrSvc.NewMackerelUpdater(body, app.Backend())
executeRule := func() error {
var errs []error
for _, rule := range matchedRules {
ctxWithRule := slogutils.With(ctx, "rule_name", rule.Name())
if err := rule.Execute(ctxWithRule, evalCtx, u); err != nil {
slog.ErrorContext(ctxWithRule, "failed execute rule", "error", err.Error())
errs = append(errs, fmt.Errorf(
"%s: %w",
rule.Name(),
app.UnwrapAndDumpDiagnoctics(err),
))
}
}
if len(errs) > 0 {
return errors.Join(errs...)
}
if err := u.Flush(ctx, evalCtx); err != nil {
return fmt.Errorf("failed flush to mackerel: %w", err)
}
return nil
}
var mu sync.Mutex
var wg sync.WaitGroup
var errs []error
for queryFQN := range dependsOnQueries {
query, ok := app.queries[queryFQN]
if !ok {
errs = append(errs, fmt.Errorf("not found query %q", queryFQN))
continue
}
mu.Lock()
evalCtxQueryVariables := &provider.EvalContextQueryVariables{
FQN: queryFQN,
Status: "running",
}
var err error
evalCtx, err = provider.WithQury(evalCtx, evalCtxQueryVariables)
mu.Unlock()
if err != nil {
errs = append(errs, fmt.Errorf("failed set query status %q", queryFQN))
continue
}
wg.Add(1)
go func(v *provider.EvalContextQueryVariables, query provider.Query) {
defer func() {
wg.Done()
}()
egctxWithQueryName := slogutils.With(
ctx,
"query", v.FQN,
)
slog.InfoContext(egctxWithQueryName, "start run query")
result, err := query.Run(egctxWithQueryName, evalCtx)
mu.Lock()
defer mu.Unlock()
if err != nil {
var diags hcl.Diagnostics
slog.DebugContext(
egctxWithQueryName,
"failed run query",
"error", err.Error(),
"errType", fmt.Sprintf("%T", err),
)
if errors.As(err, &diags) {
app.diagWriter.WriteDiagnostics(diags)
}
errs = append(errs, err)
slog.WarnContext(egctxWithQueryName, "failed run query", "reason", err.Error())
v.Status = "failed"
v.Error = err.Error()
evalCtx, err = provider.WithQury(evalCtx, v)
if err != nil {
errs = append(errs, fmt.Errorf("failed set query status %q: %w", v.FQN, err))
}
return
}
v.Status = "success"
v.Result = result
evalCtx, err = provider.WithQury(evalCtx, v)
if err != nil {
slog.ErrorContext(egctxWithQueryName, "failed marshal query result", "error", err.Error())
err = app.UnwrapAndDumpDiagnoctics(err)
errs = append(errs, fmt.Errorf("failed set query status %q: %w", v.FQN, err))
}
if err := executeRule(); err != nil {
errs = append(errs, err)
return
}
slog.InfoContext(egctxWithQueryName, "end run query")
}(evalCtxQueryVariables, query)
}
wg.Wait()
if len(errs) > 0 {
return fmt.Errorf("failed process Mackerel webhook body: %w", errors.Join(errs...))
}
if len(dependsOnQueries) > 0 {
return nil
}
if err := executeRule(); err != nil {
return fmt.Errorf("failed process Mackerel webhook body: %w", err)
}
slog.InfoContext(ctx, "finish process rules", "matched_rule_count", matchCount)
return nil
}
func (app *App) EnableBasicAuth() bool {
return app.webhookClientID != "" && app.webhookClientSecret != ""
}
func (app *App) CheckBasicAuth(r *http.Request) bool {
clientID, clientSecret, ok := r.BasicAuth()
if !ok {
return false
}
return clientID == app.webhookClientID && clientSecret == app.webhookClientSecret
}
func (app *App) UnwrapAndDumpDiagnoctics(err error) error {
var diags hcl.Diagnostics
if errors.As(err, &diags) {
app.diagWriter.WriteDiagnostics(diags)
return err
}
return err
}