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:
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
16 from socket import inet_pton, inet_ntop, AF_INET6, AF_INET
20 class VPPFormatError(Exception):
24 class VPPFormat(object):
25 VPPFormatError = VPPFormatError
28 def format_vl_api_ip6_prefix_t(args):
29 prefix, len = args.split('/')
30 return {'prefix': {'address': inet_pton(AF_INET6, prefix)},
34 def unformat_vl_api_ip6_prefix_t(args):
35 return "{}/{}".format(inet_ntop(AF_INET6, args.prefix.address),
39 def format_vl_api_ip4_prefix_t(args):
40 prefix, len = args.split('/')
41 return {'prefix': {'address': inet_pton(AF_INET, prefix)},
45 def unformat_vl_api_ip4_prefix_t(args):
46 return "{}/{}".format(inet_ntop(AF_INET, args.prefix.address),
50 def format_vl_api_ip6_address_t(args):
51 return {'address': inet_pton(AF_INET6, args)}
54 def format_vl_api_ip4_address_t(args):
55 return {'address': inet_pton(AF_INET, args)}
58 def format_vl_api_address_t(args):
60 return {'un': {'ip6': {'address': inet_pton(AF_INET6, args)}},
62 except socket.error as e:
63 return {'un': {'ip4': {'address': inet_pton(AF_INET, args)}},
67 def unformat_vl_api_address_t(arg):
69 return inet_ntop(AF_INET6, arg.un.ip6.address)
71 return inet_ntop(AF_INET, arg.un.ip4.address)
75 def format_vl_api_prefix_t(args):
76 prefix, len = args.split('/')
77 return {'address': VPPFormat.format_vl_api_address_t(prefix),
78 'address_length': int(len)}
81 def unformat_vl_api_prefix_t(arg):
82 if arg.address.af == 1:
83 return "{}/{}".format(inet_ntop(AF_INET6,
84 arg.address.un.ip6.address),
86 if arg.address.af == 0:
87 return "{}/{}".format(inet_ntop(AF_INET,
88 arg.address.un.ip4.address),
96 except Exception as e:
100 def format(typename, args):
102 return getattr(VPPFormat, 'format_' + typename)(args)
103 except AttributeError:
108 def unformat_bytes(args):
110 return args.decode('utf-8')
111 except ValueError as e:
115 def unformat_list(args):
122 s2 = VPPFormat.unformat_t(t, f)
123 s += '{} '.format(s2)
129 return VPPFormat.unformat_t(type(args).__name__, args)
131 for i, f in enumerate(args):
137 s2 = VPPFormat.unformat_t(t, f)
138 s += '{} {} '.format(args._fields[i], s2)
143 def unformat_t(typename, args):
145 return getattr(VPPFormat, 'unformat_' + typename)(args)
146 except AttributeError:
147 # Type without explicit override
148 return VPPFormat.unformat(args)