-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.py
More file actions
1955 lines (1809 loc) · 82.5 KB
/
manager.py
File metadata and controls
1955 lines (1809 loc) · 82.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""FKMTime Instance Manager - Port 8181 (+ dynamic port 80) - DYNAMIC INSTANCES"""
import os, json, subprocess, threading, hashlib, secrets, time, shutil, tarfile
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
# ── Config ─────────────────────────────────────────────────────────────────
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
INSTANCES_DIR = os.path.join(SCRIPT_DIR, "instances")
TEMPLATES_DIR = os.path.join(SCRIPT_DIR, "templates")
LOCK_FILE = os.path.join(SCRIPT_DIR, ".instance_selected")
AUTH_FILE = os.path.join(SCRIPT_DIR, "auth.json")
PORT_MAIN = 8181
PORT_ALT = 80
IS_OPENWRT = os.path.isfile("/etc/openwrt_release")
IS_ROOT = os.geteuid() == 0
def get_templates():
"""Scan templates directory and return {name: path} for each subdirectory."""
templates = {}
if os.path.isdir(TEMPLATES_DIR):
for name in sorted(os.listdir(TEMPLATES_DIR)):
p = os.path.join(TEMPLATES_DIR, name)
if os.path.isdir(p):
templates[name] = p
return templates
# ── Global instances cache ──────────────────────────────────────────────────
_instances = {}
def refresh_instances():
global _instances
_instances = {}
if not os.path.exists(INSTANCES_DIR):
os.makedirs(INSTANCES_DIR, exist_ok=True)
for name in os.listdir(INSTANCES_DIR):
p = os.path.join(INSTANCES_DIR, name)
if os.path.isdir(p):
_instances[name] = p
def get_instances():
return dict(_instances) # safe copy
# ── Auth ────────────────────────────────────────────────────────────────────
_sessions = {} # token -> expiry epoch
SESSION_TTL = 86400 * 7 # 7 days
def load_auth():
if not os.path.exists(AUTH_FILE):
h = hashlib.sha256(b"root").hexdigest()
with open(AUTH_FILE, "w") as f:
json.dump({"username": "root", "password_hash": h}, f, indent=2)
print(f"Created {AUTH_FILE} with defaults root/root")
with open(AUTH_FILE) as f:
return json.load(f)
def check_credentials(username, password):
auth = load_auth()
h = hashlib.sha256(password.encode()).hexdigest()
return auth.get("username") == username and auth.get("password_hash") == h
def create_session():
token = secrets.token_hex(32)
_sessions[token] = time.time() + SESSION_TTL
return token
def validate_session(token):
if not token:
return False
exp = _sessions.get(token)
if not exp:
return False
if time.time() > exp:
del _sessions[token]
return False
return True
def get_cookie(headers, name):
for part in headers.get("Cookie", "").split(";"):
part = part.strip()
if part.startswith(name + "="):
return part[len(name)+1:]
return None
# ── Progress state ──────────────────────────────────────────────────────────
_action_lock = threading.Lock()
_progress_lock = threading.Lock()
_progress = {
"active": False,
"stages": [],
"log": "",
"done": True,
"ok": True,
}
def progress_reset(stages):
with _progress_lock:
_progress.update(active=True, done=False, ok=True, log="",
stages=[{"label": s, "status": "pending"} for s in stages])
def progress_stage(idx, status, log_line=""):
with _progress_lock:
if idx < len(_progress["stages"]):
_progress["stages"][idx]["status"] = status
if log_line:
_progress["log"] += log_line + "\n"
def progress_done(ok=True):
with _progress_lock:
_progress.update(done=True, active=False, ok=ok)
def get_progress():
with _progress_lock:
return json.loads(json.dumps(_progress))
# ── Selected helpers ────────────────────────────────────────────────────────
def get_selected():
try:
with open(LOCK_FILE) as f:
v = f.read().strip()
if v and v in get_instances():
return v
except Exception:
pass
insts = get_instances()
if insts:
first = next(iter(insts))
set_selected(first)
return first
return None
def set_selected(name):
if name and name in get_instances():
with open(LOCK_FILE, "w") as f:
f.write(name)
elif os.path.exists(LOCK_FILE):
try:
os.unlink(LOCK_FILE)
except Exception:
pass
# ── Compose helpers ─────────────────────────────────────────────────────────
def run_cmd(args, cwd=None, timeout=180):
try:
r = subprocess.run(args, cwd=cwd, capture_output=True, text=True, timeout=timeout)
return r.returncode, r.stdout + r.stderr
except subprocess.TimeoutExpired:
return -1, "Command timed out\n"
except Exception as e:
return -1, str(e) + "\n"
def run_cmd_live(args, cwd=None, timeout=180, stage_idx=0):
"""Run a command and stream its output line-by-line into the progress log."""
try:
proc = subprocess.Popen(
args, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, bufsize=1
)
output = ""
deadline = time.time() + timeout
for line in proc.stdout:
output += line
progress_stage(stage_idx, "running", line.rstrip("\n"))
if time.time() > deadline:
proc.kill()
output += "Command timed out\n"
progress_stage(stage_idx, "running", "Command timed out")
return -1, output
proc.wait(timeout=max(0, deadline - time.time()))
return proc.returncode, output
except subprocess.TimeoutExpired:
proc.kill()
return -1, output + "Command timed out\n"
except Exception as e:
return -1, str(e) + "\n"
def sanitize_wifi_value(value, field, max_len=64):
if value is None:
return ""
if not isinstance(value, str):
raise ValueError(f"Invalid {field}")
if len(value) > max_len:
raise ValueError(f"{field} too long")
if any(c in value for c in {"\x00", "\n", "\r", "=", ";", "&", "|", "$", "`", "(", ")", "<", ">", '"', "'", "\\"}):
raise ValueError(f"Invalid {field}")
return value
def force_rmtree(path):
"""Remove a directory tree, falling back to docker if not running as root."""
try:
shutil.rmtree(path)
except PermissionError:
if IS_ROOT:
raise
abspath = os.path.abspath(path)
parent = os.path.dirname(abspath)
name = os.path.basename(abspath)
code, out = run_cmd(
["docker", "run", "--rm", "-v", f"{parent}:/mnt", "alpine",
"rm", "-rf", f"/mnt/{name}"],
timeout=60,
)
if code != 0:
raise PermissionError(
f"Permission denied and docker fallback failed: {out.strip()}"
)
def compose_status(name):
insts = get_instances()
if name not in insts:
return False, "Instance not found"
code, out = run_cmd(["docker", "compose", "ps", "--format", "json"],
cwd=insts[name], timeout=10)
if code != 0:
return False, out.strip() or "Error running docker compose ps"
lines = [l for l in out.strip().splitlines() if l.strip()]
if not lines:
return False, "No containers"
rows, all_up = [], True
for line in lines:
try:
obj = json.loads(line)
if obj.get("State") != "running":
all_up = False
rows.append(f"{obj.get('Name','?')}: {obj.get('State','?')} ({obj.get('Status','?')})")
except Exception:
rows.append(line)
return all_up, "\n".join(rows)
def any_instance_running():
for name in get_instances():
running, _ = compose_status(name)
if running:
return True
return False
def read_env(name):
insts = get_instances()
if name not in insts:
return ""
try:
with open(os.path.join(insts[name], ".env")) as f:
return f.read()
except FileNotFoundError:
return ""
def read_template(name):
insts = get_instances()
if name not in insts:
return "# Instance not found"
try:
with open(os.path.join(insts[name], ".env.template")) as f:
return f.read()
except FileNotFoundError:
return "# .env.template not found"
def write_env(name, content):
insts = get_instances()
if name not in insts:
raise FileNotFoundError("Instance not found")
with open(os.path.join(insts[name], ".env"), "w") as f:
f.write(content)
def read_compose(name):
insts = get_instances()
if name not in insts:
return ""
try:
with open(os.path.join(insts[name], "docker-compose.yml")) as f:
return f.read()
except FileNotFoundError:
return ""
def write_compose(name, content):
insts = get_instances()
if name not in insts:
raise FileNotFoundError("Instance not found")
with open(os.path.join(insts[name], "docker-compose.yml"), "w") as f:
f.write(content)
# ── Instance management ─────────────────────────────────────────────────────
def create_instance(name, template_key):
name = name.strip()
if not name or len(name) > 64 or not all(c.isalnum() or c in ('-', '_') for c in name):
return False, "Invalid name (alphanumeric + - _ only, max 64 chars)"
insts = get_instances()
if name in insts:
return False, "Instance already exists"
src = get_templates().get(template_key)
if not src or not os.path.isdir(src):
return False, f"Template '{template_key}' not found or is not a directory"
dst = os.path.join(INSTANCES_DIR, name)
try:
shutil.copytree(src, dst)
# Store which template was used
with open(os.path.join(dst, ".fkm_template"), "w") as f:
f.write(template_key)
env_template = os.path.join(dst, ".env.template")
env_file = os.path.join(dst, ".env")
if os.path.isfile(env_template) and not os.path.isfile(env_file):
shutil.copy2(env_template, env_file)
refresh_instances()
if get_selected() is None:
set_selected(name)
return True, None
except Exception as e:
return False, str(e)
def get_instance_template_path(name):
"""Return the template directory path for an instance, or None."""
insts = get_instances()
if name not in insts:
return None
tmpl_file = os.path.join(insts[name], ".fkm_template")
if os.path.isfile(tmpl_file):
try:
with open(tmpl_file) as f:
tmpl_key = f.read().strip()
tmpl_path = get_templates().get(tmpl_key)
if tmpl_path and os.path.isdir(tmpl_path):
return tmpl_path
except Exception:
pass
return None
def purge_extra_dirs(instance_path, template_path):
"""Delete directories in instance that don't exist in the template. Returns list of removed dirs."""
template_entries = set(os.listdir(template_path))
removed = []
for entry in os.listdir(instance_path):
entry_path = os.path.join(instance_path, entry)
if os.path.islink(entry_path):
continue
if os.path.isdir(entry_path) and entry not in template_entries:
force_rmtree(entry_path)
removed.append(entry)
return removed
def delete_instance(name):
name = name.strip()
insts = get_instances()
if name not in insts:
return False, "Instance not found"
path = insts[name]
output = f"=== Down + Delete Volumes + Remove {name} ===\n"
code, out = run_cmd(["docker", "compose", "down", "--volumes"], cwd=path, timeout=90)
output += out
if code != 0:
output += "WARNING: docker compose down --volumes failed (continuing with folder removal)\n"
try:
force_rmtree(path)
refresh_instances()
if get_selected() == name:
new_insts = get_instances()
if new_insts:
set_selected(next(iter(new_insts)))
else:
try:
os.unlink(LOCK_FILE)
except Exception:
pass
return True, output
except Exception as e:
return False, output + "\n" + str(e)
# ── Async switch worker ─────────────────────────────────────────────────────
def _do_switch_to(target):
with _action_lock:
insts = get_instances()
if target not in insts:
progress_done(ok=False)
return
selected = get_selected()
if selected == target or selected is None:
progress_reset([f"Start {target}"])
progress_stage(0, "running")
code, out = run_cmd_live(["docker", "compose", "up", "-d"], cwd=insts[target], stage_idx=0)
progress_stage(0, "done" if code == 0 else "error")
if code == 0:
set_selected(target)
progress_done(ok=code == 0)
return
# full switch
progress_reset([f"Stop {selected}", f"Start {target}", "Update selection"])
progress_stage(0, "running")
code, out = run_cmd_live(["docker", "compose", "down"], cwd=insts[selected], stage_idx=0)
progress_stage(0, "done" if code == 0 else "error")
if code != 0:
progress_done(ok=False)
return
progress_stage(1, "running")
code, out = run_cmd_live(["docker", "compose", "up", "-d"], cwd=insts[target], stage_idx=1)
progress_stage(1, "done" if code == 0 else "error")
if code != 0:
progress_done(ok=False)
return
progress_stage(2, "running")
set_selected(target)
progress_stage(2, "done", f"Selected: {target}")
progress_done(ok=True)
# ── Async action worker ─────────────────────────────────────────────────────
def _do_action_async(action, target):
with _action_lock:
insts = get_instances()
use_name = target if (target and target in insts) else get_selected()
if not use_name or use_name not in insts:
progress_reset([action])
progress_stage(0, "error", "No valid instance selected")
progress_done(ok=False)
return
cwd = insts[use_name]
label_map = {
"pull": f"Pull images for {use_name}",
"pull_up": f"Pull images for {use_name}",
"stop": f"Stop {use_name}",
"start": f"Start {use_name}",
"down_volumes": f"Clear data for {use_name}",
}
cmd_map = {
"pull": ["docker", "compose", "pull"],
"pull_up": ["docker", "compose", "pull"],
"stop": ["docker", "compose", "down"],
"start": ["docker", "compose", "up", "-d"],
"down_volumes": ["docker", "compose", "down", "--volumes"],
}
label = label_map.get(action, action)
cmd = cmd_map.get(action)
if not cmd:
progress_reset([label])
progress_stage(0, "error", "Unknown action")
progress_done(ok=False)
return
# For down_volumes: check if containers were running so we can restart after
was_running = False
tmpl_path = None
if action == "down_volumes":
was_running, _ = compose_status(use_name)
tmpl_path = get_instance_template_path(use_name)
stages = [label]
if action == "down_volumes" and tmpl_path:
stages.append(f"Purge extra dirs for {use_name}")
if action == "down_volumes" and was_running:
stages.append(f"Restart {use_name}")
if action == "pull_up":
stages.append(f"Start {use_name}")
progress_reset(stages)
progress_stage(0, "running")
code, out = run_cmd_live(cmd, cwd=cwd, stage_idx=0)
progress_stage(0, "done" if code == 0 else "error")
if code != 0:
progress_done(ok=False)
return
si = 1
if action == "down_volumes" and tmpl_path:
progress_stage(si, "running")
try:
removed = purge_extra_dirs(cwd, tmpl_path)
if removed:
progress_stage(si, "running", f"Removed dirs: {', '.join(removed)}")
else:
progress_stage(si, "running", "No extra directories to remove")
progress_stage(si, "done")
except Exception as e:
progress_stage(si, "error", str(e))
progress_done(ok=False)
return
si += 1
if (action == "down_volumes" and was_running) or action == "pull_up":
progress_stage(si, "running")
code, out = run_cmd_live(["docker", "compose", "up", "-d"], cwd=cwd, stage_idx=si)
progress_stage(si, "done" if code == 0 else "error")
progress_done(ok=code == 0)
def _do_delete_async(name):
with _action_lock:
insts = get_instances()
if name not in insts:
progress_reset([f"Delete {name}"])
progress_stage(0, "error", "Instance not found")
progress_done(ok=False)
return
path = insts[name]
progress_reset([f"Stop containers for {name}", f"Remove {name}"])
progress_stage(0, "running")
code, out = run_cmd_live(["docker", "compose", "down", "--volumes"], cwd=path, timeout=90, stage_idx=0)
progress_stage(0, "done" if code == 0 else "error")
progress_stage(1, "running")
try:
force_rmtree(path)
refresh_instances()
if get_selected() == name:
new_insts = get_instances()
if new_insts:
set_selected(next(iter(new_insts)))
else:
try:
os.unlink(LOCK_FILE)
except Exception:
pass
progress_stage(1, "done", f"Instance {name} removed")
progress_done(ok=True)
except Exception as e:
progress_stage(1, "error", str(e))
progress_done(ok=False)
def _do_wifi_async(hs_ssid, hs_psk, sta_ssid, sta_psk):
with _action_lock:
stages = []
cmds_set = []
if hs_ssid:
cmds_set += [["uci","set",f"wireless.default_radio1.ssid={hs_ssid}"],
["uci","set",f"wireless.default_radio2.ssid={hs_ssid}"]]
if hs_psk:
cmds_set += [["uci","set",f"wireless.default_radio1.key={hs_psk}"],
["uci","set",f"wireless.default_radio2.key={hs_psk}"]]
if sta_ssid:
cmds_set.append(["uci","set",f"wireless.default_radio0.ssid={sta_ssid}"])
if sta_psk:
cmds_set.append(["uci","set",f"wireless.default_radio0.key={sta_psk}"])
if not cmds_set:
progress_reset(["Apply WiFi"])
progress_stage(0, "error", "Nothing to set.")
progress_done(ok=False)
return
stages = ["Set WiFi parameters", "Commit & reload WiFi"]
selected = get_selected()
if selected:
running, _ = compose_status(selected)
if running:
stages.append(f"Restart {selected} compose")
progress_reset(stages)
# Stage 0: uci set commands
progress_stage(0, "running")
ok = True
for cmd in cmds_set:
log_line = f"$ {' '.join(cmd)}"
progress_stage(0, "running", log_line)
code, out = run_cmd(cmd, timeout=10)
if out.strip():
progress_stage(0, "running", out.strip())
if code != 0:
ok = False
progress_stage(0, "done" if ok else "error")
if not ok:
progress_done(ok=False)
return
# Stage 1: commit + reload
progress_stage(1, "running")
progress_stage(1, "running", "$ uci commit wireless")
code, out = run_cmd(["uci","commit","wireless"], timeout=10)
if out.strip():
progress_stage(1, "running", out.strip())
if code != 0:
progress_stage(1, "error", "uci commit failed")
progress_done(ok=False)
return
progress_stage(1, "running", "$ wifi reload")
code, out = run_cmd_live(["wifi","reload"], timeout=15, stage_idx=1)
progress_stage(1, "done")
# Stage 2 (optional): restart compose
if len(stages) > 2 and selected:
progress_stage(2, "running")
progress_stage(2, "running", f"$ docker compose restart ({selected})")
code, out = run_cmd_live(["docker","compose","restart"], cwd=get_instances()[selected], stage_idx=2)
progress_stage(2, "done" if code == 0 else "error")
progress_done(ok=True)
def _do_env_restart_async(name):
"""Restart compose after .env change using 'docker compose up -d' to pick up new env."""
with _action_lock:
insts = get_instances()
if name not in insts:
progress_reset([f"Restart {name}"])
progress_stage(0, "error", "Instance not found")
progress_done(ok=False)
return
progress_reset([f"Apply .env changes to {name}"])
progress_stage(0, "running")
progress_stage(0, "running", f"$ docker compose up -d ({name})")
code, out = run_cmd_live(["docker", "compose", "up", "-d"], cwd=insts[name], stage_idx=0)
progress_stage(0, "done" if code == 0 else "error")
progress_done(ok=code == 0)
def _do_compose_restart_async(name):
"""Down then up compose after docker-compose.yml change."""
with _action_lock:
insts = get_instances()
if name not in insts:
progress_reset([f"Restart {name}"])
progress_stage(0, "error", "Instance not found")
progress_done(ok=False)
return
cwd = insts[name]
progress_reset([f"Stop {name}", f"Start {name}"])
progress_stage(0, "running")
progress_stage(0, "running", f"$ docker compose down ({name})")
code, out = run_cmd_live(["docker", "compose", "down"], cwd=cwd, stage_idx=0)
progress_stage(0, "done" if code == 0 else "error")
if code != 0:
progress_done(ok=False)
return
progress_stage(1, "running")
progress_stage(1, "running", f"$ docker compose up -d ({name})")
code, out = run_cmd_live(["docker", "compose", "up", "-d"], cwd=cwd, stage_idx=1)
progress_stage(1, "done" if code == 0 else "error")
progress_done(ok=code == 0)
# ── Backup state ────────────────────────────────────────────────────────────
_backup_lock = threading.Lock()
_backup_ready = {} # name -> tar_path
def _do_backup_async(name):
with _action_lock:
insts = get_instances()
if name not in insts:
progress_reset([f"Backup {name}"])
progress_stage(0, "error", "Instance not found")
progress_done(ok=False)
return
cwd = insts[name]
running, _ = compose_status(name)
stages = []
if running:
stages.append(f"Stop {name}")
stages.append(f"Create archive for {name}")
if running:
stages.append(f"Restart {name}")
progress_reset(stages)
si = 0
if running:
progress_stage(si, "running")
progress_stage(si, "running", f"$ docker compose down ({name})")
code, out = run_cmd_live(["docker", "compose", "down"], cwd=cwd, stage_idx=si)
progress_stage(si, "done" if code == 0 else "error")
if code != 0:
progress_done(ok=False)
return
si += 1
progress_stage(si, "running")
safe_name = os.path.basename(name)
tar_path = os.path.join(SCRIPT_DIR, f"{safe_name}.tar.gz")
try:
progress_stage(si, "running", f"Creating {name}.tar.gz …")
with tarfile.open(tar_path, "w:gz") as tar:
tar.add(cwd, arcname=name)
progress_stage(si, "done", f"Archive ready: {name}.tar.gz")
with _backup_lock:
_backup_ready[name] = tar_path
except Exception as e:
progress_stage(si, "error", str(e))
progress_done(ok=False)
return
si += 1
if running:
progress_stage(si, "running")
progress_stage(si, "running", f"$ docker compose up -d ({name})")
code, out = run_cmd_live(["docker", "compose", "up", "-d"], cwd=cwd, stage_idx=si)
progress_stage(si, "done" if code == 0 else "error")
progress_done(ok=True)
# ── Dynamic port 80 manager ─────────────────────────────────────────────────
_port80_server = None
_port80_lock = threading.Lock()
_port80_running = False
def _update_port80():
if not IS_ROOT:
return
global _port80_server, _port80_running
should_run = not any_instance_running()
with _port80_lock:
if should_run and _port80_server is None:
try:
srv = ThreadingHTTPServer(("0.0.0.0", PORT_ALT), Handler)
threading.Thread(target=srv.serve_forever, daemon=True).start()
_port80_server = srv
_port80_running = True
print(f"Port {PORT_ALT} listener started")
except Exception as e:
print(f"Could not start port {PORT_ALT}: {e}")
elif not should_run and _port80_server is not None:
_port80_server.shutdown()
_port80_server = None
_port80_running = False
print(f"Port {PORT_ALT} listener stopped")
def _port80_monitor():
while True:
time.sleep(4)
try:
_update_port80()
except Exception as e:
print(f"Port 80 monitor error: {e}")
# ── HTML pages ──────────────────────────────────────────────────────────────
LOGIN_HTML = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>FKMTime Instance Manager — Login</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Segoe UI',sans-serif;background:#0f1117;color:#e0e0e0;
min-height:100vh;display:flex;align-items:center;justify-content:center}
.box{background:#1a1d27;border:1px solid #2a2d3a;border-radius:12px;
padding:36px 32px;width:100%;max-width:360px}
h1{font-size:1.1rem;font-weight:600;margin-bottom:6px;color:#fff}
p{font-size:.82rem;color:#555;margin-bottom:24px}
label{font-size:.82rem;color:#777;display:block;margin-bottom:4px}
input{width:100%;background:#0f1117;color:#e0e0e0;border:1px solid #2a2d3a;
border-radius:6px;padding:9px 11px;font-size:.9rem;margin-bottom:14px}
input:focus{outline:none;border-color:#3a5caa}
button{width:100%;padding:10px;background:#2a5caa;color:#fff;border:none;
border-radius:6px;font-size:.9rem;font-weight:600;cursor:pointer}
button:hover{background:#3a6cba}
#err{color:#ff7070;font-size:.82rem;margin-top:10px;min-height:18px}
</style>
</head>
<body>
<div class="box">
<h1>🐳 FKMTime Instance Manager</h1>
<p>Enter your credentials to continue</p>
<label>Username</label>
<input type="text" id="u" autofocus>
<label>Password</label>
<input type="password" id="p" onkeydown="if(event.key==='Enter')login()">
<button onclick="login()">Sign In</button>
<div id="err"></div>
</div>
<script>
async function login() {
const r = await fetch('/api/login', {
method:'POST',
headers:{'Content-Type':'application/json'},
body: JSON.stringify({username: document.getElementById('u').value,
password: document.getElementById('p').value})
});
const d = await r.json();
if (d.ok) { window.location.href = '/'; }
else { document.getElementById('err').textContent = 'Invalid credentials'; }
}
</script>
</body>
</html>"""
MAIN_HTML = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>FKMTime Instance Manager</title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:'Segoe UI',sans-serif;background:#0f1117;color:#e0e0e0;min-height:100vh}
header{background:#1a1d27;border-bottom:1px solid #2a2d3a;padding:14px 24px;display:flex;align-items:center;gap:16px;flex-wrap:wrap}
header h1{font-size:1.2rem;font-weight:600;letter-spacing:.5px;color:#fff}
.badge{padding:4px 12px;border-radius:20px;font-size:.75rem;font-weight:700;letter-spacing:.5px;transition:all .3s ease}
.badge-fkmtest{background:#1a3a5c;color:#60aaff}
.badge-prod{background:#3a1a1a;color:#ff6060}
.badge-ok{background:#1a3a1a;color:#60ff90}
.badge-down{background:#2a2a2a;color:#999}
main{max-width:960px;margin:0 auto;padding:24px 16px}
.tabs{display:flex;gap:4px;margin-bottom:20px;border-bottom:1px solid #2a2d3a}
.tab{padding:10px 20px;cursor:pointer;border-radius:8px 8px 0 0;font-size:.9rem;background:#1a1d27;color:#888;border:1px solid #2a2d3a;border-bottom:none;transition:all .2s}
.tab.active{background:#22253a;color:#fff;border-color:#3a3d5a}
.tab:hover:not(.active):not(.tab-disabled){color:#ccc}
.tab.tab-disabled{color:#555;cursor:not-allowed;opacity:.5}
.panel{display:none;animation:fadeIn .25s ease}.panel.active{display:block}
@keyframes fadeIn{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}
.card{background:#1a1d27;border:1px solid #2a2d3a;border-radius:10px;padding:20px;margin-bottom:16px}
.card h2{font-size:1rem;font-weight:600;margin-bottom:14px;color:#aab}
.row{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-bottom:10px}
button{padding:8px 18px;border:none;border-radius:6px;cursor:pointer;font-size:.85rem;font-weight:600;transition:all .2s}
.btn-primary{background:#2a5caa;color:#fff}.btn-primary:hover{background:#3a6cba}
.btn-danger{background:#aa2a2a;color:#fff}.btn-danger:hover{background:#ba3a3a}
.btn-success{background:#2a7a2a;color:#fff}.btn-success:hover{background:#3a8a3a}
.btn-warn{background:#8a6a00;color:#fff}.btn-warn:hover{background:#aa8000}
.btn-neutral{background:#2a2d3a;color:#ccc}.btn-neutral:hover{background:#3a3d4a}
button:disabled{opacity:.4;cursor:not-allowed}
button .spinner{display:inline-block;width:12px;height:12px;border:2px solid transparent;border-top-color:currentColor;border-radius:50%;animation:spin .6s linear infinite;margin-right:6px;vertical-align:middle}
@keyframes spin{to{transform:rotate(360deg)}}
textarea{width:100%;background:#0f1117;color:#d0e0d0;border:1px solid #2a2d3a;border-radius:6px;padding:10px;font-family:'Courier New',monospace;font-size:.82rem;resize:vertical;line-height:1.5}
.status-box{background:#0f1117;border:1px solid #2a2d3a;border-radius:6px;padding:12px;font-family:'Courier New',monospace;font-size:.8rem;white-space:pre-wrap;max-height:180px;overflow-y:auto;color:#90c090;transition:color .3s ease}
.status-box.err{color:#c09090}
input[type=text],input[type=password],select{background:#0f1117;color:#e0e0e0;border:1px solid #2a2d3a;border-radius:6px;padding:8px 10px;font-size:.85rem;width:100%}
label{font-size:.85rem;color:#888;margin-bottom:4px;display:block}
.field{margin-bottom:12px}
.split{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@media(max-width:600px){.split{grid-template-columns:1fr}}
.instance-list{display:flex;flex-direction:column;gap:6px}
.instance-row{display:flex;align-items:center;gap:12px;padding:10px 14px;background:#1a1d27;border:1px solid #2a2d3a;border-radius:8px;border-left:4px solid #333;transition:border-color .3s ease}
.instance-row.animate-in{animation:rowIn .3s ease both}
@keyframes rowIn{from{opacity:0;transform:translateX(-6px)}to{opacity:1;transform:translateX(0)}}
.instance-row.selected{border-left-color:#60aaff}
.instance-row.selected.prod{border-left-color:#ff6060}
.instance-row .inst-name{font-weight:600;font-size:.9rem;min-width:80px}
.instance-row .inst-actions{display:flex;gap:6px;margin-left:auto;flex-wrap:wrap}
.instance-row .inst-actions button{padding:6px 12px;font-size:.78rem;white-space:nowrap}
.section-title{font-size:.75rem;font-weight:700;text-transform:uppercase;letter-spacing:1px;color:#555;margin-bottom:10px}
.progress-modal-overlay{display:none;position:fixed;inset:0;background:#000b;z-index:150;align-items:center;justify-content:center;opacity:0;transition:opacity .2s ease}
.progress-modal-overlay.show{display:flex;opacity:1}
.progress-modal{background:#1a1d27;border:1px solid #2a2d3a;border-radius:12px;padding:28px;max-width:480px;width:90%;box-shadow:0 8px 40px #0009;transform:scale(.95);transition:transform .2s ease}
.progress-modal-overlay.show .progress-modal{transform:scale(1)}
.progress-modal h3{font-size:1rem;font-weight:600;color:#fff;margin-bottom:16px}
.progress-stages{display:flex;flex-direction:column;gap:8px;margin-bottom:10px}
.stage-row{display:flex;align-items:center;gap:10px;font-size:.85rem}
.stage-icon{width:22px;height:22px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.75rem;flex-shrink:0;transition:all .3s;font-weight:700}
.stage-icon.pending{background:#2a2d3a;color:#555}
.stage-icon.running{background:#1a3a5c;color:#60aaff;animation:pulse 1s ease-in-out infinite}
.stage-icon.done{background:#1a3a1a;color:#60ff90}
.stage-icon.error{background:#3a1a1a;color:#ff6060}
.stage-label{color:#ccc}
.stage-label.running{color:#60aaff;font-weight:600}
.stage-label.done{color:#777}
.stage-label.error{color:#ff6060;font-weight:600}
.progress-track{height:5px;background:#2a2d3a;border-radius:3px;overflow:hidden;margin-bottom:12px}
.progress-fill{height:100%;background:linear-gradient(90deg,#2a5caa,#60aaff);border-radius:3px;transition:width .5s ease;width:0%}
@keyframes pulse{0%,100%{box-shadow:0 0 0 0 #2a5caa88}50%{box-shadow:0 0 0 6px #2a5caa00}}
.output-panel{position:fixed;bottom:0;left:0;right:0;z-index:50;background:#131620;border-top:1px solid #2a2d3a;transition:transform .3s ease;transform:translateY(100%)}
.output-panel.show{transform:translateY(0)}
.output-panel-header{display:flex;align-items:center;padding:8px 16px;cursor:pointer;gap:10px;user-select:none}
.output-panel-header span{font-size:.8rem;font-weight:600;color:#888}
.output-panel-header .chevron{transition:transform .2s;color:#666}
.output-panel-header .chevron.up{transform:rotate(180deg)}
.output-panel-body{max-height:220px;overflow-y:auto;padding:0 16px 12px;font-family:'Courier New',monospace;font-size:.78rem;white-space:pre-wrap;color:#b0c0a0;transition:max-height .3s ease}
.output-panel-body.collapsed{max-height:0;padding-bottom:0;overflow:hidden}
.modal-overlay{display:none;position:fixed;inset:0;background:#000b;z-index:100;align-items:center;justify-content:center;opacity:0;transition:opacity .2s ease}
.modal-overlay.show{display:flex;opacity:1}
.modal{background:#1a1d27;border:1px solid #3a2020;border-radius:12px;padding:28px;max-width:420px;width:90%;box-shadow:0 8px 40px #0009;transform:scale(.95);transition:transform .2s ease}
.modal-overlay.show .modal{transform:scale(1)}
.modal h3{font-size:1rem;color:#ff9090;margin-bottom:10px}
.modal p{font-size:.85rem;color:#aaa;margin-bottom:18px;line-height:1.6}
.modal .row{margin-bottom:0}
.modal-input-wrap{margin-bottom:16px}
.modal-input-wrap input,.modal-input-wrap select{border-color:#3a2020;width:100%;background:#0f1117;color:#e0e0e0;border:1px solid #2a2d3a;border-radius:6px;padding:9px 11px}
.redirect-banner{display:none;position:fixed;top:0;left:0;right:0;z-index:200;
background:#2a5caa;color:#fff;text-align:center;padding:12px;font-size:.9rem;font-weight:600}
.toast-container{position:fixed;top:16px;right:16px;z-index:300;display:flex;flex-direction:column;gap:8px;pointer-events:none}
.toast{pointer-events:auto;padding:10px 18px;border-radius:8px;font-size:.85rem;font-weight:600;color:#fff;box-shadow:0 4px 20px #0006;animation:toastIn .3s ease forwards,toastOut .3s ease forwards;animation-delay:0s,3s;opacity:0}
.toast-success{background:#1a5a2a}
.toast-error{background:#7a2020}
.toast-info{background:#1a3a6a}
@keyframes toastIn{from{opacity:0;transform:translateX(20px)}to{opacity:1;transform:translateX(0)}}
@keyframes toastOut{from{opacity:1;transform:translateX(0)}to{opacity:0;transform:translateX(20px)}}
.logs-modal-overlay{display:none;position:fixed;inset:0;background:#000d;z-index:200;flex-direction:column;opacity:0;transition:opacity .2s ease}
.logs-modal-overlay.show{display:flex;opacity:1}
.logs-modal-header{display:flex;align-items:center;padding:14px 20px;background:#1a1d27;border-bottom:1px solid #2a2d3a;gap:12px}
.logs-modal-header h3{font-size:1rem;font-weight:600;color:#fff;flex:1;margin:0}
.logs-modal-body{flex:1;overflow-y:auto;padding:12px 16px;font-family:'Courier New',monospace;font-size:.78rem;white-space:pre-wrap;color:#b0c0a0;background:#0a0c10;line-height:1.6}
</style>
</head>
<body>
<div class="redirect-banner" id="redirect-banner">
Redirecting to port 8181…
</div>
<div class="toast-container" id="toast-container"></div>
<header>
<h1>🐳 FKMTime Instance Manager</h1>
<span id="hdr-selected" class="badge">…</span>
<span id="hdr-status" class="badge badge-down">…</span>
<span style="flex:1"></span>
<button class="btn-neutral" style="padding:6px 12px;font-size:.8rem" onclick="refreshAll()">↻ Refresh</button>
<button class="btn-neutral" style="padding:6px 12px;font-size:.8rem" onclick="logout()">Sign Out</button>
</header>
<!-- Volumes modal (selected only) -->
<div id="modal-overlay" class="modal-overlay">
<div class="modal">
<h3>⚠ Delete All Volume Data?</h3>
<p>This will run <code>docker compose down --volumes</code> on the selected instance, permanently destroying all container volumes.<br><br>Type <strong style="color:#ff9090">DELETE</strong> to confirm.</p>
<div class="modal-input-wrap">
<input type="text" id="modal-confirm-input" placeholder="Type DELETE here…" oninput="checkModalInput()">
</div>
<div class="row">
<button class="btn-danger" id="modal-ok-btn" onclick="confirmDownVolumes()" disabled>Delete Everything</button>
<button class="btn-neutral" onclick="closeModal()">Cancel</button>
</div>
</div>
</div>
<!-- Create modal -->
<div id="create-modal-overlay" class="modal-overlay">
<div class="modal">
<h3>➕ Create New Instance</h3>
<div class="modal-input-wrap">
<label>Template</label>
<select id="create-template">
</select>
</div>
<div class="modal-input-wrap">
<label>Instance Name</label>
<input type="text" id="create-name" placeholder="e.g. dev-v2, staging" oninput="checkCreateReady()">
</div>
<div class="row">
<button class="btn-success" id="create-ok-btn" onclick="confirmCreate()" disabled>Create Instance</button>
<button class="btn-neutral" onclick="closeCreateModal()">Cancel</button>
</div>
</div>
</div>
<!-- Delete modal -->
<div id="delete-modal-overlay" class="modal-overlay">
<div class="modal">
<h3>🗑 Delete Instance <span id="delete-instance-name" style="color:#ff6060"></span></h3>
<p>This will run <code>docker compose down --volumes</code> and then permanently remove the entire instance folder.<br><br>Type <strong style="color:#ff9090">DELETE</strong> to confirm.</p>
<div class="modal-input-wrap">
<input type="text" id="delete-confirm-input" placeholder="Type DELETE here…" oninput="checkDeleteInput()">
</div>
<div class="row">
<button class="btn-danger" id="delete-ok-btn" onclick="confirmDeleteInstance()" disabled>Delete Instance</button>
<button class="btn-neutral" onclick="closeDeleteModal()">Cancel</button>
</div>
</div>
</div>
<!-- Pull modal -->
<div id="pull-modal-overlay" class="modal-overlay">
<div class="modal">
<h3 style="color:#60aaff">⬇ Pull Images</h3>
<p>Do you want to start containers (<code>docker compose up -d</code>) after pulling?</p>
<div class="row">
<button class="btn-success" onclick="confirmPull(true)">Pull & Start</button>
<button class="btn-neutral" onclick="confirmPull(false)">Pull Only</button>
<button class="btn-neutral" onclick="closePullModal()">Cancel</button>
</div>
</div>
</div>
<!-- Compose save confirm modal -->
<div id="compose-save-modal-overlay" class="modal-overlay">
<div class="modal">
<h3 style="color:#ffaa60">📝 Save docker-compose.yml?</h3>
<p>This will overwrite the current <code>docker-compose.yml</code>.<br><br>If the instance is running, it will be stopped and restarted to apply the changes.</p>
<div class="row">
<button class="btn-success" onclick="confirmComposeSave()">Save & Apply</button>
<button class="btn-neutral" onclick="closeComposeSaveModal()">Cancel</button>
</div>
</div>
</div>
<!-- Backup confirm modal -->
<div id="backup-modal-overlay" class="modal-overlay">
<div class="modal">
<h3 style="color:#60aaff">📦 Backup Instance <span id="backup-instance-name" style="color:#60aaff"></span></h3>
<p>This will create a <code>.tar.gz</code> archive of the entire instance directory and download it.<br><br>If the instance is running, it will be <strong>stopped</strong> during the backup and then <strong>restarted</strong> automatically.</p>
<div class="row">
<button class="btn-primary" onclick="confirmBackup()">Backup & Download</button>
<button class="btn-neutral" onclick="closeBackupModal()">Cancel</button>
</div>
</div>
</div>
<!-- Progress modal overlay -->
<div id="progress-modal-overlay" class="progress-modal-overlay">
<div class="progress-modal">
<h3 id="progress-modal-title">⏳ Action in progress…</h3>
<div class="progress-track"><div class="progress-fill" id="progress-fill"></div></div>
<div class="progress-stages" id="progress-stages"></div>
</div>
</div>
<!-- Logs modal (full-screen) -->
<div id="logs-modal-overlay" class="logs-modal-overlay">
<div class="logs-modal-header">
<h3>📋 Logs — <span id="logs-instance-name">…</span></h3>
<button class="btn-neutral" style="padding:6px 14px;font-size:.82rem" onclick="closeLogsModal()">✕ Close</button>
</div>