-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmain.py
More file actions
1023 lines (902 loc) · 38 KB
/
main.py
File metadata and controls
1023 lines (902 loc) · 38 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
from utils.config_loader import CONFIG_MANAGER as config
from utils.global_logger import logger, websocket_manager
from utils import user_management
from api.api_service import start_fastapi_process
from api.connection_manager import ConnectionManager
from utils.metrics_history import MetricsHistoryWriter
from utils.processes import ProcessHandler
from utils.auto_update import Update
from utils.dependencies import initialize_dependencies
from utils.core_services import get_core_services, has_core_service
from utils.dependency_map import build_conditional_dependency_map
from utils.plex_dbrepair import start_plex_dbrepair_worker
from utils.ffprobe_monitor import start_ffprobe_monitor
from utils.setup import setup_project
from utils.seerr_sync import start_seerr_sync_service
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED, as_completed
import subprocess, threading, time, tomllib, os, socket, errno, psutil, json, urllib.parse
def log_ascii_art():
env_version = (os.environ.get("DUMB_VERSION") or "").strip()
if env_version:
version = env_version
else:
with open("pyproject.toml", "rb") as file:
pyproject = tomllib.load(file)
version = pyproject["tool"]["poetry"]["version"]
ascii_art = f"""
DDDDDDDDDDDDD UUUUUUUU UUUUUUUUMMMMMMMM MMMMMMMMBBBBBBBBBBBBBBBBB
D::::::::::::DDD U::::::U U::::::UM:::::::M M:::::::MB::::::::::::::::B
D:::::::::::::::DD U::::::U U::::::UM::::::::M M::::::::MB::::::BBBBBB:::::B
DDD:::::DDDDD:::::D UU:::::U U:::::UUM:::::::::M M:::::::::MBB:::::B B:::::B
D:::::D D:::::D U:::::U U:::::U M::::::::::M M::::::::::M B::::B B:::::B
D:::::D D:::::DU:::::D D:::::U M:::::::::::M M:::::::::::M B::::B B:::::B
D:::::D D:::::DU:::::D D:::::U M:::::::M::::M M::::M:::::::M B::::BBBBBB:::::B
D:::::D D:::::DU:::::D D:::::U M::::::M M::::M M::::M M::::::M B:::::::::::::BB
D:::::D D:::::DU:::::D D:::::U M::::::M M::::M::::M M::::::M B::::BBBBBB:::::B
D:::::D D:::::DU:::::D D:::::U M::::::M M:::::::M M::::::M B::::B B:::::B
D:::::D D:::::DU:::::D D:::::U M::::::M M:::::M M::::::M B::::B B:::::B
D:::::D D:::::D U::::::U U::::::U M::::::M MMMMM M::::::M B::::B B:::::B
DDD:::::DDDDD:::::D U:::::::UUU:::::::U M::::::M M::::::MBB:::::BBBBBB::::::B
D:::::::::::::::DD UU:::::::::::::UU M::::::M M::::::MB:::::::::::::::::B
D::::::::::::DDD UU:::::::::UU M::::::M M::::::MB::::::::::::::::B
DDDDDDDDDDDDD UUUUUUUUU MMMMMMMM MMMMMMMMBBBBBBBBBBBBBBBBB
Version: {version}
"""
logger.info(ascii_art + "\n")
def _find_free_port(start_port: int, used_ports: set[int]) -> int:
port = start_port
while port in used_ports or not _is_port_available(port):
port += 1
return port
def _check_bind(family: int, addr: str, port: int) -> bool | None:
sock = None
try:
sock = socket.socket(family, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if family == socket.AF_INET6:
try:
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
except OSError:
pass
sock.bind((addr, port))
return True
except OSError as exc:
if exc.errno in (errno.EADDRINUSE, errno.EACCES, errno.EPERM):
return False
if exc.errno in (errno.EAFNOSUPPORT, errno.EADDRNOTAVAIL, errno.EINVAL):
return None
return False
finally:
if sock is not None:
sock.close()
def _is_port_available(port: int) -> bool:
try:
for conn in psutil.net_connections(kind="inet"):
if conn.status == psutil.CONN_LISTEN and conn.laddr:
if conn.laddr.port == port:
return False
except Exception:
pass
checks = [
(socket.AF_INET, "0.0.0.0"),
(socket.AF_INET6, "::"),
]
for family, addr in checks:
result = _check_bind(family, addr, port)
if result is False:
return False
return True
def _reserve_port(
used_ports: dict[int, str], desired: int, owner: str, label: str
) -> tuple[int | None, bool]:
if not isinstance(desired, int) or desired <= 0:
return None, False
existing_owner = used_ports.get(desired)
if existing_owner and existing_owner != owner:
new_port = _find_free_port(desired + 1, set(used_ports.keys()))
logger.info(
"Port %s already in use by %s; assigning %s for %s.",
desired,
existing_owner,
new_port,
label,
)
used_ports[new_port] = owner
return new_port, True
if not _is_port_available(desired):
new_port = _find_free_port(desired + 1, set(used_ports.keys()))
logger.info(
"Port %s already in use by another process; assigning %s for %s.",
desired,
new_port,
label,
)
used_ports[new_port] = owner
return new_port, True
used_ports[desired] = owner
return desired, False
def _reserve_config_port(
cfg: dict,
field: str,
used_ports: dict[int, str],
owner: str,
label: str,
) -> bool:
desired = cfg.get(field)
chosen, changed = _reserve_port(used_ports, desired, owner, label)
if chosen is None:
return False
if cfg.get(field) != chosen:
cfg[field] = chosen
return True
return changed
def _seed_used_ports(config_obj: dict, used_ports: dict[int, str]) -> None:
if not isinstance(config_obj, dict):
return
def _add(port: int | None, owner: str) -> None:
if not isinstance(port, int) or port <= 0:
return
if port in used_ports and used_ports[port] != owner:
logger.warning(
"Port %s already reserved by %s; %s may be auto-shifted.",
port,
used_ports[port],
owner,
)
return
used_ports[port] = owner
for key, cfg in config_obj.items():
if not isinstance(cfg, dict):
continue
if key == "dumb":
for subkey in ("api_service", "frontend"):
subcfg = cfg.get(subkey, {})
if isinstance(subcfg, dict) and subcfg.get("enabled"):
_add(subcfg.get("port"), f"dumb_{subkey}:port")
continue
if "instances" in cfg and isinstance(cfg["instances"], dict):
for inst_name, inst_cfg in cfg["instances"].items():
if isinstance(inst_cfg, dict) and inst_cfg.get("enabled"):
_add(inst_cfg.get("port"), f"{key}:{inst_name}")
continue
if cfg.get("enabled"):
if key == "nzbdav":
_add(cfg.get("frontend_port"), "nzbdav:frontend_port")
_add(cfg.get("backend_port"), "nzbdav:backend_port")
_add(cfg.get("port"), f"{key}:port")
def _apply_global_port_reservations(config_manager) -> None:
used_ports: dict[int, str] = {}
_seed_used_ports(config_manager.config, used_ports)
changed = False
dumb_cfg = config_manager.get("dumb", {})
for subkey in ("api_service", "frontend"):
subcfg = dumb_cfg.get(subkey, {})
if isinstance(subcfg, dict) and subcfg.get("enabled"):
changed |= _reserve_config_port(
subcfg,
"port",
used_ports,
f"dumb_{subkey}:port",
f"DUMB {subkey} port",
)
for key, cfg in config_manager.config.items():
if key == "dumb" or not isinstance(cfg, dict):
continue
if "instances" in cfg and isinstance(cfg["instances"], dict):
for inst_name, inst_cfg in cfg["instances"].items():
if isinstance(inst_cfg, dict) and inst_cfg.get("enabled"):
changed |= _reserve_config_port(
inst_cfg,
"port",
used_ports,
f"{key}:{inst_name}",
f"{key} {inst_name} port",
)
continue
if cfg.get("enabled"):
if key == "nzbdav":
changed |= _reserve_config_port(
cfg,
"frontend_port",
used_ports,
"nzbdav:frontend_port",
"NzbDAV frontend port",
)
changed |= _reserve_config_port(
cfg,
"backend_port",
used_ports,
"nzbdav:backend_port",
"NzbDAV backend port",
)
changed |= _reserve_config_port(
cfg,
"port",
used_ports,
f"{key}:port",
f"{key} port",
)
if changed:
config_manager.save_config()
def start_configured_process(config_obj, updater, key_name, exit_on_error=True):
try:
if "instances" in config_obj:
any_enabled = False
for name, instance in config_obj["instances"].items():
if instance.get("enabled"):
process_name = instance.get("process_name", name)
auto = instance.get("auto_update", False)
success, error = updater.auto_update(process_name, auto)
if not success and error:
logger.error(
"Startup for %s failed (instance %s): %s",
process_name,
name,
error,
)
any_enabled = True
if key_name in {"profilarr", "sonarr", "radarr"}:
_run_profilarr_sync_retries(key_name)
if not any_enabled:
logger.debug(f"No enabled instances found in {key_name}. Skipping.")
elif config_obj.get("enabled"):
process_name = config_obj.get("process_name", key_name)
auto = config_obj.get("auto_update", False)
success, error = updater.auto_update(process_name, auto)
if not success and error:
logger.error("Startup for %s failed: %s", process_name, error)
if key_name in {"profilarr", "sonarr", "radarr"}:
_run_profilarr_sync_retries(key_name)
else:
logger.debug(f"{key_name} is disabled. Skipping process start.")
except Exception as e:
logger.error(f"An error occurred in setup for {key_name}: {e}")
if exit_on_error:
raise
def _service_has_enabled_instance(config_obj: dict) -> bool:
if not isinstance(config_obj, dict):
return False
if "instances" in config_obj and isinstance(config_obj["instances"], dict):
return any(
isinstance(inst, dict) and inst.get("enabled")
for inst in config_obj["instances"].values()
)
return bool(config_obj.get("enabled"))
def _migrate_huntarr_to_neutarr(config_manager) -> None:
"""One-time migration: rename 'huntarr' service key to 'neutarr' and update
all associated paths, env vars, and use_huntarr flags in-place. Persists
to disk only when changes are detected."""
changed = False
cfg = config_manager.config
# 1. Rename top-level service key
if "huntarr" in cfg and "neutarr" not in cfg:
cfg["neutarr"] = cfg.pop("huntarr")
changed = True
# 2. Update neutarr instance internals
neutarr_cfg = cfg.get("neutarr")
if isinstance(neutarr_cfg, dict):
instances = neutarr_cfg.get("instances") or {}
if isinstance(instances, dict):
for inst in instances.values():
if not isinstance(inst, dict):
continue
if inst.get("process_name") == "Huntarr":
inst["process_name"] = "NeutArr"
changed = True
if inst.get("repo_owner") == "plexguide":
inst["repo_owner"] = "I-am-PUID-0"
changed = True
if inst.get("repo_name") == "Huntarr.io":
inst["repo_name"] = "NeutArr"
changed = True
# Paths: /huntarr/ → /neutarr/
for path_key in ("config_dir", "config_file", "log_file"):
val = inst.get(path_key)
if isinstance(val, str) and "/huntarr/" in val:
inst[path_key] = val.replace("/huntarr/", "/neutarr/")
changed = True
if isinstance(val := inst.get("config_file"), str) and val.endswith("huntarr.db"):
inst["config_file"] = val[: -len("huntarr.db")] + "general.json"
changed = True
if isinstance(inst.get("command"), list):
new_cmd = [
c.replace("/huntarr/", "/neutarr/") if isinstance(c, str) else c
for c in inst["command"]
]
if new_cmd != inst["command"]:
inst["command"] = new_cmd
changed = True
if isinstance(inst.get("exclude_dirs"), list):
new_excl = [
d.replace("/huntarr/", "/neutarr/") if isinstance(d, str) else d
for d in inst["exclude_dirs"]
]
if new_excl != inst["exclude_dirs"]:
inst["exclude_dirs"] = new_excl
changed = True
# Env keys/values
env = inst.get("env")
if isinstance(env, dict):
if "HUNTARR_CONFIG_DIR" in env:
env["NEUTARR_CONFIG_DIR"] = env.pop("HUNTARR_CONFIG_DIR").replace(
"/huntarr/", "/neutarr/"
)
changed = True
if "HUNTARR_PORT" in env:
env["NEUTARR_PORT"] = env.pop("HUNTARR_PORT")
changed = True
for k, v in list(env.items()):
if isinstance(v, str) and "/huntarr/" in v:
env[k] = v.replace("/huntarr/", "/neutarr/")
changed = True
# 3. Migrate use_huntarr → use_neutarr on Arr service instances
for svc_key in ("sonarr", "radarr", "lidarr", "whisparr", "eros"):
svc_cfg = cfg.get(svc_key)
if not isinstance(svc_cfg, dict):
continue
for inst in (svc_cfg.get("instances") or {}).values():
if not isinstance(inst, dict):
continue
if "use_huntarr" in inst:
inst["use_neutarr"] = inst.pop("use_huntarr")
changed = True
if changed:
config_manager.save_config()
logger.info("Migrated huntarr → neutarr config entries")
def _service_has_neutarr_instance(config_obj: dict) -> bool:
if not isinstance(config_obj, dict):
return False
if "instances" not in config_obj or not isinstance(config_obj["instances"], dict):
return False
return any(
isinstance(inst, dict) and inst.get("enabled") and inst.get("use_neutarr")
for inst in config_obj["instances"].values()
)
def _enable_neutarr_if_needed(config_manager) -> None:
if not any(
_service_has_neutarr_instance(config_manager.get(svc, {}))
for svc in ("sonarr", "radarr", "lidarr", "whisparr")
):
return
neutarr_cfg = config_manager.get("neutarr", {})
if not isinstance(neutarr_cfg, dict):
return
instances = neutarr_cfg.get("instances", {}) or {}
if not isinstance(instances, dict) or not instances:
return
if any(
isinstance(inst, dict) and inst.get("enabled") for inst in instances.values()
):
return
first = next(iter(instances.values()))
if isinstance(first, dict):
first["enabled"] = True
config_manager.save_config()
def _run_profilarr_sync_retries(start_key: str) -> None:
try:
from utils.profilarr_settings import (
any_arr_uses_profilarr,
patch_profilarr_config,
)
if start_key != "profilarr" and not any_arr_uses_profilarr():
return
ok, err = patch_profilarr_config()
if not ok and err:
logger.warning("Profilarr config sync failed: %s", err)
if start_key in {"sonarr", "radarr"}:
for attempt in range(2):
time.sleep(10)
ok, err = patch_profilarr_config()
if ok:
break
if err:
logger.warning(
"Profilarr config retry %s failed: %s", attempt + 1, err
)
except Exception as exc:
logger.warning("Profilarr config sync skipped: %s", exc)
def _read_decypharr_mount_path(decypharr_cfg: dict) -> str | None:
mount_type = (decypharr_cfg.get("mount_type") or "").strip().lower()
if mount_type not in {"rclone", "dfs"}:
return None
config_file = decypharr_cfg.get("config_file")
if config_file and os.path.exists(config_file):
try:
with open(config_file, "r") as handle:
data = json.load(handle)
mount_path = (data.get("mount") or {}).get("mount_path")
if not mount_path:
mount_path = (data.get("rclone") or {}).get("mount_path")
if isinstance(mount_path, str) and mount_path.strip():
return mount_path
except Exception as e:
logger.debug("Failed to read Decypharr mount path: %s", e)
return "/mnt/debrid/decypharr"
def _extract_decypharr_debrid_mount(
folder_path: str, mount_base: str | None
) -> str | None:
if not folder_path:
return None
norm_path = os.path.normpath(folder_path)
candidates = []
if mount_base:
candidates.append(os.path.normpath(mount_base))
candidates.append("/mnt/debrid/decypharr")
for base in candidates:
if norm_path.startswith(base + os.sep):
rel = norm_path[len(base) + 1 :]
parts = [p for p in rel.split(os.sep) if p]
if parts:
return os.path.join(base, parts[0])
return None
def _collect_decypharr_mount_paths(decypharr_cfg: dict) -> list[str]:
mount_type = (decypharr_cfg.get("mount_type") or "").strip().lower()
if mount_type not in {"rclone", "dfs"}:
return []
branch_name = (decypharr_cfg.get("branch") or "").strip().lower()
beta_branch_requested = (
bool(decypharr_cfg.get("branch_enabled")) and branch_name == "beta"
)
config_file = decypharr_cfg.get("config_file")
if not config_file or not os.path.exists(config_file):
return []
try:
with open(config_file, "r") as handle:
data = json.load(handle)
except Exception as e:
logger.debug("Failed to read Decypharr config: %s", e)
return []
mount_block = data.get("mount") if isinstance(data.get("mount"), dict) else {}
debrids = data.get("debrids") or []
mount_mode = (mount_block.get("type") or "").strip().lower()
mount_base = mount_block.get("mount_path")
if not mount_base:
mount_base = (data.get("rclone") or {}).get("mount_path")
if not isinstance(mount_base, str):
mount_base = None
if not mount_base:
cfg_mount_base = decypharr_cfg.get("mount_path")
if isinstance(cfg_mount_base, str) and cfg_mount_base.strip():
mount_base = cfg_mount_base.strip()
else:
mount_base = "/mnt/debrid/decypharr"
if beta_branch_requested:
return [mount_base]
# New consolidated config uses top-level "mount" with a single mount_path
# for both DFS and rclone modes. Legacy/stable configs may still carry a
# stale top-level mount block while provider-specific debrid folders are the
# true source for mount waits, so only treat it as consolidated when those
# folder paths are not present.
has_legacy_debrid_folders = any(
isinstance(debrid, dict)
and isinstance(debrid.get("folder"), str)
and debrid.get("folder").strip()
for debrid in debrids
)
if mount_mode in {"dfs", "rclone"} and not has_legacy_debrid_folders:
return [mount_base] if mount_base else []
if mount_mode in {"external_rclone", "none"}:
return []
mounts = set()
for debrid in debrids:
if not isinstance(debrid, dict):
continue
folder = debrid.get("folder")
mount_path = _extract_decypharr_debrid_mount(folder, mount_base)
if mount_path:
mounts.add(mount_path)
elif mount_base:
debrid_name = debrid.get("name") or debrid.get("provider")
if debrid_name:
mounts.add(os.path.join(mount_base, str(debrid_name)))
# For legacy non-consolidated mounts, infer provider paths from api_keys if
# debrids[] has not been materialized yet.
if not mounts and mount_base:
for provider_name in (decypharr_cfg.get("api_keys") or {}).keys():
if provider_name:
mounts.add(os.path.join(mount_base, str(provider_name)))
return sorted(mounts)
def _collect_mount_paths(config_manager) -> list[str]:
mount_paths = set()
rclone_instances = config_manager.get("rclone", {}).get("instances", {}) or {}
for instance in rclone_instances.values():
if not isinstance(instance, dict) or not instance.get("enabled"):
continue
mount_dir = instance.get("mount_dir")
mount_name = instance.get("mount_name")
if mount_dir and mount_name:
mount_paths.add(os.path.join(mount_dir, mount_name))
decypharr_cfg = config_manager.get("decypharr", {}) or {}
mount_type = (decypharr_cfg.get("mount_type") or "").strip().lower()
if decypharr_cfg.get("enabled") and mount_type in {"rclone", "dfs"}:
decypharr_mounts = _collect_decypharr_mount_paths(decypharr_cfg)
if decypharr_mounts:
mount_paths.update(decypharr_mounts)
else:
mount_path = _read_decypharr_mount_path(decypharr_cfg)
if mount_path:
mount_paths.add(mount_path)
return sorted(mount_paths)
def _merge_wait_for_mounts(config_obj: dict, mount_paths: list[str]) -> None:
existing = config_obj.get("wait_for_mounts") or []
merged = sorted(set(existing) | set(mount_paths))
if merged:
config_obj["wait_for_mounts"] = merged
def _set_wait_for_urls(config_obj: dict, wait_entries: list[dict]) -> None:
existing = []
seen = set()
for entry in wait_entries:
url = entry.get("url")
if url and url not in seen:
existing.append(entry)
seen.add(url)
if existing:
config_obj["wait_for_url"] = existing
else:
config_obj.pop("wait_for_url", None)
def _apply_mount_waits(config_manager, mount_paths: list[str]) -> None:
if not mount_paths:
return
mount_wait_keys = {
"plex",
"jellyfin",
"emby",
}
for key in mount_wait_keys:
cfg = config_manager.get(key, {})
if not isinstance(cfg, dict):
continue
if "instances" in cfg and isinstance(cfg["instances"], dict):
for inst in cfg["instances"].values():
if isinstance(inst, dict) and inst.get("enabled"):
_merge_wait_for_mounts(inst, mount_paths)
elif cfg.get("enabled"):
_merge_wait_for_mounts(cfg, mount_paths)
def _collect_arr_ping_waits(config_manager) -> list[dict]:
wait_entries = []
for service in ("sonarr", "radarr", "lidarr", "whisparr"):
instances = config_manager.get(service, {}).get("instances", {}) or {}
for instance in instances.values():
if not isinstance(instance, dict) or not instance.get("enabled"):
continue
port = instance.get("port")
if not port:
continue
host = instance.get("host") or "127.0.0.1"
base_url = instance.get("base_url") or instance.get("url_base") or ""
if isinstance(base_url, str):
base_url = base_url.strip()
if base_url in ("", "/"):
base_url = ""
else:
base_url = "/" + base_url.lstrip("/")
else:
base_url = ""
wait_entries.append({"url": f"http://{host}:{port}{base_url}/ping"})
return wait_entries
def _apply_prowlarr_waits(config_manager, wait_entries: list[dict]) -> None:
if not wait_entries:
return
cfg = config_manager.get("prowlarr", {})
if not isinstance(cfg, dict):
return
wait_urls = [entry.get("url") for entry in wait_entries if entry.get("url")]
has_enabled = _service_has_enabled_instance(cfg)
if wait_urls and has_enabled:
logger.info(
"Prowlarr will wait for Arr services to be ready: %s",
", ".join(wait_urls),
)
if not has_enabled:
return
if "instances" in cfg and isinstance(cfg["instances"], dict):
for inst in cfg["instances"].values():
if isinstance(inst, dict) and inst.get("enabled"):
_set_wait_for_urls(inst, wait_entries)
elif cfg.get("enabled"):
_set_wait_for_urls(cfg, wait_entries)
def _build_plex_wait_entries(config_manager) -> list[dict]:
plex_cfg = config_manager.get("plex", {}) or {}
if not _service_has_enabled_instance(plex_cfg):
return []
plex_address = (config_manager.get("dumb", {}) or {}).get("plex_address") or ""
plex_port = plex_cfg.get("port", 32400)
base_url = ""
if plex_address:
parsed = urllib.parse.urlparse(plex_address)
if parsed.scheme and parsed.hostname:
host = parsed.hostname
if parsed.port:
base_url = f"{parsed.scheme}://{host}:{parsed.port}"
else:
base_url = f"{parsed.scheme}://{host}"
if not base_url:
base_url = f"http://127.0.0.1:{plex_port}"
return [{"url": f"{base_url}/identity", "core_service": "plex"}]
def _build_media_wait_entries(config_manager) -> list[dict]:
wait_entries = []
plex_entries = _build_plex_wait_entries(config_manager)
wait_entries.extend(plex_entries)
for key in ("jellyfin", "emby"):
cfg = config_manager.get(key, {}) or {}
if not _service_has_enabled_instance(cfg):
continue
port = cfg.get("port")
if not port:
continue
wait_entries.append(
{"url": f"http://127.0.0.1:{port}/System/Info/Public", "core_service": key}
)
return wait_entries
def _apply_waits_to_service(config_manager, key: str, wait_entries: list[dict]) -> None:
if not wait_entries:
return
cfg = config_manager.get(key, {})
if not isinstance(cfg, dict):
return
core_key = key.strip().lower()
if "instances" in cfg and isinstance(cfg["instances"], dict):
for inst in cfg["instances"].values():
if isinstance(inst, dict) and inst.get("enabled"):
inst_entries = wait_entries
if core_key == "seerr":
core_services = get_core_services(inst)
if core_services:
inst_entries = [
entry
for entry in wait_entries
if entry.get("core_service") in core_services
]
_set_wait_for_urls(inst, inst_entries)
elif cfg.get("enabled"):
inst_entries = wait_entries
if core_key == "seerr":
core_services = get_core_services(cfg)
if core_services:
inst_entries = [
entry
for entry in wait_entries
if entry.get("core_service") in core_services
]
_set_wait_for_urls(cfg, inst_entries)
def _collect_preinstall_targets(config_manager) -> list[tuple[str, str]]:
targets = []
for key, cfg in config_manager.config.items():
if not isinstance(cfg, dict):
continue
if key == "dumb":
continue
if "instances" in cfg and isinstance(cfg["instances"], dict):
for inst_cfg in cfg["instances"].values():
if isinstance(inst_cfg, dict) and inst_cfg.get("enabled"):
process_name = inst_cfg.get("process_name")
if process_name:
targets.append((key, process_name))
break
continue
if cfg.get("enabled"):
process_name = cfg.get("process_name")
if process_name:
targets.append((key, process_name))
return targets
def _preinstall_enabled_services(process_handler, config_manager) -> None:
targets = _collect_preinstall_targets(config_manager)
if not targets:
return
logger.info("Pre-installing enabled services before startup.")
max_workers = min(4, max(1, len(targets)))
def _run_preinstall(key: str, name: str) -> None:
if process_handler.shutting_down:
return
with process_handler.process_context(name):
if key in {"pgadmin", "postgres"}:
logger.info(
"Preinstall skip for %s; requires running dependency.", name
)
return
logger.info("Preinstall start: %s", name)
success, error = setup_project(process_handler, name, preinstall=True)
if not success:
raise RuntimeError(error)
process_handler.preinstalled_processes.add(name)
logger.info("Preinstall done: %s", name)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = {
executor.submit(_run_preinstall, key, name): name for key, name in targets
}
for future in as_completed(futures):
name = futures[future]
try:
future.result()
except Exception as e:
logger.error("Pre-install failed for %s: %s", name, e)
process_handler.shutdown(exit_code=1)
raise
logger.info("Pre-install phase complete.")
process_handler.preinstall_complete = True
def _build_dependency_map(config_manager) -> dict[str, set[str]]:
return build_conditional_dependency_map(lambda key: config_manager.get(key, {}))
def _start_processes_with_dependencies(
process_handler, updater, config_manager, keys: list[str], dependency_map
) -> None:
enabled = {
key: _service_has_enabled_instance(config_manager.get(key, {})) for key in keys
}
pending = {key for key in keys if enabled.get(key)}
deps = {
key: {d for d in dependency_map.get(key, set()) if enabled.get(d)}
for key in pending
}
def _start_key(key: str) -> None:
cfg = config_manager.get(key, {})
start_configured_process(cfg, updater, key)
in_progress = {}
completed = set()
with ThreadPoolExecutor() as executor:
while pending or in_progress:
if process_handler.shutting_down:
for future in list(in_progress):
future.cancel()
return
ready = [key for key in list(pending) if deps.get(key, set()) <= completed]
for key in ready:
if process_handler.shutting_down:
break
pending.remove(key)
in_progress[executor.submit(_start_key, key)] = key
if not in_progress:
raise RuntimeError(
f"Dependency resolution stalled. Remaining: {sorted(pending)}"
)
done, _ = wait(in_progress.keys(), return_when=FIRST_COMPLETED)
for future in done:
key = in_progress.pop(future)
try:
future.result()
except Exception as e:
logger.error("Failed while starting %s: %s", key, e)
process_handler.shutdown(exit_code=1)
completed.add(key)
def main():
log_ascii_art()
process_handler = ProcessHandler(logger)
updater = Update(process_handler)
metrics_manager = ConnectionManager()
status_manager = ConnectionManager()
initialize_dependencies(
process_handler=process_handler,
updater=updater,
websocket_manager=websocket_manager,
metrics_manager=metrics_manager,
status_manager=status_manager,
logger=logger,
)
process_handler.start_auto_restart_monitor()
try:
user_management.create_system_user()
except Exception as e:
logger.error(f"An error occurred while creating system user: {e}")
process_handler.shutdown(exit_code=1)
_apply_global_port_reservations(config)
mount_paths = _collect_mount_paths(config)
_apply_mount_waits(config, mount_paths)
_apply_prowlarr_waits(config, _collect_arr_ping_waits(config))
_apply_waits_to_service(config, "tautulli", _build_plex_wait_entries(config))
_apply_waits_to_service(config, "seerr", _build_media_wait_entries(config))
_preinstall_enabled_services(process_handler, config)
if config.get("dumb", {}).get("api_service", {}).get("enabled"):
start_fastapi_process()
api_cfg = config.get("dumb", {}).get("api_service", {})
api_name = api_cfg.get("process_name", "DUMB API")
process_handler.register_external_process(api_name, os.getpid())
try:
dumb_config = config.get("dumb", {})
start_configured_process(dumb_config.get("frontend", {}), updater, "frontend")
except Exception:
process_handler.shutdown(exit_code=1)
def metrics_history_worker():
def _get_metrics_cfg():
cfg_root = config.config if hasattr(config, "config") else config
return (cfg_root.get("dumb", {}) or {}).get("metrics", {})
from utils.dependencies import get_metrics_collector
collector = get_metrics_collector()
writer = None
last_writer_cfg = None
while True:
try:
metrics_cfg = _get_metrics_cfg()
enabled = metrics_cfg.get("history_enabled", True)
interval = metrics_cfg.get("history_interval_sec", 5)
retention_days = metrics_cfg.get("history_retention_days", 7)
max_file_mb = metrics_cfg.get("history_max_file_mb", 50)
max_total_mb = metrics_cfg.get("history_max_total_mb", 100)
history_dir = metrics_cfg.get("history_dir", "/config/metrics")
try:
interval = float(interval)
except (TypeError, ValueError):
interval = 5.0
interval = max(0.5, interval)
writer_cfg = (history_dir, retention_days, max_file_mb, max_total_mb)
if enabled:
if writer is None or writer_cfg != last_writer_cfg:
writer = MetricsHistoryWriter(
base_dir=history_dir,
retention_days=retention_days,
max_file_mb=max_file_mb,
max_total_mb=max_total_mb,
logger=logger,
)
last_writer_cfg = writer_cfg
snapshot = collector.snapshot()
writer.write(snapshot)
else:
writer = None
last_writer_cfg = None
except Exception as e:
logger.error(f"Metrics history worker error: {e}")
time.sleep(interval)
try:
if config.get("traefik", {}).get("enabled"):
start_configured_process(config.get("traefik", {}), updater, "traefik")
grouped_keys = [
"zurg",
"radarr",
"sonarr",
"lidarr",
"whisparr",
"prowlarr",
"neutarr",
"profilarr",
"decypharr",
"nzbdav",
"rclone",
"postgres",
"pgadmin",
"zilean",
"plex_debrid",
"phalanx_db",
"cli_debrid",
"cli_battery",
"riven_backend",
"riven_frontend",
"plex",
"jellyfin",
"emby",
"tautulli",
"seerr",
]
_migrate_huntarr_to_neutarr(config)
_enable_neutarr_if_needed(config)
dependency_map = _build_dependency_map(config)
_start_processes_with_dependencies(
process_handler, updater, config, grouped_keys, dependency_map
)
except Exception as e:
logger.error(e)
process_handler.shutdown(exit_code=1)
start_ffprobe_monitor(process_handler, logger)
def healthcheck():
time.sleep(60)
while True:
time.sleep(10)
try:
result = subprocess.run(
["python", "healthcheck.py"], capture_output=True, text=True
)
if result.stderr: