-
-
Notifications
You must be signed in to change notification settings - Fork 244
/
interfaces.py
1389 lines (1239 loc) · 50.4 KB
/
interfaces.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
import errno
import socket
import traceback
from pyroute2 import config
from pyroute2.common import basestring
from pyroute2.common import dqn2int
from pyroute2.common import View
from pyroute2.common import Dotkeys
from pyroute2.netlink import rtnl
from pyroute2.netlink import NLM_F_ACK
from pyroute2.netlink import NLM_F_REQUEST
from pyroute2.netlink.exceptions import NetlinkError
from pyroute2.netlink.rtnl import RTM_NEWLINK
from pyroute2.netlink.rtnl.ifinfmsg import IFF_MASK
from pyroute2.netlink.rtnl.ifinfmsg import ifinfmsg
from pyroute2.ipdb.transactional import Transactional
from pyroute2.ipdb.transactional import with_transaction
from pyroute2.ipdb.transactional import SYNC_TIMEOUT
from pyroute2.ipdb.linkedset import LinkedSet
from pyroute2.ipdb.exceptions import CreateException
from pyroute2.ipdb.exceptions import CommitException
from pyroute2.ipdb.exceptions import PartialCommitException
groups = rtnl.RTNLGRP_LINK |\
rtnl.RTNLGRP_NEIGH |\
rtnl.RTNLGRP_IPV4_IFADDR |\
rtnl.RTNLGRP_IPV6_IFADDR
def _get_data_fields():
ret = []
for data in ('bridge',
'bond',
'tuntap',
'vxlan',
'gre',
'ip6gre',
'macvlan',
'macvtap',
'ipvlan',
'vrf'):
msg = ifinfmsg.ifinfo.data_map[data]
if getattr(msg, 'prefix', None) is not None:
ret += [msg.nla2name(i[0]) for i in msg.nla_map]
else:
ret += [ifinfmsg.nla2name(i[0]) for i in msg.nla_map]
return ret
def _br_time_check(x, y):
return abs(x - y) < 5
class Interface(Transactional):
'''
Objects of this class represent network interface and
all related objects:
* addresses
* (todo) neighbours
* (todo) routes
Interfaces provide transactional model and can act as
context managers. Any attribute change implicitly
starts a transaction. The transaction can be managed
with three methods:
* review() -- review changes
* rollback() -- drop all the changes
* commit() -- try to apply changes
If anything will go wrong during transaction commit,
it will be rolled back authomatically and an
exception will be raised. Failed transaction review
will be attached to the exception.
'''
_fields_cmp = {'flags': lambda x, y: x & y & IFF_MASK == y & IFF_MASK,
'br_hello_time': _br_time_check,
'br_max_age': _br_time_check,
'br_ageing_time': _br_time_check,
'br_forward_delay': _br_time_check,
'br_mcast_membership_intvl': _br_time_check,
'br_mcast_querier_intvl': _br_time_check,
'br_mcast_query_intvl': _br_time_check,
'br_mcast_query_response_intvl': _br_time_check,
'br_mcast_startup_query_intvl': _br_time_check}
_virtual_fields = ['ipdb_scope',
'ipdb_priority',
'vlans',
'ipaddr',
'ports',
'vlan_flags',
'net_ns_fd',
'net_ns_pid']
_fields = [ifinfmsg.nla2name(i[0]) for i in ifinfmsg.nla_map]
for name in ('bridge_data', 'bridge_slave_data'):
data = getattr(ifinfmsg.ifinfo, name)
_fields.extend([ifinfmsg.nla2name(i[0]) for i in data.nla_map])
_fields.append('index')
_fields.append('flags')
_fields.append('mask')
_fields.append('change')
_fields.append('kind')
_fields.append('peer')
_fields.append('vlan_id')
_fields.append('bond_mode')
_fields.extend(_get_data_fields())
_fields.extend(_virtual_fields)
def __init__(self, ipdb, mode=None, parent=None, uid=None):
'''
Parameters:
* ipdb -- ipdb() reference
* mode -- transaction mode
'''
Transactional.__init__(self, ipdb, mode)
self.cleanup = ('header',
'linkinfo',
'protinfo',
'af_spec',
'attrs',
'event',
'map',
'stats',
'stats64',
'change',
'__align')
self.ingress = None
self.egress = None
self.nlmsg = None
self.errors = []
self.partial = False
self._exception = None
self._deferred_link = None
self._tb = None
self._linked_sets.add('ipaddr')
self._linked_sets.add('ports')
self._linked_sets.add('vlans')
self._freeze = None
self._delay_add_port = set()
self._delay_del_port = set()
# 8<-----------------------------------
# local setup: direct state is required
with self._direct_state:
for i in ('change', 'mask'):
del self[i]
self['ipaddr'] = self.ipdb._ipaddr_set()
self['ports'] = LinkedSet()
self['vlans'] = LinkedSet()
self['ipdb_priority'] = 0
# 8<-----------------------------------
def __hash__(self):
return self['index']
@property
def if_master(self):
'''
[property] Link to the parent interface -- if it exists
'''
return self.get('master', None)
def detach(self):
self.ipdb.interfaces._detach(self['ifname'], self['index'], self.nlmsg)
return self
def freeze(self):
if self._freeze is not None:
raise RuntimeError("the interface is frozen already")
dump = self.pick()
def cb(ipdb, msg, action):
if msg.get('index', -1) == dump['index']:
try:
# important: that's a rollback, so do not
# try to revert changes in the case of failure
self.commit(transaction=dump,
commit_phase=2,
commit_mask=2)
except Exception:
pass
self._freeze = self.ipdb.register_callback(cb)
return self
def unfreeze(self):
self.ipdb.unregister_callback(self._freeze)
self._freeze = None
return self
def load(self, data):
'''
Load the data from a dictionary to an existing
transaction. Requires `commit()` call, or must be
called from within a `with` statement.
Sample::
data = json.loads(...)
with ipdb.interfaces['dummy1'] as i:
i.load(data)
Sample, mode `explicit::
data = json.loads(...)
i = ipdb.interfaces['dummy1']
i.begin()
i.load(data)
i.commit()
'''
for key in data:
if key == 'ipaddr':
for addr in self['ipaddr']:
self.del_ip(*addr)
for addr in data[key]:
if isinstance(addr, basestring):
addr = (addr, )
self.add_ip(*addr)
elif key == 'ports':
for port in self['ports']:
self.del_port(port)
for port in data[key]:
self.add_port(port)
elif key == 'vlans':
for vlan in self['vlans']:
self.del_vlan(vlan)
for vlan in data[key]:
self.add_vlan(vlan)
elif key == 'neighbours':
# ignore neighbours on load
pass
else:
self[key] = data[key]
return self
def make_transaction(self, data):
'''
Create a new transaction instance from a dictionary.
One can apply it the with `commit(transaction=...)`
call.
Sample::
data = json.loads(...)
t = ipdb.interfaces['dummy1'].make_transaction(data)
ipdb.interfaces['dummy1'].commit(transaction=t)
'''
with self._write_lock:
template = self.__class__(ipdb=self.ipdb, mode='snapshot')
template.load_dict(data)
return template
def load_dict(self, data):
'''
Update the interface info from a dictionary.
This call always bypasses open transactions, loading
changes directly into the interface data.
'''
with self._direct_state:
self.load(data)
def load_netlink(self, dev):
'''
Update the interface info from RTM_NEWLINK message.
This call always bypasses open transactions, loading
changes directly into the interface data.
'''
with self._direct_state:
if self['ipdb_scope'] == 'locked':
# do not touch locked interfaces
return
if self['ipdb_scope'] in ('shadow', 'create'):
# ignore non-broadcast messages
if dev['header']['sequence_number'] != 0:
return
# ignore ghost RTM_NEWLINK messages
if (config.kernel[0] < 3) and \
(not dev.get_attr('IFLA_AF_SPEC')):
return
for (name, value) in dev.items():
self[name] = value
for cell in dev['attrs']:
#
# Parse on demand
#
# At that moment, being not referenced, the
# NLA is not decoded (yet). Calling
# `__getitem__()` on nla_slot triggers the
# NLA decoding, if the nla is referenced:
#
norm = ifinfmsg.nla2name(cell[0])
if norm not in self.cleanup:
self[norm] = cell[1]
# load interface kind
linkinfo = dev.get_attr('IFLA_LINKINFO')
if linkinfo is not None:
kind = linkinfo.get_attr('IFLA_INFO_KIND')
if kind is not None:
self['kind'] = kind
if kind == 'vlan':
data = linkinfo.get_attr('IFLA_INFO_DATA')
self['vlan_id'] = data.get_attr('IFLA_VLAN_ID')
self['vlan_flags'] = data\
.get_attr('IFLA_VLAN_FLAGS', {})\
.get('flags', 0)
if kind in ('vxlan', 'macvlan', 'macvtap', 'gre',
'gretap', 'ipvlan', 'bridge',
'ip6gre', 'ip6gretap'):
data = linkinfo.get_attr('IFLA_INFO_DATA') or {}
for nla in data.get('attrs', []):
norm = ifinfmsg.nla2name(nla[0])
self[norm] = nla[1]
# load vlans
if dev['family'] == socket.AF_BRIDGE:
spec = dev.get_attr('IFLA_AF_SPEC')
if spec is not None:
vlans = spec.get_attrs('IFLA_BRIDGE_VLAN_INFO')
vmap = {}
for vlan in vlans:
vmap[vlan['vid']] = vlan
vids = set(vmap.keys())
# remove vids we do not have anymore
for vid in (self['vlans'] - vids):
self.del_vlan(vid)
for vid in (vids - self['vlans']):
self.add_vlan(vmap[vid])
protinfo = dev.get_attr('IFLA_PROTINFO')
if protinfo is not None:
for attr, value in protinfo['attrs']:
attr = attr[5:].lower()
self[attr] = value
# the rest is possible only when interface
# is used in IPDB, not standalone
if self.ipdb is not None:
self['ipaddr'] = self.ipdb.ipaddr[self['index']]
self['neighbours'] = self.ipdb.neighbours[self['index']]
# finally, cleanup all not needed
for item in self.cleanup:
if item in self:
del self[item]
# AF_BRIDGE messages for bridges contain
# IFLA_MASTER == self.index, we should fix it
if self.get('master', None) == self['index']:
self['master'] = None
self['ipdb_scope'] = 'system'
def wait_ip(self, *argv, **kwarg):
return self['ipaddr'].wait_ip(*argv, **kwarg)
@with_transaction
def add_ip(self, ip, mask=None, broadcast=None, anycast=None, scope=None):
'''
Add IP address to an interface
Keyword arguments:
* mask
* broadcast
* anycast
* scope
'''
# split mask
if mask is None:
ip, mask = ip.split('/')
if mask.find('.') > -1:
mask = dqn2int(mask)
else:
mask = int(mask, 0)
elif isinstance(mask, basestring):
mask = dqn2int(mask)
# if it is a transaction or an interface update, apply the change
self['ipaddr'].unlink((ip, mask))
request = {}
if broadcast is not None:
request['broadcast'] = broadcast
if anycast is not None:
request['anycast'] = anycast
if scope is not None:
request['scope'] = scope
self['ipaddr'].add((ip, mask), raw=request)
@with_transaction
def del_ip(self, ip, mask=None):
'''
Delete IP address from an interface
'''
if mask is None:
ip, mask = ip.split('/')
if mask.find('.') > -1:
mask = dqn2int(mask)
else:
mask = int(mask, 0)
if (ip, mask) in self['ipaddr']:
self['ipaddr'].unlink((ip, mask))
self['ipaddr'].remove((ip, mask))
@with_transaction
def add_vlan(self, vlan):
if isinstance(vlan, dict):
vid = vlan['vid']
else:
vid = vlan
vlan = {'vid': vlan, 'flags': 0}
self['vlans'].unlink(vid)
self['vlans'].add(vid, raw=vlan)
@with_transaction
def del_vlan(self, vlan):
if vlan in self['vlans']:
self['vlans'].unlink(vlan)
self['vlans'].remove(vlan)
@with_transaction
def add_port(self, port):
'''
Add port to a bridge or bonding
'''
ifindex = self._resolve_port(port)
if not ifindex:
self._delay_add_port.add(port)
else:
self['ports'].unlink(ifindex)
self['ports'].add(ifindex)
@with_transaction
def del_port(self, port):
'''
Remove port from a bridge or bonding
'''
ifindex = self._resolve_port(port)
if not ifindex:
self._delay_del_port.add(port)
else:
self['ports'].unlink(ifindex)
self['ports'].remove(ifindex)
def reload(self):
'''
Reload interface information
'''
countdown = 3
while countdown:
links = self.nl.get_links(self['index'])
if links:
self.load_netlink(links[0])
break
else:
countdown -= 1
time.sleep(1)
return self
def review(self):
ret = super(Interface, self).review()
last = self.current_tx
if self['ipdb_scope'] == 'create':
ret['+ipaddr'] = last['ipaddr']
ret['+ports'] = last['ports']
ret['+vlans'] = last['vlans']
del ret['ports']
del ret['ipaddr']
del ret['vlans']
if last._delay_add_port:
ports = set(['*%s' % x for x in last._delay_add_port])
if '+ports' in ret:
ret['+ports'] |= ports
else:
ret['+ports'] = ports
if last._delay_del_port:
ports = set(['*%s' % x for x in last._delay_del_port])
if '-ports' in ret:
ret['-ports'] |= ports
else:
ret['-ports'] = ports
return ret
def _run(self, cmd, *argv, **kwarg):
try:
return cmd(*argv, **kwarg)
except Exception as error:
if self.partial:
self.errors.append(error)
return []
raise error
def _resolve_port(self, port):
# for now just a stupid resolver, will be
# improved later with search by mac, etc.
if isinstance(port, Interface):
return port['index']
else:
return self.ipdb.interfaces.get(port, {}).get('index', None)
def commit(self,
tid=None,
transaction=None,
commit_phase=1,
commit_mask=0xff,
newif=False):
'''
Commit transaction. In the case of exception all
changes applied during commit will be reverted.
'''
if not commit_phase & commit_mask:
return self
def invalidate():
# on failure, invalidate the interface and detach it
# from the parent
# 0. obtain lock on IPDB, to avoid deadlocks
# ... all the DB updates will wait
with self.ipdb.exclusive:
# 1. drop the IPRoute() link
self.nl = None
# 2. clean up ipdb
self.detach()
# 3. invalidate the interface
with self._direct_state:
for i in tuple(self.keys()):
del self[i]
# 4. the rest
self._mode = 'invalid'
error = None
added = None
removed = None
drop = True
init = None
debug = {'traceback': None,
'transaction': None,
'next_stage': None}
if tid:
transaction = self.global_tx[tid]
else:
if transaction:
drop = False
else:
transaction = self.current_tx
if transaction.partial:
transaction.errors = []
with self._write_lock:
# if the interface does not exist, create it first ;)
if self['ipdb_scope'] != 'system':
# a special case: transition "create" -> "remove"
if transaction['ipdb_scope'] == 'remove' and \
self['ipdb_scope'] == 'create':
self.ipdb.interfaces._detach(self['ifname'], 0)
return self
newif = True
self.set_target('ipdb_scope', 'system')
try:
# 8<---------------------------------------------------
# link resolve
if self._deferred_link:
link_key, link_obj = self._deferred_link
transaction[link_key] = self._resolve_port(link_obj)
self._deferred_link = None
# 8<----------------------------------------------------
# ACHTUNG: hack for old platforms
if self['address'] == '00:00:00:00:00:00':
with self._direct_state:
self['address'] = None
self['broadcast'] = None
# 8<----------------------------------------------------
init = self.pick()
try:
request = {key: transaction[key] for key in
filter(lambda x: x[:3] != 'br_',
transaction)}
for key in ('net_ns_fd', 'net_ns_pid'):
if key in request:
with self._direct_state:
self[key] = None
del request[key]
self.nl.link('add', **request)
except NetlinkError as x:
# File exists
if x.code == errno.EEXIST:
# A bit special case, could be one of two cases:
#
# 1. A race condition between two different IPDB
# processes
# 2. An attempt to create dummy0, gre0, bond0 when
# the corrseponding module is not loaded. Being
# loaded, the module creates a default interface
# by itself, causing the request to fail
#
# The exception in that case can cause the DB
# inconsistence, since there can be queued not only
# the interface creation, but also IP address
# changes etc.
#
# So we ignore this particular exception and try to
# continue, as it is created by us.
#
# 3. An attempt to create VLAN or VXLAN interface
# with the same ID but under different name
#
# In that case we should forward error properly
if self['kind'] in ('vlan', 'vxlan'):
newif = x
else:
raise
except Exception as e:
if transaction.partial:
transaction.errors.append(e)
raise PartialCommitException()
else:
# If link('add', ...) raises an exception, no netlink
# broadcast will be sent, and the object is unmodified.
# After the exception forwarding, the object is ready
# to repeat the commit() call.
raise
if transaction['ipdb_scope'] == 'create' and commit_phase > 1:
if self['index']:
wd = self.ipdb.watchdog(action='RTM_DELLINK',
ifname=self['ifname'])
with self._direct_state:
self['ipdb_scope'] = 'locked'
self.nl.link('delete', index=self['index'])
wd.wait()
self.load_dict(transaction)
return self
elif newif:
# Here we come only if a new interface is created
#
if commit_phase == 1 and not self.wait_target('ipdb_scope'):
invalidate()
if isinstance(newif, Exception):
raise newif
else:
raise CreateException()
# Re-populate transaction.ipaddr to have a proper IP target
#
# The reason behind the code is that a new interface in the
# "up" state will have automatic IPv6 addresses, that aren't
# reflected in the transaction. This may cause a false IP
# target mismatch and a commit failure.
#
# To avoid that, collect automatic addresses to the
# transaction manually, since it is not yet properly linked.
#
for addr in self.ipdb.ipaddr[self['index']]:
transaction['ipaddr'].add(addr)
# now we have our index and IP set and all other stuff
snapshot = self.pick()
# resolve all delayed ports
def resolve_ports(transaction, ports, callback, self, drop):
def error(x):
return KeyError('can not resolve port %s' % x)
for port in tuple(ports):
ifindex = self._resolve_port(port)
if not ifindex:
if transaction.partial:
transaction.errors.append(error(port))
else:
if drop:
self.drop(transaction.uid)
raise error(port)
else:
ports.remove(port)
with transaction._direct_state: # ????
callback(ifindex)
resolve_ports(transaction,
transaction._delay_add_port,
transaction.add_port,
self, drop)
resolve_ports(transaction,
transaction._delay_del_port,
transaction.del_port,
self, drop)
try:
removed, added = snapshot // transaction
run = transaction._run
nl = transaction.nl
# 8<---------------------------------------------
# Port vlans
if removed['vlans'] or added['vlans']:
if added['vlans']:
transaction['vlans'].add(1)
self['vlans'].set_target(transaction['vlans'])
for i in removed['vlans']:
if i != 1:
# remove vlan from the port
run(nl.vlan_filter, 'del',
index=self['index'],
vlan_info=self['vlans'][i])
for i in added['vlans']:
if i != 1:
# add vlan to the port
run(nl.vlan_filter, 'add',
index=self['index'],
vlan_info=transaction['vlans'][i])
self['vlans'].target.wait(SYNC_TIMEOUT)
if not self['vlans'].target.is_set():
raise CommitException('vlans target is not set')
# 8<---------------------------------------------
# Ports
if removed['ports'] or added['ports']:
self['ports'].set_target(transaction['ports'])
for i in removed['ports']:
# detach port
if i in self.ipdb.interfaces:
(self.ipdb.interfaces[i]
.set_target('master', None)
.mirror_target('master', 'link'))
run(nl.link, 'set', index=i, master=0)
else:
transaction.errors.append(KeyError(i))
for i in added['ports']:
# attach port
if i in self.ipdb.interfaces:
(self.ipdb.interfaces[i]
.set_target('master', self['index'])
.mirror_target('master', 'link'))
run(nl.link, 'set', index=i, master=self['index'])
else:
transaction.errors.append(KeyError(i))
self['ports'].target.wait(SYNC_TIMEOUT)
if not self['ports'].target.is_set():
raise CommitException('ports target is not set')
# 1. wait for proper targets on ports
# 2. wait for mtu sync
#
# the bridge mtu is set from the port, if the latter is smaller
# the bond mtu sets the port mtu, if the latter is smaller
#
# FIXME: team interfaces?
for i in list(added['ports']) + list(removed['ports']):
port = self.ipdb.interfaces[i]
# port update
target = port._local_targets['master']
target.wait(SYNC_TIMEOUT)
with port._write_lock:
del port._local_targets['master']
del port._local_targets['link']
if not target.is_set():
raise CommitException('master target failed')
if i in added['ports']:
if port.if_master != self['index']:
raise CommitException('master set failed')
else:
if port.if_master == self['index']:
raise CommitException('master unset failed')
# master update
if self['kind'] == 'bridge' and self['mtu'] > port['mtu']:
self.set_target('mtu', port['mtu'])
self.wait_target('mtu')
# 8<---------------------------------------------
# Interface changes
request = {}
brequest = {}
prequest = {}
# preseed requests with the interface kind
request['kind'] = self['kind']
brequest['kind'] = self['kind']
wait_all = False
for key in added:
if (key not in self._virtual_fields) and (key != 'kind'):
if key[:3] == 'br_':
brequest[key] = added[key]
elif key[:7] == 'brport_':
prequest[key[7:]] = added[key]
else:
request[key] = added[key]
# FIXME: flush the interface type so the next two conditions
# will work correctly
request['kind'] = None
brequest['kind'] = None
# apply changes only if there is something to apply
if (self['kind'] == 'bridge') and \
any([brequest[item] is not None for item in brequest]):
brequest['index'] = self['index']
brequest['kind'] = self['kind']
brequest['family'] = socket.AF_BRIDGE
wait_all = True
run(nl.link, (RTM_NEWLINK, NLM_F_REQUEST | NLM_F_ACK),
**brequest)
if any([request[item] is not None for item in request]):
request['index'] = self['index']
request['kind'] = self['kind']
if request.get('address', None) == '00:00:00:00:00:00':
request.pop('address')
request.pop('broadcast', None)
wait_all = True
run(nl.link, 'set', **request)
# Yet another trick: setting ifalias doesn't cause
# netlink updates
if 'ifalias' in request:
self.reload()
if any([prequest[item] is not None for item in prequest]):
prequest['index'] = self['index']
run(nl.brport, "set", **prequest)
if (wait_all) and (not transaction.partial):
transaction.wait_all_targets()
# 8<---------------------------------------------
# VLAN flags -- a dirty hack, pls do something with it
if added.get('vlan_flags') is not None:
run(nl.link,
(RTM_NEWLINK, NLM_F_REQUEST | NLM_F_ACK),
**{'kind': 'vlan',
'index': self['index'],
'vlan_flags': added['vlan_flags']})
# 8<---------------------------------------------
# IP address changes
for _ in range(3):
ip2add = transaction['ipaddr'] - self['ipaddr']
ip2remove = self['ipaddr'] - transaction['ipaddr']
if not ip2add and not ip2remove:
break
self['ipaddr'].set_target(transaction['ipaddr'])
###
# Remove
#
# The promote_secondaries sysctl causes the kernel
# to add secondary addresses back after the primary
# address is removed.
#
# The library can not tell this from the result of
# an external program.
#
# One simple way to work that around is to remove
# secondaries first.
rip = sorted(ip2remove,
key=lambda x: self['ipaddr'][x]['flags'],
reverse=True)
# 8<--------------------------------------
for i in rip:
# When you remove a primary IP addr, all the
# subnetwork can be removed. In this case you
# will fail, but it is OK, no need to roll back
try:
run(nl.addr, 'delete', self['index'], i[0], i[1])
except NetlinkError as x:
# bypass only errno 99,
# 'Cannot assign address'
if x.code != errno.EADDRNOTAVAIL:
raise
except socket.error as x:
# bypass illegal IP requests
if isinstance(x.args[0], basestring) and \
x.args[0].startswith('illegal IP'):
continue
raise
###
# Add addresses
# 8<--------------------------------------
for i in ip2add:
# Try to fetch additional address attributes
try:
kwarg = dict([k for k
in transaction['ipaddr'][i].items()
if k[0] in ('broadcast',
'anycast',
'scope')])
except KeyError:
kwarg = None
try:
# feed the address to the OS
run(nl.addr, 'add', self['index'], i[0], i[1],
**kwarg if kwarg else {})
except NetlinkError as x:
if x.code != errno.EEXIST:
raise
# 8<--------------------------------------
# some interfaces do not send IPv6 address
# updates, when are down
#
# beside of that, bridge interfaces are
# down by default, so they never send
# address updates from beginning
#
# FIXME:
#
# that all is a dirtiest hack ever, pls do
# something with it
#
if (not self['flags'] & 1) or hasattr(self.ipdb.nl, 'netns'):
# 1. flush old IPv6 addresses
for addr in list(self['ipaddr'].ipv6):
self['ipaddr'].remove(addr)
# 2. reload addresses
for addr in self.nl.get_addr(index=self['index'],
family=socket.AF_INET6):
self.ipdb.ipaddr._new(addr)
# if there are tons of IPv6 addresses, it may take a
# really long time, and that's bad, but it's broken in
# the kernel :|
# 8<--------------------------------------
self['ipaddr'].target.wait(SYNC_TIMEOUT)
if self['ipaddr'].target.is_set():
break
else:
raise CommitException('ipaddr target is not set')
# 8<---------------------------------------------
# Iterate callback chain
for ch in self._commit_hooks:
# An exception will rollback the transaction
ch(self.dump(), snapshot.dump(), transaction.dump())
# 8<---------------------------------------------
# Move the interface to a netns
if ('net_ns_fd' in added) or ('net_ns_pid' in added):
request = {}
for key in ('net_ns_fd', 'net_ns_pid'):
if key in added:
request[key] = added[key]
request['index'] = self['index']
run(nl.link, 'set', **request)
countdown = 10
while countdown:
# wait until the interface will disappear
# from the current network namespace --
# up to 1 second (make it configurable?)
try:
self.nl.get_links(self['index'])
except NetlinkError as e:
if e.code == errno.ENODEV:
break
raise
except Exception:
raise
countdown -= 1
time.sleep(0.1)
# 8<---------------------------------------------
# Interface removal
if added.get('ipdb_scope') in ('shadow', 'remove'):
wd = self.ipdb.watchdog(action='RTM_DELLINK',
ifname=self['ifname'])
with self._direct_state:
self['ipdb_scope'] = 'locked'
self.nl.link('delete', index=self['index'])
wd.wait()
with self._direct_state:
self['ipdb_scope'] = 'shadow'
# system-wide checks
if commit_phase == 1:
self.ipdb.ensure('run')
if added.get('ipdb_scope') == 'remove':
self.ipdb.interfaces._detach(None, self['index'], None)
if drop:
self.drop(transaction.uid)
return self
# 8<---------------------------------------------
# system-wide checks
if commit_phase == 1:
self.ipdb.ensure('run')