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