anitazha / rpms / systemd

Forked from rpms/systemd 3 years ago
Clone

Blame SOURCES/0515-nspawn-new-option-to-start-as-PID2.patch

923a60
From 41e91ccdf9fa3097d7b90718cc83e743f4dc8d6b Mon Sep 17 00:00:00 2001
923a60
From: Jan Rybar <jrybar@redhat.com>
923a60
Date: Thu, 17 Aug 2017 18:01:42 +0200
923a60
Subject: [PATCH] nspawn: new option to start as PID2
923a60
923a60
Cherry-picked from: 7732f92
923a60
Resolves: #1417387
923a60
---
923a60
 Makefile.am                   |   2 +
923a60
 man/systemd-nspawn.xml        |  65 +++++++++--
923a60
 src/nspawn/nspawn-stub-pid1.c | 196 ++++++++++++++++++++++++++++++++++
923a60
 src/nspawn/nspawn-stub-pid1.h |  22 ++++
923a60
 src/nspawn/nspawn.c           |  56 ++++++++--
923a60
 5 files changed, 328 insertions(+), 13 deletions(-)
923a60
 create mode 100644 src/nspawn/nspawn-stub-pid1.c
923a60
 create mode 100644 src/nspawn/nspawn-stub-pid1.h
923a60
923a60
diff --git a/Makefile.am b/Makefile.am
923a60
index 7c58fd0504..0e2f8d561c 100644
923a60
--- a/Makefile.am
923a60
+++ b/Makefile.am
923a60
@@ -2658,6 +2658,8 @@ systemd_cgtop_LDADD = \
923a60
 # ------------------------------------------------------------------------------
923a60
 systemd_nspawn_SOURCES = \
923a60
 	src/nspawn/nspawn.c \
923a60
+	src/nspawn/nspawn-stub-pid1.c \
923a60
+	src/nspawn/nspawn-stub-pid1.h \
923a60
 	src/core/mount-setup.c \
923a60
 	src/core/mount-setup.h \
923a60
 	src/core/loopback-setup.c \
923a60
diff --git a/man/systemd-nspawn.xml b/man/systemd-nspawn.xml
923a60
index cbd44d4aba..d0eddaacc3 100644
923a60
--- a/man/systemd-nspawn.xml
923a60
+++ b/man/systemd-nspawn.xml
923a60
@@ -241,16 +241,69 @@
923a60
         <option>--ephemeral</option>.</para></listitem>
923a60
       </varlistentry>
923a60
 
923a60
+      <varlistentry>
923a60
+      <term><option>-a</option></term>
923a60
+        <term><option>--as-pid2</option></term>
923a60
+
923a60
+        <listitem><para>Invoke the shell or specified program as process ID (PID) 2 instead of PID 1 (init). By
923a60
+        default, if neither this option nor <option>--boot</option> is used, the selected binary is run as process with
923a60
+        PID 1, a mode only suitable for programs that are aware of the special semantics that the process with PID 1
923a60
+        has on UNIX. For example, it needs to reap all processes reparented to it, and should implement
923a60
+        <command>sysvinit</command> compatible signal handling (specifically: it needs to reboot on SIGINT, reexecute
923a60
+        on SIGTERM, reload configuration on SIGHUP, and so on). With <option>--as-pid2</option> a minimal stub init
923a60
+        process is run as PID 1 and the selected binary is executed as PID 2 (and hence does not need to implement any
923a60
+        special semantics). The stub init process will reap processes as necessary and react appropriately to
923a60
+        signals. It is recommended to use this mode to invoke arbitrary commands in containers, unless they have been
923a60
+        modified to run correctly as PID 1. Or in other words: this switch should be used for pretty much all commands,
923a60
+        except when the command refers to an init or shell implementation, as these are generally capable of running
923a60
+        correctly as PID 1). This option may not be combined with <option>--boot</option> or
923a60
+        <option>--share-system</option>.</para>
923a60
+        </listitem>
923a60
+      </varlistentry>
923a60
+
923a60
       <varlistentry>
923a60
         <term><option>-b</option></term>
923a60
         <term><option>--boot</option></term>
923a60
 
