-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathbridge.py
491 lines (367 loc) · 11.2 KB
/
bridge.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
# -*- coding: utf-8 -*-
'''
Module for gathering and managing bridging information
'''
from __future__ import absolute_import, print_function, unicode_literals
import sys
import re
import salt.utils.path
__func_alias__ = {
'list_': 'list'
}
# Other BSD-like derivatives that use ifconfig may work too
SUPPORTED_BSD_LIKE = ['FreeBSD', 'NetBSD', 'OpenBSD']
def __virtual__():
'''
Confirm this module is supported by the OS and the system has
required tools
'''
supported_os_tool = {
'FreeBSD': 'ifconfig',
'Linux': 'brctl',
'NetBSD': 'brconfig',
'OpenBSD': 'ifconfig'
}
cur_os = __grains__.get('kernel')
for _os in supported_os_tool:
if cur_os == _os and salt.utils.path.which(supported_os_tool[cur_os]):
return True
return (False, 'The bridge execution module failed to load: requires one of the following tool/os'
' combinations: ifconfig on FreeBSD/OpenBSD, brctl on Linux or brconfig on NetBSD.')
def _tool_path(ostool):
'''
Internal, returns tools path
'''
return salt.utils.path.which(ostool)
def _linux_brshow(br=None):
'''
Internal, returns bridges and enslaved interfaces (GNU/Linux - brctl)
'''
brctl = _tool_path('brctl')
if br:
cmd = '{0} show {1}'.format(brctl, br)
else:
cmd = '{0} show'.format(brctl)
brs = {}
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
# get rid of first line
if line.startswith('bridge name'):
continue
# get rid of ^\n's
vals = line.split()
if not vals:
continue
# bridge name bridge id STP enabled interfaces
# br0 8000.e4115bac8ddc no eth0
# foo0
# br1 8000.e4115bac8ddc no eth1
if len(vals) > 1:
brname = vals[0]
brs[brname] = {
'id': vals[1],
'stp': vals[2],
}
if len(vals) > 3:
brs[brname]['interfaces'] = [vals[3]]
if len(vals) == 1 and brname:
brs[brname]['interfaces'].append(vals[0])
if br:
try:
return brs[br]
except KeyError:
return None
return brs
def _linux_bradd(br):
'''
Internal, creates the bridge
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} addbr {1}'.format(brctl, br),
python_shell=False)
def _linux_brdel(br):
'''
Internal, deletes the bridge
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} delbr {1}'.format(brctl, br),
python_shell=False)
def _linux_addif(br, iface):
'''
Internal, adds an interface to a bridge
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} addif {1} {2}'.format(brctl, br, iface),
python_shell=False)
def _linux_delif(br, iface):
'''
Internal, removes an interface from a bridge
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} delif {1} {2}'.format(brctl, br, iface),
python_shell=False)
def _linux_stp(br, state):
'''
Internal, sets STP state
'''
brctl = _tool_path('brctl')
return __salt__['cmd.run']('{0} stp {1} {2}'.format(brctl, br, state),
python_shell=False)
def _bsd_brshow(br=None):
'''
Internal, returns bridges and member interfaces (BSD-like: ifconfig)
'''
if __grains__['kernel'] == 'NetBSD':
return _netbsd_brshow(br)
ifconfig = _tool_path('ifconfig')
ifaces = {}
if br:
ifaces[br] = br
else:
cmd = '{0} -g bridge'.format(ifconfig)
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
ifaces[line] = line
brs = {}
for iface in ifaces:
cmd = '{0} {1}'.format(ifconfig, iface)
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
brs[iface] = {
'interfaces': [],
'stp': 'no'
}
line = line.lstrip()
if line.startswith('member:'):
brs[iface]['interfaces'].append(line.split(' ')[1])
if 'STP' in line:
brs[iface]['stp'] = 'yes'
if br:
return brs[br]
return brs
def _netbsd_brshow(br=None):
'''
Internal, returns bridges and enslaved interfaces (NetBSD - brconfig)
'''
brconfig = _tool_path('brconfig')
if br:
cmd = '{0} {1}'.format(brconfig, br)
else:
cmd = '{0} -a'.format(brconfig)
brs = {}
start_int = False
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
if line.startswith('bridge'):
start_int = False
brname = line.split(':')[0] # on NetBSD, always ^bridge([0-9]+):
brs[brname] = {
'interfaces': [],
'stp': 'no'
}
if 'Interfaces:' in line:
start_int = True
continue
if start_int and brname:
m = re.match(r'\s*([a-z0-9]+)\s.*<.*>', line)
if m:
brs[brname]['interfaces'].append(m.group(1))
if 'STP' in line:
brs[brname]['stp'] = 'yes'
if br:
try:
return brs[br]
except KeyError:
return None
return brs
def _bsd_bradd(br):
'''
Internal, creates the bridge
'''
kernel = __grains__['kernel']
ifconfig = _tool_path('ifconfig')
if not br:
return False
if __salt__['cmd.retcode']('{0} {1} create up'.format(ifconfig, br),
python_shell=False) != 0:
return False
# NetBSD is two cmds
if kernel == 'NetBSD':
brconfig = _tool_path('brconfig')
if __salt__['cmd.retcode']('{0} {1} up'.format(brconfig, br),
python_shell=False) != 0:
return False
return True
def _bsd_brdel(br):
'''
Internal, deletes the bridge
'''
ifconfig = _tool_path('ifconfig')
if not br:
return False
return __salt__['cmd.run']('{0} {1} destroy'.format(ifconfig, br),
python_shell=False)
def _bsd_addif(br, iface):
'''
Internal, adds an interface to a bridge
'''
kernel = __grains__['kernel']
if kernel == 'NetBSD':
cmd = _tool_path('brconfig')
brcmd = 'add'
else:
cmd = _tool_path('ifconfig')
brcmd = 'addem'
if not br or not iface:
return False
return __salt__['cmd.run']('{0} {1} {2} {3}'.format(cmd, br, brcmd, iface),
python_shell=False)
def _bsd_delif(br, iface):
'''
Internal, removes an interface from a bridge
'''
kernel = __grains__['kernel']
if kernel == 'NetBSD':
cmd = _tool_path('brconfig')
brcmd = 'delete'
else:
cmd = _tool_path('ifconfig')
brcmd = 'deletem'
if not br or not iface:
return False
return __salt__['cmd.run']('{0} {1} {2} {3}'.format(cmd, br, brcmd, iface),
python_shell=False)
def _bsd_stp(br, state, iface):
'''
Internal, sets STP state. On BSD-like, it is required to specify the
STP physical interface
'''
kernel = __grains__['kernel']
if kernel == 'NetBSD':
cmd = _tool_path('brconfig')
else:
cmd = _tool_path('ifconfig')
if not br or not iface:
return False
return __salt__['cmd.run']('{0} {1} {2} {3}'.format(cmd, br, state, iface),
python_shell=False)
def _os_dispatch(func, *args, **kwargs):
'''
Internal, dispatches functions by operating system
'''
if __grains__['kernel'] in SUPPORTED_BSD_LIKE:
kernel = 'bsd'
else:
kernel = __grains__['kernel'].lower()
_os_func = getattr(sys.modules[__name__], '_{0}_{1}'.format(kernel, func))
if callable(_os_func):
return _os_func(*args, **kwargs)
# End of internal functions
def show(br=None):
'''
Returns bridges interfaces along with enslaved physical interfaces. If
no interface is given, all bridges are shown, else only the specified
bridge values are returned.
CLI Example:
.. code-block:: bash
salt '*' bridge.show
salt '*' bridge.show br0
'''
return _os_dispatch('brshow', br)
def list_():
'''
Returns the machine's bridges list
CLI Example:
.. code-block:: bash
salt '*' bridge.list
'''
brs = _os_dispatch('brshow')
if not brs:
return None
brlist = []
for br in brs:
brlist.append(br)
return brlist
def interfaces(br=None):
'''
Returns interfaces attached to a bridge
CLI Example:
.. code-block:: bash
salt '*' bridge.interfaces br0
'''
if not br:
return None
br_ret = _os_dispatch('brshow', br)
if br_ret:
return br_ret['interfaces']
def find_interfaces(*args):
'''
Returns the bridge to which the interfaces are bond to
CLI Example:
.. code-block:: bash
salt '*' bridge.find_interfaces eth0 [eth1...]
'''
brs = _os_dispatch('brshow')
if not brs:
return None
iflist = {}
for iface in args:
for br in brs:
try: # a bridge may not contain interfaces
if iface in brs[br]['interfaces']:
iflist[iface] = br
except Exception:
pass
return iflist
def add(br=None):
'''
Creates a bridge
CLI Example:
.. code-block:: bash
salt '*' bridge.add br0
'''
return _os_dispatch('bradd', br)
def delete(br=None):
'''
Deletes a bridge
CLI Example:
.. code-block:: bash
salt '*' bridge.delete br0
'''
return _os_dispatch('brdel', br)
def addif(br=None, iface=None):
'''
Adds an interface to a bridge
CLI Example:
.. code-block:: bash
salt '*' bridge.addif br0 eth0
'''
return _os_dispatch('addif', br, iface)
def delif(br=None, iface=None):
'''
Removes an interface from a bridge
CLI Example:
.. code-block:: bash
salt '*' bridge.delif br0 eth0
'''
return _os_dispatch('delif', br, iface)
def stp(br=None, state='disable', iface=None):
'''
Sets Spanning Tree Protocol state for a bridge
CLI Example:
.. code-block:: bash
salt '*' bridge.stp br0 enable
salt '*' bridge.stp br0 disable
For BSD-like operating systems, it is required to add the interface on
which to enable the STP.
CLI Example:
.. code-block:: bash
salt '*' bridge.stp bridge0 enable fxp0
salt '*' bridge.stp bridge0 disable fxp0
'''
kernel = __grains__['kernel']
if kernel == 'Linux':
states = {'enable': 'on', 'disable': 'off'}
return _os_dispatch('stp', br, states[state])
elif kernel in SUPPORTED_BSD_LIKE:
states = {'enable': 'stp', 'disable': '-stp'}
return _os_dispatch('stp', br, states[state], iface)
else:
return False
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4