-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.py
More file actions
1821 lines (1570 loc) · 76.2 KB
/
Copy pathinstall.py
File metadata and controls
1821 lines (1570 loc) · 76.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
# ==============================================================================
# Wake-On-Request Installer
# https://github.com/msenturk/wake-on-request
#
# Usage:
# python3 install.py Install in current directory
# python3 install.py /path/to/npm Install in specified directory
# python3 install.py --path /path/to/npm Target specific NPM directory
# python3 install.py --dry-run Preview what will change, no files written
# python3 install.py --npm <container> Manually specify the NPM container name/ID
# python3 install.py -h, --help Show this help message
# ==============================================================================
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
import socket
import sqlite3
import subprocess
import sys
import tempfile
import urllib.request
import uuid
import hashlib
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Optional
# ── Constants ──────────────────────────────────────────────────────────────────
REPO = "msenturk/wake-on-request"
BRANCH = "master"
RAW_BASE = f"https://raw.githubusercontent.com/{REPO}/{BRANCH}"
# Directory where install.py itself lives — used for backup files etc.
SCRIPT_DIR = Path(__file__).parent.resolve()
# GitHub source path → destination filename inside NPM's /data/nginx/custom/
# Files are copied directly into the NPM data directory — no volume mounts needed.
NGINX_CUSTOM_FILES: list[tuple[str, str]] = [
("wakeonrequest.lua", "wakeonrequest.lua"),
("npm-custom/http_top.conf", "http_top.conf"),
# server_proxy.conf is bundled in SERVER_PROXY_CONF constant below
]
VOL_SOCK = "/var/run/docker.sock:/var/run/docker.sock"
SERVER_PROXY_CONF = """\
# ── Wake-On-Request: Global Interceptor ──────────────────────────────────────
# Injected into every NPM proxy-host server block via server_proxy.conf.
# Calls global_wake() which looks up the request host in the shared dict
# (populated from Docker labels) and starts the matching container if needed.
# No per-host NPM Advanced Tab configuration required.
access_by_lua_block {
require("wakeonrequest").global_wake()
}
"""
# ── Terminal Output ────────────────────────────────────────────────────────────
class Console:
"""ANSI-colored terminal output helpers."""
_RED = "\033[0;31m"
_GREEN = "\033[0;32m"
_BLUE = "\033[0;34m"
_YELLOW = "\033[1;33m"
_BOLD = "\033[1m"
_NC = "\033[0m"
@classmethod
def _c(cls, code: str, text: str) -> str:
if sys.stdout.isatty():
return f"{code}{text}{cls._NC}"
return text
@classmethod
def section(cls, title: str) -> None:
print(f"\n{cls._c(cls._BOLD + cls._BLUE, f'── {title} ──')}")
@classmethod
def ok(cls, msg: str) -> None:
print(f" {cls._c(cls._GREEN, f'✅ {msg}')}")
@classmethod
def warn(cls, msg: str) -> None:
print(f" {cls._c(cls._YELLOW, f'⚠️ {msg}')}")
@classmethod
def err(cls, msg: str) -> None:
print(f" {cls._c(cls._RED, f'❌ {msg}')}")
@classmethod
def info(cls, msg: str) -> None:
print(f" {cls._c(cls._BLUE, f'ℹ️ {msg}')}")
@classmethod
def change(cls, msg: str) -> None:
print(f" {cls._c(cls._YELLOW, f'📝 {msg}')}")
@classmethod
def bold(cls, text: str) -> str:
return cls._c(cls._BOLD, text)
@classmethod
def green(cls, text: str) -> str:
return cls._c(cls._GREEN, text)
@classmethod
def yellow(cls, text: str) -> str:
return cls._c(cls._YELLOW, text)
@classmethod
def red(cls, text: str) -> str:
return cls._c(cls._RED, text)
@classmethod
def blue(cls, text: str) -> str:
return cls._c(cls._BLUE, text)
@classmethod
def banner(cls, title: str, color: str = "") -> None:
color = color or (cls._BOLD + cls._BLUE)
bar = cls._c(color, "════════════════════════════════════════")
print(f"\n{bar}")
print(f"{cls._c(color, f' {title}')}")
print(bar)
# ── Container Info ─────────────────────────────────────────────────────────────
@dataclass
class ContainerInfo:
name: str = ""
status: str = ""
restart: str = ""
network_mode: str = ""
enabled: str = ""
domain: str = ""
idle_timeout: str = ""
start_timeout: str = ""
port_label: str = ""
compose_config_files: str = ""
compose_working_dir: str = ""
compose_service: str = ""
network_ids: list[str] = field(default_factory=list)
exposed_ports: list[str] = field(default_factory=list) # "80/tcp"
published_ports: list[str] = field(default_factory=list) # "8080"
ips: list[str] = field(default_factory=list)
long_id: str = ""
mounts: list[str] = field(default_factory=list) # host bind-mount paths
@property
def restart_problematic(self) -> bool:
return self.restart in ("always", "unless-stopped")
@property
def single_exposed_port(self) -> Optional[str]:
if len(self.exposed_ports) == 1:
return self.exposed_ports[0].split("/")[0]
return None
@property
def single_published_port(self) -> Optional[str]:
if len(self.published_ports) == 1:
return self.published_ports[0]
return None
# ── Docker / Podman Client ─────────────────────────────────────────────────────
class DockerClient:
"""Detects and wraps docker or podman CLI calls."""
def __init__(self, cmd_override: str = "", npm_override: str = "") -> None:
self._cmd: list[str] = []
self._cmd_override = cmd_override
self.npm_override = npm_override
self._detected = False
# ── Detection ─────────────────────────────────────────────────────────────
def detect(self) -> bool:
"""Return True if a working container runtime was found."""
if self._detected:
return bool(self._cmd)
# 1. Explicit override via env var or constructor
if self._cmd_override:
self._cmd = self._cmd_override.split()
self._detected = True
return True
env_cmd = os.environ.get("DOCKER_CMD", "")
if env_cmd:
self._cmd = env_cmd.split()
self._detected = True
return True
# 2. sudo context: prefer the runtime holding NPM (Unix only)
if hasattr(os, "geteuid") and os.geteuid() == 0 and os.environ.get("SUDO_USER"):
result = self._detect_sudo_context()
if result:
self._detected = True
return True
# 3. Standard detection
result = self._detect_standard()
self._detected = True
return result
def _run_quiet(self, cmd: list[str]) -> bool:
try:
subprocess.run(cmd, capture_output=True, check=True, timeout=5)
return True
except Exception:
return False
def _run_output(self, cmd: list[str]) -> str:
try:
r = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
return r.stdout.strip()
except Exception:
return ""
def _has_npm(self, base_cmd: list[str]) -> bool:
out = self._run_output(base_cmd + ["ps", "-a", "--format", "{{.Image}}"])
return "nginx-proxy-manager" in out
def _detect_standard(self) -> bool:
has_podman = shutil.which("podman") is not None
has_docker = shutil.which("docker") is not None
npm_podman = has_podman and self._has_npm(["podman"])
npm_docker = has_docker and self._has_npm(["docker"])
if npm_podman and not npm_docker:
self._cmd = ["podman"]; return True
if npm_docker and not npm_podman:
self._cmd = ["docker"]; return True
# Fallback: running container count
podman_count = len(self._run_output(["podman", "ps", "-q"]).splitlines()) if has_podman else 0
docker_count = len(self._run_output(["docker", "ps", "-q"]).splitlines()) if has_docker else 0
if podman_count > 0 and docker_count == 0:
self._cmd = ["podman"]; return True
if docker_count > 0 and podman_count == 0:
self._cmd = ["docker"]; return True
if has_docker and self._run_quiet(["docker", "ps"]):
self._cmd = ["docker"]; return True
if has_podman and self._run_quiet(["podman", "ps"]):
self._cmd = ["podman"]; return True
return False
def _detect_sudo_context(self) -> bool:
sudo_user = os.environ["SUDO_USER"]
try:
import pwd # type: ignore[import-not-found,import-untyped]
user_info = pwd.getpwnam(sudo_user) # type: ignore[attr-defined]
uid = user_info.pw_uid
home = user_info.pw_dir
except Exception:
uid = 0
home = f"/home/{sudo_user}"
env = {"HOME": home, "XDG_RUNTIME_DIR": f"/run/user/{uid}"}
env_list = [f"{k}={v}" for k, v in env.items()]
for runtime in ("podman", "docker"):
if not shutil.which(runtime):
continue
base = ["sudo", "-u", sudo_user, "env"] + env_list + [runtime]
if self._has_npm(base):
self._cmd = base
return True
for runtime in ("podman", "docker"):
if not shutil.which(runtime):
continue
base = ["sudo", "-u", sudo_user, "env"] + env_list + [runtime]
if self._run_quiet(base + ["ps"]):
self._cmd = base
return True
return False
# ── Public API ────────────────────────────────────────────────────────────
@property
def available(self) -> bool:
return self.detect()
def run(self, args: list[str], timeout: int = 15) -> str:
if not self._cmd:
return ""
try:
r = subprocess.run(
self._cmd + args,
capture_output=True,
text=True,
timeout=timeout,
)
return r.stdout
except subprocess.TimeoutExpired:
Console.warn(f"Docker command timed out: {args}")
return ""
except FileNotFoundError:
return "" # runtime not installed, expected
except Exception as exc:
Console.warn(f"Docker command failed: {exc}")
return ""
def run_exec(self, container_id: str, args: list[str]) -> str:
return self.run(["exec", container_id] + args, timeout=10)
def container_ids(self) -> list[str]:
out = self.run(["ps", "-a", "-q"])
return [line.strip() for line in out.splitlines() if line.strip()]
def find_npm_container(self) -> str:
if self.npm_override:
cid = self.run(["ps", "-q", "-f", f"name={self.npm_override}"]).strip().splitlines()
if cid:
return cid[0]
cid = self.run(["ps", "-q", "-f", f"id={self.npm_override}"]).strip().splitlines()
if cid:
return cid[0]
return self.npm_override
# Try compose service first
for svc in ("app", "nginx-proxy-manager"):
cid = self.run(["compose", "ps", "-q", svc]).strip()
if cid:
return cid.splitlines()[0]
# Scan all containers
out = self.run(["ps", "-a", "--format", "{{.ID}}|{{.Image}}"])
for line in out.splitlines():
if "nginx-proxy-manager" in line:
return line.split("|")[0].strip()
return ""
def inspect(self, cid: str) -> Optional[ContainerInfo]:
raw = self.run(["inspect", cid])
try:
data = json.loads(raw)
except json.JSONDecodeError:
return None
if not data:
return None
c = data[0]
labels: dict = (c.get("Config") or {}).get("Labels") or {}
net_settings: dict = c.get("NetworkSettings") or {}
networks: dict = net_settings.get("Networks") or {}
ports_map: dict = net_settings.get("Ports") or {}
mounts: list = c.get("Mounts") or []
hc: dict = c.get("HostConfig") or {}
# Exposed ports (keys of ports_map)
exposed = list(ports_map.keys())
# Published ports (HostPort bindings)
published: list[str] = []
for bindings in ports_map.values():
if not bindings:
continue
for b in bindings:
if b and b.get("HostPort"):
published.append(b["HostPort"])
# Bind-mount sources (skip anonymous volumes)
mount_sources = [
m["Source"]
for m in mounts
if m.get("Source") and "/containers/storage/volumes/" not in m.get("Source", "")
and "/var/lib/docker/volumes/" not in m.get("Source", "")
]
return ContainerInfo(
name=c.get("Name", "").lstrip("/"),
status=(c.get("State") or {}).get("Status", ""),
restart=(hc.get("RestartPolicy") or {}).get("Name", ""),
network_mode=hc.get("NetworkMode", ""),
enabled=labels.get("wakeonrequest.enable", ""),
domain=labels.get("wakeonrequest.domain", ""),
idle_timeout=labels.get("wakeonrequest.idle_timeout", ""),
start_timeout=labels.get("wakeonrequest.start_timeout", ""),
port_label=labels.get("wakeonrequest.port", ""),
compose_config_files=labels.get("com.docker.compose.project.config_files", ""),
compose_working_dir=labels.get("com.docker.compose.project.working_dir", ""),
compose_service=labels.get("com.docker.compose.service", ""),
network_ids=[v.get("NetworkID", "") for v in networks.values()],
exposed_ports=exposed,
published_ports=published,
ips=[v.get("IPAddress", "") for v in networks.values() if v.get("IPAddress")],
long_id=c.get("Id", ""),
mounts=mount_sources,
)
def network_ids_for(self, cid: str) -> list[str]:
info = self.inspect(cid)
return info.network_ids if info else []
# ── NPM Database ───────────────────────────────────────────────────────────────
class NpmDatabase:
"""Reads and writes the NPM SQLite database."""
def __init__(self, docker: DockerClient, target_dir: Path, db_override: Optional[Path] = None) -> None:
self._docker = docker
self._target = target_dir
self._db_override = db_override # explicit sqlite file path from --path
self._proxy_hosts: list[dict] = [] # [{domain_names, forward_host, forward_port}]
self._fetched = False
self._npm_cid: Optional[str] = None
def _get_npm_cid(self) -> str:
if self._npm_cid is None:
self._npm_cid = self._docker.find_npm_container() if self._docker.available else ""
return self._npm_cid
def _query_at(self, db_path: Path, sql: str, params: tuple = ()) -> list[tuple]:
"""Run SQL directly against a local SQLite file."""
try:
with sqlite3.connect(str(db_path)) as conn:
return conn.execute(sql, params).fetchall()
except Exception:
return []
def _local_db(self) -> Optional[Path]:
if self._db_override and self._db_override.exists():
return self._db_override
for candidate in (
self._target / "database.sqlite",
self._target / "data" / "database.sqlite",
):
if candidate.exists():
return candidate
return None
def _query_local(self, sql: str, params: tuple = ()) -> list[tuple]:
db = self._local_db()
if not db:
return []
return self._query_at(db, sql, params)
def _find_npm_db_via_inspect(self, npm_cid: str) -> Optional[Path]:
"""Inspect the NPM container to find its /data bind-mount host path.
This is the most portable strategy — it reads the DB file directly
from the host filesystem without needing any tools inside the container.
Works with Docker, Podman, rootless, rootful.
"""
out = self._docker.run(["inspect", "--format", "{{json .Mounts}}", npm_cid])
if not out:
return None
try:
mounts = json.loads(out.strip())
for m in mounts:
dest = m.get("Destination") or m.get("destination") or ""
src = m.get("Source") or m.get("source") or ""
if dest == "/data" and src:
for candidate in (
Path(src) / "database.sqlite",
Path(src) / "data" / "database.sqlite",
):
if candidate.exists():
return candidate
except Exception:
pass
return None
def _exec_query(self, npm_cid: str, sql: str) -> list[tuple]:
"""Run SQL against the NPM database via container exec.
SECURITY:
- SQL must be a string literal with no external interpolation.
- Use Python-side filtering of results, never SQL WHERE clauses with user data.
Tries in order:
1. python3 inside the NPM container
2. sqlite3 CLI inside the NPM container
3. Throwaway Alpine container with --volumes-from (named-volume fallback)
"""
assert '"' not in sql and "$" not in sql and "`" not in sql, "SQL must be a constant literal without double quotes or shell metachars"
sep = "\x1e" # ASCII Record Separator — never appears in SQL text output
# Strategy 1: python3 (present in jc21/nginx-proxy-manager images)
py_cmd = (
"import sqlite3,sys; conn=sqlite3.connect('/data/database.sqlite'); "
f"rows=conn.execute({sql!r}).fetchall(); "
"[sys.stdout.write('\x1e'.join(str(c) for c in r) + '\n') for r in rows]"
)
out = self._docker.run_exec(npm_cid, ["python3", "-c", py_cmd])
if out and out.strip():
return [tuple(line.split(sep)) for line in out.split("\n") if line.strip()]
# Strategy 2: sqlite3 CLI inside the NPM container (Alpine-based images)
out2 = self._docker.run_exec(
npm_cid, ["sh", "-c", f"sqlite3 -separator '\x1e' /data/database.sqlite \"{sql}\""]
)
if out2 and out2.strip():
return [tuple(line.split(sep)) for line in out2.split("\n") if line.strip()]
# Strategy 3: throwaway Alpine container with --volumes-from
# Used when the DB is in a named Docker volume (no host path).
return self._query_via_temp_container(npm_cid, sql, sep)
def _query_via_temp_container(self, npm_cid: str, sql: str, sep: str = "\x1e") -> list[tuple]:
"""Spin up a minimal, hardened throwaway container to run sqlite3.
Uses the exact same image as the NPM container to ensure sqlite3 is present
without requiring outbound network access or root filesystem writes.
"""
if not self._docker.available:
return []
npm_image = self._docker.run(["inspect", "--format", "{{.Image}}", npm_cid]).strip()
if not npm_image:
return []
cmd = self._docker._cmd + [
"run", "--rm",
"--network", "none",
"--read-only",
"--cap-drop", "ALL",
"--volumes-from", npm_cid,
"--entrypoint", "sh",
npm_image,
"-c",
f"sqlite3 -separator '{sep}' /data/database.sqlite \"{sql}\"",
]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
out = result.stdout
if out and out.strip():
return [tuple(line.split(sep)) for line in out.split("\n") if line.strip()]
except Exception:
pass
return []
def _exec_write(self, npm_cid: str, sql: str) -> int:
"""Execute a write SQL query inside the NPM container.
SECURITY:
- SQL must be a string literal with no external interpolation.
"""
assert '"' not in sql and "$" not in sql and "`" not in sql, "SQL must be a constant literal without double quotes or shell metachars"
py_cmd = (
"import sqlite3; conn=sqlite3.connect('/data/database.sqlite'); "
f"cur=conn.execute({sql!r}); conn.commit(); print(cur.rowcount)"
)
out = self._docker.run_exec(npm_cid, ["python3", "-c", py_cmd])
if out and out.strip():
try:
return int(out.strip())
except ValueError:
pass
# Fallback: sqlite3 CLI
out2 = self._docker.run_exec(
npm_cid,
["sh", "-c", f"sqlite3 /data/database.sqlite \"{sql}; SELECT changes();\""]
)
try:
return int(out2.strip().splitlines()[-1])
except (ValueError, IndexError):
pass
# Fallback: temp Alpine container
rows = self._query_via_temp_container(npm_cid, sql)
if len(rows) > 0:
return -1 # rowcount not recoverable this way, but > 0 means success
return 0
def fetch(self) -> None:
if self._fetched:
return
self._fetched = True
npm_cid = self._get_npm_cid()
sql = "SELECT domain_names, forward_host, forward_port FROM proxy_host WHERE is_deleted=0"
rows: list[tuple] = []
if npm_cid:
# Strategy 0: read DB directly from the host path found via container inspect.
# Most reliable — no tools required inside the NPM container.
db_path = self._find_npm_db_via_inspect(npm_cid)
if db_path:
Console.info(f"Reading NPM database from {db_path}")
rows = self._query_at(db_path, sql)
# Fallback: exec strategies (needed when DB is in a named Docker volume)
if not rows:
rows = self._exec_query(npm_cid, sql)
if not rows:
Console.warn(
"Could not read NPM database from container — "
"domain auto-detection will be skipped."
)
Console.info(
" Tip: run the installer from your NPM data directory "
"(the one containing data/database.sqlite), "
"or pass --path /path/to/npm-data."
)
if not rows:
rows = self._query_local(sql)
self._proxy_hosts = [
{"domain_names": r[0], "forward_host": str(r[1]), "forward_port": str(r[2])}
for r in rows
if len(r) >= 3
]
def find_config_for(
self, cname: str, ips: list[str], published_ports: list[str]
) -> Optional[dict]:
"""Return {domain, port, fwd_host, access_type} or None."""
self.fetch()
host_ip = _detect_host_ip()
for row in self._proxy_hosts:
fwd_host = row["forward_host"]
fwd_port = row["forward_port"]
raw_domains = row["domain_names"]
access_type = ""
matched = False
if fwd_host == cname:
matched = True
access_type = "name"
elif fwd_host in ips:
matched = True
access_type = "ip"
elif fwd_host in (host_ip, "127.0.0.1", "localhost", "0.0.0.0"):
if fwd_port in published_ports:
matched = True
access_type = "ip"
if matched:
try:
domains = json.loads(raw_domains)
first_domain = domains[0] if domains else ""
except Exception:
first_domain = raw_domains.strip('[]"\'').split(",")[0].strip()
return {
"domain": first_domain,
"port": fwd_port,
"fwd_host": fwd_host,
"access_type": access_type,
}
return None
def count_old_snippets(self) -> Optional[int]:
npm_cid = self._get_npm_cid()
sql = "SELECT COUNT(*) FROM proxy_host WHERE advanced_config LIKE '%wakeonrequest%'"
if npm_cid:
rows = self._exec_query(npm_cid, sql)
if rows:
try:
return int(rows[0][0])
except (IndexError, ValueError):
pass
rows = self._query_local(sql)
if rows:
try:
return int(rows[0][0])
except (IndexError, ValueError):
pass
return None
def clear_old_snippets(self) -> Optional[int]:
npm_cid = self._get_npm_cid()
sql = "UPDATE proxy_host SET advanced_config = '' WHERE advanced_config LIKE '%wakeonrequest%'"
if npm_cid:
n = self._exec_write(npm_cid, sql)
if n >= 0:
return n
rows = self._query_local(
"SELECT COUNT(*) FROM proxy_host WHERE advanced_config LIKE '%wakeonrequest%'"
)
if not rows:
return None
db = self._local_db()
if not db:
return None
try:
with sqlite3.connect(str(db)) as conn:
cur = conn.execute(sql)
conn.commit()
return cur.rowcount
except Exception:
return None
def write_advanced_config(self, domain: str, snippet: str) -> Optional[int]:
"""Inject `snippet` into the NPM advanced_config column for the proxy host
matching `domain`. Uses parameterized queries to prevent SQL injection.
Returns the number of rows updated, or None on failure.
After the DB write, also patches the live nginx config file and reloads
nginx so the change takes effect immediately — no NPM UI save needed.
"""
npm_cid = self._get_npm_cid()
rows_updated: Optional[int] = None
host_id: Optional[int] = None
# Strategy 1: direct local SQLite file (safest — no shell involved)
db_path = self._find_npm_db_via_inspect(npm_cid) if npm_cid else None
if not db_path:
db_path = self._local_db()
if db_path:
Console.info(f"Writing to NPM database at {db_path} ...")
try:
with sqlite3.connect(str(db_path)) as conn:
# Fetch the proxy host ID so we can locate its nginx config file
row = conn.execute(
"SELECT id FROM proxy_host WHERE is_deleted = 0 AND domain_names LIKE ?",
(f'%{domain}%',),
).fetchone()
if row:
host_id = int(row[0])
cur = conn.execute(
"UPDATE proxy_host SET advanced_config = ? "
"WHERE is_deleted = 0 AND domain_names LIKE ?",
(snippet, f'%{domain}%'),
)
conn.commit()
rows_updated = cur.rowcount
except Exception as exc:
Console.warn(f"Direct DB write failed: {exc}")
# Strategy 2: docker exec python3 using a proper parameterized script
if rows_updated is None and npm_cid:
Console.info(f"Writing via docker exec into container {npm_cid[:12]} ...")
py_script = (
"import sqlite3\n"
"conn = sqlite3.connect('/data/database.sqlite')\n"
f"snippet = {snippet!r}\n"
f"domain = {domain!r}\n"
"row = conn.execute(\n"
" 'SELECT id FROM proxy_host WHERE is_deleted=0 AND domain_names LIKE ?',\n"
" ('%' + domain + '%',)\n"
").fetchone()\n"
"if row: print('ID:' + str(row[0]))\n"
"cur = conn.execute(\n"
" 'UPDATE proxy_host SET advanced_config=?'\n"
" ' WHERE is_deleted=0 AND domain_names LIKE ?',\n"
" (snippet, '%' + domain + '%')\n"
")\n"
"conn.commit()\n"
"print(cur.rowcount)\n"
)
out = self._docker.run_exec(npm_cid, ["python3", "-c", py_script])
if out and out.strip():
for line in out.strip().splitlines():
if line.startswith("ID:"):
try:
host_id = int(line[3:])
except ValueError:
pass
else:
try:
rows_updated = int(line.strip())
except ValueError:
Console.warn(f"Unexpected output from docker exec: {line!r}")
else:
Console.warn("docker exec returned no output — python3 may not be available in the NPM container.")
# ── Patch the live nginx config file + reload nginx ────────────────────
# NPM doesn't regenerate its nginx config files when the DB is written
# directly (bypassing the NPM API). We patch the file ourselves and
# reload nginx so the change is instant — no NPM restart needed.
if host_id is not None and rows_updated:
self._patch_nginx_conf(host_id, snippet, npm_cid)
return rows_updated
def _patch_nginx_conf(self, host_id: int, snippet: str, npm_cid: str) -> None:
"""Write `snippet` into the live nginx proxy host config file and reload nginx."""
# Determine the nginx config file path on the host filesystem
nginx_conf: Optional[Path] = None
db_path = self._find_npm_db_via_inspect(npm_cid) if npm_cid else None
if db_path:
# data dir is the parent of database.sqlite (or its parent if nested)
data_dir = db_path.parent
if data_dir.name == "data":
data_dir = data_dir # already at /data
nginx_conf = data_dir / "nginx" / "proxy_host" / f"{host_id}.conf"
if not nginx_conf:
# Fallback: look relative to CWD (the --path target dir)
nginx_conf = Path.cwd() / "data" / "nginx" / "proxy_host" / f"{host_id}.conf"
if not nginx_conf or not nginx_conf.exists():
Console.warn(
f"Could not find nginx config for proxy host {host_id} "
f"— nginx reload skipped. Changes will apply after NPM restart."
)
return
try:
original = nginx_conf.read_text(encoding="utf-8")
# Remove any existing wakeonrequest snippet first (idempotent)
import re as _re
cleaned = _re.sub(
r'\n?# wake-on-request begin.*?# wake-on-request end\n?',
'',
original,
flags=_re.DOTALL,
)
# Insert before the first `location` block
tagged = f"\n# wake-on-request begin\n{snippet.strip()}\n# wake-on-request end\n"
if 'location ' in cleaned:
patched = cleaned.replace(
cleaned[cleaned.index('location '):],
tagged + cleaned[cleaned.index('location '):],
1,
)
else:
patched = cleaned + tagged
nginx_conf.write_text(patched, encoding="utf-8")
Console.ok(f"Nginx config patched: data/nginx/proxy_host/{host_id}.conf")
except Exception as exc:
Console.warn(f"Could not patch nginx config file: {exc}")
return
# Reload nginx inside the NPM container
if npm_cid:
out = self._docker.run_exec(npm_cid, ["nginx", "-s", "reload"])
if out is not None:
Console.ok("Nginx reloaded — advanced config is live immediately.")
else:
Console.warn("nginx reload failed — changes apply after next NPM restart.")
else:
Console.info("Nginx reload skipped (no NPM container found). Restart NPM to apply.")
# ── Compose File Resolver ──────────────────────────────────────────────────────
class ComposeResolver:
"""Find the docker-compose.yml for a container using multiple fallback strategies."""
_FILENAMES = [
"docker-compose.yml",
"docker-compose.yaml",
"compose.yml",
"compose.yaml",
]
def resolve(
self,
config_files: str,
working_dir: str,
mounts: list[str],
service_name: Optional[str] = None,
) -> Optional[Path]:
# Strategy 1: config_files label
if config_files:
p = self._wsl_path(config_files)
if p and p.is_file():
return p
# Strategy 2: working_dir + common filenames
if working_dir:
wdir = self._wsl_path(working_dir)
if wdir and wdir.is_dir():
for name in self._FILENAMES:
candidate = wdir / name
if candidate.is_file():
return candidate
# Strategy 3: Walk up from each bind mount (up to 4 parents)
for mount_src in mounts:
candidate = self._search_from_mount(mount_src, service_name)
if candidate:
return candidate
# Strategy 4: Return translated path even if not found (for display)
if config_files:
return self._wsl_path(config_files)
return None
def _search_from_mount(self, mount_src: str, service_name: Optional[str] = None) -> Optional[Path]:
p = self._wsl_path(mount_src)
if p is None:
return None
if p.is_file():
p = p.parent
depth = 0
while p and p != p.parent and depth < 4:
for name in self._FILENAMES:
candidate = p / name
if candidate.is_file():
if service_name and service_name not in candidate.read_text():
continue
return candidate
p = p.parent
depth += 1
return None
@staticmethod
def _wsl_path(raw: str) -> Optional[Path]:
"""Return Path from a raw string, or None if empty."""
return Path(raw) if raw else None
# ── Compose File Patcher ───────────────────────────────────────────────────────
class ComposePatcher:
"""Reads, validates, backs up, and patches docker-compose.yml."""
def __init__(self, compose_path: Path) -> None:
self.path = compose_path
def validate(self) -> bool:
"""Return True if the file is parseable YAML with a services: block."""
try:
import importlib
yaml_mod = importlib.import_module("yaml")
try:
with self.path.open() as f:
yaml_mod.safe_load(f)
return True
except Exception:
return False
except ImportError:
pass
# Fallback: basic structural check
text = self.path.read_text()
return "services:" in text
def backup(self) -> Path:
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
bak = self.path.with_suffix(f"{self.path.suffix}.bak.{ts}.{uuid.uuid4().hex[:8]}")
shutil.copy2(self.path, bak)
Console.info(f"Backed up {self.path.name} → {bak.name}")
return bak
def volumes_section_count(self) -> int:
"""Count top-level volumes: blocks (to detect multi-service compose files)."""
text = self.path.read_text()
return len(re.findall(r"^\s{2,}volumes:", text, re.MULTILINE))
def has_volume(self, volume_string: str) -> bool:
return volume_string in self.path.read_text()
def add_volumes(self, volumes: list[str]) -> bool:
"""
Idempotently add volumes under the first 'volumes:' block found.
Returns True if the file was successfully modified and verified.
"""
try:
text = self.path.read_text()
except Exception:
return False
changed = False
for vol in volumes:
if vol in text:
continue
# Find first indented volumes: block and insert after it
match = re.search(r"^( {2,})volumes:[ \t]*\n", text, re.MULTILINE)
if match:
indent = len(match.group(1))
vol_indent = " " * (indent + 2)
insertion = f"{vol_indent}- {vol}\n"
pos = match.end()
text = text[:pos] + insertion + text[pos:]
changed = True
if changed:
try:
self.path.write_text(text)
# Verification pass
if volumes[0] not in self.path.read_text():
return False
except Exception:
return False
return changed
def add_labels_to_service(
self,
service_name: str,
labels: list[str],
) -> bool:
"""
Add wakeonrequest labels under a named service. Returns True if changed.
Safe fallback: if YAML module available, round-trip parse;
otherwise display instructions rather than risk corrupting the file.