Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable support for multi-process pytwin import #103

Merged
merged 5 commits into from
Aug 25, 2023
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading