Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

revert: "Merge branches 'feat/piping-MAPDL-output-to-a-given-file', 'main' and 'main' of https://github.com/ansys/pymapdl" #3607

Merged
merged 1 commit into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion doc/changelog.d/3596.miscellaneous.md

This file was deleted.

49 changes: 10 additions & 39 deletions src/ansys/mapdl/core/launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
import subprocess # nosec B404
import threading
import time
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Union
import warnings

import psutil
Expand Down Expand Up @@ -115,7 +115,6 @@ def version_from_path(*args, **kwargs):
"license_type",
"log_apdl",
"loglevel",
"mapdl_output",
"mode",
"nproc",
"override",
Expand Down Expand Up @@ -438,7 +437,6 @@ def launch_grpc(
run_location: str = None,
env_vars: Optional[Dict[str, str]] = None,
launch_on_hpc: bool = False,
mapdl_output: Optional[str] = None,
) -> subprocess.Popen:
"""Start MAPDL locally in gRPC mode.

Expand All @@ -458,9 +456,6 @@ def launch_grpc(
If running on an HPC, this needs to be :class:`True` to avoid the
temporary file creation on Windows.

mapdl_output : str, optional
Whether redirect MAPDL console output (stdout and stderr) to a file.

Returns
-------
subprocess.Popen
Expand Down Expand Up @@ -492,13 +487,6 @@ def launch_grpc(
"\n============"
)

if mapdl_output:
stdout = open(str(mapdl_output), "wb", 0)
stderr = subprocess.STDOUT
else:
stdout = subprocess.PIPE
stderr = subprocess.PIPE

if os.name == "nt":
# getting tmp file name
if not launch_on_hpc:
Expand All @@ -517,8 +505,8 @@ def launch_grpc(
shell=shell, # sbatch does not work without shell.
cwd=run_location,
stdin=subprocess.DEVNULL,
stdout=stdout,
stderr=stderr,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env_vars=env_vars,
)

Expand Down Expand Up @@ -566,7 +554,7 @@ def check_mapdl_launch(

if os.name == "posix" and not ON_WSL:
LOG.debug("Checking if gRPC server is alive.")
_check_server_is_alive(stdout_queue, timeout)
_check_server_is_alive(stdout_queue, run_location, timeout)

except MapdlDidNotStart as e: # pragma: no cover
msg = (
Expand Down Expand Up @@ -608,11 +596,7 @@ def _check_file_error_created(run_location, timeout):
raise MapdlDidNotStart(msg)


def _check_server_is_alive(stdout_queue, timeout):
if not stdout_queue:
LOG.debug("No STDOUT queue. Not checking MAPDL this way.")
return

def _check_server_is_alive(stdout_queue, run_location, timeout):
t0 = time.time()
empty_attemps = 3
empty_i = 0
Expand Down Expand Up @@ -645,9 +629,6 @@ def _check_server_is_alive(stdout_queue, timeout):


def _get_std_output(std_queue, timeout=1):
if not std_queue:
return [None]

lines = []
reach_empty = False
t0 = time.time()
Expand All @@ -661,15 +642,10 @@ def _get_std_output(std_queue, timeout=1):
return lines


def _create_queue_for_std(
std: subprocess.PIPE,
) -> Tuple[Optional[Queue[str]], Optional[threading.Thread]]:
def _create_queue_for_std(std):
"""Create a queue and thread objects for a given PIPE std"""
if not std:
LOG.debug("No STDOUT. Not checking MAPDL this way.")
return None, None

def enqueue_output(out: subprocess.PIPE, queue: Queue[str]) -> None:
def enqueue_output(out, queue):
try:
for line in iter(out.readline, b""):
queue.put(line)
Expand All @@ -679,16 +655,16 @@ def enqueue_output(out: subprocess.PIPE, queue: Queue[str]) -> None:
# ValueError: PyMemoryView_FromBuffer(): info -> buf must not be NULL
pass

q: Queue[str] = Queue()
t: threading.Thread = threading.Thread(target=enqueue_output, args=(std, q))
q = Queue()
t = threading.Thread(target=enqueue_output, args=(std, q))
t.daemon = True # thread dies with the program
t.start()

return q, t


def launch_remote_mapdl(
version: Optional[str] = None,
version: str = None,
cleanup_on_exit: bool = True,
) -> MapdlGrpc:
"""Start MAPDL remotely using the product instance management API.
Expand Down Expand Up @@ -1044,7 +1020,6 @@ def launch_mapdl(
version: Optional[Union[int, str]] = None,
running_on_hpc: bool = True,
launch_on_hpc: bool = False,
mapdl_output: Optional[str] = None,
**kwargs: Dict[str, Any],
) -> Union[MapdlGrpc, "MapdlConsole"]:
"""Start MAPDL locally.
Expand Down Expand Up @@ -1230,9 +1205,6 @@ def launch_mapdl(
to specify the scheduler arguments as a string or as a dictionary.
For more information, see :ref:`ref_hpc_slurm`.

mapdl_output : str, optional
Redirect the MAPDL console output to a given file.

kwargs : dict, Optional
These keyword arguments are interface-specific or for
development purposes. For more information, see Notes.
Expand Down Expand Up @@ -1603,7 +1575,6 @@ def launch_mapdl(
run_location=args["run_location"],
env_vars=env_vars,
launch_on_hpc=args.get("launch_on_hpc"),
mapdl_output=args.get("mapdl_output"),
)

if args["launch_on_hpc"]:
Expand Down
4 changes: 2 additions & 2 deletions src/ansys/mapdl/core/mapdl_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,7 @@ def _read_stds(self):
_get_std_output, # Avoid circular import error
)

if self._mapdl_process is None or not self._mapdl_process.stdout:
if self._mapdl_process is None:
return

self._log.debug("Reading stdout")
Expand Down Expand Up @@ -2691,7 +2691,7 @@ def _download_as_raw(self, target_name: str) -> str:
@property
def is_alive(self) -> bool:
"""True when there is an active connect to the gRPC server"""
if self.channel_state not in ["IDLE", "READY", None]:
if self.channel_state not in ["IDLE", "READY"]:
self._log.debug(
"MAPDL instance is not alive because the channel is not 'IDLE' o 'READY'."
)
Expand Down
47 changes: 0 additions & 47 deletions tests/test_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -1947,50 +1947,3 @@ def raising():
@patch("ansys.mapdl.core.launcher.check_valid_ansys", raising)
def test_check_has_mapdl_failed():
assert check_has_mapdl() is False


@requires("local")
@requires("nostudent")
def test_mapdl_output(tmpdir):
mapdl_output = os.path.join(tmpdir, "apdl.out")
mapdl = launch_mapdl(mapdl_output=mapdl_output)

assert os.path.exists(mapdl_output)

with open(mapdl_output, "r") as fid:
content = fid.read()

assert "Beta activation of the GRPC server." in content
assert "### START GRPC SERVER ###" in content
assert " Server listening on" in content

mapdl.exit()


def test_mapdl_output_patch(tmpdir):
def submitter(**kwargs):
from _io import FileIO

from ansys.mapdl.core.launcher import submitter

# Checking we are passing the arguments
assert isinstance(kwargs["stdout"], FileIO)
assert kwargs["stderr"] is subprocess.STDOUT

return submitter(**kwargs)

with patch("ansys.mapdl.core.launcher.submitter") as mck_sub:

mapdl_output = os.path.join(tmpdir, "apdl.out")
mapdl = launch_mapdl(mapdl_output=mapdl_output)

assert os.path.exists(mapdl_output)

with open(mapdl_output, "r") as fid:
content = fid.read()

assert "Beta activation of the GRPC server." in content
assert "### START GRPC SERVER ###" in content
assert " Server listening on" in content

mapdl.exit()
Loading