-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfastcgi_ops_root.sh
887 lines (789 loc) · 37 KB
/
fastcgi_ops_root.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
#!/bin/bash
# Copyright (C) 2024 Hasan CALISIR <hasan.calisir@psauxit.com>
# Distributed under the GNU General Public License, version 2.0.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# SCRIPT DESCRIPTION:
# -------------------
# This script is written for "FastCGI Cache Purge and Preload for Nginx"
# Wordpress Plugin.
# URL: https://wordpress.org/plugins/fastcgi-cache-purge-and-preload-nginx/
# This script attempts to automatically match and grant (via setfacl)
# permissions for PHP-FPM-USER (as known, process owner or website-user)
# along with their associated Nginx Cache Paths.
# If it cannot automatically match the PHP-FPM-USER along with their
# associated Nginx Cache Path, it offers an easy manual setup option
# with the 'manual-configs.nginx' file.
# Mainly, in case your current web server setup involves two distinct
# users, WEBSERVER-USER (nginx or www-data) and PHP-FPM-USER, the solution
# proposed by this script involves combining Linux server side tools
# 'inotifywait' with 'setfacl' to automatically grant write permissions
# to the PHP-FPM-USER for the corresponding Nginx Cache Paths (listening
# cache events), which are matched either automatically or via a manual
# configuration file.
# This approach is an alternative to external Nginx modules like Cache
# Purge module for purge operations.
# This script creates an npp-wordpress systemd service to manage grant
# permission for purge and preload actions.
# After completing the setup (whether automatic or manual), you can manage
# the automatically created 'npp-wordpress' systemd service on the WP admin
# dashboard NPP plugin settings page.
# This allows you to start and stop inotifywait/setfacl operations (via
# systemd) for Nginx Cache Path directly from the front-end for associated
# PHP-FPM-USER.
# Manual setup instructions
manual_setup() {
echo -e "\n\e[91mCanceled:\e[0m Automated Setup has been canceled by the user. Proceeding to manual setup."
# Provide instructions for manual configuration
echo -e "\e[36mTo set up manual configuration, create a file named \e[95m'manual-configs.nginx' \e[0m \e[36min current directory."
echo -e "Each entry should follow the format: 'PHP_FPM_USER NGINX_CACHE_PATH', with one entry per virtual host, space-delimited."
echo -e "Example --> psauxit /dev/shm/fastcgi-cache-psauxit <--"
echo -e "Ensure that every new website added to your host is accompanied by an entry in this file."
echo -e "After making changes, remember to restart the script \e[95mfastcgi_ops_root.sh\e[0m manually."
exit 1
}
# Handle ctrl+c
trap manual_setup SIGINT
# Get help before and interrupt
help() {
if command -v tput > /dev/null 2>&1; then
cyan=$(tput setaf 6)
reset=$(tput sgr0)
m_tab=' '
fi
echo -e "\n${m_tab}${cyan}# Wordpress FastCGI Cache Purge&Preload Help"
echo -e "${m_tab}# ---------------------------------------------------------------------------------------------------"
echo -e "${m_tab}#${m_tab}--wp-inotify-start need root! start listening events(cache folder), set ACL permission(PHP-FPM USER)"
echo -e "${m_tab}#${m_tab}--wp-inotify-stop need root! stop listening events(cache folder), unset ACL permission(PHP-FPM USER)"
echo -e "${m_tab}# ---------------------------------------------------------------------------------------------------${reset}\n"
}
# Check if script is executed as root
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
# Required commands
required_commands=(
"realpath"
"dirname"
"pgrep"
"basename"
"nginx"
"inotifywait"
"tune2fs"
"setfacl"
"systemctl"
)
# Check if required commands are available
for cmd in "${required_commands[@]}"; do
if ! command -v "$cmd" >/dev/null 2>&1; then
echo "Error: $cmd is not installed or not found in PATH."
exit 1
fi
done
# Check ACL configured properly
fs="$(df / | awk 'NR==2 {print $1}')"
if ! tune2fs -l "${fs}" | grep -q "Default mount options:.*acl"; then
echo "Filesystem not mounted with the acl!"
exit 1
fi
# Discover script path
this_script_full_path=$(realpath "${BASH_SOURCE[0]}")
this_script_path=$(dirname "${this_script_full_path}")
this_script_name=$(basename "${this_script_full_path}")
# Ensure script path is resolved
if [[ -z "${this_script_path}" ]]; then
echo "ERROR: Cannot find script path!"
exit 1
fi
# Enable extglob
# Remove trailing / (removes / and //) from script path
shopt -s extglob
this_script_path="${this_script_path%%+(/)}"
# Systemd service files
service_file_new="/etc/systemd/system/npp-wordpress.service"
service_file_old="/etc/systemd/system/wp-fcgi-notify.service"
# Define the main sudoers file and tmp/backup paths
SUDOERS_FILE="/etc/sudoers"
TEMP_FILE="/etc/sudoers.tmp"
BACKUP_FILE="/etc/sudoers.bak"
# Define NPP Wordpress sudoers config file
NPP_SUDOERS="npp_wordpress"
# Define the @includedir path if it does not already exist.
# We use a path other than "/etc/sudoers.d" to avoid overriding the user's current setup.
# Users may avoid using "/etc/sudoers.d" specifically because it is a catch-all directory
# where system package managers can place sudoers file rules during package installation.
CUSTOM_INCLUDEDIR_PATH="/etc/sudoers.npp"
# Check for sudo and visudo
check_sudo_and_visudo() {
for cmd in sudo visudo; do
command -v "${cmd}" > /dev/null 2>&1 || return 1
done
# Check if /etc/sudoers exists and not empty
if [[ ! -s "${SUDOERS_FILE}" ]]; then
return 1
fi
return 0
}
# Function to check/add for @includedir or #includedir (sudo v1.9.1 and older)
# to main sudoers file if not exists.
# We don't want to add entry to main sudoers file directly for safety.
find_create_includedir() {
if check_sudo_and_visudo; then
includedir_path=""
# Check for @includedir or #includedir in the sudoers file
while IFS= read -r line; do
if [[ "${line}" =~ ^[@#]includedir[[:space:]]+([^#]*) ]]; then
includedir_path="${BASH_REMATCH[1]}"
break
fi
done < "${SUDOERS_FILE}"
# Did we find any @includedir or #includedir?
if [[ -n "${includedir_path}" ]]; then
# Trim leading and trailing whitespace
includedir_path="${includedir_path#"${includedir_path%%[![:space:]]*}"}"
includedir_path="${includedir_path%"${includedir_path##*[![:space:]]}"}"
# Remove trailing slash if it exists
includedir_path="${includedir_path%/}"
# Check if the includedir is a directory if not create it
if ! [[ -d "${includedir_path}" ]]; then
mkdir -p "${includedir_path}" || { echo -e "\e[91mFailed to create includedir path\e[0m"; return 1; }
fi
else
# We need to add @includedir or #includedir to main sudoers file
# --> Workflow <--
# 1. Create sudoers backup/tmp files
# 2. Modify sudoers tmp file according to sudo version
# 3. Create includedir path before testing tmp file via visudo
# 4. Test tmp file before replacing the original sudoers file
# 5. Replace the original sudoers file with the tmp file
# 6. Test the updated sudoers file and restore from backup if there is an error
# 7. Clean up tmp and backup files
# 8. Assign custom_includedir to includedir
# 1. Create sudoers backup/tmp files
cp "${SUDOERS_FILE}" "${TEMP_FILE}" || { echo -e "\e[91mFailed to create sudoers tmp file\e[0m"; return 1; }
cp "${SUDOERS_FILE}" "${BACKUP_FILE}" || { echo -e "\e[91mFailed to create sudoers backup file\e[0m"; return 1; }
# 2. Modify sudoers tmp file according to sudo version
# Get the version of sudo to determine the correct includedir syntax (@ or #)
SUDO_VERSION="$(sudo -V | grep 'Sudo version' | awk '{print $3}')"
VERSION_MAJOR="$(echo "$SUDO_VERSION" | cut -d. -f1)"
VERSION_MINOR="$(echo "$SUDO_VERSION" | cut -d. -f2)"
# Check if SUDO_VERSION, VERSION_MAJOR, and VERSION_MINOR were successfully retrieved
if [[ -z "$SUDO_VERSION" || -z "$VERSION_MAJOR" || -z "$VERSION_MINOR" ]]; then
echo -e "\e[91mCannot find sudo version\e[0m"
return 1
fi
# Compare the version with reference 1.9.1 (https://www.sudo.ws/docs/man/sudoers.man/#Including_other_files_from_within_sudoers)
if [[ "${VERSION_MAJOR}" -gt 1 || ( "${VERSION_MAJOR}" -eq 1 && "${VERSION_MINOR}" -ge 9 ) ]]; then
echo "@includedir ${CUSTOM_INCLUDEDIR_PATH}" | sudo EDITOR='tee -a' visudo -f "${TEMP_FILE}" > /dev/null 2>&1 || { echo -e "\e[91mFailed to add includedir to sudoers file\e[0m"; return 1; }
else
echo "#includedir ${CUSTOM_INCLUDEDIR_PATH}" | sudo EDITOR='tee -a' visudo -f "${TEMP_FILE}" > /dev/null 2>&1 || { echo -e "\e[91mFailed to add includedir to sudoers file\e[0m"; return 1; }
fi
# 3. Create includedir path before testing tmp file via visudo
mkdir -p "${CUSTOM_INCLUDEDIR_PATH}" || { echo -e "\e[91mFailed to create /etc/sudoers.npp\e[0m"; return 1; }
# 4. Test tmp file before replacing the original sudoers file
if visudo -c -f "${TEMP_FILE}" > /dev/null 2>&1; then
# 5. Replace the original sudoers file with the tmp file
cp "${TEMP_FILE}" "${SUDOERS_FILE}" || { echo -e "\e[91mFailed to update sudoers file\e[0m"; return 1; }
fi
# 6. Test the updated sudoers file and restore from backup if there is an error
if ! visudo -c -f "${SUDOERS_FILE}" > /dev/null 2>&1; then
cp "${BACKUP_FILE}" "${SUDOERS_FILE}" || { echo -e "\e[91mFailed to return from sudoers backup file\e[0m"; return 1; }
return 1
fi
# 7. Clean up tmp and backup files
rm -f "${TEMP_FILE:?}"
rm -f "${BACKUP_FILE:?}"
# 8. Assign custom_includedir_path to includedir_path
includedir_path="${CUSTOM_INCLUDEDIR_PATH}"
fi
else
echo -e "\033[1;33mWarning:\033[1;36m '\033[1;35msudo\033[1;36m', '\033[1;35mvisudo\033[1;36m' need to be installed, and '\033[1;35m${SUDOERS_FILE}\033[1;36m' must exist to manage systemd service from WordPress admin dashboard directly. Skipped integration..\033[0m"
return 1
fi
return 0
}
# Automate the process of granting specific sudo permissions to the PHP-FPM
# process owners on a system. These permissions specifically authorize
# PHP-FPM process owners to execute systemctl commands (start, stop, status)
# for NPP plugin main systemd service 'npp-wordpress'.
# By granting these permissions, the goal is to allow the 'npp-wordpress'
# systemd service to be controlled directly from the WordPress admin
# dashboard, enhancing operational flexibility and automation.
# This automation enhances security by limiting sudo access to only
# specific systemd service management tasks.
# After successful integration, NPP users will be able to manage (start,
# stop, status) the 'npp-wordpress' systemd service on WP admin dashboard
# NPP plugin settings page.
# This implementation is not strictly necessary for functional cache
# purge & preload actions and does not break the default setup process,
# but it is nice to have this ability to control the main plugin systemd
# service 'npp-wordpress' on WP admin dashboard.
grant_sudo_perm_systemctl_for_php_process_owner() {
# Try to get/create the includedir first
if find_create_includedir; then
# Check if we have already implemented sudo privileges
if ! [[ -f "${includedir_path}/${NPP_SUDOERS}" ]]; then
SYSTEMCTL_PATH=$(type -P systemctl)
for user in "${!fcgi[@]}"; do
PERMISSIONS="${user} ALL=(ALL) NOPASSWD: ${SYSTEMCTL_PATH} start ${service_file_new##*/}, ${SYSTEMCTL_PATH} stop ${service_file_new##*/}, ${SYSTEMCTL_PATH} status ${service_file_new##*/}"
echo "${PERMISSIONS}" | sudo EDITOR='tee -a' visudo -f "${includedir_path}/${NPP_SUDOERS}" > /dev/null 2>&1 || { echo -e "\e[91mFailed to grant permission for npp-wordpress systemd service to PHP-FPM user: ${user}\e[0m"; return 1; }
done
chmod 0440 "${includedir_path}/${NPP_SUDOERS}"
fi
else
return 1
fi
# Check the integrity, checking main sudoers file is enough it also checks the includedir paths
if ! visudo -c -f "${SUDOERS_FILE}" > /dev/null 2>&1; then
# Revert back changes
rm "${includedir_path:?}/${NPP_SUDOERS:?}"
return 1
fi
return 0
}
# Restart setup
restart_auto_setup() {
if [[ $1 == "manual" ]]; then
setup_flag_nginx="${this_script_path}/manual-configs.nginx"
setup_flag="${this_script_path}/manual_setup_on"
else
setup_flag="${this_script_path}/auto_setup_on"
fi
# Remove the completed setup lock files
[[ -n "${setup_flag}" ]] && rm -f "${setup_flag}" > /dev/null 2>&1
[[ -n "${setup_flag_nginx}" ]] && rm -f "${setup_flag_nginx}" > /dev/null 2>&1
# Revert NPP sudoers configs
if check_sudo_and_visudo; then
# Check for @includedir or #includedir in the sudoers file
while IFS= read -r line; do
if [[ "${line}" =~ ^[@#]includedir[[:space:]]+([^#]*) ]]; then
includedir_path="${BASH_REMATCH[1]}"
break
fi
done < "${SUDOERS_FILE}"
# Did we find any @includedir or #includedir ?
if [[ -n "${includedir_path}" ]]; then
# Trim leading and trailing whitespace
includedir_path="${includedir_path#"${includedir_path%%[![:space:]]*}"}"
includedir_path="${includedir_path%"${includedir_path##*[![:space:]]}"}"
# Remove trailing slash if it exists
includedir_path="${includedir_path%/}"
fi
if [[ -f "${includedir_path}/${NPP_SUDOERS}" ]]; then
rm -f "${includedir_path:?}/${NPP_SUDOERS:?}"
fi
# Remove custom includedir in main sudoers file if we put before
# Check if includedir_path matches CUSTOM_INCLUDEDIR_PATH
if [[ "${includedir_path}" == "${CUSTOM_INCLUDEDIR_PATH}" ]]; then
# Create sudoers backup/tmp files
cp "${SUDOERS_FILE}" "${TEMP_FILE}"
cp "${SUDOERS_FILE}" "${BACKUP_FILE}"
# Use sed to remove the exact @includedir and #includedir lines from the sudoers file
sed -i "\|^@includedir ${CUSTOM_INCLUDEDIR_PATH}$|d" "${TEMP_FILE}" > /dev/null 2>&1
sed -i "\|^#includedir ${CUSTOM_INCLUDEDIR_PATH}$|d" "${TEMP_FILE}" > /dev/null 2>&1
# Test tmp before replacement with original
if visudo -c -f "${TEMP_FILE}" > /dev/null 2>&1; then
# Replace original with tmp
cp "${TEMP_FILE}" "${SUDOERS_FILE}"
fi
# Test original before remove backup, if we get error return from backup
if ! visudo -c -f "${SUDOERS_FILE}" > /dev/null 2>&1; then
cp "${BACKUP_FILE}" "${SUDOERS_FILE}"
else
# Clean up tmp/backup
rm -f "${TEMP_FILE:?}"
rm -f "${BACKUP_FILE:?}"
# Remove custom includedir
rmdir "${CUSTOM_INCLUDEDIR_PATH:?}" > /dev/null 2>&1
fi
fi
fi
# Stop and remove systemd service
if [[ -f "${service_file_new}" ]]; then
systemctl stop "${service_file_new##*/}" > /dev/null 2>&1
systemctl disable "${service_file_new##*/}" > /dev/null 2>&1
rm -f "${service_file_new}"
systemctl daemon-reload > /dev/null 2>&1
fi
# Migrate old service file as name changed -- wp-fcgi-notify.service --> npp-wordpress.service
if [[ -f "${service_file_old}" ]]; then
systemctl stop wp-fcgi-notify.service > /dev/null 2>&1
systemctl disable wp-fcgi-notify.service > /dev/null 2>&1
rm -f "${service_file_old}"
systemctl daemon-reload > /dev/null 2>&1
fi
# Restart the setup
exec bash "${this_script_path}/${this_script_name}"
}
# Print the currently listening Nginx Cache Paths
print_nginx_cache_paths() {
# Add a short delay to ensure all log entries are captured
sleep 2
journalctl -n 3 -u "${service_file_new##*/}" --no-pager \
| grep -E '(Started NPP|All done!)' \
| sed -E 's/.*?(Started NPP|All done!) /\1/' \
| awk '{
gsub(/\(/, "\x1b[33m(", $0);
gsub(/\)/, ")\x1b[0m\x1b[36m", $0);
print "\x1b[36m" $0 "\x1b[0m"
}'
echo ""
}
# Prompt restart setup or apply changes in current setup
# Check if running in an interactive terminal
if [[ -t 0 ]]; then
if [[ -f "${this_script_path}/auto_setup_on" ]]; then
# User prompt for fresh restart auto setup
read -rp $'\e[96mAuto setup has already been completed. If you want to restart the setup, select [R/r]. If you want to just apply \e[93mnginx.conf\e[0m \e[96mchanges, select [A/a] \e[92m[R/A]: \e[0m' restart_confirm
if [[ $restart_confirm =~ ^[Rr]$ ]]; then
restart_auto_setup
elif [[ $restart_confirm =~ ^[Aa]$ ]]; then
# Handle newly added Nginx Cache Paths to take affect immediately with service restart (modified nginx.conf)
systemctl restart "${service_file_new##*/}" > /dev/null 2>&1
# Check if the service restarted successfully
if systemctl is-active --quiet "${service_file_new##*/}"; then
echo ""
echo -e "\e[92mSuccess:\e[0m Systemd service \e[93mnpp-wordpress\e[0m is re-started. If there are newly added Nginx Cache paths to \e[93mnginx.conf\e[0m, they should now be listening via \e[93minotifywait/setfacl\e[0m."
print_nginx_cache_paths
else
echo -e "\e[91mError:\e[0m Systemd service \e[93mnpp-wordpress\e[0m failed to restart."
fi
else
exit 0
fi
elif [[ -f "${this_script_path}/manual_setup_on" ]]; then
read -rp $'\e[96mManual setup via \e[35m'"${this_script_path}"$'/manual-configs.nginx\e[96m has already been completed. If you want to restart the setup, select [R/r]. If you want to just apply \e[35mmanual-configs.nginx\e[0m \e[96mchanges, select [A/a] \e[92m[R/A]: \e[0m' restart_confirm
if [[ $restart_confirm =~ ^[Rr]$ ]]; then
restart_auto_setup manual
elif [[ $restart_confirm =~ ^[Aa]$ ]]; then
# Handle newly added Nginx Cache Paths to take affect immediately with service restart (modified manual-configs.nginx)
systemctl restart "${service_file_new##*/}" > /dev/null 2>&1
# Check if the service restarted successfully
if systemctl is-active --quiet "${service_file_new##*/}"; then
echo ""
echo -e "\e[92mSuccess:\e[0m Systemd service \e[93mnpp-wordpress\e[0m is re-started. If there are newly added Nginx Cache paths to \e[93mmanual-configs.nginx\e[0m, they should now be listening via \e[93minotifywait/setfacl\e[0m."
print_nginx_cache_paths
else
echo -e "\e[91mError:\e[0m Systemd service \e[93mnpp-wordpress\e[0m failed to restart."
fi
else
exit 0
fi
elif [[ -f "${service_file_new}" || -f "${service_file_old}" ]]; then
read -rp $'\e[96mIt appears that an instance of the setup has already been completed in a different directory. Do you want to remove old and restart the clean setup here? \e[92m[Y/n]: \e[0m' restart_confirm
if [[ $restart_confirm =~ ^[Yy]$ ]]; then
restart_auto_setup
else
# Prevent multiple setup in different locations
exit 0
fi
fi
fi
# Function to dynamically detect the location of nginx.conf
detect_nginx_conf() {
local DEFAULT_NGINX_CONF_PATHS=(
"/etc/nginx/nginx.conf"
"/usr/local/nginx/conf/nginx.conf"
)
for path in "${DEFAULT_NGINX_CONF_PATHS[@]}"; do
if [[ -f "$path" ]]; then
NGINX_CONF="$path"
break
fi
done
if [[ -z "$NGINX_CONF" ]]; then
echo ""
echo -e "\e[31mError: Nginx configuration file (\e[33mnginx.conf\e[31m) not found in default paths.\e[0m"
echo -e "\e[36mPlease create a symbolic link from your original \e[33mnginx.conf\e[36m to \e[33m/etc/nginx/nginx.conf\e[36m, or continue with manual setup.\e[0m"
echo -e "\e[36mExample: ln -s \e[33m/path/to/your/original/nginx.conf\e[36m \e[33m/etc/nginx/nginx.conf\e[0m"
# Provide instructions for manual configuration
echo ""
echo -e "\e[35mManual Setup Instructions\e[0m\n\e[36m#########################\e[0m"
echo -e "\n\e[36mTo set up manual configuration, create a file named \e[95m'manual-configs.nginx' \e[0m \e[36min current directory."
echo -e "Each entry should follow the format: 'PHP_FPM_USER NGINX_CACHE_PATH', with one entry per virtual host, space-delimited."
echo -e "Example --> psauxit /dev/shm/fastcgi-cache-psauxit <--"
echo -e "Ensure that every new website added to your host is accompanied by an entry in this file."
echo -e "After making changes, remember to restart the script \e[95mfastcgi_ops_root.sh\e[0m."
echo ""
exit 1
fi
}
# Function to extract FastCGI cache paths from NGINX configuration files
extract_fastcgi_cache_paths() {
{
# Extract paths from directly nginx.conf
grep -E "^\s*fastcgi_cache_path\s+" "$NGINX_CONF" | awk '{print $2}'
# Also get included paths to nginx.conf and extract fastcgi cache paths
while IFS= read -r include_line; do
include_path=$(echo "$include_line" | awk '{print $2}')
# Check wildcard for multiple files
if [[ "${include_path}" == *"*"* ]]; then
# Remove wildcard, slash, get the exact path
target_dir=$(echo "$include_path" | sed 's/\*.*//' | sed 's/\/$//')
else
# This is a directly included single file
grep -E "^\s*fastcgi_cache_path\s+" "${include_path}" | awk '{print $2}'
fi
# Search for fastcgi_cache_path in the target directory recursively
if [ -d "${target_dir}" ]; then
find -L "${target_dir}" -type f -exec grep -H "fastcgi_cache_path" {} + | awk -F: '{print $2":"$3}' | sed '/^\s*#/d' | awk '{print $2}'
fi
done < <(grep -E "^\s*include\s+" "${NGINX_CONF}" | grep -v "^\s*#" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/;//')
} | sort | uniq
}
# Function to validate FastCGI cache paths for safety
validate_cache_paths() {
local path_list=("$@")
local invalid_paths=()
local critical_dirs=("/bin" "/boot" "/etc" "/home" "/lib" "/media" "/mnt" "/opt" "/proc" "/root" "/sbin" "/srv" "/sys" "/usr")
for path in "${path_list[@]}"; do
# Check if path is just '/'
if [[ "$path" == "/" ]]; then
invalid_paths+=("$path")
continue
fi
# Check Nginx cache path is a critical directory or starts with any critical directory
for critical in "${critical_dirs[@]}"; do
if [[ "$path" == "$critical" || "$path" == "$critical/"* ]]; then
invalid_paths+=("$path")
break
fi
done
done
if [[ ${#invalid_paths[@]} -gt 0 ]]; then
if [[ -s "${this_script_path}/manual-configs.nginx" ]]; then
echo -e "\033[0;36m\033[91mError:\033[0m \033[0;36mThe following Nginx Cache Paths in '\033[35mmanual-configs.nginx\033[0;36m' file are critical system directories or root directory and cannot be used:\033[0m"
echo -e "\033[33mFor safety, paths such as '/home' and other critical system paths are prohibited in default. Best practice using directories like '/dev/shm/' or '/var/cache/'\033[0m"
else
echo -e "\033[91mError:\033[0m \033[0;36mThe automatically detected following Nginx Cache Paths are critical system directories or root directory and cannot be used:\033[0m"
echo -e "\033[33mFor safety, paths such as '/home' and other critical system paths are prohibited in default. Best practice using directories like '/dev/shm/' or '/var/cache/'\033[0m"
fi
for invalid in "${invalid_paths[@]}"; do
echo ""
echo -e "\033[0;31m$invalid\033[0m"
done
return 1
fi
}
# Auto detection stuff
if ! [[ -f "${this_script_path}/manual-configs.nginx" ]]; then
# Get nginx.conf
detect_nginx_conf
# Extract FastCGI Cache Paths from nginx.conf
FASTCGI_CACHE_PATHS=$(extract_fastcgi_cache_paths)
# Find active vhosts
ACTIVE_VHOSTS=$(nginx -T 2>/dev/null | grep -E "server_name|fastcgi_pass" | grep -B1 "fastcgi_pass" | grep "server_name" | awk '{print $2}' | sed 's/;$//')
# Find all php-fpm users
PHP_FPM_USERS=$(grep -ri -h -E "^\s*user\s*=" /etc/php | awk -F '=' '{print $2}' | sort | uniq | sed 's/^\s*//;s/\s*$//' | grep -v "nobody")
# Validate the found Nginx FastCGI cache paths
if ! validate_cache_paths ${FASTCGI_CACHE_PATHS}; then
exit 1
fi
# Associative array to store php-fpm user and fastcgi cache path
declare -A fcgi
# Loop through active vhosts
while IFS= read -r VHOST; do
ACTIVE_VHOSTS+=("$VHOST")
# Extract PHP-FPM users from running processes, excluding root
while read -r user; do
ACTIVE_PHP_FPM_USERS+=("$user")
done < <(ps -eo user:30,cmd | grep "[p]hp-fpm:.*$VHOST" | awk '{print $1}' | awk '!seen[$0]++' | grep -v "root")
done <<< "$ACTIVE_VHOSTS"
# Check if the PHP-FPM user's name is present in the FastCGI cache path
for PHP_FPM_USER in $PHP_FPM_USERS; do
for FASTCGI_CACHE_PATH in $FASTCGI_CACHE_PATHS; do
if echo "$FASTCGI_CACHE_PATH" | grep -q "$PHP_FPM_USER"; then
fcgi["$PHP_FPM_USER"]="$FASTCGI_CACHE_PATH"
break
fi
done
done
# Check if the user exists
for user in "${!fcgi[@]}"; do
if ! id "$user" &>/dev/null; then
echo -e "\e[91mError:\e[0m User: $user does not exist. Please ensure the user exists and try again."
exit 1
fi
done
fi
# Systemd operations
check_and_start_systemd_service() {
# Check if the service file exists, if not create it
if [[ ! -f "${service_file_new}" ]]; then
# Generate systemd service file
cat <<- NGINX_ > "${service_file_new}"
[Unit]
Description=NPP Wordpress Plugin Cache Operations Service
After=network.target nginx.service local-fs.target
Requires=nginx.service
[Service]
KillSignal=SIGKILL
TimeoutStopSec=5
Type=simple
RemainAfterExit=yes
User=root
Group=root
ProtectSystem=full
ExecStart=/bin/bash ${this_script_path}/${this_script_name} --wp-inotify-start
ExecStop=/bin/bash ${this_script_path}/${this_script_name} --wp-inotify-stop
[Install]
WantedBy=multi-user.target
NGINX_
# Check if generating the service file was successful
if [[ $? -ne 0 ]]; then
echo -e "\e[91mError:\e[0m Failed to create systemd service file."
exit 1
fi
# Reload systemd
systemctl daemon-reload > /dev/null 2>&1 || {
echo -e "\e[91mError:\e[0m Failed to reload systemd daemon."
exit 1
}
# Enable and start the service
systemctl enable --now "${service_file_new##*/}" > /dev/null 2>&1 || {
echo -e "\e[91mError:\e[0m Failed to enable and start systemd service."
exit 1
}
# Check if the service started successfully
if systemctl is-active --quiet "${service_file_new##*/}"; then
echo ""
echo -e "\e[92mSuccess:\e[0m Systemd service \e[93mnpp-wordpress\e[0m is started."
else
echo -e "\e[91mError:\e[0m Systemd service \e[93mnpp-wordpress\e[0m failed to start."
fi
else
if systemctl is-active --quiet "${service_file_new##*/}"; then
systemctl stop "${service_file_new##*/}" > /dev/null 2>&1
fi
systemctl start "${service_file_new##*/}" > /dev/null 2>&1 && echo -e "\e[92mSuccess:\e[0m Systemd service \e[93mnpp-wordpress\e[0m is re-started."
fi
}
# Check if manual configuration file exists
if [[ -f "${this_script_path}/manual-configs.nginx" ]]; then
if [[ ! -s "${this_script_path}/manual-configs.nginx" ]]; then
echo -e "\e[91mError:\e[0m The manual configuration file 'manual-configs.nginx' is empty. Please provide configuration details and try again."
exit 1
fi
# Reset/clear associative array that we continue with manual setup
declare -A fcgi=()
# Read manual configuration file
while IFS= read -r line; do
# Trim leading and trailing whitespace from the line
line=$(echo "$line" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
# Check if the line is empty after trimming whitespace
if [[ -z "$line" ]]; then
continue # Skip empty lines
fi
# Validate the format of the line (expects "user cache_path")
if [[ "$(echo "$line" | awk '{print NF}')" -ne 2 ]]; then
echo -e "\e[91mError:\e[0m Invalid format in the manual configuration file 'manual-configs.nginx'. Each line must contain only two fields: 'PHP_FPM_USER NGINX_CACHE_PATH'"
echo "Invalid line: $line"
exit 1
fi
# Validate the format of the line (expects "PHP_FPM_USER NGINX_CACHE_PATH")
if [[ ! "$line" =~ ^[[:alnum:]_-]+\ [[:print:]]+$ ]]; then
echo -e "\e[91mError:\e[0m Invalid format in the manual configuration file 'manual-configs.nginx'. Each line must be in the format 'PHP_FPM_USER NGINX_CACHE_PATH'"
echo "Invalid line: $line"
exit 1
fi
# Extract PHP-FPM user and FastCGI cache path from each line
user=$(echo "$line" | awk '{print $1}')
cache_path=$(echo "$line" | awk '{print $2}')
# Validate the Nginx FastCGI cache path
if ! validate_cache_paths "$cache_path"; then
exit 1
fi
# Check if the directory exists
if [[ ! -d "$cache_path" ]]; then
echo -e "\e[33mWarning: Cache path $cache_path for user $user does not exist. This vhost will be excluded if other vhosts are successful.\e[0m"
fi
# Check if the user exists
if ! id "$user" &>/dev/null; then
echo -e "\e[91mError:\e[0m User: $user specified in the manual configuration file does not exist. Please ensure the user exists and try again."
exit 1
fi
fcgi["$user"]="$cache_path"
done < "${this_script_path}/manual-configs.nginx"
# Check manual setup already completed or not
if ! [[ -f "${this_script_path}/manual_setup_on" ]]; then
check_and_start_systemd_service && touch "${this_script_path}/manual_setup_on"
print_nginx_cache_paths
if grant_sudo_perm_systemctl_for_php_process_owner; then
echo -e "\e[92mSuccess:\e[0m sudo privileges granted for systemd service \e[93mnpp-wordpress\e[0m to PHP-FPM users"
for user in "${!fcgi[@]}"; do
echo -e "User: \e[93m${user}\e[0m is a passwordless sudoer to manage the systemd service \e[93mnpp-wordpress\e[0m"
done
fi
echo ""
fi
else
if (( ${#fcgi[@]} == 0 )); then
echo ""
echo -e "\e[91mError:\e[0m Auto setup failed! Nginx cache paths with associated PHP-FPM users cannot be automatically detected."
echo -e "\e[91mPlease ensure that your Nginx configuration is properly set up. \e[95mIf the issue persist please try to manual setup.\e[0m"
# Provide instructions for manual configuration
echo -e "\n\e[36mTo set up manual configuration, create a file named \e[95m'manual-configs.nginx' \e[0m \e[36min current directory."
echo -e "Each entry should follow the format: 'PHP_FPM_USER NGINX_CACHE_PATH', with one entry per virtual host, space-delimited."
echo -e "Example --> psauxit /dev/shm/fastcgi-cache-psauxit <--"
echo -e "Ensure that every new website added to your host is accompanied by an entry in this file."
echo -e "After making changes, remember to restart the script \e[95mfastcgi_ops_root.sh\e[0m."
echo ""
exit 1
fi
# check auto setup already completed or not
if ! [[ -f "${this_script_path}/auto_setup_on" ]]; then
green=$(tput setaf 2)
magenta=$(tput setaf 5)
reset=$(tput sgr0)
# remove duplicates from array
ACTIVE_PHP_FPM_USERS=($(printf "%s\n" "${ACTIVE_PHP_FPM_USERS[@]}" | sort -u))
# Convert PHP_FPM_USERS string to an array
IFS=$'\n' read -r -d '' -a PHP_FPM_USERS <<< "${PHP_FPM_USERS}"
echo ""
echo -e "${green}AUTO DETECTION STARTED${reset}"
echo -e "\e[96mNOTE: You can always continue with the manual setup via (\e[95mN/n\e[96m) if the auto detection does not work for you.\e[0m"
echo ""
echo -e "${green}All PHP-FPM Users:${reset}"
echo -e "${magenta}${PHP_FPM_USERS[@]:-"None"}${reset}"
echo -e "${green}Dynamic PHP-FPM Users:${reset}"
echo -e "${magenta}${ACTIVE_PHP_FPM_USERS[@]:-"None"}${reset}"
echo -e "${green}Ondemand PHP-FPM Users:${reset}"
echo -e "${magenta}$(comm -23 <(printf "%s\n" "${PHP_FPM_USERS[@]}") <(printf "%s\n" "${ACTIVE_PHP_FPM_USERS[@]}"))${reset}"
# Print detected FastCGI cache paths and associated PHP-FPM users for auto setup confirmation
echo ""
echo -e "\e[96mAuto detected Nginx cache paths and associated PHP-FPM users:\e[0m"
for user in "${!fcgi[@]}"; do
echo -e "User: \e[92m$user\e[0m, Nginx Cache Path: \e[93m${fcgi[$user]}\e[0m"
done
read -rp $'\e[96mDo you want to continue with the auto configuration? This may takes a while.. \e[92m[Y/n]: \e[0m' confirm
if [[ $confirm =~ ^[Yy]$ ]]; then
check_and_start_systemd_service && touch "${this_script_path}/auto_setup_on"
print_nginx_cache_paths
if grant_sudo_perm_systemctl_for_php_process_owner; then
echo -e "\e[92mSuccess:\e[0m sudo privileges granted for systemd service \e[93mnpp-wordpress\e[0m to PHP-FPM users"
for user in "${!fcgi[@]}"; do
echo -e "User: \e[93m${user}\e[0m is a passwordless sudoer to manage the systemd service \e[93mnpp-wordpress\e[0m"
done
fi
echo ""
else
manual_setup
fi
fi
fi
# listens fastcgi cache folder for create events and
# give write permission to website user for further purge operations.
inotify-start() {
# Check instances properly
if (( ${#fcgi[@]} == 0 )); then
# If non instance set up, exit
echo "There is no any instance, please read documentation"
exit 1
elif (( ${#fcgi[@]} == 1 )); then
# if only one instance exists and it is broken, exit
for path in "${!fcgi[@]}"; do
if ! [[ -d "${fcgi[$path]}" ]]; then
echo "Your FastCGI cache directory (${fcgi[$path]}) not found, if path is correct please restart nginx.service to automatically create it"
exit 1
fi
done
elif (( ${#fcgi[@]} > 1 )); then
# In many instances If only one instance is broken, exclude and continue
for path in "${!fcgi[@]}"; do
if ! [[ -d "${fcgi[$path]}" ]]; then
echo "Your FastCGI cache directory (${fcgi[$path]}) not found, if path is correct please restart nginx.service to automatically create it, EXCLUDED"
unset "fcgi[$path]"
fi
done
fi
# Prevent starting multiple instances for same path
for path in "${!fcgi[@]}"; do
if pgrep -f "inotifywait.*${fcgi[$path]}" >/dev/null 2>&1; then
echo "Your FastCGI cache directory (${fcgi[$path]})is already listening, EXCLUDED"
unset "fcgi[$path]"
fi
done
# Check if all instances are excluded and already running
all_excluded=true
for path in "${!fcgi[@]}"; do
if ! pgrep -f "inotifywait.*${fcgi[$path]}" >/dev/null 2>&1; then
all_excluded=false
break
fi
done
# Exit if all instances are excluded and already running
if [ "$all_excluded" = true ]; then
echo "All instances(paths) already listening, nothing to do"
exit 0
fi
# Exit if all instances are excluded and already running
#! (( "${#fcgi[@]}" )) && { echo "All instances(paths) already listening, nothing to do"; exit 0; }
# start to listen fastcgi cache folder events
# give write permission to website user for further purge ops
for user in "${!fcgi[@]}"
do
setfacl -R -m u:"${user}":rwX,g:"${user}":rwX "${fcgi[$user]}"/
# Start inotifywait/setfacl
while read -r directory event file_folder; do
# While this loop working If fastcgi cache path
# deleted manually by user that cause strange
# behaviours, kill it
if [[ ! -d "${fcgi[$user]}" ]]; then
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "Cache folder ${fcgi[$user]} destroyed manually, inotifywait/setfacl process for user: ${user} is killed!"
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
break
fi
# Set ACLs for files and folders created and modified in cache directory
setfacl -R -m u:"${user}":rwX,g:"${user}":rwX "${fcgi[$user]}"/
done < <(inotifywait -m -q -e modify,create -r "${fcgi[$user]}") >/dev/null 2>&1 &
done
# Check if inotifywait processes are alive
for path in "${!fcgi[@]}"; do
if pgrep -f "inotifywait.*${fcgi[$path]}" >/dev/null 2>&1; then
echo "All done! Started to listen to Nginx FastCGI Cache Path: (${fcgi[$path]}) events to set up ACLs for PHP-FPM-USER: (${path})"
else
echo "Unknown error occurred during cache listen event."
fi
done
}
# stop on-going preload actions
# the rest of the stuff (killing child processes) will handled by systemd via stop command
inotify-stop() {
# Kill on-going preload process for all websites first
for load in "${!fcgi[@]}"; do
read -r -a PIDS <<< "$(pgrep -a -f "wget.*-q -m -p -E -k -P ${fcgi[$load]}" | grep -v "cpulimit" | awk '{print $1}')"
if (( "${#PIDS[@]}" )); then
for pid in "${PIDS[@]}"; do
if ps -p "${pid}" >/dev/null 2>&1; then
kill -9 $pid && echo "Cache preload process $pid for website $load is killed!"
else
echo "No cache preload process found for website $load - last running process was $pid"
fi
done
else
echo "No cache preload process found for website $load"
fi
done
}
# set script arguments
case "$1" in
--wp-inotify-start ) inotify-start ;;
--wp-inotify-stop ) inotify-stop ;;
* )
if [ $# -gt 1 ]; then
help
fi ;;
esac