/
puppy.go
270 lines (233 loc) · 6.99 KB
/
puppy.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
// Copyright © 2016 Joubin Houshyar. All rights reserved.
//
// This file is part of puppy.
//
// puppy is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
//
// puppy is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with puppy. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
)
// ----------------------------------------------------------------------
// command-line flags and configuration
var conf = struct {
fname string
trafficLimitLow, trafficLimitHigh uint
statPeriodSec, alertPeriodMin uint
logJournalSize, alertsJournalSize uint
}{
"", 100, 10000, 1, 5, 1024, 1024,
}
func init() {
flag.StringVar(&conf.fname, "f", conf.fname, "apache log file")
flag.UintVar(&conf.trafficLimitLow, "tmin", conf.trafficLimitLow, "traffic min threshold ")
flag.UintVar(&conf.trafficLimitHigh, "tmax", conf.trafficLimitHigh, "traffic max threshold ")
flag.UintVar(&conf.statPeriodSec, "s", conf.statPeriodSec, "stat snapshot period (sec)")
flag.UintVar(&conf.alertPeriodMin, "a", conf.alertPeriodMin, "alerts check period (min)")
}
// ----------------------------------------------------------------------
// cleanup
func cleanup() {
fmt.Println("DEBUG - cleanup - tooleh.go")
restoreTerminal()
}
// ----------------------------------------------------------------------
// state
// maintain a sliding window of tail emits
var logJournal *ringBuffer
// maintain a sliding window of alerts notices.
var alertsJournal *ringBuffer
// maintain reference to last period's alert notice. Reminder that alert notices
// are in {alertRaised, alertRecovered}. This reference may be nil, indicating
// no standing (un-recovered) alert is in effect, keeping in mind that if an alert
// condition is not recovered in the current cycle, a new alert will be raised
// and referenced here.
var activeAlert *alert
// collect resource specific periodic. We'll accumulate data for each
// cycle (c.f. conf.statPeriodSec) and then compute the snapshot analysis.
var accessMetrics *metrics
// last snapshot's statistical analysis
var accessStatistic *statistic
// ----------------------------------------------------------------------
// process loop
func main() {
var stat int
var e error
/// best effort for clean shutdown /////////////////////////////////////
/* insure cleanup of terminal */
defer func(stat0 *int, e0 *error) {
cleanup()
if *e0 != nil {
log.Printf("%s\n", (*e0).Error())
}
log.Printf("exit - stat: %d\n", *stat0)
os.Exit(*stat0)
}(&stat, &e)
defer func(stat0 *int, e0 *error) {
p := recover()
if p != nil {
log.Printf("panic - recovered: %v\n", p)
*e0 = fmt.Errorf("panic - %v ", p)
*stat0 = -1
}
}(&stat, &e)
/// config & setup /////////////////////////////////////////////////////
flag.Parse()
if conf.fname == "" {
e = fmt.Errorf("log file name (option -f) is required.")
stat = 6
return
}
/* -- state objects */
alertsJournal = newRingBuffer(conf.alertsJournalSize)
logJournal = newRingBuffer(conf.logJournalSize)
// snapshotsPerAlertCheck := uint16(60 * conf.alertPeriodMin / conf.statPeriodSec)
snapshotsPerAlertCheck := uint16(conf.alertPeriodMin / conf.statPeriodSec) // TODO
accessMetrics, e = newMetrics(snapshotsPerAlertCheck)
if e != nil {
stat = 10 // TODO use consts or just -1:panics;1:error;0:ok
return
}
/* -- clocks --- */
// stats timer
stats_timer := time.NewTicker(time.Second * time.Duration(conf.statPeriodSec))
defer stats_timer.Stop()
/* -- signals --- */
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Kill, os.Interrupt)
defer close(interrupt) /* yes, pedantic */
ttyevent := make(chan os.Signal, 1)
signal.Notify(ttyevent, syscall.SIGWINCH)
defer close(ttyevent)
/* -- inputs --- */
// tail process
var tailproc *tailProc
tailproc, e = tail(conf.fname)
if e != nil {
stat = 1
return
}
// user input
var ui <-chan uiEvent
ui, e = uiEventPipe()
if e != nil {
stat = 2
return
}
/// processing loop ////////////////////////////////////////////////////
alertChkCountdown := uint16(0)
refreshDisplay(true)
for {
select {
case <-stats_timer.C:
// note: REVU comment of the function below addresses high
// perofmrance concerns.
accessStatistic = accessMetrics.takeSnapshot()
alertChkCountdown++
if alertChkCountdown == snapshotsPerAlertCheck {
alertChkCountdown = 0
checkTraffic()
}
refreshDisplay(false)
case event, ok := <-ui:
if !ok {
e = fmt.Errorf("ui events channel unepxectedly closed. will exit.")
stat = 3
tailproc.stop <- true
return
}
switch {
case event.is(viewStats, viewAlerts, viewLog, viewDebug):
setView(event)
case event.is(pageUp, pageDown):
scrollView(event)
case event.is(doQuit):
tailproc.stop <- true
return
default:
beep()
}
case line, ok := <-tailproc.out:
if !ok {
e = fmt.Errorf("err - tail stopped. (killed?)")
stat = 4
return
}
entry, err := parseW3cCommonLogFormat(line)
if err != nil {
e = fmt.Errorf("err - failed to parse tail out - %s\n", err.Error())
stat = 5
tailproc.stop <- true
return
}
accessMetrics.Update(entry)
logJournal.add(string(line)) // REVU: this optional feature is likely not worth the perf. hit.
if currentView.id == logView {
displayLog()
}
case sig := <-interrupt:
if tailproc != nil {
tailproc.cmd.Process.Kill()
}
signal.Stop(interrupt)
selfSignal(sig)
tailproc.stop <- true
stat = 7
return
case _ = <-ttyevent:
updateWinSize()
refreshDisplay(true)
}
}
}
// we need to let the shell know that the processes was killed.
// so we reissue the signal (expected to be Interrupt or Kill)
// to self and this time we will not be catching it.
//
func selfSignal(s os.Signal) error {
proc, e := os.FindProcess(os.Getpid())
if e != nil {
return e
}
return proc.Signal(s)
}
// checks total traffic for the sliding time window and
// updates activeAlert per results.
func checkTraffic() {
var total uint
counts := accessMetrics.traffic.items()
for _, obj := range counts {
total += obj.(*accessCounter).total
}
if total < conf.trafficLimitHigh {
/* all ok. did we recover? */
if activeAlert != nil && activeAlert.typ == alertRaised {
activeAlert, _ = activeAlert.recovered(time.Now())
} else {
activeAlert = nil
}
} else {
/* trouble in paradise */
activeAlert, _ = newAlert(total, time.Now()) /* safe to not check error here */
}
if activeAlert != nil {
alertsJournal.add(activeAlert)
}
return
}