bd1529
From 2f584bd93d64a75ab11b5a5aa31d0b7145da5a86 Mon Sep 17 00:00:00 2001
bd1529
From: =?UTF-8?q?Zbigniew=20J=C4=99drzejewski-Szmek?= <zbyszek@in.waw.pl>
bd1529
Date: Fri, 26 Apr 2019 13:37:31 +0200
bd1529
Subject: [PATCH] basic/virt: try the /proc/1/sched hack also for PID1
bd1529
bd1529
If a container manager does not set $container, we could end up
bd1529
in a strange situation when detect-virt returns container-other when
bd1529
run as non-pid-1 and none when run as pid-1.
bd1529
bd1529
(cherry picked from commit 342bed02084c4396dd2f1054bd559bfb2699cfcb)
bd1529
Resolves: #1868877
bd1529
---
bd1529
 src/basic/virt.c | 16 +++++++++++-----
bd1529
 1 file changed, 11 insertions(+), 5 deletions(-)
bd1529
bd1529
diff --git a/src/basic/virt.c b/src/basic/virt.c
bd1529
index e05b3e6d99..dfa1525219 100644
bd1529
--- a/src/basic/virt.c
bd1529
+++ b/src/basic/virt.c
bd1529
@@ -427,7 +427,6 @@ finish:
bd1529
 }
bd1529
 
bd1529
 int detect_container(void) {
bd1529
-
bd1529
         static const struct {
bd1529
                 const char *value;
bd1529
                 int id;
bd1529
@@ -456,9 +455,15 @@ int detect_container(void) {
bd1529
         }
bd1529
 
bd1529
         if (getpid_cached() == 1) {
bd1529
-                /* If we are PID 1 we can just check our own environment variable, and that's authoritative. */
bd1529
-
bd1529
+                /* If we are PID 1 we can just check our own environment variable, and that's authoritative.
bd1529
+                 * We distinguish three cases:
bd1529
+                 * - the variable is not defined → we jump to other checks
bd1529
+                 * - the variable is defined to an empty value → we are not in a container
bd1529
+                 * - anything else → some container, either one of the known ones or "container-other"
bd1529
+                 */
bd1529
                 e = getenv("container");
bd1529
+                if (!e)
bd1529
+                        goto check_sched;
bd1529
                 if (isempty(e)) {
bd1529
                         r = VIRTUALIZATION_NONE;
bd1529
                         goto finish;
bd1529
@@ -486,8 +491,9 @@ int detect_container(void) {
bd1529
         if (r < 0) /* This only works if we have CAP_SYS_PTRACE, hence let's better ignore failures here */
bd1529
                 log_debug_errno(r, "Failed to read $container of PID 1, ignoring: %m");
bd1529
 
bd1529
-        /* Interestingly /proc/1/sched actually shows the host's PID for what we see as PID 1. Hence, if the PID shown
bd1529
-         * there is not 1, we know we are in a PID namespace. and hence a container. */
bd1529
+        /* Interestingly /proc/1/sched actually shows the host's PID for what we see as PID 1. If the PID
bd1529
+         * shown there is not 1, we know we are in a PID namespace and hence a container. */
bd1529
+ check_sched:
bd1529
         r = read_one_line_file("/proc/1/sched", &m);
bd1529
         if (r >= 0) {
bd1529
                 const char *t;