[PATCH] run: gracefully handle SIGHUP, SIGQUIT, SIGTERM

Daniel P. Berrangé posted 1 patch 2 years, 1 month ago
Patches applied successfully (tree, apply log)
git fetch https://github.com/patchew-project/libvirt tags/patchew/20220309105433.788649-1-berrange@redhat.com
Test syntax-check failed
run.in | 10 ++++++++++
1 file changed, 10 insertions(+)
[PATCH] run: gracefully handle SIGHUP, SIGQUIT, SIGTERM
Posted by Daniel P. Berrangé 2 years, 1 month ago
When using thue 'run' script to launch a daemon, it is intended to
temporarily stop the systemd units and re-start them again after.

When using this script over an SSH connection, it will get SIGHUP
if the connection goes away, and in this case it fails to re-start
the systemd units. We need to catch SIGHUP and turn it into a
normal python exception. For good measure we do the same for
SIGQUIT and SIGTERM too.  SIGINT already gets turned into an
exception by default which we handle.

Signed-off-by: Daniel P. Berrangé <berrange@redhat.com>
---
 run.in | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/run.in b/run.in
index 3be7818d32..c6d3411082 100644
--- a/run.in
+++ b/run.in
@@ -43,6 +43,7 @@
 import os
 import os.path
 import random
+import signal
 import sys
 import subprocess
 
@@ -155,6 +156,13 @@ else:
     print("Temporarily stopping systemd units...")
     stopped_units = []
 
+    def sighandler(signum, frame):
+        raise OSError("Signal %d received, terminating" % signum)
+
+    signal.signal(signal.SIGHUP, sighandler)
+    signal.signal(signal.SIGTERM, sighandler)
+    signal.signal(signal.SIGQUIT, sighandler)
+
     try:
         for unit in try_stop_units:
             print(" > %s" % unit)
@@ -167,6 +175,8 @@ else:
         ret = subprocess.call(args, env=env)
     except KeyboardInterrupt:
         pass
+    except Exception as e:
+        print("%s" % e, file=sys.stderr)
     finally:
         print("Re-starting original systemd units...")
         stopped_units.reverse()
-- 
2.35.1

Re: [PATCH] run: gracefully handle SIGHUP, SIGQUIT, SIGTERM
Posted by Ján Tomko 2 years, 1 month ago
On a Wednesday in 2022, Daniel P. Berrangé wrote:
>When using thue 'run' script to launch a daemon, it is intended to
>temporarily stop the systemd units and re-start them again after.
>
>When using this script over an SSH connection, it will get SIGHUP
>if the connection goes away, and in this case it fails to re-start
>the systemd units. We need to catch SIGHUP and turn it into a
>normal python exception. For good measure we do the same for
>SIGQUIT and SIGTERM too.  SIGINT already gets turned into an
>exception by default which we handle.
>
>Signed-off-by: Daniel P. Berrangé <berrange@redhat.com>
>---
> run.in | 10 ++++++++++
> 1 file changed, 10 insertions(+)
>

Reviewed-by: Ján Tomko <jtomko@redhat.com>

Jano