summaryrefslogtreecommitdiffstats
path: root/func/minion/modules/bridge.py
blob: 12998f2a08958abfe44305b98e4b1e6c3e3d83f5 (plain)
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
#
# Copyright 2008, Stone-IT
# Jasper Capel <capel@stone-it.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301  USA

import func_module
import os, re

class Bridge(func_module.FuncModule):
    version = "0.0.2"
    api_version = "0.0.2"
    description = "Func module for Bridge management"

    # A list of bridge names that should be ignored. You can use this if you
    # have bridges that should never be touched by func.
    # This should go the the module-specific configuration file in the future.
    # Will ignore virbr0 by default, as it's managed by libvirtd, it's probably
    # a bad idea to touch it.
    ignorebridges = [ "virbr0" ]
    brctl = "/usr/sbin/brctl"
    ip = "/sbin/ip"
    ifup = "/sbin/ifup"
    ifdown = "/sbin/ifdown"

    def list(self, listvif=True):
        # Returns a dictionary. Elements look like this:
        # key: bridgename, value: [ interface1, interface2, ..., interfacen ]
        # If listvif is provided as a parameter and set to false, the xen-style
        # virtual interfaces (vifX.Y) will be omitted from the listing.

        retlist = {}

        command = self.brctl + " show"

        fp = os.popen(command)

        vifpattern = re.compile('vif[0-9]+\.[0-9]+')

        # Read output, discard the first line (header):
        # Example output:
        # bridge name   bridge id       STP enabled interfaces
        # mgmtbr        8000.feffffffffff   no      vif12.0
        #                                           vif11.0
        # netsbr        8000.feffffffffff   no      pbond1
        #                                           vif0.2

        lines = fp.readlines()[1:]
        fp.close()

        curbr = ""
        for line in lines:
            elements = line.split()

            if len(elements) > 1:
                # Line containing a new bridge name + interface
                curbr = elements[0]
                if not curbr in self.ignorebridges:
                    if len(elements) == 3:
                        # This is a bridge without connected devices
                        retlist[elements[0]] = [ ]
                    elif len(elements) == 4:
                        # This is a bridge with one or more devices attached to
                        # it.
                        if vifpattern.match(elements[3]) and listvif == False:
                            # Omit this interface from the listing
                            retlist[elements[0]] = [ ]
                        else:
                            retlist[elements[0]] = [ elements[3] ]

            elif len(elements) == 1:
                # Dictionary key containing interface name should already
                # exist, append the interface.
                if not curbr in self.ignorebridges:
                    if not vifpattern.match(elements[0]) and listvif == True:
                        retlist[curbr].append(elements[0])
    
        return retlist

    def list_permanent(self):
        # Returns a list of permanent bridges (bridges configured to be enabled
        # at boot-time.
        retlist = {}
        ifpattern = re.compile('ifcfg-([a-z0-9]+)')
        # RHEL treats this value as case-sensitive, so so will we.
        brpattern = re.compile('TYPE=Bridge')
        brifpattern = re.compile('BRIDGE=([a-zA-Z0-9]+)')
        devpattern = re.compile('DEVICE=([a-zA-Z0-9\.]+)')
        nwscriptdir = "/etc/sysconfig/network-scripts"

        # Pass one: find bridges
        for item in os.listdir(nwscriptdir):
            match = ifpattern.match(item)
            if match:
                filename = "%s/%s" % (nwscriptdir, item)
                fp = open(filename, "r")
                lines = fp.readlines()
                fp.close()
                bridge = False
                ifname = ""
                for line in lines:
                    if brpattern.match(line):
                        bridge = True
                    devmatch = devpattern.match(line)
                    if devmatch:
                        ifname = devmatch.group(1)
                if bridge == True:
                    # Create empty interface list for bridge
                    retlist[ifname] = []

        # Pass two: match interface to bridge
        for item in os.listdir(nwscriptdir):
            match = ifpattern.match(item)
            if match:
                filename = "%s/%s" % (nwscriptdir, item)
                fp = open(filename, "r")
                lines = fp.readlines()
                fp.close()
                ifname = ""
                brname = ""
                for line in lines:
                    devmatch = devpattern.match(line)
                    if devmatch:
                        ifname = devmatch.group(1)
                    brmatch = brifpattern.match(line)
                    if brmatch:
                        brname = brmatch.group(1)
                if brname != "":
                    # Interface belongs to bridge
                    if brname in retlist:
                        # Just to be sure... if it doesn't match this interface
                        # is orphaned.
                        retlist[brname].append(ifname)
        return retlist
    
    def add_bridge(self, brname):
        # Creates a bridge
        if brname not in self.ignorebridges:
            brlist = self.list()
            if brname not in brlist:
                exitcode = os.spawnv(os.P_WAIT, self.brctl, [ self.brctl, "addbr", brname ] )
            else:
                # Bridge already exists, return 0 anyway.
                exitcode = 0
        else:
            exitcode = -1

        return exitcode

    def add_bridge_permanent(self, brname, ipaddr=None, netmask=None, gateway=None):
        # Creates a permanent bridge (writes to
        # /etc/sysconfig/network-scripts)
        if brname not in self.ignorebridges:
            filename = "/etc/sysconfig/network-scripts/ifcfg-%s" % brname
            fp = open(filename, "w")
            filelines = [ "DEVICE=%s\n" % brname, "TYPE=Bridge\n", "ONBOOT=yes\n" ]
            if ipaddr != None:
                filelines.append("IPADDR=%s\n" % ipaddr)
            if netmask != None:
                filelines.append("NETMASK=%s\n" % netmask)
            if gateway != None:
                filelines.append("GATEWAY=%s\n" % gateway)
            fp.writelines(filelines)
            fp.close()
            exitcode = os.spawnv(os.P_WAIT, self.ifup, [ self.ifup, brname ] )
        else:
            exitcode = -1
        return exitcode


    def add_interface(self, brname, ifname):
        # Adds an interface to a bridge
        if brname not in self.ignorebridges:
            brlist = self.list()
            if ifname not in brlist[brname]:
                exitcode = os.spawnv(os.P_WAIT, self.brctl, [ self.brctl, "addif", brname, ifname ] )
            else:
                # Interface is already a member of this bridge, return 0
                # anyway.
                exitcode = 0
        else:
            exitcode = -1

        return exitcode

    def add_interface_permanent(self, brname, ifname):
        # Permanently adds an interface to a bridge.
        # Both interface and bridge must have a ifcfg-file we can write to.
        brfilename = "/etc/sysconfig/network-scripts/ifcfg-%s" % brname
        iffilename = "/etc/sysconfig/network-scripts/ifcfg-%s" % ifname
        if os.path.exists(brfilename) and os.path.exists(iffilename):
            # Read all lines first, then we append a BRIDGE= line.
            fp = open(iffilename, "r")
            lines = fp.readlines()
            fp.close()
            pattern = re.compile("BRIDGE=(.*)")
            exitcode = 0
            for line in lines:
                if pattern.match(line) != None:
                    # This interface is configured to bridge already, leave it
                    # alone.
                    exitcode = 1
                    break
            if exitcode == 0:
                # Try change on live interface
                if self.add_interface(brname, ifname) == 0:
                    # Change succeeded, write to ifcfg-file
                    # Reopen file for writing
                    fp = open(iffilename, "w")
                    lines.append("BRIDGE=%s\n" % brname)
                    fp.writelines(lines)
                    fp.close()
                else:
                    exitcode = 2
        else:
            exitcode = -1

        return exitcode

    def delete_bridge(self, brname):
        # Deletes a bridge
        if brname not in self.ignorebridges:
            # This needs some more error checking. :)
            self.down_bridge(brname)
            exitcode = os.spawnv(os.P_WAIT, self.brctl, [ self.brctl, "delbr", brname ] )
        else:
            exitcode = -1

        return exitcode

    def delete_bridge_permanent(self, brname):
        # Deletes a bridge permanently
        filename = "/etc/sysconfig/network-scripts/ifcfg-%s" % brname
        if brname not in self.ignorebridges:
            returncode = self.delete_bridge(brname)
            if os.path.exists(filename):
                os.remove(filename)
        else:
            returncode = -1
        return returncode
    
    def delete_interface(self, brname, ifname):
        # Deletes an interface from a bridge
        if brname not in self.ignorebridges:
            exitcode = os.spawnv(os.P_WAIT, self.brctl, [ self.brctl, "delif", brname, ifname ] )
        else:
            exitcode = -1

        return exitcode

    def delete_interface_permanent(self, brname, ifname):
        # Permanently deletes interface from bridge
        iffilename = "/etc/sysconfig/network-scripts/ifcfg-%s" % ifname

        if brname in self.ignorebridges:
            exitcode = -1
        elif os.path.exists(iffilename):
            # This only works if the interface itself is permanent
            fp = open(iffilename, "r")
            lines = fp.readlines()
            fp.close()
            pattern = re.compile("BRIDGE=(.*)")
            exitcode = 1
            for line in lines:
                if pattern.match(line):
                    lines.remove(line)
                    exitcode = 0
            if exitcode == 0:
                # Try change live
                trychange = self.delete_interface(brname, ifname)
                if trychange == 0:
                    # Change succeeded, write new interface file.
                    fp = open(iffilename, "w")
                    fp.writelines(lines)
                    fp.close()
                else:
                    exitcode = trychange
        else:
            exitcode = 2
        return exitcode

    def delete_all_interfaces(self, brname):
        # Deletes all interfaces from a bridge
        if brname not in self.ignorebridges:
            bridgelist = self.list()
            if brname in bridgelist:
                # Does this bridge exist?
                exitcode = 0
                interfaces = bridgelist[brname]
                for interface in interfaces:
                    childexitcode = self.delete_interface(brname, interface)
                    if exitcode == 0 and childexitcode != 0:
                        exitcode = childexitcode
            else:
                exitcode = 1
        else:
            exitcode = -1
        return exitcode

    def delete_all_interfaces_permanent(self, brname):
        # Permanently deletes all interfaces from a bridge
        if brname not in self.ignorebridges:
            bridgelist = self.list_permanent()
            if brname in bridgelist:
                exitcode = 0
                interfaces = bridgelist[brname]
                for interface in interfaces:
                    childexitcode = self.delete_interface_permanent(brname, interface)
                    if exitcode == 0 and childexitcode != 0:
                        exitcode = childexitcode
                # Now that the startup-config is gone, remove all interfaces
                # from this bridge in the running configuration
                if exitcode == 0:
                    exitcode = self.delete_all_interfaces(brname)
            else:
                exitcode = 1
        else:
            exitcode = -1
        return exitcode

    def make_it_so(self, newconfig):
        # Applies supplied configuration to system

        # The false argument is to make sure we don't get the VIFs in the
        # listing.
        currentconfig = self.list(False)

        # First, delete all bridges / bridge interfaces not present in new
        # configuration.
        for bridge, interfaces in currentconfig.iteritems():
            if bridge not in newconfig:
                self.delete_all_interfaces(bridge)
                self.delete_bridge(bridge)

            else:
                for interface in interfaces:
                    if interface not in newconfig[bridge]:
                        self.delete_interface(bridge, interface)

        # Now, check for bridges / interfaces we need to add.
        for bridge, interfaces in newconfig.iteritems():
            if bridge not in currentconfig:
                # Create this bridge
                self.add_bridge(bridge)
                for interface in interfaces:
                    # Add all the interfaces to the bridge
                    self.add_interface(bridge, interface)
            else:
                for interface in interfaces:
                    if interface not in currentconfig[bridge]:
                        self.add_interface(bridge, interface)

        return self.list()

    def write(self):
        # Applies running configuration to startup configuration

        # The false argument is to make sure we don't get the VIFs in the
        # listing.
        newconfig = self.list(False)
        currentconfig = self.list_permanent()

        # First, delete all bridges / bridge interfaces not present in new
        # configuration.
        for bridge, interfaces in currentconfig.iteritems():
            if bridge not in newconfig:
                self.delete_all_interfaces_permanent(bridge)
                self.delete_bridge_permanent(bridge)

            else:
                for interface in interfaces:
                    if interface not in newconfig[bridge]:
                        self.delete_interface_permanent(bridge, interface)

        # Now, check for bridges / interfaces we need to add.
        for bridge, interfaces in newconfig.iteritems():
            if bridge not in currentconfig:
                # Create this bridge
                self.add_bridge_permanent(bridge)
                for interface in interfaces:
                    # Add all the interfaces to the bridge
                    self.add_interface_permanent(bridge, interface)
            else:
                for interface in interfaces:
                    if interface not in currentconfig[bridge]:
                        self.add_interface_permanent(bridge, interface)

        return self.list_permanent()

    def add_promisc_bridge(self, brname, ifname):
        # Creates a new bridge brname, attaches interface ifname to it and sets
        # the MAC address of the connected interface to FE:FF:FF:FF:FF:FF so
        # traffic can flow freely through the bridge. This is required for use
        # with Xen.
        addbrret = self.add_bridge(brname)
        addifret = self.add_interface(brname,ifname)
        # Set the MAC address of the interface we're adding to the bridge to
        # FE:FF:FF:FF:FF:FF. This is consistent with the behaviour of the
        # Xen network-bridge script.
        setaddrret = os.spawnv(os.P_WAIT, self.ip, [ self.ip, "link", "set", ifname, "address", "fe:ff:ff:ff:ff:ff" ])
        if addbrret or addifret or setaddrret:
            return -1
        else:
            return 0

    def updown_bridge(self, brname, up):
        # Marks a bridge and all it's connected interfaces up or down (used
        # internally)

        if up:
            updown = "up"
        else:
            updown = "down"

        bridges = self.list()
        if not brname in bridges:
            # Bridge doesn't exist, or should be ignored.
            return -1

        interfaces = [ brname ]
        for bridgemember in bridges[brname]:
            interfaces.append(bridgemember)

        exitcode = 0

        for ifname in interfaces:
            retcode = os.spawnv(os.P_WAIT, self.ip, [self.ip, "link", "set", ifname, updown ] )
            if retcode != 0:
                exitcode = retcode

        return exitcode

    def up_bridge(self, brname):
        # Marks a bridge and all it's connected interfaces up
        return self.updown_bridge(brname, 1)

    def down_bridge(self, brname):
        # Marks a bridge and all it's connected interfaces down
        return self.updown_bridge(brname, 0)