forked from OpenModelica/OMPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOMCSession.py
More file actions
1903 lines (1533 loc) · 70.5 KB
/
OMCSession.py
File metadata and controls
1903 lines (1533 loc) · 70.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Definition of an OMC session.
"""
from __future__ import annotations
import abc
import dataclasses
import io
import json
import logging
import os
import pathlib
import platform
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from typing import Any, Optional, Tuple
import uuid
import warnings
import psutil
import pyparsing
import zmq
# TODO: replace this with the new parser
from OMPython.OMTypedParser import om_parser_typed
from OMPython.OMParser import om_parser_basic
# define logger using the current module name as ID
logger = logging.getLogger(__name__)
class DockerPopen:
"""
Dummy implementation of Popen for a (running) docker process. The process is identified by its process ID (pid).
"""
def __init__(self, pid):
self.pid = pid
self.process = psutil.Process(pid)
self.returncode = 0
def poll(self):
return None if self.process.is_running() else True
def kill(self):
return os.kill(pid=self.pid, signal=signal.SIGKILL)
def wait(self, timeout):
try:
self.process.wait(timeout=timeout)
except psutil.TimeoutExpired:
pass
class OMCSessionException(Exception):
"""
Exception which is raised by any OMC* class.
"""
class OMCSessionCmd:
"""
Implementation of Open Modelica Compiler API functions. Depreciated!
"""
def __init__(self, session: OMSessionABC, readonly: bool = False):
if not isinstance(session, OMSessionABC):
raise OMCSessionException("Invalid OMC process definition!")
self._session = session
self._readonly = readonly
self._omc_cache: dict[tuple[str, bool], Any] = {}
def _ask(self, question: str, opt: Optional[list[str]] = None, parsed: bool = True):
if opt is None:
expression = question
elif isinstance(opt, list):
expression = f"{question}({','.join([str(x) for x in opt])})"
else:
raise OMCSessionException(f"Invalid definition of options for {repr(question)}: {repr(opt)}")
p = (expression, parsed)
if self._readonly and question != 'getErrorString':
# can use cache if readonly
if p in self._omc_cache:
return self._omc_cache[p]
try:
res = self._session.sendExpression(expression, parsed=parsed)
except OMCSessionException as ex:
raise OMCSessionException(f"OMC _ask() failed: {expression} (parsed={parsed})") from ex
# save response
self._omc_cache[p] = res
return res
# TODO: Open Modelica Compiler API functions. Would be nice to generate these.
def loadFile(self, filename):
return self._ask(question='loadFile', opt=[f'"{filename}"'])
def loadModel(self, className):
return self._ask(question='loadModel', opt=[className])
def isModel(self, className):
return self._ask(question='isModel', opt=[className])
def isPackage(self, className):
return self._ask(question='isPackage', opt=[className])
def isPrimitive(self, className):
return self._ask(question='isPrimitive', opt=[className])
def isConnector(self, className):
return self._ask(question='isConnector', opt=[className])
def isRecord(self, className):
return self._ask(question='isRecord', opt=[className])
def isBlock(self, className):
return self._ask(question='isBlock', opt=[className])
def isType(self, className):
return self._ask(question='isType', opt=[className])
def isFunction(self, className):
return self._ask(question='isFunction', opt=[className])
def isClass(self, className):
return self._ask(question='isClass', opt=[className])
def isParameter(self, className):
return self._ask(question='isParameter', opt=[className])
def isConstant(self, className):
return self._ask(question='isConstant', opt=[className])
def isProtected(self, className):
return self._ask(question='isProtected', opt=[className])
def getPackages(self, className="AllLoadedClasses"):
return self._ask(question='getPackages', opt=[className])
def getClassRestriction(self, className):
return self._ask(question='getClassRestriction', opt=[className])
def getDerivedClassModifierNames(self, className):
return self._ask(question='getDerivedClassModifierNames', opt=[className])
def getDerivedClassModifierValue(self, className, modifierName):
return self._ask(question='getDerivedClassModifierValue', opt=[className, modifierName])
def typeNameStrings(self, className):
return self._ask(question='typeNameStrings', opt=[className])
def getComponents(self, className):
return self._ask(question='getComponents', opt=[className])
def getClassComment(self, className):
try:
return self._ask(question='getClassComment', opt=[className])
except pyparsing.ParseException as ex:
logger.warning("Method 'getClassComment(%s)' failed; OMTypedParser error: %s",
className, ex.msg)
return 'No description available'
def getNthComponent(self, className, comp_id):
""" returns with (type, name, description) """
return self._ask(question='getNthComponent', opt=[className, comp_id])
def getNthComponentAnnotation(self, className, comp_id):
return self._ask(question='getNthComponentAnnotation', opt=[className, comp_id])
def getImportCount(self, className):
return self._ask(question='getImportCount', opt=[className])
def getNthImport(self, className, importNumber):
# [Path, id, kind]
return self._ask(question='getNthImport', opt=[className, importNumber])
def getInheritanceCount(self, className):
return self._ask(question='getInheritanceCount', opt=[className])
def getNthInheritedClass(self, className, inheritanceDepth):
return self._ask(question='getNthInheritedClass', opt=[className, inheritanceDepth])
def getParameterNames(self, className):
try:
return self._ask(question='getParameterNames', opt=[className])
except KeyError as ex:
logger.warning('OMPython error: %s', ex)
# FIXME: OMC returns with a different structure for empty parameter set
return []
def getParameterValue(self, className, parameterName):
try:
return self._ask(question='getParameterValue', opt=[className, parameterName])
except pyparsing.ParseException as ex:
logger.warning("Method 'getParameterValue(%s, %s)' failed; OMTypedParser error: %s",
className, parameterName, ex.msg)
return ""
def getComponentModifierNames(self, className, componentName):
return self._ask(question='getComponentModifierNames', opt=[className, componentName])
def getComponentModifierValue(self, className, componentName):
return self._ask(question='getComponentModifierValue', opt=[className, componentName])
def getExtendsModifierNames(self, className, componentName):
return self._ask(question='getExtendsModifierNames', opt=[className, componentName])
def getExtendsModifierValue(self, className, extendsName, modifierName):
return self._ask(question='getExtendsModifierValue', opt=[className, extendsName, modifierName])
def getNthComponentModification(self, className, comp_id):
# FIXME: OMPython exception Results KeyError exception
# get {$Code(....)} field
# \{\$Code\((\S*\s*)*\)\}
value = self._ask(question='getNthComponentModification', opt=[className, comp_id], parsed=False)
value = value.replace("{$Code(", "")
return value[:-3]
# return self.re_Code.findall(value)
# function getClassNames
# input TypeName class_ = $Code(AllLoadedClasses);
# input Boolean recursive = false;
# input Boolean qualified = false;
# input Boolean sort = false;
# input Boolean builtin = false "List also builtin classes if true";
# input Boolean showProtected = false "List also protected classes if true";
# output TypeName classNames[:];
# end getClassNames;
def getClassNames(self, className=None, recursive=False, qualified=False, sort=False, builtin=False,
showProtected=False):
opt = [className] if className else [] + [f'recursive={str(recursive).lower()}',
f'qualified={str(qualified).lower()}',
f'sort={str(sort).lower()}',
f'builtin={str(builtin).lower()}',
f'showProtected={str(showProtected).lower()}']
return self._ask(question='getClassNames', opt=opt)
# due to the compatibility layer to Python < 3.12, the OM(C)Path classes must be hidden behind the following if
# conditions. This is also the reason for OMPathABC, a simple base class to be used in ModelicaSystem* classes.
# Reason: before Python 3.12, pathlib.PurePosixPath can not be derived from; therefore, OMPathABC is not possible
if sys.version_info < (3, 12):
class OMPathCompatibility(pathlib.Path):
"""
Compatibility class for OMPathABC in Python < 3.12. This allows to run all code which uses OMPathABC (mainly
ModelicaSystem) on these Python versions. There are remaining limitation as only local execution is possible.
"""
# modified copy of pathlib.Path.__new__() definition
def __new__(cls, *args, **kwargs):
logger.warning("Python < 3.12 - using a version of class OMCPath "
"based on pathlib.Path for local usage only.")
if cls is OMPathCompatibility:
cls = OMPathCompatibilityWindows if os.name == 'nt' else OMPathCompatibilityPosix
self = cls._from_parts(args)
if not self._flavour.is_supported:
raise NotImplementedError(f"cannot instantiate {cls.__name__} on your system")
return self
def size(self) -> int:
"""
Needed compatibility function to have the same interface as OMCPathReal
"""
return self.stat().st_size
class OMPathCompatibilityPosix(pathlib.PosixPath, OMPathCompatibility):
"""
Compatibility class for OMCPath on Posix systems (Python < 3.12)
"""
class OMPathCompatibilityWindows(pathlib.WindowsPath, OMPathCompatibility):
"""
Compatibility class for OMCPath on Windows systems (Python < 3.12)
"""
OMPathABC = OMPathCompatibility
OMCPath = OMPathCompatibility
OMPathRunnerABC = OMPathCompatibility
OMPathRunnerLocal = OMPathCompatibility
else:
class OMPathABC(pathlib.PurePosixPath, metaclass=abc.ABCMeta):
"""
Implementation of a basic (PurePosix)Path object to be used within OMPython. The derived classes can use OMC as
backend and - thus - work on different configurations like docker or WSL. The connection to OMC is provided via
an instances of classes derived from BaseSession.
PurePosixPath is selected as it covers all but Windows systems (Linux, docker, WSL). However, the code is
written such that possible Windows system are taken into account. Nevertheless, the overall functionality is
limited compared to standard pathlib.Path objects.
"""
def __init__(self, *path, session: OMSessionABC) -> None:
super().__init__(*path)
self._session = session
def with_segments(self, *pathsegments):
"""
Create a new OMCPath object with the given path segments.
The original definition of Path is overridden to ensure the session data is set.
"""
return type(self)(*pathsegments, session=self._session)
@abc.abstractmethod
def is_file(self) -> bool:
"""
Check if the path is a regular file.
"""
@abc.abstractmethod
def is_dir(self) -> bool:
"""
Check if the path is a directory.
"""
@abc.abstractmethod
def is_absolute(self):
"""
Check if the path is an absolute path.
"""
@abc.abstractmethod
def read_text(self) -> str:
"""
Read the content of the file represented by this path as text.
"""
@abc.abstractmethod
def write_text(self, data: str):
"""
Write text data to the file represented by this path.
"""
@abc.abstractmethod
def mkdir(self, parents: bool = True, exist_ok: bool = False):
"""
Create a directory at the path represented by this class.
The argument parents with default value True exists to ensure compatibility with the fallback solution for
Python < 3.12. In this case, pathlib.Path is used directly and this option ensures, that missing parent
directories are also created.
"""
@abc.abstractmethod
def cwd(self):
"""
Returns the current working directory as an OMPathABC object.
"""
@abc.abstractmethod
def unlink(self, missing_ok: bool = False) -> None:
"""
Unlink (delete) the file or directory represented by this path.
"""
@abc.abstractmethod
def resolve(self, strict: bool = False):
"""
Resolve the path to an absolute path.
"""
def absolute(self):
"""
Resolve the path to an absolute path. Just a wrapper for resolve().
"""
return self.resolve()
def exists(self) -> bool:
"""
Semi replacement for pathlib.Path.exists().
"""
return self.is_file() or self.is_dir()
@abc.abstractmethod
def size(self) -> int:
"""
Get the size of the file in bytes - this is an extra function and the best we can do using OMC.
"""
class _OMCPath(OMPathABC):
"""
Implementation of a OMPathABC using OMC as backend. The connection to OMC is provided via an instances of an
OMCSession* classes.
"""
def is_file(self) -> bool:
"""
Check if the path is a regular file.
"""
return self._session.sendExpression(expr=f'regularFileExists("{self.as_posix()}")')
def is_dir(self) -> bool:
"""
Check if the path is a directory.
"""
return self._session.sendExpression(expr=f'directoryExists("{self.as_posix()}")')
def is_absolute(self):
"""
Check if the path is an absolute path.
"""
if isinstance(self._session, OMCSessionLocal) and platform.system() == 'Windows':
return pathlib.PureWindowsPath(self.as_posix()).is_absolute()
return super().is_absolute()
def read_text(self) -> str:
"""
Read the content of the file represented by this path as text.
"""
return self._session.sendExpression(expr=f'readFile("{self.as_posix()}")')
def write_text(self, data: str):
"""
Write text data to the file represented by this path.
"""
if not isinstance(data, str):
raise TypeError(f"data must be str, not {data.__class__.__name__}")
data_omc = self._session.escape_str(data)
self._session.sendExpression(expr=f'writeFile("{self.as_posix()}", "{data_omc}", false);')
return len(data)
def mkdir(self, parents: bool = True, exist_ok: bool = False):
"""
Create a directory at the path represented by this class.
The argument parents with default value True exists to ensure compatibility with the fallback solution for
Python < 3.12. In this case, pathlib.Path is used directly and this option ensures, that missing parent
directories are also created.
"""
if self.is_dir() and not exist_ok:
raise FileExistsError(f"Directory {self.as_posix()} already exists!")
return self._session.sendExpression(expr=f'mkdir("{self.as_posix()}")')
def cwd(self):
"""
Returns the current working directory as an OMPathABC object.
"""
cwd_str = self._session.sendExpression(expr='cd()')
return OMCPath(cwd_str, session=self._session)
def unlink(self, missing_ok: bool = False) -> None:
"""
Unlink (delete) the file or directory represented by this path.
"""
res = self._session.sendExpression(expr=f'deleteFile("{self.as_posix()}")')
if not res and not missing_ok:
raise FileNotFoundError(f"Cannot delete file {self.as_posix()} - it does not exists!")
def resolve(self, strict: bool = False):
"""
Resolve the path to an absolute path. This is done based on available OMC functions.
"""
if strict and not (self.is_file() or self.is_dir()):
raise OMCSessionException(f"Path {self.as_posix()} does not exist!")
if self.is_file():
pathstr_resolved = self._omc_resolve(self.parent.as_posix())
omcpath_resolved = self._session.omcpath(pathstr_resolved) / self.name
elif self.is_dir():
pathstr_resolved = self._omc_resolve(self.as_posix())
omcpath_resolved = self._session.omcpath(pathstr_resolved)
else:
raise OMCSessionException(f"Path {self.as_posix()} is neither a file nor a directory!")
if not omcpath_resolved.is_file() and not omcpath_resolved.is_dir():
raise OMCSessionException(f"OMCPath resolve failed for {self.as_posix()} - path does not exist!")
return omcpath_resolved
def _omc_resolve(self, pathstr: str) -> str:
"""
Internal function to resolve the path of the OMCPath object using OMC functions *WITHOUT* changing the cwd
within OMC.
"""
expr = ('omcpath_cwd := cd(); '
f'omcpath_check := cd("{pathstr}"); ' # check requested pathstring
'cd(omcpath_cwd)')
try:
result = self._session.sendExpression(expr=expr, parsed=False)
result_parts = result.split('\n')
pathstr_resolved = result_parts[1]
pathstr_resolved = pathstr_resolved[1:-1] # remove quotes
except OMCSessionException as ex:
raise OMCSessionException(f"OMCPath resolve failed for {pathstr}!") from ex
return pathstr_resolved
def size(self) -> int:
"""
Get the size of the file in bytes - this is an extra function and the best we can do using OMC.
"""
if not self.is_file():
raise OMCSessionException(f"Path {self.as_posix()} is not a file!")
res = self._session.sendExpression(expr=f'stat("{self.as_posix()}")')
if res[0]:
return int(res[1])
raise OMCSessionException(f"Error reading file size for path {self.as_posix()}!")
class OMPathRunnerABC(OMPathABC, metaclass=abc.ABCMeta):
"""
Base function for OMPath definitions *without* OMC server
"""
def _path(self) -> pathlib.Path:
return pathlib.Path(self.as_posix())
class _OMPathRunnerLocal(OMPathRunnerABC):
"""
Implementation of OMPathBase which does not use the session data at all. Thus, this implementation can run
locally without any usage of OMC.
This class is based on OMPathBase and, therefore, on pathlib.PurePosixPath. This is working well, but it is not
the correct implementation on Windows systems. To get a valid Windows representation of the path, use the
conversion via pathlib.Path(<OMCPathDummy>.as_posix()).
"""
def is_file(self) -> bool:
"""
Check if the path is a regular file.
"""
return self._path().is_file()
def is_dir(self) -> bool:
"""
Check if the path is a directory.
"""
return self._path().is_dir()
def is_absolute(self):
"""
Check if the path is an absolute path.
"""
return self._path().is_absolute()
def read_text(self) -> str:
"""
Read the content of the file represented by this path as text.
"""
return self._path().read_text(encoding='utf-8')
def write_text(self, data: str):
"""
Write text data to the file represented by this path.
"""
return self._path().write_text(data=data, encoding='utf-8')
def mkdir(self, parents: bool = True, exist_ok: bool = False):
"""
Create a directory at the path represented by this class.
The argument parents with default value True exists to ensure compatibility with the fallback solution for
Python < 3.12. In this case, pathlib.Path is used directly and this option ensures, that missing parent
directories are also created.
"""
return self._path().mkdir(parents=parents, exist_ok=exist_ok)
def cwd(self):
"""
Returns the current working directory as an OMPathBase object.
"""
return self._path().cwd()
def unlink(self, missing_ok: bool = False) -> None:
"""
Unlink (delete) the file or directory represented by this path.
"""
return self._path().unlink(missing_ok=missing_ok)
def resolve(self, strict: bool = False):
"""
Resolve the path to an absolute path. This is done based on available OMC functions.
"""
path_resolved = self._path().resolve(strict=strict)
return type(self)(path_resolved, session=self._session)
def size(self) -> int:
"""
Get the size of the file in bytes - implementation baseon on pathlib.Path.
"""
if not self.is_file():
raise OMCSessionException(f"Path {self.as_posix()} is not a file!")
path = self._path()
return path.stat().st_size
OMCPath = _OMCPath
OMPathRunnerLocal = _OMPathRunnerLocal
class ModelExecutionException(Exception):
"""
Exception which is raised by ModelException* classes.
"""
@dataclasses.dataclass
class ModelExecutionData:
"""
Data class to store the command line data for running a model executable in the OMC environment.
All data should be defined for the environment, where OMC is running (local, docker or WSL)
To use this as a definition of an OMC simulation run, it has to be processed within
OMCProcess*.self_update(). This defines the attribute cmd_model_executable.
"""
# cmd_path is the expected working directory
cmd_path: str
cmd_model_name: str
# command prefix data (as list of strings); needed for docker or WSL
cmd_prefix: list[str]
# cmd_model_executable is build out of cmd_path and cmd_model_name; this is mainly needed on Windows (add *.exe)
cmd_model_executable: str
# command line arguments for the model executable
cmd_args: list[str]
# result file with the simulation output
cmd_result_file: str
# command timeout
cmd_timeout: float
# additional library search path; this is mainly needed if OMCProcessLocal is run on Windows
cmd_library_path: Optional[str] = None
# working directory to be used on the *local* system
cmd_cwd_local: Optional[str] = None
def get_cmd(self) -> list[str]:
"""
Get the command line to run the model executable in the environment defined by the OMCProcess definition.
"""
cmdl = self.cmd_prefix
cmdl += [self.cmd_model_executable]
cmdl += self.cmd_args
return cmdl
def run(self) -> int:
"""
Run the model execution defined in this class.
"""
my_env = os.environ.copy()
if isinstance(self.cmd_library_path, str):
my_env["PATH"] = self.cmd_library_path + os.pathsep + my_env["PATH"]
cmdl = self.get_cmd()
logger.debug("Run OM command %s in %s", repr(cmdl), self.cmd_path)
try:
cmdres = subprocess.run(
cmdl,
capture_output=True,
text=True,
env=my_env,
cwd=self.cmd_cwd_local,
timeout=self.cmd_timeout,
check=True,
)
stdout = cmdres.stdout.strip()
stderr = cmdres.stderr.strip()
returncode = cmdres.returncode
logger.debug("OM output for command %s:\n%s", repr(cmdl), stdout)
if stderr:
raise ModelExecutionException(f"Error running model executable {repr(cmdl)}: {stderr}")
except subprocess.TimeoutExpired as ex:
raise ModelExecutionException(f"Timeout running model executable {repr(cmdl)}: {ex}") from ex
except subprocess.CalledProcessError as ex:
raise ModelExecutionException(f"Error running model executable {repr(cmdl)}: {ex}") from ex
return returncode
class PostInitCaller(type):
"""
Metaclass definition to define a new function __post_init__() which is called after all __init__() functions where
executed. The workflow would read as follows:
On creating a class with the following inheritance Class2 => Class1 => Class0, where each class calls the __init__()
functions of its parent, i.e. super().__init__(), as well as __post_init__() the call schema would be:
myclass = Class2()
Class2.__init__()
Class1.__init__()
Class0.__init__()
Class2.__post_init__() <= this is done due to the metaclass
Class1.__post_init__()
Class0.__post_init__()
References:
* https://stackoverflow.com/questions/100003/what-are-metaclasses-in-python
* https://stackoverflow.com/questions/795190/how-to-perform-common-post-initialization-tasks-in-inherited-classes
"""
def __call__(cls, *args, **kwargs):
obj = type.__call__(cls, *args, **kwargs)
obj.__post_init__()
return obj
class OMSessionMeta(abc.ABCMeta, PostInitCaller):
"""
Helper class to get a combined metaclass of ABCMeta and PostInitCaller.
References:
* https://stackoverflow.com/questions/11276037/resolving-metaclass-conflicts
"""
class OMSessionABC(metaclass=OMSessionMeta):
"""
This class implements the basic structure a OMPython session definition needs. It provides the structure for an
implementation using OMC as backend (via ZMQ) or a dummy implementation which just runs a model executable.
"""
def __init__(
self,
timeout: float = 10.00,
**kwargs,
) -> None:
"""
Initialisation for OMSessionBase
"""
# some helper data
self.model_execution_windows = platform.system() == "Windows"
self.model_execution_local = False
# store variables
self._timeout = timeout
# command prefix (to be used for docker or WSL)
self._cmd_prefix: list[str] = []
def __post_init__(self) -> None:
"""
Post initialisation method.
"""
def get_cmd_prefix(self) -> list[str]:
"""
Get session definition used for this instance of OMPath.
"""
return self._cmd_prefix.copy()
@staticmethod
def escape_str(value: str) -> str:
"""
Escape a string such that it can be used as string within OMC expressions, i.e. escape all double quotes.
"""
return value.replace("\\", "\\\\").replace('"', '\\"')
@abc.abstractmethod
def model_execution_prefix(self, cwd: Optional[OMPathABC] = None) -> list[str]:
"""
Helper function which returns a command prefix.
"""
@abc.abstractmethod
def get_version(self) -> str:
"""
Get the OM version.
"""
@abc.abstractmethod
def set_workdir(self, workdir: OMPathABC) -> None:
"""
Set the workdir for this session.
"""
@abc.abstractmethod
def omcpath(self, *path) -> OMPathABC:
"""
Create an OMPathABC object based on the given path segments and the current class.
"""
@abc.abstractmethod
def omcpath_tempdir(self, tempdir_base: Optional[OMPathABC] = None) -> OMPathABC:
"""
Get a temporary directory based on the specific definition for this session.
"""
@staticmethod
def _tempdir(tempdir_base: OMPathABC) -> OMPathABC:
names = [str(uuid.uuid4()) for _ in range(100)]
tempdir: Optional[OMPathABC] = None
for name in names:
# create a unique temporary directory name
tempdir = tempdir_base / name
if tempdir.exists():
continue
tempdir.mkdir(parents=True, exist_ok=False)
break
if tempdir is None or not tempdir.is_dir():
raise FileNotFoundError(f"Cannot create a temporary directory in {tempdir_base}!")
return tempdir
@abc.abstractmethod
def sendExpression(self, expr: str, parsed: bool = True) -> Any:
"""
Function needed to send expressions to the OMC server via ZMQ.
"""
class OMCSessionABC(OMSessionABC, metaclass=abc.ABCMeta):
"""
Base class for an OMC session started via ZMQ. This class contains common functionality for all variants of an
OMC session definition.
The main method is sendExpression() which is used to send commands to the OMC process.
The following variants are defined:
* OMCSessionLocal
* OMCSessionPort
* OMCSessionDocker
* OMCSessionDockerContainer
* OMCSessionWSL
"""
def __init__(
self,
timeout: float = 10.00,
**kwargs,
) -> None:
"""
Initialisation for OMCSession
"""
super().__init__(timeout=timeout)
# some helper data
self.model_execution_windows = platform.system() == "Windows"
self.model_execution_local = False
# generate a random string for this instance of OMC
self._random_string = uuid.uuid4().hex
# get a temporary directory
self._temp_dir = pathlib.Path(tempfile.gettempdir())
# omc process
self._omc_process: Optional[subprocess.Popen] = None
# omc ZMQ port to use
self._omc_port: Optional[str] = None
# omc port and log file
self._omc_filebase = f"openmodelica.{self._random_string}"
# ZMQ socket to communicate with OMC
self._omc_zmq: Optional[zmq.Socket[bytes]] = None
# setup log file - this file must be closed in the destructor
self._omc_logfile = self._temp_dir / (self._omc_filebase + ".log")
self._omc_loghandle: Optional[io.TextIOWrapper] = None
try:
self._omc_loghandle = open(file=self._omc_logfile, mode="w+", encoding="utf-8")
except OSError as ex:
raise OMCSessionException(f"Cannot open log file {self._omc_logfile}.") from ex
# variables to store compiled re expressions use in self.sendExpression()
self._re_log_entries: Optional[re.Pattern[str]] = None
self._re_log_raw: Optional[re.Pattern[str]] = None
self._re_portfile_path = re.compile(pattern=r'\nDumped server port in file: (.*?)($|\n)',
flags=re.MULTILINE | re.DOTALL)
def __post_init__(self) -> None:
"""
Create the connection to the OMC server using ZeroMQ.
"""
# set_timeout() is used to define the value of _timeout as it includes additional checks
self.set_timeout(timeout=self._timeout)
port = self.get_port()
if not isinstance(port, str):
raise OMCSessionException(f"Invalid content for port: {port}")
# Create the ZeroMQ socket and connect to OMC server
context = zmq.Context.instance()
omc = context.socket(zmq.REQ)
omc.setsockopt(zmq.LINGER, 0) # Dismisses pending messages if closed
omc.setsockopt(zmq.IMMEDIATE, True) # Queue messages only to completed connections
omc.connect(port)
self._omc_zmq = omc
def __del__(self):
if isinstance(self._omc_zmq, zmq.Socket):
try:
self.sendExpression(expr="quit()")
except OMCSessionException as exc:
logger.warning(f"Exception on sending 'quit()' to OMC: {exc}! Continue nevertheless ...")
finally:
self._omc_zmq = None
if self._omc_loghandle is not None:
try:
self._omc_loghandle.close()
except (OSError, IOError):
pass
finally:
self._omc_loghandle = None
if isinstance(self._omc_process, subprocess.Popen):
try:
self._omc_process.wait(timeout=2.0)
except subprocess.TimeoutExpired:
if self._omc_process:
logger.warning("OMC did not exit after being sent the 'quit()' command; "
"killing the process with pid=%s", self._omc_process.pid)
self._omc_process.kill()
self._omc_process.wait()
finally:
self._omc_process = None
def _timeout_loop(
self,
timeout: Optional[float] = None,
timestep: float = 0.1,
):
"""
Helper (using yield) for while loops to check OMC startup / response. The loop is executed as long as True is
returned, i.e. the first False will stop the while loop.
"""
if timeout is None:
timeout = self._timeout
if timeout <= 0:
raise OMCSessionException(f"Invalid timeout: {timeout}")
timer = 0.0
yield True
while True:
timer += timestep
if timer > timeout:
break
time.sleep(timestep)
yield True
yield False
def set_timeout(self, timeout: Optional[float] = None) -> float:
"""
Set the timeout to be used for OMC communication (OMCSession).
The defined value is set and the current value is returned. If None is provided as argument, nothing is changed.
"""
retval = self._timeout
if timeout is not None:
if timeout <= 0.0:
raise OMCSessionException(f"Invalid timeout value: {timeout}!")
self._timeout = timeout
return retval
@staticmethod
def escape_str(value: str) -> str:
"""
Escape a string such that it can be used as string within OMC expressions, i.e. escape all double quotes.
"""
return value.replace("\\", "\\\\").replace('"', '\\"')
def get_version(self) -> str:
"""
Get the OM version.
"""
return self.sendExpression("getVersion()", parsed=True)
def set_workdir(self, workdir: OMPathABC) -> None:
"""
Set the workdir for this session.
"""
exp = f'cd("{workdir.as_posix()}")'
self.sendExpression(exp)
def model_execution_prefix(self, cwd: Optional[OMPathABC] = None) -> list[str]: