Debian Codegraph @

neutron_taas/services/taas/service_drivers/ovn/ovsdb/impl_idl_taas.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import atexit
14 import contextlib
15 import tenacity
16
17 from neutron.common.ovn import exceptions as ovn_exceptions
18 from neutron.conf.plugins.ml2.drivers.ovn import ovn_conf
19 from neutron_lib import exceptions as n_exc
20 from oslo_config import cfg
21 from oslo_log import log
22 from ovsdbapp.backend import ovs_idl
23 from ovsdbapp.backend.ovs_idl import connection
24 from ovsdbapp.backend.ovs_idl import idlutils
25 from ovsdbapp.backend.ovs_idl import transaction as idl_trans
26 from ovsdbapp.schema.ovn_northbound import impl_idl as nb_impl_idl
27
28
29 LOG = log.getLogger(__name__)
30 CONF = cfg.CONF
31
32
33 class Backend(ovs_idl.Backend):
34 lookup_table = {}
35 ovsdb_connection = None
36
37 def __init__(self, connection):
38 ovn_conf.register_opts()
39 self.ovsdb_connection = connection
40 super().__init__(connection)
41
42 def start_connection(self, connection):
43 try:
44 self.ovsdb_connection.start()
45 except Exception as e:
46 connection_exception = OvsdbConnectionUnavailable(
47 db_schema=self.schema, error=e)
48 LOG.exception(connection_exception)
49 raise connection_exception from e
50
51 @property
52 def idl(self):
53 return self.ovsdb_connection.idl
54
55 @property
56 def tables(self):
57 return self.idl.tables
58
59 _tables = tables
60
61 def is_table_present(self, table_name):
62 return table_name in self._tables
63
64 def is_col_present(self, table_name, col_name):
65 return self.is_table_present(table_name) and (
66 col_name in self._tables[table_name].columns)
67
68 def create_transaction(self, check_error=False, log_errors=True):
69 return idl_trans.Transaction(
70 self, self.ovsdb_connection, self.ovsdb_connection.timeout,
71 check_error, log_errors)
72
73 # Check for a column match in the table. If not found do a retry with
74 # a stop delay of 10 secs. This function would be useful if the caller
75 # wants to verify for the presence of a particular row in the table
76 # with the column match before doing any transaction.
77 # Eg. We can check if Logical_Switch row is present before adding a
78 # logical switch port to it.
79 @tenacity.retry(retry=tenacity.retry_if_exception_type(RuntimeError),
80 wait=tenacity.wait_exponential(),
81 stop=tenacity.stop_after_delay(10),
82 reraise=True)
83 def check_for_row_by_value_and_retry(self, table, column, match):
84 try:
85 idlutils.row_by_value(self.idl, table, column, match)
86 except idlutils.RowNotFound as e:
87 msg = (_("%(match)s does not exist in %(column)s of %(table)s")
88 % {'match': match, 'column': column, 'table': table})
89 raise RuntimeError(msg) from e
90
91
92 class OvsdbConnectionUnavailable(n_exc.ServiceUnavailable):
93 message = _("OVS database connection to %(db_schema)s failed with error: "
94 "'%(error)s'. Verify that the OVS and OVN services are "
95 "available and that the 'ovn_nb_connection' and "
96 "'ovn_sb_connection' configuration options are correct.")
97
98
99 class OvsdbNbOvnIdl(nb_impl_idl.OvnNbApiIdlImpl, Backend):
100 def __init__(self, connection):
101 super().__init__(connection)
102 self.idl._session.reconnect.set_probe_interval(
103 ovn_conf.get_ovn_ovsdb_probe_interval())
104
105 @contextlib.contextmanager
106 def transaction(self, check_error=False, log_errors=True, nested=True,
107 **kwargs):
108 """A wrapper on the ovsdbapp transaction to work with revisions.
109
110 This method is just a wrapper around the ovsdbapp transaction
111 to handle revision conflicts correctly.
112 """
113 try:
114 with super().transaction(check_error, log_errors, nested,
115 **kwargs) as t:
116 yield t
117 except ovn_exceptions.RevisionConflict as e:
118 LOG.info('Transaction aborted. Reason: %s', e)
119
120
121 class OvnNbIdlForTaas(connection.OvsdbIdl):
122
123 SCHEMA = "OVN_Northbound"
124 TABLES = ('Logical_Switch_Port', 'Mirror')
125
126 def __init__(self):
127 ovn_conf.register_opts()
128 self.conn_string = ovn_conf.get_ovn_nb_connection()
129 helper = self._get_ovsdb_helper(self.conn_string)
130 for table in OvnNbIdlForTaas.TABLES:
131 helper.register_table(table)
132 super().__init__(self.conn_string, helper)
133 atexit.register(self.stop)
134
135 @tenacity.retry(
136 wait=tenacity.wait_exponential(18),
137 reraise=True)
138 def _get_ovsdb_helper(self, connection_string):
139 return idlutils.get_schema_helper(connection_string, self.SCHEMA)
140
141 def start(self):
142 self.conn = connection.Connection(self, timeout=180)
143 return OvsdbNbOvnIdl(self.conn)
144
145 def stop(self):
146 # Close the running connection if it has been initalized
147 if hasattr(self, 'conn'):
148 if not self.conn.stop(timeout=180):
149 LOG.debug("Connection terminated to OvnNb "
150 "but a thread is still alive")
151 del self.conn
152 # Close the idl session
153 self.close()