✨ Add (optional) support for shutdown action command. (#4358)
* Adding shutdown action command. * Add myself * Add error handling. * First attempt at systemcommands module * Fix pre-commit issues * Fix pre-commit issues * Add log message. * Update src/octoprint/systemcommands/__init__.py * Renamed __call, simplified code. * Inject systemcommands into plugins * Use underscore between words in dict. * ♻️ systemcommands -> system_command_manager * ♻️ Switch places that make sense to system_commands_manager Also switch SCM to use CommandlineCaller instead of reinventing the wheel, same for other places. * 🔒️ Don't enable support for action:shutdown by default It could be abused by malicious firmware and/or GCODE somehow tricked on the user, so let's play it safe and make it something the user has to consciously enable. * 📝 Add missing documentation Co-authored-by: Gina Häußge <gina@octoprint.org>
This commit is contained in:
1 parent
1fd2764508
commit
c3dda0966a
13 files changed
+267
-100
No files matched your search
@@ -160,7 +160,9 @@ date of first contribution):
|
||||
* [Adam Wolf](https://github.com/adamwolf)
|
||||
* [Didi Kohen](https://github.com/kohend)
|
||||
* [Taylor Talkington](https://github.com/The-EG)
|
||||
* [Carey Metcalfe](https://github.com/pR0Ps)
|
||||
* [Shell M. Shrader](https://github.com/synman)
|
||||
* [Johan Verrept](https://github.com/JoveToo)
|
||||
|
||||
OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by
|
||||
[Daid Braam](https://github.com/daid). Parts of its communication layer and
|
||||
|
||||
@@ -814,6 +814,10 @@ Use the following settings to configure the serial connection to the printer:
|
||||
# other values can be used: https://docs.python.org/3/library/codecs.html#standard-encodings
|
||||
encoding: ascii
|
||||
|
||||
# Whether to enable support for the shutdown action command, allowing the printer to
|
||||
# shut down OctoPrint and the system it's running on
|
||||
enableShutdownActionCommand: false
|
||||
|
||||
# Whether to "manually" trigger an ok for M29 (a lot of versions of this command are buggy and
|
||||
# the response skips on the ok)
|
||||
triggerOkForM29: true
|
||||
|
||||
@@ -75,8 +75,18 @@ sd_updated
|
||||
|
||||
.. versionadded:: 1.6.0
|
||||
|
||||
shutdown
|
||||
When this command is received from the printer, **support for it is enabled in its settings**
|
||||
and a working system shutdown command is configured, OctoPrint will immediately shutdown the system.
|
||||
This command is not enabled by default due to the high risk of seeing it abused by malicious
|
||||
firmware or manipulated GCODE, but can be enabled in the OctoPrint settings via Serial Connection >
|
||||
Firmware & Protocol > Action Commands if so desired by the user.
|
||||
|
||||
.. versionadded:: 1.8.0
|
||||
|
||||
If the bundled :ref:`Action Command Prompt Support Plugin <sec-bundledplugins-action_command_prompt>` is enabled (which
|
||||
should be the case by default), OctoPrint will also interactive dialog creation through its :ref:`supported commands <sec-bundledplugins-action_command_prompt-action_commands>`.
|
||||
should be the case by default), OctoPrint will also support interactive dialog creation
|
||||
through its :ref:`supported commands <sec-bundledplugins-action_command_prompt-action_commands>`.
|
||||
|
||||
Support for additional commands may be added by plugins by implementing a handler for the
|
||||
:ref:`octoprint.comm.protocol.action <sec-plugins-hook-comm-protocol-action>` hook.
|
||||
@@ -29,6 +29,7 @@ from octoprint.server.util.flask import (
|
||||
with_revalidation_checking,
|
||||
)
|
||||
from octoprint.util import dict_merge, get_formatted_size, to_unicode, yaml
|
||||
from octoprint.util.commandline import CommandlineError
|
||||
from octoprint.util.pip import create_pip_caller
|
||||
from octoprint.util.version import (
|
||||
get_comparable_version,
|
||||
@@ -628,8 +629,7 @@ class SoftwareUpdatePlugin(
|
||||
return False
|
||||
|
||||
restart_type = self._get_restart_type(check)
|
||||
restart_command = self._get_restart_command(restart_type)
|
||||
return restart_command is not None
|
||||
return self._has_restart_command(restart_type)
|
||||
|
||||
def _get_restart_type(self, check):
|
||||
if check.get("restart") in self.VALID_RESTART_TYPES:
|
||||
@@ -641,17 +641,13 @@ class SoftwareUpdatePlugin(
|
||||
|
||||
return target_restart_type
|
||||
|
||||
def _get_restart_command(self, restart_type):
|
||||
def _has_restart_command(self, restart_type):
|
||||
if restart_type == "octoprint":
|
||||
return self._settings.global_get(
|
||||
["server", "commands", "serverRestartCommand"]
|
||||
)
|
||||
return self._system_commands.has_server_restart_command()
|
||||
elif restart_type == "environment":
|
||||
return self._settings.global_get(
|
||||
["server", "commands", "systemRestartCommand"]
|
||||
)
|
||||
return self._system_commands.has_system_restart_command()
|
||||
else:
|
||||
return None
|
||||
return False
|
||||
|
||||
# ~~ SettingsPlugin API
|
||||
|
||||
@@ -1947,14 +1943,13 @@ class SoftwareUpdatePlugin(
|
||||
# one of our updates requires a restart of either type "octoprint" or "environment". Let's see if
|
||||
# we can actually perform that
|
||||
|
||||
restart_command = self._get_restart_command(restart_type)
|
||||
if restart_command:
|
||||
if self._has_restart_command(restart_type):
|
||||
self._send_client_message(
|
||||
"restarting",
|
||||
{"restart_type": restart_type, "results": target_results},
|
||||
)
|
||||
try:
|
||||
self._perform_restart(restart_command)
|
||||
self._perform_restart(restart_type)
|
||||
except exceptions.RestartFailed:
|
||||
self._send_client_message(
|
||||
"restart_failed",
|
||||
@@ -2164,18 +2159,19 @@ class SoftwareUpdatePlugin(
|
||||
|
||||
check["current"] = current
|
||||
|
||||
def _perform_restart(self, restart_command):
|
||||
def _perform_restart(self, restart_type):
|
||||
"""
|
||||
Performs a restart using the supplied restart_command.
|
||||
Performs a restart using the supplied restart_type.
|
||||
"""
|
||||
|
||||
self._logger.info("Restarting...")
|
||||
try:
|
||||
util.execute(restart_command, evaluate_returncode=False, do_async=True)
|
||||
except exceptions.ScriptError as e:
|
||||
self._logger.exception(
|
||||
f"Error while restarting via command {restart_command}"
|
||||
)
|
||||
if restart_type == "octoprint":
|
||||
return self._system_commands.perform_server_restart()
|
||||
elif restart_type == "environment":
|
||||
return self._system_commands.perform_system_restart()
|
||||
except CommandlineError as e:
|
||||
self._logger.exception(f"Error while restarting of type {restart_type}")
|
||||
self._logger.warning(f"Restart stdout:\n{e.stdout}")
|
||||
self._logger.warning(f"Restart stderr:\n{e.stderr}")
|
||||
raise exceptions.RestartFailed()
|
||||
|
||||
@@ -43,6 +43,7 @@ from werkzeug.exceptions import HTTPException
|
||||
import octoprint.util
|
||||
import octoprint.util.net
|
||||
from octoprint.server import util
|
||||
from octoprint.systemcommands import system_command_manager
|
||||
from octoprint.util.json import JsonEncoding
|
||||
from octoprint.vendor.flask_principal import ( # noqa: F401
|
||||
AnonymousIdentity,
|
||||
@@ -377,6 +378,7 @@ class Server:
|
||||
###
|
||||
### See also issues #2035 and #2090
|
||||
|
||||
systemCommandManager = system_command_manager()
|
||||
printerProfileManager = PrinterProfileManager()
|
||||
eventManager = self._event_manager
|
||||
|
||||
@@ -483,6 +485,7 @@ class Server:
|
||||
"json_decoder": jsonDecoder,
|
||||
"connectivity_checker": connectivityChecker,
|
||||
"environment_detector": self._environment_detector,
|
||||
"system_commands": systemCommandManager,
|
||||
}
|
||||
|
||||
# ~~ setup access control
|
||||
|
||||
@@ -262,6 +262,9 @@ def getSettings():
|
||||
"resendRatioStart": s.getInt(["serial", "resendRatioStart"]),
|
||||
"ignoreEmptyPorts": s.getBoolean(["serial", "ignoreEmptyPorts"]),
|
||||
"encoding": s.get(["serial", "encoding"]),
|
||||
"enableShutdownActionCommand": s.get(
|
||||
["serial", "enableShutdownActionCommand"]
|
||||
),
|
||||
},
|
||||
"folder": {
|
||||
"uploads": s.getBaseFolder("uploads"),
|
||||
@@ -968,6 +971,12 @@ def _saveSettings(data):
|
||||
if "encoding" in data["serial"]:
|
||||
s.set(["serial", "encoding"], data["serial"]["encoding"])
|
||||
|
||||
if "enableShutdownActionCommand" in data["serial"]:
|
||||
s.setBoolean(
|
||||
["serial", "enableShutdownActionCommand"],
|
||||
data["serial"]["enableShutdownActionCommand"],
|
||||
)
|
||||
|
||||
oldLog = s.getBoolean(["serial", "log"])
|
||||
if "log" in data["serial"]:
|
||||
s.setBoolean(["serial", "log"], data["serial"]["log"])
|
||||
|
||||
@@ -7,7 +7,6 @@ import re
|
||||
import threading
|
||||
|
||||
import psutil
|
||||
import sarge
|
||||
from flask import abort, jsonify, request, url_for
|
||||
from flask_babel import gettext
|
||||
|
||||
@@ -18,7 +17,8 @@ from octoprint.server import NO_CONTENT
|
||||
from octoprint.server.api import api
|
||||
from octoprint.server.util.flask import get_remote_address, no_firstrun_access
|
||||
from octoprint.settings import settings as s
|
||||
from octoprint.util.platform import CLOSE_FDS
|
||||
from octoprint.systemcommands import system_command_manager
|
||||
from octoprint.util.commandline import CommandlineCaller
|
||||
|
||||
|
||||
@api.route("/system/usage", methods=["GET"])
|
||||
@@ -165,22 +165,14 @@ def executeSystemCommand(source, command):
|
||||
# we run this with shell=True since we have to trust whatever
|
||||
# our admin configured as command and since we want to allow
|
||||
# shell-alike handling here...
|
||||
p = sarge.run(
|
||||
command_spec["command"],
|
||||
close_fds=CLOSE_FDS,
|
||||
stdout=sarge.Capture(),
|
||||
stderr=sarge.Capture(),
|
||||
shell=True,
|
||||
return_code, stdout_lines, stderr_lines = CommandlineCaller().call(
|
||||
command_spec["command"], shell=True
|
||||
)
|
||||
|
||||
if not do_ignore and p.returncode != 0:
|
||||
returncode = p.returncode
|
||||
stdout_text = p.stdout.text
|
||||
stderr_text = p.stderr.text
|
||||
|
||||
error = "Command for {}:{} failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(
|
||||
source, command, returncode, stdout_text, stderr_text
|
||||
)
|
||||
if not do_ignore and return_code != 0:
|
||||
stdout = "\n".join(stdout_lines)
|
||||
stderr = "\n".join(stderr_lines)
|
||||
error = f"Command for {source}:{command} failed with return code {return_code}:\n\nSTDOUT:\n{stdout}\n\nSTDERR:\n{stderr}"
|
||||
logger.warning(prefix_multilines(error, prefix="! "))
|
||||
if not do_async:
|
||||
raise CommandFailed(error)
|
||||
@@ -241,28 +233,28 @@ def _get_core_command_specs():
|
||||
|
||||
commands = collections.OrderedDict(
|
||||
shutdown={
|
||||
"command": s().get(["server", "commands", "systemShutdownCommand"]),
|
||||
"command": system_command_manager().get_system_shutdown_command(),
|
||||
"name": gettext("Shutdown system"),
|
||||
"confirm": gettext(
|
||||
"<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
|
||||
),
|
||||
},
|
||||
reboot={
|
||||
"command": s().get(["server", "commands", "systemRestartCommand"]),
|
||||
"command": system_command_manager().get_system_restart_command(),
|
||||
"name": gettext("Reboot system"),
|
||||
"confirm": gettext(
|
||||
"<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
|
||||
),
|
||||
},
|
||||
restart={
|
||||
"command": s().get(["server", "commands", "serverRestartCommand"]),
|
||||
"command": system_command_manager().get_server_restart_command(),
|
||||
"name": gettext("Restart OctoPrint"),
|
||||
"confirm": gettext(
|
||||
"<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
|
||||
),
|
||||
},
|
||||
restart_safe={
|
||||
"command": s().get(["server", "commands", "serverRestartCommand"]),
|
||||
"command": system_command_manager().get_server_restart_command(),
|
||||
"name": gettext("Restart OctoPrint in safe mode"),
|
||||
"confirm": gettext(
|
||||
"<strong>You are about to restart the OctoPrint server in safe mode.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
|
||||
|
||||
@@ -168,6 +168,7 @@ default_settings = {
|
||||
"resendRatioStart": 100,
|
||||
"ignoreEmptyPorts": False,
|
||||
"encoding": "ascii",
|
||||
"enableShutdownActionCommand": False,
|
||||
# command specific flags
|
||||
"triggerOkForM29": True,
|
||||
},
|
||||
|
||||
@@ -247,6 +247,7 @@ $(function () {
|
||||
self.serial_ackMax = ko.observable(undefined);
|
||||
self.serial_resendRatioThreshold = ko.observable(100);
|
||||
self.serial_resendRatioStart = ko.observable(100);
|
||||
self.serial_enableShutdownActionCommand = ko.observable(undefined);
|
||||
|
||||
self.folder_uploads = ko.observable(undefined);
|
||||
self.folder_timelapse = ko.observable(undefined);
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
This module represents OctoPrint's system and server commands.
|
||||
"""
|
||||
|
||||
__author__ = "Johan Verrept <johan@verrept.eu>"
|
||||
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
|
||||
__copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
import logging
|
||||
|
||||
from octoprint.settings import settings
|
||||
from octoprint.util.commandline import CommandlineCaller, CommandlineError
|
||||
|
||||
# singleton
|
||||
_instance = None
|
||||
|
||||
|
||||
def system_command_manager():
|
||||
global _instance
|
||||
if _instance is None:
|
||||
_instance = SystemCommandManager()
|
||||
return _instance
|
||||
|
||||
|
||||
class SystemCommandManager:
|
||||
|
||||
SERVER_RESTART_COMMAND = "serverRestartCommand"
|
||||
SYSTEM_RESTART_COMMAND = "systemRestartCommand"
|
||||
SYSTEM_SHUTDOWN_COMMAND = "systemShutdownCommand"
|
||||
|
||||
def __init__(self):
|
||||
self._logger = logging.getLogger(__name__)
|
||||
self._caller = CommandlineCaller()
|
||||
|
||||
def execute(self, command):
|
||||
if not command:
|
||||
return False
|
||||
|
||||
try:
|
||||
# we run this with shell=True since we have to trust whatever
|
||||
# our admin configured as command and since we want to allow
|
||||
# shell-alike handling here...
|
||||
p = self._caller.non_blocking_call(command, shell=True)
|
||||
|
||||
if p is None:
|
||||
raise CommandlineError(None, "", "")
|
||||
|
||||
if p.returncode is not None:
|
||||
stdout = p.stdout.text if p is not None and p.stdout is not None else ""
|
||||
stderr = p.stderr.text if p is not None and p.stderr is not None else ""
|
||||
raise CommandlineError(p.returncode, stdout, stderr)
|
||||
except CommandlineError:
|
||||
raise
|
||||
except Exception:
|
||||
self._logger.exception(f"Error while executing command: {command}")
|
||||
raise CommandlineError(None, "", "")
|
||||
|
||||
return True
|
||||
|
||||
def get_command(self, cmd):
|
||||
return settings().get(["server", "commands", cmd])
|
||||
|
||||
def has_command(self, cmd):
|
||||
return self.get_command(cmd) is not None
|
||||
|
||||
def get_server_restart_command(self):
|
||||
return self.get_command(self.SERVER_RESTART_COMMAND)
|
||||
|
||||
def get_system_restart_command(self):
|
||||
return self.get_command(self.SYSTEM_RESTART_COMMAND)
|
||||
|
||||
def get_system_shutdown_command(self):
|
||||
return self.get_command(self.SYSTEM_SHUTDOWN_COMMAND)
|
||||
|
||||
def has_server_restart_command(self):
|
||||
return self.get_server_restart_command() is not None
|
||||
|
||||
def has_system_restart_command(self):
|
||||
return self.get_system_restart_command() is not None
|
||||
|
||||
def has_system_shutdown_command(self):
|
||||
return self.get_system_shutdown_command() is not None
|
||||
|
||||
def perform_server_restart(self):
|
||||
return self.execute(self.get_server_restart_command())
|
||||
|
||||
def perform_system_restart(self):
|
||||
return self.execute(self.get_system_restart_command())
|
||||
|
||||
def perform_system_shutdown(self):
|
||||
return self.execute(self.get_system_shutdown_command())
|
||||
@@ -486,6 +486,15 @@
|
||||
</div>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>{{ _('Action commands') }}</legend>
|
||||
<div class="controls">
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" data-bind="checked: serial_enableShutdownActionCommand" id="settings-serialEnableShutdownActionCommand"> {{ _('Enable the <code>shutdown</code> action command') }}
|
||||
<span class="help-block">{{ _('If enabled and the system shutdown command is configured, your printer\'s firmware will be able to shutdown your OctoPrint server via an action command on the serial connection. This could get abused, so only enable this if you trust your firmware and your GCODE files!') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div id="settings_serial_behaviour" class="tab-pane">
|
||||
<fieldset>
|
||||
|
||||
+56
-14
@@ -27,6 +27,7 @@ from octoprint.events import Events, eventManager
|
||||
from octoprint.filemanager import valid_file_type
|
||||
from octoprint.filemanager.destinations import FileDestinations
|
||||
from octoprint.settings import settings
|
||||
from octoprint.systemcommands import system_command_manager
|
||||
from octoprint.util import (
|
||||
CountedEvent,
|
||||
PrependableQueue,
|
||||
@@ -48,7 +49,7 @@ try:
|
||||
import winreg
|
||||
except ImportError:
|
||||
try:
|
||||
import _winreg as winreg
|
||||
import _winreg as winreg # type: ignore
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
@@ -773,6 +774,11 @@ class MachineCom:
|
||||
# serial encoding
|
||||
self._serial_encoding = settings().get(["serial", "encoding"])
|
||||
|
||||
# action commands
|
||||
self._enable_shutdown_action_command = settings().getBoolean(
|
||||
["serial", "enableShutdownActionCommand"]
|
||||
)
|
||||
|
||||
# print job
|
||||
self._currentFile = None
|
||||
self._job_on_hold = CountedEvent()
|
||||
@@ -2282,25 +2288,32 @@ class MachineCom:
|
||||
|
||||
if action_name == "start":
|
||||
if self._currentFile is not None:
|
||||
self._log(
|
||||
"(Re)Starting current job on request of the printer..."
|
||||
self._dual_log(
|
||||
"(Re)Starting current job on request of the printer...",
|
||||
level=logging.INFO,
|
||||
)
|
||||
self.startPrint(
|
||||
tags={"trigger:serial.action_command.start"}
|
||||
)
|
||||
elif action_name == "cancel":
|
||||
self._log("Cancelling on request of the printer...")
|
||||
self._dual_log(
|
||||
"Cancelling on request of the printer...",
|
||||
level=logging.INFO,
|
||||
)
|
||||
self.cancelPrint(
|
||||
tags={"trigger:serial.action_command.cancel"}
|
||||
)
|
||||
elif action_name == "pause":
|
||||
self._log("Pausing on request of the printer...")
|
||||
self._dual_log(
|
||||
"Pausing on request of the printer...", level=logging.INFO
|
||||
)
|
||||
self.setPause(
|
||||
True, tags={"trigger:serial.action_command.pause"}
|
||||
)
|
||||
elif action_name == "paused":
|
||||
self._log(
|
||||
"Printer signalled that it paused, switching state..."
|
||||
self._dual_log(
|
||||
"Printer signalled that it paused, switching state...",
|
||||
level=logging.INFO,
|
||||
)
|
||||
self.setPause(
|
||||
True,
|
||||
@@ -2308,13 +2321,17 @@ class MachineCom:
|
||||
tags={"trigger:serial.action_command.paused"},
|
||||
)
|
||||
elif action_name == "resume":
|
||||
self._log("Resuming on request of the printer...")
|
||||
self._dual_log(
|
||||
"Resuming on request of the printer...",
|
||||
level=logging.INFO,
|
||||
)
|
||||
self.setPause(
|
||||
False, tags={"trigger:serial.action_command.resume"}
|
||||
)
|
||||
elif action_name == "resumed":
|
||||
self._log(
|
||||
"Printer signalled that it resumed, switching state..."
|
||||
self._dual_log(
|
||||
"Printer signalled that it resumed, switching state...",
|
||||
level=logging.INFO,
|
||||
)
|
||||
self.setPause(
|
||||
False,
|
||||
@@ -2322,20 +2339,45 @@ class MachineCom:
|
||||
tags={"trigger:serial.action_command.resumed"},
|
||||
)
|
||||
elif action_name == "disconnect":
|
||||
self._log("Disconnecting on request of the printer...")
|
||||
self._dual_log(
|
||||
"Disconnecting on request of the printer...",
|
||||
level=logging.INFO,
|
||||
)
|
||||
self._callback.on_comm_force_disconnect()
|
||||
elif action_name == "shutdown":
|
||||
if self._enable_shutdown_action_command:
|
||||
self._dual_log(
|
||||
"Shutting down system on request of printer...",
|
||||
level=logging.WARNING,
|
||||
)
|
||||
try:
|
||||
system_command_manager().perform_system_shutdown()
|
||||
except Exception as ex:
|
||||
self._log(f"Error executing system shutdown: {ex}")
|
||||
else:
|
||||
self._dual_log(
|
||||
"Received a shutdown command from the printer, but processing of this command is disabled",
|
||||
level=logging.WARNING,
|
||||
)
|
||||
elif self._sdEnabled and action_name == "sd_inserted":
|
||||
self._log("Printer reported SD card as inserted")
|
||||
self._dual_log(
|
||||
"Printer reported SD card as inserted", level=logging.INFO
|
||||
)
|
||||
self._sdAvailable = True
|
||||
self.refreshSdFiles()
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
elif self._sdEnabled and action_name == "sd_ejected":
|
||||
self._log("Printer reported SD card as ejected")
|
||||
self._dual_log(
|
||||
"Printer reported SD card as ejected", level=logging.INFO
|
||||
)
|
||||
self._sdAvailable = False
|
||||
self._sdFiles = []
|
||||
self._callback.on_comm_sd_state_change(self._sdAvailable)
|
||||
elif self._sdEnabled and action_name == "sd_updated":
|
||||
self._log("Printer reported a change on the SD card")
|
||||
self._dual_log(
|
||||
"Printer reported a change on the SD card",
|
||||
level=logging.INFO,
|
||||
)
|
||||
self.refreshSdFiles()
|
||||
else:
|
||||
for name, hook in self._printer_action_hooks.items():
|
||||
|
||||
@@ -8,7 +8,7 @@ import queue
|
||||
import re
|
||||
import time
|
||||
import warnings
|
||||
from typing import Dict, List, Tuple, Union
|
||||
from typing import List, Optional, Tuple, Union
|
||||
|
||||
import sarge
|
||||
|
||||
@@ -157,8 +157,12 @@ class CommandlineCaller:
|
||||
return returncode, stdout, stderr
|
||||
|
||||
def call(
|
||||
self, command: Union[str, List[str], Tuple[str]], **kwargs: Dict[str, str]
|
||||
) -> Tuple[int, List[str], List[str]]:
|
||||
self,
|
||||
command: Union[str, List[str], Tuple[str]],
|
||||
delimiter: bytes = b"\n",
|
||||
buffer_size: int = -1,
|
||||
**kwargs,
|
||||
) -> Tuple[Optional[int], List[str], List[str]]:
|
||||
"""
|
||||
Calls a command
|
||||
|
||||
@@ -171,49 +175,10 @@ class CommandlineCaller:
|
||||
(tuple) a 3-tuple of return code, full stdout and full stderr output
|
||||
"""
|
||||
|
||||
if isinstance(command, (list, tuple)):
|
||||
joined_command = " ".join(command)
|
||||
else:
|
||||
joined_command = command
|
||||
self._logger.debug(f"Calling: {joined_command}")
|
||||
self.on_log_call(joined_command)
|
||||
|
||||
delimiter = kwargs.get("delimiter", b"\n")
|
||||
try:
|
||||
kwargs.pop("delimiter")
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
buffer_size = kwargs.get("buffer_size", -1)
|
||||
try:
|
||||
kwargs.pop("buffer_size")
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
kwargs.update(
|
||||
{
|
||||
"close_fds": CLOSE_FDS,
|
||||
"async_": True,
|
||||
"stdout": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
|
||||
"stderr": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
|
||||
}
|
||||
p = self.non_blocking_call(
|
||||
command, delimiter=delimiter, buffer_size=buffer_size, **kwargs
|
||||
)
|
||||
|
||||
p = sarge.run(command, **kwargs)
|
||||
while len(p.commands) == 0:
|
||||
# somewhat ugly... we can't use wait_events because
|
||||
# the events might not be all set if an exception
|
||||
# by sarge is triggered within the async process
|
||||
# thread
|
||||
time.sleep(0.01)
|
||||
|
||||
# by now we should have a command, let's wait for its
|
||||
# process to have been prepared
|
||||
p.commands[0].process_ready.wait()
|
||||
|
||||
if not p.commands[0].process:
|
||||
# the process might have been set to None in case of any exception
|
||||
self._logger.error(f"Error while trying to run command {joined_command}")
|
||||
if p is None:
|
||||
return None, [], []
|
||||
|
||||
all_stdout = []
|
||||
@@ -248,6 +213,48 @@ class CommandlineCaller:
|
||||
|
||||
return p.returncode, all_stdout, all_stderr
|
||||
|
||||
def non_blocking_call(
|
||||
self,
|
||||
command: Union[str, List, Tuple],
|
||||
delimiter: bytes = b"\n",
|
||||
buffer_size: int = -1,
|
||||
**kwargs,
|
||||
) -> Optional[sarge.Pipeline]:
|
||||
if isinstance(command, (list, tuple)):
|
||||
joined_command = " ".join(command)
|
||||
else:
|
||||
joined_command = command
|
||||
self._logger.debug(f"Calling: {joined_command}")
|
||||
self.on_log_call(joined_command)
|
||||
|
||||
kwargs.update(
|
||||
{
|
||||
"close_fds": CLOSE_FDS,
|
||||
"async_": True,
|
||||
"stdout": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
|
||||
"stderr": DelimiterCapture(delimiter=delimiter, buffer_size=buffer_size),
|
||||
}
|
||||
)
|
||||
|
||||
p = sarge.run(command, **kwargs)
|
||||
while len(p.commands) == 0:
|
||||
# somewhat ugly... we can't use wait_events because
|
||||
# the events might not be all set if an exception
|
||||
# by sarge is triggered within the async process
|
||||
# thread
|
||||
time.sleep(0.01)
|
||||
|
||||
# by now we should have a command, let's wait for its
|
||||
# process to have been prepared
|
||||
p.commands[0].process_ready.wait()
|
||||
|
||||
if not p.commands[0].process:
|
||||
# the process might have been set to None in case of any exception
|
||||
self._logger.error(f"Error while trying to run command {joined_command}")
|
||||
return None
|
||||
|
||||
return p
|
||||
|
||||
def _log_stdout(self, *lines):
|
||||
self.on_log_stdout(*lines)
|
||||
|
||||
|
||||
Reference in new issue
Block a user