license: Add license info to all project files
[vswitchperf.git] / tools / report / report.py
1 # Copyright 2015-2017 Intel Corporation.
2 #
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
15 """
16 vSwitch Characterization Report Generation.
17
18 Generate reports in format defined by X.
19 """
20
21 import sys
22 import os
23 import logging
24 import jinja2
25
26 from core.results.results_constants import ResultsConstants
27 from conf import settings as S
28 from tools import systeminfo
29
30 _TEMPLATE_FILES = ['report.jinja', 'report_rst.jinja']
31 _ROOT_DIR = os.path.normpath(os.path.dirname(os.path.realpath(__file__)))
32
33
34 def _get_env(result):
35     """
36     Get system configuration.
37
38     :returns: Return a dictionary of the test environment.
39               The following is an example return value:
40                {'kernel': '3.10.0-229.4.2.el7.x86_64',
41                 'os': 'OS Version',
42                 'cpu': ' CPU 2.30GHz',
43                 'platform': '[2 sockets]',
44                 'nic': 'NIC'}
45
46     """
47
48     env = {
49         'os': systeminfo.get_os(),
50         'kernel': systeminfo.get_kernel(),
51         'nics': systeminfo.get_nic(),
52         'cpu': systeminfo.get_cpu(),
53         'cpu_cores': systeminfo.get_cpu_cores(),
54         'memory' : systeminfo.get_memory(),
55         'platform': systeminfo.get_platform(),
56         'vsperf': systeminfo.get_version('vswitchperf'),
57         'traffic_gen': systeminfo.get_version(S.getValue('TRAFFICGEN')),
58         'vswitch': systeminfo.get_version(S.getValue('VSWITCH')),
59     }
60
61     if S.getValue('VSWITCH').lower().count('dpdk'):
62         env.update({'dpdk': systeminfo.get_version('dpdk')})
63
64     if result[ResultsConstants.DEPLOYMENT].count('v'):
65         env.update({'vnf': systeminfo.get_version(S.getValue('VNF')),
66                     'guest_image': S.getValue('GUEST_IMAGE'),
67                     'loopback_app': list(map(systeminfo.get_loopback_version,
68                                              S.getValue('GUEST_LOOPBACK'))),
69                    })
70
71     return env
72
73
74 def generate(input_file, tc_results, tc_stats, test_type='performance'):
75     """Generate actual report.
76
77     Generate a Markdown and RST formatted files using results of tests and some
78     parsed system info.
79
80     :param input_file: Path to CSV results file
81     :param tc_results: A list of dictionaries with detailed test results.
82         Each dictionary represents test results for one of specified packet
83         sizes.
84     :param tc_stats: System statistics collected during testcase execution.
85         These statistics are overall statistics for all specified packet
86         sizes.
87     :test_type: Specifies type of the testcase. Supported values are
88         'performance' and 'integration'.
89
90     :returns: Path to generated report
91     """
92     output_files = [('.'.join([os.path.splitext(input_file)[0], 'md'])),
93                     ('.'.join([os.path.splitext(input_file)[0], 'rst']))]
94     template_loader = jinja2.FileSystemLoader(searchpath=_ROOT_DIR)
95     template_env = jinja2.Environment(loader=template_loader)
96
97     tests = []
98     try:
99         for result in tc_results:
100             test_config = {}
101             if test_type == 'performance':
102                 for tc_conf in S.getValue('PERFORMANCE_TESTS'):
103                     if tc_conf['Name'] == result[ResultsConstants.ID]:
104                         test_config = tc_conf
105                         break
106             elif test_type == 'integration':
107                 for tc_conf in S.getValue('INTEGRATION_TESTS'):
108                     if tc_conf['Name'] == result[ResultsConstants.ID]:
109                         test_config = tc_conf
110                         break
111             else:
112                 logging.error("Unsupported test type '%s'. Test details are not known.", test_type)
113
114             # pass test results, env details and configuration to template
115             tests.append({
116                 'ID': result[ResultsConstants.ID].upper(),
117                 'id': result[ResultsConstants.ID],
118                 'deployment': result[ResultsConstants.DEPLOYMENT],
119                 'conf': test_config,
120                 'result': result,
121                 'env': _get_env(result),
122                 'stats': tc_stats
123             })
124
125             # remove id and deployment from results before rendering
126             # but after _get_env() is called; tests dict has its shallow copy
127             del result[ResultsConstants.ID]
128             del result[ResultsConstants.DEPLOYMENT]
129
130         template_vars = {
131             'tests': tests,
132         }
133         i = 0
134         # pylint: disable=no-member
135         for output_file in output_files:
136             template = template_env.get_template(_TEMPLATE_FILES[i])
137             output_text = template.render(template_vars)
138             with open(output_file, 'w') as file_:
139                 file_.write(output_text)
140                 logging.info('Test report written to "%s"', output_file)
141             i += 1
142
143     except KeyError:
144         logging.info("Report: Ignoring file (Wrongly defined columns): %s",
145                      (input_file))
146         raise
147     return output_files
148
149
150 if __name__ == '__main__':
151     S.load_from_dir('conf')
152     OUT = generate(sys.argv[1], '', '')
153     print('Test report written to "%s"...' % OUT)