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

Implementing unique session id #1912

Merged
merged 62 commits into from
Jul 17, 2023
Merged
Show file tree
Hide file tree
Changes from 39 commits
Commits
Show all changes
62 commits
Select commit Hold shift + click to select a range
54b4372
First implementation of session_id
germa89 Mar 13, 2023
2ebdb90
Raising warning if lenght of string is GT 32 chars
germa89 Mar 13, 2023
fabd762
Merge branch 'fix/raise-warning-if-string-is-longer-than-32-chars' in…
germa89 Mar 13, 2023
704d962
Moving everything to the gRPC interface
germa89 Mar 13, 2023
9214dae
Adding unit tests
germa89 Mar 13, 2023
e50725f
Updating CICD
germa89 Mar 13, 2023
50ba295
Activating flag.
germa89 Mar 13, 2023
0658467
Fixing docstring
germa89 Mar 13, 2023
65e05c4
Merge branch 'fix/raise-warning-if-string-is-longer-than-32-chars' in…
germa89 Mar 13, 2023
047c136
Avoiding muting
germa89 Mar 13, 2023
c2d5f3f
Merge branch 'main' into feat/unique_session_id
germa89 Mar 13, 2023
7d6a26d
Fixing CI tests
germa89 Mar 13, 2023
7cb6e29
fixing wref attribute
germa89 Mar 13, 2023
82c0130
fixing call
germa89 Mar 13, 2023
0a291c2
Disabling muting
germa89 Mar 13, 2023
16d771f
Avoiding muting
germa89 Mar 13, 2023
742e2f8
Avoiding muting when connecting to a session
germa89 Mar 13, 2023
373f3bc
Using env vars for the pytest arguments.
germa89 Mar 14, 2023
71e0d3a
Forcing output
germa89 Mar 14, 2023
393879a
Using force output for getting mapdl session id.
germa89 Mar 14, 2023
4070222
Merge branch 'main' into feat/unique_session_id
germa89 Mar 14, 2023
d73262c
Avoiding recursion error
germa89 Mar 14, 2023
e6287b5
Avoid force_output
germa89 Mar 14, 2023
89f713b
Fixing test
germa89 Mar 14, 2023
8f5879f
Fixing wrong order of error catching
germa89 Mar 14, 2023
2e727c1
Getting read of an error
germa89 Mar 14, 2023
2ba46f9
Fixing raising many errors at test
germa89 Mar 14, 2023
19f2c7a
fixing double raises
germa89 Mar 14, 2023
9665723
Merge branch 'main' into feat/unique_session_id
germa89 Mar 14, 2023
c314b4f
Removing comments
germa89 Mar 14, 2023
507cca5
Renaming variables to avoid privates.
germa89 Mar 14, 2023
064ab28
Merge branch 'main' into feat/unique_session_id
germa89 Mar 14, 2023
ae02445
adding check id to startget
germa89 Mar 14, 2023
2924b37
Merge branch 'main' into feat/unique_session_id
germa89 Apr 24, 2023
86654be
Merge branch 'main' into feat/unique_session_id
akaszynski Apr 24, 2023
2f0adec
Apply suggestions from code review
akaszynski Apr 24, 2023
20898e5
Merge branch 'main' into feat/unique_session_id
germa89 Apr 25, 2023
a5f2a37
fixing typo
germa89 Apr 25, 2023
8407ad8
Merge branch 'main' into feat/unique_session_id
akaszynski Apr 25, 2023
21a9262
Merge branch 'main' into feat/unique_session_id
germa89 May 3, 2023
14dc0ff
Merge branch 'main' into feat/unique_session_id
germa89 May 5, 2023
bf823b0
Merge branch 'main' into feat/unique_session_id
germa89 May 5, 2023
a85a06c
Merge branch 'main' into feat/unique_session_id
germa89 Jun 16, 2023
d6dd597
Merge branch 'main' into feat/unique_session_id
germa89 Jun 22, 2023
2320f27
Merge branch 'main' into feat/unique_session_id
germa89 Jul 3, 2023
d22c334
Removing outdated arg
germa89 Jul 3, 2023
aaacd49
Replacing `_RUNNING_TESTS` by `RUNNING_TESTS`
germa89 Jul 3, 2023
85333b7
fixing not creating session id after failed example
germa89 Jul 3, 2023
f51869d
Force recreating session when using clean.
germa89 Jul 3, 2023
db7fec1
test
germa89 Jul 3, 2023
e6df5cd
Undoing ci pytest configuration changes
germa89 Jul 4, 2023
91909ea
Update tests/conftest.py
germa89 Jul 4, 2023
a16effe
fixing missing import
germa89 Jul 4, 2023
d3f3f08
Improving `running_test` context manager.
germa89 Jul 4, 2023
952f4ea
Merge branch 'feat/unique_session_id' of https://github.com/pyansys/p…
germa89 Jul 4, 2023
a40c226
Merge branch 'main' into feat/unique_session_id
germa89 Jul 4, 2023
ce4dbd0
fixing bracket test
germa89 Jul 5, 2023
d9e9e46
Merge branch 'main' into feat/unique_session_id
germa89 Jul 12, 2023
fadef4f
Bypassing error
germa89 Jul 14, 2023
8481df1
Adding more static typing
germa89 Jul 14, 2023
7277c2a
fixing tests
germa89 Jul 14, 2023
734c1fa
Merge branch 'main' into feat/unique_session_id
germa89 Jul 17, 2023
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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ env:
DOCKER_PACKAGE: ghcr.io/pyansys/mapdl
DOCKER_IMAGE_VERSION_DOCS_BUILD: v23.1.0
ON_CI: True
PYTEST_ARGUMENTS: '-vv --durations=10 --maxfail=10 --reruns 7 --reruns-delay 5 --cov=ansys.mapdl.core --cov-report=html'
PYTEST_ARGUMENTS: '-vv --durations=10 --maxfail=10 --reruns 7 --cov=ansys.mapdl.core --cov-report=html --only-rerun MapdlExitedError --only-rerun DifferentSessionConnectionError --only-rerun EmptyRecordError --reruns-delay 3'

