test-env.sh 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/bin/bash
  2. ENVNAME=$1
  3. LAST_OCTET=$2
  4. HASH=$(echo $ENVNAME | md5sum | head -c 6)
  5. IP_OCTET_3=$(printf "%d" 0x$(echo $HASH | head -c 2))
  6. IP_OCTET_4=$(printf "%d" 0x$(echo $HASH | tail -c 2))
  7. IP_ADDR=10.0.$IP_OCTET_3.$IP_OCTET_4
  8. # create root ns holder
  9. touch .fleck-lock
  10. mkdir -p .fleck-ns
  11. flock -Fn .fleck-lock -c 'exec unshare -mrnU sh -c "echo $$ > .fleck-lock; rm .fleck-ns/netns/*; mount --bind .fleck-ns /run; exec sleep infinity"' &
  12. sleep .1
  13. ROOT_PID=$(cat .fleck-lock)
  14. nsenter --preserve-credentials -U -m -n -t $ROOT_PID bash -x <<ROOT_NS
  15. # do initial setup?
  16. grep fleck-br <(ip link list) > /dev/null || (
  17. ip link set lo up
  18. ip link add name fleck-br type bridge
  19. ip link set dev fleck-br up
  20. )
  21. # set up namespace?
  22. grep ^$ENVNAME$ <(ip netns list | awk '{print \$1}') > /dev/null || (
  23. ip netns add $ENVNAME > /dev/null
  24. ip link add $ENVNAME-root type veth peer name $ENVNAME-inner netns $ENVNAME
  25. ip link set $ENVNAME-root up
  26. ip link set $ENVNAME-root master fleck-br
  27. ip netns exec $ENVNAME ip link set up lo
  28. ip netns exec $ENVNAME ip link set up $ENVNAME-inner
  29. ip netns exec $ENVNAME ip addr add $IP_ADDR/16 dev $ENVNAME-inner
  30. ip netns exec $ENVNAME ip route add 224.0.0.0/4 dev $ENVNAME-inner
  31. )
  32. ROOT_NS
  33. # give a shell
  34. exec nsenter -w --preserve-credentials -U -m -n -t $ROOT_PID bash -i -c "DEBIAN_CHROOT=$ENVNAME ip netns exec $ENVNAME unshare --map-user=1024 $SHELL"