Redesigned attach/detach

This commit is contained in:
Bryan Boreham committed 2014-09-23 13:01:21 +01:00
1 parent 47310fbfc5
commit d1896e86d0
1 file changed
+51 -22
+51 -22
View File
@@ -103,7 +103,7 @@ stop_masquerading() {
}
# the following borrows from https://github.com/jpetazzo/pipework
find_container_pid() {
container_netns_preamble() {
DOCKERPID=$(docker inspect --format='{{ .State.Pid }}' $1)
[ "$DOCKERPID" = 0 ] && {
echo "Container $1 not running." >&2
@@ -113,20 +113,40 @@ find_container_pid() {
echo "Container $1 unknown to Docker." >&2
exit 1
}
return 0
}
configure_container_networking() {
find_container_pid $1
NSPID=$DOCKERPID
[ ! -d /var/run/netns ] && mkdir -p /var/run/netns
rm -f /var/run/netns/$NSPID
ln -s /proc/$NSPID/ns/net /var/run/netns/$NSPID
EXITCODE=1
LOCAL_IFNAME="v${CONTAINER_IFNAME}pl${NSPID}"
GUEST_IFNAME="v${CONTAINER_IFNAME}pg${NSPID}"
return 0
}
container_netns_cleanup() {
rm -f /var/run/netns/$NSPID
}
# Parameters are container ID, CIDR address
configure_container_networking() {
container_netns_preamble $1
EXITCODE=1
# If veth name already exists then assume we set it up already;
# just add the IP address
if ip link show $LOCAL_IFNAME >/dev/null 2>&1 ; then
if ip netns exec $NSPID ip addr add $2 dev $CONTAINER_IFNAME ; then
EXITCODE=0
else
echo "Failed to attach address $2 to container $1" >&2
fi
container_netns_cleanup
return $EXITCODE
fi
IP_TMPFILE=/tmp/weave_ip_output_$$
rm -f $IP_TMPFILE
if ip link add name $LOCAL_IFNAME mtu $MTU type veth peer name $GUEST_IFNAME mtu $MTU >$IP_TMPFILE 2>&1 ; then
@@ -155,18 +175,33 @@ configure_container_networking() {
fi
rm -f $IP_TMPFILE
rm -f /var/run/netns/$NSPID
container_netns_cleanup
return $EXITCODE
}
takedown_container_networking() {
find_container_pid $1
NSPID=$DOCKERPID
# Parameters are container ID, CIDR address, interface-name
detach() {
container_netns_preamble $1
LOCAL_IFNAME="v${CONTAINER_IFNAME}pl${NSPID}"
EXITCODE=1
if ip netns exec $NSPID ip addr del $2 dev $CONTAINER_IFNAME ; then
# if no inet addresses remain then delete the veth
if [ $(ip netns exec $NSPID ip -f inet addr show dev ethwe | wc -c) -eq 0 ] ; then
if ip link del $LOCAL_IFNAME type veth ; then
EXITCODE=0
else
echo "Failed to delete virtual ethernet device $LOCAL_IFNAME from container $1" >&2
fi
else
EXITCODE=0
fi
else
echo "Failed to detach address $2 from container $1" >&2
fi
ip link del $LOCAL_IFNAME type veth || true
container_netns_cleanup
return $EXITCODE
}
case "$COMMAND" in
@@ -244,18 +279,12 @@ case "$COMMAND" in
;;
attach)
[ $# -gt 1 ] || usage
IPADDR=$1
shift 1
create_bridge
CONTAINER=$1
shift 1
configure_container_networking $CONTAINER $IPADDR $CONTAINER_IFNAME
configure_container_networking $2 $1 $CONTAINER_IFNAME
;;
detach)
[ $# -gt 0 ] || usage
CONTAINER=$1
shift 1
takedown_container_networking $CONTAINER
[ $# -gt 1 ] || usage
detach $2 $1
;;
expose)
[ $# -gt 0 ] || usage