github.com/jfrazelle/docker@v1.1.2-0.20210712172922-bf78e25fe508/libnetwork/drivers/bridge/link.go (about)

     1  // +build linux
     2  
     3  package bridge
     4  
     5  import (
     6  	"fmt"
     7  	"net"
     8  
     9  	"github.com/docker/docker/libnetwork/iptables"
    10  	"github.com/docker/docker/libnetwork/types"
    11  	"github.com/sirupsen/logrus"
    12  )
    13  
    14  type link struct {
    15  	parentIP string
    16  	childIP  string
    17  	ports    []types.TransportPort
    18  	bridge   string
    19  }
    20  
    21  func (l *link) String() string {
    22  	return fmt.Sprintf("%s <-> %s [%v] on %s", l.parentIP, l.childIP, l.ports, l.bridge)
    23  }
    24  
    25  func newLink(parentIP, childIP string, ports []types.TransportPort, bridge string) *link {
    26  	return &link{
    27  		childIP:  childIP,
    28  		parentIP: parentIP,
    29  		ports:    ports,
    30  		bridge:   bridge,
    31  	}
    32  
    33  }
    34  
    35  func (l *link) Enable() error {
    36  	// -A == iptables append flag
    37  	linkFunction := func() error {
    38  		return linkContainers("-A", l.parentIP, l.childIP, l.ports, l.bridge, false)
    39  	}
    40  
    41  	iptables.OnReloaded(func() { linkFunction() })
    42  	return linkFunction()
    43  }
    44  
    45  func (l *link) Disable() {
    46  	// -D == iptables delete flag
    47  	err := linkContainers("-D", l.parentIP, l.childIP, l.ports, l.bridge, true)
    48  	if err != nil {
    49  		logrus.Errorf("Error removing IPTables rules for a link %s due to %s", l.String(), err.Error())
    50  	}
    51  	// Return proper error once we move to use a proper iptables package
    52  	// that returns typed errors
    53  }
    54  
    55  func linkContainers(action, parentIP, childIP string, ports []types.TransportPort, bridge string,
    56  	ignoreErrors bool) error {
    57  	var nfAction iptables.Action
    58  
    59  	switch action {
    60  	case "-A":
    61  		nfAction = iptables.Append
    62  	case "-I":
    63  		nfAction = iptables.Insert
    64  	case "-D":
    65  		nfAction = iptables.Delete
    66  	default:
    67  		return InvalidIPTablesCfgError(action)
    68  	}
    69  
    70  	ip1 := net.ParseIP(parentIP)
    71  	if ip1 == nil {
    72  		return InvalidLinkIPAddrError(parentIP)
    73  	}
    74  	ip2 := net.ParseIP(childIP)
    75  	if ip2 == nil {
    76  		return InvalidLinkIPAddrError(childIP)
    77  	}
    78  
    79  	chain := iptables.ChainInfo{Name: DockerChain}
    80  	for _, port := range ports {
    81  		err := chain.Link(nfAction, ip1, ip2, int(port.Port), port.Proto.String(), bridge)
    82  		if !ignoreErrors && err != nil {
    83  			return err
    84  		}
    85  	}
    86  	return nil
    87  }