-
Notifications
You must be signed in to change notification settings - Fork 2
/
patches.sh
2039 lines (1719 loc) · 74.4 KB
/
patches.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
################################################################################
# Initial definitions required for the rest of the program #
################################################################################
SCRIPT_DIR=$(cd $(dirname $0); pwd)
TOP_DIR=$(cd ${SCRIPT_DIR}/../; pwd)
NGINX_CONFIG_DIR=${SCRIPT_DIR}/nginx_config
containers=("patches-psql" "patches-backend" "patches-frontend" "patches-httpd" "patches-nginx" )
cd ${TOP_DIR}
IMPORT_KEYS=1 # Used to determine if the code was run with import keys
# Function: patches_echo
#
# Description: Custom echo command for Patches scripts. Changes the output color to a readable font
# that stands out and adds a logging timestamp to each message.
#
# Parameters:
# - message: The message to be printed.
# - options: Additional options for customization. Supported options: "--error".
#
# Returns: None
#
function patches_echo() {
local timestamp=$(date +"%Y-%m-%d %H:%M:%S")
local color='\033[1;33m' # Yellow color
local error_color='\033[1;31m' # Red color
local reset_color='\033[0m' # Reset color
local message="$1"
local option="$2"
# Print first line of 80 #
printf '%.0s#' {1..80}
echo
if [[ "$option" == "--error" ]]; then
# Print timestamp and modified message in red color
printf "${timestamp} - ${error_color}%s${reset_color}\n" "$message" | fold -sw 80
else
# Print timestamp and modified message in yellow color
printf "${timestamp} - ${color}%s${reset_color}\n" "$message" | fold -sw 80
fi
# Print last line of 80 #
printf '%.0s#' {1..80}
echo
}
# Function: patches_read
#
# Description: Custom read command for Patches scripts. Prompts the user for input
# and sets the text color to a bold blue.
#
# Parameters:
# - prompt: The prompt message to display to the user.
# - --password: (Optional) Use this option to securely read a password without displaying the input.
#
# Environment Variables:
# - RETURN_VALUE: A global variable that stores the user input.
#
# Returns: The user input.
#
function patches_read() {
local color='\033[1;34m' # Bold blue color
local reset_color='\033[0m' # Reset color
local prompt="$@"
local wrapped_prompt=""
local line_length=0
local password=false
if [[ "$prompt" == *"--password"* ]]; then
# --password is present in the prompt
password=true
fi
# Print first line of 80 #
printf '%.0s#' {1..80}
echo
# Wrap the prompt at 80 characters
for word in $prompt; do
if [[ "$word" != "--password" ]]; then # Skip "--password" from the wrapped prompt
if (( line_length + ${#word} > 80 )); then
wrapped_prompt+="\n${word}"
line_length=${#word}
else
if (( line_length > 0 )); then
wrapped_prompt+=" ${word}"
line_length=$(( line_length + ${#word} + 1 ))
else
wrapped_prompt+="${word}"
line_length=${#word}
fi
fi
fi
done
# Print prompt message
echo -ne "${color}${wrapped_prompt}${reset_color}"
# Print last line of 80 #
echo
printf '%.0s#' {1..80}
echo
# Read user input
if [ "${password}" = true ]; then
# Read password securely (hidden input)
read -s input
else
read input
fi
# Set the value of RETURN_VALUE variable
RETURN_VALUE="$input"
}
################################################################################
# Perform checks to make sure that the conditions required to run the program #
# are met. #
################################################################################
if [[ $(id -u) = 0 ]]; then
patches_echo "Please do not run $(basename $0) as root, it is designed to be run as a normal user account that has podman permissions."
exit 1
fi
if [[ $# -eq 0 ]] ; then
patches_echo 'No arguments provided. Run with -h for help.'
exit 1
fi
if ! command -v wget &>/dev/null; then
patches_echo "wget is not installed. Please install wget to continue."
exit 1
fi
################################################################################
# Function definitions #
################################################################################
# Function: get_ip_address
#
# Description: Prompts the user to select an interface with an assigned IPv4 address and UP/UP state.
#
# Environment Variables:
# - interface: A global variable that stores the selected interface.
# - ipv4_address: A global variable that stores the IPv4 address of the selected interface.
#
# Returns: None
function get_ip_address() {
patches_echo "Checking interfaces..."
# Check for invalid interfaces and inform the user that they are ignored
for iface in $(ip addr | awk '/state/ {print $2}' | sed 's/://; /^lo/d' | grep -v "${interfaces}")
do
patches_echo "Ignored $iface because it is not in an UP/UP state with an assigned IPv4 address."
done
# Get a list of physical interfaces in an UP/UP state with an assigned IPv4 address
interfaces=$(ip addr | awk '/state UP/ {print $2}' | sed 's/://; /^lo/d' | xargs -I {} sh -c 'if ip addr show {} | grep -q "inet "; then echo {}; fi')
if [ -z "${interfaces}" ]; then
patches_echo "No interfaces found with an assigned IPv4 address and UP/UP state."
exit 1
fi
# Prompt the user to enter an interface
patches_echo "List of available interfaces:"
PS3=$(echo -e "\033[1;34mEnter the number of the interface you want to use: \033[0m")
select interface in "${interfaces[@]}"
do
if [ -z "$interface" ]; then
patches_echo "Invalid input. Please enter a number from 1 to $(echo "${#interfaces[@]}" | wc -w)."
else
ipv4_address=$(ip addr show "$interface" | awk '$1 == "inet" {gsub(/\/.*$/, "", $2); print $2}')
patches_echo "Using interface $interface with IPv4 address $ipv4_address."
break
fi
done
}
# Function to generate a random color code
get_random_color() {
local colors=("31" "32" "33" "34" "35" "36")
local num_colors=${#colors[@]}
local random_index=$((RANDOM % num_colors))
echo "${colors[random_index]}"
}
# Function: print_ascii_art
#
# Description: Prints ASCII art with random colors and a border of # symbols.
#
# Parameters:
# - ascii_art: The ASCII art to be printed.
#
# Returns: None
#
function print_ascii_art() {
local ascii_art=$1
# Print the border of #
printf '%.0s#' {1..80}
echo
# Save the current IFS value
local original_ifs=$IFS
# Set the IFS to empty to preserve leading/trailing spaces
IFS=
# Read each line of the ASCII art and print in random colors
while IFS= read -r line; do
color_code="\033[1;$(get_random_color)m"
reset_color="\033[0m"
printf "${color_code}%s${reset_color}\n" "$line"
done <<< "$ascii_art"
# Restore the original IFS value
IFS=$original_ifs
# Print the border of #
printf '%.0s#' {1..80}
echo
}
ascii_art=$(cat << "EOF"
___ _ _
| _ \ __ _ | |_ __ | |_ ___ ___
| _/ / _` | | _| / _| | ' \ / -_) (_-<
_|_|_ \__,_| _\__| \__|_ |_||_| \___| /__/_
_| """ |_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|
"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'
EOF
)
# Call the function to print the ASCII art
print_ascii_art "$ascii_art"
# Function: ask_yes_no
#
# Description: This function prompts the user with a yes/no question, validates the input,
# and returns a boolean value indicating the user's choice.
#
# Parameters:
# - prompt: The prompt message to display to the user.
#
# Returns:
# - 0: If the user answers "yes".
# - 1: If the user answers "no".
#
function ask_yes_no() {
local prompt="$1 (yes/no): "
local response
while true; do
patches_read "$prompt"
response=${RETURN_VALUE}
case "$response" in
[Yy][Ee][Ss])
return 0
;;
[Nn][Oo])
return 1
;;
*)
patches_echo "Invalid input. Please enter either 'yes' or 'no'."
;;
esac
done
}
# Function: parse_yaml
#
# Description: This function parses a YAML file and converts it to a Bash script.
# It takes the path to the YAML file and a prefix as parameters.
# The function processes the YAML file and generates Bash variable
# declarations based on its contents.
#
# Parameters:
# - $1: The path to the YAML file to parse.
# - $2: The prefix to use for Bash variable names.
#
# Returns: None
#
function parse_yaml {
local prefix=$2
# Define regular expressions to match various parts of YAML syntax
local s='[[:space:]]*'
local w='[a-zA-Z0-9_]*'
local fs=$(echo @|tr @ '\034')
# Use sed to replace various parts of the YAML with Bash syntax
sed -ne "s|^\($s\):|\1|" \
-e "s|^\($s\)\($w\)$s:$s[\"']\(.*\)[\"']$s\$|\1$fs\2$fs\3|p" \
-e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p" $1 |
# Use awk to create Bash variables based on the YAML data
awk -F$fs '{
indent = length($1)/2;
vname[indent] = $2;
for (i in vname) {
if (i > indent) {
delete vname[i]
}
}
if (length($3) > 0) {
vn="";
for (i=0; i<indent; i++) {
vn=(vn)(vname[i])("_")
}
printf("%s%s%s=\"%s\"\n", "'$prefix'",vn, $2, $3);
}
}'
}
# Function: configure_administrator
#
# Description: Configures the administrator for the PostgreSQL database. Executes an SQL script
# within the specified PostgreSQL container to set up the admin user, roles, and permissions.
#
# Parameters:
# - administrator_name: The name of the administrator for patches.
#
# Environment Variables:
# - PSQL_USERNAME: The username for connecting to the PostgreSQL database.
# - PSQL_PASSWORD: The password for connecting to the PostgreSQL database.
# - PSQL_PORT: The port number for the PostgreSQL database.
# - POSTGRES_DB: The name of the PostgreSQL database.
#
# Returns: None
#
configure_administrator() {
patches_echo "Configuring ${1} as an administrator for the PostgreSQL database..."
# URL encode the password
urlencode() {
local string="${1}"
local strlen=${#string}
local encoded=""
local pos c o
for ((pos = 0; pos < strlen; pos++)); do
c="${string:$pos:1}"
case "$c" in
[-_.~a-zA-Z0-9]) o="${c}" ;;
*) printf -v o '%%%02x' "'$c"
esac
encoded+="${o}"
done
echo "${encoded}"
}
encoded_password=$(urlencode "${PSQL_PASSWORD}")
# Construct the connection URL with the encoded password
connection_url="postgresql://${PSQL_USERNAME}:${encoded_password}@patches-psql:${PSQL_PORT}/${POSTGRES_DB}"
# Check if the user already exists in the user_roles table
user_exists=$(echo "SELECT COUNT(*) FROM user_roles WHERE username = '${1}';" | podman exec -i "patches-psql" psql -t "${connection_url}")
if [ "${user_exists}" -eq 0 ]; then
# User doesn't exist in user_roles table, insert a new row
echo "-- SQL script for setting up admin user
INSERT INTO users (name) VALUES ('${1}');
INSERT INTO user_roles (username, role_id, updating_user)
VALUES ('${1}', 1, 'System');
" | podman exec -i "patches-psql" psql "${connection_url}"
patches_echo "${1} added as a Patches administrator."
else
# User already exists in user_roles table, update the role
echo "-- SQL script for updating admin role
UPDATE user_roles SET role_id = 1, updating_user = 'System'
WHERE username = '${1}';
" | podman exec -i "patches-psql" psql "${connection_url}"
patches_echo "${1}'s administrator role updated."
fi
}
# Function: cleanup_containers
#
# Description: Stops and removes old containers for the specified names using podman.
#
# Parameters:
# None
#
# Environment Variables:
# None
#
# Returns: None
#
function cleanup_containers() {
patches_echo "Removing any old containers..."
for container in "${containers[@]}"
do
podman rm -f -t 0 $container
# We ignore errors here beacuse if there are no volumes it will complain
podman volume rm -f $(podman volume ls -q) 2> /dev/null || true
done
}
# Function: reset_database
#
# Description: Resets the database by removing parsed XML files and running Knex database migrations.
# It deletes the parsed XML files directory and executes Knex migrate:rollback and migrate:latest commands.
#
# Parameters: None
#
# Environment Variables:
# - TOP_DIR: The top-level directory path.
#
# Returns: None
#
function reset_database() {
patches_echo "Reinitializing database by clearing the ${TOP_DIR}/repos/xml/parsed/ directory and resetting the PSQL database..."
rm -rf ${TOP_DIR}/repos/xml/parsed/*
podman exec -it patches-backend sh -c '/home/node/app/node_modules/knex/bin/cli.js migrate:rollback --knexfile /home/node/app/server/knexfile.js'
podman stop patches-backend
podman start patches-backend
}
# Function: build_drm
#
# Description: This function builds and runs the DRM (Dell Repository Manager) container.
# It checks for available disk space, validates the DRM_INSTALL_URL variable,
# extracts the version number from the URL, and performs the build using podman.
#
# Parameters: None
#
# Environment Variables:
# - DRM_INSTALL_URL: The URL pointing to the latest DRM version for Linux.
# - REQUIRED_SPACE: The minimum required disk space in GB for the installation.
#
# Returns: None
function build_drm() {
podman rm -f -t 0 patches-drm
if ask_yes_no "The code downloads several 10s of GB of data to populate the Enterprise PowerEdge catalog data for Patches. It checks if you have at least ${REQUIRED_SPACE}GB of disk space available, which is more than what the final container will use. There may be pauses of 60 seconds due to an expect script running to install DRM. Do you want to continue? If you would like more granular control of which patches are downloaded see https://github.com/dell/patches/blob/main/MANUALLY_PULL_REPOS.md."; then
# Check available disk space of the partition containing ${TOP_DIR}/repos
patches_echo "Checking which partition we are using..."
partition=$(df -P "${TOP_DIR}/repos" | awk 'NR==2{print $1}')
patches_echo "repos folder is on partition ${partition}..."
available_space=$(df -BG --output=avail "$partition" | sed '1d;s/[^0-9]*//g')
if [[ "$available_space" -lt "$REQUIRED_SPACE" ]]; then
patches_echo "Insufficient disk space. At least ${REQUIRED_SPACE}GB of free space is required on the partition: $partition" --error
patches_echo "Available disk space: $available_space GB" --error
patches_echo "To check disk space, run the following command: df -BG --output=avail $partition | sed '1d;s/[^0-9]*//g'" --error
exit 1
else
patches_echo "${partition} has sufficient disk space..."
fi
patches_echo "Disk space check passed. Continuing installation..."
do_drm_build=true
# Check if the DRM container image already exists
if podman image exists localhost/dell/patches-drm:latest; then
if ask_yes_no "The DRM container localhost/dell/patches-drm:latest already exists. Do you want to rebuild it from scratch? This probably isn't necessary."; then
podman rm -f -t 0 patches-drm
podman rmi -f patches-drm
else
do_drm_build=false
fi
fi
if [ "$do_drm_build" = true ]; then
read -n 1 -s -r -p $'\033[1;35mA script will run that automatically installs DRM. You will see prompts asking \nyou to press various keys. These inputs will be provided automatically. \nYou do not need to press anything. All required prompts for Patches will appear \nin blue. Press any key to continue.\033[0m'
echo
podman build \
--tag dell/patches-drm:latest \
--squash-all \
-f "${SCRIPT_DIR}/Dockerfile.drm" \
--build-arg "DRM_NAME=${DRM_NAME}" \
"${TOP_DIR}"
fi
# Define the container name
container_name="patches-drm"
# Run the patches-drm container
podman run -d --name "$container_name" localhost/dell/patches-drm:latest tail -f /dev/null
# Get the user ID of drmuser from the container
user_id=$(podman exec "$container_name" id -u drmuser)
group_id=$(podman exec "$container_name" id -g drmuser)
patches_echo "DRM user's ID is ${user_id}. Setting permissions on appropriate directories."
# Change ownership of directories on the host system
directories=("${TOP_DIR}/drm_repos/drm_download" "${TOP_DIR}/repos/xml")
for directory in "${directories[@]}"; do
chown -R ${user_id}:${group_id} "$directory"
done
# Stop and remove the container
podman rm -f -t 0 "$container_name"
patches_echo "Beginning DRM pull. This is roughly 30GBs. It is likely this is going to take a long time. Now is a good time to get a coffee."
podman run \
--name patches-drm \
--volume ${TOP_DIR}/drm_repos/drm_download:/patches/drm_download:z \
--volume ${TOP_DIR}/repos/xml:/patches/drm_export:z \
localhost/dell/patches-drm:latest
patches_echo "Restore original directory permissions..."
for directory in "${directories[@]}"; do
chown -R $(id -u):$(id -g) "$directory"
done
podman rm -f -t 0 "$container_name"
else
patches_echo "Installation cancelled." --error
exit 1
fi
}
# Function to check if unprivileged ports start at 80 or lower
check_unprivileged_ports() {
if [ "$(sysctl -n net.ipv4.ip_unprivileged_port_start)" -le 80 ]; then
return 0 # Ports already start at 80 or lower
else
return 1 # Ports don't start at 80 or lower
fi
}
# check_nginx_status - checks if NGINX is up and running within a timeout of 1 minute
#
# This function checks if NGINX is running by sending a request to http://localhost:443.
# It waits for NGINX to start within a timeout duration of 60 seconds. If NGINX starts
# successfully, it echoes a success message. If the timeout is reached, it echoes an error
# message and exits with status 1.
#
# Parameters:
# None
#
# Environment Variables:
# None
#
# Returns:
# None
check_nginx_status() {
patches_echo "Waiting for NGINX to start..."
elapsed_time=0
TIMEOUT_DURATION=60 # Timeout duration in seconds
while [ ${elapsed_time} -lt ${TIMEOUT_DURATION} ]; do
if curl -s -o /dev/null http://localhost:443; then
patches_echo "NGINX is up and running"
break
fi
patches_echo "Attempting to connect to NGINX..."
sleep 1
elapsed_time=$((elapsed_time + 1))
done
if [ ${elapsed_time} -ge ${TIMEOUT_DURATION} ]; then
patches_echo "NGINX failed to start within the timeout period of ${TIMEOUT_DURATION} seconds" --error
exit 1
fi
}
# run_nginx - runs an Nginx container using Podman
#
# This function generates the Nginx configuration, asks the user if they want to run with sudo, and then
# runs the Nginx container using Podman. If the user chooses to run with sudo, the container will listen
# on ports 80 and 443. If the user chooses not to run with sudo, the container will listen on port 8080.
#
# Parameters:
# None
#
# Environment Variables:
# TOP_DIR - the top-level directory of the Patches application
# SCRIPT_DIR - the directory in which to write the Nginx configuration file
# NGINX_VERSION - the version of Nginx to use for the container
#
# Returns:
# None
function run_nginx() {
# Check if unprivileged ports start at 80 or lower
if check_unprivileged_ports; then
patches_echo "Unprivileged ports already start at 80 or lower. Skipping."
podman run \
--name patches-nginx \
--env-file ${TOP_DIR}/.patches-nginx \
--volume ${SCRIPT_DIR}/nginx_config/nginx.conf:/etc/nginx/nginx.conf:Z \
--volume ${TOP_DIR}/${CERT_DIRECTORY}:/patches/${CERT_DIRECTORY}:z \
--publish 443:443 \
--publish 80:80 \
--detach \
--network host-bridge-net \
docker.io/library/nginx:${NGINX_VERSION}
else
# Ask if user wants to run as sudo
if ask_yes_no "In order to run Patches on ports 80 (redirects to 443) and 443 you will need to change the unprivileged ports on your host to start at port 80. This allows non-root users to bind to any port 80 and higher. You can continue without sudo privileges in which case nginx will run on a high port of your choosing. Users will have to explicitly add the port to all URLs when doing this. Do you want to run as sudo?"; then
patches_echo "Enter your password *NOTE: on STIGed servers you will have to do enter the password multiple times*:"
if sudo -v 2>/dev/null; then
patches_echo "Current user is a sudo user"
else
patches_echo "This user does not have sudo privileges. You will need to give this user sudo privileges in order to continue." --error
exit 1
fi
patches_echo "Setting unprivileged ports to start at port 80..."
sudo sysctl net.ipv4.ip_unprivileged_port_start=80
sudo touch /etc/sysctl.d/local.conf
echo "net.ipv4.ip_unprivileged_port_start=80" | sudo tee -a /etc/sysctl.d/local.conf
patches_echo "Starting nginx. nginx will listen on ports 80 and 443. Port 80 will redirect to 443..."
podman run \
--name patches-nginx \
--env-file ${TOP_DIR}/.patches-nginx \
--volume ${SCRIPT_DIR}/nginx_config/nginx.conf:/etc/nginx/nginx.conf:Z \
--volume ${TOP_DIR}/${CERT_DIRECTORY}:/patches/${CERT_DIRECTORY}:z \
--publish 443:443 \
--publish 80:80 \
--detach \
--network host-bridge-net \
docker.io/library/nginx:${NGINX_VERSION}
else
# Prompt the user for the nginx port and validate it
while true; do
patches_read "What port would you like to use for nginx?"
nginx_port="$RETURN_VALUE"
if (( nginx_port >= 1025 && nginx_port <= 65535 )); then
break
else
patches_echo "Invalid port. Please choose a port within the range 1025 - 65535."
fi
done
patches_echo "Running nginx on port ${nginx_port}. Users will need to manually add both https:// and the port :${nginx_port} to the Patches URL to access it."
# Update the config file with the NGINX_PORT
sed -i "s/^NGINX_PORT:.*/NGINX_PORT: ${nginx_port}/" "${SCRIPT_DIR}/config.yml"
podman run \
--name patches-nginx \
--env-file ${TOP_DIR}/.patches-nginx \
--volume ${SCRIPT_DIR}/nginx_config/nginx.conf:/etc/nginx/nginx.conf:Z \
--volume ${TOP_DIR}/${CERT_DIRECTORY}:/patches/${CERT_DIRECTORY}:z \
--publish ${nginx_port}:443 \
--detach \
--network host-bridge-net \
docker.io/library/nginx:${NGINX_VERSION}
fi
fi
check_nginx_status
}
# generate_certificates - This function generates certificates required for
# the server. It ensures that any old containers are cleaned up before running
# the certificate generation process. The function uses Podman to run a
# containerized process that executes a script called
# generate_certificates_entrypoint.sh.
#
# Parameters:
# None
#
# Environment Variables:
# - TOP_DIR: The top directory path.
# - CERT_DIRECTORY: The directory where certificates will be stored.
# - SCRIPT_DIR: The directory path of the script.
#
# Returns:
# None
function generate_certificates() {
# Check if variables interfaces or ipv4_address are not defined
if [[ -z ${interfaces+x} || -z ${ipv4_address+x} ]]; then
get_ip_address
fi
# Setup environment variables for the certificate generator
echo "IPV4_ADDRESS=${ipv4_address}" > ${TOP_DIR}/.patches-certificate-generator
echo "ROOT_CERT_DIRECTORY=${ROOT_CERT_DIRECTORY}" >> ${TOP_DIR}/.patches-certificate-generator
echo "CERT_DIRECTORY=${CERT_DIRECTORY}" >> ${TOP_DIR}/.patches-certificate-generator
# Check to see if the generic client names are still present
if [[ -n ${clients_gelante+x} ]] && [[ -n ${clients_geleisi+x} ]]; then
if ask_yes_no "The default client names gelante and geleisi are still present in ${SCRIPT_DIR}/config.yml. This means when you generate keys the only clients that will be available will be named gelante and geleisi. You will likely want to change this to your own client information by modifying ${SCRIPT_DIR}/config.yml. See https://github.com/dell/patches#customizing-setup for details. Would you like to stop the setup?"; then
patches_echo "Terminating." --error
exit 1
fi
fi
# Make sure any old containers are cleaned up
podman rm -f patches-certificate-generator || true
podman run \
--name patches-certificate-generator \
-it \
--env-file ${TOP_DIR}/.patches-certificate-generator \
--volume ${TOP_DIR}/${CERT_DIRECTORY}:/app/${CERT_DIRECTORY}:Z \
--volume ${SCRIPT_DIR}/config.yml:/app/config.yml:Z \
--entrypoint /app/generate_certificates_entrypoint.sh \
localhost/dell/patches-python:latest
# Make sure any old containers are cleaned up
podman rm -f patches-certificate-generator || true
# Reparse the YAML file because it has been updated
eval "$(parse_yaml "${SCRIPT_DIR}/config.yml")"
printf $'\033[1;35mYour user certificates have been generated. They are available in\n %s/server_certs. Press any key to continue.\033[0m\n' "${TOP_DIR}"
read -n 1 -s -r -p ""
}
# wait_for_postgresql - waits for PostgreSQL to start within a timeout duration
#
# This function waits for PostgreSQL to be available by executing the `pg_isready` command
# with the specified parameters. It waits until PostgreSQL is ready or the timeout duration
# is reached. If PostgreSQL starts successfully, it echoes a success message. If the timeout
# is reached, it echoes an error message and exits with status 1.
#
# Parameters:
# None
#
# Environment Variables:
# POSTGRES_DB - the name of the PostgreSQL database
# PSQL_USERNAME - the username to connect to PostgreSQL
# PSQL_HOST - the host address of PostgreSQL
# PSQL_PORT - the port number of PostgreSQL
#
# Returns:
# None
wait_for_postgresql() {
patches_echo "Waiting for PostgreSQL to start..."
start_time=$(date +%s)
timeout=60
until podman exec patches-psql pg_isready --dbname=${POSTGRES_DB} --username=${PSQL_USERNAME} --host=${PSQL_HOST} --port=${PSQL_PORT} >/dev/null 2>&1; do
current_time=$(date +%s)
elapsed_time=$((current_time - start_time))
if [[ $elapsed_time -ge $timeout ]]; then
patches_echo --error "PostgreSQL did not start within ${timeout} seconds."
exit 1
fi
patches_echo "PostgreSQL is not yet available. Retrying..."
sleep 1
done
patches_echo "PSQL server is up and running"
}
# run_postgresql starts a PSQL server and configures the administrator for the PostgreSQL database
#
# Parameters:
# None
#
# Environment variables:
# PSQL_VERSION: Version of the PostgreSQL container image to use
# PATCHES_ADMINISTRATOR: Username of the administrator for the PostgreSQL database
# PSQL_USERNAME: Username to use for connecting to the PostgreSQL server
# POSTGRES_DB: Name of the PostgreSQL database
# PSQL_PORT: Port number on which the PostgreSQL server is running
# TOP_DIR: Path to the top-level directory
#
# Returns:
# None
function run_postgresql() {
patches_echo "Running PSQL server"
podman run \
--name "patches-psql" \
--env-file ${TOP_DIR}/.patches-psql \
--volume psql-storage:/var/lib/postgresql/data:Z \
--network host-bridge-net \
--detach \
docker.io/library/postgres:${PSQL_VERSION}
# Wait for PostgreSQL to be available
wait_for_postgresql
}
# run_patches_services starts the patches-backend and patches-frontend applications using podman
#
# Parameters:
# None
#
# Environment variables:
# TOP_DIR: Path to the top-level directory
# CERT_DIRECTORY: Path to the certificate directory
# FRONTEND_PORT: Port number for the patches-frontend application
#
# Returns:
# None
function run_patches_services() {
# Set NODE_ENV to production for production mode
echo "NODE_ENV=production" >> ${TOP_DIR}/.patches-backend
echo "Running patches-backend in production mode"
# Start podman in production mode
podman run \
--name patches-backend \
--env-file ${TOP_DIR}/.patches-backend \
--volume ${TOP_DIR}/${CERT_DIRECTORY}:/patches/${CERT_DIRECTORY}:Z \
--volume ${TOP_DIR}/repos/xml:/patches/xml:z \
--volume ${TOP_DIR}/repos/xml/parsed:/patches/xml/parsed:Z \
--network host-bridge-net \
--detach \
localhost/dell/patches-base:latest \
sh -c 'node /home/node/app/node_modules/knex/bin/cli.js --knexfile /home/node/app/server/knexfile.js migrate:latest && node /home/node/app/server/index.js'
patches_echo "Running patches-frontend"
echo "NODE_ENV=production" >> ${TOP_DIR}/.patches-frontend
podman run \
--name patches-frontend \
--env-file ${TOP_DIR}/.patches-frontend \
--network host-bridge-net \
--detach \
localhost/dell/patches-base:latest \
sh -c "/home/node/app/node_modules/.bin/serve --listen tcp://0.0.0.0:${FRONTEND_PORT} /home/node/app/build"
}
# enable_cron_job enables the creation of a systemd service to run Patches on startup
#
# Parameters:
# None
#
# Environment variables:
# SCRIPT_DIR: Path to the directory containing the Patches script
# USER: Username of the current user
#
# Returns:
# None
function enable_cron_job() {
# Check if the script is already executable
if [ ! -x "$0" ]; then
# Make the script executable
chmod +x "${SCRIPT_DIR}/$(basename "$0")"
patches_echo "patches.sh is now executable."
fi
# Define the line to be added to the crontab
CRON_LINE="@reboot $SCRIPT_DIR/patches.sh start"
# Check if the line already exists in the crontab
if ! (sudo -u $(whoami) crontab -l | grep -qF "$CRON_LINE"); then
# If not found, add the line to the user's crontab
(sudo -u $(whoami) crontab -l; echo "$CRON_LINE") | sudo -u $(whoami) crontab -
patches_echo "Cron job added to start Patches."
else
patches_echo "Cron job already exists. Not adding it again."
fi
}
# patches_build builds the necessary Docker images for the Patches application
#
# Parameters:
# None
#
# Environment variables:
# SCRIPT_DIR: Path to the directory containing the Dockerfiles
# TOP_DIR: Path to the top-level directory
#
# Returns:
# None
function patches_build() {
local container_name="$1"
if [[ -z "$container_name" ]]; then
# Delete any old containers still running on the server
cleanup_containers
podman build \
--tag dell/patches-python:latest \
--squash-all \
-f ${SCRIPT_DIR}/python_container/Dockerfile.python \
--build-arg "PYTHON_CONTAINER_DIR=podman-build/python_container" \
${TOP_DIR}
podman build \
--tag dell/patches-base:latest \
--squash-all \
-f ${SCRIPT_DIR}/Dockerfile.patches_base \
${TOP_DIR}
else
case "$container_name" in
"python")
podman build \
--tag dell/patches-python:latest \
--squash-all \
-f ${SCRIPT_DIR}/python_container/Dockerfile.python \
--build-arg "PYTHON_CONTAINER_DIR=podman-build/python_container" \
${TOP_DIR}
;;
"base")
podman build \
--tag dell/patches-base:latest \
--squash-all \
-f ${SCRIPT_DIR}/Dockerfile.patches_base \
${TOP_DIR}
;;
*)
echo "Invalid container name: $container_name"
exit 1
;;
esac
fi
ascii_art=$(cat << "EOF"
___ _ _ _
| _ ) _ _ (_) | | __| |
| _ \ | +| | | | | | / _` |
|___/ \_,_| _|_|_ _|_|_ \__,_|
_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|
"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'
___ _ __ _ _
/ __| ___ _ __ | '_ \ | | ___ | |_ ___
| (__ / _ \ | ' \ | .__/ | | / -_) | _| / -_)
\___| \___/ |_|_|_| |_|__ _|_|_ \___| _\__| \___|
_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|_|"""""|
"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'"`-0-0-'
EOF
)
print_ascii_art "$ascii_art"
}
# patches_setup performs the setup and configuration steps for Patches.
#
# Description: Performs the setup and configuration steps for Patches.
# - Checks if the operating system is Rocky Linux.
# - Prompts the user for the administrator name if PATCHES_ADMINISTRATOR is not set.
# - Cleans up any old containers.
# - Sets up environment variables for the Patches backend and frontend.
# - Enables and starts the Podman service.
# - Checks the presence of repository XML files and prompts the user to use Dell Repository Manager if no files are found.
# - Configures Patches interfaces.
# - Generates Nginx configuration.
# - Checks for the presence of Patches build containers and builds them if missing.
# - Removes old containers.
# - Generates Nginx configuration.
# - Sets up environment variables for the certificate generator.
# - Checks for existing keys and prompts the user to continue or generate new keys.
# - Runs PostgreSQL, Patches services, and Nginx.
# - Runs an HTTP server container for servicing OME hosts.
# - Configures the administrator for the PostgreSQL database.
# - Enables the Patches systemd service.
#
# Parameters:
# None
#
# Environment Variables:
# - PATCHES_ADMINISTRATOR: The name of the administrator for Patches.
#
# Returns:
# None
#
function patches_setup() {
# Check if the current operating system is Rocky Linux
if [ -f /etc/os-release ]; then
source /etc/os-release
if [[ $ID == "rocky" ]]; then
patches_echo "Running on Rocky Linux..."
else
if ! ask_yes_no "You are not running Rocky Linux. Patches has only been tested on Rocky Linux and we recommend using Rocky Linux. While Patches was designed to run on all *nix flavors, you may run into errors unique to your OS. Do you want to continue?"; then
patches_echo "Exiting" --error
exit 1
fi