BackendPlugin.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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. }
  78. if Platform.isWindows():
  79. popen_kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
  80. self._process = subprocess.Popen(self._validatePluginCommand(), **popen_kwargs)
  81. self._is_running = True
  82. return True
  83. except PermissionError:
  84. Logger.log("e", f"Couldn't start EnginePlugin: {self._plugin_id} No permission to execute process.")
  85. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  86. f"Couldn't start EnginePlugin: {self._plugin_id}\nNo permission to execute process."),
  87. message_type = Message.MessageType.ERROR)
  88. except FileNotFoundError:
  89. Logger.logException("e", f"Unable to find local EnginePlugin server executable for: {self._plugin_id}")
  90. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  91. f"Unable to find local EnginePlugin server executable for: {self._plugin_id}"),
  92. message_type = Message.MessageType.ERROR)
  93. except BlockingIOError:
  94. Logger.logException("e", f"Couldn't start EnginePlugin: {self._plugin_id} Resource is temporarily unavailable")
  95. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  96. f"Couldn't start EnginePlugin: {self._plugin_id}\nResource is temporarily unavailable"),
  97. message_type = Message.MessageType.ERROR)
  98. except OSError as e:
  99. Logger.logException("e", f"Couldn't start EnginePlugin {self._plugin_id} Operating system is blocking it (antivirus?)")
  100. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  101. f"Couldn't start EnginePlugin: {self._plugin_id}\nOperating system is blocking it (antivirus?)"),
  102. message_type = Message.MessageType.ERROR)
  103. return False
  104. def stop(self) -> bool:
  105. if not self._process:
  106. self._is_running = False
  107. return True # Nothing to stop
  108. try:
  109. self._process.terminate()
  110. return_code = self._process.wait()
  111. self._is_running = False
  112. Logger.log("d", f"EnginePlugin: {self._plugin_id} was killed. Received return code {return_code}")
  113. return True
  114. except PermissionError:
  115. Logger.log("e", f"Unable to kill running EnginePlugin: {self._plugin_id} Access is denied.")
  116. self._showMessage(self.catalog.i18nc("@info:plugin_failed",
  117. f"Unable to kill running EnginePlugin: {self._plugin_id}\nAccess is denied."),
  118. message_type = Message.MessageType.ERROR)
  119. return False
  120. def _showMessage(self, message: str, message_type: Message.MessageType = Message.MessageType.ERROR) -> None:
  121. Message(message, title=self.catalog.i18nc("@info:title", "EnginePlugin"), message_type = message_type).show()