From f9cb41c45bc46d64b9caac41ccfd94d28acb2b03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9ophile=20Diot?= Date: Tue, 28 May 2024 09:26:05 +0100 Subject: [PATCH] chore: Refactor Config.py to handle database read-only mode in autoconf --- src/autoconf/Config.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/autoconf/Config.py b/src/autoconf/Config.py index 5fb89bc89..9f1b9acb9 100644 --- a/src/autoconf/Config.py +++ b/src/autoconf/Config.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 +from contextlib import suppress from os import getenv from time import sleep from copy import deepcopy @@ -119,6 +120,10 @@ class Config(ConfigCaller): } ) + err = self.try_database_readonly() + if err: + return False + while not self._db.is_initialized(): self.__logger.warning("Database is not initialized, retrying in 5 seconds ...") sleep(5) @@ -162,3 +167,33 @@ class Config(ConfigCaller): self.__logger.error(f"An error occurred when setting the changes to checked in the database : {ret}") return success + + def _try_database_readonly(self) -> bool: + if not self.db.readonly: + try: + self.db.test_write() + except BaseException: + self.db.readonly = True + return True + + if self.db.database_uri and self.db.readonly: + try: + self.db.retry_connection(pool_timeout=1) + self.db.retry_connection(log=False) + self.db.readonly = False + self.__logger.info("The database is no longer read-only, defaulting to read-write mode") + except BaseException: + try: + self.db.retry_connection(readonly=True, pool_timeout=1) + self.db.retry_connection(readonly=True, log=False) + except BaseException: + if self.db.database_uri_readonly: + with suppress(BaseException): + self.db.retry_connection(fallback=True, pool_timeout=1) + self.db.retry_connection(fallback=True, log=False) + self.db.readonly = True + + if self.db.readonly: + self.__logger.error("Database is in read-only mode, configuration will not be saved") + + return self.db.readonly