Add JWT authentication with user/password login, role-based access control, and Bearer token support while maintaining legacy API key compatibility for transition; update README with comprehensive JWT security guidelines, installation instructions for Python/SSH, development startup scripts (.env, run_dev.sh/ps1), and migrate all API examples to JWT authentication; update Ansible inventory SSH key paths from Docker container paths to local user paths
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
Routes API pour l'application Homelab Automation.
|
||||
|
||||
Ce module agrège tous les routers FastAPI pour une inclusion
|
||||
dans l'application principale.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.routes.auth import router as auth_router
|
||||
from app.routes.hosts import router as hosts_router
|
||||
from app.routes.groups import router as groups_router
|
||||
from app.routes.tasks import router as tasks_router
|
||||
from app.routes.logs import router as logs_router
|
||||
from app.routes.ansible import router as ansible_router
|
||||
from app.routes.playbooks import router as playbooks_router
|
||||
from app.routes.schedules import router as schedules_router
|
||||
from app.routes.adhoc import router as adhoc_router
|
||||
from app.routes.bootstrap import router as bootstrap_router
|
||||
from app.routes.health import router as health_router
|
||||
from app.routes.notifications import router as notifications_router
|
||||
from app.routes.help import router as help_router
|
||||
from app.routes.metrics import router as metrics_router
|
||||
from app.routes.builtin_playbooks import router as builtin_playbooks_router
|
||||
from app.routes.server import router as server_router
|
||||
from app.routes.alerts import router as alerts_router
|
||||
|
||||
# Router principal qui agrège tous les sous-routers
|
||||
api_router = APIRouter()
|
||||
|
||||
# Inclure tous les routers avec leurs préfixes
|
||||
api_router.include_router(auth_router, prefix="/auth", tags=["Auth"])
|
||||
api_router.include_router(hosts_router, prefix="/hosts", tags=["Hosts"])
|
||||
api_router.include_router(groups_router, prefix="/groups", tags=["Groups"])
|
||||
api_router.include_router(tasks_router, prefix="/tasks", tags=["Tasks"])
|
||||
api_router.include_router(logs_router, prefix="/logs", tags=["Logs"])
|
||||
api_router.include_router(ansible_router, prefix="/ansible", tags=["Ansible"])
|
||||
api_router.include_router(playbooks_router, prefix="/playbooks", tags=["Playbooks"])
|
||||
api_router.include_router(schedules_router, prefix="/schedules", tags=["Schedules"])
|
||||
api_router.include_router(adhoc_router, prefix="/adhoc", tags=["Ad-hoc"])
|
||||
api_router.include_router(bootstrap_router, prefix="/bootstrap", tags=["Bootstrap"])
|
||||
api_router.include_router(health_router, prefix="/health", tags=["Health"])
|
||||
api_router.include_router(notifications_router, prefix="/notifications", tags=["Notifications"])
|
||||
api_router.include_router(help_router, prefix="/help", tags=["Help"])
|
||||
api_router.include_router(metrics_router, prefix="/metrics", tags=["Metrics"])
|
||||
api_router.include_router(builtin_playbooks_router, prefix="/builtin-playbooks", tags=["Builtin Playbooks"])
|
||||
api_router.include_router(server_router, prefix="/server", tags=["Server"])
|
||||
api_router.include_router(alerts_router, prefix="/alerts", tags=["Alerts"])
|
||||
|
||||
__all__ = [
|
||||
"api_router",
|
||||
"hosts_router",
|
||||
"groups_router",
|
||||
"tasks_router",
|
||||
"logs_router",
|
||||
"ansible_router",
|
||||
"playbooks_router",
|
||||
"schedules_router",
|
||||
"adhoc_router",
|
||||
"bootstrap_router",
|
||||
"health_router",
|
||||
"notifications_router",
|
||||
"help_router",
|
||||
]
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
Routes API pour l'historique des commandes ad-hoc.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
|
||||
from app.core.dependencies import verify_api_key
|
||||
from app.services import adhoc_history_service
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/history")
|
||||
async def get_adhoc_history(
|
||||
category: Optional[str] = None,
|
||||
search: Optional[str] = None,
|
||||
limit: int = 50,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Récupère l'historique des commandes ad-hoc."""
|
||||
commands = await adhoc_history_service.get_commands(
|
||||
category=category,
|
||||
search=search,
|
||||
limit=limit,
|
||||
)
|
||||
return {
|
||||
"commands": [cmd.dict() for cmd in commands],
|
||||
"count": len(commands)
|
||||
}
|
||||
|
||||
|
||||
@router.get("/categories")
|
||||
async def get_adhoc_categories(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère la liste des catégories de commandes ad-hoc."""
|
||||
categories = await adhoc_history_service.get_categories()
|
||||
return {"categories": [cat.dict() for cat in categories]}
|
||||
|
||||
|
||||
@router.post("/categories")
|
||||
async def create_adhoc_category(
|
||||
name: str,
|
||||
description: Optional[str] = None,
|
||||
color: str = "#7c3aed",
|
||||
icon: str = "fa-folder",
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Crée une nouvelle catégorie de commandes ad-hoc."""
|
||||
category = await adhoc_history_service.add_category(name, description, color, icon)
|
||||
return {"category": category.dict(), "message": "Catégorie créée"}
|
||||
|
||||
|
||||
@router.put("/categories/{category_name}")
|
||||
async def update_adhoc_category(
|
||||
category_name: str,
|
||||
request: Request,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Met à jour une catégorie existante."""
|
||||
try:
|
||||
data = await request.json()
|
||||
new_name = data.get("name", category_name)
|
||||
description = data.get("description", "")
|
||||
color = data.get("color", "#7c3aed")
|
||||
icon = data.get("icon", "fa-folder")
|
||||
|
||||
success = await adhoc_history_service.update_category(category_name, new_name, description, color, icon)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Catégorie non trouvée")
|
||||
return {"message": "Catégorie mise à jour", "category": new_name}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/categories/{category_name}")
|
||||
async def delete_adhoc_category(
|
||||
category_name: str,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Supprime une catégorie et déplace ses commandes vers 'default'."""
|
||||
if category_name == "default":
|
||||
raise HTTPException(status_code=400, detail="La catégorie 'default' ne peut pas être supprimée")
|
||||
|
||||
success = await adhoc_history_service.delete_category(category_name)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Catégorie non trouvée")
|
||||
return {"message": "Catégorie supprimée", "category": category_name}
|
||||
|
||||
|
||||
@router.put("/history/{command_id}/category")
|
||||
async def update_adhoc_command_category(
|
||||
command_id: str,
|
||||
category: str,
|
||||
description: Optional[str] = None,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Met à jour la catégorie d'une commande dans l'historique."""
|
||||
success = await adhoc_history_service.update_command_category(command_id, category, description)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Commande non trouvée")
|
||||
return {"message": "Catégorie mise à jour", "command_id": command_id, "category": category}
|
||||
|
||||
|
||||
@router.delete("/history/{command_id}")
|
||||
async def delete_adhoc_command(command_id: str, api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Supprime une commande de l'historique."""
|
||||
success = await adhoc_history_service.delete_command(command_id)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Commande non trouvée")
|
||||
return {"message": "Commande supprimée", "command_id": command_id}
|
||||
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
Routes API pour les alertes.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.dependencies import get_db, verify_api_key
|
||||
from app.crud.alert import AlertRepository
|
||||
from app.services import ws_manager
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class AlertCreate(BaseModel):
|
||||
category: str = "general"
|
||||
level: Optional[str] = "info"
|
||||
title: Optional[str] = None
|
||||
message: str
|
||||
source: Optional[str] = None
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_alert(
|
||||
alert_data: AlertCreate,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Crée une nouvelle alerte."""
|
||||
repo = AlertRepository(db_session)
|
||||
alert = await repo.create(
|
||||
category=alert_data.category,
|
||||
level=alert_data.level,
|
||||
title=alert_data.title,
|
||||
message=alert_data.message,
|
||||
source=alert_data.source,
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "alert_created",
|
||||
"data": {
|
||||
"id": alert.id,
|
||||
"title": alert.title,
|
||||
"message": alert.message,
|
||||
"level": alert.level,
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
"id": alert.id,
|
||||
"title": alert.title,
|
||||
"message": alert.message,
|
||||
"level": alert.level,
|
||||
"category": alert.category,
|
||||
"created_at": alert.created_at,
|
||||
}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_alerts(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
unread_only: bool = False,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Récupère les alertes avec pagination."""
|
||||
repo = AlertRepository(db_session)
|
||||
alerts = await repo.list(limit=limit, offset=offset, unread_only=unread_only)
|
||||
|
||||
return {
|
||||
"alerts": [
|
||||
{
|
||||
"id": a.id,
|
||||
"title": a.title,
|
||||
"message": a.message,
|
||||
"level": a.level,
|
||||
"source": a.source,
|
||||
"category": a.category,
|
||||
"read": a.read_at is not None,
|
||||
"read_at": a.read_at,
|
||||
"created_at": a.created_at,
|
||||
}
|
||||
for a in alerts
|
||||
],
|
||||
"count": len(alerts)
|
||||
}
|
||||
|
||||
|
||||
@router.get("/unread-count")
|
||||
async def get_unread_count(
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Récupère le nombre d'alertes non lues."""
|
||||
repo = AlertRepository(db_session)
|
||||
count = await repo.count_unread()
|
||||
return {"unread": count}
|
||||
|
||||
|
||||
@router.post("/{alert_id}/read")
|
||||
async def mark_as_read(
|
||||
alert_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Marque une alerte comme lue."""
|
||||
repo = AlertRepository(db_session)
|
||||
alert = await repo.get(alert_id)
|
||||
|
||||
if not alert:
|
||||
raise HTTPException(status_code=404, detail="Alerte non trouvée")
|
||||
|
||||
await repo.mark_as_read(alert_id)
|
||||
await db_session.commit()
|
||||
|
||||
return {"message": "Alerte marquée comme lue", "id": alert_id}
|
||||
|
||||
|
||||
@router.post("/mark-all-read")
|
||||
async def mark_all_as_read(
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Marque toutes les alertes comme lues."""
|
||||
repo = AlertRepository(db_session)
|
||||
count = await repo.mark_all_as_read()
|
||||
await db_session.commit()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "alerts_cleared",
|
||||
"data": {"count": count}
|
||||
})
|
||||
|
||||
return {"message": f"{count} alerte(s) marquée(s) comme lue(s)"}
|
||||
|
||||
|
||||
@router.delete("/{alert_id}")
|
||||
async def delete_alert(
|
||||
alert_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Supprime une alerte."""
|
||||
repo = AlertRepository(db_session)
|
||||
alert = await repo.get(alert_id)
|
||||
|
||||
if not alert:
|
||||
raise HTTPException(status_code=404, detail="Alerte non trouvée")
|
||||
|
||||
await repo.delete(alert_id)
|
||||
await db_session.commit()
|
||||
|
||||
return {"message": "Alerte supprimée", "id": alert_id}
|
||||
@@ -0,0 +1,519 @@
|
||||
"""
|
||||
Routes API pour l'exécution Ansible.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
import subprocess
|
||||
from datetime import datetime, timezone
|
||||
from time import perf_counter
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.dependencies import get_db, verify_api_key
|
||||
from app.crud.task import TaskRepository
|
||||
from app.schemas.ansible import AnsibleExecutionRequest, AdHocCommandRequest, AdHocCommandResult
|
||||
from app.schemas.task_api import Task
|
||||
from app.schemas.common import LogEntry
|
||||
from app.services import (
|
||||
ansible_service,
|
||||
ws_manager,
|
||||
notification_service,
|
||||
adhoc_history_service,
|
||||
db,
|
||||
)
|
||||
from app.services.task_log_service import TaskLogService
|
||||
from app.utils.ssh_utils import find_ssh_private_key
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Instance du service de logs de tâches
|
||||
task_log_service = TaskLogService(settings.tasks_logs_dir)
|
||||
|
||||
|
||||
@router.get("/playbooks")
|
||||
async def get_ansible_playbooks(
|
||||
target: Optional[str] = None,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Liste les playbooks Ansible disponibles."""
|
||||
if target:
|
||||
playbooks = ansible_service.get_compatible_playbooks(target)
|
||||
else:
|
||||
playbooks = ansible_service.get_playbooks()
|
||||
|
||||
return {
|
||||
"playbooks": playbooks,
|
||||
"categories": ansible_service.get_playbook_categories(),
|
||||
"ansible_dir": str(settings.ansible_dir),
|
||||
"filter": target
|
||||
}
|
||||
|
||||
|
||||
@router.get("/inventory")
|
||||
async def get_ansible_inventory(
|
||||
group: Optional[str] = None,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Récupère l'inventaire Ansible."""
|
||||
return {
|
||||
"hosts": [h.dict() for h in ansible_service.get_hosts_from_inventory(group_filter=group)],
|
||||
"groups": ansible_service.get_groups(),
|
||||
"inventory_path": str(ansible_service.inventory_path),
|
||||
"filter": group
|
||||
}
|
||||
|
||||
|
||||
@router.get("/groups")
|
||||
async def get_ansible_groups(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère la liste des groupes Ansible."""
|
||||
return {"groups": ansible_service.get_groups()}
|
||||
|
||||
|
||||
@router.get("/ssh-config")
|
||||
async def get_ssh_config(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Diagnostic de la configuration SSH."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
ssh_key_path = Path(settings.ssh_key_path)
|
||||
ssh_dir = ssh_key_path.parent
|
||||
|
||||
available_files = []
|
||||
if ssh_dir.exists():
|
||||
available_files = [f.name for f in ssh_dir.iterdir()]
|
||||
|
||||
private_key_exists = ssh_key_path.exists()
|
||||
public_key_exists = Path(settings.ssh_key_path + ".pub").exists()
|
||||
|
||||
pub_keys_found = []
|
||||
for key_type in ["id_rsa", "id_ed25519", "id_ecdsa", "id_dsa"]:
|
||||
key_path = ssh_dir / f"{key_type}.pub"
|
||||
if key_path.exists():
|
||||
pub_keys_found.append(str(key_path))
|
||||
|
||||
active_private_key = find_ssh_private_key()
|
||||
|
||||
return {
|
||||
"ssh_key_path": settings.ssh_key_path,
|
||||
"ssh_dir": str(ssh_dir),
|
||||
"ssh_dir_exists": ssh_dir.exists(),
|
||||
"private_key_exists": private_key_exists,
|
||||
"public_key_exists": public_key_exists,
|
||||
"available_files": available_files,
|
||||
"public_keys_found": pub_keys_found,
|
||||
"active_private_key": active_private_key,
|
||||
"ssh_user": settings.ssh_user,
|
||||
"sshpass_available": shutil.which("sshpass") is not None,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/execute")
|
||||
async def execute_ansible_playbook(
|
||||
request: AnsibleExecutionRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Exécute un playbook Ansible."""
|
||||
start_time_dt = datetime.now(timezone.utc)
|
||||
|
||||
# Valider la compatibilité playbook-target
|
||||
playbooks = ansible_service.get_playbooks()
|
||||
playbook_info = next(
|
||||
(pb for pb in playbooks if pb['filename'] == request.playbook or pb['name'] == request.playbook.replace('.yml', '').replace('.yaml', '')),
|
||||
None
|
||||
)
|
||||
|
||||
if playbook_info:
|
||||
playbook_hosts = playbook_info.get('hosts', 'all')
|
||||
if not ansible_service.is_target_compatible_with_playbook(request.target, playbook_hosts):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Le playbook '{request.playbook}' (hosts: {playbook_hosts}) n'est pas compatible avec la cible '{request.target}'."
|
||||
)
|
||||
|
||||
# Créer une tâche en BD
|
||||
task_repo = TaskRepository(db_session)
|
||||
task_id = f"pb_{uuid.uuid4().hex[:12]}"
|
||||
playbook_name = request.playbook.replace('.yml', '').replace('-', ' ').title()
|
||||
|
||||
db_task = await task_repo.create(
|
||||
id=task_id,
|
||||
action=f"playbook:{request.playbook}",
|
||||
target=request.target,
|
||||
playbook=request.playbook,
|
||||
status="running",
|
||||
)
|
||||
await task_repo.update(db_task, started_at=start_time_dt)
|
||||
await db_session.commit()
|
||||
|
||||
# Créer aussi en mémoire
|
||||
task = Task(
|
||||
id=task_id,
|
||||
name=f"Playbook: {playbook_name}",
|
||||
host=request.target,
|
||||
status="running",
|
||||
progress=0,
|
||||
start_time=start_time_dt
|
||||
)
|
||||
db.tasks.insert(0, task)
|
||||
|
||||
try:
|
||||
result = await ansible_service.execute_playbook(
|
||||
playbook=request.playbook,
|
||||
target=request.target,
|
||||
extra_vars=request.extra_vars,
|
||||
check_mode=request.check_mode,
|
||||
verbose=request.verbose
|
||||
)
|
||||
|
||||
# Mettre à jour la tâche
|
||||
task.status = "completed" if result["success"] else "failed"
|
||||
task.progress = 100
|
||||
task.end_time = datetime.now(timezone.utc)
|
||||
task.duration = f"{result.get('execution_time', 0):.1f}s"
|
||||
task.output = result.get("stdout", "")
|
||||
task.error = result.get("stderr", "") if not result["success"] else None
|
||||
|
||||
# Ajouter un log
|
||||
log_entry = LogEntry(
|
||||
id=db.get_next_id("logs"),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
level="INFO" if result["success"] else "ERROR",
|
||||
message=f"Playbook {request.playbook} exécuté sur {request.target}: {'succès' if result['success'] else 'échec'}",
|
||||
source="ansible",
|
||||
host=request.target
|
||||
)
|
||||
db.logs.insert(0, log_entry)
|
||||
|
||||
# Sauvegarder le log markdown
|
||||
try:
|
||||
log_path = task_log_service.save_task_log(
|
||||
task=task,
|
||||
output=result.get("stdout", ""),
|
||||
error=result.get("stderr", "")
|
||||
)
|
||||
|
||||
created_log = task_log_service.index_log_file(log_path)
|
||||
if created_log:
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_log_created",
|
||||
"data": created_log.dict()
|
||||
})
|
||||
except Exception as log_error:
|
||||
print(f"Erreur sauvegarde log markdown: {log_error}")
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "ansible_execution",
|
||||
"data": result
|
||||
})
|
||||
|
||||
# Mettre à jour la BD
|
||||
await task_repo.update(
|
||||
db_task,
|
||||
status=task.status,
|
||||
completed_at=task.end_time,
|
||||
error_message=task.error,
|
||||
result_data={"output": result.get("stdout", "")[:5000]}
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
# Notification
|
||||
if result["success"]:
|
||||
await notification_service.notify_task_completed(
|
||||
task_name=task.name,
|
||||
target=request.target,
|
||||
duration=task.duration
|
||||
)
|
||||
else:
|
||||
await notification_service.notify_task_failed(
|
||||
task_name=task.name,
|
||||
target=request.target,
|
||||
error=result.get("stderr", "Erreur inconnue")[:200]
|
||||
)
|
||||
|
||||
result["task_id"] = task_id
|
||||
return result
|
||||
|
||||
except FileNotFoundError as e:
|
||||
task.status = "failed"
|
||||
task.end_time = datetime.now(timezone.utc)
|
||||
task.error = str(e)
|
||||
try:
|
||||
log_path = task_log_service.save_task_log(task=task, error=str(e))
|
||||
created_log = task_log_service.index_log_file(log_path)
|
||||
if created_log:
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_log_created",
|
||||
"data": created_log.dict()
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
await task_repo.update(db_task, status="failed", completed_at=task.end_time, error_message=str(e))
|
||||
await db_session.commit()
|
||||
await notification_service.notify_task_failed(task_name=task.name, target=request.target, error=str(e)[:200])
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
except Exception as e:
|
||||
task.status = "failed"
|
||||
task.end_time = datetime.now(timezone.utc)
|
||||
task.error = str(e)
|
||||
try:
|
||||
log_path = task_log_service.save_task_log(task=task, error=str(e))
|
||||
created_log = task_log_service.index_log_file(log_path)
|
||||
if created_log:
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_log_created",
|
||||
"data": created_log.dict()
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
await task_repo.update(db_task, status="failed", completed_at=task.end_time, error_message=str(e))
|
||||
await db_session.commit()
|
||||
await notification_service.notify_task_failed(task_name=task.name, target=request.target, error=str(e)[:200])
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/adhoc", response_model=AdHocCommandResult)
|
||||
async def execute_adhoc_command(
|
||||
request: AdHocCommandRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Exécute une commande ad-hoc Ansible."""
|
||||
start_time_perf = perf_counter()
|
||||
start_time_dt = datetime.now(timezone.utc)
|
||||
|
||||
# Créer une tâche en BD
|
||||
task_repo = TaskRepository(db_session)
|
||||
task_id = f"adhoc_{uuid.uuid4().hex[:12]}"
|
||||
task_name = f"Ad-hoc: {request.command[:40]}{'...' if len(request.command) > 40 else ''}"
|
||||
|
||||
db_task = await task_repo.create(
|
||||
id=task_id,
|
||||
action=f"adhoc:{request.module}",
|
||||
target=request.target,
|
||||
playbook=None,
|
||||
status="running",
|
||||
)
|
||||
await task_repo.update(db_task, started_at=start_time_dt)
|
||||
await db_session.commit()
|
||||
|
||||
# Créer aussi en mémoire
|
||||
task = Task(
|
||||
id=task_id,
|
||||
name=task_name,
|
||||
host=request.target,
|
||||
status="running",
|
||||
progress=0,
|
||||
start_time=start_time_dt
|
||||
)
|
||||
db.tasks.insert(0, task)
|
||||
|
||||
# Construire la commande ansible
|
||||
ansible_cmd = [
|
||||
"ansible",
|
||||
request.target,
|
||||
"-i", str(settings.ansible_dir / "inventory" / "hosts.yml"),
|
||||
"-m", request.module,
|
||||
"-a", request.command,
|
||||
"--timeout", str(request.timeout),
|
||||
]
|
||||
|
||||
if request.become:
|
||||
ansible_cmd.append("--become")
|
||||
|
||||
private_key = find_ssh_private_key()
|
||||
if private_key:
|
||||
ansible_cmd.extend(["--private-key", private_key])
|
||||
|
||||
if settings.ssh_user:
|
||||
ansible_cmd.extend(["-u", settings.ssh_user])
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
ansible_cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=request.timeout + 10,
|
||||
cwd=str(settings.ansible_dir)
|
||||
)
|
||||
|
||||
duration = perf_counter() - start_time_perf
|
||||
success = result.returncode == 0
|
||||
|
||||
task.status = "completed" if success else "failed"
|
||||
task.progress = 100
|
||||
task.end_time = datetime.now(timezone.utc)
|
||||
task.duration = f"{round(duration, 2)}s"
|
||||
task.output = result.stdout
|
||||
task.error = result.stderr if result.stderr else None
|
||||
|
||||
log_path = task_log_service.save_task_log(task, output=result.stdout, error=result.stderr or "", source_type='adhoc')
|
||||
|
||||
created_log = task_log_service.index_log_file(log_path)
|
||||
if created_log:
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_log_created",
|
||||
"data": created_log.dict()
|
||||
})
|
||||
|
||||
log_entry = LogEntry(
|
||||
id=db.get_next_id("logs"),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
level="INFO" if success else "WARN",
|
||||
message=f"Ad-hoc [{request.module}] sur {request.target}: {request.command[:50]}{'...' if len(request.command) > 50 else ''}",
|
||||
source="ansible-adhoc",
|
||||
host=request.target
|
||||
)
|
||||
db.logs.insert(0, log_entry)
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "adhoc_executed",
|
||||
"data": {
|
||||
"target": request.target,
|
||||
"command": request.command,
|
||||
"success": success,
|
||||
"task_id": task_id
|
||||
}
|
||||
})
|
||||
|
||||
await adhoc_history_service.add_command(
|
||||
command=request.command,
|
||||
target=request.target,
|
||||
module=request.module,
|
||||
become=request.become,
|
||||
category=request.category or "default"
|
||||
)
|
||||
|
||||
await task_repo.update(
|
||||
db_task,
|
||||
status=task.status,
|
||||
completed_at=task.end_time,
|
||||
error_message=task.error,
|
||||
result_data={"output": result.stdout[:5000] if result.stdout else None}
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
if success:
|
||||
await notification_service.notify_task_completed(
|
||||
task_name=task.name,
|
||||
target=request.target,
|
||||
duration=task.duration
|
||||
)
|
||||
else:
|
||||
await notification_service.notify_task_failed(
|
||||
task_name=task.name,
|
||||
target=request.target,
|
||||
error=(result.stderr or "Erreur inconnue")[:200]
|
||||
)
|
||||
|
||||
return AdHocCommandResult(
|
||||
target=request.target,
|
||||
command=request.command,
|
||||
success=success,
|
||||
return_code=result.returncode,
|
||||
stdout=result.stdout,
|
||||
stderr=result.stderr if result.stderr else None,
|
||||
duration=round(duration, 2)
|
||||
)
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
duration = perf_counter() - start_time_perf
|
||||
task.status = "failed"
|
||||
task.progress = 100
|
||||
task.end_time = datetime.now(timezone.utc)
|
||||
task.duration = f"{round(duration, 2)}s"
|
||||
task.error = f"Timeout après {request.timeout} secondes"
|
||||
|
||||
try:
|
||||
log_path = task_log_service.save_task_log(task, error=task.error, source_type='adhoc')
|
||||
created_log = task_log_service.index_log_file(log_path)
|
||||
if created_log:
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_log_created",
|
||||
"data": created_log.dict()
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
await task_repo.update(db_task, status="failed", completed_at=task.end_time, error_message=task.error)
|
||||
await db_session.commit()
|
||||
|
||||
await notification_service.notify_task_failed(task_name=task.name, target=request.target, error=task.error[:200])
|
||||
|
||||
return AdHocCommandResult(
|
||||
target=request.target,
|
||||
command=request.command,
|
||||
success=False,
|
||||
return_code=-1,
|
||||
stdout="",
|
||||
stderr=f"Timeout après {request.timeout} secondes",
|
||||
duration=round(duration, 2)
|
||||
)
|
||||
except FileNotFoundError:
|
||||
duration = perf_counter() - start_time_perf
|
||||
error_msg = "ansible non trouvé. Vérifiez que Ansible est installé."
|
||||
task.status = "failed"
|
||||
task.progress = 100
|
||||
task.end_time = datetime.now(timezone.utc)
|
||||
task.duration = f"{round(duration, 2)}s"
|
||||
task.error = error_msg
|
||||
|
||||
try:
|
||||
log_path = task_log_service.save_task_log(task, error=error_msg, source_type='adhoc')
|
||||
created_log = task_log_service.index_log_file(log_path)
|
||||
if created_log:
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_log_created",
|
||||
"data": created_log.dict()
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
await task_repo.update(db_task, status="failed", completed_at=task.end_time, error_message=error_msg)
|
||||
await db_session.commit()
|
||||
|
||||
await notification_service.notify_task_failed(task_name=task.name, target=request.target, error=error_msg[:200])
|
||||
|
||||
return AdHocCommandResult(
|
||||
target=request.target,
|
||||
command=request.command,
|
||||
success=False,
|
||||
return_code=-1,
|
||||
stdout="",
|
||||
stderr=error_msg,
|
||||
duration=round(duration, 2)
|
||||
)
|
||||
except Exception as e:
|
||||
duration = perf_counter() - start_time_perf
|
||||
error_msg = f"Erreur interne: {str(e)}"
|
||||
task.status = "failed"
|
||||
task.progress = 100
|
||||
task.end_time = datetime.now(timezone.utc)
|
||||
task.duration = f"{round(duration, 2)}s"
|
||||
task.error = error_msg
|
||||
|
||||
try:
|
||||
log_path = task_log_service.save_task_log(task, error=error_msg, source_type='adhoc')
|
||||
created_log = task_log_service.index_log_file(log_path)
|
||||
if created_log:
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_log_created",
|
||||
"data": created_log.dict()
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
await task_repo.update(db_task, status="failed", completed_at=task.end_time, error_message=error_msg)
|
||||
await db_session.commit()
|
||||
|
||||
await notification_service.notify_task_failed(task_name=task.name, target=request.target, error=error_msg[:200])
|
||||
|
||||
return AdHocCommandResult(
|
||||
target=request.target,
|
||||
command=request.command,
|
||||
success=False,
|
||||
return_code=-1,
|
||||
stdout="",
|
||||
stderr=error_msg,
|
||||
duration=round(duration, 2)
|
||||
)
|
||||
@@ -0,0 +1,224 @@
|
||||
"""
|
||||
Routes API pour l'authentification JWT.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.dependencies import get_db, get_current_user, get_current_user_optional
|
||||
from app.crud.user import UserRepository
|
||||
from app.schemas.auth import (
|
||||
LoginRequest, Token, UserOut, UserCreate, PasswordChange
|
||||
)
|
||||
from app.services import auth_service
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def auth_status(
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
current_user: Optional[dict] = Depends(get_current_user_optional)
|
||||
):
|
||||
"""Vérifie le statut d'authentification et si le setup initial est requis."""
|
||||
repo = UserRepository(db_session)
|
||||
users_count = await repo.count()
|
||||
|
||||
if users_count == 0:
|
||||
return {
|
||||
"setup_required": True,
|
||||
"authenticated": False,
|
||||
"user": None
|
||||
}
|
||||
|
||||
if current_user:
|
||||
return {
|
||||
"setup_required": False,
|
||||
"authenticated": True,
|
||||
"user": {
|
||||
"id": current_user.get("user_id"),
|
||||
"username": current_user.get("username"),
|
||||
"role": current_user.get("role"),
|
||||
"display_name": current_user.get("display_name")
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
"setup_required": False,
|
||||
"authenticated": False,
|
||||
"user": None
|
||||
}
|
||||
|
||||
|
||||
@router.post("/setup")
|
||||
async def setup_admin(
|
||||
user_data: UserCreate,
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Crée le premier utilisateur admin (uniquement si aucun utilisateur n'existe)."""
|
||||
repo = UserRepository(db_session)
|
||||
users_count = await repo.count()
|
||||
|
||||
if users_count > 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Le setup a déjà été effectué. Utilisez /login pour vous connecter."
|
||||
)
|
||||
|
||||
# Hasher le mot de passe
|
||||
hashed_password = auth_service.hash_password(user_data.password)
|
||||
|
||||
# Créer l'utilisateur admin
|
||||
user = await repo.create(
|
||||
username=user_data.username,
|
||||
hashed_password=hashed_password,
|
||||
email=user_data.email,
|
||||
display_name=user_data.display_name,
|
||||
role="admin"
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
return {
|
||||
"message": "Compte administrateur créé avec succès",
|
||||
"user": {
|
||||
"id": user.id,
|
||||
"username": user.username,
|
||||
"role": user.role
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
async def login_form(
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Connexion via formulaire OAuth2 (form-urlencoded)."""
|
||||
repo = UserRepository(db_session)
|
||||
user = await repo.get_by_username(form_data.username)
|
||||
|
||||
if not user or not auth_service.verify_password(form_data.password, user.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Nom d'utilisateur ou mot de passe incorrect",
|
||||
headers={"WWW-Authenticate": "Bearer"}
|
||||
)
|
||||
|
||||
if not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Compte désactivé"
|
||||
)
|
||||
|
||||
# Mettre à jour last_login
|
||||
await repo.update(user, last_login=datetime.now(timezone.utc))
|
||||
await db_session.commit()
|
||||
|
||||
# Créer le token
|
||||
token, expires_in = auth_service.create_token_for_user(user)
|
||||
|
||||
return Token(
|
||||
access_token=token,
|
||||
token_type="bearer",
|
||||
expires_in=expires_in
|
||||
)
|
||||
|
||||
|
||||
@router.post("/login/json", response_model=Token)
|
||||
async def login_json(
|
||||
credentials: LoginRequest,
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Connexion via JSON body."""
|
||||
repo = UserRepository(db_session)
|
||||
user = await repo.get_by_username(credentials.username)
|
||||
|
||||
if not user or not auth_service.verify_password(credentials.password, user.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Nom d'utilisateur ou mot de passe incorrect"
|
||||
)
|
||||
|
||||
if not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Compte désactivé"
|
||||
)
|
||||
|
||||
# Mettre à jour last_login
|
||||
await repo.update(user, last_login=datetime.now(timezone.utc))
|
||||
await db_session.commit()
|
||||
|
||||
# Créer le token
|
||||
token, expires_in = auth_service.create_token_for_user(user)
|
||||
|
||||
return Token(
|
||||
access_token=token,
|
||||
token_type="bearer",
|
||||
expires_in=expires_in
|
||||
)
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserOut)
|
||||
async def get_current_user_info(
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Récupère les informations de l'utilisateur connecté."""
|
||||
if not current_user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Non authentifié"
|
||||
)
|
||||
|
||||
repo = UserRepository(db_session)
|
||||
user = await repo.get(current_user.get("user_id"))
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Utilisateur non trouvé"
|
||||
)
|
||||
|
||||
return UserOut.model_validate(user)
|
||||
|
||||
|
||||
@router.put("/password")
|
||||
async def change_password(
|
||||
password_data: PasswordChange,
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Change le mot de passe de l'utilisateur connecté."""
|
||||
if not current_user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Non authentifié"
|
||||
)
|
||||
|
||||
repo = UserRepository(db_session)
|
||||
user = await repo.get(current_user.get("user_id"))
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Utilisateur non trouvé"
|
||||
)
|
||||
|
||||
# Vérifier l'ancien mot de passe
|
||||
if not auth_service.verify_password(password_data.current_password, user.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Mot de passe actuel incorrect"
|
||||
)
|
||||
|
||||
# Hasher et enregistrer le nouveau mot de passe
|
||||
new_hashed = auth_service.hash_password(password_data.new_password)
|
||||
await repo.update(user, hashed_password=new_hashed)
|
||||
await db_session.commit()
|
||||
|
||||
return {"message": "Mot de passe modifié avec succès"}
|
||||
@@ -0,0 +1,182 @@
|
||||
"""
|
||||
Routes API pour le bootstrap des hôtes.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from app.core.dependencies import verify_api_key
|
||||
from app.schemas.ansible import BootstrapRequest
|
||||
from app.schemas.common import CommandResult, LogEntry
|
||||
from app.services import (
|
||||
bootstrap_status_service,
|
||||
ws_manager,
|
||||
notification_service,
|
||||
db,
|
||||
)
|
||||
from app.utils.ssh_utils import bootstrap_host
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
async def get_all_bootstrap_status(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère le statut de bootstrap de tous les hôtes."""
|
||||
return {
|
||||
"hosts": bootstrap_status_service.get_all_status()
|
||||
}
|
||||
|
||||
|
||||
@router.get("/status/{host_name}")
|
||||
async def get_host_bootstrap_status(
|
||||
host_name: str,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Récupère le statut de bootstrap d'un hôte spécifique."""
|
||||
status = bootstrap_status_service.get_bootstrap_status(host_name)
|
||||
return {
|
||||
"host": host_name,
|
||||
**status
|
||||
}
|
||||
|
||||
|
||||
@router.post("/status/{host_name}")
|
||||
async def set_host_bootstrap_status(
|
||||
host_name: str,
|
||||
success: bool = True,
|
||||
details: Optional[str] = None,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Définit manuellement le statut de bootstrap d'un hôte."""
|
||||
result = bootstrap_status_service.set_bootstrap_status(
|
||||
host_name=host_name,
|
||||
success=success,
|
||||
details=details or f"Status défini manuellement"
|
||||
)
|
||||
|
||||
db.invalidate_hosts_cache()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "bootstrap_status_updated",
|
||||
"data": {
|
||||
"host": host_name,
|
||||
"bootstrap_ok": success
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
"host": host_name,
|
||||
"status": "updated",
|
||||
**result
|
||||
}
|
||||
|
||||
|
||||
@router.post("", response_model=CommandResult)
|
||||
async def bootstrap_ansible_host(
|
||||
request: BootstrapRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Bootstrap un hôte pour Ansible.
|
||||
|
||||
Cette opération:
|
||||
1. Se connecte à l'hôte via SSH avec le mot de passe root
|
||||
2. Crée l'utilisateur d'automatisation
|
||||
3. Configure la clé SSH publique
|
||||
4. Configure sudo sans mot de passe
|
||||
5. Installe Python3
|
||||
6. Vérifie la connexion SSH par clé
|
||||
"""
|
||||
import logging
|
||||
import traceback
|
||||
logger = logging.getLogger("bootstrap_endpoint")
|
||||
|
||||
try:
|
||||
logger.info(f"Bootstrap request for host={request.host}, user={request.automation_user}")
|
||||
result = bootstrap_host(
|
||||
host=request.host,
|
||||
root_password=request.root_password,
|
||||
automation_user=request.automation_user
|
||||
)
|
||||
logger.info(f"Bootstrap result: status={result.status}, return_code={result.return_code}")
|
||||
|
||||
if result.return_code != 0:
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail={
|
||||
"status": result.status,
|
||||
"return_code": result.return_code,
|
||||
"stdout": result.stdout,
|
||||
"stderr": result.stderr
|
||||
}
|
||||
)
|
||||
|
||||
# Trouver le nom de l'hôte
|
||||
host_name = request.host
|
||||
for h in db.hosts:
|
||||
if h.ip == request.host or h.name == request.host:
|
||||
host_name = h.name
|
||||
break
|
||||
|
||||
# Enregistrer le statut de bootstrap réussi
|
||||
bootstrap_status_service.set_bootstrap_status(
|
||||
host_name=host_name,
|
||||
success=True,
|
||||
details=f"Bootstrap réussi via API (user: {request.automation_user})"
|
||||
)
|
||||
|
||||
db.invalidate_hosts_cache()
|
||||
|
||||
log_entry = LogEntry(
|
||||
id=db.get_next_id("logs"),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
level="INFO",
|
||||
message=f"Bootstrap réussi pour {host_name} (user: {request.automation_user})",
|
||||
source="bootstrap",
|
||||
host=host_name
|
||||
)
|
||||
db.logs.insert(0, log_entry)
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "bootstrap_success",
|
||||
"data": {
|
||||
"host": host_name,
|
||||
"user": request.automation_user,
|
||||
"status": "ok",
|
||||
"bootstrap_ok": True
|
||||
}
|
||||
})
|
||||
|
||||
asyncio.create_task(notification_service.notify_bootstrap_success(host_name))
|
||||
|
||||
return result
|
||||
|
||||
except HTTPException as http_exc:
|
||||
error_detail = str(http_exc.detail) if http_exc.detail else "Erreur inconnue"
|
||||
asyncio.create_task(notification_service.notify_bootstrap_failed(
|
||||
hostname=request.host,
|
||||
error=error_detail[:200]
|
||||
))
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Bootstrap exception: {e}")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
log_entry = LogEntry(
|
||||
id=db.get_next_id("logs"),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
level="ERROR",
|
||||
message=f"Échec bootstrap pour {request.host}: {str(e)}",
|
||||
source="bootstrap",
|
||||
host=request.host
|
||||
)
|
||||
db.logs.insert(0, log_entry)
|
||||
|
||||
asyncio.create_task(notification_service.notify_bootstrap_failed(
|
||||
hostname=request.host,
|
||||
error=str(e)[:200]
|
||||
))
|
||||
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
@@ -0,0 +1,174 @@
|
||||
"""
|
||||
Routes API pour les builtin playbooks (collecte métriques).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.dependencies import get_db, verify_api_key
|
||||
from app.crud.host import HostRepository
|
||||
from app.crud.host_metrics import HostMetricsRepository
|
||||
from app.services import ansible_service, ws_manager
|
||||
from app.services.builtin_playbooks import (
|
||||
BuiltinPlaybookService,
|
||||
BUILTIN_PLAYBOOKS,
|
||||
get_builtin_playbook_service,
|
||||
init_builtin_playbook_service,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _get_service() -> BuiltinPlaybookService:
|
||||
"""Récupère ou initialise le service builtin playbooks."""
|
||||
try:
|
||||
return get_builtin_playbook_service()
|
||||
except RuntimeError:
|
||||
return init_builtin_playbook_service(settings.ansible_dir, ansible_service)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_builtin_playbooks(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Liste tous les builtin playbooks disponibles."""
|
||||
return [pb.model_dump() for pb in BUILTIN_PLAYBOOKS.values()]
|
||||
|
||||
|
||||
@router.get("/{builtin_id}")
|
||||
async def get_builtin_playbook(
|
||||
builtin_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Récupère les détails d'un builtin playbook."""
|
||||
if builtin_id not in BUILTIN_PLAYBOOKS:
|
||||
raise HTTPException(status_code=404, detail=f"Builtin playbook '{builtin_id}' non trouvé")
|
||||
return BUILTIN_PLAYBOOKS[builtin_id].model_dump()
|
||||
|
||||
|
||||
@router.post("/execute")
|
||||
async def execute_builtin_playbook(
|
||||
builtin_id: str,
|
||||
target: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Exécute un builtin playbook sur une cible."""
|
||||
if builtin_id not in BUILTIN_PLAYBOOKS:
|
||||
raise HTTPException(status_code=404, detail=f"Builtin playbook '{builtin_id}' non trouvé")
|
||||
|
||||
service = _get_service()
|
||||
result = await service.execute_builtin(builtin_id, target)
|
||||
|
||||
# Si collecte de métriques, sauvegarder en BD
|
||||
if BUILTIN_PLAYBOOKS[builtin_id].collect_metrics and result.get("success"):
|
||||
metrics_repo = HostMetricsRepository(db_session)
|
||||
host_repo = HostRepository(db_session)
|
||||
|
||||
for hostname, metrics_data in result.get("parsed_metrics", {}).items():
|
||||
# Trouver l'host_id
|
||||
host = await host_repo.get_by_name(hostname)
|
||||
if host:
|
||||
metrics_create = service.create_metrics_from_parsed(
|
||||
host_id=host.id,
|
||||
parsed_data=metrics_data,
|
||||
builtin_id=builtin_id,
|
||||
execution_time_ms=result.get("execution_time_ms", 0)
|
||||
)
|
||||
await metrics_repo.create(**metrics_create.model_dump())
|
||||
|
||||
await db_session.commit()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "builtin_executed",
|
||||
"data": {
|
||||
"builtin_id": builtin_id,
|
||||
"target": target,
|
||||
"success": result.get("success", False)
|
||||
}
|
||||
})
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/execute-background")
|
||||
async def execute_builtin_playbook_background(
|
||||
builtin_id: str,
|
||||
target: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Exécute un builtin playbook en arrière-plan."""
|
||||
if builtin_id not in BUILTIN_PLAYBOOKS:
|
||||
raise HTTPException(status_code=404, detail=f"Builtin playbook '{builtin_id}' non trouvé")
|
||||
|
||||
async def run_in_background():
|
||||
service = _get_service()
|
||||
result = await service.execute_builtin(builtin_id, target)
|
||||
await ws_manager.broadcast({
|
||||
"type": "builtin_executed",
|
||||
"data": {
|
||||
"builtin_id": builtin_id,
|
||||
"target": target,
|
||||
"success": result.get("success", False)
|
||||
}
|
||||
})
|
||||
|
||||
# Planifier l'exécution en arrière-plan
|
||||
background_tasks.add_task(asyncio.create_task, run_in_background())
|
||||
|
||||
return {
|
||||
"message": f"Builtin playbook '{builtin_id}' planifié pour exécution sur {target}",
|
||||
"builtin_id": builtin_id,
|
||||
"target": target
|
||||
}
|
||||
|
||||
|
||||
@router.post("/collect-all")
|
||||
async def collect_all_metrics(
|
||||
background_tasks: BackgroundTasks,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Collecte les métriques de tous les hôtes."""
|
||||
host_repo = HostRepository(db_session)
|
||||
hosts = await host_repo.list(limit=1000)
|
||||
|
||||
if not hosts:
|
||||
return {"message": "Aucun hôte trouvé", "hosts_count": 0}
|
||||
|
||||
async def collect_for_all():
|
||||
service = _get_service()
|
||||
results = []
|
||||
|
||||
for host in hosts:
|
||||
try:
|
||||
result = await service.execute_builtin("collect_system_info", host.name)
|
||||
results.append({
|
||||
"host": host.name,
|
||||
"success": result.get("success", False)
|
||||
})
|
||||
except Exception as e:
|
||||
results.append({
|
||||
"host": host.name,
|
||||
"success": False,
|
||||
"error": str(e)
|
||||
})
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "metrics_collection_complete",
|
||||
"data": {
|
||||
"total": len(hosts),
|
||||
"success": sum(1 for r in results if r.get("success")),
|
||||
"failed": sum(1 for r in results if not r.get("success"))
|
||||
}
|
||||
})
|
||||
|
||||
background_tasks.add_task(asyncio.create_task, collect_for_all())
|
||||
|
||||
return {
|
||||
"message": f"Collecte des métriques lancée pour {len(hosts)} hôte(s)",
|
||||
"hosts_count": len(hosts)
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
Routes API pour la gestion des groupes Ansible.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from app.core.dependencies import verify_api_key
|
||||
from app.schemas.group import GroupRequest, GroupUpdateRequest, GroupDeleteRequest
|
||||
from app.services import ansible_service
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_groups(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère la liste de tous les groupes Ansible."""
|
||||
groups = ansible_service.get_groups()
|
||||
env_groups = ansible_service.get_env_groups()
|
||||
role_groups = ansible_service.get_role_groups()
|
||||
|
||||
result = []
|
||||
for group in groups:
|
||||
group_type = "env" if group in env_groups else ("role" if group in role_groups else "other")
|
||||
hosts = ansible_service.get_group_hosts(group)
|
||||
result.append({
|
||||
"name": group,
|
||||
"type": group_type,
|
||||
"display_name": group.replace("env_", "").replace("role_", "").replace("_", " ").title(),
|
||||
"hosts_count": len(hosts),
|
||||
"hosts": hosts,
|
||||
})
|
||||
|
||||
return {
|
||||
"groups": result,
|
||||
"env_count": len(env_groups),
|
||||
"role_count": len(role_groups),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{group_name}")
|
||||
async def get_group(group_name: str, api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère les détails d'un groupe."""
|
||||
if not ansible_service.group_exists(group_name):
|
||||
raise HTTPException(status_code=404, detail=f"Groupe '{group_name}' non trouvé")
|
||||
|
||||
env_groups = ansible_service.get_env_groups()
|
||||
role_groups = ansible_service.get_role_groups()
|
||||
group_type = "env" if group_name in env_groups else ("role" if group_name in role_groups else "other")
|
||||
hosts = ansible_service.get_group_hosts(group_name)
|
||||
|
||||
return {
|
||||
"name": group_name,
|
||||
"type": group_type,
|
||||
"display_name": group_name.replace("env_", "").replace("role_", "").replace("_", " ").title(),
|
||||
"hosts_count": len(hosts),
|
||||
"hosts": hosts,
|
||||
}
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_group(request: GroupRequest, api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Crée un nouveau groupe."""
|
||||
# Valider le préfixe selon le type
|
||||
expected_prefix = f"{request.type}_"
|
||||
if not request.name.startswith(expected_prefix):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Le nom du groupe de type '{request.type}' doit commencer par '{expected_prefix}'"
|
||||
)
|
||||
|
||||
# Vérifier si le groupe existe déjà
|
||||
if ansible_service.group_exists(request.name):
|
||||
raise HTTPException(status_code=400, detail=f"Le groupe '{request.name}' existe déjà")
|
||||
|
||||
try:
|
||||
ansible_service.add_group(request.name, request.type)
|
||||
return {
|
||||
"message": f"Groupe '{request.name}' créé avec succès",
|
||||
"group": {
|
||||
"name": request.name,
|
||||
"type": request.type,
|
||||
"hosts_count": 0,
|
||||
}
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Erreur lors de la création du groupe: {str(e)}")
|
||||
|
||||
|
||||
@router.put("/{group_name}")
|
||||
async def update_group(
|
||||
group_name: str,
|
||||
request: GroupUpdateRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Renomme un groupe."""
|
||||
if not ansible_service.group_exists(group_name):
|
||||
raise HTTPException(status_code=404, detail=f"Groupe '{group_name}' non trouvé")
|
||||
|
||||
# Vérifier que le nouveau nom a le même préfixe
|
||||
old_prefix = group_name.split("_")[0] + "_" if "_" in group_name else ""
|
||||
new_prefix = request.new_name.split("_")[0] + "_" if "_" in request.new_name else ""
|
||||
|
||||
if old_prefix and old_prefix != new_prefix:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Le nouveau nom doit conserver le même préfixe '{old_prefix}'"
|
||||
)
|
||||
|
||||
# Vérifier si le nouveau nom existe déjà
|
||||
if ansible_service.group_exists(request.new_name):
|
||||
raise HTTPException(status_code=400, detail=f"Le groupe '{request.new_name}' existe déjà")
|
||||
|
||||
try:
|
||||
ansible_service.rename_group(group_name, request.new_name)
|
||||
return {
|
||||
"message": f"Groupe renommé de '{group_name}' vers '{request.new_name}'",
|
||||
"old_name": group_name,
|
||||
"new_name": request.new_name,
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Erreur lors du renommage: {str(e)}")
|
||||
|
||||
|
||||
@router.delete("/{group_name}")
|
||||
async def delete_group(
|
||||
group_name: str,
|
||||
move_hosts_to: str = None,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Supprime un groupe."""
|
||||
if not ansible_service.group_exists(group_name):
|
||||
raise HTTPException(status_code=404, detail=f"Groupe '{group_name}' non trouvé")
|
||||
|
||||
# Vérifier le groupe de destination si spécifié
|
||||
if move_hosts_to and not ansible_service.group_exists(move_hosts_to):
|
||||
raise HTTPException(status_code=400, detail=f"Groupe de destination '{move_hosts_to}' non trouvé")
|
||||
|
||||
hosts = ansible_service.get_group_hosts(group_name)
|
||||
|
||||
try:
|
||||
ansible_service.delete_group(group_name, move_hosts_to)
|
||||
return {
|
||||
"message": f"Groupe '{group_name}' supprimé",
|
||||
"hosts_moved": len(hosts) if move_hosts_to else 0,
|
||||
"moved_to": move_hosts_to,
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Erreur lors de la suppression: {str(e)}")
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
Routes API pour les health checks.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from app.core.dependencies import verify_api_key
|
||||
from app.schemas.health import HealthCheck
|
||||
from app.schemas.common import LogEntry, SystemMetrics
|
||||
from app.services import ws_manager, db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("", response_model=SystemMetrics)
|
||||
async def get_metrics(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère les métriques système."""
|
||||
return db.metrics
|
||||
|
||||
|
||||
@router.get("/global")
|
||||
async def global_health_check():
|
||||
"""Endpoint de healthcheck global utilisé par Docker.
|
||||
|
||||
Ne nécessite pas de clé API pour permettre aux orchestrateurs
|
||||
de vérifier l'état du service facilement.
|
||||
"""
|
||||
return {
|
||||
"status": "ok",
|
||||
"service": "homelab-automation-api",
|
||||
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{host_name}", response_model=HealthCheck)
|
||||
async def check_host_health(host_name: str, api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Effectue un health check sur un hôte spécifique."""
|
||||
host = next((h for h in db.hosts if h.name == host_name), None)
|
||||
if not host:
|
||||
raise HTTPException(status_code=404, detail="Hôte non trouvé")
|
||||
|
||||
# Simuler un health check
|
||||
health_check = HealthCheck(
|
||||
host=host_name,
|
||||
ssh_ok=host.status == "online",
|
||||
ansible_ok=host.status == "online",
|
||||
sudo_ok=host.status == "online",
|
||||
reachable=host.status != "offline",
|
||||
response_time=0.123 if host.status == "online" else None,
|
||||
error_message=None if host.status != "offline" else "Hôte injoignable"
|
||||
)
|
||||
|
||||
# Mettre à jour le statut runtime
|
||||
new_status = "online" if health_check.reachable else "offline"
|
||||
db.update_host_status(host_name, new_status, host.os)
|
||||
|
||||
log_entry = LogEntry(
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
level="INFO" if health_check.reachable else "ERROR",
|
||||
message=f"Health check {'réussi' if health_check.reachable else 'échoué'} pour {host_name}",
|
||||
source="health_check",
|
||||
host=host_name
|
||||
)
|
||||
|
||||
db.logs.insert(0, log_entry)
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "health_check",
|
||||
"data": health_check.dict()
|
||||
})
|
||||
|
||||
return health_check
|
||||
|
||||
|
||||
@router.post("/refresh")
|
||||
async def refresh_hosts(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Force le rechargement des hôtes depuis l'inventaire Ansible."""
|
||||
from app.services import ansible_service
|
||||
|
||||
ansible_service.invalidate_cache()
|
||||
hosts = db.refresh_hosts()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "hosts_refreshed",
|
||||
"data": {"count": len(hosts)}
|
||||
})
|
||||
|
||||
return {"message": f"{len(hosts)} hôtes rechargés depuis l'inventaire Ansible"}
|
||||
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
Routes API pour l'aide et la documentation.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.responses import Response
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.dependencies import verify_api_key
|
||||
from app.utils.markdown_parser import build_help_markdown
|
||||
from app.utils.pdf_generator import markdown_to_pdf_bytes
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/documentation.md")
|
||||
async def download_help_markdown(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Télécharge la documentation d'aide en format Markdown."""
|
||||
# Essayer de charger depuis index.html
|
||||
html_path = settings.base_dir / "index.html"
|
||||
markdown_content = build_help_markdown(html_path=html_path)
|
||||
|
||||
return Response(
|
||||
content=markdown_content,
|
||||
media_type="text/markdown",
|
||||
headers={
|
||||
"Content-Disposition": "attachment; filename=homelab-automation-help.md"
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@router.get("/documentation.pdf")
|
||||
async def download_help_pdf(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Télécharge la documentation d'aide en format PDF."""
|
||||
# Essayer de charger depuis index.html
|
||||
html_path = settings.base_dir / "index.html"
|
||||
markdown_content = build_help_markdown(html_path=html_path)
|
||||
|
||||
pdf_bytes = markdown_to_pdf_bytes(
|
||||
markdown_content,
|
||||
title="Homelab Automation - Documentation"
|
||||
)
|
||||
|
||||
return Response(
|
||||
content=pdf_bytes,
|
||||
media_type="application/pdf",
|
||||
headers={
|
||||
"Content-Disposition": "attachment; filename=homelab-automation-help.pdf"
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,399 @@
|
||||
"""
|
||||
Routes API pour la gestion des hôtes.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.dependencies import get_db, verify_api_key
|
||||
from app.crud.host import HostRepository
|
||||
from app.crud.bootstrap_status import BootstrapStatusRepository
|
||||
from app.schemas.host_api import HostRequest, HostUpdateRequest, HostResponse
|
||||
from app.services import ansible_service, ws_manager
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _host_to_response(host, bootstrap=None) -> dict:
|
||||
"""Convertit un modèle Host DB en réponse API."""
|
||||
return {
|
||||
"id": host.id,
|
||||
"name": host.name,
|
||||
"ip": host.ip_address,
|
||||
"status": host.status or "unknown",
|
||||
"os": "Linux",
|
||||
"last_seen": host.last_seen,
|
||||
"created_at": host.created_at,
|
||||
"groups": [host.ansible_group] if host.ansible_group else [],
|
||||
"bootstrap_ok": bootstrap.status == "success" if bootstrap else False,
|
||||
"bootstrap_date": bootstrap.last_attempt if bootstrap else None,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/groups")
|
||||
async def get_host_groups(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère la liste des groupes disponibles pour les hôtes."""
|
||||
return {
|
||||
"env_groups": ansible_service.get_env_groups(),
|
||||
"role_groups": ansible_service.get_role_groups(),
|
||||
"all_groups": ansible_service.get_groups(),
|
||||
}
|
||||
|
||||
|
||||
@router.get("/by-name/{host_name}")
|
||||
async def get_host_by_name(
|
||||
host_name: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Récupère un hôte par son nom."""
|
||||
repo = HostRepository(db_session)
|
||||
bs_repo = BootstrapStatusRepository(db_session)
|
||||
|
||||
host = await repo.get_by_name(host_name)
|
||||
if not host:
|
||||
host = await repo.get_by_ip(host_name)
|
||||
|
||||
if not host:
|
||||
raise HTTPException(status_code=404, detail=f"Hôte '{host_name}' non trouvé")
|
||||
|
||||
bootstrap = await bs_repo.latest_for_host(host.id)
|
||||
return _host_to_response(host, bootstrap)
|
||||
|
||||
|
||||
@router.post("/refresh")
|
||||
async def refresh_hosts(
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Force le rechargement des hôtes depuis l'inventaire Ansible."""
|
||||
ansible_service.invalidate_cache()
|
||||
hosts = ansible_service.get_hosts_from_inventory()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "hosts_refreshed",
|
||||
"data": {"count": len(hosts)}
|
||||
})
|
||||
|
||||
return {
|
||||
"message": f"{len(hosts)} hôtes rechargés depuis l'inventaire Ansible",
|
||||
"count": len(hosts)
|
||||
}
|
||||
|
||||
|
||||
@router.post("/sync")
|
||||
async def sync_hosts_from_ansible(
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Synchronise les hôtes depuis l'inventaire Ansible vers la base de données."""
|
||||
repo = HostRepository(db_session)
|
||||
|
||||
ansible_service.invalidate_cache()
|
||||
inventory_hosts = ansible_service.get_hosts_from_inventory()
|
||||
|
||||
created_count = 0
|
||||
updated_count = 0
|
||||
|
||||
for inv_host in inventory_hosts:
|
||||
existing = await repo.get_by_name(inv_host.name)
|
||||
|
||||
if existing:
|
||||
await repo.update(
|
||||
existing,
|
||||
ip_address=inv_host.ansible_host or inv_host.name,
|
||||
ansible_group=inv_host.groups[0] if inv_host.groups else None,
|
||||
)
|
||||
updated_count += 1
|
||||
else:
|
||||
await repo.create(
|
||||
id=uuid.uuid4().hex,
|
||||
name=inv_host.name,
|
||||
ip_address=inv_host.ansible_host or inv_host.name,
|
||||
ansible_group=inv_host.groups[0] if inv_host.groups else None,
|
||||
status="unknown",
|
||||
reachable=False,
|
||||
)
|
||||
created_count += 1
|
||||
|
||||
await db_session.commit()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "hosts_synced",
|
||||
"data": {
|
||||
"created": created_count,
|
||||
"updated": updated_count,
|
||||
"total": len(inventory_hosts)
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
"message": f"Synchronisation terminée: {created_count} créé(s), {updated_count} mis à jour",
|
||||
"created": created_count,
|
||||
"updated": updated_count,
|
||||
"total": len(inventory_hosts)
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{host_id}")
|
||||
async def get_host(
|
||||
host_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Récupère un hôte par son ID."""
|
||||
repo = HostRepository(db_session)
|
||||
bs_repo = BootstrapStatusRepository(db_session)
|
||||
|
||||
host = await repo.get(host_id)
|
||||
if not host:
|
||||
raise HTTPException(status_code=404, detail="Hôte non trouvé")
|
||||
|
||||
bootstrap = await bs_repo.latest_for_host(host.id)
|
||||
return _host_to_response(host, bootstrap)
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_hosts(
|
||||
bootstrap_status: Optional[str] = None,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Récupère la liste des hôtes."""
|
||||
from app.services import db
|
||||
|
||||
repo = HostRepository(db_session)
|
||||
bs_repo = BootstrapStatusRepository(db_session)
|
||||
|
||||
hosts = await repo.list(limit=limit, offset=offset)
|
||||
|
||||
# Si la base ne contient aucun hôte, fallback sur les données de l'inventaire Ansible
|
||||
if not hosts:
|
||||
hybrid_hosts = db.hosts
|
||||
fallback_results = []
|
||||
for h in hybrid_hosts:
|
||||
# Appliquer les filtres de bootstrap
|
||||
if bootstrap_status == "ready" and not h.bootstrap_ok:
|
||||
continue
|
||||
if bootstrap_status == "not_configured" and h.bootstrap_ok:
|
||||
continue
|
||||
|
||||
fallback_results.append({
|
||||
"id": h.id,
|
||||
"name": h.name,
|
||||
"ip": h.ip,
|
||||
"status": h.status,
|
||||
"os": h.os,
|
||||
"last_seen": h.last_seen,
|
||||
"created_at": h.created_at,
|
||||
"groups": h.groups,
|
||||
"bootstrap_ok": h.bootstrap_ok,
|
||||
"bootstrap_date": h.bootstrap_date,
|
||||
})
|
||||
return fallback_results
|
||||
|
||||
result = []
|
||||
for host in hosts:
|
||||
bootstrap = await bs_repo.latest_for_host(host.id)
|
||||
# Appliquer les filtres de bootstrap
|
||||
if bootstrap_status == "ready" and not (bootstrap and bootstrap.status == "success"):
|
||||
continue
|
||||
if bootstrap_status == "not_configured" and bootstrap and bootstrap.status == "success":
|
||||
continue
|
||||
result.append(_host_to_response(host, bootstrap))
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_host(
|
||||
host_request: HostRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Crée un nouvel hôte."""
|
||||
repo = HostRepository(db_session)
|
||||
bs_repo = BootstrapStatusRepository(db_session)
|
||||
|
||||
# Vérifier si l'hôte existe déjà
|
||||
existing = await repo.get_by_name(host_request.name)
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail=f"L'hôte '{host_request.name}' existe déjà")
|
||||
|
||||
# Valider le groupe d'environnement
|
||||
env_groups = ansible_service.get_env_groups()
|
||||
if host_request.env_group not in env_groups and not host_request.env_group.startswith("env_"):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Le groupe d'environnement doit commencer par 'env_'. Groupes existants: {env_groups}"
|
||||
)
|
||||
|
||||
# Valider les groupes de rôles
|
||||
role_groups = ansible_service.get_role_groups()
|
||||
for role in host_request.role_groups:
|
||||
if role not in role_groups and not role.startswith("role_"):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Le groupe de rôle '{role}' doit commencer par 'role_'."
|
||||
)
|
||||
|
||||
try:
|
||||
# Ajouter l'hôte à l'inventaire Ansible
|
||||
ansible_service.add_host_to_inventory(
|
||||
hostname=host_request.name,
|
||||
env_group=host_request.env_group,
|
||||
role_groups=host_request.role_groups,
|
||||
ansible_host=host_request.ip,
|
||||
)
|
||||
|
||||
# Créer en base
|
||||
host = await repo.create(
|
||||
id=uuid.uuid4().hex,
|
||||
name=host_request.name,
|
||||
ip_address=host_request.ip or host_request.name,
|
||||
ansible_group=host_request.env_group,
|
||||
status="unknown",
|
||||
reachable=False,
|
||||
last_seen=None,
|
||||
)
|
||||
bootstrap = await bs_repo.latest_for_host(host.id)
|
||||
await db_session.commit()
|
||||
|
||||
# Notifier les clients WebSocket
|
||||
await ws_manager.broadcast({
|
||||
"type": "host_created",
|
||||
"data": _host_to_response(host, bootstrap),
|
||||
})
|
||||
|
||||
return {
|
||||
"message": f"Hôte '{host_request.name}' ajouté avec succès",
|
||||
"host": _host_to_response(host, bootstrap),
|
||||
"inventory_updated": True,
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
await db_session.rollback()
|
||||
raise HTTPException(status_code=500, detail=f"Erreur lors de l'ajout de l'hôte: {str(e)}")
|
||||
|
||||
|
||||
@router.put("/{host_name}")
|
||||
async def update_host(
|
||||
host_name: str,
|
||||
update_request: HostUpdateRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Met à jour un hôte existant."""
|
||||
repo = HostRepository(db_session)
|
||||
bs_repo = BootstrapStatusRepository(db_session)
|
||||
|
||||
host = await repo.get_by_name(host_name)
|
||||
if not host:
|
||||
host = await repo.get(host_name)
|
||||
if not host:
|
||||
raise HTTPException(status_code=404, detail=f"Hôte '{host_name}' non trouvé")
|
||||
|
||||
# Valider le groupe d'environnement si fourni
|
||||
if update_request.env_group:
|
||||
env_groups = ansible_service.get_env_groups()
|
||||
if update_request.env_group not in env_groups and not update_request.env_group.startswith("env_"):
|
||||
raise HTTPException(status_code=400, detail="Le groupe d'environnement doit commencer par 'env_'")
|
||||
|
||||
# Valider les groupes de rôles si fournis
|
||||
if update_request.role_groups:
|
||||
for role in update_request.role_groups:
|
||||
if not role.startswith("role_"):
|
||||
raise HTTPException(status_code=400, detail=f"Le groupe de rôle '{role}' doit commencer par 'role_'")
|
||||
|
||||
try:
|
||||
ansible_service.update_host_groups(
|
||||
hostname=host_name,
|
||||
env_group=update_request.env_group,
|
||||
role_groups=update_request.role_groups,
|
||||
ansible_host=update_request.ansible_host,
|
||||
)
|
||||
|
||||
await repo.update(
|
||||
host,
|
||||
ansible_group=update_request.env_group or host.ansible_group,
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
bootstrap = await bs_repo.latest_for_host(host.id)
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "host_updated",
|
||||
"data": _host_to_response(host, bootstrap),
|
||||
})
|
||||
|
||||
return {
|
||||
"message": f"Hôte '{host_name}' mis à jour avec succès",
|
||||
"host": _host_to_response(host, bootstrap),
|
||||
"inventory_updated": True,
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
await db_session.rollback()
|
||||
raise
|
||||
except Exception as e:
|
||||
await db_session.rollback()
|
||||
raise HTTPException(status_code=500, detail=f"Erreur lors de la mise à jour: {str(e)}")
|
||||
|
||||
|
||||
@router.delete("/by-name/{host_name}")
|
||||
async def delete_host_by_name(
|
||||
host_name: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Supprime un hôte par son nom."""
|
||||
repo = HostRepository(db_session)
|
||||
|
||||
host = await repo.get_by_name(host_name)
|
||||
if not host:
|
||||
host = await repo.get(host_name)
|
||||
if not host:
|
||||
raise HTTPException(status_code=404, detail=f"Hôte '{host_name}' non trouvé")
|
||||
|
||||
try:
|
||||
ansible_service.remove_host_from_inventory(host_name)
|
||||
await repo.soft_delete(host.id)
|
||||
await db_session.commit()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "host_deleted",
|
||||
"data": {"name": host_name},
|
||||
})
|
||||
|
||||
return {"message": f"Hôte '{host_name}' supprimé avec succès", "inventory_updated": True}
|
||||
except HTTPException:
|
||||
await db_session.rollback()
|
||||
raise
|
||||
except Exception as e:
|
||||
await db_session.rollback()
|
||||
raise HTTPException(status_code=500, detail=f"Erreur lors de la suppression: {str(e)}")
|
||||
|
||||
|
||||
@router.delete("/{host_id}")
|
||||
async def delete_host(
|
||||
host_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Supprime un hôte par son ID."""
|
||||
repo = HostRepository(db_session)
|
||||
host = await repo.get(host_id)
|
||||
if not host:
|
||||
raise HTTPException(status_code=404, detail="Hôte non trouvé")
|
||||
|
||||
return await delete_host_by_name(host.name, api_key_valid, db_session)
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
Routes API pour la gestion des logs.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import delete
|
||||
|
||||
from app.core.dependencies import get_db, verify_api_key
|
||||
from app.crud.log import LogRepository
|
||||
from app.services import ws_manager
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_logs(
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
level: Optional[str] = None,
|
||||
source: Optional[str] = None,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Récupère les logs récents avec filtrage optionnel."""
|
||||
repo = LogRepository(db_session)
|
||||
logs = await repo.list(limit=limit, offset=offset, level=level, source=source)
|
||||
return [
|
||||
{
|
||||
"id": log.id,
|
||||
"timestamp": log.created_at,
|
||||
"level": log.level,
|
||||
"message": log.message,
|
||||
"source": log.source,
|
||||
"host": log.host_id,
|
||||
}
|
||||
for log in logs
|
||||
]
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_log(
|
||||
level: str,
|
||||
message: str,
|
||||
source: Optional[str] = None,
|
||||
host_id: Optional[str] = None,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Ajoute une nouvelle entrée de log."""
|
||||
repo = LogRepository(db_session)
|
||||
log = await repo.create(
|
||||
level=level.upper(),
|
||||
message=message,
|
||||
source=source,
|
||||
host_id=host_id,
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
response_data = {
|
||||
"id": log.id,
|
||||
"timestamp": log.created_at,
|
||||
"level": log.level,
|
||||
"message": log.message,
|
||||
"source": log.source,
|
||||
"host": log.host_id,
|
||||
}
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "new_log",
|
||||
"data": response_data
|
||||
})
|
||||
|
||||
return response_data
|
||||
|
||||
|
||||
@router.delete("")
|
||||
async def clear_logs(
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Efface tous les logs (attention: opération destructive)."""
|
||||
from app.models.log import Log as LogModel
|
||||
await db_session.execute(delete(LogModel))
|
||||
await db_session.commit()
|
||||
return {"message": "Tous les logs ont été supprimés"}
|
||||
@@ -0,0 +1,143 @@
|
||||
"""
|
||||
Routes API pour les métriques système et des hôtes.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.dependencies import get_db, verify_api_key
|
||||
|
||||
|
||||
from app.crud.host_metrics import HostMetricsRepository
|
||||
from app.crud.app_setting import AppSettingRepository
|
||||
from app.services import db
|
||||
|
||||
|
||||
class CollectionScheduleRequest(BaseModel):
|
||||
interval: str = "off"
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_metrics(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère les métriques système globales."""
|
||||
return db.metrics
|
||||
|
||||
|
||||
@router.get("/all-hosts")
|
||||
async def get_all_hosts_metrics(
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Récupère les métriques de tous les hôtes."""
|
||||
try:
|
||||
repo = HostMetricsRepository(db_session)
|
||||
metrics_dict = await repo.get_all_latest()
|
||||
|
||||
# Convertir en dict host_id -> metrics
|
||||
result = {}
|
||||
for host_id, m in metrics_dict.items():
|
||||
result[m.host_id] = {
|
||||
"host_id": m.host_id,
|
||||
"metric_type": m.metric_type,
|
||||
"cpu_usage_percent": m.cpu_usage_percent,
|
||||
"cpu_load_1m": m.cpu_load_1m,
|
||||
"cpu_model": m.cpu_model,
|
||||
"cpu_count": m.cpu_count,
|
||||
"memory_usage_percent": m.memory_usage_percent,
|
||||
"memory_total_mb": m.memory_total_mb,
|
||||
"memory_used_mb": m.memory_used_mb,
|
||||
"disk_root_usage_percent": m.disk_root_usage_percent,
|
||||
"disk_root_total_gb": m.disk_root_total_gb,
|
||||
"disk_root_used_gb": m.disk_root_used_gb,
|
||||
"os_name": m.os_name,
|
||||
"uptime_human": m.uptime_human,
|
||||
"collected_at": m.collected_at,
|
||||
"collection_status": "success" if not m.error_message else "failed",
|
||||
"error_message": m.error_message,
|
||||
}
|
||||
return result
|
||||
except Exception as e:
|
||||
# Si la table n'existe pas encore ou autre erreur
|
||||
return {}
|
||||
|
||||
|
||||
@router.get("/collection-schedule")
|
||||
async def get_collection_schedule(
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Récupère l'intervalle de collecte des métriques."""
|
||||
try:
|
||||
repo = AppSettingRepository(db_session)
|
||||
setting = await repo.get("metrics_collection_interval")
|
||||
interval = setting.value if setting else "off"
|
||||
return {"interval": interval}
|
||||
except Exception:
|
||||
return {"interval": "off"}
|
||||
|
||||
|
||||
@router.post("/collection-schedule")
|
||||
async def set_collection_schedule(
|
||||
request: CollectionScheduleRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Définit l'intervalle de collecte des métriques."""
|
||||
interval = request.interval
|
||||
valid_intervals = ["off", "5min", "15min", "30min", "1h", "6h", "12h", "24h"]
|
||||
if interval not in valid_intervals:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Intervalle invalide. Valeurs acceptées: {valid_intervals}"
|
||||
)
|
||||
|
||||
try:
|
||||
repo = AppSettingRepository(db_session)
|
||||
await repo.set("metrics_collection_interval", interval)
|
||||
await db_session.commit()
|
||||
return {"interval": interval, "message": f"Intervalle de collecte défini à {interval}"}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/{host_id}")
|
||||
async def get_host_metrics(
|
||||
host_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""Récupère les métriques d'un hôte spécifique."""
|
||||
try:
|
||||
repo = HostMetricsRepository(db_session)
|
||||
metrics = await repo.get_latest_for_host(host_id)
|
||||
|
||||
if not metrics:
|
||||
return {"host_id": host_id, "collection_status": "no_data"}
|
||||
|
||||
return {
|
||||
"host_id": metrics.host_id,
|
||||
"metric_type": metrics.metric_type,
|
||||
"cpu_usage_percent": metrics.cpu_usage_percent,
|
||||
"cpu_load_1m": metrics.cpu_load_1m,
|
||||
"cpu_model": metrics.cpu_model,
|
||||
"cpu_count": metrics.cpu_count,
|
||||
"memory_usage_percent": metrics.memory_usage_percent,
|
||||
"memory_total_mb": metrics.memory_total_mb,
|
||||
"memory_used_mb": metrics.memory_used_mb,
|
||||
"disk_root_usage_percent": metrics.disk_root_usage_percent,
|
||||
"disk_root_total_gb": metrics.disk_root_total_gb,
|
||||
"disk_root_used_gb": metrics.disk_root_used_gb,
|
||||
"disk_info": metrics.disk_info,
|
||||
"os_name": metrics.os_name,
|
||||
"uptime_human": metrics.uptime_human,
|
||||
"collected_at": metrics.collected_at,
|
||||
"collection_status": "success" if not metrics.error_message else "failed",
|
||||
"error_message": metrics.error_message,
|
||||
}
|
||||
except Exception as e:
|
||||
return {"host_id": host_id, "collection_status": "error", "error_message": str(e)}
|
||||
@@ -0,0 +1,81 @@
|
||||
"""
|
||||
Routes API pour les notifications ntfy.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from app.core.dependencies import verify_api_key
|
||||
from app.schemas.notification import NotificationRequest, NotificationResponse, NtfyConfig
|
||||
from app.services import notification_service
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/config")
|
||||
async def get_notification_config(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère la configuration actuelle des notifications ntfy."""
|
||||
config = notification_service.config
|
||||
return {
|
||||
"enabled": config.enabled,
|
||||
"base_url": config.base_url,
|
||||
"default_topic": config.default_topic,
|
||||
"timeout": config.timeout,
|
||||
"has_auth": config.has_auth,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/test")
|
||||
async def test_notification(
|
||||
topic: Optional[str] = None,
|
||||
message: str = "🧪 Test de notification depuis Homelab Automation API",
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Envoie une notification de test."""
|
||||
success = await notification_service.send(
|
||||
topic=topic,
|
||||
message=message,
|
||||
title="🔔 Test Notification",
|
||||
priority=3,
|
||||
tags=["test_tube", "robot"]
|
||||
)
|
||||
|
||||
return {
|
||||
"success": success,
|
||||
"topic": topic or notification_service.config.default_topic,
|
||||
"message": "Notification envoyée" if success else "Échec de l'envoi (voir logs serveur)"
|
||||
}
|
||||
|
||||
|
||||
@router.post("/send", response_model=NotificationResponse)
|
||||
async def send_custom_notification(
|
||||
request: NotificationRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Envoie une notification personnalisée via ntfy."""
|
||||
return await notification_service.send_request(request)
|
||||
|
||||
|
||||
@router.post("/toggle")
|
||||
async def toggle_notifications(
|
||||
enabled: bool,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Active ou désactive les notifications ntfy."""
|
||||
current_config = notification_service.config
|
||||
new_config = NtfyConfig(
|
||||
base_url=current_config.base_url,
|
||||
default_topic=current_config.default_topic,
|
||||
enabled=enabled,
|
||||
timeout=current_config.timeout,
|
||||
username=current_config.username,
|
||||
password=current_config.password,
|
||||
token=current_config.token,
|
||||
)
|
||||
notification_service.reconfigure(new_config)
|
||||
|
||||
return {
|
||||
"enabled": enabled,
|
||||
"message": f"Notifications {'activées' if enabled else 'désactivées'}"
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
"""
|
||||
Routes API pour la gestion des playbooks.
|
||||
"""
|
||||
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import yaml
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from app.core.dependencies import verify_api_key
|
||||
from app.schemas.ansible import PlaybookContentRequest
|
||||
from app.schemas.common import LogEntry
|
||||
from app.services import ansible_service, db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/{filename}/content")
|
||||
async def get_playbook_content(
|
||||
filename: str,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Récupère le contenu d'un playbook."""
|
||||
playbook_path = ansible_service.playbooks_dir / filename
|
||||
|
||||
if not filename.endswith(('.yml', '.yaml')):
|
||||
raise HTTPException(status_code=400, detail="Extension de fichier invalide. Utilisez .yml ou .yaml")
|
||||
|
||||
if not playbook_path.exists():
|
||||
raise HTTPException(status_code=404, detail=f"Playbook non trouvé: {filename}")
|
||||
|
||||
# Vérifier que le fichier est bien dans le répertoire playbooks (sécurité)
|
||||
try:
|
||||
playbook_path.resolve().relative_to(ansible_service.playbooks_dir.resolve())
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=403, detail="Accès non autorisé")
|
||||
|
||||
try:
|
||||
content = playbook_path.read_text(encoding='utf-8')
|
||||
stat = playbook_path.stat()
|
||||
return {
|
||||
"filename": filename,
|
||||
"content": content,
|
||||
"size": stat.st_size,
|
||||
"modified": datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat()
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Erreur lecture fichier: {str(e)}")
|
||||
|
||||
|
||||
@router.put("/{filename}/content")
|
||||
async def save_playbook_content(
|
||||
filename: str,
|
||||
request: PlaybookContentRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Sauvegarde le contenu d'un playbook."""
|
||||
if not filename.endswith(('.yml', '.yaml')):
|
||||
raise HTTPException(status_code=400, detail="Extension de fichier invalide. Utilisez .yml ou .yaml")
|
||||
|
||||
# Valider le nom de fichier (sécurité)
|
||||
if not re.match(r'^[a-zA-Z0-9_-]+\.(yml|yaml)$', filename):
|
||||
raise HTTPException(status_code=400, detail="Nom de fichier invalide")
|
||||
|
||||
playbook_path = ansible_service.playbooks_dir / filename
|
||||
|
||||
# S'assurer que le répertoire existe
|
||||
ansible_service.playbooks_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Valider le contenu YAML
|
||||
try:
|
||||
parsed = yaml.safe_load(request.content)
|
||||
if parsed is None:
|
||||
raise HTTPException(status_code=400, detail="Contenu YAML vide ou invalide")
|
||||
except yaml.YAMLError as e:
|
||||
raise HTTPException(status_code=400, detail=f"Erreur de syntaxe YAML: {str(e)}")
|
||||
|
||||
is_new = not playbook_path.exists()
|
||||
|
||||
try:
|
||||
playbook_path.write_text(request.content, encoding='utf-8')
|
||||
stat = playbook_path.stat()
|
||||
|
||||
# Log l'action
|
||||
action = "créé" if is_new else "modifié"
|
||||
log_entry = LogEntry(
|
||||
id=db.get_next_id("logs"),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
level="INFO",
|
||||
message=f"Playbook {filename} {action}",
|
||||
source="playbook_editor"
|
||||
)
|
||||
db.logs.insert(0, log_entry)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Playbook {filename} {'créé' if is_new else 'sauvegardé'} avec succès",
|
||||
"filename": filename,
|
||||
"size": stat.st_size,
|
||||
"modified": datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat(),
|
||||
"is_new": is_new
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Erreur sauvegarde fichier: {str(e)}")
|
||||
|
||||
|
||||
@router.delete("/{filename}")
|
||||
async def delete_playbook(
|
||||
filename: str,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Supprime un playbook."""
|
||||
if not filename.endswith(('.yml', '.yaml')):
|
||||
raise HTTPException(status_code=400, detail="Extension de fichier invalide")
|
||||
|
||||
playbook_path = ansible_service.playbooks_dir / filename
|
||||
|
||||
if not playbook_path.exists():
|
||||
raise HTTPException(status_code=404, detail=f"Playbook non trouvé: {filename}")
|
||||
|
||||
# Vérifier que le fichier est bien dans le répertoire playbooks (sécurité)
|
||||
try:
|
||||
playbook_path.resolve().relative_to(ansible_service.playbooks_dir.resolve())
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=403, detail="Accès non autorisé")
|
||||
|
||||
try:
|
||||
playbook_path.unlink()
|
||||
|
||||
log_entry = LogEntry(
|
||||
id=db.get_next_id("logs"),
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
level="WARN",
|
||||
message=f"Playbook {filename} supprimé",
|
||||
source="playbook_editor"
|
||||
)
|
||||
db.logs.insert(0, log_entry)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Playbook {filename} supprimé avec succès"
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Erreur suppression fichier: {str(e)}")
|
||||
@@ -0,0 +1,554 @@
|
||||
"""
|
||||
Routes API pour la gestion des schedules.
|
||||
"""
|
||||
|
||||
import json
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.dependencies import get_db, verify_api_key
|
||||
from app.crud.schedule import ScheduleRepository
|
||||
from app.crud.schedule_run import ScheduleRunRepository
|
||||
from app.crud.log import LogRepository
|
||||
from app.schemas.schedule_api import (
|
||||
Schedule,
|
||||
ScheduleCreateRequest,
|
||||
ScheduleUpdateRequest,
|
||||
)
|
||||
from app.services import ansible_service, ws_manager, scheduler_service
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_schedules(
|
||||
enabled: Optional[bool] = None,
|
||||
playbook: Optional[str] = None,
|
||||
tag: Optional[str] = None,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
):
|
||||
"""Liste tous les schedules."""
|
||||
schedules = scheduler_service.get_all_schedules(
|
||||
enabled=enabled,
|
||||
playbook=playbook,
|
||||
tag=tag,
|
||||
)
|
||||
|
||||
paginated = schedules[offset:offset + limit]
|
||||
|
||||
results = []
|
||||
for s in paginated:
|
||||
rec = s.recurrence
|
||||
results.append({
|
||||
"id": s.id,
|
||||
"name": s.name,
|
||||
"playbook": s.playbook,
|
||||
"target": s.target,
|
||||
"schedule_type": s.schedule_type,
|
||||
"recurrence": rec.model_dump() if rec else None,
|
||||
"enabled": s.enabled,
|
||||
"notification_type": getattr(s, 'notification_type', 'all'),
|
||||
"tags": s.tags,
|
||||
"next_run_at": s.next_run_at,
|
||||
"last_run_at": s.last_run_at,
|
||||
"last_status": s.last_status,
|
||||
"run_count": s.run_count,
|
||||
"success_count": s.success_count,
|
||||
"failure_count": s.failure_count,
|
||||
"created_at": s.created_at,
|
||||
"updated_at": s.updated_at,
|
||||
})
|
||||
|
||||
return {"schedules": results, "count": len(schedules)}
|
||||
|
||||
|
||||
@router.get("/stats")
|
||||
async def get_schedules_stats(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère les statistiques des schedules."""
|
||||
stats = scheduler_service.get_stats()
|
||||
upcoming = scheduler_service.get_upcoming_executions(limit=5)
|
||||
|
||||
return {
|
||||
"stats": stats.dict(),
|
||||
"upcoming": upcoming
|
||||
}
|
||||
|
||||
|
||||
@router.get("/upcoming")
|
||||
async def get_upcoming_schedules(
|
||||
limit: int = 10,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Récupère les prochaines exécutions planifiées."""
|
||||
upcoming = scheduler_service.get_upcoming_executions(limit=limit)
|
||||
return {
|
||||
"upcoming": upcoming,
|
||||
"count": len(upcoming)
|
||||
}
|
||||
|
||||
|
||||
@router.get("/validate-cron")
|
||||
async def validate_cron_expression(
|
||||
expression: str,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Valide une expression cron."""
|
||||
result = scheduler_service.validate_cron_expression(expression)
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/{schedule_id}")
|
||||
async def get_schedule(
|
||||
schedule_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Récupère les détails d'un schedule."""
|
||||
repo = ScheduleRepository(db_session)
|
||||
schedule = await repo.get(schedule_id)
|
||||
if not schedule:
|
||||
raise HTTPException(status_code=404, detail=f"Schedule '{schedule_id}' non trouvé")
|
||||
|
||||
return {
|
||||
"id": schedule.id,
|
||||
"name": schedule.name,
|
||||
"playbook": schedule.playbook,
|
||||
"target": schedule.target,
|
||||
"schedule_type": schedule.schedule_type,
|
||||
"recurrence_type": schedule.recurrence_type,
|
||||
"recurrence_time": schedule.recurrence_time,
|
||||
"recurrence_days": json.loads(schedule.recurrence_days) if schedule.recurrence_days else None,
|
||||
"cron_expression": schedule.cron_expression,
|
||||
"enabled": schedule.enabled,
|
||||
"notification_type": schedule.notification_type or "all",
|
||||
"tags": json.loads(schedule.tags) if schedule.tags else [],
|
||||
"next_run": schedule.next_run,
|
||||
"last_run": schedule.last_run,
|
||||
"created_at": schedule.created_at,
|
||||
"updated_at": schedule.updated_at,
|
||||
}
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_schedule(
|
||||
request: ScheduleCreateRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Crée un nouveau schedule."""
|
||||
# Vérifier que le playbook existe
|
||||
playbooks = ansible_service.get_playbooks()
|
||||
playbook_names = [p['filename'] for p in playbooks] + [p['name'] for p in playbooks]
|
||||
|
||||
playbook_file = request.playbook
|
||||
if not playbook_file.endswith(('.yml', '.yaml')):
|
||||
playbook_file = f"{playbook_file}.yml"
|
||||
|
||||
if playbook_file not in playbook_names and request.playbook not in playbook_names:
|
||||
raise HTTPException(status_code=400, detail=f"Playbook '{request.playbook}' non trouvé")
|
||||
|
||||
# Récupérer les infos du playbook pour validation
|
||||
playbook_info = next((pb for pb in playbooks if pb['filename'] == playbook_file or pb['name'] == request.playbook), None)
|
||||
|
||||
# Vérifier la cible
|
||||
if request.target_type == "group":
|
||||
groups = ansible_service.get_groups()
|
||||
if request.target not in groups and request.target != "all":
|
||||
raise HTTPException(status_code=400, detail=f"Groupe '{request.target}' non trouvé")
|
||||
else:
|
||||
if not ansible_service.host_exists(request.target):
|
||||
raise HTTPException(status_code=400, detail=f"Hôte '{request.target}' non trouvé")
|
||||
|
||||
# Valider la compatibilité playbook-target
|
||||
if playbook_info:
|
||||
playbook_hosts = playbook_info.get('hosts', 'all')
|
||||
if not ansible_service.is_target_compatible_with_playbook(request.target, playbook_hosts):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Le playbook '{request.playbook}' (hosts: {playbook_hosts}) n'est pas compatible avec la cible '{request.target}'."
|
||||
)
|
||||
|
||||
# Valider la récurrence
|
||||
if request.schedule_type == "recurring" and not request.recurrence:
|
||||
raise HTTPException(status_code=400, detail="La récurrence est requise pour un schedule récurrent")
|
||||
|
||||
if request.recurrence and request.recurrence.type == "custom":
|
||||
if not request.recurrence.cron_expression:
|
||||
raise HTTPException(status_code=400, detail="Expression cron requise pour le type 'custom'")
|
||||
validation = scheduler_service.validate_cron_expression(request.recurrence.cron_expression)
|
||||
if not validation["valid"]:
|
||||
raise HTTPException(status_code=400, detail=f"Expression cron invalide: {validation.get('error')}")
|
||||
|
||||
# Créer en DB
|
||||
repo = ScheduleRepository(db_session)
|
||||
schedule_id = f"sched_{uuid.uuid4().hex[:12]}"
|
||||
|
||||
recurrence = request.recurrence
|
||||
schedule_obj = await repo.create(
|
||||
id=schedule_id,
|
||||
name=request.name,
|
||||
description=request.description,
|
||||
playbook=playbook_file,
|
||||
target_type=request.target_type,
|
||||
target=request.target,
|
||||
extra_vars=request.extra_vars,
|
||||
schedule_type=request.schedule_type,
|
||||
schedule_time=request.start_at,
|
||||
recurrence_type=recurrence.type if recurrence else None,
|
||||
recurrence_time=recurrence.time if recurrence else None,
|
||||
recurrence_days=json.dumps(recurrence.days) if recurrence and recurrence.days else None,
|
||||
cron_expression=recurrence.cron_expression if recurrence else None,
|
||||
timezone=request.timezone,
|
||||
start_at=request.start_at,
|
||||
end_at=request.end_at,
|
||||
enabled=request.enabled,
|
||||
retry_on_failure=request.retry_on_failure,
|
||||
timeout=request.timeout,
|
||||
notification_type=request.notification_type,
|
||||
tags=json.dumps(request.tags) if request.tags else None,
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
# Créer le schedule Pydantic et l'ajouter au cache du scheduler
|
||||
pydantic_schedule = Schedule(
|
||||
id=schedule_id,
|
||||
name=request.name,
|
||||
description=request.description,
|
||||
playbook=playbook_file,
|
||||
target_type=request.target_type,
|
||||
target=request.target,
|
||||
extra_vars=request.extra_vars,
|
||||
schedule_type=request.schedule_type,
|
||||
recurrence=request.recurrence,
|
||||
timezone=request.timezone,
|
||||
start_at=request.start_at,
|
||||
end_at=request.end_at,
|
||||
enabled=request.enabled,
|
||||
retry_on_failure=request.retry_on_failure,
|
||||
timeout=request.timeout,
|
||||
notification_type=request.notification_type,
|
||||
tags=request.tags or [],
|
||||
)
|
||||
scheduler_service.add_schedule_to_cache(pydantic_schedule)
|
||||
|
||||
# Log en DB
|
||||
log_repo = LogRepository(db_session)
|
||||
await log_repo.create(
|
||||
level="INFO",
|
||||
message=f"Schedule '{request.name}' créé pour {playbook_file} sur {request.target}",
|
||||
source="scheduler",
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
# Notifier via WebSocket
|
||||
await ws_manager.broadcast({
|
||||
"type": "schedule_created",
|
||||
"data": {
|
||||
"id": schedule_obj.id,
|
||||
"name": schedule_obj.name,
|
||||
"playbook": schedule_obj.playbook,
|
||||
"target": schedule_obj.target,
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Schedule '{request.name}' créé avec succès",
|
||||
"schedule": {
|
||||
"id": schedule_obj.id,
|
||||
"name": schedule_obj.name,
|
||||
"playbook": schedule_obj.playbook,
|
||||
"target": schedule_obj.target,
|
||||
"enabled": schedule_obj.enabled,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.put("/{schedule_id}")
|
||||
async def update_schedule(
|
||||
schedule_id: str,
|
||||
request: ScheduleUpdateRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Met à jour un schedule existant."""
|
||||
sched = scheduler_service.get_schedule(schedule_id)
|
||||
repo = ScheduleRepository(db_session)
|
||||
schedule = await repo.get(schedule_id)
|
||||
|
||||
if not sched and not schedule:
|
||||
raise HTTPException(status_code=404, detail=f"Schedule '{schedule_id}' non trouvé")
|
||||
|
||||
schedule_name = sched.name if sched else schedule.name
|
||||
|
||||
# Valider le playbook si modifié
|
||||
if request.playbook:
|
||||
playbooks = ansible_service.get_playbooks()
|
||||
playbook_names = [p['filename'] for p in playbooks] + [p['name'] for p in playbooks]
|
||||
playbook_file = request.playbook
|
||||
if not playbook_file.endswith(('.yml', '.yaml')):
|
||||
playbook_file = f"{playbook_file}.yml"
|
||||
if playbook_file not in playbook_names and request.playbook not in playbook_names:
|
||||
raise HTTPException(status_code=400, detail=f"Playbook '{request.playbook}' non trouvé")
|
||||
|
||||
# Valider l'expression cron si modifiée
|
||||
if request.recurrence and request.recurrence.type == "custom":
|
||||
if request.recurrence.cron_expression:
|
||||
validation = scheduler_service.validate_cron_expression(request.recurrence.cron_expression)
|
||||
if not validation["valid"]:
|
||||
raise HTTPException(status_code=400, detail=f"Expression cron invalide: {validation.get('error')}")
|
||||
|
||||
# Mettre à jour en DB
|
||||
update_fields = {}
|
||||
if request.name:
|
||||
update_fields["name"] = request.name
|
||||
if request.description:
|
||||
update_fields["description"] = request.description
|
||||
if request.playbook:
|
||||
update_fields["playbook"] = request.playbook
|
||||
if request.target:
|
||||
update_fields["target"] = request.target
|
||||
if request.schedule_type:
|
||||
update_fields["schedule_type"] = request.schedule_type
|
||||
if request.timezone:
|
||||
update_fields["timezone"] = request.timezone
|
||||
if request.enabled is not None:
|
||||
update_fields["enabled"] = request.enabled
|
||||
if request.retry_on_failure is not None:
|
||||
update_fields["retry_on_failure"] = request.retry_on_failure
|
||||
if request.timeout is not None:
|
||||
update_fields["timeout"] = request.timeout
|
||||
if request.notification_type:
|
||||
update_fields["notification_type"] = request.notification_type
|
||||
if request.tags:
|
||||
update_fields["tags"] = json.dumps(request.tags)
|
||||
if request.recurrence:
|
||||
update_fields["recurrence_type"] = request.recurrence.type
|
||||
update_fields["recurrence_time"] = request.recurrence.time
|
||||
update_fields["recurrence_days"] = json.dumps(request.recurrence.days) if request.recurrence.days else None
|
||||
update_fields["cron_expression"] = request.recurrence.cron_expression
|
||||
|
||||
if schedule:
|
||||
await repo.update(schedule, **update_fields)
|
||||
await db_session.commit()
|
||||
|
||||
scheduler_service.update_schedule(schedule_id, request)
|
||||
|
||||
# Log en DB
|
||||
log_repo = LogRepository(db_session)
|
||||
await log_repo.create(
|
||||
level="INFO",
|
||||
message=f"Schedule '{schedule_name}' mis à jour",
|
||||
source="scheduler",
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "schedule_updated",
|
||||
"data": {"id": schedule_id, "name": schedule_name}
|
||||
})
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Schedule '{schedule_name}' mis à jour",
|
||||
"schedule": {"id": schedule_id, "name": schedule_name}
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{schedule_id}")
|
||||
async def delete_schedule(
|
||||
schedule_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Supprime un schedule."""
|
||||
repo = ScheduleRepository(db_session)
|
||||
schedule = await repo.get(schedule_id)
|
||||
if not schedule:
|
||||
try:
|
||||
scheduler_service.delete_schedule(schedule_id)
|
||||
except Exception:
|
||||
pass
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Schedule '{schedule_id}' déjà supprimé ou inexistant."
|
||||
}
|
||||
|
||||
schedule_name = schedule.name
|
||||
|
||||
await repo.soft_delete(schedule_id)
|
||||
await db_session.commit()
|
||||
|
||||
scheduler_service.delete_schedule(schedule_id)
|
||||
|
||||
log_repo = LogRepository(db_session)
|
||||
await log_repo.create(
|
||||
level="WARN",
|
||||
message=f"Schedule '{schedule_name}' supprimé",
|
||||
source="scheduler",
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "schedule_deleted",
|
||||
"data": {"id": schedule_id, "name": schedule_name}
|
||||
})
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Schedule '{schedule_name}' supprimé"
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{schedule_id}/run")
|
||||
async def run_schedule_now(
|
||||
schedule_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Exécute immédiatement un schedule."""
|
||||
sched = scheduler_service.get_schedule(schedule_id)
|
||||
if not sched:
|
||||
repo = ScheduleRepository(db_session)
|
||||
schedule = await repo.get(schedule_id)
|
||||
if not schedule:
|
||||
raise HTTPException(status_code=404, detail=f"Schedule '{schedule_id}' non trouvé")
|
||||
schedule_name = schedule.name
|
||||
else:
|
||||
schedule_name = sched.name
|
||||
|
||||
run = await scheduler_service.run_now(schedule_id)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Schedule '{schedule_name}' lancé",
|
||||
"run": run.dict() if run else None
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{schedule_id}/pause")
|
||||
async def pause_schedule(
|
||||
schedule_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Met en pause un schedule."""
|
||||
sched = scheduler_service.get_schedule(schedule_id)
|
||||
repo = ScheduleRepository(db_session)
|
||||
schedule = await repo.get(schedule_id)
|
||||
|
||||
if not sched and not schedule:
|
||||
raise HTTPException(status_code=404, detail=f"Schedule '{schedule_id}' non trouvé")
|
||||
|
||||
schedule_name = sched.name if sched else schedule.name
|
||||
|
||||
if schedule:
|
||||
await repo.update(schedule, enabled=False)
|
||||
await db_session.commit()
|
||||
|
||||
scheduler_service.pause_schedule(schedule_id)
|
||||
|
||||
log_repo = LogRepository(db_session)
|
||||
await log_repo.create(
|
||||
level="INFO",
|
||||
message=f"Schedule '{schedule_name}' mis en pause",
|
||||
source="scheduler",
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "schedule_updated",
|
||||
"data": {"id": schedule_id, "name": schedule_name, "enabled": False}
|
||||
})
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Schedule '{schedule_name}' mis en pause",
|
||||
"schedule": {"id": schedule_id, "name": schedule_name, "enabled": False}
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{schedule_id}/resume")
|
||||
async def resume_schedule(
|
||||
schedule_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Reprend un schedule en pause."""
|
||||
sched = scheduler_service.get_schedule(schedule_id)
|
||||
repo = ScheduleRepository(db_session)
|
||||
schedule = await repo.get(schedule_id)
|
||||
|
||||
if not sched and not schedule:
|
||||
raise HTTPException(status_code=404, detail=f"Schedule '{schedule_id}' non trouvé")
|
||||
|
||||
schedule_name = sched.name if sched else schedule.name
|
||||
|
||||
if schedule:
|
||||
await repo.update(schedule, enabled=True)
|
||||
await db_session.commit()
|
||||
|
||||
scheduler_service.resume_schedule(schedule_id)
|
||||
|
||||
log_repo = LogRepository(db_session)
|
||||
await log_repo.create(
|
||||
level="INFO",
|
||||
message=f"Schedule '{schedule_name}' repris",
|
||||
source="scheduler",
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "schedule_updated",
|
||||
"data": {"id": schedule_id, "name": schedule_name, "enabled": True}
|
||||
})
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Schedule '{schedule_name}' repris",
|
||||
"schedule": {"id": schedule_id, "name": schedule_name, "enabled": True}
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{schedule_id}/runs")
|
||||
async def get_schedule_runs(
|
||||
schedule_id: str,
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Récupère l'historique des exécutions d'un schedule."""
|
||||
sched = scheduler_service.get_schedule(schedule_id)
|
||||
repo = ScheduleRepository(db_session)
|
||||
schedule = await repo.get(schedule_id)
|
||||
|
||||
if not sched and not schedule:
|
||||
raise HTTPException(status_code=404, detail=f"Schedule '{schedule_id}' non trouvé")
|
||||
|
||||
schedule_name = sched.name if sched else schedule.name
|
||||
|
||||
run_repo = ScheduleRunRepository(db_session)
|
||||
runs = await run_repo.list_for_schedule(schedule_id, limit=limit, offset=offset)
|
||||
|
||||
return {
|
||||
"schedule_id": schedule_id,
|
||||
"schedule_name": schedule_name,
|
||||
"runs": [
|
||||
{
|
||||
"id": r.id,
|
||||
"status": r.status,
|
||||
"started_at": r.started_at,
|
||||
"finished_at": r.completed_at,
|
||||
"duration_seconds": r.duration,
|
||||
"error_message": r.error_message,
|
||||
}
|
||||
for r in runs
|
||||
],
|
||||
"count": len(runs)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
Routes API pour les logs serveur.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.dependencies import get_db, verify_api_key
|
||||
from app.crud.log import LogRepository
|
||||
from app.services import console_log_service
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/logs")
|
||||
async def get_server_logs(
|
||||
limit: int = 500,
|
||||
offset: int = 0,
|
||||
level: Optional[str] = None,
|
||||
source: Optional[str] = None,
|
||||
log_source: str = "console",
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Récupère les logs serveur avec pagination.
|
||||
|
||||
Args:
|
||||
log_source: "console" pour les logs stdout/stderr en temps réel,
|
||||
"db" pour les logs stockés en base de données
|
||||
"""
|
||||
if log_source == "console":
|
||||
# Logs console en temps réel
|
||||
logs = console_log_service.get_logs(limit=limit, offset=offset, level=level)
|
||||
return {
|
||||
"logs": logs,
|
||||
"count": console_log_service.get_count(),
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
"source": "console"
|
||||
}
|
||||
else:
|
||||
# Logs depuis la base de données
|
||||
repo = LogRepository(db_session)
|
||||
logs = await repo.list(limit=limit, offset=offset, level=level, source=source)
|
||||
|
||||
return {
|
||||
"logs": [
|
||||
{
|
||||
"id": log.id,
|
||||
"timestamp": log.created_at,
|
||||
"level": log.level,
|
||||
"message": log.message,
|
||||
"source": log.source,
|
||||
"host": log.host_id,
|
||||
}
|
||||
for log in logs
|
||||
],
|
||||
"count": len(logs),
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
"source": "db"
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
"""
|
||||
Routes API pour la gestion des tâches.
|
||||
"""
|
||||
|
||||
import uuid
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.constants import ACTION_PLAYBOOK_MAP, ACTION_DISPLAY_NAMES
|
||||
from app.core.dependencies import get_db, verify_api_key
|
||||
from app.crud.task import TaskRepository
|
||||
from app.crud.log import LogRepository
|
||||
from app.schemas.task_api import TaskRequest
|
||||
from app.services import ws_manager, db, ansible_service, notification_service
|
||||
from app.services.task_log_service import TaskLogService
|
||||
from app.models.database import async_session_maker
|
||||
from app.schemas.task_api import Task
|
||||
from app.schemas.common import LogEntry
|
||||
from time import perf_counter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# Instance du service de logs de tâches
|
||||
task_log_service = TaskLogService(settings.tasks_logs_dir)
|
||||
|
||||
# Dictionnaire des tâches en cours d'exécution
|
||||
running_task_handles = {}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_tasks(
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Récupère la liste des tâches."""
|
||||
repo = TaskRepository(db_session)
|
||||
tasks = await repo.list(limit=limit, offset=offset)
|
||||
return [
|
||||
{
|
||||
"id": t.id,
|
||||
"name": t.action,
|
||||
"host": t.target,
|
||||
"status": t.status,
|
||||
"progress": 100 if t.status == "completed" else (50 if t.status == "running" else 0),
|
||||
"start_time": t.started_at,
|
||||
"end_time": t.completed_at,
|
||||
"duration": None,
|
||||
"output": t.result_data.get("output") if t.result_data else None,
|
||||
"error": t.error_message,
|
||||
}
|
||||
for t in tasks
|
||||
]
|
||||
|
||||
|
||||
@router.get("/running")
|
||||
async def get_running_tasks(
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Récupère les tâches en cours d'exécution."""
|
||||
repo = TaskRepository(db_session)
|
||||
tasks = await repo.list(limit=100, offset=0)
|
||||
running_tasks = [t for t in tasks if t.status in ("running", "pending")]
|
||||
return {
|
||||
"tasks": [
|
||||
{
|
||||
"id": t.id,
|
||||
"name": t.action,
|
||||
"host": t.target,
|
||||
"status": t.status,
|
||||
"progress": 50 if t.status == "running" else 0,
|
||||
"start_time": t.started_at,
|
||||
"end_time": t.completed_at,
|
||||
}
|
||||
for t in running_tasks
|
||||
],
|
||||
"count": len(running_tasks)
|
||||
}
|
||||
|
||||
|
||||
@router.get("/logs")
|
||||
async def get_task_logs(
|
||||
status: Optional[str] = None,
|
||||
year: Optional[str] = None,
|
||||
month: Optional[str] = None,
|
||||
day: Optional[str] = None,
|
||||
hour_start: Optional[str] = None,
|
||||
hour_end: Optional[str] = None,
|
||||
target: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
source_type: Optional[str] = None,
|
||||
limit: int = 50,
|
||||
offset: int = 0,
|
||||
api_key_valid: bool = Depends(verify_api_key)
|
||||
):
|
||||
"""Récupère les logs de tâches depuis les fichiers markdown."""
|
||||
logs, total_count = task_log_service.get_task_logs(
|
||||
year=year,
|
||||
month=month,
|
||||
day=day,
|
||||
status=status,
|
||||
target=target,
|
||||
category=category,
|
||||
source_type=source_type,
|
||||
hour_start=hour_start,
|
||||
hour_end=hour_end,
|
||||
limit=limit,
|
||||
offset=offset
|
||||
)
|
||||
return {
|
||||
"logs": [log.dict() for log in logs],
|
||||
"count": len(logs),
|
||||
"total_count": total_count,
|
||||
"has_more": offset + len(logs) < total_count,
|
||||
"filters": {
|
||||
"status": status,
|
||||
"year": year,
|
||||
"month": month,
|
||||
"day": day,
|
||||
"hour_start": hour_start,
|
||||
"hour_end": hour_end,
|
||||
"target": target,
|
||||
"source_type": source_type
|
||||
},
|
||||
"pagination": {
|
||||
"limit": limit,
|
||||
"offset": offset
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.get("/logs/dates")
|
||||
async def get_task_logs_dates(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère les dates disponibles pour le filtrage."""
|
||||
return task_log_service.get_available_dates()
|
||||
|
||||
|
||||
@router.get("/logs/stats")
|
||||
async def get_task_logs_stats(api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère les statistiques des logs de tâches."""
|
||||
return task_log_service.get_stats()
|
||||
|
||||
|
||||
@router.get("/logs/{log_id}")
|
||||
async def get_task_log_content(log_id: str, api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Récupère le contenu d'un log de tâche spécifique."""
|
||||
logs, _ = task_log_service.get_task_logs(limit=0)
|
||||
log = next((l for l in logs if l.id == log_id), None)
|
||||
|
||||
if not log:
|
||||
raise HTTPException(status_code=404, detail="Log non trouvé")
|
||||
|
||||
try:
|
||||
content = Path(log.path).read_text(encoding='utf-8')
|
||||
return {
|
||||
"log": log.dict(),
|
||||
"content": content
|
||||
}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Erreur lecture du fichier: {str(e)}")
|
||||
|
||||
|
||||
@router.delete("/logs/{log_id}")
|
||||
async def delete_task_log(log_id: str, api_key_valid: bool = Depends(verify_api_key)):
|
||||
"""Supprime un fichier de log de tâche."""
|
||||
logs, _ = task_log_service.get_task_logs(limit=0)
|
||||
log = next((l for l in logs if l.id == log_id), None)
|
||||
|
||||
if not log:
|
||||
raise HTTPException(status_code=404, detail="Log non trouvé")
|
||||
|
||||
try:
|
||||
log_path = Path(log.path)
|
||||
if log_path.exists():
|
||||
log_path.unlink()
|
||||
# Le TaskLogService met en cache l'index des fichiers pendant ~60s.
|
||||
# Invalider immédiatement pour que la suppression soit visible instantanément.
|
||||
task_log_service.invalidate_index()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_log_deleted",
|
||||
"data": {"id": log_id}
|
||||
})
|
||||
return {"message": "Log supprimé", "id": log_id}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Erreur suppression: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/{task_id}/cancel")
|
||||
async def cancel_task(
|
||||
task_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Annule une tâche en cours d'exécution."""
|
||||
repo = TaskRepository(db_session)
|
||||
task = await repo.get(task_id)
|
||||
|
||||
if not task:
|
||||
raise HTTPException(status_code=404, detail="Tâche non trouvée")
|
||||
|
||||
if task.status not in ("running", "pending"):
|
||||
raise HTTPException(status_code=400, detail=f"La tâche n'est pas en cours (statut: {task.status})")
|
||||
|
||||
# Marquer comme annulée
|
||||
if task_id in running_task_handles:
|
||||
running_task_handles[task_id]["cancelled"] = True
|
||||
|
||||
async_task = running_task_handles[task_id].get("asyncio_task")
|
||||
if async_task and not async_task.done():
|
||||
async_task.cancel()
|
||||
|
||||
process = running_task_handles[task_id].get("process")
|
||||
if process:
|
||||
try:
|
||||
process.terminate()
|
||||
await asyncio.sleep(0.5)
|
||||
if process.returncode is None:
|
||||
process.kill()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
del running_task_handles[task_id]
|
||||
|
||||
await repo.update(
|
||||
task,
|
||||
status="cancelled",
|
||||
completed_at=datetime.now(timezone.utc),
|
||||
error_message="Tâche annulée par l'utilisateur"
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
# Log
|
||||
log_repo = LogRepository(db_session)
|
||||
await log_repo.create(
|
||||
level="WARNING",
|
||||
message=f"Tâche '{task.action}' annulée manuellement",
|
||||
source="task",
|
||||
task_id=task_id,
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_cancelled",
|
||||
"data": {
|
||||
"id": task_id,
|
||||
"status": "cancelled",
|
||||
"message": "Tâche annulée par l'utilisateur"
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Tâche {task_id} annulée avec succès",
|
||||
"task_id": task_id
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{task_id}")
|
||||
async def get_task(
|
||||
task_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Récupère une tâche spécifique."""
|
||||
repo = TaskRepository(db_session)
|
||||
task = await repo.get(task_id)
|
||||
if not task:
|
||||
raise HTTPException(status_code=404, detail="Tâche non trouvée")
|
||||
return {
|
||||
"id": task.id,
|
||||
"name": task.action,
|
||||
"host": task.target,
|
||||
"status": task.status,
|
||||
"progress": 100 if task.status == "completed" else (50 if task.status == "running" else 0),
|
||||
"start_time": task.started_at,
|
||||
"end_time": task.completed_at,
|
||||
"duration": None,
|
||||
"output": task.result_data.get("output") if task.result_data else None,
|
||||
"error": task.error_message,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{task_id}")
|
||||
async def delete_task(
|
||||
task_id: str,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Supprime une tâche."""
|
||||
repo = TaskRepository(db_session)
|
||||
task = await repo.get(task_id)
|
||||
if not task:
|
||||
raise HTTPException(status_code=404, detail="Tâche non trouvée")
|
||||
|
||||
await db_session.delete(task)
|
||||
await db_session.commit()
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_deleted",
|
||||
"data": {"id": task_id}
|
||||
})
|
||||
|
||||
return {"message": "Tâche supprimée avec succès"}
|
||||
|
||||
|
||||
@router.post("")
|
||||
async def create_task(
|
||||
task_request: TaskRequest,
|
||||
api_key_valid: bool = Depends(verify_api_key),
|
||||
db_session: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Crée une nouvelle tâche et exécute le playbook correspondant."""
|
||||
repo = TaskRepository(db_session)
|
||||
task_id = uuid.uuid4().hex
|
||||
target = task_request.host or task_request.group or "all"
|
||||
playbook = ACTION_PLAYBOOK_MAP.get(task_request.action)
|
||||
|
||||
task_obj = await repo.create(
|
||||
id=task_id,
|
||||
action=task_request.action,
|
||||
target=target,
|
||||
playbook=playbook,
|
||||
status="running",
|
||||
)
|
||||
await repo.update(task_obj, started_at=datetime.now(timezone.utc))
|
||||
await db_session.commit()
|
||||
|
||||
task_name = ACTION_DISPLAY_NAMES.get(task_request.action, f"Tâche {task_request.action}")
|
||||
|
||||
response_data = {
|
||||
"id": task_obj.id,
|
||||
"name": task_name,
|
||||
"host": target,
|
||||
"status": "running",
|
||||
"progress": 0,
|
||||
"start_time": task_obj.started_at,
|
||||
"end_time": None,
|
||||
"duration": None,
|
||||
"output": None,
|
||||
"error": None,
|
||||
}
|
||||
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_created",
|
||||
"data": response_data
|
||||
})
|
||||
|
||||
# Exécuter le playbook en arrière-plan
|
||||
if playbook:
|
||||
asyncio.create_task(_execute_task_playbook(
|
||||
task_id=task_id,
|
||||
task_name=task_name,
|
||||
playbook=playbook,
|
||||
target=target,
|
||||
extra_vars=task_request.extra_vars,
|
||||
check_mode=task_request.dry_run if hasattr(task_request, 'dry_run') else False
|
||||
))
|
||||
|
||||
return response_data
|
||||
|
||||
|
||||
async def _execute_task_playbook(
|
||||
task_id: str,
|
||||
task_name: str,
|
||||
playbook: str,
|
||||
target: str,
|
||||
extra_vars: dict = None,
|
||||
check_mode: bool = False
|
||||
):
|
||||
"""Exécute un playbook Ansible en arrière-plan et met à jour le statut."""
|
||||
start_time = perf_counter()
|
||||
|
||||
# Créer une tâche en mémoire pour le service de logs
|
||||
mem_task = Task(
|
||||
id=task_id,
|
||||
name=task_name,
|
||||
host=target,
|
||||
status="running",
|
||||
progress=10,
|
||||
start_time=datetime.now(timezone.utc)
|
||||
)
|
||||
|
||||
# Notifier la progression
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_progress",
|
||||
"data": {"id": task_id, "progress": 10, "message": "Démarrage du playbook..."}
|
||||
})
|
||||
|
||||
try:
|
||||
# Exécuter le playbook
|
||||
result = await ansible_service.execute_playbook(
|
||||
playbook=playbook,
|
||||
target=target,
|
||||
extra_vars=extra_vars,
|
||||
check_mode=check_mode,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
execution_time = perf_counter() - start_time
|
||||
success = result.get("success", False)
|
||||
|
||||
# Mettre à jour la tâche en mémoire
|
||||
mem_task.status = "completed" if success else "failed"
|
||||
mem_task.progress = 100
|
||||
mem_task.end_time = datetime.now(timezone.utc)
|
||||
mem_task.duration = f"{execution_time:.1f}s"
|
||||
mem_task.output = result.get("stdout", "")
|
||||
mem_task.error = result.get("stderr", "") if not success else None
|
||||
|
||||
# Mettre à jour en BD
|
||||
async with async_session_maker() as session:
|
||||
repo = TaskRepository(session)
|
||||
db_task = await repo.get(task_id)
|
||||
if db_task:
|
||||
await repo.update(
|
||||
db_task,
|
||||
status=mem_task.status,
|
||||
completed_at=mem_task.end_time,
|
||||
error_message=mem_task.error,
|
||||
result_data={"output": result.get("stdout", "")[:5000]}
|
||||
)
|
||||
await session.commit()
|
||||
|
||||
# Sauvegarder le log markdown
|
||||
try:
|
||||
log_path = task_log_service.save_task_log(
|
||||
task=mem_task,
|
||||
output=result.get("stdout", ""),
|
||||
error=result.get("stderr", "")
|
||||
)
|
||||
created_log = task_log_service.index_log_file(log_path)
|
||||
if created_log:
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_log_created",
|
||||
"data": created_log.dict()
|
||||
})
|
||||
except Exception as log_error:
|
||||
print(f"Erreur sauvegarde log markdown: {log_error}")
|
||||
|
||||
# Notifier la fin via WebSocket
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_completed",
|
||||
"data": {
|
||||
"id": task_id,
|
||||
"status": mem_task.status,
|
||||
"progress": 100,
|
||||
"duration": mem_task.duration,
|
||||
"success": success
|
||||
}
|
||||
})
|
||||
|
||||
# Notification ntfy
|
||||
if success:
|
||||
await notification_service.notify_task_completed(
|
||||
task_name=task_name,
|
||||
target=target,
|
||||
duration=mem_task.duration
|
||||
)
|
||||
else:
|
||||
await notification_service.notify_task_failed(
|
||||
task_name=task_name,
|
||||
target=target,
|
||||
error=result.get("stderr", "Erreur inconnue")[:200]
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
execution_time = perf_counter() - start_time
|
||||
error_msg = str(e)
|
||||
|
||||
mem_task.status = "failed"
|
||||
mem_task.end_time = datetime.now(timezone.utc)
|
||||
mem_task.duration = f"{execution_time:.1f}s"
|
||||
mem_task.error = error_msg
|
||||
|
||||
# Mettre à jour en BD
|
||||
try:
|
||||
async with async_session_maker() as session:
|
||||
repo = TaskRepository(session)
|
||||
db_task = await repo.get(task_id)
|
||||
if db_task:
|
||||
await repo.update(
|
||||
db_task,
|
||||
status="failed",
|
||||
completed_at=mem_task.end_time,
|
||||
error_message=error_msg
|
||||
)
|
||||
await session.commit()
|
||||
except Exception as db_error:
|
||||
print(f"Erreur mise à jour BD: {db_error}")
|
||||
|
||||
# Sauvegarder le log markdown
|
||||
try:
|
||||
log_path = task_log_service.save_task_log(task=mem_task, error=error_msg)
|
||||
created_log = task_log_service.index_log_file(log_path)
|
||||
if created_log:
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_log_created",
|
||||
"data": created_log.dict()
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Notifier l'échec
|
||||
await ws_manager.broadcast({
|
||||
"type": "task_failed",
|
||||
"data": {
|
||||
"id": task_id,
|
||||
"status": "failed",
|
||||
"error": error_msg
|
||||
}
|
||||
})
|
||||
|
||||
await notification_service.notify_task_failed(
|
||||
task_name=task_name,
|
||||
target=target,
|
||||
error=error_msg[:200]
|
||||
)
|
||||
@@ -0,0 +1,22 @@
|
||||
"""
|
||||
Routes WebSocket pour les mises à jour en temps réel.
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
|
||||
from app.services import ws_manager
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def websocket_endpoint(websocket: WebSocket):
|
||||
"""Endpoint WebSocket pour les mises à jour en temps réel."""
|
||||
await ws_manager.connect(websocket)
|
||||
try:
|
||||
while True:
|
||||
# Garder la connexion ouverte
|
||||
data = await websocket.receive_text()
|
||||
# Traiter les messages entrants si nécessaire
|
||||
except WebSocketDisconnect:
|
||||
ws_manager.disconnect(websocket)
|
||||
Reference in New Issue
Block a user