blob: 702b5546d3b8f6386cac35c8d3b8e0bbff1fd019 [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'])
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020047
48 return singular
49
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +020050def xproto_singularize_pluralize(field):
51 try:
52 # The user has set a plural, as an exception that cannot be handled automatically
53 plural = field['options']['plural']
54 plural = unquote(plural)
55 except KeyError:
Scott Baker391f5d82018-10-02 16:34:41 -070056 plural = inflect_engine.plural_noun(inflect_engine.singular_noun(field['name']))
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +020057
58 return plural
59
Sapan Bhatia7886e122017-05-17 11:19:39 +020060def xproto_pluralize(field):
61 try:
62 # The user has set a plural, as an exception that cannot be handled automatically
63 plural = field['options']['plural']
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020064 plural = unquote(plural)
Sapan Bhatia7886e122017-05-17 11:19:39 +020065 except KeyError:
Scott Baker391f5d82018-10-02 16:34:41 -070066 plural = inflect_engine.plural_noun(field['name'])
Sapan Bhatia7886e122017-05-17 11:19:39 +020067
68 return plural
Sapan Bhatiac4f803f2017-04-21 11:50:39 +020069
Sapan Bhatiaa3d2e622017-07-31 22:25:55 -040070def xproto_base_def(model_name, base, suffix='', suffix_list=[]):
Sapan Bhatia4e80a262017-05-19 23:10:51 +020071 if (model_name=='XOSBase'):
72 return '(models.Model, PlModelMixIn)'
73 elif (not base):
Sapan Bhatiaff1b8fa2017-04-10 19:44:38 -070074 return ''
75 else:
Sapan Bhatiaa3d2e622017-07-31 22:25:55 -040076 int_base = [i['name']+suffix for i in base if i['name'] in suffix_list]
77 ext_base = [i['name'] for i in base if i['name'] not in suffix_list]
78 return '(' + ','.join(int_base + ext_base) + ')'
Sapan Bhatiaff1b8fa2017-04-10 19:44:38 -070079
Sapan Bhatia504cc972017-04-27 01:56:28 +020080def xproto_first_non_empty(lst):
81 for l in lst:
82 if l: return l
83
Sapan Bhatia943dad52017-05-19 18:41:01 +020084def xproto_api_type(field):
85 try:
86 if (unquote(field['options']['content_type'])=='date'):
Scott Baker450e5d02017-09-06 11:18:16 -070087 return 'double'
Sapan Bhatia943dad52017-05-19 18:41:01 +020088 except KeyError:
89 pass
90
91 return field['type']
92
Sapan Bhatiac4f803f2017-04-21 11:50:39 +020093
94def xproto_base_name(n):
95 # Hack - Refactor NetworkParameter* to make this go away
96 if (n.startswith('NetworkParameter')):
97 return '_'
98
Sapan Bhatia4e80a262017-05-19 23:10:51 +020099 expr = r'^[A-Z]+[a-z]*'
Sapan Bhatiac4f803f2017-04-21 11:50:39 +0200100
101 try:
102 match = re.findall(expr, n)[0]
103 except:
104 return '_'
105
106 return match
Sapan Bhatiaae9645c2017-05-05 15:35:54 +0200107
Sapan Bhatia943dad52017-05-19 18:41:01 +0200108def xproto_base_fields(m, table):
109 fields = []
110
111 for b in m['bases']:
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200112 option1 = b['fqn']
113 try:
114 option2 = m['package'] + '.' + b['name']
115 except TypeError:
116 option2 = option1
Sapan Bhatia943dad52017-05-19 18:41:01 +0200117
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200118 accessor = None
119 if option1 in table: accessor = option1
120 elif option2 in table: accessor = option2
121
122 if accessor:
123 base_fields = xproto_base_fields(table[accessor], table)
124
Scott Bakerc237f882018-09-28 14:12:47 -0700125 model_fields = [x.copy() for x in table[accessor]['fields']]
126 for field in model_fields:
127 field["accessor"] = accessor
128
Sapan Bhatia943dad52017-05-19 18:41:01 +0200129 fields.extend(base_fields)
130 fields.extend(model_fields)
131
Matteo Scandolo39b4a272017-11-17 11:09:21 -0800132 if 'no_sync' in m['options'] and m['options']['no_sync']:
133 fields = [f for f in fields if f['name'] != 'backend_status' and f['name'] != 'backend_code']
134
135 if 'no_policy' in m['options'] and m['options']['no_policy']:
136 fields = [f for f in fields if f['name'] != 'policy_status' and f['name'] != 'policy_code']
137
Sapan Bhatia943dad52017-05-19 18:41:01 +0200138 return fields
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200139
Scott Bakerc237f882018-09-28 14:12:47 -0700140def xproto_fields(m, table):
141 """ Generate the full list of models for the xproto message `m` including fields from the classes it inherits.
142
143 Inserts the special field "id" at the very beginning.
144
145 Each time we descend a new level of inheritance, increment the offset field numbers by 100. The base
146 class's fields will be numbered from 1-99, the first descendant will be number 100-199, the second
147 descdendant numbered from 200-299, and so on. This assumes any particular model as at most 100
148 fields.
149 """
150
151 model_fields = [x.copy() for x in m["fields"]]
152 for field in model_fields:
153 field["accessor"] = m["fqn"]
154
155 fields = xproto_base_fields(m, table) + model_fields
156
157 # The "id" field is a special field. Every model has one. Put it up front and pretend it's part of the
158
159 id_field = {'type': 'int32', 'name': 'id', 'options': {}, "id": "1", "accessor": fields[0]["accessor"]}
160
161 fields = [id_field] + fields
162
163 # Walk through the list of fields. They will be in depth-first search order from the base model forward. Each time
164 # the model changes, offset the protobuf field numbers by 100.
165 offset = 0
166 last_accessor = fields[0]["accessor"]
167 for field in fields:
168 if (field["accessor"] != last_accessor):
169 last_accessor = field["accessor"]
170 offset += 100
171 field_id = int(field["id"])
172 if (field_id < 1) or (field_id >= 100):
173 raise Exception("Only field numbers from 1 to 99 are permitted, field %s in model %s" % (field["name"], field["accessor"]))
174 field["id"] = int(field["id"]) + offset
175
176 # Check for duplicates
177 fields_by_number = {}
178 for field in fields:
179 id = field["id"]
180 dup = fields_by_number.get(id)
181 if dup:
182 raise Exception("Field %s has duplicate number %d with field %s in model %s" % (field["name"], id, dup["name"], field["accessor"]))
183 fields_by_number[id] = field
184
185 return fields
186
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200187def xproto_base_rlinks(m, table):
188 links = []
189
190 for base in m['bases']:
191 b = base['name']
192 if b in table:
193 base_rlinks = xproto_base_rlinks(table[b], table)
194
195 model_rlinks = table[b]['rlinks']
196 links.extend(base_rlinks)
197 links.extend(model_rlinks)
198
199 return links
200
Scott Bakerc237f882018-09-28 14:12:47 -0700201def xproto_rlinks(m, table):
202 """ Return the reverse links for the xproto message `m`.
203
204 If the link includes a reverse_id, then it will be used for the protobuf field id. If there is no
205 reverse_id, then one will automatically be allocated started at id 1900. It is incouraged that all links
206 include reverse_ids, so that field identifiers are deterministic across all protobuf messages.
207 """
208
209 index = 1900
210 links = xproto_base_rlinks(m, table) + m["rlinks"]
211
212 links = [x for x in links if ("+" not in x["src_port"]) and ("+" not in x["dst_port"])]
213
214 for link in links:
215 if link["reverse_id"]:
216 link["id"] = int(link["reverse_id"])
217 else:
218 link["id"] = index
219 index += 1
220
221 # check for duplicates
222 links_by_number={}
223 for link in links:
224 id = link["id"]
225 dup=links_by_number.get(id)
226 if dup:
227 raise Exception("Field %s has duplicate number %d with field %s in model %s" % (link["src_port"], id, link["src_port"], m["name"]))
228 links_by_number[id] = link
229
230 return links
231
232
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200233def xproto_base_links(m, table):
234 links = []
235
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200236 for base in m['bases']:
237 b = base['name']
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200238 if b in table:
239 base_links = xproto_base_links(table[b], table)
240
241 model_links = table[b]['links']
242 links.extend(base_links)
243 links.extend(model_links)
244 return links
245
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200246def xproto_string_type(xptags):
247 try:
248 max_length = eval(xptags['max_length'])
249 except:
250 max_length = 1024
251
252 if ('varchar' not in xptags):
253 return 'string'
254 else:
255 return 'text'
256
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700257def xproto_tuplify(nested_list_or_set):
258 if not isinstance(nested_list_or_set, list) and not isinstance(nested_list_or_set, set):
259 return nested_list_or_set
260 else:
261 return tuple([xproto_tuplify(i) for i in nested_list_or_set])
262
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700263def xproto_field_graph_components(fields, model, tag='unique_with'):
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700264 def find_components(graph):
265 pending = set(graph.keys())
266 components = []
267
268 while pending:
269 front = { pending.pop() }
270 component = set()
271
272 while front:
273 node = front.pop()
274 neighbours = graph[node]
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700275 neighbours -= component # These we have already visited
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700276 front |= neighbours
277
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700278 pending -= neighbours
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700279 component |= neighbours
280
281 components.append(component)
282
283 return components
284
285 field_graph = {}
286 field_names = {f['name'] for f in fields}
287
288 for f in fields:
289 try:
290 tagged_str = unquote(f['options'][tag])
291 tagged_fields = tagged_str.split(',')
292
293 for uf in tagged_fields:
294 if uf not in field_names:
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700295 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 -0700296
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700297 field_graph.setdefault(f['name'], set()).add(uf)
298 field_graph.setdefault(uf, set()).add(f['name'])
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700299 except KeyError:
300 pass
301
Matteo Scandoloa17e6e42018-05-25 10:28:25 -0700302 return find_components(field_graph)
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700303
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200304def xproto_api_opts(field):
305 options = []
306 if 'max_length' in field['options'] and field['type']=='string':
307 options.append('(val).maxLength = %s'%field['options']['max_length'])
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700308
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200309 try:
310 if field['options']['null'] == 'False':
311 options.append('(val).nonNull = true')
312 except KeyError:
313 pass
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700314
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200315 if 'link' in field and 'model' in field['options']:
316 options.append('(foreignKey).modelName = "%s"'%field['options']['model'])
Scott Bakerc4156c32017-12-08 10:58:21 -0800317 if ("options" in field) and ("port" in field["options"]):
318 options.append('(foreignKey).reverseFieldName = "%s"' % field['options']['port'])
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700319
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200320 if options:
321 options_str = '[' + ', '.join(options) + ']'
322 else:
323 options_str = ''
324
325 return options_str
Matteo Scandolo67654fa2017-06-09 09:33:17 -0700326
Matteo Scandolo431781c2017-09-06 15:33:07 -0700327def xproto_type_to_swagger_type(f):
328 try:
329 content_type = f['options']['content_type']
330 content_type = eval(content_type)
331 except:
332 content_type = None
333 pass
334
335 if 'choices' in f['options']:
336 return 'string'
337 elif content_type == 'date':
338 return 'string'
339 elif f['type'] == 'bool':
340 return 'boolean'
341 elif f['type'] == 'string':
342 return 'string'
343 elif f['type'] in ['int','uint32','int32'] or 'link' in f:
344 return 'integer'
345 elif f['type'] in ['double','float']:
346 return 'string'
347
348def xproto_field_to_swagger_enum(f):
349 if 'choices' in f['options']:
350 list = []
351
352 for c in eval(xproto_unquote(f['options']['choices'])):
353 list.append(c[0])
354
355 return list
356 else:
Sapan Bhatiabfb233a2018-02-09 14:53:09 -0800357 return False
Scott Bakera33ccb02018-01-26 13:03:28 -0800358
359def xproto_is_true(x):
360 # TODO: Audit xproto and make specification of trueness more uniform
361 if (x==True) or (x=="True") or (x=='"True"'):
362 return True
363 return False