summaryrefslogtreecommitdiff
path: root/python/ovs/db/data.py
blob: 3075ee6be9ed52da22e9cf6393e22d7bb18835e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# Copyright (c) 2009, 2010, 2011, 2014 Nicira, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
import uuid

import six

import ovs.poller
import ovs.socket_util
import ovs.json
import ovs.jsonrpc
import ovs.ovsuuid

import ovs.db.parser
from ovs.db import error
import ovs.db.types


class ConstraintViolation(error.Error):
    def __init__(self, msg, json=None):
        error.Error.__init__(self, msg, json, tag="constraint violation")


def escapeCString(src):
    dst = []
    for c in src:
        if c in "\\\"":
            dst.append("\\" + c)
        elif ord(c) < 32:
            if c == '\n':
                dst.append('\\n')
            elif c == '\r':
                dst.append('\\r')
            elif c == '\a':
                dst.append('\\a')
            elif c == '\b':
                dst.append('\\b')
            elif c == '\f':
                dst.append('\\f')
            elif c == '\t':
                dst.append('\\t')
            elif c == '\v':
                dst.append('\\v')
            else:
                dst.append('\\%03o' % ord(c))
        else:
            dst.append(c)
    return ''.join(dst)


def returnUnchanged(x):
    return x


class Atom(object):
    def __init__(self, type_, value=None):
        self.type = type_
        if value is not None:
            self.value = value
        else:
            self.value = type_.default_atom()

    def __cmp__(self, other):
        if not isinstance(other, Atom) or self.type != other.type:
            return NotImplemented
        elif self.value < other.value:
            return -1
        elif self.value > other.value:
            return 1
        else:
            return 0

    def __hash__(self):
        return hash(self.value)

    @staticmethod
    def default(type_):
        """Returns the default value for the given type_, which must be an
        instance of ovs.db.types.AtomicType.

        The default value for each atomic type is;

          - 0, for integer or real atoms.

          - False, for a boolean atom.

          - "", for a string atom.

          - The all-zeros UUID, for a UUID atom."""
        return Atom(type_)

    def is_default(self):
        return self == self.default(self.type)

    @staticmethod
    def from_json(base, json, symtab=None):
        type_ = base.type
        json = ovs.db.parser.float_to_int(json)
        if ((type_ == ovs.db.types.IntegerType and type(json) in [int, long])
            or (type_ == ovs.db.types.RealType
                and type(json) in [int, long, float])
            or (type_ == ovs.db.types.BooleanType and type(json) == bool)
            or (type_ == ovs.db.types.StringType
                and type(json) in [str, unicode])):
            atom = Atom(type_, json)
        elif type_ == ovs.db.types.UuidType:
            atom = Atom(type_, ovs.ovsuuid.from_json(json, symtab))
        else:
            raise error.Error("expected %s" % type_.to_string(), json)
        atom.check_constraints(base)
        return atom

    @staticmethod
    def from_python(base, value):
        value = ovs.db.parser.float_to_int(value)
        if type(value) in base.type.python_types:
            atom = Atom(base.type, value)
        else:
            raise error.Error("expected %s, got %s" % (base.type, type(value)))
        atom.check_constraints(base)
        return atom

    def check_constraints(self, base):
        """Checks whether 'atom' meets the constraints (if any) defined in
        'base' and raises an ovs.db.error.Error if any constraint is violated.

        'base' and 'atom' must have the same type.
        Checking UUID constraints is deferred to transaction commit time, so
        this function does nothing for UUID constraints."""
        assert base.type == self.type
        if base.enum is not None and self not in base.enum:
            raise ConstraintViolation(
                "%s is not one of the allowed values (%s)"
                % (self.to_string(), base.enum.to_string()))
        elif base.type in [ovs.db.types.IntegerType, ovs.db.types.RealType]:
            if ((base.min is None or self.value >= base.min) and
                (base.max is None or self.value <= base.max)):
                pass
            elif base.min is not None and base.max is not None:
                raise ConstraintViolation(
                    "%s is not in the valid range %.15g to %.15g (inclusive)"
                    % (self.to_string(), base.min, base.max))
            elif base.min is not None:
                raise ConstraintViolation(
                    "%s is less than minimum allowed value %.15g"
                            % (self.to_string(), base.min))
            else:
                raise ConstraintViolation(
                    "%s is greater than maximum allowed value %.15g"
                    % (self.to_string(), base.max))
        elif base.type == ovs.db.types.StringType:
            # XXX The C version validates that the string is valid UTF-8 here.
            # Do we need to do that in Python too?
            s = self.value
            length = len(s)
            if length < base.min_length:
                raise ConstraintViolation(
                    '"%s" length %d is less than minimum allowed length %d'
                    % (s, length, base.min_length))
            elif length > base.max_length:
                raise ConstraintViolation(
                    '"%s" length %d is greater than maximum allowed '
                    'length %d' % (s, length, base.max_length))

    def to_json(self):
        if self.type == ovs.db.types.UuidType:
            return ovs.ovsuuid.to_json(self.value)
        else:
            return self.value

    def cInitAtom(self, var):
        if self.type == ovs.db.types.IntegerType:
            return ['%s.integer = %d;' % (var, self.value)]
        elif self.type == ovs.db.types.RealType:
            return ['%s.real = %.15g;' % (var, self.value)]
        elif self.type == ovs.db.types.BooleanType:
            if self.value:
                return ['%s.boolean = true;']
            else:
                return ['%s.boolean = false;']
        elif self.type == ovs.db.types.StringType:
            return ['%s.string = xstrdup("%s");'
                    % (var, escapeCString(self.value))]
        elif self.type == ovs.db.types.UuidType:
            return ovs.ovsuuid.to_c_assignment(self.value, var)

    def toEnglish(self, escapeLiteral=returnUnchanged):
        if self.type == ovs.db.types.IntegerType:
            return '%d' % self.value
        elif self.type == ovs.db.types.RealType:
            return '%.15g' % self.value
        elif self.type == ovs.db.types.BooleanType:
            if self.value:
                return 'true'
            else:
                return 'false'
        elif self.type == ovs.db.types.StringType:
            return escapeLiteral(self.value)
        elif self.type == ovs.db.types.UuidType:
            return self.value.value

    __need_quotes_re = re.compile("$|true|false|[^_a-zA-Z]|.*[^-._a-zA-Z]")

    @staticmethod
    def __string_needs_quotes(s):
        return Atom.__need_quotes_re.match(s)

    def to_string(self):
        if self.type == ovs.db.types.IntegerType:
            return '%d' % self.value
        elif self.type == ovs.db.types.RealType:
            return '%.15g' % self.value
        elif self.type == ovs.db.types.BooleanType:
            if self.value:
                return 'true'
            else:
                return 'false'
        elif self.type == ovs.db.types.StringType:
            if Atom.__string_needs_quotes(self.value):
                return ovs.json.to_string(self.value)
            else:
                return self.value
        elif self.type == ovs.db.types.UuidType:
            return str(self.value)

    @staticmethod
    def new(x):
        if type(x) in [int, long]:
            t = ovs.db.types.IntegerType
        elif type(x) == float:
            t = ovs.db.types.RealType
        elif x in [False, True]:
            t = ovs.db.types.BooleanType
        elif type(x) in [str, unicode]:
            t = ovs.db.types.StringType
        elif isinstance(x, uuid):
            t = ovs.db.types.UuidType
        else:
            raise TypeError
        return Atom(t, x)


