-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworker_template.py
More file actions
2447 lines (2205 loc) · 111 KB
/
worker_template.py
File metadata and controls
2447 lines (2205 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import time
import requests
import subprocess
import os
import re
import shutil
import threading
import sys
import platform
import json
import signal
import zipfile
import tarfile
import gzip
import traceback
import ctypes
import hashlib
from datetime import datetime, timedelta
# Textual TUI (optional — install with: pip install textual)
# Minimum required version: 0.20 (RichLog, ModalScreen, Binding, DataTable etc.)
_TEXTUAL_MIN_VERSION = (0, 20)
_VENV_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.worker_venv')
def _bootstrap_textual():
"""Auto-install/upgrade textual if missing or too old, then re-exec.
Strategy:
1. Try plain pip install into the current interpreter (works on most systems).
2. If pip rejects it (externally-managed-environment / PEP 668), create a
local venv at _VENV_DIR and install there, then re-exec with that Python.
"""
try:
import textual as _t
try:
from importlib.metadata import version as _pkg_version
_tv_str = _pkg_version('textual')
except Exception:
_tv_str = getattr(_t, '__version__', '0.0')
if tuple(int(x) for x in _tv_str.split('.')[:2]) >= _TEXTUAL_MIN_VERSION:
return # already fine
reason = f"textual {_tv_str} is too old (>= {'.'.join(str(x) for x in _TEXTUAL_MIN_VERSION)} required)"
except ImportError:
reason = "textual not found"
print(f"[*] {reason} — attempting automatic install...")
# Attempt 1: plain pip upgrade into current interpreter
result = subprocess.run(
[sys.executable, '-m', 'pip', 'install', '--upgrade', 'textual'],
capture_output=True, text=True,
)
if result.returncode == 0:
print("[*] textual installed — restarting...")
os.execv(sys.executable, [sys.executable] + sys.argv)
# Attempt 2: create/reuse a local venv and install there
print("[*] pip install failed (system-managed env?) — trying local venv...")
try:
import venv as _venv
if not os.path.isdir(_VENV_DIR):
print(f"[*] Creating venv at {_VENV_DIR} ...")
_venv.create(_VENV_DIR, with_pip=True)
venv_python = (
os.path.join(_VENV_DIR, 'Scripts', 'python.exe') # Windows
if sys.platform == 'win32' else
os.path.join(_VENV_DIR, 'bin', 'python')
)
result2 = subprocess.run(
[venv_python, '-m', 'pip', 'install', '--upgrade', 'textual', 'requests'],
capture_output=True, text=True,
)
if result2.returncode == 0:
print(f"[*] textual installed in venv — restarting under {venv_python} ...")
os.execv(venv_python, [venv_python] + sys.argv)
else:
print(f"[!] venv pip install failed:\n{result2.stderr.strip()}")
except Exception as _ve:
print(f"[!] venv setup failed: {_ve}")
print("[!] Could not install textual automatically — continuing without TUI.")
_bootstrap_textual()
try:
import textual as _textual_mod
try:
from importlib.metadata import version as _pkg_version
_tv_str = _pkg_version('textual')
except Exception:
_tv_str = getattr(_textual_mod, '__version__', '0.0')
_tv = tuple(int(x) for x in _tv_str.split('.')[:2])
if _tv < _TEXTUAL_MIN_VERSION:
raise ImportError(
f"textual {_tv_str} is too old; "
f">= {'.'.join(str(x) for x in _TEXTUAL_MIN_VERSION)} required"
)
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, RichLog, DataTable, Button, Label
from textual.screen import ModalScreen
from textual.containers import Horizontal, Vertical
from textual.binding import Binding
HAS_TEXTUAL = True
_TEXTUAL_UNAVAIL_REASON = ""
except ImportError as _e:
HAS_TEXTUAL = False
_TEXTUAL_UNAVAIL_REASON = str(_e)
# ==============================================================================
# CONFIGURATION
# ==============================================================================
DEFAULT_MANAGER_URL = "https://encode.fractumseraph.net/"
DEFAULT_USERNAME = "Anonymous"
DEFAULT_WORKERNAME = f"Node-{int(time.time())}"
WORKER_VERSION = "3.0.26"
WORKER_SECRET = os.environ.get("WORKER_SECRET", "DefaultInsecureSecret")
SHUTDOWN_EVENT = threading.Event()
UPDATE_AVAILABLE = False
LAST_UPDATE_CHECK = 0
CHECK_LOCK = threading.Lock()
CONSOLE_LOCK = threading.Lock()
PROGRESS_LOCK = threading.Lock()
MONITOR_PAUSED = threading.Event()
WORKER_PROGRESS = {}
PAUSE_REQUESTED = False
ACTIVE_PROCS = {}
PROC_LOCK = threading.Lock()
TUI_APP = None # Set to WorkerApp instance when running in TUI mode
_TUI_WAS_RUNNING = False # Set True before app.run(), never cleared; guards safe_print post-TUI
_TUI_SIGNAL = None # Set to 'pause' or 'quit' by signal handler, polled by app timer
# Per-worker rich state, polled by the TUI every 0.5s
# {"file": str, "phase": str, "pct": int, "job_start": float, "jobs_done": int}
WORKER_DETAILS = {}
SESSION_STATS = {"jobs_done": 0, "bytes_uploaded": 0, "start": 0.0}
STATS_LOCK = threading.Lock()
# Global paths for executables
FFMPEG_CMD = "ffmpeg"
FFPROBE_CMD = "ffprobe"
_FFMPEG_META_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.ffmpeg_meta.json')
# Detect OS to handle Fonts
_script_dir = os.path.dirname(os.path.abspath(__file__))
ENCODING_CONFIG = {
"VIDEO_CODEC": "libsvtav1",
"VIDEO_PRESET": "2",
"VIDEO_CRF": "63",
"VIDEO_PIX_FMT": "yuv420p",
"VIDEO_SCALE": "scale=-2:480",
"AUDIO_CODEC": "libopus",
"AUDIO_BITRATE": "24k", # Perfect for Mono Speech
"AUDIO_CHANNELS": "1", # CHANGED: 2 -> 1 (Mono) for better quality
"SUBTITLE_CODEC": "mov_text",
"OUTPUT_EXT": ".mp4"
}
class QuotaTracker:
def __init__(self, limit_gb, worker_name):
self.limit_bytes = int(limit_gb * 1024**3) if limit_gb > 0 else 0
self.filename = f"usage_{re.sub(r'[^a-zA-Z0-9]', '', worker_name)}.json"
self.lock = threading.Lock()
self.current_usage = 0
self.last_save = 0
self._load()
def _load(self):
today = datetime.now().strftime("%Y-%m-%d")
if os.path.exists(self.filename):
try:
with open(self.filename, 'r') as f:
data = json.load(f)
if data.get('date') == today:
self.current_usage = data.get('bytes', 0)
else:
self.current_usage = 0
self._save()
except:
self.current_usage = 0
else:
self.current_usage = 0
def _save(self):
today = datetime.now().strftime("%Y-%m-%d")
try:
with open(self.filename, 'w') as f:
json.dump({"date": today, "bytes": self.current_usage}, f)
except: pass
def check_cap(self):
if self.limit_bytes <= 0: return False
today = datetime.now().strftime("%Y-%m-%d")
if os.path.exists(self.filename):
try:
with open(self.filename, 'r') as f:
data = json.load(f)
if data.get('date') != today:
with self.lock:
self.current_usage = 0
self._save()
return False
except: pass
with self.lock:
return self.current_usage >= self.limit_bytes
def add_usage(self, num_bytes):
if self.limit_bytes <= 0: return
with self.lock:
self.current_usage += num_bytes
if time.time() - self.last_save > 30:
self._save()
self.last_save = time.time()
def force_save(self):
with self.lock: self._save()
def get_remaining_str(self):
if self.limit_bytes <= 0: return "Unlimited"
rem = self.limit_bytes - self.current_usage
if rem < 0: rem = 0
return f"{rem / 1024**3:.2f} GB"
def get_wait_time(self):
now = datetime.now()
tomorrow = now + timedelta(days=1)
midnight = datetime(year=tomorrow.year, month=tomorrow.month, day=tomorrow.day, hour=0, minute=0, second=1)
return (midnight - now).total_seconds()
# ==============================================================================
# TEXTUAL TUI
# ==============================================================================
if HAS_TEXTUAL:
from rich.text import Text
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _phase_style(phase: str) -> str:
return {
"Idle": "dim",
"Starting": "dim",
"Probe": "cyan",
"DL": "bold cyan",
"Encoding": "bold yellow",
"Uploading": "bold green",
"Done": "bright_green",
"Failed": "bold red",
"Paused": "bold orange3",
"Quota": "orange_red1",
"Retrying": "bold orange3",
}.get(phase, "white")
def _make_bar(pct: int, width: int = 16) -> str:
pct = max(0, min(100, pct))
filled = int(width * pct / 100)
return "▓" * filled + "░" * (width - filled) + f" {pct:3d}%"
def _fmt_elapsed(seconds: float) -> str:
if seconds <= 0:
return "-"
s = int(seconds)
h, r = divmod(s, 3600)
m, sec = divmod(r, 60)
return f"{h}:{m:02d}:{sec:02d}" if h else f"{m}:{sec:02d}"
# ---------------------------------------------------------------------------
# Pause modal
# ---------------------------------------------------------------------------
class PauseModal(ModalScreen):
"""Modal dialog shown when the worker is paused."""
BINDINGS = [ # type: ignore[assignment]
Binding("c", "choose_continue", show=False),
Binding("f", "choose_finish", show=False),
Binding("s", "choose_stop", show=False),
Binding("escape", "choose_continue", show=False),
]
def compose(self) -> ComposeResult:
on_windows = platform.system() == 'Windows'
subtitle = "FFmpeg has been suspended." if not on_windows else "FFmpeg has been suspended (Windows)."
with Vertical(id="pause-dialog"):
yield Label("\u23f8 WORKER PAUSED", id="pause-title")
yield Label(subtitle, id="pause-subtitle")
with Horizontal(id="pause-buttons"):
yield Button("[C] Continue", id="btn-continue", variant="success")
yield Button("[F] Finish", id="btn-finish", variant="warning")
yield Button("[S] Stop", id="btn-stop", variant="error")
def action_choose_continue(self) -> None: self.dismiss("continue")
def action_choose_finish(self) -> None: self.dismiss("finish")
def action_choose_stop(self) -> None: self.dismiss("stop")
def on_key(self, event) -> None:
"""Explicit key handler — belt-and-suspenders in case BINDINGS
don't fire (known issue in some Textual versions over SSH/tmux)."""
key = event.key
if key in ('c', 'escape'): self.dismiss("continue")
elif key == 'f': self.dismiss("finish")
elif key == 's': self.dismiss("stop")
def on_button_pressed(self, event: Button.Pressed) -> None:
choices = {"btn-continue": "continue", "btn-finish": "finish", "btn-stop": "stop"}
if event.button.id in choices:
self.dismiss(choices[event.button.id])
# ---------------------------------------------------------------------------
# Main application
# ---------------------------------------------------------------------------
class WorkerApp(App):
"""Fractum Distributed Worker \u2014 Textual TUI."""
CSS = """
Screen {
background: $background;
}
#workers-table {
height: auto;
max-height: 16;
margin: 1 1 0 1;
border: solid $primary;
}
#stats-bar {
height: 1;
margin: 0 2;
background: $surface-darken-1;
color: $text-muted;
padding: 0 1;
}
#log-panel {
height: 1fr;
margin: 0 1 1 1;
border: solid $primary-darken-2;
}
PauseModal {
align: center middle;
}
#pause-dialog {
background: $surface;
border: thick $warning;
padding: 1 4;
width: 56;
height: auto;
}
#pause-title {
text-align: center;
color: $warning;
text-style: bold;
padding-bottom: 1;
}
#pause-subtitle {
text-align: center;
color: $text-disabled;
padding-bottom: 1;
}
#pause-buttons {
height: auto;
align: center middle;
padding-top: 1;
}
#btn-continue { margin: 0 1; }
#btn-finish { margin: 0 1; }
#btn-stop { margin: 0 1; }
"""
BINDINGS = [ # type: ignore[assignment]
Binding("p", "request_pause", "Pause [P]", show=True, priority=True),
Binding("q", "request_quit", "Quit [Q]", show=True, priority=True),
]
def __init__(self, worker_ids: list, threads: list,
quota_tracker=None, manager_url: str = "", **kwargs):
super().__init__(**kwargs)
self._worker_ids = worker_ids
self._threads = threads
self._quota_tracker = quota_tracker
self._manager_url = manager_url
# Column keys assigned in on_mount
self._col_file = self._col_phase = self._col_bar = None
self._col_elapsed = self._col_done = self._col_eta = None
# Monotonic timestamp recorded when the pause modal is first shown.
# Used by _check_signals to distinguish a genuine second press (force-stop)
# from the race-condition echo of the *same* keypress handled by both
# Textual's binding and the _tty_key_reader fallback simultaneously.
self._pause_requested_at = 0.0
def compose(self) -> ComposeResult:
yield Header()
# can_focus=False here (not just in on_mount) prevents the DataTable from
# receiving keyboard focus before on_mount runs. In recent Textual versions
# DataTable captures unrecognised keys for its internal row-search feature
# instead of bubbling them, so focus on startup caused the first 'p' press
# to be swallowed and the second press to actually trigger the App binding.
yield DataTable(id="workers-table", show_cursor=False)
yield Label("", id="stats-bar", markup=False)
yield RichLog(id="log-panel", highlight=True, markup=False, max_lines=1000)
yield Footer()
def on_mount(self) -> None:
table = self.query_one("#workers-table", DataTable)
cols = table.add_columns("Worker", "Current File", "Phase", "Progress", "Elapsed", "Done", "ETA")
_cw, self._col_file, self._col_phase, self._col_bar, self._col_elapsed, self._col_done, self._col_eta = cols
for wid in self._worker_ids:
table.add_row(wid, "-", "Starting", _make_bar(0), "-", "0", "-", key=wid)
self.title = "Fractum Distributed Worker"
url_display = self._manager_url or "no manager"
self.sub_title = f"v{WORKER_VERSION} \u2502 {len(self._worker_ids)} worker(s) \u2502 {url_display}"
self.set_interval(0.5, self._tick)
self.set_interval(0.25, self._check_signals)
self.set_interval(1.5, self._check_all_done)
# Prevent these widgets from stealing focus and swallowing key events.
# Belt-and-suspenders: can_focus=False is also set in the constructor,
# but re-set here for safety in case Textual ever resets it internally.
self.query_one("#workers-table").can_focus = False
self.query_one("#log-panel").can_focus = False
# Drop focus from any widget so the App (and its BINDINGS) receives
# key events directly from the first keypress, not the second.
self.set_focus(None)
# NOTE: do NOT write raw escape sequences to sys.stdout here.
# Textual owns the terminal once on_mount fires; writing outside its
# rendering pipeline corrupts its cursor-position tracking and causes
# subsequent renders to land at wrong positions (e.g. on the stats bar).
# Mouse-tracking cleanup is handled exclusively by the atexit handler
# and the reset block that runs after app.run() returns.
# Start a fallback key reader on /dev/tty. On some SSH/tmux setups
# Textual's own input driver receives no key events; reading /dev/tty
# directly bypasses that entirely. We only read p/q here so we
# don't conflict with Textual's normal key handling in healthy envs.
threading.Thread(target=self._tty_key_reader, daemon=True).start()
def _tty_key_reader(self) -> None:
"""Read single chars from /dev/tty to set _TUI_SIGNAL as a fallback
for environments where Textual's input driver is broken (SSH/tmux)."""
global _TUI_SIGNAL
try:
import tty, termios, atexit
tty_fd = open('/dev/tty', 'rb', buffering=0)
old = termios.tcgetattr(tty_fd)
# Register atexit BEFORE entering cbreak mode so the terminal is
# always restored even if the daemon thread is killed mid-read on
# program exit (blocking read(1) won't unblock for the finally).
def _restore_tty():
try:
termios.tcsetattr(tty_fd, termios.TCSADRAIN, old)
tty_fd.close()
except Exception:
pass
atexit.register(_restore_tty)
tty.setcbreak(tty_fd)
try:
while not SHUTDOWN_EVENT.is_set():
ch = tty_fd.read(1)
if not ch:
break
c = ch.decode('utf-8', errors='ignore').lower()
if PAUSE_REQUESTED:
# While paused, route c/f/s as pause-choice signals
if c == 'c':
_TUI_SIGNAL = 'choice:continue'
elif c == 'f':
_TUI_SIGNAL = 'choice:finish'
elif c == 's':
_TUI_SIGNAL = 'choice:stop'
else:
if c == 'p' and _TUI_SIGNAL is None:
_TUI_SIGNAL = 'pause'
elif c == 'q' and _TUI_SIGNAL is None:
_TUI_SIGNAL = 'quit'
finally:
# Normal clean exit — unregister the atexit handler and
# restore immediately so it doesn't run a second time.
atexit.unregister(_restore_tty)
_restore_tty()
except Exception:
pass # Not available on Windows or if /dev/tty is inaccessible
# ------------------------------------------------------------------
# Periodic refresh
# ------------------------------------------------------------------
def _tick(self) -> None:
"""Refresh the workers table and stats bar from shared state."""
table = self.query_one("#workers-table", DataTable)
now = time.time()
for wid in self._worker_ids:
d = WORKER_DETAILS.get(wid, {})
phase = d.get("phase", "Starting")
pct = d.get("pct", 0)
filename = d.get("file", "-")
job_start = d.get("job_start", 0.0)
jobs_done = d.get("jobs_done", 0)
idle_phases = {"Idle", "Starting", "Quota", "Done", "Failed"}
elapsed = (now - job_start) if job_start > 0 and phase not in idle_phases else 0.0
# ETA: estimate remaining time from elapsed and progress
if pct > 5 and elapsed > 0 and phase == "Encoding":
eta_sec = elapsed * (100 - pct) / pct
else:
eta_sec = 0.0
style = _phase_style(phase)
phase_text = Text(phase, style=style)
bar_text = Text(_make_bar(pct) if phase not in {"Idle", "Starting"} else " " * 20, style=style)
max_fn = 32
fn_display = filename if len(filename) <= max_fn else "\u2026" + filename[-(max_fn - 1):]
try:
table.update_cell(wid, self._col_file, fn_display, update_width=False)
table.update_cell(wid, self._col_phase, phase_text, update_width=False)
table.update_cell(wid, self._col_bar, bar_text, update_width=False)
table.update_cell(wid, self._col_elapsed, _fmt_elapsed(elapsed), update_width=False)
table.update_cell(wid, self._col_done, str(jobs_done), update_width=False)
table.update_cell(wid, self._col_eta, _fmt_elapsed(eta_sec), update_width=False)
except Exception:
pass
# Stats bar
with STATS_LOCK:
jd = SESSION_STATS.get("jobs_done", 0)
bu = SESSION_STATS.get("bytes_uploaded", 0)
st = SESSION_STATS.get("start", now)
uptime_str = _fmt_elapsed(now - st)
gb_str = f"{bu / 1024 ** 3:.2f} GB"
quota_str = ""
if self._quota_tracker:
quota_str = f" \u2502 Quota Remaining: {self._quota_tracker.get_remaining_str()}"
stats = (
f" Jobs Completed: {jd}"
f" \u2502 Uploaded: {gb_str}"
f" \u2502 Uptime: {uptime_str}"
f"{quota_str}"
)
try:
self.query_one("#stats-bar", Label).update(stats)
except Exception:
pass
async def _check_signals(self) -> None:
"""Poll the signal flag set by the OS signal handler or tty key reader."""
global _TUI_SIGNAL
sig = _TUI_SIGNAL
if sig is None:
return
_TUI_SIGNAL = None
if sig == 'pause':
if not PAUSE_REQUESTED:
await self.action_request_pause()
else:
# Second Ctrl+C / P while already paused = force stop.
# Debounce: if the modal was shown less than 0.5 s ago, this
# signal is almost certainly the same keypress being handled by
# both Textual's binding and the _tty_key_reader fallback at the
# same time (race condition). Ignore it; the modal stays open.
if time.monotonic() - self._pause_requested_at < 0.5:
return
if isinstance(self.screen, PauseModal):
self.screen.dismiss("stop")
else:
self._handle_pause_result('stop')
elif sig == 'quit':
self.action_request_quit()
elif sig.startswith('choice:'):
choice = sig[len('choice:'):]
# SSH/tmux keyboard fallback: dismiss the modal so the callback
# fires automatically, rather than calling _handle_pause_result
# directly (which would leave the modal open on screen).
if isinstance(self.screen, PauseModal):
self.screen.dismiss(choice)
else:
self._handle_pause_result(choice)
def _check_all_done(self) -> None:
if SHUTDOWN_EVENT.is_set() and all(not t.is_alive() for t in self._threads):
self.exit()
# ------------------------------------------------------------------
# Thread-safe log write (called via call_from_thread)
# ------------------------------------------------------------------
def write_log(self, message: str) -> None:
try:
self.query_one("#log-panel", RichLog).write(message)
except Exception:
pass
def update_worker_status(self, worker_id: str, status: str) -> None:
# Status is now driven by WORKER_DETAILS polling in _tick; this is a no-op.
pass
# ------------------------------------------------------------------
# Pause / quit actions
# ------------------------------------------------------------------
async def action_request_pause(self) -> None:
global PAUSE_REQUESTED
if PAUSE_REQUESTED:
return
PAUSE_REQUESTED = True
self._pause_requested_at = time.monotonic()
threading.Thread(target=lambda: toggle_processes(suspend=True),
daemon=True).start()
# Show the popup modal — buttons are mouse-clickable on Windows;
# keyboard C/F/S work via Textual bindings or the _tty_key_reader
# fallback for SSH/tmux (which dismisses the modal via _check_signals).
self.push_screen(PauseModal(), callback=self._handle_pause_result)
def _handle_pause_result(self, choice) -> None:
global PAUSE_REQUESTED
if choice == "continue":
PAUSE_REQUESTED = False
threading.Thread(target=lambda: toggle_processes(suspend=False),
daemon=True).start()
self.write_log("[*] Encoding resumed.")
elif choice == "finish":
PAUSE_REQUESTED = False
threading.Thread(target=lambda: toggle_processes(suspend=False),
daemon=True).start()
SHUTDOWN_EVENT.set()
self.write_log("[*] Finishing active jobs, then stopping...")
elif choice == "stop":
threading.Thread(target=lambda: toggle_processes(suspend=False),
daemon=True).start()
kill_processes()
SHUTDOWN_EVENT.set()
PAUSE_REQUESTED = False
self.write_log("[*] Stopping immediately...")
self.set_timer(1.5, self.exit)
def action_request_quit(self) -> None:
SHUTDOWN_EVENT.set()
kill_processes()
self.exit()
def _run_text_pause_menu() -> str:
"""Synchronous text pause menu shown when the TUI is suspended.
Reads directly from /dev/tty so it works even when stdin is piped.
Returns 'continue', 'finish', or 'stop'.
"""
src = None
if not sys.stdin.isatty():
try:
src = open('/dev/tty', 'r')
except Exception:
pass
try:
sys.stdout.write("\n" + "="*40 + "\n")
sys.stdout.write(" [!] WORKER PAUSED\n")
sys.stdout.write("="*40 + "\n")
sys.stdout.write(" [C]ontinue - Resume encoding\n")
sys.stdout.write(" [F]inish - Finish active, then stop\n")
sys.stdout.write(" [S]top - Abort immediately\n")
sys.stdout.write(" Ctrl+C - Force abort\n")
sys.stdout.flush()
while True:
try:
prompt_src = src if src else sys.stdin
sys.stdout.write("Select [c/f/s]: ")
sys.stdout.flush()
line = prompt_src.readline()
if not line:
return 'stop'
ch = line.strip().lower()
if ch in ('c', ''):
return 'continue'
if ch == 'f':
return 'finish'
if ch == 's':
return 'stop'
except KeyboardInterrupt:
sys.stdout.write("\n[*] Force abort.\n")
sys.stdout.flush()
return 'stop'
except EOFError:
return 'stop'
finally:
if src:
try:
src.close()
except Exception:
pass
def get_auth_headers():
headers = {'User-Agent': f'FractumWorker/{WORKER_VERSION}'}
if WORKER_SECRET:
headers['X-Worker-Token'] = WORKER_SECRET
return headers
def get_term_width():
try: return shutil.get_terminal_size((80, 20)).columns
except: return 80
def safe_print(message):
# During interpreter shutdown daemon threads can't safely acquire the
# internal C-level lock on BufferedWriter, causing a Fatal Python error.
# Bail out early — nobody is reading stdout at that point anyway.
if sys.is_finalizing():
return
if TUI_APP is not None:
try:
TUI_APP.call_from_thread(TUI_APP.write_log, message)
except Exception:
pass
# Never fall through to direct stdout writes while the TUI owns the
# terminal — writing raw bytes into Textual's alternate screen places
# stray characters wherever the cursor happens to be (often top-left
# during a render cycle).
return
# After the TUI exits (TUI_APP set back to None) but before Python fully
# finalizes, daemon threads can briefly reach sys.stdout.write(). The
# C-level BufferedWriter lock may already be destroyed by then, causing
# "Fatal Python error: _enter_buffered_busy" which cannot be caught.
# sys.is_finalizing() has a race window — SHUTDOWN_EVENT closes it.
if _TUI_WAS_RUNNING and SHUTDOWN_EVENT.is_set():
return
if not CONSOLE_LOCK.acquire(timeout=2):
return
try:
width = get_term_width()
# Truncate long messages to avoid wrapping onto a second line
if len(message) > width - 1:
message = message[:width-1]
# \033[K (Erase to End of Line) clears any leftover chars from a
# previously longer line drawn at the same position — avoids the
# padding-width-mismatch flicker that occurred on terminal resize.
sys.stdout.write(f'\r{message}\033[K\n')
sys.stdout.flush()
except Exception:
# Absolute fallback
try: print(message)
except Exception: pass
finally:
CONSOLE_LOCK.release()
def log(worker_id, message, level="INFO"):
timestamp = datetime.now().strftime("%H:%M:%S")
safe_print(f"[{timestamp}] [{worker_id}] [{level}] {message}")
def signal_handler(sig, frame):
global PAUSE_REQUESTED, _TUI_SIGNAL
if platform.system() == 'Windows':
SHUTDOWN_EVENT.set()
try: kill_processes()
except: pass
if TUI_APP is not None:
# Route through the TUI's quit action so Textual can restore the
# Windows console mode (echo, VT processing, cursor visibility)
# before the process exits. sys.exit() here skips that cleanup.
_TUI_SIGNAL = 'quit'
else:
try:
sys.stdout.write('\n[!] Shutdown initiated...\n')
sys.stdout.flush()
except Exception:
pass
return # Let app.run() / join loop exit naturally
else:
if TUI_APP is not None:
# In TUI mode, Ctrl+C opens the pause menu so the user can choose
# Continue / Finish / Stop. SIGTERM still shuts down cleanly.
if sig == signal.SIGTERM:
SHUTDOWN_EVENT.set()
try: kill_processes()
except: pass
_TUI_SIGNAL = 'quit'
else:
# SIGINT (Ctrl+C) → request pause via flag; the app's polling
# timer picks this up on the event loop thread (call_from_thread
# cannot be used from a signal handler — same thread as the loop).
_TUI_SIGNAL = 'pause'
elif not PAUSE_REQUESTED:
PAUSE_REQUESTED = True
try:
sys.stdout.write('\n\n[!] PAUSE REQUESTED (Stopping gracefully...)\n')
sys.stdout.flush()
except: pass
def toggle_processes(suspend=True):
if platform.system() == 'Windows':
# Windows has no SIGSTOP/SIGCONT, but NtSuspendProcess / NtResumeProcess
# (ntdll.dll) achieve the identical effect: all threads in the target
# process are frozen atomically. ctypes is stdlib — no extra deps.
try:
ntdll = ctypes.windll.ntdll
kernel32 = ctypes.windll.kernel32
PROCESS_ALL_ACCESS = 0x1F0FFF
with PROC_LOCK:
for wid, proc in ACTIVE_PROCS.items():
if proc.poll() is None:
try:
h = kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, proc.pid)
if h:
if suspend:
ntdll.NtSuspendProcess(h)
else:
ntdll.NtResumeProcess(h)
kernel32.CloseHandle(h)
except Exception as _e:
safe_print(f"[!] Could not {'suspend' if suspend else 'resume'} PID {proc.pid}: {_e}")
except Exception as _e:
if suspend:
safe_print(f"[!] WARNING: Windows process suspension unavailable: {_e}")
return
with PROC_LOCK:
for wid, proc in ACTIVE_PROCS.items():
if proc.poll() is None:
try:
sig = signal.SIGSTOP if suspend else signal.SIGCONT # type: ignore[attr-defined]
os.kill(proc.pid, sig)
except: pass
def kill_processes():
with PROC_LOCK:
for wid, proc in ACTIVE_PROCS.items():
try:
if proc.poll() is None: proc.kill()
except: pass
def check_version(manager_url):
global LAST_UPDATE_CHECK
with CHECK_LOCK:
if time.time() - LAST_UPDATE_CHECK < 600: return False
LAST_UPDATE_CHECK = time.time()
try:
url = f"{manager_url}/dl/worker"
r = requests.get(url, headers=get_auth_headers(), timeout=10)
if r.status_code == 200:
match = re.search(r'WORKER_VERSION\s*=\s*"([^"]+)"', r.text)
if match and match.group(1) != WORKER_VERSION:
safe_print(f"[!] Update found: {WORKER_VERSION} -> {match.group(1)}")
return True
except: pass
return False
def apply_update(manager_url):
safe_print("[*] Downloading and applying update...")
tmp_path = None
try:
url = f"{manager_url}/dl/worker"
r = requests.get(url, headers=get_auth_headers(), timeout=30)
if r.status_code == 200:
target_path = os.path.abspath(sys.argv[0])
tmp_path = target_path + '.tmp'
with open(tmp_path, 'w', encoding='utf-8') as f:
f.write(r.text)
os.replace(tmp_path, target_path)
safe_print("[*] Restarting worker...")
os.execv(sys.executable, [sys.executable] + sys.argv)
except Exception as e:
safe_print(f"[!] Failed to apply update: {e}")
if tmp_path:
try:
if os.path.exists(tmp_path): os.remove(tmp_path)
except: pass
def print_progress(worker_id, current, total, prefix='', suffix=''):
if total <= 0: return
percent = min(100, int(100 * current / float(total)))
if TUI_APP is not None:
# Update WORKER_DETAILS so the polling _tick() picks it up
d = WORKER_DETAILS.get(worker_id)
if d is not None:
phase_map = {'DL': 'DL', 'Enc': 'Encoding', 'Up': 'Uploading'}
d["phase"] = phase_map.get(prefix, prefix)
d["pct"] = percent
return
if sys.is_finalizing():
return
width = get_term_width()
overhead = 12 + len(worker_id) + len(prefix) + 10 + len(suffix)
bar_length = width - overhead - 5
if bar_length < 10: bar_length = 10
filled_length = int(bar_length * current // total)
block_char = '█'
fill_char = '-'
try:
bar = block_char * filled_length + fill_char * (bar_length - filled_length)
line = f'[{datetime.now().strftime("%H:%M:%S")}] [{worker_id}] {prefix} |{bar}| {percent:.1f}% {suffix}'
if len(line) > width - 1:
line = line[:width - 1]
with CONSOLE_LOCK:
sys.stdout.write(f'\r{line}\033[K')
sys.stdout.flush()
except UnicodeEncodeError:
block_char = '='
fill_char = '-'
try:
bar = block_char * filled_length + fill_char * (bar_length - filled_length)
line = f'[{datetime.now().strftime("%H:%M:%S")}] [{worker_id}] {prefix} |{bar}| {percent:.1f}% {suffix}'
if len(line) > width - 1: line = line[:width - 1]
with CONSOLE_LOCK:
sys.stdout.write(f'\r{line}\033[K')
sys.stdout.flush()
except: pass
if current >= total:
try: sys.stdout.write('\n')
except: pass
def monitor_status_loop(worker_ids):
while not SHUTDOWN_EVENT.is_set():
# Daemon threads writing to stdout after interpreter shutdown started
# will crash Python at the C level — bail out early.
if sys.is_finalizing():
return
if TUI_APP is not None:
time.sleep(1); continue # TUI handles all status display
if PAUSE_REQUESTED or MONITOR_PAUSED.is_set():
time.sleep(0.5); continue
parts = []
with PROGRESS_LOCK:
for wid in sorted(worker_ids, key=lambda x: x.split('-')[-1]):
try: short_id = wid.split('-')[-1]
except: short_id = wid
state = WORKER_PROGRESS.get(wid, "Idle")
parts.append(f"[{short_id}: {state}]")
if parts:
line = " ".join(parts)
width = get_term_width()
if len(line) > width - 4: line = line[:width-4] + "..."
with CONSOLE_LOCK:
try:
sys.stdout.write(f'\r{line}\033[K')
sys.stdout.flush()
except: pass
time.sleep(0.5)
def get_seconds(t):
try:
parts = t.split(':')
h = int(parts[0]); m = int(parts[1]); s = float(parts[2])
return h*3600 + m*60 + s
except: return 0
# ==============================================================================
# RESUME / PARTIAL ENCODE HELPERS
# ==============================================================================
_RESUME_CHK_PREFIX = "resume_chk_"
def _probe_local_duration(file_path):
"""Return duration in seconds of a local media file, or 0.0 on failure."""
try:
res = subprocess.run(
[FFPROBE_CMD, '-v', 'quiet', '-print_format', 'json', '-show_format', file_path],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
encoding='utf-8', errors='replace', timeout=60)
dur = json.loads(res.stdout).get('format', {}).get('duration')
return float(dur) if dur else 0.0
except Exception:
return 0.0
def _save_resume_checkpoint(path, payload):
"""Atomically write a resume checkpoint JSON."""
tmp = path + '.tmp'
try:
with open(tmp, 'w', encoding='utf-8') as f:
json.dump(payload, f)
os.replace(tmp, path)
except Exception:
try:
if os.path.exists(tmp): os.remove(tmp)
except Exception:
pass
def _load_resume_checkpoints(temp_dir):
"""Return list of (path, data) for all resume checkpoints found in temp_dir."""
results = []
try:
for fname in os.listdir(temp_dir):
if fname.startswith(_RESUME_CHK_PREFIX) and fname.endswith('.json'):
fpath = os.path.join(temp_dir, fname)
try:
with open(fpath, 'r', encoding='utf-8') as f:
data = json.load(f)
results.append((fpath, data))
except Exception:
pass
except Exception:
pass
return results
# Number of bytes hashed for source-integrity check (must match server constant)