77ab7840f3ab343cdfcbc396822cb583527c8d62
[releng.git] / utils / test / reporting / functest / reporting-status.py
1 #!/usr/bin/python
2 #
3 # This program and the accompanying materials
4 # are made available under the terms of the Apache License, Version 2.0
5 # which accompanies this distribution, and is available at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 import datetime
10 import jinja2
11 import os
12 import sys
13 import time
14
15 import testCase as tc
16 import scenarioResult as sr
17
18 # manage conf
19 import utils.reporting_utils as rp_utils
20
21 # Logger
22 logger = rp_utils.getLogger("Functest-Status")
23
24 # Initialization
25 testValid = []
26 otherTestCases = []
27 reportingDate = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
28
29 # init just connection_check to get the list of scenarios
30 # as all the scenarios run connection_check
31 healthcheck = tc.TestCase("connection_check", "functest", -1)
32
33 # Retrieve the Functest configuration to detect which tests are relevant
34 # according to the installer, scenario
35 cf = rp_utils.get_config('functest.test_conf')
36 period = rp_utils.get_config('general.period')
37 versions = rp_utils.get_config('general.versions')
38 installers = rp_utils.get_config('general.installers')
39 blacklist = rp_utils.get_config('functest.blacklist')
40 log_level = rp_utils.get_config('general.log.log_level')
41 exclude_noha = rp_utils.get_config('functest.exclude_noha')
42 exclude_virtual = rp_utils.get_config('functest.exclude_virtual')
43
44 functest_yaml_config = rp_utils.getFunctestConfig()
45
46 logger.info("*******************************************")
47 logger.info("*                                         *")
48 logger.info("*   Generating reporting scenario status  *")
49 logger.info("*   Data retention: %s days               *" % period)
50 logger.info("*   Log level: %s                         *" % log_level)
51 logger.info("*                                         *")
52 logger.info("*   Virtual PODs exluded: %s              *" % exclude_virtual)
53 logger.info("*   NOHA scenarios excluded: %s           *" % exclude_noha)
54 logger.info("*                                         *")
55 logger.info("*******************************************")
56
57 # Retrieve test cases of Tier 1 (smoke)
58 config_tiers = functest_yaml_config.get("tiers")
59
60 # we consider Tier 0 (Healthcheck), Tier 1 (smoke),2 (features)
61 # to validate scenarios
62 # Tier > 2 are not used to validate scenarios but we display the results anyway
63 # tricky thing for the API as some tests are Functest tests
64 # other tests are declared directly in the feature projects
65 for tier in config_tiers:
66     if tier['order'] >= 0 and tier['order'] < 2:
67         for case in tier['testcases']:
68             if case['case_name'] not in blacklist:
69                 testValid.append(tc.TestCase(case['case_name'],
70                                              "functest",
71                                              case['dependencies']))
72     elif tier['order'] == 2:
73         for case in tier['testcases']:
74             if case['case_name'] not in blacklist:
75                 testValid.append(tc.TestCase(case['case_name'],
76                                              case['case_name'],
77                                              case['dependencies']))
78     elif tier['order'] > 2:
79         for case in tier['testcases']:
80             if case['case_name'] not in blacklist:
81                 otherTestCases.append(tc.TestCase(case['case_name'],
82                                                   "functest",
83                                                   case['dependencies']))
84
85 logger.debug("Functest reporting start")
86
87 # For all the versions
88 for version in versions:
89     # For all the installers
90     scenario_directory = "./display/" + version + "/functest/"
91     scenario_file_name = scenario_directory + "scenario_history.txt"
92
93     # check that the directory exists, if not create it
94     # (first run on new version)
95     if not os.path.exists(scenario_directory):
96         os.makedirs(scenario_directory)
97
98     # initiate scenario file if it does not exist
99     if not os.path.isfile(scenario_file_name):
100         with open(scenario_file_name, "a") as my_file:
101             logger.debug("Create scenario file: %s" % scenario_file_name)
102             my_file.write("date,scenario,installer,detail,score\n")
103
104     for installer in installers:
105
106         # get scenarios
107         scenario_results = rp_utils.getScenarios(healthcheck,
108                                                  installer,
109                                                  version)
110         # get nb of supported architecture (x86, aarch64)
111         architectures = rp_utils.getArchitectures(scenario_results)
112         logger.info("Supported architectures: {}".format(architectures))
113
114         for architecture in architectures:
115             logger.info("architecture: {}".format(architecture))
116             # Consider only the results for the selected architecture
117             # i.e drop x86 for aarch64 and vice versa
118             filter_results = rp_utils.filterArchitecture(scenario_results,
119                                                          architecture)
120             scenario_stats = rp_utils.getScenarioStats(filter_results)
121             items = {}
122             scenario_result_criteria = {}
123
124             # in case of more than 1 architecture supported
125             # precise the architecture
126             installer_display = installer
127             if (len(architectures) > 1):
128                 installer_display = installer + "@" + architecture
129
130             # For all the scenarios get results
131             for s, s_result in filter_results.items():
132                 logger.info("---------------------------------")
133                 logger.info("installer %s, version %s, scenario %s:" %
134                             (installer, version, s))
135                 logger.debug("Scenario results: %s" % s_result)
136
137                 # Green or Red light for a given scenario
138                 nb_test_runnable_for_this_scenario = 0
139                 scenario_score = 0
140                 # url of the last jenkins log corresponding to a given
141                 # scenario
142                 s_url = ""
143                 if len(s_result) > 0:
144                     build_tag = s_result[len(s_result)-1]['build_tag']
145                     logger.debug("Build tag: %s" % build_tag)
146                     s_url = rp_utils.getJenkinsUrl(build_tag)
147                     if s_url is None:
148                         s_url = "http://testresultS.opnfv.org/reporting"
149                     logger.info("last jenkins url: %s" % s_url)
150                 testCases2BeDisplayed = []
151                 # Check if test case is runnable / installer, scenario
152                 # for the test case used for Scenario validation
153                 try:
154                     # 1) Manage the test cases for the scenario validation
155                     # concretely Tiers 0-3
156                     for test_case in testValid:
157                         test_case.checkRunnable(installer, s,
158                                                 test_case.getConstraints())
159                         logger.debug("testcase %s (%s) is %s" %
160                                      (test_case.getDisplayName(),
161                                       test_case.getName(),
162                                       test_case.isRunnable))
163                         time.sleep(1)
164                         if test_case.isRunnable:
165                             name = test_case.getName()
166                             displayName = test_case.getDisplayName()
167                             project = test_case.getProject()
168                             nb_test_runnable_for_this_scenario += 1
169                             logger.info(" Searching results for case %s " %
170                                         (displayName))
171                             result = rp_utils.getResult(name, installer,
172                                                         s, version)
173                             # if no result set the value to 0
174                             if result < 0:
175                                 result = 0
176                             logger.info(" >>>> Test score = " + str(result))
177                             test_case.setCriteria(result)
178                             test_case.setIsRunnable(True)
179                             testCases2BeDisplayed.append(tc.TestCase(name,
180                                                                      project,
181                                                                      "",
182                                                                      result,
183                                                                      True,
184                                                                      1))
185                             scenario_score = scenario_score + result
186
187                     # 2) Manage the test cases for the scenario qualification
188                     # concretely Tiers > 3
189                     for test_case in otherTestCases:
190                         test_case.checkRunnable(installer, s,
191                                                 test_case.getConstraints())
192                         logger.debug("testcase %s (%s) is %s" %
193                                      (test_case.getDisplayName(),
194                                       test_case.getName(),
195                                       test_case.isRunnable))
196                         time.sleep(1)
197                         if test_case.isRunnable:
198                             name = test_case.getName()
199                             displayName = test_case.getDisplayName()
200                             project = test_case.getProject()
201                             logger.info(" Searching results for case %s " %
202                                         (displayName))
203                             result = rp_utils.getResult(name, installer,
204                                                         s, version)
205                             # at least 1 result for the test
206                             if result > -1:
207                                 test_case.setCriteria(result)
208                                 test_case.setIsRunnable(True)
209                                 testCases2BeDisplayed.append(tc.TestCase(
210                                     name,
211                                     project,
212                                     "",
213                                     result,
214                                     True,
215                                     4))
216                             else:
217                                 logger.debug("No results found")
218
219                         items[s] = testCases2BeDisplayed
220                 except:
221                     logger.error("Error: installer %s, version %s, scenario %s"
222                                  % (installer, version, s))
223                     logger.error("No data available: %s" % (sys.exc_info()[0]))
224
225                 # **********************************************
226                 # Evaluate the results for scenario validation
227                 # **********************************************
228                 # the validation criteria = nb runnable tests x 3
229                 # because each test case = 0,1,2 or 3
230                 scenario_criteria = nb_test_runnable_for_this_scenario * 3
231                 # if 0 runnable tests set criteria at a high value
232                 if scenario_criteria < 1:
233                     scenario_criteria = 50  # conf.MAX_SCENARIO_CRITERIA
234
235                 s_score = str(scenario_score) + "/" + str(scenario_criteria)
236                 s_score_percent = rp_utils.getScenarioPercent(
237                     scenario_score,
238                     scenario_criteria)
239
240                 s_status = "KO"
241                 if scenario_score < scenario_criteria:
242                     logger.info(">>>> scenario not OK, score = %s/%s" %
243                                 (scenario_score, scenario_criteria))
244                     s_status = "KO"
245                 else:
246                     logger.info(">>>>> scenario OK, save the information")
247                     s_status = "OK"
248                     path_validation_file = ("./display/" + version +
249                                             "/functest/" +
250                                             "validated_scenario_history.txt")
251                     with open(path_validation_file, "a") as f:
252                         time_format = "%Y-%m-%d %H:%M"
253                         info = (datetime.datetime.now().strftime(time_format) +
254                                 ";" + installer_display + ";" + s + "\n")
255                         f.write(info)
256
257                 # Save daily results in a file
258                 with open(scenario_file_name, "a") as f:
259                     info = (reportingDate + "," + s + "," + installer_display +
260                             "," + s_score + "," +
261                             str(round(s_score_percent)) + "\n")
262                     f.write(info)
263
264                 scenario_result_criteria[s] = sr.ScenarioResult(
265                     s_status,
266                     s_score,
267                     s_score_percent,
268                     s_url)
269                 logger.info("--------------------------")
270
271             templateLoader = jinja2.FileSystemLoader(".")
272             templateEnv = jinja2.Environment(
273                 loader=templateLoader, autoescape=True)
274
275             TEMPLATE_FILE = "./functest/template/index-status-tmpl.html"
276             template = templateEnv.get_template(TEMPLATE_FILE)
277
278             outputText = template.render(
279                             scenario_stats=scenario_stats,
280                             scenario_results=scenario_result_criteria,
281                             items=items,
282                             installer=installer_display,
283                             period=period,
284                             version=version,
285                             date=reportingDate)
286
287             with open("./display/" + version +
288                       "/functest/status-" +
289                       installer_display + ".html", "wb") as fh:
290                 fh.write(outputText)
291
292             logger.info("Manage export CSV & PDF")
293             rp_utils.export_csv(scenario_file_name, installer_display, version)
294             logger.error("CSV generated...")
295
296             # Generate outputs for export
297             # pdf
298             # TODO Change once web site updated...use the current one
299             # to test pdf production
300             url_pdf = rp_utils.get_config('general.url')
301             pdf_path = ("./display/" + version +
302                         "/functest/status-" + installer_display + ".html")
303             pdf_doc_name = ("./display/" + version +
304                             "/functest/status-" + installer_display + ".pdf")
305             rp_utils.export_pdf(pdf_path, pdf_doc_name)
306             logger.info("PDF generated...")