Debian Codegraph @

networking_l2gw/services/l2gateway/agent/ovsdb/base_connection.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 import copy
17 import os.path
18 import socket
19 import ssl
20 import threading
21 import time
22
23 from oslo_config import cfg
24 from oslo_log import log as logging
25 from oslo_serialization import jsonutils
26 from oslo_utils import excutils
27
28 from networking_l2gw._i18n import _
29 from networking_l2gw.services.l2gateway.common import constants as n_const
30
31 LOG = logging.getLogger(__name__)
32 OVSDB_UNREACHABLE_MSG = 'Unable to reach OVSDB server %s'
33 OVSDB_CONNECTED_MSG = 'Connected to OVSDB server %s'
34
35
36 class BaseConnection:
37 """Connects to OVSDB server.
38
39 Connects to an ovsdb server with/without SSL
40 on a given host and TCP port.
41 """
42 def __init__(self, conf, gw_config, mgr=None):
43 self.responses = []
44 self.connected = False
45 self.mgr = mgr
46 self.enable_manager = cfg.CONF.ovsdb.enable_manager
47 if self.enable_manager:
48 self.manager_table_listening_port = (
49 cfg.CONF.ovsdb.manager_table_listening_port)
50 self.ip_ovsdb_mapping = self._get_ovsdb_ip_mapping()
51 self.s = None
52 self.check_c_sock = None
53 self.check_sock_rcv = False
54 self.ovsdb_dicts = {}
55 self.ovsdb_fd_states = {}
56 self.ovsdb_conn_list = []
57 sock_thread = threading.Thread(target=self._rcv_socket)
58 sock_thread.daemon = True
59 sock_thread.start()
60 else:
61 self.gw_config = gw_config
62 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
63 if gw_config.use_ssl:
64 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
65 context.load_cert_chain(gw_config.certificate,
66 gw_config.private_key)
67 context.load_verify_locations(gw_config.ca_cert)
68 context.check_hostname = False
69 context.verify_mode = ssl.CERT_REQUIRED
70 self.socket = context.wrap_socket(self.socket)
71 retryCount = 0
72 while True:
73 try:
74 self.socket.connect((str(gw_config.ovsdb_ip),
75 int(gw_config.ovsdb_port)))
76 break
77 except (OSError, TimeoutError):
78 LOG.warning(OVSDB_UNREACHABLE_MSG, gw_config.ovsdb_ip)
79 if retryCount == conf.max_connection_retries:
80 # Retried for max_connection_retries times.
81 # Give up and return so that it can be tried in
82 # the next periodic interval.
83 with excutils.save_and_reraise_exception(reraise=True):
84 LOG.exception("Socket error in connecting to "
85 "the OVSDB server")
86 else:
87 time.sleep(1)
88 retryCount += 1
89
90 # Successfully connected to the socket
91 LOG.debug(OVSDB_CONNECTED_MSG, gw_config.ovsdb_ip)
92 self.connected = True
93
94 def _get_ovsdb_ip_mapping(self):
95 ovsdb_ip_mapping = {}
96 ovsdb_hosts = cfg.CONF.ovsdb.ovsdb_hosts
97 if ovsdb_hosts != '':
98 ovsdb_hosts = ovsdb_hosts.split(',')
99 for host in ovsdb_hosts:
100 host_splits = str(host).split(':')
101 ovsdb_identifier = str(host_splits[0]).strip()
102 ovsdb_ip = str(host_splits[1]).strip()
103 ovsdb_ip_mapping[ovsdb_ip] = ovsdb_identifier
104 return ovsdb_ip_mapping
105
106 def _is_ssl_configured(self, addr, client_sock):
107 priv_key_path = cfg.CONF.ovsdb.l2_gw_agent_priv_key_base_path
108 cert_path = cfg.CONF.ovsdb.l2_gw_agent_cert_base_path
109 ca_cert_path = cfg.CONF.ovsdb.l2_gw_agent_ca_cert_base_path
110 use_ssl = priv_key_path and cert_path and ca_cert_path
111 if use_ssl:
112 LOG.debug("ssl is enabled with priv_key_path %s, cert_path %s, "
113 "ca_cert_path %s", priv_key_path,
114 cert_path, ca_cert_path)
115 if addr in self.ip_ovsdb_mapping.keys():
116 ovsdb_id = self.ip_ovsdb_mapping.get(addr)
117 priv_key_file = priv_key_path + "/" + ovsdb_id + ".key"
118 cert_file = cert_path + "/" + ovsdb_id + ".cert"
119 ca_cert_file = ca_cert_path + "/" + ovsdb_id + ".ca_cert"
120 is_priv_key = os.path.isfile(priv_key_file)
121 is_cert_file = os.path.isfile(cert_file)
122 is_ca_cert_file = os.path.isfile(ca_cert_file)
123 if is_priv_key and is_cert_file and is_ca_cert_file:
124 context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
125 context.load_cert_chain(cert_file, priv_key_file)
126 context.load_verify_locations(ca_cert_file)
127 client_sock = context.wrap_socket(client_sock,
128 server_side=True)
129 else:
130 if not is_priv_key:
131 LOG.error("Could not find private key in"
132 " %(path)s dir, expecting in the "
133 "file name %(file)s ",
134 {'path': priv_key_path,
135 'file': ovsdb_id + ".key"})
136 if not is_cert_file:
137 LOG.error("Could not find cert in %(path)s dir, "
138 "expecting in the file name %(file)s",
139 {'path': cert_path,
140 'file': ovsdb_id + ".cert"})
141 if not is_ca_cert_file:
142 LOG.error("Could not find cacert in %(path)s "
143 "dir, expecting in the file name "
144 "%(file)s",
145 {'path': ca_cert_path,
146 'file': ovsdb_id + ".ca_cert"})
147 else:
148 LOG.error("you have enabled SSL for ovsdb %s, "
149 "expecting the ovsdb identifier and ovsdb IP "
150 "entry in ovsdb_hosts in l2gateway_agent.ini",
151 addr)
152 return client_sock
153
154 def _rcv_socket(self):
155 # Create a socket object.
156 self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
157 host = '' # Get local machine name
158 port = self.manager_table_listening_port
159 # configured port for your service.
160 self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
161 self.s.bind((host, port)) # Bind to the port
162 self.s.listen(5) # Now wait for client connection.
163 while True:
164 # Establish connection with client.
165 c_sock, ip_addr = self.s.accept()
166 addr = ip_addr[0]
167 c_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
168 c_sock = self._is_ssl_configured(addr, c_sock)
169 LOG.debug("Got connection from %s ", addr)
170 self.connected = True
171 if addr in self.ovsdb_fd_states.keys():
172 del self.ovsdb_fd_states[addr]
173 if addr in self.ovsdb_conn_list:
174 self.ovsdb_conn_list.remove(addr)
175 if addr in self.ovsdb_dicts.keys():
176 if self.ovsdb_dicts.get(addr):
177 self.ovsdb_dicts.get(addr).close()
178 del self.ovsdb_dicts[addr]
179 self.ovsdb_dicts[addr] = c_sock
180 common_s_thread = threading.Thread(
181 target=self._common_sock_rcv_thread,
182 daemon=True,
183 kwargs={'addr': addr})
184 common_s_thread.start()
185 # Now that OVSDB server has sent a socket open request, let us wait
186 # for echo request. After the first echo request, we will send the
187 # "monitor" request to the OVSDB server.
188
189 def _send_monitor_msg_to_ovsdb_connection(self, addr):
190 if self.mgr.l2gw_agent_type == n_const.MONITOR:
191 try:
192 if (self.mgr.ovsdb_fd) and (addr in self.ovsdb_conn_list):
193 self.mgr.ovsdb_fd._spawn_monitor_table_thread(addr)
194 except Exception:
195 LOG.warning("Could not send monitor message to the "
196 "OVSDB server.")
197 self.disconnect(addr)
198
199 def _common_sock_rcv_thread(self, addr):
200 chunks = []
201 lc = rc = 0
202 prev_char = None
203 self.read_on = True
204 check_monitor_msg = True
205 self._echo_response(addr)
206 if self.enable_manager and (addr in self.ovsdb_conn_list):
207 while self.read_on:
208 response = self.ovsdb_dicts.get(addr).recv(n_const.BUFFER_SIZE)
209 self.ovsdb_fd_states[addr] = 'connected'
210 self.check_sock_rcv = True
211 time.sleep(0)
212 if check_monitor_msg:
213 self._send_monitor_msg_to_ovsdb_connection(addr)
214 check_monitor_msg = False
215 if response:
216 response = response.decode('utf8')
217 message_mark = 0
218 for i, c in enumerate(response):
219 if c == '{' and not (prev_char and
220 prev_char == '\\'):
221 lc += 1
222 elif c == '}' and not (prev_char and
223 prev_char == '\\'):
224 rc += 1
225 if rc > lc:
226 raise Exception(_("json string not valid"))
227 elif lc == rc and lc != 0:
228 chunks.append(response[message_mark:i + 1])
229 message = "".join(chunks)
230 self._on_remote_message(message, addr)
231 time.sleep(0)
232 lc = rc = 0
233 message_mark = i + 1
234 chunks = []
235 prev_char = c
236 chunks.append(response[message_mark:])
237 else:
238 self.read_on = False
239 self.disconnect(addr)
240 return
241
242 def _echo_response(self, addr):
243 while True:
244 try:
245 if self.enable_manager:
246 time.sleep(0)
247 response = self.ovsdb_dicts.get(addr).recv(
248 n_const.BUFFER_SIZE)
249 sock_json_m = jsonutils.loads(response)
250 sock_handler_method = sock_json_m.get('method', None)
251 if sock_handler_method == 'echo':
252 self.check_c_sock = True
253 self.ovsdb_dicts.get(addr).send(jsonutils.dumps(
254 {"result": sock_json_m.get("params", None),
255 "error": None, "id": sock_json_m['id']}))
256 if (addr not in self.ovsdb_conn_list):
257 self.ovsdb_conn_list.append(addr)
258 break
259 except Exception:
260 continue
261
262 def send(self, message, callback=None, addr=None):
263 """Sends a message to the OVSDB server."""
264 if callback:
265 self.callbacks[message['id']] = callback
266 retry_count = 0
267 bytes_sent = 0
268 while retry_count <= n_const.MAX_RETRIES:
269 try:
270 data = jsonutils.dumps(message)
271 if not isinstance(data, bytes):
272 data = data.encode()
273 if self.enable_manager:
274 bytes_sent = self.ovsdb_dicts.get(addr).send(data)
275 else:
276 bytes_sent = self.socket.send(data)
277 if bytes_sent:
278 return True
279 except Exception as ex:
280 LOG.exception("Exception [%s] occurred while sending "
281 "message to the OVSDB server", ex)
282 retry_count += 1
283
284 LOG.warning("Could not send message to the "
285 "OVSDB server.")
286 self.disconnect(addr)
287 return False
288
289 def disconnect(self, addr=None):
290 """disconnects the connection from the OVSDB server."""
291 if self.enable_manager:
292 self.ovsdb_dicts.get(addr).close()
293 del self.ovsdb_dicts[addr]
294 if addr in self.ovsdb_fd_states.keys():
295 del self.ovsdb_fd_states[addr]
296 self.ovsdb_conn_list.remove(addr)
297 else:
298 self.socket.close()
299 self.connected = False
300
301 def _response(self, operation_id):
302 x_copy = None
303 to_delete = None
304 for x in self.responses:
305 if x['id'] == operation_id:
306 x_copy = copy.deepcopy(x)
307 to_delete = x
308 break
309 if to_delete:
310 self.responses.remove(to_delete)
311 return x_copy