blob: 57a2238322b9e533f8dba307319ff3eb0bdde215 [file] [log] [blame]
Klement Sekera8f2a4ea2017-05-04 06:15:18 +02001#!/usr/bin/env python3
2
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
25class Field:
26
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
49class Type:
50 def __init__(self, name):
51 self.name = name
52
53
54class SimpleType (Type):
55
56 def __init__(self, name):
57 super().__init__(name)
58
59 def __str__(self):
60 return self.name
61
62
63def get_msg_header_defs(struct_type_class, field_class, typedict):
64 return [
65 struct_type_class(['msg_header1_t',
66 ['u16', '_vl_msg_id'],
67 ['u32', 'context'],
68 ],
69 typedict, field_class
70 ),
71 struct_type_class(['msg_header2_t',
72 ['u16', '_vl_msg_id'],
73 ['u32', 'client_index'],
74 ['u32', 'context'],
75 ],
76 typedict, field_class
77 ),
78 ]
79
80
81class Struct:
82
83 def __init__(self, name, fields):
84 self.name = name
85 self.fields = fields
86 self.field_names = [n.name for n in self.fields]
87
88
89class Message:
90
91 def __init__(self, logger, definition, typedict,
92 struct_type_class, simple_type_class, field_class):
93 self.logger = logger
94 m = definition
95 logger.debug("Parsing message definition `%s'" % m)
96 name = m[0]
97 self.name = name
98 logger.debug("Message name is `%s'" % name)
99 ignore = True
100 self.header = None
101 fields = []
102 for header in get_msg_header_defs(struct_type_class, field_class,
103 typedict):
104 logger.debug("Probing header `%s'" % header.name)
105 if header.is_part_of_def(m[1:]):
106 self.header = header
107 logger.debug("Found header `%s'" % header.name)
108 fields.append(field_class(field_name='header',
109 field_type=self.header))
110 ignore = False
111 break
112 if ignore and not msg_is_reply(name):
113 raise ParseError("While parsing message `%s': could not find all "
114 "common header fields" % name)
115 for field in m[1:]:
116 if len(field) == 1 and 'crc' in field:
117 self.crc = field['crc']
118 logger.debug("Found CRC `%s'" % self.crc)
119 continue
120 else:
121 field_type = field[0]
122 if field_type in typedict:
123 field_type = typedict[field_type]
124 else:
125 field_type = typedict[remove_magic(field_type)]
126 if len(field) == 2:
127 if self.header is not None and\
128 self.header.has_field(field[1]):
129 continue
130 p = field_class(field_name=field[1],
131 field_type=field_type)
132 elif len(field) == 3:
133 if field[2] == 0:
134 raise ParseError(
135 "While parsing message `%s': variable length "
136 "array `%s' doesn't have reference to member "
137 "containing the actual length" % (
138 name, field[1]))
139 p = field_class(
140 field_name=field[1],
141 field_type=field_type,
142 array_len=field[2])
143 elif len(field) == 4:
144 nelem_field = None
145 for f in fields:
146 if f.name == field[3]:
147 nelem_field = f
148 if nelem_field is None:
149 raise ParseError(
150 "While parsing message `%s': couldn't find "
151 "variable length array `%s' member containing "
152 "the actual length `%s'" % (
153 name, field[1], field[3]))
154 p = field_class(
155 field_name=field[1],
156 field_type=field_type,
157 array_len=field[2],
158 nelem_field=nelem_field)
159 else:
160 raise Exception("Don't know how to parse message "
161 "definition for message `%s': `%s'" %
162 (m, m[1:]))
163 logger.debug("Parsed field `%s'" % p)
164 fields.append(p)
165 self.fields = fields
166
167 def is_dump(self):
168 return self.name.endswith('_dump')
169
170 def is_reply(self):
171 return msg_is_reply(self.name)
172
173
174class StructType (Type, Struct):
175
176 def __init__(self, definition, typedict, field_class):
177 t = definition
178 name = t[0]
179 fields = []
180 for field in t[1:]:
181 if len(field) == 1 and 'crc' in field:
182 self.crc = field['crc']
183 continue
184 elif len(field) == 2:
185 p = field_class(field_name=field[1],
186 field_type=typedict[field[0]])
187 elif len(field) == 3:
188 if field[2] == 0:
189 raise ParseError("While parsing type `%s': array `%s' has "
190 "variable length" % (name, field[1]))
191 p = field_class(field_name=field[1],
192 field_type=typedict[field[0]],
193 array_len=field[2])
194 else:
195 raise ParseError(
196 "Don't know how to parse type definition for "
197 "type `%s': `%s'" % (t, t[1:]))
198 fields.append(p)
199 Type.__init__(self, name)
200 Struct.__init__(self, name, fields)
201
202 def has_field(self, name):
203 return name in self.field_names
204
205 def is_part_of_def(self, definition):
206 for idx in range(len(self.fields)):
207 field = definition[idx]
208 p = self.fields[idx]
209 if field[1] != p.name:
210 return False
211 if field[0] != p.type.name:
212 raise ParseError(
213 "Unexpected field type `%s' (should be `%s'), "
214 "while parsing msg/def/field `%s/%s/%s'" %
215 (field[0], p.type, p.name, definition, field))
216 return True
217
218
219class JsonParser:
220 def __init__(self, logger, files, simple_type_class=SimpleType,
221 struct_type_class=StructType, field_class=Field,
222 message_class=Message):
223 self.messages = {}
224 self.types = {
225 x: simple_type_class(x) for x in [
226 'i8', 'i16', 'i32', 'i64',
227 'u8', 'u16', 'u32', 'u64',
228 'f64'
229 ]
230 }
231
232 self.simple_type_class = simple_type_class
233 self.struct_type_class = struct_type_class
234 self.field_class = field_class
235 self.message_class = message_class
236
237 self.exceptions = []
238 self.json_files = []
239 self.types_by_json = {}
240 self.messages_by_json = {}
241 self.logger = logger
242 for f in files:
243 self.parse_json_file(f)
244 self.finalize_parsing()
245
246 def parse_json_file(self, path):
247 self.logger.info("Parsing json api file: `%s'" % path)
248 self.json_files.append(path)
249 self.types_by_json[path] = {}
250 self.messages_by_json[path] = {}
251 with open(path) as f:
252 j = json.load(f)
253 for t in j['types']:
254 try:
255 type_ = self.struct_type_class(t, self.types,
256 self.field_class)
257 if type_.name in self.types:
258 raise ParseError("Duplicate type `%s'" % type_.name)
259 except ParseError as e:
260 self.exceptions.append(e)
261 continue
262 self.types[type_.name] = type_
263 self.types_by_json[path][type_.name] = type_
264 for m in j['messages']:
265 try:
266 msg = self.message_class(self.logger, m, self.types,
267 self.struct_type_class,
268 self.simple_type_class,
269 self.field_class)
270 if msg.name in self.messages:
271 raise ParseError("Duplicate message `%s'" % msg.name)
272 except ParseError as e:
273 self.exceptions.append(e)
274 continue
275 self.messages[msg.name] = msg
276 self.messages_by_json[path][msg.name] = msg
277
278 def get_reply(self, message):
279 if self.messages[message].is_dump():
280 return self.messages["%s_details" % message[:-len("_dump")]]
281 return self.messages["%s_reply" % message]
282
283 def finalize_parsing(self):
284 if len(self.messages) == 0:
285 for e in self.exceptions:
286 self.logger.error(e)
287 raise Exception("No messages parsed.")
288 for jn, j in self.messages_by_json.items():
289 remove = []
290 for n, m in j.items():
291 try:
292 if not m.is_reply():
293 try:
294 m.reply = self.get_reply(n)
295 except:
296 raise ParseError(
297 "Cannot find reply to message `%s'" % n)
298 except ParseError as e:
299 self.exceptions.append(e)
300 remove.append(n)
301
302 self.messages_by_json[jn] = {
303 k: v for k, v in j.items() if k not in remove}