-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathdrive-backup.sh
More file actions
executable file
·1821 lines (1625 loc) · 74.5 KB
/
Copy pathdrive-backup.sh
File metadata and controls
executable file
·1821 lines (1625 loc) · 74.5 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
# Write efficient Emoncms backup to an attached drive: USB disk, or a NAS share
#
# Unlike emoncms-export.sh, which rebuilds and recompresses a complete tar archive
# on every run, this script maintains a directory *mirror* on the destination drive
# and only writes the bytes that have actually changed.
#
# It does this by exploiting the fact that the PHPFina and PHPTimeSeries feed
# engines are append only fixed record size stores: PHPFina .dat files are a
# sequence of 4 byte values, PHPTimeSeries feed_<id>.MYD files are a sequence of
# 9 byte records. Day to day the only new data is at the end of each file, so
# rsync --append-verify sends and writes just that tail.
#
# Two modes:
#
# sync (default) Append new feed data only. Minimal reads and writes.
# verify Full checksum comparison of every file, rewriting only
# the blocks that differ. Slower (reads everything on both
# sides) but detects damage that the sync mode cannot see.
#
# Run 'verify' periodically (weekly or monthly). It is needed because
# --append-verify skips any file whose size on the destination already matches
# the source, so a same size in place rewrite (PHPFina back filling padding, or
# the postprocess module rewriting history) is invisible to the sync mode.
#
# Usage:
# ./drive-backup.sh --init Prepare a destination drive (one time)
# ./drive-backup.sh Daily append mode backup
# ./drive-backup.sh --verify Full checksum verify and repair
# ./drive-backup.sh --dry-run Report what would be written, write nothing
# ./drive-backup.sh --if-mounted Skip quietly if the drive is not plugged in,
# rather than reporting it as a failure. Used by
# the systemd timer.
# ./drive-backup.sh --discover List mounted drives that could hold a backup
# ./drive-backup.sh --set-path <mountpoint>
# Select a destination from that list and
# prepare it. Used by the Emoncms interface.
# ./drive-backup.sh --discover-devices
# List attached drives that are NOT mounted yet
# ./drive-backup.sh --mount <id> Mount one of those drives, record it in
# /etc/fstab so it comes back after a reboot,
# and use it as the backup destination
# ./drive-backup.sh --format-mount <id> --confirm-erase
# As --mount, but first put a btrfs filesystem
# on the drive. ERASES THE WHOLE DISK the drive
# is on, every partition included.
# ./drive-backup.sh --enable-schedule
# ./drive-backup.sh --disable-schedule
# Turn the daily backup and weekly verify
# systemd timers on or off
#
# Everything except --discover, --discover-devices and --disable-schedule needs
# drive_backup_enabled="yes" in config.cfg. install.sh sets it on a Raspberry
# Pi; on any other system it is off until set by hand, so that a root process
# that mounts and formats drives cannot be reached where nobody wants it.
# Set the shell to trigger errors when commands within a pipe have a non-zero return code
set -o pipefail
# The errors variable is set when error_handler() is called, the variable is used by the finish() function for success or failure messages
errors=false
# This error handler function display information of what happened and where, but does NOT stop the script execution
error_handler() {
echo "Error: RC=$1 occurred on line $2"
errors=true
}
# Set trap for ERR to pass the return code and line number to error_handler()
trap 'error_handler $? $LINENO' ERR
start_seconds=$SECONDS
# The arguments exactly as given. The parse loop below consumes them with shift,
# so they are kept here for the re-exec under sudo further down.
original_args=("$@")
# State gathered as the script runs, reported in the summary and status.json
bytes_written=0
files_repaired=0
files_realigned=0
orphans=0
dest_ready=false
skipped=false
mysql_defaults_file=""
# Set by mount_device() and format_device() when they succeed
mounted_at=""
formatted_device=""
formatted_stale_specs=""
# Exit handler used to ensure the exit message AJAX expects is found, whilst summarising if errors were found
# This also picks up the natural exit when reaching end of script
function finish() {
local rc=$?
# Never leave the temporary mysql credentials file behind
if [ -n "${mysql_defaults_file}" ] && [ -f "${mysql_defaults_file}" ]; then
rm -f "${mysql_defaults_file}"
fi
# The drive simply not being plugged in is a normal state, not a failure
if [[ "${skipped}" == "true" ]]; then
echo "=== Emoncms drive backup skipped ==="
# The strings output are identified in the interface to stop ongoing AJAX calls, please ammend in interface if changed here
exit 0
fi
if [[ "${dest_ready}" == "true" ]]; then
write_status_json
fi
if [[ "${errors}" == "false" && ${rc} == 0 ]]; then
echo "=== Emoncms drive backup complete! ==="
# The strings output are identified in the interface to stop ongoing AJAX calls, please ammend in interface if changed here
else
echo "=== Emoncms drive backup completed with ERRORS! ==="
# The strings output are identified in the interface to stop ongoing AJAX calls, please ammend in interface if changed here
# Exit non-zero so that systemd reports the run as failed rather than
# silently succeeding, and so OnFailure= handlers can act on it
if [ ${rc} -eq 0 ]; then
exit 1
fi
fi
}
# Set trap for whenever EXIT is called to call finish()
trap finish EXIT
#-----------------------------------------------------------------------------------------------
# Helper functions
#-----------------------------------------------------------------------------------------------
# Machine readable summary of the last run, read by the Emoncms interface
write_status_json() {
local duration=$(( SECONDS - start_seconds ))
local free_mb=$(df -Pm "${drive_backup_path}" 2>/dev/null | awk 'NR==2{print $4}')
cat > "${drive_backup_path}/status.json" << EOF
{
"last_run": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
"hostname": "$(hostname)",
"mode": "${mode}",
"dry_run": ${dry_run},
"duration_seconds": ${duration},
"bytes_written": ${bytes_written},
"files_repaired": ${files_repaired},
"files_realigned": ${files_realigned},
"orphans": ${orphans},
"destination_free_mb": ${free_mb:-0},
"errors": ${errors}
}
EOF
}
# Walk up from a path until an existing directory is found, used so the
# filesystem safety checks work even when the destination does not exist yet
existing_ancestor() {
local p="$1"
while [ ! -e "${p}" ] && [ "${p}" != "/" ]; do
p=$(dirname "${p}")
done
echo "${p}"
}
# rsync --stats reports "Literal data: N bytes", the count of new bytes actually
# written to the destination. Sum it so we can report the real write volume.
# Note that rsync must not be given --human-readable, which would round this to
# a value that cannot be summed.
add_literal_data() {
local literal
literal=$(echo "$1" | grep -E "^Literal data:" | awk '{print $3}' | tr -d ',')
if [[ "${literal}" =~ ^[0-9]+$ ]]; then
bytes_written=$(( bytes_written + literal ))
fi
}
human_bytes() {
numfmt --to=iec-i --suffix=B "$1" 2>/dev/null || echo "$1 bytes"
}
# Filesystems that cannot store unix ownership and permissions. Asking rsync to
# preserve them there produces an error per file and a failed run.
rsync_ownership_opts() {
case "${drive_backup_preserve_permissions}" in
yes) return 0 ;;
no) echo "--no-perms --no-owner --no-group"; return 0 ;;
esac
# auto
case "${dest_fstype}" in
cifs|smb3|smbfs|vfat|exfat|msdos|ntfs|ntfs3|fuseblk)
echo "--no-perms --no-owner --no-group"
;;
esac
}
# Enumerate mounted filesystems that could plausibly hold a backup, one per line as
# mountpoint<TAB>source<TAB>fstype<TAB>kind<TAB>free_mb<TAB>initialised<TAB>compressed<TAB>snapshots
#
# compressed and snapshots report what the destination filesystem can add on top
# of the incremental sync. Both come from copy on write filesystems rather than
# from anything this script does: compression there happens per extent below the
# append, and a CoW snapshot costs only the delta. Neither can be done to the
# mirror itself, because compressing a feed file or hard linking it would mean
# rewriting it whole on every run, which is the one thing this design avoids.
#
# This is the authority on which destinations may be selected. The Emoncms
# interface offers the user a choice from this list and --set-path accepts
# nothing that is not in it, so a compromised web interface cannot point a root
# process at a directory of its own choosing.
discover_destinations() {
local target source fstype options kind free marker dev base removable
local seen=""
# Process substitution rather than a pipe, so the loop runs in this shell and
# can remember which mountpoints it has already reported
while read -r target source fstype options; do
case "${fstype}" in
ext2|ext3|ext4|xfs|btrfs|f2fs|vfat|exfat|msdos|ntfs|ntfs3|fuseblk|nfs|nfs4|cifs|smb3|smbfs) ;;
*) continue ;;
esac
# Never offer the system's own filesystems as a backup destination
case "${target}" in
/|/boot|/boot/*|/usr|/usr/*|/var|/var/*|/etc|/etc/*|/home|/root|/root/*) continue ;;
/run|/run/*|/snap/*|/proc/*|/sys/*|/dev|/dev/*|/tmp|/tmp/*) continue ;;
esac
# systemd gives services private /tmp and inaccessible directory mounts,
# which show up here as duplicates of real mountpoints
case "${source}" in
*systemd-private*|*systemd/inaccessible*) continue ;;
esac
# The same mountpoint can appear more than once, from a bind mount say.
# Report it once: a repeated entry would be a duplicate row, and a
# duplicate key, in the interface.
case " ${seen} " in *" ${target} "*) continue ;; esac
seen="${seen} ${target}"
kind="fixed"
case "${source}" in
//*|*:/*) kind="network" ;;
/dev/*)
dev=$(basename "${source}")
base=$(lsblk -rno PKNAME "${source}" 2>/dev/null | head -1)
removable=$(cat "/sys/block/${base:-$dev}/removable" 2>/dev/null)
[ "${removable}" == "1" ] && kind="removable"
;;
esac
free=$(df -Pm "${target}" 2>/dev/null | awk 'NR==2{print $4}')
marker="no"
[ -f "${target}/emoncms/.emoncms-backup-target" ] && marker="yes"
# Copy on write filesystems can compress transparently and snapshot cheaply
local compressed="no" snapshots="no"
case "${fstype}" in
btrfs)
snapshots="yes"
case "${options}" in *compress=*|*compress-force=*) compressed="yes" ;; esac
;;
esac
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
"${target}" "${source}" "${fstype}" "${kind}" "${free:-0}" "${marker}" \
"${compressed}" "${snapshots}"
done < <(findmnt -rno TARGET,SOURCE,FSTYPE,OPTIONS)
}
#-----------------------------------------------------------------------------------------------
# Attached drives that are not mounted yet
#
# discover_destinations() above only sees filesystems that are already mounted,
# which leaves the common case unsolved: a USB drive has just been plugged in and
# nothing has mounted it. The functions below find those drives, and mount one
# and record it in /etc/fstab so it comes back after a reboot.
#
# The same rule applies as to --set-path: the interface may only name a drive
# that this script's own discovery reported, and the mount is re-checked against
# that list here before anything privileged happens.
#-----------------------------------------------------------------------------------------------
# Run a command as root. The systemd timers already run this script as root; from
# the Emoncms interface it runs as the service-runner user, which has sudo.
# -n so that a system without the sudo rule fails immediately with a message
# rather than blocking forever on a password prompt no one can answer.
as_root() {
if [ "${EUID}" -eq 0 ]; then
"$@"
else
sudo -n "$@"
fi
}
# A single lsblk field for one device. Asked for one at a time on purpose: with
# several fields a device with an empty value in the middle, no filesystem label
# say, shifts every later column along and the wrong value is read.
lsblk_field() {
lsblk -dno "$2" "$1" 2>/dev/null | head -1 | sed -e 's/[[:space:]]*$//' -e 's/^[[:space:]]*//'
}
# Values reported here end up in tab separated output and then in a web page, so
# strip anything that would break the format. Labels and models come from the
# drive itself and are not to be trusted to be well behaved.
tsv_safe() {
printf '%s' "$1" | tr -d '\000-\037' | cut -c1-64
}
# The disks the running system is using. Anything on one of these is never
# offered as a backup drive and never formatted, so a mistake here cannot reach
# the SD card the system boots from.
#
# Every mounted filesystem and every active swap device counts. Each is walked
# down to the disk it ultimately sits on, through partitions, LVM and device
# mapper alike, because the format action erases whole disks.
system_disks() {
local src disk
{
findmnt -rno SOURCE | sed 's/\[.*\]//'
awk 'NR>1 && $1 ~ /^\/dev\// {print $1}' /proc/swaps 2>/dev/null
} | sort -u | while read -r src; do
case "${src}" in /dev/*) ;; *) continue ;; esac
# /dev/root and the like are not real device nodes, find the device by
# its major:minor number instead
if [ ! -b "${src}" ]; then
src="/dev/block/$(findmnt -rno MAJ:MIN --source "${src}" 2>/dev/null | head -1)"
[ -b "${src}" ] || continue
fi
# The inverse tree ends at the disk itself
disk=$(lsblk -srno NAME "${src}" 2>/dev/null | tail -1)
[ -z "${disk}" ] && disk=$(basename "$(readlink -f "${src}")")
echo "${disk}"
done | sort -u
}
# The disk a partition sits on, or the device itself if it is a whole disk
disk_of() {
local dev="$1" parent
parent=$(lsblk_field "${dev}" PKNAME)
if [ -n "${parent}" ]; then
echo "/dev/${parent}"
else
readlink -f "${dev}"
fi
}
# Everything found on a disk, for the person about to erase it: one entry per
# partition with its filesystem, size and label, or the disk itself if it has
# no partition table. Reported alongside each drive in --discover-devices so
# the interface can say what the format action would destroy.
disk_contents() {
local disk="$1" node fstype label size_b out="" item
local nodes
nodes=$(lsblk -pnro NAME "${disk}" 2>/dev/null)
# With partitions, describe those and not the disk that holds them
if [ "$(printf '%s\n' "${nodes}" | wc -l)" -gt 1 ]; then
nodes=$(printf '%s\n' "${nodes}" | sed '1d')
fi
while read -r node; do
[ -n "${node}" ] || continue
fstype=$(lsblk_field "${node}" FSTYPE)
label=$(tsv_safe "$(lsblk_field "${node}" LABEL)" | tr -d ';')
size_b=$(lsblk -bdno SIZE "${node}" 2>/dev/null | head -1)
item="$(basename "${node}") ($(human_bytes "${size_b:-0}"), ${fstype:-no filesystem}"
[ -n "${label}" ] && item="${item}, ${label}"
item="${item})"
out="${out:+${out}; }${item}"
done <<< "${nodes}"
printf '%s' "${out}"
}
# A name for a drive that survives unplugging and replugging it. Kernel names
# like /dev/sda are assigned in the order drives appear, so a drive scanned as
# /dev/sda can be a different drive by the time the user confirms. /dev/disk/by-id
# is derived from the hardware itself, which matters most for the format action.
stable_id() {
local dev="$1" real link uuid
real=$(readlink -f "${dev}")
# Prefer the descriptive id (usb-Samsung_Flash_Drive_...) over the bare wwn-
local pass
for pass in descriptive wwn; do
for link in /dev/disk/by-id/*; do
[ -e "${link}" ] || continue
case "${link}" in
*/wwn-*|*/nvme-eui.*) [ "${pass}" == "wwn" ] || continue ;;
*) [ "${pass}" == "descriptive" ] || continue ;;
esac
if [ "$(readlink -f "${link}")" == "${real}" ]; then
echo "${link}"
return 0
fi
done
done
uuid=$(lsblk_field "${dev}" UUID)
if [ -n "${uuid}" ] && [ -e "/dev/disk/by-uuid/${uuid}" ]; then
echo "/dev/disk/by-uuid/${uuid}"
return 0
fi
echo "${real}"
}
# Is this device, or any partition on it, mounted right now
device_is_mounted() {
local dev="$1" mp
while read -r mp; do
[ -n "${mp}" ] && return 0
done < <(lsblk -nro MOUNTPOINT "${dev}" 2>/dev/null)
return 1
}
# Enumerate attached drives that are not mounted, one per line as
# id<TAB>device<TAB>size_mb<TAB>fstype<TAB>label<TAB>model<TAB>kind<TAB>state
# <TAB>disk<TAB>disk_size_mb<TAB>disk_contents
#
# state is one of:
# available has a filesystem that can be mounted and used as it is
# infstab already has an /etc/fstab entry, so it is configured but not
# mounted: the drive was unplugged, or the entry is wrong
# nofilesystem nothing on it to mount, it has to be formatted first
# nomedia a card reader with no card in it. Listed so the interface can
# say so; it cannot be mounted or formatted
#
# The last three columns describe the whole disk the device sits on, which is
# what --format-mount erases: a used SD card carries a boot partition and a
# root partition, and formatting one of them would leave a mixed card. The
# interface shows disk_contents to whoever is about to confirm the erase.
#
# This is the authority on which drives may be mounted or formatted, in the same
# way discover_destinations() is the authority on which may be selected.
discover_devices() {
local sys_disks dev kname type fstype id spec label model size_b size_mb
local parent ro kind state children disk disk_size_b disk_size_mb
sys_disks=" $(system_disks | tr '\n' ' ') "
while read -r dev; do
[ -n "${dev}" ] || continue
[ -b "${dev}" ] || continue
type=$(lsblk_field "${dev}" TYPE)
case "${type}" in disk|part) ;; *) continue ;; esac
# A read only device cannot hold a backup
[ "$(lsblk_field "${dev}" RO)" == "1" ] && continue
kname=$(basename "$(readlink -f "${dev}")")
parent=$(lsblk_field "${dev}" PKNAME)
[ -z "${parent}" ] && parent="${kname}"
case " ${sys_disks} " in *" ${parent} "*) continue ;; esac
# A disk that has been partitioned is offered as its partitions, not as
# the whole disk, which could not be mounted anyway
if [ "${type}" == "disk" ]; then
children=$(lsblk -nro NAME "${dev}" 2>/dev/null | wc -l)
[ "${children}" -gt 1 ] && continue
fi
# Anything already mounted belongs in the discover_destinations() list
device_is_mounted "${dev}" && continue
fstype=$(lsblk_field "${dev}" FSTYPE)
case "${fstype}" in
ext2|ext3|ext4|xfs|btrfs|f2fs|vfat|exfat|msdos|ntfs|ntfs3) state="available" ;;
"") state="nofilesystem" ;;
# swap, LVM and RAID members, encrypted volumes and optical media are
# not something this module should be reformatting or mounting
*) continue ;;
esac
size_b=$(lsblk -bdno SIZE "${dev}" 2>/dev/null | head -1)
size_mb=$(( ${size_b:-0} / 1048576 ))
if [ "${size_mb}" -eq 0 ] && [ "${type}" == "disk" ] && [ "$(lsblk_field "${dev}" RM)" == "1" ]; then
# A card reader with no card in it: a removable disk of size zero.
# Reported so the interface can say the reader is there but empty,
# rather than leaving the user wondering why nothing was found.
state="nomedia"
elif [ "${size_mb}" -lt 512 ]; then
# Below this it is a boot or recovery partition rather than a backup
# drive, and offering it would only be a way to pick the wrong thing
continue
fi
id=$(stable_id "${dev}")
if [ "${state}" == "available" ]; then
spec=$(fstab_spec_for "${dev}" "${id}" || true)
if [ -n "${spec}" ] && fstab_has_spec "${spec}"; then
state="infstab"
fi
fi
kind="fixed"
[ "$(lsblk_field "${dev}" RM)" == "1" ] && kind="removable"
[ "$(lsblk_field "${dev}" HOTPLUG)" == "1" ] && kind="removable"
label=$(lsblk_field "${dev}" LABEL)
model=$(lsblk_field "${dev}" MODEL)
# A partition carries no model of its own, it belongs to the disk
[ -z "${model}" ] && [ -n "${parent}" ] && model=$(lsblk_field "/dev/${parent}" MODEL)
disk="/dev/${parent}"
disk_size_b=$(lsblk -bdno SIZE "${disk}" 2>/dev/null | head -1)
disk_size_mb=$(( ${disk_size_b:-0} / 1048576 ))
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
"${id}" "${dev}" "${size_mb}" "${fstype}" \
"$(tsv_safe "${label}")" "$(tsv_safe "${model}")" "${kind}" "${state}" \
"${disk}" "${disk_size_mb}" "$(disk_contents "${disk}" | tr -d '\000-\037' | cut -c1-512)"
done < <(lsblk -pnro NAME 2>/dev/null)
# Finding no drives is an answer, not a failure
return 0
}
# How this filesystem should be named in the first column of /etc/fstab.
#
# A filesystem UUID is the best answer: it follows the drive to another USB port
# and is unaffected by other disks being added or repartitioned. Not every
# filesystem has one. FAT has only a short volume serial and some drives report
# none at all, so fall back to the partition's own UUID from the partition table,
# and finally to the /dev/disk/by-id path the drive was chosen by, which is
# derived from the hardware and is stable in the same way.
#
# Only reads udev and the blkid cache, so this works as the web server user and
# gives the same answer as the privileged path below.
fstab_spec_for() {
local dev="$1" id="$2" uuid partuuid
uuid=$(lsblk_field "${dev}" UUID)
[ -z "${uuid}" ] && uuid=$(blkid -s UUID -o value "${dev}" 2>/dev/null || true)
if [ -n "${uuid}" ]; then
echo "UUID=${uuid}"
return 0
fi
partuuid=$(lsblk_field "${dev}" PARTUUID)
[ -z "${partuuid}" ] && partuuid=$(blkid -s PARTUUID -o value "${dev}" 2>/dev/null || true)
if [ -n "${partuuid}" ]; then
echo "PARTUUID=${partuuid}"
return 0
fi
case "${id}" in
/dev/disk/by-id/*) echo "${id}"; return 0 ;;
esac
return 1
}
# Is this filesystem already named in /etc/fstab
fstab_has_spec() {
local spec="$1"
[ -n "${spec}" ] || return 1
[ -f /etc/fstab ] || return 1
awk -v s="${spec}" '
/^[[:space:]]*#/ {next}
NF >= 2 && tolower($1) == tolower(s) {found=1}
END {exit !found}' /etc/fstab
}
# The mountpoint /etc/fstab already gives this filesystem, if any
fstab_mountpoint_for_spec() {
local spec="$1"
[ -n "${spec}" ] || return 0
[ -f /etc/fstab ] || return 0
awk -v s="${spec}" '
/^[[:space:]]*#/ {next}
NF >= 2 && tolower($1) == tolower(s) {print $2; exit}' /etc/fstab
}
# Mount options for a backup drive.
#
# noatime reading every file on each run would otherwise write a metadata
# update per file, which on a flash drive is wear for nothing
# nofail a drive that is not plugged in must not stop the system booting
# x-systemd.device-timeout and must not delay the boot by 90s either
fstab_options_for() {
local fstype="$1"
local common="noatime,nofail,x-systemd.device-timeout=10"
case "${fstype}" in
btrfs)
# Compresses as it writes, which on feed data is worth about 80%
echo "defaults,${common},compress=zstd"
;;
vfat|msdos|exfat|ntfs|ntfs3)
# These cannot store unix ownership, so it is fixed at mount time.
# drive-restore.sh sets ownership correctly on the way back in.
echo "defaults,${common},uid=root,gid=root,umask=0022"
;;
*)
echo "defaults,${common}"
;;
esac
}
# ext filesystems are worth a boot time fsck pass, the others either have no
# fsck or should not be checked automatically
fstab_pass_for() {
case "$1" in
ext2|ext3|ext4) echo 2 ;;
*) echo 0 ;;
esac
}
# A free mountpoint under /media. One fixed name, numbered if it is taken, so
# that what ends up in fstab is predictable and matches the documentation.
choose_mountpoint() {
local base="/media/emoncms-backup" candidate n
for n in "" -2 -3 -4 -5 -6 -7 -8 -9; do
candidate="${base}${n}"
# Already used by another fstab entry
if [ -f /etc/fstab ] && awk -v p="${candidate}" '
/^[[:space:]]*#/ {next} $2==p {found=1} END{exit !found}' /etc/fstab; then
continue
fi
# Something is mounted there
mountpoint -q "${candidate}" 2>/dev/null && continue
# Exists and has something in it, which mounting over would hide
if [ -d "${candidate}" ] && [ -n "$(ls -A "${candidate}" 2>/dev/null)" ]; then
continue
fi
echo "${candidate}"
return 0
done
return 1
}
# Remove /etc/fstab entries whose first column is one of the given specs, one
# per line. Used after a format, when the entries that named the old
# filesystems on the disk can no longer match anything. A comment line this
# module wrote above an entry goes with it. Same backup and atomic write as
# adding an entry.
fstab_remove_specs() {
local specs="$1" backup tmp
[ -n "${specs}" ] || return 0
[ -f /etc/fstab ] || return 0
echo "Removing /etc/fstab entries for the filesystems that were on the disk:"
printf '%s\n' "${specs}" | sed '/^$/d; s/^/ /'
backup="/etc/fstab.emoncms-backup.$(date +%Y%m%d%H%M%S).bak"
as_root cp -a /etc/fstab "${backup}" || return 1
echo "Previous /etc/fstab saved as ${backup}"
tmp=$(mktemp) || return 1
awk -v specs="${specs}" '
BEGIN { n = split(specs, a, "\n"); for (i = 1; i <= n; i++) if (a[i] != "") drop[tolower(a[i])] = 1 }
/^# Added by the Emoncms backup module/ { held = $0; have = 1; next }
!/^[[:space:]]*#/ && NF >= 2 && (tolower($1) in drop) { have = 0; next }
{ if (have) { print held; have = 0 } print }
END { if (have) print held }' /etc/fstab > "${tmp}" || { rm -f "${tmp}"; return 1; }
if ! as_root cp "${tmp}" /etc/fstab; then
rm -f "${tmp}"
echo "ERROR: could not write /etc/fstab"
return 1
fi
rm -f "${tmp}"
as_root chmod 644 /etc/fstab
as_root systemctl daemon-reload 2>/dev/null || true
return 0
}
# Put a btrfs filesystem on a drive. Destructive: the WHOLE DISK the device sits
# on is erased, every partition on it included. Reached only from --format-mount
# with --confirm-erase, on a drive discover_devices() reported, which by
# construction is not on any disk the system is using. That is checked again
# here, on the disk itself, immediately before anything is written.
#
# btrfs rather than ext4 because a backup drive is exactly where it pays:
# every block is checksummed so bit rot on an SD card is detected instead of
# restored, and feed data compresses by about 80% with compress=zstd.
#
# Sets formatted_device to the new partition and formatted_stale_specs to the
# /etc/fstab specs that named filesystems that no longer exist.
format_device() {
local dev="$1" disk node part spec stale=""
disk=$(disk_of "${dev}")
if [ -z "${disk}" ] || [ ! -b "${disk}" ]; then
echo "ERROR: cannot find the disk that ${dev} is on"
return 1
fi
# The disk is what gets erased, so it is the disk that has to be clear of
# anything the system is using, whatever discover_devices() said moments ago
case " $(system_disks | tr '\n' ' ') " in
*" $(basename "${disk}") "*)
echo "ERROR: ${disk} holds a filesystem or swap the system is using, refusing to erase it"
return 1
;;
esac
if device_is_mounted "${disk}"; then
echo "ERROR: something on ${disk} is mounted, refusing to erase it"
return 1
fi
if ! command -v parted > /dev/null; then
echo "ERROR: parted is not installed, cannot partition ${disk}"
echo "Install it with: sudo apt-get install -y parted"
return 1
fi
if ! command -v mkfs.btrfs > /dev/null; then
echo "ERROR: mkfs.btrfs is not installed, cannot format ${disk}"
echo "Install it with: sudo apt-get install -y btrfs-progs"
return 1
fi
if ! grep -qw btrfs /proc/filesystems && ! as_root modprobe btrfs 2>/dev/null; then
echo "ERROR: this kernel has no btrfs support, cannot use ${disk}"
return 1
fi
echo "Disk to erase: ${disk} ($(lsblk_field "${disk}" MODEL), $(human_bytes "$(lsblk -bdno SIZE "${disk}" 2>/dev/null | head -1)"))"
echo "Currently holding: $(disk_contents "${disk}")"
# /etc/fstab entries for the filesystems about to be destroyed would never
# match again. Collect them now, while the filesystems still have UUIDs.
while read -r node; do
[ -n "${node}" ] || continue
spec=$(fstab_spec_for "${node}" "$(stable_id "${node}")" || true)
[ -n "${spec}" ] && fstab_has_spec "${spec}" && stale="${stale}${spec}"$'\n'
done < <(lsblk -pnro NAME "${disk}" 2>/dev/null)
# Wipe the filesystem signatures inside each partition before the partition
# table, so that nothing can be recognised at its old offset afterwards
echo "Removing every filesystem signature on ${disk}"
while read -r node; do
[ -n "${node}" ] || continue
[ "${node}" == "${disk}" ] && continue
as_root wipefs -a "${node}" > /dev/null 2>&1 || true
done < <(lsblk -pnro NAME "${disk}" 2>/dev/null | tac)
as_root wipefs -a "${disk}" > /dev/null || return 1
echo "Creating a GPT partition table and a single partition on ${disk}"
as_root parted -s "${disk}" mklabel gpt mkpart primary btrfs 1MiB 100% || return 1
as_root udevadm settle || true
sleep 2
part=$(lsblk -pnro NAME "${disk}" 2>/dev/null | sed -n '2p')
if [ -z "${part}" ] || [ ! -b "${part}" ]; then
echo "ERROR: no partition appeared on ${disk} after partitioning"
return 1
fi
echo "Created ${part}"
echo "Creating a btrfs filesystem on ${part}"
# Single device, so mkfs.btrfs keeps two copies of the metadata by default,
# which is worth having on flash. Data is compressed at mount time instead,
# see fstab_options_for().
as_root mkfs.btrfs -f -L emoncms-backup "${part}" || return 1
as_root udevadm settle || true
formatted_device="${part}"
formatted_stale_specs="${stale}"
return 0
}
# Does the destination actually accept a write?
#
# A drive that is unplugged and plugged back in comes back as a new device and
# leaves the old mount in place. That mount is still listed, and reads can still
# be answered from the kernel's caches, so the marker file check above can pass
# on a destination where every write will fail with an I/O error. Writing a few
# bytes and forcing them out to the device is the only way to know.
probe_destination_writable() {
local probe="${drive_backup_path}/.emoncms-backup-probe"
local content="emoncms-backup-probe-$$"
echo "${content}" > "${probe}" 2>/dev/null || return 1
# Without this the write sits in the page cache and the error surfaces
# later, part way through the backup, rather than here
sync -f "${probe}" 2>/dev/null || { rm -f "${probe}" 2>/dev/null; return 1; }
[ "$(cat "${probe}" 2>/dev/null)" == "${content}" ] || { rm -f "${probe}" 2>/dev/null; return 1; }
rm -f "${probe}" 2>/dev/null || return 1
return 0
}
# Turn the daily backup and weekly verify timers on or off.
#
# install.sh only enables them when drive_backup_path is already set, which on a
# fresh install it is not, so a drive chosen afterwards would be backed up only
# when someone presses the button. The interface can say that backups are not
# scheduled, so it needs to be able to do something about it too.
set_schedule() {
local action="$1"
local units="emoncms-drive-backup.timer emoncms-drive-backup-verify.timer"
local unit missing=false
for unit in ${units}; do
if ! systemctl list-unit-files "${unit}" 2>/dev/null | grep -q "^${unit}"; then
echo "ERROR: ${unit} is not installed"
missing=true
fi
done
if [ "${missing}" == "true" ]; then
echo "Run ${script_location}/install.sh to install the systemd units."
return 1
fi
if [ "${action}" == "enable" ]; then
echo "Enabling ${units}"
# --now so the timer starts counting immediately rather than at the next
# boot, which is what someone pressing this in the interface means
as_root systemctl enable --now ${units} || return 1
echo "Daily backup and weekly verify are now scheduled."
else
echo "Disabling ${units}"
as_root systemctl disable --now ${units} || return 1
echo "Backups will now only run when started by hand."
fi
systemctl list-timers 'emoncms-drive-backup*' --no-pager 2>/dev/null || true
return 0
}
# Mount a drive and record it in /etc/fstab so it returns after a reboot.
# Sets mounted_at on success.
mount_device() {
local id="$1" do_format="$2"
local row dev state fstype uuid spec mountpoint options pass line backup existing
echo "Requested drive: ${id}"
# The caller does not get to name an arbitrary device. It has to be one this
# script's own discovery just reported, which is what makes it safe to reach
# from the web interface.
row=$(discover_devices | awk -F'\t' -v i="${id}" '$1==i {print; exit}')
if [ -z "${row}" ]; then
echo "ERROR: ${id} is not one of the drives available to set up"
echo "Available:"
discover_devices | awk -F'\t' '{printf " %s (%s, %s MB, %s, %s)\n", $1, $2, $3, ($4==""?"no filesystem":$4), $8}'
return 1
fi
dev=$(printf '%s' "${row}" | cut -f2)
fstype=$(printf '%s' "${row}" | cut -f4)
state=$(printf '%s' "${row}" | cut -f8)
echo "Device: ${dev}"
echo "Filesystem: ${fstype:-none}"
echo "State: ${state}"
if [ "${state}" == "nomedia" ]; then
echo "ERROR: ${dev} is a card reader with no card in it"
return 1
fi
if [ "${do_format}" != "true" ]; then
case "${fstype}" in
vfat|msdos)
echo "NOTE: FAT cannot hold a file larger than 4 GB and cannot store unix"
echo " ownership. Feed files are well below 4 GB and drive-restore.sh sets"
echo " ownership on the way back in, so this works, but a drive formatted"
echo " as btrfs is a better long term choice."
;;
esac
fi
if [ "${do_format}" == "true" ]; then
echo ""
echo "--- Formatting the disk that holds ${dev}, everything on it is being erased ---"
formatted_device=""
formatted_stale_specs=""
format_device "${dev}" || return 1
dev="${formatted_device}"
fstype="btrfs"
# The by-id name of the partition just created, not of the device that
# was scanned and confirmed, which may no longer exist
id=$(stable_id "${dev}")
# Entries for the filesystems that were on the disk are now stale. Take
# them out before looking for one to reuse, or a stale entry with the
# wrong filesystem type would be found and used.
fstab_remove_specs "${formatted_stale_specs}" || return 1
elif [ "${state}" == "nofilesystem" ]; then
echo "ERROR: ${dev} has no filesystem, so there is nothing to mount"
echo "Format it first, or use a drive that already has a filesystem."
return 1
fi
# fstab names the filesystem by UUID rather than by /dev/sda1, which is
# assigned in the order drives are found and changes when another is added
spec=$(fstab_spec_for "${dev}" "${id}" || true)
if [ -z "${spec}" ]; then
# A filesystem created moments ago is not in the udev database or the
# blkid cache yet, so probe the device itself
uuid=$(as_root blkid -p -s UUID -o value "${dev}" 2>/dev/null || true)
[ -n "${uuid}" ] && spec="UUID=${uuid}"
fi
if [ -z "${spec}" ]; then
echo "ERROR: ${dev} has no UUID, partition UUID or by-id name to identify it by,"
echo " so no stable /etc/fstab entry can be written for it."
return 1
fi
echo "Identified in /etc/fstab as: ${spec}"
# Already in fstab: use the mountpoint it names rather than adding a second
# entry for the same filesystem, which is how fstab files end up broken
existing=$(fstab_mountpoint_for_spec "${spec}")
if [ -n "${existing}" ]; then
echo "Already in /etc/fstab, mounted at ${existing}"
mountpoint="${existing}"
as_root mkdir -p "${mountpoint}"
else
mountpoint=$(choose_mountpoint)
if [ -z "${mountpoint}" ]; then
echo "ERROR: could not find a free mountpoint under /media"
return 1
fi
options=$(fstab_options_for "${fstype}")
pass=$(fstab_pass_for "${fstype}")
line=$(printf '%s\t%s\t%s\t%s\t0\t%s' "${spec}" "${mountpoint}" "${fstype}" "${options}" "${pass}")
echo "Mountpoint: ${mountpoint}"
echo "Adding to /etc/fstab:"
echo " ${line}"
as_root mkdir -p "${mountpoint}" || return 1
backup="/etc/fstab.emoncms-backup.$(date +%Y%m%d%H%M%S).bak"
as_root cp -a /etc/fstab "${backup}" || return 1
echo "Previous /etc/fstab saved as ${backup}"
# Written through a temporary file and copied into place, so that a
# failure part way through cannot leave the system with a truncated
# fstab and an unbootable configuration
local tmp
tmp=$(mktemp) || return 1
{
cat /etc/fstab
echo ""
echo "# Added by the Emoncms backup module on $(date -u +"%Y-%m-%dT%H:%M:%SZ")"
echo "${line}"
} > "${tmp}"
if ! as_root cp "${tmp}" /etc/fstab; then
rm -f "${tmp}"
echo "ERROR: could not write /etc/fstab"
return 1
fi
rm -f "${tmp}"
as_root chmod 644 /etc/fstab
fi
# systemd generates a .mount unit per fstab entry at daemon-reload, and
# mounts by mountpoint alone only once it has seen the new entry
as_root systemctl daemon-reload 2>/dev/null || true
echo "Mounting ${mountpoint}"
if ! as_root mount "${mountpoint}"; then
echo "ERROR: could not mount ${dev} at ${mountpoint}"
if [ -n "${backup}" ] && [ -f "${backup}" ]; then
echo "Restoring the previous /etc/fstab"
as_root cp "${backup}" /etc/fstab
as_root systemctl daemon-reload 2>/dev/null || true
as_root rmdir "${mountpoint}" 2>/dev/null || true
fi
return 1
fi
if ! mountpoint -q "${mountpoint}"; then
echo "ERROR: ${mountpoint} is still not a mount point after mounting"
return 1
fi
# The backup runs as root from the timer but the interface reads the drive as
# the web user, so the mountpoint itself has to be traversable by both
as_root chmod 755 "${mountpoint}" 2>/dev/null || true
echo "Mounted:"
findmnt -no SOURCE,TARGET,FSTYPE,OPTIONS "${mountpoint}"
echo "It will be mounted again automatically after a reboot."
mounted_at="${mountpoint}"
return 0
}
# rsync --dry-run does not report Literal data, so for a dry run work the append
# volume out directly from the file sizes. Exact for the append case, and needs
# only a stat of each file.
estimate_append_bytes() {
local engine="$1"
local src_dir="${database_path}/${engine}"
local dst_dir="${drive_backup_path}/${engine}"
local total=0
shopt -s nullglob
local src_file
for src_file in "${src_dir}"/*; do
[ -f "${src_file}" ] || continue
local name src_size dst_size=0
name=$(basename "${src_file}")
src_size=$(stat -c%s "${src_file}")
if [ -f "${dst_dir}/${name}" ]; then
dst_size=$(stat -c%s "${dst_dir}/${name}")
fi
if [ "${src_size}" -gt "${dst_size}" ]; then
total=$(( total + src_size - dst_size ))
fi
done
shopt -u nullglob