# Following env vars when changed will "reset" the mentioned cache,
# by changing the cache file name. It is rendered as ...-v%RESET_XXX%-...
Expand Down
5 changes: 5 additions & 0 deletions src/ansys/mapdl/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
LOG = Logger(level=logging.ERROR, to_file=False, to_stdout=True)
LOG.debug("Loaded logging module as LOG")

_RUNNING_ON_PYTEST = False

if _RUNNING_ON_PYTEST:
LOG.debug("Running tests on Pytest")

_LOCAL_PORTS = []


Expand Down
7 changes: 7 additions & 0 deletions src/ansys/mapdl/core/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,13 @@ def __init__(self, msg=""):
MapdlRuntimeError.__init__(self, msg)


class DifferentSessionConnectionError(RuntimeError):
"""Provides the error when connecting to the MAPDL instance fails."""

def __init__(self, msg=""):
RuntimeError.__init__(self, msg)


# handler for protect_grpc
def handler(sig, frame): # pragma: no cover
"""Pass signal to custom interrupt handler."""
Expand Down
12 changes: 12 additions & 0 deletions src/ansys/mapdl/core/mapdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -2902,6 +2902,9 @@ def run(self, command, write_to_log=True, mute=None, **kwargs) -> str:
>>> mapdl.prep7()

"""
if self._session_id is not None:
self._check_session_id()

if mute is None:
if hasattr(self, "mute"):
mute = self.mute
Expand Down Expand Up @@ -2974,6 +2977,10 @@ def run(self, command, write_to_log=True, mute=None, **kwargs) -> str:
verbose = kwargs.get("verbose", False)
text = self._run(command, verbose=verbose, mute=mute)

if command[:4].upper() == "/CLE" and self.is_grpc:
# We have reset the database, so we need to create a new session id
self._create_session()

if mute:
return

Expand Down Expand Up @@ -3988,6 +3995,11 @@ def _raise_output_errors(self, response):
[each for each in error_message.splitlines() if each]
)

# Trimming empty lines
error_message = "\n".join(
[each for each in error_message.splitlines() if each]
)

# Checking for permitted error.
for each_error in _PERMITTED_ERRORS:
permited_error_message = re.search(each_error, error_message)
Expand Down
71 changes: 70 additions & 1 deletion src/ansys/mapdl/core/mapdl_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import threading
import time
from typing import Optional
from uuid import uuid4
import warnings
from warnings import warn
import weakref
Expand All @@ -39,14 +40,15 @@
except ImportError: # pragma: no cover
raise ImportError(MSG_IMPORT)

from ansys.mapdl.core import _LOCAL_PORTS, __version__
from ansys.mapdl.core import _LOCAL_PORTS, _RUNNING_ON_PYTEST, __version__
from ansys.mapdl.core.common_grpc import (
ANSYS_VALUE_TYPE,
DEFAULT_CHUNKSIZE,
DEFAULT_FILE_CHUNK_SIZE,
parse_chunks,
)
from ansys.mapdl.core.errors import (
DifferentSessionConnectionError,
MapdlConnectionError,
MapdlExitedError,
MapdlRuntimeError,
Expand All @@ -62,6 +64,8 @@
run_as_prep7,
supress_logging,
)
from ansys.mapdl.core.parameters import interp_star_status
from ansys.mapdl.core.post import PostProcessing

# Checking if tqdm is installed.
# If it is, the default value for progress_bar is true.
Expand All @@ -81,6 +85,9 @@
VAR_IR = 9 # Default variable number for automatic variable retrieving (/post26)


SESSION_ID_NAME = "__PYMAPDL_SESSION_ID__"


def chunk_raw(raw, save_as):
with io.BytesIO(raw) as f:
while True:
Expand Down Expand Up @@ -300,6 +307,8 @@ def __init__(

self.__distributed = None
self._remote_instance = remote_instance
self._session_id_ = None
self._checking_session_id_ = False

if channel is not None:
if ip is not None or port is not None:
Expand Down Expand Up @@ -415,6 +424,8 @@ def __init__(
if self._local and "exec_file" in start_parm:
self._cache_pids()

self._create_session()

def _create_process_stds_queue(self, process=None):
from ansys.mapdl.core.launcher import (
_create_queue_for_std, # Avoid circular import error
Expand Down Expand Up @@ -1977,6 +1988,9 @@ def _get(
Not thread safe. Uses ``_get_lock`` to ensure multiple
request are not evaluated simultaneously.
"""
if self._session_id is not None:
self._check_session_id()

