github.com/jfrazelle/docker@v1.1.2-0.20210712172922-bf78e25fe508/libnetwork/iptables/conntrack.go (about) 1 // +build linux 2 3 package iptables 4 5 import ( 6 "errors" 7 "net" 8 "syscall" 9 10 "github.com/sirupsen/logrus" 11 "github.com/vishvananda/netlink" 12 ) 13 14 var ( 15 // ErrConntrackNotConfigurable means that conntrack module is not loaded or does not have the netlink module loaded 16 ErrConntrackNotConfigurable = errors.New("conntrack is not available") 17 ) 18 19 // IsConntrackProgrammable returns true if the handle supports the NETLINK_NETFILTER and the base modules are loaded 20 func IsConntrackProgrammable(nlh *netlink.Handle) bool { 21 return nlh.SupportsNetlinkFamily(syscall.NETLINK_NETFILTER) 22 } 23 24 // DeleteConntrackEntries deletes all the conntrack connections on the host for the specified IP 25 // Returns the number of flows deleted for IPv4, IPv6 else error 26 func DeleteConntrackEntries(nlh *netlink.Handle, ipv4List []net.IP, ipv6List []net.IP) (uint, uint, error) { 27 if !IsConntrackProgrammable(nlh) { 28 return 0, 0, ErrConntrackNotConfigurable 29 } 30 31 var totalIPv4FlowPurged uint 32 for _, ipAddress := range ipv4List { 33 flowPurged, err := purgeConntrackState(nlh, syscall.AF_INET, ipAddress) 34 if err != nil { 35 logrus.Warnf("Failed to delete conntrack state for %s: %v", ipAddress, err) 36 continue 37 } 38 totalIPv4FlowPurged += flowPurged 39 } 40 41 var totalIPv6FlowPurged uint 42 for _, ipAddress := range ipv6List { 43 flowPurged, err := purgeConntrackState(nlh, syscall.AF_INET6, ipAddress) 44 if err != nil { 45 logrus.Warnf("Failed to delete conntrack state for %s: %v", ipAddress, err) 46 continue 47 } 48 totalIPv6FlowPurged += flowPurged 49 } 50 51 logrus.Debugf("DeleteConntrackEntries purged ipv4:%d, ipv6:%d", totalIPv4FlowPurged, totalIPv6FlowPurged) 52 return totalIPv4FlowPurged, totalIPv6FlowPurged, nil 53 } 54 55 func purgeConntrackState(nlh *netlink.Handle, family netlink.InetFamily, ipAddress net.IP) (uint, error) { 56 filter := &netlink.ConntrackFilter{} 57 // NOTE: doing the flush using the ipAddress is safe because today there cannot be multiple networks with the same subnet 58 // so it will not be possible to flush flows that are of other containers 59 if err := filter.AddIP(netlink.ConntrackNatAnyIP, ipAddress); err != nil { 60 return 0, err 61 } 62 return nlh.ConntrackDeleteFilter(netlink.ConntrackTable, family, filter) 63 }