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