Skip to content

Commit

Permalink
REFACTOR: Refactor grpc plugin (#4719)
Browse files Browse the repository at this point in the history
Co-authored-by: maxcapodi78 <Shark78>
Co-authored-by: Kathy Pippert <[email protected]>
  • Loading branch information
maxcapodi78 and PipKat authored May 24, 2024
1 parent 1966da9 commit 4c4932b
Show file tree
Hide file tree
Showing 6 changed files with 449 additions and 426 deletions.
1 change: 1 addition & 0 deletions _unittest/test_01_Design.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@ def test_27_odesktop(self):
"<class 'win32com.client.CDispatch'>",
"<class 'PyDesktopPlugin.AedtObjWrapper'>",
"<class 'pyaedt.generic.grpc_plugin.AedtObjWrapper'>",
"<class 'pyaedt.generic.grpc_plugin_dll_class.AedtObjWrapper'>",
]

def test_28_get_pyaedt_app(self):
Expand Down
1 change: 0 additions & 1 deletion pyaedt/application/Design.py
Original file line number Diff line number Diff line change
Expand Up @@ -3340,7 +3340,6 @@ def _insert_design(self, design_type, design_name=None):
if not is_windows and settings.aedt_version and self.design_type == "Circuit Design":
time.sleep(1)
self.odesktop.CloseAllWindows()

if new_design is None: # pragma: no cover
new_design = self.desktop_class.active_design(self.oproject, unique_design_name, self.design_type)
if new_design is None:
Expand Down
105 changes: 45 additions & 60 deletions pyaedt/desktop.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,32 +261,12 @@ def _close_aedt_application(desktop_class, close_desktop, pid, is_grpc_api):
return True
except Exception: # pragma: no cover
warnings.warn("Something went wrong closing AEDT. Exception in `_main.oDesktop.QuitApplication()`.")
elif _desktop_sessions and len(_desktop_sessions) > 1 and not desktop_class.parent_desktop_id:
pyaedt_logger.error("Release is not allowed when multiple desktop sessions are available.")
pyaedt_logger.error("Closing Desktop session.")
try:
os.kill(pid, 9)
if _desktop_sessions:
for v in _desktop_sessions.values():
if pid in v.parent_desktop_id:
del v.parent_desktop_id[v.parent_desktop_id.index(pid)]
return True
except Exception: # pragma: no cover
warnings.warn("Something went wrong closing AEDT. Exception in `_main.oDesktop.QuitApplication()`.")
elif _desktop_sessions and len(_desktop_sessions) > 1:
pyaedt_logger.error("A child desktop session is linked to this session.")
pyaedt_logger.error("Multiple desktop sessions must be released in reverse order.")
return False
else:
try:
import pyaedt.generic.grpc_plugin as python_grpc_wrapper

python_grpc_wrapper.AedtAPI.ReleaseAll()
return True
except Exception: # pragma: no cover
warnings.warn(
"Something went wrong releasing AEDT. Exception in `StandalonePyScriptWrapper.Release()`."
)
for k, d in _desktop_sessions.items():
if k == pid:
d.grpc_plugin.recreate_application(True)
d.grpc_plugin.Release()
return True
elif not inside_desktop:
if close_desktop:
try:
Expand Down Expand Up @@ -455,16 +435,17 @@ def __new__(cls, *args, **kwargs):
# machine = kwargs.get("machine") or "" if (not args or len(args)<6) else args[5]
port = kwargs.get("port") or 0 if (not args or len(args) < 7) else args[6]
aedt_process_id = kwargs.get("aedt_process_id") or None if (not args or len(args) < 8) else args[7]
if settings.use_multi_desktop and is_windows and not inside_desktop and new_desktop_session:
if settings.use_multi_desktop and not inside_desktop and new_desktop_session:
pyaedt_logger.info("Initializing new Desktop session.")
return object.__new__(cls)
elif len(_desktop_sessions.keys()) > 0:
if settings.use_multi_desktop and is_windows and (port or aedt_process_id):
if settings.use_multi_desktop and (port or aedt_process_id):
for el in list(_desktop_sessions.values()):
if (el.port != 0 and el.port == port) or (
el.aedt_process_id and el.aedt_process_id == aedt_process_id
):
return el
return object.__new__(cls)
sessions = list(_desktop_sessions.keys())
try:
process_id = _desktop_sessions[sessions[0]].odesktop.GetProcessID()
Expand All @@ -491,18 +472,22 @@ def __init__(
port=0,
aedt_process_id=None,
):
if _desktop_sessions and (specified_version is None or not settings.use_grpc_api):
if _desktop_sessions and specified_version is None:
specified_version = list(_desktop_sessions.values())[-1].aedt_version_id
if aedt_process_id: # pragma no cover
aedt_process_id = int(aedt_process_id)
if getattr(self, "_initialized", None) is not None and self._initialized:
try:
self.grpc_plugin.recreate_application(True)
except Exception:
pass
return
else:
self._initialized = True
self._initialized_from_design = True if Desktop._invoked_from_design else False
Desktop._invoked_from_design = False
self.parent_desktop_id = []

