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 import argparse, sys, os, importlib, pprint
19 parser = argparse.ArgumentParser(description='VPP Python API generator')
20 parser.add_argument('-i', action="store", dest="inputfile")
21 parser.add_argument('-c', '--cfile', action="store")
22 args = parser.parse_args()
26 inputfile = args.inputfile.replace('.py', '')
27 cfg = importlib.import_module(inputfile, package=None)
29 # https://docs.python.org/3/library/struct.html
30 format_struct = {'u8': 'B',
36 'vl_api_ip4_fib_counter_t' : 'IBQQ',
37 'vl_api_ip6_fib_counter_t' : 'QQBQQ',
38 'vl_api_lisp_adjacency_t' : 'B' * 35,
41 # NB: If new types are introduced in vpe.api, these must be updated.
49 'vl_api_ip4_fib_counter_t' : 21,
50 'vl_api_ip6_fib_counter_t' : 33,
51 'vl_api_lisp_adjacency_t' : 35,
58 argslist.append(i[1][1:])
72 if len(i) is 3 or len(i) is 4: # TODO: add support for variable length arrays (VPP-162)
73 size = type_size[i[0]]
74 bytecount += size * int(i[2])
75 # Check if we have a zero length array
77 tup += 'msg[' + str(bytecount) + ':],'
83 tup += 'tr[' + str(j) + '],'
85 pack += format_struct[i[0]] * int(i[2])
86 tup += 'tr[' + str(j) + ':' + str(j + int(i[2])) + '],'
89 bytecount += type_size[i[0]]
90 pack += format_struct[i[0]]
91 tup += 'tr[' + str(j) + '],'
92 return pack, bytecount, tup, zeroarray
94 def get_reply_func(f):
95 if f['name']+'_reply' in func_name:
96 return func_name[f['name']+'_reply']
97 if f['name'].find('_dump') > 0:
98 r = f['name'].replace('_dump','_details')
104 # Read enums from stdin
109 l = l.replace(',\n','')
112 l = l.replace('VL_API_','').lower()
114 enums_by_index[i] = l
117 return enums_by_name, enums_by_index
119 def get_definitions():
124 for a in cfg.messages:
125 pack, packlen, tup, zeroarray = get_pack(a[1:])
126 func_name[a[0]] = dict([('name', a[0]), ('pack', pack), ('packlen', packlen), ('tup', tup), ('args', get_args(a[1:])),
127 ('zeroarray', zeroarray)])
128 func_list.append(func_name[a[0]]) # Indexed by name
129 return func_list, func_name
131 def generate_c_macros(func_list, enums_by_name):
132 file = open(args.cfile, 'w+')
133 print >>file, "#define foreach_api_msg \\"
135 if not f['name'] in enums_by_name:
137 print >>file, "_(" + f['name'].upper() + ", " + f['name'] + ") \\"
139 void pneum_set_handlers(void) {
141 api_func_table[VL_API_##N] = sizeof(vl_api_##n##_t);
148 # Print array with a hash of 'decode' and 'multipart'
149 # Simplify to do only decode for now. And deduce multipart from _dump?
151 def decode_function_print(name, args, pack, packlen, tup):
153 print(u'def ' + name + u'_decode(msg):')
154 print(u" n = namedtuple('" + name + "', '" + ', '.join(args) + "')" +
159 print(u" tr = unpack('" + pack + "', msg[:" + str(packlen) + "])")
160 print(u" r = n._make((" + tup + "))" +
167 def function_print(name, id, args, pack, multipart, zeroarray):
169 print "def", name + "(async = False):"
171 print "def", name + "(" + ', '.join(args[3:]) + ", async = False):"
172 print " global waiting_for_reply"
173 print " context = get_context(" + id + ")"
176 results[context] = {}
177 results[context]['e'] = threading.Event()
178 results[context]['e'].clear()
179 results[context]['r'] = []
180 waiting_for_reply = True
182 if multipart == True:
183 print " results[context]['m'] = True"
185 if zeroarray == True:
186 print " vpp_api.write(pack('" + pack + "', " + id + ", 0, context, " + ', '.join(args[3:-1]) + ") + " + args[-1] + ")"
188 print " vpp_api.write(pack('" + pack + "', " + id + ", 0, context, " + ', '.join(args[3:]) + "))"
190 if multipart == True:
191 print " vpp_api.write(pack('>HII', VL_API_CONTROL_PING, 0, context))"
195 results[context]['e'].wait(5)
196 return results[context]['r']
201 # Should dynamically create size
203 def api_table_print (name, msg_id):
205 print('api_func_table[' + msg_id + '] = ' + f)
208 # Generate the main Python file
214 # AUTO-GENERATED FILE. PLEASE DO NOT EDIT.
216 import sys, time, threading, signal, os, logging
218 from collections import namedtuple
221 # Import C API shared object
227 waiting_for_reply = False
230 # XXX: Make this return a unique number
237 def msg_handler(msg):
238 global result, context, event_callback, waiting_for_reply
240 logging.warning('vpp_api.read failed')
243 id = unpack('>H', msg[0:2])
244 logging.debug('Received message', id[0])
245 if id[0] == VL_API_RX_THREAD_EXIT:
246 logging.info("We got told to leave")
250 # Decode message and returns a tuple.
252 logging.debug('api_func', api_func_table[id[0]])
253 r = api_func_table[id[0]](msg)
255 logging.warning('Message decode failed', id[0])
258 if 'context' in r._asdict():
263 # XXX: Call provided callback for event
264 # Are we guaranteed to not get an event during processing of other messages?
265 # How to differentiate what's a callback message and what not? Context = 0?
267 logging.debug('R:', context, r, waiting_for_reply)
268 if waiting_for_reply == False:
273 # Collect results until control ping
275 if id[0] == VL_API_CONTROL_PING_REPLY:
276 results[context]['e'].set()
277 waiting_for_reply = False
279 if not context in results:
280 logging.warning('Not expecting results for this context', context)
282 if 'm' in results[context]:
283 results[context]['r'].append(r)
286 results[context]['r'] = r
287 results[context]['e'].set()
288 waiting_for_reply = False
291 signal.alarm(3) # 3 second
292 rv = vpp_api.connect(name, msg_handler)
294 logging.info("Connect:", rv)
298 rv = vpp_api.disconnect()
299 logging.info("Disconnected")
302 def register_event_callback(callback):
303 global event_callback
304 event_callback = callback
307 enums_by_name, enums_by_index = get_enums()
308 func_list, func_name = get_definitions()
311 # Not needed with the new msg_size field.
312 # generate_c_macros(func_list, enums_by_name)
315 pp = pprint.PrettyPrinter(indent=4)
316 #print 'enums_by_index =', pp.pprint(enums_by_index)
317 #print 'func_name =', pp.pprint(func_name)
322 # 1) The VPE API lacks a clear definition of what messages are reply messages
323 # 2) Length is missing, and has to be pre-known or in case of variable sized ones calculated per message type
326 #if f['name'].find('_reply') > 0 or f['name'].find('_details') > 0:
327 decode_function_print(f['name'], f['args'], f['pack'], f['packlen'], f['tup'])
329 #r = get_reply_func(f)
332 # # XXX: Functions here are not taken care of. E.g. events
334 # print('Missing function', f)
337 if f['name'].find('_dump') > 0:
338 f['multipart'] = True
340 f['multipart'] = False
341 msg_id_in = 'VL_API_' + f['name'].upper()
342 function_print(f['name'], msg_id_in, f['args'], f['pack'], f['multipart'], f['zeroarray'])
345 print "api_func_table = [0] * 10000"
347 # if f['name'].find('_reply') > 0 or f['name'].find('_details') > 0:
348 msg_id_in = 'VL_API_' + f['name'].upper()
349 api_table_print(f['name'], msg_id_in)