-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtb_cli_hook.go
572 lines (502 loc) · 20.5 KB
/
tb_cli_hook.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
package main
import (
"context"
"errors"
log "github.com/sirupsen/logrus"
"os"
"os/exec"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
)
type TbCliStatus struct {
Gateway string
CommandPath string
}
func (cli *TbCliStatus) runStatusCmd() ([]byte, error) {
osDetect := runtime.GOOS
if osDetect == "linux" {
log.Info("Running on Linux machine... continuing")
} else if !DEBUG {
log.Fatal("This exporter is only supported on Linux, please run on a Linux machine. We love Linus Torvalds!")
}
var cmd *exec.Cmd
args := []string{"-c", "tbstatus -gw " + cli.Gateway + " " + cli.CommandPath}
cmd = exec.CommandContext(context.TODO(), "/bin/bash", args...)
out, err := cmd.CombinedOutput()
return out, err
}
const (
napBeginning = "^\\w*:\\/nap:(\\w*)$"
napValueNormal = "^\\s{3}-\\s(\\w*)\\s*(\\w*)\\s*$"
napValueStruct = "^\\s{5}\\|-\\s(\\w*)\\s*([0-9]*[.]?[0-9]+)\\s*$"
napStructTitle = "^\\s{3}-\\s(\\w*)\\s*$"
)
func GetStatusNAP(cli TbCliStatus) (map[string]*NapStatus, error) {
cli.CommandPath = "/nap"
var out string
var err error
if !DEBUG {
outT, err := cli.runStatusCmd()
if err != nil {
return nil, err
}
out = string(outT)
} else {
outT, err := os.ReadFile("./out_test.txt")
if err != nil {
return nil, err
}
out = string(outT)
}
// check empty data??
if len(out) <= 0 {
return nil, err
}
// precompile the regex expressions
rNapBeginning, err := regexp.Compile(napBeginning)
if err != nil {
return nil, err
}
rNapValueNorm, err := regexp.Compile(napValueNormal)
if err != nil {
return nil, err
}
rNapValueStruct, err := regexp.Compile(napValueStruct)
if err != nil {
return nil, err
}
rNapStructTitle, err := regexp.Compile(napStructTitle)
if err != nil {
return nil, err
}
// store these values for later
napStatuses := make(map[string]*NapStatus)
var currentStruct string
var currentNAP string
var insideStats bool
// keep track of the previous line processed, ignore if it was blank, as well as keep the line number??
lines := strings.Split(out, "\n")
for _, l := range lines {
if strings.Contains(l, "local_drop_stats") ||
strings.Contains(l, "remote_drop_stats") ||
strings.Contains(l, "system_drop_stats") {
if DEBUG {
log.Warnf("Found drop stats, ignoring until handled correctly")
}
currentStruct = rNapStructTitle.FindAllStringSubmatch(l, -1)[0][1]
vVal := reflect.ValueOf(napStatuses[currentNAP]).Elem()
for i := 0; i < vVal.NumField(); i++ {
field := vVal.Type().Field(i)
if field.Tag.Get("json") == currentStruct {
if field.Type.Kind() == reflect.Map {
// get the map values, and append to the map, as each line is actually a different statistic
// so we don't want to overwrite the map, but append to it
vVal.Field(i).Set(reflect.MakeMap(vVal.Field(i).Type()))
break
} else {
if DEBUG {
log.Errorf("Found unknown type: %s", field.Type.Kind())
}
continue
}
}
}
insideStats = true
continue
} else if insideStats && rNapValueStruct.MatchString(l) {
// match stats line
fields := rNapValueStruct.FindAllStringSubmatch(l, -1)
fieldName := fields[0][1]
fieldValue := fields[0][2]
if DEBUG {
log.Infof("Found field in stats: %s with value: %s", fieldName, fieldValue)
}
vVal := reflect.ValueOf(napStatuses[currentNAP]).Elem()
for i := 0; i < vVal.NumField(); i++ {
field := vVal.Type().Field(i)
if field.Tag.Get("json") == currentStruct {
if field.Type.Kind() == reflect.Map {
// get the map values, and append to the map, as each line is actually a different statistic
// so we don't want to overwrite the map, but append to it
atoi, err := strconv.Atoi(fieldValue)
if err != nil {
return nil, err
}
key := reflect.ValueOf(fieldName)
value := reflect.ValueOf(atoi)
vVal.Field(i).SetMapIndex(key, value) // append to the map
break
} else {
if DEBUG {
log.Errorf("Found unknown type: %s", field.Type.Kind())
}
continue
}
if DEBUG {
log.Infof("12 - Found field: %s with value: %s, NAP: %s", fieldName, fieldValue, currentNAP)
}
}
}
}
if strings.Contains(l, "struct") {
if insideStats {
if DEBUG {
log.Info("Previously inside stats, changing to false, and continuing")
}
insideStats = false
}
if currentStruct != "" {
if DEBUG {
log.Errorf("Current struct is not empty, assuming it can be overwritten")
}
}
if currentNAP == "" {
if DEBUG {
log.Errorf("Current NAP is empty, cannot process struct")
}
continue
}
if rNapStructTitle.MatchString(l) {
if DEBUG {
log.Warnln("Found struct, entering struct mode")
log.Infof("Current struct is: %s", currentStruct)
}
currentStruct = rNapStructTitle.FindAllStringSubmatch(l, -1)[0][1]
// todo reflect onto the struct
continue
}
// mark it as entered the struct
// get the map name from the
} else if currentStruct != "" && rNapValueStruct.MatchString(l) {
// reflect based on current struct, to parse the next data, and append to built struct
// todo build out the inside struct data
if insideStats {
if DEBUG {
log.Info("Inside stats, ignoring fields")
}
continue
}
if currentNAP == "" {
if DEBUG {
log.Errorf("Current NAP is empty, cannot process struct")
}
continue
}
if currentStruct == "" {
// todo why would this be empty??
return nil, errors.New("found struct data, but current struct is empty, ignoring")
}
fields := rNapValueStruct.FindAllStringSubmatch(l, -1)
fieldName := fields[0][1]
fieldValue := fields[0][2]
vVal := reflect.ValueOf(napStatuses[currentNAP]).Elem()
for i := 0; i < vVal.NumField(); i++ {
f := vVal.Type().Field(i)
if f.Tag.Get("json") == currentStruct {
if f.Type.Kind() == reflect.Struct {
// todo handle nested structs
//log.Warnln("Found nested struct, todo handle")
nVal := vVal.Field(i)
for j := 0; j < nVal.NumField(); j++ {
field := nVal.Type().Field(j)
if field.Tag.Get("json") == fieldName {
if DEBUG {
log.Infof("Found field: %s with value: %s, NAP: %s", fieldName, fieldValue, currentNAP)
}
if field.Type.Kind() == reflect.Int {
fieldValueInt, err := strconv.Atoi(fieldValue)
if err != nil {
if DEBUG {
log.Errorf("Failed to convert string to int: %s", err)
}
continue
}
nVal.Field(j).SetInt(int64(fieldValueInt))
break
} else if field.Type.Kind() == reflect.String {
nVal.Field(j).SetString(fieldValue)
break
} else if field.Type.Kind() == reflect.Bool {
fieldValueBool, err := strconv.ParseBool(fieldValue)
if err != nil {
if DEBUG {
log.Errorf("Failed to convert string to bool: %s", err)
}
continue
}
nVal.Field(j).SetBool(fieldValueBool)
break
} else if field.Type.Kind() == reflect.Float64 {
fieldValueFloat, err := strconv.ParseFloat(fieldValue, 64)
if err != nil {
if DEBUG {
log.Errorf("Failed to convert string to float64: %s", err)
}
continue
}
nVal.Field(j).SetFloat(fieldValueFloat)
break
} else if field.Type.Kind() == reflect.Struct {
if DEBUG {
log.Errorf("Found unknown type: %s", field.Type.Kind())
}
continue
} else {
if DEBUG {
log.Errorf("Found unknown type: %s", field.Type.Kind())
}
continue
}
break
}
}
break
} else {
continue
}
if DEBUG {
log.Infof("12 - Found field: %s with value: %s, NAP: %s", fieldName, fieldValue, currentNAP)
}
}
}
// todo reflect onto the struct
continue
} else if rNapBeginning.MatchString(l) {
napName := rNapBeginning.FindAllStringSubmatch(l, -1)[0][1]
_, ok := napStatuses[napName]
// If the key exists
if !ok {
napStatuses[napName] = &NapStatus{}
} else {
if DEBUG {
log.Errorf("NAP already exists, skipping")
}
}
currentNAP = napName
continue
// todo check if the line is empty?? or do we just skip those??
} else if rNapValueNorm.MatchString(l) {
// if normal values match, and it *was* in struct mode, remove struct mode and resume.
if currentNAP == "" {
if DEBUG {
log.Errorf("Current NAP is empty, cannot process struct")
}
continue
}
if currentStruct != "" {
if DEBUG {
log.Warn("Found normal value, but was in struct mode, exiting struct mode")
}
currentStruct = ""
}
fieldName := rNapValueNorm.FindAllStringSubmatch(l, -1)[0][1]
fieldValue := rNapValueNorm.FindAllStringSubmatch(l, -1)[0][2]
if DEBUG {
log.Infof("Found field: %s with value: %s, NAP: %s", fieldName, fieldValue, currentNAP)
}
nVal := reflect.ValueOf(napStatuses[currentNAP]).Elem()
for i := 0; i < nVal.NumField(); i++ {
field := nVal.Type().Field(i)
if field.Tag.Get("json") == fieldName {
if field.Type.Kind() == reflect.Int {
fieldValueInt, err := strconv.Atoi(fieldValue)
if err != nil {
if DEBUG {
log.Errorf("Failed to convert string to int: %s", err)
}
continue
}
nVal.Field(i).SetInt(int64(fieldValueInt))
break
} else if field.Type.Kind() == reflect.String {
nVal.Field(i).SetString(fieldValue)
break
} else if field.Type.Kind() == reflect.Bool {
fieldValueBool, err := strconv.ParseBool(fieldValue)
if err != nil {
if DEBUG {
log.Errorf("Failed to convert string to bool: %s", err)
}
continue
}
nVal.Field(i).SetBool(fieldValueBool)
break
} else if field.Type.Kind() == reflect.Float64 {
fieldValueFloat, err := strconv.ParseFloat(fieldValue, 64)
if err != nil {
if DEBUG {
log.Errorf("Failed to convert string to float64: %s", err)
}
continue
}
nVal.Field(i).SetFloat(fieldValueFloat)
break
} else if field.Type.Kind() == reflect.Struct {
if DEBUG {
log.Errorf("Found unknown type: %s", field.Type.Kind())
}
continue
} else {
if DEBUG {
log.Errorf("Found unknown type: %s", field.Type.Kind())
}
continue
}
if DEBUG {
log.Infof("11 - Found field: %s with value: %s, NAP: %s", fieldName, fieldValue, currentNAP)
}
nVal.Field(i).Set(reflect.ValueOf(fieldValue))
break
}
}
continue
}
}
return napStatuses, nil
}
/*
there's also this section that will need to be handled accordingly...
- local_drop_stats
|- TOTAL 8
|- TOOLPACK_NORMAL 4
|- TOOLPACK_SIGNALING_ERROR 4
- remote_drop_stats
|- TOTAL 8
|- NORMAL_CALL_CLEARING (16) 2
|- 404_NOT_FOUND 6
- system_drop_stats
|- TOTAL 42
|- TOOLPACK_SIGNALING_ERROR 41
|- 488_NOT_ACCEPTBLE_HERE 1
*/
type NapStatus struct {
AvailabilityDetectionStruct AvailabilityDetectionStruct `json:"availability_detection_struct"`
PortRangeSharedUsagePercent int `json:"port_range_shared_usage_percent"`
AvailableCnt int `json:"available_cnt"`
InstIncomingCallCntTerminating int `json:"inst_incoming_call_cnt_terminating"`
InstIncomingCallCntAnswered int `json:"inst_incoming_call_cnt_answered"`
SignalingType string `json:"signaling_type"`
TotalIncomingFilePlaybacks int `json:"total_incoming_file_playbacks"`
InstOutgoingCallCnt int `json:"inst_outgoing_call_cnt"`
InstIncomingEmergencyCallCnt int `json:"inst_incoming_emergency_call_cnt"`
ResetAsrStats string `json:"reset_asr_stats"`
InstOutgoingCallRate int `json:"inst_outgoing_call_rate"`
InstIncomingCallRateAnswered int `json:"inst_incoming_call_rate_answered"`
InstIncomingCallRateAccepted int `json:"inst_incoming_call_rate_accepted"`
FirewallBlockedCnt int `json:"firewall_blocked_cnt"`
ResetStats string `json:"reset_stats"`
ResetNapDropStats string `json:"reset_nap_drop_stats"`
AsrStatsIncomingStruct AsrStatsIncomingStruct `json:"asr_stats_incoming_struct"`
UsagePercent int `json:"usage_percent"`
TotalIncomingInterceptions int `json:"total_incoming_interceptions"`
InstIncomingFilePlaybacks int `json:"inst_incoming_file_playbacks"`
InstOutgoingCallCntAnswered int `json:"inst_outgoing_call_cnt_answered"`
InstIncomingEmergencyCallRateHighest int `json:"inst_incoming_emergency_call_rate_highest"`
UniqueId int `json:"unique_id"`
SystemDropStats map[string]int `json:"system_drop_stats"`
LocalDropStats map[string]int `json:"local_drop_stats"`
RemoteDropStats map[string]int `json:"remote_drop_stats"`
MosStruct MosStruct `json:"mos_struct"`
SipSharedUsagePercent int `json:"sip_shared_usage_percent"`
InstIncomingCallRateAnsweredHighest int `json:"inst_incoming_call_rate_answered_highest"`
InstIncomingCallCnt int `json:"inst_incoming_call_cnt"`
TotalOutgoingFileRecordings int `json:"total_outgoing_file_recordings"`
InstOutgoingCallRateAnsweredHighest int `json:"inst_outgoing_call_rate_answered_highest"`
InstIncomingCallRate int `json:"inst_incoming_call_rate"`
InstIncomingCallCntInProgress int `json:"inst_incoming_call_cnt_in_progress"`
AvailabilityPercent int `json:"availability_percent"`
InstIncomingFileRecordings int `json:"inst_incoming_file_recordings"`
InstOutgoingCallRateAccepted int `json:"inst_outgoing_call_rate_accepted"`
FirewallBlocked bool `json:"firewall_blocked"`
CallCongestionPeriodDroppedCalls int `json:"call_congestion_period_dropped_calls"`
RegistrationStruct RegistrationStruct `json:"registration_struct"`
NetworkQualityStruct NetworkQualityStruct `json:"network_quality_struct"`
AsrStatsOutgoingStruct AsrStatsOutgoingStruct `json:"asr_stats_outgoing_struct"`
InstOutgoingCallRateHighest int `json:"inst_outgoing_call_rate_highest"`
InstIncomingEmergencyCallRate int `json:"inst_incoming_emergency_call_rate"`
LowDelayRelaySharedUsagePercent int `json:"low_delay_relay_shared_usage_percent"`
TotalOutgoingInterceptions int `json:"total_outgoing_interceptions"`
InstOutgoingFilePlaybacks int `json:"inst_outgoing_file_playbacks"`
InstIncomingInterceptions int `json:"inst_incoming_interceptions"`
CallCongestion bool `json:"call_congestion"`
MipsSharedUsagePercent int `json:"mips_shared_usage_percent"`
SharedUsagePercent int `json:"shared_usage_percent"`
UnavailableCnt int `json:"unavailable_cnt"`
InstOutgoingFileRecordings int `json:"inst_outgoing_file_recordings"`
InstOutgoingCallRateAnswered int `json:"inst_outgoing_call_rate_answered"`
InstOutgoingCallCntTerminating int `json:"inst_outgoing_call_cnt_terminating"`
InstIncomingEmergencyCallCntAnswered int `json:"inst_incoming_emergency_call_cnt_answered"`
RtpStatisticsStruct RtpStatisticsStruct `json:"rtp_statistics_struct"`
ResetRtpStats string `json:"reset_rtp_stats"`
TotalOutgoingFilePlaybacks int `json:"total_outgoing_file_playbacks"`
InstOutgoingInterceptions int `json:"inst_outgoing_interceptions"`
TotalIncomingFileRecordings int `json:"total_incoming_file_recordings"`
InstOutgoingCallRateAcceptedHighest int `json:"inst_outgoing_call_rate_accepted_highest"`
InstIncomingCallRateAcceptedHighest int `json:"inst_incoming_call_rate_accepted_highest"`
InstIncomingCallRateHighest int `json:"inst_incoming_call_rate_highest"`
}
type MosStruct struct {
CurrentHourEgress float64 `json:"current_hour_egress"`
LastHourEgress float64 `json:"last_hour_egress"`
CurrentHourIngress float64 `json:"current_hour_ingress"`
LastHourIngress float64 `json:"last_hour_ingress"`
Last24HIngress float64 `json:"last_24h_ingress"`
Last24HEgress float64 `json:"last_24h_egress"`
}
type RtpStatisticsStruct struct {
FromNetNbOtherErrors int `json:"from_net_nb_other_errors"`
FromNetNbLostPackets int `json:"from_net_nb_lost_packets"`
T38NbPagesFromTdm int `json:"t38_nb_pages_from_tdm"`
FromNetNbBadProtocolHeaders int `json:"from_net_nb_bad_protocol_headers"`
FromNetNbPackets int `json:"from_net_nb_packets"`
ToNetNbPackets int `json:"to_net_nb_packets"`
T38NbPagesToTdm int `json:"t38_nb_pages_to_tdm"`
ToNetNbArpFailures int `json:"to_net_nb_arp_failures"`
FromNetNbBufferOverflows int `json:"from_net_nb_buffer_overflows"`
FromNetNbOutOfSeqPackets int `json:"from_net_nb_out_of_seq_packets"`
FromNetNbEarlyLatePackets int `json:"from_net_nb_early_late_packets"`
FromNetNbDuplicatePackets int `json:"from_net_nb_duplicate_packets"`
}
type AvailabilityDetectionStruct struct {
PollRemoteProxy string `json:"poll_remote_proxy"`
IsAvailable string `json:"is_available"`
}
type AsrStatsOutgoingStruct struct {
Last24HCallCnt int `json:"last_24h_call_cnt"`
Last24HAsrPercent int `json:"last_24h_asr_percent"`
TotalCallCnt int `json:"total_call_cnt"`
GlobalAsrPercent int `json:"global_asr_percent"`
LastHourCallCnt int `json:"last_hour_call_cnt"`
CurrentHourCallCnt int `json:"current_hour_call_cnt"`
TotalAnsweredCallCnt int `json:"total_answered_call_cnt"`
TotalAcceptedCallCnt int `json:"total_accepted_call_cnt"`
LastHourAsrPercent int `json:"last_hour_asr_percent"`
CurrentHourAsrPercent int `json:"current_hour_asr_percent"`
}
type AsrStatsIncomingStruct struct {
Last24HCallCnt int `json:"last_24h_call_cnt"`
Last24HAsrPercent int `json:"last_24h_asr_percent"`
TotalCallCnt int `json:"total_call_cnt"`
GlobalAsrPercent int `json:"global_asr_percent"`
LastHourCallCnt int `json:"last_hour_call_cnt"`
CurrentHourCallCnt int `json:"current_hour_call_cnt"`
TotalAnsweredCallCnt int `json:"total_answered_call_cnt"`
TotalAcceptedCallCnt int `json:"total_accepted_call_cnt"`
LastHourAsrPercent int `json:"last_hour_asr_percent"`
CurrentHourAsrPercent int `json:"current_hour_asr_percent"`
}
type RegistrationStruct struct {
Registered string `json:"registered"`
RegisterToProxy string `json:"register_to_proxy"`
}
type NetworkQualityStruct struct {
CurrentHourEgress int `json:"current_hour_egress"`
LastHourEgress int `json:"last_hour_egress"`
CurrentHourIngress int `json:"current_hour_ingress"`
LastHourIngress int `json:"last_hour_ingress"`
Last24HIngress int `json:"last_24h_ingress"`
Last24HEgress int `json:"last_24h_egress"`
}