-
Notifications
You must be signed in to change notification settings - Fork 11
/
upgrade-2.x.sh
executable file
·1580 lines (1429 loc) · 61 KB
/
upgrade-2.x.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
# default configuration
NOREBOOT=no
DELTA_VERSION=3
SCRIPTNAME=upgrade-2.x.sh
LEGACY_UPDATE=no
STOP_ALL=no
set -o errexit
set -E
set -o pipefail
preferred_hostos_version=2.0.7
minimum_target_version=2.0.7
minimum_hostapp_target_version=2.5.1
minimum_balena_target_version=2.9.0
minimum_supervisor_stop=2.53.10
# This will set VERSION, SLUG
# shellcheck disable=SC1091
. /etc/os-release
# Don't run anything before this source as it sets PATH here
# shellcheck disable=SC1091
source /etc/profile
if [ -x "$(command -v balena)" ]; then
DOCKER_CMD="balena"
DOCKERD="balenad"
else
DOCKER_CMD="docker"
DOCKERD="dockerd"
fi
###
# Helper functions
###
# Preventing running multiple instances of upgrades running
LOCKFILE="/var/lock/resinhup.lock"
LOCKFD=99
## Private functions
_lock() { flock "-$1" $LOCKFD; }
_exit_handler() {
_exit_status=$?
if [ "${_exit_status}" -ne 0 ]; then
log "Exit on error ${_exit_status}"
if ! report_update_failed > /dev/null 2>&1; then
log "Failed to report progress on exit with status $?"
fi
if [ "${_exit_status}" -eq 9 ]; then
log "No concurrent updates allowed - lock file in place."
fi
fi
_no_more_locking
log "Lock removed - end."
}
_no_more_locking() { _lock u; _lock xn && rm -f $LOCKFILE;rm -f "${outfifo}";rm -f "${errfifo}"; }
_prepare_locking() { eval "exec $LOCKFD>\"$LOCKFILE\""; trap _exit_handler EXIT; }
# Public functions
exlock_now() { _lock xn; } # obtain an exclusive lock immediately or fail
# workaround for self-signed certs, waiting for https://github.com/balena-os/meta-balena/issues/1398
TMPCRT=$(mktemp)
jq -r '.balenaRootCA' < /mnt/boot/config.json | base64 -d > "${TMPCRT}"
cat /etc/ssl/certs/ca-certificates.crt >> "${TMPCRT}"
CURL="curl --silent --retry 10 --fail --location --compressed"
# Dashboard progress helper
function progress {
percentage=$1
message=$2
resin-device-progress --percentage "${percentage}" --state "${message}" > /dev/null || true
}
function help {
cat << EOF
Helper to run hostOS updates on balenaOS 2.x devices
Options:
-h, --help
Display this help and exit.
--force-slug <SLUG>
Override slug detection and force this slug to be used for the script.
--hostos-version <HOSTOS_VERSION>
Run the updater for this specific HostOS version as semver.
Omit the 'v' in front of the version. e.g.: 2.2.0+rev1 and not v2.2.0+rev1.
This is a mandatory argument.
--supervisor-version <SUPERVISOR_VERSION>
Run the supervisor update for this specific supervisor version as semver.
Omit the 'v' in front of the version. e.g.: 6.2.5 and not v6.2.5
If not defined, then the update will try to run for the HOSTOS_VERSION's
original supervisor release.
-n, --nolog
By default tool logs to stdout and file. This flag deactivates log to file.
--no-reboot
Do not reboot if update is successful. This is useful when debugging.
--balenaos-registry
Upstream registry to use for host OS applications.
--balenaos-repo
No op
--balenaos-tag
No op
--staging
No op
--stop-all
Request the updater to stop all containers (including user application)
before the update.
--assume-supported
This is now deprecated. Assuming supported device, and disabling the relevant check.
Only enabled for updates that does not use update hooks, otherwise the updater
wouldn't know how to switch partitions, so only available for balenaOS
below ${minimum_hostapp_target_version}.
EOF
}
function report_update_failed() {
perc=100
state="OS update failed"
while ! compare_device_state "${perc}" "${state}"; do
((c++)) && ((c==60)) && break
if resin-device-progress --percentage "${perc}" --state "${state}"; then
continue
fi
log WARN "Retrying failure report - try $c"
sleep 60
done
}
# Log function helper
function log {
# Address log levels
priority=6
case $1 in
ERROR)
loglevel=ERROR
priority=3
shift
;;
WARN)
loglevel=WARNING
priority=4
shift
;;
*)
loglevel=INFO
;;
esac
echo "${1}" | systemd-cat --level-prefix=0 --identifier="${SCRIPTNAME}" --priority="${priority}" 2> /dev/null || true
endtime=$(date +%s)
printf "[%s][%09d%s%s\n" "$SCRIPTNAME" "$((endtime - starttime))" "][$loglevel]" "$1"
if [ "$loglevel" == "ERROR" ]; then
exit 1
fi
}
# Test if a version is greater than another
function version_gt() {
test "$(echo "$@" | tr " " "\n" | sort -V | head -n 1)" != "$1"
}
function compare_device_state() {
perc=$1
state=$2
local resp
local remote_perc
local remote_state
resp=$(CURL_CA_BUNDLE="${TMPCRT}" ${CURL} --header "Authorization: Bearer ${APIKEY}" \
"${API_ENDPOINT}/v6/device(uuid='${UUID}')?\$select=provisioning_state,provisioning_progress" | jq '.d[]')
remote_perc=$(echo "${resp}" | jq -r '.provisioning_progress')
remote_state=$(echo "${resp}" | jq -r '.provisioning_state')
if [ -n "${remote_perc}" ] && [ -n "${remote_state}" ]; then
test "${perc}" -eq "${remote_perc}" && test "${state}" = "${remote_state}"
else
return 1
fi
}
function stop_services() {
# Stopping supervisor and related services
log "Stopping supervisor and related services..."
systemctl stop update-balena-supervisor.timer > /dev/null 2>&1 || systemctl stop update-resin-supervisor.timer > /dev/null 2>&1
systemctl stop balena-supervisor > /dev/null 2>&1 || systemctl stop resin-supervisor > /dev/null 2>&1
${DOCKER_CMD} rm -f balena_supervisor resin_supervisor > /dev/null 2>&1 || true
}
function remove_containers() {
log "Stopping all containers.."
# shellcheck disable=SC2046
${DOCKER_CMD} stop $(${DOCKER_CMD} ps -a -q) > /dev/null 2>&1 || true
log "Removing all containers..."
# shellcheck disable=SC2046
${DOCKER_CMD} rm $(${DOCKER_CMD} ps -a -q) > /dev/null 2>&1 || true
}
function remove_rec_files() {
local boot_dir='/mnt/boot'
shopt -s nullglob
for f in "${boot_dir}"/*.REC; do
log WARN "Removing $f from boot partition"
rm -f "$f"
done
sync ${boot_dir}
}
#######################################
# Helper function to run a transient unit to update the supervisor.
# Returns
# 0: Success
# 1: Failure
#######################################
function _run_supervisor_update() {
local supervisor_update
local ret=0
local update_balena_supervisor_script
update_balena_supervisor_script="$(command -v update-balena-supervisor || command -v update-resin-supervisor)"
# use a transient unit in order to namespace-collide with a potential API-initiated update
if grep -q "os-helpers-logging" "${update_balena_supervisor_script}"; then
# if the update-balena-supervisor script used os-helpers-logging append stderr to the log file
supervisor_update="systemd-run --wait --property=StandardError=append:${LOGFILE} --unit run-update-supervisor ${update_balena_supervisor_script}"
else
supervisor_update="systemd-run --wait --unit run-update-supervisor ${update_balena_supervisor_script}"
fi
if version_gt "${HOST_OS_VERSION}" "${minimum_supervisor_stop}"; then
supervisor_update+=' -n'
fi
if ! eval "${supervisor_update}"; then
log WARN "Supervisor couldn't be updated" && ret=1
fi
journalctl -a -u run-update-supervisor --no-pager || true
return "${ret}"
}
# Fetch the current and scheduled supervisor versions from the API
#
# Returns:
#
# 0: Success
# 1: Failure
#
# Outputs:
#
# On success, a string separated string of current and scheduled supervisor
# versions.
#
function _fetch_supervisor_version() {
local resp
local supervisor_version
local scheduled_supervisor_version
resp=$(CURL_CA_BUNDLE="${TMPCRT}" ${CURL} --header "Authorization: Bearer ${APIKEY}" "${API_ENDPOINT}/v6/device(uuid='${UUID}')?\$select=supervisor_version&\$expand=should_be_managed_by__supervisor_release(\$top=1;\$select=supervisor_version)")
if supervisor_version=$(echo "${resp}" | jq -e -r '.d[0].supervisor_version' | tr -d 'v'); then
if [ -z "${supervisor_version}" ]; then
log ERROR "Could not get current supervisor version from the API, got ${resp}"
return 1
fi
scheduled_supervisor_version=$(echo "${resp}" | jq -e -r '.d[0].should_be_managed_by__supervisor_release[0].supervisor_version' | tr -d 'v')
if [ -n "${scheduled_supervisor_version}" ] && [ "${scheduled_supervisor_version}" != "null" ]; then
if version_gt "${scheduled_supervisor_version}" "${supervisor_version}"; then
# The supervisor is scheduled to update
echo "${supervisor_version} ${scheduled_supervisor_version}"
return 0
fi
fi
echo "${supervisor_version} ${supervisor_version}"
else
log ERROR "Could not fetch current supervisor version from the API, got ${resp}"
return 1
fi
}
#######################################
# Helper function to patch the supervisor version in the target state.
# Globals:
# API_ENDPOINT
# APIKEY
# UUID
# SLUG
# Arguments:
# version: supervisor version to update the target state to
# Returns
# 0: Success
# 1: Failure
#######################################
function _patch_supervisor_version() {
local version=$1
local current_version
local _status_code
local _errfile
local _outfile
local UPDATER_SUPERVISOR_TAG
local UPDATER_SUPERVISOR_ID
[ -z "${version}" ] && log "Supervisor version is required" && return 1
UPDATER_SUPERVISOR_TAG="v${version}"
# Get the supervisor id
resp=$(CURL_CA_BUNDLE="${TMPCRT}" ${CURL} --header "Authorization: Bearer ${APIKEY}" "${API_ENDPOINT}/v5/supervisor_release?\$select=id,image_name&\$filter=((device_type%20eq%20'$SLUG')%20and%20(supervisor_version%20eq%20'${UPDATER_SUPERVISOR_TAG}'))")
if UPDATER_SUPERVISOR_ID=$(echo "${resp}" | jq -e -r '.d[0].id'); then
log "Extracted supervisor vars: ID: $UPDATER_SUPERVISOR_ID"
log "Setting supervisor version in the API..."
_errfile=$(mktemp)
_outfile=$(mktemp)
if _status_code=$(CURL_CA_BUNDLE="${TMPCRT}" ${CURL} --request PATCH -w "%{http_code}" --show-error -o "${_outfile}" --header "Authorization: Bearer ${APIKEY}" --header 'Content-Type: application/json' "${API_ENDPOINT}/v6/device(uuid='${UUID}')" --data-binary "{\"should_be_managed_by__supervisor_release\": \"${UPDATER_SUPERVISOR_ID}\"}" 2> "${_errfile}"); then
rm -f "${_errfile}"
case "${_status_code}" in
2*) log "Successfully set supervision version in target state";rm -f "${_outfile}";return 0;;
4*) log WARN "[${_status_code}]: Bad request: $(cat "${_outfile}")"; rm -f "${_outfile}"; if current_version=$(_fetch_supervisor_version | cut -d " " -f1); then if version_gt "${current_version}" "${version}"; then return 0; else return 1; fi; else return 1; fi;;
*) log WARN "[${_status_code}]: Request failed: $(cat "${_outfile}")";rm -f "${_outfile}";return 1;;
esac
else
log WARN "$(cat "${_errfile}")"
rm -f "${_errfile}"
return 1
fi
else
log WARN "Failed fetching supervisor id from API: ${resp}"
return 1
fi
}
#######################################
# Upgrade the supervisor on the device.
# Extract the supervisor version with which the the target hostOS is shipped,
# and if it's newer than the supervisor running on the device, then fetch the
# information that is required for supervisor update, and do the update with
# the tools shipped with the hostOS.
# Globals:
# API_ENDPOINT
# APIKEY
# UUID
# SLUG
# target_supervisor_version
# Arguments:
# image: the docker image to exctract the config from
# non_docker_host: empty value will use docker-host, non empty value will use the main docker
# Returns:
# None
#######################################
function upgrade_supervisor() {
local image=$1
local no_docker_host=$2
log "Supervisor update start..."
if [ -z "$target_supervisor_version" ]; then
log "No explicit supervisor version was provided, update to default version in target balenaOS..."
local DEFAULT_SUPERVISOR_VERSION
versioncheck_cmd=("run" "--rm" "${image}" "bash" "-c" "cat /etc/*-supervisor/supervisor.conf | sed -rn 's/SUPERVISOR_(TAG|VERSION)=v(.*)/\\2/p'")
if [ -z "$no_docker_host" ]; then
DEFAULT_SUPERVISOR_VERSION=$(DOCKER_HOST="unix:///var/run/${DOCKER_CMD}-host.sock" ${DOCKER_CMD} "${versioncheck_cmd[@]}")
else
DEFAULT_SUPERVISOR_VERSION=$(${DOCKER_CMD} "${versioncheck_cmd[@]}")
fi
if [ -z "$DEFAULT_SUPERVISOR_VERSION" ]; then
log ERROR "Could not get the default supervisor version for this balenaOS release, bailing out."
else
log "Extracted default version is v$DEFAULT_SUPERVISOR_VERSION..."
target_supervisor_version="$DEFAULT_SUPERVISOR_VERSION"
fi
fi
if supervisor_target_state_versions=$(_fetch_supervisor_version); then
read -r CURRENT_SUPERVISOR_VERSION SCHEDULED_SUPERVISOR_VERSION <<< "${supervisor_target_state_versions}"
log "Supervisor state: Target ${target_supervisor_version}, current ${CURRENT_SUPERVISOR_VERSION}, scheduled ${SCHEDULED_SUPERVISOR_VERSION}"
# If scheduled higher than current and target, update to scheduled
# If scheduled not higher than current:
# If target higher than current, patch and update to target
# If target not higher than current, do nothing
if ! version_gt "${SCHEDULED_SUPERVISOR_VERSION}" "${CURRENT_SUPERVISOR_VERSION}"; then
# Supervisor target state current version is higher or equal than the scheduled version.
if version_gt "$target_supervisor_version" "$CURRENT_SUPERVISOR_VERSION" ; then
# Supervisor target version is higher than current target state version
log "Patching supervisor target state from v${CURRENT_SUPERVISOR_VERSION} to v${target_supervisor_version}"
progress 90 "Patching supervisor update"
if ! _patch_supervisor_version "$target_supervisor_version"; then
log ERROR "Failed to patch supervisor version in target state, bailing out."
fi
else
log "Supervisor update: no update needed."
return 0
fi
else
# Supervisor target state scheduled version is higher than the current version
if version_gt "$SCHEDULED_SUPERVISOR_VERSION" "$target_supervisor_version" ; then
target_supervisor_version="$SCHEDULED_SUPERVISOR_VERSION"
fi
fi
log "Updating supervisor target state from v${CURRENT_SUPERVISOR_VERSION} to v${target_supervisor_version}"
progress 95 "Running supervisor update"
if _run_supervisor_update; then
if version_gt "6.5.9" "${target_supervisor_version}" ; then
remove_containers
log "Removing supervisor database for migration"
rm /resin-data/resin-supervisor/database.sqlite || true
fi
else
log WARN "Failed to update supervisor version - leave to next boot."
fi
else
log ERROR "Failed to fetch current supervisor version from the API."
fi
# Post supervisor update fixes
persistent_logging_config_var
}
function error_handler() {
# If script fails (e.g. docker pull fails), restart the stopped services like the supervisor
systemctl start balena-supervisor resin-supervisor || true
systemctl start update-balena-supervisor.timer update-resin-supervisor.timer || true
exit 1
}
function remove_sample_wifi {
# Removing the `resin-sample` file if it exists on the device, and has the default
# connection settings, as they are well known and thus insecure
local filename=$1
if [ -f "${filename}" ] && grep -Fxq "ssid=My_Wifi_Ssid" "${filename}" && grep -Fxq "psk=super_secret_wifi_password" "${filename}" ; then
if nmcli c show --active | grep "resin-sample" ; then
# If a connection with that name is in use, do not actually remove the settings
log WARN "resin-sample configuration found at ${filename} but it might be connected, not removing..."
else
log "resin-sample configuration found at ${filename}, removing..."
rm "${filename}" || log WARN "couldn't remove ${filename}; continuing anyways..."
fi
else
log "No resin-sample found at ${filename} with default config, good..."
fi
}
# Pre update cleanup: remove some not-required files from the boot partition to clear some space
function pre_update_pi_bootfiles_removal {
local boot_files_for_removal=('start_db.elf' 'fixup_db.dat')
for f in "${boot_files_for_removal[@]}"; do
log "Removing $f from boot partition"
rm -f "/mnt/boot/$f"
done
sync /mnt/boot
}
function pre_update_fix_bootfiles_hook {
log "Applying bootfiles hostapp-hook fix"
local bootfiles_temp
bootfiles_temp=$(mktemp)
CURL_CA_BUNDLE="${TMPCRT}" ${CURL} -o "$bootfiles_temp" https://raw.githubusercontent.com/balena-os/balenahup/77401f3ecdeddaac843b26827f0a44d3b044efdd/upgrade-patches/0-bootfiles || log ERROR "Couldn't download fixed '0-bootfiles', aborting."
chmod 755 "$bootfiles_temp"
mount --bind "$bootfiles_temp" /etc/hostapp-update-hooks.d/0-bootfiles
}
function pre_update_jetson_fix {
log "Caching current extlinux.conf for ${SLUG} fix"
extlinux_root_path="boot/extlinux"
mkdir -p "/tmp/${extlinux_root_path}"
cp "/mnt/${extlinux_root_path}/extlinux.conf" "/tmp/${extlinux_root_path}/extlinux.conf"
log "Stopping supervisor to prevent reboots during extlinux.conf updating"
stop_services
}
function parse_isolcpus {
path=$1
if grep -q "isolcpus=" "${path}" ; then
# shellcheck disable=SC2013
for val in $(awk '/isolcpus=/' "${path}"); do
if echo "${val}" | grep -q "isolcpus="; then
echo "${val}"
fi
done
fi
}
function post_update_jetson_fix {
log "Applying extlinux.conf fix for ${SLUG}"
# check if current config has isolcpus set in extlinux.conf
extlinux_file="boot/extlinux/extlinux.conf"
uEnv_file="/mnt/boot/extra_uEnv.txt"
new_extlinux="/mnt/${extlinux_file}"
old_extlinux="/tmp/${extlinux_file}"
# step 1, translate the values from extlinux.conf
local OLD_isolcpus NEW_isolcpus replacement_isolcpu
OLD_isolcpus=$(parse_isolcpus "${old_extlinux}")
NEW_isolcpus=$(parse_isolcpus "${new_extlinux}")
if [ "${OLD_isolcpus}" != "${NEW_isolcpus}" ]; then
replacement_isolcpu=$(mktemp)
cp "${new_extlinux}" "${replacement_isolcpu}"
log "extlinux difference detected"
if [ -n "${NEW_isolcpus}" ]; then
log "replacing \`isolcpu\` value in extlinux.conf"
sed -in "s/${NEW_isolcpus}/${OLD_isolcpus}/" "${replacement_isolcpu}"
else
log "adding previous \`isolcpu\` value to extlinux.conf"
sed -in "/APPEND/s/$/ ${OLD_isolcpus}/" "${replacement_isolcpu}"
fi
# do replacement
mv "${replacement_isolcpu}" "${new_extlinux}" && sync "${new_extlinux}"
fi
# step 2, port across the FDT directive
FDT_value=$(awk '/^ *FDT/{print $NF}' ${old_extlinux})
if [ -n "${FDT_value}" ] && [ "${FDT_value}" != "default" ]; then
log "adding previous \`FDT\` value in ${uEnv_file}"
echo "custom_fdt_file=${FDT_value}" >> "${uEnv_file}" && sync "${uEnv_file}"
fi
# step 3, port across entire APPEND
APPEND_value=$(awk '/^ *APPEND/{for (i=2; i<=NF; i++) printf $i " "; print $NF}' ${old_extlinux})
if [ -n "${APPEND_value}" ]; then
if [ -e "${uEnv_file}" ] && grep -q extra_os_cmdline "${uEnv_file}"; then
log "replacing previous \`APPEND\` value in ${uEnv_file}"
sed -in "s/extra_os_cmdline=.*/extra_os_cmdline=${APPEND_value}/" "${uEnv_file}" && sync "${uEnv_file}"
else
log "appending previous \`APPEND\` value in ${uEnv_file}"
echo "extra_os_cmdline=${APPEND_value}" >> "${uEnv_file}" && sync "${uEnv_file}"
fi
fi
if [ -e "${uEnv_file}" ] && grep -q '^os_bc_lim=' "${uEnv_file}"; then
log "Fix for jetson-tx2 bootcount limit already applied"
else
echo "os_bc_lim=3" >> "${uEnv_file}" && sync "${uEnv_file}"
log "Applied fix for jetson-tx2 bootcount limit to extra_uEnv.txt"
fi
}
#######################################
# Update problematic persistent logging env var
# Earlier supervisors might have set it to "", and
# that doesn't validate on newer supervisor versions.
# Convert into proper false value.
# Globals:
# API_ENDPOINT
# APIKEY
# CONFIGJSON
# UUID
# Returns:
# None
#######################################
function persistent_logging_config_var {
PROBLEMATIC_ENV_VAR=$(CURL_CA_BUNDLE="${TMPCRT}" ${CURL} "${API_ENDPOINT}/v5/device_config_variable?\$filter=device/uuid%20eq%20'${UUID}'" -H "Content-Type: application/json" -H "Authorization: Bearer ${APIKEY}" | jq -r '.d[] | select((.name == "RESIN_SUPERVISOR_PERSISTENT_LOGGING") and (.value == "")) | .id')
if [ -n "${PROBLEMATIC_ENV_VAR}" ]; then
local tmpfile
log "Updating problematic RESIN_SUPERVISOR_PERSISTENT_LOGGING config variable"
CURL_CA_BUNDLE="${TMPCRT}" ${CURL} -X PATCH \
"${API_ENDPOINT}/v5/device_config_variable(${PROBLEMATIC_ENV_VAR})" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${APIKEY}" \
--data '{
"value": "false"
}' >> /dev/null
log "Updating config.json with sanitized '.persistentLogging' value."
tmpfile=$(mktemp -t configjson.XXXXXXXX)
jq '.persistentLogging="false"' < "${CONFIGJSON}" > "${tmpfile}"
# 2-step move for atomicity
cp "${tmpfile}" "$CONFIGJSON.temp" || log ERROR "Couldn't copy temporary config.json to final partition."
sync
mv "$CONFIGJSON.temp" "$CONFIGJSON" || log ERROR "Couldn't move updated config.json onto original."
sync
fi
}
#######################################
# Prepares and runs update based on hostapp-update
# Includes pre-update fixes and balena migration
# Globals:
# DOCKER_CMD
# target_version
# minimum_balena_target_version
# Arguments:
# update_package: the docker image to use for the update
# tmp_inactive: host path to the directory that will be bind-mounted to /mnt/sysroot/inactive inside the container
# Returns:
# None
#######################################
function in_container_hostapp_update {
local update_package=$1
local tmp_inactive=$2
local inactive="/mnt/sysroot/inactive"
local hostapp_update_extra_args=""
local target_docker_cmd
local target_dockerd
local volumes_args=()
local -i retrycount=0
local tmp_image
stop_services
if [ "${STOP_ALL}" == "yes" ]; then
remove_containers
fi
# Disable rollbacks when doing migration to rollback enabled system, as couldn't roll back anyways
if version_gt "${target_version}" "2.9.3"; then
hostapp_update_extra_args="-x"
fi
# Set the name of the docker/balena command within the target image to the appropriate one
if version_gt "${target_version}" "${minimum_balena_target_version}"; then
target_docker_cmd="balena"
target_dockerd="balenad"
else
target_docker_cmd="docker"
target_dockerd="dockerd"
fi
while true ; do
if ${DOCKER_CMD} pull "${update_package}"; then
break
else
log WARN "Couldn't pull docker image, was try #${retrycount}..."
fi
retrycount+=1
if [ $retrycount -ge 10 ]; then
log ERROR "Couldn't pull docker image, giving up..."
else
sleep 10
fi
done
tmp_image=$(mktemp -u "/tmp/hupfile.XXXXXXXX")
log "Using ${tmp_image} for update image transfer into container"
mkfifo "${tmp_image}"
${DOCKER_CMD} save "${update_package}" > "${tmp_image}" &
mkdir -p /mnt/data/balenahup/tmp
# The setting up the required volumes
volumes_args+=("-v" "/dev/disk:/dev/disk")
volumes_args+=("-v" "/mnt/boot:/mnt/boot")
volumes_args+=("-v" "/mnt/data/balenahup/tmp:/mnt/data/balenahup/tmp")
if mountpoint "/mnt/sysroot/active"; then
volumes_args+=("-v" "/mnt/sysroot/active:/mnt/sysroot/active")
else
volumes_args+=("-v" "/:/mnt/sysroot/active")
fi
volumes_args+=("-v" "${tmp_inactive}:${inactive}")
volumes_args+=("-v" "${tmp_image}:/balenaos-image.docker")
log "Starting hostapp-update within a container"
# Note that the following docker daemon is started with a different --bip and --fixed-cidr
# setting, otherwise it is clashing with the system docker on balenaOS >=2.3.0 || <2.5.1
# and then docker pull would not succeed
# shellcheck disable=SC2016
${DOCKER_CMD} run \
--rm \
--name balenahup \
--privileged \
"${volumes_args[@]}" \
"${update_package}" \
/bin/bash -c 'storage_driver=$(cat /boot/storage-driver) ; DOCKER_TMPDIR=/mnt/data/balenahup/tmp/ '"${target_dockerd}"' --storage-driver=$storage_driver --data-root='"${inactive}"'/'"${target_docker_cmd}"' --host=unix:///var/run/'"${target_docker_cmd}"'-host.sock --pidfile=/var/run/'"${target_docker_cmd}"'-host.pid --exec-root=/var/run/'"${target_docker_cmd}"'-host --bip=10.114.201.1/24 --fixed-cidr=10.114.201.128/25 --iptables=false & timeout_iterations=0; until DOCKER_HOST="unix:///var/run/'"${target_docker_cmd}"'-host.sock" '"${target_docker_cmd}"' ps &> /dev/null; do sleep 0.2; if [ $((timeout_iterations++)) -ge 1500 ]; then echo "'"${target_docker_cmd}"'-host did not come up before check timed out..."; exit 1; fi; done; echo "Starting hostapp-update"; hostapp-update -f /balenaos-image.docker '"${hostapp_update_extra_args}"'' \
|| log ERROR "Update based on hostapp-update has failed..."
}
#######################################
# Prepares and runs update based on hostapp-update
# Includes pre-update fixes and balena migration
# Globals:
# DOCKER_CMD
# DOCKERD
# LEGACY_UPDATE
# SLUG
# HOST_OS_VERSION
# target_version
# minimum_balena_target_version
# Arguments:
# update_package: the docker image to use for the update
# Returns:
# None
#######################################
function hostapp_based_update {
local update_package=$1
local storage_driver
local inactive="/mnt/sysroot/inactive"
local balena_migration=no
local inactive_used
local hostapp_image_count
storage_driver=overlay2
if [ -f /boot/storage-driver ]; then
storage_driver=$(cat /boot/storage-driver)
fi
local active_part_dev
local inactive_part_dev
# Resolve the active and inactive partition devices and canonicalize links
active_part_dev=$(df -P /mnt/sysroot/active | tail -1 | awk '{print $1}' | xargs readlink -f)
inactive_part_dev=$(df -P /mnt/sysroot/inactive | tail -1 | awk '{print $1}' | xargs readlink -f)
# Check that the inactive partition is not the same as active.
# This avoids any issues with partitions being mislabled leading to a bricked device.
if [[ "${active_part_dev}" = "${inactive_part_dev}" ]]; then
log ERROR "Active and inactive partitions are the same, bailing out..."
fi
# remove REC files on boot partition
remove_rec_files
case ${SLUG} in
raspberry*)
log "Running pre-update fixes for ${SLUG}"
pre_update_pi_bootfiles_removal
if ! version_gt "${HOST_OS_VERSION}" "2.7.6" ; then
pre_update_fix_bootfiles_hook
fi
;;
jetson-tx2)
log "Running pre-update fixes for ${SLUG}"
if version_gt "${HOST_OS_VERSION}" "2.31.1" && version_gt "2.84.7" "${target_version}" ; then
export JETSON_FIX=1
pre_update_jetson_fix
fi
;;
*)
log "No device-specific pre-update fix for ${SLUG}"
esac
if [ "${DOCKER_CMD}" = "docker" ] &&
version_gt "${target_version}" "${minimum_balena_target_version}" ; then
balena_migration="yes"
fi
if ! [ -S "/var/run/${DOCKER_CMD}-host.sock" ]; then
## Happens on devices booting after a regular HUP update onto a hostapps enabled balenaOS
log "Do not have ${DOCKER_CMD}-host running; legacy mode"
LEGACY_UPDATE=yes
log "Clean inactive partition"
rm -rf "${inactive:?}/"*
if [ "$balena_migration" = "no" ]; then
log "Starting ${DOCKER_CMD}-host with ${storage_driver} storage driver"
${DOCKERD} --log-driver=journald --storage-driver="${storage_driver}" --data-root="${inactive}/${DOCKER_CMD}" --host="unix:///var/run/${DOCKER_CMD}-host.sock" --pidfile="/var/run/${DOCKER_CMD}-host.pid" --exec-root="/var/run/${DOCKER_CMD}-host" --bip=10.114.101.1/24 --fixed-cidr=10.114.101.128/25 --iptables=false &
local timeout_iterations=0
until DOCKER_HOST="unix:///var/run/${DOCKER_CMD}-host.sock" ${DOCKER_CMD} ps &> /dev/null; do sleep 0.2; if [ $((timeout_iterations++)) -ge 1500 ]; then log ERROR "${DOCKER_CMD}-host did not come up before check timed out..."; fi; done
fi
else
if [ -f "$inactive/resinos.fingerprint" ]; then
# Happens on a device, which has HUP'd from a non-hostapp balenaOS to
# a hostapp version. The previous "active", partition now inactive,
# and still has leftover data
log "Have ${DOCKER_CMD}-host running, with dirty inactive partition"
systemctl stop "${DOCKER_CMD}-host"
log "Clean inactive partition"
rm -rf "${inactive:?}/"*
systemctl start "${DOCKER_CMD}-host"
local timeout_iterations=0
until DOCKER_HOST="unix:///var/run/${DOCKER_CMD}-host.sock" ${DOCKER_CMD} ps &> /dev/null; do sleep 0.2; if [ $((timeout_iterations++)) -ge 1500 ]; then log ERROR "${DOCKER_CMD}-host did not come up before check timed out..."; fi; done
fi
if [ "${DOCKER_CMD}" = "balena" ] &&
[ -d "$inactive/docker" ]; then
log "Removing leftover docker folder on a balena device"
rm -rf "$inactive/docker"
fi
# Check leftover data on the Inactive partition, and clean up when found
inactive_used=$(df "${inactive}" | grep "${inactive}" | awk '{ print $3}')
# The empty/default storage space use is about 2200kb, so if more than that is in use, trigger cleanup
if [ "$inactive_used" -gt "5000" ]; then
hostapp_image_count=$(DOCKER_HOST="unix:///var/run/${DOCKER_CMD}-host.sock" ${DOCKER_CMD} images -q | wc -l)
if [ "$hostapp_image_count" -eq "0" ]; then
# There are no hostapp images, but space is still taken up
local target_folder="${inactive}/${DOCKER_CMD}/"
log "Found potential leftover data, cleaning ${target_folder}"
systemctl stop "${DOCKER_CMD}-host"
find "$target_folder" -mindepth 1 -maxdepth 1 -exec rm -r "{}" \; || true
log "Inactive partition usage after cleanup: $(df -h "${inactive}" | grep "${inactive}" | awk '{ print $3}')"
systemctl start "${DOCKER_CMD}-host"
local timeout_iterations=0
until DOCKER_HOST="unix:///var/run/${DOCKER_CMD}-host.sock" ${DOCKER_CMD} ps &> /dev/null; do sleep 0.2; if [ $((timeout_iterations++)) -ge 1500 ]; then log ERROR "${DOCKER_CMD}-host did not come up before check timed out..."; fi; done
fi
fi
fi
if [ "$balena_migration" = "yes" ]; then
# Migrating to balena and hostapp-update hooks run inside the target container
log "Balena migration"
systemctl stop docker-host || true
if [ -d "${inactive}/docker" ] &&
[ ! -L "${inactive}/docker" ] ; then
log "Need to move docker folder on the inactive partition"
rm -rf "${inactive}/balena" || true
mv "${inactive}/"{docker,balena} && ln -s "${inactive}/"{balena,docker}
fi
in_container_hostapp_update "${update_package}" "${inactive}"
if [ "${LEGACY_UPDATE}" != "yes" ]; then
systemctl start docker-host
fi
else
if [ "$STOP_ALL" = "yes" ]; then
stop_services
remove_containers
fi
log "Calling hostapp-update for ${update_package}"
hostapp-update -i "${update_package}" && post_update_fixes
fi
}
#######################################
# Upgrade from a non-hostapp (<2.7.0) to a hostapp-enabled balenaOS version
# Handles both pre-balena and balena updates
# Globals:
# SLUG
# minimum_balena_target_version
# target_version
# Arguments:
# update_package: the docker image to use for the update
# Returns:
# None
#######################################
function non_hostapp_to_hostapp_update {
local update_package=$1
local tmp_inactive
# Mount spare root partition
find_partitions
umount "${update_part}" || true
mkfs.ext4 -F -E lazy_itable_init=0,lazy_journal_init=0 -i 8192 -L "${update_label}" "${update_part}"
tmp_inactive=$(mktemp -d "/tmp/hupinactive.XXXXXXXX")
log "Mounting inactive partition ${update_part} to ${tmp_inactive}..."
mount "${update_part}" "${tmp_inactive}" || log ERROR "Cannot mount inactive partition..."
# remove REC files on boot partition
remove_rec_files
case "${SLUG}" in
raspberry*)
log "Running pre-update fixes for ${SLUG}"
pre_update_pi_bootfiles_removal
;;
*)
log "No device-specific pre-update fix for ${SLUG}"
esac
in_container_hostapp_update "${update_package}" "${tmp_inactive}"
}
function find_partitions {
# Find which partition is / and which we should write the update to
# This function is only used in pre-hostapp-update-enabled 2.x devices
root_part=$(findmnt -n --raw --evaluate --output=source /)
log "Found root at ${root_part}..."
case ${root_part} in
# on 2.x the following device types have these kinds of results for $root_part, examples
# raspberrypi: /dev/mmcblk0p2
# beaglebone: /dev/disk/by-partuuid/93956da0-02
# edison: /dev/disk/by-partuuid/012b3303-34ac-284d-99b4-34e03a2335f4
# NUC: /dev/disk/by-label/resin-rootA and underlying /dev/sda2
# up-board: /dev/disk/by-label/resin-rootA and underlying /dev/mmcblk0p2
/dev/disk/by-partuuid/*)
# reread the physical device that that part refers to
root_part=$(readlink -f "${root_part}")
case ${root_part} in
*p2)
root_dev=${root_part%p2}
update_part=${root_dev}p3
update_part_no=3
update_label=resin-rootB
;;
*p3)
root_dev=${root_part%p3}
update_part=${root_dev}p2
update_part_no=2
update_label=resin-rootA
;;
*p8)
root_dev=${root_part%p8}
update_part=${root_dev}p9
update_part_no=9
update_label=resin-rootB
;;
*p9)
root_dev=${root_part%p9}
update_part=${root_dev}p8
update_part_no=8
update_label=resin-rootA
;;
*)
log ERROR "Couldn't get the root partition from the part-uuid..."
esac
;;
/dev/disk/by-label/resin-rootA)
old_label=resin-rootA
update_label=resin-rootB
root_part_dev=$(readlink -f /dev/disk/by-label/${old_label})
update_part=${root_part_dev%2}3
;;
/dev/disk/by-label/resin-rootB)
old_label=resin-rootB
update_label=resin-rootA
root_part_dev=$(readlink -f /dev/disk/by-label/${old_label})
update_part=${root_part_dev%3}2
;;
*2)
root_dev=${root_part%2}
update_part=${root_dev}3
update_part_no=3
update_label=resin-rootB
;;
*3)
root_dev=${root_part%3}
update_part=${root_dev}2
update_part_no=2
update_label=resin-rootA
;;
*)
log ERROR "Unknown root partition ${root_part}."
esac
if [ ! -b "${update_part}" ]; then
log ERROR "Update partition detected as ${update_part} but it's not a block device."
fi
log "Update partition: ${update_part}"
}
#######################################
# Query public apps for a matching image
# Globals:
# APIKEY
# API_ENDPOINT
# SLUG
# VARIANT (deprecated)
# Arguments:
# version: the OS version to look for
# Returns:
# Registry URL for desired image
#######################################
function get_image_location() {
local variant_tag
# we need to strip the target_version's variant tag to query the API properly
local version=${1/.dev/}
version=${version/.prod/}
# TODO: Get the target variant from the raw version the user provided
variant_tag=$(echo "${VARIANT:-production}" | tr "[:upper:]" "[:lower:]")
image=$(CURL_CA_BUNDLE="${TMPCRT}" ${CURL} \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${APIKEY}" \
"${API_ENDPOINT}/v6/release?\$select=id&\$expand=contains__image/image&\$filter=(belongs_to__application/any(a:a/is_for__device_type/any(dt:dt/slug%20eq%20'${SLUG}')%20and%20is_host%20eq%20true))%20and%20is_invalidated%20eq%20false%20and%20raw_version%20eq%20'${version}'" \
| jq -r "[.d[] | .contains__image[0].image[0] | [.is_stored_at__image_location, .content_hash] | \"\(.[0])@\(.[1])\"]")
if echo "${image}" | jq -e '. | length == 1' > /dev/null; then
echo "${image}" | jq -r '.[0]'
else
# We still need to try finding the hostApp release by filtering using the deprecated release_tags,
# since the versioning format of balenaOS [2019.10.0.dev, 2022.01.0] was non-semver compliant
# and they were not migrated to the release semver fields.
image=$(CURL_CA_BUNDLE="${TMPCRT}" ${CURL} \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${APIKEY}" \
"${API_ENDPOINT}/v6/release?\$select=id&\$expand=contains__image/image&\$filter=(belongs_to__application/any(a:a/is_for__device_type/any(dt:dt/slug%20eq%20'${SLUG}')%20and%20is_host%20eq%20true))%20and%20is_final%20eq%20true%20and%20is_invalidated%20eq%20false%20and%20(release_tag/any(rt:(rt/tag_key%20eq%20'version')%20and%20(rt/value%20eq%20'${version}')))%20and%20((release_tag/any(rt:(rt/tag_key%20eq%20'variant')%20and%20(rt/value%20eq%20'${variant_tag}')))%20or%20not(release_tag/any(rt:rt/tag_key%20eq%20'variant')))" \
| jq -r "[.d[] | .contains__image[0].image[0] | [.is_stored_at__image_location, .content_hash] | \"\(.[0])@\(.[1])\"]")
if echo "${image}" | jq -e '. | length == 1' > /dev/null; then
echo "${image}" | jq -r '.[0]'
else
# we should only get one result, something is wrong
echo
fi
fi
}
#######################################
# Get a delta token
# Globals:
# APIKEY
# API_ENDPOINT
# REGISTRY_ENDPOINT
# UUID
# Arguments:
# src: the source OS version location {registry}/{repo}:{hash}
# dst: the target OS version location {registry}/{repo}:{hash}
# Returns:
# JWT scoped to access desired delta image
#######################################
function get_delta_token() {
src=$(echo "${1}" | awk -F@ '{print $1}' | sed -e 's/.*\/v2/v2/g')
dst=$(echo "${2}" | awk -F@ '{print $1}' | sed -e 's/.*\/v2/v2/g')
CURL_CA_BUNDLE="${TMPCRT}" ${CURL} \
-u "d_${UUID}:${APIKEY}" \
-H "Content-Type: application/json" \
"${API_ENDPOINT}/auth/v1/token?service=${REGISTRY_ENDPOINT}&scope=repository:${dst}:pull&scope=repository:${src}:pull" \
| jq -r '.token'
}
#######################################
# Find a delta in the registry between two hostapp versions using the API
# Globals:
# APIKEY