Skip to content

Commit

Permalink
Fixed a merge issue. Allowed server version to be set by the user via…
Browse files Browse the repository at this point in the history
… the new changes, rather than always the latest version. Client used to raise 2 exceptions if Sherlock did not start. One was for sherlock not starting and another was that it was unable to connect to Sherlock. Now it will raise 1 exception. If Sherlock cannot start it will raise that exception. If Sherlock starts but PySherlock cannot connect it will raise that exception.
  • Loading branch information
anskhanson committed Nov 7, 2024
1 parent f73d5cb commit 1f52446
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 95 deletions.
2 changes: 1 addition & 1 deletion src/ansys/sherlock/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# Ease import statements
# ------------------------------------------------------------------------------

from ansys.sherlock.core.logging import Logger
from ansys.sherlock.core.pysherlock_logging import Logger

LOG = Logger("sherlock")
"""PySherlock logger."""
54 changes: 23 additions & 31 deletions src/ansys/sherlock/core/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,25 +84,21 @@ def launch_sherlock(
except Exception as e:
print(str(e))
return None
server_version = None
_server_version = None
try:

args = [_get_sherlock_exe_path(year=year, release_number=release_number)]
args.append("-grpcPort=" + str(port))
sherlock_launch_cmd, _server_version = _get_sherlock_exe_path(
year=year, release_number=release_number
)
args = [sherlock_launch_cmd, "-grpcPort=" + str(port)]
if single_project_path != "":
args.append("-singleProject")
args.append(single_project_path)
if sherlock_cmd_args != "":
args.append(f"{shlex.split(sherlock_cmd_args)}")
print(args)
server_version = get_latest_version()
subprocess.Popen(args)
except Exception as e:
LOG.error("Error encountered while starting or executing Sherlock, error = %s" + str(e))

try:

sherlock = connect_grpc_channel(port, server_version)
sherlock = connect_grpc_channel(port, _server_version)

# Check that the gRPC connection is up (timeout after 3 minutes).
count = 0
Expand All @@ -121,7 +117,7 @@ def launch_sherlock(

return sherlock
except Exception as e:
LOG.error(str(e))
LOG.error("Error encountered while starting or executing Sherlock, error = %s" + str(e))


# First PySherlock Release "0.2.0"
Expand All @@ -144,11 +140,11 @@ def connect_grpc_channel(port=SHERLOCK_DEFAULT_PORT, server_version=None):
"""
channel_param = f"{LOCALHOST}:{port}"
channel = grpc.insecure_channel(channel_param)
SHERLOCK = Sherlock(channel, server_version)
return SHERLOCK
sherlock = Sherlock(channel, server_version)
return sherlock


def _get_base_ansys(year: int = None, release_number: int = None) -> str:
def _get_base_ansys(year: int = None, release_number: int = None) -> tuple[str, int]:
supported_installed_versions = {
env_key: path
for env_key, path in os.environ.items()
Expand All @@ -158,9 +154,11 @@ def _get_base_ansys(year: int = None, release_number: int = None) -> str:
if year is not None and release_number is not None:
try:
year = _extract_sherlock_version_year(year)
version_key = f"AWP_ROOT{year}{release_number}"

sherlock_version = int(f"{year}{release_number}")
version_key = f"AWP_ROOT{sherlock_version}"
if version_key in supported_installed_versions:
return supported_installed_versions[version_key]
return supported_installed_versions[version_key], sherlock_version
else:
raise ValueError(f"Sherlock {year} {release_number} is not installed.")
except ValueError as e:
Expand All @@ -169,35 +167,29 @@ def _get_base_ansys(year: int = None, release_number: int = None) -> str:

for key in sorted(supported_installed_versions, reverse=True):
ansys_version = _get_ansys_version_from_awp_root(key)

sherlock_version = int(ansys_version)
if ansys_version >= _EARLIEST_SUPPORTED_VERSION:
return ansys_version
return ""
return supported_installed_versions[key], sherlock_version

raise ValueError("Could not find any installed version of Sherlock.")

def _get_base_ansys():
supported_installed_versions = {
env_key: path
for env_key, path in os.environ.items()
if env_key.startswith("AWP_ROOT") and os.path.isdir(path)
}

for key in sorted(supported_installed_versions, reverse=True):
ansys_version = _get_ansys_version_from_awp_root(key)
if ansys_version >= _EARLIEST_SUPPORTED_VERSION:
return supported_installed_versions[key]
def _get_ansys_version_from_awp_root(awp_root):
if awp_root.find("AWP_ROOT") >= 0:
return int(awp_root.replace("AWP_ROOT", ""))

return ""


def _get_sherlock_exe_path(year: int = None, release_number: int = None) -> str:
ansys_base = _get_base_ansys(year=year, release_number=release_number)
ansys_base, sherlock_version = _get_base_ansys(year=year, release_number=release_number)
if not ansys_base:
return ""
if os.name == "nt":
sherlock_bin = os.path.join(ansys_base, "sherlock", "SherlockClient.exe")
else:
sherlock_bin = os.path.join(ansys_base, "sherlock", "runSherlock")
return sherlock_bin
return sherlock_bin, sherlock_version


def _extract_sherlock_version_year(year: int) -> int:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,63 +1,63 @@
# © 2023 ANSYS, Inc. All rights reserved

"""PySherlock logger."""
from datetime import datetime
import logging
from logging.handlers import TimedRotatingFileHandler
import sys

LOG_LEVEL = logging.DEBUG
FILE_NAME = "PySherlock.log"

# Formatting
STDOUT_MSG_FORMAT = logging.Formatter("%(levelname)s - %(module)s - %(funcName)s - %(message)s")
FILE_MSG_FORMAT = STDOUT_MSG_FORMAT

DEFAULT_STDOUT_HEADER = """
LEVEL - INSTANCE NAME - MODULE - FUNCTION - MESSAGE
"""
DEFAULT_FILE_HEADER = DEFAULT_STDOUT_HEADER

NEW_SESSION_HEADER = f"""
===============================================================================
NEW SESSION - {datetime.now().strftime("%m/%d/%Y, %H:%M:%S")}
==============================================================================="""


def _get_console_handler():
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(STDOUT_MSG_FORMAT)
return console_handler


def _get_file_handler():
file_handler = TimedRotatingFileHandler(FILE_NAME, when="midnight")
file_handler.setFormatter(STDOUT_MSG_FORMAT)
file_handler.stream.write(NEW_SESSION_HEADER)
file_handler.stream.write(DEFAULT_FILE_HEADER)
return file_handler


def __get_logger(logger_name):
return logging.get_logger(logger_name)


class Logger:
"""Provides the PySherlock logger."""

def __init__(self, logger_name, level=logging.WARN):
"""Initialize logger."""
self.logger = logging.getLogger(logger_name)
self.logger.setLevel(LOG_LEVEL)
self.logger.addHandler(_get_console_handler())
self.logger.addHandler(_get_file_handler())
self.debug = self.logger.debug
self.info = self.logger.info
self.warning = self.logger.warning
self.error = self.logger.error
self.critical = self.logger.critical
self.log = self.logger.log

def setLevel(self, level):
"""Set the logging level."""
self.logger.setLevel(level)
# © 2023 ANSYS, Inc. All rights reserved

"""PySherlock logger."""
from datetime import datetime
import logging
from logging.handlers import TimedRotatingFileHandler
import sys

LOG_LEVEL = logging.DEBUG
FILE_NAME = "PySherlock.log"

# Formatting
STDOUT_MSG_FORMAT = logging.Formatter("%(levelname)s - %(module)s - %(funcName)s - %(message)s")
FILE_MSG_FORMAT = STDOUT_MSG_FORMAT

DEFAULT_STDOUT_HEADER = """
LEVEL - INSTANCE NAME - MODULE - FUNCTION - MESSAGE
"""
DEFAULT_FILE_HEADER = DEFAULT_STDOUT_HEADER

NEW_SESSION_HEADER = f"""
===============================================================================
NEW SESSION - {datetime.now().strftime("%m/%d/%Y, %H:%M:%S")}
==============================================================================="""


def _get_console_handler():
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(STDOUT_MSG_FORMAT)
return console_handler


def _get_file_handler():
file_handler = TimedRotatingFileHandler(FILE_NAME, when="midnight")
file_handler.setFormatter(STDOUT_MSG_FORMAT)
file_handler.stream.write(NEW_SESSION_HEADER)
file_handler.stream.write(DEFAULT_FILE_HEADER)
return file_handler


def __get_logger(logger_name):
return logging.get_logger(logger_name)


class Logger:
"""Provides the PySherlock logger."""

def __init__(self, logger_name, level=logging.WARN):
"""Initialize logger."""
self.logger = logging.getLogger(logger_name)
self.logger.setLevel(LOG_LEVEL)
self.logger.addHandler(_get_console_handler())
self.logger.addHandler(_get_file_handler())
self.debug = self.logger.debug
self.info = self.logger.info
self.warning = self.logger.warning
self.error = self.logger.error
self.critical = self.logger.critical
self.log = self.logger.log

def setLevel(self, level):
"""Set the logging level."""
self.logger.setLevel(level)

0 comments on commit 1f52446

Please sign in to comment.