Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: uninstall custom signal handlers before shutdown #5913

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions cloudinit/config/cc_package_update_upgrade_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import os
import time

from cloudinit import subp, util
from cloudinit import signal_handler, subp, util
from cloudinit.cloud import Cloud
from cloudinit.config import Config
from cloudinit.config.schema import MetaSchema
Expand Down Expand Up @@ -48,6 +48,9 @@ def _fire_reboot(
wait_attempts: int = 6, initial_sleep: int = 1, backoff: int = 2
):
"""Run a reboot command and panic if it doesn't happen fast enough."""
# systemd will kill cloud-init with a signal
# this is expected so don't behave as if this is a failure state
signal_handler.detach_handlers()
subp.subp(REBOOT_CMD)
start = time.monotonic()
wait_time = initial_sleep
Expand Down Expand Up @@ -106,8 +109,9 @@ def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:
break
if (upgrade or pkglist) and reboot_if_required and reboot_fn_exists:
try:
LOG.warning(
"Rebooting after upgrade or install per %s", reboot_marker
LOG.info(
"***WARNING*** Rebooting after upgrade or install per %s",
reboot_marker,
)
# Flush the above warning + anything else out...
flush_loggers(LOG)
Expand Down
5 changes: 4 additions & 1 deletion cloudinit/config/cc_power_state_change.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import subprocess
import time

from cloudinit import subp, util
from cloudinit import signal_handler, subp, util
from cloudinit.cloud import Cloud
from cloudinit.config import Config
from cloudinit.config.schema import MetaSchema
Expand Down Expand Up @@ -217,4 +217,7 @@ def fatal(msg):
except Exception as e:
fatal("Unexpected Exception when checking condition: %s" % e)

# systemd could kill this process with a signal before it exits
# this is expected, so remove the signal handlers
signal_handler.detach_handlers()
func(*args)
63 changes: 56 additions & 7 deletions cloudinit/signal_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,59 @@
import signal
import sys
from io import StringIO
from typing import Callable, Dict, NamedTuple, Union

from cloudinit import version as vr
from cloudinit.log import log_util

LOG = logging.getLogger(__name__)


class SignalType(NamedTuple):
message: str
exit_code: int
default_signal: Union[Callable, int, None]


def default_handler(_num, _stack) -> None:
"""an empty handler"""
return None


def get_handler(sig: Union[int, Callable, None]) -> Callable:
"""get_handler gets a callable from signal.signal() output."""
if callable(sig):
return sig
elif sig is None:
LOG.warning("Signal handler was not installed from Python!")
elif sig == signal.SIG_DFL:
LOG.warning("Signal was in unexpected state: SIG_DFL")
elif sig == signal.SIG_IGN:
LOG.warning("Signal was in unexpected state: SIG_IGN")
else:
LOG.warning(
"Process signal is in an unknown state: %s(%s)", type(sig), sig
)
return default_handler


BACK_FRAME_TRACE_DEPTH = 3
EXIT_FOR = {
signal.SIGINT: ("Cloud-init %(version)s received SIGINT, exiting...", 1),
signal.SIGTERM: ("Cloud-init %(version)s received SIGTERM, exiting...", 1),
# Can't be caught...
# signal.SIGKILL: ('Cloud-init killed, exiting...', 1),
signal.SIGABRT: ("Cloud-init %(version)s received SIGABRT, exiting...", 1),
EXIT_FOR: Dict[int, SignalType] = {
signal.SIGINT: SignalType(
"Cloud-init %(version)s received SIGINT, exiting...",
1,
signal.getsignal(signal.SIGINT),
),
signal.SIGTERM: SignalType(
"Cloud-init %(version)s received SIGTERM, exiting...",
1,
signal.getsignal(signal.SIGTERM),
),
signal.SIGABRT: SignalType(
"Cloud-init %(version)s received SIGABRT, exiting...",
1,
signal.getsignal(signal.SIGABRT),
),
}


Expand All @@ -39,7 +78,7 @@ def _pprint_frame(frame, depth, max_depth, contents):


def _handle_exit(signum, frame):
(msg, rc) = EXIT_FOR[signum]
msg, rc, _ = EXIT_FOR[signum]
msg = msg % ({"version": vr.version_string()})
contents = StringIO()
contents.write("%s\n" % (msg))
Expand All @@ -49,8 +88,18 @@ def _handle_exit(signum, frame):


def attach_handlers():
"""attach cloud-init's handlers"""
sigs_attached = 0
for signum in EXIT_FOR.keys():
signal.signal(signum, _handle_exit)
sigs_attached += len(EXIT_FOR)
return sigs_attached


def detach_handlers():
"""dettach cloud-init's handlers"""
sigs_attached = 0
for number, sig_type in EXIT_FOR.items():
signal.signal(number, get_handler(sig_type.default_signal))
sigs_attached += len(EXIT_FOR)
return sigs_attached
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def _isfile(filename: str):
# subp and not really rebooting the system
subp_call = ["/sbin/reboot"]

caplog.set_level(logging.WARNING)
caplog.set_level(logging.INFO)
with mock.patch(
"cloudinit.subp.subp", return_value=SubpResult("{}", "fakeerr")
) as m_subp:
Expand Down
Loading