blob: 561aeea72626bda86af64f3225ce4cca443cd80d [file] [log] [blame]
Matteo Scandolod2044a42017-08-07 16:08:28 -07001
2# Copyright 2017-present Open Networking Foundation
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain 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,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16
Sapan Bhatiaff1b8fa2017-04-10 19:44:38 -070017import pdb
Sapan Bhatiac4f803f2017-04-21 11:50:39 +020018import re
Sapan Bhatia7886e122017-05-17 11:19:39 +020019from pattern import en
20
Sapan Bhatiaf7934b52017-06-12 05:04:23 -070021class FieldNotFound(Exception):
22 def __init__(self, message):
23 super(FieldNotFound, self).__init__(message)
24
Sapan Bhatiad4567592017-07-24 17:26:26 -040025def xproto_debug(**kwargs):
26 print kwargs
27 pdb.set_trace()
28
Sapan Bhatia943dad52017-05-19 18:41:01 +020029def xproto_unquote(s):
30 return unquote(s)
31
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020032def unquote(s):
33 if (s.startswith('"') and s.endswith('"')):
34 return s[1:-1]
Matteo Scandolo292cc2a2017-07-31 19:02:12 -070035 else:
36 return s
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020037
38def xproto_singularize(field):
39 try:
40 # The user has set a singular, as an exception that cannot be handled automatically
41 singular = field['options']['singular']
42 singular = unquote(singular)
43 except KeyError:
44 singular = en.singularize(field['name'])
45
46 return singular
47
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +020048def xproto_singularize_pluralize(field):
49 try:
50 # The user has set a plural, as an exception that cannot be handled automatically
51 plural = field['options']['plural']
52 plural = unquote(plural)
53 except KeyError:
54 plural = en.pluralize(en.singularize(field['name']))
55
56 return plural
57
Sapan Bhatia7886e122017-05-17 11:19:39 +020058def xproto_pluralize(field):
59 try:
60 # The user has set a plural, as an exception that cannot be handled automatically
61 plural = field['options']['plural']
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020062 plural = unquote(plural)
Sapan Bhatia7886e122017-05-17 11:19:39 +020063 except KeyError:
64 plural = en.pluralize(field['name'])
65
66 return plural
Sapan Bhatiac4f803f2017-04-21 11:50:39 +020067
Sapan Bhatiaa3d2e622017-07-31 22:25:55 -040068def xproto_base_def(model_name, base, suffix='', suffix_list=[]):
Sapan Bhatia4e80a262017-05-19 23:10:51 +020069 if (model_name=='XOSBase'):
70 return '(models.Model, PlModelMixIn)'
71 elif (not base):
Sapan Bhatiaff1b8fa2017-04-10 19:44:38 -070072 return ''
73 else:
Sapan Bhatiaa3d2e622017-07-31 22:25:55 -040074 int_base = [i['name']+suffix for i in base if i['name'] in suffix_list]
75 ext_base = [i['name'] for i in base if i['name'] not in suffix_list]
76 return '(' + ','.join(int_base + ext_base) + ')'
Sapan Bhatiaff1b8fa2017-04-10 19:44:38 -070077
Sapan Bhatia504cc972017-04-27 01:56:28 +020078def xproto_first_non_empty(lst):
79 for l in lst:
80 if l: return l
81
Sapan Bhatia943dad52017-05-19 18:41:01 +020082def xproto_api_type(field):
83 try:
84 if (unquote(field['options']['content_type'])=='date'):
Scott Baker450e5d02017-09-06 11:18:16 -070085 return 'double'
Sapan Bhatia943dad52017-05-19 18:41:01 +020086 except KeyError:
87 pass
88
89 return field['type']
90
Sapan Bhatiac4f803f2017-04-21 11:50:39 +020091
92def xproto_base_name(n):
93 # Hack - Refactor NetworkParameter* to make this go away
94 if (n.startswith('NetworkParameter')):
95 return '_'
96
Sapan Bhatia4e80a262017-05-19 23:10:51 +020097 expr = r'^[A-Z]+[a-z]*'
Sapan Bhatiac4f803f2017-04-21 11:50:39 +020098
99 try:
100 match = re.findall(expr, n)[0]
101 except:
102 return '_'
103
104 return match
Sapan Bhatiaae9645c2017-05-05 15:35:54 +0200105
Sapan Bhatia943dad52017-05-19 18:41:01 +0200106def xproto_base_fields(m, table):
107 fields = []
108
109 for b in m['bases']:
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200110 option1 = b['fqn']
111 try:
112 option2 = m['package'] + '.' + b['name']
113 except TypeError:
114 option2 = option1
Sapan Bhatia943dad52017-05-19 18:41:01 +0200115
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200116 accessor = None
117 if option1 in table: accessor = option1
118 elif option2 in table: accessor = option2
119
120 if accessor:
121 base_fields = xproto_base_fields(table[accessor], table)
122
Scott Bakerc237f882018-09-28 14:12:47 -0700123 model_fields = [x.copy() for x in table[accessor]['fields']]
124 for field in model_fields:
125 field["accessor"] = accessor
126
Sapan Bhatia943dad52017-05-19 18:41:01 +0200127 fields.extend(base_fields)
128 fields.extend(model_fields)
129
Matteo Scandolo39b4a272017-11-17 11:09:21 -0800130 if 'no_sync' in m['options'] and m['options']['no_sync']:
131 fields = [f for f in fields if f['name'] != 'backend_status' and f['name'] != 'backend_code']
132
133 if 'no_policy' in m['options'] and m['options']['no_policy']:
134 fields = [f for f in fields if f['name'] != 'policy_status' and f['name'] != 'policy_code']
135
Sapan Bhatia943dad52017-05-19 18:41:01 +0200136 return fields
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200137
Scott Bakerc237f882018-09-28 14:12:47 -0700138def xproto_fields(m, table):
139 """ Generate the full list of models for the xproto message `m` including fields from the classes it inherits.
140
141 Inserts the special field "id" at the very beginning.
142
143 Each time we descend a new level of inheritance, increment the offset field numbers by 100. The base
144 class's fields will be numbered from 1-99, the first descendant will be number 100-199, the second
145 descdendant numbered from 200-299, and so on. This assumes any particular model as at most 100
146 fields.
147 """
148
149 model_fields = [x.copy() for x in m["fields"]]
150 for field in model_fields:
151 field["accessor"] = m["fqn"]
152
153 fields = xproto_base_fields(m, table) + model_fields
154
155 # The "id" field is a special field. Every model has one. Put it up front and pretend it's part of the
156
157 id_field = {'type': 'int32', 'name': 'id', 'options': {}, "id": "1", "accessor": fields[0]["accessor"]}
158
159 fields = [id_field] + fields
160
161 # Walk through the list of fields. They will be in depth-first search order from the base model forward. Each time
162 # the model changes, offset the protobuf field numbers by 100.
163 offset = 0
164 last_accessor = fields[0]["accessor"]
165 for field in fields:
166 if (field["accessor"] != last_accessor):
167 last_accessor = field["accessor"]
168 offset += 100
169 field_id = int(field["id"])
170 if (field_id < 1) or (field_id >= 100):
171 raise Exception("Only field numbers from 1 to 99 are permitted, field %s in model %s" % (field["name"], field["accessor"]))
172 field["id"] = int(field["id"]) + offset
173
174 # Check for duplicates
175 fields_by_number = {}
176 for field in fields:
177 id = field["id"]
178 dup = fields_by_number.get(id)
179 if dup:
180 raise Exception("Field %s has duplicate number %d with field %s in model %s" % (field["name"], id, dup["name"], field["accessor"]))
181 fields_by_number[id] = field
182
183 return fields
184
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200185def xproto_base_rlinks(m, table):
186 links = []
187
188 for base in m['bases']:
189 b = base['name']
190 if b in table:
191 base_rlinks = xproto_base_rlinks(table[b], table)
192
193 model_rlinks = table[b]['rlinks']
194 links.extend(base_rlinks)
195 links.extend(model_rlinks)
196
197 return links
198
Scott Bakerc237f882018-09-28 14:12:47 -0700199def xproto_rlinks(m, table):
200 """ Return the reverse links for the xproto message `m`.
201
202 If the link includes a reverse_id, then it will be used for the protobuf field id. If there is no
203 reverse_id, then one will automatically be allocated started at id 1900. It is incouraged that all links
204 include reverse_ids, so that field identifiers are deterministic across all protobuf messages.
205 """
206
207 index = 1900
208 links = xproto_base_rlinks(m, table) + m["rlinks"]
209
210 links = [x for x in links if ("+" not in x["src_port"]) and ("+" not in x["dst_port"])]
211
212 for link in links:
213 if link["reverse_id"]:
214 link["id"] = int(link["reverse_id"])
215 else:
216 link["id"] = index
217 index += 1
218
219 # check for duplicates
220 links_by_number={}
221 for link in links:
222 id = link["id"]
223 dup=links_by_number.get(id)
224 if dup:
225 raise Exception("Field %s has duplicate number %d with field %s in model %s" % (link["src_port"], id, link["src_port"], m["name"]))
226 links_by_number[id] = link
227
228 return links
229
230
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200231def xproto_base_links(m, table):
232 links = []
233
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200234 for base in m['bases']:
235 b = base['name']
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200236 if b in table:
237 base_links = xproto_base_links(table[b], table)
238
239 model_links = table[b]['links']
240 links.extend(base_links)
241 links.extend(model_links)
242 return links
243
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200244def xproto_string_type(xptags):
245 try:
246 max_length = eval(xptags['max_length'])
247 except:
248 max_length = 1024
249
250 if ('varchar' not in xptags):
251 return 'string'
252 else:
253 return 'text'
254
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700255def xproto_tuplify(nested_list_or_set):
256 if not isinstance(nested_list_or_set, list) and not isinstance(nested_list_or_set, set):
257 return nested_list_or_set
258 else:
259 return tuple([xproto_tuplify(i) for i in nested_list_or_set])
260
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700261def xproto_field_graph_components(fields, model, tag='unique_with'):
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700262 def find_components(graph):
263 pending = set(graph.keys())
264 components = []
265
266 while pending:
267 front = { pending.pop() }
268 component = set()
269
270 while front:
271 node = front.pop()
272 neighbours = graph[node]
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700273 neighbours -= component # These we have already visited
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700274 front |= neighbours
275
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700276 pending -= neighbours
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700277 component |= neighbours
278
279 components.append(component)
280
281 return components
282
283 field_graph = {}
284 field_names = {f['name'] for f in fields}
285
286 for f in fields:
287 try:
288 tagged_str = unquote(f['options'][tag])
289 tagged_fields = tagged_str.split(',')
290
291 for uf in tagged_fields:
292 if uf not in field_names:
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700293 raise FieldNotFound('Field "%s" not found in model "%s", referenced from field "%s" by option "%s"' % (uf, model['name'], f['name'], tag))
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700294
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700295 field_graph.setdefault(f['name'], set()).add(uf)
296 field_graph.setdefault(uf, set()).add(f['name'])
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700297 except KeyError:
298 pass
299
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700300 return find_components(field_graph)
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700301
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200302def xproto_api_opts(field):
303 options = []
304 if 'max_length' in field['options'] and field['type']=='string':
305 options.append('(val).maxLength = %s'%field['options']['max_length'])
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700306
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200307 try:
308 if field['options']['null'] == 'False':
309 options.append('(val).nonNull = true')
310 except KeyError:
311 pass
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700312
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200313 if 'link' in field and 'model' in field['options']:
314 options.append('(foreignKey).modelName = "%s"'%field['options']['model'])
Scott Bakerc4156c32017-12-08 10:58:21 -0800315 if ("options" in field) and ("port" in field["options"]):
316 options.append('(foreignKey).reverseFieldName = "%s"' % field['options']['port'])
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700317
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200318 if options:
319 options_str = '[' + ', '.join(options) + ']'
320 else:
321 options_str = ''
322
323 return options_str
Matteo Scandolo67654fa2017-06-09 09:33:17 -0700324
Matteo Scandolo431781c2017-09-06 15:33:07 -0700325def xproto_type_to_swagger_type(f):
326 try:
327 content_type = f['options']['content_type']
328 content_type = eval(content_type)
329 except:
330 content_type = None
331 pass
332
333 if 'choices' in f['options']:
334 return 'string'
335 elif content_type == 'date':
336 return 'string'
337 elif f['type'] == 'bool':
338 return 'boolean'
339 elif f['type'] == 'string':
340 return 'string'
341 elif f['type'] in ['int','uint32','int32'] or 'link' in f:
342 return 'integer'
343 elif f['type'] in ['double','float']:
344 return 'string'
345
346def xproto_field_to_swagger_enum(f):
347 if 'choices' in f['options']:
348 list = []
349
350 for c in eval(xproto_unquote(f['options']['choices'])):
351 list.append(c[0])
352
353 return list
354 else:
Sapan Bhatiabfb233a2018-02-09 14:53:09 -0800355 return False
Scott Bakera33ccb02018-01-26 13:03:28 -0800356
357def xproto_is_true(x):
358 # TODO: Audit xproto and make specification of trueness more uniform
359 if (x==True) or (x=="True") or (x=='"True"'):
360 return True
361 return False