blob: 644aeac65c63a7747e9382b760b7f54c2a08b415 [file] [log] [blame]
Ole Troana7564e82018-06-12 21:06:44 +02001#
2# Copyright (c) 2018 Cisco and/or its affiliates.
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at:
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14#
Ole Troana7564e82018-06-12 21:06:44 +020015import collections
Paul Vinciguerra2e876062020-05-12 10:45:17 -040016from enum import IntFlag
Ole Troan85465582019-04-30 10:04:36 +020017import logging
Ole Troan85465582019-04-30 10:04:36 +020018import socket
Paul Vinciguerraae8819f2019-06-07 13:35:37 -040019import struct
20import sys
Paul Vinciguerra42bdba82019-03-07 11:26:23 -080021
Paul Vinciguerra2e876062020-05-12 10:45:17 -040022from . import vpp_format
Paul Vinciguerra42bdba82019-03-07 11:26:23 -080023
Ole Troana7564e82018-06-12 21:06:44 +020024
25#
26# Set log-level in application by doing e.g.:
27# logger = logging.getLogger('vpp_serializer')
28# logger.setLevel(logging.DEBUG)
29#
Paul Vinciguerra5395c6a2020-12-02 17:43:59 -050030logger = logging.getLogger('vpp_papi.serializer')
Ole Troana7564e82018-06-12 21:06:44 +020031
Paul Vinciguerrad7adc292020-12-02 14:34:27 -050032
33def check(d):
34 return type(d) is dict or type(d) is bytes
Ole Troan8006c6a2018-12-17 12:02:26 +010035
Ole Troan0bcad322018-12-11 13:04:01 +010036
37def conversion_required(data, field_type):
38 if check(data):
39 return False
40 try:
41 if type(data).__name__ in vpp_format.conversion_table[field_type]:
42 return True
43 except KeyError:
44 return False
45
46
47def conversion_packer(data, field_type):
48 t = type(data).__name__
49 return types[field_type].pack(vpp_format.
50 conversion_table[field_type][t](data))
51
52
53def conversion_unpacker(data, field_type):
54 if field_type not in vpp_format.conversion_unpacker_table:
55 return data
56 return vpp_format.conversion_unpacker_table[field_type](data)
57
Ole Troana7564e82018-06-12 21:06:44 +020058
Paul Vinciguerrad7adc292020-12-02 14:34:27 -050059class Packer:
Ole Troan418ebb72019-11-19 04:38:20 +010060 options = {}
61
62 def pack(self, data, kwargs):
63 raise NotImplementedError
64
65 def unpack(self, data, offset, result=None, ntc=False):
66 raise NotImplementedError
67
68 # override as appropriate in subclasses
Ole Troanda47f672019-11-24 15:22:55 +010069 @staticmethod
70 def _get_packer_with_options(f_type, options):
Ole Troan418ebb72019-11-19 04:38:20 +010071 return types[f_type]
72
73 def get_packer_with_options(self, f_type, options):
74 if options is not None:
75 try:
Ole Troanda47f672019-11-24 15:22:55 +010076 c = types[f_type].__class__
77 return c._get_packer_with_options(f_type, options)
Ole Troan418ebb72019-11-19 04:38:20 +010078 except IndexError:
79 raise VPPSerializerValueError(
80 "Options not supported for {}{} ({})".
Ole Troanda47f672019-11-24 15:22:55 +010081 format(f_type, types[f_type].__class__,
82 options))
Ole Troan418ebb72019-11-19 04:38:20 +010083
84
85class BaseTypes(Packer):
Ole Troan85465582019-04-30 10:04:36 +020086 def __init__(self, type, elements=0, options=None):
Paul Vinciguerra14b0b472019-11-23 23:49:57 -050087 self._type = type
88 self._elements = elements
Ole Troana7564e82018-06-12 21:06:44 +020089 base_types = {'u8': '>B',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -040090 'i8': '>b',
Ole Troan413f4a52018-11-28 11:36:05 +010091 'string': '>s',
Ole Troana7564e82018-06-12 21:06:44 +020092 'u16': '>H',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -040093 'i16': '>h',
Ole Troana7564e82018-06-12 21:06:44 +020094 'u32': '>I',
95 'i32': '>i',
96 'u64': '>Q',
Paul Vinciguerra6ce0f352019-07-02 13:06:21 -040097 'i64': '>q',
Paul Vinciguerra888640a2019-05-14 21:01:28 -040098 'f64': '=d',
Ole Troanf47e9b62018-10-16 15:14:03 +020099 'bool': '>?',
Ole Troana7564e82018-06-12 21:06:44 +0200100 'header': '>HI'}
101
Ole Troan413f4a52018-11-28 11:36:05 +0100102 if elements > 0 and (type == 'u8' or type == 'string'):
Ole Troana7564e82018-06-12 21:06:44 +0200103 self.packer = struct.Struct('>%ss' % elements)
104 else:
105 self.packer = struct.Struct(base_types[type])
106 self.size = self.packer.size
Ole Troan85465582019-04-30 10:04:36 +0200107 self.options = options
108
Ole Troana7564e82018-06-12 21:06:44 +0200109 def pack(self, data, kwargs=None):
Ole Troan40dc4b32019-10-22 14:01:53 +0200110 if data is None: # Default to zero if not specified
Ole Troan85465582019-04-30 10:04:36 +0200111 if self.options and 'default' in self.options:
112 data = self.options['default']
113 else:
114 data = 0
Ole Troana7564e82018-06-12 21:06:44 +0200115 return self.packer.pack(data)
116
Ole Troan0bcad322018-12-11 13:04:01 +0100117 def unpack(self, data, offset, result=None, ntc=False):
Ole Troanc84cbad2018-09-06 22:58:05 +0200118 return self.packer.unpack_from(data, offset)[0], self.packer.size
Ole Troana7564e82018-06-12 21:06:44 +0200119
Ole Troanda47f672019-11-24 15:22:55 +0100120 @staticmethod
121 def _get_packer_with_options(f_type, options):
122 return BaseTypes(f_type, options=options)
Ole Troana7564e82018-06-12 21:06:44 +0200123
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500124 def __repr__(self):
125 return "BaseTypes(type=%s, elements=%s, options=%s)" % (self._type,
126 self._elements,
127 self.options)
128
Ole Troan418ebb72019-11-19 04:38:20 +0100129
130class String(Packer):
Ole Troane5ff5a32019-08-23 22:55:18 +0200131 def __init__(self, name, num, options):
132 self.name = name
133 self.num = num
Ole Troan413f4a52018-11-28 11:36:05 +0100134 self.size = 1
135 self.length_field_packer = BaseTypes('u32')
Ole Troane5ff5a32019-08-23 22:55:18 +0200136 self.limit = options['limit'] if 'limit' in options else num
137 self.fixed = True if num else False
138 if self.fixed and not self.limit:
Ole Troan9ac11382019-04-23 17:11:01 +0200139 raise VPPSerializerValueError(
Paul Vinciguerracebed412020-12-01 23:45:38 -0500140 "Invalid combination for: {}, {} fixed:{} limit:{}".
141 format(name, options, self.fixed, self.limit))
Ole Troan9ac11382019-04-23 17:11:01 +0200142
Ole Troane5ff5a32019-08-23 22:55:18 +0200143 def pack(self, list, kwargs=None):
144 if not list:
145 if self.fixed:
146 return b"\x00" * self.limit
147 return self.length_field_packer.pack(0) + b""
148 if self.limit and len(list) > self.limit - 1:
149 raise VPPSerializerValueError(
150 "Invalid argument length for: {}, {} maximum {}".
151 format(list, len(list), self.limit - 1))
152 if self.fixed:
153 return list.encode('ascii').ljust(self.limit, b'\x00')
154 return self.length_field_packer.pack(len(list)) + list.encode('ascii')
Ole Troan413f4a52018-11-28 11:36:05 +0100155
156 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troane5ff5a32019-08-23 22:55:18 +0200157 if self.fixed:
158 p = BaseTypes('u8', self.num)
159 s = p.unpack(data, offset)
160 s2 = s[0].split(b'\0', 1)[0]
161 return (s2.decode('ascii'), self.num)
162
Ole Troan413f4a52018-11-28 11:36:05 +0100163 length, length_field_size = self.length_field_packer.unpack(data,
164 offset)
165 if length == 0:
Ole Troane5ff5a32019-08-23 22:55:18 +0200166 return '', 0
Ole Troan413f4a52018-11-28 11:36:05 +0100167 p = BaseTypes('u8', length)
168 x, size = p.unpack(data, offset + length_field_size)
Ole Troan33a58172019-09-04 09:12:29 +0200169 return (x.decode('ascii', errors='replace'), size + length_field_size)
Ole Troan413f4a52018-11-28 11:36:05 +0100170
171
Paul Vinciguerraba2c7fa2019-11-23 21:02:27 -0500172types = {'u8': BaseTypes('u8'), 'i8': BaseTypes('i8'),
173 'u16': BaseTypes('u16'), 'i16': BaseTypes('i16'),
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800174 'u32': BaseTypes('u32'), 'i32': BaseTypes('i32'),
Paul Vinciguerraba2c7fa2019-11-23 21:02:27 -0500175 'u64': BaseTypes('u64'), 'i64': BaseTypes('i64'),
176 'f64': BaseTypes('f64'),
Ole Troan9ac11382019-04-23 17:11:01 +0200177 'bool': BaseTypes('bool'), 'string': String}
Ole Troana7564e82018-06-12 21:06:44 +0200178
Ole Troan40dc4b32019-10-22 14:01:53 +0200179class_types = {}
Ole Troana7564e82018-06-12 21:06:44 +0200180
Ole Troan418ebb72019-11-19 04:38:20 +0100181
Ole Troan0685da42018-10-16 14:42:50 +0200182def vpp_get_type(name):
183 try:
184 return types[name]
185 except KeyError:
186 return None
187
188
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800189class VPPSerializerValueError(ValueError):
190 pass
191
192
Ole Troan418ebb72019-11-19 04:38:20 +0100193class FixedList_u8(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200194 def __init__(self, name, field_type, num):
195 self.name = name
196 self.num = num
197 self.packer = BaseTypes(field_type, num)
198 self.size = self.packer.size
Ole Troan413f4a52018-11-28 11:36:05 +0100199 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200200
Ole Troan0bcad322018-12-11 13:04:01 +0100201 def pack(self, data, kwargs=None):
Ole Troana7564e82018-06-12 21:06:44 +0200202 """Packs a fixed length bytestring. Left-pads with zeros
203 if input data is too short."""
Ole Troan0bcad322018-12-11 13:04:01 +0100204 if not data:
Ole Troan31555a32018-10-22 09:30:26 +0200205 return b'\x00' * self.size
Ole Troan0bcad322018-12-11 13:04:01 +0100206
207 if len(data) > self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800208 raise VPPSerializerValueError(
209 'Fixed list length error for "{}", got: {}'
210 ' expected: {}'
Ole Troan0bcad322018-12-11 13:04:01 +0100211 .format(self.name, len(data), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200212
Ole Troan64e978b2019-10-17 21:40:36 +0200213 try:
214 return self.packer.pack(data)
215 except struct.error:
216 raise VPPSerializerValueError(
217 'Packing failed for "{}" {}'
218 .format(self.name, kwargs))
Ole Troan418ebb72019-11-19 04:38:20 +0100219
Ole Troan0bcad322018-12-11 13:04:01 +0100220 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200221 if len(data[offset:]) < self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800222 raise VPPSerializerValueError(
223 'Invalid array length for "{}" got {}'
224 ' expected {}'
225 .format(self.name, len(data[offset:]), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200226 return self.packer.unpack(data, offset)
227
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500228 def __repr__(self):
229 return "FixedList_u8(name=%s, field_type=%s, num=%s)" % (
230 self.name, self.field_type, self.num
231 )
232
Ole Troana7564e82018-06-12 21:06:44 +0200233
Ole Troan418ebb72019-11-19 04:38:20 +0100234class FixedList(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200235 def __init__(self, name, field_type, num):
236 self.num = num
237 self.packer = types[field_type]
238 self.size = self.packer.size * num
Ole Troan0bcad322018-12-11 13:04:01 +0100239 self.name = name
240 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200241
242 def pack(self, list, kwargs):
Ole Troana7564e82018-06-12 21:06:44 +0200243 if len(list) != self.num:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800244 raise VPPSerializerValueError(
245 'Fixed list length error, got: {} expected: {}'
246 .format(len(list), self.num))
Ole Troana7564e82018-06-12 21:06:44 +0200247 b = bytes()
248 for e in list:
249 b += self.packer.pack(e)
250 return b
251
Ole Troan0bcad322018-12-11 13:04:01 +0100252 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200253 # Return a list of arguments
254 result = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200255 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200256 for e in range(self.num):
Ole Troan0bcad322018-12-11 13:04:01 +0100257 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200258 result.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200259 offset += size
260 total += size
261 return result, total
Ole Troana7564e82018-06-12 21:06:44 +0200262
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500263 def __repr__(self):
Paul Vinciguerra99fbf052019-11-26 14:15:53 -0500264 return "FixedList(name=%s, field_type=%s, num=%s)" % (
Ole Troanda47f672019-11-24 15:22:55 +0100265 self.name, self.field_type, self.num)
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500266
Ole Troana7564e82018-06-12 21:06:44 +0200267
Ole Troan418ebb72019-11-19 04:38:20 +0100268class VLAList(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200269 def __init__(self, name, field_type, len_field_name, index):
Ole Troanc84cbad2018-09-06 22:58:05 +0200270 self.name = name
Ole Troan413f4a52018-11-28 11:36:05 +0100271 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200272 self.index = index
273 self.packer = types[field_type]
274 self.size = self.packer.size
275 self.length_field = len_field_name
276
Ole Troan22674292019-10-21 18:59:11 +0200277 def pack(self, lst, kwargs=None):
278 if not lst:
Ole Troan31555a32018-10-22 09:30:26 +0200279 return b""
Ole Troan22674292019-10-21 18:59:11 +0200280 if len(lst) != kwargs[self.length_field]:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800281 raise VPPSerializerValueError(
282 'Variable length error, got: {} expected: {}'
Ole Troan22674292019-10-21 18:59:11 +0200283 .format(len(lst), kwargs[self.length_field]))
Ole Troana7564e82018-06-12 21:06:44 +0200284
285 # u8 array
286 if self.packer.size == 1:
Ole Troan22674292019-10-21 18:59:11 +0200287 if isinstance(lst, list):
288 return b''.join(lst)
289 return bytes(lst)
Ole Troana7564e82018-06-12 21:06:44 +0200290
Ole Troan22674292019-10-21 18:59:11 +0200291 b = bytes()
292 for e in lst:
Ole Troana7564e82018-06-12 21:06:44 +0200293 b += self.packer.pack(e)
294 return b
295
Ole Troan0bcad322018-12-11 13:04:01 +0100296 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200297 # Return a list of arguments
Ole Troanc84cbad2018-09-06 22:58:05 +0200298 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200299
300 # u8 array
301 if self.packer.size == 1:
302 if result[self.index] == 0:
Ole Troanc84cbad2018-09-06 22:58:05 +0200303 return b'', 0
Ole Troana7564e82018-06-12 21:06:44 +0200304 p = BaseTypes('u8', result[self.index])
Ole Troan0bcad322018-12-11 13:04:01 +0100305 return p.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200306
307 r = []
308 for e in range(result[self.index]):
Ole Troan0bcad322018-12-11 13:04:01 +0100309 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200310 r.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200311 offset += size
312 total += size
313 return r, total
Ole Troana7564e82018-06-12 21:06:44 +0200314
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500315 def __repr__(self):
316 return "VLAList(name=%s, field_type=%s, " \
317 "len_field_name=%s, index=%s)" % (
Ole Troanda47f672019-11-24 15:22:55 +0100318 self.name, self.field_type, self.length_field, self.index
319 )
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500320
Ole Troana7564e82018-06-12 21:06:44 +0200321
Ole Troan418ebb72019-11-19 04:38:20 +0100322class VLAList_legacy(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200323 def __init__(self, name, field_type):
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500324 self.name = name
325 self.field_type = field_type
Ole Troana7564e82018-06-12 21:06:44 +0200326 self.packer = types[field_type]
327 self.size = self.packer.size
328
329 def pack(self, list, kwargs=None):
Ole Troana7564e82018-06-12 21:06:44 +0200330 if self.packer.size == 1:
331 return bytes(list)
332
333 b = bytes()
334 for e in list:
335 b += self.packer.pack(e)
336 return b
337
Ole Troan0bcad322018-12-11 13:04:01 +0100338 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troanc84cbad2018-09-06 22:58:05 +0200339 total = 0
Ole Troana7564e82018-06-12 21:06:44 +0200340 # Return a list of arguments
341 if (len(data) - offset) % self.packer.size:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800342 raise VPPSerializerValueError(
343 'Legacy Variable Length Array length mismatch.')
Ole Troana7564e82018-06-12 21:06:44 +0200344 elements = int((len(data) - offset) / self.packer.size)
345 r = []
Ole Troana7564e82018-06-12 21:06:44 +0200346 for e in range(elements):
Ole Troan0bcad322018-12-11 13:04:01 +0100347 x, size = self.packer.unpack(data, offset, ntc=ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200348 r.append(x)
349 offset += self.packer.size
Ole Troanc84cbad2018-09-06 22:58:05 +0200350 total += size
351 return r, total
Ole Troana7564e82018-06-12 21:06:44 +0200352
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500353 def __repr__(self):
354 return "VLAList_legacy(name=%s, field_type=%s)" % (
355 self.name, self.field_type
356 )
357
Ole Troana7564e82018-06-12 21:06:44 +0200358
Paul Vinciguerra3825d932020-12-03 21:06:28 -0500359# Will change to IntEnum after 21.04 release
Ole Troan418ebb72019-11-19 04:38:20 +0100360class VPPEnumType(Packer):
Paul Vinciguerra3825d932020-12-03 21:06:28 -0500361 output_class = IntFlag
362
Ole Troan40dc4b32019-10-22 14:01:53 +0200363 def __init__(self, name, msgdef, options=None):
Ole Troana7564e82018-06-12 21:06:44 +0200364 self.size = types['u32'].size
Ole Troan40dc4b32019-10-22 14:01:53 +0200365 self.name = name
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100366 self.enumtype = 'u32'
Ole Troan40dc4b32019-10-22 14:01:53 +0200367 self.msgdef = msgdef
Ole Troana7564e82018-06-12 21:06:44 +0200368 e_hash = {}
369 for f in msgdef:
370 if type(f) is dict and 'enumtype' in f:
371 if f['enumtype'] != 'u32':
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100372 self.size = types[f['enumtype']].size
373 self.enumtype = f['enumtype']
Ole Troana7564e82018-06-12 21:06:44 +0200374 continue
375 ename, evalue = f
376 e_hash[ename] = evalue
Paul Vinciguerra3825d932020-12-03 21:06:28 -0500377 self.enum = self.output_class(name, e_hash)
Ole Troana7564e82018-06-12 21:06:44 +0200378 types[name] = self
Paul Vinciguerra3825d932020-12-03 21:06:28 -0500379 class_types[name] = self.__class__
Ole Troan40dc4b32019-10-22 14:01:53 +0200380 self.options = options
Ole Troan85465582019-04-30 10:04:36 +0200381
Ole Troana7564e82018-06-12 21:06:44 +0200382 def __getattr__(self, name):
383 return self.enum[name]
384
Paul Vinciguerraa089ae12019-07-08 15:41:07 -0400385 def __bool__(self):
Ole Troan0685da42018-10-16 14:42:50 +0200386 return True
387
Ole Troana7564e82018-06-12 21:06:44 +0200388 def pack(self, data, kwargs=None):
Ole Troan40dc4b32019-10-22 14:01:53 +0200389 if data is None: # Default to zero if not specified
390 if self.options and 'default' in self.options:
391 data = self.options['default']
392 else:
393 data = 0
394
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100395 return types[self.enumtype].pack(data)
Ole Troana7564e82018-06-12 21:06:44 +0200396
Ole Troan0bcad322018-12-11 13:04:01 +0100397 def unpack(self, data, offset=0, result=None, ntc=False):
Andrew Yourtchenko5c4b9f12019-03-19 14:52:29 +0100398 x, size = types[self.enumtype].unpack(data, offset)
Ole Troanc84cbad2018-09-06 22:58:05 +0200399 return self.enum(x), size
Ole Troana7564e82018-06-12 21:06:44 +0200400
Paul Vinciguerra3825d932020-12-03 21:06:28 -0500401 @classmethod
402 def _get_packer_with_options(cls, f_type, options):
403 return cls(f_type, types[f_type].msgdef, options=options)
Ole Troana7564e82018-06-12 21:06:44 +0200404
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500405 def __repr__(self):
Paul Vinciguerra3825d932020-12-03 21:06:28 -0500406 return "%s(name=%s, msgdef=%s, options=%s)" % (
407 self.__class__.__name__, self.name, self.msgdef, self.options
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500408 )
409
Ole Troan418ebb72019-11-19 04:38:20 +0100410
Paul Vinciguerra3825d932020-12-03 21:06:28 -0500411class VPPEnumFlagType(VPPEnumType):
412 output_class = IntFlag
413
414 def __init__(self, name, msgdef, options=None):
415 super(VPPEnumFlagType, self).__init__(name, msgdef, options)
416
417
Ole Troan418ebb72019-11-19 04:38:20 +0100418class VPPUnionType(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200419 def __init__(self, name, msgdef):
420 self.name = name
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500421 self.msgdef = msgdef
Ole Troana7564e82018-06-12 21:06:44 +0200422 self.size = 0
423 self.maxindex = 0
424 fields = []
425 self.packers = collections.OrderedDict()
426 for i, f in enumerate(msgdef):
427 if type(f) is dict and 'crc' in f:
428 self.crc = f['crc']
429 continue
430 f_type, f_name = f
431 if f_type not in types:
432 logger.debug('Unknown union type {}'.format(f_type))
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800433 raise VPPSerializerValueError(
434 'Unknown message type {}'.format(f_type))
Ole Troana7564e82018-06-12 21:06:44 +0200435 fields.append(f_name)
436 size = types[f_type].size
437 self.packers[f_name] = types[f_type]
438 if size > self.size:
439 self.size = size
440 self.maxindex = i
441
442 types[name] = self
443 self.tuple = collections.namedtuple(name, fields, rename=True)
Ole Troana7564e82018-06-12 21:06:44 +0200444
Ole Troan31555a32018-10-22 09:30:26 +0200445 # Union of variable length?
Ole Troana7564e82018-06-12 21:06:44 +0200446 def pack(self, data, kwargs=None):
Ole Troan31555a32018-10-22 09:30:26 +0200447 if not data:
448 return b'\x00' * self.size
449
Ole Troana7564e82018-06-12 21:06:44 +0200450 for k, v in data.items():
451 logger.debug("Key: {} Value: {}".format(k, v))
452 b = self.packers[k].pack(v, kwargs)
Ole Troana7564e82018-06-12 21:06:44 +0200453 break
454 r = bytearray(self.size)
Ole Troanb199e982018-08-02 19:19:21 +0200455 r[:len(b)] = b
Ole Troana7564e82018-06-12 21:06:44 +0200456 return r
457
Ole Troan0bcad322018-12-11 13:04:01 +0100458 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200459 r = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200460 maxsize = 0
Ole Troana7564e82018-06-12 21:06:44 +0200461 for k, p in self.packers.items():
Ole Troan0bcad322018-12-11 13:04:01 +0100462 x, size = p.unpack(data, offset, ntc=ntc)
Ole Troanc84cbad2018-09-06 22:58:05 +0200463 if size > maxsize:
464 maxsize = size
465 r.append(x)
466 return self.tuple._make(r), maxsize
Ole Troana7564e82018-06-12 21:06:44 +0200467
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500468 def __repr__(self):
469 return"VPPUnionType(name=%s, msgdef=%r)" % (self.name, self.msgdef)
470
Ole Troana7564e82018-06-12 21:06:44 +0200471
Ole Troan418ebb72019-11-19 04:38:20 +0100472class VPPTypeAlias(Packer):
473 def __init__(self, name, msgdef, options=None):
Ole Troan0bcad322018-12-11 13:04:01 +0100474 self.name = name
Ole Troan418ebb72019-11-19 04:38:20 +0100475 self.msgdef = msgdef
Ole Troan0bcad322018-12-11 13:04:01 +0100476 t = vpp_get_type(msgdef['type'])
477 if not t:
Ole Troan75761b92019-09-11 17:49:08 +0200478 raise ValueError('No such type: {}'.format(msgdef['type']))
Ole Troan0bcad322018-12-11 13:04:01 +0100479 if 'length' in msgdef:
480 if msgdef['length'] == 0:
481 raise ValueError()
482 if msgdef['type'] == 'u8':
483 self.packer = FixedList_u8(name, msgdef['type'],
484 msgdef['length'])
485 self.size = self.packer.size
486 else:
487 self.packer = FixedList(name, msgdef['type'], msgdef['length'])
Ole Troan8c8acc02018-11-27 10:05:23 +0100488 else:
Ole Troan0bcad322018-12-11 13:04:01 +0100489 self.packer = t
490 self.size = t.size
491
492 types[name] = self
Ole Troan75761b92019-09-11 17:49:08 +0200493 self.toplevelconversion = False
Ole Troan418ebb72019-11-19 04:38:20 +0100494 self.options = options
Ole Troan0bcad322018-12-11 13:04:01 +0100495
496 def pack(self, data, kwargs=None):
497 if data and conversion_required(data, self.name):
498 try:
499 return conversion_packer(data, self.name)
500 # Python 2 and 3 raises different exceptions from inet_pton
501 except(OSError, socket.error, TypeError):
502 pass
Ole Troan418ebb72019-11-19 04:38:20 +0100503 if data is None: # Default to zero if not specified
504 if self.options and 'default' in self.options:
505 data = self.options['default']
506 else:
507 data = 0
Ole Troan0bcad322018-12-11 13:04:01 +0100508
509 return self.packer.pack(data, kwargs)
510
Ole Troanda47f672019-11-24 15:22:55 +0100511 @staticmethod
512 def _get_packer_with_options(f_type, options):
513 return VPPTypeAlias(f_type, types[f_type].msgdef, options=options)
Ole Troan418ebb72019-11-19 04:38:20 +0100514
Ole Troan0bcad322018-12-11 13:04:01 +0100515 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troan418ebb72019-11-19 04:38:20 +0100516 if ntc is False and self.name in vpp_format.conversion_unpacker_table:
Ole Troan75761b92019-09-11 17:49:08 +0200517 # Disable type conversion for dependent types
518 ntc = True
519 self.toplevelconversion = True
Ole Troan0bcad322018-12-11 13:04:01 +0100520 t, size = self.packer.unpack(data, offset, result, ntc=ntc)
Ole Troan75761b92019-09-11 17:49:08 +0200521 if self.toplevelconversion:
522 self.toplevelconversion = False
Ole Troan0bcad322018-12-11 13:04:01 +0100523 return conversion_unpacker(t, self.name), size
524 return t, size
Ole Troan53fffa12018-11-13 12:36:56 +0100525
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500526 def __repr__(self):
527 return "VPPTypeAlias(name=%s, msgdef=%s, options=%s)" % (
528 self.name, self.msgdef, self.options)
529
Ole Troan53fffa12018-11-13 12:36:56 +0100530
Ole Troan418ebb72019-11-19 04:38:20 +0100531class VPPType(Packer):
Ole Troana7564e82018-06-12 21:06:44 +0200532 # Set everything up to be able to pack / unpack
533 def __init__(self, name, msgdef):
534 self.name = name
535 self.msgdef = msgdef
536 self.packers = []
537 self.fields = []
538 self.fieldtypes = []
539 self.field_by_name = {}
540 size = 0
541 for i, f in enumerate(msgdef):
542 if type(f) is dict and 'crc' in f:
543 self.crc = f['crc']
544 continue
545 f_type, f_name = f[:2]
546 self.fields.append(f_name)
547 self.field_by_name[f_name] = None
548 self.fieldtypes.append(f_type)
549 if f_type not in types:
550 logger.debug('Unknown type {}'.format(f_type))
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800551 raise VPPSerializerValueError(
552 'Unknown message type {}'.format(f_type))
Ole Troan9ac11382019-04-23 17:11:01 +0200553
Ole Troan85465582019-04-30 10:04:36 +0200554 fieldlen = len(f)
Ole Troan9ac11382019-04-23 17:11:01 +0200555 options = [x for x in f if type(x) is dict]
556 if len(options):
557 self.options = options[0]
Ole Troan85465582019-04-30 10:04:36 +0200558 fieldlen -= 1
Ole Troan9ac11382019-04-23 17:11:01 +0200559 else:
560 self.options = {}
Ole Troan85465582019-04-30 10:04:36 +0200561 if fieldlen == 3: # list
Ole Troana7564e82018-06-12 21:06:44 +0200562 list_elements = f[2]
563 if list_elements == 0:
Ole Troane5ff5a32019-08-23 22:55:18 +0200564 if f_type == 'string':
565 p = String(f_name, 0, self.options)
566 else:
567 p = VLAList_legacy(f_name, f_type)
Ole Troana7564e82018-06-12 21:06:44 +0200568 self.packers.append(p)
Ole Troane5ff5a32019-08-23 22:55:18 +0200569 elif f_type == 'u8':
Ole Troana7564e82018-06-12 21:06:44 +0200570 p = FixedList_u8(f_name, f_type, list_elements)
571 self.packers.append(p)
572 size += p.size
Ole Troane5ff5a32019-08-23 22:55:18 +0200573 elif f_type == 'string':
574 p = String(f_name, list_elements, self.options)
575 self.packers.append(p)
576 size += p.size
Ole Troana7564e82018-06-12 21:06:44 +0200577 else:
578 p = FixedList(f_name, f_type, list_elements)
579 self.packers.append(p)
580 size += p.size
Ole Troan85465582019-04-30 10:04:36 +0200581 elif fieldlen == 4: # Variable length list
Ole Troan413f4a52018-11-28 11:36:05 +0100582 length_index = self.fields.index(f[3])
583 p = VLAList(f_name, f_type, f[3], length_index)
584 self.packers.append(p)
Ole Troana7564e82018-06-12 21:06:44 +0200585 else:
Ole Troan418ebb72019-11-19 04:38:20 +0100586 # default support for types that decay to basetype
Ole Troan40dc4b32019-10-22 14:01:53 +0200587 if 'default' in self.options:
Ole Troan418ebb72019-11-19 04:38:20 +0100588 p = self.get_packer_with_options(f_type, self.options)
Ole Troan40dc4b32019-10-22 14:01:53 +0200589 else:
590 p = types[f_type]
Ole Troan418ebb72019-11-19 04:38:20 +0100591
Ole Troan9ac11382019-04-23 17:11:01 +0200592 self.packers.append(p)
593 size += p.size
Ole Troana7564e82018-06-12 21:06:44 +0200594
595 self.size = size
596 self.tuple = collections.namedtuple(name, self.fields, rename=True)
597 types[name] = self
Ole Troan75761b92019-09-11 17:49:08 +0200598 self.toplevelconversion = False
Ole Troana7564e82018-06-12 21:06:44 +0200599
600 def pack(self, data, kwargs=None):
601 if not kwargs:
602 kwargs = data
Ole Troana7564e82018-06-12 21:06:44 +0200603 b = bytes()
Ole Troan31555a32018-10-22 09:30:26 +0200604
Ole Troan0bcad322018-12-11 13:04:01 +0100605 # Try one of the format functions
606 if data and conversion_required(data, self.name):
607 return conversion_packer(data, self.name)
608
609 for i, a in enumerate(self.fields):
Ole Troan31555a32018-10-22 09:30:26 +0200610 if data and type(data) is not dict and a not in data:
Paul Vinciguerra6ccc6e92018-11-27 08:15:22 -0800611 raise VPPSerializerValueError(
612 "Invalid argument: {} expected {}.{}".
613 format(data, self.name, a))
Ole Troan31555a32018-10-22 09:30:26 +0200614
615 # Defaulting to zero.
616 if not data or a not in data: # Default to 0
617 arg = None
618 kwarg = None # No default for VLA
619 else:
620 arg = data[a]
621 kwarg = kwargs[a] if a in kwargs else None
Ole Troana7564e82018-06-12 21:06:44 +0200622 if isinstance(self.packers[i], VPPType):
Ole Troan0bcad322018-12-11 13:04:01 +0100623 b += self.packers[i].pack(arg, kwarg)
Ole Troana7564e82018-06-12 21:06:44 +0200624 else:
Ole Troan31555a32018-10-22 09:30:26 +0200625 b += self.packers[i].pack(arg, kwargs)
626
Ole Troana7564e82018-06-12 21:06:44 +0200627 return b
628
Ole Troan0bcad322018-12-11 13:04:01 +0100629 def unpack(self, data, offset=0, result=None, ntc=False):
Ole Troana7564e82018-06-12 21:06:44 +0200630 # Return a list of arguments
631 result = []
Ole Troanc84cbad2018-09-06 22:58:05 +0200632 total = 0
Ole Troan418ebb72019-11-19 04:38:20 +0100633 if ntc is False and self.name in vpp_format.conversion_unpacker_table:
Ole Troan75761b92019-09-11 17:49:08 +0200634 # Disable type conversion for dependent types
635 ntc = True
636 self.toplevelconversion = True
637
Ole Troana7564e82018-06-12 21:06:44 +0200638 for p in self.packers:
Ole Troan0bcad322018-12-11 13:04:01 +0100639 x, size = p.unpack(data, offset, result, ntc)
Ole Troana7564e82018-06-12 21:06:44 +0200640 if type(x) is tuple and len(x) == 1:
641 x = x[0]
642 result.append(x)
Ole Troanc84cbad2018-09-06 22:58:05 +0200643 offset += size
644 total += size
645 t = self.tuple._make(result)
Ole Troan75761b92019-09-11 17:49:08 +0200646
647 if self.toplevelconversion:
648 self.toplevelconversion = False
Ole Troan0bcad322018-12-11 13:04:01 +0100649 t = conversion_unpacker(t, self.name)
Ole Troanc84cbad2018-09-06 22:58:05 +0200650 return t, total
Ole Troana7564e82018-06-12 21:06:44 +0200651
Paul Vinciguerra14b0b472019-11-23 23:49:57 -0500652 def __repr__(self):
653 return "%s(name=%s, msgdef=%s)" % (
654 self.__class__.__name__, self.name, self.msgdef
655 )
656
Ole Troana7564e82018-06-12 21:06:44 +0200657
658class VPPMessage(VPPType):
659 pass