f2d48ea1d1a40de4855bc1e5ec1a5f2c0e811136
[cascardo/ovs.git] / python / ovs / ovsuuid.py
1 # Copyright (c) 2009, 2010, 2011 Nicira, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain 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,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import re
16 import uuid
17
18 from six.moves import range
19
20 from ovs.db import error
21 import ovs.db.parser
22
23 uuidRE = re.compile("^xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx$"
24                     .replace('x', '[0-9a-fA-F]'))
25
26
27 def zero():
28     return uuid.UUID(int=0)
29
30
31 def is_valid_string(s):
32     return uuidRE.match(s) is not None
33
34
35 def from_string(s):
36     if not is_valid_string(s):
37         raise error.Error("%s is not a valid UUID" % s)
38     return uuid.UUID(s)
39
40
41 def from_json(json, symtab=None):
42     try:
43         s = ovs.db.parser.unwrap_json(json, "uuid", [str, unicode], "string")
44         if not uuidRE.match(s):
45             raise error.Error("\"%s\" is not a valid UUID" % s, json)
46         return uuid.UUID(s)
47     except error.Error as e:
48         if not symtab:
49             raise e
50         try:
51             name = ovs.db.parser.unwrap_json(json, "named-uuid",
52                                              [str, unicode], "string")
53         except error.Error:
54             raise e
55
56         if name not in symtab:
57             symtab[name] = uuid.uuid4()
58         return symtab[name]
59
60
61 def to_json(uuid_):
62     return ["uuid", str(uuid_)]
63
64
65 def to_c_assignment(uuid_, var):
66     """Returns an array of strings, each of which contain a C statement.  The
67     statements assign 'uuid_' to a "struct uuid" as defined in Open vSwitch
68     lib/uuid.h."""
69
70     hex_string = uuid_.hex
71     return ["%s.parts[%d] = 0x%s;" % (var, x, hex_string[x * 8:(x + 1) * 8])
72             for x in range(4)]