Debian Codegraph @

networking_l2gw/services/l2gateway/service_drivers/rpc_l2gw.py

raw symbols SCIP
1 # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
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 abc
17
18 from neutron.db import agents_db
19 from neutron_lib import rpc as n_rpc
20
21 from networking_l2gw._i18n import _
22 from networking_l2gw.db.l2gateway import l2gateway_db as l2_gw_db
23 from networking_l2gw.db.l2gateway.ovsdb import lib as db
24 from networking_l2gw.services.l2gateway import agent_scheduler
25 from networking_l2gw.services.l2gateway.common import constants
26 from networking_l2gw.services.l2gateway.common import l2gw_validators
27 from networking_l2gw.services.l2gateway.common import ovsdb_schema
28 from networking_l2gw.services.l2gateway.common import topics
29 from networking_l2gw.services.l2gateway import exceptions as l2gw_exc
30 from networking_l2gw.services.l2gateway import service_drivers
31 from networking_l2gw.services.l2gateway.service_drivers import agent_api
32
33 from neutron.plugins.ml2 import managers
34
35 from neutron_lib.api.definitions import portbindings
36 from neutron_lib import constants as n_const
37 from neutron_lib.db import api as db_api
38 from neutron_lib import exceptions
39 from oslo_config import cfg
40 from oslo_log import log as logging
41 import oslo_messaging as messaging
42 from oslo_utils import importutils
43
44 LOG = logging.getLogger(__name__)
45
46 L2GW = 'l2gw'
47 L2GW_CALLBACK = ("networking_l2gw.services.l2gateway.ovsdb."
48 "data.L2GatewayOVSDBCallbacks")
49
50
51 class L2gwRpcDriver(service_drivers.L2gwDriver, metaclass=abc.ABCMeta):
52 """L2gw RPC Service Driver class."""
53
54 def __init__(self, service_plugin, validator=None):
55 super().__init__(service_plugin, validator)
56 self.ovsdb_callback = importutils.import_object(
57 L2GW_CALLBACK, self)
58 self.endpoints = (
59 [self.ovsdb_callback, agents_db.AgentExtRpcCallback()])
60 self.conn = n_rpc.Connection()
61 self.conn.create_consumer(topics.L2GATEWAY_PLUGIN,
62 self.endpoints,
63 fanout=False)
64 self.conn.consume_in_threads()
65 self.create_rpc_conn()
66 LOG.debug("starting l2gateway agent scheduler")
67 self.start_l2gateway_agent_scheduler()
68 self.gateway_resource = constants.GATEWAY_RESOURCE_NAME
69 self.l2gateway_db = l2_gw_db.L2GatewayMixin()
70 self.type_manager = managers.TypeManager()
71 self.port_dict_before_update = []
72
73 @property
74 def service_type(self):
75 return L2GW
76
77 def create_rpc_conn(self):
78 self.agent_rpc = agent_api.L2gatewayAgentApi(topics.L2GATEWAY_AGENT,
79 cfg.CONF.host)
80
81 def start_l2gateway_agent_scheduler(self):
82 """Start l2gateway agent scheduler thread."""
83 self.agentscheduler = agent_scheduler.L2GatewayAgentScheduler(
84 self.agent_rpc)
85 self.agentscheduler.initialize_thread()
86
87 def _get_dict(self, resource):
88 return resource.__dict__
89
90 def add_port_mac(self, context, port_dict):
91 """Process the created port and trigger the RPC
92
93 to add to the gateway.
94 """
95 port_id = port_dict.get("id")
96 port = self.service_plugin._core_plugin.get_port(context, port_id)
97 if port['device_owner']:
98 network_id = port.get("network_id")
99 dst_ip, ip_address = self._get_ip_details(context, port)
100 network = self._get_network_details(context, network_id)
101 l2gateway_connections = (
102 self.service_plugin.get_l2_gateway_connections(
103 context, filters={'network_id': [network_id]}))
104 if not l2gateway_connections:
105 return
106 logical_switches = db.get_all_logical_switches_by_name(context,
107 network_id)
108 if not logical_switches:
109 return
110 for logical_switch in logical_switches:
111 logical_switch['description'] = network.get('name')
112 ovsdb_identifier = logical_switch.get('ovsdb_identifier')
113 locator_dict = {'dst_ip': dst_ip,
114 'ovsdb_identifier': ovsdb_identifier}
115 physical_locator = self._form_physical_locator_schema(
116 context, locator_dict)
117 locator_uuid = physical_locator.get('uuid')
118 logical_switch_uuid = logical_switch.get('uuid')
119 mac_remote = self._get_dict(ovsdb_schema.UcastMacsRemote(
120 uuid=None,
121 mac=port['mac_address'],
122 logical_switch_id=logical_switch_uuid,
123 physical_locator_id=locator_uuid,
124 ip_address=ip_address))
125 mac_dict = mac_remote
126 mac_dict['ovsdb_identifier'] = ovsdb_identifier
127 mac_dict['logical_switch_uuid'] = logical_switch_uuid
128 ucast_mac_remote = db.get_ucast_mac_remote_by_mac_and_ls(
129 context, mac_dict)
130 if ucast_mac_remote:
131 # check whether locator got changed in vm migration
132 if ucast_mac_remote['physical_locator_id'
133 ] != physical_locator['uuid']:
134 mac_remote['uuid'] = ucast_mac_remote['uuid']
135 try:
136 self.agent_rpc.update_vif_to_gateway(
137 context, ovsdb_identifier,
138 physical_locator, mac_remote)
139 LOG.debug(
140 "VM migrated from %s to %s. Update"
141 "locator in Ucast_Macs_Remote",
142 ucast_mac_remote['physical_locator_id'],
143 physical_locator['uuid'])
144 except messaging.MessagingTimeout:
145 # If RPC is timed out, then the RabbitMQ
146 # will retry the operation.
147 LOG.exception("Communication error with "
148 "the L2 gateway agent")
149 except Exception:
150 # The remote OVSDB server may be down.
151 # We need to retry this operation later.
152 db.add_pending_ucast_mac_remote(
153 context, 'update',
154 ovsdb_identifier,
155 logical_switch_uuid,
156 physical_locator,
157 [mac_remote])
158 else:
159 LOG.debug("add_port_mac: MAC %s exists "
160 "in Gateway", mac_dict['mac'])
161 ovsdb_data_handler = (
162 self.ovsdb_callback.get_ovsdbdata_object(
163 ovsdb_identifier))
164 ovsdb_data_handler._handle_l2pop(
165 context, [ucast_mac_remote])
166 continue
167 # else it is a new port created
168 try:
169 self.agent_rpc.add_vif_to_gateway(
170 context, ovsdb_identifier, logical_switch,
171 physical_locator, mac_remote)
172 except messaging.MessagingTimeout:
173 # If RPC is timed out, then the RabbitMQ
174 # will retry the operation.
175 LOG.exception("Communication error with "
176 "the L2 gateway agent")
177 except Exception:
178 # The remote OVSDB server may be down.
179 # We need to retry this operation later.
180 LOG.debug("The remote OVSDB server may be down")
181 db.add_pending_ucast_mac_remote(
182 context, 'insert', ovsdb_identifier,
183 logical_switch_uuid,
184 physical_locator,
185 [mac_remote])
186
187 def _form_physical_locator_schema(self, context, pl_dict):
188 locator_uuid = None
189 locator = db.get_physical_locator_by_dst_ip(
190 context, pl_dict)
191 if locator:
192 locator_uuid = locator.get('uuid')
193 physical_locator = self._get_dict(
194 ovsdb_schema.PhysicalLocator(uuid=locator_uuid,
195 dst_ip=pl_dict.get('dst_ip')))
196 return physical_locator
197
198 def delete_port_mac(self, context, port):
199 """Process the deleted port and trigger the RPC
200
201 to delete from the gateway.
202
203 When the ML2 plugin invokes this call, the argument port is
204 a single port dict, whereas the L2gateway service plugin
205 sends it as a list of port dicts.
206 """
207 ls_dict = {}
208 mac_list = []
209 logical_switches = []
210 ovsdb_identifier = None
211 if isinstance(port, list):
212 from_l2gw_plugin = True
213 network_id = port[0].get('network_id')
214 ovsdb_identifier = port[0].get('ovsdb_identifier')
215 lg_dict = {'logical_switch_name': network_id,
216 'ovsdb_identifier': ovsdb_identifier}
217 logical_switch = db.get_logical_switch_by_name(
218 context, lg_dict)
219 logical_switches.append(logical_switch)
220 port_list = port
221 else:
222 from_l2gw_plugin = False
223 network_id = port.get('network_id')
224 logical_switches = (
225 db.get_all_logical_switches_by_name(
226 context, network_id))
227 l2gateway_connections = (
228 self.service_plugin.get_l2_gateway_connections(
229 context, filters={'network_id': [network_id]}))
230 if not l2gateway_connections:
231 return
232 port_list = [port]
233 for port_dict in port_list:
234 if port_dict['device_owner']:
235 if logical_switches:
236 for logical_switch in logical_switches:
237 logical_switch_uuid = logical_switch.get('uuid')
238 macs = []
239 if isinstance(port_dict.get("allowed_address_pairs"),
240 list):
241 for address_pair in port_dict[
242 'allowed_address_pairs']:
243 mac = address_pair['mac_address']
244 macs.append(mac)
245 macs.append(port_dict.get("mac_address"))
246 if port_dict.get('ovsdb_identifier', None):
247 ovsdb_identifier = port_dict.get(
248 'ovsdb_identifier')
249 else:
250 ovsdb_identifier = logical_switch.get(
251 'ovsdb_identifier')
252
253 if from_l2gw_plugin:
254 ls = logical_switch.get('name')
255 l2gateway_connections = (
256 self.service_plugin.
257 get_l2_gateway_connections(
258 context,
259 filters={'network_id': [ls]}))
260 if len(l2gateway_connections) > 1:
261 continue
262 for mac in macs:
263 record_dict = {'mac': mac,
264 'logical_switch_uuid':
265 logical_switch_uuid,
266 'ovsdb_identifier':
267 ovsdb_identifier}
268
269 ucast_mac_remote = (
270 db.get_ucast_mac_remote_by_mac_and_ls(
271 context, record_dict))
272 del_count = 0
273 if not ucast_mac_remote:
274 LOG.debug("delete_port_mac: MAC %s does"
275 " not exist", mac)
276 # It is possible that this MAC is present
277 # in the pending_ucast_mac_remote table.
278 # Delete this MAC as it was not inserted
279 # into the OVSDB server earlier.
280 del_count = db.delete_pending_ucast_mac_remote(
281 context, 'insert',
282 ovsdb_identifier,
283 logical_switch_uuid,
284 mac)
285 if not del_count:
286 mac_list = ls_dict.get(logical_switch_uuid, [])
287 mac_list.append(mac)
288 ls_dict[logical_switch_uuid] = mac_list
289 else:
290 LOG.debug("delete_port_mac:Logical Switch %s "
291 "does not exist ", port_dict.get('network_id'))
292 return
293 for logical_switch_uuid, mac_list in ls_dict.items():
294 try:
295 if mac_list:
296 self.agent_rpc.delete_vif_from_gateway(context,
297 ovsdb_identifier,
298 logical_switch_uuid,
299 mac_list)
300 except messaging.MessagingTimeout:
301 # If RPC is timed out, then the RabbitMQ
302 # will retry the operation.
303 LOG.exception("Communication error with "
304 "the L2 gateway agent")
305 except Exception as ex:
306 # The remote OVSDB server may be down.
307 # We need to retry this operation later.
308 LOG.debug("Exception occurred %s", str(ex))
309 db.add_pending_ucast_mac_remote(
310 context, 'delete', ovsdb_identifier,
311 logical_switch_uuid,
312 None,
313 mac_list)
314
315 def _check_port_fault_status_and_switch_fault_status(self, context,
316 l2_gateway_id):
317 l2gw = self.service_plugin.get_l2_gateway(context, l2_gateway_id)
318 if not l2gw:
319 raise l2gw_exc.L2GatewayNotFound(gateway_id=l2_gateway_id)
320 devices = l2gw['devices']
321 rec_dict = {}
322 for device in devices:
323 device_name = device['device_name']
324 dev_db = db.get_physical_switch_by_name(context, device_name)
325 if not dev_db:
326 raise l2gw_exc.L2GatewayDeviceNotFound(device_id=device_name)
327 rec_dict['physical_switch_id'] = dev_db['uuid']
328 rec_dict['ovsdb_identifier'] = dev_db['ovsdb_identifier']
329 status = dev_db.get('switch_fault_status')
330 if status and status != constants.SWITCH_FAULT_STATUS_UP:
331 raise l2gw_exc.L2GatewayPhysicalSwitchFaultStatus(
332 device_name=device_name, fault_status=status)
333 for interface_list in device['interfaces']:
334 int_name = interface_list.get('name')
335 rec_dict['interface_name'] = int_name
336 port_db = db.get_physical_port_by_name_and_ps(context,
337 rec_dict)
338 if not port_db:
339 raise l2gw_exc.L2GatewayInterfaceNotFound(
340 interface_id=int_name)
341
342 port_status = port_db['port_fault_status']
343 if (port_status and port_status !=
344 constants.PORT_FAULT_STATUS_UP):
345 raise l2gw_exc.L2GatewayPhysicalPortFaultStatus(
346 int_name=int_name, device_name=device_name,
347 fault_status=port_status)
348
349 def _validate_gateway_for_update(self, context, gw):
350 LOG.debug("L2gwRpcDriver._validate_gateway_for_update gw=%s",
351 gw)
352 # Note(lajoskatona): If the update is updating other keys than
353 # devices, just return, as the tricky part is updating devices.
354 devices = gw['l2_gateway'].get('devices', [])
355
356 for device in devices:
357 interfaces = device.get('interfaces')
358 device_name = device.get("device_name")
359 for interface in interfaces:
360 interface_name = interface.get('name')
361 physical_switch = db.get_physical_switch_by_name(
362 context, device.get('device_name'))
363 if not physical_switch:
364 raise l2gw_exc.L2GatewayDeviceNotFound(
365 device_id=device_name)
366 ovsdb_identifier = physical_switch.get('ovsdb_identifier')
367 pp_dict = {'interface_name': interface_name,
368 'ovsdb_identifier': ovsdb_identifier,
369 'physical_switch_id': physical_switch.get('uuid')}
370
371 ps_port = db.get_physical_port_by_name_and_ps(context, pp_dict)
372 if not ps_port:
373 raise l2gw_exc.L2GatewayPhysicalPortNotFound(
374 int_name=interface_name,
375 device_name=device_name)
376
377 def _validate_connection(self, context, gw_connection):
378 seg_id = gw_connection.get('segmentation_id', None)
379 l2_gw_id = gw_connection.get('l2_gateway_id')
380 self._check_port_fault_status_and_switch_fault_status(context,
381 l2_gw_id)
382 check_vlan = (
383 self.service_plugin._is_vlan_configured_on_any_interface_for_l2gw(
384 context, l2_gw_id))
385 nw_map = {}
386 network_id = gw_connection.get(constants.NETWORK_ID)
387 nw_map[constants.NETWORK_ID] = network_id
388 nw_map['l2_gateway_id'] = l2_gw_id
389 if seg_id:
390 nw_map[constants.SEG_ID] = gw_connection.get(constants.SEG_ID)
391 if not self.service_plugin._get_network(context, network_id):
392 raise exceptions.NetworkNotFound(net_id=network_id)
393 if self.service_plugin._retrieve_gateway_connections(context,
394 l2_gw_id, nw_map):
395 raise l2gw_exc.L2GatewayConnectionExists(mapping=nw_map,
396 gateway_id=l2_gw_id)
397 l2gw_validators.validate_network_mapping_list(nw_map, check_vlan)
398 gw_db = self.service_plugin._get_l2_gateway(context, l2_gw_id)
399 tenant_id = self.service_plugin._get_tenant_id_for_create(
400 context, gw_db)
401 l2gw_connection = self.service_plugin.get_l2_gateway_connections(
402 context, filters={'network_id': [network_id],
403 'tenant_id': [tenant_id],
404 'l2_gateway_id': [l2_gw_id]})
405 if l2gw_connection:
406 raise l2gw_exc.L2GatewayConnectionExists(mapping=nw_map,
407 gateway_id=l2_gw_id)
408
409 def _process_port_list(self, context, device,
410 gw_connection, method,
411 gw_connection_ovsdb_set=None):
412 port_dicts = []
413 port_dict = {}
414 logical_switch_uuid = None
415 seg_id = gw_connection.get('segmentation_id', None)
416 interfaces = self.service_plugin.get_l2gateway_interfaces_by_device_id(
417 context, device['id'])
418 LOG.debug("L2gwRpcDriver._process_port_list: ints=%s",
419 interfaces)
420 for interface in interfaces:
421 interface_name = interface.get('interface_name')
422 LOG.debug("L2gwRpcDriver._process_port_list: int_name=%s",
423 interface_name)
424 physical_switch = db.get_physical_switch_by_name(
425 context, device.get('device_name'))
426 if not physical_switch:
427 msg = _('The PHYSICAL SWITCH data not found in the server')
428 raise Exception(msg)
429 ovsdb_identifier = physical_switch.get('ovsdb_identifier')
430 pp_dict = {'interface_name': interface_name,
431 'ovsdb_identifier': ovsdb_identifier,
432 'physical_switch_id': physical_switch.get('uuid'),
433 'logical_switch_name': gw_connection.get(
434 'network_id')}
435 logical_switch = db.get_logical_switch_by_name(
436 context, pp_dict)
437 if method == "DELETE":
438 if not logical_switch:
439 msg = _('The LOGICAL SWITCH data not found in the server')
440 raise Exception(msg)
441 if not (ovsdb_identifier in list(gw_connection_ovsdb_set)):
442 continue
443 if logical_switch:
444 logical_switch_uuid = logical_switch.get('uuid')
445 ps_port = db.get_physical_port_by_name_and_ps(context, pp_dict)
446 if not ps_port:
447 msg = _('The PHYSICAL PORT data not found in the server')
448 raise Exception(msg)
449 pp_dict['uuid'] = ps_port.get('uuid')
450 pp_dict['name'] = ps_port.get('name')
451 LOG.debug("L2gwRpcDriver._process_port_list: pp_dict.name=%s",
452 pp_dict['name'])
453 port_dict = self._generate_port_list(
454 context, method, seg_id, interface, pp_dict,
455 logical_switch_uuid, gw_connection)
456 port_dicts.append(port_dict)
457 return ovsdb_identifier, logical_switch, port_dicts
458
459 def _generate_port_list(self, context, method, seg_id,
460 interface, pp_dict,
461 logical_switch_uuid, gw_connection=None):
462 port_list = []
463 vlan_bindings = db.get_all_vlan_bindings_by_physical_port(
464 context, pp_dict)
465 if method == "CREATE":
466 if not seg_id:
467 vlan_id = interface.get('segmentation_id')
468 else:
469 vlan_id = int(seg_id)
470 vlan_dict = {'vlan': vlan_id,
471 'logical_switch_uuid': logical_switch_uuid}
472 port_list.append(vlan_dict)
473 for vlan_binding in vlan_bindings:
474 if vlan_binding.get('vlan') == vlan_id:
475 msg = _('Duplicate segmentation ID for the interface '
476 'name=%(name)s uuid=%(uuid)s'
477 ) % {'name': pp_dict['name'],
478 'uuid': pp_dict['uuid']}
479 raise l2gw_exc.L2GatewayDuplicateSegmentationID(message=msg
480 )
481 physical_port = self._get_dict(
482 ovsdb_schema.PhysicalPort(
483 uuid=pp_dict.get('uuid'),
484 name=pp_dict.get('interface_name'),
485 phys_switch_id=pp_dict.get('physical_switch_id'),
486 vlan_binding_dicts=None,
487 port_fault_status=None))
488 physical_port['vlan_bindings'] = port_list
489 else:
490 vlan_id = gw_connection.get('segmentation_id')
491 if not vlan_id:
492 vlan_id = interface.get('segmentation_id')
493 vlan_dict = {'vlan': vlan_id,
494 'logical_switch_uuid': logical_switch_uuid}
495 port_list.append(vlan_dict)
496 physical_port = self._get_dict(
497 ovsdb_schema.PhysicalPort(
498 uuid=pp_dict.get('uuid'),
499 name=pp_dict.get('interface_name'),
500 phys_switch_id=pp_dict.get('physical_switch_id'),
501 vlan_binding_dicts=None,
502 port_fault_status=None))
503 physical_port['vlan_bindings'] = port_list
504 return physical_port
505
506 def _get_ip_details(self, context, port):
507 host = port[portbindings.HOST_ID]
508 if (not host and
509 (port['device_owner'] == n_const.DEVICE_OWNER_DVR_INTERFACE)):
510 return self._get_l3_dvr_agent_details(context, port)
511 agent = self._get_agent_details(context, host)
512 conf_dict = agent.get("configurations")
513 dst_ip = conf_dict.get("tunneling_ip")
514 fixed_ip_list = port.get('fixed_ips')
515 fixed_ip_list = fixed_ip_list[0]
516 return dst_ip, fixed_ip_list.get('ip_address')
517
518 def _get_network_details(self, context, network_id):
519 network = self.service_plugin._core_plugin.get_network(context,
520 network_id)
521 return network
522
523 def _get_port_details(self, context, network_id):
524 ports = self.service_plugin._core_plugin.get_ports(
525 context, filters={'network_id': [network_id]})
526 return ports
527
528 def _get_agent_details(self, context, host):
529 l2_agent = None
530 agents = self.service_plugin._core_plugin.get_agents(
531 context, filters={'host': [host]})
532 for agent in agents:
533 agent_tunnel_type = agent['configurations'].get('tunnel_types', [])
534 if constants.VXLAN in agent_tunnel_type:
535 l2_agent = agent
536 break
537 if not l2_agent:
538 raise l2gw_exc.L2AgentNotFoundByHost(
539 host=host)
540 return l2_agent
541
542 def _get_l3_dvr_agent_details(self, context, port):
543 """Getting host IP for router port in DVR mode
544
545 in case of DVR, the router port will not have host information as
546 there is router in each Compute Node and in the Network Node.
547 Here we look for the L3 Agent in the Network Node, get its hostname and
548 resolve its hostname to IP address to be used as destination IP.
549 """
550 endpoints = self.type_manager.drivers.get('vxlan').obj.get_endpoints()
551 agents = self.service_plugin._core_plugin.get_agents(
552 context,
553 filters={
554 'agent_type': [n_const.AGENT_TYPE_L3],
555 'alive': ['true']
556 })
557 for agent in agents:
558 conf_dict = agent.get("configurations")
559 if conf_dict.get("agent_mode") == n_const.L3_AGENT_MODE_DVR_SNAT:
560 hostname = agent.get('host')
561 for endpoint in endpoints:
562 if endpoint.get('host') == hostname:
563 dst_ip = endpoint.get('ip_address')
564 fixed_ip_list = port.get('fixed_ips')
565 fixed_ip = fixed_ip_list[0].get('ip_address')
566 LOG.debug(
567 'Adding DVR dst_ip: %s, fixed_ip: %s',
568 dst_ip,
569 fixed_ip
570 )
571 return dst_ip, fixed_ip
572 raise l2gw_exc.DvrAgentHostnameNotFound(host=hostname)
573 raise l2gw_exc.L3DvrAgentNotFound()
574
575 def _get_logical_switch_dict(self, context, logical_switch, gw_connection):
576 if logical_switch:
577 uuid = logical_switch.get('uuid')
578 else:
579 uuid = None
580 network_id = gw_connection.get('network_id')
581 ls_dict = {'uuid': uuid,
582 'name': network_id}
583 network = self._get_network_details(context,
584 network_id)
585 ls_dict['description'] = network.get('name')
586 logical_segments = network.get('segments')
587 if logical_segments:
588 vxlan_seg_id = None
589 for seg in logical_segments:
590 if seg.get('provider:network_type') == constants.VXLAN:
591 if vxlan_seg_id:
592 raise l2gw_exc.MultipleVxlanSegmentsFound(
593 network_id=network_id)
594 vxlan_seg_id = seg.get('provider:segmentation_id')
595 ls_dict['key'] = vxlan_seg_id
596 if not vxlan_seg_id:
597 raise l2gw_exc.VxlanSegmentationIDNotFound(
598 network_id=network_id)
599 elif network.get('provider:network_type') == constants.VXLAN:
600 ls_dict['key'] = network.get('provider:segmentation_id')
601 else:
602 raise l2gw_exc.VxlanSegmentationIDNotFound(network_id=network_id)
603 return ls_dict
604
605 def _get_physical_locator_dict(self, dst_ip,
606 uuid=None, macs=None,
607 ovsdb_identifier=None):
608 pl_dict = {'uuid': uuid,
609 'dst_ip': dst_ip,
610 'ovsdb_identifier': ovsdb_identifier}
611 if macs:
612 pl_dict['macs'] = macs
613 else:
614 pl_dict['macs'] = []
615 return pl_dict
616
617 def _get_locator_list(self, context, dst_ip, ovsdb_identifier,
618 mac_list, locator_list):
619 locator_uuid = None
620 locator_dict = self._get_physical_locator_dict(
621 dst_ip, None, None, ovsdb_identifier)
622 locator = db.get_physical_locator_by_dst_ip(
623 context, locator_dict)
624 if locator:
625 locator_uuid = locator.get('uuid')
626 for locator in locator_list:
627 if locator.get('dst_ip') == dst_ip:
628 (locator.get('macs')).extend(mac_list)
629 return locator_list
630 pl_dict = self._get_physical_locator_dict(
631 dst_ip, locator_uuid, mac_list)
632 locator_list.append(pl_dict)
633 return locator_list
634
635 def create_l2_gateway(self, context, l2_gateway):
636 pass
637
638 def create_l2_gateway_postcommit(self, context, l2_gateway):
639 pass
640
641 def update_l2_gateway(self, context, l2_gateway_id, l2_gateway):
642 """Check the port list for update"""
643 self.service_plugin._admin_check(context, 'UPDATE')
644 self._validate_gateway_for_update(context, l2_gateway)
645 self.port_dict_before_update = []
646 # get l2 gateway devices
647 l2gateway_devices = (
648 self.service_plugin.get_l2gateway_devices_by_gateway_id(
649 context, l2_gateway_id))
650 # get l2 gateway connections
651 gw_connections = self.service_plugin._get_l2_gateway_connections(
652 context)
653
654 for gw_connection in gw_connections:
655 for device in l2gateway_devices:
656 ovsdb_identifier, logical_switch, port_dict \
657 = (self._process_port_list(context, device,
658 gw_connection, "UPDATE"))
659 self.port_dict_before_update.extend(port_dict)
660
661 def update_l2_gateway_postcommit(self, context, l2_gateway):
662 """Process the call from the CLI and trigger the RPC,
663
664 to update the connection of the gateway.
665 """
666 self.service_plugin._admin_check(context, 'UPDATE')
667
668 # get l2 gateway devices
669 l2gateway_devices = (
670 self.service_plugin.get_l2gateway_devices_by_gateway_id(
671 context, l2_gateway['id']))
672 # get l2 gateway connections
673 gw_connections = self.service_plugin._get_l2_gateway_connections(
674 context)
675
676 for gw_connection in gw_connections:
677 u_mac_dict = {}
678 mac_dict = {}
679 for device in l2gateway_devices:
680 locator_list = []
681 ovsdb_identifier, logical_switch, port_dict = (
682 self._process_port_list(context, device,
683 gw_connection, "UPDATE"))
684 ls_dict = self._get_logical_switch_dict(
685 context, logical_switch, gw_connection)
686 port_dict_before_update_con = \
687 [port for port in self.port_dict_before_update
688 if port['vlan_bindings'][0]['logical_switch_uuid'] ==
689 logical_switch['uuid']]
690 port_dict_add = \
691 [port for port in port_dict
692 if port not in port_dict_before_update_con]
693 port_dict_delete = \
694 [port for port in port_dict_before_update_con
695 if port not in port_dict]
696 if port_dict_add:
697 ports = self._get_port_details(
698 context, gw_connection.get('network_id'))
699 LOG.debug("L2gwRpcDriver.update_l2_gw: ports=%s", ports)
700 for port in ports:
701 mac_list = []
702 if port['device_owner']:
703 dst_ip, ip_address = self._get_ip_details(context,
704 port)
705 mac_ip_pairs = []
706 if isinstance(
707 port.get("allowed_address_pairs"), list):
708 for address_pair in \
709 port['allowed_address_pairs']:
710 mac = address_pair['mac_address']
711 mac_ip_pairs.append(
712 (mac, address_pair['ip_address']))
713 mac_ip_pairs.append((port.get('mac_address'),
714 ip_address))
715
716 for mac, ip in mac_ip_pairs:
717 mac_remote = self._get_dict(
718 ovsdb_schema.UcastMacsRemote(
719 uuid=None,
720 mac=mac,
721 logical_switch_id=None,
722 physical_locator_id=None,
723 ip_address=ip))
724 if logical_switch:
725 u_mac_dict['mac'] = mac
726 u_mac_dict['ovsdb_identifier'] = \
727 ovsdb_identifier
728 u_mac_dict['logical_switch_uuid'] = (
729 logical_switch.get('uuid'))
730 ucast_mac_remote = (
731 db.get_ucast_mac_remote_by_mac_and_ls(
732 context, u_mac_dict))
733 if not ucast_mac_remote:
734 mac_list.append(mac_remote)
735 else:
736 mac_list.append(mac_remote)
737 locator_list = self._get_locator_list(
738 context, dst_ip, ovsdb_identifier, mac_list,
739 locator_list)
740 for locator in locator_list:
741 mac_dict[locator.get('dst_ip')] = locator.pop('macs')
742 locator.pop('ovsdb_identifier')
743 self.agent_rpc.update_connection_to_gateway(
744 context, ovsdb_identifier, ls_dict, locator_list,
745 mac_dict, port_dict_add, 'CREATE')
746
747 if port_dict_delete:
748 self.agent_rpc.update_connection_to_gateway(
749 context, ovsdb_identifier, ls_dict, locator_list,
750 mac_dict, port_dict_delete, 'DELETE')
751
752 def delete_l2_gateway(self, context, id):
753 """delete the l2 gateway by id."""
754 self.l2gateway_db._admin_check(context, 'DELETE')
755 with db_api.CONTEXT_WRITER.using(context):
756 gw_db = self.l2gateway_db._get_l2_gateway(context, id)
757 if gw_db is None:
758 raise l2gw_exc.L2GatewayNotFound(gateway_id=id)
759 if gw_db.network_connections:
760 raise l2gw_exc.L2GatewayInUse(gateway_id=id)
761 return gw_db
762
763 def delete_l2_gateway_postcommit(self, context, l2_gateway_id):
764 pass
765
766 def create_l2_gateway_connection(self, context, l2_gateway_connection):
767 """Process the call from the CLI and trigger the RPC,
768
769 to update the connection to the gateway.
770 """
771 u_mac_dict = {}
772 ls_dict = {}
773 mac_dict = {}
774 self.service_plugin._admin_check(context, 'CREATE')
775 gw_connection = l2_gateway_connection.get('l2_gateway_connection')
776 # validate connection
777 self._validate_connection(context, gw_connection)
778 # get l2 gateway devices
779 l2gateway_devices = (
780 self.service_plugin.get_l2gateway_devices_by_gateway_id(
781 context, gw_connection.get('l2_gateway_id')))
782 for device in l2gateway_devices:
783 locator_list = []
784 ovsdb_identifier, logical_switch, port_dict = (
785 self._process_port_list(context, device,
786 gw_connection, "CREATE"))
787 ls_dict = self._get_logical_switch_dict(
788 context, logical_switch, gw_connection)
789 ports = self._get_port_details(context,
790 gw_connection.get('network_id'))
791 for port in ports:
792 mac_list = []
793 if port['device_owner']:
794 dst_ip, ip_address = self._get_ip_details(context, port)
795 mac_ip_pairs = []
796 if isinstance(port.get("allowed_address_pairs"), list):
797 for address_pair in port['allowed_address_pairs']:
798 mac = address_pair['mac_address']
799 mac_ip_pairs.append((mac,
800 address_pair['ip_address']))
801 mac_ip_pairs.append((port.get('mac_address'), ip_address))
802
803 for mac, ip in mac_ip_pairs:
804 mac_remote = self._get_dict(
805 ovsdb_schema.UcastMacsRemote(
806 uuid=None,
807 mac=mac,
808 logical_switch_id=None,
809 physical_locator_id=None,
810 ip_address=ip))
811 if logical_switch:
812 u_mac_dict['mac'] = mac
813 u_mac_dict['ovsdb_identifier'] = ovsdb_identifier
814 u_mac_dict['logical_switch_uuid'] = (
815 logical_switch.get('uuid'))
816 ucast_mac_remote = (
817 db.get_ucast_mac_remote_by_mac_and_ls(
818 context, u_mac_dict))
819 if not ucast_mac_remote:
820 mac_list.append(mac_remote)
821 else:
822 mac_list.append(mac_remote)
823 locator_list = self._get_locator_list(
824 context, dst_ip, ovsdb_identifier, mac_list,
825 locator_list)
826 for locator in locator_list:
827 mac_dict[locator.get('dst_ip')] = locator.pop('macs')
828 locator.pop('ovsdb_identifier')
829 self.agent_rpc.update_connection_to_gateway(
830 context, ovsdb_identifier, ls_dict, locator_list, mac_dict,
831 port_dict, 'CREATE')
832
833 def _get_identifer_list(self, context, gw_connection):
834 identifier_list = []
835 l2gateway_devices = (
836 self.service_plugin.get_l2gateway_devices_by_gateway_id(
837 context, gw_connection.get('l2_gateway_id')))
838 for device in l2gateway_devices:
839 physical_switch = db.get_physical_switch_by_name(
840 context, device.get('device_name'))
841 if not physical_switch:
842 msg = _('The PHYSICAL SWITCH data not found in the server')
843 raise Exception(msg)
844 ovsdb_identifier = physical_switch.get('ovsdb_identifier')
845 identifier_list.append(ovsdb_identifier)
846 return set(identifier_list)
847
848 def _get_set_of_ovsdb_ids(self, context, gw_connection,
849 gw_connection_ovsdb_set):
850 ovsdb_id_set = set()
851 network_id = gw_connection.get('network_id')
852 l2gateway_connections = self.service_plugin.get_l2_gateway_connections(
853 context, filters={'network_id': [network_id]})
854 for l2gatewayconnection in l2gateway_connections:
855 if l2gatewayconnection['id'] == gw_connection['id']:
856 l2gateway_connections.remove(l2gatewayconnection)
857 else:
858 ovsdb_id_set.union(self._get_identifer_list(
859 context, l2gatewayconnection))
860 ovsdb_id_set = gw_connection_ovsdb_set.difference(ovsdb_id_set)
861 return ovsdb_id_set
862
863 def _remove_vm_macs(self, context, network_id, ovsdb_id_set):
864 ports = self._get_port_details(context, network_id)
865 if ports:
866 for ovsdb_id in list(ovsdb_id_set):
867 for port in ports:
868 port['ovsdb_identifier'] = ovsdb_id
869 self.delete_port_mac(context, ports)
870
871 def create_l2_gateway_connection_postcommit(self, context,
872 l2_gateway_connection):
873 pass
874
875 def delete_l2_gateway_connection(self, context, l2_gateway_connection):
876 """Process the call from the CLI and trigger the RPC,
877
878 to update the connection from the gateway.
879 """
880 locator_list = []
881 ls_dict = {}
882 mac_dict = {}
883 self.service_plugin._admin_check(context, 'DELETE')
884 gw_connection = self.service_plugin.get_l2_gateway_connection(
885 context, l2_gateway_connection)
886 if not gw_connection:
887 raise l2gw_exc.L2GatewayConnectionNotFound(l2_gateway_connection)
888 gw_connection_ovsdb_set = self._get_identifer_list(context,
889 gw_connection)
890 network_id = gw_connection.get('network_id')
891 # get list of ovsdb_ids
892 ovsdb_id_set = self._get_set_of_ovsdb_ids(context,
893 gw_connection,
894 gw_connection_ovsdb_set)
895 # call delete connection RPC to gw_connection_ovsdb_set
896 l2gateway_devices = (
897 self.service_plugin.get_l2gateway_devices_by_gateway_id(
898 context, gw_connection.get('l2_gateway_id')))
899 for device in l2gateway_devices:
900 port_dict = {}
901 (ovsdb_identifier, logical_switch, port_dict) = (
902 self._process_port_list(
903 context, device, gw_connection,
904 "DELETE", gw_connection_ovsdb_set))
905 self.agent_rpc.update_connection_to_gateway(
906 context, ovsdb_identifier, ls_dict, locator_list, mac_dict,
907 port_dict, 'DELETE')
908 # call delete vif_from_gateway for ovsdb_id_set
909 self._remove_vm_macs(context, network_id, ovsdb_id_set)
910
911 def delete_l2_gateway_connection_postcommit(self, context,
912 l2_gateway_connection):
913 pass