Repository navigation
Expand file tree
/
Copy pathnpu_workers.py
More file actions
1482 lines (1179 loc) · 45.4 KB
/
Copy pathnpu_workers.py
File metadata and controls
1482 lines (1179 loc) · 45.4 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
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
# AutoBot - AI-Powered Automation Platform
# Author: mrveiss
"""
NPU Worker Registry API
RESTful API endpoints for managing NPU workers, load balancing, and monitoring.
Issue #641: Workers no longer self-register. Main host controls all registration.
- Workers are added via POST /api/npu/workers/pair (contacts worker, assigns ID)
- Heartbeats from unpaired workers are rejected
- Bootstrap endpoint deprecated in favor of pair endpoint
Endpoints:
- GET /api/npu/workers - List all workers
- POST /api/npu/workers - Register new worker (manual)
- POST /api/npu/workers/pair - Pair with worker at URL (Issue #641 - preferred method)
- GET /api/npu/workers/{id} - Get worker details
- PUT /api/npu/workers/{id} - Update worker
- DELETE /api/npu/workers/{id} - Remove worker
- POST /api/npu/workers/{id}/test - Test worker connection
- GET /api/npu/workers/{id}/metrics - Get worker metrics
- POST /api/npu/workers/{id}/unpair - Unpair worker from master (Issue #640)
- POST /api/npu/workers/{id}/repair - Re-pair worker with master (Issue #640)
- GET /api/npu/load-balancing - Get load balancing config
- PUT /api/npu/load-balancing - Update load balancing config
- GET /api/npu/status - Get NPU worker pool status
- POST /api/npu/workers/heartbeat - Receive worker heartbeat (paired workers only)
- POST /api/npu/workers/bootstrap - Bootstrap configuration (deprecated)
- GET /api/npu/pool/stats - Get pool-level statistics (Issue #168)
- GET /api/npu/pool/workers - Get per-worker health states (Issue #168)
- POST /api/npu/pool/reload - Hot-reload pool configuration (Issue #168)
"""
from typing import Any, Dict, List
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import JSONResponse
from auth_middleware import check_admin_permission
from autobot_shared.error_boundaries import ErrorCategory, with_error_handling
from autobot_shared.logging_manager import get_logger
from autobot_shared.redis_management.types import DATABASE_MAPPING
from autobot_shared.ssot_config import DEFAULT_EMBEDDING_MODEL, DEFAULT_LLM_MODEL
from autobot_shared.time_utils import utc_timestamp
from models.npu_models import (
LoadBalancingConfig,
NPUWorkerConfig,
NPUWorkerDetails,
NPUWorkerMetrics,
WorkerHeartbeat,
WorkerTestResult,
)
from services.npu_worker_manager import get_worker_manager
from utils.catalog_http_exceptions import raise_internal_error, raise_invalid_input, raise_not_found
from .schemas_system import (
NPUPoolReloadResponse,
NPUPoolWorkersResponse,
NPUStatusResponse,
NPUWorkerHeartbeatResponse,
NPUWorkerPairResponse,
NPUWorkerRepairResponse,
NPUWorkerUnpairResponse,
)
logger = get_logger(__name__)
# Create router with /api/npu prefix
router = APIRouter()
# ==============================================
# WORKER MANAGEMENT ENDPOINTS
# ==============================================
@router.get("/npu/workers", response_model=List[NPUWorkerDetails])
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="list_workers",
error_code_prefix="NPU_WORKERS",
)
async def list_workers(admin_check: bool = Depends(check_admin_permission)):
"""
List all registered NPU workers with their current status.
Issue #744: Requires admin authentication.
Returns:
List of worker details including configuration and runtime status
"""
try:
manager = await get_worker_manager()
workers = await manager.list_workers()
return workers
except Exception as e:
logger.error("Failed to list workers: %s", e)
raise_internal_error("Failed to retrieve workers")
@router.post("/npu/workers", response_model=NPUWorkerDetails, status_code=status.HTTP_201_CREATED)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="add_worker",
error_code_prefix="NPU_WORKERS",
)
async def add_worker(
admin_check: bool = Depends(check_admin_permission),
worker_config: NPUWorkerConfig = None,
):
"""
Register a new NPU worker.
Issue #744: Requires admin authentication.
The worker will be validated by testing connectivity before registration.
Args:
worker_config: Worker configuration
Returns:
Created worker details with initial status
Raises:
400: If worker ID already exists or connection test fails
500: If registration fails
"""
try:
manager = await get_worker_manager()
worker_details = await manager.add_worker(worker_config)
logger.info("Successfully registered worker: %s", worker_config.id)
return worker_details
except ValueError as e:
logger.warning("Worker registration failed: %s", e)
raise_invalid_input("worker", str(e))
except Exception as e:
logger.error("Failed to add worker: %s", e)
raise_internal_error("Failed to register worker")
@router.get("/npu/workers/{worker_id}", response_model=NPUWorkerDetails)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="get_worker",
error_code_prefix="NPU_WORKERS",
)
async def get_worker(
admin_check: bool = Depends(check_admin_permission),
worker_id: str = None,
):
"""
Get detailed information about a specific worker.
Issue #744: Requires admin authentication.
Args:
worker_id: Worker identifier
Returns:
Worker details including config, status, and metrics
Raises:
404: If worker not found
500: If retrieval fails
"""
try:
manager = await get_worker_manager()
worker = await manager.get_worker(worker_id)
if not worker:
raise_not_found("Worker", worker_id)
return worker
except HTTPException:
raise
except Exception as e:
logger.error("Failed to get worker %s: %s", worker_id, e)
raise_internal_error("Failed to retrieve worker")
@router.put("/npu/workers/{worker_id}", response_model=NPUWorkerDetails)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="update_worker",
error_code_prefix="NPU_WORKERS",
)
async def update_worker(
admin_check: bool = Depends(check_admin_permission),
worker_id: str = None,
worker_config: NPUWorkerConfig = None,
):
"""
Update existing worker configuration.
Issue #744: Requires admin authentication.
The updated configuration will be validated by testing connectivity.
Args:
worker_id: Worker identifier
worker_config: Updated worker configuration
Returns:
Updated worker details
Raises:
400: If worker ID mismatch or connection test fails
404: If worker not found
500: If update fails
"""
try:
# Validate worker_id matches config
if worker_config.id != worker_id:
raise_invalid_input("worker_id", "must match ID in configuration")
manager = await get_worker_manager()
worker_details = await manager.update_worker(worker_id, worker_config)
logger.info("Successfully updated worker: %s", worker_id)
return worker_details
except ValueError as e:
logger.warning("Worker update failed: %s", e)
raise_invalid_input("worker", str(e))
except HTTPException:
raise
except Exception as e:
logger.error("Failed to update worker %s: %s", worker_id, e)
raise_internal_error("Failed to update worker")
@router.delete("/npu/workers/{worker_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="remove_worker",
error_code_prefix="NPU_WORKERS",
)
async def remove_worker(
admin_check: bool = Depends(check_admin_permission),
worker_id: str = None,
):
"""
Remove worker from registry.
Issue #744: Requires admin authentication.
Args:
worker_id: Worker identifier
Raises:
404: If worker not found
500: If removal fails
"""
try:
manager = await get_worker_manager()
await manager.remove_worker(worker_id)
logger.info("Successfully removed worker: %s", worker_id)
return JSONResponse(status_code=status.HTTP_204_NO_CONTENT, content=None)
except ValueError as e:
logger.warning("Worker removal failed: %s", e)
raise_not_found("Worker", worker_id)
except Exception as e:
logger.error("Failed to remove worker %s: %s", worker_id, e)
raise_internal_error("Failed to remove worker")
@router.post("/npu/workers/{worker_id}/test", response_model=WorkerTestResult)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="test_worker",
error_code_prefix="NPU_WORKERS",
)
async def test_worker(
admin_check: bool = Depends(check_admin_permission),
worker_id: str = None,
):
"""
Test connection to a specific worker.
Issue #744: Requires admin authentication.
Args:
worker_id: Worker identifier
Returns:
Test result with connection details and response time
Raises:
404: If worker not found
500: If test fails
"""
try:
manager = await get_worker_manager()
worker = await manager.get_worker(worker_id)
if not worker:
raise_not_found("Worker", worker_id)
# Test connection using worker config
test_result = await manager.test_worker_connection(worker.config)
logger.info(f"Worker {worker_id} test: {'SUCCESS' if test_result.success else 'FAILED'}")
return test_result
except HTTPException:
raise
except Exception as e:
logger.error("Failed to test worker %s: %s", worker_id, e)
raise_internal_error("Failed to test worker")
@router.get("/npu/workers/{worker_id}/metrics", response_model=NPUWorkerMetrics | None)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="get_worker_metrics",
error_code_prefix="NPU_WORKERS",
)
async def get_worker_metrics(
admin_check: bool = Depends(check_admin_permission),
worker_id: str = None,
):
"""
Get performance metrics for a specific worker.
Issue #744: Requires admin authentication.
Args:
worker_id: Worker identifier
Returns:
Worker performance metrics or None if not available
Raises:
404: If worker not found
500: If retrieval fails
"""
try:
manager = await get_worker_manager()
worker = await manager.get_worker(worker_id)
if not worker:
raise_not_found("Worker", worker_id)
metrics = await manager.get_worker_metrics(worker_id)
return metrics
except HTTPException:
raise
except Exception as e:
logger.error("Failed to get metrics for worker %s: %s", worker_id, e)
raise_internal_error("Failed to retrieve metrics")
# ==============================================
# WORKER LOGGING CONFIGURATION ENDPOINTS
# ==============================================
@router.get("/npu/workers/{worker_id}/logging", response_model=Dict[str, Any])
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="get_worker_log_level",
error_code_prefix="NPU_WORKERS",
)
async def get_worker_log_level(
admin_check: bool = Depends(check_admin_permission),
worker_id: str = None,
):
"""
Get the current log level of a worker.
Issue #744: Requires admin authentication.
Args:
worker_id: Worker identifier
Returns:
Current log level configuration
Raises:
404: If worker not found
500: If request fails
"""
import httpx
try:
manager = await get_worker_manager()
worker = await manager.get_worker(worker_id)
if not worker:
raise_not_found("Worker", worker_id)
worker_url = f"http://{worker.config.ip_address}:{worker.config.port}"
async with httpx.AsyncClient(timeout=5.0) as client:
response = await client.get(f"{worker_url}/config/logging")
if response.status_code != 200:
raise_internal_error(f"Worker returned error: {response.status_code}")
return response.json()
except HTTPException:
raise
except Exception as e:
logger.error("Failed to get log level for worker %s: %s", worker_id, e)
raise_internal_error("Failed to get log level")
async def _send_log_level_to_worker(worker_url: str, level: str, worker_id: str) -> dict:
"""Helper for set_worker_log_level. Ref: #1088."""
import httpx
async with httpx.AsyncClient(timeout=5.0) as client:
response = await client.put(f"{worker_url}/config/logging", params={"level": level})
if response.status_code != 200:
raise_internal_error(f"Worker returned error: {response.status_code}")
logger.info("Set log level to %s for worker %s", level, worker_id)
return response.json()
@router.put("/npu/workers/{worker_id}/logging", response_model=Dict[str, Any])
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="set_worker_log_level",
error_code_prefix="NPU_WORKERS",
)
async def set_worker_log_level(
admin_check: bool = Depends(check_admin_permission),
worker_id: str = None,
level: str = "INFO",
):
"""
Set the log level of a worker at runtime.
Issue #744: Requires admin authentication.
Args:
worker_id: Worker identifier
level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
Returns:
Updated log level configuration
Raises:
400: If invalid log level
404: If worker not found
500: If request fails
"""
level = level.upper()
valid_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
if level not in valid_levels:
raise_invalid_input("log_level", f"must be one of: {valid_levels}")
try:
manager = await get_worker_manager()
worker = await manager.get_worker(worker_id)
if not worker:
raise_not_found("Worker", worker_id)
worker_url = f"http://{worker.config.ip_address}:{worker.config.port}"
return await _send_log_level_to_worker(worker_url, level, worker_id)
except HTTPException:
raise
except Exception as e:
logger.error("Failed to set log level for worker %s: %s", worker_id, e)
raise_internal_error("Failed to set log level")
# ==============================================
# LOAD BALANCING CONFIGURATION ENDPOINTS
# ==============================================
@router.get("/npu/load-balancing", response_model=LoadBalancingConfig)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="get_load_balancing_config",
error_code_prefix="NPU_WORKERS",
)
async def get_load_balancing_config(
admin_check: bool = Depends(check_admin_permission),
):
"""
Get current load balancing configuration.
Issue #744: Requires admin authentication.
Returns:
Load balancing configuration including strategy and health check settings
"""
try:
manager = await get_worker_manager()
config = manager.get_load_balancing_config()
return config
except Exception as e:
logger.error("Failed to get load balancing config: %s", e)
raise_internal_error("Failed to retrieve load balancing configuration")
@router.put("/npu/load-balancing", response_model=LoadBalancingConfig)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="update_load_balancing_config",
error_code_prefix="NPU_WORKERS",
)
async def update_load_balancing_config(
admin_check: bool = Depends(check_admin_permission),
config: LoadBalancingConfig = None,
):
"""
Update load balancing configuration.
Issue #744: Requires admin authentication.
Args:
config: New load balancing configuration
Returns:
Updated load balancing configuration
Raises:
400: If configuration is invalid
500: If update fails
"""
try:
manager = await get_worker_manager()
await manager.update_load_balancing_config(config)
logger.info("Updated load balancing config: strategy=%s", config.strategy)
return config
except ValueError as e:
logger.warning("Load balancing config update failed: %s", e)
raise_invalid_input("load_balancing_config", str(e))
except Exception as e:
logger.error("Failed to update load balancing config: %s", e)
raise_internal_error("Failed to update load balancing configuration")
# ==============================================
# HEALTH AND STATUS ENDPOINTS
# ==============================================
@router.get("/npu/status", response_model=NPUStatusResponse)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="get_npu_status",
error_code_prefix="NPU_WORKERS",
)
async def get_npu_status(admin_check: bool = Depends(check_admin_permission)):
"""
Get overall NPU worker pool status.
Issue #744: Requires admin authentication.
Returns:
Summary of worker pool health and availability
"""
try:
manager = await get_worker_manager()
workers = await manager.list_workers()
# Aggregate statistics
total_workers = len(workers)
online_workers = sum(1 for w in workers if w.status.status == "online")
total_capacity = sum(w.config.max_concurrent_tasks for w in workers if w.config.enabled)
current_load = sum(w.status.current_load for w in workers)
return {
"status": "healthy" if online_workers > 0 else "degraded",
"total_workers": total_workers,
"online_workers": online_workers,
"offline_workers": total_workers - online_workers,
"total_capacity": total_capacity,
"current_load": current_load,
"utilization_percent": round((current_load / total_capacity * 100) if total_capacity > 0 else 0, 2),
"load_balancing_strategy": manager.get_load_balancing_config().strategy,
}
except Exception as e:
logger.error("Failed to get NPU status: %s", e)
raise_internal_error("Failed to retrieve NPU status")
# ==============================================
# NPU HEALTH PROXY (Issue #1007)
# ==============================================
@router.get("/npu/health", response_model=None)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="proxy_npu_health",
error_code_prefix="NPU_WORKERS",
)
async def proxy_npu_health():
"""
Proxy NPU worker health check to avoid CORS/mixed content.
Issue #1007: Frontend must not fetch NPU directly from browser.
"""
from autobot_shared.ssot_config import config as ssot_config
npu_host = ssot_config.vm.npu
npu_port = ssot_config.port.npu
url = f"http://{npu_host}:{npu_port}/health"
try:
async with httpx.AsyncClient(timeout=5.0) as client:
resp = await client.get(url)
return JSONResponse(
status_code=resp.status_code,
content=resp.json(),
)
except httpx.ConnectError:
return JSONResponse(
status_code=503,
content={"status": "offline", "detail": "NPU worker unreachable"},
)
except Exception as e:
logger.error("NPU health proxy failed: %s", e)
return JSONResponse(
status_code=502,
content={"status": "error", "detail": "Internal server error"},
)
# ==============================================
# WORKER RE-PAIRING ENDPOINTS (Issue #640)
# ==============================================
@router.post("/npu/workers/{worker_id}/unpair", response_model=NPUWorkerUnpairResponse)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="unpair_worker",
error_code_prefix="NPU_WORKERS",
)
async def unpair_worker(
admin_check: bool = Depends(check_admin_permission),
worker_id: str = None,
):
"""
Unpair a worker from the master (Issue #640).
Issue #744: Requires admin authentication.
This clears the worker's registration, allowing it to re-pair
when it next starts or receives a bootstrap request.
Args:
worker_id: Worker identifier to unpair
Returns:
Confirmation of unpair action
Raises:
404: If worker not found
500: If unpair fails
"""
try:
manager = await get_worker_manager()
worker = await manager.get_worker(worker_id)
if not worker:
raise_not_found("Worker", worker_id)
# Remove worker from registry
await manager.remove_worker(worker_id)
logger.info("Successfully unpaired worker: %s", worker_id)
return {
"success": True,
"worker_id": worker_id,
"message": "Worker unpaired successfully. It will re-register on next startup.",
}
except HTTPException:
raise
except Exception as e:
logger.error("Failed to unpair worker %s: %s", worker_id, e)
raise_internal_error("Failed to unpair worker")
def _generate_repair_bootstrap_config() -> dict:
"""
Generate fresh bootstrap configuration for worker re-pairing.
Issue #665: Extracted from repair_worker() for single responsibility.
Returns:
Dict with redis, backend, models, and logging configuration.
"""
from autobot_shared.ssot_config import config as ssot_config
return {
"redis": {
"host": ssot_config.vm.redis,
"port": ssot_config.port.redis,
"password": ssot_config.redis.password,
"db": DATABASE_MAPPING["main"],
"socket_timeout": 5,
"max_connections": 10,
},
"backend": {
"host": ssot_config.vm.main,
"port": ssot_config.port.backend,
"register_with_backend": True,
"health_check_interval": 30,
},
"models": {
"autoload_defaults": True,
"default_embedding": DEFAULT_EMBEDDING_MODEL,
"default_llm": DEFAULT_LLM_MODEL,
},
"logging": {"level": "INFO", "format": "structured"},
}
async def _handle_existing_worker_removal(manager, worker, worker_id: str, force: bool) -> tuple[str, str]:
"""
Handle removal of existing worker registration.
Issue #665: Extracted from repair_worker() for single responsibility.
Returns:
Tuple of (worker_url, platform)
Raises:
HTTPException: If worker is active and force is not set
"""
worker_url = worker.config.url
platform = worker.config.platform
if worker.status.status == "online" and not force:
logger.warning("Attempted to re-pair active worker %s without force flag", worker_id)
raise_invalid_input("worker", "Worker is currently active. Use force=true to re-pair anyway.")
await manager.remove_worker(worker_id)
logger.info("Removed existing registration for worker: %s", worker_id)
return worker_url, platform
async def _resolve_repair_worker_info(manager, worker_id: str, request: dict) -> tuple[str, str, str]:
"""Helper for repair_worker. Ref: #1088."""
import uuid
worker = await manager.get_worker(worker_id)
force = request.get("force", False)
if worker:
worker_url, platform = await _handle_existing_worker_removal(manager, worker, worker_id, force)
worker_url = request.get("url", "") or worker_url
else:
worker_url = request.get("url", "")
platform = request.get("platform", "unknown")
new_worker_id = f"{platform}_npu_worker_{uuid.uuid4().hex[:8]}"
return worker_url, platform, new_worker_id
@router.post("/npu/workers/{worker_id}/repair", response_model=NPUWorkerRepairResponse)
@with_error_handling(
category=ErrorCategory.SERVER_ERROR,
operation="repair_worker",
error_code_prefix="NPU_WORKERS",
)
async def repair_worker(
admin_check: bool = Depends(check_admin_permission),
worker_id: str = None,
request: dict = None,
):
"""
Re-pair a worker with the master (Issue #640).
Issue #744: Requires admin authentication.
This initiates a re-pairing sequence:
1. Removes existing worker registration (if any)
2. Optionally sends command to worker to clear its local pairing
3. Returns new bootstrap configuration for immediate re-registration
Issue #665: Refactored to extract helper methods.
Args:
worker_id: Worker identifier
request: Optional dict with:
- url: Worker URL (if different from registered)
- force: Force re-pair even if worker is active
Returns:
New bootstrap configuration for the worker
Raises:
400: If re-pair is not possible
500: If re-pair fails
"""
try:
manager = await get_worker_manager()
request = request or {}
worker_url, platform, new_worker_id = await _resolve_repair_worker_info(manager, worker_id, request)
logger.info("Re-pair initiated for worker %s -> new ID: %s", worker_id, new_worker_id)
return {
"success": True,
"old_worker_id": worker_id,
"new_worker_id": new_worker_id,
"config": _generate_repair_bootstrap_config(),
"server_timestamp": utc_timestamp(),
"message": "Worker unpaired. Use provided config for re-registration.",
}
except HTTPException:
raise
except Exception as e:
logger.error("Failed to re-pair worker %s: %s", worker_id, e)
raise_internal_error("Failed to re-pair worker")
# ==============================================
# WORKER PAIRING ENDPOINT (Issue #641)
# ==============================================
import uuid
from dataclasses import dataclass
from typing import Dict, Tuple
import httpx
@dataclass
class WorkerHealthInfo:
"""Health information from a worker."""
platform: str
existing_worker_id: str | None
already_paired: bool
async def _check_worker_health(client: httpx.AsyncClient, worker_url: str) -> WorkerHealthInfo:
"""
Check if worker is reachable and get health information.
Args:
client: HTTP client for requests
worker_url: Base URL of the worker
Returns:
WorkerHealthInfo with platform and pairing status
Raises:
HTTPException: If worker is unreachable or health check fails
"""
try:
health_response = await client.get(f"{worker_url}/health")
if health_response.status_code != 200:
raise_invalid_input("worker_url", f"health check failed: {health_response.status_code}")
health_data = health_response.json()
info = WorkerHealthInfo(
platform=health_data.get("platform", "unknown"),
existing_worker_id=health_data.get("worker_id"),
already_paired=health_data.get("paired", False),
)
logger.info(
"Worker reachable: platform=%s, existing_id=%s, paired=%s",
info.platform,
info.existing_worker_id,
info.already_paired,
)
return info
except httpx.RequestError:
raise_invalid_input("worker_url", "Cannot reach worker at {worker_url}")
def _generate_worker_id(health_info: WorkerHealthInfo) -> str:
"""Generate or reuse worker ID based on health information."""
if health_info.existing_worker_id and health_info.already_paired:
logger.info("Reusing existing worker ID: %s", health_info.existing_worker_id)
return health_info.existing_worker_id
worker_id = f"{health_info.platform}_npu_worker_{uuid.uuid4().hex[:8]}"
logger.info("Generated new worker ID: %s", worker_id)
return worker_id
def _build_pairing_config() -> Tuple[Dict, str]:
"""
Build configuration to send to worker during pairing.
Returns:
Tuple of (worker_config dict, main_host string)
"""
from autobot_shared.ssot_config import config as ssot_config
worker_config = {
"redis": {
"host": ssot_config.vm.redis,
"port": ssot_config.port.redis,
"password": ssot_config.redis.password,
"db": DATABASE_MAPPING["main"],
},
"backend": {
"host": ssot_config.vm.main,
"port": ssot_config.port.backend,
},
}
main_host = f"{ssot_config.vm.main}:{ssot_config.port.backend}"
return worker_config, main_host
async def _send_pairing_request(
client: httpx.AsyncClient,
worker_url: str,
worker_id: str,
worker_config: Dict,
main_host: str,
) -> Dict:
"""
Send pairing request to worker and return device info.
Args:
client: HTTP client for requests
worker_url: Base URL of the worker
worker_id: Assigned worker ID
worker_config: Configuration for the worker
main_host: Main host address
Returns:
Device info dict from worker response
Raises:
HTTPException: If pairing request fails
"""
pair_request = {
"worker_id": worker_id,
"main_host": main_host,
"config": worker_config,
}
try:
pair_response = await client.post(f"{worker_url}/pair", json=pair_request)
if pair_response.status_code != 200:
raise_invalid_input("worker_url", f"Worker rejected pairing: {pair_response.text}")
pair_result = pair_response.json()
return pair_result.get("device_info", {})
except httpx.RequestError:
raise_invalid_input("worker_url", "Failed to send pair request to worker")
async def _register_worker_in_backend(
worker_id: str,
worker_url: str,
platform: str,
worker_name: str,
enabled: bool,
) -> None:
"""
Register or update worker in backend database.
Args:
worker_id: Worker's unique ID
worker_url: Worker's URL
platform: Worker's platform (windows/linux)
worker_name: Friendly name for worker
enabled: Whether worker is enabled
"""
manager = await get_worker_manager()
existing = await manager.get_worker(worker_id)
if existing:
logger.info("Updating existing worker registration: %s", worker_id)
heartbeat = WorkerHeartbeat(
worker_id=worker_id,
platform=platform,
url=worker_url,
status="online",
current_load=0,
models_loaded=[],
uptime_seconds=0,
)
await manager.update_worker_status_from_heartbeat(heartbeat)