4fa19760da344ca09844d9f7705b0eb1e7e34fd2
[openstack-build/neutron-build.git] / neutron / cmd / linuxbridge_cleanup.py
1 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
2 #    not use this file except in compliance with the License. You may obtain
3 #    a copy of the License at
4 #
5 #         http://www.apache.org/licenses/LICENSE-2.0
6 #
7 #    Unless required by applicable law or agreed to in writing, software
8 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 #    License for the specific language governing permissions and limitations
11 #    under the License.
12
13 import sys
14
15 from oslo_config import cfg
16 from oslo_log import log as logging
17
18 from neutron._i18n import _LE, _LI
19 from neutron.common import config
20 from neutron.common import utils as n_utils
21 from neutron.plugins.ml2.drivers.linuxbridge.agent \
22     import linuxbridge_neutron_agent
23
24
25 LOG = logging.getLogger(__name__)
26
27
28 def remove_empty_bridges():
29     try:
30         interface_mappings = n_utils.parse_mappings(
31             cfg.CONF.LINUX_BRIDGE.physical_interface_mappings)
32     except ValueError as e:
33         LOG.error(_LE("Parsing physical_interface_mappings failed: %s."), e)
34         sys.exit(1)
35     LOG.info(_LI("Interface mappings: %s."), interface_mappings)
36
37     try:
38         bridge_mappings = n_utils.parse_mappings(
39             cfg.CONF.LINUX_BRIDGE.bridge_mappings)
40     except ValueError as e:
41         LOG.error(_LE("Parsing bridge_mappings failed: %s."), e)
42         sys.exit(1)
43     LOG.info(_LI("Bridge mappings: %s."), bridge_mappings)
44
45     lb_manager = linuxbridge_neutron_agent.LinuxBridgeManager(
46         bridge_mappings, interface_mappings)
47
48     bridge_names = lb_manager.get_deletable_bridges()
49     for bridge_name in bridge_names:
50         if lb_manager.get_tap_devices_count(bridge_name):
51             continue
52
53         try:
54             lb_manager.delete_bridge(bridge_name)
55             LOG.info(_LI("Linux bridge %s deleted"), bridge_name)
56         except RuntimeError:
57             LOG.exception(_LE("Linux bridge %s delete failed"), bridge_name)
58     LOG.info(_LI("Linux bridge cleanup completed successfully"))
59
60
61 def main():
62     """Main method for cleaning up empty linux bridges.
63
64     This tool deletes every empty linux bridge managed by linuxbridge agent
65     (brq.* linux bridges) except thes ones defined using bridge_mappings option
66     in section LINUX_BRIDGE (created by deployers).
67
68     This tool should not be called during an instance create, migrate, etc. as
69     it can delete a linux bridge about to be used by nova.
70     """
71     cfg.CONF(sys.argv[1:])
72     config.setup_logging()
73     remove_empty_bridges()