BackendPlugin.py 6.4 KB

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