github.com/rish1988/moby@v25.0.2+incompatible/libnetwork/drivers/ipvlan/ipvlan_store.go (about)

     1  //go:build linux
     2  
     3  package ipvlan
     4  
     5  import (
     6  	"context"
     7  	"encoding/json"
     8  	"fmt"
     9  	"net"
    10  
    11  	"github.com/containerd/log"
    12  	"github.com/docker/docker/libnetwork/datastore"
    13  	"github.com/docker/docker/libnetwork/discoverapi"
    14  	"github.com/docker/docker/libnetwork/netlabel"
    15  	"github.com/docker/docker/libnetwork/types"
    16  )
    17  
    18  const (
    19  	ipvlanPrefix         = "ipvlan"
    20  	ipvlanNetworkPrefix  = ipvlanPrefix + "/network"
    21  	ipvlanEndpointPrefix = ipvlanPrefix + "/endpoint"
    22  )
    23  
    24  // networkConfiguration for this driver's network specific configuration
    25  type configuration struct {
    26  	ID               string
    27  	Mtu              int
    28  	dbIndex          uint64
    29  	dbExists         bool
    30  	Internal         bool
    31  	Parent           string
    32  	IpvlanMode       string
    33  	IpvlanFlag       string
    34  	CreatedSlaveLink bool
    35  	Ipv4Subnets      []*ipSubnet
    36  	Ipv6Subnets      []*ipSubnet
    37  }
    38  
    39  type ipSubnet struct {
    40  	SubnetIP string
    41  	GwIP     string
    42  }
    43  
    44  // initStore drivers are responsible for caching their own persistent state
    45  func (d *driver) initStore(option map[string]interface{}) error {
    46  	if data, ok := option[netlabel.LocalKVClient]; ok {
    47  		var err error
    48  		dsc, ok := data.(discoverapi.DatastoreConfigData)
    49  		if !ok {
    50  			return types.InternalErrorf("incorrect data in datastore configuration: %v", data)
    51  		}
    52  		d.store, err = datastore.FromConfig(dsc)
    53  		if err != nil {
    54  			return types.InternalErrorf("ipvlan driver failed to initialize data store: %v", err)
    55  		}
    56  
    57  		err = d.populateNetworks()
    58  		if err != nil {
    59  			return err
    60  		}
    61  		err = d.populateEndpoints()
    62  		if err != nil {
    63  			return err
    64  		}
    65  	}
    66  
    67  	return nil
    68  }
    69  
    70  // populateNetworks is invoked at driver init to recreate persistently stored networks
    71  func (d *driver) populateNetworks() error {
    72  	kvol, err := d.store.List(&configuration{})
    73  	if err != nil && err != datastore.ErrKeyNotFound {
    74  		return fmt.Errorf("failed to get ipvlan network configurations from store: %v", err)
    75  	}
    76  	// If empty it simply means no ipvlan networks have been created yet
    77  	if err == datastore.ErrKeyNotFound {
    78  		return nil
    79  	}
    80  	for _, kvo := range kvol {
    81  		config := kvo.(*configuration)
    82  		if _, err = d.createNetwork(config); err != nil {
    83  			log.G(context.TODO()).Warnf("could not create ipvlan network for id %s from persistent state", config.ID)
    84  		}
    85  	}
    86  
    87  	return nil
    88  }
    89  
    90  func (d *driver) populateEndpoints() error {
    91  	kvol, err := d.store.List(&endpoint{})
    92  	if err != nil && err != datastore.ErrKeyNotFound {
    93  		return fmt.Errorf("failed to get ipvlan endpoints from store: %v", err)
    94  	}
    95  
    96  	if err == datastore.ErrKeyNotFound {
    97  		return nil
    98  	}
    99  
   100  	for _, kvo := range kvol {
   101  		ep := kvo.(*endpoint)
   102  		n, ok := d.networks[ep.nid]
   103  		if !ok {
   104  			log.G(context.TODO()).Debugf("Network (%.7s) not found for restored ipvlan endpoint (%.7s)", ep.nid, ep.id)
   105  			log.G(context.TODO()).Debugf("Deleting stale ipvlan endpoint (%.7s) from store", ep.id)
   106  			if err := d.storeDelete(ep); err != nil {
   107  				log.G(context.TODO()).Debugf("Failed to delete stale ipvlan endpoint (%.7s) from store", ep.id)
   108  			}
   109  			continue
   110  		}
   111  		n.endpoints[ep.id] = ep
   112  		log.G(context.TODO()).Debugf("Endpoint (%.7s) restored to network (%.7s)", ep.id, ep.nid)
   113  	}
   114  
   115  	return nil
   116  }
   117  
   118  // storeUpdate used to update persistent ipvlan network records as they are created
   119  func (d *driver) storeUpdate(kvObject datastore.KVObject) error {
   120  	if d.store == nil {
   121  		log.G(context.TODO()).Warnf("ipvlan store not initialized. kv object %s is not added to the store", datastore.Key(kvObject.Key()...))
   122  		return nil
   123  	}
   124  	if err := d.store.PutObjectAtomic(kvObject); err != nil {
   125  		return fmt.Errorf("failed to update ipvlan store for object type %T: %v", kvObject, err)
   126  	}
   127  
   128  	return nil
   129  }
   130  
   131  // storeDelete used to delete ipvlan network records from persistent cache as they are deleted
   132  func (d *driver) storeDelete(kvObject datastore.KVObject) error {
   133  	if d.store == nil {
   134  		log.G(context.TODO()).Debugf("ipvlan store not initialized. kv object %s is not deleted from store", datastore.Key(kvObject.Key()...))
   135  		return nil
   136  	}
   137  retry:
   138  	if err := d.store.DeleteObjectAtomic(kvObject); err != nil {
   139  		if err == datastore.ErrKeyModified {
   140  			if err := d.store.GetObject(kvObject); err != nil {
   141  				return fmt.Errorf("could not update the kvobject to latest when trying to delete: %v", err)
   142  			}
   143  			goto retry
   144  		}
   145  		return err
   146  	}
   147  
   148  	return nil
   149  }
   150  
   151  func (config *configuration) MarshalJSON() ([]byte, error) {
   152  	nMap := make(map[string]interface{})
   153  	nMap["ID"] = config.ID
   154  	nMap["Mtu"] = config.Mtu
   155  	nMap["Parent"] = config.Parent
   156  	nMap["IpvlanMode"] = config.IpvlanMode
   157  	nMap["IpvlanFlag"] = config.IpvlanFlag
   158  	nMap["Internal"] = config.Internal
   159  	nMap["CreatedSubIface"] = config.CreatedSlaveLink
   160  	if len(config.Ipv4Subnets) > 0 {
   161  		iis, err := json.Marshal(config.Ipv4Subnets)
   162  		if err != nil {
   163  			return nil, err
   164  		}
   165  		nMap["Ipv4Subnets"] = string(iis)
   166  	}
   167  	if len(config.Ipv6Subnets) > 0 {
   168  		iis, err := json.Marshal(config.Ipv6Subnets)
   169  		if err != nil {
   170  			return nil, err
   171  		}
   172  		nMap["Ipv6Subnets"] = string(iis)
   173  	}
   174  
   175  	return json.Marshal(nMap)
   176  }
   177  
   178  func (config *configuration) UnmarshalJSON(b []byte) error {
   179  	var (
   180  		err  error
   181  		nMap map[string]interface{}
   182  	)
   183  
   184  	if err = json.Unmarshal(b, &nMap); err != nil {
   185  		return err
   186  	}
   187  	config.ID = nMap["ID"].(string)
   188  	config.Mtu = int(nMap["Mtu"].(float64))
   189  	config.Parent = nMap["Parent"].(string)
   190  	config.IpvlanMode = nMap["IpvlanMode"].(string)
   191  	if v, ok := nMap["IpvlanFlag"]; ok {
   192  		config.IpvlanFlag = v.(string)
   193  	} else {
   194  		// Migrate config from an older daemon which did not have the flag configurable.
   195  		config.IpvlanFlag = flagBridge
   196  	}
   197  	config.Internal = nMap["Internal"].(bool)
   198  	config.CreatedSlaveLink = nMap["CreatedSubIface"].(bool)
   199  	if v, ok := nMap["Ipv4Subnets"]; ok {
   200  		if err := json.Unmarshal([]byte(v.(string)), &config.Ipv4Subnets); err != nil {
   201  			return err
   202  		}
   203  	}
   204  	if v, ok := nMap["Ipv6Subnets"]; ok {
   205  		if err := json.Unmarshal([]byte(v.(string)), &config.Ipv6Subnets); err != nil {
   206  			return err
   207  		}
   208  	}
   209  
   210  	return nil
   211  }
   212  
   213  func (config *configuration) Key() []string {
   214  	return []string{ipvlanNetworkPrefix, config.ID}
   215  }
   216  
   217  func (config *configuration) KeyPrefix() []string {
   218  	return []string{ipvlanNetworkPrefix}
   219  }
   220  
   221  func (config *configuration) Value() []byte {
   222  	b, err := json.Marshal(config)
   223  	if err != nil {
   224  		return nil
   225  	}
   226  	return b
   227  }
   228  
   229  func (config *configuration) SetValue(value []byte) error {
   230  	return json.Unmarshal(value, config)
   231  }
   232  
   233  func (config *configuration) Index() uint64 {
   234  	return config.dbIndex
   235  }
   236  
   237  func (config *configuration) SetIndex(index uint64) {
   238  	config.dbIndex = index
   239  	config.dbExists = true
   240  }
   241  
   242  func (config *configuration) Exists() bool {
   243  	return config.dbExists
   244  }
   245  
   246  func (config *configuration) Skip() bool {
   247  	return false
   248  }
   249  
   250  func (config *configuration) New() datastore.KVObject {
   251  	return &configuration{}
   252  }
   253  
   254  func (config *configuration) CopyTo(o datastore.KVObject) error {
   255  	dstNcfg := o.(*configuration)
   256  	*dstNcfg = *config
   257  	return nil
   258  }
   259  
   260  func (ep *endpoint) MarshalJSON() ([]byte, error) {
   261  	epMap := make(map[string]interface{})
   262  	epMap["id"] = ep.id
   263  	epMap["nid"] = ep.nid
   264  	epMap["SrcName"] = ep.srcName
   265  	if len(ep.mac) != 0 {
   266  		epMap["MacAddress"] = ep.mac.String()
   267  	}
   268  	if ep.addr != nil {
   269  		epMap["Addr"] = ep.addr.String()
   270  	}
   271  	if ep.addrv6 != nil {
   272  		epMap["Addrv6"] = ep.addrv6.String()
   273  	}
   274  	return json.Marshal(epMap)
   275  }
   276  
   277  func (ep *endpoint) UnmarshalJSON(b []byte) error {
   278  	var (
   279  		err   error
   280  		epMap map[string]interface{}
   281  	)
   282  
   283  	if err = json.Unmarshal(b, &epMap); err != nil {
   284  		return fmt.Errorf("Failed to unmarshal to ipvlan endpoint: %v", err)
   285  	}
   286  
   287  	if v, ok := epMap["MacAddress"]; ok {
   288  		if ep.mac, err = net.ParseMAC(v.(string)); err != nil {
   289  			return types.InternalErrorf("failed to decode ipvlan endpoint MAC address (%s) after json unmarshal: %v", v.(string), err)
   290  		}
   291  	}
   292  	if v, ok := epMap["Addr"]; ok {
   293  		if ep.addr, err = types.ParseCIDR(v.(string)); err != nil {
   294  			return types.InternalErrorf("failed to decode ipvlan endpoint IPv4 address (%s) after json unmarshal: %v", v.(string), err)
   295  		}
   296  	}
   297  	if v, ok := epMap["Addrv6"]; ok {
   298  		if ep.addrv6, err = types.ParseCIDR(v.(string)); err != nil {
   299  			return types.InternalErrorf("failed to decode ipvlan endpoint IPv6 address (%s) after json unmarshal: %v", v.(string), err)
   300  		}
   301  	}
   302  	ep.id = epMap["id"].(string)
   303  	ep.nid = epMap["nid"].(string)
   304  	ep.srcName = epMap["SrcName"].(string)
   305  
   306  	return nil
   307  }
   308  
   309  func (ep *endpoint) Key() []string {
   310  	return []string{ipvlanEndpointPrefix, ep.id}
   311  }
   312  
   313  func (ep *endpoint) KeyPrefix() []string {
   314  	return []string{ipvlanEndpointPrefix}
   315  }
   316  
   317  func (ep *endpoint) Value() []byte {
   318  	b, err := json.Marshal(ep)
   319  	if err != nil {
   320  		return nil
   321  	}
   322  	return b
   323  }
   324  
   325  func (ep *endpoint) SetValue(value []byte) error {
   326  	return json.Unmarshal(value, ep)
   327  }
   328  
   329  func (ep *endpoint) Index() uint64 {
   330  	return ep.dbIndex
   331  }
   332  
   333  func (ep *endpoint) SetIndex(index uint64) {
   334  	ep.dbIndex = index
   335  	ep.dbExists = true
   336  }
   337  
   338  func (ep *endpoint) Exists() bool {
   339  	return ep.dbExists
   340  }
   341  
   342  func (ep *endpoint) Skip() bool {
   343  	return false
   344  }
   345  
   346  func (ep *endpoint) New() datastore.KVObject {
   347  	return &endpoint{}
   348  }
   349  
   350  func (ep *endpoint) CopyTo(o datastore.KVObject) error {
   351  	dstEp := o.(*endpoint)
   352  	*dstEp = *ep
   353  	return nil
   354  }