Debian Codegraph @

networking_l2gw/services/l2gateway/agent/ovsdb/ovsdb_monitor.py

raw symbols SCIP
1 # Copyright (c) 2015 OpenStack Foundation.
2 # All Rights Reserved.
3 #
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
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
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
14 # under the License.
15
16 import random
17 import threading
18 import time
19
20 from oslo_config import cfg
21 from oslo_log import log as logging
22 from oslo_serialization import jsonutils
23 from oslo_utils import excutils
24
25 from networking_l2gw._i18n import _
26 from networking_l2gw.services.l2gateway.agent.ovsdb import base_connection
27 from networking_l2gw.services.l2gateway.common import constants as n_const
28 from networking_l2gw.services.l2gateway.common import ovsdb_schema
29 from networking_l2gw.services.l2gateway import exceptions
30
31 LOG = logging.getLogger(__name__)
32
33
34 class Activity:
35 Initial, Update = range(2)
36
37
38 class OVSDBMonitor(base_connection.BaseConnection):
39 """Monitors OVSDB servers."""
40 def __init__(self, conf, gw_config, callback, mgr=None):
41 super().__init__(conf, gw_config, mgr=None)
42 self.mgr = mgr
43 self.rpc_callback = callback
44 self.callbacks = {}
45 self._setup_dispatch_table()
46 self.read_on = True
47 self.handlers = {"echo": self._default_echo_handler}
48 self.sock_timeout = cfg.CONF.ovsdb.socket_timeout
49 if self.enable_manager:
50 self.check_monitor_table_thread = False
51 if not self.enable_manager:
52 rcv_thread = threading.Thread(target=self._rcv_thread)
53 rcv_thread.daemon = True
54 rcv_thread.start()
55
56 def _spawn_monitor_table_thread(self, addr):
57 self.set_monitor_response_handler(addr)
58 self.check_monitor_table_thread = True
59
60 def _initialize_data_dict(self):
61 data_dict = {'new_local_macs': [],
62 'deleted_local_macs': [],
63 'modified_local_macs': [],
64 'new_remote_macs': [],
65 'deleted_remote_macs': [],
66 'modified_remote_macs': [],
67 'new_physical_ports': [],
68 'deleted_physical_ports': [],
69 'modified_physical_ports': [],
70 'new_physical_switches': [],
71 'deleted_physical_switches': [],
72 'modified_physical_switches': [],
73 'new_physical_locators': [],
74 'deleted_physical_locators': [],
75 'modified_physical_locators': [],
76 'new_logical_switches': [],
77 'deleted_logical_switches': [],
78 'modified_logical_switches': [],
79 'new_mlocal_macs': [],
80 'deleted_mlocal_macs': [],
81 'modified_mlocal_macs': [],
82 'new_locator_sets': [],
83 'deleted_locator_sets': [],
84 'modified_locator_sets': []}
85 return data_dict
86
87 def _setup_dispatch_table(self):
88 self.dispatch_table = {'Logical_Switch': self._process_logical_switch,
89 'Ucast_Macs_Local':
90 self._process_ucast_macs_local,
91 'Physical_Locator':
92 self._process_physical_locator,
93 'Ucast_Macs_Remote':
94 self._process_ucast_macs_remote,
95 'Mcast_Macs_Local':
96 self._process_mcast_macs_local,
97 'Physical_Locator_Set':
98 self._process_physical_locator_set
99 }
100
101 def set_monitor_response_handler(self, addr=None):
102 """Monitor OVSDB tables to receive events for any changes in OVSDB."""
103 if self.connected:
104 op_id = str(random.getrandbits(128))
105 props = {'select': {'initial': True,
106 'insert': True,
107 'delete': True,
108 'modify': True}}
109 monitor_message = {'id': op_id,
110 'method': 'monitor',
111 'params': [n_const.OVSDB_SCHEMA_NAME,
112 None,
113 {'Logical_Switch': [props],
114 'Physical_Switch': [props],
115 'Physical_Port': [props],
116 'Ucast_Macs_Local': [props],
117 'Ucast_Macs_Remote': [props],
118 'Physical_Locator': [props],
119 'Mcast_Macs_Local': [props],
120 'Physical_Locator_Set': [props]}
121 ]}
122 self._set_handler("update", self._update_event_handler)
123 if not self.send(monitor_message, addr=addr):
124 # Return so that this will retried in the next iteration
125 return
126 try:
127 response_result = self._process_response(op_id)
128 except exceptions.OVSDBError:
129 with excutils.save_and_reraise_exception():
130 if self.enable_manager:
131 self.check_monitor_table_thread = False
132 LOG.exception("Exception while receiving the "
133 "response for the monitor message")
134 self._process_monitor_msg(response_result, addr)
135
136 def _update_event_handler(self, message, addr):
137 self._process_update_event(message, addr)
138
139 def _process_update_event(self, message, addr):
140 """Process update event that is triggered by the OVSDB server."""
141 LOG.debug("_process_update_event: message = %s ", str(message))
142 data_dict = self._initialize_data_dict()
143 if message.get('method') == 'update':
144 params_list = message.get('params')
145 param_dict = params_list[1]
146 self._process_tables(param_dict, data_dict)
147 self.rpc_callback(Activity.Update,
148 self._form_ovsdb_data(data_dict, addr))
149
150 def _process_tables(self, param_dict, data_dict):
151 # Process all the tables one by one.
152 # OVSDB table name is the key in the dictionary.
153 port_map = {}
154 for table_name in param_dict.keys():
155 table_dict = param_dict.get(table_name)
156 for uuid in table_dict.keys():
157 uuid_dict = table_dict.get(uuid)
158 if table_name == 'Physical_Switch':
159 self._process_physical_switch(uuid,
160 uuid_dict,
161 port_map,
162 data_dict)
163 elif table_name == 'Physical_Port':
164 self._process_physical_port(uuid, uuid_dict,
165 port_map, data_dict)
166 else:
167 self.dispatch_table.get(table_name)(uuid, uuid_dict,
168 data_dict)
169
170 def _process_response(self, op_id):
171 result = self._response(op_id)
172 count = 0
173 while (not result and count <= n_const.MAX_RETRIES):
174 count = count + 1
175 time.sleep(0)
176 result = self._response(op_id)
177 if not result and count >= n_const.MAX_RETRIES:
178 raise exceptions.OVSDBError(
179 message="OVSDB server did not respond within "
180 "max retry attempts.")
181 error = result.get("error", None)
182 if error:
183 raise exceptions.OVSDBError(
184 message="Error from the OVSDB server %s" % error
185 )
186 return result
187
188 def _default_echo_handler(self, message, addr):
189 """Message handler for the OVSDB server's echo request."""
190 self.send({"result": message.get("params", None),
191 "error": None, "id": message['id']}, addr=addr)
192
193 def _set_handler(self, method_name, handler):
194 self.handlers[method_name] = handler
195
196 def _on_remote_message(self, message, addr=None):
197 """Processes the message received on the socket."""
198 try:
199 json_m = jsonutils.loads(message)
200 handler_method = json_m.get('method', None)
201 if handler_method:
202 self.handlers.get(handler_method)(json_m, addr)
203 else:
204 self.responses.append(json_m)
205 except Exception as e:
206 LOG.exception("Exception [%s] while handling "
207 "message", e)
208
209 def _rcv_thread(self):
210 chunks = []
211 lc = rc = 0
212 prev_char = None
213 while self.read_on:
214 try:
215 # self.socket.recv() is a blocked call
216 # (if timeout value is not passed) due to which we cannot
217 # determine if the remote OVSDB server has died. The remote
218 # OVSDB server sends echo requests every 4 seconds.
219 # If there is no echo request on the socket for socket_timeout
220 # seconds(by default its 30 seconds),
221 # the agent can safely assume that the connection with the
222 # remote OVSDB server is lost. Better to retry by reopening
223 # the socket.
224 self.socket.settimeout(self.sock_timeout)
225 response = self.socket.recv(n_const.BUFFER_SIZE)
226 time.sleep(0)
227 if response:
228 response = response.decode('utf8')
229 message_mark = 0
230 for i, c in enumerate(response):
231 if c == '{' and not (prev_char and
232 prev_char == '\\'):
233 lc += 1
234 elif c == '}' and not (prev_char and
235 prev_char == '\\'):
236 rc += 1
237 if rc > lc:
238 raise Exception(_("json string not valid"))
239 elif lc == rc and lc != 0:
240 chunks.append(response[message_mark:i + 1])
241 message = "".join(chunks)
242 self._on_remote_message(message)
243 lc = rc = 0
244 message_mark = i + 1
245 chunks = []
246 prev_char = c
247 chunks.append(response[message_mark:])
248 else:
249 self.read_on = False
250 self.disconnect()
251 except Exception as ex:
252 self.read_on = False
253 self.disconnect()
254 LOG.exception("Exception [%s] occurred while receiving"
255 "message from the OVSDB server", ex)
256
257 def disconnect(self, addr=None):
258 """disconnects the connection from the OVSDB server."""
259 self.read_on = False
260 super().disconnect(addr)
261
262 def _process_monitor_msg(self, message, addr=None):
263 """Process initial set of records in the OVSDB at startup."""
264 result_dict = message.get('result')
265 data_dict = self._initialize_data_dict()
266 try:
267 self._process_tables(result_dict, data_dict)
268 self.rpc_callback(Activity.Initial,
269 self._form_ovsdb_data(data_dict, addr))
270 except Exception as e:
271 LOG.exception("_process_monitor_msg:ERROR %s ", e)
272
273 def _get_list(self, resource_list):
274 return [element.__dict__ for element in resource_list]
275
276 def _form_ovsdb_data(self, data_dict, addr):
277 return {n_const.OVSDB_IDENTIFIER: str(addr) if (
278 self.enable_manager) else (self.gw_config.ovsdb_identifier),
279 'new_logical_switches': self._get_list(
280 data_dict.get('new_logical_switches')),
281 'new_physical_switches': self._get_list(
282 data_dict.get('new_physical_switches')),
283 'new_physical_ports': self._get_list(
284 data_dict.get('new_physical_ports')),
285 'new_physical_locators': self._get_list(
286 data_dict.get('new_physical_locators')),
287 'new_local_macs': self._get_list(
288 data_dict.get('new_local_macs')),
289 'new_remote_macs': self._get_list(
290 data_dict.get('new_remote_macs')),
291 'new_mlocal_macs': self._get_list(
292 data_dict.get('new_mlocal_macs')),
293 'new_locator_sets': self._get_list(
294 data_dict.get('new_locator_sets')),
295 'deleted_logical_switches': self._get_list(
296 data_dict.get('deleted_logical_switches')),
297 'deleted_physical_switches': self._get_list(
298 data_dict.get('deleted_physical_switches')),
299 'deleted_physical_ports': self._get_list(
300 data_dict.get('deleted_physical_ports')),
301 'deleted_physical_locators': self._get_list(
302 data_dict.get('deleted_physical_locators')),
303 'deleted_local_macs': self._get_list(
304 data_dict.get('deleted_local_macs')),
305 'deleted_remote_macs': self._get_list(
306 data_dict.get('deleted_remote_macs')),
307 'deleted_mlocal_macs': self._get_list(
308 data_dict.get('deleted_mlocal_macs')),
309 'deleted_locator_sets': self._get_list(
310 data_dict.get('deleted_locator_sets')),
311 'modified_logical_switches': self._get_list(
312 data_dict.get('modified_logical_switches')),
313 'modified_physical_switches': self._get_list(
314 data_dict.get('modified_physical_switches')),
315 'modified_physical_ports': self._get_list(
316 data_dict.get('modified_physical_ports')),
317 'modified_physical_locators': self._get_list(
318 data_dict.get('modified_physical_locators')),
319 'modified_local_macs': self._get_list(
320 data_dict.get('modified_local_macs')),
321 'modified_remote_macs': self._get_list(
322 data_dict.get('modified_remote_macs')),
323 'modified_mlocal_macs': self._get_list(
324 data_dict.get('modified_mlocal_macs')),
325 'modified_locator_sets': self._get_list(
326 data_dict.get('modified_locator_sets'))}
327
328 def _process_physical_port(self, uuid, uuid_dict, port_map, data_dict):
329 """Processes Physical_Port record from the OVSDB event."""
330 new_row = uuid_dict.get('new', None)
331 old_row = uuid_dict.get('old', None)
332 if new_row:
333 port_fault_status = new_row.get('port_fault_status')
334 if type(port_fault_status) is list:
335 port_fault_status = None
336 port = ovsdb_schema.PhysicalPort(uuid, new_row.get('name'), None,
337 None,
338 port_fault_status)
339 switch_id = port_map.get(uuid, None)
340 if switch_id:
341 port.physical_switch_id = switch_id
342 # Update the vlan bindings
343 outer_binding_list = new_row.get('vlan_bindings')
344 # First element is "map"
345 outer_binding_list.remove(outer_binding_list[0])
346 vlan_bindings = []
347 if len(outer_binding_list) > 0:
348 for binding in outer_binding_list:
349 if len(binding) > 0:
350 for element in binding:
351 vlan = element[0]
352 inner_most_list = element[1]
353 ls_id = inner_most_list[1]
354 vb = ovsdb_schema.VlanBinding(vlan, ls_id).__dict__
355 vlan_bindings.append(vb)
356 port.vlan_bindings = vlan_bindings
357 if old_row:
358 modified_physical_ports = data_dict.get(
359 'modified_physical_ports')
360 modified_physical_ports.append(port)
361 else:
362 new_physical_ports = data_dict.get(
363 'new_physical_ports')
364 new_physical_ports.append(port)
365 elif old_row:
366 # Port is deleted permanently from OVSDB server
367 port_fault_status = old_row.get('port_fault_status')
368 if type(port_fault_status) is list:
369 port_fault_status = None
370 port = ovsdb_schema.PhysicalPort(uuid, old_row.get('name'), None,
371 None,
372 port_fault_status)
373 deleted_physical_ports = data_dict.get('deleted_physical_ports')
374 deleted_physical_ports.append(port)
375
376 def _process_physical_switch(self, uuid, uuid_dict, port_map, data_dict):
377 """Processes Physical_Switch record from the OVSDB event."""
378 new_row = uuid_dict.get('new', None)
379 old_row = uuid_dict.get('old', None)
380 if new_row:
381 # insert or modify operation
382 ports = new_row.get('ports')
383 # First element in the list is either 'set' or 'uuid'
384 # Let us remove it.
385 is_set = False
386 if ports[0] == 'set':
387 is_set = True
388 ports.remove(ports[0])
389 all_ports = []
390 if not is_set:
391 all_ports.append(ports[0])
392 else:
393 for port_list in ports:
394 # each port variable is again list
395 for port in port_list:
396 for inner_port in port:
397 if inner_port != 'uuid':
398 all_ports.append(inner_port)
399 switch_fault_status = new_row.get('switch_fault_status')
400 if type(switch_fault_status) is list:
401 switch_fault_status = None
402 phys_switch = ovsdb_schema.PhysicalSwitch(
403 uuid, new_row.get('name'), new_row.get('tunnel_ips'),
404 switch_fault_status)
405 # Now, store mapping of physical ports to
406 # physical switch so that it is useful while
407 # processing Physical_Switch record
408 for port in all_ports:
409 port_map[port] = uuid
410 for pport in data_dict['new_physical_ports']:
411 if pport.uuid == port:
412 pport.physical_switch_id = uuid
413 if old_row:
414 modified_physical_switches = data_dict.get(
415 'modified_physical_switches')
416 modified_physical_switches.append(phys_switch)
417 else:
418 new_physical_switches = data_dict.get(
419 'new_physical_switches')
420 new_physical_switches.append(phys_switch)
421 elif old_row:
422 # Physical switch is deleted permanently from OVSDB
423 # server
424 switch_fault_status = old_row.get('switch_fault_status')
425 if type(switch_fault_status) is list:
426 switch_fault_status = None
427 phys_switch = ovsdb_schema.PhysicalSwitch(
428 uuid, old_row.get('name'), old_row.get('tunnel_ips'),
429 switch_fault_status)
430 deleted_physical_switches = data_dict.get(
431 'deleted_physical_switches')
432 deleted_physical_switches.append(phys_switch)
433
434 def _process_logical_switch(self, uuid, uuid_dict, data_dict):
435 """Processes Logical_Switch record from the OVSDB event."""
436 new_row = uuid_dict.get('new', None)
437 old_row = uuid_dict.get('old', None)
438 if new_row:
439 l_switch = ovsdb_schema.LogicalSwitch(uuid,
440 new_row.get('name'),
441 new_row.get('tunnel_key'),
442 new_row.get('description'))
443 if old_row:
444 modified_logical_switches = data_dict.get(
445 'modified_logical_switches')
446 modified_logical_switches.append(l_switch)
447 else:
448 new_logical_switches = data_dict.get(
449 'new_logical_switches')
450 new_logical_switches.append(l_switch)
451 elif old_row:
452 l_switch = ovsdb_schema.LogicalSwitch(uuid,
453 old_row.get('name'),
454 old_row.get('tunnel_key'),
455 old_row.get('description'))
456 deleted_logical_switches = data_dict.get(
457 'deleted_logical_switches')
458 deleted_logical_switches.append(l_switch)
459
460 def _process_ucast_macs_local(self, uuid, uuid_dict, data_dict):
461 """Processes Ucast_Macs_Local record from the OVSDB event."""
462 new_row = uuid_dict.get('new', None)
463 old_row = uuid_dict.get('old', None)
464 if new_row:
465 locator_list = new_row.get('locator')
466 locator_id = locator_list[1]
467 logical_switch_list = new_row.get('logical_switch')
468 logical_switch_id = logical_switch_list[1]
469 mac_local = ovsdb_schema.UcastMacsLocal(uuid,
470 new_row.get('MAC'),
471 logical_switch_id,
472 locator_id,
473 new_row.get('ipaddr'))
474 if old_row:
475 modified_local_macs = data_dict.get(
476 'modified_local_macs')
477 modified_local_macs.append(mac_local)
478 else:
479 new_local_macs = data_dict.get(
480 'new_local_macs')
481 new_local_macs.append(mac_local)
482 elif old_row:
483 # A row from UcastMacLocal is deleted.
484 logical_switch_list = old_row.get('logical_switch')
485 l_sw_id = logical_switch_list[1]
486 mac_local = ovsdb_schema.UcastMacsLocal(uuid,
487 old_row.get('MAC'),
488 l_sw_id,
489 None,
490 None)
491 deleted_local_macs = data_dict.get(
492 'deleted_local_macs')
493 deleted_local_macs.append(mac_local)
494
495 def _process_ucast_macs_remote(self, uuid, uuid_dict, data_dict):
496 """Processes Ucast_Macs_Remote record from the OVSDB event."""
497 new_row = uuid_dict.get('new', None)
498 old_row = uuid_dict.get('old', None)
499 if new_row:
500 locator_list = new_row.get('locator')
501 locator_id = locator_list[1]
502 logical_switch_list = new_row.get('logical_switch')
503 logical_switch_id = logical_switch_list[1]
504 mac_remote = ovsdb_schema.UcastMacsRemote(uuid,
505 new_row.get('MAC'),
506 logical_switch_id,
507 locator_id,
508 new_row.get('ipaddr'))
509 if old_row:
510 modified_remote_macs = data_dict.get(
511 'modified_remote_macs')
512 modified_remote_macs.append(mac_remote)
513 else:
514 new_remote_macs = data_dict.get(
515 'new_remote_macs')
516 new_remote_macs.append(mac_remote)
517 elif old_row:
518 logical_switch_list = old_row.get('logical_switch')
519 l_sw_id = logical_switch_list[1]
520 mac_remote = ovsdb_schema.UcastMacsRemote(uuid,
521 old_row.get('MAC'),
522 l_sw_id,
523 None,
524 None)
525 deleted_remote_macs = data_dict.get(
526 'deleted_remote_macs')
527 deleted_remote_macs.append(mac_remote)
528
529 def _process_physical_locator(self, uuid, uuid_dict, data_dict):
530 """Processes Physical_Locator record from the OVSDB event."""
531 new_row = uuid_dict.get('new', None)
532 old_row = uuid_dict.get('old', None)
533 if new_row:
534 dstip = new_row['dst_ip']
535 locator = ovsdb_schema.PhysicalLocator(uuid, dstip)
536 if old_row:
537 modified_physical_locators = data_dict.get(
538 'modified_physical_locators')
539 modified_physical_locators.append(locator)
540 else:
541 new_physical_locators = data_dict.get(
542 'new_physical_locators')
543 new_physical_locators.append(locator)
544 elif old_row:
545 dstip = old_row['dst_ip']
546 locator = ovsdb_schema.PhysicalLocator(uuid, dstip)
547 deleted_physical_locators = data_dict.get(
548 'deleted_physical_locators')
549 deleted_physical_locators.append(locator)
550
551 def _process_mcast_macs_local(self, uuid, uuid_dict, data_dict):
552 """Processes Mcast_Macs_Local record from the OVSDB event."""
553 new_row = uuid_dict.get('new', None)
554 old_row = uuid_dict.get('old', None)
555 if new_row:
556 locator_set_list = new_row.get('locator_set')
557 logical_switch_list = new_row.get('logical_switch')
558 mcast_local = ovsdb_schema.McastMacsLocal(uuid,
559 new_row['MAC'],
560 logical_switch_list[1],
561 locator_set_list[1],
562 new_row['ipaddr'])
563 if old_row:
564 modified_mlocal_macs = data_dict.get(
565 'modified_mlocal_macs')
566 modified_mlocal_macs.append(mcast_local)
567 else:
568 new_mlocal_macs = data_dict.get(
569 'new_mlocal_macs')
570 new_mlocal_macs.append(mcast_local)
571 elif old_row:
572 logical_switch_list = old_row.get('logical_switch')
573 l_sw_id = logical_switch_list[1]
574 mcast_local = ovsdb_schema.McastMacsLocal(uuid,
575 old_row.get('MAC'),
576 l_sw_id,
577 None,
578 None)
579 deleted_mlocal_macs = data_dict.get(
580 'deleted_mlocal_macs')
581 deleted_mlocal_macs.append(mcast_local)
582
583 def _process_physical_locator_set(self, uuid, uuid_dict, data_dict):
584 """Processes Physical_Locator_Set record from the OVSDB event."""
585 new_row = uuid_dict.get('new', None)
586 old_row = uuid_dict.get('old', None)
587 if new_row:
588 locator_set = self._form_locator_set(uuid, new_row)
589 if old_row:
590 modified_locator_sets = data_dict.get(
591 'modified_locator_sets')
592 modified_locator_sets.append(locator_set)
593 else:
594 new_locator_sets = data_dict.get(
595 'new_locator_sets')
596 new_locator_sets.append(locator_set)
597 elif old_row:
598 locator_set = self._form_locator_set(uuid, old_row)
599 deleted_locator_sets = data_dict.get(
600 'deleted_locator_sets')
601 deleted_locator_sets.append(locator_set)
602
603 def _form_locator_set(self, uuid, row):
604 locators = []
605 locator_set_list = row.get('locators')
606 if locator_set_list[0] == 'set':
607 locator_set_list = locator_set_list[1]
608 for locator in locator_set_list:
609 locators.append(locator[1])
610 else:
611 locators.append(locator_set_list[1])
612 locator_set = ovsdb_schema.PhysicalLocatorSet(uuid,
613 locators)
614 return locator_set