/
mapdl_grpc.py
3165 lines (2593 loc) · 105 KB
/
mapdl_grpc.py
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
"""gRPC specific class and methods for the MAPDL gRPC client """
import fnmatch
from functools import wraps
import glob
import io
import os
import pathlib
import re
import shutil
import subprocess
import tempfile
import threading
import time
from typing import Optional
import warnings
from warnings import warn
import weakref
from ansys.tools.versioning.utils import version_string_as_tuple
import grpc
from grpc._channel import _InactiveRpcError, _MultiThreadedRendezvous
import numpy as np
import psutil
MSG_IMPORT = """There was a problem importing the ANSYS MAPDL API module `ansys-api-mapdl`.
Please make sure you have the latest updated version using:
'pip install ansys-api-mapdl' or 'pip install --upgrade ansys-api-mapdl'
If this does not solve it, please reinstall 'ansys.mapdl.core'
or contact Technical Support at 'https://github.com/pyansys/pymapdl'."""
try:
from ansys.api.mapdl.v0 import ansys_kernel_pb2 as anskernel
from ansys.api.mapdl.v0 import mapdl_pb2 as pb_types
from ansys.api.mapdl.v0 import mapdl_pb2_grpc as mapdl_grpc
except ImportError: # pragma: no cover
raise ImportError(MSG_IMPORT)
from ansys.mapdl.core import _LOCAL_PORTS, __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 (
MapdlConnectionError,
MapdlExitedError,
MapdlRuntimeError,
protect_grpc,
)
from ansys.mapdl.core.mapdl import _MapdlCore
from ansys.mapdl.core.mapdl_types import MapdlInt
from ansys.mapdl.core.misc import (
check_valid_ip,
last_created,
random_string,
requires_package,
run_as_prep7,
supress_logging,
)
# Checking if tqdm is installed.
# If it is, the default value for progress_bar is true.
try:
from tqdm import tqdm
_HAS_TQDM = True
except ModuleNotFoundError: # pragma: no cover
_HAS_TQDM = False
TMP_VAR = "__tmpvar__"
VOID_REQUEST = anskernel.EmptyRequest()
# Default 256 MB message length
MAX_MESSAGE_LENGTH = int(os.environ.get("PYMAPDL_MAX_MESSAGE_LENGTH", 256 * 1024**2))
VAR_IR = 9 # Default variable number for automatic variable retrieving (/post26)
def chunk_raw(raw, save_as):
with io.BytesIO(raw) as f:
while True:
piece = f.read(DEFAULT_FILE_CHUNK_SIZE)
length = len(piece)
if length == 0:
return
yield pb_types.UploadFileRequest(
file_name=os.path.basename(save_as),
chunk=anskernel.Chunk(payload=piece, size=length),
)
def get_file_chunks(filename, progress_bar=False):
"""Serializes a file into chunks"""
pbar = None
if progress_bar:
if not _HAS_TQDM: # pragma: no cover
raise ModuleNotFoundError(
"To use the keyword argument 'progress_bar', you need to have "
"installed the `tqdm` package. "
"To avoid this message set `progress_bar=False`."
)
n_bytes = os.path.getsize(filename)
base_name = os.path.basename(filename)
pbar = tqdm(
total=n_bytes,
desc=f"Uploading {base_name}",
unit="B",
unit_scale=True,
unit_divisor=1024,
)
with open(filename, "rb") as f:
while True:
piece = f.read(DEFAULT_FILE_CHUNK_SIZE)
length = len(piece)
if length == 0:
if pbar is not None:
pbar.close()
return
if pbar is not None:
pbar.update(length)
chunk = anskernel.Chunk(payload=piece, size=length)
yield pb_types.UploadFileRequest(
file_name=os.path.basename(filename), chunk=chunk
)
def save_chunks_to_file(
chunks, filename, progress_bar=False, file_size=None, target_name=""
):
"""Saves chunks to a local file
Returns
-------
file_size : int
File size saved in bytes. ``0`` means no file was written.
"""
pbar = None
if progress_bar:
if not _HAS_TQDM: # pragma: no cover
raise ModuleNotFoundError(
f"To use the keyword argument 'progress_bar', you need to have installed the 'tqdm' package."
"To avoid this message you can set 'progress_bar=False'."
)
pbar = tqdm(
total=file_size,
desc="Downloading %s" % target_name,
unit="B",
unit_scale=True,
unit_divisor=1024,
)
file_size = 0
with open(filename, "wb") as f:
for chunk in chunks:
f.write(chunk.payload)
payload_size = len(chunk.payload)
file_size += payload_size
if pbar is not None:
pbar.update(payload_size)
if pbar is not None:
pbar.close()
return file_size
class RepeatingTimer(threading.Timer):
"""Run a function repeately"""
def run(self):
while not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.wait(self.interval)
class MapdlGrpc(_MapdlCore):
"""This class connects to a GRPC MAPDL server and allows commands
to be passed to a persistent session.
Parameters
----------
ip : str, optional
IP address to connect to the server. The default is 'localhost'.
port : int, optional
Port to connect to the MAPDL server. The default is ``50052``.
timeout : float
Maximum allowable time to connect to the MAPDL server.
loglevel : str, optional
Sets which messages are printed to the console. Default
'INFO' prints out all ANSYS messages, 'WARNING` prints only
messages containing ANSYS warnings, and 'ERROR' prints only
error messages.
cleanup_on_exit : bool, optional
Exit MAPDL when Python exits or when this instance is garbage
collected.
set_no_abort : bool, optional
Sets MAPDL to not abort at the first error within /BATCH mode.
The default is ``True``.
remove_temp_dir : bool, optional
When this parameter is ``True``, the MAPDL working directory will be
deleted when MAPDL is exited provided that it is within the temporary
user directory. The default is ``False``.
log_file : bool, optional
Copy the log to a file called `logs.log` located where the
python script is executed. The default is ``True``.
print_com : bool, optional
Print the command ``/COM`` arguments to the standard output.
The default is ``False``.
channel : grpc.Channel, optional
gRPC channel to use for the connection. Can be used as an
alternative to the ``ip`` and ``port`` parameters.
remote_instance : ansys.platform.instancemanagement.Instance
The corresponding remote instance when MAPDL is launched through
PyPIM. This instance will be deleted when calling
:func:`Mapdl.exit <ansys.mapdl.core.Mapdl.exit>`.
Examples
--------
Connect to an instance of MAPDL already running on locally on the
default port 50052.
>>> from ansys.mapdl import core as pymapdl
>>> mapdl = pymapdl.Mapdl()
Connect to an instance of MAPDL running on the LAN on a default port.
>>> mapdl = pymapdl.Mapdl('192.168.1.101')
Connect to an instance of MAPDL running on the LAN on a non-default port.
>>> mapdl = pymapdl.Mapdl('192.168.1.101', port=60001)
If you wish to customize the channel, you can also directly connect
directly to gRPC channels. For example, if you wanted to create an insecure
channel with a maximum message length of 8 MB.
>>> import grpc
>>> channel = grpc.insecure_channel(
... '127.0.0.1:50052',
... options=[
... ("grpc.max_receive_message_length", 8*1024**2),
... ],
... )
>>> mapdl = pymapdl.Mapdl(channel=channel)
"""
# Required by `_name` method to be defined before __init__ be
_ip = None
_port = None
def __init__(
self,
ip=None,
port=None,
timeout=15,
loglevel="WARNING",
log_file=False,
cleanup_on_exit=False,
log_apdl=None,
set_no_abort=True,
remove_temp_files=None,
remove_temp_dir_on_exit=False,
print_com=False,
channel=None,
remote_instance=None,
**start_parm,
):
"""Initialize connection to the mapdl server"""
if remove_temp_files is not None: # pragma: no cover
warnings.warn(
"The option ``remove_temp_files`` is being deprecated and it will be removed by PyMAPDL version 0.66.0.\n"
"Please use ``remove_temp_dir_on_exit`` instead.",
DeprecationWarning,
stacklevel=2,
)
remove_temp_dir_on_exit = remove_temp_files
remove_temp_files = None
self.__distributed = None
self._remote_instance = remote_instance
if channel is not None:
if ip is not None or port is not None:
raise ValueError(
"If `channel` is specified, neither `port` nor `ip` can be specified."
)
if ip is None:
ip = "127.0.0.1"
# port and ip are needed to setup the log
self._port = port
check_valid_ip(ip)
self._ip = ip
super().__init__(
loglevel=loglevel,
log_apdl=log_apdl,
log_file=log_file,
print_com=print_com,
**start_parm,
)
self._mode = "grpc"
# gRPC request specific locks as these gRPC request are not thread safe
self._vget_lock = False
self._get_lock = False
self._prioritize_thermal = False
self._locked = False # being used within MapdlPool
self._stub = None
self._cleanup = cleanup_on_exit
self.__remove_temp_dir_on_exit = remove_temp_dir_on_exit
self._jobname = start_parm.get("jobname", "file")
self._path = start_parm.get("run_location", None)
self._busy = False # used to check if running a command on the server
self._local = ip in ["127.0.0.1", "127.0.1.1", "localhost"]
if "local" in start_parm: # pragma: no cover # allow this to be overridden
self._local = start_parm["local"]
self._health_response_queue = None
self._exiting = False
self._exited = None
self._mute = False
self._db = None
self.__server_version = None
# saving for later use (for example open_gui)
start_parm["ip"] = ip
start_parm["port"] = port
self._start_parm = start_parm
if port is None:
from ansys.mapdl.core.launcher import MAPDL_DEFAULT_PORT
port = MAPDL_DEFAULT_PORT
self._state = None
self._stub = None
self._timeout = timeout
self._pids = []
if channel is None:
self._log.debug("Creating channel to %s:%s", ip, port)
self._channel = self._create_channel(ip, port)
else:
self._log.debug("Using provided channel")
self._channel = channel
# connect and validate to the channel
self._mapdl_process = start_parm.pop("process", None)
# Queueing the stds
if self._mapdl_process:
self._create_process_stds_queue()
try:
self._multi_connect(timeout=timeout)
except MapdlConnectionError as err: # pragma: no cover
self._post_mortem_checks()
self._log.debug(
"The error wasn't catch by the post-mortem checks.\nThe stdout is printed now:"
)
self._log.debug(self._stdout)
raise err # Raise original error if we couldn't catch it in post-mortem analysis
else:
self._log.debug("Connection established")
# Avoiding muting when connecting to the session
# It might trigger some errors later on if not.
self._run("/gopr")
# initialize mesh, post processing, and file explorer interfaces
try:
from ansys.mapdl.core.mesh_grpc import MeshGrpc
self._mesh_rep = MeshGrpc(self)
except ModuleNotFoundError: # pragma: no cover
self._mesh_rep = None
# Run at connect
self._run_at_connect()
# HOUSEKEEPING:
# Set to not abort after encountering errors. Otherwise, many
# failures in a row will cause MAPDL to exit without returning
# anything useful. Also avoids abort in batch mode if set.
if set_no_abort:
self._set_no_abort()
# double check we have access to the local path if not
# explicitly specified
if "local" not in start_parm:
self._verify_local()
# only cache process IDs if launched locally
if self._local and "exec_file" in start_parm:
self._cache_pids()
def _create_process_stds_queue(self, process=None):
from ansys.mapdl.core.launcher import (
_create_queue_for_std, # Avoid circular import error
)
if not process:
process = self._mapdl_process
self._stdout_queue, self._stdout_thread = _create_queue_for_std(process.stdout)
self._stderr_queue, self._stderr_thread = _create_queue_for_std(process.stderr)
def _create_channel(self, ip, port):
"""Create an insecured grpc channel."""
# open the channel
channel_str = f"{ip}:{port}"
self._log.debug("Opening insecure channel at %s", channel_str)
return grpc.insecure_channel(
channel_str,
options=[
("grpc.max_receive_message_length", MAX_MESSAGE_LENGTH),
],
)
def _multi_connect(self, n_attempts=5, timeout=15):
"""Try to connect over a series of attempts to the channel.
Parameters
----------
n_attempts : int, optional
Number of connection attempts.
timeout : float, optional
Total timeout.
"""
# This prevents a single failed connection from blocking other attempts
connected = False
attempt_timeout = int(timeout / n_attempts)
max_time = time.time() + timeout
i = 0
while time.time() < max_time and i <= n_attempts:
self._log.debug("Connection attempt %d", i + 1)
connected = self._connect(timeout=attempt_timeout)
i += 1
if connected:
self._log.debug("Connected")
break
else: # pragma: no cover
# Check if mapdl process is alive
msg = (
f"Unable to connect to MAPDL gRPC instance at {self._channel_str}.\n"
f"Reached either maximum amount of connection attempts ({n_attempts}) or timeout ({timeout} s)."
)
if self._mapdl_process is not None and psutil.pid_exists(
self._mapdl_process.pid
):
# Process is alive
raise MapdlConnectionError(
msg
+ f"The MAPDL process seems to be alive (PID: {self._mapdl_process.pid}) but PyMAPDL cannot connect to it."
)
else:
pid_msg = (
f" PID: {self._mapdl_process.pid}"
if self._mapdl_process is not None
else ""
)
raise MapdlConnectionError(
msg + f"The MAPDL process has died{pid_msg}."
)
self._exited = False
def _is_alive_subprocess(self):
"""Returns:
* True if the PID is alive.
* False if it is not.
* None if there was no process
"""
if self._mapdl_process:
return psutil.pid_exists(self._mapdl_process.pid)
@property
def process_is_alive(self):
return self._is_alive_subprocess()
def _post_mortem_checks(self):
"""Check possible reasons for not having a successful connection."""
# Check early exit
process = self._mapdl_process
if process is None or not self.is_grpc:
return
# check the stdout for any errors
self._read_stds()
self._check_stds()
def _read_stds(self):
"""Read the stdout and stderr from the subprocess."""
from ansys.mapdl.core.launcher import (
_get_std_output, # Avoid circular import error
)
if self._mapdl_process is None:
return
self._log.debug("Reading stdout")
self._stdout = _get_std_output(self._stdout_queue)
self._log.debug(f"Read stdout: {self._stdout[:20]}")
self._log.debug("Reading stderr")
self._stderr = _get_std_output(self._stderr_queue)
self._log.debug(f"Read stderr: {self._stderr[:20]}")
def _check_stds(self, stdout=None, stderr=None):
"""Check the stdout and stderr for any errors."""
if stdout is None:
stdout = self._stdout
if stderr is None:
stderr = self._stderr
if not stderr:
self._log.debug("MAPDL exited without stderr.")
else:
self._parse_stderr()
if not stdout:
self._log.debug("MAPDL exited without stdout.")
else:
self._parse_stdout()
def _parse_stderr(self, stderr=None):
"""Parse the stderr for any errors."""
if stderr is None:
stderr = self._stderr
errs = self._parse_std(stderr)
if errs:
self._log.debug("MAPDL exited with errors in stderr.")
# Custom errors
self._raise_custom_stds_errors(errs)
def _parse_stdout(self, stdout=None):
"""Parse the stdout for any errors."""
if stdout is None:
stdout = self._stdout
errs = self._parse_std(stdout)
if errs:
self._log.debug("MAPDL exited with errors in stdout.")
# Custom errors
self._raise_custom_stds_errors(errs)
def _parse_std(self, std):
# check for errors in stderr
# split the stderr into groups
if isinstance(std, list):
std = "\n".join(std)
std = std.replace("\n\n", "\n")
groups = std.split("\r\n\r\n")
errs = []
for each in groups:
if (
"error" in each.lower()
or "fatal" in each.lower()
or "warning" in each.lower()
):
errs.append(each)
if errs:
errs = "\r\n\r\n".join(errs)
errs = errs.replace("\r\n", "\n")
else:
errs = ""
return errs
def _raise_custom_stds_errors(self, errs_message):
"""Custom errors for stdout and stderr."""
if "Only one usage of each socket address" in errs_message:
raise MapdlConnectionError(
f"A process is already running on the specified port ({self._port}).\n"
"Only one usage of each socket address (protocol/network address/port) is normally permitted.\n"
f"\nFull error message:\n{errs_message.split('########',1)[0]}"
)
else:
raise MapdlConnectionError(errs_message)
@property
def _channel_str(self):
"""Return the target string.
Generally of the form of "ip:port", like "127.0.0.1:50052".
"""
channel = self._channel
while channel is not None:
# When creating interceptors, channels have a nested "_channel" member
# containing the intercepted channel.
# Only the actual channel contains the "target" member describing the address
if hasattr(channel, "target"):
return channel.target().decode()
channel = getattr(channel, "_channel", None)
# This method is relying on grpc channel's private attributes, fallback in case
# it does not exist
return "unknown" # pragma: no cover Unreachable in the current gRPC version
def _verify_local(self):
"""Check if Python is local to the MAPDL instance."""
# Verify if python has assess to the MAPDL directory.
if self._local:
directory = self.directory
if self._jobname is None:
jobname = self.jobname
else:
jobname = self._jobname
lockfile = os.path.join(directory, jobname + ".err")
lockfile0 = os.path.join(directory, jobname + "0.err")
if os.path.isfile(lockfile):
return
if os.path.isfile(lockfile0):
return
self._local = False
@property
def mute(self):
"""Silence the response from all MAPDL functions unless
explicitly set to ``True``.
Returns
-------
bool
Current state of the mute.
Examples
--------
>>> mapdl.mute = True
>>> mapdl.prep7()
''
Temporarily override the instance setting this with
``mute=False``. This is useful for methods that parse the
MAPDL output like ``k``.
>>> mapdl.k('', 1, 1, 1, mute=False)
1
"""
return self._mute
@mute.setter
def mute(self, value):
self._mute = value
def __repr__(self):
info = super().__repr__()
return info
def _connect(self, timeout=5, enable_health_check=False):
"""Establish a gRPC channel to a remote or local MAPDL instance.
Parameters
----------
timeout : float
Time in seconds to wait until the connection has been established
"""
self._state = grpc.channel_ready_future(self._channel)
self._stub = mapdl_grpc.MapdlServiceStub(self._channel)
# verify connection
tstart = time.time()
while ((time.time() - tstart) < timeout) and not self._state._matured:
time.sleep(0.01)
if not self._state._matured: # pragma: no cover
return False
self._log.debug("Established connection to MAPDL gRPC")
# keeps mapdl session alive
self._timer = None
if not self._local:
self._initialised = threading.Event()
self._t_trigger = time.time()
self._t_delay = 30
self._timer = threading.Thread(
target=MapdlGrpc._threaded_heartbeat,
args=(weakref.proxy(self),),
)
self._timer.daemon = True
self._timer.start()
# enable health check
if enable_health_check:
self._enable_health_check()
return True
@property
def _server_version(self):
"""Return the server version.
Examples
--------
>>> mapdl._server_version
(0, 3, 0)
Uses cached ``__server_version`` to avoid unnecessary communication.
"""
# check cache
if self.__server_version is None:
self.__server_version = self._get_server_version()
return self.__server_version
def _get_server_version(self):
"""Request version from gRPC server.
Generally tied to the release version unless on a development release.
2020R2 --> 0.0.0 (or any unknown version)
2021R1 --> 0.3.0
2021R2 --> 0.4.0
2022R1 --> 0.X.X
"""
sver = (0, 0, 0)
verstr = self._ctrl("VERSION")
if verstr:
sver = version_string_as_tuple(verstr)
return sver
def _enable_health_check(self):
"""Places the status of the health check in _health_response_queue"""
# lazy imports here to speed up module load
from grpc_health.v1 import health_pb2, health_pb2_grpc
def _consume_responses(response_iterator, response_queue):
try:
for response in response_iterator:
response_queue.put(response)
# NOTE: we're doing absolutely nothing with this as
# this point since the server side health check
# doesn't change state.
except Exception as err:
if self._exiting:
return
self._exited = True
raise MapdlExitedError("Lost connection with MAPDL server") from None
# enable health check
from queue import Queue
request = health_pb2.HealthCheckRequest()
self._health_stub = health_pb2_grpc.HealthStub(self._channel)
rendezvous = self._health_stub.Watch(request)
# health check feature implemented after 2020R2
try:
status = rendezvous.next()
except Exception as err:
if err.code().name != "UNIMPLEMENTED":
raise err
return
if status.status != health_pb2.HealthCheckResponse.SERVING:
raise MapdlRuntimeError(
"Unable to enable health check and/or connect to" " the MAPDL server"
)
self._health_response_queue = Queue()
# allow main process to exit by setting daemon to true
thread = threading.Thread(
target=_consume_responses,
args=(rendezvous, self._health_response_queue),
daemon=True,
)
thread.start()
def _launch(self, start_parm, timeout=10):
"""Launch a local session of MAPDL in gRPC mode.
This should only need to be used for legacy ``open_gui``
"""
if not self._local:
raise MapdlRuntimeError(
"Can only launch the GUI with a local instance of MAPDL"
)
from ansys.mapdl.core.launcher import launch_grpc
self._exited = False # reset exit state
port, directory, process = launch_grpc(**start_parm)
self._connect(port)
# may need to wait for viable connection in open_gui case
tmax = time.time() + timeout
success = False
while time.time() < tmax:
try:
self.prep7()
success = True
break
except:
pass
if not success:
raise MapdlConnectionError("Unable to reconnect to MAPDL")
@supress_logging
def _set_no_abort(self):
"""Do not abort MAPDL."""
self.nerr(abort=-1, mute=True)
def _run_at_connect(self):
"""Run house-keeping commands when initially connecting to MAPDL."""
# increase the number of variables allowed in POST26 to the maximum
with self.run_as_routine("POST26"):
self.numvar(200, mute=True)
def _reset_cache(self):
"""Reset cached items."""
if self._mesh_rep is not None:
self._mesh_rep._reset_cache()
if self._geometry is not None:
self._geometry._reset_cache()
@property
@requires_package("pyvista")
def _mesh(self):
return self._mesh_rep
def _run(self, cmd, verbose=False, mute=None):
"""Sens a command and return the response as a string.
Parameters
----------
cmd : str
Valid MAPDL command.
verbose : bool, optional
Print the response of a command while it is being run.
mute : bool, optional
Whether output is to be sent from the gRPC server. The default
is ``None``, in which case the global setting specified by
``mapdl.mute = <bool>`` is used, which is ``False`` by default.
Examples
--------
Run a basic command.
>>> mapdl.run('/PREP7')
Run a command and suppress its output.
>>> mapdl.run('/PREP7', mute=True)
Run a command and stream its output while it is being run.
>>> mapdl.run('/PREP7', verbose=True)
"""
if mute is None:
mute = self._mute
if self._exited:
raise MapdlExitedError
# don't allow empty commands
if not cmd.strip():
raise ValueError("Empty commands not allowed")
if len(cmd) > 639: # CMD_MAX_LENGTH
raise ValueError("Maximum command length must be less than 640 characters")
self._busy = True
if verbose:
response = self._send_command_stream(cmd, True)
else:
response = self._send_command(cmd, mute=mute)
self._busy = False
return response.strip()
@property
def busy(self):
"""True when MAPDL gRPC server is executing a command"""
return self._busy
@protect_grpc
def _send_command(self, cmd, mute=False):
"""Send a MAPDL command and return the response as a string"""
opt = ""
if mute:
opt = "MUTE" # suppress any output
request = pb_types.CmdRequest(command=cmd, opt=opt)
# TODO: Capture keyboard exception and place this in a thread
grpc_response = self._stub.SendCommand(request)
resp = grpc_response.response
if resp is not None:
return resp.strip()
return None
@protect_grpc
def _send_command_stream(self, cmd, verbose=False):
"""Send a command and expect a streaming response"""
request = pb_types.CmdRequest(command=cmd)
metadata = [("time_step_stream", "100")]
stream = self._stub.SendCommandS(request, metadata=metadata)
response = []
for item in stream:
cmdout = "\n".join(item.cmdout)
if verbose:
print(cmdout)
response.append(cmdout.strip())
return "".join(response)
def _threaded_heartbeat(self):
"""To be called from a thread to verify mapdl instance is alive"""
self._initialised.set()
while True:
if self._exited:
break
try:
time.sleep(self._t_delay)
if not self.is_alive:
break
except ReferenceError:
break
except Exception:
continue
def exit(self, save=False, force=False): # pragma: no cover
"""Exit MAPDL.
Parameters
----------
save : bool, optional
Save the database on exit. The default is ``False``.
force : bool, optional
Override any environment variables that may inhibit exiting MAPDL.
Notes
-----
If ``PYMAPDL_START_INSTANCE`` is set to ``False`` (generally set in
remote testing or documentation build), then this will be
ignored. Override this behavior with ``force=True`` to always force
exiting MAPDL regardless of your local environment.
Examples
--------
>>> mapdl.exit()
"""
# check if permitted to start (and hence exit) instances
if self._exited is None:
return # Some edge cases the class object is not completely initialized but the __del__ method
# is called when exiting python. So, early exit here instead an error in the following
# self.directory command.
# See issue #1796
elif self._exited:
# Already exited.
return
else:
mapdl_path = self.directory
if save:
self._log.debug("Saving MAPDL database")
self.save()