forked from robertvoy/ComfyUI-Distributed
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdistributed.py
More file actions
1523 lines (1281 loc) · 63.1 KB
/
distributed.py
File metadata and controls
1523 lines (1281 loc) · 63.1 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 torch
import numpy as np
from PIL import Image
import folder_paths
import os
import json
import asyncio
import aiohttp
from aiohttp import web
import io
import server
import subprocess
import platform
import time
import atexit
import signal
# Import shared utilities
from .utils.logging import debug_log, log
from .utils.config import CONFIG_FILE, get_default_config, load_config, save_config, ensure_config_exists
from .utils.image import tensor_to_pil, pil_to_tensor, ensure_contiguous
from .utils.process import is_process_alive, terminate_process, get_python_executable
from .utils.network import handle_api_error, get_server_port, get_server_loop, get_client_session, cleanup_client_session
from .utils.async_helpers import run_async_in_server_loop
from .utils.constants import (
WORKER_JOB_TIMEOUT, PROCESS_TERMINATION_TIMEOUT, WORKER_CHECK_INTERVAL,
STATUS_CHECK_INTERVAL, CHUNK_SIZE, LOG_TAIL_BYTES, WORKER_LOG_PATTERN,
WORKER_STARTUP_DELAY, PROCESS_WAIT_TIMEOUT, MEMORY_CLEAR_DELAY
)
# Try to import psutil for better process management
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
log("psutil not available, using fallback process management")
PSUTIL_AVAILABLE = False
# Register cleanup for aiohttp session
def cleanup():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(cleanup_client_session())
loop.close()
atexit.register(cleanup)
# --- API Endpoints ---
@server.PromptServer.instance.routes.get("/distributed/config")
async def get_config_endpoint(request):
config = load_config()
return web.json_response(config)
@server.PromptServer.instance.routes.get("/distributed/queue_status/{job_id}")
async def queue_status_endpoint(request):
"""Check if a job queue is initialized."""
try:
job_id = request.match_info['job_id']
# Import to ensure initialization
from .distributed_upscale import ensure_tile_jobs_initialized
prompt_server = ensure_tile_jobs_initialized()
async with prompt_server.distributed_tile_jobs_lock:
exists = job_id in prompt_server.distributed_pending_tile_jobs
debug_log(f"Queue status check for job {job_id}: {'exists' if exists else 'not found'}")
return web.json_response({"exists": exists, "job_id": job_id})
except Exception as e:
return await handle_api_error(request, e, 500)
@server.PromptServer.instance.routes.post("/distributed/worker/clear_launching")
async def clear_launching_state(request):
"""Clear the launching flag when worker is confirmed running."""
try:
data = await request.json()
worker_id = str(data.get('worker_id'))
if not worker_id:
return await handle_api_error(request, "worker_id is required", 400)
# Clear launching flag in managed processes
if worker_id in worker_manager.processes:
if 'launching' in worker_manager.processes[worker_id]:
del worker_manager.processes[worker_id]['launching']
worker_manager.save_processes()
debug_log(f"Cleared launching state for worker {worker_id}")
return web.json_response({"status": "success"})
except Exception as e:
return await handle_api_error(request, e, 500)
@server.PromptServer.instance.routes.get("/distributed/network_info")
async def get_network_info_endpoint(request):
"""Get network interfaces and recommend best IP for master."""
import socket
def get_network_ips():
"""Get all network IPs, trying multiple methods."""
ips = []
hostname = socket.gethostname()
# Method 1: Try socket.getaddrinfo
try:
addr_info = socket.getaddrinfo(hostname, None)
for info in addr_info:
ip = info[4][0]
if ip and ip not in ips and not ip.startswith('::'): # Skip IPv6 for now
ips.append(ip)
except:
pass
# Method 2: Try to connect to external server and get local IP
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80)) # Google DNS
local_ip = s.getsockname()[0]
s.close()
if local_ip not in ips:
ips.append(local_ip)
except:
pass
# Method 3: Platform-specific commands
try:
if platform.system() == "Windows":
# Windows ipconfig
result = subprocess.run(["ipconfig"], capture_output=True, text=True)
lines = result.stdout.split('\n')
for i, line in enumerate(lines):
if 'IPv4' in line and i + 1 < len(lines):
ip = lines[i].split(':')[-1].strip()
if ip and ip not in ips:
ips.append(ip)
else:
# Unix/Linux/Mac ifconfig or ip addr
try:
result = subprocess.run(["ip", "addr"], capture_output=True, text=True)
except:
result = subprocess.run(["ifconfig"], capture_output=True, text=True)
import re
ip_pattern = re.compile(r'inet\s+(\d+\.\d+\.\d+\.\d+)')
for match in ip_pattern.finditer(result.stdout):
ip = match.group(1)
if ip and ip not in ips:
ips.append(ip)
except:
pass
return ips
def get_recommended_ip(ips):
"""Choose the best IP for master-worker communication."""
# Priority order:
# 1. Private network ranges (192.168.x.x, 10.x.x.x, 172.16-31.x.x)
# 2. Other non-localhost IPs
# 3. Localhost as last resort
private_ips = []
public_ips = []
for ip in ips:
if ip.startswith('127.') or ip == 'localhost':
continue
elif (ip.startswith('192.168.') or
ip.startswith('10.') or
(ip.startswith('172.') and 16 <= int(ip.split('.')[1]) <= 31)):
private_ips.append(ip)
else:
public_ips.append(ip)
# Prefer private IPs
if private_ips:
# Prefer 192.168 range as it's most common
for ip in private_ips:
if ip.startswith('192.168.'):
return ip
return private_ips[0]
elif public_ips:
return public_ips[0]
elif ips:
return ips[0]
else:
return None
try:
hostname = socket.gethostname()
all_ips = get_network_ips()
recommended_ip = get_recommended_ip(all_ips)
return web.json_response({
"status": "success",
"hostname": hostname,
"all_ips": all_ips,
"recommended_ip": recommended_ip,
"message": "Auto-detected network configuration"
})
except Exception as e:
return web.json_response({
"status": "error",
"message": str(e),
"hostname": "unknown",
"all_ips": [],
"recommended_ip": None
})
@server.PromptServer.instance.routes.post("/distributed/config/update_worker")
async def update_worker_endpoint(request):
try:
data = await request.json()
worker_id = data.get("worker_id")
if worker_id is None:
return await handle_api_error(request, "Missing worker_id", 400)
config = load_config()
worker_found = False
for worker in config.get("workers", []):
if worker["id"] == worker_id:
# Update all provided fields
if "enabled" in data:
worker["enabled"] = data["enabled"]
if "name" in data:
worker["name"] = data["name"]
if "port" in data:
worker["port"] = data["port"]
# Handle host field - remove it if None
if "host" in data:
if data["host"] is None:
worker.pop("host", None)
else:
worker["host"] = data["host"]
# Handle cuda_device field - remove it if None
if "cuda_device" in data:
if data["cuda_device"] is None:
worker.pop("cuda_device", None)
else:
worker["cuda_device"] = data["cuda_device"]
# Handle extra_args field - remove it if None
if "extra_args" in data:
if data["extra_args"] is None:
worker.pop("extra_args", None)
else:
worker["extra_args"] = data["extra_args"]
worker_found = True
break
if not worker_found:
# If worker not found and all required fields are provided, create new worker
if all(key in data for key in ["name", "port", "cuda_device"]):
new_worker = {
"id": worker_id,
"name": data["name"],
"host": data.get("host", "localhost"),
"port": data["port"],
"cuda_device": data["cuda_device"],
"enabled": data.get("enabled", False),
"extra_args": data.get("extra_args", "")
}
if "workers" not in config:
config["workers"] = []
config["workers"].append(new_worker)
worker_found = True
else:
return await handle_api_error(request, f"Worker {worker_id} not found and missing required fields for creation", 404)
if save_config(config):
return web.json_response({"status": "success"})
else:
return await handle_api_error(request, "Failed to save config")
except Exception as e:
return await handle_api_error(request, e, 400)
@server.PromptServer.instance.routes.post("/distributed/config/delete_worker")
async def delete_worker_endpoint(request):
try:
data = await request.json()
worker_id = data.get("worker_id")
if worker_id is None:
return await handle_api_error(request, "Missing worker_id", 400)
config = load_config()
workers = config.get("workers", [])
# Find and remove the worker
worker_index = -1
for i, worker in enumerate(workers):
if worker["id"] == worker_id:
worker_index = i
break
if worker_index == -1:
return await handle_api_error(request, f"Worker {worker_id} not found", 404)
# Remove the worker
removed_worker = workers.pop(worker_index)
if save_config(config):
return web.json_response({
"status": "success",
"message": f"Worker {removed_worker.get('name', worker_id)} deleted"
})
else:
return await handle_api_error(request, "Failed to save config")
except Exception as e:
return await handle_api_error(request, e, 400)
@server.PromptServer.instance.routes.post("/distributed/config/update_setting")
async def update_setting_endpoint(request):
"""Updates a specific key in the settings object."""
try:
data = await request.json()
key = data.get("key")
value = data.get("value")
if not key or value is None:
return await handle_api_error(request, "Missing 'key' or 'value' in request", 400)
config = load_config()
if 'settings' not in config:
config['settings'] = {}
config['settings'][key] = value
if save_config(config):
return web.json_response({"status": "success", "message": f"Setting '{key}' updated."})
else:
return await handle_api_error(request, "Failed to save config")
except Exception as e:
return await handle_api_error(request, e, 400)
@server.PromptServer.instance.routes.post("/distributed/config/update_master")
async def update_master_endpoint(request):
"""Updates master configuration."""
try:
data = await request.json()
config = load_config()
if 'master' not in config:
config['master'] = {}
# Update all provided fields
if "host" in data:
config['master']['host'] = data['host']
if "port" in data:
config['master']['port'] = data['port']
if "cuda_device" in data:
config['master']['cuda_device'] = data['cuda_device']
if "extra_args" in data:
config['master']['extra_args'] = data['extra_args']
if save_config(config):
return web.json_response({"status": "success", "message": "Master configuration updated."})
else:
return await handle_api_error(request, "Failed to save config")
except Exception as e:
return await handle_api_error(request, e, 400)
@server.PromptServer.instance.routes.post("/distributed/prepare_job")
async def prepare_job_endpoint(request):
try:
data = await request.json()
multi_job_id = data.get('multi_job_id')
if not multi_job_id:
return await handle_api_error(request, "Missing multi_job_id", 400)
async with prompt_server.distributed_jobs_lock:
if multi_job_id not in prompt_server.distributed_pending_jobs:
prompt_server.distributed_pending_jobs[multi_job_id] = asyncio.Queue()
debug_log(f"Prepared queue for job {multi_job_id}")
return web.json_response({"status": "success"})
except Exception as e:
return await handle_api_error(request, e)
@server.PromptServer.instance.routes.post("/distributed/clear_memory")
async def clear_memory_endpoint(request):
debug_log("Received request to clear VRAM.")
try:
# Use ComfyUI's prompt server queue system like the /free endpoint does
if hasattr(server.PromptServer.instance, 'prompt_queue'):
server.PromptServer.instance.prompt_queue.set_flag("unload_models", True)
server.PromptServer.instance.prompt_queue.set_flag("free_memory", True)
debug_log("Set queue flags for memory clearing.")
# Wait a bit for the queue to process
await asyncio.sleep(MEMORY_CLEAR_DELAY)
# Also do direct cleanup as backup, but with error handling
import gc
import comfy.model_management as mm
try:
mm.unload_all_models()
except AttributeError as e:
debug_log(f"Warning during model unload: {e}")
try:
mm.soft_empty_cache()
except Exception as e:
debug_log(f"Warning during cache clear: {e}")
for _ in range(3):
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
debug_log("VRAM cleared successfully.")
return web.json_response({"status": "success", "message": "GPU memory cleared."})
except Exception as e:
# Even if there's an error, try to do basic cleanup
import gc
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
debug_log(f"Partial VRAM clear completed with warning: {e}")
return web.json_response({"status": "success", "message": "GPU memory cleared (with warnings)"})
@server.PromptServer.instance.routes.post("/distributed/launch_worker")
async def launch_worker_endpoint(request):
"""Launch a worker process from the UI."""
try:
data = await request.json()
worker_id = data.get("worker_id")
if not worker_id:
return await handle_api_error(request, "Missing worker_id", 400)
# Find worker config
config = load_config()
worker = next((w for w in config.get("workers", []) if w["id"] == worker_id), None)
if not worker:
return await handle_api_error(request, f"Worker {worker_id} not found", 404)
# Ensure consistent string ID
worker_id_str = str(worker_id)
# Check if already running (managed by this instance)
if worker_id_str in worker_manager.processes:
proc_info = worker_manager.processes[worker_id_str]
process = proc_info.get('process')
# Check if still running
is_running = False
if process:
is_running = process.poll() is None
else:
# Restored process without subprocess object
is_running = worker_manager._is_process_running(proc_info['pid'])
if is_running:
return web.json_response({
"status": "error",
"message": "Worker already running (managed by UI)",
"pid": proc_info['pid'],
"log_file": proc_info.get('log_file')
}, status=409)
else:
# Process is dead, remove it
del worker_manager.processes[worker_id_str]
worker_manager.save_processes()
# Launch the worker
try:
pid = worker_manager.launch_worker(worker)
log_file = worker_manager.processes[worker_id_str].get('log_file')
return web.json_response({
"status": "success",
"pid": pid,
"message": f"Worker {worker['name']} launched",
"log_file": log_file
})
except Exception as e:
return await handle_api_error(request, f"Failed to launch worker: {str(e)}", 500)
except Exception as e:
return await handle_api_error(request, e, 400)
@server.PromptServer.instance.routes.post("/distributed/stop_worker")
async def stop_worker_endpoint(request):
"""Stop a worker process that was launched from the UI."""
try:
data = await request.json()
worker_id = data.get("worker_id")
if not worker_id:
return await handle_api_error(request, "Missing worker_id", 400)
success, message = worker_manager.stop_worker(worker_id)
if success:
return web.json_response({"status": "success", "message": message})
else:
return web.json_response({"status": "error", "message": message},
status=404 if "not managed" in message else 409)
except Exception as e:
return await handle_api_error(request, e, 400)
@server.PromptServer.instance.routes.get("/distributed/managed_workers")
async def get_managed_workers_endpoint(request):
"""Get list of workers managed by this UI instance."""
try:
managed = worker_manager.get_managed_workers()
return web.json_response({
"status": "success",
"managed_workers": managed
})
except Exception as e:
return await handle_api_error(request, e, 500)
@server.PromptServer.instance.routes.get("/distributed/worker_log/{worker_id}")
async def get_worker_log_endpoint(request):
"""Get log content for a specific worker."""
try:
worker_id = request.match_info['worker_id']
# Ensure worker_id is string
worker_id = str(worker_id)
# Check if we manage this worker
if worker_id not in worker_manager.processes:
return await handle_api_error(request, f"Worker {worker_id} not managed by UI", 404)
proc_info = worker_manager.processes[worker_id]
log_file = proc_info.get('log_file')
if not log_file or not os.path.exists(log_file):
return await handle_api_error(request, "Log file not found", 404)
# Read last N lines (or full file if small)
lines_to_read = int(request.query.get('lines', 1000))
try:
# Get file size
file_size = os.path.getsize(log_file)
with open(log_file, 'r', encoding='utf-8', errors='replace') as f:
if lines_to_read > 0 and file_size > 1024 * 1024: # If file > 1MB and limited lines requested
# Read last N lines efficiently
lines = []
# Start from end and work backwards
f.seek(0, 2) # Go to end
file_length = f.tell()
# Read chunks from end
chunk_size = min(CHUNK_SIZE, file_length)
while len(lines) < lines_to_read and f.tell() > 0:
# Move back and read chunk
current_pos = max(0, f.tell() - chunk_size)
f.seek(current_pos)
chunk = f.read(chunk_size)
# Process chunk
chunk_lines = chunk.splitlines()
if current_pos > 0:
# Partial line at beginning, combine with next chunk
chunk_lines = chunk_lines[1:]
lines = chunk_lines + lines
# Move back for next chunk
f.seek(current_pos)
# Take only last N lines
content = '\n'.join(lines[-lines_to_read:])
truncated = len(lines) > lines_to_read
else:
# Read entire file
content = f.read()
truncated = False
return web.json_response({
"status": "success",
"content": content,
"log_file": log_file,
"file_size": file_size,
"truncated": truncated,
"lines_shown": lines_to_read if truncated else content.count('\n') + 1
})
except Exception as e:
return await handle_api_error(request, f"Error reading log file: {str(e)}", 500)
except Exception as e:
return await handle_api_error(request, e, 500)
# --- Worker Process Management ---
class WorkerProcessManager:
def __init__(self):
self.processes = {} # worker_id -> process info
self.load_processes()
def find_comfy_root(self):
"""Find the ComfyUI root directory."""
# Start from current file location and go up
current_dir = os.path.dirname(os.path.abspath(__file__))
# This file is in ComfyUI/custom_nodes/ComfyUI-Distributed/
# So go up two levels to get to ComfyUI root
comfy_root = os.path.dirname(os.path.dirname(current_dir))
return comfy_root
def _find_windows_terminal(self):
"""Find Windows Terminal executable."""
# Common locations for Windows Terminal
possible_paths = [
os.path.expandvars(r"%LOCALAPPDATA%\Microsoft\WindowsApps\wt.exe"),
os.path.expandvars(r"%PROGRAMFILES%\WindowsApps\Microsoft.WindowsTerminal_*\wt.exe"),
"wt.exe" # Try PATH
]
for path in possible_paths:
if os.path.exists(path):
return path
# Handle wildcard for WindowsApps
if '*' in path:
import glob
matches = glob.glob(path)
if matches:
return matches[0]
# Try to find it in PATH
import shutil
wt_path = shutil.which("wt")
if wt_path:
return wt_path
return None
def build_launch_command(self, worker_config, comfy_root):
"""Build the command to launch a worker."""
# Use main.py directly - it's the most reliable method
main_py = os.path.join(comfy_root, "main.py")
if os.path.exists(main_py):
cmd = [
get_python_executable(),
main_py,
"--port", str(worker_config['port']),
"--enable-cors-header"
]
debug_log(f"Using main.py: {main_py}")
else:
# Fallback error
raise RuntimeError(f"Could not find main.py in {comfy_root}")
# Add any extra arguments
if worker_config.get('extra_args'):
cmd.extend(worker_config['extra_args'].split())
return cmd
def launch_worker(self, worker_config, show_window=False):
"""Launch a worker process with logging."""
comfy_root = self.find_comfy_root()
# Set up environment
env = os.environ.copy()
env['CUDA_VISIBLE_DEVICES'] = str(worker_config.get('cuda_device', 0))
env['PYTORCH_CUDA_ALLOC_CONF'] = 'expandable_segments:True'
# Pass master PID to worker so it can monitor if master is still alive
env['COMFYUI_MASTER_PID'] = str(os.getpid())
cmd = self.build_launch_command(worker_config, comfy_root)
# Change to ComfyUI root directory for the process
cwd = comfy_root
# Create log directory and file
log_dir = os.path.join(comfy_root, "logs", "workers")
os.makedirs(log_dir, exist_ok=True)
# Use daily log files instead of timestamp
date_stamp = time.strftime("%Y%m%d")
worker_name = worker_config.get('name', f'Worker{worker_config["id"]}')
# Clean worker name for filename
safe_name = "".join(c if c.isalnum() or c in ('-', '_') else '_' for c in worker_name)
log_file = os.path.join(log_dir, f"{safe_name}_{date_stamp}.log")
# Launch process with logging (append mode for daily logs)
with open(log_file, 'a') as log_handle:
# Write startup info to log with timestamp
log_handle.write(f"\n\n{'='*50}\n")
log_handle.write(f"=== ComfyUI Worker Session Started ===\n")
log_handle.write(f"Worker: {worker_name}\n")
log_handle.write(f"Port: {worker_config['port']}\n")
log_handle.write(f"CUDA Device: {worker_config.get('cuda_device', 0)}\n")
log_handle.write(f"Started: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
log_handle.write(f"Command: {' '.join(cmd)}\n")
# Note about worker behavior
config = load_config()
stop_on_master_exit = config.get('settings', {}).get('stop_workers_on_master_exit', True)
if stop_on_master_exit:
log_handle.write("Note: Worker will stop when master shuts down\n")
else:
log_handle.write("Note: Worker will continue running after master shuts down\n")
log_handle.write("=" * 30 + "\n\n")
log_handle.flush()
# Wrap command with monitor if needed
if stop_on_master_exit and env.get('COMFYUI_MASTER_PID'):
# Use the monitor wrapper
monitor_script = os.path.join(os.path.dirname(__file__), 'worker_monitor.py')
monitored_cmd = [get_python_executable(), monitor_script] + cmd
log_handle.write(f"[Worker Monitor] Monitoring master PID: {env['COMFYUI_MASTER_PID']}\n")
log_handle.flush()
else:
monitored_cmd = cmd
# Platform-specific process creation - always hidden with logging
if platform.system() == "Windows":
CREATE_NO_WINDOW = 0x08000000
process = subprocess.Popen(
monitored_cmd, env=env, cwd=cwd,
stdout=log_handle,
stderr=subprocess.STDOUT,
creationflags=CREATE_NO_WINDOW
)
else:
# Unix-like systems
process = subprocess.Popen(
monitored_cmd, env=env, cwd=cwd,
stdout=log_handle,
stderr=subprocess.STDOUT,
start_new_session=True # Detach from parent
)
# Track the process with log file info - use string ID for consistency
worker_id = str(worker_config['id'])
self.processes[worker_id] = {
'pid': process.pid,
'process': process,
'started_at': time.time(),
'config': worker_config,
'log_file': log_file,
'is_monitor': stop_on_master_exit and env.get('COMFYUI_MASTER_PID'), # Track if using monitor
'launching': True # Mark as launching until confirmed running
}
# Save process info for persistence
self.save_processes()
if stop_on_master_exit and env.get('COMFYUI_MASTER_PID'):
debug_log(f"Launched worker {worker_name} via monitor (Monitor PID: {process.pid})")
else:
log(f"Launched worker {worker_name} directly (PID: {process.pid})")
debug_log(f"Log file: {log_file}")
return process.pid
def stop_worker(self, worker_id):
"""Stop a worker process."""
# Ensure worker_id is string
worker_id = str(worker_id)
if worker_id not in self.processes:
return False, "Worker not managed by UI"
proc_info = self.processes[worker_id]
process = proc_info.get('process')
pid = proc_info['pid']
debug_log(f"Attempting to stop worker {worker_id} (PID: {pid})")
# For restored processes without subprocess object
if not process:
try:
print(f"[Distributed] Stopping restored process (no subprocess object)")
if self._kill_process_tree(pid):
del self.processes[worker_id]
self.save_processes()
debug_log(f"Successfully stopped worker {worker_id} and all child processes")
return True, "Worker stopped"
else:
return False, "Failed to stop worker process"
except Exception as e:
print(f"[MultiGPU] Exception during stop: {e}")
return False, f"Error stopping worker: {str(e)}"
# Normal case with subprocess object
# Check if still running
if process.poll() is not None:
# Already stopped
print(f"[Distributed] Worker {worker_id} already stopped")
del self.processes[worker_id]
self.save_processes()
return False, "Worker already stopped"
# Try to kill the entire process tree
try:
debug_log(f"Using process tree kill for worker {worker_id}")
if self._kill_process_tree(pid):
# Clean up tracking
del self.processes[worker_id]
self.save_processes()
debug_log(f"Successfully stopped worker {worker_id} and all child processes")
return True, "Worker stopped"
else:
# Fallback to normal termination
print(f"[Distributed] Process tree kill failed, trying normal termination")
if process:
terminate_process(process, timeout=PROCESS_TERMINATION_TIMEOUT)
del self.processes[worker_id]
self.save_processes()
return True, "Worker stopped (fallback)"
except Exception as e:
print(f"[Distributed] Exception during stop: {e}")
return False, f"Error stopping worker: {str(e)}"
def get_managed_workers(self):
"""Get list of workers managed by this process."""
managed = {}
for worker_id, proc_info in list(self.processes.items()):
# Check if process is still running
is_running, _ = self._check_worker_process(worker_id, proc_info)
if is_running:
managed[worker_id] = {
'pid': proc_info['pid'],
'started_at': proc_info['started_at'],
'log_file': proc_info.get('log_file'),
'launching': proc_info.get('launching', False)
}
else:
# Process has stopped, remove from tracking
del self.processes[worker_id]
return managed
def cleanup_all(self):
"""Stop all managed workers (called on shutdown)."""
for worker_id in list(self.processes.keys()):
try:
self.stop_worker(worker_id)
except Exception as e:
print(f"[Distributed] Error stopping worker {worker_id}: {e}")
# Clear all managed processes from config
config = load_config()
config['managed_processes'] = {}
save_config(config)
def load_processes(self):
"""Load persisted process information from config."""
config = load_config()
managed_processes = config.get('managed_processes', {})
# Verify each saved process is still running
for worker_id, proc_info in managed_processes.items():
pid = proc_info.get('pid')
if pid and self._is_process_running(pid):
# Reconstruct process info
self.processes[worker_id] = {
'pid': pid,
'process': None, # Can't reconstruct subprocess object
'started_at': proc_info.get('started_at'),
'config': proc_info.get('config'),
'log_file': proc_info.get('log_file')
}
print(f"[Distributed] Restored worker {worker_id} (PID: {pid})")
else:
if pid:
print(f"[Distributed] Worker {worker_id} (PID: {pid}) is no longer running")
def save_processes(self):
"""Save process information to config."""
config = load_config()
# Create serializable version of process info
managed_processes = {}
for worker_id, proc_info in self.processes.items():
# Only save if process is running
is_running, _ = self._check_worker_process(worker_id, proc_info)
if is_running:
managed_processes[worker_id] = {
'pid': proc_info['pid'],
'started_at': proc_info['started_at'],
'config': proc_info['config'],
'log_file': proc_info.get('log_file'),
'launching': proc_info.get('launching', False)
}
# Update config with managed processes
config['managed_processes'] = managed_processes
save_config(config)
def _is_process_running(self, pid):
"""Check if a process with given PID is running."""
return is_process_alive(pid)
def _check_worker_process(self, worker_id, proc_info):
"""Check if a worker process is still running and return status.
Returns:
tuple: (is_running, has_subprocess_object)
"""
process = proc_info.get('process')
pid = proc_info.get('pid')
if process:
# Normal case with subprocess object
return process.poll() is None, True
elif pid:
# Restored process without subprocess object
return self._is_process_running(pid), False
else:
# No process or PID
return False, False
def _kill_process_tree(self, pid):
"""Kill a process and all its children."""
if PSUTIL_AVAILABLE:
try:
parent = psutil.Process(pid)
children = parent.children(recursive=True)
# Log what we're about to kill
debug_log(f"Killing process tree for PID {pid} ({parent.name()})")
for child in children:
debug_log(f" - Child PID {child.pid} ({child.name()})")
# Kill children first
for child in children:
try:
debug_log(f"Terminating child {child.pid}")
child.terminate()
except psutil.NoSuchProcess:
pass
# Wait a bit for graceful termination
gone, alive = psutil.wait_procs(children, timeout=PROCESS_WAIT_TIMEOUT)
# Force kill any remaining
for child in alive:
try:
debug_log(f"Force killing child {child.pid}")
child.kill()
except psutil.NoSuchProcess:
pass
# Finally kill the parent
try:
debug_log(f"Terminating parent {pid}")
parent.terminate()
parent.wait(timeout=PROCESS_WAIT_TIMEOUT)
except psutil.TimeoutExpired:
debug_log(f"Force killing parent {pid}")
parent.kill()
except psutil.NoSuchProcess:
debug_log(f"Parent process {pid} already gone")
return True
except psutil.NoSuchProcess:
debug_log(f"Process {pid} does not exist")
return False
except Exception as e:
debug_log(f"Error killing process tree: {e}")
# Fall through to OS commands
# Fallback to OS-specific commands
print(f"[Distributed] Using OS commands to kill process tree")
if platform.system() == "Windows":
try:
# Use wmic to find child processes
result = subprocess.run(['wmic', 'process', 'where', f'ParentProcessId={pid}', 'get', 'ProcessId'],
capture_output=True, text=True)
if result.returncode == 0:
lines = result.stdout.strip().split('\n')[1:] # Skip header
child_pids = [line.strip() for line in lines if line.strip() and line.strip().isdigit()]
print(f"[Distributed] Found child processes: {child_pids}")
# Kill each child
for child_pid in child_pids:
try:
subprocess.run(['taskkill', '/F', '/PID', child_pid],
capture_output=True, check=False)
except:
pass