File size: 1,896 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package metricsmanager

import (
	"context"
	"database/sql"

	"github.com/target/goalert/engine/processinglock"
	"github.com/target/goalert/util"
)

const engineVersion = 3

// DB handles updating metrics
type DB struct {
	db   *sql.DB
	lock *processinglock.Lock

	boundNow *sql.Stmt

	scanLogs      *sql.Stmt
	insertMetrics *sql.Stmt
}

// Name returns the name of the module.
func (db *DB) Name() string { return "Engine.MetricsManager" }

// NewDB creates a new DB.
func NewDB(ctx context.Context, db *sql.DB) (*DB, error) {
	lock, err := processinglock.NewLock(ctx, db, processinglock.Config{
		Version: engineVersion,
		Type:    processinglock.TypeMetrics,
	})
	if err != nil {
		return nil, err
	}

	p := &util.Prepare{Ctx: ctx, DB: db}

	return &DB{
		db:   db,
		lock: lock,

		// NOTE: this buffer provides time for in-flight requests to settle
		boundNow: p.P(`select now() - '2 minutes'::interval`),

		scanLogs: p.P(`
			select alert_id, timestamp, id 
			from alert_logs 
			where event='closed' and timestamp < $3 and (timestamp > $1 or (timestamp = $1 and id > $2)) 
			order by timestamp, id 
			limit 500`),

		insertMetrics: p.P(`
			insert into alert_metrics (alert_id, service_id, time_to_ack, time_to_close, escalated, closed_at)
			select
				a.id,
				a.service_id,
				(select timestamp - a.created_at from alert_logs where alert_id = a.id and event = 'acknowledged' order by timestamp limit 1),
				(select timestamp - a.created_at from alert_logs where alert_id = a.id and event = 'closed'       order by timestamp limit 1),
				(select count(*) > 1             from alert_logs where alert_id = a.id and event = 'escalated'),
				(select timestamp                from alert_logs where alert_id = a.id and event = 'closed'       order by timestamp limit 1)
			from alerts a
			where a.id = any($1) and a.service_id is not null
			on conflict do nothing
		`),
	}, p.Err
}