Skip to content
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: 1 addition & 0 deletions doc/changelog.d/226.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Remote rendering 5.2c - Wire ParaView mode in VISOR
13 changes: 11 additions & 2 deletions src/ansys/visor/viewer/api/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from ansys.visor.viewer.api.visor_cache import VisorCache
from ansys.visor.viewer.config import settings
from ansys.visor.viewer.core.net import find_unused_port
from ansys.visor.viewer.core.pvserver_address import PvserverAddress
from ansys.visor.viewer.core.visor_enums import RenderingMode
from ansys.visor.viewer.core.visor_logging import VisorLogger

Expand Down Expand Up @@ -139,6 +140,7 @@ def __init__(self):
self.settings.default_port,
self.settings.default_standalone,
self.settings.default_dark_mode,
None,
)[0]

# Configure FastAPI application
Expand Down Expand Up @@ -209,12 +211,15 @@ async def connect_or_initialize_server(self, init_props: InitProps = Body(
else settings.default_dark_mode
rendering_mode = init_props.rendering_mode if init_props.rendering_mode is not None\
else RenderingMode.CLIENT
pvserver = init_props.pvserver_address(self.settings.default_pvserver_address())\
if rendering_mode == RenderingMode.PARAVIEW else None
# initialize an instance of Visor
self.visualizer, warnings = self._connect_or_initialize_visualizer(
host,
port,
standalone,
dark_mode,
pvserver,
rendering_mode
)
url = self._get_url(host, port)
Expand Down Expand Up @@ -440,17 +445,21 @@ def _connect_or_initialize_visualizer(
port: int,
standalone: bool,
dark_mode: bool,
pvserver: PvserverAddress | None,
rendering_mode: RenderingMode = RenderingMode.CLIENT,
) -> Tuple[Visor, str]:
"""Connect to a visualizer instance with the given host and port if one
exists; otherwise, create a new visualizer instance on that host and port."""
exists; otherwise, create a new visualizer instance on that host and port.
pvserver is the PARAVIEW session's address, None for other modes."""
url = self._get_url(host, port)
msg = (
f'Connecting to Visor server on {url} (standalone={standalone}, dark_mode={dark_mode})'
)
logger.info(msg)
# Initialize the server with the given port, host and client distribution path
instance, warnings = VisorCache.get_instance(url, rendering_mode, standalone, dark_mode, self.trame_log_dir)
instance, warnings = VisorCache.get_instance(
url, rendering_mode, standalone, dark_mode, pvserver, self.trame_log_dir
)
return instance, warnings


Expand Down
28 changes: 21 additions & 7 deletions src/ansys/visor/viewer/api/visor_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
from typing import Dict, Tuple

from ansys.visor.viewer import Visor
from ansys.visor.viewer.app.paraview.paraview_handle import VisorParaviewHandle
from ansys.visor.viewer.app.visor_vtk import VisorVTK
from ansys.visor.viewer.core.pvserver_address import PvserverAddress
from ansys.visor.viewer.core.visor_enums import RenderingMode
from ansys.visor.viewer.core.visor_logging import VisorLogger

Expand All @@ -20,10 +22,13 @@ def get_instance(cls,
rendering_mode: RenderingMode,
standalone: bool,
dark_mode: bool,
pvserver: PvserverAddress | None,
trame_log_dir: str | None = None,
) -> Tuple["Visor", str | None]:
"""Get an instance of Visor from the cache or create a new one.

pvserver is the PARAVIEW session's address, None for other modes.

Returns
-------
tuple[Visor, list[str], bool]
Expand All @@ -36,16 +41,16 @@ def get_instance(cls,
f"Visor instance not found on url {url}. "
f"Creating a new one with rendering_mode={rendering_mode},"
f"standalone={standalone},"
f"dark_mode={dark_mode}, trame_log_dir={trame_log_dir}."
f"dark_mode={dark_mode}, pvserver={pvserver}, trame_log_dir={trame_log_dir}."
)
logger.warning(msg)
cls.create_instance(url, rendering_mode, standalone, dark_mode, trame_log_dir)
cls.create_instance(url, rendering_mode, standalone, dark_mode, pvserver, trame_log_dir)
instance = cls._instances[url]
if instance is None:
raise Exception(f"Failed to create Visor instance for url {url}.")
return instance, None

warnings = cls.validate_args(url, rendering_mode, standalone, dark_mode, trame_log_dir)
warnings = cls.validate_args(url, rendering_mode, standalone, dark_mode, pvserver, trame_log_dir)
return cls._instances.get(url), warnings

@classmethod
Expand All @@ -55,13 +60,14 @@ def validate_args(
rendering_mode: RenderingMode,
standalone: bool,
dark_mode: bool,
pvserver: PvserverAddress | None,
trame_log_dir: str
) -> str:
"""Validate the arguments for this instance."""
warnings = None
existing = cls._instances[url]
ignored = []
if rendering_mode is not None and not isinstance(existing, VisorVTK):
if rendering_mode is not None and not isinstance(existing, (VisorVTK, VisorParaviewHandle)):
# TODO: update to check the VisorVtkLocal class type once VisorVTK has
# been renamed VisorVtk with VisorVtkLocal as a concrete implementation/subclass.
ignored.append(
Expand All @@ -75,6 +81,12 @@ def validate_args(
ignored.append(
f"dark_mode={dark_mode} (existing value: {existing.dark_mode})"
)
if pvserver is not None:
existing_pvserver = existing.pvserver if isinstance(existing, VisorParaviewHandle) else None
if existing_pvserver != pvserver:
ignored.append(
f"pvserver={pvserver} (existing value: {existing_pvserver})"
)
if ignored:
warnings = (
f"Connected to existing Visor instance at {url}. "
Expand All @@ -92,6 +104,7 @@ def create_instance(
rendering_mode: RenderingMode,
standalone: bool,
dark_mode: bool,
pvserver: PvserverAddress | None,
trame_log_dir: str | None = None
) -> None:
"""Create a new instance of Visor and store it in the cache."""
Expand All @@ -101,21 +114,22 @@ def create_instance(
standalone=standalone,
dark_mode=dark_mode,
trame_log_dir=trame_log_dir,
pvserver=pvserver,
)
msg = (
f"Created new Visor instance for URL: {url} "
f"(rendering_mode={rendering_mode}, standalone={standalone}, "
f"dark_mode={dark_mode}, trame_log_dir={trame_log_dir})"
f"dark_mode={dark_mode}, pvserver={pvserver}, trame_log_dir={trame_log_dir})"
)
logger.info(msg)
print(msg)

@classmethod
def delete_instance(cls, url: str) -> None:
"""Delete an instance of Visor from the cache."""
"""Delete an instance of Visor from the cache and close it."""
if url not in cls._instances:
return
cls._instances.pop(url)
cls._instances.pop(url).close()
return

@classmethod
Expand Down
209 changes: 209 additions & 0 deletions src/ansys/visor/viewer/app/paraview/paraview_handle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
"""
PARAVIEW handle
===============
The Visor that ``Visor(rendering_mode="PARAVIEW", ...)`` returns. The session
runs in its own pvpython process; this object launches it, forwards each
Visor method over the session channel, and ends it.

The session process is ended by :meth:`VisorParaviewHandle.close`, or at
interpreter exit if close was never called.
"""

from __future__ import annotations

import asyncio
import threading
import weakref
from typing import Any

from ansys.visor.viewer.app.paraview.session_channel import SessionLaunchRequest
from ansys.visor.viewer.app.paraview.session_process import ParaviewSessionProcess
from ansys.visor.viewer.app.visor import Visor
from ansys.visor.viewer.config import settings
from ansys.visor.viewer.core.errors import ParaviewSessionError, UnsupportedInModeError
from ansys.visor.viewer.core.metadata import Metadata
from ansys.visor.viewer.core.pvserver_address import PvserverAddress
from ansys.visor.viewer.core.visor_enums import RenderingMode
from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger
from ansys.visor.viewer.core.visor_types import VisorDatasetType
from ansys.visor.viewer.vtk.variables.visor_part_variables import VisorPartVariables

logger = VisorDefaultLogger(__name__)

BLOCKING_WAIT_SLICE_S = 0.5
"""Seconds between checks that the session process is running while a blocking start waits."""


class VisorParaviewHandle(Visor):
"""Visor for PARAVIEW mode: the session runs in its own pvpython process, reached over its channel."""

def __init__(
self,
url: str | None = None,
rendering_mode: RenderingMode = RenderingMode.PARAVIEW,
standalone: bool = True,
dark_mode: bool | None = None,
trame_log_dir: str | None = None,
pvserver: PvserverAddress | None = None,
) -> None:
"""Launch the session for url against pvserver, the settings default when None.

Raises ValueError for a rendering mode other than PARAVIEW, and
whatever the session process raises when it cannot start.
"""
rendering_mode = RenderingMode.from_string(rendering_mode)
if rendering_mode is not RenderingMode.PARAVIEW:
raise ValueError(f"VisorParaviewHandle runs PARAVIEW sessions only, not {rendering_mode.name}")
super().__init__(url, standalone, dark_mode)
self._pvserver = pvserver if pvserver is not None else settings.default_pvserver_address()
self._wait_released = threading.Event()
process = self._create_session_process()
self._channel = process.launch(
SessionLaunchRequest(
url=self.url,
standalone=standalone,
dark_mode=self.dark_mode,
trame_log_dir=trame_log_dir,
pvserver=self._pvserver,
)
)
self._process = process
self._finalizer = weakref.finalize(self, process.end)
logger.info("PARAVIEW session ready on %s (pvserver %s, pid %s)", self.url, self._pvserver, process.pid)

def _create_session_process(self) -> ParaviewSessionProcess:
"""The session process for this handle's port, configured from settings."""
return ParaviewSessionProcess.from_settings(settings, self.port)

""" Properties """
@property
def pvserver(self) -> PvserverAddress:
"""The pvserver this session renders on."""
return self._pvserver

@property
def running(self) -> bool:
"""Whether the session process is running."""
return self._process.alive

""" Public Methods """
def start(self,
input: str | VisorDatasetType | None = None,
metadata: Metadata | str | None = None,
timeout: int = 0,
blocking: bool = False,
) -> int | None:
"""Start the session's server; with blocking, wait until the session ends.

The wait ends when :meth:`stop` or :meth:`close` is called. A session
process that exits by itself during the wait raises
ParaviewSessionError. KeyboardInterrupt during the wait ends the
session through :meth:`close` and is raised again.
"""
self._reject_in_memory_input(input)
self._wait_released.clear()
dataset_id = self._channel.call("start", input, metadata, timeout)
if blocking:
self._wait_until_released()
return dataset_id

def stop(self) -> None:
"""Stop the session's server; a blocking start waiting on this handle returns."""
self._channel.call("stop")
self._wait_released.set()

def update(self,
input: str | VisorDatasetType,
metadata: Metadata | str | None = None,
) -> int:
"""Replace the session's datasets with the file at input."""
self._reject_in_memory_input(input)
return self._channel.call("update", input, metadata)

def add_dataset(self,
input: str | VisorDatasetType,
metadata: Metadata | str | None = None,
) -> int:
"""Add the file at input to the session's scene and return its dataset ID."""
self._reject_in_memory_input(input)
return self._channel.call("add_dataset", input, metadata)

def remove_dataset(self, dataset_id: int) -> None:
"""Remove a dataset from the session's scene."""
return self._channel.call("remove_dataset", dataset_id)

def list_datasets(self) -> dict:
"""List the datasets in the session's scene."""
return self._channel.call("list_datasets")

def list_variables(self, dataset_id: int) -> list[VisorPartVariables]:
"""List the variables of a dataset in the session's scene, grouped by part."""
return self._channel.call("list_variables", dataset_id)

def update_variables(self, dataset_id: int, variables: list[dict[str, Any]]) -> None:
"""Raise UnsupportedInModeError: pvserver holds its own copy of the arrays."""
raise UnsupportedInModeError("update_variables is not supported in PARAVIEW mode")

async def save_state(self, state_dir: str) -> None:
"""Save the session's state to state_dir; the call waits on a worker thread, not the event loop."""
await asyncio.to_thread(self._channel.call, "save_state", state_dir)

def load_state(self, state_dir: str) -> None:
"""Load the session's state from state_dir."""
return self._channel.call("load_state", state_dir)

def close(self) -> None:
"""End the session process; idempotent. A blocking start waiting on this handle returns."""
self._wait_released.set()
self._finalizer()

def _health(self) -> bool:
"""The session server's health; False when the session process is gone."""
if not self._process.alive:
return False
return self._channel.call("_health")

""" Protected Async Methods (for use in the FastAPI endpoints) """
async def _start_async(self,
input: str | VisorDatasetType | None = None,
metadata: Metadata | str | None = None,
timeout: int = 0,
) -> tuple[int | None, None]:
"""Start the session's server on a worker thread; there is no server task in this process."""
dataset_id = await asyncio.to_thread(self.start, input, metadata, timeout)
return dataset_id, None

async def _stop_async(self) -> None:
"""Stop the session's server on a worker thread."""
await asyncio.to_thread(self.stop)

""" Private Methods """
@staticmethod
def _reject_in_memory_input(input: str | VisorDatasetType | None) -> None:
"""Raise UnsupportedInModeError for input other than a file path or None: pvserver opens files only."""
if input is not None and not isinstance(input, str):
raise UnsupportedInModeError("in-memory dataset input is not supported in PARAVIEW mode")

def _wait_until_released(self) -> None:
"""Wait until stop or close releases the wait.

close releases the wait before it ends the session process, so a
process found gone with the wait released was ended by close, not by
itself.
"""
try:
while not self._wait_released.wait(BLOCKING_WAIT_SLICE_S):
if self._process.alive:
continue
if self._wait_released.is_set():
return
code = self._process.exit_code
self.close()
raise ParaviewSessionError(
f"The PARAVIEW session process exited with code {code} while start was blocking; "
f"see its log at {self._process.log_path}"
)
except KeyboardInterrupt:
logger.info("Interrupted; ending the PARAVIEW session on %s", self.url)
self.close()
raise
Loading
Loading