-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathonprem_upgrade.sh
More file actions
executable file
·1374 lines (1118 loc) · 52 KB
/
onprem_upgrade.sh
File metadata and controls
executable file
·1374 lines (1118 loc) · 52 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
# SPDX-FileCopyrightText: 2025 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
# Script Name: onprem_upgrade.sh
# Description: This script:
# If requested - does a backup of PVs and cluster's ETCD
# Downloads debian packages and repo artifacts,
# Upgrades packages to v3.1.0:
# - OS config,
# - RKE2 and basic cluster components,
# - ArgoCD,
# - Gitea,
# - Edge Orchestrator Applications
# Usage: ./onprem_upgrade
# -o: Override production values with dev values
# -b: enable backup of Orchestrator PVs before upgrade (optional)
# -h: help (optional)
set -e
set -o pipefail
# Setup logging - capture all output to log file while still displaying on console
LOG_FILE="onprem_upgrade_$(date +'%Y%m%d_%H%M%S').log"
LOG_DIR="/var/log/orch-upgrade"
# Create log directory if it doesn't exist
sudo mkdir -p "$LOG_DIR"
sudo chown "$(whoami):$(whoami)" "$LOG_DIR"
# Full path to log file
FULL_LOG_PATH="$LOG_DIR/$LOG_FILE"
# Function to log messages with timestamp
log_message() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" | tee -a "$FULL_LOG_PATH"
}
# Function to log info messages
log_info() {
log_message "INFO: $*"
}
# Function to log warning messages
log_warn() {
log_message "WARN: $*"
}
# Function to log error messages
log_error() {
log_message "ERROR: $*"
}
# Redirect all output to both console and log file
exec > >(tee -a "$FULL_LOG_PATH")
exec 2> >(tee -a "$FULL_LOG_PATH" >&2)
log_info "Starting OnPrem Edge Orchestrator upgrade script"
log_info "Log file: $FULL_LOG_PATH"
# Import shared functions
# shellcheck disable=SC1091
source "$(dirname "${0}")/functions.sh"
# shellcheck disable=SC1091
source "$(dirname "${0}")/upgrade_postgres.sh"
# shellcheck disable=SC1091
source "$(dirname "${0}")/vault_unseal.sh"
# shellcheck disable=SC1091
source "$(dirname "$0")/onprem.env"
### Constants
RELEASE_SERVICE_URL="${RELEASE_SERVICE_URL:-registry-rs.edgeorchestration.intel.com}"
ORCH_INSTALLER_PROFILE="${ORCH_INSTALLER_PROFILE:-onprem}"
DEPLOY_VERSION="${DEPLOY_VERSION:-v3.1.0}" # Updated to v3.1.0
GITEA_IMAGE_REGISTRY="${GITEA_IMAGE_REGISTRY:-docker.io}"
USE_LOCAL_PACKAGES="${USE_LOCAL_PACKAGES:-false}" # New flag for local packages
INSTALL_GITEA=true
echo "Checking PostgreSQL pod in orch-database namespace..."
if kubectl get pod postgresql-cluster-1 -n orch-database >/dev/null 2>&1; then
echo "Found postgresql-cluster-1 pod"
else
echo "❌ ERROR: PostgreSQL pod postgresql-cluster-1 not found in orch-database namespace."
exit 1
fi
### Variables
cwd=$(pwd)
deb_dir_name="installers"
git_arch_name="repo_archives"
archives_rs_path="edge-orch/common/files/orchestrator"
installer_rs_path="edge-orch/common/files"
si_config_repo="edge-manageability-framework"
apps_ns=onprem
argo_cd_ns=argocd
gitea_ns=gitea
# shellcheck disable=SC2034
root_app=root-app
# Variables that depend on the above and might require updating later, are placed in here
set_artifacts_version() {
installer_list=()
if [ "$INSTALL_GITEA" = "true" ]; then
installer_list+=("onprem-gitea-installer:${DEPLOY_VERSION}")
fi
installer_list+=(
"onprem-config-installer:${DEPLOY_VERSION}"
"onprem-ke-installer:${DEPLOY_VERSION}"
"onprem-argocd-installer:${DEPLOY_VERSION}"
"onprem-orch-installer:${DEPLOY_VERSION}"
)
git_archive_list=(
"onpremfull:${DEPLOY_VERSION}"
)
}
export GIT_REPOS=$cwd/$git_arch_name
export ONPREM_UPGRADE_SYNC="${ONPREM_UPGRADE_SYNC:-true}"
reset_runtime_variables() {
local config_file="$cwd/onprem.env"
echo "Cleaning up runtime variables from previous runs..."
local temp_file="${config_file}.tmp"
local in_multiline=0
while IFS= read -r line || [[ -n "$line" ]]; do
# Skip lines while inside a multi-line variable
if [[ $in_multiline -eq 1 ]]; then
[[ "$line" =~ [\'\"][[:space:]]*$ ]] && in_multiline=0
continue
fi
# Check if line is a runtime variable
if [[ "$line" =~ ^export\ (SRE_TLS_ENABLED|SRE_DEST_CA_CERT|SMTP_SKIP_VERIFY|DISABLE_CO_PROFILE|DISABLE_AO_PROFILE|DISABLE_O11Y_PROFILE|SINGLE_TENANCY_PROFILE)= ]]; then
# Check if it's multi-line (opening quote without closing quote on same line)
if [[ "$line" =~ =[\'\"]. ]] && ! [[ "$line" =~ =[\'\"].*[\'\"]\ *$ ]]; then
in_multiline=1
fi
continue
fi
# Keep non-runtime variable lines
echo "$line" >> "$temp_file"
done < "$config_file"
mv "$temp_file" "$config_file"
# Unset variables in current shell
unset SRE_TLS_ENABLED SRE_DEST_CA_CERT SMTP_SKIP_VERIFY
unset DISABLE_CO_PROFILE DISABLE_AO_PROFILE DISABLE_O11Y_PROFILE SINGLE_TENANCY_PROFILE
echo "Runtime variables cleaned successfully."
}
retrieve_and_update_config() {
local config_file="$cwd/onprem.env"
echo "Retrieving cluster configuration values..."
# Get LoadBalancer IPs
ARGO_IP=$(kubectl get svc argocd-server -n argocd -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
TRAEFIK_IP=$(kubectl get svc traefik -n orch-gateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}')
if kubectl get svc ingress-haproxy-kubernetes-ingress -n orch-boots >/dev/null 2>&1; then
HAPROXY_IP=$(kubectl get svc ingress-haproxy-kubernetes-ingress -n orch-boots \
-o jsonpath='{.status.loadBalancer.ingress[0].ip}')
echo "Using HAProxy ingress: $HAPROXY_IP"
elif kubectl get svc ingress-nginx-controller -n orch-boots >/dev/null 2>&1; then
HAPROXY_IP=$(kubectl get svc ingress-nginx-controller -n orch-boots \
-o jsonpath='{.status.loadBalancer.ingress[0].ip}')
echo "Using NGINX ingress: $HAPROXY_IP"
else
echo "ERROR: No ingress service found in orch-boots namespace"
exit 1
fi
# Update IPs
update_config_variable "$config_file" "ARGO_IP" "$ARGO_IP"
update_config_variable "$config_file" "TRAEFIK_IP" "$TRAEFIK_IP"
update_config_variable "$config_file" "HAPROXY_IP" "$HAPROXY_IP"
# --------------------------
# SRE TLS Configuration
# --------------------------
SRE_TLS_ENABLED=$(kubectl get applications -n "$apps_ns" sre-exporter \
-o jsonpath='{.spec.sources[*].helm.valuesObject.otelCollector.tls.enabled}')
if [[ "$SRE_TLS_ENABLED" == "true" ]]; then
update_config_variable "$config_file" "SRE_TLS_ENABLED" "true"
SRE_DEST_CA_CERT=$(kubectl get applications -n "$apps_ns" sre-exporter \
-o jsonpath='{.spec.sources[*].helm.valuesObject.otelCollector.tls.caSecret.enabled}')
[[ "$SRE_DEST_CA_CERT" == "true" ]] && \
update_config_variable "$config_file" "SRE_DEST_CA_CERT" "true"
else
update_config_variable "$config_file" "SRE_TLS_ENABLED" "false"
fi
# --------------------------
# Profiles
# --------------------------
VALUE_FILES=$(kubectl get application root-app -n "$apps_ns" \
-o jsonpath='{.spec.sources[0].helm.valueFiles[*]}')
if [[ -z "$VALUE_FILES" ]]; then
echo "⚠️ No value files found in root-app"
exit 1
fi
DISABLE_CO_PROFILE="false"
DISABLE_AO_PROFILE="false"
DISABLE_O11Y_PROFILE="false"
SINGLE_TENANCY_PROFILE="false"
echo "$VALUE_FILES" | grep -q "enable-cluster-orch.yaml" || DISABLE_CO_PROFILE="true"
echo "$VALUE_FILES" | grep -q "enable-app-orch.yaml" || DISABLE_AO_PROFILE="true"
echo "$VALUE_FILES" | grep -qE "(enable-o11y\.yaml|o11y-onprem-1k\.yaml)" || DISABLE_O11Y_PROFILE="true"
echo "$VALUE_FILES" | grep -q "enable-singleTenancy.yaml" && SINGLE_TENANCY_PROFILE="true"
INSTALL_GITEA=$([[ "$DISABLE_CO_PROFILE" == "true" || "$DISABLE_AO_PROFILE" == "true" ]] && echo "false" || echo "true")
# Update profile values
update_config_variable "$config_file" "DISABLE_CO_PROFILE" "$DISABLE_CO_PROFILE"
update_config_variable "$config_file" "DISABLE_AO_PROFILE" "$DISABLE_AO_PROFILE"
update_config_variable "$config_file" "DISABLE_O11Y_PROFILE" "$DISABLE_O11Y_PROFILE"
update_config_variable "$config_file" "SINGLE_TENANCY_PROFILE" "$SINGLE_TENANCY_PROFILE"
update_config_variable "$config_file" "INSTALL_GITEA" "$INSTALL_GITEA"
# --------------------------
# SMTP
# --------------------------
SMTP_SKIP_VERIFY=$(kubectl get application alerting-monitor -n "$apps_ns" \
-o jsonpath='{.spec.sources[*].helm.valuesObject.alertingMonitor.smtp.insecureSkipVerify}' \
2>/dev/null || echo "false")
update_config_variable "$config_file" "SMTP_SKIP_VERIFY" "$SMTP_SKIP_VERIFY"
echo "Configuration retrieval and update completed successfully."
}
apply_and_package_config() {
tmp_dir="$cwd/$git_arch_name/tmp"
rm -rf "$tmp_dir"
mkdir -p "$tmp_dir"
repo_file=$(find "$cwd/$git_arch_name" -name "*$si_config_repo*.tgz" -type f -printf "%f\n")
tar -xf "$cwd/$git_arch_name/$repo_file" -C "$tmp_dir"
rm -rf "$ORCH_INSTALLER_PROFILE".yaml
./generate_cluster_yaml.sh onprem
cp "$ORCH_INSTALLER_PROFILE".yaml \
"$tmp_dir/$si_config_repo/orch-configs/clusters/$ORCH_INSTALLER_PROFILE.yaml"
while true; do
read -rp "Edit values.yaml if required. Ready to proceed? (yes/no): " yn
case $yn in
[Yy]* ) break;;
[Nn]* ) exit 1;;
* ) echo "Please answer yes or no.";;
esac
done
cd "$tmp_dir"
tar -zcvf "$repo_file" ./edge-manageability-framework
mv -f "$repo_file" "$cwd/$git_arch_name/$repo_file"
cd "$cwd"
rm -rf "$tmp_dir"
}
resync_all_apps() {
# Re-create the patch file for ArgoCD sync operation if it doesn't exist
if [[ ! -f /tmp/argo-cd/sync-patch.yaml ]]; then
sudo mkdir -p /tmp/argo-cd
cat <<EOF | sudo tee /tmp/argo-cd/sync-patch.yaml >/dev/null
operation:
sync:
syncStrategy:
hook: {}
EOF
fi
kubectl patch application root-app -n "$apps_ns" --type merge -p '{"operation":null}'
kubectl patch application root-app -n "$apps_ns" --type json -p '[{"op": "remove", "path": "/status/operationState"}]'
sleep 10
kubectl patch application root-app -n "$apps_ns" --patch-file /tmp/argo-cd/sync-patch.yaml --type merge
}
terminate_existing_sync() {
local app_name=$1
local namespace=$2
local current_phase
current_phase=$(kubectl get application "$app_name" -n "$namespace" -o jsonpath='{.status.operationState.phase}' 2>/dev/null)
if [[ "$current_phase" == "Running" ]]; then
echo "🛑 Terminating existing sync operation..."
kubectl patch application "$app_name" -n "$namespace" --type='merge' -p='{"operation": null}'
# Wait for termination
timeout 30 bash -c "while [[ \"\$(kubectl get application $app_name -n $namespace -o jsonpath='{.status.operationState.phase}' 2>/dev/null)\" == \"Running\" ]]; do sleep 2; done"
echo "✅ Existing operation terminated"
else
echo "ℹ️ No running operation to terminate"
fi
}
force_sync_outofsync_app() {
local app_name=$1
local namespace=$2
local server_side_apply=${3:-false} # Default to false if not specified
set +e
terminate_existing_sync "$app_name" "$namespace"
echo "Force syncing $app_name (ServerSideApply=$server_side_apply)..."
kubectl patch -n "$namespace" application "$app_name" --type merge --patch "$(cat <<EOF
{
"operation": {
"initiatedBy": {
"username": "admin"
},
"sync": {
"syncOptions": [
"Replace=true",
"Force=true",
"ServerSideApply=$server_side_apply"
]
}
}
}
EOF
)"
set -e
}
# Function to check and force sync application if not healthy
check_and_force_sync_app() {
local app_name=$1
local namespace=$2
local server_side_apply=${3:-false} # Default to false if not specified
local max_retries=2
for ((i=1; i<=max_retries; i++)); do
app_status=$(kubectl get application "$app_name" -n "$namespace" -o jsonpath='{.status.sync.status} {.status.health.status}' 2>/dev/null || echo "NotFound NotFound")
if [[ "$app_status" == "Synced Healthy" ]]; then
echo "✅ $app_name is Synced and Healthy"
return 0
fi
echo "⚠️ $app_name is not Synced and Healthy (status: $app_status). Force-syncing... (attempt $i/$max_retries)"
force_sync_outofsync_app "$app_name" "$namespace" "$server_side_apply"
echo "✅ $app_name sync triggered"
# Check status every 5s for 90s
local check_timeout=90
local check_interval=3
local elapsed=0
while (( elapsed < check_timeout )); do
app_status=$(kubectl get application "$app_name" -n "$namespace" -o jsonpath='{.status.sync.status} {.status.health.status}' 2>/dev/null || echo "NotFound NotFound")
if [[ "$app_status" == "Synced Healthy" ]]; then
echo "✅ $app_name became Synced and Healthy"
return 0
else
echo "Current status: $app_status (elapsed: ${elapsed}s)"
fi
sleep $check_interval
elapsed=$((elapsed + check_interval))
done
echo "⏳ $app_name did not become healthy within ${check_timeout}s"
done
echo "⚠️ $app_name may still require attention after $max_retries attempts"
}
check_and_patch_sync_app() {
local app_name=$1
local namespace=$2
local max_retries=2
for ((i=1; i<=max_retries; i++)); do
app_status=$(kubectl get application "$app_name" -n "$namespace" -o jsonpath='{.status.sync.status} {.status.health.status}' 2>/dev/null || echo "NotFound NotFound")
if [[ "$app_status" == "Synced Healthy" ]]; then
echo "✅ $app_name is Synced and Healthy"
return 0
fi
echo "⚠️ $app_name is not Synced and Healthy (status: $app_status). Force-syncing... (attempt $i/$max_retries)"
set +e
terminate_existing_sync "$app_name" "$namespace"
kubectl patch -n "$namespace" application "$app_name" --patch-file /tmp/argo-cd/sync-patch.yaml --type merge
set -e
# Check status every 5s for 90s
local check_timeout=90
local check_interval=3
local elapsed=0
while (( elapsed < check_timeout )); do
app_status=$(kubectl get application "$app_name" -n "$namespace" -o jsonpath='{.status.sync.status} {.status.health.status}' 2>/dev/null || echo "NotFound NotFound")
if [[ "$app_status" == "Synced Healthy" ]]; then
echo "✅ $app_name became Synced and Healthy"
return 0
else
echo "Current status: $app_status (elapsed: ${elapsed}s)"
fi
sleep $check_interval
elapsed=$((elapsed + check_interval))
done
echo "⏳ $app_name did not become healthy within ${check_timeout}s"
done
echo "⚠️ $app_name may still require attention after $max_retries attempts"
}
# Function to wait for application to be Synced and Healthy with timeout
wait_for_app_synced_healthy() {
resync_all_apps
local app_name=$1
local namespace=$2
local timeout=${3:-120} # Default 120 seconds if not specified
local start_time
start_time=$(date +%s)
set +e
while true; do
echo "Checking $app_name application status..."
local app_status
app_status=$(kubectl get application "$app_name" -n "$namespace" -o jsonpath='{.status.sync.status} {.status.health.status}' 2>/dev/null || echo "NotFound NotFound")
if [[ "$app_status" == "Synced Healthy" ]]; then
echo "✅ $app_name application is Synced and Healthy."
set -e
return 0
fi
local current_time
current_time=$(date +%s)
local elapsed=$((current_time - start_time))
if (( elapsed > timeout )); then
echo "⚠️ Timeout waiting for $app_name to be Synced and Healthy after ${timeout}s (status: $app_status)"
set -e
return 0
fi
echo "Waiting for $app_name to be Synced and Healthy... (status: $app_status, ${elapsed}s/${timeout}s elapsed)"
sleep 3
done
}
# Function to restart a StatefulSet by scaling to 0 and back
restart_statefulset() {
local name=$1
local namespace=$2
echo "Restarting StatefulSet $name in namespace $namespace..."
# Get current replica count
REPLICAS=$(kubectl get statefulset "$name" -n "$namespace" -o jsonpath='{.spec.replicas}')
echo "Current replicas: $REPLICAS"
# Scale to 0
kubectl scale statefulset "$name" -n "$namespace" --replicas=0
# Wait for pods to terminate
kubectl wait --for=delete pod -l app="$name" -n "$namespace" --timeout=300s
# Scale back to original replica count
kubectl scale statefulset "$name" -n "$namespace" --replicas="$REPLICAS"
echo "✅ $name restarted"
}
# Function to check app status and clean up job if needed
check_and_cleanup_job() {
local app_name=$1
local namespace=$2
local job_label=${3:-job-name}
app_status=$(kubectl get application "$app_name" -n "$apps_ns" -o jsonpath='{.status.sync.status} {.status.health.status}' 2>/dev/null || echo "NotFound NotFound")
if [[ "$app_status" != "Synced Healthy" ]]; then
if kubectl get job -n "$namespace" -l "$job_label" 2>/dev/null | grep "$app_name"; then
echo "Deleting $app_name job..."
job_name=$(kubectl get job -n "$namespace" -l "$job_label" | grep "$app_name" | awk '{print $1}')
kubectl delete job "$job_name" -n "$namespace" --force --grace-period=0 --ignore-not-found
echo "✅ $app_name job deleted"
kubectl patch -n "$apps_ns" application "$app_name" --patch-file /tmp/argo-cd/sync-patch.yaml --type merge
else
echo "ℹ️ No $app_name job found to delete"
fi
fi
}
# Checks if orchestrator is currently installed on the node
# check_orch_install <array[@] of package names>
check_orch_install() {
package_list=("$@")
for package in "${package_list[@]}"; do
package_name="${package%%:*}"
if ! dpkg -l "$package_name" >/dev/null 2>&1; then
echo "Package: $package_name is not installed on the node, OnPrem Edge Orchestrator is not installed or installation is broken"
exit 1
fi
# shellcheck disable=SC2034
installed_ver=$(dpkg-query -W -f='${Version}' "$package_name")
incoming_ver="${package#*:}"
incoming_ver="${incoming_ver#v}"
# if [[ $installed_ver = "$incoming_ver" ]]; then
# echo "Package: $package_name is already at version: $incoming_ver"
# exit 1
# fi
done
}
# Get LV size and format it to be ready for lvcreate command
# get_lv_size <lv_path> returns <formatted size>
get_lv_size() {
lv_path=$1
size_output=$(sudo lvdisplay "$lv_path" | grep "LV Size" | awk '{print $3, $4}')
size=$(echo "$size_output" | awk '{print $1}')
unit=$(echo "$size_output" | awk '{print $2}')
case $unit in
GiB)
formatted_size="${size}G"
;;
MiB)
formatted_size="${size}M"
;;
TiB)
formatted_size="${size}T"
;;
*)
echo "Error: Unsupported unit $unit."
exit 1
;;
esac
echo "$formatted_size"
}
check_space_for_backup() {
vg_info=$(sudo vgs --noheadings --units g --nosuffix -o vg_size,vg_free 2>/dev/null)
vsize=$(echo "$vg_info" | awk '{print $1}')
vfree=$(echo "$vg_info" | awk '{print $2}')
vused=$(echo "$vsize - $vfree" | bc)
margin=$(echo "$vused * 0.05" | bc)
enough_space=$(echo "$vfree > ($vused + $margin)" | bc)
echo "$enough_space"
}
# Backup all PVs to LVs in the same VG. They won't get deleted during orchestrator removal from node.
backup_pvs() {
space_check_result=$(check_space_for_backup)
if [[ $space_check_result -eq 0 ]]; then
echo "Error: there is not enough space for PVs backup in VG"
return 1
fi
vg_name=lvmvg
vol_snap_class_name=openebs-lvm-vsc
backup_date=$(date +'%Y-%m-%d-%H_%M')
pvs_to_backup=$(kubectl get pvc --all-namespaces -o jsonpath='{range .items[?(@.status.phase=="Bound")]}{.metadata.name}{" "}{.metadata.namespace}{" "}{.spec.volumeName}{"\n"}{end}')
echo "$pvs_to_backup" | while IFS= read -r line; do
read -r pvc_name pvc_namespace lv_name <<<"$line"
# dkam-pvc doesn't need backup as its data will get re-populated anyway
if [[ $pvc_name == 'dkam-pvc' ]]; then
continue
fi
# Create VolumeSnapshot and use it in backup for data consistency
kubectl apply -f - <<EOF
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
name: $pvc_name-snap
namespace: $pvc_namespace
spec:
volumeSnapshotClassName: $vol_snap_class_name
source:
persistentVolumeClaimName: $pvc_name
EOF
attempts=0
max_attempts=40
while [ "$(kubectl get volumesnapshot -n "$pvc_namespace" "$pvc_name-snap" -o jsonpath='{.status.readyToUse}')" != "true" ]; do
echo "Waiting for VolumeSnaphot $pvc_name-snap in $pvc_namespace to be readyToUse..."
sleep 5
attempts=$((attempts + 1))
if [ $attempts -ge $max_attempts ]; then
echo "Reached maximum number of attempts ($max_attempts), stopping upgrade operation"
exit 1
fi
done
# Create backup LV on VG
formatted_size=$(get_lv_size "/dev/$vg_name/$lv_name")
bak_lv_name="${pvc_name}-${pvc_namespace}-bak-${backup_date}"
sudo lvcreate -n "$bak_lv_name" -L "$formatted_size" $vg_name -y
sudo mkfs.ext4 "/dev/$vg_name/$bak_lv_name"
# Create mounts for copying files from original LV to backup
sudo mkdir -p /mnt/original-lv
sudo mkdir -p /mnt/backup-lv
# Copy data from original LV snapshot filesystem to backup LV filesystem
snap_name=$(sudo lvs --options lv_name,origin --noheadings | grep "$lv_name" | awk -v lv_name="$lv_name" '$1 != lv_name {print $1}')
sudo mount "/dev/$vg_name/$snap_name" /mnt/original-lv
sudo mount "/dev/$vg_name/$bak_lv_name" /mnt/backup-lv
sudo cp -a /mnt/original-lv/. /mnt/backup-lv/
sudo umount "/dev/$vg_name/$snap_name"
sudo umount "/dev/$vg_name/$bak_lv_name"
sudo rm -fr /mnt/original-lv
sudo rm -fr /mnt/backup-lv
# Delete VolumeSnapshot as data there is backed up already
kubectl delete volumesnapshot -n "$pvc_namespace" "$pvc_name-snap"
done
}
# Function to search and delete specific secrets in the 'gitea' namespace
cleanup_gitea_secrets() {
echo "Checking for secrets in namespace: gitea"
local secrets=(
"gitea-apporch-token"
"gitea-argocd-token"
"gitea-clusterorch-token"
)
for secret in "${secrets[@]}"; do
if kubectl get secret "$secret" -n gitea >/dev/null 2>&1; then
echo "Secret found: $secret - Deleting..."
kubectl delete secret "$secret" -n gitea
else
echo "Secret not found: $secret"
fi
done
echo "Secret cleanup completed."
}
delete_nginx_if_any() {
echo "🔍 Checking and deleting nginx ingress (if any)..."
# Delete ArgoCD applications (ignore if not found)
kubectl delete application ingress-nginx -n onprem --ignore-not-found=true || true
kubectl delete application nginx-ingress-pxe-boots -n onprem --ignore-not-found=true || true
# Find and delete harbor nginx pods
local HARBOR_PODS
HARBOR_PODS=$(kubectl get pods -n orch-harbor --no-headers 2>/dev/null | awk '/harbor-oci-nginx/ {print $1}' || true)
if [ -n "${HARBOR_PODS:-}" ]; then
echo "🧹 Deleting harbor nginx pods:"
echo "$HARBOR_PODS"
kubectl delete pod -n orch-harbor "$HARBOR_PODS" || true
else
echo "ℹ️ No harbor-oci-nginx pods found in orch-harbor."
fi
echo "✅ nginx cleanup done."
}
usage() {
cat >&2 <<EOF
Purpose:
Upgrade OnPrem Edge Orchestrator to v3.1.0.
Usage:
$(basename "$0") [option...] [argument]
ex:
./onprem_upgrade.sh -b
./onprem_upgrade.sh -bl # Use local packages with backup
Options:
-b: enable backup of Orchestrator PVs before upgrade (optional)
-l: use local packages instead of downloading (optional)
-o: override production values with dev values (optional)
-h: help (optional)
EOF
}
################################
##### UPGRADE SCRIPT START #####
################################
# CLI flags (must be initialized for shells with nounset enabled)
HELP=''
BACKUP=''
OVERRIDE=''
# shellcheck disable=SC2034
while getopts 'v:hbol' flag; do
case "${flag}" in
h) HELP='true' ;;
b) BACKUP='true' ;;
o) OVERRIDE='true' ;;
l) USE_LOCAL_PACKAGES='true' ;; # New local packages flag
*) HELP='true' ;;
esac
done
if [[ "${HELP:-}" == "true" ]]; then
usage
exit 1
fi
# Check if postgres is running and if it is safe to backup
check_postgres
if ! check_postgres; then
echo "PostgreSQL is not running or backup file already exists. Exiting..."
exit 1
fi
# Perform PostgreSQL secret backup if not done already
if [[ ! -f postgres_secret.yaml ]]; then
kubectl get secret -n orch-database postgresql-cluster-superuser -o yaml > postgres_secret.yaml
fi
# Remove runtime variables from previous runs, then retrieve fresh config
reset_runtime_variables
# Re-source the config file after cleanup to get fresh values
# shellcheck disable=SC1091
source "$(dirname "${0}")/onprem.env"
# Retrieve/Apply config that was set during onprem installation and apply it to orch-configs
#retrieve_and_apply_config
retrieve_and_update_config
# Delete gitea secrets before backup
if [[ "$INSTALL_GITEA" == "true" ]]; then
cleanup_gitea_secrets
fi
# Backup PostgreSQL databases
backup_postgres
echo "Running On Premise Edge Orchestrator upgrade to $DEPLOY_VERSION"
# Refresh variables after checking user args
set_artifacts_version
# Check if orchestrator is currently installed
check_orch_install "${installer_list[@]}"
# Check & install script dependencies
check_oras
install_yq
### Backup
if [[ "${BACKUP:-}" == "true" ]]; then
echo "Backing up PVs..."
backup_pvs
if [[ $? -eq 1 ]]; then
exit 1
fi
echo "PVs backed up successfully"
# Take RKE2 backup (etcd) -> https://docs.rke2.io/backup_restore
echo "Taking rke2 snapshot..."
sudo rke2 etcd-snapshot save --name "pre-upgrade-snapshot-$(dpkg-query -W -f='${Version}' onprem-ke-installer)"
sudo mkdir -p /var/orch-backups/
sudo find /var/lib/rancher/rke2/server/db/snapshots/ -name "pre-upgrade-snapshot-*" -exec mv {} /var/orch-backups/ \;
echo "Snapshot saved to /var/orch-backups/"
fi
# Skip artifact download if using local packages
if [[ $USE_LOCAL_PACKAGES != "true" ]]; then
# Cleanup and download .deb packages
sudo rm -rf "${cwd:?}/${deb_dir_name:?}/"
download_artifacts "$cwd" "$deb_dir_name" "$RELEASE_SERVICE_URL" "$installer_rs_path" "${installer_list[@]}"
sudo chown -R _apt:root "$deb_dir_name"
# Cleanup and download .git packages
sudo rm -rf "${cwd:?}/${git_arch_name:?}/"
download_artifacts "$cwd" "$git_arch_name" "$RELEASE_SERVICE_URL" "$archives_rs_path" "${git_archive_list[@]}"
else
echo "Using local packages..."
# Ensure local directories exist with required files
if [[ ! -d "$deb_dir_name" ]]; then
echo "Error: Local $deb_dir_name directory not found!"
echo "Please place your .deb files in: $cwd/$deb_dir_name/"
exit 1
fi
if [[ ! -d "$git_arch_name" ]]; then
echo "Error: Local $git_arch_name directory not found!"
echo "Please place your onpremFull_edge-manageability-framework_3.1.0-dev.tgz in: $cwd/$git_arch_name/"
exit 1
fi
# Verify required .deb files exist
for package in "${installer_list[@]}"; do
package_name="${package%%:*}"
if ! ls "$cwd/$deb_dir_name/${package_name}"_*_amd64.deb 1> /dev/null 2>&1; then
echo "Error: ${package_name} .deb file not found in $cwd/$deb_dir_name/"
exit 1
fi
done
# Verify .tgz file exists
if ! ls "$cwd/$git_arch_name/"*edge-manageability-framework*.tgz 1> /dev/null 2>&1; then
echo "Error: edge-manageability-framework .tgz file not found in $cwd/$git_arch_name/"
exit 1
fi
sudo chown -R _apt:root "$deb_dir_name"
fi
# Check if kyverno-clean-reports job exists before attempting cleanup
if kubectl get job kyverno-clean-reports -n kyverno >/dev/null 2>&1; then
echo "Cleaning up kyverno-clean-reports job..."
kubectl delete job kyverno-clean-reports -n kyverno &
kubectl delete pods -l job-name="kyverno-clean-reports" -n kyverno &
kubectl patch job kyverno-clean-reports -n kyverno --type=merge -p='{"metadata":{"finalizers":[]}}'
else
echo "kyverno-clean-reports job not found in kyverno namespace, skipping cleanup"
fi
### Upgrade
apply_and_package_config
# Run OS Configuration upgrade
echo "Upgrading the OS level configuration..."
eval "sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l apt-get install --only-upgrade --allow-downgrades -y $cwd/$deb_dir_name/onprem-config-installer_*_amd64.deb"
echo "OS level configuration upgraded to $(dpkg-query -W -f='${Version}' onprem-config-installer)"
# Run RKE2 upgrade
echo "Upgrading RKE2..."
eval "sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l apt-get install --only-upgrade --allow-downgrades -y $cwd/$deb_dir_name/onprem-ke-installer_*_amd64.deb"
echo "RKE2 upgraded to $(dpkg-query -W -f='${Version}' onprem-ke-installer)"
# Run Gitea upgrade
if [[ "$INSTALL_GITEA" == "true" ]]; then
echo "Upgrading Gitea..."
eval "sudo IMAGE_REGISTRY=${GITEA_IMAGE_REGISTRY} INSTALL_GITEA=${INSTALL_GITEA} DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l apt-get install --only-upgrade --allow-downgrades -y $cwd/$deb_dir_name/onprem-gitea-installer_*_amd64.deb"
wait_for_pods_running $gitea_ns
echo "Gitea upgraded to $(dpkg-query -W -f='${Version}' onprem-gitea-installer)"
else
echo "Skipping Gitea upgrade (INSTALL_GITEA is false)"
fi
# Run ArgoCD upgrade
echo "Upgrading ArgoCD..."
eval "sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l apt-get install --only-upgrade --allow-downgrades -y $cwd/$deb_dir_name/onprem-argocd-installer_*_amd64.deb"
wait_for_pods_running $argo_cd_ns
echo "ArgoCD upgraded to $(dpkg-query -W -f='${Version}' onprem-argocd-installer)"
# Run Orchestrator upgrade
echo "Upgrading Edge Orchestrator Packages..."
# Skip saving passwords if postgres-secrets-password.txt exists and is not empty
if [[ ! -s postgres-secrets-password.txt ]]; then
ALERTING=$(kubectl get secret alerting-local-postgresql -n orch-infra -o jsonpath='{.data.PGPASSWORD}')
CATALOG_SERVICE=$(kubectl get secret app-orch-catalog-local-postgresql -n orch-app -o jsonpath='{.data.PGPASSWORD}')
INVENTORY=$(kubectl get secret inventory-local-postgresql -n orch-infra -o jsonpath='{.data.PGPASSWORD}')
IAM_TENANCY=$(kubectl get secret iam-tenancy-local-postgresql -n orch-iam -o jsonpath='{.data.PGPASSWORD}')
PLATFORM_KEYCLOAK=$(kubectl get secret platform-keycloak-local-postgresql -n orch-platform -o jsonpath='{.data.PGPASSWORD}')
VAULT=$(kubectl get secret vault-local-postgresql -n orch-platform -o jsonpath='{.data.PGPASSWORD}')
POSTGRESQL=$(kubectl get secret orch-database-postgresql -n orch-database -o jsonpath='{.data.password}')
MPS=$(kubectl get secret mps-local-postgresql -n orch-infra -o jsonpath='{.data.PGPASSWORD}')
RPS=$(kubectl get secret rps-local-postgresql -n orch-infra -o jsonpath='{.data.PGPASSWORD}')
{
echo "Alerting: $ALERTING"
echo "CatalogService: $CATALOG_SERVICE"
echo "Inventory: $INVENTORY"
echo "IAMTenancy: $IAM_TENANCY"
echo "PlatformKeycloak: $PLATFORM_KEYCLOAK"
echo "Vault: $VAULT"
echo "PostgreSQL: $POSTGRESQL"
echo "Mps: $MPS"
echo "Rps: $RPS"
} > postgres-secrets-password.txt
else
echo "postgres-secrets-password.txt exists and is not empty, skipping password save."
fi
# Delete secrets for mps and rps if they exist, so that they can be recreated later
if kubectl get secret mps -n orch-infra >/dev/null 2>&1; then
kubectl get secret mps -n orch-infra -o yaml > mps_secret.yaml
kubectl delete secret mps -n orch-infra
fi
if kubectl get secret rps -n orch-infra >/dev/null 2>&1; then
kubectl get secret rps -n orch-infra -o yaml > rps_secret.yaml
kubectl delete secret rps -n orch-infra
fi
# Idea is the same as in postrm_patch but for orch-installer whole new script is required
sudo tee /var/lib/dpkg/info/onprem-orch-installer.postrm >/dev/null <<'EOF'
#!/usr/bin/env bash
set -o errexit
export KUBECONFIG=/home/$USER/.kube/config
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
kubectl delete job -n gitea -l managed-by=edge-manageability-framework || true
kubectl delete sts -n orch-database postgresql || true
kubectl delete job -n orch-infra credentials || true
kubectl delete job -n orch-infra loca-credentials || true
if [ "${1}" = "upgrade" ]; then
exit 0
fi
# Secrets for postgresql are generated on each installation, so we have to clean them up to avoid issues during reinstallation
kubectl delete secret -l managed-by=edge-manageability-framework -A || true
EOF
# Build environment variables for orchestrator upgrade
GIT_ENV_VARS="INSTALL_GITEA=${INSTALL_GITEA} ORCH_INSTALLER_PROFILE=$ORCH_INSTALLER_PROFILE GIT_REPOS=$GIT_REPOS"
if [[ "$INSTALL_GITEA" == "false" ]]; then
# When Gitea is disabled, pass GitHub credentials if available
if [[ -n "$GIT_TOKEN" ]]; then
GIT_ENV_VARS="$GIT_ENV_VARS GIT_TOKEN=$GIT_TOKEN"
fi
if [[ -n "$GIT_USER" ]]; then
GIT_ENV_VARS="$GIT_ENV_VARS GIT_USER=$GIT_USER"
fi
if [[ -n "$DEPLOY_REPO_URL" ]]; then
GIT_ENV_VARS="$GIT_ENV_VARS DEPLOY_REPO_URL=$DEPLOY_REPO_URL"
fi
fi
eval "sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=l $GIT_ENV_VARS apt-get install --only-upgrade --allow-downgrades -y $cwd/$deb_dir_name/onprem-orch-installer_*_amd64.deb"
echo "Edge Orchestrator getting upgraded to version $(dpkg-query -W -f='${Version}' onprem-orch-installer), wait for SW to deploy... "
# Allow adjustments as some PVCs sizes might have changed
#kubectl patch storageclass openebs-lvmpv -p '{"allowVolumeExpansion": true}'
# Delete rke2-metrics-server chart. If it fails ignore
helm delete -n kube-system rke2-metrics-server || true
resync_all_apps
# Restore PostgreSQL passwords after they have been overwritten
set +e
while true; do
if kubectl get secret -n orch-app app-orch-catalog-reader-local-postgresql; then
echo "Proceeding with passwords restoration..."
sleep 10
break
else
echo "Passwords not yet overwritten, waiting..."
sleep 10
fi
done
set -e
patch_secrets() {
# Patch secrets with passwords from postgres-secrets-password.txt
# If the file is not empty, read the passwords and patch the secrets accordingly
if [[ -s postgres-secrets-password.txt ]]; then
echo "Patching secrets with passwords from postgres-secrets-password.txt"
while IFS=': ' read -r key value; do
case "$key" in
Alerting) ALERTING="$value" ;;