bug fix
[rrq/overlay-boot.git] / overlay-boot
1 #!/bin/sh
2 #
3 # This boot method runs a service subhost with a root filesystem that
4 # is an overlay of the subhost's root and an OS root. The service
5 # subhost is defined by a configuration file named on teh command line
6
7 OVERLAYDIR="$(dirname $(realpath $0))"
8
9 [ $(id -u) = 0 ] || exec sudo $0 $@
10 . $OVERLAYDIR/functions $*
11
12 CONFIG="$1"
13 [ -r "$CONFIG" ] || die "Missing configuration $CONFIG"
14
15 config NAME $(basename $1 .${1##*.})
16 config LOG /tmp/oly-$NAME.log
17
18 if [ -z "$UNSHARED" ] ; then
19     # Pre-unsharing:
20     #
21     # Create the network namespace for the subhost, then trigger
22     # detached re-run with unshared mount namespace
23     [ -r /run/netns/$NAME ] || {
24         ip netns add $NAME
25         ip netns exec $NAME ip link set lo up
26     }
27     exec env UNSHARED=yes unshare -m $0 $@ > $LOG 2>&1 &
28     echo "Logging to $LOG" >&2
29     exit 0
30 fi
31
32 config BASE
33 BASE="$(cd $(dirname $CONFIG); realpath $BASE)"
34
35 [ -z "$BASE" ] && die "BASE is unset; bogus $CONFIG ?"
36 [ -d "$BASE" ] || die "$BASE is not a directory; bogus $CONFIG ?"
37 cd "$BASE" || die "$BASE is inaccessible"
38
39 config LIVE "$BASE/live"
40 config UPPER "$BASE/root"
41 config WORK "$BASE/work"
42 config LOWER "/"
43 config CABLES ""
44 config START "networking ssh"
45 config SUBSHELL /bin/sh
46
47 # Setup virtual cabling
48 setup_veth_cables $NAME $CABLES
49
50 # Set up the mount for this subhost, including a new tmpfs on its /run
51 # and a default $UPPER/etc/network/interfaces if needed
52 echo setup_overlay "$NAME" "$LIVE" "$LOWER" "$UPPER" "$WORK"
53 setup_overlay "$NAME" "$LIVE" "$LOWER" "$UPPER" "$WORK"
54
55 exithandler() {
56     ip netns del $NAME
57     [ "$LOWER" != "$LIVE" ] && umount -R "$LIVE"
58     [ -f "${UPPER%% *}" ] && [ -x "${UPPER%% *}" ] && \
59         env ACTION=teardown $UPPER
60 }
61 trap "exithandler" 0
62
63 CMD="unshare -fp --mount-proc -i -u ip netns exec $NAME chroot $LIVE /bin/sh"
64 echo "$CMD"
65
66 config RAM_SIZE 50M
67
68 cat <<EOF | $CMD
69 set -x
70 mount -t proc proc /proc
71 mount -t devpts devpts /dev/pts
72 mount -t sysfs sysfs /sys
73 if [ "$RAM_SIZE" != "none" ] && ! grep -q '/run tmpfs' /proc/mounts ; then
74     mount -t tmpfs -osize=$RAM_SIZE,mode=755 tmpfs /run
75 fi
76 for srv in $START ; do service \$srv start ; done
77 dummy_service() {
78     [ \$# -gt 3 ] && return 0
79     echo "Starting dummy service" >&2
80     set +x
81     [ -p /run/dummy_service ] || mkfifo /run/dummy_service
82     ( printf dummy_service > /proc/self/comm ; read X < /run/dummy_service ) &
83     set -x
84 }
85 dummy_service /proc/*/comm
86 exec /.reaper $NAME
87 EOF
88 echo "EXITED $CMD"