Projects / Container runtime / Phase 4
Phase 4 of 4 · about 2.5 hours
Layers, a network of its own, and a real init
You end with a runtime that gives each run a throwaway writable layer on a shared image, a private loopback network, and a process number 1 that reaps orphans, plus a script that checks all of it.
Step 4.1: Layers with overlayfs (about 40 minutes)
Here is a problem we have not looked at. Our container writes straight into the directory it runs from. Go back to the p3 folder for a moment and let's see:
sudo ./rt run rootfs sh -c 'echo hi > /root/note'
ls rootfs/root
note
The file is now part of our "image". Two containers started from the same directory would see each other's files, and nothing could be undone. Real runtimes keep the image read-only and put every run's changes in a separate layer that is thrown away at the end.
Linux has a file system for exactly this, overlayfs. It stacks directories. You give it:
lowerdir: the read-only image, which is never modified,upperdir: an empty directory that collects all changes,workdir: an empty scratch directory on the same file system asupperdir, which the kernel needs for its own bookkeeping.
When a program reads a file, overlayfs takes it from the upper layer if the name is there and from the lower one if not. When a program writes to a file that only exists below, the kernel first copies it up, then changes the copy. Deleting a file below leaves a marker in the upper layer. A real image has many lower layers, which you list with colons in lowerdir. We use one.
The mount is a few lines:
/* Stack a writable layer on top of the read-only image. Writes go to `upper`. */
static void mount_overlay(const struct run *r, const char *merged) {
char real[PATH_MAX], opts[3 * PATH_MAX];
if (!realpath(r->image, real)) die(r->image);
snprintf(opts, sizeof opts, "lowerdir=%s,upperdir=%s/upper,workdir=%s/work", real, r->dir, r->dir);
if (mount("overlay", merged, "overlay", 0, opts) < 0) die("mount overlay");
}
Each run needs its own empty upper, work and merged directories. We create them under a fresh temporary directory and delete everything with nftw, which walks a tree, after the container ends:
static int remove_entry(const char *path, const struct stat *sb, int type, struct FTW *ftw) {
(void)sb;
(void)type;
(void)ftw;
return remove(path);
}
/* Every run gets its own empty writable layer, and throws it away at the end. */
static void make_scratch(struct run *r) {
snprintf(r->dir, sizeof r->dir, "/tmp/rt-XXXXXX");
if (!mkdtemp(r->dir)) die("mkdtemp");
const char *parts[] = {"upper", "work", "merged"};
for (int i = 0; i < 3; i++) {
char path[96];
snprintf(path, sizeof path, "%s/%s", r->dir, parts[i]);
if (mkdir(path, 0755) < 0) die(path);
}
}
The struct grows a field for that directory. And child_main now mounts the overlay on merged and switches into that instead of into the image. This is the final child_main of the project. The loopback call is explained in Step 4.2 and the last line in Step 4.3:
struct run {
const char *image; /* read-only base file system */
char dir[64]; /* per-run scratch directory: upper, work, merged */
char **cmd;
long mem_mb; /* 0 means no limit */
long cpu_secs; /* 0 means no limit */
};
/* This function runs inside the new namespaces. It is process number 1 there. */
static int child_main(void *arg) {
struct run *r = arg;
if (sethostname("box", 3) < 0) die("sethostname");
/* Stop our mounts from leaking out to the host. */
if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) < 0) die("make mounts private");
char merged[sizeof r->dir + 8];
snprintf(merged, sizeof merged, "%s/merged", r->dir);
mount_overlay(r, merged);
enter_rootfs(merged);
if (mount("proc", "/proc", "proc", 0, NULL) < 0) die("mount /proc");
mount_dev();
if (mount("tmpfs", "/tmp", "tmpfs", MS_NOSUID | MS_NODEV, "size=16m") < 0) die("mount /tmp");
setenv("PATH", "/usr/bin:/bin:/usr/sbin:/sbin", 1);
bring_up_loopback();
restrict_process(r);
return run_as_init(r->cmd);
}
If the mount fails with "invalid argument" or "operation not supported", the kernel is telling you that the file system under /tmp cannot be used for the upper layer. The kernel documentation says it must support extended attributes and report valid directory entry types. Move the scratch directory to another disk to test.
Step 4.2: A network of its own (about 40 minutes)
The same clone flags give us a new network namespace. CLONE_NEWNET creates a private copy of everything about networking: devices, addresses, routes, firewall rules and ports. It starts with one device, the loopback lo, and that one is down. So with the flag added the container has no network at all. To make local connections work, we bring lo up with two ioctl calls: read the interface flags, set the IFF_UP bit.
/* Bring the loopback interface up. A new network namespace starts with it down. */
static void bring_up_loopback(void) {
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) die("socket");
struct ifreq ifr;
memset(&ifr, 0, sizeof ifr);
strncpy(ifr.ifr_name, "lo", IFNAMSIZ - 1);
if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) die("read lo flags");
ifr.ifr_flags |= IFF_UP;
if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0) die("bring lo up");
close(fd);
}
Here is a program that tests both cases. It sends a datagram to itself over the loopback, or tries to find a route to the outside:
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
/* "nettest loopback" sends a datagram to ourselves. "nettest outside" asks for a route to the internet. */
int main(int argc, char **argv) {
if (argc < 2) return 2;
int fd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in addr = {.sin_family = AF_INET};
if (strcmp(argv[1], "loopback") == 0) {
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
socklen_t len = sizeof addr;
if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0 ||
getsockname(fd, (struct sockaddr *)&addr, &len) < 0 ||
sendto(fd, "ping", 4, 0, (struct sockaddr *)&addr, sizeof addr) < 0) {
printf("loopback: %s\n", strerror(errno));
return 1;
}
char buf[8];
ssize_t n = recv(fd, buf, sizeof buf, 0);
printf("loopback: got %zd bytes back\n", n);
return 0;
}
addr.sin_port = htons(53);
inet_pton(AF_INET, "8.8.8.8", &addr.sin_addr);
if (connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
printf("outside: %s\n", strerror(errno));
return 1;
}
printf("outside: a route exists\n");
return 0;
}
Rebuild the image (the new tools are picked up automatically) and look at the container's view of the network:
sh build.sh
sh mkrootfs.sh image
sudo ./rt run image sh -c 'cat /proc/net/dev | cut -c1-40'
sudo ./rt run image nettest loopback
sudo ./rt run image nettest outside
Inter-| Receive
face |bytes packets errs drop fifo f
lo: 0 0 0 0 0
loopback: got 4 bytes back
outside: Network is unreachable
exit status 1
Only lo exists. Local traffic works, and there is no way out. Compare with the Phase 3 runtime on the same image, which never created a network namespace:
sudo ../p3/rt run image nettest outside
outside: a route exists
If your machine is offline, this prints the same error as above and the comparison tells you nothing. On a connected machine it finds a route, which means the old container shared the host's network. Giving a container a real connection takes a virtual cable between two namespaces. We leave that for "Keep going".
Step 4.3: A real process number 1 (about 40 minutes)
In Phase 1 we said that process number 1 is special. Here is why. When a process dies, the kernel keeps a small record of it, a zombie, until its parent calls wait and reads the exit status. If the parent dies first, the children are adopted by someone. Inside a PID namespace that someone is process number 1. If number 1 never calls wait, those zombies stay forever. And if number 1 itself ends, the kernel kills everything else in the namespace.
Until now, the user's command was process number 1, and most programs never wait for children they did not start. Let's look at the problem. This program makes an orphan on purpose: A starts B and exits at once, so B is adopted by process 1:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
/* Make an orphan: A starts B and exits at once, so B is adopted by process 1. */
int main(void) {
pid_t a = fork();
if (a == 0) {
if (fork() == 0) _exit(0); /* B: finishes right away */
_exit(0); /* A: leaves B without a parent */
}
waitpid(a, NULL, 0); /* we only wait for A, never for B */
sleep(1);
execlp("ps", "ps", "-o", "pid,stat,args", (char *)NULL);
return 1;
}
Run it on the old runtime, where the program is process 1 and never reaps the orphan. We borrow the Phase 3 binary and the new image:
sudo ../p3/rt run image orphan
PID STAT COMMAND
1 R ps -o pid,stat,args
3 Z [orphan] <defunct>
The Z in the STAT column marks the zombie. The fix is a tiny init program of our own. rt itself stays as process number 1, starts the command as a child, and waits in a loop for every child that ends, whether it started it or not:
/* Process number 1 must collect the processes that nobody else adopts. */
static int run_as_init(char **cmd) {
pid_t main_pid = fork();
if (main_pid < 0) die("fork");
if (main_pid == 0) {
execvp(cmd[0], cmd);
die(cmd[0]);
}
int main_status = 0;
for (;;) {
int status;
pid_t done = wait(&status);
if (done == main_pid) main_status = status;
if (done < 0 && errno == EINTR) continue;
if (done < 0) break; /* ECHILD: nobody is left */
if (done == main_pid) break;
}
return WIFEXITED(main_status) ? WEXITSTATUS(main_status) : 128 + WTERMSIG(main_status);
}
- The loop ends when
waitreports that nobody is left, or when the main command is the one that ended. The exit status we return is always the main command's. - A
waitthat is interrupted by a signal returnsEINTR, so we try again.
And child_main (Step 4.1) ends with return run_as_init(r->cmd) in place of the old execvp. Rebuild, then run the same program on the new runtime:
sh build.sh
sudo ./rt run image orphan
PID STAT COMMAND
1 S ./rt run image orphan
2 R ps -o pid,stat,args
No zombie. The runtime is process 1, and the command is process 2:
sudo ./rt run image sh -c 'echo "my pid is $$"; ps -e -o pid,args'
my pid is 2
PID COMMAND
1 ./rt run image sh -c echo "my pid is $$"; ps -e -o pid,args
2 sh -c echo "my pid is $$"; ps -e -o pid,args
3 ps -e -o pid,args
One limit of our init: it does not forward signals to the command. Press Ctrl-C in your terminal while a long command runs and see what happens. Small init programs such as tini exist for this job, and Docker can add one for you.
Step 4.4: Put it together (about 30 minutes)
The last piece is the part that parses the command line and starts everything. It has an image instead of a rootfs now, and main creates the scratch directory before clone and removes it after the container ends:
static void usage(const char *prog) {
fprintf(stderr, "usage: %s run [--mem MB] [--cpu SECONDS] IMAGE COMMAND [ARGS...]\n", prog);
exit(2);
}
static void parse_args(int argc, char **argv, struct run *r) {
if (argc < 2 || strcmp(argv[1], "run") != 0) usage(argv[0]);
int i = 2;
while (i < argc && strncmp(argv[i], "--", 2) == 0) {
if (i + 1 >= argc) usage(argv[0]);
if (strcmp(argv[i], "--mem") == 0) r->mem_mb = atol(argv[i + 1]);
else if (strcmp(argv[i], "--cpu") == 0) r->cpu_secs = atol(argv[i + 1]);
else usage(argv[0]);
i += 2;
}
if (argc - i < 2) usage(argv[0]);
r->image = argv[i];
r->cmd = &argv[i + 1];
}
int main(int argc, char **argv) {
struct run r = {0};
parse_args(argc, argv, &r);
make_scratch(&r);
char *stack = malloc(STACK_SIZE);
if (!stack) die("malloc");
int flags = CLONE_NEWUTS | CLONE_NEWPID | CLONE_NEWNS | CLONE_NEWNET | SIGCHLD;
pid_t pid = clone(child_main, stack + STACK_SIZE, flags, &r);
if (pid < 0) die("clone (are you root?)");
int status;
if (waitpid(pid, &status, 0) < 0) die("waitpid");
nftw(r.dir, remove_entry, 16, FTW_DEPTH | FTW_PHYS);
return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
}
Count what you built:
wc -l rt.c
223 rt.c
Now let's check every promise in one go. This script runs a test per property and prints ok or FAIL. Save it as tour.sh next to rt and the image folder:
# Check every promise the runtime makes. Run it as root in the folder that holds rt and image.
check() { # check NAME EXPECTED COMMAND...
name=$1 want=$2
shift 2
got=$("$@" 2>/dev/null)
if [ "$got" = "$want" ]; then echo "ok $name"; else echo "FAIL $name (got: $got)"; fi
}
refused() { # refused NAME COMMAND... (the command must fail)
name=$1
shift
if "$@" >/dev/null 2>&1; then echo "FAIL $name"; else echo "ok $name"; fi
}
check "the hostname is box" box ./rt run image hostname
check "the command is process 2" 2 ./rt run image sh -c 'echo $$'
check "only the loopback device exists" 1 ./rt run image sh -c 'grep -c : /proc/net/dev'
check "capabilities are cut down" 00000000000000eb ./rt run image sh -c 'grep CapEff /proc/self/status | cut -f2'
check "the memory limit holds" "hog: could not get 200 MB" ./rt run --mem 64 image hog 200
check "writes stay in the layer" 0 sh -c './rt run image sh -c "echo x > /root/f"; ls image/root | wc -l'
check "no zombie is left behind" 0 sh -c './rt run image orphan | grep -c Z'
refused "the hostname cannot be changed" ./rt run image hostname other
refused "nothing can be mounted" ./rt run image mount -t tmpfs none /tmp
refused "there is no way out to the network" ./rt run image nettest outside
sudo sh tour.sh
ok the hostname is box
ok the command is process 2
ok only the loopback device exists
ok capabilities are cut down
ok the memory limit holds
ok writes stay in the layer
ok no zombie is left behind
ok the hostname cannot be changed
ok nothing can be mounted
ok there is no way out to the network
Ten lines of ok: a separate hostname and process numbers, a private network with only a loopback, a shrunken set of capabilities, a memory limit that holds, changes that stay in the layer, no zombies, and refusals for the things root could do before.