chrony-network-stats.sh 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. #!/bin/bash
  2. set -e
  3. ####################### Configuration ######################
  4. ENABLE_NETWORK_STATS="yes" ## Enable or disable network statistics generation using vnStat
  5. INTERFACE="eth0" ## Network interface to monitor (e.g., eth0, wlan0)
  6. PAGE_TITLE="Network Traffic and Chrony Statistics for ${INTERFACE}"
  7. OUTPUT_DIR="/var/www/html/" ## Output directory for HTML and images
  8. HTML_FILENAME="index.html" ## Output HTML file name
  9. RRD_DIR="/var/lib/chrony-rrd"
  10. RRD_FILE="$RRD_DIR/chrony.rrd" ## RRD file for storing chrony statistics
  11. ENABLE_LOGGING="yes"
  12. LOG_FILE="/var/log/chrony-network-stats.log"
  13. # In-script log truncation (prevents logfile from growing indefinitely)
  14. # - LOG_MAX_SIZE_BYTES: when >0 use byte-based truncation (default 10MB)
  15. # - LOG_MAX_LINES: when >0 use line-based truncation instead of bytes
  16. # - LOG_TRIM_TO_BYTES / LOG_TRIM_TO_LINES: amount to keep when trimming (defaults to half)
  17. LOG_MAX_SIZE_BYTES=0 # $((10 * 1024 * 1024)) # 10 MB
  18. LOG_MAX_LINES=10000
  19. LOG_TRIM_TO_BYTES=0 # $((LOG_MAX_SIZE_BYTES / 2))
  20. LOG_TRIM_TO_LINES=9000
  21. AUTO_REFRESH_SECONDS=0 ## Auto-refresh interval in seconds (0 = disabled, e.g., 300 for 5 minutes)
  22. GITHUB_REPO_LINK_SHOW="no" ## You can display the link to the repo 'chrony-stats' in the HTML footer | Not required | Default: no
  23. ###### Advanced Configuration ######
  24. CHRONY_ALLOW_DNS_LOOKUP="yes" ## Yes allow DNS reverse lookups. No to prevent slow DNS reverse lookups
  25. DISPLAY_PRESET="default" # Preset for large screens. Options: default | 2k | 4k
  26. TIMEOUT_SECONDS=5
  27. SERVER_STATS_UPPER_LIMIT=100000 ## When chrony restarts, it generate abnormally high values (e.g., 12M) | This filters out values above the threshold
  28. ##############################################################
  29. WIDTH=800 ## These graph sizes are changing with DISPLAY_PRESET
  30. HEIGHT=300 ##
  31. log_message() {
  32. local level="$1"
  33. local message="$2"
  34. if [[ "$ENABLE_LOGGING" == "yes" ]]; then
  35. # ensure logfile stays within configured limits before writing
  36. rotate_logfile_if_needed
  37. printf '[%s] [%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$level" "$message" >> "$LOG_FILE"
  38. fi
  39. echo "[$level] $message"
  40. }
  41. rotate_logfile_if_needed() {
  42. # no-op when logging disabled or logfile missing
  43. [ "$ENABLE_LOGGING" != "yes" ] && return 0
  44. [ -f "$LOG_FILE" ] || return 0
  45. # Line-based truncation (preferred when configured)
  46. if [[ "${LOG_MAX_LINES:-0}" -gt 0 ]]; then
  47. local total_lines
  48. total_lines=$(wc -l < "$LOG_FILE" 2>/dev/null || echo 0)
  49. if [[ "$total_lines" -gt "$LOG_MAX_LINES" ]]; then
  50. local keep_lines=${LOG_TRIM_TO_LINES:-$(( LOG_MAX_LINES / 2 ))}
  51. (( keep_lines <= 0 )) && keep_lines=$(( LOG_MAX_LINES / 2 ))
  52. tail -n "$keep_lines" "$LOG_FILE" > "${LOG_FILE}.tmp" && mv "${LOG_FILE}.tmp" "$LOG_FILE"
  53. printf '[%s] [INFO] Log truncated to last %d lines (was %d lines)\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$keep_lines" "$total_lines" >> "$LOG_FILE"
  54. fi
  55. return 0
  56. fi
  57. # Size-based truncation (bytes)
  58. local max_bytes=${LOG_MAX_SIZE_BYTES:-10485760}
  59. local filesize
  60. if ! filesize=$(stat -c%s "$LOG_FILE" 2>/dev/null); then
  61. filesize=$(wc -c < "$LOG_FILE" 2>/dev/null || echo 0)
  62. fi
  63. if [[ "$filesize" -ge "$max_bytes" ]]; then
  64. local keep_bytes=${LOG_TRIM_TO_BYTES:-$(( max_bytes / 2 ))}
  65. (( keep_bytes <= 0 )) && keep_bytes=$(( max_bytes / 2 ))
  66. tail -c "$keep_bytes" "$LOG_FILE" > "${LOG_FILE}.tmp" && mv "${LOG_FILE}.tmp" "$LOG_FILE"
  67. printf '[%s] [INFO] Log truncated to last %d bytes (was %d bytes)\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$keep_bytes" "$filesize" >> "$LOG_FILE"
  68. fi
  69. }
  70. configure_display_preset() {
  71. local preset="${DISPLAY_PRESET,,}"
  72. local scale_pct=100
  73. local container_px=1400
  74. local font_px=16
  75. case "$preset" in
  76. 1080p|1080|default)
  77. scale_pct=100; container_px=1400; font_px=16 ;;
  78. 2k|1440p|qhd)
  79. scale_pct=135; container_px=2000; font_px=18 ;;
  80. 4k|2160p|uhd)
  81. scale_pct=170; container_px=2600; font_px=20 ;;
  82. *)
  83. scale_pct=100; container_px=1400; font_px=16 ;;
  84. esac
  85. WIDTH=$(( WIDTH * scale_pct / 100 ))
  86. HEIGHT=$(( HEIGHT * scale_pct / 100 ))
  87. CSS_CUSTOM_ROOT=$(cat <<EOF
  88. :root {
  89. --container-max: ${container_px}px;
  90. --font-size-base: ${font_px}px;
  91. }
  92. EOF
  93. )
  94. log_message "INFO" "Preset '${DISPLAY_PRESET}' -> graph ${WIDTH}x${HEIGHT}, container ${container_px}px, font ${font_px}px"
  95. }
  96. validate_numeric() {
  97. local value="$1"
  98. local name="$2"
  99. if ! [[ "$value" =~ ^[0-9]+$ ]]; then
  100. log_message "ERROR" "Invalid $name: $value. Must be numeric."
  101. exit 1
  102. fi
  103. }
  104. check_commands() {
  105. local commands=("rrdtool" "chronyc" "sudo" "timeout")
  106. if [[ "$ENABLE_NETWORK_STATS" == "yes" ]]; then
  107. commands+=("vnstati")
  108. fi
  109. for cmd in "${commands[@]}"; do
  110. if ! command -v "$cmd" &>/dev/null; then
  111. log_message "ERROR" "Command '$cmd' not found in PATH."
  112. exit 1
  113. fi
  114. done
  115. }
  116. setup_directories() {
  117. log_message "INFO" "Checking and preparing directories..."
  118. for dir in "$OUTPUT_DIR" "$RRD_DIR" "$OUTPUT_DIR/img"; do
  119. mkdir -p "$dir" || {
  120. log_message "ERROR" "Failed to create directory: $dir"
  121. exit 1
  122. }
  123. if [ ! -w "$dir" ]; then
  124. log_message "ERROR" "Directory '$dir' is not writable."
  125. exit 1
  126. fi
  127. done
  128. }
  129. generate_vnstat_images() {
  130. if [[ "$ENABLE_NETWORK_STATS" != "yes" ]]; then
  131. log_message "INFO" "Network stats disabled, skipping vnStat image generation..."
  132. return 0
  133. fi
  134. log_message "INFO" "Generating vnStat images for interface '$INTERFACE'..."
  135. local modes=("s" "d" "t" "h" "m" "y")
  136. for mode in "${modes[@]}"; do
  137. vnstati -"$mode" -i "$INTERFACE" -o "$OUTPUT_DIR/img/vnstat_${mode}.png" || {
  138. log_message "ERROR" "Failed to generate vnstat image for mode $mode Check configuaration section : INTERFACE=\"here\""
  139. exit 1
  140. }
  141. done
  142. }
  143. collect_chrony_data() {
  144. log_message "INFO" "Collecting Chrony data..."
  145. local CHRONYC_OPTS=""
  146. if [[ "$CHRONY_ALLOW_DNS_LOOKUP" == "no" ]]; then
  147. CHRONYC_OPTS="-n"
  148. log_message "INFO" "Using chronyc -n option to prevent DNS lookups"
  149. fi
  150. get_html() {
  151. timeout "$TIMEOUT_SECONDS"s sudo chronyc $CHRONYC_OPTS "$1" -v 2>&1 | sed 's/&/\&amp;/g;s/</\&lt;/g;s/>/\&gt;/g' || {
  152. log_message "ERROR" "Failed to collect chronyc $1 data"
  153. return 1
  154. }
  155. }
  156. RAW_TRACKING=$(timeout "$TIMEOUT_SECONDS"s sudo chronyc $CHRONYC_OPTS tracking) || {
  157. log_message "ERROR" "Failed to collect chronyc tracking data"
  158. exit 1
  159. }
  160. CHRONYC_TRACKING_HTML=$(echo "$RAW_TRACKING" | sed 's/&/\&amp;/g;s/</\&lt;/g;s/>/\&gt;/g')
  161. CHRONYC_SOURCES=$(get_html sources) || exit 1
  162. CHRONYC_SOURCESTATS=$(get_html sourcestats) || exit 1
  163. CHRONYC_SELECTDATA=$(get_html selectdata) || exit 1
  164. }
  165. extract_chronyc_values() {
  166. extract_val() {
  167. echo "$RAW_TRACKING" | awk "/$1/ {print \$($2)}" | grep -E '^[-+]?[0-9.]+$' || echo "U"
  168. }
  169. OFFSET=$(extract_val "Last offset" "NF-1")
  170. local systime_line
  171. systime_line=$(echo "$RAW_TRACKING" | grep "System time")
  172. if [[ -n "$systime_line" ]]; then
  173. local value
  174. value=$(echo "$systime_line" | awk '{print $4}')
  175. if [[ "$systime_line" == *"slow"* ]]; then
  176. SYSTIME="-$value"
  177. else
  178. SYSTIME="$value"
  179. fi
  180. else
  181. SYSTIME="U"
  182. fi
  183. FREQ=$(extract_val "Frequency" "NF-2")
  184. RESID_FREQ=$(extract_val "Residual freq" "NF-1")
  185. SKEW=$(extract_val "Skew" "NF-1")
  186. DELAY=$(extract_val "Root delay" "NF-1")
  187. DISPERSION=$(extract_val "Root dispersion" "NF-1")
  188. STRATUM=$(extract_val "Stratum" "3")
  189. local CHRONYC_OPTS=""
  190. if [[ "$CHRONY_ALLOW_DNS_LOOKUP" == "no" ]]; then
  191. CHRONYC_OPTS="-n"
  192. fi
  193. RAW_STATS=$(LC_ALL=C sudo chronyc $CHRONYC_OPTS serverstats) || {
  194. log_message "ERROR" "Failed to collect chronyc serverstats"
  195. exit 1
  196. }
  197. get_stat() {
  198. echo "$RAW_STATS" | awk -F'[[:space:]]*:[[:space:]]*' "/$1/ {print \$2}" | grep -E '^[0-9]+$' || echo "U"
  199. }
  200. PKTS_RECV=$(get_stat "NTP packets received")
  201. PKTS_DROP=$(get_stat "NTP packets dropped")
  202. CMD_RECV=$(get_stat "Command packets received")
  203. CMD_DROP=$(get_stat "Command packets dropped")
  204. LOG_DROP=$(get_stat "Client log records dropped")
  205. NTS_KE_ACC=$(get_stat "NTS-KE connections accepted")
  206. NTS_KE_DROP=$(get_stat "NTS-KE connections dropped")
  207. AUTH_PKTS=$(get_stat "Authenticated NTP packets")
  208. INTERLEAVED=$(get_stat "Interleaved NTP packets")
  209. TS_HELD=$(get_stat "NTP timestamps held")
  210. }
  211. create_rrd_database() {
  212. if [ ! -f "$RRD_FILE" ]; then
  213. log_message "INFO" "Creating new RRD file: $RRD_FILE"
  214. LC_ALL=C rrdtool create "$RRD_FILE" --step 300 \
  215. DS:offset:GAUGE:600:U:U DS:frequency:GAUGE:600:U:U DS:resid_freq:GAUGE:600:U:U DS:skew:GAUGE:600:U:U \
  216. DS:delay:GAUGE:600:U:U DS:dispersion:GAUGE:600:U:U DS:stratum:GAUGE:600:0:16 \
  217. DS:systime:GAUGE:600:U:U \
  218. DS:pkts_recv:COUNTER:600:0:U DS:pkts_drop:COUNTER:600:0:U DS:cmd_recv:COUNTER:600:0:U \
  219. DS:cmd_drop:COUNTER:600:0:U DS:log_drop:COUNTER:600:0:U DS:nts_ke_acc:COUNTER:600:0:U \
  220. DS:nts_ke_drop:COUNTER:600:0:U DS:auth_pkts:COUNTER:600:0:U DS:interleaved:COUNTER:600:0:U \
  221. DS:ts_held:GAUGE:600:0:U \
  222. RRA:AVERAGE:0.5:1:576 RRA:AVERAGE:0.5:6:672 RRA:AVERAGE:0.5:24:732 RRA:AVERAGE:0.5:288:730 \
  223. RRA:MAX:0.5:1:576 RRA:MAX:0.5:6:672 RRA:MAX:0.5:24:732 RRA:MAX:0.5:288:730 \
  224. RRA:MIN:0.5:1:576 RRA:MIN:0.5:6:672 RRA:MIN:0.5:24:732 RRA:MIN:0.5:288:730 || {
  225. log_message "ERROR" "Failed to create RRD database"
  226. exit 1
  227. }
  228. fi
  229. }
  230. update_rrd_database() {
  231. log_message "INFO" "Updating RRD database..."
  232. UPDATE_STRING="N:$OFFSET:$FREQ:$RESID_FREQ:$SKEW:$DELAY:$DISPERSION:$STRATUM:$SYSTIME:$PKTS_RECV:$PKTS_DROP:$CMD_RECV:$CMD_DROP:$LOG_DROP:$NTS_KE_ACC:$NTS_KE_DROP:$AUTH_PKTS:$INTERLEAVED:$TS_HELD"
  233. LC_ALL=C rrdtool update "$RRD_FILE" "$UPDATE_STRING" || {
  234. log_message "ERROR" "Failed to update RRD database"
  235. exit 1
  236. }
  237. }
  238. generate_graphs() {
  239. log_message "INFO" "Generating graphs..."
  240. local END_TIME=$(date +%s)
  241. declare -A time_periods=(
  242. ["day"]="end-1d"
  243. ["week"]="end-1w"
  244. ["month"]="end-1m"
  245. )
  246. declare -A period_titles=(
  247. ["day"]="by day"
  248. ["week"]="by week"
  249. ["month"]="by month"
  250. )
  251. declare -A graphs=(
  252. ["chrony_serverstats"]="--title 'Chrony Server Statistics - PERIOD_TITLE' --vertical-label 'Packets/second' \
  253. --lower-limit 0 --rigid --units-exponent 0 \
  254. DEF:pkts_recv_raw='$RRD_FILE':pkts_recv:AVERAGE \
  255. DEF:pkts_drop_raw='$RRD_FILE':pkts_drop:AVERAGE \
  256. DEF:cmd_recv_raw='$RRD_FILE':cmd_recv:AVERAGE \
  257. DEF:cmd_drop_raw='$RRD_FILE':cmd_drop:AVERAGE \
  258. DEF:log_drop_raw='$RRD_FILE':log_drop:AVERAGE \
  259. DEF:nts_ke_acc_raw='$RRD_FILE':nts_ke_acc:AVERAGE \
  260. DEF:nts_ke_drop_raw='$RRD_FILE':nts_ke_drop:AVERAGE \
  261. DEF:auth_pkts_raw='$RRD_FILE':auth_pkts:AVERAGE \
  262. CDEF:pkts_recv=pkts_recv_raw,$SERVER_STATS_UPPER_LIMIT,GT,UNKN,pkts_recv_raw,IF \
  263. CDEF:pkts_drop=pkts_drop_raw,$SERVER_STATS_UPPER_LIMIT,GT,UNKN,pkts_drop_raw,IF \
  264. CDEF:cmd_recv=cmd_recv_raw,$SERVER_STATS_UPPER_LIMIT,GT,UNKN,cmd_recv_raw,IF \
  265. CDEF:cmd_drop=cmd_drop_raw,$SERVER_STATS_UPPER_LIMIT,GT,UNKN,cmd_drop_raw,IF \
  266. CDEF:log_drop=log_drop_raw,$SERVER_STATS_UPPER_LIMIT,GT,UNKN,log_drop_raw,IF \
  267. CDEF:nts_ke_acc=nts_ke_acc_raw,$SERVER_STATS_UPPER_LIMIT,GT,UNKN,nts_ke_acc_raw,IF \
  268. CDEF:nts_ke_drop=nts_ke_drop_raw,$SERVER_STATS_UPPER_LIMIT,GT,UNKN,nts_ke_drop_raw,IF \
  269. CDEF:auth_pkts=auth_pkts_raw,$SERVER_STATS_UPPER_LIMIT,GT,UNKN,auth_pkts_raw,IF \
  270. 'COMMENT: \l' \
  271. 'AREA:pkts_recv#C4FFC4:Packets received ' \
  272. 'LINE1:pkts_recv#00E000:' \
  273. 'GPRINT:pkts_recv:LAST:Cur\: %5.2lf%s' \
  274. 'GPRINT:pkts_recv:MIN:Min\: %5.2lf%s' \
  275. 'GPRINT:pkts_recv:AVERAGE:Avg\: %5.2lf%s' \
  276. 'GPRINT:pkts_recv:MAX:Max\: %5.2lf%s\l' \
  277. 'LINE1:pkts_drop#FF8C00:Packets dropped ' \
  278. 'GPRINT:pkts_drop:LAST:Cur\: %5.2lf%s' \
  279. 'GPRINT:pkts_drop:MIN:Min\: %5.2lf%s' \
  280. 'GPRINT:pkts_drop:AVERAGE:Avg\: %5.2lf%s' \
  281. 'GPRINT:pkts_drop:MAX:Max\: %5.2lf%s\l' \
  282. 'LINE1:cmd_recv#4169E1:Command packets received ' \
  283. 'GPRINT:cmd_recv:LAST:Cur\: %5.2lf%s' \
  284. 'GPRINT:cmd_recv:MIN:Min\: %5.2lf%s' \
  285. 'GPRINT:cmd_recv:AVERAGE:Avg\: %5.2lf%s' \
  286. 'GPRINT:cmd_recv:MAX:Max\: %5.2lf%s\l' \
  287. 'LINE1:cmd_drop#FFD700:Command packets dropped ' \
  288. 'GPRINT:cmd_drop:LAST:Cur\: %5.2lf%s' \
  289. 'GPRINT:cmd_drop:MIN:Min\: %5.2lf%s' \
  290. 'GPRINT:cmd_drop:AVERAGE:Avg\: %5.2lf%s' \
  291. 'GPRINT:cmd_drop:MAX:Max\: %5.2lf%s\l' \
  292. 'LINE1:log_drop#9400D3:Client log records dropped ' \
  293. 'GPRINT:log_drop:LAST:Cur\: %5.2lf%s' \
  294. 'GPRINT:log_drop:MIN:Min\: %5.2lf%s' \
  295. 'GPRINT:log_drop:AVERAGE:Avg\: %5.2lf%s' \
  296. 'GPRINT:log_drop:MAX:Max\: %5.2lf%s\l' \
  297. 'LINE1:nts_ke_acc#8A2BE2:NTS-KE connections accepted ' \
  298. 'GPRINT:nts_ke_acc:LAST:Cur\: %5.2lf%s' \
  299. 'GPRINT:nts_ke_acc:MIN:Min\: %5.2lf%s' \
  300. 'GPRINT:nts_ke_acc:AVERAGE:Avg\: %5.2lf%s' \
  301. 'GPRINT:nts_ke_acc:MAX:Max\: %5.2lf%s\l' \
  302. 'LINE1:nts_ke_drop#9370DB:NTS-KE connections dropped ' \
  303. 'GPRINT:nts_ke_drop:LAST:Cur\: %5.2lf%s' \
  304. 'GPRINT:nts_ke_drop:MIN:Min\: %5.2lf%s' \
  305. 'GPRINT:nts_ke_drop:AVERAGE:Avg\: %5.2lf%s' \
  306. 'GPRINT:nts_ke_drop:MAX:Max\: %5.2lf%s\l' \
  307. 'LINE1:auth_pkts#FF0000:Authenticated NTP packets ' \
  308. 'GPRINT:auth_pkts:LAST:Cur\: %5.2lf%s' \
  309. 'GPRINT:auth_pkts:MIN:Min\: %5.2lf%s' \
  310. 'GPRINT:auth_pkts:AVERAGE:Avg\: %5.2lf%s' \
  311. 'GPRINT:auth_pkts:MAX:Max\: %5.2lf%s\l'"
  312. ["chrony_tracking"]="--title 'Chrony Dispersion + Stratum - PERIOD_TITLE' --vertical-label 'milliseconds' --alt-autoscale \
  313. --units-exponent 0 \
  314. DEF:stratum='$RRD_FILE':stratum:AVERAGE \
  315. DEF:freq='$RRD_FILE':frequency:AVERAGE \
  316. DEF:skew='$RRD_FILE':skew:AVERAGE \
  317. DEF:delay='$RRD_FILE':delay:AVERAGE \
  318. DEF:dispersion='$RRD_FILE':dispersion:AVERAGE \
  319. CDEF:skew_scaled=skew,100,* \
  320. CDEF:delay_scaled=delay,1000,* \
  321. CDEF:disp_scaled=dispersion,1000,* \
  322. 'COMMENT: \l' \
  323. 'LINE1:stratum#00ff00:Stratum ' \
  324. 'GPRINT:stratum:LAST: Cur\: %5.2lf%s' \
  325. 'GPRINT:stratum:MIN:Min\: %5.2lf%s' \
  326. 'GPRINT:stratum:AVERAGE:Avg\: %5.2lf%s' \
  327. 'GPRINT:stratum:MAX:Max\: %5.2lf%s\l' \
  328. 'LINE1:disp_scaled#9400D3:Root dispersion [Root dispersion] ' \
  329. 'GPRINT:disp_scaled:LAST: Cur\: %5.2lf%s' \
  330. 'GPRINT:disp_scaled:MIN:Min\: %5.2lf%s' \
  331. 'GPRINT:disp_scaled:AVERAGE:Avg\: %5.2lf%s' \
  332. 'GPRINT:disp_scaled:MAX:Max\: %5.2lf%s\l'"
  333. ["chrony_offset"]="--title 'Chrony System Time Offset - PERIOD_TITLE' --vertical-label 'milliseconds' \
  334. DEF:offset='$RRD_FILE':offset:AVERAGE \
  335. DEF:systime='$RRD_FILE':systime:AVERAGE \
  336. CDEF:systime_scaled=systime,1000,* \
  337. CDEF:offset_ms=offset,1000,* \
  338. 'LINE2:offset_ms#00ff00:Actual Offset from NTP Source [Last Offset] ' \
  339. 'GPRINT:offset_ms:LAST: Cur\: %5.2lf%s' \
  340. 'GPRINT:offset_ms:MIN:Min\: %5.2lf%s' \
  341. 'GPRINT:offset_ms:AVERAGE:Avg\: %5.2lf%s' \
  342. 'GPRINT:offset_ms:MAX:Max\: %5.2lf%s\l' \
  343. 'LINE1:systime_scaled#4169E1:System Clock Adjustment [System Time] ' \
  344. 'GPRINT:systime_scaled:LAST: Cur\: %5.2lf%s' \
  345. 'GPRINT:systime_scaled:MIN:Min\: %5.2lf%s' \
  346. 'GPRINT:systime_scaled:AVERAGE:Avg\: %5.2lf%s' \
  347. 'GPRINT:systime_scaled:MAX:Max\: %5.2lf%s\l'"
  348. ["chrony_delay"]="--title 'Chrony Root Delay - PERIOD_TITLE' --vertical-label 'milliseconds' --units-exponent 0 \
  349. DEF:delay='$RRD_FILE':delay:AVERAGE \
  350. CDEF:delay_ms=delay,1000,* \
  351. LINE2:delay_ms#00ff00:'Network Delay to Root Source [Root Delay] ' \
  352. 'GPRINT:delay_ms:LAST:Cur\: %5.2lf%s' \
  353. 'GPRINT:delay_ms:MIN:Min\: %5.2lf%s' \
  354. 'GPRINT:delay_ms:AVERAGE:Avg\: %5.2lf%s' \
  355. 'GPRINT:delay_ms:MAX:Max\: %5.2lf%s\l'"
  356. ["chrony_frequency"]="--title 'Chrony Clock Frequency Error - PERIOD_TITLE' --vertical-label 'ppm'\
  357. DEF:freq='$RRD_FILE':frequency:AVERAGE \
  358. DEF:resid_freq='$RRD_FILE':resid_freq:AVERAGE \
  359. CDEF:resfreq_scaled=resid_freq,100,* \
  360. CDEF:freq_scaled=freq,1,* \
  361. 'LINE2:freq_scaled#00ff00:Natural Clock Drift [Frequency] ' \
  362. 'GPRINT:freq_scaled:LAST:Cur\: %5.2lf%s' \
  363. 'GPRINT:freq_scaled:MIN:Min\: %5.2lf%s' \
  364. 'GPRINT:freq_scaled:AVERAGE:Avg\: %5.2lf%s' \
  365. 'GPRINT:freq_scaled:MAX:Max\: %5.2lf%s\n' \
  366. 'LINE1:resfreq_scaled#4169E1:Residual Drift (x100) [Residual freq] ' \
  367. 'GPRINT:resfreq_scaled:LAST:Cur\: %5.2lf%s' \
  368. 'GPRINT:resfreq_scaled:MIN:Min\: %5.2lf%s' \
  369. 'GPRINT:resfreq_scaled:AVERAGE:Avg\: %5.2lf%s' \
  370. 'GPRINT:resfreq_scaled:MAX:Max\: %5.2lf%s\l'"
  371. ["chrony_drift"]="--title 'Chrony Drift Margin Error - PERIOD_TITLE' --vertical-label 'ppm' \
  372. --units-exponent 0 \
  373. DEF:resid_freq='$RRD_FILE':resid_freq:AVERAGE \
  374. DEF:skew_raw='$RRD_FILE':skew:AVERAGE \
  375. CDEF:resfreq_scaled=resid_freq,100,* \
  376. CDEF:skew_scaled=skew_raw,100,* \
  377. 'COMMENT: \l' \
  378. 'LINE1:skew_scaled#00ff00:Estimate Drift Error Margin (x100) [Skew] ' \
  379. 'GPRINT:skew_scaled:LAST:Cur\: %5.2lf' \
  380. 'GPRINT:skew_scaled:MIN:Min\: %5.2lf' \
  381. 'GPRINT:skew_scaled:AVERAGE:Avg\: %5.2lf' \
  382. 'GPRINT:skew_scaled:MAX:Max\: %5.2lf\l'"
  383. )
  384. for period in "${!time_periods[@]}"; do
  385. for graph in "${!graphs[@]}"; do
  386. local graph_title="${graphs[$graph]//PERIOD_TITLE/${period_titles[$period]}}"
  387. local output_file="$OUTPUT_DIR/img/${graph}_${period}.png"
  388. local time_range="${time_periods[$period]}"
  389. local cmd="LC_ALL=C rrdtool graph '$output_file' --width '$WIDTH' --height '$HEIGHT' --start $time_range --end now-180s $graph_title"
  390. eval "$cmd" || {
  391. log_message "ERROR" "Failed to generate graph: ${graph}_${period}"
  392. exit 1
  393. }
  394. done
  395. done
  396. }
  397. generate_html() {
  398. log_message "INFO" "Generating HTML report..."
  399. local GENERATED_TIMESTAMP=$(date)
  400. local CHRONYC_DISPLAY_OPTS=""
  401. if [[ "$CHRONY_ALLOW_DNS_LOOKUP" == "no" ]]; then
  402. CHRONYC_DISPLAY_OPTS=" -n"
  403. fi
  404. local AUTO_REFRESH_META=""
  405. if [[ "$AUTO_REFRESH_SECONDS" -gt 0 ]]; then
  406. AUTO_REFRESH_META=" <meta http-equiv=\"refresh\" content=\"$AUTO_REFRESH_SECONDS\">"
  407. fi
  408. cat >"$OUTPUT_DIR/$HTML_FILENAME" <<EOF
  409. <!DOCTYPE html>
  410. <html lang="en">
  411. <head>
  412. <meta charset="utf-8">
  413. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  414. $AUTO_REFRESH_META
  415. <title>${PAGE_TITLE} - Server Status</title>
  416. <style>
  417. :root {
  418. --primary-text: #212529;
  419. --secondary-text: #6c757d;
  420. --background-color: #f8f9fa;
  421. --content-background: #ffffff;
  422. --border-color: #787879;
  423. --code-background: #e1e1e1;
  424. --code-text: #000000;
  425. --container-max: 1400px;
  426. --font-size-base: 16px;
  427. }
  428. $CSS_CUSTOM_ROOT
  429. body {
  430. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  431. margin: 0;
  432. padding: 20px;
  433. background-color: var(--background-color);
  434. color: var(--primary-text);
  435. line-height: 1.6;
  436. font-size: var(--font-size-base);
  437. }
  438. .container {
  439. max-width: var(--container-max);
  440. margin: 0 auto;
  441. background-color: var(--content-background);
  442. padding: 20px 20px;
  443. border-radius: 8px;
  444. box-shadow: 0 4px 8px rgba(0,0,0,0.05);
  445. }
  446. header {
  447. text-align: center;
  448. border-bottom: 1px solid var(--border-color);
  449. padding-bottom: 20px;
  450. margin-bottom: 30px;
  451. }
  452. header h1 {
  453. margin: 0;
  454. font-size: 2.5em;
  455. color: var(--primary-text);
  456. }
  457. section {
  458. margin-bottom: 40px;
  459. }
  460. h2 {
  461. font-size: 1.8em;
  462. color: var(--primary-text);
  463. border-bottom: 1px solid var(--border-color);
  464. padding-bottom: 10px;
  465. margin-top: 0;
  466. margin-bottom: 20px;
  467. }
  468. h2 a {
  469. font-size: 0.8em;
  470. font-weight: normal;
  471. vertical-align: middle;
  472. margin-left: 10px;
  473. }
  474. h3 {
  475. font-size: 1.3em;
  476. color: var(--primary-text);
  477. margin-top: 25px;
  478. }
  479. @media (max-width: 767px) {
  480. #vnstat-graphs table,
  481. #vnstat-graphs tbody,
  482. #vnstat-graphs tr,
  483. #vnstat-graphs td {
  484. display: block;
  485. width: 100%;
  486. }
  487. #vnstat-graphs td {
  488. padding-left: 0;
  489. padding-right: 0;
  490. text-align: center;
  491. }
  492. }
  493. .graph-grid {
  494. display: grid;
  495. grid-template-columns: 1fr;
  496. gap: 10px;
  497. text-align: center;
  498. }
  499. @media (min-width: 768px) {
  500. .graph-grid {
  501. grid-template-columns: repeat(2, 1fr);
  502. }
  503. }
  504. figure {
  505. margin: 0;
  506. padding: 0;
  507. }
  508. img {
  509. max-width: 100%;
  510. height: auto;
  511. border: 1px solid var(--border-color);
  512. border-radius: 4px;
  513. box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  514. cursor: zoom-in;
  515. }
  516. .lightbox-overlay {
  517. position: fixed;
  518. inset: 0;
  519. background: rgba(0, 0, 0, 0.85);
  520. display: none;
  521. align-items: center;
  522. justify-content: center;
  523. z-index: 9999;
  524. cursor: zoom-out;
  525. }
  526. .lightbox-overlay.open {
  527. display: flex;
  528. }
  529. .lightbox-img {
  530. width: 96vw;
  531. height: 94vh;
  532. object-fit: contain;
  533. border: 0;
  534. cursor: zoom-out;
  535. }
  536. pre {
  537. background-color: var(--code-background);
  538. color: var(--code-text);
  539. padding: 10px;
  540. border: 1px solid #c3bebe;
  541. border-radius: 4px;
  542. overflow-x: auto;
  543. white-space: pre-wrap;
  544. word-wrap: break-word;
  545. font-size: 0.8em;
  546. }
  547. footer {
  548. text-align: center;
  549. margin-top: 40px;
  550. padding-top: 20px;
  551. border-top: 1px solid var(--border-color);
  552. font-size: 0.9em;
  553. color: var(--secondary-text);
  554. }
  555. .tabs {
  556. display: flex;
  557. border-bottom: 1px solid var(--border-color);
  558. margin-bottom: 20px;
  559. }
  560. .tab {
  561. padding: 10px 20px;
  562. cursor: pointer;
  563. background-color: var(--background-color);
  564. border: 1px solid var(--border-color);
  565. border-bottom: none;
  566. margin-right: 2px;
  567. transition: background-color 0.3s;
  568. }
  569. .tab:hover {
  570. background-color: #e9ecef;
  571. }
  572. .tab.active {
  573. background-color: var(--content-background);
  574. border-bottom: 1px solid var(--content-background);
  575. margin-bottom: -1px;
  576. }
  577. .tab-content {
  578. display: none;
  579. }
  580. .tab-content.active {
  581. display: block;
  582. }
  583. </style>
  584. </head>
  585. <body>
  586. <div class="container">
  587. <main>
  588. <section id="chrony-graphs">
  589. <h2>Chrony Graphs <a target="_blank" href="https://chrony-project.org/doc/4.3/chronyc.html#:~:text=System%20clock-,tracking,-The%20tracking%20command">[Data Legend]</a></h2>
  590. <div class="tabs">
  591. <div class="tab active" onclick="showTab('day')">Day</div>
  592. <div class="tab" onclick="showTab('week')">Week</div>
  593. <div class="tab" onclick="showTab('month')">Month</div>
  594. </div>
  595. <div id="day-content" class="tab-content active">
  596. <div class="graph-grid">
  597. <figure>
  598. <img src="img/chrony_serverstats_day.png" alt="Chrony server statistics graph - day">
  599. </figure>
  600. <figure>
  601. <img src="img/chrony_offset_day.png" alt="Chrony system clock offset graph - day">
  602. </figure>
  603. <figure>
  604. <img src="img/chrony_tracking_day.png" alt="Chrony system clock tracking graph - day">
  605. </figure>
  606. <figure>
  607. <img src="img/chrony_delay_day.png" alt="Chrony sync delay graph - day">
  608. </figure>
  609. <figure>
  610. <img src="img/chrony_frequency_day.png" alt="Chrony clock frequency graph - day">
  611. </figure>
  612. <figure>
  613. <img src="img/chrony_drift_day.png" alt="Chrony clock frequency drift graph - day">
  614. </figure>
  615. </div>
  616. </div>
  617. <div id="week-content" class="tab-content">
  618. <div class="graph-grid">
  619. <figure>
  620. <img src="img/chrony_serverstats_week.png" alt="Chrony server statistics graph - week">
  621. </figure>
  622. <figure>
  623. <img src="img/chrony_offset_week.png" alt="Chrony system clock offset graph - week">
  624. </figure>
  625. <figure>
  626. <img src="img/chrony_tracking_week.png" alt="Chrony system clock tracking graph - week">
  627. </figure>
  628. <figure>
  629. <img src="img/chrony_delay_week.png" alt="Chrony sync delay graph - week">
  630. </figure>
  631. <figure>
  632. <img src="img/chrony_frequency_week.png" alt="Chrony clock frequency graph - week">
  633. </figure>
  634. <figure>
  635. <img src="img/chrony_drift_week.png" alt="Chrony clock frequency drift graph - week">
  636. </figure>
  637. </div>
  638. </div>
  639. <div id="month-content" class="tab-content">
  640. <div class="graph-grid">
  641. <figure>
  642. <img src="img/chrony_serverstats_month.png" alt="Chrony server statistics graph - month">
  643. </figure>
  644. <figure>
  645. <img src="img/chrony_offset_month.png" alt="Chrony system clock offset graph - month">
  646. </figure>
  647. <figure>
  648. <img src="img/chrony_tracking_month.png" alt="Chrony system clock tracking graph - month">
  649. </figure>
  650. <figure>
  651. <img src="img/chrony_delay_month.png" alt="Chrony sync delay graph - month">
  652. </figure>
  653. <figure>
  654. <img src="img/chrony_frequency_month.png" alt="Chrony clock frequency graph - month">
  655. </figure>
  656. <figure>
  657. <img src="img/chrony_drift_month.png" alt="Chrony clock frequency drift graph - month">
  658. </figure>
  659. </div>
  660. </div>
  661. </section>
  662. EOF
  663. if [[ "$ENABLE_NETWORK_STATS" == "yes" ]]; then
  664. cat >>"$OUTPUT_DIR/$HTML_FILENAME" <<EOF
  665. <section id="vnstat-graphs">
  666. <h2>vnStati Graphs</h2>
  667. <table border="0" style="margin-left: auto; margin-right: auto;">
  668. <tbody>
  669. <tr>
  670. <td valign="top" style="padding: 0 10px;">
  671. <img src="img/vnstat_s.png" alt="vnStat summary"><br>
  672. <img src="img/vnstat_d.png" alt="vnStat daily" style="margin-top: 4px;"><br>
  673. <img src="img/vnstat_t.png" alt="vnStat top 10" style="margin-top: 4px;"><br>
  674. </td>
  675. <td valign="top" style="padding: 0 10px;">
  676. <img src="img/vnstat_h.png" alt="vnStat hourly"><br>
  677. <img src="img/vnstat_m.png" alt="vnStat monthly" style="margin-top: 4px;"><br>
  678. <img src="img/vnstat_y.png" alt="vnStat yearly" style="margin-top: 4px;"><br>
  679. </td>
  680. </tr>
  681. </tbody>
  682. </table>
  683. </section>
  684. EOF
  685. fi
  686. cat >>"$OUTPUT_DIR/$HTML_FILENAME" <<EOF
  687. <section id="chrony-stats">
  688. <h2>Chrony - NTP Statistics</h2>
  689. <h3>Command: <code>chronyc${CHRONYC_DISPLAY_OPTS} sources -v</code></h3>
  690. <pre><code>${CHRONYC_SOURCES}</code></pre>
  691. <h3>Command: <code>chronyc${CHRONYC_DISPLAY_OPTS} selectdata -v</code></h3>
  692. <pre><code>${CHRONYC_SELECTDATA}</code></pre>
  693. <h3>Command: <code>chronyc${CHRONYC_DISPLAY_OPTS} sourcestats -v</code></h3>
  694. <pre><code>${CHRONYC_SOURCESTATS}</code></pre>
  695. <h3>Command: <code>chronyc${CHRONYC_DISPLAY_OPTS} tracking</code></h3>
  696. <pre><code>${CHRONYC_TRACKING_HTML}</code></pre>
  697. </section>
  698. </main>
  699. <footer>
  700. <p>Page generated on: ${GENERATED_TIMESTAMP}</p>
  701. EOF
  702. if [[ "$GITHUB_REPO_LINK_SHOW" == "yes" ]]; then
  703. cat >>"$OUTPUT_DIR/$HTML_FILENAME" <<EOF
  704. <p>Made with ❤️ by TheHuman00 | <a href="https://github.com/TheHuman00/chrony-stats" target="_blank">View on GitHub</a></p>
  705. EOF
  706. fi
  707. cat >>"$OUTPUT_DIR/$HTML_FILENAME" <<EOF
  708. </footer>
  709. </div>
  710. <div id="lightbox" class="lightbox-overlay" aria-hidden="true" role="dialog">
  711. <img id="lightbox-img" class="lightbox-img" alt="Expanded graph">
  712. </div>
  713. <script>
  714. function showTab(period) {
  715. const contents = document.querySelectorAll('.tab-content');
  716. contents.forEach(content => content.classList.remove('active'));
  717. const tabs = document.querySelectorAll('.tab');
  718. tabs.forEach(tab => tab.classList.remove('active'));
  719. document.getElementById(period + '-content').classList.add('active');
  720. const evt = event || window.event; // works with inline onclick
  721. if (evt && evt.target) {
  722. evt.target.classList.add('active');
  723. }
  724. }
  725. (function enableImageLightbox() {
  726. const overlay = document.getElementById('lightbox');
  727. const overlayImg = document.getElementById('lightbox-img');
  728. if (!overlay || !overlayImg) return;
  729. const open = (src, alt) => {
  730. overlayImg.src = src;
  731. overlayImg.alt = alt || 'Expanded image';
  732. overlay.classList.add('open');
  733. overlay.setAttribute('aria-hidden', 'false');
  734. // Prevent background scroll
  735. document.body.style.overflow = 'hidden';
  736. };
  737. const close = () => {
  738. overlay.classList.remove('open');
  739. overlay.setAttribute('aria-hidden', 'true');
  740. overlayImg.src = '';
  741. document.body.style.overflow = '';
  742. };
  743. document.querySelectorAll('.container img').forEach(img => {
  744. img.addEventListener('click', () => open(img.src, img.alt));
  745. });
  746. overlay.addEventListener('click', close);
  747. overlayImg.addEventListener('click', close);
  748. document.addEventListener('keydown', (e) => {
  749. if (e.key === 'Escape' && overlay.classList.contains('open')) close();
  750. });
  751. })();
  752. </script>
  753. </body>
  754. </html>
  755. EOF
  756. }
  757. main() {
  758. log_message "INFO" "Starting chrony-network-stats script..."
  759. validate_numeric "$WIDTH" "WIDTH"
  760. validate_numeric "$HEIGHT" "HEIGHT"
  761. validate_numeric "$TIMEOUT_SECONDS" "TIMEOUT_SECONDS"
  762. validate_numeric "$SERVER_STATS_UPPER_LIMIT" "SERVER_STATS_UPPER_LIMIT"
  763. validate_numeric "$AUTO_REFRESH_SECONDS" "AUTO_REFRESH_SECONDS"
  764. configure_display_preset
  765. check_commands
  766. setup_directories
  767. generate_vnstat_images
  768. collect_chrony_data
  769. extract_chronyc_values
  770. create_rrd_database
  771. update_rrd_database
  772. generate_graphs
  773. generate_html
  774. log_message "INFO" "HTML page and graphs generated in: $OUTPUT_DIR/$HTML_FILENAME"
  775. echo "✅ Successfully generated report"
  776. }
  777. main