-
Notifications
You must be signed in to change notification settings - Fork 24
/
cake-autorate.sh
executable file
·1800 lines (1485 loc) · 66.2 KB
/
cake-autorate.sh
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# cake-autorate automatically adjusts CAKE bandwidth(s)
# in dependence on: a) receive and transmit transfer rates; and b) latency
# (or can just be used to monitor and log transfer rates and latency)
# requires: bash; and one of the supported ping binaries
# each cake-autorate instance must be configured using a corresponding config file
# Project homepage: https://github.com/lynxthecat/cake-autorate
# Licence details: https://github.com/lynxthecat/cake-autorate/blob/master/LICENCE.md
# Author and maintainer: lynxthecat
# Contributors: rany2; moeller0; richb-hanover
cake_autorate_version="3.3.0-PRERELEASE"
## cake-autorate uses multiple asynchronous processes including:
## main - main process
## monitor_achieved_rates - monitor network transfer rates
## maintain_log_file - maintain and rotate log file
##
## IPC is facilitated via FIFOs in the form of anonymous pipes
## thereby to enable transferring data between processes
# Set the IFS to space and comma
IFS=" ,"
# Initialize file descriptors
## -1 signifies that the log file fd will not be used and
## that the log file will be written to directly
log_fd=-1
exec {main_fd}<> <(:)
# process pids are stored below in the form
# proc_pids['process_identifier']=${!}
declare -A proc_pids
# Bash correctness options
## Disable globbing (expansion of *).
set -f
## Forbid using unset variables.
set -u
## The exit status of a pipeline is the status of the last
## command to exit with a non-zero status, or zero if no
## command exited with a non-zero status.
set -o pipefail
## Errors are intercepted via intercept_stderr below
## and sent to the log file and system log
# Possible performance improvement
export LC_ALL=C
# Set SCRIPT_PREFIX and CONFIG_PREFIX
POSSIBLE_SCRIPT_PREFIXES=(
"${CAKE_AUTORATE_SCRIPT_PREFIX:-}" # User defined
"/jffs/scripts/cake-autorate" # Asuswrt-Merlin
"/opt/cake-autorate"
"/usr/lib/cake-autorate"
"/root/cake-autorate"
)
for SCRIPT_PREFIX in "${POSSIBLE_SCRIPT_PREFIXES[@]}"
do
[[ -d ${SCRIPT_PREFIX} ]] && break
done
if [[ -z ${SCRIPT_PREFIX} || ! -d ${SCRIPT_PREFIX} ]]
then
printf "ERROR: Unable to find a working SCRIPT_PREFIX for cake-autorate. Exiting now.\n" >&2
printf "ERROR: Please set the CAKE_AUTORATE_SCRIPT_PREFIX environment variable to the correct path.\n" >&2
exit 1
fi
POSSIBLE_CONFIG_PREFIXES=(
"${CAKE_AUTORATE_CONFIG_PREFIX:-}" # User defined
"/jffs/configs/cake-autorate" # Asuswrt-Merlin
"${SCRIPT_PREFIX}" # Default
)
for CONFIG_PREFIX in "${POSSIBLE_CONFIG_PREFIXES[@]}"
do
[[ -d ${CONFIG_PREFIX} ]] && break
done
if [[ -z ${CONFIG_PREFIX} || ! -d ${CONFIG_PREFIX} ]]
then
printf "ERROR: Unable to find a working CONFIG_PREFIX for cake-autorate. Exiting now.\n" >&2
printf "ERROR: Please set the CAKE_AUTORATE_CONFIG_PREFIX environment variable to the correct path.\n" >&2
exit 1
fi
# shellcheck source=lib.sh
. "${SCRIPT_PREFIX}/lib.sh"
# shellcheck source=defaults.sh
. "${SCRIPT_PREFIX}/defaults.sh"
# get valid config overrides
mapfile -t valid_config_entries < <(grep -E '^[^(#| )].*=' "${SCRIPT_PREFIX}/defaults.sh" | sed -e 's/[\t ]*\#.*//g' -e 's/=.*//g')
trap cleanup_and_killall INT TERM EXIT
cleanup_and_killall()
{
# Do not fail on error for this critical cleanup code
set +e
trap : INT TERM EXIT
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
log_msg "INFO" "Stopping cake-autorate with PID: ${BASHPID} and config: ${config_path}"
log_msg "INFO" "Killing all background processes and cleaning up temporary files."
terminate "${proc_pids['monitor_achieved_rates']:-}"
terminate "${pinger_pids[*]}"
((terminate_maintain_log_file_timeout_ms=log_file_buffer_timeout_ms+500))
terminate "${proc_pids['maintain_log_file']}" "${terminate_maintain_log_file_timeout_ms}"
[[ -d ${run_path} ]] && rm -r "${run_path}"
rmdir /var/run/cake-autorate 2>/dev/null
# give some time for processes to gracefully exit
sleep_s 1
# terminate any processes that remain, save for main and intercept_stderr
unset "proc_pids[main]"
intercept_stderr_pid=${proc_pids[intercept_stderr]:-}
if [[ -n ${intercept_stderr_pid} ]]
then
unset "proc_pids[intercept_stderr]"
fi
terminate "${proc_pids[*]}"
# restore original stderr, and terminate intercept_stderr
if [[ -n ${intercept_stderr_pid} ]]
then
exec 2>&"${original_stderr_fd}"
terminate "${intercept_stderr_pid}"
fi
log_msg "SYSLOG" "Stopped cake-autorate with PID: ${BASHPID} and config: ${config_path}"
trap - INT TERM EXIT
exit
}
log_msg()
{
# send logging message to terminal, log file fifo, log file and/or system logger
local type=${1} msg=${2} instance_id=${instance_id:-"unknown"} log_timestamp=${EPOCHREALTIME}
case ${type} in
DEBUG)
((debug == 0)) && return # skip over DEBUG messages where debug disabled
((log_DEBUG_messages_to_syslog && use_logger)) && \
logger -t "cake-autorate.${instance_id}" "${type}: ${log_timestamp} ${msg}"
;;
ERROR)
((use_logger)) && \
logger -t "cake-autorate.${instance_id}" "${type}: ${log_timestamp} ${msg}"
;;
SYSLOG)
((use_logger)) && \
logger -t "cake-autorate.${instance_id}" "INFO: ${log_timestamp} ${msg}"
;;
*)
;;
esac
printf -v msg '%s; %(%F-%H:%M:%S)T; %s; %s\n' "${type}" -1 "${log_timestamp}" "${msg}"
((terminal)) && printf '%s' "${msg}"
# Output to the log file fifo if available (for rotation handling)
# else output directly to the log file
((log_to_file)) || return
if (( log_fd >= 0 ))
then
printf '%s' "${msg}" >&"${log_fd}"
else
printf '%s' "${msg}" >> "${log_file_path}"
fi
}
print_headers()
{
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
if ((output_processing_stats))
then
header="DATA_HEADER; LOG_DATETIME; LOG_TIMESTAMP; PROC_TIME_US; DL_ACHIEVED_RATE_KBPS; UL_ACHIEVED_RATE_KBPS; DL_LOAD_PERCENT; UL_LOAD_PERCENT; ICMP_TIMESTAMP; REFLECTOR; SEQUENCE; DL_OWD_BASELINE; DL_OWD_US; DL_OWD_DELTA_EWMA_US; DL_OWD_DELTA_US; DL_ADJ_DELAY_THR; UL_OWD_BASELINE; UL_OWD_US; UL_OWD_DELTA_EWMA_US; UL_OWD_DELTA_US; UL_ADJ_DELAY_THR; DL_SUM_DELAYS; DL_AVG_OWD_DELTA_US; DL_ADJ_MAX_ADJUST_UP_THR_US; DL_ADJ_MAX_ADJUST_DOWN_THR_US; UL_SUM_DELAYS; UL_AVG_OWD_DELTA_US; UL_ADJ_MAX_ADJUST_UP_THR_US; UL_ADJ_MAX_ADJUST_DOWN_THR_US; DL_LOAD_CONDITION; UL_LOAD_CONDITION; CAKE_DL_RATE_KBPS; CAKE_UL_RATE_KBPS"
((log_to_file)) && printf '%s\n' "${header}" >&${log_file_fd}
((terminal)) && printf '%s\n' "${header}"
fi
if ((output_load_stats))
then
header="LOAD_HEADER; LOG_DATETIME; LOG_TIMESTAMP; PROC_TIME_US; DL_ACHIEVED_RATE_KBPS; UL_ACHIEVED_RATE_KBPS; CAKE_DL_RATE_KBPS; CAKE_UL_RATE_KBPS"
((log_to_file)) && printf '%s\n' "${header}" >&${log_file_fd}
((terminal)) && printf '%s\n' "${header}"
fi
if ((output_reflector_stats))
then
header="REFLECTOR_HEADER; LOG_DATETIME; LOG_TIMESTAMP; PROC_TIME_US; REFLECTOR; MIN_SUM_OWD_BASELINES_US; SUM_OWD_BASELINES_US; SUM_OWD_BASELINES_DELTA_US; SUM_OWD_BASELINES_DELTA_THR_US; MIN_DL_DELTA_EWMA_US; DL_DELTA_EWMA_US; DL_DELTA_EWMA_DELTA_US; DL_DELTA_EWMA_DELTA_THR; MIN_UL_DELTA_EWMA_US; UL_DELTA_EWMA_US; UL_DELTA_EWMA_DELTA_US; UL_DELTA_EWMA_DELTA_THR"
((log_to_file)) && printf '%s\n' "${header}" >&${log_file_fd}
((terminal)) && printf '%s\n' "${header}"
fi
if ((output_summary_stats))
then
header="SUMMARY_HEADER; LOG_DATETIME; LOG_TIMESTAMP; DL_ACHIEVED_RATE_KBPS; UL_ACHIEVED_RATE_KBPS; DL_SUM_DELAYS; UL_SUM_DELAYS; DL_AVG_OWD_DELTA_US; UL_AVG_OWD_DELTA_US; DL_LOAD_CONDITION; UL_LOAD_CONDITION; CAKE_DL_RATE_KBPS; CAKE_UL_RATE_KBPS"
((log_to_file)) && printf '%s\n' "${header}" >&${log_file_fd}
((terminal)) && printf '%s\n' "${header}"
fi
if ((output_cpu_stats))
then
header="CPU_HEADER; LOG_DATETIME; LOG_TIMESTAMP; STATS_READ_TIME; ${cpu_ids// /_USAGE; }_USAGE"
((log_to_file)) && printf '%s\n' "${header}" >&${log_file_fd}
((terminal)) && printf '%s\n' "${header}"
fi
if ((output_cpu_raw_stats))
then
header="CPU_RAW_HEADER; LOG_DATETIME; LOG_TIMESTAMP; STATS_READ_TIME; CPU_ID; USER; NICE; SYSTEM; IDLE; IOWAIT; IRQ; SIRQ; STEAL; GUEST; GUEST_NICE"
((log_to_file)) && printf '%s\n' "${header}" >&${log_file_fd}
((terminal)) && printf '%s\n' "${header}"
fi
}
# MAINTAIN_LOG_FILE + HELPER FUNCTIONS
rotate_log_file()
{
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
[[ -f ${log_file_path} ]] || return
cat "${log_file_path}" > "${log_file_path}.old"
: > "${log_file_path}"
}
reset_log_file()
{
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
rm -f "${log_file_path}.old"
: > "${log_file_path}"
}
generate_log_file_scripts()
{
cat > "${run_path}/log_file_export" <<- EOT
#!${BASH}
timeout_s=\${1:-20}
if kill -USR1 "${proc_pids['maintain_log_file']}"
then
printf "Successfully signalled maintain_log_file process to request log file export.\n"
else
printf "ERROR: Failed to signal maintain_log_file process.\n" >&2
exit 1
fi
rm -f "${run_path}/last_log_file_export"
read_try=0
while [[ ! -f "${run_path}/last_log_file_export" ]]
do
sleep 1
if (( ++read_try >= \${timeout_s} ))
then
printf "ERROR: Timeout (\${timeout_s}s) reached before new log file export identified.\n" >&2
exit 1
fi
done
read -r log_file_export_path < "${run_path}/last_log_file_export"
printf "Log file export complete.\n"
printf "Log file available at location: "
printf "\${log_file_export_path}\n"
EOT
cat > "${run_path}/log_file_reset" <<- EOT
#!${BASH}
if kill -USR2 "${proc_pids['maintain_log_file']}"
then
printf "Successfully signalled maintain_log_file process to request log file reset.\n"
else
printf "ERROR: Failed to signal maintain_log_file process.\n" >&2
exit 1
fi
EOT
chmod +x "${run_path}/log_file_export" "${run_path}/log_file_reset"
}
export_log_file()
{
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
printf -v log_file_export_datetime '%(%Y_%m_%d_%H_%M_%S)T'
log_file_export_path="${log_file_path/.log/_${log_file_export_datetime}.log}"
log_msg "DEBUG" "Exporting log file with path: ${log_file_path/.log/_${log_file_export_datetime}.log}"
flush_log_pipe
# Now export with or without compression to the appropriate export path
if ((log_file_export_compress))
then
log_file_export_path="${log_file_export_path}.gz"
export_cmd=("gzip" "-c")
else
export_cmd=("cat")
fi
if [[ -f ${log_file_path}.old ]]
then
"${export_cmd[@]}" "${log_file_path}.old" > "${log_file_export_path}"
"${export_cmd[@]}" "${log_file_path}" >> "${log_file_export_path}"
else
"${export_cmd[@]}" "${log_file_path}" > "${log_file_export_path}"
fi
printf '%s' "${log_file_export_path}" > "${run_path}/last_log_file_export"
}
flush_log_pipe()
{
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
while read -r -t 0 -u "${log_fd}"
do
read -r -u "${log_fd}" log_line
printf '%s\n' "${log_line}" >&${log_file_fd}
((log_file_size_bytes+=${#log_line}))
done
}
maintain_log_file()
{
signal=""
trap '' INT
trap 'signal+=KILL' TERM EXIT
trap 'signal+=EXPORT' USR1
trap 'signal+=RESET' USR2
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
printf -v log_file_buffer_timeout_s %.1f "${log_file_buffer_timeout_ms}e-3"
while :
do
exec {log_file_fd}> "${log_file_path}"
print_headers
log_file_size_bytes=$(wc -c "${log_file_path}" 2>/dev/null | awk '{print $1}')
log_file_size_bytes=${log_file_size_bytes:-0}
t_log_file_start_s=${SECONDS}
while :
do
read -r -N "${log_file_buffer_size_B}" -t "${log_file_buffer_timeout_s}" -u "${log_fd}" log_chunk
printf '%s' "${log_chunk}" >&${log_file_fd}
((log_file_size_bytes+=${#log_chunk}))
# Verify log file time < configured maximum
if (( SECONDS - t_log_file_start_s > log_file_max_time_s ))
then
log_msg "DEBUG" "log file maximum time: ${log_file_max_time_mins} minutes has elapsed so flushing and rotating log file."
flush_log_pipe
rotate_log_file
break
# Verify log file size < configured maximum
elif (( log_file_size_bytes > log_file_max_size_bytes ))
then
((log_file_size_KB=log_file_size_bytes/1024))
log_msg "DEBUG" "log file size: ${log_file_size_KB} KB has exceeded configured maximum: ${log_file_max_size_KB} KB so flushing and rotating log file."
flush_log_pipe
rotate_log_file
break
fi
# Check for signals
case ${signal-} in
"")
;;
*KILL*)
log_msg "DEBUG" "received log file kill signal so flushing log and exiting."
flush_log_pipe
trap - TERM EXIT
exit
;;
*EXPORT*)
log_msg "DEBUG" "received log file export signal so exporting log file."
export_log_file
signal="${signal//EXPORT}"
;;
*RESET*)
log_msg "DEBUG" "received log file reset signal so flushing log and resetting log file."
flush_log_pipe
reset_log_file
signal="${signal//RESET}"
break
;;
*)
signal=""
log_msg "ERROR" "processed unknown signal(s): ${signal}."
;;
esac
done
exec {log_file_fd}>&-
done
}
export_proc_pids()
{
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
: > "${run_path}/proc_pids"
for proc_pid in "${!proc_pids[@]}"
do
printf "%s=%s\n" "${proc_pid}" "${proc_pids[${proc_pid}]}" >> "${run_path}/proc_pids"
done
}
monitor_achieved_rates()
{
trap '' INT
# track rx and tx bytes transfered and divide by time since last update
# to determine achieved dl and ul transfer rates
local rx_bytes_path=${1} tx_bytes_path=${2} monitor_achieved_rates_interval_us=${3}
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
compensated_monitor_achieved_rates_interval_us=${monitor_achieved_rates_interval_us}
{ read -r prev_rx_bytes < "${rx_bytes_path}"; } 2> /dev/null || prev_rx_bytes=0
{ read -r prev_tx_bytes < "${tx_bytes_path}"; } 2> /dev/null || prev_tx_bytes=0
sleep_duration_s=0 t_start_us=0
declare -A achieved_rate_kbps load_percent
while :
do
t_start_us=${EPOCHREALTIME/.}
# read in rx/tx bytes file, and if this fails then set to prev_bytes
# this addresses interfaces going down and back up
{ read -r rx_bytes < "${rx_bytes_path}"; } 2> /dev/null || rx_bytes=${prev_rx_bytes}
{ read -r tx_bytes < "${tx_bytes_path}"; } 2> /dev/null || tx_bytes=${prev_tx_bytes}
((
achieved_rate_kbps[dl] = 8000*(rx_bytes - prev_rx_bytes) / compensated_monitor_achieved_rates_interval_us,
achieved_rate_kbps[ul] = 8000*(tx_bytes - prev_tx_bytes) / compensated_monitor_achieved_rates_interval_us,
achieved_rate_kbps[dl]<0 && (achieved_rate_kbps[dl]=0),
achieved_rate_kbps[ul]<0 && (achieved_rate_kbps[ul]=0),
prev_rx_bytes=rx_bytes,
prev_tx_bytes=tx_bytes,
compensated_monitor_achieved_rates_interval_us = monitor_achieved_rates_interval_us>(10*max_wire_packet_rtt_us) ? monitor_achieved_rates_interval_us : 10*max_wire_packet_rtt_us
))
printf "SARS %s %s\n" "${achieved_rate_kbps[dl]}" "${achieved_rate_kbps[ul]}" >&${main_fd}
sleep_remaining_tick_time "${t_start_us}" "${compensated_monitor_achieved_rates_interval_us}"
done
}
# GENERIC PINGER START AND STOP FUNCTIONS
start_pinger()
{
local pinger=${1}
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
case ${pinger_binary} in
tsping)
# accommodate present tsping interval/sleep handling to prevent ping flood with only one pinger
(( tsping_sleep_time = no_pingers == 1 ? ping_response_interval_ms : 0 ))
${ping_prefix_string} tsping ${ping_extra_args} --print-timestamps --machine-readable=, --sleep-time "${tsping_sleep_time}" --target-spacing "${ping_response_interval_ms}" "${reflectors[@]:0:${no_pingers}}" 2>/dev/null >&"${main_fd}" &
pinger_pids[0]=${!}
proc_pids['tsping_pinger']=${pinger_pids[0]}
;;
fping)
${ping_prefix_string} fping ${ping_extra_args} --timestamp --loop --period "${reflector_ping_interval_ms}" --interval "${ping_response_interval_ms}" --timeout 10000 "${reflectors[@]:0:${no_pingers}}" 2> /dev/null >&"${main_fd}" &
pinger_pids[0]=${!}
proc_pids['fping_pinger']=${pinger_pids[0]}
;;
ping)
sleep_until_next_pinger_time_slot "${pinger}"
${ping_prefix_string} ping ${ping_extra_args} -D -i "${reflector_ping_interval_s}" "${reflectors[pinger]}" 2> /dev/null >&"${main_fd}" &
pinger_pids[pinger]=${!}
proc_pids["ping_${pinger}_pinger"]=${pinger_pids[0]}
;;
*)
log_msg "ERROR" "Unknown pinger binary: ${pinger_binary}"
kill $$ 2>/dev/null
;;
esac
export_proc_pids
}
start_pingers()
{
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
((pingers_active)) && return
case ${pinger_binary} in
tsping|fping)
start_pinger 0
;;
ping)
for ((pinger=0; pinger < no_pingers; pinger++))
do
start_pinger "${pinger}"
done
;;
*)
log_msg "ERROR" "Unknown pinger binary: ${pinger_binary}"
kill $$ 2>/dev/null
;;
esac
pingers_active=1
}
sleep_until_next_pinger_time_slot()
{
# wait until next pinger time slot and start pinger in its slot
# this allows pingers to be stopped and started (e.g. during sleep or reflector rotation)
# whilst ensuring pings will remain spaced out appropriately to maintain granularity
local pinger=${1}
t_start_us=${EPOCHREALTIME/.}
(( time_to_next_time_slot_us = (reflector_ping_interval_us-(t_start_us-pingers_t_start_us)%reflector_ping_interval_us) + pinger*ping_response_interval_us ))
sleep_remaining_tick_time "${t_start_us}" "${time_to_next_time_slot_us}"
}
kill_pinger()
{
local pinger=${1}
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
case ${pinger_binary} in
tsping|fping)
pinger=0
;;
*)
;;
esac
terminate "${pinger_pids[pinger]}"
}
stop_pingers()
{
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
((pingers_active)) || return
case ${pinger_binary} in
tsping|fping)
log_msg "DEBUG" "Killing ${pinger_binary} instance."
kill_pinger 0
;;
ping)
for (( pinger=0; pinger < no_pingers; pinger++))
do
log_msg "DEBUG" "Killing pinger instance: ${pinger}"
kill_pinger "${pinger}"
done
;;
*)
log_msg "ERROR" "Unknown pinger binary: ${pinger_binary}"
kill $$ 2>/dev/null
;;
esac
pingers_active=0
}
replace_pinger_reflector()
{
# pingers always use reflectors[0]..[no_pingers-1] as the initial set
# and the additional reflectors are spare reflectors should any from initial set go stale
# a bad reflector in the initial set is replaced with ${reflectors[no_pingers]}
# ${reflectors[no_pingers]} is then unset
# and the the bad reflector moved to the back of the queue (last element in ${reflectors[]})
# and finally the indices for ${reflectors} are updated to reflect the new order
local pinger=${1}
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
if ((no_reflectors > no_pingers))
then
log_msg "DEBUG" "replacing reflector: ${reflectors[pinger]} with ${reflectors[no_pingers]}."
kill_pinger "${pinger}"
bad_reflector=${reflectors[pinger]}
# overwrite the bad reflector with the reflector that is next in the queue (the one after 0..${no_pingers}-1)
reflectors[pinger]=${reflectors[no_pingers]}
# remove the new reflector from the list of additional reflectors beginning from ${reflectors[no_pingers]}
unset "reflectors[no_pingers]"
# bad reflector goes to the back of the queue
# shellcheck disable=SC2206
reflectors+=(${bad_reflector})
# reset array indices
mapfile -t reflectors < <(for i in "${reflectors[@]}"; do printf '%s\n' "${i}"; done)
# set up the new pinger with the new reflector and retain pid
dl_owd_baselines_us[${reflectors[pinger]}]=${dl_owd_baselines_us[${reflectors[pinger]}]:-100000} \
ul_owd_baselines_us[${reflectors[pinger]}]=${ul_owd_baselines_us[${reflectors[pinger]}]:-100000} \
dl_owd_delta_ewmas_us[${reflectors[pinger]}]=${dl_owd_delta_ewmas_us[${reflectors[pinger]}]:-0} \
ul_owd_delta_ewmas_us[${reflectors[pinger]}]=${ul_owd_delta_ewmas_us[${reflectors[pinger]}]:-0} \
last_timestamp_reflectors_us[${reflectors[pinger]}]=${t_start_us}
start_pinger "${pinger}"
else
log_msg "DEBUG" "No additional reflectors specified so just retaining: ${reflectors[pinger]}."
fi
log_msg "DEBUG" "Resetting reflector offences associated with reflector: ${reflectors[pinger]}."
declare -n reflector_offences="reflector_${pinger}_offences"
for ((i=0; i<reflector_misbehaving_detection_window; i++)) do reflector_offences[i]=0; done
sum_reflector_offences[pinger]=0
}
# END OF GENERIC PINGER START AND STOP FUNCTIONS
set_shaper_rate()
{
# Fire up tc and update max_wire_packet_compensation if there are rates to change for the given direction
local direction=${1} # 'dl' or 'ul'
(( shaper_rate_kbps[${direction}] != last_shaper_rate_kbps[${direction}] )) || return
((output_cake_changes)) && log_msg "SHAPER" "tc qdisc change root dev ${interface[${direction}]} cake bandwidth ${shaper_rate_kbps[${direction}]}Kbit"
if ((adjust_shaper_rate[${direction}]))
then
tc qdisc change root dev "${interface[${direction}]}" cake bandwidth "${shaper_rate_kbps[${direction}]}Kbit" 2> /dev/null
else
((output_cake_changes)) && log_msg "DEBUG" "adjust_${direction}_shaper_rate set to 0 in config, so skipping the corresponding tc qdisc change call."
fi
# Compensate for delays imposed by active traffic shaper
# This will serve to increase the delay thr at rates below around 12Mbit/s
((
dl_compensation_us=(1000*dl_max_wire_packet_size_bits)/shaper_rate_kbps[dl],
ul_compensation_us=(1000*ul_max_wire_packet_size_bits)/shaper_rate_kbps[ul],
compensated_avg_owd_delta_max_adjust_up_thr_us[dl]=dl_avg_owd_delta_max_adjust_up_thr_us + dl_compensation_us,
compensated_avg_owd_delta_max_adjust_up_thr_us[ul]=ul_avg_owd_delta_max_adjust_up_thr_us + ul_compensation_us,
compensated_owd_delta_delay_thr_us[dl]=dl_owd_delta_delay_thr_us + dl_compensation_us,
compensated_owd_delta_delay_thr_us[ul]=ul_owd_delta_delay_thr_us + ul_compensation_us,
compensated_avg_owd_delta_max_adjust_down_thr_us[dl]=dl_avg_owd_delta_max_adjust_down_thr_us + dl_compensation_us,
compensated_avg_owd_delta_max_adjust_down_thr_us[ul]=ul_avg_owd_delta_max_adjust_down_thr_us + ul_compensation_us,
max_wire_packet_rtt_us=(1000*dl_max_wire_packet_size_bits)/shaper_rate_kbps[dl] + (1000*ul_max_wire_packet_size_bits)/shaper_rate_kbps[ul],
last_shaper_rate_kbps[${direction}]=${shaper_rate_kbps[${direction}]}
))
}
get_max_wire_packet_size_bits()
{
local interface=${1}
local -n max_wire_packet_size_bits=${2}
read -r max_wire_packet_size_bits < "/sys/class/net/${interface:?}/mtu"
[[ $(tc qdisc show dev "${interface}") =~ (atm|noatm)[[:space:]]overhead[[:space:]]([0-9]+) ]]
(( max_wire_packet_size_bits=8*(max_wire_packet_size_bits+BASH_REMATCH[2]) ))
# atm compensation = 53*ceil(X/48) bytes = 8*53*((X+8*(48-1)/(8*48)) bits = 424*((X+376)/384) bits
[[ ${BASH_REMATCH[1]:-} == "atm" ]] && (( max_wire_packet_size_bits=424*((max_wire_packet_size_bits+376)/384) ))
}
verify_ifs_up()
{
# Check the rx/tx paths exist and give extra time for ifb's to come up if needed
# This will block if ifs never come up
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
while [[ ! -f ${rx_bytes_path} || ! -f ${tx_bytes_path} ]]
do
[[ -f ${rx_bytes_path} ]] || log_msg "DEBUG" "Warning: The configured download interface: '${dl_if}' does not appear to be present. Waiting ${if_up_check_interval_s} seconds for the interface to come up."
[[ -f ${tx_bytes_path} ]] || log_msg "DEBUG" "Warning: The configured upload interface: '${ul_if}' does not appear to be present. Waiting ${if_up_check_interval_s} seconds for the interface to come up."
sleep_s "${if_up_check_interval_s}"
done
}
change_state_main()
{
local main_next_state=${1}
log_msg "DEBUG" "Starting: ${FUNCNAME[0]} with PID: ${BASHPID}"
case ${main_next_state} in
${main_state})
log_msg "ERROR" "Received request to change main state to existing state."
;;
RUNNING|IDLE|STALL)
log_msg "DEBUG" "Changing main state from: ${main_state} to: ${main_next_state}"
main_state=${main_next_state}
;;
*)
log_msg "ERROR" "Received unrecognized main state change request: ${main_next_state}. Exiting now."
kill $$ 2>/dev/null
;;
esac
}
intercept_stderr()
{
# send stderr to log_msg and exit cake-autorate
# use with redirection: exec 2> >(intercept_stderr)
while read -r error
do
log_msg "ERROR" "${error}"
kill $$ 2>/dev/null
done
}
# shellcheck disable=SC1090,SC2311
validate_config_entry() {
# Must be called before loading config_path into the global scope.
#
# When the entry is invalid, two types are returned with the first type
# being the invalid user type and second type is the default type with
# the user needing to adapt the config file so that the entry uses the
# default type.
#
# When the entry is valid, one type is returned and it will be the
# the type of either the default or user type. However because in that
# case they are both valid. It doesn't matter as they'd both have the
# same type.
local config_path=${1}
local user_type
local valid_type
user_type=$(unset "${2}" && . "${config_path}" && typeof "${2}")
valid_type=$(typeof "${2}")
if [[ ${user_type} != "${valid_type}" ]]
then
printf '%s' "${user_type} ${valid_type}"
return
elif [[ ${user_type} != "string" ]]
then
printf '%s' "${valid_type}"
return
fi
# extra validation for string, check for empty string
local -n default_value=${2}
local user_value
user_value=$(. "${config_path}" && local -n x="${2}" && printf '%s' "${x}")
# if user is empty but default is not, invalid entry
if [[ -z ${user_value} && -n ${default_value} ]]
then
printf '%s' "${user_type} ${valid_type}"
else
printf '%s' "${valid_type}"
fi
}
# ======= Start of the Main Routine ========
[[ -t 1 ]] && terminal=1 || terminal=0
type logger &> /dev/null && use_logger=1 || use_logger=0 # only perform the test once.
log_file_path=/var/log/cake-autorate.log
# *** WARNING: take great care if attempting to alter the run_path! ***
# *** cake-autorate issues mkdir -p ${run_path} and rm -r ${run_path} on exit. ***
run_path=/var/run/cake-autorate/
# cake-autorate first argument is config file path
if [[ -n ${1-} ]]
then
config_path="${1}"
else
config_path="${CONFIG_PREFIX}/config.primary.sh"
fi
if [[ ! -f ${config_path} ]]
then
log_msg "ERROR" "No config file found. Exiting now."
exit 1
fi
# validate config entries before loading
mapfile -t user_config < <(grep -E '^[^(#| )].*=' "${config_path}" | sed -e 's/[\t ]*\#.*//g' -e 's/=.*//g')
config_error_count=0
for key in "${user_config[@]}"
do
# Despite the fact that config_file_check is no longer required,
# we make an exemption just in this case as that variable in
# particular does not have any real impact to the operation
# of the script.
[[ ${key} == "config_file_check" ]] && continue
# shellcheck disable=SC2076
if [[ ! " ${valid_config_entries[*]} " =~ " ${key} " ]]
then
((config_error_count++))
log_msg "ERROR" "The key: '${key}' in config file: '${config_path}' is not a valid config entry."
else
# shellcheck disable=SC2311
read -r user supposed <<< "$(validate_config_entry "${config_path}" "${key}")"
if [[ -n "${supposed}" ]]
then
error_msg="The value of '${key}' in config file: '${config_path}' is not a valid value of type: '${supposed}'."
case ${user} in
negative-*) error_msg="${error_msg} Also, negative numbers are not supported." ;;
*) ;;
esac
log_msg "ERROR" "${error_msg}"
unset error_msg
((config_error_count++))
fi
unset user supposed
fi
done
if ((config_error_count))
then
log_msg "ERROR" "The config file: '${config_path}' contains ${config_error_count} error(s). Exiting now."
exit 1
fi
unset valid_config_entries user_config config_error_count key
# shellcheck source=config.primary.sh
. "${config_path}"
if [[ ${config_path} =~ config\.(.*)\.sh ]]
then
instance_id=${BASH_REMATCH[1]} run_path="/var/run/cake-autorate/${instance_id}"
else
log_msg "ERROR" "Instance identifier 'X' set by config.X.sh cannot be empty. Exiting now."
exit 1
fi
if [[ -n ${log_file_path_override-} ]]
then
if [[ ! -d ${log_file_path_override} ]]
then
broken_log_file_path_override="${log_file_path_override}"
log_file_path="/var/log/cake-autorate${instance_id:+.${instance_id}}.log"
log_msg "ERROR" "Log file path override: '${broken_log_file_path_override}' does not exist. Exiting now."
exit 1
fi
log_file_path="${log_file_path_override}/cake-autorate${instance_id:+.${instance_id}}.log"
else
log_file_path="/var/log/cake-autorate${instance_id:+.${instance_id}}.log"
fi
rotate_log_file
# save stderr fd, redirect stderr to intercept_stderr
# intercept_stderr sends stderr to log_msg and exits cake-autorate
exec {original_stderr_fd}>&2 2> >(intercept_stderr)
proc_pids['intercept_stderr']=${!}
log_msg "SYSLOG" "Starting cake-autorate with PID: ${BASHPID} and config: ${config_path}"
# ${run_path}/ is used to store temporary files
# it should not exist on startup so if it does exit, else create the directory
if [[ -d ${run_path} ]]
then
if [[ -f ${run_path}/proc_pids ]] && running_main_pid=$(awk -F= '/^main=/ {print $2}' "${run_path}/proc_pids") && [[ -d /proc/${running_main_pid} ]]
then
log_msg "ERROR" "${run_path} already exists and an instance appears to be running with main process pid ${running_main_pid}. Exiting script."
trap - INT TERM EXIT
exit 1
else
log_msg "DEBUG" "${run_path} already exists but no instance is running. Removing and recreating."
rm -r "${run_path}"
mkdir -p "${run_path}"
fi
else
mkdir -p "${run_path}"
fi
proc_pids['main']=${BASHPID}
no_reflectors=${#reflectors[@]}
# Check ping binary exists
command -v "${pinger_binary}" &> /dev/null || { log_msg "ERROR" "ping binary ${pinger_binary} does not exist. Exiting script."; exit 1; }
# Check no_pingers <= no_reflectors
(( no_pingers > no_reflectors )) && { log_msg "ERROR" "number of pingers cannot be greater than number of reflectors. Exiting script."; exit 1; }
# Check dl/if interface not the same
[[ "${dl_if}" == "${ul_if}" ]] && { log_msg "ERROR" "download interface and upload interface are both set to: '${dl_if}', but cannot be the same. Exiting script."; exit 1; }
# Check bufferbloat detection threshold not greater than window length
(( bufferbloat_detection_thr > bufferbloat_detection_window )) && { log_msg "ERROR" "bufferbloat_detection_thr cannot be greater than bufferbloat_detection_window. Exiting script."; exit 1; }
# Check if connection_active_thr_kbps is greater than min dl/ul shaper rate
(( connection_active_thr_kbps > min_dl_shaper_rate_kbps )) && { log_msg "ERROR" "connection_active_thr_kbps cannot be greater than min_dl_shaper_rate_kbps. Exiting script."; exit 1; }
(( connection_active_thr_kbps > min_ul_shaper_rate_kbps )) && { log_msg "ERROR" "connection_active_thr_kbps cannot be greater than min_ul_shaper_rate_kbps. Exiting script."; exit 1; }
# Passed error checks
cpu_idx=0
while :
do
read -r cpu_id rem
case ${cpu_id} in
cpu*)
cpu_ids[cpu_idx]=${cpu_id^^}
((cpu_idx++))
;;
*)
break
;;
esac
done</proc/stat
cpu_ids="${cpu_ids[@]}"
((cpu_cores=cpu_idx-1))
log_msg "DEBUG" "Detected ${cpu_cores} CPU cores."
mapfile -t cpu_usage < <(for ((i=0; i <= cpu_cores; i++)); do echo 0; done)
mapfile -t last_cpu_sum < <(for ((i=0; i <= cpu_cores; i++)); do echo 0; done)
mapfile -t last_cpu_idle < <(for ((i=0; i <= cpu_cores; i++)); do echo 0; done)
if ((log_to_file))
then
((
log_file_max_time_s=log_file_max_time_mins*60,
log_file_max_size_bytes=log_file_max_size_KB*1024
))
exec {log_fd}<> <(:)
maintain_log_file &
proc_pids['maintain_log_file']=${!}
fi
# test if stdout is a tty (terminal)
if ! ((terminal))
then
echo "stdout not a terminal so redirecting output to: ${log_file_path}"
((log_to_file)) && exec 1>&${log_fd}
fi
# Initialize rx_bytes_path and tx_bytes_path if not set
if [[ -z ${rx_bytes_path-} ]]
then
case ${dl_if} in
veth*)
rx_bytes_path="/sys/class/net/${dl_if}/statistics/tx_bytes"
;;
ifb*)
rx_bytes_path="/sys/class/net/${dl_if}/statistics/tx_bytes"
;;
*)
rx_bytes_path="/sys/class/net/${dl_if}/statistics/tx_bytes"
;;
esac
fi
if [[ -z ${tx_bytes_path-} ]]
then