forked from ShaerWare/AI_Secretary_System
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice_manager.py
More file actions
887 lines (738 loc) · 34.7 KB
/
service_manager.py
File metadata and controls
887 lines (738 loc) · 34.7 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
#!/usr/bin/env python3
"""
Service Manager - управление процессами и сервисами AI Secretary System.
Поддерживает запуск/остановку vLLM и других внешних сервисов.
"""
import asyncio
import json
import logging
import os
import subprocess
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import TYPE_CHECKING, AsyncGenerator, Dict, List, Optional
import psutil
if TYPE_CHECKING:
import docker
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class ServiceConfig:
"""Конфигурация сервиса"""
name: str
display_name: str
start_script: Optional[str] = None
port: Optional[int] = None
health_endpoint: Optional[str] = None
log_file: Optional[str] = None
venv_path: Optional[str] = None
internal: bool = False # True = управляется orchestrator, False = внешний процесс
gpu_required: bool = False
cpu_only: bool = False
pid_file: Optional[str] = None
# Конфигурация всех сервисов системы
SERVICE_CONFIGS: Dict[str, ServiceConfig] = {
"vllm": ServiceConfig(
name="vllm",
display_name="vLLM Server",
start_script="start_qwen.sh",
port=11434,
health_endpoint="/health",
log_file="logs/vllm.log",
venv_path=os.path.expanduser("~/vllm_env/venv"),
internal=False,
gpu_required=True,
pid_file="logs/vllm.pid",
),
"xtts_anna": ServiceConfig(
name="xtts_anna",
display_name="XTTS Anna",
internal=True,
gpu_required=True,
),
"xtts_marina": ServiceConfig(
name="xtts_marina",
display_name="XTTS Marina",
internal=True,
gpu_required=True,
),
"piper": ServiceConfig(
name="piper",
display_name="Piper TTS",
internal=True,
cpu_only=True,
),
"openvoice": ServiceConfig(
name="openvoice",
display_name="OpenVoice TTS",
internal=True,
gpu_required=True,
),
"orchestrator": ServiceConfig(
name="orchestrator",
display_name="Orchestrator",
port=8002,
health_endpoint="/health",
log_file="logs/orchestrator.log",
internal=True,
),
}
class ServiceManager:
"""
Менеджер сервисов для запуска/остановки/мониторинга.
Особенности:
- Внешние сервисы (vLLM) запускаются через start_script
- Внутренние сервисы (XTTS, Piper) управляются orchestrator
- Поддерживает чтение логов и streaming
- Отслеживает PID и память процессов
"""
def __init__(self, base_dir: Optional[Path] = None):
self.base_dir = base_dir or Path(__file__).parent
self.logs_dir = self.base_dir / "logs"
self.logs_dir.mkdir(exist_ok=True)
# Запущенные процессы (только внешние, управляемые этим классом)
self.processes: Dict[str, subprocess.Popen] = {}
# Последние ошибки
self.last_errors: Dict[str, str] = {}
# Время запуска сервисов
self.start_times: Dict[str, datetime] = {}
logger.info(f"🔧 ServiceManager инициализирован: {self.base_dir}")
def _get_config(self, service_name: str) -> ServiceConfig:
"""Получает конфигурацию сервиса"""
if service_name not in SERVICE_CONFIGS:
raise ValueError(f"Неизвестный сервис: {service_name}")
return SERVICE_CONFIGS[service_name]
def _find_process_by_port(self, port: int) -> Optional[psutil.Process]:
"""Находит процесс, слушающий указанный порт"""
for conn in psutil.net_connections(kind="inet"):
if conn.laddr.port == port and conn.status == "LISTEN":
try:
return psutil.Process(conn.pid)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
return None
def _find_process_by_pid_file(self, pid_file: str) -> Optional[psutil.Process]:
"""Находит процесс по PID файлу"""
pid_path = self.base_dir / pid_file
if pid_path.exists():
try:
pid = int(pid_path.read_text().strip())
proc = psutil.Process(pid)
if proc.is_running():
return proc
except (ValueError, psutil.NoSuchProcess, psutil.AccessDenied):
pass
return None
def _is_service_running(self, service_name: str) -> tuple[bool, Optional[int], Optional[float]]:
"""
Проверяет, запущен ли сервис.
Returns: (is_running, pid, memory_mb)
"""
config = self._get_config(service_name)
# Проверяем внутренний процесс
if service_name in self.processes:
proc = self.processes[service_name]
if proc.poll() is None: # Still running
try:
ps_proc = psutil.Process(proc.pid)
memory_mb = ps_proc.memory_info().rss / (1024 * 1024)
return True, proc.pid, memory_mb
except psutil.NoSuchProcess:
pass
# Процесс завершился
del self.processes[service_name]
# Проверяем по PID файлу
if config.pid_file:
ps_proc = self._find_process_by_pid_file(config.pid_file)
if ps_proc:
memory_mb = ps_proc.memory_info().rss / (1024 * 1024)
return True, ps_proc.pid, memory_mb
# Проверяем по порту
if config.port:
ps_proc = self._find_process_by_port(config.port)
if ps_proc:
memory_mb = ps_proc.memory_info().rss / (1024 * 1024)
return True, ps_proc.pid, memory_mb
return False, None, None
async def _check_health(self, service_name: str) -> bool:
"""Проверяет health endpoint сервиса"""
config = self._get_config(service_name)
if not config.port or not config.health_endpoint:
return True # Нет health check = считаем OK если процесс работает
import httpx
try:
async with httpx.AsyncClient(timeout=5.0) as client:
url = f"http://localhost:{config.port}{config.health_endpoint}"
response = await client.get(url)
return bool(response.status_code == 200)
except Exception:
return False
def _is_docker_mode(self) -> bool:
"""Определяет, запущены ли мы в Docker-контейнере"""
return Path("/.dockerenv").exists() or os.getenv("DOCKER_CONTAINER") == "1"
def _get_docker_client(self) -> Optional["docker.DockerClient"]:
"""Получает Docker клиент (lazy initialization)"""
if not hasattr(self, "_docker_client"):
try:
import docker
self._docker_client = docker.from_env()
except Exception as e:
logger.warning(f"Docker client unavailable: {e}")
self._docker_client = None
return self._docker_client
async def _get_vllm_model_from_db(self) -> Optional[str]:
"""Получает выбранную модель vLLM из БД"""
try:
from db.database import get_session_context
async with get_session_context() as session:
from db.repositories.config import ConfigRepository
config_repo = ConfigRepository(session)
llm_config = await config_repo.get_llm_config()
return llm_config.get("vllm_model")
except Exception as e:
logger.debug(f"Could not get vLLM model from DB: {e}")
return None
async def _start_vllm_container(self, model_override: Optional[str] = None) -> dict:
"""Запускает vLLM контейнер через Docker API"""
container_name = os.getenv("VLLM_CONTAINER_NAME", "ai-secretary-vllm")
# Приоритет: model_override > DB config > env var
vllm_model = model_override
if not vllm_model:
# Попробуем получить из БД
vllm_model = await self._get_vllm_model_from_db()
if not vllm_model:
vllm_model = os.getenv("VLLM_MODEL", "Qwen/Qwen2.5-7B-Instruct-AWQ")
docker_client = self._get_docker_client()
if not docker_client:
return {"status": "error", "message": "Docker client недоступен"}
try:
# Проверяем, есть ли уже контейнер
try:
container = docker_client.containers.get(container_name)
if container.status == "running":
return {
"status": "ok",
"message": "vLLM контейнер уже запущен",
"container_id": container.short_id,
}
# Контейнер существует, но остановлен - запускаем
logger.info(f"🚀 Запуск существующего контейнера {container_name}...")
container.start()
self.start_times["vllm"] = datetime.now()
return {
"status": "ok",
"message": "vLLM контейнер запущен",
"container_id": container.short_id,
}
except Exception:
pass # Контейнер не существует
# Проверяем наличие образа
vllm_image = "vllm/vllm-openai:latest"
try:
docker_client.images.get(vllm_image)
except Exception:
return {
"status": "error",
"message": f"Образ {vllm_image} не найден. Выполните: docker pull {vllm_image}",
}
# Создаём контейнер через Docker SDK
logger.info(f"🚀 Создание контейнера {container_name}...")
# Получаем сеть ai-secretary
try:
network = docker_client.networks.get("ai_secretary_system_ai-secretary")
except Exception:
# Пробуем альтернативное имя
try:
network = docker_client.networks.get("ai-secretary")
except Exception:
network = None
# Конфигурация контейнера
container = docker_client.containers.run(
image="vllm/vllm-openai:latest",
name=container_name,
command=[
"--model",
vllm_model,
"--gpu-memory-utilization",
"0.5",
"--max-model-len",
"4096",
"--dtype",
"float16",
"--max-num-seqs",
"32",
"--enforce-eager",
"--trust-remote-code",
"--host",
"0.0.0.0",
"--port",
"8000",
],
volumes={
os.path.expanduser("~/.cache/huggingface"): {
"bind": "/root/.cache/huggingface",
"mode": "rw",
},
},
environment={
"HUGGING_FACE_HUB_TOKEN": os.getenv("HF_TOKEN", ""),
"VLLM_LOGGING_LEVEL": "WARNING",
# Note: CUDA_VISIBLE_DEVICES not needed - DeviceIDs handles GPU selection
},
device_requests=[
{
"Driver": "nvidia",
"DeviceIDs": [os.getenv("VLLM_GPU_ID", "1")], # Use RTX 3060 (CC 8.6)
"Capabilities": [["gpu"]],
}
],
detach=True,
restart_policy={"Name": "unless-stopped"},
)
# Подключаем к сети
if network:
network.connect(container)
self.start_times["vllm"] = datetime.now()
logger.info(f"✅ vLLM контейнер создан: {container.short_id}")
return {
"status": "ok",
"message": "vLLM контейнер запускается (загрузка модели ~2-3 мин)",
"container_id": container.short_id,
}
except Exception as e:
error_msg = str(e)
self.last_errors["vllm"] = error_msg
logger.error(f"❌ Ошибка запуска vLLM контейнера: {error_msg}")
return {"status": "error", "message": f"Ошибка запуска: {error_msg}"}
async def _stop_vllm_container(self) -> dict:
"""Останавливает vLLM контейнер через Docker API"""
container_name = os.getenv("VLLM_CONTAINER_NAME", "ai-secretary-vllm")
docker_client = self._get_docker_client()
if not docker_client:
return {"status": "error", "message": "Docker client недоступен"}
try:
container = docker_client.containers.get(container_name)
if container.status != "running":
return {"status": "ok", "message": "vLLM контейнер уже остановлен"}
logger.info(f"🛑 Остановка контейнера {container_name}...")
container.stop(timeout=30)
self.start_times.pop("vllm", None)
logger.info("✅ vLLM контейнер остановлен")
return {"status": "ok", "message": "vLLM контейнер остановлен"}
except Exception as e:
if "No such container" in str(e) or "404" in str(e):
return {"status": "ok", "message": "vLLM контейнер не существует"}
error_msg = str(e)
self.last_errors["vllm"] = error_msg
logger.error(f"❌ Ошибка остановки vLLM контейнера: {error_msg}")
return {"status": "error", "message": f"Ошибка остановки: {error_msg}"}
async def _remove_vllm_container(self) -> dict:
"""Удаляет vLLM контейнер для переключения модели"""
container_name = os.getenv("VLLM_CONTAINER_NAME", "ai-secretary-vllm")
docker_client = self._get_docker_client()
if not docker_client:
return {"status": "error", "message": "Docker client недоступен"}
try:
container = docker_client.containers.get(container_name)
# Если запущен - останавливаем
if container.status == "running":
logger.info(f"🛑 Остановка контейнера {container_name}...")
container.stop(timeout=30)
# Удаляем контейнер
logger.info(f"🗑️ Удаление контейнера {container_name}...")
container.remove()
self.start_times.pop("vllm", None)
logger.info("✅ vLLM контейнер удалён")
return {"status": "ok", "message": "vLLM контейнер удалён"}
except Exception as e:
if "No such container" in str(e) or "404" in str(e):
return {"status": "ok", "message": "vLLM контейнер не существует"}
error_msg = str(e)
self.last_errors["vllm"] = error_msg
logger.error(f"❌ Ошибка удаления vLLM контейнера: {error_msg}")
return {"status": "error", "message": f"Ошибка удаления: {error_msg}"}
async def switch_vllm_model(self, model: str) -> dict:
"""
Переключает модель vLLM: удаляет текущий контейнер и создаёт новый.
Args:
model: Полное имя модели (например, "Qwen/Qwen2.5-7B-Instruct-AWQ")
Returns:
dict с результатом операции
"""
logger.info(f"🔄 Переключение vLLM на модель: {model}")
# Сохраняем модель в БД
try:
from db.database import get_session_context
async with get_session_context() as session:
from db.repositories.config import ConfigRepository
config_repo = ConfigRepository(session)
await config_repo.set_llm_config({"vllm_model": model})
logger.info(f"✅ Модель {model} сохранена в конфигурации")
except Exception as e:
logger.error(f"❌ Ошибка сохранения модели в БД: {e}")
return {"status": "error", "message": f"Ошибка сохранения конфигурации: {e}"}
# Удаляем текущий контейнер
remove_result = await self._remove_vllm_container()
if remove_result.get("status") == "error" and "не существует" not in remove_result.get(
"message", ""
):
return remove_result
# Запускаем с новой моделью
return await self._start_vllm_container(model_override=model)
def _is_vllm_container_running(self) -> tuple[bool, Optional[str]]:
"""Проверяет, запущен ли vLLM контейнер"""
container_name = os.getenv("VLLM_CONTAINER_NAME", "ai-secretary-vllm")
docker_client = self._get_docker_client()
if not docker_client:
return False, None
try:
container = docker_client.containers.get(container_name)
return container.status == "running", container.short_id
except Exception:
return False, None
async def start_service(self, service_name: str) -> dict:
"""
Запускает сервис.
Returns: {"status": "ok/error", "message": str, "pid": int}
"""
config = self._get_config(service_name)
if config.internal:
return {
"status": "error",
"message": f"Сервис {config.display_name} управляется orchestrator, перезапустите orchestrator",
}
# Для vLLM в Docker режиме используем Docker API
if service_name == "vllm" and self._is_docker_mode():
return await self._start_vllm_container()
# Проверяем, не запущен ли уже
is_running, pid, _ = self._is_service_running(service_name)
if is_running:
return {"status": "ok", "message": f"{config.display_name} уже запущен", "pid": pid}
if not config.start_script:
return {"status": "error", "message": f"Нет скрипта запуска для {config.display_name}"}
script_path = self.base_dir / config.start_script
if not script_path.exists():
return {"status": "error", "message": f"Скрипт не найден: {script_path}"}
try:
# Запускаем процесс
log_file = (
self.logs_dir / f"{service_name}.log"
if not config.log_file
else self.base_dir / config.log_file
)
with open(log_file, "a") as log:
log.write(f"\n{'=' * 60}\n")
log.write(f"Starting {config.display_name} at {datetime.now().isoformat()}\n")
log.write(f"{'=' * 60}\n")
env = os.environ.copy()
# Активируем venv если указан
if config.venv_path:
venv_bin = Path(config.venv_path) / "bin"
env["PATH"] = f"{venv_bin}:{env['PATH']}"
env["VIRTUAL_ENV"] = config.venv_path
proc = subprocess.Popen(
["bash", str(script_path)],
stdout=open(log_file, "a"),
stderr=subprocess.STDOUT,
cwd=str(self.base_dir),
env=env,
start_new_session=True, # Отсоединяем от родительского процесса
)
self.processes[service_name] = proc
self.start_times[service_name] = datetime.now()
# Ждем немного и проверяем, что процесс не упал
await asyncio.sleep(2)
if proc.poll() is not None:
# Процесс завершился
return {
"status": "error",
"message": f"{config.display_name} завершился сразу после запуска. Проверьте логи.",
}
# Сохраняем PID
if config.pid_file:
pid_path = self.base_dir / config.pid_file
pid_path.write_text(str(proc.pid))
logger.info(f"✅ {config.display_name} запущен (PID: {proc.pid})")
return {"status": "ok", "message": f"{config.display_name} запущен", "pid": proc.pid}
except Exception as e:
error_msg = str(e)
self.last_errors[service_name] = error_msg
logger.error(f"❌ Ошибка запуска {config.display_name}: {error_msg}")
return {"status": "error", "message": f"Ошибка запуска: {error_msg}"}
async def stop_service(self, service_name: str) -> dict:
"""Останавливает сервис"""
config = self._get_config(service_name)
if config.internal:
return {
"status": "error",
"message": f"Сервис {config.display_name} управляется orchestrator",
}
# Для vLLM в Docker режиме используем Docker API
if service_name == "vllm" and self._is_docker_mode():
return await self._stop_vllm_container()
is_running, _pid, _ = self._is_service_running(service_name)
if not is_running:
return {"status": "ok", "message": f"{config.display_name} уже остановлен"}
try:
# Пытаемся остановить gracefully через SIGTERM
if service_name in self.processes:
proc = self.processes[service_name]
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
del self.processes[service_name]
else:
# Процесс не наш - ищем по PID/порту
proc = None
if config.pid_file:
proc = self._find_process_by_pid_file(config.pid_file)
if not proc and config.port:
proc = self._find_process_by_port(config.port)
if proc:
proc.terminate()
try:
proc.wait(timeout=10)
except psutil.TimeoutExpired:
proc.kill()
# Удаляем PID файл
if config.pid_file:
pid_path = self.base_dir / config.pid_file
if pid_path.exists():
pid_path.unlink()
# Убираем из времени запуска
self.start_times.pop(service_name, None)
logger.info(f"🛑 {config.display_name} остановлен")
return {"status": "ok", "message": f"{config.display_name} остановлен"}
except Exception as e:
error_msg = str(e)
self.last_errors[service_name] = error_msg
logger.error(f"❌ Ошибка остановки {config.display_name}: {error_msg}")
return {"status": "error", "message": f"Ошибка остановки: {error_msg}"}
async def restart_service(self, service_name: str) -> dict:
"""Перезапускает сервис"""
self._get_config(service_name) # Validate service exists
stop_result = await self.stop_service(service_name)
if stop_result["status"] == "error" and "управляется orchestrator" not in stop_result.get(
"message", ""
):
return stop_result
# Даем время на освобождение порта
await asyncio.sleep(2)
return await self.start_service(service_name)
def get_service_status(self, service_name: str) -> dict:
"""Получает статус сервиса"""
config = self._get_config(service_name)
# Для vLLM в Docker режиме проверяем контейнер
if service_name == "vllm" and self._is_docker_mode():
is_running, container_id = self._is_vllm_container_running()
status = {
"name": service_name,
"display_name": config.display_name,
"is_running": is_running,
"pid": None,
"container_id": container_id,
"memory_mb": None,
"port": 8000, # vLLM container port
"internal": False,
"gpu_required": config.gpu_required,
"cpu_only": config.cpu_only,
"log_file": None,
"last_error": self.last_errors.get(service_name),
"docker_mode": True,
}
if service_name in self.start_times and is_running:
uptime = datetime.now() - self.start_times[service_name]
status["uptime_seconds"] = uptime.total_seconds()
return status
is_running, pid, memory_mb = self._is_service_running(service_name)
status = {
"name": service_name,
"display_name": config.display_name,
"is_running": is_running,
"pid": pid,
"memory_mb": round(memory_mb, 2) if memory_mb else None,
"port": config.port,
"internal": config.internal,
"gpu_required": config.gpu_required,
"cpu_only": config.cpu_only,
"log_file": config.log_file,
"last_error": self.last_errors.get(service_name),
}
# Добавляем uptime
if service_name in self.start_times and is_running:
uptime = datetime.now() - self.start_times[service_name]
status["uptime_seconds"] = uptime.total_seconds()
return status
def get_all_status(self) -> dict:
"""Получает статус всех сервисов"""
services = {}
for name in SERVICE_CONFIGS:
services[name] = self.get_service_status(name)
return {"services": services, "timestamp": datetime.now().isoformat()}
def read_log(
self, service_name: str, lines: int = 100, offset: int = 0, search: Optional[str] = None
) -> dict:
"""
Читает логи сервиса.
Args:
service_name: Имя сервиса или имя лог-файла
lines: Количество строк
offset: Пропустить N строк с конца
search: Фильтр по подстроке
Returns:
{"lines": [...], "total_lines": int, "file": str}
"""
# Определяем путь к логу
if service_name in SERVICE_CONFIGS:
config = SERVICE_CONFIGS[service_name]
if config.log_file:
log_path = self.base_dir / config.log_file
else:
log_path = self.logs_dir / f"{service_name}.log"
else:
# Возможно это имя файла
log_path = self.logs_dir / service_name
if not log_path.exists():
log_path = self.base_dir / service_name
if not log_path.exists():
return {
"lines": [],
"total_lines": 0,
"file": str(log_path),
"error": "Лог файл не найден",
}
try:
with open(log_path, encoding="utf-8", errors="replace") as f:
all_lines = f.readlines()
# Фильтруем по поиску если указан
if search:
all_lines = [line for line in all_lines if search.lower() in line.lower()]
total = len(all_lines)
# Применяем offset и limit
if offset > 0:
end_idx = max(0, total - offset)
start_idx = max(0, end_idx - lines)
else:
start_idx = max(0, total - lines)
end_idx = total
result_lines = all_lines[start_idx:end_idx]
return {
"lines": [line.rstrip("\n") for line in result_lines],
"total_lines": total,
"file": str(log_path),
"start_line": start_idx + 1,
"end_line": end_idx,
}
except Exception as e:
return {"lines": [], "total_lines": 0, "file": str(log_path), "error": str(e)}
async def stream_log(
self, service_name: str, interval: float = 1.0
) -> AsyncGenerator[str, None]:
"""
Async generator для SSE streaming логов.
Возвращает новые строки по мере их появления.
"""
# Определяем путь к логу
if service_name in SERVICE_CONFIGS:
config = SERVICE_CONFIGS[service_name]
if config.log_file:
log_path = self.base_dir / config.log_file
else:
log_path = self.logs_dir / f"{service_name}.log"
else:
log_path = self.logs_dir / service_name
if not log_path.exists():
yield json.dumps({"error": "Лог файл не найден", "file": str(log_path)})
return
# Начинаем с конца файла
last_position = log_path.stat().st_size
while True:
try:
current_size = log_path.stat().st_size
if current_size > last_position:
# Есть новые данные
with open(log_path, encoding="utf-8", errors="replace") as f:
f.seek(last_position)
new_content = f.read()
last_position = f.tell()
# Отправляем новые строки
for line in new_content.splitlines():
if line.strip():
yield json.dumps(
{"line": line, "timestamp": datetime.now().isoformat()}
)
elif current_size < last_position:
# Файл был перезаписан (rotate)
last_position = 0
await asyncio.sleep(interval)
except asyncio.CancelledError:
break
except Exception as e:
yield json.dumps({"error": str(e)})
await asyncio.sleep(interval)
def get_available_logs(self) -> List[dict]:
"""Возвращает список доступных лог-файлов"""
logs = []
# Логи из конфигураций сервисов
for name, config in SERVICE_CONFIGS.items():
if config.log_file:
log_path = self.base_dir / config.log_file
if log_path.exists():
stat = log_path.stat()
logs.append(
{
"name": name,
"file": config.log_file,
"display_name": config.display_name,
"size_kb": round(stat.st_size / 1024, 2),
"modified": datetime.fromtimestamp(stat.st_mtime).isoformat(),
}
)
# Дополнительные логи в папке logs
for log_file in self.logs_dir.glob("*.log"):
if not any(
log_file.name == Path(c.log_file).name
for c in SERVICE_CONFIGS.values()
if c.log_file
):
stat = log_file.stat()
logs.append(
{
"name": log_file.stem,
"file": str(log_file.relative_to(self.base_dir)),
"display_name": log_file.stem,
"size_kb": round(stat.st_size / 1024, 2),
"modified": datetime.fromtimestamp(stat.st_mtime).isoformat(),
}
)
return sorted(logs, key=lambda x: x["modified"], reverse=True)
# Глобальный экземпляр для использования в orchestrator
_service_manager: Optional[ServiceManager] = None
def get_service_manager() -> ServiceManager:
"""Получает или создает глобальный ServiceManager"""
global _service_manager
if _service_manager is None:
_service_manager = ServiceManager()
return _service_manager
if __name__ == "__main__":
import asyncio
async def test() -> None:
manager = ServiceManager()
print("=== Service Status ===")
status = manager.get_all_status()
for name, info in status["services"].items():
running = "✅" if info["is_running"] else "❌"
print(
f"{running} {info['display_name']}: PID={info['pid']}, Memory={info['memory_mb']}MB"
)
print("\n=== Available Logs ===")
for log in manager.get_available_logs():
print(f" - {log['display_name']}: {log['file']} ({log['size_kb']}KB)")
print("\n=== Recent vLLM Logs ===")
logs = manager.read_log("vllm", lines=10)
for line in logs["lines"]:
print(f" {line}")
asyncio.run(test())