forked from OpenModelica/OMPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathom_session_runner.py
More file actions
383 lines (312 loc) · 14.2 KB
/
Copy pathom_session_runner.py
File metadata and controls
383 lines (312 loc) · 14.2 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
# -*- coding: utf-8 -*-
"""
Definition of an OM session just executing a compiled model executable (Runner).
"""
from __future__ import annotations
import abc
import logging
import pathlib
import subprocess
import sys
import tempfile
from typing import Any, Optional, Type
from OMPython.om_session_abc import (
OMPathABC,
OMSessionABC,
OMSessionException,
)
# define logger using the current module name as ID
logger = logging.getLogger(__name__)
# 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):
OMPathRunnerABC = OMPathABC
OMPathRunnerLocal = OMPathABC
OMPathRunnerBash = OMPathABC
else:
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 OMPathABC 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 OMPathABC 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(<OM*Path*>.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) -> bool:
"""
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.
"""
if not isinstance(data, str):
raise TypeError(f"data must be str, not {data.__class__.__name__}")
return self._path().write_text(data=data, encoding='utf-8')
def mkdir(self, parents: bool = True, exist_ok: bool = False) -> None:
"""
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.
"""
self._path().mkdir(parents=parents, exist_ok=exist_ok)
def cwd(self) -> OMPathABC:
"""
Returns the current working directory as an OMPathABC object.
"""
return type(self)(self._path().cwd().as_posix(), session=self._session)
def unlink(self, missing_ok: bool = False) -> None:
"""
Unlink (delete) the file or directory represented by this path.
"""
self._path().unlink(missing_ok=missing_ok)
def resolve(self, strict: bool = False) -> OMPathABC:
"""
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 based on pathlib.Path.
"""
if not self.is_file():
raise OMSessionException(f"Path {self.as_posix()} is not a file!")
path = self._path()
return path.stat().st_size
class _OMPathRunnerBash(OMPathRunnerABC):
"""
Implementation of OMPathABC which does not use the session data at all. Thus, this implementation can run
locally without any usage of OMC. The special case of this class is the usage of POSIX bash to run all the
commands. Thus, it can be used in WSL or docker.
This class is based on OMPathABC 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(<OM*Path*>.as_posix()).
"""
def is_file(self) -> bool:
"""
Check if the path is a regular file.
"""
cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', f'test -f "{self.as_posix()}"']
try:
subprocess.run(cmdl, check=True)
return True
except subprocess.CalledProcessError:
return False
def is_dir(self) -> bool:
"""
Check if the path is a directory.
"""
cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', f'test -d "{self.as_posix()}"']
try:
subprocess.run(cmdl, check=True)
return True
except subprocess.CalledProcessError:
return False
def is_absolute(self) -> bool:
"""
Check if the path is an absolute path.
"""
cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', f'case "{self.as_posix()}" in /*) exit 0;; *) exit 1;; esac']
try:
subprocess.check_call(cmdl)
return True
except subprocess.CalledProcessError:
return False
def read_text(self) -> str:
"""
Read the content of the file represented by this path as text.
"""
cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', f'cat "{self.as_posix()}"']
result = subprocess.run(cmdl, capture_output=True, check=True)
if result.returncode == 0:
return result.stdout.decode('utf-8')
raise FileNotFoundError(f"Cannot read file: {self.as_posix()}")
def write_text(self, data: str) -> int:
"""
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_escape = self._session.escape_str(data)
cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', f'printf %s "{data_escape}" > "{self.as_posix()}"']
try:
subprocess.run(cmdl, check=True)
return len(data)
except subprocess.CalledProcessError as exc:
raise IOError(f"Error writing data to file {self.as_posix()}!") from exc
def mkdir(self, parents: bool = True, exist_ok: bool = False) -> None:
"""
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_file():
raise OSError(f"The given path {self.as_posix()} exists and is a file!")
if self.is_dir() and not exist_ok:
raise OSError(f"The given path {self.as_posix()} exists and is a directory!")
if not parents and not self.parent.is_dir():
raise FileNotFoundError(f"Parent directory of {self.as_posix()} does not exists!")
cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', f'mkdir -p "{self.as_posix()}"']
try:
subprocess.run(cmdl, check=True)
except subprocess.CalledProcessError as exc:
raise OMSessionException(f"Error on directory creation for {self.as_posix()}!") from exc
def cwd(self) -> OMPathABC:
"""
Returns the current working directory as an OMPathABC object.
"""
cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', 'pwd']
result = subprocess.run(cmdl, capture_output=True, text=True, check=True)
if result.returncode == 0:
return type(self)(result.stdout.strip(), session=self._session)
raise OSError("Can not get current work directory ...")
def unlink(self, missing_ok: bool = False) -> None:
"""
Unlink (delete) the file or directory represented by this path.
"""
if not self.is_file():
raise OSError(f"Can not unlink a directory: {self.as_posix()}!")
if not self.is_file():
return
cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', f'rm "{self.as_posix()}"']
try:
subprocess.run(cmdl, check=True)
except subprocess.CalledProcessError as exc:
raise OSError(f"Cannot unlink file {self.as_posix()}: {exc}") from exc
def resolve(self, strict: bool = False) -> OMPathABC:
"""
Resolve the path to an absolute path. This is done based on available OMC functions.
"""
cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', f'readlink -f "{self.as_posix()}"']
result = subprocess.run(cmdl, capture_output=True, text=True, check=True)
if result.returncode == 0:
return type(self)(result.stdout.strip(), session=self._session)
raise FileNotFoundError(f"Cannot resolve path: {self.as_posix()}")
def size(self) -> int:
"""
Get the size of the file in bytes - implementation based on pathlib.Path.
"""
if not self.is_file():
raise OMSessionException(f"Path {self.as_posix()} is not a file!")
cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', f'stat -c %s "{self.as_posix()}"']
result = subprocess.run(cmdl, capture_output=True, text=True, check=True)
stdout = result.stdout.strip()
if result.returncode == 0:
try:
return int(stdout)
except ValueError as exc:
raise OSError(f"Invalid return value for file size ({self.as_posix()}): {stdout}") from exc
else:
raise OSError(f"Cannot get size for file {self.as_posix()}")
OMPathRunnerLocal = _OMPathRunnerLocal
OMPathRunnerBash = _OMPathRunnerBash
class OMSessionRunnerABC(OMSessionABC, metaclass=abc.ABCMeta):
"""
Implementation based on OMSessionABC without any use of an OMC server.
"""
def __init__(
self,
ompath_runner: Type[OMPathRunnerABC],
timeout: Optional[float] = None,
version: str = "1.27.0",
cmd_prefix: Optional[list[str]] = None,
model_execution_local: bool = True,
) -> None:
super().__init__(timeout=timeout)
self._version = version
if not issubclass(ompath_runner, OMPathRunnerABC):
raise OMSessionException(f"Invalid OMPathRunner class: {type(ompath_runner)}!")
self._ompath_runner = ompath_runner
self.model_execution_local = model_execution_local
if cmd_prefix is not None:
self._cmd_prefix = cmd_prefix
class OMSessionRunner(OMSessionRunnerABC):
"""
Implementation based on OMSessionABC without any use of an OMC server.
"""
def __init__(
self,
ompath_runner: Type[OMPathRunnerABC] = OMPathRunnerLocal,
timeout: Optional[float] = None,
version: str = "1.27.0",
cmd_prefix: Optional[list[str]] = None,
model_execution_local: bool = True,
) -> None:
super().__init__(
ompath_runner=ompath_runner,
timeout=timeout,
version=version,
cmd_prefix=cmd_prefix,
model_execution_local=model_execution_local,
)
def __post_init__(self) -> None:
"""
No connection to an OMC server is created by this class!
"""
def model_execution_prefix(self, cwd: Optional[OMPathABC] = None) -> list[str]:
"""
Helper function which returns a command prefix.
"""
return self.get_cmd_prefix()
def get_version(self) -> str:
"""
We can not provide an OM version as we are not link to an OMC server. Thus, the provided version string is used
directly.
"""
return self._version
def set_workdir(self, workdir: OMPathABC) -> None:
"""
Set the workdir for this session. For OMSessionRunner this is a nop. The workdir must be defined within the
definition of cmd_prefix.
"""
def omcpath(self, *path) -> OMPathABC:
"""
Create an OMCPath object based on the given path segments and the current OMCSession* class.
"""
return self._ompath_runner(*path, session=self)
def omcpath_tempdir(self, tempdir_base: Optional[OMPathABC] = None) -> OMPathABC:
"""
Get a temporary directory without using OMC.
"""
if tempdir_base is None:
tempdir_str = tempfile.gettempdir()
tempdir_base = self.omcpath(tempdir_str)
return self._tempdir(tempdir_base=tempdir_base)
def sendExpression(self, expr: str, parsed: bool = True) -> Any:
raise OMSessionException(f"{self.__class__.__name__} does not uses an OMC server!")