Skip to content

remote-connection server API changed. #237

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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/237.miscellaneous.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
remote-connection server API changed.
12 changes: 11 additions & 1 deletion src/ansys/workbench/core/public_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

"""Module for public API on PyWorkbench."""

import atexit
import logging
import tempfile

Expand Down Expand Up @@ -112,17 +113,26 @@ def __init__(
port = self._launcher.launch(version, show_gui, server_workdir, host, username, password)
if port is None or port <= 0:
raise Exception("Filed to launch Ansys Workbench service.")
self.server_version = int(version)
super().__init__(port, client_workdir, host)
atexit.register(self.exit)
self._exited = False

def exit(self):
"""Terminate the Workbench server and disconnect the client."""
if self._exited:
return
self.run_script_string("Reset()")
self.run_script_string("internal_wbexit()")
if self.server_version >= 252:
self.run_script_string("internal_wbexit()")
else:
self.run_script_string("StopServer()")

super().exit()

self._launcher.exit()
logging.info("Workbench server connection has ended.")
self._exited = True


def launch_workbench(
Expand Down
50 changes: 48 additions & 2 deletions src/ansys/workbench/core/workbench_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import os
import re
import time
import warnings

import grpc
import tqdm
Expand All @@ -52,13 +53,52 @@ class WorkbenchClient:
Port number of the server.
"""

def __init__(self, local_workdir, server_host, server_port):
def __init__(self, local_workdir, server_host, server_port, allow_remote_host=False):
"""Create a Workbench client."""
self.workdir = local_workdir
self._server_host = server_host
self._server_port = server_port
self.allow_remote_host = allow_remote_host
self.__init_logging()

# HACK: use setters to verify values for host and port
self.host = server_host
self.port = server_port

@property
def host(self):
"""Return the hostname value."""
return self._server_host

@host.setter
def host(self, value):
"""Set the hostname value."""
if value not in ["localhost", "127.0.0.1"]:
warnings.warn(
"Allowing remote access can expose the server to unauthorized "
"connections and may transmit data over an unencrypted channel "
"if the server is not properly configured."
)
if not self.allow_remote_host:
raise ValueError(
"Remote host connections are not permitted by default. "
"To enable connections to hosts other than localhost, set "
"the `allow_remote_host` parameter to `True`."
)
self._server_host = value

@property
def port(self):
"""Return the value of the port."""
return self._server_port

@port.setter(self, value)
def port(self, value: int):
"""Set the value of the port."""
if value < 0 or value > 65535:
raise ValueError("Port value must be in the range of [0, 65535].")
self._server_port = value

def __enter__(self):
"""Connect to the server when entering a context."""
self._connect()
Expand All @@ -70,10 +110,16 @@ def __exit__(self, exc_type, exc_value, traceback):

def _connect(self):
"""Connect to the server."""
hnp = self._server_host + ":" + str(self._server_port)
hnp = self.host + ":" + str(self.port)
self.channel = grpc.insecure_channel(hnp)
self.stub = WorkbenchServiceStub(self.channel)
logging.info("connected to the WB server at " + hnp)
self.server_version = int(
self.run_script_string(
"""import json
wb_script_result=json.dumps(GetFrameworkVersion())"""
).replace(".", "")
)

def _disconnect(self):
"""Disconnect from the server."""
Expand Down
29 changes: 27 additions & 2 deletions src/ansys/workbench/core/workbench_launcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import subprocess
import time
import uuid
import warnings


class Launcher:
Expand Down Expand Up @@ -77,6 +78,7 @@ def launch(
host=None,
username=None,
password=None,
allow_remote_host=False,
):
"""Launch PyWorkbench server on the local or a remote computer.

Expand All @@ -98,6 +100,8 @@ def launch(
password : str, default: None
User's password on the server. The default is ``None``, which launches Workbench
on the local computer.
allow_remote_host : bool
If ``True``, remote host connections are allowed. ``False`` otherwise.

Raises
------
Expand All @@ -118,6 +122,19 @@ def launch(
):
raise Exception("Invalid Ansys version: " + version)

if host not in ["localhost", "127.0.0.1"]:
warnings.warn(
"Allowing remote access can expose the server to unauthorized "
"connections and may transmit data over an unencrypted channel "
"if the server is not properly configured."
)
if not allow_remote_host:
raise ValueError(
"Remote host connections are not permitted by default. "
"To enable connections to hosts other than localhost, set "
"the `allow_remote_host` parameter to `True`."
)

if host and not self._wmi:
raise Exception(
"Launching PyWorkbench on a remote machine from Linux is not supported."
Expand Down Expand Up @@ -148,9 +165,9 @@ def launch(

ansys_install_path = self.__getenv("AWP_ROOT" + version)
if ansys_install_path:
logging.info("Ansys installation is found at: " + ansys_install_path)
logging.info(f"Ansys installation is found at: {ansys_install_path}")
else:
raise Exception("Ansys installation is not found.")
raise Exception(f"Ansys {version} installation is not found.")

args = []
if platform.system() == "Windows":
Expand All @@ -172,10 +189,18 @@ def launch(
# use forward slash only to avoid escaping as command line argument
server_workdir = server_workdir.replace("\\", "/")
cmd += ",WorkingDirectory='" + server_workdir + "'"
if host is not None:
cmd += ",AllowRemoteConnection=True"
cmd += ")"
args.append(cmd)
command_line = " ".join(args)

# security precaution statement
if host is not None:
print("""The server started will allow remote access connections to be
established, possibly permitting control of the machine and any data which resides on it.
It is highly recommended to only utilize these features on a trusted, secure network.""")

successful = False
process = None
if self._wmi:
Expand Down
Loading