blob: 3bfcd70ce452643d717e130d8856abc6a298b9ea [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
Scott Baker391f5d82018-10-02 16:34:41 -070019from inflect import engine as inflect_engine_class
20
21inflect_engine = inflect_engine_class()
Sapan Bhatia7886e122017-05-17 11:19:39 +020022
Sapan Bhatiaf7934b52017-06-12 05:04:23 -070023class FieldNotFound(Exception):
24 def __init__(self, message):
25 super(FieldNotFound, self).__init__(message)
26
Sapan Bhatiad4567592017-07-24 17:26:26 -040027def xproto_debug(**kwargs):
28 print kwargs
29 pdb.set_trace()
30
Sapan Bhatia943dad52017-05-19 18:41:01 +020031def xproto_unquote(s):
32 return unquote(s)
33
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020034def unquote(s):
35 if (s.startswith('"') and s.endswith('"')):
36 return s[1:-1]
Matteo Scandolo292cc2a2017-07-31 19:02:12 -070037 else:
38 return s
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020039
40def xproto_singularize(field):
41 try:
42 # The user has set a singular, as an exception that cannot be handled automatically
43 singular = field['options']['singular']
44 singular = unquote(singular)
45 except KeyError:
Scott Baker391f5d82018-10-02 16:34:41 -070046 singular = inflect_engine.singular_noun(field['name'])
Scott Bakera1b089a2018-10-05 09:59:17 -070047 if singular is False:
48 # singular_noun returns False on a noun it can't singularize
49 singular = field["name"]
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020050
51 return singular
52
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +020053def xproto_singularize_pluralize(field):
54 try:
55 # The user has set a plural, as an exception that cannot be handled automatically
56 plural = field['options']['plural']
57 plural = unquote(plural)
58 except KeyError:
Scott Bakera1b089a2018-10-05 09:59:17 -070059 singular = inflect_engine.singular_noun(field['name'])
60 if singular is False:
61 # singular_noun returns False on a noun it can't singularize
62 singular = field["name"]
63
64 plural = inflect_engine.plural_noun(singular)
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +020065
66 return plural
67
Sapan Bhatia7886e122017-05-17 11:19:39 +020068def xproto_pluralize(field):
69 try:
70 # The user has set a plural, as an exception that cannot be handled automatically
71 plural = field['options']['plural']
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020072 plural = unquote(plural)
Sapan Bhatia7886e122017-05-17 11:19:39 +020073 except KeyError:
Scott Baker391f5d82018-10-02 16:34:41 -070074 plural = inflect_engine.plural_noun(field['name'])
Sapan Bhatia7886e122017-05-17 11:19:39 +020075
76 return plural
Sapan Bhatiac4f803f2017-04-21 11:50:39 +020077
Sapan Bhatiaa3d2e622017-07-31 22:25:55 -040078def xproto_base_def(model_name, base, suffix='', suffix_list=[]):
Sapan Bhatia4e80a262017-05-19 23:10:51 +020079 if (model_name=='XOSBase'):
80 return '(models.Model, PlModelMixIn)'
81 elif (not base):
Sapan Bhatiaff1b8fa2017-04-10 19:44:38 -070082 return ''
83 else:
Sapan Bhatiaa3d2e622017-07-31 22:25:55 -040084 int_base = [i['name']+suffix for i in base if i['name'] in suffix_list]
85 ext_base = [i['name'] for i in base if i['name'] not in suffix_list]
86 return '(' + ','.join(int_base + ext_base) + ')'
Sapan Bhatiaff1b8fa2017-04-10 19:44:38 -070087
Sapan Bhatia504cc972017-04-27 01:56:28 +020088def xproto_first_non_empty(lst):
89 for l in lst:
90 if l: return l
91
Sapan Bhatia943dad52017-05-19 18:41:01 +020092def xproto_api_type(field):
93 try:
94 if (unquote(field['options']['content_type'])=='date'):
Scott Baker450e5d02017-09-06 11:18:16 -070095 return 'double'
Sapan Bhatia943dad52017-05-19 18:41:01 +020096 except KeyError:
97 pass
98
99 return field['type']
100
Sapan Bhatiac4f803f2017-04-21 11:50:39 +0200101
102def xproto_base_name(n):
103 # Hack - Refactor NetworkParameter* to make this go away
104 if (n.startswith('NetworkParameter')):
105 return '_'
106
Sapan Bhatia4e80a262017-05-19 23:10:51 +0200107 expr = r'^[A-Z]+[a-z]*'
Sapan Bhatiac4f803f2017-04-21 11:50:39 +0200108
109 try:
110 match = re.findall(expr, n)[0]
111 except:
112 return '_'
113
114 return match
Sapan Bhatiaae9645c2017-05-05 15:35:54 +0200115
Sapan Bhatia943dad52017-05-19 18:41:01 +0200116def xproto_base_fields(m, table):
117 fields = []
118
119 for b in m['bases']:
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200120 option1 = b['fqn']
121 try:
122 option2 = m['package'] + '.' + b['name']
123 except TypeError:
124 option2 = option1
Sapan Bhatia943dad52017-05-19 18:41:01 +0200125
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200126 accessor = None
127 if option1 in table: accessor = option1
128 elif option2 in table: accessor = option2
129
130 if accessor:
131 base_fields = xproto_base_fields(table[accessor], table)
132
Scott Bakerc237f882018-09-28 14:12:47 -0700133 model_fields = [x.copy() for x in table[accessor]['fields']]
134 for field in model_fields:
135 field["accessor"] = accessor
136
Sapan Bhatia943dad52017-05-19 18:41:01 +0200137 fields.extend(base_fields)
138 fields.extend(model_fields)
139
Matteo Scandolo39b4a272017-11-17 11:09:21 -0800140 if 'no_sync' in m['options'] and m['options']['no_sync']:
141 fields = [f for f in fields if f['name'] != 'backend_status' and f['name'] != 'backend_code']
142
143 if 'no_policy' in m['options'] and m['options']['no_policy']:
144 fields = [f for f in fields if f['name'] != 'policy_status' and f['name'] != 'policy_code']
145
Sapan Bhatia943dad52017-05-19 18:41:01 +0200146 return fields
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200147
Scott Bakerc237f882018-09-28 14:12:47 -0700148def xproto_fields(m, table):
149 """ Generate the full list of models for the xproto message `m` including fields from the classes it inherits.
150
151 Inserts the special field "id" at the very beginning.
152
153 Each time we descend a new level of inheritance, increment the offset field numbers by 100. The base
154 class's fields will be numbered from 1-99, the first descendant will be number 100-199, the second
155 descdendant numbered from 200-299, and so on. This assumes any particular model as at most 100
156 fields.
157 """
158
159 model_fields = [x.copy() for x in m["fields"]]
160 for field in model_fields:
161 field["accessor"] = m["fqn"]
162
163 fields = xproto_base_fields(m, table) + model_fields
164
165 # The "id" field is a special field. Every model has one. Put it up front and pretend it's part of the
166
167 id_field = {'type': 'int32', 'name': 'id', 'options': {}, "id": "1", "accessor": fields[0]["accessor"]}
168
169 fields = [id_field] + fields
170
171 # Walk through the list of fields. They will be in depth-first search order from the base model forward. Each time
172 # the model changes, offset the protobuf field numbers by 100.
173 offset = 0
174 last_accessor = fields[0]["accessor"]
175 for field in fields:
176 if (field["accessor"] != last_accessor):
177 last_accessor = field["accessor"]
178 offset += 100
179 field_id = int(field["id"])
180 if (field_id < 1) or (field_id >= 100):
181 raise Exception("Only field numbers from 1 to 99 are permitted, field %s in model %s" % (field["name"], field["accessor"]))
182 field["id"] = int(field["id"]) + offset
183
184 # Check for duplicates
185 fields_by_number = {}
186 for field in fields:
187 id = field["id"]
188 dup = fields_by_number.get(id)
189 if dup:
190 raise Exception("Field %s has duplicate number %d with field %s in model %s" % (field["name"], id, dup["name"], field["accessor"]))
191 fields_by_number[id] = field
192
193 return fields
194
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200195def xproto_base_rlinks(m, table):
196 links = []
197
198 for base in m['bases']:
199 b = base['name']
200 if b in table:
201 base_rlinks = xproto_base_rlinks(table[b], table)
202
203 model_rlinks = table[b]['rlinks']
204 links.extend(base_rlinks)
205 links.extend(model_rlinks)
206
207 return links
208
Scott Bakerc237f882018-09-28 14:12:47 -0700209def xproto_rlinks(m, table):
210 """ Return the reverse links for the xproto message `m`.
211
212 If the link includes a reverse_id, then it will be used for the protobuf field id. If there is no
213 reverse_id, then one will automatically be allocated started at id 1900. It is incouraged that all links
214 include reverse_ids, so that field identifiers are deterministic across all protobuf messages.
215 """
216
217 index = 1900
218 links = xproto_base_rlinks(m, table) + m["rlinks"]
219
220 links = [x for x in links if ("+" not in x["src_port"]) and ("+" not in x["dst_port"])]
221
222 for link in links:
223 if link["reverse_id"]:
224 link["id"] = int(link["reverse_id"])
225 else:
226 link["id"] = index
227 index += 1
228
229 # check for duplicates
230 links_by_number={}
231 for link in links:
232 id = link["id"]
233 dup=links_by_number.get(id)
234 if dup:
235 raise Exception("Field %s has duplicate number %d with field %s in model %s" % (link["src_port"], id, link["src_port"], m["name"]))
236 links_by_number[id] = link
237
238 return links
239
240
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200241def xproto_base_links(m, table):
242 links = []
243
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200244 for base in m['bases']:
245 b = base['name']
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200246 if b in table:
247 base_links = xproto_base_links(table[b], table)
248
249 model_links = table[b]['links']
250 links.extend(base_links)
251 links.extend(model_links)
252 return links
253
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200254def xproto_string_type(xptags):
255 try:
256 max_length = eval(xptags['max_length'])
257 except:
258 max_length = 1024
259
260 if ('varchar' not in xptags):
261 return 'string'
262 else:
263 return 'text'
264
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700265def xproto_tuplify(nested_list_or_set):
266 if not isinstance(nested_list_or_set, list) and not isinstance(nested_list_or_set, set):
267 return nested_list_or_set
268 else:
269 return tuple([xproto_tuplify(i) for i in nested_list_or_set])
270
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700271def xproto_field_graph_components(fields, model, tag='unique_with'):
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700272 def find_components(graph):
273 pending = set(graph.keys())
274 components = []
275
276 while pending:
277 front = { pending.pop() }
278 component = set()
279
280 while front:
281 node = front.pop()
282 neighbours = graph[node]
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700283 neighbours -= component # These we have already visited
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700284 front |= neighbours
285
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700286 pending -= neighbours
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700287 component |= neighbours
288
289 components.append(component)
290
291 return components
292
293 field_graph = {}
294 field_names = {f['name'] for f in fields}
295
296 for f in fields:
297 try:
298 tagged_str = unquote(f['options'][tag])
299 tagged_fields = tagged_str.split(',')
300
301 for uf in tagged_fields:
302 if uf not in field_names:
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700303 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 -0700304
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700305 field_graph.setdefault(f['name'], set()).add(uf)
306 field_graph.setdefault(uf, set()).add(f['name'])
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700307 except KeyError:
308 pass
309
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700310 return find_components(field_graph)
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700311
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200312def xproto_api_opts(field):
313 options = []
314 if 'max_length' in field['options'] and field['type']=='string':
315 options.append('(val).maxLength = %s'%field['options']['max_length'])
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700316
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200317 try:
318 if field['options']['null'] == 'False':
319 options.append('(val).nonNull = true')
320 except KeyError:
321 pass
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700322
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200323 if 'link' in field and 'model' in field['options']:
324 options.append('(foreignKey).modelName = "%s"'%field['options']['model'])
Scott Bakerc4156c32017-12-08 10:58:21 -0800325 if ("options" in field) and ("port" in field["options"]):
326 options.append('(foreignKey).reverseFieldName = "%s"' % field['options']['port'])
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700327
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200328 if options:
329 options_str = '[' + ', '.join(options) + ']'
330 else:
331 options_str = ''
332
333 return options_str
Matteo Scandolo67654fa2017-06-09 09:33:17 -0700334
Matteo Scandolo431781c2017-09-06 15:33:07 -0700335def xproto_type_to_swagger_type(f):
336 try:
337 content_type = f['options']['content_type']
338 content_type = eval(content_type)
339 except:
340 content_type = None
341 pass
342
343 if 'choices' in f['options']:
344 return 'string'
345 elif content_type == 'date':
346 return 'string'
347 elif f['type'] == 'bool':
348 return 'boolean'
349 elif f['type'] == 'string':
350 return 'string'
351 elif f['type'] in ['int','uint32','int32'] or 'link' in f:
352 return 'integer'
353 elif f['type'] in ['double','float']:
354 return 'string'
355
356def xproto_field_to_swagger_enum(f):
357 if 'choices' in f['options']:
358 list = []
359
360 for c in eval(xproto_unquote(f['options']['choices'])):
361 list.append(c[0])
362
363 return list
364 else:
Sapan Bhatiabfb233a2018-02-09 14:53:09 -0800365 return False
Scott Bakera33ccb02018-01-26 13:03:28 -0800366
367def xproto_is_true(x):
368 # TODO: Audit xproto and make specification of trueness more uniform
369 if (x==True) or (x=="True") or (x=='"True"'):
370 return True
371 return False