From c4c373dfb7ba8476f696d1decac1074ed3346c60 Mon Sep 17 00:00:00 2001 From: Thomas Liske Date: Mon, 28 Jan 2019 22:16:18 +0100 Subject: [PATCH] [Core] Detect if run inside a container or vm using systemd (closes #139 by Tobby @tobby88). --- ChangeLog | 2 ++ needrestart | 30 +++++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/ChangeLog b/ChangeLog index d4aaa3e8..c45fad15 100644 --- a/ChangeLog +++ b/ChangeLog @@ -7,6 +7,8 @@ needrestart (3.4) unstable; urgency=high (github pull request #133 by @p-bo) - [Core] Add FRR to override. (github pull request #138 by David Lamparter @eqvinox) + - [Core] Detect if run inside a container or vm using systemd. + (github issue #139 by Tobby @tobby88) * Fixes: - [uCode] Ignore broken microcode files (required for CentOS). diff --git a/needrestart b/needrestart index a871a06a..2fc3379d 100755 --- a/needrestart +++ b/needrestart @@ -45,12 +45,26 @@ $|++; $Getopt::Std::STANDARD_HELP_VERSION++; my $LOGPREF = '[main]'; -my $is_systemd = -d qq(/run/systemd/system); +my $is_systemd = -d q(/run/systemd/system); my $is_tty = (-t *STDERR || -t *STDOUT || -t *STDIN); +my $is_vm; my $is_container; -# check if we are inside of a container -if (-r "/proc/1/environ") { +if($is_systemd && -x q(/usr/bin/systemd-detect-virt)) { + # check if we are inside of a vm + my $ret = system(qw(/usr/bin/systemd-detect-virt --vm --quiet)); + unless($? == -1 || $? & 127) { + $is_vm = ($? >> 8) == 0; + } + + # check if we are inside of a container + $ret = system(qw(/usr/bin/systemd-detect-virt --container --quiet)); + unless($? == -1 || $? & 127) { + $is_container = ($? >> 8) == 0; + } +} +elsif (-r "/proc/1/environ") { + # check if we are inside of a container (fallback) local $/; open(HENV, '<', '/proc/1/environ'); $is_container = scalar(grep {/^container=/;} unpack("(Z*)*", )); @@ -325,6 +339,7 @@ sub parse_lsbinit($) { } print STDERR "$LOGPREF systemd detected\n" if($nrconf{verbosity} > 1 && $is_systemd); +print STDERR "$LOGPREF vm detected\n" if($nrconf{verbosity} > 1 && $is_vm); print STDERR "$LOGPREF container detected\n" if($nrconf{verbosity} > 1 && $is_container); sub systemd_refuse_restart { @@ -775,10 +790,15 @@ foreach my $rc (keys %restart) { delete($restart{$rc}); } -# Skip kernel and uCode stuff within containers +# Skip kernel stuff within container if($is_container || needrestart_cont_check($nrconf{verbosity} > 1, 1, nr_readlink(1), 1)) { - print STDERR "$LOGPREF inside container, skipping kernel and microcode checks\n" if($nrconf{verbosity} > 1); + print STDERR "$LOGPREF inside container, skipping kernel checks\n" if($nrconf{verbosity} > 1); $opt_k = undef; +} + +# Skip uCode stuff within container or vm +if($is_container || $is_vm || needrestart_cont_check($nrconf{verbosity} > 1, 1, nr_readlink(1), 1)) { + print STDERR "$LOGPREF inside container or vm, skipping microcode checks\n" if($nrconf{verbosity} > 1); $opt_w = undef; }