923a60
-        <listitem><para>Automatically search for an init binary and
923a60
-        invoke it instead of a shell or a user supplied program. If
923a60
-        this option is used, arguments specified on the command line
923a60
-        are used as arguments for the init binary. This option may not
923a60
-        be combined with <option>--share-system</option>.
923a60
-        </para></listitem>
923a60
+        <listitem><para>Automatically search for an init binary and invoke it as PID 1, instead of a shell or a user
923a60
+        supplied program. If this option is used, arguments specified on the command line are used as arguments for the
923a60
+        init binary. This option may not be combined with <option>--as-pid2</option> or
923a60
+        <option>--share-system</option>.</para>
923a60
+
923a60
+        <para>The following table explains the different modes of invocation and relationship to
923a60
+        <option>--as-pid2</option> (see above):</para>
923a60
+
923a60
+        
923a60
+          <title>Invocation Mode</title>
923a60
+          <tgroup cols='2' align='left' colsep='1' rowsep='1'>
923a60
+            <colspec colname="switch" />
923a60
+            <colspec colname="explanation" />
923a60
+            
923a60
+              <row>
923a60
+                <entry>Switch</entry>
923a60
+                <entry>Explanation</entry>
923a60
+              </row>
923a60
+            
923a60
+            
923a60
+              <row>
923a60
+                <entry>Neither <option>--as-pid2</option> nor <option>--boot</option> specified</entry>
923a60
+                <entry>The passed parameters are interpreted as command line, which is executed as PID 1 in the container.</entry>
923a60
+              </row>
923a60
+
923a60
+              <row>
923a60
+                <entry><option>--as-pid2</option> specified</entry>
923a60
+                <entry>The passed parameters are interpreted as command line, which are executed as PID 2 in the container. A stub init process is run as PID 1.</entry>
923a60
+              </row>
923a60
+
923a60
+              <row>
923a60
+                <entry><option>--boot</option> specified</entry>
923a60
+                <entry>An init binary as automatically searched and run as PID 1 in the container. The passed parameters are used as invocation parameters for this process.</entry>
923a60
+              </row>
923a60
+
923a60
+            
923a60
+          </tgroup>
923a60
+        
923a60
+        </listitem>
923a60
       </varlistentry>
923a60
 
923a60
       <varlistentry>
