diff libervia/backend/core/main.py @ 4266:9fc3d28bc3f6

core (main): add a mechanism to have a shared temp directory: this directory may be used to share files between backend and frontends. Normally, an os-dependent temporary directory is created for that, but if this option is set, the directory will be created in <local_dir>/<cache_dir>, which may be useful in some use case (e.g. containerized frontends and backend).
author Goffi <goffi@goffi.org>
date Wed, 12 Jun 2024 22:47:34 +0200
parents e11b13418ba6
children 0d7bb4df2343
line wrap: on
line diff
--- a/libervia/backend/core/main.py	Wed Jun 12 22:37:04 2024 +0200
+++ b/libervia/backend/core/main.py	Wed Jun 12 22:47:34 2024 +0200
@@ -22,6 +22,7 @@
 import hashlib
 import copy
 from pathlib import Path
+import shutil
 from typing import Optional, List, Tuple, Dict, cast
 
 from wokkel.data_form import Option
@@ -104,6 +105,22 @@
             log.exception("bridge can't be initialised, can't start Libervia Backend")
             sys.exit(1)
 
+        # If set, a temporary dir in cache will be used to share files between backend and
+        # frontends, useful when they are separated (e.g. when using containers). If
+        # unset, a temporary dir will be automatically created in os-relevant location.
+        use_local_shared_tmp: bool = C.bool(
+            self.memory.config_get("", "use_local_shared_tmp", C.BOOL_FALSE)
+        )
+        if use_local_shared_tmp:
+            self.local_shared_path = self.get_local_path(
+                None, C.CACHE_DIR, C.LOCAL_SHARED_DIR
+            )
+            shutil.rmtree(self.local_shared_path, ignore_errors=True)
+            self.local_shared_path.mkdir(0o700, parents=True, exist_ok=True)
+        else:
+            self.local_shared_path = None
+
+
         defer.ensureDeferred(self._post_init())
 
     @property
@@ -647,7 +664,11 @@
         log.info("Salut à toi ô mon frère !")
 
     def stopService(self):
-        log.info("Salut aussi à Rantanplan")
+        if self.local_shared_path is not None:
+            log.debug("Cleaning shared temporary dir.")
+            shutil.rmtree(self.local_shared_path, ignore_errors=True)
+        log.info("Salut aussi à Rantanplan.")
+
         return self.plugins_unload()
 
     def run(self):