2 # Copyright 2016 Cisco Systems, Inc. All rights reserved.
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # 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, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
26 from attrdict import AttrDict
28 from pkg_resources import resource_string
30 from __init__ import __version__
31 from chain_runner import ChainRunner
32 from cleanup import Cleaner
33 from config import config_load
34 from config import config_loads
35 import credentials as credentials
36 from fluentd import FluentLogHandler
39 from nfvbenchd import WebServer
40 from specs import ChainType
41 from specs import Specs
42 from summarizer import NFVBenchSummarizer
48 class NFVBench(object):
49 """Main class of NFV benchmarking tool."""
52 STATUS_ERROR = 'ERROR'
54 def __init__(self, config, openstack_spec, config_plugin, factory, notifier=None):
55 # the base config never changes for a given NFVbench instance
56 self.base_config = config
57 # this is the running config, updated at every run()
59 self.config_plugin = config_plugin
60 self.factory = factory
61 self.notifier = notifier
62 self.cred = credentials.Credentials(config.openrc_file, None, False) \
63 if config.openrc_file else None
64 self.chain_runner = None
66 self.specs.set_openstack_spec(openstack_spec)
70 def set_notifier(self, notifier):
71 self.notifier = notifier
73 def run(self, opts, args):
74 """This run() method is called for every NFVbench benchmark request.
76 In CLI mode, this method is called only once per invocation.
77 In REST server mode, this is called once per REST POST request
79 status = NFVBench.STATUS_OK
83 # take a snapshot of the current time for this new run
84 # so that all subsequent logs can relate to this run
85 fluent_logger.start_new_run()
88 # recalc the running config based on the base config and options for this run
89 self._update_config(opts)
90 if self.config.cache_size < 0:
91 self.config.cache_size = self.config.flow_count
92 # check that an empty openrc file (no OpenStack) is only allowed
94 if not self.config.openrc_file and self.config.service_chain != ChainType.EXT:
95 raise Exception("openrc_file in the configuration is required for PVP/PVVP chains")
97 self.specs.set_run_spec(self.config_plugin.get_run_spec(self.config,
98 self.specs.openstack))
99 self.chain_runner = ChainRunner(self.config,
105 # make sure that the min frame size is 64
107 for frame_size in self.config.frame_sizes:
109 if int(frame_size) < min_packet_size:
110 frame_size = str(min_packet_size)
111 LOG.info("Adjusting frame size %s bytes to minimum size %s bytes",
112 frame_size, min_packet_size)
113 if frame_size not in new_frame_sizes:
114 new_frame_sizes.append(frame_size)
116 new_frame_sizes.append(frame_size.upper())
117 self.config.frame_sizes = new_frame_sizes
119 "date": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
120 "nfvbench_version": __version__,
121 "config": self.config_plugin.prepare_results_config(copy.deepcopy(self.config)),
124 "service_chain": self.chain_runner.run(),
125 "versions": self.chain_runner.get_version(),
129 if self.specs.openstack:
130 result['openstack_spec'] = {"vswitch": self.specs.openstack.vswitch,
131 "encaps": self.specs.openstack.encaps}
132 result['benchmarks']['network']['versions'].update(self.config_plugin.get_version())
134 status = NFVBench.STATUS_ERROR
135 message = traceback.format_exc()
136 except KeyboardInterrupt:
137 status = NFVBench.STATUS_ERROR
138 message = traceback.format_exc()
140 if self.chain_runner:
141 self.chain_runner.close()
143 if status == NFVBench.STATUS_OK:
144 # result2 = utils.dict_to_json_dict(result)
151 'error_message': message
154 def prepare_summary(self, result):
155 """Prepare summary of the result to print and send it to logger (eg: fluentd)."""
157 summary = NFVBenchSummarizer(result, fluent_logger)
158 LOG.info(str(summary))
160 def save(self, result):
161 """Save results in json format file."""
162 utils.save_json_result(result,
163 self.config.json_file,
164 self.config.std_json_path,
165 self.config.service_chain,
166 self.config.service_chain_count,
167 self.config.flow_count,
168 self.config.frame_sizes)
170 def _update_config(self, opts):
171 """Recalculate the running config based on the base config and opts.
173 Sanity check on the config is done here as well.
175 self.config = AttrDict(dict(self.base_config))
176 self.config.update(opts)
179 config.service_chain = config.service_chain.upper()
180 config.service_chain_count = int(config.service_chain_count)
181 if config.l2_loopback:
182 # force the number of chains to be 1 in case of l2 loopback
183 config.service_chain_count = 1
184 config.service_chain = ChainType.EXT
186 LOG.info('Running L2 loopback: using EXT chain/no ARP')
187 config.flow_count = utils.parse_flow_count(config.flow_count)
188 required_flow_count = config.service_chain_count * 2
189 if config.flow_count < required_flow_count:
190 LOG.info("Flow count %d has been set to minimum value of '%d' "
191 "for current configuration", config.flow_count,
193 config.flow_count = required_flow_count
195 if config.flow_count % 2:
196 config.flow_count += 1
198 config.duration_sec = float(config.duration_sec)
199 config.interval_sec = float(config.interval_sec)
200 config.pause_sec = float(config.pause_sec)
202 if config.traffic is None or not config.traffic:
203 raise Exception("Missing traffic property in configuration")
205 if config.openrc_file:
206 config.openrc_file = os.path.expanduser(config.openrc_file)
207 if config.flavor.vcpus < 2:
208 raise Exception("Flavor vcpus must be >= 2")
211 config.ndr_run = (not config.no_traffic and
212 'ndr' in config.rate.strip().lower().split('_'))
213 config.pdr_run = (not config.no_traffic and
214 'pdr' in config.rate.strip().lower().split('_'))
215 config.single_run = (not config.no_traffic and
216 not (config.ndr_run or config.pdr_run))
218 config.json_file = config.json if config.json else None
220 (path, _filename) = os.path.split(config.json)
221 if not os.path.exists(path):
222 raise Exception('Please provide existing path for storing results in JSON file. '
223 'Path used: {path}'.format(path=path))
225 config.std_json_path = config.std_json if config.std_json else None
226 if config.std_json_path:
227 if not os.path.exists(config.std_json):
228 raise Exception('Please provide existing path for storing results in JSON file. '
229 'Path used: {path}'.format(path=config.std_json_path))
231 # Check that multiqueue is between 1 and 8 (8 is the max allowed by libvirt/qemu)
232 if config.vif_multiqueue_size < 1 or config.vif_multiqueue_size > 8:
233 raise Exception('vif_multiqueue_size (%d) must be in [1..8]' %
234 config.vif_multiqueue_size)
236 # VxLAN sanity checks
238 if config.vlan_tagging:
239 config.vlan_tagging = False
240 LOG.info('VxLAN: vlan_tagging forced to False '
241 '(inner VLAN tagging must be disabled)')
243 self.config_plugin.validate_config(config, self.specs.openstack)
246 def _parse_opts_from_cli():
247 parser = argparse.ArgumentParser()
249 parser.add_argument('--status', dest='status',
252 help='Provide NFVbench status')
254 parser.add_argument('-c', '--config', dest='config',
256 help='Override default values with a config file or '
257 'a yaml/json config string',
258 metavar='<file_name_or_yaml>')
260 parser.add_argument('--server', dest='server',
263 help='Run nfvbench in server mode')
265 parser.add_argument('--host', dest='host',
268 help='Host IP address on which server will be listening (default 0.0.0.0)')
270 parser.add_argument('-p', '--port', dest='port',
273 help='Port on which server will be listening (default 7555)')
275 parser.add_argument('-sc', '--service-chain', dest='service_chain',
276 choices=ChainType.names,
278 help='Service chain to run')
280 parser.add_argument('-scc', '--service-chain-count', dest='service_chain_count',
282 help='Set number of service chains to run',
283 metavar='<service_chain_count>')
285 parser.add_argument('-fc', '--flow-count', dest='flow_count',
287 help='Set number of total flows for all chains and all directions',
288 metavar='<flow_count>')
290 parser.add_argument('--rate', dest='rate',
292 help='Specify rate in pps, bps or %% as total for all directions',
295 parser.add_argument('--duration', dest='duration_sec',
297 help='Set duration to run traffic generator (in seconds)',
298 metavar='<duration_sec>')
300 parser.add_argument('--interval', dest='interval_sec',
302 help='Set interval to record traffic generator stats (in seconds)',
303 metavar='<interval_sec>')
305 parser.add_argument('--inter-node', dest='inter_node',
310 parser.add_argument('--sriov', dest='sriov',
313 help='Use SRIOV (no vswitch - requires SRIOV support in compute nodes)')
315 parser.add_argument('--use-sriov-middle-net', dest='use_sriov_middle_net',
318 help='Use SRIOV to handle the middle network traffic '
319 '(PVVP with SRIOV only)')
321 parser.add_argument('-d', '--debug', dest='debug',
324 help='print debug messages (verbose)')
326 parser.add_argument('-g', '--traffic-gen', dest='generator_profile',
328 help='Traffic generator profile to use')
330 parser.add_argument('-l3', '--l3-router', dest='l3_router',
333 help='Use L3 neutron routers to handle traffic')
335 parser.add_argument('-0', '--no-traffic', dest='no_traffic',
338 help='Check config and connectivity only - do not generate traffic')
340 parser.add_argument('--no-arp', dest='no_arp',
343 help='Do not use ARP to find MAC addresses, '
344 'instead use values in config file')
346 parser.add_argument('--no-vswitch-access', dest='no_vswitch_access',
349 help='Skip vswitch configuration and retrieving of stats')
351 parser.add_argument('--vxlan', dest='vxlan',
354 help='Enable VxLan encapsulation')
356 parser.add_argument('--no-cleanup', dest='no_cleanup',
359 help='no cleanup after run')
361 parser.add_argument('--cleanup', dest='cleanup',
364 help='Cleanup NFVbench resources (prompt to confirm)')
366 parser.add_argument('--force-cleanup', dest='force_cleanup',
369 help='Cleanup NFVbench resources (do not prompt)')
371 parser.add_argument('--restart', dest='restart',
374 help='Restart TRex server')
376 parser.add_argument('--json', dest='json',
378 help='store results in json format file',
379 metavar='<path>/<filename>')
381 parser.add_argument('--std-json', dest='std_json',
383 help='store results in json format file with nfvbench standard filename: '
384 '<service-chain-type>-<service-chain-count>-<flow-count>'
385 '-<packet-sizes>.json',
388 parser.add_argument('--show-default-config', dest='show_default_config',
391 help='print the default config in yaml format (unedited)')
393 parser.add_argument('--show-config', dest='show_config',
396 help='print the running config in json format')
398 parser.add_argument('-ss', '--show-summary', dest='summary',
400 help='Show summary from nfvbench json file',
403 parser.add_argument('-v', '--version', dest='version',
408 parser.add_argument('-fs', '--frame-size', dest='frame_sizes',
410 help='Override traffic profile frame sizes',
411 metavar='<frame_size_bytes or IMIX>')
413 parser.add_argument('--unidir', dest='unidir',
416 help='Override traffic profile direction (requires -fs)')
418 parser.add_argument('--log-file', '--logfile', dest='log_file',
420 help='Filename for saving logs',
421 metavar='<log_file>')
423 parser.add_argument('--user-label', '--userlabel', dest='user_label',
425 help='Custom label for performance records')
427 parser.add_argument('--hypervisor', dest='hypervisor',
429 metavar='<hypervisor name>',
430 help='Where chains must run ("compute", "az:", "az:compute")')
432 parser.add_argument('--l2-loopback', '--l2loopback', dest='l2_loopback',
435 help='Port to port or port to switch to port L2 loopback with VLAN id')
437 parser.add_argument('--cache-size', dest='cache_size',
440 help='Specify the FE cache size (default: 0, flow-count if < 0)')
442 parser.add_argument('--service-mode', dest='service_mode',
445 help='Enable T-Rex service mode for debugging only')
447 parser.add_argument('--no-flow-stats', dest='no_flow_stats',
450 help='Disable extra flow stats (on high load traffic)')
452 parser.add_argument('--no-latency-stats', dest='no_latency_stats',
455 help='Disable flow stats for latency traffic')
457 parser.add_argument('--no-latency-streams', dest='no_latency_streams',
460 help='Disable latency measurements (no streams)')
462 opts, unknown_opts = parser.parse_known_args()
463 return opts, unknown_opts
466 def load_default_config():
467 default_cfg = resource_string(__name__, "cfg.default.yaml")
468 config = config_loads(default_cfg)
469 config.name = '(built-in default config)'
470 return config, default_cfg
473 def override_custom_traffic(config, frame_sizes, unidir):
474 """Override the traffic profiles with a custom one."""
475 if frame_sizes is not None:
476 traffic_profile_name = "custom_traffic_profile"
477 config.traffic_profile = [
479 "l2frame_size": frame_sizes,
480 "name": traffic_profile_name
484 traffic_profile_name = config.traffic["profile"]
486 bidirectional = config.traffic['bidirectional'] if unidir is None else not unidir
488 "bidirectional": bidirectional,
489 "profile": traffic_profile_name
493 def check_physnet(name, netattrs):
494 if not netattrs.physical_network:
495 raise Exception("SRIOV requires physical_network to be specified for the {n} network"
497 if not netattrs.segmentation_id:
498 raise Exception("SRIOV requires segmentation_id to be specified for the {n} network"
501 def status_cleanup(config, cleanup, force_cleanup):
502 LOG.info('Version: %s', pbr.version.VersionInfo('nfvbench').version_string_with_vcs())
503 # check if another run is pending
506 with utils.RunLock():
507 LOG.info('Status: idle')
509 LOG.info('Status: busy (run pending)')
511 # check nfvbench resources
512 if config.openrc_file and config.service_chain != ChainType.EXT:
513 cleaner = Cleaner(config)
514 count = cleaner.show_resources()
515 if count and (cleanup or force_cleanup):
516 cleaner.clean(not force_cleanup)
521 run_summary_required = False
524 # load default config file
525 config, default_cfg = load_default_config()
526 # create factory for platform specific classes
528 factory_module = importlib.import_module(config['factory_module'])
529 factory = getattr(factory_module, config['factory_class'])()
530 except AttributeError:
531 raise Exception("Requested factory module '{m}' or class '{c}' was not found."
532 .format(m=config['factory_module'], c=config['factory_class']))
533 # create config plugin for this platform
534 config_plugin = factory.get_config_plugin_class()(config)
535 config = config_plugin.get_config()
537 opts, unknown_opts = _parse_opts_from_cli()
538 log.set_level(debug=opts.debug)
541 print pbr.version.VersionInfo('nfvbench').version_string_with_vcs()
545 with open(opts.summary) as json_data:
546 result = json.load(json_data)
548 result['config']['user_label'] = opts.user_label
549 print NFVBenchSummarizer(result, fluent_logger)
552 # show default config in text/yaml format
553 if opts.show_default_config:
559 # do not check extra_specs in flavor as it can contain any key/value pairs
560 whitelist_keys = ['extra_specs']
561 # override default config options with start config at path parsed from CLI
562 # check if it is an inline yaml/json config or a file name
563 if os.path.isfile(opts.config):
564 LOG.info('Loading configuration file: %s', opts.config)
565 config = config_load(opts.config, config, whitelist_keys)
566 config.name = os.path.basename(opts.config)
568 LOG.info('Loading configuration string: %s', opts.config)
569 config = config_loads(opts.config, config, whitelist_keys)
571 # setup the fluent logger as soon as possible right after the config plugin is called,
572 # if there is any logging or result tag is set then initialize the fluent logger
573 for fluentd in config.fluentd:
574 if fluentd.logging_tag or fluentd.result_tag:
575 fluent_logger = FluentLogHandler(config.fluentd)
576 LOG.addHandler(fluent_logger)
579 # traffic profile override options
580 override_custom_traffic(config, opts.frame_sizes, opts.unidir)
582 # copy over cli options that are used in config
583 config.generator_profile = opts.generator_profile
587 config.log_file = opts.log_file
588 if opts.service_chain:
589 config.service_chain = opts.service_chain
590 if opts.service_chain_count:
591 config.service_chain_count = opts.service_chain_count
592 if opts.no_vswitch_access:
593 config.no_vswitch_access = opts.no_vswitch_access
595 # can be any of 'comp1', 'nova:', 'nova:comp1'
596 config.compute_nodes = opts.hypervisor
600 config.restart = True
601 if opts.service_mode:
602 config.service_mode = True
603 if opts.no_flow_stats:
604 config.no_flow_stats = True
605 if opts.no_latency_stats:
606 config.no_latency_stats = True
607 if opts.no_latency_streams:
608 config.no_latency_streams = True
609 # port to port loopback (direct or through switch)
611 config.l2_loopback = True
612 if config.service_chain != ChainType.EXT:
613 LOG.info('Changing service chain type to EXT')
614 config.service_chain = ChainType.EXT
615 if not config.no_arp:
616 LOG.info('Disabling ARP')
618 config.vlans = [int(opts.l2_loopback), int(opts.l2_loopback)]
619 LOG.info('Running L2 loopback: using EXT chain/no ARP')
621 if opts.use_sriov_middle_net:
622 if (not config.sriov) or (config.service_chain != ChainType.PVVP):
623 raise Exception("--use-sriov-middle-net is only valid for PVVP with SRIOV")
624 config.use_sriov_middle_net = True
626 if config.sriov and config.service_chain != ChainType.EXT:
627 # if sriov is requested (does not apply to ext chains)
628 # make sure the physnet names are specified
629 check_physnet("left", config.internal_networks.left)
630 check_physnet("right", config.internal_networks.right)
631 if config.service_chain == ChainType.PVVP and config.use_sriov_middle_net:
632 check_physnet("middle", config.internal_networks.middle)
634 # show running config in json format
636 print json.dumps(config, sort_keys=True, indent=4)
639 # update the config in the config plugin as it might have changed
640 # in a copy of the dict (config plugin still holds the original dict)
641 config_plugin.set_config(config)
643 if opts.status or opts.cleanup or opts.force_cleanup:
644 status_cleanup(config, opts.cleanup, opts.force_cleanup)
646 # add file log if requested
648 log.add_file_logger(config.log_file)
650 openstack_spec = config_plugin.get_openstack_spec() if config.openrc_file \
653 nfvbench_instance = NFVBench(config, openstack_spec, config_plugin, factory)
656 server = WebServer(nfvbench_instance, fluent_logger)
658 port = int(opts.port)
660 server.run(host=opts.host)
662 server.run(host=opts.host, port=port)
663 # server.run() should never return
665 with utils.RunLock():
666 run_summary_required = True
668 err_msg = 'Unknown options: ' + ' '.join(unknown_opts)
670 raise Exception(err_msg)
672 # remove unfilled values
673 opts = {k: v for k, v in vars(opts).iteritems() if v is not None}
675 params = ' '.join(str(e) for e in sys.argv[1:])
676 result = nfvbench_instance.run(opts, params)
677 if 'error_message' in result:
678 raise Exception(result['error_message'])
680 if 'result' in result and result['status']:
681 nfvbench_instance.save(result['result'])
682 nfvbench_instance.prepare_summary(result['result'])
683 except Exception as exc:
684 run_summary_required = True
686 'status': NFVBench.STATUS_ERROR,
687 'error_message': traceback.format_exc()
692 # only send a summary record if there was an actual nfvbench run or
693 # if an error/exception was logged.
694 fluent_logger.send_run_summary(run_summary_required)
697 if __name__ == '__main__':