|
| 1 | +""" |
| 2 | +PARAVIEW handle |
| 3 | +=============== |
| 4 | +The Visor that ``Visor(rendering_mode="PARAVIEW", ...)`` returns. The session |
| 5 | +runs in its own pvpython process; this object launches it, forwards each |
| 6 | +Visor method over the session channel, and ends it. |
| 7 | +
|
| 8 | +The session process is ended by :meth:`VisorParaviewHandle.close`, or at |
| 9 | +interpreter exit if close was never called. |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import asyncio |
| 15 | +import threading |
| 16 | +import weakref |
| 17 | +from typing import Any |
| 18 | + |
| 19 | +from ansys.visor.viewer.app.paraview.session_channel import SessionLaunchRequest |
| 20 | +from ansys.visor.viewer.app.paraview.session_process import ParaviewSessionProcess |
| 21 | +from ansys.visor.viewer.app.visor import Visor |
| 22 | +from ansys.visor.viewer.config import settings |
| 23 | +from ansys.visor.viewer.core.errors import ParaviewSessionError, UnsupportedInModeError |
| 24 | +from ansys.visor.viewer.core.metadata import Metadata |
| 25 | +from ansys.visor.viewer.core.pvserver_address import PvserverAddress |
| 26 | +from ansys.visor.viewer.core.visor_enums import RenderingMode |
| 27 | +from ansys.visor.viewer.core.visor_logging import VisorDefaultLogger |
| 28 | +from ansys.visor.viewer.core.visor_types import VisorDatasetType |
| 29 | +from ansys.visor.viewer.vtk.variables.visor_part_variables import VisorPartVariables |
| 30 | + |
| 31 | +logger = VisorDefaultLogger(__name__) |
| 32 | + |
| 33 | +BLOCKING_WAIT_SLICE_S = 0.5 |
| 34 | +"""Seconds between checks that the session process is running while a blocking start waits.""" |
| 35 | + |
| 36 | + |
| 37 | +class VisorParaviewHandle(Visor): |
| 38 | + """Visor for PARAVIEW mode: the session runs in its own pvpython process, reached over its channel.""" |
| 39 | + |
| 40 | + def __init__( |
| 41 | + self, |
| 42 | + url: str | None = None, |
| 43 | + rendering_mode: RenderingMode = RenderingMode.PARAVIEW, |
| 44 | + standalone: bool = True, |
| 45 | + dark_mode: bool | None = None, |
| 46 | + trame_log_dir: str | None = None, |
| 47 | + pvserver: PvserverAddress | None = None, |
| 48 | + ) -> None: |
| 49 | + """Launch the session for url against pvserver, the settings default when None. |
| 50 | +
|
| 51 | + Raises ValueError for a rendering mode other than PARAVIEW, and |
| 52 | + whatever the session process raises when it cannot start. |
| 53 | + """ |
| 54 | + rendering_mode = RenderingMode.from_string(rendering_mode) |
| 55 | + if rendering_mode is not RenderingMode.PARAVIEW: |
| 56 | + raise ValueError(f"VisorParaviewHandle runs PARAVIEW sessions only, not {rendering_mode.name}") |
| 57 | + super().__init__(url, standalone, dark_mode) |
| 58 | + self._pvserver = pvserver if pvserver is not None else settings.default_pvserver_address() |
| 59 | + self._wait_released = threading.Event() |
| 60 | + process = self._create_session_process() |
| 61 | + self._channel = process.launch( |
| 62 | + SessionLaunchRequest( |
| 63 | + url=self.url, |
| 64 | + standalone=standalone, |
| 65 | + dark_mode=self.dark_mode, |
| 66 | + trame_log_dir=trame_log_dir, |
| 67 | + pvserver=self._pvserver, |
| 68 | + ) |
| 69 | + ) |
| 70 | + self._process = process |
| 71 | + self._finalizer = weakref.finalize(self, process.end) |
| 72 | + logger.info("PARAVIEW session ready on %s (pvserver %s, pid %s)", self.url, self._pvserver, process.pid) |
| 73 | + |
| 74 | + def _create_session_process(self) -> ParaviewSessionProcess: |
| 75 | + """The session process for this handle's port, configured from settings.""" |
| 76 | + return ParaviewSessionProcess.from_settings(settings, self.port) |
| 77 | + |
| 78 | + """ Properties """ |
| 79 | + @property |
| 80 | + def pvserver(self) -> PvserverAddress: |
| 81 | + """The pvserver this session renders on.""" |
| 82 | + return self._pvserver |
| 83 | + |
| 84 | + @property |
| 85 | + def running(self) -> bool: |
| 86 | + """Whether the session process is running.""" |
| 87 | + return self._process.alive |
| 88 | + |
| 89 | + """ Public Methods """ |
| 90 | + def start(self, |
| 91 | + input: str | VisorDatasetType | None = None, |
| 92 | + metadata: Metadata | str | None = None, |
| 93 | + timeout: int = 0, |
| 94 | + blocking: bool = False, |
| 95 | + ) -> int | None: |
| 96 | + """Start the session's server; with blocking, wait until the session ends. |
| 97 | +
|
| 98 | + The wait ends when :meth:`stop` or :meth:`close` is called. A session |
| 99 | + process that exits by itself during the wait raises |
| 100 | + ParaviewSessionError. KeyboardInterrupt during the wait ends the |
| 101 | + session through :meth:`close` and is raised again. |
| 102 | + """ |
| 103 | + self._reject_in_memory_input(input) |
| 104 | + self._wait_released.clear() |
| 105 | + dataset_id = self._channel.call("start", input, metadata, timeout) |
| 106 | + if blocking: |
| 107 | + self._wait_until_released() |
| 108 | + return dataset_id |
| 109 | + |
| 110 | + def stop(self) -> None: |
| 111 | + """Stop the session's server; a blocking start waiting on this handle returns.""" |
| 112 | + self._channel.call("stop") |
| 113 | + self._wait_released.set() |
| 114 | + |
| 115 | + def update(self, |
| 116 | + input: str | VisorDatasetType, |
| 117 | + metadata: Metadata | str | None = None, |
| 118 | + ) -> int: |
| 119 | + """Replace the session's datasets with the file at input.""" |
| 120 | + self._reject_in_memory_input(input) |
| 121 | + return self._channel.call("update", input, metadata) |
| 122 | + |
| 123 | + def add_dataset(self, |
| 124 | + input: str | VisorDatasetType, |
| 125 | + metadata: Metadata | str | None = None, |
| 126 | + ) -> int: |
| 127 | + """Add the file at input to the session's scene and return its dataset ID.""" |
| 128 | + self._reject_in_memory_input(input) |
| 129 | + return self._channel.call("add_dataset", input, metadata) |
| 130 | + |
| 131 | + def remove_dataset(self, dataset_id: int) -> None: |
| 132 | + """Remove a dataset from the session's scene.""" |
| 133 | + return self._channel.call("remove_dataset", dataset_id) |
| 134 | + |
| 135 | + def list_datasets(self) -> dict: |
| 136 | + """List the datasets in the session's scene.""" |
| 137 | + return self._channel.call("list_datasets") |
| 138 | + |
| 139 | + def list_variables(self, dataset_id: int) -> list[VisorPartVariables]: |
| 140 | + """List the variables of a dataset in the session's scene, grouped by part.""" |
| 141 | + return self._channel.call("list_variables", dataset_id) |
| 142 | + |
| 143 | + def update_variables(self, dataset_id: int, variables: list[dict[str, Any]]) -> None: |
| 144 | + """Raise UnsupportedInModeError: pvserver holds its own copy of the arrays.""" |
| 145 | + raise UnsupportedInModeError("update_variables is not supported in PARAVIEW mode") |
| 146 | + |
| 147 | + async def save_state(self, state_dir: str) -> None: |
| 148 | + """Save the session's state to state_dir; the call waits on a worker thread, not the event loop.""" |
| 149 | + await asyncio.to_thread(self._channel.call, "save_state", state_dir) |
| 150 | + |
| 151 | + def load_state(self, state_dir: str) -> None: |
| 152 | + """Load the session's state from state_dir.""" |
| 153 | + return self._channel.call("load_state", state_dir) |
| 154 | + |
| 155 | + def close(self) -> None: |
| 156 | + """End the session process; idempotent. A blocking start waiting on this handle returns.""" |
| 157 | + self._wait_released.set() |
| 158 | + self._finalizer() |
| 159 | + |
| 160 | + def _health(self) -> bool: |
| 161 | + """The session server's health; False when the session process is gone.""" |
| 162 | + if not self._process.alive: |
| 163 | + return False |
| 164 | + return self._channel.call("_health") |
| 165 | + |
| 166 | + """ Protected Async Methods (for use in the FastAPI endpoints) """ |
| 167 | + async def _start_async(self, |
| 168 | + input: str | VisorDatasetType | None = None, |
| 169 | + metadata: Metadata | str | None = None, |
| 170 | + timeout: int = 0, |
| 171 | + ) -> tuple[int | None, None]: |
| 172 | + """Start the session's server on a worker thread; there is no server task in this process.""" |
| 173 | + dataset_id = await asyncio.to_thread(self.start, input, metadata, timeout) |
| 174 | + return dataset_id, None |
| 175 | + |
| 176 | + async def _stop_async(self) -> None: |
| 177 | + """Stop the session's server on a worker thread.""" |
| 178 | + await asyncio.to_thread(self.stop) |
| 179 | + |
| 180 | + """ Private Methods """ |
| 181 | + @staticmethod |
| 182 | + def _reject_in_memory_input(input: str | VisorDatasetType | None) -> None: |
| 183 | + """Raise UnsupportedInModeError for input other than a file path or None: pvserver opens files only.""" |
| 184 | + if input is not None and not isinstance(input, str): |
| 185 | + raise UnsupportedInModeError("in-memory dataset input is not supported in PARAVIEW mode") |
| 186 | + |
| 187 | + def _wait_until_released(self) -> None: |
| 188 | + """Wait until stop or close releases the wait. |
| 189 | +
|
| 190 | + close releases the wait before it ends the session process, so a |
| 191 | + process found gone with the wait released was ended by close, not by |
| 192 | + itself. |
| 193 | + """ |
| 194 | + try: |
| 195 | + while not self._wait_released.wait(BLOCKING_WAIT_SLICE_S): |
| 196 | + if self._process.alive: |
| 197 | + continue |
| 198 | + if self._wait_released.is_set(): |
| 199 | + return |
| 200 | + code = self._process.exit_code |
| 201 | + self.close() |
| 202 | + raise ParaviewSessionError( |
| 203 | + f"The PARAVIEW session process exited with code {code} while start was blocking; " |
| 204 | + f"see its log at {self._process.log_path}" |
| 205 | + ) |
| 206 | + except KeyboardInterrupt: |
| 207 | + logger.info("Interrupted; ending the PARAVIEW session on %s", self.url) |
| 208 | + self.close() |
| 209 | + raise |
0 commit comments