/
add-juju-bridge.py
executable file
·373 lines (296 loc) · 12.4 KB
/
add-juju-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
#!/usr/bin/env python
# Copyright 2015 Canonical Ltd.
# Licensed under the AGPLv3, see LICENCE file for details.
#
# This file has been and should be formatted using pyfmt(1).
#
from __future__ import print_function
import argparse
import os
import re
import shutil
import subprocess
import sys
class SeekableIterator(object):
"""An iterator that supports relative seeking."""
def __init__(self, iterable):
self.iterable = iterable
self.index = 0
def __iter__(self):
return self
def next(self): # Python 2
try:
value = self.iterable[self.index]
self.index += 1
return value
except IndexError:
raise StopIteration
def __next__(self): # Python 3
return self.next()
def seek(self, n, relative=False):
if relative:
self.index += n
else:
self.index = n
if self.index < 0 or self.index >= len(self.iterable):
raise IndexError
class PhysicalInterface(object):
"""Represents a physical ('auto') interface."""
def __init__(self, definition):
self.name = definition.split()[1]
def __str__(self):
return self.name
class LogicalInterface(object):
"""Represents a logical ('iface') interface."""
def __init__(self, definition, options=None):
if not options:
options = []
_, self.name, self.family, self.method = definition.split()
self.options = options
self.is_bonded = [x for x in self.options if "bond-" in x]
self.is_alias = ":" in self.name
self.is_vlan = [x for x in self.options if x.startswith("vlan-raw-device")]
self.is_active = self.method == "dhcp" or self.method == "static"
self.is_bridged = [x for x in self.options if x.startswith("bridge_ports ")]
def __str__(self):
return self.name
# Returns an ordered set of stanzas to bridge this interface.
def bridge(self, prefix, bridge_name, add_auto_stanza):
if bridge_name is None:
bridge_name = prefix + self.name
# Note: the testing order here is significant.
if not self.is_active or self.is_bridged:
return self._bridge_unchanged(add_auto_stanza)
elif self.is_alias:
return self._bridge_alias(add_auto_stanza)
elif self.is_vlan:
return self._bridge_vlan(prefix, bridge_name, add_auto_stanza)
elif self.is_bonded:
return self._bridge_bond(prefix, bridge_name, add_auto_stanza)
else:
return self._bridge_device(prefix, bridge_name)
def _bridge_device(self, prefix, bridge_name):
s1 = IfaceStanza(self.name, self.family, "manual", [])
s2 = AutoStanza(bridge_name)
options = list(self.options)
options.append("bridge_ports {}".format(self.name))
s3 = IfaceStanza(bridge_name, self.family, self.method, options)
return [s1, s2, s3]
def _bridge_vlan(self, prefix, bridge_name, add_auto_stanza):
stanzas = []
s1 = IfaceStanza(self.name, self.family, "manual", self.options)
stanzas.append(s1)
if add_auto_stanza:
stanzas.append(AutoStanza(bridge_name))
options = [x for x in self.options if not x.startswith("vlan")]
options.append("bridge_ports {}".format(self.name))
s3 = IfaceStanza(bridge_name, self.family, self.method, options)
stanzas.append(s3)
return stanzas
def _bridge_alias(self, add_auto_stanza):
stanzas = []
if add_auto_stanza:
stanzas.append(AutoStanza(self.name))
s1 = IfaceStanza(self.name, self.family, self.method, list(self.options))
stanzas.append(s1)
return stanzas
def _bridge_bond(self, prefix, bridge_name, add_auto_stanza):
stanzas = []
if add_auto_stanza:
stanzas.append(AutoStanza(self.name))
s1 = IfaceStanza(self.name, self.family, "manual", list(self.options))
s2 = AutoStanza(bridge_name)
options = [x for x in self.options if not x.startswith("bond")]
options.append("bridge_ports {}".format(self.name))
s3 = IfaceStanza(bridge_name, self.family, self.method, options)
stanzas.extend([s1, s2, s3])
return stanzas
def _bridge_unchanged(self, add_auto_stanza):
stanzas = []
if add_auto_stanza:
stanzas.append(AutoStanza(self.name))
s1 = IfaceStanza(self.name, self.family, self.method, list(self.options))
stanzas.append(s1)
return stanzas
class Stanza(object):
"""Represents one stanza together with all of its options."""
def __init__(self, definition, options=None):
if not options:
options = []
self.definition = definition
self.options = options
self.is_logical_interface = definition.startswith('iface ')
self.is_physical_interface = definition.startswith('auto ')
self.iface = None
self.phy = None
if self.is_logical_interface:
self.iface = LogicalInterface(definition, self.options)
if self.is_physical_interface:
self.phy = PhysicalInterface(definition)
def __str__(self):
return self.definition
class NetworkInterfaceParser(object):
"""Parse a network interface file into a set of stanzas."""
@classmethod
def is_stanza(cls, s):
return re.match(r'^(iface|mapping|auto|allow-|source)', s)
def __init__(self, filename):
self._stanzas = []
with open(filename, 'r') as f:
lines = f.readlines()
line_iterator = SeekableIterator(lines)
for line in line_iterator:
if self.is_stanza(line):
stanza = self._parse_stanza(line, line_iterator)
self._stanzas.append(stanza)
def _parse_stanza(self, stanza_line, iterable):
stanza_options = []
for line in iterable:
line = line.strip()
if line.startswith('#') or line == "":
continue
if self.is_stanza(line):
iterable.seek(-1, True)
break
stanza_options.append(line)
return Stanza(stanza_line.strip(), stanza_options)
def stanzas(self):
return [x for x in self._stanzas]
def physical_interfaces(self):
return {x.phy.name: x.phy for x in [y for y in self._stanzas if y.is_physical_interface]}
def __iter__(self): # class iter
for s in self._stanzas:
yield s
def uniq_append(dst, src):
for x in src:
if x not in dst:
dst.append(x)
return dst
def IfaceStanza(name, family, method, options):
"""Convenience function to create a new "iface" stanza.
Maintains original options order but removes duplicates with the
exception of 'dns-*' options which are normlised as required by
resolvconf(8) and all the dns-* options are moved to the end.
"""
dns_search = []
dns_nameserver = []
dns_sortlist = []
unique_options = []
for o in options:
words = o.split()
ident = words[0]
if ident == "dns-nameservers":
dns_nameserver = uniq_append(dns_nameserver, words[1:])
elif ident == "dns-search":
dns_search = uniq_append(dns_search, words[1:])
elif ident == "dns-sortlist":
dns_sortlist = uniq_append(dns_sortlist, words[1:])
elif o not in unique_options:
unique_options.append(o)
if dns_nameserver:
option = "dns-nameservers " + " ".join(dns_nameserver)
unique_options.append(option)
if dns_search:
option = "dns-search " + " ".join(dns_search)
unique_options.append(option)
if dns_sortlist:
option = "dns-sortlist " + " ".join(dns_sortlist)
unique_options.append(option)
return Stanza("iface {} {} {}".format(name, family, method), unique_options)
def AutoStanza(name):
# Convenience function to create a new "auto" stanza.
return Stanza("auto {}".format(name))
def print_stanza(s, stream=sys.stdout):
print(s.definition, file=stream)
for o in s.options:
print(" ", o, file=stream)
def print_stanzas(stanzas, stream=sys.stdout):
n = len(stanzas)
for i, stanza in enumerate(stanzas):
print_stanza(stanza, stream)
if stanza.is_logical_interface and i + 1 < n:
print(file=stream)
def shell_cmd(s):
p = subprocess.Popen(s, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return [out, err, p.returncode]
def print_shell_cmd(s, verbose=True, exit_on_error=False):
if verbose:
print(s)
out, err, retcode = shell_cmd(s)
if out and len(out) > 0:
print(out.decode().rstrip('\n'))
if err and len(err) > 0:
print(err.decode().rstrip('\n'))
if exit_on_error and retcode != 0:
exit(1)
def check_shell_cmd(s, verbose=False):
if verbose:
print(s)
output = subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).strip().decode("utf-8")
if verbose:
print(output.rstrip('\n'))
return output
def arg_parser():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--bridge-prefix', help="bridge prefix", type=str, required=False, default='br-')
parser.add_argument('--one-time-backup', help='A one time backup of filename', action='store_true', default=True, required=False)
parser.add_argument('--activate', help='activate new configuration', action='store_true', default=False, required=False)
parser.add_argument('--interface-to-bridge', help="interface to bridge", type=str, required=False)
parser.add_argument('--bridge-name', help="bridge name", type=str, required=False)
parser.add_argument('filename', help="interfaces(5) based filename")
return parser
def main(args):
if args.bridge_name and args.interface_to_bridge is None:
sys.stderr.write("error: --interface-to-bridge required when using --bridge-name\n")
exit(1)
if args.interface_to_bridge and args.bridge_name is None:
sys.stderr.write("error: --bridge-name required when using --interface-to-bridge\n")
exit(1)
stanzas = []
config_parser = NetworkInterfaceParser(args.filename)
physical_interfaces = config_parser.physical_interfaces()
# Bridging requires modifying 'auto' and 'iface' stanzas only.
# Calling <iface>.bridge() will return a set of stanzas that cover
# both of those stanzas. The 'elif' clause catches all the other
# stanza types. The args.interface_to_bridge test is to bridge a
# single interface only, which is only used for juju < 2.0. And if
# that argument is specified then args.bridge_name takes
# precendence over any args.bridge_prefix.
for s in config_parser.stanzas():
if s.is_logical_interface:
add_auto_stanza = s.iface.name in physical_interfaces
if args.interface_to_bridge and args.interface_to_bridge != s.iface.name:
if add_auto_stanza:
stanzas.append(AutoStanza(s.iface.name))
stanzas.append(s)
else:
stanzas.extend(s.iface.bridge(args.bridge_prefix, args.bridge_name, add_auto_stanza))
elif not s.is_physical_interface:
stanzas.append(s)
if not args.activate:
print_stanzas(stanzas)
exit(0)
if args.one_time_backup:
backup_file = "{}-before-add-juju-bridge".format(args.filename)
if not os.path.isfile(backup_file):
shutil.copy2(args.filename, backup_file)
ifquery = "$(ifquery --interfaces={} --exclude=lo --list)".format(args.filename)
print("**** Original configuration")
print_shell_cmd("cat {}".format(args.filename))
print_shell_cmd("ifconfig -a")
print_shell_cmd("ifdown --exclude=lo --interfaces={} {}".format(args.filename, ifquery))
print("**** Activating new configuration")
with open(args.filename, 'w') as f:
print_stanzas(stanzas, f)
f.close()
print_shell_cmd("cat {}".format(args.filename))
print_shell_cmd("ifup --exclude=lo --interfaces={} {}".format(args.filename, ifquery))
print_shell_cmd("ip link show up")
print_shell_cmd("ifconfig -a")
print_shell_cmd("ip route show")
print_shell_cmd("brctl show")
# This script re-renders an interfaces(5) file to add a bridge to
# either all active interfaces, or a specific interface.
if __name__ == '__main__':
main(arg_parser().parse_args())