3 # Copyright (c) 2016 Cisco and/or its affiliates.
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:
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 from __future__ import print_function
18 import argparse, sys, os, importlib, pprint
20 parser = argparse.ArgumentParser(description='VPP Python API generator')
21 parser.add_argument('-i', '--input', action="store", dest="inputfile", type=argparse.FileType('r'))
22 parser.add_argument('-c', '--cfile', action="store")
23 args = parser.parse_args()
26 # Read API definitions file into vppapidefs
28 exec(args.inputfile.read())
30 # https://docs.python.org/3/library/struct.html
31 format_struct = {'u8': 'B',
37 'vl_api_ip4_fib_counter_t' : 'IBQQ',
38 'vl_api_ip6_fib_counter_t' : 'QQBQQ',
39 'vl_api_lisp_adjacency_t' : 'B' * 35
42 # NB: If new types are introduced in vpe.api, these must be updated.
50 'vl_api_ip4_fib_counter_t' : 21,
51 'vl_api_ip6_fib_counter_t' : 33,
52 'vl_api_lisp_adjacency_t' : 35
55 def eprint(*args, **kwargs):
56 print(*args, file=sys.stderr, **kwargs)
62 argslist.append(i[1][1:])
73 if len(f) is 3 or len(f) is 4:
74 size = type_size[f[0]]
75 bytecount += size * int(f[2])
76 # Check if we have a zero length array
80 pack += format_struct[f[0]]
86 pack += format_struct[f[0]] * int(f[2])
89 bytecount += type_size[f[0]]
90 pack += format_struct[f[0]]
91 return (pack, elements, bytecount)
95 def get_reply_func(f):
96 if f['name']+'_reply' in func_name:
97 return func_name[f['name']+'_reply']
98 if f['name'].find('_dump') > 0:
99 r = f['name'].replace('_dump','_details')
107 def msg_id_base_set(b):
112 name = os.path.splitext(os.path.basename(__file__))[0]
114 print(u"plugin_register(name, api_func_table, api_name_to_id,", vl_api_version, ", msg_id_base_set)")
116 def api_table_print(name, i):
117 msg_id_in = 'VL_API_' + name.upper()
118 fstr = name + '_decode'
119 print('api_func_table.append(' + fstr + ')')
120 print('api_name_to_id["' + msg_id_in + '"] =', i)
124 def encode_print(name, id, t):
127 if name.find('_dump') > 0:
133 print(u"def", name + "(async = False):")
135 print(u"def", name + "(" + ', '.join(args[3:]) + ", async = False):")
136 print(u" global base")
137 print(u" context = get_context(base + " + id + ")")
140 results_prepare(context)
141 waiting_for_reply_set()
143 if multipart == True:
144 print(u" results_more_set(context)")
148 # only the last field can be a variable-length-array
149 # it can either be 0, or a string
150 # first, deal with all the other fields
151 pack = '>' + ''.join([get_pack(f)[0] for f in t[:-1]])
153 # named variable-length-array
154 if len(t[-1]) == 4 and t[-1][2] == '0' and t[-1][3] == t[-2][1]:
155 print(u" vpp_api.write(pack('" + pack + "', base + "
156 + id + ", 0, context, " + ', '.join(args[3:-2] + ["len(" + args[-1] + ")"])
157 + ") + " + args[-1] + ")")
159 # unnamed variable-length-array
160 elif len(t[-1]) >= 3 and t[-1][2] == '0':
161 print(u" vpp_api.write(pack('" + pack + "', base + " +
162 id + ", 0, context, " + ', '.join(args[3:-1]) + ") + "
166 # not a variable-length-array
168 pack += get_pack(t[-1])[0]
169 print(u" vpp_api.write(pack('" + pack + "', base + " + id +
170 ", 0, context, " + ', '.join(args[3:]) + "))")
172 if multipart == True:
174 u" vpp_api.write(pack('>HII', VL_API_CONTROL_PING, 0, context))")
178 results_event_wait(context, 5)
179 return results_get(context)
183 def get_normal_pack(t, i, pack, offset):
188 return t, i, pack, offset, f
189 p, elements, size = get_pack(f)
192 return t, i, pack, offset, None
194 def decode_print(name, t):
196 # Generate code for each element
198 print(u'def ' + name + u'_decode(msg):')
201 print(u" n = namedtuple('" + name + "', '" + ', '.join(args) + "')")
211 t, i, pack, offset, array = get_normal_pack(t, i, pack, offset)
213 p, elements, size = get_pack(array)
216 if elements > 0 and type_size[array[0]] == 1:
218 offset += size * elements
221 # Dump current pack string
223 print(u" tr = unpack_from('" + pack + "', msg[" + str(start) + ":])")
224 print(u" res.extend(list(tr))")
229 # This has to be the last element
231 print(u" res.append(msg[" + str(offset) + ":])")
233 eprint('WARNING: Variable length array must be last element in message', name, array)
236 if size == 1 or len(p) == 1:
237 # Do it as a bytestring.
240 # XXX: Assume that length parameter is the previous field. Add validation.
241 print(u" c = res[" + str(i - 2) + "]")
242 print(u" tr = unpack_from('>' + str(c) + '" + p + "', msg[" + str(start) + ":])")
243 print(u" res.append(tr)")
246 print(u" offset = " + str(total))
247 print(u" for j in range(res[" + str(i - 2) + "]):")
248 print(u" tr2.append(unpack_from('>" + p + "', msg[" + str(start) + ":], offset))")
249 print(u" offset += " + str(size))
250 print(u" res.append(tr2)")
253 # Missing something!!
254 print(u" tr = unpack_from('>" + p + "', msg[" + str(start) + ":])")
257 print(u" res.append(tr)")
260 print(u" tr = unpack_from('" + pack + "', msg[" + str(start) + ":])")
261 print(u" res.extend(list(tr))")
262 print(u" return n._make(res)")
266 # Generate the main Python file
271 # AUTO-GENERATED FILE. PLEASE DO NOT EDIT.
273 from vpp_api_base import *
275 from collections import namedtuple
281 for i, a in enumerate(messages):
283 encode_print(name, str(i), a[1:])
284 decode_print(name, a[1:])
285 api_table_print(name, i)
288 if __name__ == "__main__":