updates.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. """Update checking and management routes."""
  2. import asyncio
  3. import logging
  4. import os
  5. import re
  6. import shutil
  7. import sys
  8. import httpx
  9. from fastapi import APIRouter, BackgroundTasks, Depends
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  12. from backend.app.core.config import APP_VERSION, GITHUB_REPO, settings
  13. from backend.app.core.database import get_db
  14. from backend.app.core.permissions import Permission
  15. from backend.app.models.user import User
  16. logger = logging.getLogger(__name__)
  17. router = APIRouter(prefix="/updates", tags=["updates"])
  18. # Global state for update progress
  19. _update_status = {
  20. "status": "idle", # idle, checking, downloading, installing, complete, error
  21. "progress": 0,
  22. "message": "",
  23. "error": None,
  24. }
  25. def _is_docker_environment() -> bool:
  26. """Detect if running inside a Docker container."""
  27. if os.path.exists("/.dockerenv"):
  28. return True
  29. try:
  30. with open("/proc/1/cgroup") as f:
  31. if "docker" in f.read():
  32. return True
  33. except (FileNotFoundError, PermissionError):
  34. pass # cgroup file unavailable; continue with other detection methods
  35. git_dir = settings.base_dir / ".git"
  36. return not git_dir.exists()
  37. def _find_executable(name: str) -> str | None:
  38. """Find an executable in PATH or common locations."""
  39. # Try standard PATH first
  40. path = shutil.which(name)
  41. if path:
  42. return path
  43. # Common locations for executables (useful when running as systemd service)
  44. common_paths = [
  45. f"/usr/bin/{name}",
  46. f"/usr/local/bin/{name}",
  47. f"/opt/homebrew/bin/{name}",
  48. f"/home/linuxbrew/.linuxbrew/bin/{name}",
  49. f"{os.path.expanduser('~')}/.nvm/current/bin/{name}",
  50. f"{os.path.expanduser('~')}/.local/bin/{name}",
  51. ]
  52. for p in common_paths:
  53. if os.path.isfile(p) and os.access(p, os.X_OK):
  54. return p
  55. return None
  56. def parse_version(version: str) -> tuple:
  57. """Parse version string into tuple for comparison.
  58. Returns (major, minor, patch, is_prerelease, prerelease_num)
  59. where is_prerelease is 0 for release, 1 for prerelease.
  60. This ensures releases sort higher than prereleases of same version.
  61. Examples:
  62. "0.1.5" -> (0, 1, 5, 0, 0) # release
  63. "0.1.5b7" -> (0, 1, 5, 1, 7) # beta 7
  64. "0.1.5b10" -> (0, 1, 5, 1, 10) # beta 10
  65. """
  66. # Remove 'v' prefix if present
  67. version = version.lstrip("v")
  68. # Match version pattern: major.minor.patch[b|beta|alpha|rc]N
  69. match = re.match(r"(\d+)\.(\d+)\.(\d+)(?:b|beta|alpha|rc)?(\d+)?", version)
  70. if match:
  71. major = int(match.group(1))
  72. minor = int(match.group(2))
  73. patch = int(match.group(3))
  74. prerelease_num = int(match.group(4)) if match.group(4) else 0
  75. # Check if this is a prerelease (has b/beta/alpha/rc suffix)
  76. is_prerelease = 1 if re.search(r"[a-zA-Z]", version.split(".")[-1]) else 0
  77. return (major, minor, patch, is_prerelease, prerelease_num)
  78. # Fallback: try simple split
  79. parts = []
  80. for part in version.split("."):
  81. try:
  82. parts.append(int(part))
  83. except ValueError:
  84. num = "".join(c for c in part if c.isdigit())
  85. parts.append(int(num) if num else 0)
  86. return tuple(parts) + (0, 0)
  87. def is_newer_version(latest: str, current: str) -> bool:
  88. """Check if latest version is newer than current.
  89. Properly handles prerelease versions:
  90. - 0.1.5 > 0.1.5b7 (release is newer than any beta)
  91. - 0.1.5b8 > 0.1.5b7 (later beta is newer)
  92. - 0.1.6b1 > 0.1.5 (next version beta is newer than current release)
  93. """
  94. try:
  95. latest_parsed = parse_version(latest)
  96. current_parsed = parse_version(current)
  97. # Compare (major, minor, patch) first
  98. latest_base = latest_parsed[:3]
  99. current_base = current_parsed[:3]
  100. if latest_base > current_base:
  101. return True
  102. elif latest_base < current_base:
  103. return False
  104. # Same base version - compare prerelease status
  105. # is_prerelease: 0 = release, 1 = prerelease
  106. # Release (0) should be "greater" than prerelease (1)
  107. latest_is_prerelease = latest_parsed[3] if len(latest_parsed) > 3 else 0
  108. current_is_prerelease = current_parsed[3] if len(current_parsed) > 3 else 0
  109. if latest_is_prerelease < current_is_prerelease:
  110. # latest is release, current is prerelease -> latest is newer
  111. return True
  112. elif latest_is_prerelease > current_is_prerelease:
  113. # latest is prerelease, current is release -> latest is NOT newer
  114. return False
  115. # Both are same type (both release or both prerelease)
  116. # Compare prerelease numbers
  117. latest_prerelease_num = latest_parsed[4] if len(latest_parsed) > 4 else 0
  118. current_prerelease_num = current_parsed[4] if len(current_parsed) > 4 else 0
  119. return latest_prerelease_num > current_prerelease_num
  120. except Exception:
  121. return False
  122. @router.get("/version")
  123. async def get_version():
  124. """Get current application version.
  125. Note: Unauthenticated - needed to display version in UI without login.
  126. """
  127. return {
  128. "version": APP_VERSION,
  129. "repo": GITHUB_REPO,
  130. }
  131. @router.get("/check")
  132. async def check_for_updates(
  133. db: AsyncSession = Depends(get_db),
  134. _: User | None = RequirePermissionIfAuthEnabled(Permission.SYSTEM_READ),
  135. ):
  136. """Check GitHub for available updates."""
  137. global _update_status
  138. _update_status = {
  139. "status": "checking",
  140. "progress": 0,
  141. "message": "Checking for updates...",
  142. "error": None,
  143. }
  144. try:
  145. async with httpx.AsyncClient() as client:
  146. response = await client.get(
  147. f"https://api.github.com/repos/{GITHUB_REPO}/releases/latest",
  148. headers={"Accept": "application/vnd.github.v3+json"},
  149. timeout=10.0,
  150. )
  151. if response.status_code == 404:
  152. # No releases yet
  153. _update_status = {
  154. "status": "idle",
  155. "progress": 100,
  156. "message": "No releases found",
  157. "error": None,
  158. }
  159. return {
  160. "update_available": False,
  161. "current_version": APP_VERSION,
  162. "latest_version": None,
  163. "message": "No releases found",
  164. }
  165. response.raise_for_status()
  166. release_data = response.json()
  167. latest_version = release_data.get("tag_name", "").lstrip("v")
  168. release_name = release_data.get("name", latest_version)
  169. release_notes = release_data.get("body", "")
  170. release_url = release_data.get("html_url", "")
  171. published_at = release_data.get("published_at", "")
  172. update_available = is_newer_version(latest_version, APP_VERSION)
  173. _update_status = {
  174. "status": "idle",
  175. "progress": 100,
  176. "message": "Update available" if update_available else "Up to date",
  177. "error": None,
  178. }
  179. is_docker = _is_docker_environment()
  180. return {
  181. "update_available": update_available,
  182. "current_version": APP_VERSION,
  183. "latest_version": latest_version,
  184. "release_name": release_name,
  185. "release_notes": release_notes,
  186. "release_url": release_url,
  187. "published_at": published_at,
  188. "is_docker": is_docker,
  189. "update_method": "docker" if is_docker else "git",
  190. }
  191. except httpx.HTTPError as e:
  192. logger.error("Failed to check for updates: %s", e)
  193. _update_status = {
  194. "status": "error",
  195. "progress": 0,
  196. "message": "Failed to check for updates",
  197. "error": str(e),
  198. }
  199. return {
  200. "update_available": False,
  201. "current_version": APP_VERSION,
  202. "latest_version": None,
  203. "error": str(e),
  204. }
  205. async def _perform_update():
  206. """Perform the actual update using git fetch and reset."""
  207. global _update_status
  208. try:
  209. base_dir = settings.base_dir
  210. # Find git executable (may not be in PATH when running as systemd service)
  211. git_path = _find_executable("git")
  212. if not git_path:
  213. _update_status = {
  214. "status": "error",
  215. "progress": 0,
  216. "message": "Git not found",
  217. "error": "Could not find git executable. Please ensure git is installed.",
  218. }
  219. return
  220. logger.info("Using git at: %s", git_path)
  221. # Git config to avoid safe.directory issues
  222. git_config = ["-c", f"safe.directory={base_dir}"]
  223. _update_status = {
  224. "status": "downloading",
  225. "progress": 10,
  226. "message": "Configuring git...",
  227. "error": None,
  228. }
  229. # Ensure remote uses HTTPS (SSH may not be available)
  230. https_url = f"https://github.com/{GITHUB_REPO}.git"
  231. process = await asyncio.create_subprocess_exec(
  232. git_path,
  233. *git_config,
  234. "remote",
  235. "set-url",
  236. "origin",
  237. https_url,
  238. cwd=str(base_dir),
  239. stdout=asyncio.subprocess.PIPE,
  240. stderr=asyncio.subprocess.PIPE,
  241. )
  242. await process.communicate()
  243. _update_status = {
  244. "status": "downloading",
  245. "progress": 20,
  246. "message": "Fetching latest changes...",
  247. "error": None,
  248. }
  249. # Fetch from origin
  250. process = await asyncio.create_subprocess_exec(
  251. git_path,
  252. *git_config,
  253. "fetch",
  254. "origin",
  255. "main",
  256. cwd=str(base_dir),
  257. stdout=asyncio.subprocess.PIPE,
  258. stderr=asyncio.subprocess.PIPE,
  259. )
  260. stdout, stderr = await process.communicate()
  261. if process.returncode != 0:
  262. error_msg = stderr.decode() if stderr else "Git fetch failed"
  263. logger.error("Git fetch failed: %s", error_msg)
  264. _update_status = {
  265. "status": "error",
  266. "progress": 0,
  267. "message": "Failed to fetch updates",
  268. "error": error_msg,
  269. }
  270. return
  271. _update_status = {
  272. "status": "downloading",
  273. "progress": 40,
  274. "message": "Applying updates...",
  275. "error": None,
  276. }
  277. # Hard reset to origin/main (clean update, no merge conflicts)
  278. process = await asyncio.create_subprocess_exec(
  279. git_path,
  280. *git_config,
  281. "reset",
  282. "--hard",
  283. "origin/main",
  284. cwd=str(base_dir),
  285. stdout=asyncio.subprocess.PIPE,
  286. stderr=asyncio.subprocess.PIPE,
  287. )
  288. stdout, stderr = await process.communicate()
  289. if process.returncode != 0:
  290. error_msg = stderr.decode() if stderr else "Git reset failed"
  291. logger.error("Git reset failed: %s", error_msg)
  292. _update_status = {
  293. "status": "error",
  294. "progress": 0,
  295. "message": "Failed to apply updates",
  296. "error": error_msg,
  297. }
  298. return
  299. _update_status = {
  300. "status": "installing",
  301. "progress": 50,
  302. "message": "Installing dependencies...",
  303. "error": None,
  304. }
  305. # Install Python dependencies
  306. process = await asyncio.create_subprocess_exec(
  307. sys.executable,
  308. "-m",
  309. "pip",
  310. "install",
  311. "-r",
  312. "requirements.txt",
  313. "-q",
  314. cwd=str(base_dir),
  315. stdout=asyncio.subprocess.PIPE,
  316. stderr=asyncio.subprocess.PIPE,
  317. )
  318. stdout, stderr = await process.communicate()
  319. if process.returncode != 0:
  320. logger.warning("pip install warning: %s", stderr.decode() if stderr else "unknown")
  321. # Try to build frontend if npm is available (optional - static files are pre-built)
  322. npm_path = _find_executable("npm")
  323. frontend_dir = base_dir / "frontend"
  324. if npm_path and frontend_dir.exists():
  325. _update_status = {
  326. "status": "installing",
  327. "progress": 70,
  328. "message": "Building frontend...",
  329. "error": None,
  330. }
  331. # npm install
  332. process = await asyncio.create_subprocess_exec(
  333. npm_path,
  334. "install",
  335. cwd=str(frontend_dir),
  336. stdout=asyncio.subprocess.PIPE,
  337. stderr=asyncio.subprocess.PIPE,
  338. )
  339. await process.communicate()
  340. # npm run build
  341. process = await asyncio.create_subprocess_exec(
  342. npm_path,
  343. "run",
  344. "build",
  345. cwd=str(frontend_dir),
  346. stdout=asyncio.subprocess.PIPE,
  347. stderr=asyncio.subprocess.PIPE,
  348. )
  349. stdout, stderr = await process.communicate()
  350. if process.returncode != 0:
  351. logger.warning("Frontend build warning: %s", stderr.decode() if stderr else "unknown")
  352. else:
  353. logger.info("npm not found or frontend dir missing - using pre-built static files")
  354. _update_status = {
  355. "status": "complete",
  356. "progress": 100,
  357. "message": "Update complete! Please restart the application.",
  358. "error": None,
  359. }
  360. logger.info("Update completed successfully")
  361. except Exception as e:
  362. logger.error("Update failed: %s", e)
  363. _update_status = {
  364. "status": "error",
  365. "progress": 0,
  366. "message": "Update failed",
  367. "error": str(e),
  368. }
  369. @router.post("/apply")
  370. async def apply_update(
  371. background_tasks: BackgroundTasks,
  372. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  373. ):
  374. """Apply available update (git pull + rebuild)."""
  375. global _update_status
  376. if _update_status["status"] in ["downloading", "installing"]:
  377. return {
  378. "success": False,
  379. "message": "Update already in progress",
  380. "status": _update_status,
  381. }
  382. # Check if running in Docker
  383. if _is_docker_environment():
  384. return {
  385. "success": False,
  386. "is_docker": True,
  387. "message": (
  388. "Docker installations cannot be updated in-app. "
  389. "Please update via Docker Compose: "
  390. "git pull && docker compose build --pull && docker compose up -d"
  391. ),
  392. }
  393. # Start update in background
  394. background_tasks.add_task(_perform_update)
  395. _update_status = {
  396. "status": "downloading",
  397. "progress": 10,
  398. "message": "Starting update...",
  399. "error": None,
  400. }
  401. return {
  402. "success": True,
  403. "message": "Update started",
  404. "status": _update_status,
  405. }
  406. @router.get("/status")
  407. async def get_update_status(
  408. _: User | None = RequirePermissionIfAuthEnabled(Permission.SYSTEM_READ),
  409. ):
  410. """Get current update status."""
  411. return _update_status