github.com/Heebron/moby@v0.0.0-20221111184709-6eab4f55faf7/libnetwork/drivers/ipvlan/ipvlan_store.go (about)

     1  //go:build linux
     2  // +build linux
     3  
     4  package ipvlan
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"net"
    10  
    11  	"github.com/docker/docker/libnetwork/datastore"
    12  	"github.com/docker/docker/libnetwork/discoverapi"
    13  	"github.com/docker/docker/libnetwork/netlabel"
    14  	"github.com/docker/docker/libnetwork/types"
    15  	"github.com/sirupsen/logrus"
    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.NewDataStoreFromConfig(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(datastore.Key(ipvlanNetworkPrefix), &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  			logrus.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(datastore.Key(ipvlanEndpointPrefix), &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  			logrus.Debugf("Network (%.7s) not found for restored ipvlan endpoint (%.7s)", ep.nid, ep.id)
   105  			logrus.Debugf("Deleting stale ipvlan endpoint (%.7s) from store", ep.id)
   106  			if err := d.storeDelete(ep); err != nil {
   107  				logrus.Debugf("Failed to delete stale ipvlan endpoint (%.7s) from store", ep.id)
   108  			}
   109  			continue
   110  		}
   111  		n.endpoints[ep.id] = ep
   112  		logrus.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  		logrus.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  		logrus.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(datastore.Key(kvObject.Key()...), 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  	config.IpvlanFlag = nMap["IpvlanFlag"].(string)
   192  	config.Internal = nMap["Internal"].(bool)
   193  	config.CreatedSlaveLink = nMap["CreatedSubIface"].(bool)
   194  	if v, ok := nMap["Ipv4Subnets"]; ok {
   195  		if err := json.Unmarshal([]byte(v.(string)), &config.Ipv4Subnets); err != nil {
   196  			return err
   197  		}
   198  	}
   199  	if v, ok := nMap["Ipv6Subnets"]; ok {
   200  		if err := json.Unmarshal([]byte(v.(string)), &config.Ipv6Subnets); err != nil {
   201  			return err
   202  		}
   203  	}
   204  
   205  	return nil
   206  }
   207  
   208  func (config *configuration) Key() []string {
   209  	return []string{ipvlanNetworkPrefix, config.ID}
   210  }
   211  
   212  func (config *configuration) KeyPrefix() []string {
   213  	return []string{ipvlanNetworkPrefix}
   214  }
   215  
   216  func (config *configuration) Value() []byte {
   217  	b, err := json.Marshal(config)
   218  	if err != nil {
   219  		return nil
   220  	}
   221  	return b
   222  }
   223  
   224  func (config *configuration) SetValue(value []byte) error {
   225  	return json.Unmarshal(value, config)
   226  }
   227  
   228  func (config *configuration) Index() uint64 {
   229  	return config.dbIndex
   230  }
   231  
   232  func (config *configuration) SetIndex(index uint64) {
   233  	config.dbIndex = index
   234  	config.dbExists = true
   235  }
   236  
   237  func (config *configuration) Exists() bool {
   238  	return config.dbExists
   239  }
   240  
   241  func (config *configuration) Skip() bool {
   242  	return false
   243  }
   244  
   245  func (config *configuration) New() datastore.KVObject {
   246  	return &configuration{}
   247  }
   248  
   249  func (config *configuration) CopyTo(o datastore.KVObject) error {
   250  	dstNcfg := o.(*configuration)
   251  	*dstNcfg = *config
   252  	return nil
   253  }
   254  
   255  func (config *configuration) DataScope() string {
   256  	return datastore.LocalScope
   257  }
   258  
   259  func (ep *endpoint) MarshalJSON() ([]byte, error) {
   260  	epMap := make(map[string]interface{})
   261  	epMap["id"] = ep.id
   262  	epMap["nid"] = ep.nid
   263  	epMap["SrcName"] = ep.srcName
   264  	if len(ep.mac) != 0 {
   265  		epMap["MacAddress"] = ep.mac.String()
   266  	}
   267  	if ep.addr != nil {
   268  		epMap["Addr"] = ep.addr.String()
   269  	}
   270  	if ep.addrv6 != nil {
   271  		epMap["Addrv6"] = ep.addrv6.String()
   272  	}
   273  	return json.Marshal(epMap)
   274  }
   275  
   276  func (ep *endpoint) UnmarshalJSON(b []byte) error {
   277  	var (
   278  		err   error
   279  		epMap map[string]interface{}
   280  	)
   281  
   282  	if err = json.Unmarshal(b, &epMap); err != nil {
   283  		return fmt.Errorf("Failed to unmarshal to ipvlan endpoint: %v", err)
   284  	}
   285  
   286  	if v, ok := epMap["MacAddress"]; ok {
   287  		if ep.mac, err = net.ParseMAC(v.(string)); err != nil {
   288  			return types.InternalErrorf("failed to decode ipvlan endpoint MAC address (%s) after json unmarshal: %v", v.(string), err)
   289  		}
   290  	}
   291  	if v, ok := epMap["Addr"]; ok {
   292  		if ep.addr, err = types.ParseCIDR(v.(string)); err != nil {
   293  			return types.InternalErrorf("failed to decode ipvlan endpoint IPv4 address (%s) after json unmarshal: %v", v.(string), err)
   294  		}
   295  	}
   296  	if v, ok := epMap["Addrv6"]; ok {
   297  		if ep.addrv6, err = types.ParseCIDR(v.(string)); err != nil {
   298  			return types.InternalErrorf("failed to decode ipvlan endpoint IPv6 address (%s) after json unmarshal: %v", v.(string), err)
   299  		}
   300  	}
   301  	ep.id = epMap["id"].(string)
   302  	ep.nid = epMap["nid"].(string)
   303  	ep.srcName = epMap["SrcName"].(string)
   304  
   305  	return nil
   306  }
   307  
   308  func (ep *endpoint) Key() []string {
   309  	return []string{ipvlanEndpointPrefix, ep.id}
   310  }
   311  
   312  func (ep *endpoint) KeyPrefix() []string {
   313  	return []string{ipvlanEndpointPrefix}
   314  }
   315  
   316  func (ep *endpoint) Value() []byte {
   317  	b, err := json.Marshal(ep)
   318  	if err != nil {
   319  		return nil
   320  	}
   321  	return b
   322  }
   323  
   324  func (ep *endpoint) SetValue(value []byte) error {
   325  	return json.Unmarshal(value, ep)
   326  }
   327  
   328  func (ep *endpoint) Index() uint64 {
   329  	return ep.dbIndex
   330  }
   331  
   332  func (ep *endpoint) SetIndex(index uint64) {
   333  	ep.dbIndex = index
   334  	ep.dbExists = true
   335  }
   336  
   337  func (ep *endpoint) Exists() bool {
   338  	return ep.dbExists
   339  }
   340  
   341  func (ep *endpoint) Skip() bool {
   342  	return false
   343  }
   344  
   345  func (ep *endpoint) New() datastore.KVObject {
   346  	return &endpoint{}
   347  }
   348  
   349  func (ep *endpoint) CopyTo(o datastore.KVObject) error {
   350  	dstEp := o.(*endpoint)
   351  	*dstEp = *ep
   352  	return nil
   353  }
   354  
   355  func (ep *endpoint) DataScope() string {
   356  	return datastore.LocalScope
   357  }