Skip to content

Commit 1ff0843

Browse files
syntronadeas31
andauthored
Omc session exception (#272)
* [OMCSessionException] add exception handling for OMCSession* * [OMCSessionZMQ] use specific exceptions instead of generic Exception where possible * [OMCSessionBase] use OMCSessionException instead of generic Exception --------- Co-authored-by: Adeel Asghar <[email protected]>
1 parent 5a666a0 commit 1ff0843

File tree

2 files changed

+32
-22
lines changed

2 files changed

+32
-22
lines changed

OMPython/OMCSession.py

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,10 @@ def wait(self, timeout):
7575
return self.process.wait(timeout=timeout)
7676

7777

78+
class OMCSessionException(Exception):
79+
pass
80+
81+
7882
class OMCSessionBase(metaclass=abc.ABCMeta):
7983

8084
def __init__(self, readonly=False):
@@ -119,7 +123,7 @@ def ask(self, question, opt=None, parsed=True):
119123

120124
try:
121125
res = self.sendExpression(expression, parsed=parsed)
122-
except Exception:
126+
except OMCSessionException:
123127
logger.error("OMC failed: %s, %s, parsed=%s", question, opt, parsed)
124128
raise
125129

@@ -337,14 +341,15 @@ def __init__(self, readonly=False, timeout=10.00,
337341
def __del__(self):
338342
try:
339343
self.sendExpression("quit()")
340-
except Exception:
344+
except OMCSessionException:
341345
pass
342346
self._omc_log_file.close()
343347
try:
344348
self._omc_process.wait(timeout=2.0)
345-
except Exception:
349+
except subprocess.TimeoutExpired:
346350
if self._omc_process:
347-
logger.warning("OMC did not exit after being sent the quit() command; killing the process with pid=%s", self._omc_process.pid)
351+
logger.warning("OMC did not exit after being sent the quit() command; "
352+
"killing the process with pid=%s", self._omc_process.pid)
348353
self._omc_process.kill()
349354
self._omc_process.wait()
350355

@@ -374,18 +379,19 @@ def _start_omc_process(self, timeout):
374379
try:
375380
with open(self._dockerCidFile, "r") as fin:
376381
self._dockerCid = fin.read().strip()
377-
except Exception:
382+
except IOError:
378383
pass
379384
if self._dockerCid:
380385
break
381386
time.sleep(timeout / 40.0)
382387
try:
383388
os.remove(self._dockerCidFile)
384-
except Exception:
389+
except FileNotFoundError:
385390
pass
386391
if self._dockerCid is None:
387392
logger.error("Docker did not start. Log-file says:\n%s" % (open(self._omc_log_file.name).read()))
388-
raise Exception("Docker did not start (timeout=%f might be too short especially if you did not docker pull the image before this command)." % timeout)
393+
raise OMCSessionException("Docker did not start (timeout=%f might be too short especially if you did "
394+
"not docker pull the image before this command)." % timeout)
389395

390396
dockerTop = None
391397
if self._docker or self._dockerContainer:
@@ -402,17 +408,16 @@ def _start_omc_process(self, timeout):
402408
try:
403409
self._omc_process = DummyPopen(int(columns[1]))
404410
except psutil.NoSuchProcess:
405-
raise Exception(
406-
f"Could not find PID {dockerTop} - is this a docker instance spawned without --pid=host?\n"
407-
f"Log-file says:\n{open(self._omc_log_file.name).read()}")
411+
raise OMCSessionException(
412+
f"Could not find PID {dockerTop} - is this a docker instance spawned "
413+
f"without --pid=host?\nLog-file says:\n{open(self._omc_log_file.name).read()}")
408414
break
409415
if self._omc_process is not None:
410416
break
411417
time.sleep(timeout / 40.0)
412418
if self._omc_process is None:
413-
414-
raise Exception("Docker top did not contain omc process %s:\n%s\nLog-file says:\n%s"
415-
% (self._random_string, dockerTop, open(self._omc_log_file.name).read()))
419+
raise OMCSessionException("Docker top did not contain omc process %s:\n%s\nLog-file says:\n%s"
420+
% (self._random_string, dockerTop, open(self._omc_log_file.name).read()))
416421
return self._omc_process
417422

418423
def _getuid(self):
@@ -433,7 +438,9 @@ def _set_omc_command(self, omc_path_and_args_list):
433438
if (self._docker or self._dockerContainer) and sys.platform == "win32":
434439
extraFlags = ["-d=zmqDangerousAcceptConnectionsFromAnywhere"]
435440
if not self._interactivePort:
436-
raise Exception("docker on Windows requires knowing which port to connect to. For dockerContainer=..., the container needs to have already manually exposed this port when it was started (-p 127.0.0.1:n:n) or you get an error later.")
441+
raise OMCSessionException("docker on Windows requires knowing which port to connect to. For "
442+
"dockerContainer=..., the container needs to have already manually exposed "
443+
"this port when it was started (-p 127.0.0.1:n:n) or you get an error later.")
437444
else:
438445
extraFlags = []
439446
if self._docker:
@@ -446,7 +453,7 @@ def _set_omc_command(self, omc_path_and_args_list):
446453
dockerNetworkStr = []
447454
extraFlags = ["-d=zmqDangerousAcceptConnectionsFromAnywhere"]
448455
else:
449-
raise Exception('dockerNetwork was set to %s, but only \"host\" or \"separate\" is allowed')
456+
raise OMCSessionException('dockerNetwork was set to %s, but only \"host\" or \"separate\" is allowed')
450457
self._dockerCidFile = self._omc_log_file.name + ".docker.cid"
451458
omcCommand = ["docker", "run", "--cidfile", self._dockerCidFile, "--rm", "--env", "USER=%s" % self._currentUser, "--user", str(self._getuid())] + self._dockerExtraArgs + dockerNetworkStr + [self._docker, self._dockerOpenModelicaPath]
452459
elif self._dockerContainer:
@@ -476,7 +483,7 @@ def _get_omhome(self, omhome: str = None):
476483
if path_to_omc is not None:
477484
return pathlib.Path(path_to_omc).parents[1]
478485

479-
raise ValueError("Cannot find OpenModelica executable, please install from openmodelica.org")
486+
raise OMCSessionException("Cannot find OpenModelica executable, please install from openmodelica.org")
480487

481488
def _get_omc_path(self) -> pathlib.Path:
482489
return self.omhome / "bin" / "omc"
@@ -489,9 +496,10 @@ def _connect_to_omc(self, timeout):
489496
while True:
490497
if self._dockerCid:
491498
try:
492-
self._port = subprocess.check_output(["docker", "exec", self._dockerCid, "cat", self._port_file], stderr=subprocess.DEVNULL).decode().strip()
499+
self._port = subprocess.check_output(["docker", "exec", self._dockerCid, "cat", self._port_file],
500+
stderr=subprocess.DEVNULL).decode().strip()
493501
break
494-
except Exception:
502+
except subprocess.CalledProcessError:
495503
pass
496504
else:
497505
if os.path.isfile(self._port_file):
@@ -506,7 +514,8 @@ def _connect_to_omc(self, timeout):
506514
name = self._omc_log_file.name
507515
self._omc_log_file.close()
508516
logger.error("OMC Server did not start. Please start it! Log-file says:\n%s" % open(name).read())
509-
raise Exception(f"OMC Server did not start (timeout={timeout}). Could not open file {self._port_file}")
517+
raise OMCSessionException(f"OMC Server did not start (timeout={timeout}). "
518+
"Could not open file {self._port_file}")
510519
time.sleep(timeout / 80.0)
511520

512521
self._port = self._port.replace("0.0.0.0", self._serverIPAddress)
@@ -522,7 +531,7 @@ def _connect_to_omc(self, timeout):
522531
def sendExpression(self, command, parsed=True):
523532
p = self._omc_process.poll() # check if process is running
524533
if p is not None:
525-
raise Exception("Process Exited, No connection with OMC. Create a new instance of OMCSessionZMQ")
534+
raise OMCSessionException("Process Exited, No connection with OMC. Create a new instance of OMCSessionZMQ!")
526535

527536
attempts = 0
528537
while True:
@@ -536,7 +545,7 @@ def sendExpression(self, command, parsed=True):
536545
self._omc_log_file.seek(0)
537546
log = self._omc_log_file.read()
538547
self._omc_log_file.close()
539-
raise Exception(f"No connection with OMC (timeout={self._timeout}). Log-file says: \n{log}")
548+
raise OMCSessionException(f"No connection with OMC (timeout={self._timeout}). Log-file says: \n{log}")
540549
time.sleep(self._timeout / 50.0)
541550
if command == "quit()":
542551
self._omc.close()

OMPython/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
CONDITIONS OF OSMC-PL.
3737
"""
3838

39-
from OMPython.OMCSession import OMCSessionBase, OMCSessionZMQ
39+
from OMPython.OMCSession import OMCSessionBase, OMCSessionZMQ, OMCSessionException
4040
from OMPython.ModelicaSystem import ModelicaSystem, ModelicaSystemError, LinearizationResult
4141

4242
# global names imported if import 'from OMPython import *' is used
@@ -45,6 +45,7 @@
4545
'ModelicaSystemError',
4646
'LinearizationResult',
4747

48+
'OMCSessionException',
4849
'OMCSessionZMQ',
4950
'OMCSessionBase',
5051
]

0 commit comments

Comments
 (0)