commit 5678036c2b43afbfdca48b62caacce75740965d8
Author: David Friesecký <frieseck@students.zcu.cz>
Date:   Wed May 12 15:56:48 2021 +0200

    Re #8880 - Edited config file (inserted RootDir)
    - improved creating of logs and db directories

diff --git a/app.py b/app.py
index f08c97f..cd8a2e0 100644
--- a/app.py
+++ b/app.py
@@ -14,6 +14,7 @@ from src.controllers.exception_handlers import handle_cryptography_exception, ha
     handle_generic_exception
 from src.exceptions.database_exception import DatabaseException
 from src.services.cryptography import CryptographyService, CryptographyException
+from src.utils import logger
 from src.utils.logger import Logger
 
 app = Flask(__name__)
@@ -126,7 +127,7 @@ def initialize_app(application) -> bool:
     FlaskInjector(app=application, modules=modules)
 
     config = injector.get(Configuration)
-    configuration.configure_logging(config)
+    logger.configure_logging(config)
 
     Logger.info(f"Using configuration file: {config.config_file}")
 
diff --git a/src/config/configuration.py b/src/config/configuration.py
index d994be5..fe4b638 100644
--- a/src/config/configuration.py
+++ b/src/config/configuration.py
@@ -2,14 +2,11 @@ import os
 
 import configparser
 import logging
-from logging import handlers
 
-from injector import singleton, inject
+from injector import singleton
 
-from src.constants import DEFAULT_CONNECTION_STRING, TEST_DATABASE_FILE, DEFAULT_SERVER_BASE_URL, LOG_NAME, \
-    LOG_DIR, DEFAULT_LOG_LEVEL, LOG_FILENAME
-from src.constants import LOG_FILE_LOCATION, LOG_FORMAT
-from src.utils.logger import Logger
+from src.constants import DEFAULT_CONNECTION_STRING, TEST_DATABASE_FILE, DEFAULT_SERVER_BASE_URL, \
+    DEFAULT_LOG_LEVEL, DEFAULT_ROOT_DIR
 
 DATABASE_SECTION = "Database"
 DATABASE_CONNECTION_STRING = "ConnectionString"
@@ -17,6 +14,7 @@ DATABASE_CONNECTION_STRING = "ConnectionString"
 SERVER_SECTION = "Server"
 SERVER_BASE_URL = "ServerBaseURL"
 SERVER_LOG_LEVEL = "LogLevel"