923a60
diff --git a/src/nspawn/nspawn-stub-pid1.c b/src/nspawn/nspawn-stub-pid1.c
923a60
new file mode 100644
923a60
index 0000000000..11c11560c4
923a60
--- /dev/null
923a60
+++ b/src/nspawn/nspawn-stub-pid1.c
923a60
@@ -0,0 +1,196 @@
923a60
+/***
923a60
+  This file is part of systemd.
923a60
+
923a60
+  Copyright 2016 Lennart Poettering
923a60
+
923a60
+  systemd is free software; you can redistribute it and/or modify it
923a60
+  under the terms of the GNU Lesser General Public License as published by
923a60
+  the Free Software Foundation; either version 2.1 of the License, or
923a60
+  (at your option) any later version.
923a60
+
923a60
+  systemd is distributed in the hope that it will be useful, but
923a60
+  WITHOUT ANY WARRANTY; without even the implied warranty of
923a60
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
923a60
+  Lesser General Public License for more details.
923a60
+
923a60
+  You should have received a copy of the GNU Lesser General Public License
923a60
+  along with systemd; If not, see <http://www.gnu.org/licenses/>.
923a60
+***/
923a60
+
923a60
+#include <sys/reboot.h>
923a60
+#include <sys/unistd.h>
923a60
+#include <sys/wait.h>
923a60
+#include <sys/prctl.h>
923a60
+
923a60
+#include "log.h"
923a60
+#include "nspawn-stub-pid1.h"
923a60
+#include "util.h"
923a60
+#include "time-util.h"
923a60
+#include "def.h"
923a60
+
923a60
+static int reset_environ(const char *new_environment, size_t length) {
923a60
+        unsigned long start, end;
923a60
+
923a60
+        start = (unsigned long) new_environment;
923a60
+        end = start + length;
923a60
+
923a60
+        if (prctl(PR_SET_MM, PR_SET_MM_ENV_START, start, 0, 0) < 0)
923a60
+                return -errno;
923a60
+
923a60
+        if (prctl(PR_SET_MM, PR_SET_MM_ENV_END, end, 0, 0) < 0)
923a60
+                return -errno;
923a60
+
923a60
+        return 0;
923a60
+}
923a60
+
923a60
+int stub_pid1(sd_id128_t uuid) {
923a60
+        enum {
923a60
+                STATE_RUNNING,
923a60
+                STATE_REBOOT,
923a60
+                STATE_POWEROFF,
923a60
+        } state = STATE_RUNNING;
923a60
+
923a60
+        sigset_t fullmask, oldmask, waitmask;
923a60
+        usec_t quit_usec = USEC_INFINITY;
923a60
+        pid_t pid;
923a60
+        int r;
923a60
+
923a60
+        /* The new environment we set up, on the stack. */
923a60
+        char new_environment[] =
923a60
+                "container=systemd-nspawn\0"
923a60
+                "container_uuid=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
923a60
+
923a60
+        /* Implements a stub PID 1, that reaps all processes and processes a couple of standard signals. This is useful
923a60
+         * for allowing arbitrary processes run in a container, and still have all zombies reaped. */
923a60
+
923a60
+        assert_se(sigfillset(&fullmask) >= 0);
923a60
+        assert_se(sigprocmask(SIG_BLOCK, &fullmask, &oldmask) >= 0);
923a60
+
923a60
+        pid = fork();
923a60
+        if (pid < 0)
923a60
+                return log_error_errno(errno, "Failed to fork child pid: %m");
923a60
+
923a60
+        if (pid == 0) {
923a60
+                /* Return in the child */
923a60
+                assert_se(sigprocmask(SIG_SETMASK, &oldmask, NULL) >= 0);
923a60
+                setsid();
923a60
+                return 0;
923a60
+        }
923a60
+
923a60
+        reset_all_signal_handlers();
923a60
+
923a60
+        log_close();
923a60
+        close_all_fds(NULL, 0);
923a60
+        log_open();
923a60
+
923a60
+        /* Flush out /proc/self/environ, so that we don't leak the environment from the host into the container. Also,
923a60
+         * set $container= and $container_uuid= so that clients in the container that query it from /proc/1/environ
923a60
+         * find them set. */
923a60
+        sd_id128_to_string(uuid, new_environment + sizeof(new_environment) - SD_ID128_STRING_MAX);
923a60
+        reset_environ(new_environment, sizeof(new_environment));
923a60
+
923a60
+        rename_process("STUBINIT");
923a60
+
923a60
+        assert_se(sigemptyset(&waitmask) >= 0);
923a60
+
923a60
+        sigset_add_many(&waitmask,
923a60
+                        SIGCHLD,          /* posix: process died */
923a60
+                        SIGINT,           /* sysv: ctrl-alt-del */
923a60
+                        SIGRTMIN+3,       /* systemd: halt */
923a60
+                        SIGRTMIN+4,       /* systemd: poweroff */
923a60
+                        SIGRTMIN+5,       /* systemd: reboot */
923a60
+                        SIGRTMIN+6,       /* systemd: kexec */
923a60
+                        SIGRTMIN+13,      /* systemd: halt */
923a60
+                        SIGRTMIN+14,      /* systemd: poweroff */
923a60
+                        SIGRTMIN+15,      /* systemd: reboot */
923a60
+                        SIGRTMIN+16,      /* systemd: kexec */
923a60
+                        -1);
923a60
+
923a60
+        /* Note that we ignore SIGTERM (sysv's reexec), SIGHUP (reload), and all other signals here, since we don't
923a60
+         * support reexec/reloading in this stub process. */
923a60
+
923a60
+        for (;;) {
923a60
+                siginfo_t si;
923a60
+                usec_t current_usec;
923a60
+
923a60
+                si.si_pid = 0;
923a60
+                r = waitid(P_ALL, 0, &si, WEXITED|WNOHANG);
923a60
+                if (r < 0) {
923a60
+                        r = log_error_errno(errno, "Failed to reap children: %m");
923a60
+                        goto finish;
923a60
+                }
923a60
+
923a60
+                current_usec = now(CLOCK_MONOTONIC);
923a60
+
923a60
+                if (si.si_pid == pid || current_usec >= quit_usec) {
923a60
+
923a60
+                        /* The child we started ourselves died or we reached a timeout. */
923a60
+
923a60
+                        if (state == STATE_REBOOT) { /* dispatch a queued reboot */
923a60
+                                (void) reboot(RB_AUTOBOOT);
923a60
+                                r = log_error_errno(errno, "Failed to reboot: %m");
923a60
+                                goto finish;
923a60
+
923a60
+                        } else if (state == STATE_POWEROFF)
923a60
+                                (void) reboot(RB_POWER_OFF); /* if this fails, fall back to normal exit. */
923a60
+
923a60
+                        if (si.si_pid == pid && si.si_code == CLD_EXITED)
923a60
+                                r = si.si_status; /* pass on exit code */
923a60
+                        else
923a60
+                                r = 255; /* signal, coredump, timeout, … */
923a60
+
923a60
+                        goto finish;
923a60
+                }
923a60
+                if (si.si_pid != 0)
923a60
+                        /* We reaped something. Retry until there's nothing more to reap. */
923a60
+                        continue;
923a60
+
923a60
+                if (quit_usec == USEC_INFINITY)
923a60
+                        r = sigwaitinfo(&waitmask, &si);
923a60
+                else {
923a60
+                        struct timespec ts;
923a60
+                        r = sigtimedwait(&waitmask, &si, timespec_store(&ts, quit_usec - current_usec));
923a60
+                }
923a60
+                if (r < 0) {
923a60
+                        if (errno == EINTR) /* strace -p attach can result in EINTR, let's handle this nicely. */
923a60
+                                continue;
923a60
+                        if (errno == EAGAIN) /* timeout reached */
923a60
+                                continue;
923a60
+
923a60
+                        r = log_error_errno(errno, "Failed to wait for signal: %m");
923a60
+                        goto finish;
923a60
+                }
923a60
+
923a60
+                if (si.si_signo == SIGCHLD)
923a60
+                        continue; /* Let's reap this */
923a60
+
923a60
+                if (state != STATE_RUNNING)
923a60
+                        continue;
923a60
+
923a60
+                /* Would love to use a switch() statement here, but SIGRTMIN is actually a function call, not a
923a60
+                 * constant… */
923a60
+
923a60
+                if (si.si_signo == SIGRTMIN+3 ||
923a60
+                    si.si_signo == SIGRTMIN+4 ||
923a60
+                    si.si_signo == SIGRTMIN+13 ||
923a60
+                    si.si_signo == SIGRTMIN+14)
923a60
+
923a60
+                        state = STATE_POWEROFF;
923a60
+
923a60
+                else if (si.si_signo == SIGINT ||
923a60
+                         si.si_signo == SIGRTMIN+5 ||
923a60
+                         si.si_signo == SIGRTMIN+6 ||
923a60
+                         si.si_signo == SIGRTMIN+15 ||
923a60
+                         si.si_signo == SIGRTMIN+16)
923a60
+
923a60
+                        state = STATE_REBOOT;
923a60
+                else
923a60
+                        assert_not_reached("Got unexpected signal");
923a60
+
923a60
+                /* (void) kill_and_sigcont(pid, SIGTERM); */
923a60
+                quit_usec = now(CLOCK_MONOTONIC) + DEFAULT_TIMEOUT_USEC;
923a60
+        }
923a60
+
923a60
+finish:
923a60
+        _exit(r < 0 ? EXIT_FAILURE : r);
923a60
+}
923a60
diff --git a/src/nspawn/nspawn-stub-pid1.h b/src/nspawn/nspawn-stub-pid1.h
923a60
new file mode 100644
923a60
index 0000000000..be0f1af4cb
923a60
--- /dev/null
923a60
+++ b/src/nspawn/nspawn-stub-pid1.h
923a60
@@ -0,0 +1,22 @@
923a60
+#pragma once
923a60
+
923a60
+/***
923a60
+  This file is part of systemd.
923a60
+
923a60
+  Copyright 2016 Lennart Poettering
923a60
+
923a60
+  systemd is free software; you can redistribute it and/or modify it
923a60
+  under the terms of the GNU Lesser General Public License as published by
923a60
+  the Free Software Foundation; either version 2.1 of the License, or
923a60
+  (at your option) any later version.
923a60
+
923a60
+  systemd is distributed in the hope that it will be useful, but
923a60
+  WITHOUT ANY WARRANTY; without even the implied warranty of
923a60
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
923a60
+  Lesser General Public License for more details.
923a60
+
923a60
+  You should have received a copy of the GNU Lesser General Public License
923a60
+  along with systemd; If not, see <http://www.gnu.org/licenses/>.
923a60
+***/
923a60
+
923a60
+int stub_pid1(sd_id128_t uuid);
923a60
diff --git a/src/nspawn/nspawn.c b/src/nspawn/nspawn.c
923a60
index d0003d3790..ea365b3f9b 100644
923a60
--- a/src/nspawn/nspawn.c
923a60
+++ b/src/nspawn/nspawn.c
923a60
@@ -99,6 +99,7 @@
923a60
 #include "in-addr-util.h"
