Repository navigation
Expand file tree
/
Copy pathcloud-folder-setup.sh
More file actions
1441 lines (1370 loc) · 77.2 KB
/
Copy pathcloud-folder-setup.sh
File metadata and controls
1441 lines (1370 loc) · 77.2 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
#!/usr/bin/env bash
# cloud-folder-setup: the cloud-folder Feature's postStartCommand (a host folder is mounted, or
# not, per start; the sync timer is started per start), also behind every `task cloud-folder:*`.
#
# cloud-folder-setup post-start: make the state volume usable, start the rclone
# mount in mount mode, report on the folder, start the sync
# timer in sync mode (never fatal: always exit 0, bounded by
# DCF_CLOUD_FOLDER_START_BUDGET seconds, default 60)
# cloud-folder-setup status [--json] the report; exit 0 when the folder is usable, 1 when not
# (host: missing, not mounted, not writable; sync: no
# remote, never synced, last sync failed, not writable;
# mount: no remote, no FUSE, not mounted, uploads failed; or
# a mode this version does not know). --json: one object.
# cloud-folder-setup version the Feature version, the mode, the mount point, rclone
# cloud-folder-setup login [--relay | --token]
# sign in (interactive: rclone's browser flow in the
# container, the browser's address pasted back or relayed by
# the launcher (--relay), or a token from `rclone authorize
# "onedrive"` elsewhere (--token: only that); or client
# credentials from CLOUD_FOLDER_CLIENT_* without a prompt) and
# write the remote into the Feature's rclone.conf; then start
# the timer
# cloud-folder-setup sync [--resync] [--force]
# one `rclone bisync` between the remote and the folder
# (the first run of a folder is a --resync on its own)
# cloud-folder-setup start | stop sync mode: the sync timer (one supervised loop, PID file in
# the volume; start is idempotent, stop waits for a running
# sync). mount mode: the rclone mount (stop = unmount)
# cloud-folder-setup unmount [--force]
# mount mode: unmount once the VFS upload queue is empty
# (waits up to CLOUD_FOLDER_STOP_WAIT seconds); --force
# unmounts anyway (queued files upload at the next mount)
# cloud-folder-setup fuse-check whether FUSE is usable here, and why not: exit 0 or 1
# cloud-folder-setup run the timer loop itself (start runs it detached)
# cloud-folder-setup shutdown-check [SECONDS]
# for a repository's shutdown:check: exit 1 while a sync
# runs (after waiting up to SECONDS, default 60) or while
# local files changed since the last successful sync
# cloud-folder-setup link MOUNT_POINT HOST_MOUNT
# install.sh, as root: make MOUNT_POINT a symbolic link to
# HOST_MOUNT (nothing when they are the same path)
# cloud-folder-setup folder MOUNT_POINT
# install.sh, as root, mode sync or mount: make MOUNT_POINT a
# folder
#
# Host mode: the devcontainer-cli launcher bind-mounts the host folder named by
# DCF_HOST_CLOUD_FOLDER at one fixed path, the host mount (/mnt/cloud-folder-host), and
# install.sh links the option mountPoint to it when the two differ. "Mounted" means the path the
# mount point leads to (through the link) is the target of a mount in /proc/self/mountinfo. A
# folder that exists but is not mounted is a bare folder of the container: the status fails
# rather than call it a cloud folder.
#
# Sync mode: no link and no mount; `rclone bisync` fills the folder the mount point leads to
# (path 1 the remote cloud-folder:<remotePath>, path 2 that folder). The rclone config (and so the
# token), the bisync listings, the PID files, the last-sync record and the logs live in the
# Feature's volume (STATE_DIR), never in the workspace or the image; the token is never put on a
# command line and never printed. rclone reads it from the config file (RCLONE_CONFIG).
#
# Mount mode: `rclone mount` of the remote on the folder the mount point leads to, with a VFS
# cache of mode writes in the volume and rclone's remote control (--rc) on localhost only, with no
# credentials, so only its read-only methods answer; status asks vfs/stats for the upload queue.
# It needs FUSE, which only the launcher grants (DCF_HOST_FUSE=1, ADR 0031): /dev/fuse usable,
# CAP_SYS_ADMIN in the bounding set, no AppArmor profile that denies mount, and fusermount3. auto
# takes host, then mount, then sync (proposal section 10, decision 2).
#
# Nothing is written into the folder by a status: writability is the access check (test -w).
# The sync writes one hidden marker there (.cloud-folder-bisync, excluded from the sync) that
# tells a folder already synced from a new one (after a rebuild), which gets a --resync.
# Test hooks (not options): DCF_CLOUD_FOLDER_MOUNTINFO names the mount table to read (default
# /proc/self/mountinfo); DCF_CLOUD_FOLDER_HOST_MOUNT replaces the fixed host mount path;
# DCF_CLOUD_FOLDER_STATE_DIR replaces the state volume's path; DCF_CLOUD_FOLDER_GRACE the
# seconds a sync gets to stop gracefully (default 100); DCF_CLOUD_FOLDER_FUSE_DEV,
# DCF_CLOUD_FOLDER_PROC_STATUS, DCF_CLOUD_FOLDER_APPARMOR and DCF_CLOUD_FOLDER_FUSERMOUNT replace
# /dev/fuse, /proc/self/status, /proc/self/attr/current and the fusermount names the FUSE check
# reads; DCF_CLOUD_FOLDER_RC_ADDR the remote control's address (default 127.0.0.1:5572);
# DCF_CLOUD_FOLDER_MOUNT_WAIT the seconds a mount gets to appear (default 15);
# DCF_CLOUD_FOLDER_AUTH_WAIT the seconds rclone authorize gets to print its link (default 15);
# DCF_CLOUD_FOLDER_START_BUDGET the seconds the post-start run (report) gets in all (default 60).
set -u
# Defaults baked by install.sh from the Feature options; CLOUD_FOLDER_* in the environment
# override them without a rebuild.
# shellcheck disable=SC1091 # written by install.sh at image build
[ -f /usr/local/share/cloud-folder-feature/options.env ] && source /usr/local/share/cloud-folder-feature/options.env
mode_option="${CLOUD_FOLDER_MODE:-${MODE:-auto}}"
mount_point="${CLOUD_FOLDER_MOUNT_POINT:-${MOUNTPOINT:-/mnt/cloud-folder}}"
feature_version="${FEATURE_VERSION:-unknown}"
host_mount="${DCF_CLOUD_FOLDER_HOST_MOUNT:-${HOST_MOUNT:-/mnt/cloud-folder-host}}"
mountinfo="${DCF_CLOUD_FOLDER_MOUNTINFO:-/proc/self/mountinfo}"
host_source="${DCF_HOST_CLOUD_FOLDER:-}"
remote_type="${CLOUD_FOLDER_REMOTE_TYPE:-${REMOTETYPE:-sharepoint}}"
drive_type="${CLOUD_FOLDER_DRIVE_TYPE:-${DRIVETYPE:-documentLibrary}}"
site_url="${CLOUD_FOLDER_SITE_URL:-${SITEURL:-}}"
remote_path="${CLOUD_FOLDER_REMOTE_PATH:-${REMOTEPATH:-}}"
sync_interval="${CLOUD_FOLDER_SYNC_INTERVAL:-${SYNCINTERVAL:-15m}}"
rclone_version_option="${RCLONEVERSION:-}"
state_dir="${DCF_CLOUD_FOLDER_STATE_DIR:-${STATE_DIR:-/var/lib/devcontainer-features/cloud-folder}}"
grace="${DCF_CLOUD_FOLDER_GRACE:-100}"
fuse_dev="${DCF_CLOUD_FOLDER_FUSE_DEV:-/dev/fuse}"
proc_status="${DCF_CLOUD_FOLDER_PROC_STATUS:-/proc/self/status}"
apparmor_attr="${DCF_CLOUD_FOLDER_APPARMOR:-/proc/self/attr/current}"
fusermount_names="${DCF_CLOUD_FOLDER_FUSERMOUNT:-fusermount3 fusermount}"
# Localhost only: rclone's remote control must never answer from outside the container.
rc_addr="${DCF_CLOUD_FOLDER_RC_ADDR:-127.0.0.1:5572}"
mount_wait="${DCF_CLOUD_FOLDER_MOUNT_WAIT:-15}"
conf="$state_dir/rclone.conf"
run_dir="$state_dir/run"
remote_name=cloud-folder
remote="$remote_name:$remote_path"
marker_name=.cloud-folder-bisync
self="$(readlink -f -- "${BASH_SOURCE[0]}" 2>/dev/null || printf '%s' "$0")"
# A trailing slash would never match the mount table.
while [ "${#mount_point}" -gt 1 ] && [ "${mount_point%/}" != "$mount_point" ]; do mount_point="${mount_point%/}"; done
say() { echo "cloud-folder: $*"; }
# rcl <args>: rclone with the Feature's config and cache in the volume. Only paths and flags go
# on its command line, never a secret.
rcl() { RCLONE_CONFIG="$conf" RCLONE_CACHE_DIR="$state_dir/cache" rclone "$@"; }
as_root() { # run a command as root: directly, or through passwordless sudo
if [ "$(id -u)" -eq 0 ]; then "$@"; elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then sudo -n "$@"; else return 1; fi
}
# is_mounted <path>: the path is the target of a mount. The mount table escapes space, tab,
# newline and backslash as octal (\040, \011, \012, \134), so the path is encoded the same way.
mount_enc() {
local enc="$1"
enc="${enc//\\/\\134}"
enc="${enc// /\\040}"
enc="${enc//$'\t'/\\011}"
enc="${enc//$'\n'/\\012}"
printf '%s' "$enc"
}
is_mounted() {
[ -r "$mountinfo" ] || return 1
CF_TARGET="$(mount_enc "$1")" awk '$5 == ENVIRON["CF_TARGET"] { found = 1 } END { exit !found }' "$mountinfo" 2>/dev/null
}
# mount_fstype <path>: the file system type of the last mount on the path (the one on top), from
# the field after the separator "-" of its mountinfo line; empty when nothing is mounted there.
# rclone's mount is fuse.rclone.
mount_fstype() {
[ -r "$mountinfo" ] || return 0
CF_TARGET="$(mount_enc "$1")" awk '$5 == ENVIRON["CF_TARGET"] { t = ""; for (i = 7; i < NF; i++) if ($i == "-") { t = $(i + 1); break } }
END { print t }' "$mountinfo" 2>/dev/null
}
# real_path <path>: where the path leads, links followed (the last part need not exist).
real_path() { readlink -m -- "$1" 2>/dev/null || readlink -f -- "$1" 2>/dev/null || printf '%s\n' "$1"; }
# link_mount_point <mount point> <host mount>: the build-time link (install.sh runs it as root).
# Idempotent: an existing link is replaced, an empty folder gives way; a folder with content or
# any other file is refused, since replacing it would lose what is there.
link_mount_point() {
local mp="$1" hm="$2"
case "$mp" in /?*) ;; *) echo "cloud-folder: mountPoint '$mp' must be an absolute path." >&2; return 1 ;; esac
while [ "${#mp}" -gt 1 ] && [ "${mp%/}" != "$mp" ]; do mp="${mp%/}"; done
if [ "$mp" = "$hm" ]; then say "mountPoint is the host mount $hm itself: no link"; return 0; fi
if [ -L "$mp" ]; then
rm -f -- "$mp" || return 1
elif [ -d "$mp" ]; then
if [ -n "$(find "$mp" -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null)" ]; then
echo "cloud-folder: mountPoint $mp is a folder with content in the image; it cannot become the link to $hm. Choose another mountPoint, or empty that folder first." >&2
return 1
fi
rmdir -- "$mp" || return 1
elif [ -e "$mp" ]; then
echo "cloud-folder: mountPoint $mp exists in the image and is not a folder or a link; it cannot become the link to $hm." >&2
return 1
fi
mkdir -p -- "$(dirname -- "$mp")" || return 1
ln -s -- "$hm" "$mp" || return 1
say "mountPoint $mp links to the host mount $hm"
}
# make_folder <mount point>: the build-time folder of mode sync (install.sh runs it as root). A
# link (left by an earlier layout) gives way; a folder stays as it is; any other file is refused.
make_folder() {
local mp="$1"
case "$mp" in /?*) ;; *) echo "cloud-folder: mountPoint '$mp' must be an absolute path." >&2; return 1 ;; esac
while [ "${#mp}" -gt 1 ] && [ "${mp%/}" != "$mp" ]; do mp="${mp%/}"; done
if [ -L "$mp" ]; then rm -f -- "$mp" || return 1; fi
if [ -e "$mp" ] && [ ! -d "$mp" ]; then
echo "cloud-folder: mountPoint $mp exists in the image and is not a folder; the sync mode needs a folder there." >&2
return 1
fi
mkdir -p -- "$mp" || return 1
# Hand it to the remote user now when the build names one; the post-start report does it again.
if [ -n "${_REMOTE_USER:-}" ] && [ "${_REMOTE_USER}" != root ] && id -u "$_REMOTE_USER" >/dev/null 2>&1; then
chown "$_REMOTE_USER:$(id -gn "$_REMOTE_USER")" "$mp" || return 1
fi
say "mountPoint $mp is a folder, filled by the sync or the rclone mount (it is handed to the remote user at start)"
}
# ------------------------------------------------------------- processes ----
# alive <pid>: a running process (a zombie, gone but not yet reaped, does not count).
alive() {
local st
case "${1:-}" in '' | *[!0-9]*) return 1 ;; esac
kill -0 "$1" 2>/dev/null || return 1
st="$(cat "/proc/$1/stat" 2>/dev/null)" || return 0
st="${st##*) }"
[ "${st%% *}" != Z ]
}
# ours <pid>: alive and a cloud-folder-setup process (a PID file may outlive its process, and the
# number be reused).
ours() {
alive "${1:-}" || return 1
tr '\0' ' ' < "/proc/$1/cmdline" 2>/dev/null | grep -q cloud-folder-setup
}
pid_of() { local p=''; [ -f "$1" ] && read -r p < "$1" 2>/dev/null; case "$p" in '' | *[!0-9]*) echo '' ;; *) echo "$p" ;; esac; }
# take_lock <pid file>: write this shell's PID atomically; a file whose process is gone is stale
# and replaced. Exit 1 when another live process holds it.
take_lock() {
if (set -o noclobber; echo "$$" > "$1") 2>/dev/null; then return 0; fi
ours "$(pid_of "$1")" && return 1
rm -f -- "$1"
(set -o noclobber; echo "$$" > "$1") 2>/dev/null
}
# shellcheck disable=SC2329 # called from the EXIT traps
drop_lock() { [ "$(pid_of "$1")" = "$$" ] && rm -f -- "$1"; return 0; }
# interval_seconds: syncInterval in seconds (15m, 900s, 900, 1h; 0 = on demand only).
interval_seconds() {
local n u
[[ "$sync_interval" =~ ^([0-9]+)([smh]?)$ ]] || return 1
n="${BASH_REMATCH[1]}"; u="${BASH_REMATCH[2]}"
n=$((10#$n))
case "$u" in m) n=$((n * 60)) ;; h) n=$((n * 3600)) ;; esac
echo "$n"
}
# ----------------------------------------------------------------- state ----
# prepare_state: the volume usable by this user (dcf-persist, as every Feature of the collection
# does), the folders inside it private, the config mode 600. Quiet unless asked (report).
prepare_state() {
local verbose="${1:-quiet}"
if command -v dcf-persist >/dev/null 2>&1; then
if [ "$verbose" = verbose ]; then dcf-persist --label 'cloud-folder state' "$state_dir"; else dcf-persist "$state_dir" >/dev/null 2>&1; fi
elif [ ! -d "$state_dir" ]; then
mkdir -p -- "$state_dir" 2>/dev/null || { as_root mkdir -p -- "$state_dir" && as_root chown "$(id -u):$(id -g)" "$state_dir"; }
fi
[ -w "$state_dir" ] || return 1
chmod 0700 "$state_dir" 2>/dev/null
(umask 077; mkdir -p -- "$run_dir" "$state_dir/bisync" "$state_dir/cache") || return 1
[ -f "$conf" ] && chmod 0600 "$conf" 2>/dev/null
return 0
}
# conf_state: CONF (missing | unreadable | no-remote | no-token | ok), CONF_TYPE and CONF_AUTH
# (token | client-credentials | none), read from the config without printing any value.
conf_state() {
local out found tok cc
CONF=missing; CONF_TYPE=''; CONF_AUTH=none
[ -e "$conf" ] || return 0
if [ ! -r "$conf" ]; then CONF=unreadable; return 0; fi
out="$(awk -v sec="[$remote_name]" '
/^[[:space:]]*\[/ { s = $0; gsub(/[[:space:]]/, "", s); in_s = (s == sec); if (in_s) found = 1; next }
in_s && /^[[:space:]]*type[[:space:]]*=/ { t = $0; sub(/^[^=]*=[[:space:]]*/, "", t); sub(/[[:space:]]*$/, "", t); type = t }
in_s && /^[[:space:]]*token[[:space:]]*=[[:space:]]*[^[:space:]]/ { tok = 1 }
in_s && /^[[:space:]]*client_credentials[[:space:]]*=[[:space:]]*true/ { cc = 1 }
END { printf "%d %s %d %d\n", found, (type == "" ? "-" : type), tok, cc }' "$conf" 2>/dev/null)"
read -r found CONF_TYPE tok cc <<<"$out"
[ "$CONF_TYPE" = - ] && CONF_TYPE=''
if [ "${found:-0}" != 1 ]; then CONF=no-remote; return 0; fi
if [ "${cc:-0}" = 1 ]; then CONF_AUTH=client-credentials; elif [ "${tok:-0}" = 1 ]; then CONF_AUTH=token; fi
if [ "$CONF_TYPE" = onedrive ] && [ "$CONF_AUTH" = none ]; then CONF=no-token; return 0; fi
CONF=ok
}
# read_record: the last sync, from the record the sync writes (key=value lines, never sourced).
read_record() {
local k v
LAST_TIME=''; LAST_RESULT=''; LAST_RC=''; LAST_RESYNC=''; LAST_SECONDS=''; LAST_NOTE=''
[ -r "$state_dir/last-sync" ] || return 0
while IFS='=' read -r k v; do
case "$k" in
time) LAST_TIME="$v" ;; result) LAST_RESULT="$v" ;; rc) LAST_RC="$v" ;;
resync) LAST_RESYNC="$v" ;; seconds) LAST_SECONDS="$v" ;; note) LAST_NOTE="$v" ;;
esac
done < "$state_dir/last-sync"
}
# pending_count <folder>: files changed in the folder since the last successful sync started
# (all files when there was none). Deletions and files arriving with an old modification time
# are not seen; see the NOTES.
pending_count() {
local dir="$1"
[ -d "$dir" ] && [ -r "$dir" ] || { echo 0; return; }
if [ -f "$state_dir/last-ok" ]; then
find -H "$dir" -type f ! -name "$marker_name" -newer "$state_dir/last-ok" -print 2>/dev/null | head -n 10000 | wc -l | tr -d ' '
else
find -H "$dir" -type f ! -name "$marker_name" -print 2>/dev/null | head -n 10000 | wc -l | tr -d ' '
fi
}
# ------------------------------------------------------------------ FUSE ----
# fuse_check: FUSE (yes | no), FUSE_WHY and FUSERMOUNT, from what the container was given: the
# device (a character device this user can open for reading and writing; the device rules of the
# engine refuse the open otherwise), CAP_SYS_ADMIN (bit 21) in the capability bounding set (what
# the setuid fusermount3 needs to mount), an AppArmor profile that does not deny mount (Docker's
# docker-default does), and fusermount3 (or fusermount) on PATH. Reads only; the device is opened
# and closed. All four come from the launcher (DCF_HOST_FUSE=1) and the fuse3 package.
fuse_check() {
local capbnd='' k v prof='' f
FUSE=no; FUSE_WHY=''; FUSERMOUNT=''
if [ ! -e "$fuse_dev" ]; then
FUSE_WHY="no $fuse_dev in the container (the launcher grants FUSE when the project sets DCF_HOST_FUSE=1)"; return 0
fi
if [ ! -c "$fuse_dev" ]; then FUSE_WHY="$fuse_dev is not a character device"; return 0; fi
if ! (exec 3<>"$fuse_dev") 2>/dev/null; then
FUSE_WHY="$fuse_dev cannot be opened for reading and writing (the engine's device rules deny it: --device=/dev/fuse)"; return 0
fi
if [ -r "$proc_status" ]; then
while read -r k v; do [ "$k" = CapBnd: ] && capbnd="$v"; done < "$proc_status"
fi
if [[ "$capbnd" =~ ^[0-9a-fA-F]{1,16}$ ]] && [ $(( (16#$capbnd >> 21) & 1 )) -eq 0 ]; then
FUSE_WHY="no CAP_SYS_ADMIN in the container's capability bounding set (--cap-add=SYS_ADMIN), which mounting needs"; return 0
fi
[ -r "$apparmor_attr" ] && read -r prof < "$apparmor_attr" 2>/dev/null
case "$prof" in
*-default*'(enforce)'*)
FUSE_WHY="the AppArmor profile ${prof%% *} denies mount (--security-opt=apparmor=unconfined)"; return 0 ;;
esac
for f in $fusermount_names; do
if command -v "$f" >/dev/null 2>&1; then FUSERMOUNT="$f"; break; fi
done
if [ -z "$FUSERMOUNT" ]; then
FUSE_WHY="no fusermount3 on PATH (the fuse3 package, which the Feature installs in mode auto and mount)"; return 0
fi
FUSE=yes; FUSE_WHY="$fuse_dev opens, CAP_SYS_ADMIN is in the bounding set, $FUSERMOUNT is on PATH"
}
# parse_vfs_stats: reads the reply of `rclone rc vfs/stats` (rclone's indented JSON) on stdin and
# sets VFS_OK (yes when it is a vfs/stats reply), VFS_CACHE (off | minimal | writes | full, from
# opt.CacheMode, a number in rclone 1.75 and a name in older releases), VFS_INPROG, VFS_QUEUED and
# VFS_ERRORED (diskCache.uploadsInProgress, uploadsQueued and erroredFiles; empty when there is no
# disk cache, which is cache mode off: no queue to read) and VFS_PENDING (in progress + queued).
parse_vfs_stats() {
local out ok mode inprog queued errored
out="$(awk '
function num(s) { sub(/^[^:]*:[[:space:]]*/, "", s); gsub(/[^0-9]/, "", s); return s }
/^[[:space:]]*"fs"[[:space:]]*:/ { fs = 1 }
/^[[:space:]]*"uploadsInProgress"[[:space:]]*:/ { inprog = num($0) }
/^[[:space:]]*"uploadsQueued"[[:space:]]*:/ { queued = num($0) }
/^[[:space:]]*"erroredFiles"[[:space:]]*:/ { errored = num($0) }
/^[[:space:]]*"CacheMode"[[:space:]]*:/ { m = $0; sub(/^[^:]*:[[:space:]]*/, "", m); gsub(/[",[:space:]]/, "", m); mode = m }
END { printf "%d %s %s %s %s\n", fs, (mode == "" ? "-" : mode), (inprog == "" ? "-" : inprog), (queued == "" ? "-" : queued), (errored == "" ? "-" : errored) }')"
read -r ok mode inprog queued errored <<<"$out"
VFS_OK=no; VFS_CACHE=''; VFS_INPROG=''; VFS_QUEUED=''; VFS_ERRORED=''; VFS_PENDING=''
[ "${ok:-0}" = 1 ] || return 0
VFS_OK=yes
case "$mode" in 0) VFS_CACHE=off ;; 1) VFS_CACHE=minimal ;; 2) VFS_CACHE=writes ;; 3) VFS_CACHE=full ;; -) VFS_CACHE=unknown ;; *) VFS_CACHE="$mode" ;; esac
[ "$inprog" = - ] || VFS_INPROG="$inprog"
[ "$queued" = - ] || VFS_QUEUED="$queued"
[ "$errored" = - ] || VFS_ERRORED="$errored"
if [ -n "$VFS_INPROG" ] && [ -n "$VFS_QUEUED" ]; then VFS_PENDING=$((10#$VFS_INPROG + 10#$VFS_QUEUED)); fi
}
# vfs_query: ask the running mount's remote control for vfs/stats (no credentials: a read-only
# method) and parse it. VFS_OK=no when it does not answer.
vfs_query() {
local out
if out="$(timeout 10 rclone rc vfs/stats --url "http://$rc_addr/" 2>/dev/null)"; then
parse_vfs_stats <<<"$out"
else
parse_vfs_stats </dev/null
fi
}
# wait_uploads <seconds>: query until the upload queue is empty or the time is up; returns 0 when
# it is empty, 1 when files are still pending, 2 when the queue cannot be read.
wait_uploads() {
local max="$1" waited=0
while :; do
vfs_query
[ "$VFS_OK" = yes ] && [ -n "$VFS_PENDING" ] || return 2
[ "$VFS_PENDING" -eq 0 ] && return 0
[ "$waited" -ge "$max" ] && return 1
sleep 1; waited=$((waited + 1))
done
}
# mount_ours <pid>: alive and an `rclone mount` (the PID file may outlive its process).
mount_ours() {
alive "${1:-}" || return 1
tr '\0' ' ' < "/proc/$1/cmdline" 2>/dev/null | grep -q 'rclone mount '
}
# ---------------------------------------------------------------- assess ----
# resolve: sets the host facts (REAL, LINKED, PRESENT, MOUNTED, RCLONE_MOUNTED, IS_DIR, EMPTY,
# WRITABLE), the FUSE facts (fuse_check) and the mode: MODE_USED (host | mount | sync | none) and
# WHY, or VERDICT=unknown-mode.
resolve() {
PRESENT=no; MOUNTED=no; RCLONE_MOUNTED=no; IS_DIR=no; EMPTY=unknown; WRITABLE=no; HINT=''; LINKED=no; VERDICT=''
REAL="$(real_path "$mount_point")"
[ -L "$mount_point" ] && LINKED=yes
[ -e "$mount_point" ] && PRESENT=yes
[ -d "$mount_point" ] && IS_DIR=yes
is_mounted "$REAL" && MOUNTED=yes
[ "$MOUNTED" = yes ] && [ "$(mount_fstype "$REAL")" = fuse.rclone ] && RCLONE_MOUNTED=yes
if [ "$IS_DIR" = yes ] && [ -r "$mount_point" ] && [ -x "$mount_point" ]; then
if [ -n "$(find -H "$mount_point" -mindepth 1 -maxdepth 1 ! -name "$marker_name" -print -quit 2>/dev/null)" ]; then EMPTY=no; else EMPTY=yes; fi
fi
[ "$IS_DIR" = yes ] && [ -w "$mount_point" ] && [ -x "$mount_point" ] && WRITABLE=yes
conf_state
fuse_check
case "$mode_option" in
host | sync | mount)
MODE_USED="$mode_option"; WHY='set by the option or CLOUD_FOLDER_MODE' ;;
auto)
# host, then mount, then sync (decision 2). A folder that already holds a sync copy stays
# with sync: rclone would not mount over it, and its unsynced changes would be hidden.
if [ "$RCLONE_MOUNTED" = yes ]; then MODE_USED=mount; WHY="auto: rclone is mounted at $mount_point"
elif [ "$MOUNTED" = yes ]; then MODE_USED=host; WHY="auto: something is mounted at $mount_point"
elif [ "$CONF" != ok ]; then
MODE_USED=none; WHY="auto: nothing is mounted at $mount_point, and no remote is configured"
[ "$FUSE" = yes ] && WHY="$WHY (FUSE is usable, so a sign-in gives mount mode)"
elif [ "$FUSE" = yes ] && [ -f "$REAL/$marker_name" ]; then
MODE_USED=sync; WHY="auto: nothing is mounted at $mount_point and a remote is configured; FUSE is usable, but $REAL holds a sync copy, so sync stays (stop the timer, sync, empty the folder and run task cloud-folder:setup to move to mount)"
elif [ "$FUSE" = yes ]; then MODE_USED=mount; WHY="auto: nothing is mounted at $mount_point, a remote is configured and FUSE is usable"
else MODE_USED=sync; WHY="auto: nothing is mounted at $mount_point and a remote is configured; FUSE is not usable ($FUSE_WHY)"; fi ;;
*)
MODE_USED=none; WHY="mode '$mode_option' is unknown (auto, host, mount or sync)"
VERDICT=unknown-mode ;;
esac
}
# assess [remote]: resolve, then the verdict (ok | empty | not-mounted | no-source | not-a-folder
# | unwritable | unknown-mode, and in sync mode not-configured | no-rclone | never-synced |
# syncing | needs-resync | sync-failed) and HINT. With "remote", sync mode asks the remote
# whether it answers (REACHABLE yes | no | unknown).
assess() {
resolve
[ "$VERDICT" = unknown-mode ] && return 0
if [ "$MODE_USED" = sync ]; then assess_sync "${1:-}"; return 0; fi
if [ "$MODE_USED" = mount ]; then assess_mount "${1:-}"; return 0; fi
if [ "$MOUNTED" = no ]; then
if [ "$MODE_USED" = none ]; then VERDICT=no-source; else VERDICT=not-mounted; fi
if [ -n "$host_source" ]; then
HINT="the launcher was given DCF_HOST_CLOUD_FOLDER=$host_source, but nothing is mounted here: the host folder may not exist (the launcher then skips the mount and says so), HOST_MOUNTS=false may be set, or the container was started without the launcher (task devcontainer:up, devcontainer-cli 1.12.0 or later)."
else
HINT="no host folder: set DCF_HOST_CLOUD_FOLDER=<host path> in .devcontainer/.env on the host and start with task devcontainer:up; the launcher then mounts it here (map DCF_HOST_CLOUD_FOLDER with containerEnv so this report can name it)."
fi
if [ "$MODE_USED" = none ]; then
HINT="$HINT Or sync it with rclone: task cloud-folder:login, then the timer (or task cloud-folder:sync) fills it."
fi
if [ "$REAL" != "$host_mount" ] && is_mounted "$host_mount"; then
HINT="$HINT The host mount $host_mount is mounted, but $mount_point does not lead to it (CLOUD_FOLDER_MOUNT_POINT names another path than the option mountPoint, or the image predates the link): use $host_mount, or rebuild."
fi
if [ "$PRESENT" = yes ]; then
HINT="$HINT $mount_point exists but is a bare folder of the container: do not write there."
fi
return 0
fi
if [ "$IS_DIR" = no ]; then VERDICT=not-a-folder; HINT="$mount_point is mounted but is not a folder"; return 0; fi
if [ "$WRITABLE" = no ]; then
VERDICT=unwritable
HINT="$(id -un 2>/dev/null || id -u) cannot write to $mount_point: check the host folder's permissions (or the mount is read-only)"
return 0
fi
if [ "$EMPTY" = yes ]; then
VERDICT=empty
HINT="the folder is mounted and writable but empty: right for a new folder; otherwise check that DCF_HOST_CLOUD_FOLDER names the synced folder and that the sync client has finished"
return 0
fi
VERDICT=ok
}
# check_reachable: REACHABLE yes | no (REACH_ERR) when a remote is configured and rclone is here.
check_reachable() {
local err
[ "$CONF" = ok ] && [ "$RCLONE_OK" = yes ] || return 0
if err="$(timeout 30 env RCLONE_CONFIG="$conf" RCLONE_CACHE_DIR="$state_dir/cache" rclone lsjson --stat --contimeout 10s --timeout 15s --low-level-retries 1 --retries 1 "$remote" 2>&1 >/dev/null)"; then
REACHABLE=yes
else
REACHABLE=no; REACH_ERR="$(printf '%s\n' "$err" | grep -v '^[[:space:]]*$' | tail -n 1 | cut -c1-300)"
fi
}
# assess_mount [remote]: the verdict in mount mode (not-configured | no-rclone | no-fuse | mounting
# | not-mounted | not-a-folder | unwritable | upload-errors | empty | ok). With "remote", the
# remote is asked whether it answers; when rclone is mounted, vfs/stats is read.
assess_mount() {
local p
MOUNT_PID=''; REACHABLE=unknown; REACH_ERR=''
parse_vfs_stats </dev/null
p="$(pid_of "$run_dir/mount.pid")"; mount_ours "$p" && MOUNT_PID="$p"
RCLONE_OK=no; command -v rclone >/dev/null 2>&1 && RCLONE_OK=yes
[ "${1:-}" = remote ] && check_reachable
[ "$RCLONE_MOUNTED" = yes ] && [ "$RCLONE_OK" = yes ] && vfs_query
case "$CONF" in
ok) ;;
unreadable) VERDICT=not-configured; HINT="$conf cannot be read by $(id -un 2>/dev/null || id -u): run task cloud-folder:setup (it hands the volume to this user)"; return 0 ;;
*) VERDICT=not-configured; HINT="no remote '$remote_name' with a sign-in in $conf: run task cloud-folder:login"; return 0 ;;
esac
if [ "$RCLONE_OK" = no ]; then VERDICT=no-rclone; HINT='rclone is not on PATH: rebuild with the Feature in mode auto or mount'; return 0; fi
if [ "$RCLONE_MOUNTED" = no ]; then
if [ "$MOUNTED" = yes ]; then
VERDICT=not-mounted; HINT="something other than rclone is mounted at $REAL (a host folder?): use mode host, or remove that mount"
elif [ "$FUSE" = no ]; then
VERDICT=no-fuse
HINT="$FUSE_WHY. Mount mode needs FUSE, which the launcher grants per machine: set DCF_HOST_FUSE=1 in .devcontainer/.env on the host (the repository's devcontainer.json needs the DCF_HOST_FUSE_* runArgs of the bootstrap template) and rebuild with task devcontainer:rebuild; or use mode sync, which needs nothing privileged"
elif [ -n "$MOUNT_PID" ]; then
VERDICT=mounting; HINT="rclone mount (pid $MOUNT_PID) is starting; log: $state_dir/mount.log"
elif [ "$IS_DIR" = yes ] && [ -n "$(find -H "$REAL" -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null)" ]; then
VERDICT=not-mounted; HINT="$REAL holds files (a sync copy?) and rclone will not mount over them: sync them, move them away, then task cloud-folder:start"
else
VERDICT=not-mounted; HINT="rclone is not mounted at $REAL: task cloud-folder:start mounts it (the post-start hook does at each start); log: $state_dir/mount.log"
fi
return 0
fi
if [ "$IS_DIR" = no ]; then VERDICT=not-a-folder; HINT="$mount_point does not lead to a folder"; return 0; fi
if [ "$WRITABLE" = no ]; then VERDICT=unwritable; HINT="$(id -un 2>/dev/null || id -u) cannot write to $mount_point: the mount was made by another user; task cloud-folder:stop, then task cloud-folder:start as this user"; return 0; fi
if [ -n "$VFS_ERRORED" ] && [ "$VFS_ERRORED" -gt 0 ]; then
VERDICT=upload-errors; HINT="$VFS_ERRORED file(s) failed to upload to the remote; they stay in the VFS cache ($state_dir/cache): read $state_dir/mount.log"; return 0
fi
if [ "$EMPTY" = yes ]; then VERDICT=empty; HINT="mounted, but the folder is empty: right for an empty remote folder; otherwise check remotePath"; return 0; fi
VERDICT=ok
}
assess_sync() {
local check_remote="${1:-}" p
read_record
SYNC_PID=''; LOOP_PID=''; REACHABLE=unknown; REACH_ERR=''
p="$(pid_of "$run_dir/sync.pid")"; ours "$p" && SYNC_PID="$p"
p="$(pid_of "$run_dir/loop.pid")"; ours "$p" && LOOP_PID="$p"
RCLONE_OK=no; command -v rclone >/dev/null 2>&1 && RCLONE_OK=yes
MARKER=no; [ -f "$REAL/$marker_name" ] && MARKER=yes
PENDING="$(pending_count "$REAL")"
NEEDS_RESYNC=no
[ -n "$(find "$state_dir/bisync" -maxdepth 1 -name '*.lst-err' -print -quit 2>/dev/null)" ] && NEEDS_RESYNC=yes
[ "$check_remote" = remote ] && check_reachable
case "$CONF" in
ok) ;;
unreadable) VERDICT=not-configured; HINT="$conf cannot be read by $(id -un 2>/dev/null || id -u): run task cloud-folder:setup (it hands the volume to this user)"; return 0 ;;
*) VERDICT=not-configured; HINT="no remote '$remote_name' with a sign-in in $conf: run task cloud-folder:login"; return 0 ;;
esac
if [ "$RCLONE_OK" = no ]; then VERDICT=no-rclone; HINT='rclone is not on PATH: rebuild with the Feature in mode auto or sync'; return 0; fi
if [ "$PRESENT" = yes ] && [ "$IS_DIR" = no ]; then VERDICT=not-a-folder; HINT="$mount_point is not a folder"; return 0; fi
if [ "$IS_DIR" = yes ] && [ "$WRITABLE" = no ]; then
VERDICT=unwritable; HINT="$(id -un 2>/dev/null || id -u) cannot write to $mount_point: run task cloud-folder:setup (it hands the folder to this user)"; return 0
fi
if [ "$NEEDS_RESYNC" = yes ]; then
VERDICT=needs-resync; HINT="bisync stopped on a critical error and keeps its listings aside (.lst-err in $state_dir/bisync): read $state_dir/sync.log, then task cloud-folder:sync -- --resync"; return 0
fi
if [ -z "$LAST_RESULT" ] || [ "$MARKER" = no ]; then
if [ -n "$SYNC_PID" ]; then VERDICT=syncing; HINT="the first sync of $REAL is running (pid $SYNC_PID): wait for it"
else
VERDICT=never-synced
if [ -n "$LAST_RESULT" ]; then HINT="$REAL has not been synced yet (a new folder, after a rebuild?): task cloud-folder:sync (or wait for the timer) fills it"
else HINT="no sync yet: task cloud-folder:sync (or wait for the timer)"; fi
fi
return 0
fi
if [ "$LAST_RESULT" != ok ]; then
VERDICT=sync-failed
HINT="the last sync ($LAST_TIME) ended $LAST_RESULT (rclone exit $LAST_RC)${LAST_NOTE:+: $LAST_NOTE}; log: $state_dir/sync.log"
case "$LAST_NOTE" in
*'too many deletes'*) HINT="$HINT. bisync's delete guard stopped it (more than half the files of one side are gone): restore them, or, if the deletion is meant, task cloud-folder:sync -- --force" ;;
*'Empty current Path'*) HINT="$HINT. One side is empty and bisync will not empty the other: if the folder was emptied by mistake, task cloud-folder:sync -- --resync brings the files back" ;;
esac
return 0
fi
if [ "$EMPTY" = yes ]; then VERDICT=empty; HINT="synced, but the folder is empty: right for an empty remote folder; otherwise check remotePath"; return 0; fi
VERDICT=ok
}
json_str() { # <text>: a JSON string literal
local s="$1"
s="${s//\\/\\\\}"; s="${s//\"/\\\"}"
s="${s//$'\n'/\\n}"; s="${s//$'\r'/\\r}"; s="${s//$'\t'/\\t}"
printf '"%s"' "$s"
}
json_bool() { if [ "$1" = yes ]; then printf true; else printf false; fi; }
json_tri() { case "$1" in yes) printf true ;; no) printf false ;; *) printf null ;; esac; }
verdict_ok() { [ "$VERDICT" = ok ] || [ "$VERDICT" = empty ]; }
print_json() {
printf '{"mode_option":%s,"mode":%s,"why":%s,"mount_point":%s,"real_path":%s,"linked":%s,"host_source":%s,' \
"$(json_str "$mode_option")" "$(json_str "$MODE_USED")" "$(json_str "$WHY")" "$(json_str "$mount_point")" \
"$(json_str "$REAL")" "$(json_bool "$LINKED")" "$(json_str "$host_source")"
printf '"present":%s,"mounted":%s,"folder":%s,"empty":%s,"writable":%s,' \
"$(json_bool "$PRESENT")" "$(json_bool "$MOUNTED")" "$(json_bool "$IS_DIR")" "$(json_tri "$EMPTY")" "$(json_bool "$WRITABLE")"
if [ "$MODE_USED" = sync ]; then
printf '"remote":%s,"remote_type":%s,"configured":%s,"auth":%s,"remote_reachable":%s,"last_sync":%s,"last_result":%s,"last_rc":%s,"sync_running":%s,"sync_pid":%s,"timer_running":%s,"timer_pid":%s,"interval":%s,"pending":%s,' \
"$(json_str "$remote")" "$(json_str "$remote_type")" "$(json_bool "$([ "$CONF" = ok ] && echo yes)")" "$(json_str "$CONF_AUTH")" \
"$(json_tri "$REACHABLE")" "$(json_str "$LAST_TIME")" "$(json_str "$LAST_RESULT")" "${LAST_RC:-null}" \
"$(json_bool "$([ -n "$SYNC_PID" ] && echo yes)")" "${SYNC_PID:-null}" "$(json_bool "$([ -n "$LOOP_PID" ] && echo yes)")" "${LOOP_PID:-null}" \
"$(json_str "$sync_interval")" "${PENDING:-0}"
fi
if [ "$MODE_USED" = mount ]; then
printf '"remote":%s,"remote_type":%s,"configured":%s,"auth":%s,"remote_reachable":%s,"rclone_mounted":%s,"mount_pid":%s,"rc_addr":%s,"rc_answers":%s,"cache_mode":%s,"uploads_in_progress":%s,"uploads_queued":%s,"uploads_pending":%s,"errored_files":%s,' \
"$(json_str "$remote")" "$(json_str "$remote_type")" "$(json_bool "$([ "$CONF" = ok ] && echo yes)")" "$(json_str "$CONF_AUTH")" \
"$(json_tri "$REACHABLE")" "$(json_bool "$RCLONE_MOUNTED")" "${MOUNT_PID:-null}" "$(json_str "$rc_addr")" "$(json_bool "$VFS_OK")" \
"$(if [ -n "$VFS_CACHE" ]; then json_str "$VFS_CACHE"; else printf null; fi)" "${VFS_INPROG:-null}" "${VFS_QUEUED:-null}" "${VFS_PENDING:-null}" "${VFS_ERRORED:-null}"
fi
printf '"fuse":%s,"fuse_why":%s,' "$(json_bool "$FUSE")" "$(json_str "$FUSE_WHY")"
printf '"verdict":%s,"ok":%s,"hint":%s}\n' \
"$(json_str "$VERDICT")" "$(if verdict_ok; then printf true; else printf false; fi)" "$(json_str "$HINT")"
}
print_report() {
local state
say "mode $MODE_USED ($WHY)"
if [ "$MODE_USED" = sync ]; then print_sync_report; return; fi
if [ "$MODE_USED" = mount ]; then print_mount_report; return; fi
if [ "$MOUNTED" = yes ]; then state=mounted; elif [ "$PRESENT" = yes ]; then state='present, not mounted'; else state=missing; fi
if [ "$LINKED" = yes ]; then say "mount point $mount_point -> $REAL: $state"
else say "mount point $mount_point: $state"; fi
[ -n "$host_source" ] && say "host folder (DCF_HOST_CLOUD_FOLDER): $host_source"
if [ "$MOUNTED" = yes ] && [ "$IS_DIR" = yes ]; then
case "$EMPTY" in yes) state=empty ;; no) state='not empty' ;; *) state='cannot be listed' ;; esac
say "contents: $state; writable: $WRITABLE"
fi
print_verdict
}
print_sync_report() {
local state auth reach timer
case "$CONF_AUTH" in token) auth='signed in with a token' ;; client-credentials) auth='client credentials' ;; *) auth='no sign-in' ;; esac
case "$CONF" in ok) state="configured, $auth" ;; *) state="not configured ($CONF)" ;; esac
case "$REACHABLE" in yes) reach=reachable ;; no) reach="NOT reachable${REACH_ERR:+: $REACH_ERR}" ;; *) reach='reachability not checked' ;; esac
say "remote $remote (remoteType $remote_type${site_url:+, site $site_url}): $state; $reach"
if [ "$PRESENT" = yes ]; then state=present; else state='missing (made at the first sync)'; fi
if [ "$LINKED" = yes ]; then say "local copy $mount_point -> $REAL: $state"; else say "local copy $mount_point: $state"; fi
if [ "$IS_DIR" = yes ]; then
case "$EMPTY" in yes) state=empty ;; no) state='not empty' ;; *) state='cannot be listed' ;; esac
say "contents: $state; writable: $WRITABLE; files changed since the last sync: ${PENDING:-0}"
fi
if [ -n "$LAST_RESULT" ]; then say "last sync: $LAST_TIME, $LAST_RESULT (rclone exit $LAST_RC${LAST_SECONDS:+, ${LAST_SECONDS}s}${LAST_RESYNC:+, resync $LAST_RESYNC})"
else say "last sync: never"; fi
if [ -n "$LOOP_PID" ]; then timer="running (pid $LOOP_PID, every $sync_interval)"
elif [ "$(interval_seconds 2>/dev/null)" = 0 ]; then timer='off (syncInterval 0: on demand only)'
else timer='not running'; fi
if [ -n "$SYNC_PID" ]; then say "sync: running now (pid $SYNC_PID); timer: $timer"; else say "sync: not running; timer: $timer"; fi
print_verdict
}
print_mount_report() {
local state auth reach q
case "$CONF_AUTH" in token) auth='signed in with a token' ;; client-credentials) auth='client credentials' ;; *) auth='no sign-in' ;; esac
case "$CONF" in ok) state="configured, $auth" ;; *) state="not configured ($CONF)" ;; esac
case "$REACHABLE" in yes) reach=reachable ;; no) reach="NOT reachable${REACH_ERR:+: $REACH_ERR}" ;; *) reach='reachability not checked' ;; esac
say "remote $remote (remoteType $remote_type${site_url:+, site $site_url}): $state; $reach"
if [ "$FUSE" = yes ]; then say "FUSE: usable ($FUSE_WHY)"; else say "FUSE: not usable ($FUSE_WHY)"; fi
if [ "$RCLONE_MOUNTED" = yes ]; then state="rclone mount${MOUNT_PID:+ (pid $MOUNT_PID)}"
elif [ -n "${MOUNT_PID:-}" ]; then state="rclone mount starting (pid $MOUNT_PID)"
else state='not mounted'; fi
if [ "$LINKED" = yes ]; then say "mount point $mount_point -> $REAL: $state"; else say "mount point $mount_point: $state"; fi
if [ "$RCLONE_MOUNTED" = yes ]; then
case "$EMPTY" in yes) state=empty ;; no) state='not empty' ;; *) state='cannot be listed' ;; esac
say "contents: $state; writable: $WRITABLE"
if [ "$VFS_OK" = yes ] && [ -n "$VFS_PENDING" ]; then
say "VFS cache ($VFS_CACHE): uploads in progress $VFS_INPROG, queued $VFS_QUEUED, failed ${VFS_ERRORED:-0}"
elif [ "$VFS_OK" = yes ]; then
say "VFS cache ($VFS_CACHE): no upload queue to read (cache mode off?): pending uploads unknown"
else
q="remote control on $rc_addr does not answer"
say "VFS cache: $q: pending uploads unknown"
fi
fi
print_verdict
}
print_verdict() {
case "$VERDICT" in
ok) case "$MODE_USED" in
sync) say "ok: the folder is synced and writable" ;;
mount) say "ok: the remote is mounted and writable${VFS_PENDING:+ ($VFS_PENDING upload(s) pending)}" ;;
*) say "ok: the folder is mounted and writable" ;;
esac ;;
empty) say "ok, but empty: ${HINT#*: }" ;;
*) say "not usable ($VERDICT): ${HINT:-$WHY}" ;;
esac
}
# ------------------------------------------------------------------ sync ----
# ensure_local <folder>: the sync's local folder exists and this user can write it.
ensure_local() {
local d="$1"
if [ ! -d "$d" ]; then
mkdir -p -- "$d" 2>/dev/null || as_root mkdir -p -- "$d" || { say "cannot create $d"; return 1; }
fi
if [ ! -w "$d" ] || [ "$(stat -c %u "$d" 2>/dev/null)" != "$(id -u)" ]; then
as_root chown "$(id -u):$(id -g)" "$d" 2>/dev/null || true
fi
[ -w "$d" ] || { say "$(id -un 2>/dev/null || id -u) cannot write to $d"; return 1; }
}
# do_sync [--resync] [--force] [--timer]: one bisync. Exit 0 ok; 1 failed (a later run may
# succeed); 7 critical (bisync wants a --resync); 2 usage; 3 cannot sync here (mode, sign-in,
# rclone, folder); 4 another sync is running.
do_sync() {
local resync=no force=no timer=no why_resync='' a child rc start secs result note pair stopping=no i
for a in "$@"; do
case "$a" in
--resync) resync=yes; why_resync='asked for' ;;
--force) force=yes ;;
--timer) timer=yes ;;
*) echo "cloud-folder: sync: unknown argument '$a' (--resync, --force)" >&2; return 2 ;;
esac
done
resolve
if [ "$MODE_USED" != sync ]; then say "nothing to sync: mode $MODE_USED ($WHY)"; return 3; fi
if [ "$CONF" != ok ]; then say "no remote to sync with ($CONF): run task cloud-folder:login"; return 3; fi
command -v rclone >/dev/null 2>&1 || { say 'rclone is not on PATH'; return 3; }
prepare_state || { say "the state folder $state_dir is not writable"; return 3; }
ensure_local "$REAL" || return 3
if ! take_lock "$run_dir/sync.pid"; then
if [ "$timer" = yes ]; then say "timer: skipped, a sync is already running (pid $(pid_of "$run_dir/sync.pid"))"
else say "a sync is already running (pid $(pid_of "$run_dir/sync.pid")); try again when it ends (task cloud-folder:status)"; fi
return 4
fi
# shellcheck disable=SC2064 # the lock path is fixed now
trap "drop_lock '$run_dir/sync.pid'" EXIT
pair="$remote -> $REAL"
if [ "$resync" = no ]; then
if [ ! -f "$REAL/$marker_name" ]; then resync=yes; why_resync="first sync of $REAL"
elif [ "$(cat "$state_dir/bisync-pair" 2>/dev/null)" != "$pair" ]; then resync=yes; why_resync='the remote or the folder changed'; fi
fi
local -a args=(bisync "$remote" "$REAL" --workdir "$state_dir/bisync" --max-lock 5m --resilient --recover
--max-delete 50 --exclude "/$marker_name" --log-file "$state_dir/sync.log" --log-level INFO)
[ "$resync" = yes ] && args+=(--resync)
[ "$force" = yes ] && args+=(--force)
(umask 077; [ -f "$state_dir/sync.log" ] && mv -f "$state_dir/sync.log" "$state_dir/sync.log.1"; : > "$state_dir/sync.log")
touch "$run_dir/sync.started"
start="$(date +%s)"
say "sync: $remote <-> $REAL${why_resync:+ (--resync: $why_resync)}"
RCLONE_CONFIG="$conf" RCLONE_CACHE_DIR="$state_dir/cache" rclone "${args[@]}" </dev/null >>"$state_dir/sync.log" 2>&1 &
child=$!
# A stop (the timer's TERM, or Ctrl-C) asks bisync for its graceful shutdown (SIGINT), then
# after the grace period ends it with SIGTERM.
trap 'stopping=yes; kill -INT "$child" 2>/dev/null' TERM INT
wait "$child" 2>/dev/null; rc=$?
while alive "$child"; do
if [ "$stopping" = yes ]; then
i=0
while alive "$child" && [ "$i" -lt $((grace * 2)) ]; do sleep 0.5; i=$((i + 1)); done
alive "$child" && kill -TERM "$child" 2>/dev/null
fi
wait "$child" 2>/dev/null; rc=$?
done
trap - TERM INT
secs=$(( $(date +%s) - start ))
if [ "$rc" -eq 0 ] && [ "$stopping" = no ]; then result=ok
elif [ "$stopping" = yes ]; then result=interrupted
elif [ "$rc" -eq 7 ]; then result=critical
else result=failed; fi
# The first error that names a cause (not bisync's closing "aborted" lines), else the last one.
note="$(grep -E 'ERROR|Safety abort' "$state_dir/sync.log" 2>/dev/null | grep -v -E 'retryable|Bisync aborted' | head -n 1)"
[ -n "$note" ] || note="$(grep -E 'ERROR|Failed' "$state_dir/sync.log" 2>/dev/null | tail -n 1)"
note="$(printf '%s' "$note" | sed -E 's/^[0-9\/]+ [0-9:]+ //' | tr -d '\r' | cut -c1-300)"
[ "$result" = ok ] && note=''
(umask 077
{
printf 'time=%s\n' "$(date -u -d "@$start" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u +%Y-%m-%dT%H:%M:%SZ)"
printf 'result=%s\nrc=%s\nresync=%s\nseconds=%s\nnote=%s\n' "$result" "$rc" "$resync" "$secs" "$note"
} > "$state_dir/last-sync.tmp" && mv -f "$state_dir/last-sync.tmp" "$state_dir/last-sync")
if [ "$result" = ok ]; then
touch -r "$run_dir/sync.started" "$state_dir/last-ok"
printf '%s\n' "$pair" > "$REAL/$marker_name"
printf '%s\n' "$pair" > "$state_dir/bisync-pair"
say "sync ok in ${secs}s${why_resync:+ (resync)}"
return 0
fi
say "sync $result (rclone exit $rc)${note:+: $note}; log: $state_dir/sync.log"
case "$note" in
*'too many deletes'*) say "bisync's delete guard: restore the files, or if the deletion is meant, task cloud-folder:sync -- --force" ;;
*'Empty current Path'*) say 'one side is empty and bisync will not empty the other: if the folder was emptied by mistake, task cloud-folder:sync -- --resync brings the files back' ;;
esac
[ "$rc" -eq 7 ] && return 7
return 1
}
# ----------------------------------------------------------------- timer ----
start_timer() {
local secs p i
resolve
if [ "$MODE_USED" != sync ]; then say "timer: not started (mode $MODE_USED)"; return 0; fi
if [ "$CONF" != ok ]; then say 'timer: not started, no remote is configured yet (task cloud-folder:login starts it)'; return 0; fi
if ! secs="$(interval_seconds)"; then say "timer: not started, syncInterval '$sync_interval' is not a duration (15m, 900s, 1h, 0)"; return 1; fi
if [ "$secs" -eq 0 ]; then say 'timer: off (syncInterval 0): sync on demand with task cloud-folder:sync'; return 0; fi
p="$(pid_of "$run_dir/loop.pid")"
if ours "$p"; then say "timer: already running (pid $p, every $sync_interval)"; return 0; fi
prepare_state || { say "timer: not started, the state folder $state_dir is not writable"; return 1; }
if [ -f "$state_dir/timer.log" ] && [ "$(stat -c %s "$state_dir/timer.log" 2>/dev/null || echo 0)" -gt 1048576 ]; then
mv -f "$state_dir/timer.log" "$state_dir/timer.log.1"
fi
if command -v setsid >/dev/null 2>&1; then
(umask 077; setsid bash "$self" run </dev/null >>"$state_dir/timer.log" 2>&1 &)
else
(umask 077; nohup bash "$self" run </dev/null >>"$state_dir/timer.log" 2>&1 &)
fi
for i in 1 2 3 4 5 6 7 8 9 10; do
p="$(pid_of "$run_dir/loop.pid")"
ours "$p" && break
sleep 0.3
done
if ours "$p"; then say "timer: started (pid $p, every $sync_interval; the first sync runs now); log: $state_dir/timer.log"; return 0; fi
say "timer: did not start; see $state_dir/timer.log"
return 1
}
wait_child() { # the loop's child: wait through signals until it is gone
wait "$1" 2>/dev/null
while alive "$1"; do wait "$1" 2>/dev/null; done
}
run_loop() {
local secs child='' stopping=no
secs="$(interval_seconds)" || { say "timer: syncInterval '$sync_interval' is not a duration"; return 1; }
[ "$secs" -eq 0 ] && { say 'timer: syncInterval 0, no timer'; return 0; }
prepare_state || return 1
if ! take_lock "$run_dir/loop.pid"; then say "timer: already running (pid $(pid_of "$run_dir/loop.pid"))"; return 0; fi
# shellcheck disable=SC2064 # the lock path is fixed now
trap "drop_lock '$run_dir/loop.pid'" EXIT
trap 'stopping=yes; [ -n "$child" ] && kill -TERM "$child" 2>/dev/null' TERM INT HUP
say "timer: started $(date -u +%Y-%m-%dT%H:%M:%SZ), pid $$, every $sync_interval"
while [ "$stopping" = no ]; do
bash "$self" sync --timer &
child=$!; wait_child "$child"; child=''
[ "$stopping" = yes ] && break
sleep "$secs" &
child=$!; wait_child "$child"; child=''
done
say "timer: stopped $(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
stop_timer() {
local p i max
max="${CLOUD_FOLDER_STOP_WAIT:-120}"
p="$(pid_of "$run_dir/loop.pid")"
if ! ours "$p"; then
[ -n "$p" ] && rm -f -- "$run_dir/loop.pid"
say 'timer: not running'
return 0
fi
kill -TERM "$p" 2>/dev/null
i=0
while ours "$p" && [ "$i" -lt $((max * 2)) ]; do sleep 0.5; i=$((i + 1)); done
if ours "$p"; then say "timer: still finishing a sync after ${max}s (pid $p); task cloud-folder:status shows when it ends"; return 1; fi
say 'timer: stopped'
}
# ----------------------------------------------------------------- mount ----
# start_mount: `rclone mount` of the remote on the folder, detached (its own session), PID file in
# the volume; idempotent. The VFS cache (mode writes, so the upload queue can be read; finding 5)
# lives in the volume; the remote control listens on localhost only and has no credentials, so
# only read-only methods such as vfs/stats answer. The config and token are read from the file.
start_mount() {
local p i
resolve
if [ "$MODE_USED" != mount ]; then say "mount: not started (mode $MODE_USED)"; return 0; fi
if [ "$CONF" != ok ]; then say 'mount: not started, no remote is configured yet (task cloud-folder:login starts it)'; return 0; fi
command -v rclone >/dev/null 2>&1 || { say 'mount: not started, rclone is not on PATH'; return 3; }
if [ "$RCLONE_MOUNTED" = yes ]; then say "mount: already mounted at $REAL"; return 0; fi
p="$(pid_of "$run_dir/mount.pid")"
if mount_ours "$p"; then say "mount: rclone (pid $p) is already starting; task cloud-folder:status shows when it is up"; return 0; fi
if [ "$FUSE" = no ]; then say "mount: not started, FUSE is not usable: $FUSE_WHY"; return 1; fi
if [ "$MOUNTED" = yes ]; then say "mount: not started, something else is mounted at $REAL"; return 1; fi
prepare_state || { say "mount: not started, the state folder $state_dir is not writable"; return 1; }
ensure_local "$REAL" || return 1
if [ -n "$(find -H "$REAL" -mindepth 1 -maxdepth 1 -print -quit 2>/dev/null)" ]; then
say "mount: not started, $REAL is not empty and rclone does not mount over files (a sync copy? sync it, then move it away)"
return 1
fi
if [ -f "$state_dir/mount.log" ] && [ "$(stat -c %s "$state_dir/mount.log" 2>/dev/null || echo 0)" -gt 1048576 ]; then
mv -f "$state_dir/mount.log" "$state_dir/mount.log.1"
fi
local -a args=(mount "$remote" "$REAL" --vfs-cache-mode writes --cache-dir "$state_dir/cache"
--rc --rc-addr "$rc_addr" --log-file "$state_dir/mount.log" --log-level INFO)
# Not --daemon: the PID must be this process's, for the PID file and the stop.
if command -v setsid >/dev/null 2>&1; then
(umask 077; RCLONE_CONFIG="$conf" setsid rclone "${args[@]}" </dev/null >/dev/null 2>&1 & echo "$!" > "$run_dir/mount.pid")
else
(umask 077; RCLONE_CONFIG="$conf" nohup rclone "${args[@]}" </dev/null >/dev/null 2>&1 & echo "$!" > "$run_dir/mount.pid")
fi
p="$(pid_of "$run_dir/mount.pid")"
i=0
while [ "$i" -lt $((mount_wait * 4)) ]; do
[ "$(mount_fstype "$REAL")" = fuse.rclone ] && { say "mount: $remote mounted at $REAL (pid $p, VFS cache writes, remote control $rc_addr); log: $state_dir/mount.log"; return 0; }
alive "$p" || break
sleep 0.25; i=$((i + 1))
done
if alive "$p"; then say "mount: rclone (pid $p) has not mounted $REAL after ${mount_wait}s; task cloud-folder:status shows when it does; log: $state_dir/mount.log"; return 1; fi
rm -f -- "$run_dir/mount.pid"
say "mount: rclone exited without mounting: $(grep -E 'ERROR|CRITICAL|Fatal' "$state_dir/mount.log" 2>/dev/null | tail -n 1 | sed -E 's/^[0-9\/]+ [0-9:]+ //' | cut -c1-300); log: $state_dir/mount.log"
return 1
}
# stop_mount [--force]: unmount once the upload queue is empty (waiting up to
# CLOUD_FOLDER_STOP_WAIT seconds, default 120); refuse while files are pending or the queue cannot
# be read, unless --force (rclone uploads what is left in the VFS cache at the next mount).
stop_mount() {
local force=no a p i max rc=0
max="${CLOUD_FOLDER_STOP_WAIT:-120}"
for a in "$@"; do
case "$a" in --force) force=yes ;; *) echo "cloud-folder: unmount: unknown argument '$a' (--force)" >&2; return 2 ;; esac
done
resolve
p="$(pid_of "$run_dir/mount.pid")"; mount_ours "$p" || p=''
if [ "$RCLONE_MOUNTED" = no ] && [ -z "$p" ]; then
rm -f -- "$run_dir/mount.pid"
say 'mount: not mounted'
return 0
fi
if [ "$force" = no ] && [ "$RCLONE_MOUNTED" = yes ]; then
wait_uploads "$max" || rc=$?
if [ "$rc" -eq 2 ]; then
say "mount: not unmounted, the upload queue cannot be read (remote control on $rc_addr does not answer); task cloud-folder:unmount -- --force unmounts anyway (queued files upload at the next mount)"
return 1
fi
if [ "$rc" -eq 1 ]; then
say "mount: not unmounted, $VFS_PENDING upload(s) still pending after ${max}s; wait and try again, or task cloud-folder:unmount -- --force (they upload at the next mount)"
return 1
fi
fi
if [ "$RCLONE_MOUNTED" = yes ]; then
if [ -n "$FUSERMOUNT" ]; then "$FUSERMOUNT" -u "$REAL" 2>/dev/null || as_root umount "$REAL" 2>/dev/null
else as_root umount "$REAL" 2>/dev/null; fi
fi
if [ -n "$p" ]; then
i=0
while alive "$p" && [ "$i" -lt 40 ]; do sleep 0.25; i=$((i + 1)); done
alive "$p" && kill -TERM "$p" 2>/dev/null
i=0
while alive "$p" && [ "$i" -lt 40 ]; do sleep 0.25; i=$((i + 1)); done
fi
if [ "$(mount_fstype "$REAL")" = fuse.rclone ]; then say "mount: $REAL is still mounted (busy? a shell or editor inside it)"; return 1; fi
rm -f -- "$run_dir/mount.pid"
say "mount: unmounted $REAL"
}
# start_any / stop_any: what `start` and `stop` mean in the mode in use.
start_any() { resolve; if [ "$MODE_USED" = mount ]; then start_mount; else start_timer; fi; }
stop_any() { resolve; if [ "$MODE_USED" = mount ]; then stop_mount "$@"; else stop_timer; fi; }
# shutdown_check [SECONDS]: exit 1 while a sync runs (after waiting) or local changes wait; in
# mount mode, while uploads are pending (after waiting) or the queue cannot be read.
shutdown_check() {
local max="${1:-${CLOUD_FOLDER_SHUTDOWN_WAIT:-60}}" waited=0 p rc=0
case "$max" in '' | *[!0-9]*) echo "cloud-folder: shutdown-check: SECONDS must be a number" >&2; return 2 ;; esac
resolve
if [ "$MODE_USED" = mount ]; then shutdown_check_mount "$max"; return $?; fi
if [ "$MODE_USED" != sync ]; then say "shutdown check: mode $MODE_USED, no sync in flight"; return 0; fi
p="$(pid_of "$run_dir/sync.pid")"
if ours "$p"; then
say "shutdown check: a sync is running (pid $p); waiting up to ${max}s for it to end"
while ours "$p" && [ "$waited" -lt "$max" ]; do sleep 1; waited=$((waited + 1)); done
fi
if ours "$p"; then
say "REFUSE: a sync is still running (pid $p) after ${max}s; a stop now would cut it short. Wait and run the check again (task cloud-folder:status), or stop with FORCE=1."
rc=1
fi
read_record
local n
n="$(pending_count "$REAL")"
if [ "$CONF" = ok ] && [ "$n" -gt 0 ]; then
if [ -n "$LAST_TIME" ]; then
say "REFUSE: $n file(s) in $REAL changed since the last successful sync started; run task cloud-folder:sync first, or stop with FORCE=1."
else
say "REFUSE: $REAL has $n file(s) and has never been synced; run task cloud-folder:sync first, or stop with FORCE=1."
fi
rc=1
elif [ "$CONF" != ok ] && [ "$n" -gt 0 ]; then
say "note: $REAL has $n file(s) and no remote is configured; they live only in this container."
fi
if [ -n "$LAST_RESULT" ] && [ "$LAST_RESULT" != ok ]; then say "note: the last sync ended $LAST_RESULT (task cloud-folder:status)."; fi
[ "$rc" -eq 0 ] && say "shutdown check: no sync running, nothing changed since the last sync${LAST_TIME:+ ($LAST_TIME)}: safe to stop"
return "$rc"
}
shutdown_check_mount() {
local max="$1" rc=0
if [ "$RCLONE_MOUNTED" = no ]; then say "shutdown check: mode mount, nothing mounted: no upload in flight"; return 0; fi
if command -v rclone >/dev/null 2>&1; then
vfs_query
if [ "$VFS_OK" = yes ] && [ -n "$VFS_PENDING" ] && [ "$VFS_PENDING" -gt 0 ]; then
say "shutdown check: $VFS_PENDING upload(s) pending; waiting up to ${max}s for them"
fi
wait_uploads "$max" || rc=$?
else
rc=2
fi
case "$rc" in
2) say "REFUSE: the upload queue cannot be read (rclone's remote control on $rc_addr does not answer), so a stop could cut uploads short; task cloud-folder:status, or stop with FORCE=1."; return 1 ;;
1) say "REFUSE: $VFS_PENDING upload(s) still pending after ${max}s; wait and run the check again (task cloud-folder:status), or stop with FORCE=1 (they upload at the next mount)."; return 1 ;;
esac
[ -n "$VFS_ERRORED" ] && [ "$VFS_ERRORED" -gt 0 ] && say "note: $VFS_ERRORED file(s) failed to upload (task cloud-folder:status)."