diff --git a/frigate/app.py b/frigate/app.py index f31bd9828..db60be6eb 100644 --- a/frigate/app.py +++ b/frigate/app.py @@ -1,3 +1,4 @@ +import datetime import logging import multiprocessing as mp import os @@ -167,6 +168,15 @@ class FrigateApp: self.timeline_queue: Queue = mp.Queue() def init_database(self) -> None: + def vacuum_db(db: SqliteExtDatabase) -> None: + db.execute_sql("VACUUM;") + + try: + with open("/config/.vacuum", "w") as f: + f.write(datetime.datetime.now().timestamp()) + except PermissionError: + logger.error(f"Unable to write to /config to save DB state") + # Migrate DB location old_db_path = DEFAULT_DB_PATH if not os.path.isfile(self.config.database.path) and os.path.isfile( @@ -182,6 +192,24 @@ class FrigateApp: router = Router(migrate_db) router.run() + # check if vacuum needs to be run + if os.path.exists("/config/.vacuum"): + with open("/config/.vacuum") as f: + try: + timestamp = int(f.readline()) + except Exception: + timestamp = 0 + + if ( + timestamp + < ( + datetime.datetime.now() - datetime.timedelta(weeks=2) + ).timestamp() + ): + vacuum_db(migrate_db) + else: + vacuum_db(migrate_db) + migrate_db.close() def init_go2rtc(self) -> None: