-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
212 lines (180 loc) · 5.44 KB
/
main.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
package main
import (
"fmt"
"log"
"os"
"os/signal"
"strconv"
"syscall"
"time"
"github.com/perangel/dtail/pkg/metrics"
"github.com/perangel/dtail/pkg/metrics/collections"
"github.com/perangel/dtail/pkg/monitor"
"github.com/perangel/dtail/pkg/parser"
"github.com/perangel/dtail/pkg/tail"
"github.com/spf13/cobra"
)
var (
// flag vars
monitorAlertThreshold float64
monitorAlertWindow time.Duration
monitorResolution time.Duration
retryFollow bool
reportInterval time.Duration
)
const (
defaultLogPath = "/tmp/access.log"
)
var dtailCmd = &cobra.Command{
Use: "dtail [FILE]",
Short: "Tail, with more details",
Long: `
dtail is a cli-tool for realtime monitoring of structured log files (e.g. HTTP access log).
`,
RunE: tailFile,
}
func init() {
dtailCmd.Flags().Float64VarP(
&monitorAlertThreshold,
"alert-threshold", "t", 10.0,
"Threshold value for triggering an alert during the monitor's alert window.",
)
dtailCmd.Flags().DurationVarP(
&monitorAlertWindow,
"alert-window", "w", 2*time.Minute,
"Time frame for evaluating a metric against the alert threshold.",
)
dtailCmd.Flags().DurationVarP(
&monitorResolution,
"monitor-resolution", "r", 1*time.Second,
"Monitor resolution (e.g. 30s, 1m, 5h)",
)
dtailCmd.Flags().BoolVarP(
&retryFollow,
"retry-follow", "F", false,
"Retry file after rename or deletion. Similar to `tail -F`.",
)
dtailCmd.Flags().DurationVarP(
&reportInterval,
"report-interval", "i", 10*time.Second,
"Print a report at the given interval (e.g. 30s, 1m, 5h)",
)
}
// TODO: Move to DSL/query package
func total4xxResponses(counterMap collections.CounterMap) int64 {
total := int64(0)
for k, v := range counterMap {
// FIXME: Don't skip key on error
i, err := strconv.Atoi(k)
if err != nil {
continue
}
if 400 <= i && i <= 499 {
total += v.Value()
}
}
return total
}
// TODO: Move to DSL/query package
func total5xxResponses(counterMap collections.CounterMap) int64 {
total := int64(0)
for k, v := range counterMap {
// FIXME: Don't skip key on error
i, err := strconv.Atoi(k)
if err != nil {
continue
}
if 500 <= i && i <= 599 {
total += v.Value()
}
}
return total
}
func tailFile(cmd *cobra.Command, args []string) error {
var filepath string
if len(args) < 1 {
filepath = defaultLogPath
} else {
filepath = args[0]
}
t, err := tail.TailFile(filepath, &tail.Config{Retry: retryFollow})
if err != nil {
return err
}
fmt.Printf("\033[0;34mTailing file %s...\033[0m \n", filepath)
// create a monitor for request rate
requestRateMonitor := monitor.NewMonitor(&monitor.Config{
Aggregator: monitor.Mean, // TODO: accept aggregation on the command line
AlertThreshold: monitorAlertThreshold,
Resolution: monitorResolution,
Window: monitorAlertWindow,
})
shutdownCh := make(chan os.Signal, 1)
signal.Notify(shutdownCh, os.Interrupt, syscall.SIGTERM)
go func() {
<-shutdownCh
t.Stop()
requestRateMonitor.Stop()
}()
// TODO: Refactor this to pkg/dtail
go func() {
// NOTE: `requestCounter` will be reset at each tick of the Monitor interval,
// so DO NOT rely on it for aggregate totals during the execution of the program.
requestCounter := metrics.NewCounter()
requestRateMonitor.Watch(requestCounter)
// count total requests handled by dtail
totalRequests := metrics.NewCounter()
requestsByUser := collections.NewCounterMap()
requestsByIP := collections.NewCounterMap()
requestsBySection := collections.NewCounterMap()
requestsByURI := collections.NewCounterMap()
requestsByStatusCode := collections.NewCounterMap()
parser := parser.NewParser()
reportTick := time.NewTicker(reportInterval)
for {
select {
case line := <-t.Lines:
request, err := parser.ParseLine(line)
if err != nil {
log.Println("parser error: ", err)
}
requestCounter.Inc(1)
requestsByUser.IncKey(request.AuthUser)
requestsByIP.IncKey(request.RemoteHost)
requestsBySection.IncKey(request.Section())
requestsByURI.IncKey(request.URI)
requestsByStatusCode.IncKey(fmt.Sprintf("%d", request.StatusCode))
totalRequests.Inc(1)
case evt := <-requestRateMonitor.Triggered:
fmt.Printf("\033[0;31mHigh traffic generated an alert - hits = %.2f, triggered at %v\033[0m \n", evt.Value, evt.Time)
case evt := <-requestRateMonitor.Resolved:
fmt.Printf("\033[0;32mHigh traffic alert resolved - hits = %.2f, resolved at %v\033[0m \n", evt.Value, evt.Time)
case t := <-reportTick.C:
fmt.Println()
fmt.Println("Traffic Report:")
fmt.Printf(" Current time: %v\n", t)
fmt.Printf(" Total Requests: %d\n", totalRequests.Value())
fmt.Printf(" Top 3 IPs by # of requests: %v\n", requestsByIP.TopNKeys(3))
fmt.Printf(" Top 3 users by # of requests: %v\n", requestsByUser.TopNKeys(3))
fmt.Printf(" Top 3 site sections by # of requests: %v\n", requestsBySection.TopNKeys(3))
fmt.Printf(" Top 3 URIs by # of requests: %v\n", requestsByURI.TopNKeys(3))
fmt.Printf(" No. of 4xx responses: %v\n", total4xxResponses(requestsByStatusCode))
fmt.Printf(" No. of 5xx responses: %v\n", total5xxResponses(requestsByStatusCode))
fmt.Println()
// Reset all of the counters
totalRequests.Reset()
requestsByIP.Reset()
requestsByUser.Reset()
requestsBySection.Reset()
requestsByURI.Reset()
requestsByStatusCode.Reset()
}
}
}()
return t.Wait()
}
func main() {
if err := dtailCmd.Execute(); err != nil {
os.Exit(1)
}
}