iptables-wrapper 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. #!/bin/sh
  2. # Copyright 2019 The Kubernetes Authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. set -e
  16. # Detect whether the base system is using iptables-legacy or
  17. # iptables-nft. This assumes that some non-containerized process (eg
  18. # kubelet) has already created some iptables rules.
  19. # Bugs in iptables-nft 1.8.3 may cause it to get stuck in a loop in
  20. # some circumstances, so we have to run the nft check in a timeout. To
  21. # avoid hitting that timeout, we only bother to even check nft if
  22. # legacy iptables was empty / mostly empty.
  23. num_legacy_lines=$( (iptables-legacy-save || true; ip6tables-legacy-save || true) 2>/dev/null | grep '^-' | wc -l)
  24. if [ "${num_legacy_lines}" -ge 10 ]; then
  25. mode=legacy
  26. else
  27. num_nft_lines=$( (timeout 5 sh -c "iptables-nft-save; ip6tables-nft-save" || true) 2>/dev/null | grep '^-' | wc -l)
  28. if [ "${num_legacy_lines}" -ge "${num_nft_lines}" ]; then
  29. mode=legacy
  30. else
  31. mode=nft
  32. fi
  33. fi
  34. update-alternatives --set iptables "/usr/sbin/iptables-${mode}" > /dev/null
  35. update-alternatives --set ip6tables "/usr/sbin/ip6tables-${mode}" > /dev/null
  36. # Now re-exec the original command with the newly-selected alternative
  37. exec "$0" "$@"