Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 1 | #!/usr/bin/env python |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 2 | # |
| 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: |
| 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. |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 15 | # |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 16 | |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 17 | from __future__ import print_function |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 18 | from __future__ import absolute_import |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 19 | import sys |
| 20 | import os |
| 21 | import logging |
| 22 | import collections |
| 23 | import struct |
| 24 | import json |
| 25 | import threading |
Chris Luke | 52bf22e | 2017-11-03 23:32:38 -0400 | [diff] [blame] | 26 | import fnmatch |
Klement Sekera | 180402d | 2018-02-17 10:58:37 +0100 | [diff] [blame] | 27 | import weakref |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 28 | import atexit |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 29 | from cffi import FFI |
Ole Troan | a74b741 | 2017-11-01 10:49:03 +0100 | [diff] [blame] | 30 | import cffi |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 31 | from . vpp_serializer import VPPType, VPPEnumType, VPPUnionType, BaseTypes |
| 32 | from . vpp_serializer import VPPMessage |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 33 | |
| 34 | if sys.version[0] == '2': |
| 35 | import Queue as queue |
| 36 | else: |
| 37 | import queue as queue |
| 38 | |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 39 | ffi = FFI() |
| 40 | ffi.cdef(""" |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 41 | typedef void (*vac_callback_t)(unsigned char * data, int len); |
| 42 | typedef void (*vac_error_callback_t)(void *, unsigned char *, int); |
| 43 | int vac_connect(char * name, char * chroot_prefix, vac_callback_t cb, |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 44 | int rx_qlen); |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 45 | int vac_disconnect(void); |
| 46 | int vac_read(char **data, int *l, unsigned short timeout); |
| 47 | int vac_write(char *data, int len); |
| 48 | void vac_free(void * msg); |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 49 | |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 50 | int vac_get_msg_index(unsigned char * name); |
| 51 | int vac_msg_table_size(void); |
| 52 | int vac_msg_table_max_index(void); |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 53 | |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 54 | void vac_rx_suspend (void); |
| 55 | void vac_rx_resume (void); |
| 56 | void vac_set_error_handler(vac_error_callback_t); |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 57 | """) |
| 58 | |
| 59 | # Barfs on failure, no need to check success. |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 60 | vpp_api = ffi.dlopen('libvppapiclient.so') |
Ole Troan | 1732fc1 | 2016-08-30 21:03:51 +0200 | [diff] [blame] | 61 | |
Ole Troan | afddd83 | 2018-02-28 14:55:20 +0100 | [diff] [blame] | 62 | |
Klement Sekera | 180402d | 2018-02-17 10:58:37 +0100 | [diff] [blame] | 63 | def vpp_atexit(vpp_weakref): |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 64 | """Clean up VPP connection on shutdown.""" |
Klement Sekera | 180402d | 2018-02-17 10:58:37 +0100 | [diff] [blame] | 65 | vpp_instance = vpp_weakref() |
juraj.linkes | 184870a | 2018-07-16 14:22:01 +0200 | [diff] [blame^] | 66 | if vpp_instance and vpp_instance.connected: |
Klement Sekera | 180402d | 2018-02-17 10:58:37 +0100 | [diff] [blame] | 67 | vpp_instance.logger.debug('Cleaning up VPP on exit') |
| 68 | vpp_instance.disconnect() |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 69 | |
Ole Troan | afddd83 | 2018-02-28 14:55:20 +0100 | [diff] [blame] | 70 | |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 71 | vpp_object = None |
| 72 | |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 73 | |
| 74 | def vpp_iterator(d): |
| 75 | if sys.version[0] == '2': |
| 76 | return d.iteritems() |
| 77 | else: |
| 78 | return d.items() |
| 79 | |
| 80 | |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 81 | @ffi.callback("void(unsigned char *, int)") |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 82 | def vac_callback_sync(data, len): |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 83 | vpp_object.msg_handler_sync(ffi.buffer(data, len)) |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 84 | |
| 85 | |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 86 | @ffi.callback("void(unsigned char *, int)") |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 87 | def vac_callback_async(data, len): |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 88 | vpp_object.msg_handler_async(ffi.buffer(data, len)) |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 89 | |
| 90 | |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 91 | @ffi.callback("void(void *, unsigned char *, int)") |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 92 | def vac_error_handler(arg, msg, msg_len): |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 93 | vpp_object.logger.warning("VPP API client:: %s", ffi.string(msg, msg_len)) |
| 94 | |
Klement Sekera | 7112c54 | 2017-03-01 09:53:19 +0100 | [diff] [blame] | 95 | |
Klement Sekera | 8aedf5e | 2018-07-06 11:07:21 +0200 | [diff] [blame] | 96 | class VppApiDynamicMethodHolder(object): |
Klement Sekera | 7112c54 | 2017-03-01 09:53:19 +0100 | [diff] [blame] | 97 | pass |
| 98 | |
| 99 | |
| 100 | class FuncWrapper(object): |
| 101 | def __init__(self, func): |
| 102 | self._func = func |
| 103 | self.__name__ = func.__name__ |
| 104 | |
| 105 | def __call__(self, **kwargs): |
| 106 | return self._func(**kwargs) |
| 107 | |
| 108 | |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 109 | class VPP(): |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 110 | """VPP interface. |
| 111 | |
| 112 | This class provides the APIs to VPP. The APIs are loaded |
| 113 | from provided .api.json files and makes functions accordingly. |
| 114 | These functions are documented in the VPP .api files, as they |
| 115 | are dynamically created. |
| 116 | |
| 117 | Additionally, VPP can send callback messages; this class |
| 118 | provides a means to register a callback function to receive |
| 119 | these messages in a background thread. |
| 120 | """ |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 121 | |
| 122 | def process_json_file(self, apidef_file): |
| 123 | api = json.load(apidef_file) |
| 124 | types = {} |
| 125 | for t in api['enums']: |
| 126 | t[0] = 'vl_api_' + t[0] + '_t' |
| 127 | types[t[0]] = {'type': 'enum', 'data': t} |
| 128 | for t in api['unions']: |
| 129 | t[0] = 'vl_api_' + t[0] + '_t' |
| 130 | types[t[0]] = {'type': 'union', 'data': t} |
| 131 | for t in api['types']: |
| 132 | t[0] = 'vl_api_' + t[0] + '_t' |
| 133 | types[t[0]] = {'type': 'type', 'data': t} |
| 134 | |
| 135 | i = 0 |
| 136 | while True: |
| 137 | unresolved = {} |
| 138 | for k, v in types.items(): |
| 139 | t = v['data'] |
| 140 | if v['type'] == 'enum': |
| 141 | try: |
| 142 | VPPEnumType(t[0], t[1:]) |
| 143 | except ValueError: |
| 144 | unresolved[k] = v |
| 145 | elif v['type'] == 'union': |
| 146 | try: |
| 147 | VPPUnionType(t[0], t[1:]) |
| 148 | except ValueError: |
| 149 | unresolved[k] = v |
| 150 | elif v['type'] == 'type': |
| 151 | try: |
| 152 | VPPType(t[0], t[1:]) |
| 153 | except ValueError: |
| 154 | unresolved[k] = v |
| 155 | if len(unresolved) == 0: |
| 156 | break |
| 157 | if i > 3: |
| 158 | raise ValueError('Unresolved type definitions {}' |
| 159 | .format(unresolved)) |
| 160 | types = unresolved |
| 161 | i += 1 |
| 162 | |
| 163 | for m in api['messages']: |
| 164 | try: |
| 165 | self.messages[m[0]] = VPPMessage(m[0], m[1:]) |
| 166 | except NotImplementedError: |
| 167 | self.logger.error('Not implemented error for {}'.format(m[0])) |
| 168 | |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 169 | def __init__(self, apifiles=None, testmode=False, async_thread=True, |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 170 | logger=logging.getLogger('vpp_papi'), loglevel='debug', |
Ole Troan | afddd83 | 2018-02-28 14:55:20 +0100 | [diff] [blame] | 171 | read_timeout=0): |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 172 | """Create a VPP API object. |
| 173 | |
| 174 | apifiles is a list of files containing API |
| 175 | descriptions that will be loaded - methods will be |
| 176 | dynamically created reflecting these APIs. If not |
| 177 | provided this will load the API files from VPP's |
| 178 | default install location. |
Ian Wells | d0e812f | 2018-06-06 14:12:27 +0100 | [diff] [blame] | 179 | |
| 180 | logger, if supplied, is the logging logger object to log to. |
| 181 | loglevel, if supplied, is the log level this logger is set |
| 182 | to report at (from the loglevels in the logging module). |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 183 | """ |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 184 | global vpp_object |
| 185 | vpp_object = self |
Ian Wells | d0e812f | 2018-06-06 14:12:27 +0100 | [diff] [blame] | 186 | |
| 187 | if logger is None: |
| 188 | logger = logging.getLogger(__name__) |
| 189 | if loglevel is not None: |
| 190 | logger.setLevel(loglevel) |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 191 | self.logger = logger |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 192 | |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 193 | self.messages = {} |
| 194 | self.id_names = [] |
| 195 | self.id_msgdef = [] |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 196 | self.connected = False |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 197 | self.header = VPPType('header', [['u16', 'msgid'], |
| 198 | ['u32', 'client_index']]) |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 199 | self.apifiles = [] |
Ole Troan | 3d31f00 | 2017-01-26 11:13:00 +0100 | [diff] [blame] | 200 | self.event_callback = None |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 201 | self.message_queue = queue.Queue() |
dongjuan | 8493752 | 2017-11-09 14:46:36 +0800 | [diff] [blame] | 202 | self.read_timeout = read_timeout |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 203 | self.vpp_api = vpp_api |
Klement Sekera | 180402d | 2018-02-17 10:58:37 +0100 | [diff] [blame] | 204 | self.async_thread = async_thread |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 205 | |
Ole Troan | f5984bd | 2016-12-18 13:15:08 +0100 | [diff] [blame] | 206 | if not apifiles: |
| 207 | # Pick up API definitions from default directory |
Chris Luke | 52bf22e | 2017-11-03 23:32:38 -0400 | [diff] [blame] | 208 | try: |
| 209 | apifiles = self.find_api_files() |
| 210 | except RuntimeError: |
| 211 | # In test mode we don't care that we can't find the API files |
| 212 | if testmode: |
| 213 | apifiles = [] |
| 214 | else: |
| 215 | raise |
Ole Troan | f5984bd | 2016-12-18 13:15:08 +0100 | [diff] [blame] | 216 | |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 217 | for file in apifiles: |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 218 | with open(file) as apidef_file: |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 219 | self.process_json_file(apidef_file) |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 220 | |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 221 | self.apifiles = apifiles |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 222 | |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 223 | # Basic sanity check |
Ole Troan | f5984bd | 2016-12-18 13:15:08 +0100 | [diff] [blame] | 224 | if len(self.messages) == 0 and not testmode: |
| 225 | raise ValueError(1, 'Missing JSON message definitions') |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 226 | |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 227 | # Make sure we allow VPP to clean up the message rings. |
Klement Sekera | 180402d | 2018-02-17 10:58:37 +0100 | [diff] [blame] | 228 | atexit.register(vpp_atexit, weakref.ref(self)) |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 229 | |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 230 | # Register error handler |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 231 | if not testmode: |
| 232 | vpp_api.vac_set_error_handler(vac_error_handler) |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 233 | |
Ole Troan | a74b741 | 2017-11-01 10:49:03 +0100 | [diff] [blame] | 234 | # Support legacy CFFI |
| 235 | # from_buffer supported from 1.8.0 |
Ole Troan | afddd83 | 2018-02-28 14:55:20 +0100 | [diff] [blame] | 236 | (major, minor, patch) = [int(s) for s in |
| 237 | cffi.__version__.split('.', 3)] |
Ole Troan | a74b741 | 2017-11-01 10:49:03 +0100 | [diff] [blame] | 238 | if major >= 1 and minor >= 8: |
| 239 | self._write = self._write_new_cffi |
| 240 | else: |
| 241 | self._write = self._write_legacy_cffi |
| 242 | |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 243 | class ContextId(object): |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 244 | """Thread-safe provider of unique context IDs.""" |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 245 | def __init__(self): |
| 246 | self.context = 0 |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 247 | self.lock = threading.Lock() |
| 248 | |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 249 | def __call__(self): |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 250 | """Get a new unique (or, at least, not recently used) context.""" |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 251 | with self.lock: |
| 252 | self.context += 1 |
| 253 | return self.context |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 254 | get_context = ContextId() |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 255 | |
Chris Luke | 52bf22e | 2017-11-03 23:32:38 -0400 | [diff] [blame] | 256 | @classmethod |
| 257 | def find_api_dir(cls): |
| 258 | """Attempt to find the best directory in which API definition |
| 259 | files may reside. If the value VPP_API_DIR exists in the environment |
| 260 | then it is first on the search list. If we're inside a recognized |
| 261 | location in a VPP source tree (src/scripts and src/vpp-api/python) |
| 262 | then entries from there to the likely locations in build-root are |
| 263 | added. Finally the location used by system packages is added. |
| 264 | |
| 265 | :returns: A single directory name, or None if no such directory |
| 266 | could be found. |
| 267 | """ |
| 268 | dirs = [] |
| 269 | |
| 270 | if 'VPP_API_DIR' in os.environ: |
| 271 | dirs.append(os.environ['VPP_API_DIR']) |
| 272 | |
| 273 | # perhaps we're in the 'src/scripts' or 'src/vpp-api/python' dir; |
| 274 | # in which case, plot a course to likely places in the src tree |
| 275 | import __main__ as main |
| 276 | if hasattr(main, '__file__'): |
| 277 | # get the path of the calling script |
| 278 | localdir = os.path.dirname(os.path.realpath(main.__file__)) |
| 279 | else: |
| 280 | # use cwd if there is no calling script |
Andrey "Zed" Zaikin | 68e2ffb | 2018-04-24 14:50:02 +0300 | [diff] [blame] | 281 | localdir = os.getcwd() |
Chris Luke | 52bf22e | 2017-11-03 23:32:38 -0400 | [diff] [blame] | 282 | localdir_s = localdir.split(os.path.sep) |
| 283 | |
| 284 | def dmatch(dir): |
| 285 | """Match dir against right-hand components of the script dir""" |
| 286 | d = dir.split('/') # param 'dir' assumes a / separator |
Ole Troan | afddd83 | 2018-02-28 14:55:20 +0100 | [diff] [blame] | 287 | length = len(d) |
| 288 | return len(localdir_s) > length and localdir_s[-length:] == d |
Chris Luke | 52bf22e | 2017-11-03 23:32:38 -0400 | [diff] [blame] | 289 | |
| 290 | def sdir(srcdir, variant): |
| 291 | """Build a path from srcdir to the staged API files of |
| 292 | 'variant' (typically '' or '_debug')""" |
| 293 | # Since 'core' and 'plugin' files are staged |
| 294 | # in separate directories, we target the parent dir. |
| 295 | return os.path.sep.join(( |
| 296 | srcdir, |
| 297 | 'build-root', |
| 298 | 'install-vpp%s-native' % variant, |
| 299 | 'vpp', |
| 300 | 'share', |
| 301 | 'vpp', |
| 302 | 'api', |
| 303 | )) |
| 304 | |
| 305 | srcdir = None |
| 306 | if dmatch('src/scripts'): |
| 307 | srcdir = os.path.sep.join(localdir_s[:-2]) |
| 308 | elif dmatch('src/vpp-api/python'): |
| 309 | srcdir = os.path.sep.join(localdir_s[:-3]) |
| 310 | elif dmatch('test'): |
| 311 | # we're apparently running tests |
| 312 | srcdir = os.path.sep.join(localdir_s[:-1]) |
| 313 | |
| 314 | if srcdir: |
| 315 | # we're in the source tree, try both the debug and release |
| 316 | # variants. |
Chris Luke | 52bf22e | 2017-11-03 23:32:38 -0400 | [diff] [blame] | 317 | dirs.append(sdir(srcdir, '_debug')) |
| 318 | dirs.append(sdir(srcdir, '')) |
| 319 | |
| 320 | # Test for staged copies of the scripts |
| 321 | # For these, since we explicitly know if we're running a debug versus |
| 322 | # release variant, target only the relevant directory |
| 323 | if dmatch('build-root/install-vpp_debug-native/vpp/bin'): |
| 324 | srcdir = os.path.sep.join(localdir_s[:-4]) |
| 325 | dirs.append(sdir(srcdir, '_debug')) |
| 326 | if dmatch('build-root/install-vpp-native/vpp/bin'): |
| 327 | srcdir = os.path.sep.join(localdir_s[:-4]) |
| 328 | dirs.append(sdir(srcdir, '')) |
| 329 | |
| 330 | # finally, try the location system packages typically install into |
| 331 | dirs.append(os.path.sep.join(('', 'usr', 'share', 'vpp', 'api'))) |
| 332 | |
| 333 | # check the directories for existance; first one wins |
| 334 | for dir in dirs: |
| 335 | if os.path.isdir(dir): |
| 336 | return dir |
| 337 | |
| 338 | return None |
| 339 | |
| 340 | @classmethod |
| 341 | def find_api_files(cls, api_dir=None, patterns='*'): |
| 342 | """Find API definition files from the given directory tree with the |
| 343 | given pattern. If no directory is given then find_api_dir() is used |
| 344 | to locate one. If no pattern is given then all definition files found |
| 345 | in the directory tree are used. |
| 346 | |
| 347 | :param api_dir: A directory tree in which to locate API definition |
| 348 | files; subdirectories are descended into. |
| 349 | If this is None then find_api_dir() is called to discover it. |
| 350 | :param patterns: A list of patterns to use in each visited directory |
| 351 | when looking for files. |
| 352 | This can be a list/tuple object or a comma-separated string of |
| 353 | patterns. Each value in the list will have leading/trialing |
| 354 | whitespace stripped. |
| 355 | The pattern specifies the first part of the filename, '.api.json' |
| 356 | is appended. |
| 357 | The results are de-duplicated, thus overlapping patterns are fine. |
| 358 | If this is None it defaults to '*' meaning "all API files". |
| 359 | :returns: A list of file paths for the API files found. |
| 360 | """ |
| 361 | if api_dir is None: |
| 362 | api_dir = cls.find_api_dir() |
| 363 | if api_dir is None: |
| 364 | raise RuntimeError("api_dir cannot be located") |
| 365 | |
| 366 | if isinstance(patterns, list) or isinstance(patterns, tuple): |
| 367 | patterns = [p.strip() + '.api.json' for p in patterns] |
| 368 | else: |
| 369 | patterns = [p.strip() + '.api.json' for p in patterns.split(",")] |
| 370 | |
| 371 | api_files = [] |
| 372 | for root, dirnames, files in os.walk(api_dir): |
| 373 | # iterate all given patterns and de-dup the result |
| 374 | files = set(sum([fnmatch.filter(files, p) for p in patterns], [])) |
| 375 | for filename in files: |
| 376 | api_files.append(os.path.join(root, filename)) |
| 377 | |
| 378 | return api_files |
| 379 | |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 380 | def status(self): |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 381 | """Debug function: report current VPP API status to stdout.""" |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 382 | print('Connected') if self.connected else print('Not Connected') |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 383 | print('Read API definitions from', ', '.join(self.apifiles)) |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 384 | |
Klement Sekera | 7112c54 | 2017-03-01 09:53:19 +0100 | [diff] [blame] | 385 | @property |
| 386 | def api(self): |
| 387 | if not hasattr(self, "_api"): |
| 388 | raise Exception("Not connected, api definitions not available") |
| 389 | return self._api |
| 390 | |
Ole Troan | eabd607 | 2018-08-09 12:50:55 +0200 | [diff] [blame] | 391 | def make_function(self, msg, i, multipart, do_async): |
| 392 | if (do_async): |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 393 | def f(**kwargs): |
| 394 | return self._call_vpp_async(i, msg, **kwargs) |
| 395 | else: |
| 396 | def f(**kwargs): |
| 397 | return self._call_vpp(i, msg, multipart, **kwargs) |
| 398 | |
| 399 | f.__name__ = str(msg.name) |
| 400 | f.__doc__ = ", ".join(["%s %s" % |
| 401 | (msg.fieldtypes[j], k) |
| 402 | for j, k in enumerate(msg.fields)]) |
| 403 | return f |
| 404 | |
Ole Troan | eabd607 | 2018-08-09 12:50:55 +0200 | [diff] [blame] | 405 | def _register_functions(self, do_async=False): |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 406 | self.id_names = [None] * (self.vpp_dictionary_maxid + 1) |
| 407 | self.id_msgdef = [None] * (self.vpp_dictionary_maxid + 1) |
Klement Sekera | 8aedf5e | 2018-07-06 11:07:21 +0200 | [diff] [blame] | 408 | self._api = VppApiDynamicMethodHolder() |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 409 | for name, msg in vpp_iterator(self.messages): |
| 410 | n = name + '_' + msg.crc[2:] |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 411 | i = vpp_api.vac_get_msg_index(n.encode()) |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 412 | if i > 0: |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 413 | self.id_msgdef[i] = msg |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 414 | self.id_names[i] = name |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 415 | # TODO: Fix multipart (use services) |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 416 | multipart = True if name.find('_dump') > 0 else False |
Ole Troan | eabd607 | 2018-08-09 12:50:55 +0200 | [diff] [blame] | 417 | f = self.make_function(msg, i, multipart, do_async) |
Klement Sekera | 7112c54 | 2017-03-01 09:53:19 +0100 | [diff] [blame] | 418 | setattr(self._api, name, FuncWrapper(f)) |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 419 | else: |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 420 | self.logger.debug( |
| 421 | 'No such message type or failed CRC checksum: %s', n) |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 422 | |
Ole Troan | a74b741 | 2017-11-01 10:49:03 +0100 | [diff] [blame] | 423 | def _write_new_cffi(self, buf): |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 424 | """Send a binary-packed message to VPP.""" |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 425 | if not self.connected: |
| 426 | raise IOError(1, 'Not connected') |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 427 | return vpp_api.vac_write(ffi.from_buffer(buf), len(buf)) |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 428 | |
Ole Troan | a74b741 | 2017-11-01 10:49:03 +0100 | [diff] [blame] | 429 | def _write_legacy_cffi(self, buf): |
| 430 | """Send a binary-packed message to VPP.""" |
| 431 | if not self.connected: |
| 432 | raise IOError(1, 'Not connected') |
Andrey "Zed" Zaikin | 7fe930b | 2018-04-12 12:14:02 +0300 | [diff] [blame] | 433 | return vpp_api.vac_write(bytes(buf), len(buf)) |
Ole Troan | a74b741 | 2017-11-01 10:49:03 +0100 | [diff] [blame] | 434 | |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 435 | def _read(self): |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 436 | if not self.connected: |
| 437 | raise IOError(1, 'Not connected') |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 438 | mem = ffi.new("char **") |
| 439 | size = ffi.new("int *") |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 440 | rv = vpp_api.vac_read(mem, size, self.read_timeout) |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 441 | if rv: |
Ole Troan | b0856b4 | 2017-08-17 12:48:08 +0200 | [diff] [blame] | 442 | raise IOError(rv, 'vac_read failed') |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 443 | msg = bytes(ffi.buffer(mem[0], size[0])) |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 444 | vpp_api.vac_free(mem[0]) |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 445 | return msg |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 446 | |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 447 | def connect_internal(self, name, msg_handler, chroot_prefix, rx_qlen, |
Ole Troan | eabd607 | 2018-08-09 12:50:55 +0200 | [diff] [blame] | 448 | do_async): |
Ole Troan | 6bf177c | 2017-08-17 10:34:32 +0200 | [diff] [blame] | 449 | pfx = chroot_prefix.encode() if chroot_prefix else ffi.NULL |
| 450 | rv = vpp_api.vac_connect(name.encode(), pfx, msg_handler, rx_qlen) |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 451 | if rv != 0: |
| 452 | raise IOError(2, 'Connect failed') |
Ole Troan | 7e3a875 | 2016-12-05 10:27:09 +0100 | [diff] [blame] | 453 | self.connected = True |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 454 | self.vpp_dictionary_maxid = vpp_api.vac_msg_table_max_index() |
Ole Troan | eabd607 | 2018-08-09 12:50:55 +0200 | [diff] [blame] | 455 | self._register_functions(do_async=do_async) |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 456 | |
| 457 | # Initialise control ping |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 458 | crc = self.messages['control_ping'].crc |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 459 | self.control_ping_index = vpp_api.vac_get_msg_index( |
| 460 | ('control_ping' + '_' + crc[2:]).encode()) |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 461 | self.control_ping_msgdef = self.messages['control_ping'] |
Klement Sekera | 180402d | 2018-02-17 10:58:37 +0100 | [diff] [blame] | 462 | if self.async_thread: |
| 463 | self.event_thread = threading.Thread( |
| 464 | target=self.thread_msg_handler) |
| 465 | self.event_thread.daemon = True |
| 466 | self.event_thread.start() |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 467 | return rv |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 468 | |
Ole Troan | eabd607 | 2018-08-09 12:50:55 +0200 | [diff] [blame] | 469 | def connect(self, name, chroot_prefix=None, do_async=False, rx_qlen=32): |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 470 | """Attach to VPP. |
| 471 | |
| 472 | name - the name of the client. |
| 473 | chroot_prefix - if VPP is chroot'ed, the prefix of the jail |
Ole Troan | eabd607 | 2018-08-09 12:50:55 +0200 | [diff] [blame] | 474 | do_async - if true, messages are sent without waiting for a reply |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 475 | rx_qlen - the length of the VPP message receive queue between |
| 476 | client and server. |
| 477 | """ |
Ole Troan | eabd607 | 2018-08-09 12:50:55 +0200 | [diff] [blame] | 478 | msg_handler = vac_callback_sync if not do_async else vac_callback_async |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 479 | return self.connect_internal(name, msg_handler, chroot_prefix, rx_qlen, |
Ole Troan | eabd607 | 2018-08-09 12:50:55 +0200 | [diff] [blame] | 480 | do_async) |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 481 | |
Ole Troan | 6bf177c | 2017-08-17 10:34:32 +0200 | [diff] [blame] | 482 | def connect_sync(self, name, chroot_prefix=None, rx_qlen=32): |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 483 | """Attach to VPP in synchronous mode. Application must poll for events. |
| 484 | |
| 485 | name - the name of the client. |
| 486 | chroot_prefix - if VPP is chroot'ed, the prefix of the jail |
| 487 | rx_qlen - the length of the VPP message receive queue between |
| 488 | client and server. |
| 489 | """ |
| 490 | |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 491 | return self.connect_internal(name, ffi.NULL, chroot_prefix, rx_qlen, |
Ole Troan | eabd607 | 2018-08-09 12:50:55 +0200 | [diff] [blame] | 492 | do_async=False) |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 493 | |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 494 | def disconnect(self): |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 495 | """Detach from VPP.""" |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 496 | rv = vpp_api.vac_disconnect() |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 497 | self.connected = False |
Klement Sekera | 180402d | 2018-02-17 10:58:37 +0100 | [diff] [blame] | 498 | self.message_queue.put("terminate event thread") |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 499 | return rv |
| 500 | |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 501 | def msg_handler_sync(self, msg): |
| 502 | """Process an incoming message from VPP in sync mode. |
| 503 | |
| 504 | The message may be a reply or it may be an async notification. |
| 505 | """ |
| 506 | r = self.decode_incoming_msg(msg) |
| 507 | if r is None: |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 508 | return |
| 509 | |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 510 | # If we have a context, then use the context to find any |
| 511 | # request waiting for a reply |
| 512 | context = 0 |
| 513 | if hasattr(r, 'context') and r.context > 0: |
| 514 | context = r.context |
Ole Troan | 5f9dcff | 2016-08-01 04:59:13 +0200 | [diff] [blame] | 515 | |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 516 | if context == 0: |
| 517 | # No context -> async notification that we feed to the callback |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 518 | self.message_queue.put_nowait(r) |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 519 | else: |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 520 | raise IOError(2, 'RPC reply message received in event handler') |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 521 | |
| 522 | def decode_incoming_msg(self, msg): |
| 523 | if not msg: |
Ole Troan | 3cc4971 | 2017-03-08 12:02:24 +0100 | [diff] [blame] | 524 | self.logger.warning('vpp_api.read failed') |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 525 | return |
| 526 | |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 527 | i, ci = self.header.unpack(msg, 0) |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 528 | if self.id_names[i] == 'rx_thread_exit': |
| 529 | return |
| 530 | |
| 531 | # |
| 532 | # Decode message and returns a tuple. |
| 533 | # |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 534 | msgobj = self.id_msgdef[i] |
| 535 | if not msgobj: |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 536 | raise IOError(2, 'Reply message undefined') |
| 537 | |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 538 | r = msgobj.unpack(msg) |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 539 | |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 540 | return r |
| 541 | |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 542 | def msg_handler_async(self, msg): |
| 543 | """Process a message from VPP in async mode. |
| 544 | |
| 545 | In async mode, all messages are returned to the callback. |
| 546 | """ |
| 547 | r = self.decode_incoming_msg(msg) |
| 548 | if r is None: |
| 549 | return |
| 550 | |
| 551 | msgname = type(r).__name__ |
| 552 | |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 553 | if self.event_callback: |
| 554 | self.event_callback(msgname, r) |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 555 | |
| 556 | def _control_ping(self, context): |
| 557 | """Send a ping command.""" |
| 558 | self._call_vpp_async(self.control_ping_index, |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 559 | self.control_ping_msgdef, |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 560 | context=context) |
| 561 | |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 562 | def validate_args(self, msg, kwargs): |
| 563 | d = set(kwargs.keys()) - set(msg.field_by_name.keys()) |
| 564 | if d: |
| 565 | raise ValueError('Invalid argument {} to {}' |
| 566 | .format(list(d), msg.name)) |
| 567 | |
| 568 | def _call_vpp(self, i, msg, multipart, **kwargs): |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 569 | """Given a message, send the message and await a reply. |
| 570 | |
| 571 | msgdef - the message packing definition |
| 572 | i - the message type index |
| 573 | multipart - True if the message returns multiple |
| 574 | messages in return. |
| 575 | context - context number - chosen at random if not |
| 576 | supplied. |
| 577 | The remainder of the kwargs are the arguments to the API call. |
| 578 | |
| 579 | The return value is the message or message array containing |
| 580 | the response. It will raise an IOError exception if there was |
| 581 | no response within the timeout window. |
| 582 | """ |
| 583 | |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 584 | if 'context' not in kwargs: |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 585 | context = self.get_context() |
| 586 | kwargs['context'] = context |
| 587 | else: |
| 588 | context = kwargs['context'] |
| 589 | kwargs['_vl_msg_id'] = i |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 590 | |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 591 | self.validate_args(msg, kwargs) |
| 592 | b = msg.pack(kwargs) |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 593 | vpp_api.vac_rx_suspend() |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 594 | self._write(b) |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 595 | |
| 596 | if multipart: |
| 597 | # Send a ping after the request - we use its response |
| 598 | # to detect that we have seen all results. |
| 599 | self._control_ping(context) |
| 600 | |
| 601 | # Block until we get a reply. |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 602 | rl = [] |
| 603 | while (True): |
| 604 | msg = self._read() |
| 605 | if not msg: |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 606 | raise IOError(2, 'VPP API client: read failed') |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 607 | r = self.decode_incoming_msg(msg) |
| 608 | msgname = type(r).__name__ |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 609 | if context not in r or r.context == 0 or context != r.context: |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 610 | self.message_queue.put_nowait(r) |
| 611 | continue |
| 612 | |
| 613 | if not multipart: |
| 614 | rl = r |
| 615 | break |
| 616 | if msgname == 'control_ping_reply': |
| 617 | break |
| 618 | |
| 619 | rl.append(r) |
| 620 | |
Damjan Marion | 5fec1e8 | 2017-04-13 19:13:47 +0200 | [diff] [blame] | 621 | vpp_api.vac_rx_resume() |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 622 | |
| 623 | return rl |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 624 | |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 625 | def _call_vpp_async(self, i, msg, **kwargs): |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 626 | """Given a message, send the message and await a reply. |
| 627 | |
| 628 | msgdef - the message packing definition |
| 629 | i - the message type index |
| 630 | context - context number - chosen at random if not |
| 631 | supplied. |
| 632 | The remainder of the kwargs are the arguments to the API call. |
| 633 | """ |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 634 | if 'context' not in kwargs: |
Ole Troan | 7e3a875 | 2016-12-05 10:27:09 +0100 | [diff] [blame] | 635 | context = self.get_context() |
| 636 | kwargs['context'] = context |
| 637 | else: |
| 638 | context = kwargs['context'] |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 639 | kwargs['client_index'] = 0 |
Ole Troan | 7e3a875 | 2016-12-05 10:27:09 +0100 | [diff] [blame] | 640 | kwargs['_vl_msg_id'] = i |
Ole Troan | a7564e8 | 2018-06-12 21:06:44 +0200 | [diff] [blame] | 641 | b = msg.pack(kwargs) |
Ole Troan | 7e3a875 | 2016-12-05 10:27:09 +0100 | [diff] [blame] | 642 | |
| 643 | self._write(b) |
| 644 | |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 645 | def register_event_callback(self, callback): |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 646 | """Register a callback for async messages. |
Ole Troan | a03f4ef | 2016-12-02 12:53:55 +0100 | [diff] [blame] | 647 | |
Ole Troan | 5016f99 | 2017-01-19 09:44:44 +0100 | [diff] [blame] | 648 | This will be called for async notifications in sync mode, |
| 649 | and all messages in async mode. In sync mode, replies to |
| 650 | requests will not come here. |
| 651 | |
| 652 | callback is a fn(msg_type_name, msg_type) that will be |
| 653 | called when a message comes in. While this function is |
| 654 | executing, note that (a) you are in a background thread and |
| 655 | may wish to use threading.Lock to protect your datastructures, |
| 656 | and (b) message processing from VPP will stop (so if you take |
| 657 | a long while about it you may provoke reply timeouts or cause |
| 658 | VPP to fill the RX buffer). Passing None will disable the |
| 659 | callback. |
| 660 | """ |
| 661 | self.event_callback = callback |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 662 | |
| 663 | def thread_msg_handler(self): |
| 664 | """Python thread calling the user registerd message handler. |
| 665 | |
| 666 | This is to emulate the old style event callback scheme. Modern |
| 667 | clients should provide their own thread to poll the event |
| 668 | queue. |
| 669 | """ |
| 670 | while True: |
| 671 | r = self.message_queue.get() |
Klement Sekera | 180402d | 2018-02-17 10:58:37 +0100 | [diff] [blame] | 672 | if r == "terminate event thread": |
| 673 | break |
Ole Troan | dfc9b7c | 2017-03-06 23:51:57 +0100 | [diff] [blame] | 674 | msgname = type(r).__name__ |
Ole Troan | 4df9716 | 2017-07-07 16:06:08 +0200 | [diff] [blame] | 675 | if self.event_callback: |
| 676 | self.event_callback(msgname, r) |
Chris Luke | 52bf22e | 2017-11-03 23:32:38 -0400 | [diff] [blame] | 677 | |
| 678 | |
| 679 | # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 |