Skip to content

Commit

Permalink
[FEAT] Enable support for multi-process pytwin import (#103)
Browse files Browse the repository at this point in the history
Co-authored-by: Lucas Boucinha <lboucin@ansys.com>
  • Loading branch information
lboucin and Lucas Boucinha authored Aug 25, 2023
1 parent c9898a4 commit 3f26221
Showing 1 changed file with 10 additions and 22 deletions.
32 changes: 10 additions & 22 deletions src/ansys/pytwin/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import shutil
import sys
import tempfile
import uuid


class PyTwinLogLevel(Enum):
Expand Down Expand Up @@ -234,8 +235,8 @@ def reinit_settings_for_unit_tests():
# Mutable attributes init
_PyTwinSettings.LOGGING_OPTION = None
_PyTwinSettings.LOGGING_LEVEL = None
_PyTwinSettings.MULTI_PROCESS_IS_ENABLED = False
_PyTwinSettings.WORKING_DIRECTORY_PATH = None
_PyTwinSettings.SESSION_ID = None
logging.getLogger(_PyTwinSettings.LOGGER_NAME).handlers.clear()
_PyTwinSettings().__init__()

Expand All @@ -250,7 +251,7 @@ class _PyTwinSettings(object):
# Mutable constants
LOGGING_OPTION = None
LOGGING_LEVEL = None
MULTI_PROCESS_IS_ENABLED = False
SESSION_ID = None
WORKING_DIRECTORY_PATH = None

# Immutable constants
Expand Down Expand Up @@ -344,26 +345,13 @@ def _initialize_wd():
"""
Provides default settings for the PyTwin working directory.
"""
# Clean the PyTwin temporary directory each time the pytwin package is imported.
if _PyTwinSettings.MULTI_PROCESS_IS_ENABLED:
pytwin_temp_dir = os.path.join(
tempfile.gettempdir(), str(os.getpid()), _PyTwinSettings.WORKING_DIRECTORY_NAME
)
else:
pytwin_temp_dir = os.path.join(tempfile.gettempdir(), _PyTwinSettings.WORKING_DIRECTORY_NAME)
for i in range(5):
# Loop to wait until logging file is freed
try:
if os.path.exists(pytwin_temp_dir):
shutil.rmtree(pytwin_temp_dir)
except PermissionError as e:
import time

logging.warning(f"_PyTwinSettings failed to clear the working directory (attempt #{i})! \n {str(e)}.")
time.sleep(1)

os.mkdir(pytwin_temp_dir)
_PyTwinSettings.WORKING_DIRECTORY_PATH = pytwin_temp_dir
# Create a unique working directory for each python process that imports pytwin
_PyTwinSettings.SESSION_ID = f"{uuid.uuid4()}"[0:24].replace("-", "")
pytwin_wd_dir = os.path.join(
tempfile.gettempdir(), _PyTwinSettings.WORKING_DIRECTORY_NAME, _PyTwinSettings.SESSION_ID
)
os.makedirs(pytwin_wd_dir)
_PyTwinSettings.WORKING_DIRECTORY_PATH = pytwin_wd_dir

@staticmethod
def _migration_due_to_new_wd(old_path: str, new_path: str):
Expand Down

0 comments on commit 3f26221

Please sign in to comment.