updates.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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 time
  9. import httpx
  10. from fastapi import APIRouter, BackgroundTasks, Depends
  11. from sqlalchemy import select
  12. from sqlalchemy.ext.asyncio import AsyncSession
  13. from backend.app.core.auth import RequirePermissionIfAuthEnabled
  14. from backend.app.core.config import APP_VERSION, GITHUB_REPO, settings
  15. from backend.app.core.database import get_db
  16. from backend.app.core.permissions import Permission
  17. from backend.app.models.settings import Settings
  18. from backend.app.models.user import User
  19. logger = logging.getLogger(__name__)
  20. router = APIRouter(prefix="/updates", tags=["updates"])
  21. # Global state for update progress
  22. _update_status = {
  23. "status": "idle", # idle, checking, downloading, installing, complete, error
  24. "progress": 0,
  25. "message": "",
  26. "error": None,
  27. }
  28. # GitHub rate-limit backoff (#1420): when api.github.com returns 403 with
  29. # X-RateLimit-Remaining=0, refuse to retry until X-RateLimit-Reset (epoch
  30. # seconds). Falls back to a 1-hour pause if the header is absent. Prevents
  31. # the update checker from hammering GitHub once the unauthenticated quota
  32. # (60 req/hr per source IP) is exhausted.
  33. _GITHUB_RATE_LIMIT_FALLBACK_SECONDS = 3600
  34. _github_rate_limit_until: float = 0.0
  35. def _seconds_until_github_unblocked() -> float:
  36. """Return seconds remaining until GitHub backoff lifts, or 0 if unblocked."""
  37. remaining = _github_rate_limit_until - time.time()
  38. return remaining if remaining > 0 else 0.0
  39. def _record_github_rate_limit(response: httpx.Response) -> None:
  40. """Set the backoff window from a GitHub 403 response's headers."""
  41. global _github_rate_limit_until
  42. reset_header = response.headers.get("X-RateLimit-Reset")
  43. reset_at: float | None = None
  44. if reset_header:
  45. try:
  46. reset_at = float(reset_header)
  47. except ValueError:
  48. reset_at = None
  49. if reset_at is None:
  50. reset_at = time.time() + _GITHUB_RATE_LIMIT_FALLBACK_SECONDS
  51. # Floor at a 60s minimum: protects against clock skew between the container
  52. # and GitHub (parsed reset epoch in the past would otherwise leave us with
  53. # no real backoff and we'd hammer GitHub again immediately).
  54. reset_at = max(reset_at, time.time() + 60)
  55. # Only extend the window — never shorten it via an out-of-order response.
  56. if reset_at > _github_rate_limit_until:
  57. _github_rate_limit_until = reset_at
  58. logger.warning(
  59. "GitHub rate limit hit; suppressing update checks for %.0fs (reset header=%s)",
  60. _seconds_until_github_unblocked(),
  61. reset_header,
  62. )
  63. def _is_github_rate_limit_response(response: httpx.Response) -> bool:
  64. """Detect a rate-limit response from GitHub (403/429 with Remaining=0)."""
  65. if response.status_code not in (403, 429):
  66. return False
  67. remaining = response.headers.get("X-RateLimit-Remaining")
  68. if remaining == "0":
  69. return True
  70. # Some proxies strip the header; fall back to body inspection.
  71. try:
  72. body = response.text or ""
  73. except Exception:
  74. body = ""
  75. return "rate limit" in body.lower() or "API rate limit exceeded" in body
  76. def _is_docker_environment() -> bool:
  77. """Detect if running inside a Docker container."""
  78. if os.path.exists("/.dockerenv"):
  79. return True
  80. try:
  81. with open("/proc/1/cgroup") as f:
  82. if "docker" in f.read():
  83. return True
  84. except (FileNotFoundError, PermissionError):
  85. pass # cgroup file unavailable; continue with other detection methods
  86. # Check container runtime hint (systemd sets this for Docker/podman,
  87. # but NOT for LXC/LXD — avoids false positives on Proxmox containers)
  88. try:
  89. with open("/run/systemd/container") as f:
  90. runtime = f.read().strip()
  91. if runtime in ("docker", "podman", "oci"):
  92. return True
  93. except (FileNotFoundError, PermissionError):
  94. pass
  95. return False
  96. # Mount points the shipped compose file gives Bambuddy. Only these are
  97. # consulted when guessing the compose directory — an arbitrary bind mount
  98. # (a NAS share, an external library root) says nothing about where the
  99. # compose file lives.
  100. _COMPOSE_BIND_MOUNTPOINTS = ("/app/data", "/app/logs")
  101. # A named volume resolves to ``.../docker/volumes/<project>_bambuddy_data/_data``
  102. # in mountinfo. That names the compose *project* but reveals nothing about
  103. # the directory holding the compose file, so these entries are skipped.
  104. _DOCKER_NAMED_VOLUME_ROOT = re.compile(r"/docker/volumes/[^/]+/_data/?$")
  105. def _compose_dir_from_mountinfo() -> str | None:
  106. """Guess the host directory holding the compose file, or None (#2664).
  107. ``docker compose pull`` only works from the directory containing the
  108. compose file, so the command the update box prints is unusable until the
  109. user remembers where that is. Compose knows the answer — it stamps
  110. ``com.docker.compose.project.working_dir`` onto every container it
  111. creates — but reading your own labels requires the Docker socket, and
  112. mounting that into Bambuddy would hand the container root-equivalent
  113. access to the host in exchange for a convenience string. So we infer.
  114. ``/proc/self/mountinfo`` exposes the *host* side of a bind mount in its
  115. root field: a ``./data:/app/data`` line in the compose file surfaces as
  116. ``/opt/bambuddy/data``, whose parent is the compose directory. The leaf
  117. must match the mount point's own name before we take the parent —
  118. ``/mnt/nas/prints:/app/data`` is a bind mount whose parent is emphatically
  119. not a compose directory.
  120. This is a guess and is treated as one — it only ever prefills the setting
  121. the user can overwrite. The root field is relative to the *mounted device*
  122. rather than to the host's ``/``, so a compose directory that sits under a
  123. separate mount loses that mount's own prefix. Measured against real
  124. containers: a compose file on the root filesystem (here a ZFS dataset
  125. mounted at ``/``) came back exactly right, while one under ``/tmp`` — its
  126. own tmpfs — inferred ``/claude-1001/...`` for ``/tmp/claude-1001/...``.
  127. Nothing inside the container can tell the two apart, which is precisely
  128. why the field is editable. The shipped compose file uses named volumes,
  129. for which nothing is inferable at all.
  130. """
  131. try:
  132. with open("/proc/self/mountinfo") as f:
  133. lines = f.readlines()
  134. except OSError:
  135. return None
  136. for line in lines:
  137. parts = line.split()
  138. # mountID parentID major:minor root mountPoint ...
  139. if len(parts) < 5:
  140. continue
  141. root, mount_point = parts[3], parts[4]
  142. if mount_point not in _COMPOSE_BIND_MOUNTPOINTS:
  143. continue
  144. if _DOCKER_NAMED_VOLUME_ROOT.search(root):
  145. continue
  146. parent, _, leaf = root.rstrip("/").rpartition("/")
  147. if parent and leaf == mount_point.rsplit("/", 1)[-1]:
  148. return parent
  149. return None
  150. def _detect_compose_dir() -> str | None:
  151. """Best-effort compose directory for the update instructions (#2664).
  152. ``BAMBUDDY_COMPOSE_DIR`` wins when set — it is the only source that is
  153. stated rather than inferred, and the shipped compose file carries a
  154. commented ``${PWD}`` line for it.
  155. """
  156. env_dir = os.environ.get("BAMBUDDY_COMPOSE_DIR", "").strip()
  157. if env_dir:
  158. return env_dir
  159. if not _is_docker_environment():
  160. return None
  161. return _compose_dir_from_mountinfo()
  162. def _is_ha_addon() -> bool:
  163. """Detect if running as a Home Assistant Supervisor addon.
  164. HA Supervisor injects ``SUPERVISOR_TOKEN`` into every addon container;
  165. the variable is not set in any other environment, so a single env-var
  166. check is sufficient with no false-positive surface.
  167. """
  168. return bool(os.environ.get("SUPERVISOR_TOKEN"))
  169. def _is_windows_installer_install() -> bool:
  170. """Detect a Windows install that came from the Inno Setup installer.
  171. The installer stages backend source via ``shutil.copytree`` (no ``.git``
  172. directory) and does not bundle ``git.exe`` — so the git-fetch-and-reset
  173. update path used everywhere else is structurally inoperable here. We
  174. surface this as a distinct ``update_method`` and direct the user at the
  175. release asset instead.
  176. A Windows developer running from a real ``git clone`` keeps the git
  177. path (``.git`` present), so this only catches installer users.
  178. """
  179. if sys.platform != "win32":
  180. return False
  181. return not (settings.app_dir / ".git").exists()
  182. def _find_windows_installer_asset(release_data: dict) -> str | None:
  183. """Pick the Windows installer .exe out of a GitHub release's assets list.
  184. Both filenames the workflow uploads end in ``windows-x64-setup.exe``
  185. (versioned ``bambuddy-<version>-windows-x64-setup.exe`` and the
  186. unversioned alias ``bambuddy-windows-x64-setup.exe`` on non-daily tags
  187. only). Either works as a download URL; we prefer the versioned form
  188. because it's the one guaranteed to exist on every release including
  189. dailies.
  190. """
  191. assets = release_data.get("assets") or []
  192. versioned: str | None = None
  193. unversioned: str | None = None
  194. for asset in assets:
  195. name = asset.get("name") or ""
  196. url = asset.get("browser_download_url")
  197. if not isinstance(name, str) or not isinstance(url, str):
  198. continue
  199. if not name.endswith("windows-x64-setup.exe"):
  200. continue
  201. if name == "bambuddy-windows-x64-setup.exe":
  202. unversioned = url
  203. else:
  204. versioned = url
  205. return versioned or unversioned
  206. def _find_executable(name: str) -> str | None:
  207. """Find an executable in PATH or common locations."""
  208. # Try standard PATH first
  209. path = shutil.which(name)
  210. if path:
  211. return path
  212. # Common locations for executables (useful when running as systemd service)
  213. common_paths = [
  214. f"/usr/bin/{name}",
  215. f"/usr/local/bin/{name}",
  216. f"/opt/homebrew/bin/{name}",
  217. f"/home/linuxbrew/.linuxbrew/bin/{name}",
  218. f"{os.path.expanduser('~')}/.nvm/current/bin/{name}",
  219. f"{os.path.expanduser('~')}/.local/bin/{name}",
  220. ]
  221. for p in common_paths:
  222. if os.path.isfile(p) and os.access(p, os.X_OK):
  223. return p
  224. return None
  225. def _parse_github_remote(url: str) -> tuple[str, str] | None:
  226. """Extract `(owner, repo)` from a GitHub remote URL, or None if it isn't a
  227. GitHub URL we recognise.
  228. Handles the four forms `git remote -v` typically prints:
  229. - `git@github.com:owner/repo.git` (SSH, the dev default)
  230. - `git@github.com:owner/repo` (SSH without .git suffix)
  231. - `https://github.com/owner/repo.git` (HTTPS, what _perform_update sets)
  232. - `https://github.com/owner/repo` (HTTPS without .git)
  233. Anything else (a fork URL, a different host, a malformed value, the empty
  234. string from a missing origin) returns None so the caller treats it as
  235. "not pointing at our repo" and resets it.
  236. """
  237. s = url.strip()
  238. if not s:
  239. return None
  240. # SSH form: git@github.com:owner/repo[.git]
  241. ssh_prefix = "git@github.com:"
  242. https_prefix_a = "https://github.com/"
  243. https_prefix_b = "http://github.com/" # tolerated for legacy
  244. if s.startswith(ssh_prefix):
  245. path = s[len(ssh_prefix) :]
  246. elif s.startswith(https_prefix_a):
  247. path = s[len(https_prefix_a) :]
  248. elif s.startswith(https_prefix_b):
  249. path = s[len(https_prefix_b) :]
  250. else:
  251. return None
  252. if path.endswith(".git"):
  253. path = path[:-4]
  254. parts = path.strip("/").split("/")
  255. if len(parts) != 2 or not parts[0] or not parts[1]:
  256. return None
  257. return (parts[0], parts[1])
  258. async def _origin_points_at_repo(git_path: str, git_config: list[str], app_dir, expected_repo: str) -> bool:
  259. """Return True iff the working tree's `origin` already resolves to
  260. `<owner>/<repo>` matching `expected_repo` (e.g. "maziggy/bambuddy"),
  261. regardless of whether it's the SSH or HTTPS form. Used to skip the
  262. `git remote set-url origin https://...` rewrite when the developer's
  263. SSH origin is already correct — see `_perform_update` for context.
  264. ``app_dir`` is the working tree (where ``.git`` lives), not the data
  265. dir — see #1715 for the separate-mount layout that proved why this
  266. must NOT be ``base_dir``."""
  267. try:
  268. process = await asyncio.create_subprocess_exec(
  269. git_path,
  270. *git_config,
  271. "remote",
  272. "get-url",
  273. "origin",
  274. cwd=str(app_dir),
  275. stdout=asyncio.subprocess.PIPE,
  276. stderr=asyncio.subprocess.PIPE,
  277. )
  278. stdout, _ = await process.communicate()
  279. except (OSError, asyncio.CancelledError):
  280. # Fail closed: let the caller go through the rewrite branch if we
  281. # can't even invoke git. The unconditional set-url is the safer
  282. # fallback, only mildly destructive.
  283. return False
  284. if process.returncode != 0:
  285. # Most likely cause: no `origin` defined yet (fresh clone-style
  286. # checkout). Caller will set it.
  287. return False
  288. parsed = _parse_github_remote(stdout.decode().strip())
  289. if parsed is None:
  290. return False
  291. owner, repo = parsed
  292. expected_owner, expected_repo_name = expected_repo.split("/", 1)
  293. return owner == expected_owner and repo == expected_repo_name
  294. def parse_version(version: str) -> tuple:
  295. """Parse version string into tuple for comparison.
  296. Returns (major, minor, patch, micro, is_prerelease, prerelease_num)
  297. where is_prerelease is 0 for release, 1 for prerelease.
  298. This ensures releases sort higher than prereleases of same version.
  299. Examples:
  300. "0.1.5" -> (0, 1, 5, 0, 0, 0) # release
  301. "0.1.5b7" -> (0, 1, 5, 0, 1, 7) # beta 7
  302. "0.1.5b10" -> (0, 1, 5, 0, 1, 10) # beta 10
  303. "0.1.8.1" -> (0, 1, 8, 1, 0, 0) # patch release
  304. """
  305. # Remove 'v' prefix if present
  306. version = version.lstrip("v")
  307. # Strip daily build suffix (e.g., "0.2.2b4-daily.20260313" -> "0.2.2b4")
  308. version = re.sub(r"-daily\.\d+$", "", version)
  309. # Match version pattern: major.minor.patch[.micro][b|beta|alpha|rc]N
  310. match = re.match(r"(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?:b|beta|alpha|rc)?(\d+)?", version)
  311. if match:
  312. major = int(match.group(1))
  313. minor = int(match.group(2))
  314. patch = int(match.group(3))
  315. micro = int(match.group(4)) if match.group(4) else 0
  316. prerelease_num = int(match.group(5)) if match.group(5) else 0
  317. # Check if this is a prerelease (has b/beta/alpha/rc/daily suffix anywhere)
  318. is_prerelease = 1 if re.search(r"[a-zA-Z]", version) else 0
  319. return (major, minor, patch, micro, is_prerelease, prerelease_num)
  320. # Fallback: try simple split
  321. parts = []
  322. for part in version.split("."):
  323. try:
  324. parts.append(int(part))
  325. except ValueError:
  326. num = "".join(c for c in part if c.isdigit())
  327. parts.append(int(num) if num else 0)
  328. return tuple(parts) + (0, 0, 0)
  329. def is_newer_version(latest: str, current: str) -> bool:
  330. """Check if latest version is newer than current.
  331. Properly handles prerelease versions:
  332. - 0.1.5 > 0.1.5b7 (release is newer than any beta)
  333. - 0.1.5b8 > 0.1.5b7 (later beta is newer)
  334. - 0.1.6b1 > 0.1.5 (next version beta is newer than current release)
  335. """
  336. try:
  337. latest_parsed = parse_version(latest)
  338. current_parsed = parse_version(current)
  339. # Compare (major, minor, patch, micro) first
  340. latest_base = latest_parsed[:4]
  341. current_base = current_parsed[:4]
  342. if latest_base > current_base:
  343. return True
  344. elif latest_base < current_base:
  345. return False
  346. # Same base version - compare prerelease status
  347. # is_prerelease: 0 = release, 1 = prerelease
  348. # Release (0) should be "greater" than prerelease (1)
  349. latest_is_prerelease = latest_parsed[4] if len(latest_parsed) > 4 else 0
  350. current_is_prerelease = current_parsed[4] if len(current_parsed) > 4 else 0
  351. if latest_is_prerelease < current_is_prerelease:
  352. # latest is release, current is prerelease -> latest is newer
  353. return True
  354. elif latest_is_prerelease > current_is_prerelease:
  355. # latest is prerelease, current is release -> latest is NOT newer
  356. return False
  357. # Both are same type (both release or both prerelease)
  358. # Compare prerelease numbers
  359. latest_prerelease_num = latest_parsed[5] if len(latest_parsed) > 5 else 0
  360. current_prerelease_num = current_parsed[5] if len(current_parsed) > 5 else 0
  361. return latest_prerelease_num > current_prerelease_num
  362. except Exception:
  363. return False
  364. @router.get("/version")
  365. async def get_version():
  366. """Get current application version.
  367. Note: Unauthenticated - needed to display version in UI without login.
  368. """
  369. return {
  370. "version": APP_VERSION,
  371. "repo": GITHUB_REPO,
  372. }
  373. @router.get("/check")
  374. async def check_for_updates(
  375. db: AsyncSession = Depends(get_db),
  376. _: User | None = RequirePermissionIfAuthEnabled(Permission.SYSTEM_READ),
  377. ):
  378. """Check GitHub for available updates."""
  379. global _update_status
  380. # Respect the check_updates setting
  381. result = await db.execute(select(Settings).where(Settings.key == "check_updates"))
  382. setting = result.scalar_one_or_none()
  383. if setting and setting.value.lower() == "false":
  384. return {
  385. "update_available": False,
  386. "current_version": APP_VERSION,
  387. "latest_version": None,
  388. "message": "Update checks are disabled",
  389. }
  390. # Check if beta updates should be included
  391. result = await db.execute(select(Settings).where(Settings.key == "include_beta_updates"))
  392. beta_setting = result.scalar_one_or_none()
  393. include_beta = beta_setting and beta_setting.value.lower() == "true"
  394. # Short-circuit if we're still inside a GitHub rate-limit backoff window (#1420).
  395. backoff_remaining = _seconds_until_github_unblocked()
  396. if backoff_remaining > 0:
  397. _update_status = {
  398. "status": "error",
  399. "progress": 0,
  400. "message": "GitHub rate limit reached",
  401. "error": "GitHub rate limit reached; retry later",
  402. }
  403. return {
  404. "update_available": False,
  405. "current_version": APP_VERSION,
  406. "latest_version": None,
  407. "error": "GitHub rate limit reached; retry later",
  408. "retry_after_seconds": int(backoff_remaining),
  409. }
  410. _update_status = {
  411. "status": "checking",
  412. "progress": 0,
  413. "message": "Checking for updates...",
  414. "error": None,
  415. }
  416. try:
  417. async with httpx.AsyncClient() as client:
  418. response = await client.get(
  419. f"https://api.github.com/repos/{GITHUB_REPO}/releases?per_page=20",
  420. headers={"Accept": "application/vnd.github.v3+json"},
  421. timeout=10.0,
  422. )
  423. if _is_github_rate_limit_response(response):
  424. _record_github_rate_limit(response)
  425. _update_status = {
  426. "status": "error",
  427. "progress": 0,
  428. "message": "GitHub rate limit reached",
  429. "error": "GitHub rate limit reached; retry later",
  430. }
  431. return {
  432. "update_available": False,
  433. "current_version": APP_VERSION,
  434. "latest_version": None,
  435. "error": "GitHub rate limit reached; retry later",
  436. "retry_after_seconds": int(_seconds_until_github_unblocked()),
  437. }
  438. if response.status_code == 404:
  439. # No releases yet
  440. _update_status = {
  441. "status": "idle",
  442. "progress": 100,
  443. "message": "No releases found",
  444. "error": None,
  445. }
  446. return {
  447. "update_available": False,
  448. "current_version": APP_VERSION,
  449. "latest_version": None,
  450. "message": "No releases found",
  451. }
  452. response.raise_for_status()
  453. releases = response.json()
  454. # Find the appropriate release based on beta setting
  455. release_data = None
  456. for release in releases:
  457. tag = release.get("tag_name", "")
  458. if include_beta:
  459. # Accept any release (first = newest)
  460. release_data = release
  461. break
  462. else:
  463. # Skip prereleases (based on version parsing, not GitHub flag)
  464. parsed = parse_version(tag)
  465. if parsed[4] == 0: # is_prerelease == 0
  466. release_data = release
  467. break
  468. if not release_data:
  469. _update_status = {
  470. "status": "idle",
  471. "progress": 100,
  472. "message": "No releases found",
  473. "error": None,
  474. }
  475. return {
  476. "update_available": False,
  477. "current_version": APP_VERSION,
  478. "latest_version": None,
  479. "message": "No releases found",
  480. }
  481. latest_version = release_data.get("tag_name", "").lstrip("v")
  482. release_name = release_data.get("name", latest_version)
  483. release_notes = release_data.get("body", "")
  484. release_url = release_data.get("html_url", "")
  485. published_at = release_data.get("published_at", "")
  486. update_available = is_newer_version(latest_version, APP_VERSION)
  487. _update_status = {
  488. "status": "idle",
  489. "progress": 100,
  490. "message": "Update available" if update_available else "Up to date",
  491. "error": None,
  492. }
  493. is_docker = _is_docker_environment()
  494. is_ha_addon = _is_ha_addon()
  495. is_windows_installer = _is_windows_installer_install()
  496. installer_download_url: str | None = None
  497. if is_ha_addon:
  498. update_method = "ha_addon"
  499. elif is_docker:
  500. update_method = "docker"
  501. elif is_windows_installer:
  502. update_method = "windows_installer"
  503. installer_download_url = _find_windows_installer_asset(release_data)
  504. else:
  505. update_method = "git"
  506. return {
  507. "update_available": update_available,
  508. "current_version": APP_VERSION,
  509. "latest_version": latest_version,
  510. "release_name": release_name,
  511. "release_notes": release_notes,
  512. "release_url": release_url,
  513. "published_at": published_at,
  514. "is_docker": is_docker,
  515. "is_ha_addon": is_ha_addon,
  516. "is_windows_installer": is_windows_installer,
  517. "update_method": update_method,
  518. "installer_download_url": installer_download_url,
  519. # Prefill only — never the value the user saved. The settings
  520. # response owns ``docker_compose_dir``; keeping the two apart
  521. # means clearing the field falls back to the guess instead of
  522. # resurrecting the cleared value from a stale update check.
  523. "compose_dir_detected": _detect_compose_dir() if update_method == "docker" else None,
  524. }
  525. except httpx.HTTPError as e:
  526. logger.error("Failed to check for updates: %s", e)
  527. _update_status = {
  528. "status": "error",
  529. "progress": 0,
  530. "message": "Failed to check for updates",
  531. "error": "Failed to check for updates",
  532. }
  533. return {
  534. "update_available": False,
  535. "current_version": APP_VERSION,
  536. "latest_version": None,
  537. "error": "Failed to check for updates",
  538. }
  539. async def _discover_target_release(db: AsyncSession) -> str | None:
  540. """Look up the tag we should install from GitHub releases.
  541. Same selection logic the GUI's update-check uses: respect
  542. `include_beta_updates`, skip prereleases when the user opted out, take
  543. the first matching release. Returns the raw tag name (e.g. `v0.2.4b1`)
  544. so the git ref is unambiguous, or None if there's no release to install.
  545. The previous in-app updater path was hardcoded to `git fetch origin main
  546. && git reset --hard origin/main`, which silently no-ops whenever main
  547. isn't where the latest release lives — e.g. during a beta release cycle
  548. where the next stable hasn't been merged to main yet. Anchoring to the
  549. release tag instead lets the GUI install whatever GitHub says is latest.
  550. """
  551. result = await db.execute(select(Settings).where(Settings.key == "include_beta_updates"))
  552. beta_setting = result.scalar_one_or_none()
  553. include_beta = beta_setting and beta_setting.value.lower() == "true"
  554. if _seconds_until_github_unblocked() > 0:
  555. logger.warning("Skipping update target discovery: GitHub rate-limit backoff still active")
  556. return None
  557. try:
  558. async with httpx.AsyncClient() as client:
  559. response = await client.get(
  560. f"https://api.github.com/repos/{GITHUB_REPO}/releases?per_page=20",
  561. headers={"Accept": "application/vnd.github.v3+json"},
  562. timeout=10.0,
  563. )
  564. if _is_github_rate_limit_response(response):
  565. _record_github_rate_limit(response)
  566. return None
  567. response.raise_for_status()
  568. releases = response.json()
  569. except (httpx.HTTPError, ValueError) as exc:
  570. logger.error("Could not fetch GitHub releases for update target: %s", exc)
  571. return None
  572. for release in releases:
  573. tag = release.get("tag_name", "")
  574. if not tag:
  575. continue
  576. if include_beta:
  577. return tag
  578. # Skip prereleases (parsed from version, not GitHub flag — GitHub's
  579. # is_prerelease flag isn't always set on dailies).
  580. parsed = parse_version(tag)
  581. if parsed[4] == 0:
  582. return tag
  583. return None
  584. async def _perform_update(target_ref: str):
  585. """Perform the actual update using git fetch and reset.
  586. `target_ref` is whatever git ref the caller wants to land on — typically
  587. a release tag like `v0.2.4b1` resolved by `_discover_target_release`,
  588. but accepts any ref `git reset --hard` understands (`origin/main`, a
  589. branch, a sha). Tag-based refs are the production path because they pin
  590. the install to a specific release artifact instead of whatever happens
  591. to be on a moving branch.
  592. """
  593. global _update_status
  594. try:
  595. # Every git step runs against the working tree (app_dir), NOT base_dir.
  596. # On a standard install with DATA_DIR=INSTALL_PATH/data, git happens
  597. # to walk up from a subdirectory of the repo to find .git so cwd=base_dir
  598. # used to silently work — but only by accident. On a native install with
  599. # DATA_DIR mounted at an unrelated path (e.g. /srv/bambuddy/data while
  600. # the install is /opt/bambuddy — see #1715), git can't walk up and every
  601. # operation fails with "not a git repository". safe.directory has the
  602. # same requirement: it must equal the repo root git discovers, not the
  603. # data dir, or every call returns "fatal: detected dubious ownership."
  604. app_dir = settings.app_dir
  605. # Find git executable (may not be in PATH when running as systemd service)
  606. git_path = _find_executable("git")
  607. if not git_path:
  608. _update_status = {
  609. "status": "error",
  610. "progress": 0,
  611. "message": "Git not found",
  612. "error": "Could not find git executable. Please ensure git is installed.",
  613. }
  614. return
  615. logger.info("Using git at: %s", git_path)
  616. # Git config to avoid safe.directory issues — must point at the working
  617. # tree (where .git lives), see app_dir comment above.
  618. git_config = ["-c", f"safe.directory={app_dir}"]
  619. _update_status = {
  620. "status": "downloading",
  621. "progress": 10,
  622. "message": "Configuring git...",
  623. "error": None,
  624. }
  625. # Ensure remote points at the expected repo. We previously rewrote
  626. # origin to HTTPS unconditionally on the assumption that systemd
  627. # service users wouldn't have SSH keys configured — which is fine
  628. # for that case, but stomps on developer checkouts where origin is
  629. # legitimately `git@github.com:maziggy/bambuddy.git` and the user
  630. # auths via SSH keys. After the rewrite, `git push` prompts for
  631. # HTTPS credentials and fails.
  632. # New behaviour: read the current origin, parse out the
  633. # `<owner>/<repo>` pair, and only rewrite if it doesn't already
  634. # resolve to the right GitHub repo. SSH origins pointing at the
  635. # correct repo are preserved; only missing / wrong / corrupted
  636. # origins get reset to HTTPS.
  637. https_url = f"https://github.com/{GITHUB_REPO}.git"
  638. if not await _origin_points_at_repo(git_path, git_config, app_dir, GITHUB_REPO):
  639. process = await asyncio.create_subprocess_exec(
  640. git_path,
  641. *git_config,
  642. "remote",
  643. "set-url",
  644. "origin",
  645. https_url,
  646. cwd=str(app_dir),
  647. stdout=asyncio.subprocess.PIPE,
  648. stderr=asyncio.subprocess.PIPE,
  649. )
  650. await process.communicate()
  651. _update_status = {
  652. "status": "downloading",
  653. "progress": 20,
  654. "message": "Fetching latest changes...",
  655. "error": None,
  656. }
  657. # Fetch branches AND tags from origin so any ref the caller passes
  658. # (release tag like `v0.2.4b1`, a branch like `main`, or a sha) is
  659. # locally resolvable for the reset below. `--tags` is required —
  660. # plain `git fetch origin` doesn't bring tags by default, so a
  661. # release tag would not be resolvable.
  662. #
  663. # `--force` lets a moved tag on the remote overwrite the local copy.
  664. # Without it, any tag that was re-tagged upstream (e.g. v0.2.1 being
  665. # re-pointed after a hotfix re-tag) makes `git fetch --tags` return
  666. # a non-zero exit even though every other ref fetched cleanly —
  667. # which we'd then surface as "Failed to fetch updates" to the user.
  668. # The in-app updater's contract is "sync me to the remote"; force-
  669. # overwriting a stale local tag matches that intent.
  670. process = await asyncio.create_subprocess_exec(
  671. git_path,
  672. *git_config,
  673. "fetch",
  674. "--prune",
  675. "--tags",
  676. "--force",
  677. "origin",
  678. cwd=str(app_dir),
  679. stdout=asyncio.subprocess.PIPE,
  680. stderr=asyncio.subprocess.PIPE,
  681. )
  682. stdout, stderr = await process.communicate()
  683. if process.returncode != 0:
  684. error_msg = stderr.decode() if stderr else "Git fetch failed"
  685. logger.error("Git fetch failed: %s", error_msg)
  686. _update_status = {
  687. "status": "error",
  688. "progress": 0,
  689. "message": "Failed to fetch updates",
  690. "error": error_msg,
  691. }
  692. return
  693. _update_status = {
  694. "status": "downloading",
  695. "progress": 40,
  696. "message": "Applying updates...",
  697. "error": None,
  698. }
  699. # Hard reset to the target ref (clean update, no merge conflicts).
  700. # `target_ref` is typically a release tag like `v0.2.4b1` resolved
  701. # from the GitHub releases API by `_discover_target_release`. The
  702. # local branch name doesn't change — only HEAD moves. Falling back
  703. # to `origin/main` here was the source of the "in-app updater can't
  704. # reach beta releases" bug.
  705. process = await asyncio.create_subprocess_exec(
  706. git_path,
  707. *git_config,
  708. "reset",
  709. "--hard",
  710. target_ref,
  711. cwd=str(app_dir),
  712. stdout=asyncio.subprocess.PIPE,
  713. stderr=asyncio.subprocess.PIPE,
  714. )
  715. stdout, stderr = await process.communicate()
  716. if process.returncode != 0:
  717. error_msg = stderr.decode() if stderr else "Git reset failed"
  718. logger.error("Git reset failed: %s", error_msg)
  719. _update_status = {
  720. "status": "error",
  721. "progress": 0,
  722. "message": "Failed to apply updates",
  723. "error": error_msg,
  724. }
  725. return
  726. _update_status = {
  727. "status": "installing",
  728. "progress": 50,
  729. "message": "Installing dependencies...",
  730. "error": None,
  731. }
  732. # Install Python dependencies — must run from the source-code directory
  733. # (where requirements.txt lives). app_dir is already resolved at the top
  734. # of this function; see the comment there for why every step uses it
  735. # instead of base_dir.
  736. process = await asyncio.create_subprocess_exec(
  737. sys.executable,
  738. "-m",
  739. "pip",
  740. "install",
  741. "-r",
  742. "requirements.txt",
  743. "-q",
  744. cwd=str(app_dir),
  745. stdout=asyncio.subprocess.PIPE,
  746. stderr=asyncio.subprocess.PIPE,
  747. )
  748. stdout, stderr = await process.communicate()
  749. if process.returncode != 0:
  750. logger.warning("pip install warning: %s", stderr.decode() if stderr else "unknown")
  751. # Try to build frontend if npm is available (optional - static files are pre-built)
  752. npm_path = _find_executable("npm")
  753. frontend_dir = app_dir / "frontend"
  754. if npm_path and frontend_dir.exists():
  755. _update_status = {
  756. "status": "installing",
  757. "progress": 70,
  758. "message": "Building frontend...",
  759. "error": None,
  760. }
  761. # npm install
  762. process = await asyncio.create_subprocess_exec(
  763. npm_path,
  764. "install",
  765. cwd=str(frontend_dir),
  766. stdout=asyncio.subprocess.PIPE,
  767. stderr=asyncio.subprocess.PIPE,
  768. )
  769. await process.communicate()
  770. # npm run build
  771. process = await asyncio.create_subprocess_exec(
  772. npm_path,
  773. "run",
  774. "build",
  775. cwd=str(frontend_dir),
  776. stdout=asyncio.subprocess.PIPE,
  777. stderr=asyncio.subprocess.PIPE,
  778. )
  779. stdout, stderr = await process.communicate()
  780. if process.returncode != 0:
  781. logger.warning("Frontend build warning: %s", stderr.decode() if stderr else "unknown")
  782. else:
  783. logger.info("npm not found or frontend dir missing - using pre-built static files")
  784. _update_status = {
  785. "status": "complete",
  786. "progress": 100,
  787. "message": "Update complete! Please restart the application.",
  788. "error": None,
  789. }
  790. logger.info("Update completed successfully")
  791. except Exception as e:
  792. logger.error("Update failed: %s", e)
  793. _update_status = {
  794. "status": "error",
  795. "progress": 0,
  796. "message": "Update failed",
  797. "error": "Update failed unexpectedly",
  798. }
  799. @router.post("/apply")
  800. async def apply_update(
  801. background_tasks: BackgroundTasks,
  802. db: AsyncSession = Depends(get_db),
  803. _: User | None = RequirePermissionIfAuthEnabled(Permission.SETTINGS_UPDATE),
  804. ):
  805. """Apply available update (git pull + rebuild)."""
  806. global _update_status
  807. if _update_status["status"] in ["downloading", "installing"]:
  808. return {
  809. "success": False,
  810. "message": "Update already in progress",
  811. "status": _update_status,
  812. }
  813. # Check for managed deployment shapes that own the update lifecycle.
  814. # HA addons are also Docker, so check HA first to surface the more
  815. # specific message.
  816. if _is_ha_addon():
  817. return {
  818. "success": False,
  819. "is_ha_addon": True,
  820. "is_docker": True,
  821. "message": (
  822. "Bambuddy is running as a Home Assistant addon. "
  823. "Updates are managed by the Home Assistant Supervisor "
  824. "(Settings → Add-ons → Bambuddy → Update)."
  825. ),
  826. }
  827. if _is_docker_environment():
  828. return {
  829. "success": False,
  830. "is_docker": True,
  831. "message": (
  832. "Docker installations cannot be updated in-app. "
  833. "Please update via Docker Compose: "
  834. "git pull && docker compose build --pull && docker compose up -d"
  835. ),
  836. }
  837. if _is_windows_installer_install():
  838. # The installer layout has no ``.git`` and no bundled ``git.exe`` —
  839. # the git-fetch path would fail. Frontend swaps the "Update now"
  840. # button for a Download Installer link via update_method, so this
  841. # branch is only reached if /apply is hit directly.
  842. return {
  843. "success": False,
  844. "is_windows_installer": True,
  845. "message": (
  846. "Windows installations are updated by re-running the installer. "
  847. "Download the latest installer from the Bambuddy releases page."
  848. ),
  849. }
  850. # Discover which release tag to install. Resolved here (where we have
  851. # a DB session) and passed into the background task; the BG task can't
  852. # reuse this request's session since FastAPI closes it on response.
  853. target_ref = await _discover_target_release(db)
  854. if target_ref is None:
  855. return {
  856. "success": False,
  857. "message": (
  858. "Could not determine a release to install. Either GitHub is "
  859. "unreachable or no release matches your update channel "
  860. "(check the include_beta_updates setting)."
  861. ),
  862. }
  863. # Start update in background
  864. background_tasks.add_task(_perform_update, target_ref)
  865. _update_status = {
  866. "status": "downloading",
  867. "progress": 10,
  868. "message": "Starting update...",
  869. "error": None,
  870. }
  871. return {
  872. "success": True,
  873. "message": "Update started",
  874. "status": _update_status,
  875. }
  876. @router.get("/status")
  877. async def get_update_status(
  878. _: User | None = RequirePermissionIfAuthEnabled(Permission.SYSTEM_READ),
  879. ):
  880. """Get current update status."""
  881. return _update_status