forked from rfxn/system-tuner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapache-tuner
More file actions
executable file
·1704 lines (1454 loc) · 58.8 KB
/
apache-tuner
File metadata and controls
executable file
·1704 lines (1454 loc) · 58.8 KB
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
#!/bin/bash
# ==============================================================================
# Apache Smart Tuner v1.20.0 for cPanel / WHM & generic Apache
# Author: Ryan MacDonald <ryan@rfxn.com>
# License: GPL-3.0-or-later
#
# - Tiered by RAM & cores: LOW, LOW-MID, MID, MID-HIGH, HIGH
# - PHP-aware: conservative CPU caps on MID/HIGH
# - Tiered MaxRequestWorkers caps (prefork and threaded):
# * LOW: 128
# * LOW-MID: 256
# * MID: 1024
# * MID-HIGH: 2048
# * HIGH: 4096
# - Floors:
# * Prefork: ServerLimit / MaxRequestWorkers >= 128
# * Event/worker: MaxRequestWorkers >= 128 (threads)
# - Doubles effective concurrency on LOW and LOW-MID tiers (within caps)
# - Applies RAM, CPU, and tier-based global caps to MaxRequestWorkers
# - Shows current vs proposed values (current => proposed)
# - cPanel-aware:
# * prefers pre_virtualhost_global.conf if present for both apply and "Current" values
# * otherwise uses pre_main_global.conf (for apply)
# * runs /scripts/rebuildhttpdconf after changes
# - Safe apply with backup and rollback
# - --locate: list only conf files defining MPM / concurrency settings
# - --apply: removes legacy prefork/worker/event/mpm_* IfModule blocks in target include,
# then writes a single Smart Tuner block for the active MPM
# ==============================================================================
set -u # keep "undefined var" safety; avoid -e/pipefail to prevent silent exits
VERSION_MAJOR=1
VERSION_MINOR=20
VERSION_PATCH=0
VERSION="${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_PATCH}"
VERSION_NAME="Apache Smart Tuner v${VERSION}"
LOG_FILE="/var/log/apache-smart-tuner.log"
BUDGET_OVERRIDE=""
BUDGET_SOURCE="tier"
ERROR_LOG_LOOKBACK_HOURS=24
SPINNER_PID=""
SPINNER_MESSAGE=""
MODE="analyze"
MODE_SET=0
OUTPUT_FORMAT="text"
RELOAD_AFTER_APPLY=1
MPM_OVERRIDE=""
EXPORT_PATH=""
MPM_SOURCE="unknown"
APACHE_BINARIES=()
# Error log review defaults
APACHE_ERROR_LOG=""
ERROR_LOG_SAMPLE_LINES=0
LOG_REVIEW_STATUS="not_run"
LOG_REVIEW_MESSAGE=""
SCOREBOARD_HITS=0
SERVER_LIMIT_HITS=0
RESTART_TOTAL=0
RESTART_DAY_COUNT=0
RESTART_MAX_PER_DAY=0
LOG_SAMPLE_CONTENT=""
# Scoreboard safety defaults
SERVER_LIMIT_BUFFER_PCT="0.05"
MIN_SERVER_LIMIT_BUFFER=8
# Common error patterns to highlight during log review
declare -A COMMON_ERROR_PATTERNS=(
[segfaults]="segfault|segmentation fault|child process .*dumped core"
[timeouts]="script timed out|mod_fcgid: read data timeout|mod_fcgid: can't apply process slot"
[denied]="client denied by server configuration|AH01630|access to .* denied"
)
# Friendly labels for log review output
declare -A COMMON_ERROR_LABELS=(
[segfaults]="Process crashes/segfaults"
[timeouts]="Slow CGI/PHP timeouts"
[denied]="Client denials"
)
LOG_REVIEW_KEYS=(segfaults timeouts denied)
# Initialize per-run counts
declare -A COMMON_ERROR_COUNTS=()
set_mode() {
local NEW_MODE="$1"
if [[ "$MODE_SET" -eq 1 && "$MODE" != "$NEW_MODE" ]]; then
echo "ERROR: Modes --$MODE and --$NEW_MODE cannot be combined."
exit 1
fi
MODE="$NEW_MODE"
MODE_SET=1
}
usage() {
cat <<EOF
Usage: $0 [--analyze] [--locate] [--apply] [--version] [--json] [--batch] [--export <path>] [--no-reload] [--mpm <type>] [--budget <0.x>] [--log-file <path|none>]
--analyze (default) Print recommended Apache MPM config based on current RAM/cores
--locate Show which Apache config files currently define MPM-related directives
--apply Safely write/update recommended config into a cPanel include (or generic conf.d)
--json Emit analyze/apply output as JSON for automation (mutually exclusive with --locate)
--batch Emit analyze/apply output as a single-line bash-friendly key=value string (mutually exclusive with --locate)
--export <path> Write ONLY the recommended Smart Tuner block to <path> (no config edits/reloads)
--no-reload Skip Apache reload/restart after successful --apply (writes config only)
--mpm <type> Force MPM assumption (prefork|worker|event) when binary probing is unavailable
--budget <0.x> Override tier-based Apache RAM budget percentage (0.05-0.95)
--log-file <path> Write logs to the given file (default: /var/log/apache-smart-tuner.log)
Use "none" to disable filesystem logging
--version Display the current Apache Smart Tuner version and exit
Notes:
- --apply must be run as root
- On cPanel systems, the config will be written to the standard include locations
- Backup files are created with .bk-YYYYmmddHHMMSS suffix
EOF
}
print_version() {
echo "$VERSION_NAME"
}
parse_cli_arguments() {
OPTIND=1
local opt
while getopts ":h-:" opt; do
case "$opt" in
h)
usage
exit 0
;;
-)
case "$OPTARG" in
analyze)
set_mode "analyze"
OUTPUT_FORMAT="text"
RELOAD_AFTER_APPLY=1
;;
locate)
set_mode "locate"
;;
apply)
set_mode "apply"
;;
json)
OUTPUT_FORMAT="json"
;;
batch)
OUTPUT_FORMAT="batch"
;;
no-reload)
RELOAD_AFTER_APPLY=0
;;
mpm)
local next_mpm="${!OPTIND:-}"
if [[ -z "$next_mpm" || "$next_mpm" == -* ]]; then
echo "ERROR: --mpm requires an argument (prefork|worker|event)"
exit 1
fi
case "$next_mpm" in
prefork|worker|event)
MPM_OVERRIDE="$next_mpm"
;;
*)
echo "ERROR: Unsupported MPM type for --mpm: $next_mpm"
exit 1
;;
esac
OPTIND=$((OPTIND + 1))
;;
mpm=*)
local next_mpm="${OPTARG#*=}"
if [[ -z "$next_mpm" ]]; then
echo "ERROR: --mpm requires an argument (prefork|worker|event)"
exit 1
fi
case "$next_mpm" in
prefork|worker|event)
MPM_OVERRIDE="$next_mpm"
;;
*)
echo "ERROR: Unsupported MPM type for --mpm: $next_mpm"
exit 1
;;
esac
;;
export)
local export_path="${!OPTIND:-}"
if [[ -z "$export_path" || "$export_path" == -* ]]; then
echo "ERROR: --export requires a file path argument"
exit 1
fi
EXPORT_PATH="$export_path"
OPTIND=$((OPTIND + 1))
;;
export=*)
local export_path="${OPTARG#*=}"
if [[ -z "$export_path" ]]; then
echo "ERROR: --export requires a file path argument"
exit 1
fi
EXPORT_PATH="$export_path"
;;
budget)
local budget_value="${!OPTIND:-}"
if [[ -z "$budget_value" || "$budget_value" == -* ]]; then
echo "ERROR: --budget requires a percentage in decimal form (e.g., 0.40)"
exit 1
fi
if ! validate_budget_pct "$budget_value"; then
echo "ERROR: --budget must be between 0.05 and 0.95 (e.g., 0.35)"
exit 1
fi
BUDGET_OVERRIDE="$budget_value"
OPTIND=$((OPTIND + 1))
;;
budget=*)
local budget_value="${OPTARG#*=}"
if [[ -z "$budget_value" ]]; then
echo "ERROR: --budget requires a percentage in decimal form (e.g., 0.40)"
exit 1
fi
if ! validate_budget_pct "$budget_value"; then
echo "ERROR: --budget must be between 0.05 and 0.95 (e.g., 0.35)"
exit 1
fi
BUDGET_OVERRIDE="$budget_value"
;;
log-file)
local log_path="${!OPTIND:-}"
if [[ -z "$log_path" || "$log_path" == -* ]]; then
echo "ERROR: --log-file requires a path or 'none'"
exit 1
fi
if [[ "$log_path" == "none" ]]; then
LOG_FILE=""
else
LOG_FILE="$log_path"
fi
OPTIND=$((OPTIND + 1))
;;
log-file=*)
local log_path="${OPTARG#*=}"
if [[ -z "$log_path" ]]; then
echo "ERROR: --log-file requires a path or 'none'"
exit 1
fi
if [[ "$log_path" == "none" ]]; then
LOG_FILE=""
else
LOG_FILE="$log_path"
fi
;;
version)
print_version
exit 0
;;
help)
usage
exit 0
;;
*)
echo "Unknown argument: --${OPTARG%%=*}"
usage
exit 1
;;
esac
;;
\?)
echo "Unknown argument: -$OPTARG"
usage
exit 1
;;
esac
done
shift $((OPTIND - 1))
if [[ $# -gt 0 ]]; then
echo "Unknown argument: $1"
usage
exit 1
fi
}
# ----------------- helpers -----------------
need_cmd() {
local CMD="$1"
if ! command -v "$CMD" >/dev/null 2>&1; then
echo "ERROR: Required command '$CMD' not found in PATH."
exit 1
fi
}
discover_apache_binaries() {
APACHE_BINARIES=()
for bin in apachectl apache2ctl httpd; do
if command -v "$bin" >/dev/null 2>&1; then
APACHE_BINARIES+=("$bin")
fi
done
}
log_message() {
local LEVEL="$1"
local MESSAGE="$2"
local TS
TS=$(date +"%Y-%m-%d %H:%M:%S")
local FORMATTED="[$TS] [$LEVEL] $MESSAGE"
if command -v logger >/dev/null 2>&1; then
logger -t apache-smart-tuner "$MESSAGE"
fi
if [[ -n "$LOG_FILE" ]]; then
echo "$FORMATTED" >> "$LOG_FILE" 2>/dev/null || true
fi
}
print_if_text() {
[[ "$OUTPUT_FORMAT" == "text" ]] || return
echo "$@"
}
start_progress_indicator() {
[[ "$OUTPUT_FORMAT" == "json" || "$OUTPUT_FORMAT" == "batch" ]] && return
[[ -t 1 ]] || return
local MESSAGE="$1"
SPINNER_MESSAGE="$MESSAGE"
local FRAMES=('|' '/' '-' '\\')
local i=0
(
while true; do
printf "\r%s %s" "$SPINNER_MESSAGE" "${FRAMES[$((i % 4))]}"
sleep 0.2
((i++))
done
) &
SPINNER_PID=$!
}
stop_progress_indicator() {
[[ "$OUTPUT_FORMAT" == "json" || "$OUTPUT_FORMAT" == "batch" ]] && return
[[ -t 1 ]] || return
if [[ -n "${SPINNER_PID:-}" ]]; then
kill "$SPINNER_PID" >/dev/null 2>&1 || true
wait "$SPINNER_PID" 2>/dev/null || true
SPINNER_PID=""
printf "\r%s ... done\n" "$SPINNER_MESSAGE"
SPINNER_MESSAGE=""
fi
}
preflight_validate_options() {
if [[ "$MODE" == "locate" && ( "$OUTPUT_FORMAT" == "json" || "$OUTPUT_FORMAT" == "batch" ) ]]; then
echo "ERROR: --$OUTPUT_FORMAT is not supported with --locate mode."
exit 1
fi
if [[ "$MODE" == "locate" && -n "$EXPORT_PATH" ]]; then
echo "ERROR: --export cannot be combined with --locate mode."
exit 1
fi
}
validate_budget_pct() {
local PCT="$1"
if [[ ! "$PCT" =~ ^0\.[0-9]+$ ]]; then
return 1
fi
awk "BEGIN { exit !($PCT >= 0.05 && $PCT <= 0.95) }"
}
round_down_to_multiple_of_8() {
local VALUE=$1
local MULTIPLE=8
if [[ -z "$VALUE" || "$VALUE" -le 0 ]]; then
echo 1
return
fi
if [[ "$VALUE" -eq 1 || "$VALUE" -eq 2 ]]; then
echo "$VALUE"
return
fi
local REMAINDER=$(( VALUE % MULTIPLE ))
local NEW_VALUE=$(( VALUE - REMAINDER ))
if [[ "$NEW_VALUE" -lt 1 ]]; then
echo "$MULTIPLE"
else
echo "$NEW_VALUE"
fi
}
round_up_to_multiple_of_8() {
local VALUE=$1
local MULTIPLE=8
if [[ -z "$VALUE" || "$VALUE" -le 0 ]]; then
echo 0
return
fi
local REMAINDER=$(( VALUE % MULTIPLE ))
if [[ "$REMAINDER" -eq 0 ]]; then
echo "$VALUE"
else
echo $(( VALUE + MULTIPLE - REMAINDER ))
fi
}
calculate_server_limit_with_buffer() {
local BASE_VALUE=$1
local RAW_BUFFER
RAW_BUFFER=$(awk -v target="$BASE_VALUE" -v pct="$SERVER_LIMIT_BUFFER_PCT" 'BEGIN { printf "%.0f", (target * pct) }')
if [[ "$RAW_BUFFER" -lt "$MIN_SERVER_LIMIT_BUFFER" ]]; then
RAW_BUFFER=$MIN_SERVER_LIMIT_BUFFER
fi
local BUFFER=$(round_up_to_multiple_of_8 "$RAW_BUFFER")
echo $(( BASE_VALUE + BUFFER ))
}
# ----------------- Apache layout / env detection -----------------
detect_apache_layout() {
APACHE_ROOT=""
HTTPD_CONF=""
INCLUDES_DIR=""
PREFORK_INCLUDE=""
if [[ -f /etc/apache2/conf/httpd.conf ]]; then
APACHE_ROOT="/etc/apache2"
HTTPD_CONF="/etc/apache2/conf/httpd.conf"
INCLUDES_DIR="/etc/apache2/conf.d/includes"
PREFORK_INCLUDE="$APACHE_ROOT/conf.d/includes/pre_virtualhost_global.conf"
[[ ! -f "$PREFORK_INCLUDE" && -f "$APACHE_ROOT/conf/includes/pre_virtualhost_global.conf" ]] && PREFORK_INCLUDE="$APACHE_ROOT/conf/includes/pre_virtualhost_global.conf"
elif [[ -f /usr/local/apache/conf/httpd.conf ]]; then
APACHE_ROOT="/usr/local/apache"
HTTPD_CONF="/usr/local/apache/conf/httpd.conf"
INCLUDES_DIR="/usr/local/apache/conf/includes"
PREFORK_INCLUDE="$APACHE_ROOT/conf/includes/pre_virtualhost_global.conf"
elif [[ -f /etc/httpd/conf/httpd.conf ]]; then
APACHE_ROOT="/etc/httpd"
HTTPD_CONF="/etc/httpd/conf/httpd.conf"
INCLUDES_DIR="/etc/httpd/conf.d"
PREFORK_INCLUDE="$APACHE_ROOT/conf.d/pre_virtualhost_global.conf"
fi
if [[ -z "$APACHE_ROOT" || -z "$HTTPD_CONF" ]]; then
echo "ERROR: Could not detect Apache config layout."
exit 1
fi
}
detect_cpanel() {
if [[ -d /usr/local/cpanel || -d /etc/cpanel ]]; then
IS_CPANEL=1
else
IS_CPANEL=0
fi
}
detect_mpm() {
if [[ -n "$MPM_OVERRIDE" ]]; then
MPM_TYPE="$MPM_OVERRIDE"
MPM_SOURCE="override"
return
fi
local VOUT=""
[[ ${#APACHE_BINARIES[@]} -eq 0 ]] && discover_apache_binaries
for bin in "${APACHE_BINARIES[@]}"; do
VOUT=$("$bin" -V 2>/dev/null || true)
[[ -n "$VOUT" ]] && break
done
RAW_MPM=$(echo "$VOUT" | grep -i "Server MPM" | awk '{print $3}')
MPM_TYPE=${RAW_MPM,,}
[[ -n "$MPM_TYPE" ]] && MPM_SOURCE="binary -V"
if [[ -z "$MPM_TYPE" ]]; then
local MOUT=""
for bin in "${APACHE_BINARIES[@]}"; do
MOUT=$("$bin" -M 2>/dev/null || true)
[[ -n "$MOUT" ]] && break
done
if [[ -n "$MOUT" ]]; then
RAW_MPM=$(echo "$MOUT" | awk '/mpm_(prefork|worker|event)_module/ {print $1; exit}')
if [[ -n "$RAW_MPM" ]]; then
MPM_TYPE=$(echo "$RAW_MPM" | sed -E 's/.*mpm_([a-z]+)_module/\1/i')
MPM_TYPE=${MPM_TYPE,,}
MPM_SOURCE="module-list"
fi
fi
fi
if [[ -z "$MPM_TYPE" ]]; then
if [[ -z "${APACHE_ROOT:-}" || -z "${HTTPD_CONF:-}" ]]; then
detect_apache_layout
fi
MPM_TYPE=$(infer_mpm_from_config)
[[ -n "$MPM_TYPE" ]] && MPM_SOURCE="config"
fi
if [[ -z "$MPM_TYPE" ]]; then
echo "ERROR: Unable to detect Apache MPM type."
exit 1
fi
case "$MPM_TYPE" in
prefork|worker|event) ;;
*)
echo "ERROR: Unsupported or unknown MPM type detected: $MPM_TYPE"
exit 1
;;
esac
}
detect_resources() {
need_cmd free
need_cmd nproc
need_cmd ps
need_cmd bc
need_cmd awk
need_cmd grep
need_cmd sed
need_cmd tail
TOTAL_MEM=$(free -m | awk '/^Mem:/{print $2}')
CORES=$(nproc)
if [[ -z "$TOTAL_MEM" || -z "$CORES" ]]; then
echo "ERROR: Unable to detect RAM or CPU core count."
exit 1
fi
}
detect_apache_running() {
detect_apache_process_name
APACHE_PROCS=$(ps -C "$APACHE_PROC_NAME" -o rss= 2>/dev/null | wc -l || echo 0)
APACHE_RUNNING=0
[[ "$APACHE_PROCS" -gt 0 ]] && APACHE_RUNNING=1
}
detect_configtest_cmd() {
[[ ${#APACHE_BINARIES[@]} -eq 0 ]] && discover_apache_binaries
local FALLBACK_HTTPD=""
for cmd in "${APACHE_BINARIES[@]}"; do
case "$cmd" in
apachectl|apache2ctl)
APACHE_CONFIGTEST_CMD="$cmd"
return
;;
httpd)
FALLBACK_HTTPD="$cmd"
;;
esac
done
APACHE_CONFIGTEST_CMD="$FALLBACK_HTTPD"
}
# Pin down which httpd process name to monitor before sampling memory.
detect_apache_process_name() {
for candidate in httpd apache2; do
if ps -C "$candidate" -o pid= >/dev/null 2>&1; then
APACHE_PROC_NAME="$candidate"
return
fi
done
APACHE_PROC_NAME="httpd"
}
# Gather layout, platform, and MPM facts ahead of analysis or apply actions.
bootstrap_environment() {
detect_apache_layout
detect_cpanel
detect_mpm
detect_resources
detect_apache_running
}
reset_log_review() {
APACHE_ERROR_LOG=""
ERROR_LOG_SAMPLE_LINES=0
LOG_REVIEW_STATUS="not_run"
LOG_REVIEW_MESSAGE=""
LOG_SAMPLE_CONTENT=""
SCOREBOARD_HITS=0
SERVER_LIMIT_HITS=0
RESTART_TOTAL=0
RESTART_DAY_COUNT=0
RESTART_MAX_PER_DAY=0
for key in "${!COMMON_ERROR_PATTERNS[@]}"; do
COMMON_ERROR_COUNTS[$key]=0
done
}
extract_error_log_from_config() {
[[ -z "$HTTPD_CONF" || ! -f "$HTTPD_CONF" ]] && return
local raw=""
raw=$(awk '/^[[:space:]]*ErrorLog[[:space:]]+/ {print $2; exit}' "$HTTPD_CONF")
raw=${raw//\"/}
[[ -z "$raw" || "$raw" == "|"* ]] && return
if [[ "$raw" != /* ]]; then
echo "${APACHE_ROOT%/}/$raw"
else
echo "$raw"
fi
}
detect_error_log_path() {
local candidates=()
local cfg_log
cfg_log=$(extract_error_log_from_config)
[[ -n "$cfg_log" ]] && candidates+=("$cfg_log")
[[ -n "$APACHE_ROOT" ]] && candidates+=("$APACHE_ROOT/logs/error_log" "$APACHE_ROOT/logs/error.log")
candidates+=("/usr/local/apache/logs/error_log" "/etc/httpd/logs/error_log" "/var/log/httpd/error_log" "/var/log/apache2/error.log" "/etc/apache2/logs/error_log")
for path in "${candidates[@]}"; do
if [[ -f "$path" ]]; then
APACHE_ERROR_LOG="$path"
return
fi
done
}
load_error_log_sample() {
LOG_SAMPLE_CONTENT=""
ERROR_LOG_SAMPLE_LINES=0
if [[ -z "$APACHE_ERROR_LOG" ]]; then
return
fi
if [[ ! -r "$APACHE_ERROR_LOG" ]]; then
LOG_REVIEW_STATUS="unreadable"
LOG_REVIEW_MESSAGE="Apache error log is not readable ($APACHE_ERROR_LOG)"
return
fi
local cutoff_epoch
cutoff_epoch=$(date -d "${ERROR_LOG_LOOKBACK_HOURS} hours ago" +%s 2>/dev/null || true)
if [[ -z "$cutoff_epoch" ]]; then
cutoff_epoch=$(python - <<'PY'
import time
import sys
from datetime import datetime, timedelta
cutoff = datetime.now() - timedelta(hours=int(sys.argv[1]))
print(int(cutoff.timestamp()))
PY
"$ERROR_LOG_LOOKBACK_HOURS")
fi
LOG_SAMPLE_CONTENT=$(perl -MTime::Piece -e '
use strict;
use warnings;
my ($path, $cutoff) = @ARGV;
my $keep = 0;
my @collected;
open my $fh, "<", $path or exit 0;
while (my $line = <$fh>) {
if ($line =~ /\[[A-Za-z]{3}\s+([A-Za-z]{3})\s+(\d{1,2})\s+([0-9:]{8})(?:\.[0-9]+)?\s+(\d{4})\]/) {
my ($mon, $mday, $time, $year) = ($1, $2, $3, $4);
my $epoch = eval { Time::Piece->strptime("$year $mon $mday $time", "%Y %b %d %T")->epoch };
if ($@) {
$keep = 1;
} else {
$keep = $epoch >= $cutoff ? 1 : 0;
}
}
push @collected, $line if $keep;
}
print @collected;
' "$APACHE_ERROR_LOG" "$cutoff_epoch" 2>/dev/null || true)
ERROR_LOG_SAMPLE_LINES=$(wc -l <<< "$LOG_SAMPLE_CONTENT")
if [[ "$ERROR_LOG_SAMPLE_LINES" -eq 0 ]]; then
LOG_REVIEW_STATUS="empty"
LOG_REVIEW_MESSAGE="Apache error log is empty in the last ${ERROR_LOG_LOOKBACK_HOURS} hours ($APACHE_ERROR_LOG)"
fi
}
count_log_pattern() {
local pattern="$1"
if [[ -z "$LOG_SAMPLE_CONTENT" ]]; then
echo 0
return
fi
echo "$LOG_SAMPLE_CONTENT" | grep -Eai "$pattern" | wc -l | awk '{print $1}'
}
analyze_restarts() {
local log_content="$1"
RESTART_TOTAL=0
RESTART_DAY_COUNT=0
RESTART_MAX_PER_DAY=0
local restart_counts
restart_counts=$(echo "$log_content" | awk '
match($0,/^\[([A-Za-z]{3}) ([A-Za-z]{3}) ([ 0-9]{2}) ([0-9:]{8})(\.[0-9]+)? ([0-9]{4})\]/,a) {
if ($0 ~ /(resuming normal operations|Graceful restart|Graceful restart requested|caught SIGTERM|caught SIGUSR1|caught SIGHUP)/) {
day=sprintf("%s-%02d-%s", a[2], a[3], a[6]);
counts[day]++;
total++;
}
}
END {
for (d in counts) printf("%s %s\n", counts[d], d);
printf("TOTAL %s\n", total);
}
')
while IFS= read -r line; do
[[ -z "$line" ]] && continue
if [[ "$line" =~ ^TOTAL[[:space:]]+([0-9]+) ]]; then
RESTART_TOTAL="${BASH_REMATCH[1]}"
continue
fi
if [[ "$line" =~ ^([0-9]+)[[:space:]]+(.+) ]]; then
local count="${BASH_REMATCH[1]}"
((RESTART_DAY_COUNT++))
if (( count > RESTART_MAX_PER_DAY )); then
RESTART_MAX_PER_DAY=$count
fi
fi
done <<< "$restart_counts"
}
analyze_error_log() {
reset_log_review
detect_error_log_path
if [[ -z "$APACHE_ERROR_LOG" ]]; then
LOG_REVIEW_STATUS="not_found"
LOG_REVIEW_MESSAGE="No readable Apache error log detected."
return
fi
load_error_log_sample
if [[ "$ERROR_LOG_SAMPLE_LINES" -eq 0 ]]; then
[[ -z "$LOG_REVIEW_MESSAGE" ]] && LOG_REVIEW_MESSAGE="Apache error log is empty ($APACHE_ERROR_LOG)"
return
fi
LOG_REVIEW_STATUS="ready"
LOG_REVIEW_MESSAGE="Analyzed the last ${ERROR_LOG_LOOKBACK_HOURS} hours (${ERROR_LOG_SAMPLE_LINES} lines)"
SCOREBOARD_HITS=$(count_log_pattern "scoreboard is full|server reached MaxRequestWorkers setting|server reached MaxRequestWorkers|MaxRequestWorkers setting, consider raising the MaxRequestWorkers setting")
SERVER_LIMIT_HITS=$(count_log_pattern "ServerLimit")
for key in "${!COMMON_ERROR_PATTERNS[@]}"; do
COMMON_ERROR_COUNTS[$key]=$(count_log_pattern "${COMMON_ERROR_PATTERNS[$key]}")
done
analyze_restarts "$LOG_SAMPLE_CONTENT"
}
infer_mpm_from_config() {
local SEARCH_PATHS=()
[[ -n "$HTTPD_CONF" && -f "$HTTPD_CONF" ]] && SEARCH_PATHS+=("$HTTPD_CONF")
[[ -d "$APACHE_ROOT/conf" ]] && SEARCH_PATHS+=("$APACHE_ROOT/conf")
[[ -d "$APACHE_ROOT/conf.d" ]] && SEARCH_PATHS+=("$APACHE_ROOT/conf.d")
[[ -n "$INCLUDES_DIR" && -d "$INCLUDES_DIR" ]] && SEARCH_PATHS+=("$INCLUDES_DIR")
if ((${#SEARCH_PATHS[@]} == 0)); then
echo ""
return
fi
local FIRST_MATCH
FIRST_MATCH=$(grep -R -h -E 'mpm_(prefork|worker|event)_module' "${SEARCH_PATHS[@]}" 2>/dev/null | head -n1)
if [[ -z "$FIRST_MATCH" ]]; then
FIRST_MATCH=$(grep -R -h -E '<IfModule[[:space:]]+mpm_(prefork|worker|event)_module>' "${SEARCH_PATHS[@]}" 2>/dev/null | head -n1)
fi
if [[ -n "$FIRST_MATCH" ]]; then
echo "$FIRST_MATCH" | awk '{
for (i=1; i<=NF; i++) {
if ($i ~ /mpm_(prefork|worker|event)_module/) {
sub(/.*mpm_/, "", $i)
sub(/_module.*/, "", $i)
print tolower($i)
break
}
}
}'
return
fi
echo ""
}
set_tier_params() {
if [[ "$TOTAL_MEM" -le 2048 || "$CORES" -le 2 ]]; then
TIER="LOW"
APACHE_PCT="0.30"
PROCS_PER_CORE_CAP=64
THREADS_PER_CORE_CAP=200
START_SERVERS=1
MIN_SPARE=1
MAX_SPARE=2
MAX_CONN_PER_CHILD=2000
MRW_CAP_PREFORK=128
MRW_CAP_THREADED=128
elif [[ "$TOTAL_MEM" -le 8192 && "$CORES" -ge 2 ]]; then
TIER="LOW-MID"
APACHE_PCT="0.35"
PROCS_PER_CORE_CAP=64
THREADS_PER_CORE_CAP=220
START_SERVERS=2
MIN_SPARE=2
MAX_SPARE=5
MAX_CONN_PER_CHILD=4000
MRW_CAP_PREFORK=256
MRW_CAP_THREADED=256
elif [[ "$TOTAL_MEM" -le 16384 && "$CORES" -ge 4 ]]; then
TIER="MID"
APACHE_PCT="0.40"
PROCS_PER_CORE_CAP=48
THREADS_PER_CORE_CAP=200
START_SERVERS=3
MIN_SPARE=3
MAX_SPARE=8
MAX_CONN_PER_CHILD=6000
MRW_CAP_PREFORK=1024
MRW_CAP_THREADED=1024
elif [[ "$TOTAL_MEM" -le 32768 && "$CORES" -ge 8 ]]; then
TIER="MID-HIGH"
APACHE_PCT="0.43"
PROCS_PER_CORE_CAP=44
THREADS_PER_CORE_CAP=200
START_SERVERS=4
MIN_SPARE=4
MAX_SPARE=10
MAX_CONN_PER_CHILD=8000
MRW_CAP_PREFORK=2048
MRW_CAP_THREADED=2048
else
TIER="HIGH"
APACHE_PCT="0.45"
PROCS_PER_CORE_CAP=40
THREADS_PER_CORE_CAP=200
START_SERVERS=5
MIN_SPARE=5
MAX_SPARE=12
MAX_CONN_PER_CHILD=10000
MRW_CAP_PREFORK=4096
MRW_CAP_THREADED=4096
fi
if [[ -n "$BUDGET_OVERRIDE" ]]; then
APACHE_PCT="$BUDGET_OVERRIDE"
BUDGET_SOURCE="override"
else
BUDGET_SOURCE="tier"
fi
}
measure_apache_procs() {
detect_apache_process_name
APACHE_PROCS=$(ps -C "$APACHE_PROC_NAME" -o rss= 2>/dev/null | wc -l || echo 0)
APACHE_RUNNING=0
[[ "$APACHE_PROCS" -gt 0 ]] && APACHE_RUNNING=1
AVG_PROC_MB=$(ps -C "$APACHE_PROC_NAME" -o rss= 2>/dev/null | awk '{sum+=$1; n++} END { if(n>0) printf "%.0f", sum/n/1024; else print 0 }')
if [[ -z "$AVG_PROC_MB" || "$AVG_PROC_MB" -le 0 ]]; then
if [[ "$MPM_TYPE" == "prefork" ]]; then
AVG_PROC_MB=35
else
AVG_PROC_MB=15
fi
fi
APACHE_BUDGET_MB=$(echo "$TOTAL_MEM * $APACHE_PCT" | bc | awk '{printf "%.0f", $0}')
}
apache_configtest() {
if [[ -z "${APACHE_CONFIGTEST_CMD:-}" ]]; then
detect_configtest_cmd
fi
case "$APACHE_CONFIGTEST_CMD" in
apachectl|apache2ctl)
"$APACHE_CONFIGTEST_CMD" configtest
;;
httpd)
httpd -t
;;
*)
echo "ERROR: No suitable Apache binary found for configtest."
return 1
;;
esac
}
json_bool() {
if [[ "$1" -eq 0 ]]; then
echo "false"
else
echo "true"
fi
}
format_batch_value() {
local value="$1"
local fallback="$2"
value=$(sanitize_value "${value:-}")
if [[ -z "$value" ]]; then
value="$fallback"
fi
echo "$value"
}
extract_tuner_block() {
local FILE="$1"
[[ -f "$FILE" ]] || return
sed -n '/# BEGIN APACHE_SMART_TUNER/,/# END APACHE_SMART_TUNER/p' "$FILE"
}
# Normalize whitespace so block comparisons ignore cosmetic drift.
normalize_block_for_compare() {
printf "%s" "$1" | sed 's/[[:space:]]*$//'
}
# Drive the main analysis path that turns runtime inputs into a config block.
run_analysis_pipeline() {
set_tier_params
measure_apache_procs
get_current_values_with_precedence
analyze_error_log
detect_configtest_cmd
build_recommended_block
}
build_json_output() {
local block_json
block_json=${RECOMMENDED_BLOCK//$'\n'/\\n}
cat <<EOF
{
"version": "$VERSION",
"mode": "$MODE",
"mpm": "$MPM_TYPE",
"mpm_source": "$MPM_SOURCE",