github_backup.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. """API routes for GitHub profile backup."""
  2. import logging
  3. from fastapi import APIRouter, Depends, HTTPException, Query
  4. from sqlalchemy import delete, desc, select
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from backend.app.core.database import get_db
  7. from backend.app.models.github_backup import GitHubBackupConfig, GitHubBackupLog
  8. from backend.app.schemas.github_backup import (
  9. GitHubBackupConfigCreate,
  10. GitHubBackupConfigResponse,
  11. GitHubBackupConfigUpdate,
  12. GitHubBackupLogResponse,
  13. GitHubBackupStatus,
  14. GitHubBackupTriggerResponse,
  15. GitHubTestConnectionResponse,
  16. )
  17. from backend.app.services.github_backup import github_backup_service
  18. logger = logging.getLogger(__name__)
  19. router = APIRouter(prefix="/github-backup", tags=["github-backup"])
  20. def _config_to_response(config: GitHubBackupConfig) -> dict:
  21. """Convert config model to response dict."""
  22. return {
  23. "id": config.id,
  24. "repository_url": config.repository_url,
  25. "has_token": bool(config.access_token),
  26. "branch": config.branch,
  27. "schedule_enabled": config.schedule_enabled,
  28. "schedule_type": config.schedule_type,
  29. "backup_kprofiles": config.backup_kprofiles,
  30. "backup_cloud_profiles": config.backup_cloud_profiles,
  31. "backup_settings": config.backup_settings,
  32. "enabled": config.enabled,
  33. "last_backup_at": config.last_backup_at,
  34. "last_backup_status": config.last_backup_status,
  35. "last_backup_message": config.last_backup_message,
  36. "last_backup_commit_sha": config.last_backup_commit_sha,
  37. "next_scheduled_run": config.next_scheduled_run,
  38. "created_at": config.created_at,
  39. "updated_at": config.updated_at,
  40. }
  41. @router.get("/config", response_model=GitHubBackupConfigResponse | None)
  42. async def get_config(db: AsyncSession = Depends(get_db)):
  43. """Get the current GitHub backup configuration."""
  44. result = await db.execute(select(GitHubBackupConfig).limit(1))
  45. config = result.scalar_one_or_none()
  46. if not config:
  47. return None
  48. return _config_to_response(config)
  49. @router.post("/config", response_model=GitHubBackupConfigResponse)
  50. async def save_config(
  51. config_data: GitHubBackupConfigCreate,
  52. db: AsyncSession = Depends(get_db),
  53. ):
  54. """Create or update GitHub backup configuration.
  55. Only one configuration is supported. If one exists, it will be updated.
  56. """
  57. # Check for existing config
  58. result = await db.execute(select(GitHubBackupConfig).limit(1))
  59. config = result.scalar_one_or_none()
  60. if config:
  61. # Update existing
  62. config.repository_url = config_data.repository_url
  63. config.access_token = config_data.access_token
  64. config.branch = config_data.branch
  65. config.schedule_enabled = config_data.schedule_enabled
  66. config.schedule_type = config_data.schedule_type.value
  67. config.backup_kprofiles = config_data.backup_kprofiles
  68. config.backup_cloud_profiles = config_data.backup_cloud_profiles
  69. config.backup_settings = config_data.backup_settings
  70. config.enabled = config_data.enabled
  71. # Calculate next scheduled run if enabled
  72. if config.schedule_enabled:
  73. config.next_scheduled_run = github_backup_service._calculate_next_run(config.schedule_type)
  74. else:
  75. config.next_scheduled_run = None
  76. logger.info(f"Updated GitHub backup config: {config.repository_url}")
  77. else:
  78. # Create new
  79. config = GitHubBackupConfig(
  80. repository_url=config_data.repository_url,
  81. access_token=config_data.access_token,
  82. branch=config_data.branch,
  83. schedule_enabled=config_data.schedule_enabled,
  84. schedule_type=config_data.schedule_type.value,
  85. backup_kprofiles=config_data.backup_kprofiles,
  86. backup_cloud_profiles=config_data.backup_cloud_profiles,
  87. backup_settings=config_data.backup_settings,
  88. enabled=config_data.enabled,
  89. )
  90. if config.schedule_enabled:
  91. config.next_scheduled_run = github_backup_service._calculate_next_run(config.schedule_type)
  92. db.add(config)
  93. logger.info(f"Created GitHub backup config: {config.repository_url}")
  94. await db.commit()
  95. await db.refresh(config)
  96. return _config_to_response(config)
  97. @router.patch("/config", response_model=GitHubBackupConfigResponse)
  98. async def update_config(
  99. update_data: GitHubBackupConfigUpdate,
  100. db: AsyncSession = Depends(get_db),
  101. ):
  102. """Partially update GitHub backup configuration."""
  103. result = await db.execute(select(GitHubBackupConfig).limit(1))
  104. config = result.scalar_one_or_none()
  105. if not config:
  106. raise HTTPException(status_code=404, detail="No configuration found")
  107. update_dict = update_data.model_dump(exclude_unset=True)
  108. for key, value in update_dict.items():
  109. if key == "schedule_type" and value is not None:
  110. setattr(config, key, value.value)
  111. else:
  112. setattr(config, key, value)
  113. # Recalculate next scheduled run if schedule settings changed
  114. if "schedule_enabled" in update_dict or "schedule_type" in update_dict:
  115. if config.schedule_enabled:
  116. config.next_scheduled_run = github_backup_service._calculate_next_run(config.schedule_type)
  117. else:
  118. config.next_scheduled_run = None
  119. await db.commit()
  120. await db.refresh(config)
  121. logger.info(f"Updated GitHub backup config: {config.repository_url}")
  122. return _config_to_response(config)
  123. @router.delete("/config")
  124. async def delete_config(db: AsyncSession = Depends(get_db)):
  125. """Delete the GitHub backup configuration and all logs."""
  126. result = await db.execute(select(GitHubBackupConfig).limit(1))
  127. config = result.scalar_one_or_none()
  128. if not config:
  129. raise HTTPException(status_code=404, detail="No configuration found")
  130. await db.delete(config)
  131. await db.commit()
  132. logger.info("Deleted GitHub backup config")
  133. return {"message": "Configuration deleted"}
  134. @router.post("/test", response_model=GitHubTestConnectionResponse)
  135. async def test_connection(
  136. repo_url: str = Query(..., description="GitHub repository URL"),
  137. token: str = Query(..., description="Personal Access Token"),
  138. ):
  139. """Test GitHub connection with provided credentials."""
  140. result = await github_backup_service.test_connection(repo_url, token)
  141. return GitHubTestConnectionResponse(**result)
  142. @router.post("/test-stored", response_model=GitHubTestConnectionResponse)
  143. async def test_stored_connection(db: AsyncSession = Depends(get_db)):
  144. """Test GitHub connection using stored configuration."""
  145. result = await db.execute(select(GitHubBackupConfig).limit(1))
  146. config = result.scalar_one_or_none()
  147. if not config:
  148. raise HTTPException(status_code=404, detail="No configuration found")
  149. if not config.access_token:
  150. raise HTTPException(status_code=400, detail="No access token configured")
  151. test_result = await github_backup_service.test_connection(config.repository_url, config.access_token)
  152. return GitHubTestConnectionResponse(**test_result)
  153. @router.post("/run", response_model=GitHubBackupTriggerResponse)
  154. async def trigger_backup(db: AsyncSession = Depends(get_db)):
  155. """Manually trigger a backup."""
  156. result = await db.execute(select(GitHubBackupConfig).limit(1))
  157. config = result.scalar_one_or_none()
  158. if not config:
  159. raise HTTPException(status_code=404, detail="No configuration found. Configure backup first.")
  160. if not config.enabled:
  161. raise HTTPException(status_code=400, detail="Backup is disabled")
  162. backup_result = await github_backup_service.run_backup(config.id, trigger="manual")
  163. return GitHubBackupTriggerResponse(**backup_result)
  164. @router.get("/status", response_model=GitHubBackupStatus)
  165. async def get_status(db: AsyncSession = Depends(get_db)):
  166. """Get current backup status."""
  167. result = await db.execute(select(GitHubBackupConfig).limit(1))
  168. config = result.scalar_one_or_none()
  169. if not config:
  170. return GitHubBackupStatus(
  171. configured=False,
  172. enabled=False,
  173. is_running=False,
  174. progress=None,
  175. last_backup_at=None,
  176. last_backup_status=None,
  177. next_scheduled_run=None,
  178. )
  179. return GitHubBackupStatus(
  180. configured=True,
  181. enabled=config.enabled,
  182. is_running=github_backup_service.is_running,
  183. progress=github_backup_service.progress,
  184. last_backup_at=config.last_backup_at,
  185. last_backup_status=config.last_backup_status,
  186. next_scheduled_run=config.next_scheduled_run,
  187. )
  188. @router.get("/logs", response_model=list[GitHubBackupLogResponse])
  189. async def get_logs(
  190. limit: int = Query(default=50, ge=1, le=200),
  191. offset: int = Query(default=0, ge=0),
  192. db: AsyncSession = Depends(get_db),
  193. ):
  194. """Get backup logs."""
  195. result = await db.execute(select(GitHubBackupConfig).limit(1))
  196. config = result.scalar_one_or_none()
  197. if not config:
  198. return []
  199. logs_result = await db.execute(
  200. select(GitHubBackupLog)
  201. .where(GitHubBackupLog.config_id == config.id)
  202. .order_by(desc(GitHubBackupLog.started_at))
  203. .offset(offset)
  204. .limit(limit)
  205. )
  206. logs = logs_result.scalars().all()
  207. return [
  208. GitHubBackupLogResponse(
  209. id=log.id,
  210. config_id=log.config_id,
  211. started_at=log.started_at,
  212. completed_at=log.completed_at,
  213. status=log.status,
  214. trigger=log.trigger,
  215. commit_sha=log.commit_sha,
  216. files_changed=log.files_changed,
  217. error_message=log.error_message,
  218. )
  219. for log in logs
  220. ]
  221. @router.delete("/logs")
  222. async def clear_logs(
  223. keep_last: int = Query(default=10, ge=0, le=100, description="Number of recent logs to keep"),
  224. db: AsyncSession = Depends(get_db),
  225. ):
  226. """Clear backup logs, optionally keeping the most recent entries."""
  227. result = await db.execute(select(GitHubBackupConfig).limit(1))
  228. config = result.scalar_one_or_none()
  229. if not config:
  230. return {"deleted": 0, "message": "No configuration found"}
  231. if keep_last > 0:
  232. # Get IDs to keep
  233. keep_result = await db.execute(
  234. select(GitHubBackupLog.id)
  235. .where(GitHubBackupLog.config_id == config.id)
  236. .order_by(desc(GitHubBackupLog.started_at))
  237. .limit(keep_last)
  238. )
  239. keep_ids = [row[0] for row in keep_result.fetchall()]
  240. if keep_ids:
  241. delete_result = await db.execute(
  242. delete(GitHubBackupLog).where(
  243. GitHubBackupLog.config_id == config.id, GitHubBackupLog.id.not_in(keep_ids)
  244. )
  245. )
  246. else:
  247. delete_result = await db.execute(delete(GitHubBackupLog).where(GitHubBackupLog.config_id == config.id))
  248. else:
  249. delete_result = await db.execute(delete(GitHubBackupLog).where(GitHubBackupLog.config_id == config.id))
  250. await db.commit()
  251. deleted_count = delete_result.rowcount
  252. logger.info(f"Deleted {deleted_count} GitHub backup logs (kept {keep_last})")
  253. return {"deleted": deleted_count, "message": f"Deleted {deleted_count} logs"}