updates.py 14 KB

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