forked from keybase/managed-bots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logs.go
231 lines (211 loc) · 5.22 KB
/
logs.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
package elastiwatch
import (
"context"
"fmt"
"regexp"
"time"
"github.com/malware-unicorn/go-keybase-chat-bot/kbchat/types/chat1"
"github.com/malware-unicorn/managed-bots/base"
"github.com/olivere/elastic"
)
type LogWatch struct {
*base.DebugOutput
db *DB
cli *elastic.Client
index, email string
entries []*entry
emailer base.Emailer
sendCount int
lastSend time.Time
alertConvID chat1.ConvIDStr
emailConvID chat1.ConvIDStr
shutdownCh chan struct{}
peekCh chan struct{}
}
func NewLogWatch(cli *elastic.Client, db *DB, index, email string, emailer base.Emailer,
alertConvID, emailConvID chat1.ConvIDStr, debugConfig *base.ChatDebugOutputConfig) *LogWatch {
return &LogWatch{
DebugOutput: base.NewDebugOutput("LogWatch", debugConfig),
cli: cli,
db: db,
index: index,
email: email,
emailer: emailer,
lastSend: time.Now(),
alertConvID: alertConvID,
emailConvID: emailConvID,
shutdownCh: make(chan struct{}),
peekCh: make(chan struct{}),
}
}
func (l *LogWatch) addAndCheckForSend(entries []*entry) {
l.entries = append(l.entries, l.filterEntries(entries)...)
threshold := 10000
score := 0
for _, e := range l.entries {
switch e.Severity {
case "INFO":
score++
case "WARNING":
score += 5
case "ERROR":
score += 25
case "CRITICAL":
score += 10000
}
}
if score > threshold {
entriesCopy := make([]*entry, len(l.entries))
copy(entriesCopy, l.entries)
l.entries = nil
l.Debug("threshold reached, sending: score: %d threshold: %d entries: %d",
score, threshold, len(entriesCopy))
go l.generateAndSend(entriesCopy)
}
}
const backs = "```"
func (l *LogWatch) alertFromChunk(c chunk) {
if c.Severity != "CRITICAL" {
return
}
l.ChatEcho(l.alertConvID, `%d *CRITICAL* errors received
%s%s%s`, c.Count, backs, c.Message, backs)
}
func (l *LogWatch) alertEmail(subject string, chunks []chunk) {
body := fmt.Sprintf("Email sent: %s", subject)
for _, c := range chunks {
if c.Severity == "INFO" {
continue
}
body += fmt.Sprintf("\n%s %d %s", c.Severity, c.Count, c.Message)
}
l.ChatEcho(l.emailConvID, "```"+body+"```")
}
func (l *LogWatch) filterEntries(entries []*entry) (res []*entry) {
// get regexes
deferrals, err := l.db.List()
if err != nil {
l.Errorf("failed to get filter list: %s", err)
return entries
}
if len(deferrals) == 0 {
return entries
}
var regexs []*regexp.Regexp
for _, d := range deferrals {
r, err := regexp.Compile(d.regex)
if err != nil {
l.Errorf("invalid regex: %s err: %s", d, err)
continue
}
regexs = append(regexs, r)
}
// filter
isBlocked := func(msg string) bool {
for _, r := range regexs {
if r.Match([]byte(msg)) {
l.Debug("filtering message: %s regex: %s", msg, r)
return true
}
}
return false
}
for _, e := range entries {
if !isBlocked(e.Message) {
res = append(res, e)
}
}
return res
}
func (l *LogWatch) peek() {
groupRes := newTreeifyGrouper(3).Group(l.entries)
l.alertEmail("Peek results", groupRes)
}
func (l *LogWatch) generateAndSend(entries []*entry) {
// do tree grouping
groupRes := newTreeifyGrouper(3).Group(entries)
indivRes := newTreeifyGrouper(0).Group(entries)
for _, c := range groupRes {
l.alertFromChunk(c)
}
var sections []renderSection
sections = append(sections, renderSection{
Heading: "Grouped Messages",
Chunks: groupRes,
})
sections = append(sections, renderSection{
Heading: "Individual Messages",
Chunks: indivRes,
})
renderText, err := htmlRenderer{}.Render(sections)
if err != nil {
l.Debug("error rendering chunks: %s", err.Error())
}
dur := time.Since(l.lastSend).String()
subject := fmt.Sprintf("Log Error Report - #%d - %s", l.sendCount, dur)
l.alertEmail(subject, groupRes)
if err := l.emailer.Send(l.email, subject, renderText); err != nil {
l.Debug("error sending email: %s", err.Error())
}
l.sendCount++
l.lastSend = time.Now()
}
func (l *LogWatch) runOnce() {
query := elastic.NewBoolQuery().
Must(elastic.NewRangeQuery("@timestamp").
From(time.Now().Add(-time.Minute)).
To(time.Now())).
MustNot(elastic.NewTermQuery("severity", "debug"))
res, err := l.cli.Search().
Index(l.index).
Query(query).
Pretty(true).
From(0).Size(10000).
Do(context.Background())
if err != nil {
l.Debug("failed to run Elasticsearch query: %s", err)
return
}
var entries []*entry
if res.TotalHits() > 0 {
l.Debug("query hits: %d", res.TotalHits())
for _, hit := range res.Hits.Hits {
entry, err := newEntry(*hit.Source)
if err != nil {
l.Errorf("failed to unmarshal log entry: %s", err)
continue
}
entries = append(entries, entry)
}
} else {
l.Debug("no query hits, doing nothing")
}
l.addAndCheckForSend(entries)
}
func (l *LogWatch) Run() error {
l.Debug("log watch starting up...")
if l.alertConvID != "" {
l.Debug("alerting into convID: %s", l.alertConvID)
}
if l.emailConvID != "" {
l.Debug("email notices into convID: %s", l.emailConvID)
}
l.runOnce()
for {
select {
case <-l.shutdownCh:
return nil
case <-l.peekCh:
l.peek()
case <-time.After(time.Minute):
l.runOnce()
}
}
}
func (l *LogWatch) Peek() {
l.peekCh <- struct{}{}
}
func (l *LogWatch) Shutdown() error {
close(l.shutdownCh)
return nil
}