This repository has been archived by the owner on Apr 10, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
/
monitor.go
380 lines (354 loc) · 11.1 KB
/
monitor.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
// Stream parsers and keepers.
package main
import (
"expvar"
"fmt"
"github.com/grafov/bcast"
"math/rand"
"net/http"
"strings"
"time"
)
// Run monitors for each stream.
func StreamMonitor() {
var debugvars = expvar.NewMap("streams")
var requestedTasks = expvar.NewInt("requested-tasks")
var queueSizeHLSTasks = expvar.NewInt("hls-tasks-queue")
var executedHLSTasks = expvar.NewInt("hls-tasks-done")
var expiredHLSTasks = expvar.NewInt("hls-tasks-expired")
var queueSizeHDSTasks = expvar.NewInt("hds-tasks-queue")
var executedHDSTasks = expvar.NewInt("hds-tasks-done")
var expiredHDSTasks = expvar.NewInt("hds-tasks-expired")
var queueSizeHTTPTasks = expvar.NewInt("http-tasks-queue")
var executedHTTPTasks = expvar.NewInt("http-tasks-done")
var expiredHTTPTasks = expvar.NewInt("http-tasks-expired")
var queueSizeWVTasks = expvar.NewInt("wv-tasks-queue")
var executedWVTasks = expvar.NewInt("wv-tasks-done")
var expiredWVTasks = expvar.NewInt("wv-tasks-expired")
var hlscount, hdscount, wvcount, httpcount int
var hlsprobecount int
debugvars.Set("requested-tasks", requestedTasks)
debugvars.Set("hls-tasks-queue", queueSizeHLSTasks)
debugvars.Set("hls-tasks-done", executedHLSTasks)
debugvars.Set("hls-tasks-expired", expiredHLSTasks)
debugvars.Set("hds-tasks-queue", queueSizeHDSTasks)
debugvars.Set("hds-tasks-done", executedHDSTasks)
debugvars.Set("hds-tasks-expired", expiredHDSTasks)
debugvars.Set("http-tasks-queue", queueSizeHTTPTasks)
debugvars.Set("http-tasks-done", executedHTTPTasks)
debugvars.Set("http-tasks-expired", expiredHTTPTasks)
debugvars.Set("wv-tasks-queue", queueSizeWVTasks)
debugvars.Set("wv-tasks-done", executedWVTasks)
debugvars.Set("wv-tasks-expired", expiredWVTasks)
ctl := bcast.NewGroup()
go ctl.Broadcasting(0)
go Heartbeat(ctl)
// запуск проберов и потоков
for gname, gdata := range cfg.GroupParams {
switch gdata.Type {
case HLS:
gtasks := make(chan *Task)
for i := 0; i < gdata.Probers; i++ {
go CupertinoProber(ctl, gtasks, debugvars)
hlsprobecount++
}
gchunktasks := make(chan *Task)
for i := 0; i < gdata.MediaProbers; i++ {
go MediaProber(ctl, HLS, gchunktasks, debugvars)
}
for _, stream := range *cfg.GroupStreams[gname] {
go StreamBox(ctl, stream, HLS, gtasks, debugvars)
hlscount++
}
case HDS:
gtasks := make(chan *Task)
for i := 0; i < gdata.Probers; i++ {
go SanjoseProber(ctl, gtasks, debugvars)
}
gchunktasks := make(chan *Task)
for i := 0; i < gdata.MediaProbers; i++ {
go MediaProber(ctl, HDS, gchunktasks, debugvars)
}
for _, stream := range *cfg.GroupStreams[gname] {
go StreamBox(ctl, stream, HDS, gtasks, debugvars)
hdscount++
}
case HTTP:
gtasks := make(chan *Task)
for i := 0; i < gdata.Probers; i++ {
go SimpleProber(ctl, gtasks, debugvars)
}
for _, stream := range *cfg.GroupStreams[gname] {
go StreamBox(ctl, stream, HTTP, gtasks, debugvars)
httpcount++
}
case WV:
gtasks := make(chan *Task)
for i := 0; i < gdata.Probers; i++ {
go WidevineProber(ctl, gtasks, debugvars)
}
for _, stream := range *cfg.GroupStreams[gname] {
go StreamBox(ctl, stream, WV, gtasks, debugvars)
wvcount++
}
}
}
if hlsprobecount > 0 {
fmt.Printf("%d HLS probers started.\n", hlsprobecount)
} else {
println("No HLS probers started.")
}
// if cfg.TotalProbersHDS > 0 {
// fmt.Printf("%d HDS probers started.\n", cfg.TotalProbersHDS)
// } else {
// println("No HDS probers started.")
// }
// if cfg.TotalProbersHTTP > 0 {
// fmt.Printf("%d HTTP probers started.\n", cfg.TotalProbersHTTP)
// } else {
// println("No HTTP probers started.")
// }
// if cfg.TotalProbersWV > 0 {
// fmt.Printf("%d Widevine VOD probers started.\n", cfg.TotalProbersWV)
// } else {
// println("No Widevine probers started.")
// }
if hlscount > 0 {
StatsGlobals.TotalHLSMonitoringPoints = hlscount
fmt.Printf("%d HLS monitors started.\n", hlscount)
} else {
println("No HLS monitors started.")
}
if hdscount > 0 {
StatsGlobals.TotalHDSMonitoringPoints = hdscount
fmt.Printf("%d HDS monitors started.\n", hdscount)
} else {
println("No HDS monitors started.")
}
if httpcount > 0 {
StatsGlobals.TotalHTTPMonitoringPoints = httpcount
fmt.Printf("%d HTTP monitors started.\n", httpcount)
} else {
println("No HTTP monitors started.")
}
if wvcount > 0 {
StatsGlobals.TotalWVMonitoringPoints = wvcount
fmt.Printf("%d Widevine monitors started.\n", wvcount)
} else {
println("No Widevine monitors started.")
}
StatsGlobals.TotalMonitoringPoints = hlscount + hdscount + httpcount + wvcount
}
// Мониторинг и статистика групп потоков.
func GroupBox(ctl *bcast.Group, group string, streamType StreamType, taskq chan *Task, debugvars *expvar.Map) {
}
// Container keep single stream properties and regulary make tasks for appropriate probers.
func StreamBox(ctl *bcast.Group, stream Stream, streamType StreamType, taskq chan *Task, debugvars *expvar.Map) {
var checkCount uint64 // число прошедших проверок
var addSleepToBrokenStream time.Duration
var tid int64 = time.Now().Unix() // got increasing offset on each program start
var min, max int
var command Command
var online bool = false
var stats Stats
defer func() {
if r := recover(); r != nil {
fmt.Printf("Stream %s trace: %s\n", stream.Name, r)
}
}()
task := &Task{Stream: stream, ReplyTo: make(chan *Result)}
switch streamType {
case HTTP:
task.ReadBody = false
case HLS:
task.ReadBody = true
case HDS:
task.ReadBody = true
case WV:
task.ReadBody = false
default:
task.ReadBody = false
}
ctlrcv := ctl.Join() // управление мониторингом
timer := time.Tick(3 * time.Second)
for {
select {
case recv := <-ctlrcv.In:
command = recv.(Command)
switch command {
case START_MON:
online = true
case STOP_MON:
online = false
}
case <-timer:
SaveStats(stream, stats)
default:
if !online {
time.Sleep(1 * time.Second)
continue
}
max = int(cfg.Params(stream.Group).TimeBetweenTasks)
min = int(cfg.Params(stream.Group).TimeBetweenTasks / 4. * 3.)
time.Sleep(time.Duration(rand.Intn(max-min)+min)*time.Second + addSleepToBrokenStream) // randomize streams order
tid++
task.Tid = tid
task.TTL = time.Now().Add(time.Duration(cfg.Params(stream.Group).TaskTTL * time.Second))
stats.Checks++ // TODO potentially overflow
taskq <- task
debugvars.Add("requested-tasks", 1)
result := <-task.ReplyTo
if result.ErrType == TTLEXPIRED {
continue
} else {
checkCount++
if checkCount > 144 {
fmt.Printf("Repeated %d times %s\n", checkCount, task.Name)
}
}
for _, subres := range result.SubResults {
subres.Pid = result
go SaveResult(stream, *subres)
}
go SaveResult(stream, *result)
max = int(cfg.Params(stream.Group).CheckBrokenTime)
min = int(cfg.Params(stream.Group).CheckBrokenTime / 4. * 3.)
switch {
// permanent error, not a timeout:
case result.ErrType > CRITICAL_LEVEL, result.ErrType == TTLEXPIRED:
addSleepToBrokenStream = time.Duration(rand.Intn(max-min)+min) * time.Second
// works ok:
case result.ErrType == SUCCESS:
addSleepToBrokenStream = 0
default:
addSleepToBrokenStream = 0
}
if result.ErrType != TTLEXPIRED {
if result.ErrType >= WARNING_LEVEL {
go Log(ERROR, stream, *result)
} else {
if result.Elapsed >= cfg.Params(stream.Group).VerySlowWarningTimeout*time.Second {
result.ErrType = VERYSLOW
go Log(WARNING, stream, *result)
} else if result.Elapsed >= cfg.Params(stream.Group).SlowWarningTimeout*time.Second {
result.ErrType = SLOW
go Log(WARNING, stream, *result)
}
}
}
}
}
}
// Check & report internet availability. Stop all probers when sample internet resources not available.
// Refs to config option ``samples``.
func Heartbeat(ctl *bcast.Group) {
var previous bool
ctlsnr := ctl.Join()
time.Sleep(1 * time.Second)
for {
for _, uri := range cfg.Samples {
client := NewTimeoutClient(12*time.Second, 6*time.Second)
req, err := http.NewRequest("HEAD", uri, nil)
if err != nil {
fmt.Println("Internet not available. All checks stopped.")
StatsGlobals.MonitoringState = false
continue
}
_, err = client.Do(req)
if err != nil {
StatsGlobals.MonitoringState = false
continue
}
StatsGlobals.MonitoringState = true
}
if previous != StatsGlobals.MonitoringState {
if StatsGlobals.MonitoringState {
ctlsnr.Send(START_MON)
fmt.Println("Internet Ok. Monitoring started.")
} else {
ctlsnr.Send(STOP_MON)
fmt.Println("Internet not available. Monitoring stopped.")
}
}
previous = StatsGlobals.MonitoringState
time.Sleep(4 * time.Second)
}
}
// Helper for expired tasks. Return result with TTL Expired status.
func TaskExpired(task *Task) *Result {
result := &Result{Started: time.Now(), Elapsed: 0 * time.Second}
result.ContentLength = -1
result.ErrType = TTLEXPIRED
return result
}
// Helper. Execute stream check task and return result with check status.
func ExecHTTP(task *Task) *Result {
defer func() {
if r := recover(); r != nil {
fmt.Println("trace dumped in ExecHTTP:", r)
}
}()
result := &Result{Task: task, Started: time.Now(), Elapsed: 0 * time.Second}
if !strings.HasPrefix(task.URI, "http://") && !strings.HasPrefix(task.URI, "https://") {
result.ErrType = BADURI
result.HTTPCode = 0
result.HTTPStatus = ""
result.ContentLength = -1
return result
}
client := NewTimeoutClient(cfg.Params(task.Group).ConnectTimeout*time.Second, cfg.Params(task.Group).RWTimeout*time.Second)
req, err := http.NewRequest("GET", task.URI, nil) // TODO разделить метод по проберам cfg.Params(task.Group).MethodHTTP
if err != nil {
fmt.Println(err)
result.ErrType = BADURI
result.HTTPCode = 0
result.HTTPStatus = ""
result.ContentLength = -1
return result
}
req.Header.Set("User-Agent", UserAgent())
resp, err := client.Do(req)
result.Elapsed = time.Since(result.Started)
if err != nil {
fmt.Printf("Connect timeout %s: %v\n", result.Elapsed, err)
if result.Elapsed > cfg.Params(task.Group).ConnectTimeout*time.Second {
result.ErrType = CTIMEOUT
} else {
result.ErrType = REFUSED
}
result.HTTPCode = 0
result.HTTPStatus = ""
result.ContentLength = -1
return result
}
result.HTTPCode = resp.StatusCode
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
result.ErrType = BADSTATUS
}
result.HTTPStatus = resp.Status
result.ContentLength = resp.ContentLength
result.Headers = resp.Header
if task.ReadBody {
result.RealContentLength, err = result.Body.ReadFrom(resp.Body)
if err != nil {
result.ErrType = BODYREAD
}
}
resp.Body.Close()
if result.RealContentLength > 0 && result.ContentLength != result.RealContentLength {
result.ErrType = BADLENGTH
}
return result
}
// Helper. Verify HLS specific things.
func verifyHLS(cfg *Config, task *Task, result *Result) {
defer func() {
if r := recover(); r != nil {
fmt.Println("trace dumped in HLS parser:", r)
result.ErrType = HLSPARSER
}
}()
}
// Ограничивать число запросов в ед.времени на ip
// func RateLimiter() {
// }