3 # Copyright (c) 2019 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.
16 r"""CSIT PAPI Provider
18 TODO: Add description.
23 Request/reply or dump:
25 vpp_papi_provider.py \
27 --data '[{"api_name": "show_version", "api_args": {}}]'
31 vpp_papi_provider.py \
33 --data '[["^/if", "/err/ip4-input", "/sys/node/ip4-input"], ["^/if"]]'
44 CLIENT_NAME = 'csit_papi'
47 # Sphinx creates auto-generated documentation by importing the python source
48 # files and collecting the docstrings from them. The NO_VPP_PAPI flag allows
49 # the vpp_papi_provider.py file to be importable without having to build
50 # the whole vpp api if the user only wishes to generate the test documentation.
53 do_import = False if os.getenv("NO_VPP_PAPI") == "1" else True
59 # Find the directory where the modules are installed. The directory depends
61 # TODO: Find a better way to import papi modules.
64 for root, dirs, files in os.walk('/usr/lib'):
66 if name == 'vpp_papi.py':
67 modules_path = os.path.split(root)[0]
70 sys.path.append(modules_path)
71 from vpp_papi import VPP
72 from vpp_papi.vpp_stats import VPPStats
74 raise RuntimeError('vpp_papi module not found')
77 def _convert_reply(api_r):
78 """Process API reply / a part of API reply for smooth converting to
81 It is used only with 'request' and 'dump' methods.
83 Apply binascii.hexlify() method for string values.
85 TODO: Implement complex solution to process of replies.
87 :param api_r: API reply.
88 :type api_r: Vpp_serializer reply object (named tuple)
89 :returns: Processed API reply / a part of API reply.
92 unwanted_fields = ['count', 'index', 'context']
94 def process_value(val):
95 if isinstance(val, dict):
97 for val_k, val_v in val.iteritems():
98 val_dict[str(val_k)] = process_value(val_v)
100 elif isinstance(val, list):
101 for idx, val_l in enumerate(val):
102 val[idx] = process_value(val_l)
104 elif hasattr(val, '__int__'):
106 elif hasattr(val, '__str__'):
107 return binascii.hexlify(str(val))
108 # Next handles parameters not supporting preferred integer or string
109 # representation to get it logged
110 elif hasattr(val, '__repr__'):
116 reply_key = repr(api_r).split('(')[0]
118 for item in dir(api_r):
119 if not item.startswith('_') and item not in unwanted_fields:
120 reply_value[item] = process_value(getattr(api_r, item))
121 reply_dict[reply_key] = reply_value
125 def process_json_request(args):
126 """Process the request/reply and dump classes of VPP API methods.
128 :param args: Command line arguments passed to VPP PAPI Provider.
129 :type args: ArgumentParser
130 :returns: JSON formatted string.
132 :raises RuntimeError: If PAPI command error occurs.
137 except Exception as err:
138 raise RuntimeError('PAPI init failed:\n{err}'.format(err=repr(err)))
142 def process_value(val):
143 if isinstance(val, dict):
145 for val_k, val_v in val.iteritems():
146 val_dict[str(val_k)] = process_value(val_v)
148 elif isinstance(val, list):
149 for idx, item in enumerate(val):
150 val[idx] = process_value(item)
152 elif isinstance(val, unicode):
153 return binascii.unhexlify(val)
154 elif isinstance(val, int):
159 json_data = json.loads(args.data)
160 vpp.connect(CLIENT_NAME)
161 for data in json_data:
162 api_name = data['api_name']
163 api_args_unicode = data['api_args']
164 api_reply = dict(api_name=api_name)
166 for a_k, a_v in api_args_unicode.items():
167 api_args[str(a_k)] = process_value(a_v)
169 papi_fn = getattr(vpp.api, api_name)
170 rep = papi_fn(**api_args)
172 if isinstance(rep, list):
173 converted_reply = list()
175 converted_reply.append(_convert_reply(r))
177 converted_reply = _convert_reply(rep)
179 api_reply['api_reply'] = converted_reply
180 reply.append(api_reply)
181 except (AttributeError, ValueError) as err:
183 raise RuntimeError('PAPI command {api}({args}) input error:\n{err}'.
187 except Exception as err:
189 raise RuntimeError('PAPI command {api}({args}) error:\n{exc}'.
195 return json.dumps(reply)
198 def process_stats(args):
199 """Process the VPP Stats.
201 :param args: Command line arguments passed to VPP PAPI Provider.
202 :type args: ArgumentParser
203 :returns: JSON formatted string.
205 :raises RuntimeError: If PAPI command error occurs.
209 stats = VPPStats(args.socket)
210 except Exception as err:
211 raise RuntimeError('PAPI init failed:\n{err}'.format(err=repr(err)))
213 json_data = json.loads(args.data)
217 for path in json_data:
218 directory = stats.ls(path)
219 data = stats.dump(directory)
223 return json.dumps(reply)
224 except UnicodeDecodeError as err:
225 raise RuntimeError('PAPI reply {reply} error:\n{exc}'.format(
226 reply=reply, exc=repr(err)))
229 def process_stats_request(args):
230 """Process the VPP Stats requests.
232 :param args: Command line arguments passed to VPP PAPI Provider.
233 :type args: ArgumentParser
234 :returns: JSON formatted string.
236 :raises RuntimeError: If PAPI command error occurs.
240 stats = VPPStats(args.socket)
241 except Exception as err:
242 raise RuntimeError('PAPI init failed:\n{err}'.format(err=repr(err)))
245 json_data = json.loads(args.data)
246 except ValueError as err:
247 raise RuntimeError('Input json string is invalid:\n{err}'.
248 format(err=repr(err)))
250 papi_fn = getattr(stats, json_data["api_name"])
251 reply = papi_fn(**json_data.get("api_args", {}))
253 return json.dumps(reply)
257 """Main function for the Python API provider.
260 # The functions which process different types of VPP Python API methods.
261 process_request = dict(
262 request=process_json_request,
263 dump=process_json_request,
265 stats_request=process_stats_request
268 parser = argparse.ArgumentParser(
269 formatter_class=argparse.RawDescriptionHelpFormatter,
271 parser.add_argument("-m", "--method",
273 choices=[str(key) for key in process_request.keys()],
274 help="Specifies the VPP API methods: 1. request - "
275 "simple request / reply; 2. dump - dump function;"
276 "3. stats - VPP statistics.")
277 parser.add_argument("-d", "--data",
279 help="If the method is 'request' or 'dump', data is a "
280 "JSON string (list) containing API name(s) and "
281 "its/their input argument(s). "
282 "If the method is 'stats', data is a JSON string "
283 "containing the list of path(s) to the required "
285 parser.add_argument("-s", "--socket",
286 default="/var/run/vpp/stats.sock",
287 help="A file descriptor over the VPP stats Unix domain "
288 "socket. It is used only if method=='stats'.")
290 args = parser.parse_args()
292 return process_request[args.method](args)
295 if __name__ == '__main__':
296 sys.stdout.write(main())