923a60
 #include "fw-util.h"
923a60
 #include "local-addresses.h"
923a60
+#include "nspawn-stub-pid1.h"
923a60
 
923a60
 #ifdef HAVE_SECCOMP
923a60
 #include "seccomp-util.h"
923a60
@@ -129,6 +130,14 @@ typedef enum Volatile {
923a60
         VOLATILE_STATE,
923a60
 } Volatile;
923a60
 
923a60
+typedef enum StartMode {
923a60
+        START_PID1, /* Run parameters as command line as process 1 */
923a60
+        START_PID2, /* Use stub init process as PID 1, run parameters as command line as process 2 */
923a60
+        START_BOOT, /* Search for init system, pass arguments as parameters */
923a60
+        _START_MODE_MAX,
923a60
+        _START_MODE_INVALID = -1
923a60
+} StartMode;
923a60
+
923a60
 static char *arg_directory = NULL;
923a60
 static char *arg_template = NULL;
923a60
 static char *arg_user = NULL;
923a60
@@ -139,7 +148,7 @@ static const char *arg_selinux_apifs_context = NULL;
923a60
 static const char *arg_slice = NULL;
923a60
 static bool arg_private_network = false;
923a60
 static bool arg_read_only = false;
923a60
-static bool arg_boot = false;
923a60
+static StartMode arg_start_mode = START_PID1;
923a60
 static bool arg_ephemeral = false;
