logboard/app/api/v1/endpoints/containers.py
Сергей Антропов 011d460a38 feat: добавлено сворачивание секций и периодическое обновление контейнеров
- Добавлена функция сворачивания/разворачивания секций локальных и удаленных контейнеров
- Реализовано периодическое обновление списка контейнеров каждые 30 секунд
- Добавлена автоматическая фильтрация остановленных контейнеров
- Обновлены обработчики событий для корректной работы в свернутом sidebar
- Добавлены функции обновления счетчиков контейнеров
- Обновлена документация с описанием новых функций
- Добавлены тестовые скрипты для проверки функциональности

Автор: Сергей Антропов
Сайт: https://devops.org.ru
2025-08-20 20:06:33 +03:00

96 lines
3.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
LogBoard+ - Контейнеры API
Автор: Сергей Антропов
Сайт: https://devops.org.ru
"""
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Body
from fastapi.responses import JSONResponse
from core.auth import get_current_user
from core.docker import (
load_excluded_containers,
save_excluded_containers,
get_all_projects_with_remote,
list_containers_with_remote,
DEFAULT_PROJECT,
DEFAULT_PROJECTS
)
router = APIRouter()
@router.get("/excluded")
def api_get_excluded_containers(current_user: str = Depends(get_current_user)):
"""Получить список исключенных контейнеров"""
return JSONResponse(
content={"excluded_containers": load_excluded_containers()},
headers={
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0"
}
)
@router.post("/excluded")
def api_update_excluded_containers(
containers: List[str] = Body(...),
current_user: str = Depends(get_current_user)
):
"""Обновить список исключенных контейнеров"""
success = save_excluded_containers(containers)
if success:
return JSONResponse(
content={"status": "success", "message": "Список исключенных контейнеров обновлен"},
headers={
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0"
}
)
else:
raise HTTPException(
status_code=500,
detail="Ошибка сохранения списка исключенных контейнеров. Попробуйте еще раз или обратитесь к администратору."
)
@router.get("/projects")
def api_projects(current_user: str = Depends(get_current_user)):
"""Получить список всех проектов Docker Compose включая удаленные хосты"""
return JSONResponse(
content=get_all_projects_with_remote(),
headers={
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0"
}
)
@router.get("/services")
def api_services(
projects: Optional[str] = Query(None),
include_stopped: bool = Query(False),
current_user: str = Depends(get_current_user)
):
"""Получить список контейнеров с поддержкой множественных проектов включая удаленные хосты"""
project_list = None
if projects:
project_list = [p.strip() for p in projects.split(",") if p.strip()]
elif DEFAULT_PROJECTS and DEFAULT_PROJECTS.strip():
project_list = [p.strip() for p in DEFAULT_PROJECTS.split(",") if p.strip()]
elif DEFAULT_PROJECT and DEFAULT_PROJECT.strip():
project_list = [DEFAULT_PROJECT]
# Если ни одна переменная не указана или пустая, показываем все контейнеры (project_list остается None)
return JSONResponse(
content=list_containers_with_remote(projects=project_list, include_stopped=include_stopped),
headers={
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": "0"
}
)