Added timeout and limit to script entries

This commit is contained in:
Niels Geens
2024-11-13 17:48:39 +01:00
parent 65478e0b17
commit 834ce12e8f
21 changed files with 262 additions and 141 deletions

View File

@@ -11,27 +11,44 @@ class SingleEntry(Entry):
Attributes:
script: The script/command to execute
timeout: Maximum time to wait for script execution
limit: Maximum number of characters to capture from stdout/stderr
stdout: Captured standard output from script execution
stderr: Captured standard error from script execution
exit_code: Process exit code after completion
_executed: Whether the script has been executed
"""
default_timeout = 1
default_limit = 1024
def __init__(self, script: str, id: str, timestamp: datetime):
def __init__(
self,
id: str,
timestamp: datetime,
script: str,
timeout: Optional[float],
limit: Optional[int],
):
"""
Initialize a new single shot entry.
Args:
script: The script/command to execute
id: Unique identifier for this entry
timestamp: Creation timestamp for this entry
script: The script/command to execute
timeout: Maximum time to wait for script execution
limit: Maximum number of characters to capture from stdout/stderr
"""
super().__init__(id, timestamp)
self._script = script
self._timeout = timeout or self.default_timeout
self._limit = limit or self.default_limit
self._stdout = ""
self._stderr = ""
self._exit_code: Optional[int] = None
self._executed = False
self._timed_out = False
@property
def script(self) -> str:
@@ -60,16 +77,20 @@ class SingleEntry(Entry):
"""
if self._executed:
return
process = subprocess.run(
self.script,
shell=True,
capture_output=True,
text=True
)
self._stdout = process.stdout
self._stderr = process.stderr
self._exit_code = process.returncode
self._executed = True
try:
process = subprocess.run(
self._script,
timeout=self._timeout,
shell=True,
capture_output=True,
text=True
)
self._stdout = process.stdout
self._stderr = process.stderr
self._exit_code = process.returncode
except subprocess.TimeoutExpired as e:
self._timed_out = True
def generate_context(self) -> ET.Element:
"""
@@ -82,10 +103,16 @@ class SingleEntry(Entry):
"id": self.id,
})
element.text = self.script
if self._executed:
stdout_elem = ET.SubElement(element, "stdout")
stdout_elem.text = self._stdout
stderr_elem = ET.SubElement(element, "stderr")
stderr_elem.text = self._stderr
if self._timed_out:
element.set("timed_out", "true")
elif self._executed:
element.set("exit_code", str(self._exit_code))
if len(self._stdout) > self._limit:
element.set("stdout_truncated", "true")
stdout_elem = ET.SubElement(element, "stdout")
stdout_elem.text = self._stdout[:self._limit]
if len(self._stderr) > self._limit:
element.set("stderr_truncated", "true")
stderr_elem = ET.SubElement(element, "stderr")
stderr_elem.text = self._stderr[:self._limit]
return element