3 # Control program for bespoke arbitrary services through unshared sub-hosts
5 # $1 = the command: start or stop
6 # $2 = the sub-host to start or stop
7 # $3... = the optional chroot-ed command (/startup by default)
17 echo "$SCRIPT (start|stop) <subhost>" >&2
21 [ -z "$NAME" ] && usage
23 : ${SUBHOST=/opt/subhost}
25 : ${TOP=$SUBHOST/$NAME}
27 : ${IMAGE=$TOP/$NAME.img}
33 : ${CONFIG=$TOP/config}
35 [ -e "$CONFIG" ] && . "$CONFIG"
37 cd "$SUBHOST" || exit 1
39 # Create a simple overlay subhost without its own image file
41 mkdir -p $TARGET $MOUNT $UPPER $WORK
42 [ -d "$OSROOT" ] || OSROOT=$SUBHOST/chimaera/base
43 [ -e $CONFIG ] || cat <<EOF > "$CONFIG"
44 # Subhost $NAME is an autogenerated overlay subhost with shared filesystem
50 # map a string into a hexadecimal number with 10-digits by folding the given string into 9-digit ascii-code numbers and adding them
53 V="$(b2sum -l 40 <<< "$1" | sed 's/\(..\)/\1:/g')"
57 # Generate a mac address for given interface by passing hostname,
58 # subhost name and interface through 40-bit b2sum and with 02: prefix.
60 local V="$(b2sum -l 40 <<< "$(hostname)$NAME$1" | sed 's/\(..\)/\1:/g')"
64 # setup the subhost network namespace and link up the host side
68 for BRIDGE in ${BRIDGES[@]} ; do
69 brctl show $BRIDGE >& /dev/null || brctl addbr $BRIDGE
72 ip link add $IF type veth peer name eth$E address $MAC netns $NSNAME
74 [ -n "$BRIDGE" ] && brctl addif $BRIDGE $IF
79 # check if $1 is mounted
81 grep -qE "^[^ ]+ $1 " /proc/mounts
84 # Setup or re-setup the subhost filesystem
86 if is_mounted $TARGET ; then
87 mount -oremount $TARGET
89 if [ -e "$IMAGE" ] ; then
90 # $IMAGE is either an image file or a link to a partition,
91 # with /root and /work in it.
92 is_mounted $MOUNT || mount $IMAGE $MOUNT || exit 1
96 if [ -z "$OSROOT" ] ; then
98 mount --rbind $UPPER $TARGET
100 # overlay of $UPPER (+$WORK) over $OSROOT onto $TARGET
101 mount -t overlay $NAME \
102 -olowerdir=$OSROOT,upperdir=$UPPER,workdir=$WORK \
110 [ -e "/run/netns/$NSNAME" ] || setup_network
111 [ -d "$MOUNT" ] || create_subhost
114 [ -x $TARGET/startup ] && START=/startup
115 exec ip netns exec $NSNAME unshare \
116 --fork --pid --mount-proc --kill-child \
117 --uts --ipc --mount --cgroup \
118 chroot $TARGET $START
122 [ -e $IMAGE ] && umount $MOUNT