Repository navigation
Expand file tree
/
Copy pathmultidisk_filebalancer.py
More file actions
4944 lines (4382 loc) · 194 KB
/
Copy pathmultidisk_filebalancer.py
File metadata and controls
4944 lines (4382 loc) · 194 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
import os
from datetime import datetime, timedelta
import shutil
import yaml
import time
import requests
import threading
import asyncio
import asyncssh
import stat
import errno
import sys
import hashlib
import signal
import atexit
import subprocess
import logging
import platform
from asyncssh.sftp import SFTPName, SFTPAttrs, FXF_READ, FXF_WRITE, FXF_APPEND, FXF_CREAT, FXF_TRUNC
from flask import Flask, jsonify, request, send_from_directory
logger = logging.getLogger("multidisk_filebalancer.vfs")
def _is_wsl():
if os.environ.get("WSL_DISTRO_NAME") or os.environ.get("WSL_INTEROP"):
return True
for path in ("/proc/sys/kernel/osrelease", "/proc/version"):
try:
with open(path, "r", encoding="utf-8", errors="ignore") as f:
if "microsoft" in (f.read() or "").lower():
return True
except OSError:
continue
return False
def _ensure_linux():
if not sys.platform.lower().startswith("linux"):
raise SystemExit("This tool is Linux-only. Run it on a Linux VM (VirtualBox/VMware).")
if _is_wsl():
raise SystemExit("WSL is not supported. Run this tool in a Linux VM (VirtualBox/VMware).")
def try_import_fuse():
global FUSE, Operations, FuseOSError
try:
from fuse import FUSE, Operations, FuseOSError
return True
except (ImportError, OSError):
FUSE = None
Operations = object
class FuseOSError(Exception):
pass
return False
FUSE = None
Operations = object
class FuseOSError(Exception):
pass
try_import_fuse()
def has_admin_privileges():
try:
geteuid = getattr(os, "geteuid", None)
if geteuid is None:
return False
return geteuid() == 0
except Exception:
return False
def is_privilege_error_text(text):
message = str(text).lower()
privilege_markers = [
"permission denied",
"access is denied",
"administrator",
"admin privileges",
"requires elevation",
"operation not permitted",
"must be run as root",
"not in the sudoers",
"authentication is required",
"insufficient privileges",
]
for marker in privilege_markers:
if marker in message:
return True
return False
def admin_restart_instruction():
return "Restart this program with sudo/root privileges and try again."
def detect_fuse_install_strategy():
_ensure_linux()
if shutil.which("apt-get"):
return "sudo apt-get update && (sudo apt-get install -y fuse3 libfuse3-3 || sudo apt-get install -y fuse libfuse2)"
if shutil.which("dnf"):
return "sudo dnf install -y fuse3 fuse3-libs fuse-libs"
if shutil.which("pacman"):
return "sudo pacman -S --noconfirm fuse3 || sudo pacman -S --noconfirm fuse2"
return "Install libfuse via your distro package manager (e.g. apt/dnf/pacman)."
def _is_mount_active(path):
if not path:
return False
try:
if not os.path.exists(path):
return False
return bool(os.path.ismount(path))
except Exception:
return False
def _ensure_fuse_user_allow_other(webhook_url):
_ensure_linux()
fuse_conf = "/etc/fuse.conf"
try:
if not os.path.exists(fuse_conf):
return True
except Exception:
return True
try:
with open(fuse_conf, "r", encoding="utf-8", errors="ignore") as f:
lines = f.read().splitlines()
except Exception as exc:
if has_admin_privileges():
print_and_discord(f"FUSE warning: could not read {fuse_conf}: {exc}", webhook_url)
return False
already_enabled = False
for line in lines:
if line.strip() == "user_allow_other":
already_enabled = True
break
if already_enabled:
return True
updated = []
changed = False
for line in lines:
stripped = line.strip()
if stripped.startswith("#") and stripped.lstrip("#").strip() == "user_allow_other":
updated.append("user_allow_other")
changed = True
else:
updated.append(line)
if not changed:
if updated and updated[-1].strip() != "":
updated.append("")
updated.append("user_allow_other")
changed = True
if not changed:
return True
if not has_admin_privileges():
print_and_discord("FUSE hint: enable 'user_allow_other' in /etc/fuse.conf (run as root).", webhook_url)
return False
try:
with open(fuse_conf, "w", encoding="utf-8") as f:
f.write("\n".join(updated).rstrip("\n") + "\n")
return True
except Exception as exc:
print_and_discord(f"FUSE warning: could not update {fuse_conf}: {exc}", webhook_url)
return False
def print_startup_preflight(
webhook_url,
fuse_enabled,
webdav_enabled,
sftp_enabled,
nfs_enabled,
fuse_mount_point,
):
import platform
os_name = platform.system()
os_release = platform.release()
py_version = platform.python_version()
if has_admin_privileges():
admin_mode = "yes"
else:
admin_mode = "no"
if FUSE is not None:
fuse_loaded = "yes"
else:
fuse_loaded = "no"
if fuse_enabled:
fuse_required = "yes"
else:
fuse_required = "no"
if webdav_enabled:
webdav_mode = "yes"
else:
webdav_mode = "no"
if sftp_enabled:
sftp_mode = "yes"
else:
sftp_mode = "no"
if nfs_enabled:
nfs_mode = "yes"
else:
nfs_mode = "no"
install_strategy = detect_fuse_install_strategy()
print_and_discord("========== Startup preflight ==========", webhook_url)
print_and_discord(f"OS: {os_name} {os_release}", webhook_url)
print_and_discord(f"Python: {py_version}", webhook_url)
print_and_discord(f"Admin/root privileges: {admin_mode}", webhook_url)
print_and_discord(
f"Features enabled -> FUSE: {fuse_required}, WebDAV: {webdav_mode}, SFTP: {sftp_mode}, NFS: {nfs_mode}",
webhook_url
)
print_and_discord(f"FUSE python binding loaded: {fuse_loaded}", webhook_url)
if fuse_enabled:
print_and_discord(f"FUSE mount point: {fuse_mount_point}", webhook_url)
print_and_discord(f"FUSE installer strategy: {install_strategy}", webhook_url)
print_and_discord("=======================================", webhook_url)
def install_libfuse():
_ensure_linux()
system = "linux"
print(f"Attempting to install libfuse for {system}...")
last_error = ""
def run_cmd(cmd, shell=False):
nonlocal last_error
result = subprocess.run(cmd, check=True, shell=shell, capture_output=True, text=True)
stderr = (result.stderr or "").strip()
stdout = (result.stdout or "").strip()
last_error = stderr or stdout
def install_python_fuse_package():
nonlocal last_error
pip_cmd = [sys.executable, "-m", "pip", "install", "fusepy"]
result = subprocess.run(pip_cmd, capture_output=True, text=True)
if result.returncode == 0:
return True
last_error = (result.stderr or result.stdout or "").strip()
pip_cmd_break = [sys.executable, "-m", "pip", "install", "fusepy", "--break-system-packages"]
result_break = subprocess.run(pip_cmd_break, capture_output=True, text=True)
if result_break.returncode == 0:
return True
last_error = (result_break.stderr or result_break.stdout or last_error).strip()
return False
try:
if shutil.which("apt-get"):
run_cmd(["sudo", "apt-get", "update"])
try:
run_cmd(["sudo", "apt-get", "install", "-y", "fuse3", "libfuse3-3"])
except subprocess.CalledProcessError:
run_cmd(["sudo", "apt-get", "install", "-y", "fuse", "libfuse2"])
elif shutil.which("dnf"):
run_cmd(["sudo", "dnf", "install", "-y", "fuse3", "fuse3-libs", "fuse-libs"])
elif shutil.which("pacman"):
try:
run_cmd(["sudo", "pacman", "-S", "--noconfirm", "fuse3"])
except subprocess.CalledProcessError:
run_cmd(["sudo", "pacman", "-S", "--noconfirm", "fuse2"])
else:
print("No supported package manager (apt, dnf, pacman) found on Linux.")
return False, "No supported Linux package manager found for FUSE installation.", False
if not install_python_fuse_package():
needs_admin = is_privilege_error_text(last_error) or not has_admin_privileges()
return False, (last_error or "Could not install Python package 'fusepy'."), needs_admin
if try_import_fuse():
return True, "", False
return False, "FUSE dependencies were installed but Python still cannot load FUSE on this OS.", False
except subprocess.CalledProcessError as e:
error_parts = [str(e), getattr(e, "stderr", ""), getattr(e, "stdout", ""), last_error]
filtered_parts = []
for part in error_parts:
if part:
filtered_parts.append(part)
combined_error = "\n".join(filtered_parts).strip()
needs_admin = is_privilege_error_text(combined_error) or not has_admin_privileges()
print(f"Automatic installation failed: {combined_error}")
return False, combined_error, needs_admin
except Exception as e:
error_text = str(e)
needs_admin = is_privilege_error_text(error_text) or not has_admin_privileges()
print(f"Automatic installation failed: {error_text}")
return False, error_text, needs_admin
current_dir = os.getcwd()
config_path = os.path.join(current_dir, "config.yml")
_webpanel_thread = None
_webpanel_app = None
_stats_lock = threading.Lock()
_stats = {
"start_ts": time.time(),
"files_moved_total": 0,
"bytes_moved_total": 0,
"cleanup_actions_total": 0,
"errors_total": 0,
"last_action": None,
"moves_series": [],
"max_series_points": 120,
"recent_actions": [],
"max_recent_actions": 80,
"cycle_start_ts": None,
"cycle_start_totals": None,
"cycle": {
"last_start_ts": None,
"last_end_ts": None,
"last_duration_seconds": 0,
"last_moved_files": 0,
"last_moved_bytes": 0,
"last_cleanup_actions": 0,
"last_errors": 0,
"next_run_ts": None,
},
}
_vfs_base_paths = []
_vfs_cache_lock = threading.RLock()
_vfs_dir_cache = {}
_vfs_cache_ttl_seconds = 2.0
_file_operation_lock = threading.RLock()
_vfs_dedupe_duplicate_names = False
# Registry of Docker containers started by this process.
# Each entry is a dict with keys: 'name' and 'docker_exe' (usually "docker").
_managed_docker_containers = []
_managed_docker_lock = threading.Lock()
_managed_nfs_export_paths = []
_managed_nfs_lock = threading.Lock()
_automount_thread = None
_pkg_install_lock = threading.Lock()
_apt_updated_once = False
_pkg_install_attempted = {}
def _register_managed_nfs_export_path(export_path):
with _managed_nfs_lock:
if export_path and export_path not in _managed_nfs_export_paths:
_managed_nfs_export_paths.append(export_path)
def _sudo_prefix():
if has_admin_privileges():
return []
if shutil.which("sudo"):
return ["sudo"]
return []
def _run_capture(cmd, timeout=30):
result = subprocess.run(
[str(c) for c in cmd],
capture_output=True,
text=True,
timeout=timeout,
)
stdout = (result.stdout or "").strip()
stderr = (result.stderr or "").strip()
combined = "\n".join([p for p in (stdout, stderr) if p]).strip()
return result.returncode, combined
def _run_stream(cmd, timeout=None):
start = time.time()
proc = subprocess.Popen(
[str(c) for c in cmd],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
)
lines = []
try:
while True:
if timeout is not None and (time.time() - start) > timeout:
try:
proc.kill()
except Exception:
pass
return 124, "\n".join(lines[-200:]).strip()
line = proc.stdout.readline() if proc.stdout is not None else ""
if not line:
if proc.poll() is not None:
break
time.sleep(0.05)
continue
print(line, end="")
lines.append(line.rstrip("\n"))
if len(lines) > 400:
lines = lines[-200:]
finally:
try:
if proc.stdout is not None:
proc.stdout.close()
except Exception:
pass
return proc.returncode or 0, "\n".join(lines[-200:]).strip()
def _selinux_enforcing():
try:
enforce_path = "/sys/fs/selinux/enforce"
if os.path.exists(enforce_path):
with open(enforce_path, "r", encoding="utf-8", errors="ignore") as f:
return (f.read() or "").strip() == "1"
except Exception:
pass
try:
if shutil.which("getenforce"):
rc, out = _run_capture(["getenforce"], timeout=5)
return rc == 0 and (out or "").strip().lower() == "enforcing"
except Exception:
pass
return False
def _selinux_prepare_nfs_export(export_root, webhook_url):
if not _selinux_enforcing():
return
if not has_admin_privileges():
print_and_discord("SELinux is enforcing. NFS export may be blocked unless SELinux booleans are enabled. Run as root to auto-fix.", webhook_url)
return
if not shutil.which("setsebool"):
return
try:
_run_capture(_sudo_prefix() + ["setsebool", "-P", "nfs_export_all_rw", "1"], timeout=60)
if str(export_root).startswith("/home/"):
_run_capture(_sudo_prefix() + ["setsebool", "-P", "use_nfs_home_dirs", "1"], timeout=60)
except Exception:
pass
try:
if shutil.which("chcon"):
_run_capture(_sudo_prefix() + ["chcon", "-Rt", "public_content_rw_t", export_root], timeout=120)
except Exception:
pass
def _ensure_nfs_server_installed(webhook_url):
if shutil.which("exportfs"):
return True
last_error = ""
try:
if shutil.which("apt-get"):
rc, out = _run_capture(_sudo_prefix() + ["apt-get", "update"], timeout=180)
if rc != 0:
last_error = out
rc, out = _run_capture(_sudo_prefix() + ["apt-get", "install", "-y", "nfs-kernel-server"], timeout=300)
if rc != 0:
last_error = out
elif shutil.which("dnf"):
rc, out = _run_capture(_sudo_prefix() + ["dnf", "install", "-y", "nfs-utils"], timeout=300)
if rc != 0:
last_error = out
elif shutil.which("yum"):
rc, out = _run_capture(_sudo_prefix() + ["yum", "install", "-y", "nfs-utils"], timeout=300)
if rc != 0:
last_error = out
elif shutil.which("pacman"):
rc, out = _run_capture(_sudo_prefix() + ["pacman", "-S", "--noconfirm", "nfs-utils"], timeout=300)
if rc != 0:
last_error = out
else:
print_and_discord(
"NFS server error: no supported package manager found (apt, dnf, yum, pacman). Install NFS server packages manually.",
webhook_url,
)
return False
except Exception as e:
last_error = str(e)
if not shutil.which("exportfs"):
needs_admin = is_privilege_error_text(last_error) or not has_admin_privileges()
if needs_admin:
print_and_discord(
"NFS server error: missing exportfs/nfs tools and installation failed. Run this tool as root or ensure sudo works.",
webhook_url,
)
else:
print_and_discord(
f"NFS server error: missing exportfs/nfs tools and installation failed: {last_error}",
webhook_url,
)
return False
return True
def _ensure_os_packages_installed(packages, webhook_url):
global _apt_updated_once
if not packages:
return True
pkgs = [str(p).strip() for p in packages if str(p).strip()]
if not pkgs:
return True
with _pkg_install_lock:
key = "|".join(pkgs)
now = time.time()
last = _pkg_install_attempted.get(key)
if last is not None and (now - float(last)) < 60.0:
return False
_pkg_install_attempted[key] = now
last_error = ""
try:
if shutil.which("apt-get"):
if not _apt_updated_once:
rc, out = _run_capture(_sudo_prefix() + ["apt-get", "update"], timeout=180)
if rc == 0:
_apt_updated_once = True
else:
last_error = out
rc, out = _run_capture(_sudo_prefix() + ["apt-get", "install", "-y"] + pkgs, timeout=300)
if rc != 0:
last_error = out
elif shutil.which("dnf"):
rc, out = _run_capture(_sudo_prefix() + ["dnf", "install", "-y"] + pkgs, timeout=300)
if rc != 0:
last_error = out
elif shutil.which("yum"):
rc, out = _run_capture(_sudo_prefix() + ["yum", "install", "-y"] + pkgs, timeout=300)
if rc != 0:
last_error = out
elif shutil.which("pacman"):
rc, out = _run_capture(_sudo_prefix() + ["pacman", "-S", "--noconfirm"] + pkgs, timeout=300)
if rc != 0:
last_error = out
else:
print_and_discord(
f"[AUTOMOUNT] No supported package manager found to install: {', '.join(pkgs)}",
webhook_url,
)
return False
except Exception as exc:
last_error = str(exc)
if last_error:
needs_admin = is_privilege_error_text(last_error) or not has_admin_privileges()
if needs_admin:
print_and_discord(
f"[AUTOMOUNT] OS package installation failed (admin required): {', '.join(pkgs)}",
webhook_url,
)
else:
print_and_discord(
f"[AUTOMOUNT] OS package installation failed: {', '.join(pkgs)}\n{last_error}",
webhook_url,
)
return False
return True
def _ensure_binary_available(binary, package_options, webhook_url):
if shutil.which(binary):
return True
for pkgs in package_options or []:
ok = _ensure_os_packages_installed(pkgs, webhook_url)
if ok and shutil.which(binary):
return True
return bool(shutil.which(binary))
def _cleanup_managed_nfs_exports():
with _managed_nfs_lock:
export_paths = list(_managed_nfs_export_paths)
_managed_nfs_export_paths.clear()
for export_path in export_paths:
try:
if not export_path:
continue
if export_path == "/etc/exports":
begin = "# multidisk_filebalancer BEGIN\n"
end = "# multidisk_filebalancer END\n"
try:
with open(export_path, "r", encoding="utf-8", errors="ignore") as f:
existing = f.read() or ""
if begin in existing and end in existing:
pre, _, rest = existing.partition(begin)
_, _, post = rest.partition(end)
updated = (pre.rstrip("\n") + "\n" + post.lstrip("\n")).strip("\n") + "\n"
with open(export_path, "w", encoding="utf-8") as f:
f.write(updated)
except OSError:
pass
continue
if os.path.exists(export_path):
os.remove(export_path)
except Exception:
pass
if shutil.which("exportfs"):
try:
_run_capture(_sudo_prefix() + ["exportfs", "-ua"], timeout=60)
except Exception:
pass
try:
_run_capture(_sudo_prefix() + ["exportfs", "-ra"], timeout=60)
except Exception:
pass
def _register_managed_container(docker_exe, container_name):
with _managed_docker_lock:
_managed_docker_containers.append({'docker_exe': docker_exe, 'name': container_name})
def _stop_all_managed_containers():
with _managed_docker_lock:
containers = list(_managed_docker_containers)
_managed_docker_containers.clear()
seen = set()
for entry in containers:
name = entry['name']
if name in seen:
continue
seen.add(name)
docker_exe = entry['docker_exe']
try:
print(f"Stopping Docker container: {name}")
subprocess.run([docker_exe, 'stop', name], capture_output=True, timeout=30)
subprocess.run([docker_exe, 'rm', '-f', name], capture_output=True, timeout=15)
print(f"Docker container stopped and removed: {name}")
except Exception as e:
print(f"Warning: could not stop container {name}: {e}")
def _docker_base_cmd(docker_exe):
return _sudo_prefix() + [docker_exe]
def _docker_run_capture(docker_exe, args, timeout=60):
cmd = _docker_base_cmd(docker_exe) + [str(a) for a in args]
return _run_capture(cmd, timeout=timeout)
def _ensure_docker_daemon_running(docker_exe, webhook_url):
rc, out = _docker_run_capture(docker_exe, ["info"], timeout=30)
if rc == 0:
return True
if platform.system() != "Linux":
print_and_discord("Docker ondersteuning is enkel voorzien voor Linux.", webhook_url)
return False
started = False
try:
if shutil.which("systemctl"):
_run_capture(_sudo_prefix() + ["systemctl", "start", "docker"], timeout=90)
_run_capture(_sudo_prefix() + ["systemctl", "enable", "docker"], timeout=90)
started = True
elif shutil.which("service"):
_run_capture(_sudo_prefix() + ["service", "docker", "start"], timeout=90)
started = True
except Exception:
started = False
rc2, out2 = _docker_run_capture(docker_exe, ["info"], timeout=30)
if rc2 == 0:
return True
if started:
print_and_discord(f"Docker service started, but docker info still fails: {out2}", webhook_url)
else:
print_and_discord(f"Docker daemon not reachable: {out2}", webhook_url)
return False
def _install_docker_if_missing(webhook_url):
docker_exe = shutil.which("docker")
if docker_exe:
return True, False, docker_exe
os_name = platform.system()
attempted = False
last_error = ""
try:
if os_name == "Linux":
attempted = True
if shutil.which("apt-get"):
print_and_discord("Docker not found. Starting installation via apt-get...", webhook_url)
rc, out = _run_stream(_sudo_prefix() + ["apt-get", "update"], timeout=600)
if rc != 0:
last_error = out
rc, out = _run_stream(_sudo_prefix() + ["apt-get", "install", "-y", "docker.io"], timeout=1800)
if rc != 0:
last_error = out
elif shutil.which("dnf"):
print_and_discord("Docker not found. Starting installation via dnf...", webhook_url)
rc, out = _run_stream(_sudo_prefix() + ["dnf", "install", "-y", "docker"], timeout=1800)
if rc != 0:
last_error = out
rc2, out2 = _run_stream(_sudo_prefix() + ["dnf", "install", "-y", "moby-engine", "moby-cli"], timeout=1800)
if rc2 != 0:
last_error = out2 or last_error
elif shutil.which("yum"):
print_and_discord("Docker not found. Starting installation via yum...", webhook_url)
rc, out = _run_stream(_sudo_prefix() + ["yum", "install", "-y", "docker"], timeout=1800)
if rc != 0:
last_error = out
rc2, out2 = _run_stream(_sudo_prefix() + ["yum", "install", "-y", "moby-engine", "moby-cli"], timeout=1800)
if rc2 != 0:
last_error = out2 or last_error
elif shutil.which("pacman"):
print_and_discord("Docker not found. Starting installation via pacman...", webhook_url)
rc, out = _run_stream(_sudo_prefix() + ["pacman", "-S", "--noconfirm", "docker"], timeout=1800)
if rc != 0:
last_error = out
else:
print_and_discord(
"Docker is not installed and no supported package manager was found (apt, dnf, yum, pacman).",
webhook_url,
)
return False, False, None
else:
print_and_discord("Docker auto-install is only available for Linux (this is a Linux-only tool).", webhook_url)
return False, False, None
except Exception as exc:
last_error = str(exc)
docker_exe = shutil.which("docker")
if not docker_exe:
if attempted:
print_and_discord(f"Tried to install Docker but docker is still not available: {last_error}", webhook_url)
return False, attempted, None
return True, attempted, docker_exe
def start_filebrowser_docker(filebrowser_config, fuse_mount_point, webhook_url):
if not isinstance(filebrowser_config, dict):
filebrowser_config = {}
enabled = _coerce_bool(filebrowser_config.get("enabled", True), True)
if not enabled:
return
if not fuse_mount_point:
print_and_discord("Filebrowser: FUSE mount_point is missing. Enable fuse_server.enabled and configure mount_point.", webhook_url)
return
if not os.path.exists(fuse_mount_point):
print_and_discord(f"Filebrowser: FUSE mount does not exist: {fuse_mount_point}", webhook_url)
return
try:
if not os.path.ismount(fuse_mount_point):
print_and_discord(f"Filebrowser: FUSE mount is not active yet at: {fuse_mount_point}", webhook_url)
return
except Exception:
pass
ok, installed_now, docker_exe = _install_docker_if_missing(webhook_url)
if not ok or not docker_exe:
return
if installed_now and filebrowser_config.get("port") is None:
default_port = _coerce_int(filebrowser_config.get("port", 8082), default=8082, min_value=1, max_value=65535)
port_input = input(f"Filebrowser port (default {default_port}): ").strip()
selected_port = _coerce_int(port_input, default=default_port, min_value=1, max_value=65535)
filebrowser_config["port"] = selected_port
try:
cfg = _load_config_from_disk()
if isinstance(cfg, dict):
cfg["filebrowser"] = dict(filebrowser_config)
_save_config_to_disk(cfg)
except Exception:
pass
if not _ensure_docker_daemon_running(docker_exe, webhook_url):
return
port = _coerce_int(filebrowser_config.get("port", 8082), default=8082, min_value=1, max_value=65535)
container_name = str(filebrowser_config.get("container_name", "filebrowser") or "filebrowser")
image = str(filebrowser_config.get("image", "filebrowser/filebrowser") or "filebrowser/filebrowser")
restart_policy = str(filebrowser_config.get("restart_policy", "unless-stopped") or "unless-stopped")
try:
base_repo = image.split(":", 1)[0]
tag = image.split(":", 1)[1] if ":" in image else ""
should_pin = (not tag) or (tag.lower() == "latest")
if should_pin and base_repo == "filebrowser/filebrowser":
rc_ver, out_ver = _docker_run_capture(docker_exe, ["run", "--rm", image, "version"], timeout=30)
if rc_ver == 0 and out_ver:
import re
m = re.search(r"v(\d+\.\d+\.\d+)", out_ver)
if m:
pinned_image = f"{base_repo}:v{m.group(1)}"
image = pinned_image
filebrowser_config["image"] = pinned_image
try:
cfg = _load_config_from_disk()
if isinstance(cfg, dict):
cfg_fb = cfg.get("filebrowser")
if not isinstance(cfg_fb, dict):
cfg_fb = {}
cfg_fb["image"] = pinned_image
cfg["filebrowser"] = cfg_fb
_save_config_to_disk(cfg)
except Exception:
pass
except Exception:
pass
def _default_state_dir():
try:
if has_admin_privileges():
return "/var/lib/multidisk-filebalancer/filebrowser"
except Exception:
pass
return os.path.join(os.path.expanduser("~"), ".local", "share", "multidisk-filebalancer", "filebrowser")
state_dir = str(filebrowser_config.get("state_dir") or "").strip()
if not state_dir:
default_state_dir = _default_state_dir()
state_input = input(f"Path for Filebrowser data/config (default {default_state_dir}): ").strip()
state_dir = state_input or default_state_dir
filebrowser_config["state_dir"] = state_dir
try:
cfg = _load_config_from_disk()
if isinstance(cfg, dict):
cfg_fb = cfg.get("filebrowser")
if not isinstance(cfg_fb, dict):
cfg_fb = {}
cfg_fb["state_dir"] = state_dir
if "port" in filebrowser_config:
cfg_fb["port"] = filebrowser_config.get("port")
cfg["filebrowser"] = cfg_fb
_save_config_to_disk(cfg)
except Exception:
pass
database_dir = os.path.join(state_dir, "database")
config_dir = os.path.join(state_dir, "config")
os.makedirs(database_dir, exist_ok=True)
os.makedirs(config_dir, exist_ok=True)
try:
os.chmod(state_dir, 0o755)
os.chmod(database_dir, 0o777)
os.chmod(config_dir, 0o777)
except Exception:
pass
try:
with open(os.path.join(config_dir, ".write_test"), "w", encoding="utf-8") as f:
f.write("ok")
os.remove(os.path.join(config_dir, ".write_test"))
except Exception as exc:
if str(state_dir).startswith("/media/sf_") or str(state_dir).startswith("/media/sf-") or str(state_dir).startswith("/media/sf"):
print_and_discord(f"Filebrowser: no write permission in {state_dir} (VirtualBox shared folder). Choose a path on the local Linux disk (e.g. /var/lib/...). Error: {exc}", webhook_url)
else:
print_and_discord(f"Filebrowser: no write permission in {state_dir}. Error: {exc}", webhook_url)
return
print_and_discord(f"Filebrowser host folders: database={database_dir}, config={config_dir}", webhook_url)
db_path_in_container = "/database/filebrowser.db"
branding_dir_host = os.path.join(config_dir, "branding")
try:
os.makedirs(branding_dir_host, exist_ok=True)
with open(os.path.join(branding_dir_host, "custom.css"), "w", encoding="utf-8") as f:
f.write(
"aside .used, aside .usage, aside .credits, aside .sidebar__footer, aside .sidebar-footer, aside .sidebar__credits {\n"
" display: none !important;\n"
"}\n"
)
except Exception:
pass
is_first_db_boot = not os.path.exists(os.path.join(database_dir, "filebrowser.db"))
username = str(filebrowser_config.get("username") or "admin").strip() or "admin"
password = None
configured_password = str(filebrowser_config.get("password") or "").strip()
if configured_password:
if len(configured_password) < 12:
print_and_discord("Filebrowser: password in config.yml is too short (min 12). Update is skipped.", webhook_url)
else:
password = configured_password
need_credentials = (is_first_db_boot or not _coerce_bool(filebrowser_config.get("credentials_initialized", False), False))
if need_credentials and not password:
if not str(filebrowser_config.get("username") or "").strip():
username_input = input(f"Filebrowser username (default {username}): ").strip()
username = username_input or username
while True:
p1 = input("Filebrowser password: ").strip()
p2 = input("Filebrowser password (again): ").strip()
if p1 != p2:
print("Passwords do not match. Try again.")
continue
if not p1:
print("Password cannot be empty.")
continue
if len(p1) < 12:
print("Password is too short. Minimum length is 12.")
continue
password = p1
break
def _docker_run_filebrowser_cli(args, timeout=120):
selinux_suffix = ":Z" if _selinux_enforcing() else ""
return _docker_run_capture(
docker_exe,
[
"run",
"--rm",
"--user",
f"{os.geteuid()}:{os.getegid()}",
"-v",
f"{fuse_mount_point}:/srv{selinux_suffix}",
"-v",
f"{database_dir}:/database{selinux_suffix}",
"-v",
f"{config_dir}:/config{selinux_suffix}",
image,
] + [str(a) for a in args],
timeout=timeout,
)
if password:
rc_init, out_init = _docker_run_filebrowser_cli(["config", "init", "-d", db_path_in_container, "-r", "/srv"], timeout=120)
if rc_init != 0 and not os.path.exists(os.path.join(database_dir, "filebrowser.db")):
print_and_discord(f"Filebrowser init failed: {out_init}", webhook_url)
return
rc_find, _ = _docker_run_filebrowser_cli(["users", "find", username, "-d", db_path_in_container], timeout=60)
if rc_find == 0:
rc_set, out_set = _docker_run_filebrowser_cli(["users", "update", username, "--password", password, "--perm.admin", "-d", db_path_in_container], timeout=120)
if rc_set != 0:
print_and_discord(f"Failed to set Filebrowser credentials:\n{out_set}", webhook_url)
return
else:
rc_add, out_add = _docker_run_filebrowser_cli(["users", "add", username, password, "--perm.admin", "-d", db_path_in_container], timeout=120)
if rc_add != 0:
print_and_discord(f"Failed to set Filebrowser credentials:\n{out_add}", webhook_url)
return
filebrowser_config["username"] = username
filebrowser_config["password"] = password
filebrowser_config["credentials_initialized"] = True
try:
cfg = _load_config_from_disk()
if isinstance(cfg, dict):
cfg_fb = cfg.get("filebrowser")
if not isinstance(cfg_fb, dict):
cfg_fb = {}
cfg_fb["username"] = username
cfg_fb["password"] = password
cfg_fb["credentials_initialized"] = True
cfg_fb["state_dir"] = state_dir
cfg["filebrowser"] = cfg_fb
_save_config_to_disk(cfg)
except Exception:
pass
rc_verify, out_verify = _docker_run_filebrowser_cli(["users", "find", username, "-d", db_path_in_container], timeout=60)
if rc_verify == 0:
print_and_discord(f"Filebrowser credentials ready. Log in with user: {username}", webhook_url)
else:
print_and_discord(f"Filebrowser credentials set, but verification failed: {out_verify}", webhook_url)
try:
if os.path.exists(os.path.join(database_dir, "filebrowser.db")):
_docker_run_filebrowser_cli(
[
"config",
"set",
"-d",
db_path_in_container,
"--branding.files",
"/config/branding",
"--branding.disableExternal",
"--branding.disableUsedPercentage",
],
timeout=60,
)
except Exception:
pass
_, existing = _docker_run_capture(
docker_exe,
["ps", "-a", "--filter", f"name=^{container_name}$", "--format", "{{.Names}}"],
timeout=30,
)
exists = any(line.strip() == container_name for line in (existing or "").splitlines())
if exists:
_docker_run_capture(docker_exe, ["rm", "-f", container_name], timeout=60)
selinux_suffix = ":Z" if _selinux_enforcing() else ""
rc, out = _docker_run_capture(
docker_exe,