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
2466 lines (2095 loc) · 103 KB
/
distributed.py
File metadata and controls
2466 lines (2095 loc) · 103 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 comfy.model_management
import subprocess
import platform
import time
import atexit
import signal
import sys
import shlex
import uuid
from multiprocessing import Queue
from comfy.utils import ProgressBar
# 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, get_worker_timeout_seconds, validate_worker_config
from .utils.connection_parser import ConnectionParser, ConnectionParseError, validate_connection_string
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, MAX_BATCH
)
# 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
# Get CUDA device if available
cuda_device = None
cuda_device_count = 0
physical_device_count = 0
if torch.cuda.is_available():
try:
import os
import subprocess
# Get visible device count (what PyTorch sees)
cuda_device_count = torch.cuda.device_count()
# Try to get actual physical device info
cuda_visible = os.environ.get('CUDA_VISIBLE_DEVICES', '')
# Method 1: Parse CUDA_VISIBLE_DEVICES
if cuda_visible and cuda_visible.strip():
visible_devices = [int(d.strip()) for d in cuda_visible.split(',') if d.strip().isdigit()]
if visible_devices:
# Get the first visible device as the actual physical device
cuda_device = visible_devices[0]
# Try to get total physical device count using nvidia-smi
try:
result = subprocess.run(['nvidia-smi', '--query-gpu=name', '--format=csv,noheader'],
capture_output=True, text=True, timeout=5)
if result.returncode == 0:
physical_device_count = len(result.stdout.strip().split('\n'))
else:
physical_device_count = max(visible_devices) + 1 # Best guess
except:
physical_device_count = max(visible_devices) + 1 # Best guess
else:
cuda_device = 0
physical_device_count = cuda_device_count
else:
# No CUDA_VISIBLE_DEVICES set, current device is actual device
cuda_device = torch.cuda.current_device()
physical_device_count = cuda_device_count
except Exception as e:
debug_log(f"CUDA detection error: {e}")
cuda_device = None
cuda_device_count = 0
physical_device_count = 0
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,
"cuda_device": cuda_device,
"cuda_device_count": physical_device_count if physical_device_count > 0 else cuda_device_count,
"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.get("/distributed/system_info")
async def get_system_info_endpoint(request):
"""Get system information including machine ID for local worker detection."""
try:
import socket
return web.json_response({
"status": "success",
"hostname": socket.gethostname(),
"machine_id": get_machine_id(),
"platform": {
"system": platform.system(),
"machine": platform.machine(),
"node": platform.node(),
"path_separator": os.sep, # Add path separator
"os_name": os.name # Add OS name (posix, nt, etc.)
},
"is_docker": is_docker_environment(),
"is_runpod": is_runpod_environment(),
"runpod_pod_id": os.environ.get('RUNPOD_POD_ID')
})
except Exception as e:
return web.json_response({
"status": "error",
"message": str(e)
}, status=500)
@server.PromptServer.instance.routes.post("/distributed/validate_connection")
async def validate_connection_endpoint(request):
"""Validate a connection string and optionally test connectivity."""
try:
data = await request.json()
connection_string = data.get('connection')
test_connectivity = data.get('test_connectivity', False)
timeout = data.get('timeout', 10)
if not connection_string:
return await handle_api_error(request, "Missing connection string", 400)
# Validate connection string format
is_valid, error_message = validate_connection_string(connection_string)
if not is_valid:
return web.json_response({
"status": "invalid",
"error": error_message,
"details": None
})
# Parse connection string
try:
parsed = ConnectionParser.parse(connection_string)
except ConnectionParseError as e:
return web.json_response({
"status": "invalid",
"error": str(e),
"details": None
})
response_data = {
"status": "valid",
"error": None,
"details": {
"host": parsed['host'],
"port": parsed['port'],
"protocol": parsed['protocol'],
"worker_type": parsed['worker_type'],
"is_secure": parsed['is_secure'],
"connection_url": ConnectionParser.to_url(parsed)
}
}
# Test connectivity if requested
if test_connectivity:
try:
connectivity_result = await _test_worker_connectivity(parsed, timeout)
response_data["connectivity"] = connectivity_result
except Exception as e:
response_data["connectivity"] = {
"status": "error",
"error": str(e),
"reachable": False,
"response_time": None
}
return web.json_response(response_data)
except Exception as e:
return await handle_api_error(request, e, 500)
async def _test_worker_connectivity(parsed_connection: dict, timeout: int = 10) -> dict:
"""Test connectivity to a worker endpoint."""
import time
start_time = time.time()
connection_url = ConnectionParser.to_url(parsed_connection)
# Try to connect to the worker's health endpoint
health_url = f"{connection_url.rstrip('/')}/system_stats"
try:
session = await get_client_session()
# Use appropriate timeout
connector_timeout = aiohttp.ClientTimeout(total=timeout)
# Handle SSL appropriately based on protocol
ssl_context = None
if parsed_connection.get('protocol') == 'http':
ssl_context = False # Disable SSL for HTTP connections
async with session.get(health_url, timeout=connector_timeout, ssl=ssl_context) as response:
response_time = round((time.time() - start_time) * 1000, 2) # ms
if response.status == 200:
try:
data = await response.json()
return {
"status": "success",
"reachable": True,
"response_time": response_time,
"worker_info": {
"version": data.get("version"),
"device_name": data.get("device", {}).get("name"),
"vram_total": data.get("device", {}).get("vram_total"),
"vram_free": data.get("device", {}).get("vram_free")
}
}
except:
# Response wasn't JSON, but connection worked
return {
"status": "reachable_no_data",
"reachable": True,
"response_time": response_time,
"worker_info": None
}
else:
return {
"status": "http_error",
"reachable": True,
"response_time": response_time,
"error": f"HTTP {response.status}",
"worker_info": None
}
except asyncio.TimeoutError:
return {
"status": "timeout",
"reachable": False,
"response_time": None,
"error": f"Connection timeout after {timeout}s"
}
except aiohttp.ClientConnectorError as e:
return {
"status": "connection_error",
"reachable": False,
"response_time": None,
"error": f"Connection failed: {str(e)}"
}
except Exception as e:
return {
"status": "error",
"reachable": False,
"response_time": None,
"error": str(e)
}
@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 connection string if provided
if "connection" in data:
worker["connection"] = data["connection"]
# Parse and update host/port from connection string
try:
parsed = ConnectionParser.parse(data["connection"])
worker["host"] = parsed["host"]
worker["port"] = parsed["port"]
worker["type"] = parsed["worker_type"]
except ConnectionParseError as e:
return await handle_api_error(request, f"Invalid connection string: {e}", 400)
# 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"]
# Handle type field
if "type" in data:
worker["type"] = data["type"]
# Validate the updated worker configuration
is_valid, error_message = validate_worker_config(worker)
if not is_valid:
return await handle_api_error(request, f"Invalid worker configuration: {error_message}", 400)
worker_found = True
break
if not worker_found:
# If worker not found, create new worker
required_fields = ["name"]
# Check if connection string is provided
if "connection" in data and data["connection"]:
# Use connection string approach
new_worker = {
"id": worker_id,
"name": data["name"],
"connection": data["connection"],
"enabled": data.get("enabled", False),
"extra_args": data.get("extra_args", ""),
}
# Parse connection string to populate host/port/type
try:
parsed = ConnectionParser.parse(data["connection"])
new_worker.update({
"host": parsed["host"],
"port": parsed["port"],
"type": parsed["worker_type"]
})
except ConnectionParseError as e:
return await handle_api_error(request, f"Invalid connection string: {e}", 400)
# Add CUDA device for local workers
if parsed["worker_type"] == "local":
new_worker["cuda_device"] = data.get("cuda_device", 0)
elif all(key in data for key in ["name", "port"]):
# Use legacy host/port approach
new_worker = {
"id": worker_id,
"name": data["name"],
"host": data.get("host", "localhost"),
"port": data["port"],
"cuda_device": data.get("cuda_device", 0),
"enabled": data.get("enabled", False),
"extra_args": data.get("extra_args", ""),
"type": data.get("type", "local")
}
else:
return await handle_api_error(request, f"Worker {worker_id} not found and missing required fields for creation", 404)
# Validate new worker configuration
is_valid, error_message = validate_worker_config(new_worker)
if not is_valid:
return await handle_api_error(request, f"Invalid worker configuration: {error_message}", 400)
if "workers" not in config:
config["workers"] = []
config["workers"].append(new_worker)
worker_found = True
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 "name" in data:
config['master']['name'] = data['name']
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/local-worker-status")
async def get_local_worker_status_endpoint(request):
"""Check status of all local workers (localhost/no host specified)."""
try:
config = load_config()
worker_statuses = {}
for worker in config.get("workers", []):
# Only check local workers
if not worker.get("host") or worker.get("host") in ["localhost", "127.0.0.1"]:
worker_id = worker["id"]
port = worker["port"]
# Check if worker is enabled
if not worker.get("enabled", False):
worker_statuses[worker_id] = {
"online": False,
"enabled": False,
"processing": False,
"queue_count": 0
}
continue
# Try to connect to worker
try:
session = await get_client_session()
async with session.get(
f"http://localhost:{port}/prompt",
timeout=aiohttp.ClientTimeout(total=2)
) as resp:
if resp.status == 200:
data = await resp.json()
queue_remaining = data.get("exec_info", {}).get("queue_remaining", 0)
worker_statuses[worker_id] = {
"online": True,
"enabled": True,
"processing": queue_remaining > 0,
"queue_count": queue_remaining
}
else:
worker_statuses[worker_id] = {
"online": False,
"enabled": True,
"processing": False,
"queue_count": 0,
"error": f"HTTP {resp.status}"
}
except asyncio.TimeoutError:
worker_statuses[worker_id] = {
"online": False,
"enabled": True,
"processing": False,
"queue_count": 0,
"error": "Timeout"
}
except Exception as e:
worker_statuses[worker_id] = {
"online": False,
"enabled": True,
"processing": False,
"queue_count": 0,
"error": str(e)
}
return web.json_response({
"status": "success",
"worker_statuses": worker_statuses
})
except Exception as e:
debug_log(f"Error checking local worker status: {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
current_dir = os.path.dirname(os.path.abspath(__file__))
# Method 1: Check for environment variable override
env_root = os.environ.get('COMFYUI_ROOT')
if env_root and os.path.exists(os.path.join(env_root, "main.py")):
debug_log(f"Found ComfyUI root via COMFYUI_ROOT environment variable: {env_root}")
return env_root
# Method 2: Try going up from custom_nodes directory
# This file should be in ComfyUI/custom_nodes/ComfyUI-Distributed/
potential_root = os.path.dirname(os.path.dirname(current_dir))
if os.path.exists(os.path.join(potential_root, "main.py")):
debug_log(f"Found ComfyUI root via directory traversal: {potential_root}")
return potential_root
# Method 3: Look for common Docker paths
docker_paths = ["/basedir", "/ComfyUI", "/app", "/workspace/ComfyUI", "/comfyui", "/opt/ComfyUI", "/workspace"]
for path in docker_paths:
if os.path.exists(path) and os.path.exists(os.path.join(path, "main.py")):
debug_log(f"Found ComfyUI root in Docker path: {path}")
return path
# Method 4: Search upwards for main.py
search_dir = current_dir
for _ in range(5): # Limit search depth
if os.path.exists(os.path.join(search_dir, "main.py")):
debug_log(f"Found ComfyUI root via upward search: {search_dir}")
return search_dir
parent = os.path.dirname(search_dir)
if parent == search_dir: # Reached root
break
search_dir = parent
# Method 5: Try to import and use folder_paths
try: