ipmasq.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  6. "github.com/coreos/flannel/pkg/ip"
  7. )
  8. func setupIPMasq(ipn ip.IP4Net) error {
  9. ipt, err := ip.NewIPTables()
  10. if err != nil {
  11. return fmt.Errorf("failed to setup IP Masquerade. iptables was not found")
  12. }
  13. err = ipt.ClearChain("nat", "FLANNEL")
  14. if err != nil {
  15. return fmt.Errorf("Failed to create/clear FLANNEL chain in NAT table: %v", err)
  16. }
  17. rules := [][]string{
  18. // This rule makes sure we don't NAT traffic within overlay network (e.g. coming out of docker0)
  19. {"FLANNEL", "-d", ipn.String(), "-j", "ACCEPT"},
  20. // NAT if it's not multicast traffic
  21. {"FLANNEL", "!", "-d", "224.0.0.0/4", "-j", "MASQUERADE"},
  22. // This rule will take everything coming from overlay and sent it to FLANNEL chain
  23. {"POSTROUTING", "-s", ipn.String(), "-j", "FLANNEL"},
  24. }
  25. for _, args := range rules {
  26. log.Info("Adding iptables rule: ", strings.Join(args, " "))
  27. err = ipt.AppendUnique("nat", args...)
  28. if err != nil {
  29. return fmt.Errorf("Failed to insert IP masquerade rule: %v", err)
  30. }
  31. }
  32. return nil
  33. }