-
Notifications
You must be signed in to change notification settings - Fork 0
/
analyze.go
344 lines (323 loc) · 11 KB
/
analyze.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package main
import (
"bufio"
"fmt"
"log"
"os"
"sort"
"strconv"
"strings"
"time"
)
type LogEntry struct {
IP string
Class string
TimeStamp time.Time
Method string
Request string
Code int
RTime string
}
type Log2Analyze struct {
FileName string
DateLayout string
StartTime time.Time
EndTime time.Time
Entries []LogEntry
}
func (l *Log2Analyze) RetrieveEntries(endtime string, timerange int) {
// retrieves the records from the log file within a time range or of the whole file
// if no timerange is given
file, err := os.Open(l.FileName)
if err != nil {
LogIt.Debug("Error opening file: " + l.FileName)
fmt.Println("Error opening file: " + l.FileName)
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file) // scan the contents of a file and print line by line
c := 0
cl := 0
for scanner.Scan() {
line := scanner.Text()
cl++
entry := create_entry(line)
// StartTime is zero, if this is the first entry
if l.StartTime.IsZero() {
// TODO: check the date layout and stopp the loop, if the date layout is not correct
// set the start and end time according to the date of the first entry
LogIt.Debug("l.StartTime is zero, setting Start and End Time")
l.StartTime, l.EndTime = create_time_range(endtime, timerange, entry.TimeStamp)
LogIt.Debug("Start Time: " + l.StartTime.Format(log_2_analyze.DateLayout))
LogIt.Debug("End Time: " + l.EndTime.Format(log_2_analyze.DateLayout))
}
if (timerange == 0 || entry.Between(l.StartTime, l.EndTime)) && (*ip_adress == "" || entry.IP == *ip_adress) {
l.Entries = append(l.Entries, entry)
c++
}
// if the timerange is zero, we set the endtime to the last entry
if timerange == 0 {
l.EndTime = entry.TimeStamp
}
}
LogIt.Info("checked " + fmt.Sprintf("%d", cl) + " lines")
LogIt.Info("found Entries within timerange: " + fmt.Sprintf("%v", len(l.Entries)))
LogIt.Debug(" counter says: " + fmt.Sprintf("%d", c))
if err := scanner.Err(); err != nil {
fmt.Println("Error reading from file:", err) // print error if scanning is not done properly
}
}
func (l Log2Analyze) GetTopIPs() (map[string]int, map[int]int) {
// returns the five ip addresses with the highest request count within the last 5 minutes
ip_count := make(map[string]int)
code_count := make(map[int]int)
for _, record := range l.Entries {
ip_count[record.Class]++
code_count[record.Code]++
}
// to prevent it from crashing, when the given map ip_count, we check the length
// of the map and if it is empty, we return an empty map
// if the map is not empty, we sort the map by the request count and return the top 5 or less
top_ips := make(map[string]int)
entries := len(ip_count)
if entries > *topIPsCount {
entries = *topIPsCount
}
if entries > 0 {
// build a slice of the keys of the map, so we can sort it to get the top 5
ips := make([]string, 0, entries)
for ip := range ip_count {
ips = append(ips, ip)
}
// sort the slice by the request count
sort.SliceStable(ips, func(i, j int) bool {
return ip_count[ips[i]] > ip_count[ips[j]]
})
// get the top 5 or less, if there are less than 5 entries
// be aware, that the resulting map (top_ips) is not ordered!
for i := 0; i < entries; i++ {
top_ips[ips[i]] = ip_count[ips[i]]
}
}
return top_ips, code_count
}
func (l Log2Analyze) WriteOutputFiles(top_ips map[string]int, code_counts map[int]int) {
for ip, count := range top_ips {
file, err := os.Create(config.OutputFolder + fmt.Sprintf("%05d", count) + "_" + ip + ".txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
file.WriteString(ip + "\t" + fmt.Sprintf("%v", count) + "\n")
for _, record := range l.Entries {
if record.Class == ip {
file.WriteString(record.TimeStamp.Format(l.DateLayout) + "\t" + record.IP + "\t" + record.Method + "\t" + record.Request + "\t" + fmt.Sprintf("%d", record.Code) + "\n")
}
}
}
file, err := os.Create(config.OutputFolder + "response_codes.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close()
file.WriteString("Code\tCount\n====\t=======\n")
// maps are not ordered, so we need to sort the map by the request count
entries := len(code_counts)
if entries > 0 {
// first step: get all the keys from the map into a slice, that can be sorted
codes := make([]int, 0, entries)
for code := range code_counts {
codes = append(codes, code)
}
// second step: sort the slice by the request count
sort.SliceStable(codes, func(i, j int) bool {
return code_counts[codes[i]] > code_counts[codes[j]]
})
// third step: iterate over the sorted slice and print the code and the request count
for _, c := range codes {
file.WriteString(fmt.Sprintf("%d\t%d", c, code_counts[c]) + "\n")
}
}
}
func (e LogEntry) Between(start, end time.Time) bool {
// checks if the LogEntry is between the start and end time
passt := e.TimeStamp.After(start) && e.TimeStamp.Before(end)
// the following line produces heavy debug output
// LogIt.Debug(start.Format(log_2_analyze.DateLayout) + " > " + e.TimeStamp.Format(log_2_analyze.DateLayout) + " > " + end.Format(log_2_analyze.DateLayout) + " :: " + fmt.Sprintf("%v", passt))
return passt
}
func create_entry(line string) LogEntry {
// creates a LogEntry from a line
var ip, class, method, request, rtime string
var code int
var timestamp time.Time
switch config.LogType {
case "apache_atmire":
ip, class, timestamp, method, request, code, rtime = parse_apache_atmire(line)
case "nginx":
ip, class, timestamp, method, request, code, rtime = parse_nginx(line)
case "rosetta":
ip, class, timestamp, method, request, code, rtime = parse_rosetta(line)
}
return LogEntry{
IP: ip,
Class: class,
TimeStamp: timestamp,
Method: method,
Request: request,
Code: code,
RTime: rtime,
}
}
func parse_apache_atmire(line string) (string, string, time.Time, string, string, int, string) {
var ip, class, method, request, codestring, rtime string
var code int
var timestamp time.Time
var err error
parts := strings.Split(strings.Replace(line, "\"", "", -1), " ")
timestring := strings.Replace(parts[3], "[", "", 1) + " " + strings.Replace(parts[4], "]", "", 1)
timestamp, err = time.Parse(log_2_analyze.DateLayout, timestring)
if err != nil {
LogIt.Error("Error parsing timestamp: " + timestring + " with layout " + log_2_analyze.DateLayout)
LogIt.Error("Error parsing timestamp: " + err.Error())
}
// crude workaround for short lines
if len(parts) < 9 {
LogIt.Debug("having difficulties to parse line: " + line)
LogIt.Debug("got " + fmt.Sprintf("%d", len(parts)) + " parts")
LogIt.Debug("got parts: " + fmt.Sprintf("%v", parts))
for i := 0; i < (9 - len(parts)); i++ {
parts = append(parts, "")
}
}
ip = parts[0]
method = parts[5]
request = parts[6]
// crude workaround for lines with response code 408
if parts[8] == "-" {
codestring = parts[6]
request = parts[5]
} else {
codestring = parts[8]
}
code, err = strconv.Atoi(codestring)
if err != nil {
LogIt.Error("Error parsing code (maybe hacking?): " + codestring)
LogIt.Error(line)
LogIt.Debug("Error parsing code: " + err.Error())
code = 0
}
// switch to get the IP class
ip_parts := strings.Split(ip, ".")
switch *IPclass {
case "A":
class = ip_parts[0]
case "B":
class = ip_parts[0] + "." + ip_parts[1]
case "C":
class = ip_parts[0] + "." + ip_parts[1] + "." + ip_parts[2]
default:
class = ip
}
return ip, class, timestamp, method, request, code, rtime
}
func parse_rosetta(line string) (string, string, time.Time, string, string, int, string) {
var ip, class, method, request, codestring, rtime string
var code int
var timestamp time.Time
var err error
parts := strings.Split(strings.Replace(line, "\"", "", -1), " ")
timestring := strings.Replace(parts[4], "[", "", 1) + " " + strings.Replace(parts[5], "]", "", 1)
timestamp, err = time.Parse(log_2_analyze.DateLayout, timestring)
if err != nil {
LogIt.Error("Error parsing timestamp: " + timestring + " with layout " + log_2_analyze.DateLayout)
LogIt.Error("Error parsing timestamp: " + err.Error())
}
// crude workaround for short lines
if len(parts) < 9 {
LogIt.Debug("having difficulties to parse line: " + line)
LogIt.Debug("got " + fmt.Sprintf("%d", len(parts)) + " parts")
LogIt.Debug("got parts: " + fmt.Sprintf("%v", parts))
for i := 0; i < (9 - len(parts)); i++ {
parts = append(parts, "")
}
}
if parts[1] == "-" {
ip = parts[0]
} else {
ip = parts[1]
}
method = parts[6]
request = parts[7]
// crude workaround for lines with response code 408
if parts[9] == "-" {
codestring = parts[7]
request = parts[6]
} else {
codestring = parts[9]
}
code, err = strconv.Atoi(codestring)
if err != nil {
LogIt.Error("Error parsing code (maybe hacking?): " + codestring)
LogIt.Error(line)
LogIt.Debug("Error parsing code: " + err.Error())
code = 0
}
// switch to get the IP class
ip_parts := strings.Split(ip, ".")
switch *IPclass {
case "A":
class = ip_parts[0]
case "B":
class = ip_parts[0] + "." + ip_parts[1]
case "C":
class = ip_parts[0] + "." + ip_parts[1] + "." + ip_parts[2]
default:
class = ip
}
return ip, class, timestamp, method, request, code, rtime
}
func parse_nginx(line string) (string, string, time.Time, string, string, int, string) {
var ip, class, method, request, rtime string
var code int
var timestamp time.Time
LogIt.Info("parsing nginx not implemented yet")
return ip, class, timestamp, method, request, code, rtime
}
func create_time_range(endtimestring string, timerange int, firstTimestamp time.Time) (time.Time, time.Time) {
// creates a time range to analyze the log file
// the range is defined by the time2analyze flag
LogIt.Debug("got End Time String: " + endtimestring)
LogIt.Debug("got Time Range: " + fmt.Sprintf("%d", timerange))
LogIt.Debug("got First Timestamp: " + firstTimestamp.Format(log_2_analyze.DateLayout))
// enrich the endtimestring with the current date and timezone
endtimestring = fmt.Sprintf("%s %s:00 %s", firstTimestamp.Format("2006-01-02"), endtimestring, time.Now().Local().Format("Z0700"))
LogIt.Debug("End Time String: " + endtimestring)
// create a time object from the endtimestring
endtime, _ := time.Parse("2006-01-02 15:04:05 -0700", endtimestring)
LogIt.Debug("created End Time: " + endtime.Format(log_2_analyze.DateLayout))
starttime := firstTimestamp
if timerange > 0 {
// create a starttime by subtracting the timerange from the endtime
starttime = endtime.Add(time.Duration(-timerange) * time.Minute)
}
LogIt.Debug("created Start Time( - " + fmt.Sprintf("%d", timerange) + "): " + starttime.Format(log_2_analyze.DateLayout))
return starttime, endtime
}
// func count_requests(records []LogEntry) map[string]int {
// // counts the requests per ip
// ip_count := make(map[string]int)
// for _, record := range records {
// ip_count[record.IP]++
// }
// return ip_count
// }
//
// func count_codes(records []LogEntry) map[string]int {
// // counts the status codes
// code_count := make(map[string]int)
// for _, record := range records {
// code_count[record.Code]++
// }
// return code_count
// }