bf1edf3b19bbd9f12fcec1f47ae61eed6318d5f8
[openstack-build/neutron-build.git] / neutron / agent / linux / ovsdb_monitor.py
1 # Copyright 2013 Red Hat, Inc.
2 #
3 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
4 #    not use this file except in compliance with the License. You may obtain
5 #    a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #    Unless required by applicable law or agreed to in writing, software
10 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 #    License for the specific language governing permissions and limitations
13 #    under the License.
14
15 import eventlet
16 from oslo_log import log as logging
17 from oslo_serialization import jsonutils
18
19 from neutron._i18n import _LE
20 from neutron.agent.linux import async_process
21 from neutron.agent.ovsdb import api as ovsdb
22
23
24 LOG = logging.getLogger(__name__)
25
26 OVSDB_ACTION_INITIAL = 'initial'
27 OVSDB_ACTION_INSERT = 'insert'
28 OVSDB_ACTION_DELETE = 'delete'
29
30
31 class OvsdbMonitor(async_process.AsyncProcess):
32     """Manages an invocation of 'ovsdb-client monitor'."""
33
34     def __init__(self, table_name, columns=None, format=None,
35                  respawn_interval=None):
36
37         cmd = ['ovsdb-client', 'monitor', table_name]
38         if columns:
39             cmd.append(','.join(columns))
40         if format:
41             cmd.append('--format=%s' % format)
42         super(OvsdbMonitor, self).__init__(cmd, run_as_root=True,
43                                            respawn_interval=respawn_interval,
44                                            log_output=True,
45                                            die_on_error=True)
46
47
48 class SimpleInterfaceMonitor(OvsdbMonitor):
49     """Monitors the Interface table of the local host's ovsdb for changes.
50
51     The has_updates() method indicates whether changes to the ovsdb
52     Interface table have been detected since the monitor started or
53     since the previous access.
54     """
55
56     def __init__(self, respawn_interval=None):
57         super(SimpleInterfaceMonitor, self).__init__(
58             'Interface',
59             columns=['name', 'ofport', 'external_ids'],
60             format='json',
61             respawn_interval=respawn_interval,
62         )
63         self.new_events = {'added': [], 'removed': []}
64
65     @property
66     def has_updates(self):
67         """Indicate whether the ovsdb Interface table has been updated.
68
69         If the monitor process is not active an error will be logged since
70         it won't be able to communicate any update. This situation should be
71         temporary if respawn_interval is set.
72         """
73         if not self.is_active():
74             LOG.error(_LE("Interface monitor is not active"))
75         else:
76             self.process_events()
77         return bool(self.new_events['added'] or self.new_events['removed'])
78
79     def get_events(self):
80         self.process_events()
81         events = self.new_events
82         self.new_events = {'added': [], 'removed': []}
83         return events
84
85     def process_events(self):
86         devices_added = []
87         devices_removed = []
88         for row in self.iter_stdout():
89             json = jsonutils.loads(row).get('data')
90             for ovs_id, action, name, ofport, external_ids in json:
91                 if external_ids:
92                     external_ids = ovsdb.val_to_py(external_ids)
93                 if ofport:
94                     ofport = ovsdb.val_to_py(ofport)
95                 device = {'name': name,
96                           'ofport': ofport,
97                           'external_ids': external_ids}
98                 if action in (OVSDB_ACTION_INITIAL, OVSDB_ACTION_INSERT):
99                     devices_added.append(device)
100                 elif action == OVSDB_ACTION_DELETE:
101                     devices_removed.append(device)
102         self.new_events['added'].extend(devices_added)
103         self.new_events['removed'].extend(devices_removed)
104
105     def start(self, block=False, timeout=5):
106         super(SimpleInterfaceMonitor, self).start()
107         if block:
108             with eventlet.timeout.Timeout(timeout):
109                 while not self.is_active():
110                     eventlet.sleep()