150 lines
6.4 KiB
Python
150 lines
6.4 KiB
Python
# [DEF:backend.src.api.routes.migration:Module]
|
|
# @TIER: STANDARD
|
|
# @SEMANTICS: api, migration, dashboards
|
|
# @PURPOSE: API endpoints for migration operations.
|
|
# @LAYER: API
|
|
# @RELATION: DEPENDS_ON -> backend.src.dependencies
|
|
# @RELATION: DEPENDS_ON -> backend.src.models.dashboard
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
from typing import List, Dict, Any
|
|
from sqlalchemy.orm import Session
|
|
from ...dependencies import get_config_manager, get_task_manager, has_permission
|
|
from ...core.database import get_db
|
|
from ...models.dashboard import DashboardMetadata, DashboardSelection
|
|
from ...core.superset_client import SupersetClient
|
|
from ...core.logger import belief_scope
|
|
from ...core.mapping_service import IdMappingService
|
|
from ...models.mapping import ResourceMapping
|
|
|
|
router = APIRouter(prefix="/api", tags=["migration"])
|
|
|
|
# [DEF:get_dashboards:Function]
|
|
# @PURPOSE: Fetch all dashboards from the specified environment for the grid.
|
|
# @PRE: Environment ID must be valid.
|
|
# @POST: Returns a list of dashboard metadata.
|
|
# @PARAM: env_id (str) - The ID of the environment to fetch from.
|
|
# @RETURN: List[DashboardMetadata]
|
|
@router.get("/environments/{env_id}/dashboards", response_model=List[DashboardMetadata])
|
|
async def get_dashboards(
|
|
env_id: str,
|
|
config_manager=Depends(get_config_manager),
|
|
_ = Depends(has_permission("plugin:migration", "EXECUTE"))
|
|
):
|
|
with belief_scope("get_dashboards", f"env_id={env_id}"):
|
|
environments = config_manager.get_environments()
|
|
env = next((e for e in environments if e.id == env_id), None)
|
|
if not env:
|
|
raise HTTPException(status_code=404, detail="Environment not found")
|
|
|
|
client = SupersetClient(env)
|
|
dashboards = client.get_dashboards_summary()
|
|
return dashboards
|
|
# [/DEF:get_dashboards:Function]
|
|
|
|
# [DEF:execute_migration:Function]
|
|
# @PURPOSE: Execute the migration of selected dashboards.
|
|
# @PRE: Selection must be valid and environments must exist.
|
|
# @POST: Starts the migration task and returns the task ID.
|
|
# @PARAM: selection (DashboardSelection) - The dashboards to migrate.
|
|
# @RETURN: Dict - {"task_id": str, "message": str}
|
|
@router.post("/execute")
|
|
async def execute_migration(
|
|
selection: DashboardSelection,
|
|
config_manager=Depends(get_config_manager),
|
|
task_manager=Depends(get_task_manager),
|
|
_ = Depends(has_permission("plugin:migration", "EXECUTE"))
|
|
):
|
|
with belief_scope("execute_migration"):
|
|
# Validate environments exist
|
|
environments = config_manager.get_environments()
|
|
env_ids = {e.id for e in environments}
|
|
if selection.source_env_id not in env_ids or selection.target_env_id not in env_ids:
|
|
raise HTTPException(status_code=400, detail="Invalid source or target environment")
|
|
|
|
# Create migration task with debug logging
|
|
from ...core.logger import logger
|
|
|
|
# Include replace_db_config and fix_cross_filters in the task parameters
|
|
task_params = selection.dict()
|
|
task_params['replace_db_config'] = selection.replace_db_config
|
|
task_params['fix_cross_filters'] = selection.fix_cross_filters
|
|
|
|
logger.info(f"Creating migration task with params: {task_params}")
|
|
logger.info(f"Available environments: {env_ids}")
|
|
logger.info(f"Source env: {selection.source_env_id}, Target env: {selection.target_env_id}")
|
|
|
|
try:
|
|
task = await task_manager.create_task("superset-migration", task_params)
|
|
logger.info(f"Task created successfully: {task.id}")
|
|
return {"task_id": task.id, "message": "Migration initiated"}
|
|
except Exception as e:
|
|
logger.error(f"Task creation failed: {e}")
|
|
raise HTTPException(status_code=500, detail=f"Failed to create migration task: {str(e)}")
|
|
# [/DEF:execute_migration:Function]
|
|
|
|
# [DEF:get_migration_settings:Function]
|
|
# @PURPOSE: Get current migration Cron string explicitly.
|
|
@router.get("/settings", response_model=Dict[str, str])
|
|
async def get_migration_settings(
|
|
config_manager=Depends(get_config_manager),
|
|
_ = Depends(has_permission("plugin:migration", "READ"))
|
|
):
|
|
with belief_scope("get_migration_settings"):
|
|
# For simplicity in MVP, assuming cron expression is stored in config
|
|
# default to a valid cron if not set.
|
|
config = config_manager.get_config()
|
|
cron = config.get("migration_sync_cron", "0 2 * * *")
|
|
return {"cron": cron}
|
|
# [/DEF:get_migration_settings:Function]
|
|
|
|
# [DEF:update_migration_settings:Function]
|
|
# @PURPOSE: Update migration Cron string.
|
|
@router.put("/settings", response_model=Dict[str, str])
|
|
async def update_migration_settings(
|
|
payload: Dict[str, str],
|
|
config_manager=Depends(get_config_manager),
|
|
_ = Depends(has_permission("plugin:migration", "WRITE"))
|
|
):
|
|
with belief_scope("update_migration_settings"):
|
|
if "cron" not in payload:
|
|
raise HTTPException(status_code=400, detail="Missing 'cron' field in payload")
|
|
|
|
cron_expr = payload["cron"]
|
|
# Basic validation could go here
|
|
|
|
# In a real system, you'd save this to config and restart the scheduler.
|
|
# Here we just blindly patch the in-memory or file config for the MVP.
|
|
current_cfg = config_manager.get_config()
|
|
current_cfg["migration_sync_cron"] = cron_expr
|
|
config_manager.save_config(current_cfg)
|
|
|
|
return {"cron": cron_expr, "status": "updated"}
|
|
# [/DEF:update_migration_settings:Function]
|
|
|
|
# [DEF:get_resource_mappings:Function]
|
|
# @PURPOSE: Fetch all synchronized object mappings from the database.
|
|
@router.get("/mappings-data", response_model=List[Dict[str, Any]])
|
|
async def get_resource_mappings(
|
|
skip: int = Query(0, ge=0),
|
|
limit: int = Query(100, ge=1, le=1000),
|
|
db: Session = Depends(get_db),
|
|
_ = Depends(has_permission("plugin:migration", "READ"))
|
|
):
|
|
with belief_scope("get_resource_mappings"):
|
|
mappings = db.query(ResourceMapping).offset(skip).limit(limit).all()
|
|
result = []
|
|
for m in mappings:
|
|
result.append({
|
|
"id": m.id,
|
|
"environment_id": m.environment_id,
|
|
"resource_type": m.resource_type.value,
|
|
"uuid": m.uuid,
|
|
"remote_id": m.remote_integer_id,
|
|
"resource_name": m.resource_name,
|
|
"last_synced_at": m.last_synced_at.isoformat() if m.last_synced_at else None
|
|
})
|
|
return result
|
|
# [/DEF:get_resource_mappings:Function]
|
|
|
|
# [/DEF:backend.src.api.routes.migration:Module] |