infrapuzzle/k8s/troubleshoot/delete_duplicate_iptables.sh

46 lines
2.1 KiB
Bash
Executable File

#!/bin/bash
IPTABLES_SAVE="$( iptables-save 2> /dev/null )"
KUBECTL_ALL_PODS=$( kubectl get pods --all-namespaces -o wide | sed "s/ */ /g" )
# find all rules for "CNI-HOSTPORT-DNAT"
CHAINS_CNI_HOSTPORT_DNAT=$( echo "$IPTABLES_SAVE" | grep -e "^-A CNI-HOSTPORT-DNAT" )
echo "$CHAINS_CNI_HOSTPORT_DNAT" | while read chain || [[ -n $chain ]];
do
# find all targets
TARGET=$( echo $chain | cut -d " " -f 18 )
echo "$TARGET" | while read target || [[ -n $target ]];
do
# search for all the targets and just use the one containing "--to-destination"
ALL_DESTINATION_RULES=$( echo "$IPTABLES_SAVE" | grep -e "^-A $target")
TO_DESTINATION_RULE=$( echo "$IPTABLES_SAVE" | grep -e "^-A $target.*--to-destination" )
echo "$TO_DESTINATION_RULE" | while read rule || [[ -n $rule ]];
do
echo "rule: $rule"
HOST_PORTS=$( echo "$rule" | cut -d " " -f 8 | tr ',' ' ' )
TO_DESTINATION_RULE_ADDRESS_PORT=$( echo "$rule" | cut -d " " -f 12)
CONTAINER_ADDRESS=$( echo "$TO_DESTINATION_RULE_ADDRESS_PORT" | cut -d ":" -f 1 )
CONTAINER_PORT=$( echo "$TO_DESTINATION_RULE_ADDRESS_PORT" | cut -d ":" -f 2 )
echo "hostport: $HOST_PORT container address: $CONTAINER_ADDRESS port: $CONTAINER_PORT"
# check whether there is a pod with that address
POD=$( echo "$KUBECTL_ALL_PODS" | grep $CONTAINER_ADDRESS | cut -d " " -f 2 )
NAMESPACE=$( echo "$KUBECTL_ALL_PODS" | grep $CONTAINER_ADDRESS | cut -d " " -f 1 )
POD_COUNT=$( echo "$POD" | wc -c )
if [[ "$POD_COUNT" == "1" ]]
then
echo "#No pod found for address $CONTAINER_ADDRESS deleting iptables rules"
echo "$ALL_DESTINATION_RULES" | while read deleteRule || [[ -n $deleteRule ]];
do
echo "iptables -t nat -D ${deleteRule#-A }"
#iptables -t nat -D "${to_delete_rule#-A }"
done
echo "iptables -t nat -D ${chain#-A }"
#iptables -t nat -D ${chain#-A }
else
echo "The pod $POD actually exists in namespace $NAMESPACE"
fi
done
done
done
#k get pod nginx -n troubleshoot -o jsonpath="{$.spec.containers[*].ports[*].containerPort}"