github_backup.py 12 KB

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