Last active
February 1, 2018 21:29
-
-
Save Apsu/7947a3347fcc86bb45a7 to your computer and use it in GitHub Desktop.
Find and fix veth pairs that aren't connected to LXC containers anymore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Create associative arrays | |
declare -A interior=() | |
declare -A exterior=() | |
# Make sure ethtool is installed on this host | |
apt-get install -y ethtool | |
# For each container | |
for container in $(lxc-ls) | |
do | |
# For each list of ifindex:ifname pairs | |
for items in $(awk -F': ' '{print $1 ":" $2}' < <(lxc-attach -n $container -- ip -o l | sort -n | tail -n+2)) | |
do | |
# For each ifindex:ifname pairs | |
for item in "${items[@]}" | |
do | |
# Split into ifindex and ifname | |
index=$(echo $item | awk -F':' '{print $1}') | |
name=$(echo $item | awk -F':' '{print $2}') | |
# Add entry keyed on ifindex => ifname and container name | |
interior+=([$index]="$name $container") | |
done | |
done | |
done | |
# For each ifindex:ifname pair | |
for item in $(ip -o l | grep veth | awk -F': ' '{print $1 ":" $2}') | |
do | |
# Split into ifindex and ifname | |
index=$(echo $item | awk -F':' '{print $1}') | |
name=$(echo $item | awk -F':' '{print $2}') | |
# Extract peer ifindex from ethtool | |
peer=$(ethtool -S $name | awk '/peer_ifindex/ {print $2}') | |
# Add entry keyed on interior peer's ifindex => ifname | |
exterior+=([$peer]=$name) | |
done | |
# For each peer (interior) ifindex | |
for peer in "${!exterior[@]}" | |
do | |
# Store exterior ifname for this veth pair | |
extname=${exterior[$peer]} | |
# If this peer ifindex was also found inside the container | |
if [[ -n ${interior[$peer]} ]] | |
then | |
# Split out values into ifname and container name | |
items=(${interior[$peer]}) | |
name="${items[0]}" | |
container="${items[1]}" | |
echo "Found peer for interface $extname => $peer:$name in $container" | |
# Otherwise the exterior veth is dangling; delete it! | |
else | |
# This section redirects to stderr only | |
# You can filter just for them with: $script 1>/dev/null | |
echo "Peer $peer for interface $extname not in a container!" >&2 | |
echo "======= Deleting $extname =======" >&2 | |
ip link del $extname >&2 | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment