From fc3ace56c64058d559689dd31927f5567ef2823b Mon Sep 17 00:00:00 2001 From: Josh Hawkins <32435876+hawkeye217@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:24:02 -0600 Subject: [PATCH] stop at startup when the database location isn't writable The ownership sweep only covers /config and /media/frigate, so a database.path on another volume stayed root-owned after upgrading and Frigate boot-looped on a SQLite error. Frigate now checks the database directory and files before opening them and exits with an error naming the path, the runtime uid/gid, and the new docs section. backup.db is checked only when a migration is about to write it. --- docs/docs/configuration/non_root.md | 10 ++++++ frigate/app.py | 42 +++++++++++++++++------- frigate/test/test_ownership.py | 50 +++++++++++++++++++++++++++++ frigate/util/ownership.py | 18 +++++++++++ 4 files changed, 108 insertions(+), 12 deletions(-) diff --git a/docs/docs/configuration/non_root.md b/docs/docs/configuration/non_root.md index bdef2d9001..4fe88f8dec 100644 --- a/docs/docs/configuration/non_root.md +++ b/docs/docs/configuration/non_root.md @@ -86,6 +86,16 @@ Once the volumes are aligned, start Frigate normally. A file at `/config/.permis If something under your volumes can't be chowned, a read-only btrfs snapshot directory for example, the sweep warns and names the path and doesn't record the migration as finished. It retries on the next boot instead. Either move those paths outside `/media/frigate` or expect the scan to repeat. +### Custom database location + +The sweep only covers `/config` and `/media/frigate`. If `database.path` points somewhere else, such as a separate volume, align that directory yourself before upgrading, and again after running with `FRIGATE_RUN_AS_ROOT=true`: + +```bash +chown -R 1000:1000 /path/to/your/database/dir +``` + +Use your `PUID` and `PGID` if you've changed them. Until the directory and its files are writable, Frigate stops at startup with an error naming the path it can't write. + ### Network storage Recordings on a NAS behave differently, so check what you have before migrating: diff --git a/frigate/app.py b/frigate/app.py index b4fedbe8d0..ea698e2150 100644 --- a/frigate/app.py +++ b/frigate/app.py @@ -4,6 +4,7 @@ import multiprocessing as mp import os import secrets import shutil +import sys from collections.abc import Callable from multiprocessing import Queue from multiprocessing.managers import DictProxy, SyncManager @@ -91,7 +92,7 @@ from frigate.timeline import TimelineProcessor from frigate.track.object_processing import TrackedObjectProcessor from frigate.util.builtin import empty_and_close_queue from frigate.util.image import UntrackedSharedMemory -from frigate.util.ownership import chown_to_runtime +from frigate.util.ownership import chown_to_runtime, find_unwritable_database_path from frigate.util.process import FrigateProcess from frigate.util.runtime_deps import RuntimeDependencyError from frigate.util.services import set_file_limit @@ -197,8 +198,32 @@ class FrigateApp: except PermissionError: logger.error("Unable to write to /config to save DB state") + def exit_if_unwritable(paths: tuple[str, ...]) -> None: + unwritable = find_unwritable_database_path(paths) + + if unwritable is None: + return + + logger.error( + "Frigate is running as uid %s, gid %s and can't write to %s. Make " + "sure it exists and is owned by that user, see " + "https://docs.frigate.video/configuration/non_root#custom-database-location", + os.getuid(), + os.getgid(), + unwritable, + ) + sys.exit(1) + + db_path = self.config.database.path + backup_path = db_path.replace("frigate.db", "backup.db") + db_files = (db_path, f"{db_path}-wal", f"{db_path}-shm", backup_path) + + # the ownership sweep covers /config and /media/frigate only, so a + # database kept elsewhere can still be owned by root after upgrading + exit_if_unwritable(db_files[:3]) + # Migrate DB schema - migrate_db = SqliteDatabase(self.config.database.path) + migrate_db = SqliteDatabase(db_path) # Run migrations del logging.getLogger("peewee_migrate").handlers[:] @@ -206,10 +231,8 @@ class FrigateApp: if len(router.diff) > 0: logger.info("Making backup of DB before migrations...") - shutil.copyfile( - self.config.database.path, - self.config.database.path.replace("frigate.db", "backup.db"), - ) + exit_if_unwritable((backup_path,)) + shutil.copyfile(db_path, backup_path) router.run() @@ -235,12 +258,7 @@ class FrigateApp: # a root frigate service creates these as root; wal and shm recreated # later in the run are realigned by the per-boot /config sweep - for db_file in ( - self.config.database.path, - f"{self.config.database.path}-wal", - f"{self.config.database.path}-shm", - self.config.database.path.replace("frigate.db", "backup.db"), - ): + for db_file in db_files: if os.path.exists(db_file): chown_to_runtime(db_file) diff --git a/frigate/test/test_ownership.py b/frigate/test/test_ownership.py index 529c6e2cab..0e605119a6 100644 --- a/frigate/test/test_ownership.py +++ b/frigate/test/test_ownership.py @@ -1,5 +1,7 @@ """Tests for runtime ownership helpers.""" +import os +import tempfile import unittest from unittest.mock import patch @@ -73,5 +75,53 @@ class TestChownToRuntime(unittest.TestCase): ownership.chown_to_runtime("/config/test") # must not raise +class TestFindUnwritableDatabasePath(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.db_dir = os.path.join(tmp.name, "db") + os.mkdir(self.db_dir) + # restore access so cleanup can remove the tree + self.addCleanup(os.chmod, self.db_dir, 0o755) + self.db_path = os.path.join(self.db_dir, "frigate.db") + self.db_files = ( + self.db_path, + f"{self.db_path}-wal", + f"{self.db_path}-shm", + os.path.join(self.db_dir, "backup.db"), + ) + + def test_writable_directory_without_database(self): + assert ownership.find_unwritable_database_path(self.db_files) is None + + def test_writable_directory_and_database(self): + open(self.db_path, "w").close() + assert ownership.find_unwritable_database_path(self.db_files) is None + + def test_missing_directory(self): + missing_dir = os.path.join(self.db_dir, "missing") + db_files = (os.path.join(missing_dir, "frigate.db"),) + assert ownership.find_unwritable_database_path(db_files) == missing_dir + + @unittest.skipIf(os.geteuid() == 0, "root bypasses permission checks") + def test_unwritable_directory(self): + os.chmod(self.db_dir, 0o555) + assert ownership.find_unwritable_database_path(self.db_files) == self.db_dir + + @unittest.skipIf(os.geteuid() == 0, "root bypasses permission checks") + def test_unwritable_database(self): + open(self.db_path, "w").close() + os.chmod(self.db_path, 0o444) + assert ownership.find_unwritable_database_path(self.db_files) == self.db_path + + @unittest.skipIf(os.geteuid() == 0, "root bypasses permission checks") + def test_unwritable_backup(self): + backup = self.db_files[3] + open(self.db_path, "w").close() + open(backup, "w").close() + os.chmod(backup, 0o444) + assert ownership.find_unwritable_database_path(self.db_files) == backup + + if __name__ == "__main__": unittest.main() diff --git a/frigate/util/ownership.py b/frigate/util/ownership.py index e1b9cc236c..c4fbe50ae2 100644 --- a/frigate/util/ownership.py +++ b/frigate/util/ownership.py @@ -45,3 +45,21 @@ def chown_to_runtime(path: str) -> None: os.chown(path, *ids) except OSError as err: logger.warning(f"Unable to set ownership of {path}: {err}") + + +def find_unwritable_database_path(db_files: tuple[str, ...]) -> str | None: + """Return the database directory or file the current user can't write, if any. + + db_files starts with the database itself. SQLite creates its -wal and -shm + files next to it, so the directory has to be writable too. + """ + db_dir = os.path.dirname(os.path.abspath(db_files[0])) + + if not os.access(db_dir, os.W_OK | os.X_OK): + return db_dir + + for path in db_files: + if os.path.exists(path) and not os.access(path, os.R_OK | os.W_OK): + return path + + return None