/
verify_elk.go
279 lines (238 loc) · 7.68 KB
/
verify_elk.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"text/template"
"time"
)
type elkConfiguration struct {
Host string `json:"host"`
Port string `json:"port"`
Query string `json:"query"`
MatchesEqual *int `json:"matchesEquals"`
MatchesAtLeast *int `json:"matchesAtLeast"`
Minutes int `json:"minutes"`
NotificationMessage string `json:"notification_message"`
}
type elkURLTemplateData struct {
Host string
Port string
Date string
}
type elkBodyTemplateData struct {
Query string
Minutes string
}
func doElkVerifications(config config) []verificationError {
var errors []verificationError
for _, c := range config.ElkConfiguration {
errors = append(errors, doElkVerification(c)...)
}
return errors
}
func doElkVerification(config elkConfiguration) []verificationError {
var errors []verificationError
// if multiple indexes that will result in multiple calls to logstash
// i.e. the results might be a combination of a query against the pre-midnight index and the
// post-midnight index (as logstash does index rotation at midnight utc)
indexes := elkIndexToUse(time.Now().UTC(), config.Minutes)
var urls, err = makeUrls(config.Host, config.Port, indexes)
if err != nil {
e := verificationError{title: "Elk verification error", message: fmt.Sprintf("Failed to make urls: %s\n", fmt.Sprint(err))}
errors = append(errors, e)
return errors
}
var outputs []string
for _, url := range urls {
body, err := makeBody(config.Query, config.Minutes)
if err != nil {
e := verificationError{title: "Elk verification error", message: fmt.Sprintf("Failed to make elk request body: %s\n", fmt.Sprint(err))}
errors = append(errors, e)
return errors
}
resp, err := http.Post(url, "application/json", strings.NewReader(body))
if err != nil {
e := verificationError{title: "Elk verification error", message: fmt.Sprintf("Failed to make elk request: %s\n", fmt.Sprint(err))}
errors = append(errors, e)
return errors
}
defer resp.Body.Close()
res, err := ioutil.ReadAll(resp.Body)
if err != nil {
e := verificationError{title: "Elk verification error", message: fmt.Sprintf("Failed to read response from elk: %s\n", fmt.Sprint(err))}
errors = append(errors, e)
return errors
}
outputs = append(outputs, string(res))
}
if config.MatchesEqual != nil {
e := verifyElkExpectedNoOfMatches(outputs, *config.MatchesEqual, config.NotificationMessage)
errors = append(errors, e...)
} else {
e := verifyElkAtLeastNoOfMatches(outputs, *config.MatchesAtLeast, config.NotificationMessage)
errors = append(errors, e...)
}
return errors
}
type ElkResult struct {
Results ElkHits `json:"hits"`
}
type ElkHits struct {
Total int `json:"total"`
Hits []ElkHit `json:"hits"`
}
type ElkHit struct {
Source ElkHitSource `json:"_source"`
}
type ElkHitSource struct {
Message string `json:"message"`
DockerName string `json:"docker.name"`
Timestamp string `json:"@timestamp"`
}
func verifyElkExpectedNoOfMatches(outputs []string, expectedMatches int, notificationMessage string) []verificationError {
var errors []verificationError
var matches []ElkHit
var total = 0
// parse the json outputs. Collect the matches and sum the total number of matches
for _, o := range outputs {
var res ElkResult
err := json.Unmarshal([]byte(o), &res)
if err != nil {
e := verificationError{title: "Elk verification error", message: fmt.Sprintf("Failed to parse json output file: %s\n", fmt.Sprint(err))}
return append(errors, e)
}
matches = append(matches, res.Results.Hits...)
total += res.Results.Total
}
if total != expectedMatches {
if total == 0 {
e := verificationError{title: notificationMessage, message: fmt.Sprintf("Expected %d matches but was 0\n", expectedMatches)}
errors = append(errors, e)
} else {
for _, hit := range matches {
//errors = append(errors, fmt.Sprintf("Expected %d matches but was %d:\n", expectedMatches, total))
e := verificationError{title: notificationMessage, message: fmt.Sprintf("%s %s %s\n", hit.Source.Timestamp, hit.Source.DockerName, hit.Source.Message)}
errors = append(errors, e)
}
}
}
return errors
}
func verifyElkAtLeastNoOfMatches(outputs []string, atleast int, notificationMessage string) []verificationError {
var errors []verificationError
var matches []ElkHit
var total = 0
// parse the json outputs. Collect the matches and sum the total number of matches
for _, o := range outputs {
var res ElkResult
err := json.Unmarshal([]byte(o), &res)
if err != nil {
e := verificationError{title: notificationMessage, message: fmt.Sprintf("Failed to parse json output file: %s\n", fmt.Sprint(err))}
errors = append(errors, e)
return errors
}
matches = append(matches, res.Results.Hits...)
total += res.Results.Total
}
if total < atleast {
e := verificationError{title: notificationMessage, message: fmt.Sprintf("Expected at least %d matches but was %d\n", atleast, total)}
errors = append(errors, e)
if total > 0 {
e := verificationError{
title: "Elk verification error",
message: fmt.Sprintf("One of the matching lines: %s %s %s\n",
matches[0].Source.Timestamp,
matches[0].Source.DockerName,
matches[0].Source.Message)}
errors = append(errors, e)
}
}
return errors
}
func formatDateForElkIndex(time time.Time) string {
return time.Format("2006.01.02")
}
// elkIndexToUse figures out what logstash index to use based on the current time and the time period for the
// logstash query. If the query spans midnight UTC, when logstash does daily index rotation, this function
// will return both the pre-midnight index and the post-midnight index
func elkIndexToUse(now time.Time, minutes int) []string {
then := now.Add(time.Duration(-1*minutes) * time.Minute)
if now.Day() != then.Day() {
return []string{formatDateForElkIndex(then), formatDateForElkIndex(now)}
} else {
return []string{formatDateForElkIndex(now)}
}
}
func makeUrls(host string, port string, indexes []string) ([]string, error) {
const elkURLTemplate = "http://{{.Host}}:{{.Port}}/logstash-{{.Date}}/logs/_search"
tmpl, err := template.New("url").Parse(elkURLTemplate)
if err != nil {
return nil, fmt.Errorf("Failed to parse elk template: %s\n", fmt.Sprint(err))
}
var urls []string
for _, index := range indexes {
templateData := elkURLTemplateData{host, port, index}
var b bytes.Buffer
err = tmpl.Execute(&b, templateData)
if err != nil {
return nil, fmt.Errorf("Failed to parse elk template: %s\n", fmt.Sprint(err))
}
urls = append(urls, b.String())
}
return urls, nil
}
func makeBody(query string, minutes int) (string, error) {
const elkBodyTemplate = `{
"query": {
"filtered": {
"query": {
"query_string": {
"query": "{{.Query}}"
}
},
"filter": {
"bool": {
"must": [
{
"range": {
"@timestamp": {
"gte": "now-{{.Minutes}}m"
}
}
}
],
"must_not": []
}
}
}
},
"size": 500,
"sort": {
"@timestamp": "desc"
},
"fields": [
"_source"
],
"script_fields": {},
"fielddata_fields": [
"timestamp",
"@timestamp"
]
}'
`
tmpl, err := template.New("body").Parse(elkBodyTemplate)
if err != nil {
return "", fmt.Errorf("Failed to parse elk template: %s\n", fmt.Sprint(err))
}
templateData := elkBodyTemplateData{template.JSEscapeString(query), fmt.Sprintf("%d", minutes)}
var b bytes.Buffer
err = tmpl.Execute(&b, templateData)
if err != nil {
return "", fmt.Errorf("Failed to parse elk template: %s\n", fmt.Sprint(err))
}
return b.String(), nil
}