if self._store_commands:
raise MapdlRuntimeError(
"Cannot use gRPC enabled ``GET`` when in non_interactive mode. "
Expand Down Expand Up @@ -3146,3 +3160,58 @@ def get_esol(
)
# Using get_variable because it deletes the intermediate parameter after using it.
return self.get_variable(VAR_IR, tstrt=tstrt, kcplx=kcplx)

def _create_session(self):
akaszynski marked this conversation as resolved.
Show resolved Hide resolved
"""Generate a session ID."""
id_ = uuid4()
germa89 marked this conversation as resolved.
Show resolved Hide resolved
id_ = str(id_)[:31].replace("-", "")
self._session_id_ = id_
self._run(f"{SESSION_ID_NAME}='{id_}'")

@property
def _session_id(self):
akaszynski marked this conversation as resolved.
Show resolved Hide resolved
"""Return the session ID."""
return self._session_id_

def _check_session_id(self):
akaszynski marked this conversation as resolved.
Show resolved Hide resolved
"""Verify that the local session ID matches the remote MAPDL session ID."""
if self._checking_session_id_:
# To avoid recursion error
return

pymapdl_session_id = self._session_id
if not pymapdl_session_id:
# We return early if pymapdl_session is not fixed yet.
return

self._checking_session_id_ = True
self._mapdl_session_id = self._get_mapdl_session_id()
self._checking_session_id_ = False

if pymapdl_session_id is None:
return
elif _RUNNING_ON_PYTEST:
if pymapdl_session_id != self._mapdl_session_id:
self._log.error("The session ids do not match")
raise DifferentSessionConnectionError(
f"Local MAPDL session ID {pymapdl_session_id} is different from MAPDL session ID {self._mapdl_session_id}."
)

else:
self._log.debug("The session ids match")
return True
else:
return pymapdl_session_id == self._mapdl_session_id

def _get_mapdl_session_id(self):
"""Retrieve MAPDL session ID."""
try:
parameter = interp_star_status(
self._run(f"*STATUS,{SESSION_ID_NAME}", mute=False)
)
except AttributeError:
return None

if parameter:
return parameter[SESSION_ID_NAME]["value"]
return None
17 changes: 8 additions & 9 deletions src/ansys/mapdl/core/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,14 +280,16 @@ def type(self) -> int:
@supress_logging
def _parm(self):
"""Current MAPDL parameters"""
params = interp_star_status(self._mapdl.starstatus(avoid_non_interactive=True))
params = interp_star_status(
self._mapdl.starstatus(avoid_non_interactive=True, mute=False)
)

if self.show_leading_underscore_parameters:
_params = interp_star_status(self._mapdl.starstatus("_PRM"))
_params = interp_star_status(self._mapdl.starstatus("_PRM", mute=False))
params.update(_params)

if self.show_trailing_underscore_parameters:
params_ = interp_star_status(self._mapdl.starstatus("PRM_"))
params_ = interp_star_status(self._mapdl.starstatus("PRM_", mute=False))
params.update(params_)

return params
Expand Down Expand Up @@ -323,11 +325,8 @@ def __getitem__(self, key):
try:
val_ = interp_star_status(self._mapdl.starstatus(key))
val_ = val_[list(val_.keys())[0]]["value"]
if len(val_) == 1:
return val_[0]
else:
return val_
return
return val_[0] if len(val_) == 1 else val_

except MapdlRuntimeError:
raise IndexError("%s not a valid parameter_name" % key)

Expand Down Expand Up @@ -650,7 +649,7 @@ def interp_star_status(status):
return {}

# If there is a general call to *STATUS (no arguments), the output has some extra
# parameters that we don't want to include in the analysis.
# text that we don't want to include in the output.
ind = find_parameter_listing_line(status)
status = "\n".join(status.splitlines()[ind:])

Expand Down
5 changes: 4 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@
from ansys.tools.path import find_ansys, get_available_ansys_installations
import pyvista

from ansys.mapdl import core as pymapdl
import ansys.mapdl.core as pymapdl

pymapdl._RUNNING_ON_PYTEST = True

from ansys.mapdl.core.errors import MapdlExitedError
from ansys.mapdl.core.examples import vmfiles
from ansys.mapdl.core.launcher import (
Expand Down
31 changes: 31 additions & 0 deletions tests/test_mapdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
MapdlRuntimeError,
)
from ansys.mapdl.core.launcher import get_start_instance, launch_mapdl
from ansys.mapdl.core.mapdl_grpc import SESSION_ID_NAME
from ansys.mapdl.core.misc import random_string

skip_in_cloud = pytest.mark.skipif(
Expand Down Expand Up @@ -1860,6 +1861,36 @@ def test_force_output(mapdl):
assert mapdl.prep7()


def test_session_id(mapdl):
assert mapdl._session_id is not None

# already checking version
mapdl._checking_session_id_ = True
assert mapdl._check_session_id() is None

# Not having pymapdl session id
mapdl._checking_session_id_ = False
copy_ = mapdl._session_id_
mapdl._session_id_ = None
assert mapdl._check_session_id() is None

# Checking real case
mapdl._session_id_ = copy_
pymapdl._RUNNING_ON_PYTEST = False
assert isinstance(mapdl._check_session_id(), bool)
pymapdl._RUNNING_ON_PYTEST = True

id_ = "123412341234"
mapdl._session_id_ = id_
mapdl._run(f"{SESSION_ID_NAME}='{id_}'")
assert mapdl._check_session_id()

mapdl._session_id_ = "qwerqwerqwer"
assert not mapdl._check_session_id()

mapdl._session_id_ = id_


def test_igesin_whitespace(mapdl, cleared, tmpdir):
bracket_file = pymapdl.examples.download_bracket()
assert os.path.isfile(bracket_file)
Expand Down