923a60
 static LinkJournal arg_link_journal = LINK_AUTO;
923a60
 static bool arg_link_journal_try = false;
923a60
@@ -200,6 +209,7 @@ static void help(void) {
923a60
                "  -x --ephemeral            Run container with snapshot of root directory, and\n"
923a60
                "                            remove it after exit\n"
923a60
                "  -i --image=PATH           File system device or disk image for the container\n"
923a60
+               "  -a --as-pid2              Maintain a stub init as PID1, invoke binary as PID2\n"
923a60
                "  -b --boot                 Boot up full system (i.e. invoke init)\n"
923a60
                "  -u --user=USER            Run the command under specified user or uid\n"
923a60
                "  -M --machine=NAME         Set the machine name for the container\n"
923a60
@@ -304,6 +314,7 @@ static int parse_argv(int argc, char *argv[]) {
923a60
                 { "ephemeral",             no_argument,       NULL, 'x'                   },
923a60
                 { "user",                  required_argument, NULL, 'u'                   },
923a60
                 { "private-network",       no_argument,       NULL, ARG_PRIVATE_NETWORK   },
923a60
+                { "as-pid2",               no_argument,       NULL, 'a'                   },
923a60
                 { "boot",                  no_argument,       NULL, 'b'                   },
923a60
                 { "uuid",                  required_argument, NULL, ARG_UUID              },
923a60
                 { "read-only",             no_argument,       NULL, ARG_READ_ONLY         },
923a60
@@ -340,7 +351,7 @@ static int parse_argv(int argc, char *argv[]) {
923a60
         assert(argc >= 0);
923a60
         assert(argv);
923a60
 
923a60
-        while ((c = getopt_long(argc, argv, "+hD:u:bL:M:jS:Z:qi:xp:n", options, NULL)) >= 0)
923a60
+        while ((c = getopt_long(argc, argv, "+hD:u:abL:M:jS:Z:qi:xp:n", options, NULL)) >= 0)
923a60
 
923a60
                 switch (c) {
923a60
 
923a60
@@ -421,7 +432,21 @@ static int parse_argv(int argc, char *argv[]) {
923a60
                         break;
923a60
 
923a60
                 case 'b':
923a60
-                        arg_boot = true;
923a60
+                        if (arg_start_mode == START_PID2) {
923a60
+                                log_error("--boot and --as-pid2 may not be combined.");
923a60
+                                return -EINVAL;
923a60
+                        }
923a60
+
923a60
+                        arg_start_mode = START_BOOT;
923a60
+                        break;
923a60
+
923a60
+                case 'a':
923a60
+                        if (arg_start_mode == START_BOOT) {
923a60
+                                log_error("--boot and --as-pid2 may not be combined.");
923a60
+                                return -EINVAL;
923a60
+                        }
923a60
+
923a60
+                        arg_start_mode = START_PID2;
923a60
                         break;
923a60
 
923a60
                 case ARG_UUID:
923a60
@@ -741,7 +766,7 @@ static int parse_argv(int argc, char *argv[]) {
923a60
         if (arg_share_system)
923a60
                 arg_register = false;
923a60
 
923a60
-        if (arg_boot && arg_share_system) {
923a60
+        if (arg_start_mode != START_PID1 && arg_share_system) {
923a60
                 log_error("--boot and --share-system may not be combined.");
923a60
                 return -EINVAL;
923a60
         }
923a60
@@ -3586,6 +3611,10 @@ int main(int argc, char *argv[]) {
923a60
         log_parse_environment();
923a60
         log_open();
923a60
 
923a60
+        /* Make sure rename_process() in the stub init process can work */
923a60
+        saved_argv = argv;
923a60
+        saved_argc = argc;
923a60
+
923a60
         r = parse_argv(argc, argv);
923a60
         if (r <= 0)
923a60
                 goto finish;
923a60
@@ -3694,7 +3723,7 @@ int main(int argc, char *argv[]) {
923a60
                         }
923a60
                 }
923a60
 
923a60
-                if (arg_boot) {
923a60
+                if (arg_start_mode == START_BOOT) {
923a60
                         if (path_is_os_tree(arg_directory) <= 0) {
923a60
                                 log_error("Directory %s doesn't look like an OS root directory (os-release file is missing). Refusing.", arg_directory);
923a60
                                 r = -EINVAL;
923a60
@@ -4109,7 +4138,19 @@ int main(int argc, char *argv[]) {
923a60
                         if (!barrier_place_and_sync(&barrier))
923a60
                                 _exit(EXIT_FAILURE);
923a60
 
923a60
-                        if (arg_boot) {
923a60
+                        if (arg_start_mode == START_PID2) {
923a60
+                                r = stub_pid1(arg_uuid);
923a60
+                                if (r < 0)
923a60
+                                {
923a60
+                                        log_error_errno(r, "Failed to start as PID2: %m");
923a60
+                                        _exit(EXIT_FAILURE);
923a60
+                                }
923a60
+                        }
923a60
+
923a60
+                        log_close();
923a60
+                        (void) fdset_close_others(fds);
923a60
+
923a60
+                        if (arg_start_mode == START_BOOT) {
923a60
                                 char **a;
923a60
                                 size_t l;
923a60
 
923a60
@@ -4135,6 +4176,7 @@ int main(int argc, char *argv[]) {
923a60
                                 execle("/bin/sh", "-sh", NULL, env_use);
923a60
                         }
923a60
 
923a60
+                        log_open();
923a60
                         log_error_errno(errno, "execv() failed: %m");
923a60
                         _exit(EXIT_FAILURE);
923a60
                 }
923a60
@@ -4210,7 +4252,7 @@ int main(int argc, char *argv[]) {
923a60
                                         goto finish;
923a60
                                 }
923a60
 
923a60
-                                if (arg_boot) {
923a60
+                                if (arg_start_mode == START_BOOT) {
923a60
                                         /* Try to kill the init system on SIGINT or SIGTERM */
923a60
                                         sd_event_add_signal(event, NULL, SIGINT, on_orderly_shutdown, UINT32_TO_PTR(pid));
923a60
                                         sd_event_add_signal(event, NULL, SIGTERM, on_orderly_shutdown, UINT32_TO_PTR(pid));