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

     1  // +build linux
     2  
     3  package ipvlan
     4  
     5  import (
     6  	"fmt"
     7  
     8  	"github.com/docker/docker/libnetwork/driverapi"
     9  	"github.com/docker/docker/libnetwork/netlabel"
    10  	"github.com/docker/docker/libnetwork/ns"
    11  	"github.com/docker/docker/libnetwork/options"
    12  	"github.com/docker/docker/libnetwork/osl"
    13  	"github.com/docker/docker/libnetwork/types"
    14  	"github.com/docker/docker/pkg/parsers/kernel"
    15  	"github.com/docker/docker/pkg/stringid"
    16  	"github.com/sirupsen/logrus"
    17  )
    18  
    19  // CreateNetwork the network for the specified driver type
    20  func (d *driver) CreateNetwork(nid string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
    21  	defer osl.InitOSContext()()
    22  	kv, err := kernel.GetKernelVersion()
    23  	if err != nil {
    24  		return fmt.Errorf("Failed to check kernel version for %s driver support: %v", ipvlanType, err)
    25  	}
    26  	// ensure Kernel version is >= v4.2 for ipvlan support
    27  	if kv.Kernel < ipvlanKernelVer || (kv.Kernel == ipvlanKernelVer && kv.Major < ipvlanMajorVer) {
    28  		return fmt.Errorf("kernel version failed to meet the minimum ipvlan kernel requirement of %d.%d, found %d.%d.%d",
    29  			ipvlanKernelVer, ipvlanMajorVer, kv.Kernel, kv.Major, kv.Minor)
    30  	}
    31  	// reject a null v4 network
    32  	if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" {
    33  		return fmt.Errorf("ipv4 pool is empty")
    34  	}
    35  	// parse and validate the config and bind to networkConfiguration
    36  	config, err := parseNetworkOptions(nid, option)
    37  	if err != nil {
    38  		return err
    39  	}
    40  	config.ID = nid
    41  	err = config.processIPAM(nid, ipV4Data, ipV6Data)
    42  	if err != nil {
    43  		return err
    44  	}
    45  	// verify the ipvlan mode from -o ipvlan_mode option
    46  	switch config.IpvlanMode {
    47  	case "", modeL2:
    48  		// default to ipvlan L2 mode if -o ipvlan_mode is empty
    49  		config.IpvlanMode = modeL2
    50  	case modeL3:
    51  		config.IpvlanMode = modeL3
    52  	default:
    53  		return fmt.Errorf("requested ipvlan mode '%s' is not valid, 'l2' mode is the ipvlan driver default", config.IpvlanMode)
    54  	}
    55  	// loopback is not a valid parent link
    56  	if config.Parent == "lo" {
    57  		return fmt.Errorf("loopback interface is not a valid %s parent link", ipvlanType)
    58  	}
    59  	// if parent interface not specified, create a dummy type link to use named dummy+net_id
    60  	if config.Parent == "" {
    61  		config.Parent = getDummyName(stringid.TruncateID(config.ID))
    62  	}
    63  	foundExisting, err := d.createNetwork(config)
    64  	if err != nil {
    65  		return err
    66  	}
    67  
    68  	if foundExisting {
    69  		return types.InternalMaskableErrorf("restoring existing network %s", config.ID)
    70  	}
    71  	// update persistent db, rollback on fail
    72  	err = d.storeUpdate(config)
    73  	if err != nil {
    74  		d.deleteNetwork(config.ID)
    75  		logrus.Debugf("encountered an error rolling back a network create for %s : %v", config.ID, err)
    76  		return err
    77  	}
    78  
    79  	return nil
    80  }
    81  
    82  // createNetwork is used by new network callbacks and persistent network cache
    83  func (d *driver) createNetwork(config *configuration) (bool, error) {
    84  	foundExisting := false
    85  	networkList := d.getNetworks()
    86  	for _, nw := range networkList {
    87  		if config.Parent == nw.config.Parent {
    88  			if config.ID != nw.config.ID {
    89  				return false, fmt.Errorf("network %s is already using parent interface %s",
    90  					getDummyName(stringid.TruncateID(nw.config.ID)), config.Parent)
    91  			}
    92  			logrus.Debugf("Create Network for the same ID %s\n", config.ID)
    93  			foundExisting = true
    94  			break
    95  		}
    96  	}
    97  	if !parentExists(config.Parent) {
    98  		// Create a dummy link if a dummy name is set for parent
    99  		if dummyName := getDummyName(stringid.TruncateID(config.ID)); dummyName == config.Parent {
   100  			err := createDummyLink(config.Parent, dummyName)
   101  			if err != nil {
   102  				return false, err
   103  			}
   104  			config.CreatedSlaveLink = true
   105  
   106  			// notify the user in logs they have limited communications
   107  			logrus.Debugf("Empty -o parent= flags limit communications to other containers inside of network: %s",
   108  				config.Parent)
   109  		} else {
   110  			// if the subinterface parent_iface.vlan_id checks do not pass, return err.
   111  			//  a valid example is 'eth0.10' for a parent iface 'eth0' with a vlan id '10'
   112  			err := createVlanLink(config.Parent)
   113  			if err != nil {
   114  				return false, err
   115  			}
   116  			// if driver created the networks slave link, record it for future deletion
   117  			config.CreatedSlaveLink = true
   118  		}
   119  	}
   120  	if !foundExisting {
   121  		n := &network{
   122  			id:        config.ID,
   123  			driver:    d,
   124  			endpoints: endpointTable{},
   125  			config:    config,
   126  		}
   127  		// add the network
   128  		d.addNetwork(n)
   129  	}
   130  
   131  	return foundExisting, nil
   132  }
   133  
   134  // DeleteNetwork the network for the specified driver type
   135  func (d *driver) DeleteNetwork(nid string) error {
   136  	defer osl.InitOSContext()()
   137  	n := d.network(nid)
   138  	if n == nil {
   139  		return fmt.Errorf("network id %s not found", nid)
   140  	}
   141  	// if the driver created the slave interface, delete it, otherwise leave it
   142  	if ok := n.config.CreatedSlaveLink; ok {
   143  		// if the interface exists, only delete if it matches iface.vlan or dummy.net_id naming
   144  		if ok := parentExists(n.config.Parent); ok {
   145  			// only delete the link if it is named the net_id
   146  			if n.config.Parent == getDummyName(stringid.TruncateID(nid)) {
   147  				err := delDummyLink(n.config.Parent)
   148  				if err != nil {
   149  					logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v",
   150  						n.config.Parent, err)
   151  				}
   152  			} else {
   153  				// only delete the link if it matches iface.vlan naming
   154  				err := delVlanLink(n.config.Parent)
   155  				if err != nil {
   156  					logrus.Debugf("link %s was not deleted, continuing the delete network operation: %v",
   157  						n.config.Parent, err)
   158  				}
   159  			}
   160  		}
   161  	}
   162  	for _, ep := range n.endpoints {
   163  		if link, err := ns.NlHandle().LinkByName(ep.srcName); err == nil {
   164  			if err := ns.NlHandle().LinkDel(link); err != nil {
   165  				logrus.WithError(err).Warnf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id)
   166  			}
   167  		}
   168  
   169  		if err := d.storeDelete(ep); err != nil {
   170  			logrus.Warnf("Failed to remove ipvlan endpoint %.7s from store: %v", ep.id, err)
   171  		}
   172  	}
   173  	// delete the *network
   174  	d.deleteNetwork(nid)
   175  	// delete the network record from persistent cache
   176  	err := d.storeDelete(n.config)
   177  	if err != nil {
   178  		return fmt.Errorf("error deleting deleting id %s from datastore: %v", nid, err)
   179  	}
   180  	return nil
   181  }
   182  
   183  // parseNetworkOptions parse docker network options
   184  func parseNetworkOptions(id string, option options.Generic) (*configuration, error) {
   185  	var (
   186  		err    error
   187  		config = &configuration{}
   188  	)
   189  	// parse generic labels first
   190  	if genData, ok := option[netlabel.GenericData]; ok && genData != nil {
   191  		if config, err = parseNetworkGenericOptions(genData); err != nil {
   192  			return nil, err
   193  		}
   194  	}
   195  	if val, ok := option[netlabel.Internal]; ok {
   196  		if internal, ok := val.(bool); ok && internal {
   197  			config.Internal = true
   198  		}
   199  	}
   200  	return config, nil
   201  }
   202  
   203  // parseNetworkGenericOptions parse generic driver docker network options
   204  func parseNetworkGenericOptions(data interface{}) (*configuration, error) {
   205  	var (
   206  		err    error
   207  		config *configuration
   208  	)
   209  	switch opt := data.(type) {
   210  	case *configuration:
   211  		config = opt
   212  	case map[string]string:
   213  		config = &configuration{}
   214  		err = config.fromOptions(opt)
   215  	case options.Generic:
   216  		var opaqueConfig interface{}
   217  		if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil {
   218  			config = opaqueConfig.(*configuration)
   219  		}
   220  	default:
   221  		err = types.BadRequestErrorf("unrecognized network configuration format: %v", opt)
   222  	}
   223  	return config, err
   224  }
   225  
   226  // fromOptions binds the generic options to networkConfiguration to cache
   227  func (config *configuration) fromOptions(labels map[string]string) error {
   228  	for label, value := range labels {
   229  		switch label {
   230  		case parentOpt:
   231  			// parse driver option '-o parent'
   232  			config.Parent = value
   233  		case driverModeOpt:
   234  			// parse driver option '-o ipvlan_mode'
   235  			config.IpvlanMode = value
   236  		}
   237  	}
   238  	return nil
   239  }
   240  
   241  // processIPAM parses v4 and v6 IP information and binds it to the network configuration
   242  func (config *configuration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error {
   243  	if len(ipamV4Data) > 0 {
   244  		for _, ipd := range ipamV4Data {
   245  			s := &ipv4Subnet{
   246  				SubnetIP: ipd.Pool.String(),
   247  				GwIP:     ipd.Gateway.String(),
   248  			}
   249  			config.Ipv4Subnets = append(config.Ipv4Subnets, s)
   250  		}
   251  	}
   252  	if len(ipamV6Data) > 0 {
   253  		for _, ipd := range ipamV6Data {
   254  			s := &ipv6Subnet{
   255  				SubnetIP: ipd.Pool.String(),
   256  				GwIP:     ipd.Gateway.String(),
   257  			}
   258  			config.Ipv6Subnets = append(config.Ipv6Subnets, s)
   259  		}
   260  	}
   261  	return nil
   262  }