1 # Copyright 2015 Red Hat, Inc.
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
16 from oslo_log import log as logging
17 from oslo_utils import excutils
19 from neutron._i18n import _LE
20 from neutron.agent.linux import async_process
21 from neutron.agent.linux import ip_lib
23 LOG = logging.getLogger(__name__)
26 class IPMonitorEvent(object):
27 def __init__(self, line, added, interface, cidr):
30 self.interface = interface
37 def from_text(cls, line):
43 with excutils.save_and_reraise_exception():
44 LOG.error(_LE('Unable to parse route "%s"'), line)
46 added = (first_word != 'Deleted')
51 interface = ip_lib.remove_interface_suffix(route[1])
54 with excutils.save_and_reraise_exception():
55 LOG.error(_LE('Unable to parse route "%s"'), line)
57 return cls(line, added, interface, cidr)
60 class IPMonitor(async_process.AsyncProcess):
61 """Wrapper over `ip monitor address`.
63 To monitor and react indefinitely:
64 m = IPMonitor(namespace='tmp', root_as_root=True)
67 event = IPMonitorEvent.from_text(iterable)
68 print(event, event.added, event.interface, event.cidr)
74 respawn_interval=None):
75 super(IPMonitor, self).__init__(['ip', '-o', 'monitor', 'address'],
76 run_as_root=run_as_root,
77 respawn_interval=respawn_interval,
81 return self.iter_stdout(block=True)
84 super(IPMonitor, self).start(block=True)
87 super(IPMonitor, self).stop(block=True)