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/daedalus/root
43 [ -e $CONFIG ] || cat <<EOF > "$CONFIG"
44 # Subhost $NAME is an autogenerated overlay subhost with shared filesystem
50 # generate a mac for given $1 (interface) using the last 5 characters
52 local M="$(xxd -p <<< "${1:$(( ${#1} - 5)):5}")66666666"
53 echo "0a:${M:0:2}:${M:2:2}:${M:4:2}:${M:6:2}:${M:8:2}"
56 # setup the subhost network namespace and link up the host side
60 for BRIDGE in ${BRIDGES[@]} ; do
61 brctl show $BRIDGE >& /dev/null || brctl addbr $BRIDGE
64 ip link add $IF type veth peer name eth$E address $MAC netns $NSNAME
66 [ -n "$BRIDGE" ] && brctl addif $BRIDGE $IF
71 # check if $1 is mounted
73 grep -qE "^[^ ]+ $1 " /proc/mounts
76 # Setup or re-setup the subhost filesystem
78 if is_mounted $TARGET ; then
79 mount -oremount $TARGET
81 if [ -f "$IMAGE" ] ; then
82 # The subhost has an image file with /root and /work in it
83 is_mounted $MOUNT || mount $IMAGE $MOUNT || exit 1
87 if [ -z "$OSROOT" ] ; then
89 mount --rbind $UPPER $TARGET
91 # overlay of $UPPER (+$WORK) over $OSROOT onto $TARGET
92 mount -t overlay $NAME \
93 -olowerdir=$OSROOT,upperdir=$UPPER,workdir=$WORK \
101 [ -e "/run/netns/$NSNAME" ] || setup_network
102 [ -d "$MOUNT" ] || create_subhost
105 [ -x $TARGET/startup ] && START=/startup
106 exec ip netns exec $NSNAME unshare \
107 --fork --pid --mount-proc --kill-child \
108 --uts --ipc --mount --cgroup \
109 "--root=$TARGET" $START
113 [ -e $IMAGE ] && umount $MOUNT