[elbe-devel] [PATCH 02/10] elbepack: properly shut down async logging

Thomas Weißschuh thomas.weissschuh at linutronix.de
Mon Mar 11 18:02:55 CET 2024


When the background thread continues running the log messages from
multiple commands may be interspersed.
Instead wait for the logging to finish before returning from the exec
functions.

Signed-off-by: Thomas Weißschuh <thomas.weissschuh at linutronix.de>
---
 elbepack/log.py         |  8 ++++++++
 elbepack/shellhelper.py | 10 +++++-----
 2 files changed, 13 insertions(+), 5 deletions(-)

diff --git a/elbepack/log.py b/elbepack/log.py
index e2cceb62c203..7ea9ad0cd04a 100644
--- a/elbepack/log.py
+++ b/elbepack/log.py
@@ -286,3 +286,11 @@ def async_logging(r, w, stream, block, atmost=4096):
                          args=(r, w))
     t.daemon = True
     t.start()
+    return t
+
+
+ at contextmanager
+def async_logging_ctx(*args, **kwargs):
+    t = async_logging(*args, **kwargs)
+    yield
+    t.join()
diff --git a/elbepack/shellhelper.py b/elbepack/shellhelper.py
index edbb6f81edf7..779cdc30ba4c 100644
--- a/elbepack/shellhelper.py
+++ b/elbepack/shellhelper.py
@@ -8,7 +8,7 @@ import os
 from io import BytesIO, TextIOWrapper
 from subprocess import PIPE, Popen, STDOUT, call
 
-from elbepack.log import async_logging
+from elbepack.log import async_logging_ctx
 
 log = logging.getLogger('log')
 soap = logging.getLogger('soap')
@@ -247,8 +247,8 @@ def do(cmd, allow_fail=False, stdin=None, env_add=None, log_cmd=None):
     else:
         p = Popen(cmd, shell=True, stdin=PIPE, stdout=w, stderr=STDOUT, env=new_env)
 
-    async_logging(r, w, soap, log)
-    p.communicate(input=stdin)
+    with async_logging_ctx(r, w, soap, log):
+        p.communicate(input=stdin)
 
     if p.returncode and not allow_fail:
         raise CommandError(cmd, p.returncode)
@@ -325,8 +325,8 @@ def get_command_out(cmd, stdin=None, allow_fail=False, env_add=None):
     else:
         p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=w, env=new_env)
 
-    async_logging(r, w, soap, log)
-    stdout, _ = p.communicate(input=stdin)
+    with async_logging_ctx(r, w, soap, log):
+        stdout, _ = p.communicate(input=stdin)
 
     if p.returncode and not allow_fail:
         raise CommandError(cmd, p.returncode)

-- 
2.44.0



More information about the elbe-devel mailing list