self._odesktop = None
self._connected_app_instances = 0

"""Initialize desktop."""
Expand Down Expand Up @@ -998,41 +983,42 @@ def _initialize(
os.environ["DesktopPluginPyAEDT"] = os.path.join(settings.aedt_install_dir, "PythonFiles", "DesktopPlugin")
launch_msg = "AEDT installation Path {}".format(base_path)
self.logger.info(launch_msg)
import pyaedt.generic.grpc_plugin as python_grpc_wrapper
from pyaedt.generic.grpc_plugin_dll_class import AEDT

if _desktop_sessions:
last_session = list(_desktop_sessions.values())[-1]
all_desktop = [i for i in last_session.odesktop.GetRunningInstancesMgr().GetAllRunningInstances()]
for desktop in all_desktop:
try:
if port and desktop.GetGrpcServerPort() == port:
self.isoutsideDesktop = True
self.odesktop = desktop
self.aedt_process_id = self.odesktop.GetProcessID()
self.is_grpc_api = True
last_session.parent_desktop_id.append(self.aedt_process_id)
return True
except Exception:
messages = desktop.GetMessages("", "", 0)
for message in messages:
if "gRPC server running on port: " in message and str(port) in message:
self.isoutsideDesktop = True
self.odesktop = desktop
self.aedt_process_id = self.odesktop.GetProcessID()
self.is_grpc_api = True
last_session.parent_desktop_id.append(self.aedt_process_id)
return True
if new_session:
self.launched_by_pyaedt = new_session
oapp = python_grpc_wrapper.CreateAedtApplication(machine, port, non_graphical, new_session)
if settings.use_multi_desktop:
os.environ["DesktopPluginPyAEDT"] = os.path.join(
list(installed_versions().values())[0], "PythonFiles", "DesktopPlugin"
)
self.grpc_plugin = AEDT(os.environ["DesktopPluginPyAEDT"])
oapp = self.grpc_plugin.CreateAedtApplication(machine, port, non_graphical, new_session)
if oapp:

self.isoutsideDesktop = True
self.odesktop = oapp.GetAppDesktop()
self.aedt_process_id = self.odesktop.GetProcessID()
self.is_grpc_api = True
return True

@property
def odesktop(self):
"""AEDT instance containing all projects and designs.
Examples
--------
Get the COM object representing the desktop.
>>> from pyaedt import Desktop
>>> d = Desktop()
>>> d.odesktop
"""
try:
return self.grpc_plugin.odesktop
except Exception:
return self._odesktop

@odesktop.setter
def odesktop(self, val):
self._odesktop = val

def _init_grpc(self, non_graphical, new_aedt_session, version, student_version, version_key):
if settings.remote_rpc_session: # pragma: no cover
settings.remote_api = True
Expand All @@ -1052,12 +1038,12 @@ def _init_grpc(self, non_graphical, new_aedt_session, version, student_version,
socket.getfqdn(),
socket.getfqdn().split(".")[0],
]:
self.machine = ""
self.machine = "127.0.0.1"
else:
settings.remote_api = True
if not self.port:
if self.machine:
self.logger.error("New Session of AEDT cannot be started on remote machine from Desktop Class.")
if self.machine and self.machine != "127.0.0.1":
self.logger.error("New session of AEDT cannot be started on remote machine from Desktop Class.")
self.logger.error("Either use port argument or start an rpc session to start AEDT on remote machine.")
self.logger.error("Use client = pyaedt.common_rpc.client(machinename) to start a remote session.")
self.logger.error("Use client.aedt(port) to start aedt on remote machine before connecting.")
Expand Down Expand Up @@ -1571,7 +1557,6 @@ def release_desktop(self, close_projects=True, close_on_exit=True):
for a in props:
self.__dict__.pop(a, None)

self.odesktop = None
gc.collect()
return result

Expand Down
Loading

0 comments on commit 4c4932b

Please sign in to comment.