class Datum(object):
    def __init__(self, type_, values={}):
        self.type = type_
        self.values = values

    def __cmp__(self, other):
        if not isinstance(other, Datum):
            return NotImplemented
        elif self.values < other.values:
            return -1
        elif self.values > other.values:
            return 1
        else:
            return 0

    __hash__ = None

    def __contains__(self, item):
        return item in self.values

    def copy(self):
        return Datum(self.type, dict(self.values))

    @staticmethod
    def default(type_):
        if type_.n_min == 0:
            values = {}
        elif type_.is_map():
            values = {type_.key.default(): type_.value.default()}
        else:
            values = {type_.key.default(): None}
        return Datum(type_, values)

    def is_default(self):
        return self == Datum.default(self.type)

    def check_constraints(self):
        """Checks that each of the atoms in 'datum' conforms to the constraints
        specified by its 'type' and raises an ovs.db.error.Error.

        This function is not commonly useful because the most ordinary way to
        obtain a datum is ultimately via Datum.from_json() or Atom.from_json(),
        which check constraints themselves."""
        for keyAtom, valueAtom in six.iteritems(self.values):
            keyAtom.check_constraints(self.type.key)
            if valueAtom is not None:
                valueAtom.check_constraints(self.type.value)

    @staticmethod
    def from_json(type_, json, symtab=None):
        """Parses 'json' as a datum of the type described by 'type'.  If
        successful, returns a new datum.  On failure, raises an
        ovs.db.error.Error.

        Violations of constraints expressed by 'type' are treated as errors.

        If 'symtab' is nonnull, then named UUIDs in 'symtab' are accepted.
        Refer to RFC 7047 for information about this, and for the syntax
        that this function accepts."""
        is_map = type_.is_map()
        if (is_map or
            (type(json) == list and len(json) > 0 and json[0] == "set")):
            if is_map:
                class_ = "map"
            else:
                class_ = "set"

            inner = ovs.db.parser.unwrap_json(json, class_, [list, tuple],
                                              "array")
            n = len(inner)
            if n < type_.n_min or n > type_.n_max:
                raise error.Error("%s must have %d to %d members but %d are "
                                  "present" % (class_, type_.n_min,
                                               type_.n_max, n),
                                  json)

            values = {}
            for element in inner:
                if is_map:
                    key, value = ovs.db.parser.parse_json_pair(element)
                    keyAtom = Atom.from_json(type_.key, key, symtab)
                    valueAtom = Atom.from_json(type_.value, value, symtab)
                else:
                    keyAtom = Atom.from_json(type_.key, element, symtab)
                    valueAtom = None

                if keyAtom in values:
                    if is_map:
                        raise error.Error("map contains duplicate key")
                    else:
                        raise error.Error("set contains duplicate")

                values[keyAtom] = valueAtom

            return Datum(type_, values)
        else:
            keyAtom = Atom.from_json(type_.key, json, symtab)
            return Datum(type_, {keyAtom: None})

    def to_json(self):
        if self.type.is_map():
            return ["map", [[k.to_json(), v.to_json()]
                            for k, v in sorted(self.values.items())]]
        elif len(self.values) == 1:
            key = next(six.iterkeys(self.values))
            return key.to_json()
        else:
            return ["set", [k.to_json() for k in sorted(self.values.keys())]]

    def to_string(self):
        head = tail = None
        if self.type.n_max > 1 or len(self.values) == 0:
            if self.type.is_map():
                head = "{"
                tail = "}"
            else:
                head = "["
                tail = "]"

        s = []
        if head:
            s.append(head)

        for i, key in enumerate(sorted(self.values)):
            if i:
                s.append(", ")

            s.append(key.to_string())
            if self.type.is_map():
                s.append("=")
                s.append(self.values[key].to_string())

        if tail:
            s.append(tail)
        return ''.join(s)

    def as_list(self):
        if self.type.is_map():
            return [[k.value, v.value] for k, v in six.iteritems(self.values)]
        else:
            return [k.value for k in six.iterkeys(self.values)]

    def as_dict(self):
        return dict(self.values)

    def as_scalar(self):
        if len(self.values) == 1:
            if self.type.is_map():
                k, v = next(six.iteritems(self.values))
                return [k.value, v.value]
            else:
                return next(six.iterkeys(self.values)).value
        else:
            return None

    def to_python(self, uuid_to_row):
        """Returns this datum's value converted into a natural Python
        representation of this datum's type, according to the following
        rules:

        - If the type has exactly one value and it is not a map (that is,
          self.type.is_scalar() returns True), then the value is:

            * An int or long, for an integer column.

            * An int or long or float, for a real column.

            * A bool, for a boolean column.

            * A str or unicode object, for a string column.

            * A uuid.UUID object, for a UUID column without a ref_table.

            * An object represented the referenced row, for a UUID column with
              a ref_table.  (For the Idl, this object will be an ovs.db.idl.Row
              object.)

          If some error occurs (e.g. the database server's idea of the column
          is different from the IDL's idea), then the default value for the
          scalar type is used (see Atom.default()).

        - Otherwise, if the type is not a map, then the value is a Python list
          whose elements have the types described above.

        - Otherwise, the type is a map, and the value is a Python dict that
          maps from key to value, with key and value types determined as
          described above.

        'uuid_to_row' must be a function that takes a value and an
        ovs.db.types.BaseType and translates UUIDs into row objects."""
        if self.type.is_scalar():
            value = uuid_to_row(self.as_scalar(), self.type.key)
            if value is None:
                return self.type.key.default()
            else:
                return value
        elif self.type.is_map():
            value = {}
            for k, v in six.iteritems(self.values):
                dk = uuid_to_row(k.value, self.type.key)
                dv = uuid_to_row(v.value, self.type.value)
                if dk is not None and dv is not None:
                    value[dk] = dv
            return value
        else:
            s = set()
            for k in self.values:
                dk = uuid_to_row(k.value, self.type.key)
                if dk is not None:
                    s.add(dk)
            return sorted(s)

    @staticmethod
    def from_python(type_, value, row_to_uuid):
        """Returns a new Datum with the given ovs.db.types.Type 'type_'.  The
        new datum's value is taken from 'value', which must take the form
        described as a valid return value from Datum.to_python() for 'type'.

        Each scalar value within 'value' is initially passed through
        'row_to_uuid', which should convert objects that represent rows (if
        any) into uuid.UUID objects and return other data unchanged.

        Raises ovs.db.error.Error if 'value' is not in an appropriate form for
        'type_'."""
        d = {}
        if type(value) == dict:
            for k, v in six.iteritems(value):
                ka = Atom.from_python(type_.key, row_to_uuid(k))
                va = Atom.from_python(type_.value, row_to_uuid(v))
                d[ka] = va
        elif type(value) in (list, tuple):
            for k in value:
                ka = Atom.from_python(type_.key, row_to_uuid(k))
                d[ka] = None
        else:
            ka = Atom.from_python(type_.key, row_to_uuid(value))
            d[ka] = None

        datum = Datum(type_, d)
        datum.check_constraints()
        if not datum.conforms_to_type():
            raise error.Error("%d values when type requires between %d and %d"
                              % (len(d), type_.n_min, type_.n_max))

        return datum

    def __getitem__(self, key):
        if not isinstance(key, Atom):
            key = Atom.new(key)
        if not self.type.is_map():
            raise IndexError
        elif key not in self.values:
            raise KeyError
        else:
            return self.values[key].value

    def get(self, key, default=None):
        if not isinstance(key, Atom):
            key = Atom.new(key)
        if key in self.values:
            return self.values[key].value
        else:
            return default

    def __str__(self):
        return self.to_string()

    def conforms_to_type(self):
        n = len(self.values)
        return self.type.n_min <= n <= self.type.n_max

    def cInitDatum(self, var):
        if len(self.values) == 0:
            return ["ovsdb_datum_init_empty(%s);" % var]

        s = ["%s->n = %d;" % (var, len(self.values))]
        s += ["%s->keys = xmalloc(%d * sizeof *%s->keys);"
              % (var, len(self.values), var)]

        for i, key in enumerate(sorted(self.values)):
            s += key.cInitAtom("%s->keys[%d]" % (var, i))

        if self.type.value:
            s += ["%s->values = xmalloc(%d * sizeof *%s->values);"
                  % (var, len(self.values), var)]
            for i, (key, value) in enumerate(sorted(self.values.items())):
                s += value.cInitAtom("%s->values[%d]" % (var, i))
        else:
            s += ["%s->values = NULL;" % var]

        if len(self.values) > 1:
            s += ["ovsdb_datum_sort_assert(%s, OVSDB_TYPE_%s);"
                  % (var, self.type.key.type.to_string().upper())]

        return s