blob: a9186a15334d7b06733764e9c7526db82134cd84 [file] [log] [blame]
Klement Sekera958b7502017-09-28 06:31:53 +02001#!/usr/bin/env python2
Klement Sekera8f2a4ea2017-05-04 06:15:18 +02002
3import json
4
5
6def msg_is_reply(name):
7 return name.endswith('_reply') or name.endswith('_details') \
8 or name.endswith('_event') or name.endswith('_counters')
9
10
11class ParseError (Exception):
12 pass
13
14
15magic_prefix = "vl_api_"
16magic_suffix = "_t"
17
18
19def remove_magic(what):
20 if what.startswith(magic_prefix) and what.endswith(magic_suffix):
21 return what[len(magic_prefix): - len(magic_suffix)]
22 return what
23
24
Klement Sekera958b7502017-09-28 06:31:53 +020025class Field(object):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020026
27 def __init__(
28 self,
29 field_name,
30 field_type,
31 array_len=None,
32 nelem_field=None):
33 self.name = field_name
34 self.type = field_type
35 self.len = array_len
36 self.nelem_field = nelem_field
37
38 def __str__(self):
39 if self.len is None:
40 return "name: %s, type: %s" % (self.name, self.type)
41 elif self.len > 0:
42 return "name: %s, type: %s, length: %s" % (self.name, self.type,
43 self.len)
44 else:
45 return ("name: %s, type: %s, variable length stored in: %s" %
46 (self.name, self.type, self.nelem_field))
47
48
Klement Sekera958b7502017-09-28 06:31:53 +020049class Type(object):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020050 def __init__(self, name):
51 self.name = name
52
Klement Sekera32a9d7b2017-12-10 05:15:41 +010053 def __str__(self):
54 return self.name
55
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020056
57class SimpleType (Type):
58
59 def __init__(self, name):
Klement Sekera958b7502017-09-28 06:31:53 +020060 super(SimpleType, self).__init__(name)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020061
62 def __str__(self):
63 return self.name
64
65
66def get_msg_header_defs(struct_type_class, field_class, typedict):
67 return [
68 struct_type_class(['msg_header1_t',
69 ['u16', '_vl_msg_id'],
70 ['u32', 'context'],
71 ],
72 typedict, field_class
73 ),
74 struct_type_class(['msg_header2_t',
75 ['u16', '_vl_msg_id'],
76 ['u32', 'client_index'],
77 ['u32', 'context'],
78 ],
79 typedict, field_class
80 ),
81 ]
82
83
Klement Sekera958b7502017-09-28 06:31:53 +020084class Struct(object):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020085
86 def __init__(self, name, fields):
87 self.name = name
88 self.fields = fields
89 self.field_names = [n.name for n in self.fields]
90
Klement Sekera32a9d7b2017-12-10 05:15:41 +010091 def __str__(self):
92 return "[%s]" % "], [".join([str(f) for f in self.fields])
93
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020094
Klement Sekera958b7502017-09-28 06:31:53 +020095class Message(object):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +020096
97 def __init__(self, logger, definition, typedict,
98 struct_type_class, simple_type_class, field_class):
Klement Sekeradc15be22017-06-12 06:49:33 +020099 self.request = None
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200100 self.logger = logger
101 m = definition
102 logger.debug("Parsing message definition `%s'" % m)
103 name = m[0]
104 self.name = name
105 logger.debug("Message name is `%s'" % name)
106 ignore = True
107 self.header = None
108 fields = []
109 for header in get_msg_header_defs(struct_type_class, field_class,
110 typedict):
111 logger.debug("Probing header `%s'" % header.name)
112 if header.is_part_of_def(m[1:]):
113 self.header = header
114 logger.debug("Found header `%s'" % header.name)
115 fields.append(field_class(field_name='header',
116 field_type=self.header))
117 ignore = False
118 break
119 if ignore and not msg_is_reply(name):
120 raise ParseError("While parsing message `%s': could not find all "
121 "common header fields" % name)
122 for field in m[1:]:
123 if len(field) == 1 and 'crc' in field:
124 self.crc = field['crc']
125 logger.debug("Found CRC `%s'" % self.crc)
126 continue
127 else:
128 field_type = field[0]
129 if field_type in typedict:
130 field_type = typedict[field_type]
131 else:
Klement Sekera32a9d7b2017-12-10 05:15:41 +0100132 mundane_field_type = remove_magic(field_type)
133 if mundane_field_type in typedict:
134 field_type = typedict[mundane_field_type]
135 else:
136 raise ParseError(
137 "While parsing message `%s': could not find "
138 "type by magic name `%s' nor by mundane name "
139 "`%s'" % (name, field_type, mundane_field_type))
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200140 if len(field) == 2:
141 if self.header is not None and\
142 self.header.has_field(field[1]):
143 continue
144 p = field_class(field_name=field[1],
145 field_type=field_type)
146 elif len(field) == 3:
147 if field[2] == 0:
148 raise ParseError(
149 "While parsing message `%s': variable length "
150 "array `%s' doesn't have reference to member "
151 "containing the actual length" % (
152 name, field[1]))
153 p = field_class(
154 field_name=field[1],
155 field_type=field_type,
156 array_len=field[2])
157 elif len(field) == 4:
158 nelem_field = None
159 for f in fields:
160 if f.name == field[3]:
161 nelem_field = f
162 if nelem_field is None:
163 raise ParseError(
164 "While parsing message `%s': couldn't find "
165 "variable length array `%s' member containing "
166 "the actual length `%s'" % (
167 name, field[1], field[3]))
168 p = field_class(
169 field_name=field[1],
170 field_type=field_type,
171 array_len=field[2],
172 nelem_field=nelem_field)
173 else:
174 raise Exception("Don't know how to parse message "
175 "definition for message `%s': `%s'" %
176 (m, m[1:]))
177 logger.debug("Parsed field `%s'" % p)
178 fields.append(p)
179 self.fields = fields
180
181 def is_dump(self):
182 return self.name.endswith('_dump')
183
184 def is_reply(self):
185 return msg_is_reply(self.name)
186
187
188class StructType (Type, Struct):
189
190 def __init__(self, definition, typedict, field_class):
191 t = definition
192 name = t[0]
193 fields = []
194 for field in t[1:]:
195 if len(field) == 1 and 'crc' in field:
196 self.crc = field['crc']
197 continue
198 elif len(field) == 2:
199 p = field_class(field_name=field[1],
200 field_type=typedict[field[0]])
201 elif len(field) == 3:
202 if field[2] == 0:
203 raise ParseError("While parsing type `%s': array `%s' has "
204 "variable length" % (name, field[1]))
205 p = field_class(field_name=field[1],
206 field_type=typedict[field[0]],
207 array_len=field[2])
208 else:
209 raise ParseError(
210 "Don't know how to parse type definition for "
211 "type `%s': `%s'" % (t, t[1:]))
212 fields.append(p)
213 Type.__init__(self, name)
214 Struct.__init__(self, name, fields)
215
Klement Sekera32a9d7b2017-12-10 05:15:41 +0100216 def __str__(self):
217 return "StructType(%s, %s)" % (Type.__str__(self),
218 Struct.__str__(self))
219
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200220 def has_field(self, name):
221 return name in self.field_names
222
223 def is_part_of_def(self, definition):
224 for idx in range(len(self.fields)):
225 field = definition[idx]
226 p = self.fields[idx]
227 if field[1] != p.name:
228 return False
229 if field[0] != p.type.name:
230 raise ParseError(
231 "Unexpected field type `%s' (should be `%s'), "
232 "while parsing msg/def/field `%s/%s/%s'" %
233 (field[0], p.type, p.name, definition, field))
234 return True
235
236
Klement Sekera958b7502017-09-28 06:31:53 +0200237class JsonParser(object):
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200238 def __init__(self, logger, files, simple_type_class=SimpleType,
239 struct_type_class=StructType, field_class=Field,
240 message_class=Message):
241 self.messages = {}
242 self.types = {
243 x: simple_type_class(x) for x in [
244 'i8', 'i16', 'i32', 'i64',
245 'u8', 'u16', 'u32', 'u64',
246 'f64'
247 ]
248 }
249
250 self.simple_type_class = simple_type_class
251 self.struct_type_class = struct_type_class
252 self.field_class = field_class
253 self.message_class = message_class
254
255 self.exceptions = []
256 self.json_files = []
257 self.types_by_json = {}
258 self.messages_by_json = {}
259 self.logger = logger
260 for f in files:
261 self.parse_json_file(f)
262 self.finalize_parsing()
263
264 def parse_json_file(self, path):
265 self.logger.info("Parsing json api file: `%s'" % path)
266 self.json_files.append(path)
267 self.types_by_json[path] = {}
268 self.messages_by_json[path] = {}
269 with open(path) as f:
270 j = json.load(f)
271 for t in j['types']:
272 try:
273 type_ = self.struct_type_class(t, self.types,
274 self.field_class)
275 if type_.name in self.types:
276 raise ParseError("Duplicate type `%s'" % type_.name)
277 except ParseError as e:
278 self.exceptions.append(e)
279 continue
280 self.types[type_.name] = type_
281 self.types_by_json[path][type_.name] = type_
Klement Sekera32a9d7b2017-12-10 05:15:41 +0100282 self.logger.debug("Parsed type: %s" % type_)
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200283 for m in j['messages']:
284 try:
285 msg = self.message_class(self.logger, m, self.types,
286 self.struct_type_class,
287 self.simple_type_class,
288 self.field_class)
289 if msg.name in self.messages:
290 raise ParseError("Duplicate message `%s'" % msg.name)
291 except ParseError as e:
292 self.exceptions.append(e)
293 continue
294 self.messages[msg.name] = msg
295 self.messages_by_json[path][msg.name] = msg
296
297 def get_reply(self, message):
298 if self.messages[message].is_dump():
299 return self.messages["%s_details" % message[:-len("_dump")]]
300 return self.messages["%s_reply" % message]
301
302 def finalize_parsing(self):
303 if len(self.messages) == 0:
304 for e in self.exceptions:
305 self.logger.error(e)
306 raise Exception("No messages parsed.")
307 for jn, j in self.messages_by_json.items():
308 remove = []
309 for n, m in j.items():
310 try:
311 if not m.is_reply():
312 try:
313 m.reply = self.get_reply(n)
Klement Sekeradc15be22017-06-12 06:49:33 +0200314 m.reply.request = m
Klement Sekera8f2a4ea2017-05-04 06:15:18 +0200315 except:
316 raise ParseError(
317 "Cannot find reply to message `%s'" % n)
318 except ParseError as e:
319 self.exceptions.append(e)
320 remove.append(n)
321
322 self.messages_by_json[jn] = {
323 k: v for k, v in j.items() if k not in remove}