Debian Codegraph @

vif_plug_ovs/ovsdb/impl_vsctl.py

raw symbols SCIP
1 # Derived from neutron/agent/ovsdb/impl_vsctl.py
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15 import collections.abc
16 import itertools
17 import uuid
18
19 from oslo_concurrency import processutils
20 from oslo_log import log as logging
21 from oslo_serialization import jsonutils
22 from oslo_utils import excutils
23 from oslo_utils import uuidutils
24 from ovsdbapp import api as ovsdb_api
25
26 from vif_plug_ovs.ovsdb import api
27 from vif_plug_ovs import privsep
28
29
30 LOG = logging.getLogger(__name__)
31
32
33 def _val_to_py(val):
34 """Convert a json ovsdb return value to native python object"""
35 if isinstance(val, collections.abc.Sequence) and len(val) == 2:
36 if val[0] == "uuid":
37 return uuid.UUID(val[1])
38 elif val[0] == "set":
39 return [_val_to_py(x) for x in val[1]]
40 elif val[0] == "map":
41 return {_val_to_py(x): _val_to_py(y) for x, y in val[1]}
42 return val
43
44
45 def _py_to_val(pyval):
46 """Convert python value to ovs-vsctl value argument"""
47 if isinstance(pyval, bool):
48 return 'true' if pyval is True else 'false'
49 elif pyval == '':
50 return '""'
51 else:
52 # NOTE(twilson) If a Command object, return its record_id as a value
53 return getattr(pyval, "record_id", pyval)
54
55
56 def api_factory(context):
57 return OvsdbVsctl(context)
58
59
60 @privsep.vif_plug.entrypoint
61 def _run_vsctl(full_args):
62 # NOTE(ralonsoh): this function is defined outside the class Transaction
63 # to allow oslo_privsep.PrivContext.entrypoint to wrap
64 # the function correctly.
65 return processutils.execute(*full_args)[0].rstrip()
66
67
68 class Transaction(ovsdb_api.Transaction):
69 def __init__(self, context, check_error=False, log_errors=True, opts=None):
70 self.context = context
71 self.check_error = check_error
72 self.log_errors = log_errors
73 self.opts = ['--timeout=%d' % self.context.timeout,
74 '--oneline', '--format=json']
75 if self.context.connection:
76 self.opts += ['--db=%s' % self.context.connection]
77 if opts:
78 self.opts += opts
79 self.commands = []
80
81 def add(self, command):
82 self.commands.append(command)
83 return command
84
85 def commit(self):
86 args = []
87 for cmd in self.commands:
88 cmd.result = None
89 args += cmd.vsctl_args()
90 res = self.run_vsctl(args)
91 if res is None:
92 return
93 res = res.replace(r'\\', '\\').splitlines()
94 for i, record in enumerate(res):
95 self.commands[i].result = record
96 return [cmd.result for cmd in self.commands]
97
98 def run_vsctl(self, args):
99 full_args = ["ovs-vsctl"] + self.opts + args
100 try:
101 # We log our own errors, so never have utils.execute do it
102 return _run_vsctl(full_args)
103 except Exception as e:
104 with excutils.save_and_reraise_exception() as ctxt:
105 if self.log_errors:
106 LOG.error("Unable to execute %(cmd)s. Exception: "
107 "%(exception)s",
108 {'cmd': full_args, 'exception': e})
109 if not self.check_error:
110 ctxt.reraise = False
111
112
113 class BaseCommand(ovsdb_api.Command):
114 def __init__(self, context, cmd, opts=None, args=None):
115 self.context = context
116 self.cmd = cmd
117 self.opts = [] if opts is None else opts
118 self.args = [] if args is None else args
119 self._result = None
120
121 @property
122 def result(self):
123 return self._result
124
125 @result.setter
126 def result(self, value):
127 self._result = value
128
129 def execute(self, check_error=False, log_errors=True):
130 with Transaction(self.context, check_error=check_error,
131 log_errors=log_errors) as txn:
132 txn.add(self)
133 return self.result
134
135 def vsctl_args(self):
136 return itertools.chain(('--',), self.opts, (self.cmd,), self.args)
137
138
139 class MultiLineCommand(BaseCommand):
140 """Command for ovs-vsctl commands that return multiple lines"""
141 @property
142 def result(self):
143 return self._result
144
145 @result.setter
146 def result(self, raw_result):
147 self._result = raw_result.split(r'\n') if raw_result else []
148
149
150 class DbCommand(BaseCommand):
151 def __init__(self, context, cmd, opts=None, args=None, columns=None):
152 if opts is None:
153 opts = []
154 if columns:
155 opts += ['--columns=%s' % ",".join(columns)]
156 super(DbCommand, self).__init__(context, cmd, opts, args)
157
158 @property
159 def result(self):
160 return self._result
161
162 @result.setter
163 def result(self, raw_result):
164 # If check_error=False, run_vsctl can return None
165 if not raw_result:
166 self._result = None
167 return
168
169 try:
170 json = jsonutils.loads(raw_result)
171 except (ValueError, TypeError) as e:
172 # This shouldn't happen, but if it does and we check_errors
173 # log and raise.
174 with excutils.save_and_reraise_exception():
175 LOG.error("Could not parse: %(raw_result)s. Exception: "
176 "%(exception)s",
177 {'raw_result': raw_result, 'exception': e})
178
179 headings = json['headings']
180 data = json['data']
181 results = []
182 for record in data:
183 obj = {}
184 for pos, heading in enumerate(headings):
185 obj[heading] = _val_to_py(record[pos])
186 results.append(obj)
187 self._result = results
188
189
190 class DbGetCommand(DbCommand):
191 @DbCommand.result.setter
192 def result(self, val):
193 # super()'s never worked for setters http://bugs.python.org/issue14965
194 DbCommand.result.fset(self, val)
195 # DbCommand will return [{'column': value}] and we just want value.
196 if self._result:
197 self._result = list(self._result[0].values())[0]
198
199
200 class DbCreateCommand(BaseCommand):
201 def __init__(self, context, opts=None, args=None):
202 super(DbCreateCommand, self).__init__(context, "create", opts, args)
203 # NOTE(twilson) pre-commit result used for intra-transaction reference
204 self.record_id = "@%s" % uuidutils.generate_uuid()
205 self.opts.append("--id=%s" % self.record_id)
206
207 @property
208 def result(self):
209 return self._result
210
211 @result.setter
212 def result(self, val):
213 self._result = uuid.UUID(val) if val else val
214
215
216 class BrExistsCommand(DbCommand):
217 @DbCommand.result.setter
218 def result(self, val):
219 self._result = val is not None
220
221 def execute(self):
222 return super(BrExistsCommand, self).execute(check_error=False,
223 log_errors=False)
224
225
226 class OvsdbVsctl(ovsdb_api.API, api.ImplAPI):
227 def __init__(self, context):
228 super(OvsdbVsctl, self).__init__()
229 self.context = context
230
231 def create_transaction(self, check_error=False, log_errors=True, **kwargs):
232 return Transaction(self.context, check_error, log_errors, **kwargs)
233
234 def add_manager(self, connection_uri):
235 # This will add a new manager without overriding existing ones.
236 conn_uri = 'target="%s"' % connection_uri
237 args = ['create', 'Manager', conn_uri, '--', 'add', 'Open_vSwitch',
238 '.', 'manager_options', '@manager']
239 return BaseCommand(self.context, '--id=@manager', args=args)
240
241 def get_manager(self):
242 return MultiLineCommand(self.context, 'get-manager')
243
244 def remove_manager(self, connection_uri):
245 args = ['get', 'Manager', connection_uri, '--', 'remove',
246 'Open_vSwitch', '.', 'manager_options', '@manager']
247 return BaseCommand(self.context, '--id=@manager', args=args)
248
249 def add_br(self, name, may_exist=True, datapath_type=None):
250 opts = ['--may-exist'] if may_exist else None
251 params = [name]
252 if datapath_type:
253 params += ['--', 'set', 'Bridge', name,
254 'datapath_type=%s' % datapath_type]
255 return BaseCommand(self.context, 'add-br', opts, params)
256
257 def del_br(self, name, if_exists=True):
258 opts = ['--if-exists'] if if_exists else None
259 return BaseCommand(self.context, 'del-br', opts, [name])
260
261 def br_exists(self, name):
262 return BrExistsCommand(self.context, 'list', args=['Bridge', name])
263
264 def port_to_br(self, name):
265 return BaseCommand(self.context, 'port-to-br', args=[name])
266
267 def iface_to_br(self, name):
268 return BaseCommand(self.context, 'iface-to-br', args=[name])
269
270 def list_br(self):
271 return MultiLineCommand(self.context, 'list-br')
272
273 def br_get_external_id(self, name, field):
274 return BaseCommand(self.context, 'br-get-external-id',
275 args=[name, field])
276
277 def db_create(self, table, **col_values):
278 args = [table]
279 args += _set_colval_args(*col_values.items())
280 return DbCreateCommand(self.context, args=args)
281
282 def db_destroy(self, table, record):
283 args = [table, record]
284 return BaseCommand(self.context, 'destroy', args=args)
285
286 def db_set(self, table, record, *col_values):
287 args = [table, record]
288 args += _set_colval_args(*col_values)
289 return BaseCommand(self.context, 'set', args=args)
290
291 def db_add(self, table, record, column, *values):
292 args = [table, record, column]
293 for value in values:
294 if isinstance(value, collections.abc.Mapping):
295 args += ["{}={}".format(_py_to_val(k), _py_to_val(v))
296 for k, v in value.items()]
297 else:
298 args.append(_py_to_val(value))
299 return BaseCommand(self.context, 'add', args=args)
300
301 def db_clear(self, table, record, column):
302 return BaseCommand(self.context, 'clear', args=[table, record,
303 column])
304
305 def db_get(self, table, record, column):
306 # Use the 'list' command as it can return json and 'get' cannot so that
307 # we can get real return types instead of treating everything as string
308 # NOTE: openvswitch can return a single atomic value for fields that
309 # are sets, but only have one value. This makes directly iterating over
310 # the result of a db_get() call unsafe.
311 return DbGetCommand(self.context, 'list', args=[table, record],
312 columns=[column])
313
314 def db_list(self, table, records=None, columns=None, if_exists=False):
315 opts = ['--if-exists'] if if_exists else None
316 args = [table]
317 if records:
318 args += records
319 return DbCommand(self.context, 'list', opts=opts, args=args,
320 columns=columns)
321
322 def db_find(self, table, *conditions, **kwargs):
323 columns = kwargs.pop('columns', None)
324 args = itertools.chain([table],
325 *[_set_colval_args(c) for c in conditions])
326 return DbCommand(self.context, 'find', args=args, columns=columns)
327
328 def set_controller(self, bridge, controllers):
329 return BaseCommand(self.context, 'set-controller',
330 args=[bridge] + list(controllers))
331
332 def del_controller(self, bridge):
333 return BaseCommand(self.context, 'del-controller', args=[bridge])
334
335 def get_controller(self, bridge):
336 return MultiLineCommand(self.context, 'get-controller', args=[bridge])
337
338 def set_fail_mode(self, bridge, mode):
339 return BaseCommand(self.context, 'set-fail-mode', args=[bridge, mode])
340
341 def add_port(self, bridge, port, may_exist=True):
342 opts = ['--may-exist'] if may_exist else None
343 return BaseCommand(self.context, 'add-port', opts, [bridge, port])
344
345 def del_port(self, port, bridge=None, if_exists=True):
346 opts = ['--if-exists'] if if_exists else None
347 args = filter(None, [bridge, port])
348 return BaseCommand(self.context, 'del-port', opts, args)
349
350 def list_ports(self, bridge):
351 return MultiLineCommand(self.context, 'list-ports', args=[bridge])
352
353 def list_ifaces(self, bridge):
354 return MultiLineCommand(self.context, 'list-ifaces', args=[bridge])
355
356 def db_list_rows(self, table, record=None, if_exists=False):
357 raise NotImplementedError()
358
359 def db_find_rows(self, table, *conditions, **kwargs):
360 raise NotImplementedError()
361
362 def db_remove(self, table, record, column, *values, **keyvalues):
363 raise NotImplementedError()
364
365 def has_table_column(self, table, column):
366 try:
367 self.db_list(table, columns=[column]).execute(check_error=True)
368 return True
369 except processutils.ProcessExecutionError as e:
370 msg = ('ovs-vsctl: %s does not contain a column whose name '
371 'matches "%s"' % (table, column))
372 if msg in e.stderr:
373 return False
374 raise e
375
376
377 def _set_colval_args(*col_values):
378 args = []
379 # TODO(twilson) This is ugly, but set/find args are very similar except for
380 # op. Will try to find a better way to default this op to '='
381 for entry in col_values:
382 if len(entry) == 2:
383 col, op, val = entry[0], '=', entry[1]
384 else:
385 col, op, val = entry
386 if isinstance(val, collections.abc.Mapping):
387 args += ["%s:%s%s%s" % (
388 col, k, op, _py_to_val(v)) for k, v in val.items()]
389 elif (isinstance(val, collections.abc.Sequence) and
390 not isinstance(val, str)):
391 if len(val) == 0:
392 args.append("%s%s%s" % (col, op, "[]"))
393 else:
394 args.append(
395 "%s%s%s" % (col, op, ",".join(map(_py_to_val, val))))
396 else:
397 args.append("%s%s%s" % (col, op, _py_to_val(val)))
398 return args