-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathba_checker.go
291 lines (261 loc) · 7.09 KB
/
ba_checker.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
package main
import (
"fmt"
"net/http"
"os"
"sort"
"strconv"
"time"
"github.com/BurntSushi/toml"
"github.com/briandowns/spinner"
"github.com/jawher/mow.cli"
"github.com/olekukonko/tablewriter"
)
const (
toolVersion = "v0.8"
)
var (
lookUpStatusCodeMap = map[int]string{
0: "OK",
1: "WARNING",
2: "CRITICAL",
3: "UNKNOWN",
}
)
type configuration struct {
Sites []site `toml:"site"`
}
type site struct {
Base string `toml:"base"`
BasicAuth []string `toml:"auth"`
NoBasicAuth []string `toml:"no_auth"`
endpoints []endpoint
}
type endpoint struct {
BaShouldBe bool
URL string
BaEnabled bool
Success bool
Unknown bool
HTTPStatus string
HTTPStatusCode int
}
type endpointSorter []endpoint
func (a endpointSorter) Len() int { return len(a) }
func (a endpointSorter) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a endpointSorter) Less(i, j int) bool { return a[i].URL < a[j].URL }
func getMaxWidth(sites []site) (width int) {
var URL string
for _, site := range sites {
for _, ep := range site.endpoints {
URL = fmt.Sprintf("%s/%s", site.Base, ep.URL)
if len(URL) > width {
width = len(URL)
}
}
}
return width
}
func numberOfTotalURLs(sites []site) (count int) {
for _, site := range sites {
count += len(site.endpoints)
}
return count
}
func checkSites(sites []site) {
amountOfURLs := numberOfTotalURLs(sites)
endpointChan := make(chan *endpoint, amountOfURLs)
endpointDone := make(chan bool, amountOfURLs)
defer close(endpointChan)
defer close(endpointDone)
for i := 0; i < 30; i++ {
go endpointWorker(endpointChan, endpointDone)
}
for i := range sites {
checkSite(&sites[i], endpointChan)
}
// Wait for all endpoints to be done
for i := 0; i < amountOfURLs; i++ {
<-endpointDone // wait for one task to complete
}
}
func printSitesTable(sites []site, statusCode int) {
table := tablewriter.NewWriter(os.Stdout)
table.SetBorders(tablewriter.Border{Left: false, Top: false, Right: false, Bottom: true})
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetAutoFormatHeaders(false)
table.SetHeader([]string{"URL", "Basic Auth", "Wanted BA", "Success", "HTTP Status"})
for _, site := range sites {
sort.Sort(endpointSorter(site.endpoints))
for _, ep := range site.endpoints {
baMessage := "no"
baWantedMessage := "no"
if ep.BaEnabled {
baMessage = "yes"
}
if ep.Unknown {
baMessage = "unknown"
}
if ep.BaShouldBe {
baWantedMessage = "yes"
}
data := []string{
ep.URL,
baMessage,
baWantedMessage,
strconv.FormatBool(ep.Success),
ep.HTTPStatus,
}
table.Append(data)
}
}
table.Render()
fmt.Printf("\nStatus: %s\n", lookUpStatusCodeMap[statusCode])
}
func printNagiosResult(sites []site, statusCode int) {
totalURLs := numberOfTotalURLs(sites)
failures, unknowns := getTotalFailuresAndUnknowns(sites)
if unknowns > 0 {
fmt.Printf("BA check: %s - OK: %d/%d Unknowns: %d\n",
lookUpStatusCodeMap[statusCode],
totalURLs-(failures+unknowns),
totalURLs,
unknowns)
} else {
fmt.Printf("BA check: %s - OK: %d/%d\n",
lookUpStatusCodeMap[statusCode],
totalURLs-failures,
totalURLs)
}
}
func printResults(sites []site, outputFormat string, statusCode int) {
switch {
case outputFormat == "table":
printSitesTable(sites, statusCode)
return
case outputFormat == "nagios":
printNagiosResult(sites, statusCode)
return
}
fmt.Printf("Unkown output format: %s\n", outputFormat)
}
func endpointWorker(endpointChan <-chan *endpoint, endpointDone chan bool) {
for ep := range endpointChan {
checkURL(ep)
endpointDone <- true
}
}
func checkSite(site *site, endpointChan chan *endpoint) {
for index := range site.endpoints {
endpointChan <- &site.endpoints[index]
}
}
func checkSuccess(response *http.Response, baShouldBe bool) (success bool, baEnabled bool, unknown bool) {
if response.StatusCode == 401 {
baEnabled = true
} else if response.StatusCode > 401 {
unknown = true
}
return baEnabled == baShouldBe, baEnabled, unknown
}
func checkURL(ep *endpoint) {
client := &http.Client{}
req, err := http.NewRequest("GET", ep.URL, nil)
req.Header.Add("Cache-Control", "no-cache")
req.Header.Set("User-Agent", fmt.Sprintf("ba_checker %s", toolVersion))
response, err := client.Do(req)
if err != nil {
ep.Success = false
ep.BaEnabled = false
}
ep.HTTPStatusCode = response.StatusCode
ep.HTTPStatus = response.Status
ep.Success, ep.BaEnabled, ep.Unknown = checkSuccess(response, ep.BaShouldBe)
}
func populateURLConfig(sites []site) {
for index := range sites {
for _, baURL := range sites[index].BasicAuth {
sites[index].endpoints = append(sites[index].endpoints,
endpoint{
BaShouldBe: true,
URL: fmt.Sprintf("%s/%s", sites[index].Base, baURL),
})
}
for _, URL := range sites[index].NoBasicAuth {
sites[index].endpoints = append(sites[index].endpoints,
endpoint{
BaShouldBe: false,
URL: fmt.Sprintf("%s/%s", sites[index].Base, URL),
})
}
}
}
func getTotalFailuresAndUnknowns(sites []site) (failures int, unknowns int) {
for _, site := range sites {
for _, ep := range site.endpoints {
if !ep.Success {
failures++
}
if ep.Unknown {
unknowns++
}
}
}
return failures, unknowns
}
func checkStatus(sites []site, warningThreshold int, criticalThreshold int) (status int) {
failures, unknowns := getTotalFailuresAndUnknowns(sites)
switch {
case failures >= criticalThreshold:
return 2
case unknowns > 0 && failures != 0:
return 3
case failures >= warningThreshold:
return 1
}
return
}
func main() {
app := cli.App("ba_checker", `Check HTTP Basic Auth status
Status can be determined by Exit codes:
0=Status OK
1=Above warning threshold
2=Above critical threshold
3=Unknown Basic Auth status (4xx or 5xx HTTP codes)`)
app.Version("v version", toolVersion)
app.Spec = "[--warning=<number>] [--critical=<number>] [--output=<table|nagios>] [--no-spinner] CONFIGFILE"
var (
noSpinner = app.BoolOpt("no-spinner", false, "Disable spinner animation")
configFile = app.StringArg("CONFIGFILE", "", "Config file")
outputFormat = app.StringOpt("o output", "table", "Output format, available formats: table, nagios")
warningThreshold = app.IntOpt("w warning", 1, "Warning threshold")
criticalThreshold = app.IntOpt("c critical", 2, "Critical threshold")
)
app.Action = func() {
var config configuration
if _, err := os.Stat(*configFile); os.IsNotExist(err) {
fmt.Printf("Error: Given config file %s does not exist, exiting..\n", *configFile)
cli.Exit(1)
}
if _, err := toml.DecodeFile(*configFile, &config); err != nil {
fmt.Println("Error:", err)
cli.Exit(1)
}
s := spinner.New(spinner.CharSets[7], 100*time.Millisecond)
if !*noSpinner {
s.Prefix = "running tests "
s.Start()
}
populateURLConfig(config.Sites)
checkSites(config.Sites)
if !*noSpinner {
s.Stop()
}
lookupStatusCode := checkStatus(config.Sites, *warningThreshold, *criticalThreshold)
printResults(config.Sites, *outputFormat, lookupStatusCode)
if lookupStatusCode > 0 {
cli.Exit(lookupStatusCode)
}
}
app.Run(os.Args)
}