knaxuslearn · build · ship

Projects / Container runtime / Phase 1

Phase 1 of 4 · about 2.5 hours

Separate the view

You end with a program, rt, that runs any command with its own hostname, its own process numbers and its own list of mounts.

Step 1.1: What a container really is (about 30 minutes)

Before we write code, let's see what the kernel offers. A namespace wraps one global resource so that the processes inside see their own private copy of it. Linux has several kinds, and each one hides a different thing:

NamespaceClone flagWhat it separatesDo we use it?
UTSCLONE_NEWUTShostnamePhase 1
PIDCLONE_NEWPIDprocess numbersPhase 1
MountCLONE_NEWNSthe list of mounted file systemsPhase 1
NetworkCLONE_NEWNETdevices, addresses, routes, portsPhase 4
IPC, cgroup, time, userCLONE_NEWIPC, CLONE_NEWCGROUP, CLONE_NEWTIME, CLONE_NEWUSERmessage queues, the cgroup view, clocks, user idsno, see "Keep going"

The mount flag is called NEWNS because it was the first namespace Linux got, and nobody thought a second one would follow.

Every process has a handle to each of its namespaces in /proc. Two processes that show the same number share that namespace:

for n in uts pid mnt net; do echo "$n $(readlink /proc/self/ns/$n)"; done
uts uts:[4026531838]
pid pid:[4026531836]
mnt mnt:[4026531832]
net net:[4026531833]

Your numbers will differ. What matters is that they are numbers, so a namespace is something we can create and compare. Our runtime has one job in this phase: start a child process in new UTS, PID and mount namespaces, and let it run the command. The system call for that is clone, which works like fork but takes flags saying what the child should not share with its parent.

Creating most kinds of namespace needs the CAP_SYS_ADMIN capability. That is why rt needs root, and we come back to capabilities in Phase 3.

Step 1.2: clone, and what the child does first (about 45 minutes)

Start rt.c with the headers and a helper that prints an error and stops. The last line of the listing sets a size for the child's stack:

#define _GNU_SOURCE
#include <errno.h>
#include <sched.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/wait.h>
#include <unistd.h>

#define STACK_SIZE (1024 * 1024)
static void die(const char *what) {
    fprintf(stderr, "rt: %s: %s\n", what, strerror(errno));
    exit(1);
}

The child needs its own stack, because it shares nothing with the parent. We allocate one by hand in main. die prints the name of the thing that failed and the system's error text, which is all we need to debug this project.

Now the function the child runs. It is the main function of Phase 1:

/* This function runs inside the new namespaces. It is process number 1 there. */
static int child_main(void *arg) {
    char **cmd = arg;

    if (sethostname("box", 3) < 0) die("sethostname");

    /* Stop our mounts from leaking out to the host, then show our own /proc. */
    if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) < 0) die("make mounts private");
    if (mount("proc", "/proc", "proc", 0, NULL) < 0) die("mount /proc");

    execvp(cmd[0], cmd);
    die(cmd[0]);
    return 1;
}

Walk through it:

  • The child is process number 1 of its new PID namespace. We will see in Phase 4 why that number is special.
  • sethostname changes the hostname. It only changes the one in our UTS namespace. The host's name stays as it was.
  • mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) makes every mount below / private. Many Linux systems mark / as shared, which means that a mount made in one mount namespace shows up in the others. Without this line, the /proc we mount next would leak out to the host. MS_REC applies the change to all mounts below / as well.
  • We then mount a fresh proc on /proc. Tools such as ps read /proc, and what they see there is decided by the PID namespace of the process that mounted it. The old /proc still shows every process on the machine. This one shows only ours.
  • execvp replaces the child with the command. It keeps process number 1, and nothing else of our code is left.

Last, main starts the child:

int main(int argc, char **argv) {
    if (argc < 3 || strcmp(argv[1], "run") != 0) {
        fprintf(stderr, "usage: %s run COMMAND [ARGS...]\n", argv[0]);
        return 2;
    }

    char *stack = malloc(STACK_SIZE);
    if (!stack) die("malloc");

    int flags = CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | SIGCHLD;
    pid_t pid = clone(child_main, stack + STACK_SIZE, flags, &argv[2]);
    if (pid < 0) die("clone (are you root?)");

    int status;
    if (waitpid(pid, &status, 0) < 0) die("waitpid");
    return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
}
  • The three CLONE_NEW* flags ask for new UTS, PID and mount namespaces. SIGCHLD makes the child send us the usual signal when it ends, so waitpid works.
  • The stack grows downward on x86 and most other machines, so we hand clone the end of the memory block, stack + STACK_SIZE.
  • When clone fails the message says "are you root?", because that is by far the most common reason.
  • At the end we copy the child's exit status, so rt returns what the command returned. A shell script that calls rt can then test for success.

Step 1.3: Build it and run it (about 40 minutes)

Building takes one line. Put it in build.sh:

set -e
gcc -Wall -Wextra -O2 -o rt rt.c

Build, then start a command inside a new set of namespaces:

sh build.sh
sudo ./rt run hostname
box

The command printed box, the name we set in the child. Now let's look at the process numbers. The command below is a shell that prints its own number and then lists every process it can see:

sudo ./rt run sh -c 'echo "my pid is $$"; ps -e -o pid,args'
my pid is 1
    PID COMMAND
      1 sh -c echo "my pid is $$"; ps -e -o pid,args
      2 ps -e -o pid,args

The shell is process 1, and ps itself is process 2. On the host there are hundreds of processes, but the new /proc shows only these two. If you see the whole machine's list, check that the mount proc line ran after the line that makes mounts private.

Step 1.4: Prove it, then break it (about 35 minutes)

A claim like "it is separate" should be checked. Let's compare namespace numbers from inside and from outside:

echo "inside:  $(sudo ./rt run readlink /proc/self/ns/uts)"
echo "outside: $(readlink /proc/self/ns/uts)"
inside:  uts:[4026532265]
outside: uts:[4026531838]

Two different numbers: two different UTS namespaces. The same test works for pid and mnt. Then check the other side, that the host's own hostname was left alone. The second line prints its message only when the host is not called box:

sudo ./rt run hostname
test "$(hostname)" = box || echo "the host name is untouched"
box
the host name is untouched

Now the errors a user will meet. A command that does not exist, and a run without root (we used an ordinary user for the second one):

sudo ./rt run nosuchprogram; echo "exit status $?"
./rt run hostname; echo "exit status $?"
rt: nosuchprogram: No such file or directory
exit status 1
rt: clone (are you root?): Operation not permitted
exit status 1

The second run has no sudo, so it fails when clone is refused. Both messages say what failed, and the exit status is not zero, so scripts can notice.

So far so good, but there is a big gap. Try sudo ./rt run ls /home. The command has its own hostname and its own process numbers, and yet it walks around in the real file system of the host and can read the real files of every user. A container needs a root file system of its own. That is Phase 2.