-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker_shell.py
More file actions
executable file
·2056 lines (1762 loc) · 86.2 KB
/
Copy pathdocker_shell.py
File metadata and controls
executable file
·2056 lines (1762 loc) · 86.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 python3
"""Docker-Shell — lightweight Docker management from your file manager.
Right-click a folder -> configure how a running compose container may
access it: network isolation, RAM limit, read-only or masked mounts.
Masking bind-mounts an empty "sacrificial" folder over the real one, so
data stays physically present but invisible to the container (protects
against rm -rf and AI-agent hallucinations).
Changes are written to <compose>.override.yml via PyYAML; only
network_mode is edited in the main compose file (with automatic backup).
"""
import argparse
import json
import locale
import logging
import os
import shutil
import subprocess
import sys
from pathlib import Path
__version__ = "1.3.0"
APP_TITLE = "Docker Konfig"
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
log = logging.getLogger("docker-shell")
# ════════════════════════════════════════════════════════════════
# i18n — English default, German via system locale
# ════════════════════════════════════════════════════════════════
def _detect_lang():
for var in ("LC_ALL", "LC_MESSAGES", "LANG"):
val = os.environ.get(var)
if val:
return val[:2].lower()
try:
return (locale.getlocale()[0] or "en")[:2].lower()
except Exception:
return "en"
_DE = {
"customtkinter is not installed. Install it with: pip install customtkinter":
"customtkinter ist nicht installiert. Installation: pip install customtkinter",
"PyYAML is not installed. Install it with: pip install PyYAML":
"PyYAML ist nicht installiert. Installation: pip install PyYAML",
"Docker is not installed or not in PATH.":
"Docker ist nicht installiert oder nicht im PATH.",
"Cannot talk to the Docker daemon. Is it running and are you in the 'docker' group?":
"Keine Verbindung zum Docker-Daemon. Läuft er, und bist du in der Gruppe 'docker'?",
"Docker Compose v2 ('docker compose') is required but was not found.":
"Docker Compose v2 ('docker compose') wird benötigt, wurde aber nicht gefunden.",
"Usage: docker_shell.py <folder>":
"Verwendung: docker_shell.py <ordner>",
"'{}' is not a valid folder.":
"'{}' ist kein gültiger Ordner.",
"Cannot create the mask folder '{}': {}":
"Kann den Maskierungs-Ordner '{}' nicht erstellen: {}",
"No compose file found in {}":
"Keine Compose-Datei gefunden in {}",
"folder to configure":
"zu konfigurierender Ordner",
# Panel 1
"No running containers found.":
"Keine laufenden Container gefunden.",
"No compose project found":
"Kein Compose-Projekt gefunden",
"Folder not mounted here yet — selecting will add it":
"Ordner hier noch nicht eingebunden — Auswahl nimmt ihn neu auf",
"Close": "Schließen",
# Panel 2
"Back": "Zurück",
"Status could not be read.":
"Status konnte nicht gelesen werden.",
"This folder is not mounted in the container yet.\n\"OK\" adds it with the selected mount mode.":
"Dieser Ordner ist im Container noch nicht eingebunden.\n„OK“ nimmt ihn mit dem gewählten Mount-Modus neu auf.",
"Web / Network": "Web / Netzwerk",
"Memory limit (RAM)": "Speicherschutz (RAM-Limit)",
"Mount mode": "Mount-Modus",
"Read-Write": "Read-Write",
"Read-Only": "Read-Only",
"Hidden (masked)": "Temp versteckt",
"Main folder only": "Nur Hauptordner",
"Unmask": "Demaskieren",
# Status header
"Network": "Netzwerk",
"Web": "Web",
"Isolated": "Isoliert",
"RAM limit": "RAM-Limit",
"No limit": "Kein Limit",
"Mount": "Mount",
"Not mounted": "Nicht eingebunden",
"inherited": "vererbt",
"Applied — container is restarting, use 'Back' to reload the status.":
"Angewendet — Container startet neu, Status bitte über „Zurück“ neu laden.",
# Persist / remove share
"Make permanent": "Dauerhaft übernehmen",
"Remove share": "Freigabe entfernen",
"Remove the mount of\n{}\nfrom container '{}'?\n\nThe container will lose access to this folder.":
"Die Einbindung von\n{}\naus Container '{}' entfernen?\n\nDer Container verliert den Zugriff auf diesen Ordner.",
"Service '{}' not found in the compose file.":
"Service '{}' nicht in der Compose-Datei gefunden.",
"Saved to the main compose file — survives a reset now.":
"In die Haupt-Compose übernommen — übersteht jetzt auch einen Reset.",
"Make permanent failed:\n{}":
"Dauerhaft übernehmen fehlgeschlagen:\n{}",
"Remove share failed:\n{}":
"Freigabe entfernen fehlgeschlagen:\n{}",
# Menu / settings
"Settings…": "Einstellungen…",
"Reset project…": "Projekt zurücksetzen…",
"Reset project": "Projekt zurücksetzen",
"Reset project '{}'?\n\nThe override file is deleted and the main compose file is restored from its backup. All Docker-Shell changes for this project are reverted.":
"Projekt '{}' zurücksetzen?\n\nDie Override-Datei wird gelöscht und die Haupt-Compose aus dem Backup wiederhergestellt. Alle Docker-Shell-Änderungen an diesem Projekt werden rückgängig gemacht.",
"Settings": "Einstellungen",
"Window position": "Fensterposition",
"At mouse pointer": "Am Mauszeiger",
"Centered": "Zentriert",
"UI size": "Darstellungsgröße",
"Auto": "Auto",
"Small": "Klein",
"Medium": "Mittel",
"Large": "Groß",
"Language": "Sprache",
"System language": "Systemsprache",
"Adding new folders": "Neue Ordner aufnehmen",
"Use full host path": "Voller Host-Pfad",
"Use naming preset": "Namens-Schema",
"Ask every time": "Jedes Mal fragen",
"Naming preset ({name} = folder name)":
"Namens-Schema ({name} = Ordnername)",
"Default mode for new folders": "Standard-Modus für neue Ordner",
"Network toggle affects": "Netzwerk-Schalter wirkt auf",
"All services in the project": "Alle Services des Projekts",
"Selected service only": "Nur den gewählten Service",
"Save": "Speichern",
"Cancel": "Abbrechen",
"Some settings take effect after reopening the tool.":
"Einige Einstellungen greifen erst beim nächsten Öffnen des Tools.",
"Container path for this folder:":
"Container-Pfad für diesen Ordner:",
# Tooltips
"On: the container has network/internet access. Off: full isolation (network_mode: none).":
"An: Der Container hat Netzwerk-/Internetzugriff. Aus: vollständige Isolation (network_mode: none).",
"Limit the container's RAM. Off = no limit.":
"Begrenzt den Arbeitsspeicher des Containers. Aus = kein Limit.",
"RAM limit in 1-GB steps (minimum 1 GB).":
"RAM-Limit in 1-GB-Schritten (Minimum 1 GB).",
"Read-Write: full access.\nRead-Only: no writes.\nHidden (masked): an empty folder is mounted over this one — data stays on disk but is invisible in the container.\nMain folder only: top level read-only, every subfolder masked.":
"Read-Write: voller Zugriff.\nRead-Only: kein Schreiben.\nTemp versteckt: ein leerer Ordner wird über diesen gemountet — Daten bleiben auf der Platte, sind im Container aber unsichtbar.\nNur Hauptordner: oberste Ebene Read-Only, jeder Unterordner maskiert.",
"Lift all masks of this folder and set everything back to Read-Only.":
"Hebt alle Maskierungen dieses Ordners auf und setzt alles zurück auf Read-Only.",
"Apply the selected configuration (override file + project restart) and close.":
"Wendet die gewählte Konfiguration an (Override-Datei + Projekt-Neustart) und schließt das Fenster.",
"Also write this folder's configuration into the main compose file — survives override deletion and 'Reset project'.":
"Schreibt die Konfiguration dieses Ordners zusätzlich in die Haupt-Compose — übersteht Override-Löschung und „Projekt zurücksetzen“.",
"Remove this folder's mount from the main compose file and the override — the container loses access.":
"Entfernt die Einbindung dieses Ordners aus Haupt-Compose und Override — der Container verliert den Zugriff.",
"Settings and project reset.":
"Einstellungen und Projekt-Reset.",
# Orphaned masks
"Orphaned masks": "Verwaiste Maskierungen",
"This project has masks whose host folders no longer exist:\n\n{}\n\nRemove these mask entries now? Otherwise the container may fail to start after the next restart.":
"In diesem Projekt gibt es Maskierungen, deren Host-Ordner nicht mehr existieren:\n\n{}\n\nDiese Masken-Einträge jetzt entfernen? Andernfalls kann der Container beim nächsten Neustart nicht mehr starten.",
# Errors
"Error": "Fehler",
"docker compose up failed (rc={}):\n{}":
"docker compose up fehlgeschlagen (rc={}):\n{}",
"Apply failed:\n{}":
"Anwendung fehlgeschlagen:\n{}",
"Unmask failed:\n{}":
"Demaskieren fehlgeschlagen:\n{}",
"Reset failed: {}":
"Reset fehlgeschlagen: {}",
"Timeout after {}s":
"Timeout nach {}s",
"Docker command not found. Is Docker installed?":
"Docker-Befehl nicht gefunden. Ist Docker installiert?",
}
_LANG = _detect_lang()
def tr(text):
"""Translate a UI string (English key -> selected language)."""
table = globals().get("_TABLES", {}).get(_LANG)
if table is None and _LANG == "de":
table = _DE
return table.get(text, text) if table else text
def _notify(msg):
"""Best-effort desktop notification (visible even without a terminal)."""
try:
subprocess.run(["notify-send", APP_TITLE, msg], timeout=5)
except Exception:
pass
try:
import yaml
except ImportError:
_msg = tr("PyYAML is not installed. Install it with: pip install PyYAML")
print(_msg)
_notify(_msg)
sys.exit(1)
try:
import customtkinter as ctk
from tkinter import messagebox
except ImportError:
_msg = tr("customtkinter is not installed. Install it with: pip install customtkinter")
print(_msg)
_notify(_msg)
sys.exit(1)
# ════════════════════════════════════════════════════════════════
# Configuration — XDG paths, optional config file
# ════════════════════════════════════════════════════════════════
def _xdg(env_var, fallback):
base = os.environ.get(env_var)
return Path(base) if base else Path.home() / fallback
DATA_DIR = _xdg("XDG_DATA_HOME", ".local/share") / "docker-shell"
CONFIG_FILE = _xdg("XDG_CONFIG_HOME", ".config") / "docker-shell" / "config.yml"
def _load_config():
try:
if CONFIG_FILE.exists():
with open(CONFIG_FILE, encoding="utf-8") as f:
return yaml.safe_load(f) or {}
except (OSError, yaml.YAMLError) as e:
log.warning("Cannot read config %s: %s", CONFIG_FILE, e)
return {}
_CFG = _load_config()
def cfg(key, default=None):
"""Read a config value (settings dialog writes into _CFG + config.yml)."""
return _CFG.get(key, default)
def save_config():
"""Persist the current settings to the config file."""
CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
yaml.dump(_CFG, f, default_flow_style=False, allow_unicode=True)
log.info("Config saved: %s", CONFIG_FILE)
# ── Language tables: built-in de/en + external lang/*.yml files ──
def _load_lang_tables():
"""Built-in tables plus external ones from lang/ directories.
A file lang/fr.yml with 'English key: translation' pairs adds French."""
tables = {"de": dict(_DE)}
for d in (Path(__file__).resolve().parent / "lang", DATA_DIR / "lang"):
if not d.is_dir():
continue
for f in sorted(list(d.glob("*.yml")) + list(d.glob("*.yaml"))):
code = f.stem.lower()
try:
data = yaml.safe_load(f.read_text(encoding="utf-8")) or {}
if isinstance(data, dict):
tables[code] = {**tables.get(code, {}), **data}
except (OSError, yaml.YAMLError) as e:
log.warning("Cannot read language file %s: %s", f, e)
return tables
_TABLES = _load_lang_tables()
_lang_cfg = str(cfg("language", "auto")).lower()
if _lang_cfg and _lang_cfg != "auto":
_LANG = _lang_cfg
def available_languages():
"""Language codes selectable in the settings ('en' = built-in default)."""
return sorted({"en"} | set(_TABLES.keys()))
# The empty "sacrificial" folder that gets bind-mounted over masked paths.
TEMP_LEER = str(Path(os.path.expanduser(
str(_CFG.get("temp_leer", DATA_DIR / "temp_leer")))))
def default_new_dest(target_folder):
"""Container path for a folder that is added for the first time,
according to the configured naming behavior ('ask' is handled in the
UI before this fallback is reached)."""
if cfg("add_new_mode", "host_path") == "preset":
template = str(cfg("add_new_preset", "/mnt/{name}"))
try:
dest = template.format(name=Path(str(target_folder)).name)
if dest.startswith("/"):
return dest
except (KeyError, IndexError, ValueError):
pass
log.warning("Invalid naming preset %r — falling back to host path",
template)
return str(Path(str(target_folder)).resolve())
# Compose file names, in lookup order (compose spec first, legacy second)
COMPOSE_NAMES = ("compose.yaml", "compose.yml",
"docker-compose.yml", "docker-compose.yaml")
def find_compose_file(compose_dir):
"""Locate the main compose file in a project directory."""
for name in COMPOSE_NAMES:
p = Path(compose_dir) / name
if p.is_file():
return p
return None
def override_path_for(compose_file):
"""Matching override file name (compose.yaml -> compose.override.yaml)."""
base = Path(compose_file)
return base.with_name(f"{base.stem}.override{base.suffix}")
# ════════════════════════════════════════════════════════════════
# Backend — all Docker operations via CLI (subprocess)
# ════════════════════════════════════════════════════════════════
class DockerBackend:
"""All Docker operations via CLI. No docker-py needed."""
def __init__(self):
self.uid_gid = f"{os.getuid()}:{os.getgid()}"
# ── Helpers ────────────────────────────────────────────────
@staticmethod
def _run(cmd, timeout=30, cwd=None):
"""subprocess.run wrapper -> (stdout_str, stderr_str, returncode)"""
try:
r = subprocess.run(
cmd, capture_output=True, text=True,
timeout=timeout, cwd=cwd,
)
return r.stdout.strip(), r.stderr.strip(), r.returncode
except subprocess.TimeoutExpired:
return "", tr("Timeout after {}s").format(timeout), -1
except FileNotFoundError:
return "", tr("Docker command not found. Is Docker installed?"), -2
@staticmethod
def _backup_path(compose_dir):
"""Backup path for the original main compose file."""
return Path(compose_dir) / ".docker_shell_compose_bak"
# ── Compose volume resolution ──────────────────────────────
@staticmethod
def _compose_volumes(compose_dir, service_name=None):
"""Bind-mount entries (host_src, container_dest) from the original
compose file. Short and long syntax; named volumes are skipped.
service_name=None -> all services."""
path = find_compose_file(compose_dir)
if not path:
log.warning("No compose file in %s", compose_dir)
return []
try:
with open(path, encoding="utf-8") as f:
compose = yaml.safe_load(f) or {}
except (OSError, yaml.YAMLError) as e:
log.warning("Cannot read %s: %s", path, e)
return []
volumes = []
for sname, sconf in (compose.get("services") or {}).items():
if service_name is not None and sname != service_name:
continue
for vol in (sconf or {}).get("volumes") or []:
if isinstance(vol, str):
parts = vol.split(":")
if len(parts) < 2:
continue
src, dest = parts[0], parts[1]
elif isinstance(vol, dict):
src, dest = vol.get("source", ""), vol.get("target", "")
else:
continue
if not src or not dest:
continue
src = os.path.expanduser(src)
if not os.path.isabs(src):
if not src.startswith("."):
continue # named volume, no host path
src = str(Path(compose_dir) / src)
volumes.append((str(Path(src).resolve()), dest))
return volumes
def resolve_container_dest(self, compose_dir, service_name, host_folder):
"""Container path of the host folder, derived from the original
compose file.
Deliberately NOT from docker inspect: while masked, the live mount
points to the sacrificial folder and the mapping would be lost. The
original compose file stays stable. Also supports subpaths of a
mounted volume."""
target = Path(str(host_folder)).resolve()
for src, dest in self._compose_volumes(compose_dir, service_name):
src_path = Path(src)
if target == src_path:
return dest.rstrip("/") or "/"
try:
rel = target.relative_to(src_path)
return f"{dest.rstrip('/')}/{rel.as_posix()}"
except ValueError:
continue
return None
@staticmethod
def _read_override(compose_dir):
"""(path, parsed dict) of the override file, or (None, {})."""
base = find_compose_file(compose_dir)
if not base:
return None, {}
ov_path = override_path_for(base)
if not ov_path.exists():
return ov_path, {}
try:
with open(ov_path, encoding="utf-8") as f:
return ov_path, (yaml.safe_load(f) or {})
except (OSError, yaml.YAMLError) as e:
log.warning("Cannot read %s: %s", ov_path, e)
return ov_path, {}
def _override_dest(self, compose_dir, service_name, host_folder):
"""Container path of a folder that was ADDED by Docker-Shell (not in
the main compose). Looked up via the x-docker-shell mapping in the
override — this survives masking, where the live mount source is the
sacrificial folder. Falls back to a source match in the override
volumes."""
_, override = self._read_override(compose_dir)
target = Path(str(host_folder)).resolve()
mapping = (override.get("x-docker-shell") or {}).get("mounts") or {}
hit = mapping.get(str(target))
if hit:
return hit
svc = (override.get("services") or {}).get(service_name) or {}
for vol in svc.get("volumes") or []:
src, dest = self._vol_src_dest(vol)
if not src or src == TEMP_LEER:
continue
try:
if Path(os.path.expanduser(src)).resolve() == target:
return dest
except (ValueError, OSError):
continue
return None
def resolve_dest_any(self, compose_dir, service_name, host_folder):
"""Container path of the host folder: main compose first, then the
override (folders added by Docker-Shell). None if unknown."""
return (self.resolve_container_dest(compose_dir, service_name, host_folder)
or self._override_dest(compose_dir, service_name, host_folder))
# ── Orphaned masks ─────────────────────────────────────────
def _dest_to_host_map(self, compose_dir, service_name):
"""Known container-dest -> host-path pairs (main compose volumes +
the x-docker-shell mapping of folders added by the tool)."""
_, override = self._read_override(compose_dir)
mapping = (override.get("x-docker-shell") or {}).get("mounts") or {}
dest_to_host = {v: k for k, v in mapping.items()}
for src, dest in self._compose_volumes(compose_dir, service_name):
dest_to_host.setdefault(dest.rstrip("/") or "/", src)
return dest_to_host
def find_orphaned_masks(self, compose_dir, service_name):
"""Mask entries in the override whose host origin no longer exists.
Such entries make the container fail to start when Docker cannot
create the mount point (e.g. sub-mask below a read-only parent
mount whose host folder was deleted). Returns [(dest, host), ...].
"""
_, override = self._read_override(compose_dir)
svc = (override.get("services") or {}).get(service_name) or {}
dest_to_host = self._dest_to_host_map(compose_dir, service_name)
# Deepest known dest first, so sub-masks map to the closest parent
known = sorted(dest_to_host.items(), key=lambda kv: -len(kv[0]))
orphans = []
for vol in svc.get("volumes") or []:
src, dest = self._vol_src_dest(vol)
if src != TEMP_LEER:
continue
host = dest_to_host.get(dest)
if host is None:
for d, h in known:
prefix = d.rstrip("/") + "/"
if dest.startswith(prefix):
host = str(Path(h) / dest[len(prefix):])
break
if host and not Path(host).exists():
orphans.append((dest, host))
return orphans
def remove_orphaned_masks(self, compose_dir, service_name):
"""Drop orphaned mask volumes from the override. Returns the number
of removed entries (the caller applies afterwards)."""
orphan_dests = {dest for dest, _ in
self.find_orphaned_masks(compose_dir, service_name)}
if not orphan_dests:
return 0
ov_path, override = self._read_override(compose_dir)
svc = (override.get("services") or {}).get(service_name)
if not svc or not svc.get("volumes"):
return 0
kept = []
removed = 0
for vol in svc["volumes"]:
src, dest = self._vol_src_dest(vol)
if src == TEMP_LEER and dest in orphan_dests:
removed += 1
continue
kept.append(vol)
svc["volumes"] = kept
with open(ov_path, "w", encoding="utf-8") as f:
yaml.dump(override, f, default_flow_style=False, sort_keys=False,
allow_unicode=True)
log.info("Removed %d orphaned mask(s) from %s", removed, ov_path)
return removed
# ── Container scan ─────────────────────────────────────────
def scan_containers(self, target_folder=None):
"""Find running containers.
Returns list of dicts:
{id, name, service_name, compose_dir | None, warning, new_mount}
"""
out, err, rc = self._run(["docker", "ps", "--format", "{{.ID}}"])
if rc != 0:
log.error("docker ps failed: %s", err)
return []
containers = []
for cid in out.splitlines():
cid = cid.strip()
if not cid:
continue
out, _, rc = self._run(["docker", "inspect", cid])
if rc != 0:
continue
try:
data = json.loads(out)[0]
except (json.JSONDecodeError, IndexError):
continue
name = data.get("Name", "").lstrip("/")
labels = data.get("Config", {}).get("Labels", {})
compose_dir = labels.get("com.docker.compose.project.working_dir")
service_name = labels.get("com.docker.compose.service", name)
if not compose_dir:
containers.append({
"id": cid,
"name": name,
"service_name": None,
"compose_dir": None,
"warning": True,
})
else:
# List every compose container and mark whether the target
# folder is already known there (live mount OR original
# compose — live mounts alone are not enough: while masked,
# the mount source is the sacrificial folder). Unknown
# folders can be added on apply (new_mount=True).
is_known = bool(target_folder) and (
self._folder_mounted_in_container(
cid, Path(target_folder).resolve())
or self.resolve_dest_any(
compose_dir, service_name, target_folder) is not None)
containers.append({
"id": cid,
"name": name,
"service_name": service_name,
"compose_dir": compose_dir,
"warning": False,
"new_mount": bool(target_folder) and not is_known,
})
return containers
def _folder_mounted_in_container(self, container_id, target_path):
"""Is target_path (or a parent of it) mounted in the container?"""
out, _, rc = self._run(["docker", "inspect", "--format",
'{{range .Mounts}}{{.Source}}{{"\n"}}{{end}}',
container_id])
if rc != 0:
return False
for src in out.splitlines():
try:
src_path = Path(src.strip()).resolve()
if target_path == src_path or target_path.is_relative_to(src_path):
return True
except (ValueError, OSError):
continue
return False
# ── Status ─────────────────────────────────────────────────
def get_status(self, container_id, target_folder, compose_dir=None,
service_name=None):
"""Current state of the folder inside the container.
Returns dict:
{is_isolated, memory_gb, mounts}
"""
out, _, rc = self._run(["docker", "inspect", "--format",
'{{json .}}', container_id])
if rc != 0:
return None
data = json.loads(out)
hc = data.get("HostConfig", {})
mounts = data.get("Mounts", [])
net_mode = hc.get("NetworkMode", "default")
is_isolated = (net_mode == "none")
mem_bytes = hc.get("Memory", 0)
memory_gb = max(1, round(mem_bytes / (1024 ** 3))) if mem_bytes > 0 else 0
# Stable container path from the original compose file — the live
# mount source is useless as a key: while masked it is the
# sacrificial folder.
real_target = Path(str(target_folder)).resolve()
target_dest = None
if compose_dir and service_name:
target_dest = self.resolve_dest_any(
compose_dir, service_name, target_folder)
if not target_dest:
# Genuinely new folder: the dest it WOULD get on apply
target_dest = default_new_dest(target_folder)
mount_entries = []
parent_mount = None # deepest mount above the target (inherited rights)
for m in mounts:
source = m.get("Source", "")
dest = m.get("Destination", "")
mode = m.get("Mode", "rw") or "rw"
if target_dest:
if dest == target_dest:
# Base mount of the target folder — masked if the source
# currently is the sacrificial folder
mount_entries.append({
"source": source,
"dest": dest,
"mode": mode,
"masked": source == TEMP_LEER,
"inherited": False,
})
elif (source == TEMP_LEER
and dest.startswith(target_dest.rstrip("/") + "/")):
# Masked subfolder ("main folder only" mode)
mount_entries.append({
"source": source,
"dest": dest,
"mode": mode,
"masked": True,
"inherited": False,
})
elif target_dest.startswith(dest.rstrip("/") + "/"):
# A mount above the target covers it — rights are
# inherited from the deepest such parent
if parent_mount is None or len(dest) > len(parent_mount["dest"]):
parent_mount = {
"source": source,
"dest": dest,
"mode": mode,
"masked": source == TEMP_LEER,
"inherited": True,
}
else:
# Fallback without compose info: source-based match
try:
if Path(source).resolve() == real_target:
mount_entries.append({
"source": source,
"dest": dest,
"mode": mode,
"masked": False,
"inherited": False,
})
except (ValueError, OSError):
continue
# No own mount, but covered by a parent mount -> inherited rights
# (prevents the "not mounted" banner for such folders)
if parent_mount and not any(
e["dest"] == target_dest for e in mount_entries):
mount_entries.insert(0, parent_mount)
return {
"is_isolated": is_isolated,
"memory_gb": memory_gb,
"mounts": mount_entries,
}
# ── All volumes of a container ─────────────────────────────
def get_all_volumes(self, container_id):
"""All volume mounts as strings (docker-compose format)."""
out, _, rc = self._run(["docker", "inspect", "--format",
'{{range .Mounts}}{{.Source}}:{{.Destination}}:{{.Mode}}{{"\n"}}'
'{{end}}', container_id])
if rc != 0 or not out.strip():
return []
return [v.strip() for v in out.splitlines() if v.strip()]
# ── Write override file ────────────────────────────────────
def write_override(self, compose_dir, service_name, config):
"""Write <compose>.override.yml via PyYAML.
config dict contains:
target_folder (str) — target folder on the host
mount_mode (str) — "rw" | "ro" | "masked" | "main_only"
ram_limit_gb (int) — 0 = no limit
current_volumes (list) — all current volume strings
"""
target_folder = str(config["target_folder"])
mount_mode = config.get("mount_mode", "rw")
temp_leer = TEMP_LEER
current_volumes = config.get("current_volumes", [])
base = find_compose_file(compose_dir)
if not base:
raise FileNotFoundError(
tr("No compose file found in {}").format(compose_dir))
# Stable container target path: main compose first, then the
# x-docker-shell mapping in the override (folders added by the tool).
# Live mounts are useless as a key: while masked, the source is the
# sacrificial folder and the target folder would be unfindable
# (switching back to RW/RO would go nowhere).
real_target = Path(target_folder).resolve()
main_dest = self.resolve_container_dest(
compose_dir, service_name, target_folder)
target_dest = (main_dest
or self._override_dest(compose_dir, service_name,
target_folder)
or config.get("new_dest")
or default_new_dest(target_folder))
# Preserve the host->dest mapping of previously added folders
_, old_override = self._read_override(compose_dir)
dest_mapping = dict(
(old_override.get("x-docker-shell") or {}).get("mounts") or {})
if not main_dest:
# Folder is not in the main compose -> remember its container
# path so it stays resolvable even while masked
dest_mapping[str(real_target)] = target_dest
# Rebuild volumes — match on the container path (dest), never on
# the host source
new_volumes = []
target_seen = False
for vol in current_volumes:
parts = vol.split(":")
source = parts[0]
dest = parts[1] if len(parts) > 1 else ""
mode = parts[2] if len(parts) > 2 else ""
is_target = (dest == target_dest)
is_masked_subdir = (source == temp_leer
and dest.startswith(target_dest.rstrip("/") + "/"))
# Drop old sub-masks (regenerated below if needed)
if is_masked_subdir:
continue
if is_target:
target_seen = True
if mount_mode == "masked":
new_volumes.append(f"{temp_leer}:{dest}")
elif mount_mode in ("ro", "main_only"):
new_volumes.append(f"{target_folder}:{dest}:ro")
else: # rw — remount the real folder (lifts any mask)
new_volumes.append(f"{target_folder}:{dest}")
else:
# Pass through; clean empty mode parts ("src:dest:")
new_volumes.append(":".join(p for p in (source, dest, mode) if p))
if not target_seen:
# Target folder missing from live mounts (e.g. newly added) —
# create the entry so the mode takes effect
if mount_mode == "masked":
new_volumes.append(f"{temp_leer}:{target_dest}")
elif mount_mode in ("ro", "main_only"):
new_volumes.append(f"{target_folder}:{target_dest}:ro")
else:
new_volumes.append(f"{target_folder}:{target_dest}")
# "Main folder only": mask every first-level subdirectory
if mount_mode == "main_only" and real_target.is_dir():
for entry in sorted(real_target.iterdir()):
if entry.is_dir():
# Derive the container path for the subdir (not host path!)
container_subdir = f"{target_dest.rstrip('/')}/{entry.name}"
new_volumes.append(f"{temp_leer}:{container_subdir}")
override = {
"services": {
service_name: {
"user": self.uid_gid,
"logging": {
"driver": "json-file",
"options": {
"max-size": "10m",
"max-file": "3",
}
},
"volumes": new_volumes,
}
}
}
if config.get("ram_limit_gb", 0) > 0:
override["services"][service_name]["deploy"] = {
"resources": {
"limits": {
"memory": f"{config['ram_limit_gb']}G"
}
}
}
if dest_mapping:
override["x-docker-shell"] = {"mounts": dest_mapping}
override_path = override_path_for(base)
with open(override_path, "w", encoding="utf-8") as f:
yaml.dump(override, f, default_flow_style=False, sort_keys=False,
allow_unicode=True)
log.info("Override written: %s", override_path)
# ── Edit network in main compose ───────────────────────────
def edit_network_in_main(self, compose_dir, enable_network,
service_name=None):
"""Edit network_mode directly in the main compose file.
enable_network=True -> remove network_mode (default network)
enable_network=False -> set network_mode: "none" (isolation)
With network_scope=service in the config, only service_name is
touched; otherwise every service in the project.
The first edit creates a backup of the original file.
"""
path = find_compose_file(compose_dir)
if not path:
raise FileNotFoundError(
tr("No compose file found in {}").format(compose_dir))
backup = self._backup_path(compose_dir)
# First edit -> create backup (only if none exists yet)
if not enable_network and not backup.exists():
shutil.copy2(path, backup)
log.info("Backup created: %s", backup)
with open(path, encoding="utf-8") as f:
compose = yaml.safe_load(f)
services = compose.get("services", {})
modified = False
scope_service = (service_name
if cfg("network_scope", "all") == "service"
else None)
for sname, sconf in services.items():
if scope_service and sname != scope_service:
continue
if enable_network:
if sconf.get("network_mode") == "none":
del sconf["network_mode"]
modified = True
else:
if sconf.get("network_mode") != "none":
sconf["network_mode"] = "none"
modified = True
if modified:
with open(path, "w", encoding="utf-8") as f:
yaml.dump(compose, f, default_flow_style=False, sort_keys=False)
log.info("Main compose edited: %s (network=%s)", path, enable_network)
# ── Apply ──────────────────────────────────────────────────
def apply_compose(self, compose_dir):
"""Run docker compose up -d in the project directory.
Returns (success: bool, error_message: str | None)
"""
_, err, rc = self._run(
["docker", "compose", "up", "-d"],
timeout=120,
cwd=str(compose_dir),
)
if rc == 0:
return True, None
return False, tr("docker compose up failed (rc={}):\n{}").format(rc, err)
# ── Persist / remove share (main compose) ──────────────────
@staticmethod
def _vol_src_dest(vol):
"""(source, dest) of a compose volume entry (short or long syntax)."""
if isinstance(vol, str):
parts = vol.split(":")
return parts[0], parts[1] if len(parts) > 1 else ""
if isinstance(vol, dict):
return vol.get("source", ""), vol.get("target", "")
return "", ""
def _is_target_related(self, vol, target_dest):
"""Does this volume entry belong to the target folder (base mount
or one of its sacrificial-folder sub-masks)?"""
src, dest = self._vol_src_dest(vol)
if dest == target_dest:
return True
return src == TEMP_LEER and dest.startswith(target_dest.rstrip("/") + "/")
def _target_entries(self, target_folder, target_dest, mount_mode):
"""Volume strings for the target folder in the given mount mode
(base entry + sub-masks for 'main folder only')."""
entries = []
if mount_mode == "masked":
entries.append(f"{TEMP_LEER}:{target_dest}")
elif mount_mode in ("ro", "main_only"):
entries.append(f"{target_folder}:{target_dest}:ro")
else:
entries.append(f"{target_folder}:{target_dest}")
if mount_mode == "main_only":
real_target = Path(target_folder).resolve()
if real_target.is_dir():
for entry in sorted(real_target.iterdir()):
if entry.is_dir():
entries.append(
f"{TEMP_LEER}:{target_dest.rstrip('/')}/{entry.name}")
return entries
def _load_main_compose(self, compose_dir):
"""(path, parsed dict) of the main compose file; backs it up first."""
path = find_compose_file(compose_dir)
if not path:
raise FileNotFoundError(
tr("No compose file found in {}").format(compose_dir))
backup = self._backup_path(compose_dir)
if not backup.exists():
shutil.copy2(path, backup)
log.info("Backup created: %s", backup)
with open(path, encoding="utf-8") as f:
return path, (yaml.safe_load(f) or {})
def persist_to_main(self, compose_dir, service_name, config):
"""Write the target folder's mount config (and RAM limit) into the
MAIN compose file, so it survives override deletion / reset.
The network toggle already lives in the main file; the override keeps
being regenerated on every apply and simply mirrors these values."""
target_folder = str(config["target_folder"])
mount_mode = config.get("mount_mode", "rw")
target_dest = (self.resolve_dest_any(compose_dir, service_name,
target_folder)
or config.get("new_dest")
or default_new_dest(target_folder))
path, compose = self._load_main_compose(compose_dir)
svc = (compose.get("services") or {}).get(service_name)
if svc is None:
raise ValueError(
tr("Service '{}' not found in the compose file.").format(service_name))
kept = [v for v in (svc.get("volumes") or [])
if not self._is_target_related(v, target_dest)]
svc["volumes"] = kept + self._target_entries(
target_folder, target_dest, mount_mode)