BackendPlugin.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. # Copyright (c) 2023 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import socket
  4. import os
  5. import subprocess
  6. from typing import Optional, List
  7. from UM.Logger import Logger
  8. from UM.Message import Message
  9. from UM.Settings.AdditionalSettingDefinitionAppender import AdditionalSettingDefinitionsAppender
  10. from UM.PluginObject import PluginObject
  11. from UM.i18n import i18nCatalog
  12. from UM.Platform import Platform
  13. from UM.Resources import Resources
  14. class BackendPlugin(AdditionalSettingDefinitionsAppender, PluginObject):
  15. catalog = i18nCatalog("cura")
  16. def __init__(self) -> None:
  17. super().__init__()
  18. self.__port: int = 0
  19. self._plugin_address: str = "127.0.0.1"
  20. self._plugin_command: Optional[List[str]] = None
  21. self._process = None
  22. self._is_running = False
  23. self._supported_slots: List[int] = []
  24. self._use_plugin = True
  25. def usePlugin(self) -> bool:
  26. return self._use_plugin
  27. def getSupportedSlots(self) -> List[int]:
  28. return self._supported_slots
  29. def isRunning(self):
  30. return self._is_running
  31. def setPort(self, port: int) -> None:
  32. self.__port = port
  33. def getPort(self) -> int:
  34. return self.__port
  35. def getAddress(self) -> str:
  36. return self._plugin_address
  37. def setAvailablePort(self) -> None:
  38. """
  39. Sets the port to a random available port.
  40. """
  41. sock = socket.socket()
  42. sock.bind((self.getAddress(), 0))
  43. port = sock.getsockname()[1]
  44. self.setPort(port)
  45. def _validatePluginCommand(self) -> list[str]:
  46. """
  47. Validate the plugin command and add the port parameter if it is missing.
  48. :return: A list of strings containing the validated plugin command.
  49. """
  50. if not self._plugin_command or "--port" in self._plugin_command:
  51. return self._plugin_command or []
  52. return self._plugin_command + ["--address", self.getAddress(), "--port", str(self.__port)]
  53. def start(self) -> bool:
  54. """
  55. Starts the backend_plugin process.
  56. :return: True if the plugin process started successfully, False otherwise.
  57. """
  58. if not self.usePlugin():
  59. return False
  60. Logger.info(f"Starting backend_plugin [{self._plugin_id}] with command: {self._validatePluginCommand()}")
  61. plugin_log_path = os.path.join(Resources.getDataStoragePath(), f"{self.getPluginId()}.log")
  62. if os.path.exists(plugin_log_path):
  63. try:
  64. os.remove(plugin_log_path)
  65. except:
  66. pass # removing is only done such that it doesn't grow out of proportions, if it fails once or twice that is okay
  67. Logger.info(f"Logging plugin output to: {plugin_log_path}")
  68. try:
  69. # STDIN needs to be None because we provide no input, but communicate via a local socket instead.
  70. # The NUL device sometimes doesn't exist on some computers.
  71. with open(plugin_log_path, 'a') as f:
  72. popen_kwargs = {
  73. "stdin": None,
  74. "stdout": f, # Redirect output to file
  75. "stderr": subprocess.STDOUT, # Combine stderr and stdout
  76. }
  77. if Platform.isWindows():
  78. popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
  79. self._process = subprocess.Popen(self._validatePluginCommand(), **popen_kwargs)
  80. self._is_running = True
  81. return True
  82. except PermissionError:
  83. Logger.log("e", f"Couldn't start EnginePlugin: {self._plugin_id} No permission to execute process.")
  84. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  85. f"Couldn't start EnginePlugin: {self._plugin_id}\nNo permission to execute process."),
  86. message_type = Message.MessageType.ERROR)
  87. except FileNotFoundError:
  88. Logger.logException("e", f"Unable to find local EnginePlugin server executable for: {self._plugin_id}")
  89. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  90. f"Unable to find local EnginePlugin server executable for: {self._plugin_id}"),
  91. message_type = Message.MessageType.ERROR)
  92. except BlockingIOError:
  93. Logger.logException("e", f"Couldn't start EnginePlugin: {self._plugin_id} Resource is temporarily unavailable")
  94. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  95. f"Couldn't start EnginePlugin: {self._plugin_id}\nResource is temporarily unavailable"),
  96. message_type = Message.MessageType.ERROR)
  97. except OSError as e:
  98. Logger.logException("e", f"Couldn't start EnginePlugin {self._plugin_id} Operating system is blocking it (antivirus?)")
  99. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  100. f"Couldn't start EnginePlugin: {self._plugin_id}\nOperating system is blocking it (antivirus?)"),
  101. message_type = Message.MessageType.ERROR)
  102. return False
  103. def stop(self) -> bool:
  104. if not self._process:
  105. self._is_running = False
  106. return True # Nothing to stop
  107. try:
  108. self._process.terminate()
  109. return_code = self._process.wait()
  110. self._is_running = False
  111. Logger.log("d", f"EnginePlugin: {self._plugin_id} was killed. Received return code {return_code}")
  112. return True
  113. except PermissionError:
  114. Logger.log("e", f"Unable to kill running EnginePlugin: {self._plugin_id} Access is denied.")
  115. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  116. f"Unable to kill running EnginePlugin: {self._plugin_id}\nAccess is denied."),
  117. message_type = Message.MessageType.ERROR)
  118. return False
  119. def _showMessage(self, message: str, message_type: Message.MessageType = Message.MessageType.ERROR) -> None:
  120. Message(message, title=self.catalog.i18nc("@info:title", "EnginePlugin"), message_type = message_type).show()