File size: 2,110 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
69
70
71
72
73
74
75
76
77
78
79
80
81
package alert

import (
	"crypto/sha512"
	"encoding/hex"
	"strings"
	"time"

	"github.com/target/goalert/validation/validate"
)

// maximum lengths
const (
	MaxSummaryLength = 1024     // 1KiB
	MaxDetailsLength = 6 * 1024 // 6KiB
)

// An Alert represents an ongoing situation.
type Alert struct {
	ID        int       `json:"_id"`
	Status    Status    `json:"status"`
	Summary   string    `json:"summary"`
	Details   string    `json:"details"`
	Source    Source    `json:"source"`
	ServiceID string    `json:"service_id"`
	CreatedAt time.Time `json:"created_at"`
	Dedup     *DedupID  `json:"dedup"`
}

// DedupKey will return the de-duplication key for the alert.
// The Dedup prop is used if non-nil, otherwise one is generated
// using the Description of the Alert.
func (a *Alert) DedupKey() *DedupID {
	if a.Dedup != nil {
		return a.Dedup
	}

	// fallback is auto:1:<lcase(Sum512(Description))>
	sum := sha512.Sum512([]byte(a.Description()))
	return &DedupID{
		Type:    DedupTypeAuto,
		Version: 1,
		Payload: hex.EncodeToString(sum[:]),
	}
}

func (a *Alert) scanFrom(scanFn func(...interface{}) error) error {
	return scanFn(&a.ID, &a.Summary, &a.Details, &a.ServiceID, &a.Source, &a.Status, &a.CreatedAt, &a.Dedup)
}

func (a Alert) Normalize() (*Alert, error) {
	if string(a.Source) == "" {
		a.Source = SourceManual
	}
	if string(a.Status) == "" {
		a.Status = StatusTriggered
	}
	a.Summary = strings.ReplaceAll(a.Summary, "\n", " ")
	a.Summary = strings.ReplaceAll(a.Summary, "  ", " ")

	err := validate.Many(
		validate.Text("Summary", a.Summary, 1, MaxSummaryLength),
		validate.Text("Details", a.Details, 0, MaxDetailsLength),
		validate.OneOf("Source", a.Source, SourceManual, SourceGrafana, SourceSite24x7, SourcePrometheusAlertmanager, SourceEmail, SourceGeneric, SourceUniversal),
		validate.OneOf("Status", a.Status, StatusTriggered, StatusActive, StatusClosed),
		validate.UUID("ServiceID", a.ServiceID),
	)
	if err != nil {
		return nil, err
	}

	return &a, nil
}

func (a Alert) Description() string {
	if a.Details == "" {
		return a.Summary
	}
	return a.Summary + "\n" + a.Details
}