github.com/rawahars/moby@v24.0.4+incompatible/libnetwork/drivers/bridge/link.go (about)

     1  //go:build linux
     2  // +build linux
     3  
     4  package bridge
     5  
     6  import (
     7  	"fmt"
     8  	"net"
     9  
    10  	"github.com/docker/docker/libnetwork/iptables"
    11  	"github.com/docker/docker/libnetwork/types"
    12  	"github.com/sirupsen/logrus"
    13  )
    14  
    15  type link struct {
    16  	parentIP string
    17  	childIP  string
    18  	ports    []types.TransportPort
    19  	bridge   string
    20  }
    21  
    22  func (l *link) String() string {
    23  	return fmt.Sprintf("%s <-> %s [%v] on %s", l.parentIP, l.childIP, l.ports, l.bridge)
    24  }
    25  
    26  func newLink(parentIP, childIP string, ports []types.TransportPort, bridge string) *link {
    27  	return &link{
    28  		childIP:  childIP,
    29  		parentIP: parentIP,
    30  		ports:    ports,
    31  		bridge:   bridge,
    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  }