+SERVER_ROOT_DIR = "RootDir"
 
 LOG_LEVEL_MAPPING = {
     "DEBUG": logging.DEBUG,
@@ -42,6 +40,7 @@ class Configuration:
         self.connection_string = DEFAULT_CONNECTION_STRING
         self.base_server_url = DEFAULT_SERVER_BASE_URL
         self.log_level = DEFAULT_LOG_LEVEL
+        self.root_dir = DEFAULT_ROOT_DIR
 
 
 def test_configuration():
@@ -79,26 +78,6 @@ def configure_env_variable(binder):
             app_configuration.base_server_url = server_config.get(SERVER_BASE_URL,
                                                                   DEFAULT_SERVER_BASE_URL)
             app_configuration.log_level = server_config.get(SERVER_LOG_LEVEL, DEFAULT_LOG_LEVEL)
+            app_configuration.root_dir = server_config.get(SERVER_ROOT_DIR, DEFAULT_ROOT_DIR)
 
     binder.bind(Configuration, to=app_configuration, scope=singleton)
-
-
-def configure_logging(config: Configuration):
-    if not os.path.exists(LOG_DIR):
-        os.makedirs(LOG_DIR)
-
-    handler = logging.handlers.TimedRotatingFileHandler(
-        os.path.join(LOG_DIR, LOG_FILENAME),
-        when='H', interval=1)
-    formatter = logging.Formatter(LOG_FORMAT)
-    handler.setFormatter(formatter)
-
-    # set log level based on config file
-    app_logger = logging.getLogger(LOG_NAME)
-    app_logger.setLevel(LOG_LEVEL_MAPPING.get(config.log_level, logging.DEBUG))
-
-    app_logger.addHandler(handler)
-
-    # TODO check is 'valid'
-    log = logging.getLogger('werkzeug')
-    log.disabled = True
diff --git a/src/config/connection_provider.py b/src/config/connection_provider.py
index 63d2ff3..24a14fd 100644
--- a/src/config/connection_provider.py
+++ b/src/config/connection_provider.py
@@ -5,9 +5,9 @@ from sqlite3 import Connection
 from injector import Module, provider, singleton
 
 from src.config.configuration import Configuration
-from src.constants import DB_DIR
+from src.constants import DB_DIR, TEST_DATABASE_FILE
 from src.db.init_queries import DEFAULT_VALUES_SQL, CHECK_SCHEMA_SQL
-from src.db.setup_database import setup_database
+from src.utils.file_anchor import FileAnchor
 from src.utils.logger import Logger
 
 
@@ -28,8 +28,9 @@ class ConnectionProvider(Module):
         Logger.debug(f"Creating a database connection [{configuration.connection_string}].")
 
         try:
-            if not os.path.exists(DB_DIR):
-                os.makedirs(DB_DIR)
+            if not os.path.exists(FileAnchor(configuration.root_dir, DB_DIR).shortest_relative_path()) and \
+                    configuration.connection_string != TEST_DATABASE_FILE:
+                os.makedirs(FileAnchor(configuration.root_dir, DB_DIR).shortest_relative_path())
 
             co = sqlite3.connect(database=configuration.connection_string, check_same_thread=False)
             cu = co.cursor()
diff --git a/src/constants.py b/src/constants.py
index 3e03b6a..b046d1b 100644
--- a/src/constants.py
+++ b/src/constants.py
@@ -1,16 +1,12 @@
-from src.utils.file_anchor import FileAnchor
-
+# Database
 INMEMORY_DATABASE_FILE = ":memory:"
 TEST_DATABASE_FILE = INMEMORY_DATABASE_FILE
 DB_DIR = "db"
-DATABASE_FILE = f"{DB_DIR}/database_sqlite.db"
-DATABASE_FILE_LOCATION = FileAnchor("aswi2021jmsd", DATABASE_FILE)
 DATETIME_FORMAT = "%d.%m.%Y %H:%M:%S"
 
+# Logging
 LOG_DIR = "logs"
 LOG_FILENAME = "application.log"
-LOG_FILE = f"{LOG_DIR}/{LOG_FILENAME}"
-LOG_FILE_LOCATION = FileAnchor("aswi2021jmsd", LOG_FILE)
 LOG_FORMAT = "%(levelname)-8s %(asctime)s - %(message)s"
 LOG_NAME = "app_logger"
 
@@ -69,6 +65,7 @@ COL_USAGE_TYPE_ID = "usage_type_id"
 DEFAULT_CONNECTION_STRING = "db/database_sqlite.db"
 DEFAULT_SERVER_BASE_URL = "http://localhost"
 DEFAULT_LOG_LEVEL = "DEBUG"
+DEFAULT_ROOT_DIR = "aswi2021jmsd"
 
 # available certificate states and revocation reasons
 CERTIFICATE_STATES = {"valid", "revoked"}
diff --git a/src/db/setup_database.py b/src/db/setup_database.py
deleted file mode 100644
index a713b41..0000000
--- a/src/db/setup_database.py
+++ /dev/null
@@ -1,31 +0,0 @@
-import os
-import sqlite3
-from pathlib import Path
-
-from src.constants import DATABASE_FILE_LOCATION, DB_DIR
-from src.db.init_queries import SCHEMA_SQL, DEFAULT_VALUES_SQL
-from src.utils.logger import Logger
-
-
-def setup_database():
-    Logger.debug(f"Database is setting.")
-
-    try:
-        # TODO improve creating DB dir
-        if not os.path.exists(DB_DIR):
-            os.makedirs("../../" + DB_DIR)
-
-        # TODO improve creating DB file (now via FileAnchor)
-        co = sqlite3.connect(DATABASE_FILE_LOCATION.shortest_relative_path())
-        cu = co.cursor()
-        cu.executescript(SCHEMA_SQL)
-        cu.executescript(DEFAULT_VALUES_SQL)
-    except sqlite3.Error as e:
-        Logger.error(f"Unknown error during database setting.")
-        raise e
-
-    return co
-
-
-if __name__ == '__main__':
-    setup_database()
diff --git a/src/utils/logger.py b/src/utils/logger.py
index 496ab05..7ae4610 100644
--- a/src/utils/logger.py
+++ b/src/utils/logger.py
@@ -1,8 +1,32 @@
 import inspect
 import logging
+from logging import handlers
+import os
 from pathlib import Path
 
-from src.constants import LOG_NAME
+from src.config.configuration import Configuration, LOG_LEVEL_MAPPING
+from src.constants import LOG_NAME, LOG_DIR, LOG_FILENAME, LOG_FORMAT
+from src.utils.file_anchor import FileAnchor
+
+
+def configure_logging(config: Configuration):
+    if not os.path.exists(FileAnchor(config.root_dir, LOG_DIR).shortest_relative_path()):
+        os.makedirs(FileAnchor(config.root_dir, LOG_DIR).shortest_relative_path())
+
+    handler = logging.handlers.TimedRotatingFileHandler(
+        os.path.join(FileAnchor(config.root_dir, LOG_DIR).shortest_relative_path(), LOG_FILENAME),
+        when='H', interval=1)
+    formatter = logging.Formatter(LOG_FORMAT)
+    handler.setFormatter(formatter)
+
+    # set log level based on config file
+    app_logger = logging.getLogger(LOG_NAME)
+    app_logger.setLevel(LOG_LEVEL_MAPPING.get(config.log_level, logging.DEBUG))
+
+    app_logger.addHandler(handler)
+
+    log = logging.getLogger('werkzeug')
+    log.disabled = True
 
 
 class Logger:
diff --git a/test_server.cfg b/test_server.cfg
index 7340917..863a148 100644
--- a/test_server.cfg
+++ b/test_server.cfg
@@ -4,3 +4,4 @@ ConnectionString=db/database_sqlite.db
 [Server]
 ServerBaseURL=http://78.128.250.101
 LogLevel=DEBUG
+RootDir=app
