Debian Codegraph @

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

raw
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 from contextlib import contextmanager
17 import os.path
18
19 from neutron_lib import context as ctx
20 from oslo_config import cfg
21 from oslo_log import log as logging
22 from oslo_service import loopingcall
23
24 from networking_l2gw._i18n import _
25 from networking_l2gw.services.l2gateway.agent import base_agent_manager
26 from networking_l2gw.services.l2gateway.agent import l2gateway_config
27 from networking_l2gw.services.l2gateway.agent.ovsdb import ovsdb_common_class
28 from networking_l2gw.services.l2gateway.agent.ovsdb import ovsdb_monitor
29 from networking_l2gw.services.l2gateway.agent.ovsdb import ovsdb_writer
30 from networking_l2gw.services.l2gateway.common import constants as n_const
31
32 LOG = logging.getLogger(__name__)
33
34
35 class OVSDBManager(base_agent_manager.BaseAgentManager):
36 """OVSDB variant of agent manager.
37
38 Listens to state change notifications from OVSDB servers and
39 handles transactions (RPCs) destined to OVSDB servers.
40 """
41 def __init__(self, conf=None):
42 super().__init__(conf)
43 self._extract_ovsdb_config(conf)
44 self.enable_manager = cfg.CONF.ovsdb.enable_manager
45 periodic_interval = self.conf.ovsdb.periodic_interval
46 if self.enable_manager:
47 self.ovsdb_fd = None
48 self._sock_open_connection()
49 self.looping_task_ovsdb_states = (
50 loopingcall.FixedIntervalLoopingCall(self._send_ovsdb_states))
51 self.looping_task_ovsdb_states.start(interval=periodic_interval)
52 else:
53 self.looping_task = loopingcall.FixedIntervalLoopingCall(
54 self._connect_to_ovsdb_server)
55 self.looping_task.start(interval=periodic_interval)
56
57 def _extract_ovsdb_config(self, conf):
58 self.conf = conf or cfg.CONF
59 ovsdb_hosts = self.conf.ovsdb.ovsdb_hosts
60 if ovsdb_hosts != '':
61 ovsdb_hosts = ovsdb_hosts.split(',')
62 for host in ovsdb_hosts:
63 self._process_ovsdb_host(host)
64 # Ensure that max_connection_retries is less than
65 # the periodic interval.
66 if (self.conf.ovsdb.max_connection_retries >=
67 self.conf.ovsdb.periodic_interval):
68 raise SystemExit(_("max_connection_retries should be "
69 "less than periodic interval"))
70
71 def _process_ovsdb_host(self, host):
72 try:
73 host_splits = str(host).split(':')
74 ovsdb_identifier = str(host_splits[0]).strip()
75 ovsdb_conf = {n_const.OVSDB_IDENTIFIER: ovsdb_identifier,
76 'ovsdb_ip': str(host_splits[1]).strip(),
77 'ovsdb_port': str(host_splits[2]).strip()}
78 priv_key_path = self.conf.ovsdb.l2_gw_agent_priv_key_base_path
79 cert_path = self.conf.ovsdb.l2_gw_agent_cert_base_path
80 ca_cert_path = self.conf.ovsdb.l2_gw_agent_ca_cert_base_path
81 use_ssl = priv_key_path and cert_path and ca_cert_path
82 if use_ssl:
83 LOG.debug("ssl is enabled with priv_key_path %s, cert_path "
84 "%s, ca_cert_path %s", priv_key_path,
85 cert_path, ca_cert_path)
86 priv_key_file = priv_key_path + "/" + ovsdb_identifier + ".key"
87 cert_file = cert_path + "/" + ovsdb_identifier + ".cert"
88 ca_cert_file = (ca_cert_path + "/" + ovsdb_identifier +
89 ".ca_cert")
90 is_priv_key = os.path.isfile(priv_key_file)
91 is_cert_file = os.path.isfile(cert_file)
92 is_ca_cert_file = os.path.isfile(ca_cert_file)
93 if not is_priv_key:
94 LOG.exception("Could not find private key in "
95 "%(path)s dir, expecting in the "
96 "file name %(file)s ",
97 {'path': priv_key_path,
98 'file': ovsdb_identifier + ".key"})
99 if not is_cert_file:
100 LOG.exception("Could not find cert in %(path)s dir, "
101 "expecting in the file name %(file)s",
102 {'path': cert_path,
103 'file': ovsdb_identifier + ".cert"})
104 if not is_ca_cert_file:
105 LOG.exception("Could not find cacert in %(path)s "
106 "dir, expecting in the file name "
107 "%(file)s",
108 {'path': ca_cert_path,
109 'file': ovsdb_identifier + ".ca_cert"})
110 ssl_ovsdb = {'use_ssl': True,
111 'private_key':
112 "/".join([str(priv_key_path),
113 '.'.join([str(host_splits[0]).
114 strip(),
115 'key'])]),
116 'certificate':
117 "/".join([str(cert_path),
118 '.'.join([str(host_splits[0]).
119 strip(), 'cert'])]),
120 'ca_cert':
121 "/".join([str(ca_cert_path),
122 '.'.join([str(host_splits[0]).
123 strip(), 'ca_cert'])])
124 }
125 ovsdb_conf.update(ssl_ovsdb)
126 LOG.debug("ovsdb_conf = %s", str(ovsdb_conf))
127 gateway = l2gateway_config.L2GatewayConfig(ovsdb_conf)
128 self.gateways[ovsdb_identifier] = gateway
129 except Exception as ex:
130 LOG.exception("Exception %(ex)s occurred while processing "
131 "host %(host)s", {'ex': ex, 'host': host})
132
133 def _connect_to_ovsdb_server(self):
134 """Initializes the connection to the OVSDB servers."""
135 ovsdb_states = {}
136 if self.gateways and self.l2gw_agent_type == n_const.MONITOR:
137 for key in self.gateways.keys():
138 gateway = self.gateways.get(key)
139 ovsdb_fd = gateway.ovsdb_fd
140 if not (ovsdb_fd and ovsdb_fd.connected):
141 LOG.debug("OVSDB server %s is disconnected",
142 str(gateway.ovsdb_ip))
143 try:
144 ovsdb_fd = ovsdb_monitor.OVSDBMonitor(
145 self.conf.ovsdb,
146 gateway,
147 self.agent_to_plugin_rpc)
148 except Exception:
149 ovsdb_states[key] = 'disconnected'
150 # Log a warning and continue so that it can be
151 # retried in the next iteration.
152 LOG.error("OVSDB server %s is not "
153 "reachable", gateway.ovsdb_ip)
154 # Continue processing the next element in the list.
155 continue
156 gateway.ovsdb_fd = ovsdb_fd
157 try:
158 ovsdb_fd.set_monitor_response_handler()
159 except Exception:
160 raise SystemExit(Exception.message)
161 if ovsdb_fd and ovsdb_fd.connected:
162 ovsdb_states[key] = 'connected'
163 LOG.debug("Calling notify_ovsdb_states")
164 self.plugin_rpc.notify_ovsdb_states(ctx.get_admin_context(),
165 ovsdb_states)
166
167 def handle_report_state_failure(self):
168 # Not able to deliver the heart beats to the Neutron server.
169 # Let us change the mode to Transact so that when the
170 # Neutron server is connected back, it will make an agent
171 # Monitor agent and OVSDB data will be read entirely. This way,
172 # the OVSDB data in Neutron database will be the latest and in
173 # sync with that in the OVSDB server tables.
174 if self.l2gw_agent_type == n_const.MONITOR:
175 self.l2gw_agent_type = ''
176 self.agent_state.get('configurations')[n_const.L2GW_AGENT_TYPE
177 ] = self.l2gw_agent_type
178 if not self.enable_manager:
179 self._stop_looping_task()
180 self._disconnect_all_ovsdb_servers()
181
182 def _send_ovsdb_states(self):
183 self.plugin_rpc.notify_ovsdb_states(ctx.get_admin_context(),
184 self.ovsdb_fd.ovsdb_fd_states)
185
186 def _disconnect_all_ovsdb_servers(self):
187 if self.gateways:
188 for key, gateway in self.gateways.items():
189 ovsdb_fd = gateway.ovsdb_fd
190 if ovsdb_fd and ovsdb_fd.connected:
191 gateway.ovsdb_fd.disconnect()
192
193 def set_monitor_agent(self, context, hostname):
194 """Handle RPC call from plugin to update agent type.
195
196 RPC call from the plugin to accept that I am a monitoring
197 or a transact agent. This is a fanout cast message
198 """
199 super().set_monitor_agent(context, hostname)
200
201 # If set to Monitor, then let us start monitoring the OVSDB
202 # servers without any further delay.
203 if ((self.l2gw_agent_type == n_const.MONITOR) and not (
204 self.enable_manager)):
205 self._start_looping_task()
206 elif self.enable_manager and self.l2gw_agent_type == n_const.MONITOR:
207 if self.ovsdb_fd is None:
208 self._sock_open_connection()
209 elif ((self.ovsdb_fd) and not (
210 self.ovsdb_fd.check_monitor_table_thread) and (
211 self.ovsdb_fd.check_sock_rcv)):
212 for key in self.ovsdb_fd.ovsdb_dicts.keys():
213 if key in self.ovsdb_fd.ovsdb_conn_list:
214 self.ovsdb_fd._spawn_monitor_table_thread(key)
215 self._start_looping_task_ovsdb_states()
216 elif ((self.enable_manager) and not (
217 self.l2gw_agent_type == n_const.MONITOR)):
218 self._stop_looping_task_ovsdb_states()
219 elif (not (self.l2gw_agent_type == n_const.MONITOR) and not (
220 self.enable_manager)):
221 # Otherwise, stop monitoring the OVSDB servers
222 # and close the open connections if any.
223 self._stop_looping_task()
224 self._disconnect_all_ovsdb_servers()
225
226 def _stop_looping_task_ovsdb_states(self):
227 if self.looping_task_ovsdb_states._running:
228 self.looping_task_ovsdb_states.stop()
229
230 def _start_looping_task_ovsdb_states(self):
231 if not self.looping_task_ovsdb_states._running:
232 self.looping_task_ovsdb_states.start(
233 interval=self.conf.ovsdb.periodic_interval)
234
235 def _stop_looping_task(self):
236 if self.looping_task._running:
237 self.looping_task.stop()
238
239 def _start_looping_task(self):
240 if not self.looping_task._running:
241 self.looping_task.start(interval=self.conf.ovsdb.
242 periodic_interval)
243
244 def _sock_open_connection(self):
245 gateway = ''
246 if self.ovsdb_fd is None:
247 self.ovsdb_fd = ovsdb_common_class.OVSDB_commom_class(
248 self.conf.ovsdb,
249 gateway,
250 self.agent_to_plugin_rpc, self)
251
252 @contextmanager
253 def _open_connection(self, ovsdb_identifier):
254 ovsdb_fd = None
255 gateway = self.gateways.get(ovsdb_identifier)
256 try:
257 ovsdb_fd = ovsdb_writer.OVSDBWriter(self.conf.ovsdb,
258 gateway)
259 yield ovsdb_fd
260 finally:
261 if ovsdb_fd:
262 ovsdb_fd.disconnect()
263
264 def _is_valid_request(self, ovsdb_identifier):
265 val_req = ovsdb_identifier and ovsdb_identifier in self.gateways.keys()
266 if not val_req:
267 LOG.warning(n_const.ERROR_DICT
268 [n_const.L2GW_INVALID_OVSDB_IDENTIFIER])
269 return val_req
270
271 def delete_network(self, context, ovsdb_identifier, logical_switch_uuid):
272 """Handle RPC cast from plugin to delete a network."""
273 if self.enable_manager and self.l2gw_agent_type == n_const.MONITOR:
274 self.ovsdb_fd.delete_logical_switch(logical_switch_uuid,
275 ovsdb_identifier, False)
276 elif ((self.enable_manager) and (
277 not self.l2gw_agent_type == n_const.MONITOR)):
278 self._sock_open_connection()
279 if ovsdb_identifier in self.ovsdb_fd.ovsdb_conn_list:
280 self.ovsdb_fd.delete_logical_switch(logical_switch_uuid,
281 ovsdb_identifier,
282 False)
283 elif not self.enable_manager:
284 if self._is_valid_request(ovsdb_identifier):
285 with self._open_connection(ovsdb_identifier) as ovsdb_fd:
286 ovsdb_fd.delete_logical_switch(logical_switch_uuid,
287 ovsdb_identifier)
288
289 def add_vif_to_gateway(self, context, ovsdb_identifier,
290 logical_switch_dict, locator_dict,
291 mac_dict):
292 """Handle RPC cast from plugin to insert neutron port MACs."""
293 if self.enable_manager and self.l2gw_agent_type == n_const.MONITOR:
294 self.ovsdb_fd.insert_ucast_macs_remote(logical_switch_dict,
295 locator_dict,
296 mac_dict, ovsdb_identifier,
297 False)
298 elif ((self.enable_manager) and (
299 not self.l2gw_agent_type == n_const.MONITOR)):
300 self._sock_open_connection()
301 if ovsdb_identifier in self.ovsdb_fd.ovsdb_conn_list:
302 self.ovsdb_fd.insert_ucast_macs_remote(
303 logical_switch_dict,
304 locator_dict,
305 mac_dict, ovsdb_identifier, False)
306 elif not self.enable_manager:
307 if self._is_valid_request(ovsdb_identifier):
308 with self._open_connection(ovsdb_identifier) as ovsdb_fd:
309 ovsdb_fd.insert_ucast_macs_remote(logical_switch_dict,
310 locator_dict,
311 mac_dict,
312 ovsdb_identifier)
313
314 def delete_vif_from_gateway(self, context, ovsdb_identifier,
315 logical_switch_uuid, mac):
316 """Handle RPC cast from plugin to delete neutron port MACs."""
317 if self.enable_manager and self.l2gw_agent_type == n_const.MONITOR:
318 self.ovsdb_fd.delete_ucast_macs_remote(logical_switch_uuid, mac,
319 ovsdb_identifier,
320 False)
321 elif ((self.enable_manager) and (
322 not self.l2gw_agent_type == n_const.MONITOR)):
323 self._sock_open_connection()
324 if ovsdb_identifier in self.ovsdb_fd.ovsdb_conn_list:
325 self.ovsdb_fd.delete_ucast_macs_remote(
326 logical_switch_uuid,
327 mac, ovsdb_identifier, False)
328 elif not self.enable_manager:
329 if self._is_valid_request(ovsdb_identifier):
330 with self._open_connection(ovsdb_identifier) as ovsdb_fd:
331 ovsdb_fd.delete_ucast_macs_remote(
332 logical_switch_uuid, mac, ovsdb_identifier)
333
334 def update_vif_to_gateway(self, context, ovsdb_identifier,
335 locator_dict, mac_dict):
336 """Handle RPC cast from plugin to update neutron port MACs.
337
338 for VM migration.
339 """
340 if self.enable_manager and self.l2gw_agent_type == n_const.MONITOR:
341 self.ovsdb_fd.update_ucast_macs_remote(locator_dict,
342 mac_dict, ovsdb_identifier,
343 False)
344 elif ((self.enable_manager) and (
345 not self.l2gw_agent_type == n_const.MONITOR)):
346 self._sock_open_connection()
347 if ovsdb_identifier in self.ovsdb_fd.ovsdb_conn_list:
348 self.ovsdb_fd.update_ucast_macs_remote(locator_dict,
349 mac_dict,
350 ovsdb_identifier, False)
351 elif not self.enable_manager:
352 if self._is_valid_request(ovsdb_identifier):
353 with self._open_connection(ovsdb_identifier) as ovsdb_fd:
354 ovsdb_fd.update_ucast_macs_remote(
355 locator_dict, mac_dict, ovsdb_identifier)
356
357 def update_connection_to_gateway(self, context, ovsdb_identifier,
358 logical_switch_dict, locator_dicts,
359 mac_dicts, port_dicts, op_method):
360 """Handle RPC cast from plugin.
361
362 Handle RPC cast from plugin to connect/disconnect a network
363 to/from an L2 gateway.
364 """
365 if self.enable_manager and self.l2gw_agent_type == n_const.MONITOR:
366 self.ovsdb_fd.update_connection_to_gateway(logical_switch_dict,
367 locator_dicts,
368 mac_dicts,
369 port_dicts,
370 ovsdb_identifier,
371 op_method,
372 False)
373 elif ((self.enable_manager) and (
374 not self.l2gw_agent_type == n_const.MONITOR)):
375 self._sock_open_connection()
376 if ovsdb_identifier in self.ovsdb_fd.ovsdb_conn_list:
377 self.ovsdb_fd.update_connection_to_gateway(
378 logical_switch_dict,
379 locator_dicts,
380 mac_dicts,
381 port_dicts, ovsdb_identifier, op_method, False)
382 elif not self.enable_manager:
383 if self._is_valid_request(ovsdb_identifier):
384 with self._open_connection(ovsdb_identifier) as ovsdb_fd:
385 ovsdb_fd.update_connection_to_gateway(logical_switch_dict,
386 locator_dicts,
387 mac_dicts,
388 port_dicts,
389 ovsdb_identifier,
390 op_method)
391
392 def agent_to_plugin_rpc(self, activity, ovsdb_data):
393 self.plugin_rpc.update_ovsdb_changes(ctx.get_admin_context(),
394 activity,
395 ovsdb_data)