Fix the tempest error when creating snapshot
[functest.git] / functest / opnfv_tests / openstack / refstack_client / refstack_client.py
1 #!/usr/bin/env python
2 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
3 # matthew.lijun@huawei.com wangwulin@huawei.com
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8
9 """Refstack client testcase implemenation."""
10
11 from __future__ import division
12
13
14 import argparse
15 import logging
16 import os
17 import re
18 import sys
19 import subprocess
20 import time
21
22 import pkg_resources
23
24 from functest.core import testcase
25 from functest.energy import energy
26 from functest.opnfv_tests.openstack.refstack_client.tempest_conf \
27     import TempestConf
28 from functest.opnfv_tests.openstack.tempest import conf_utils
29 from functest.utils.constants import CONST
30 import functest.utils.functest_utils as ft_utils
31 import functest.utils.openstack_utils as os_utils
32
33 # logging configuration """
34 LOGGER = logging.getLogger(__name__)
35
36
37 class RefstackClient(testcase.TestCase):
38     """RefstackClient testcase implementation class."""
39
40     def __init__(self, **kwargs):
41         """Initialize RefstackClient testcase object."""
42         if "case_name" not in kwargs:
43             kwargs["case_name"] = "refstack_defcore"
44         super(RefstackClient, self).__init__(**kwargs)
45         self.tempestconf = None
46         self.conf_path = pkg_resources.resource_filename(
47             'functest',
48             'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
49         self.functest_test = pkg_resources.resource_filename(
50             'functest', 'opnfv_tests')
51         self.defcore_list = 'openstack/refstack_client/defcore.txt'
52         self.confpath = os.path.join(self.functest_test,
53                                      self.conf_path)
54         self.defcorelist = pkg_resources.resource_filename(
55             'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
56         self.testlist = None
57         self.insecure = ''
58         if ('https' in CONST.__getattribute__('OS_AUTH_URL') and
59                 CONST.__getattribute__('OS_INSECURE').lower() == 'true'):
60             self.insecure = '-k'
61
62     def generate_conf(self):
63         if not os.path.exists(conf_utils.REFSTACK_RESULTS_DIR):
64             os.makedirs(conf_utils.REFSTACK_RESULTS_DIR)
65
66         self.tempestconf = TempestConf()
67         self.tempestconf.generate_tempestconf()
68
69     def run_defcore(self, conf, testlist):
70         """Run defcore sys command."""
71         cmd = ("refstack-client test {0} -c {1} -v --test-list {2}"
72                .format(self.insecure, conf, testlist))
73         LOGGER.info("Starting Refstack_defcore test case: '%s'.", cmd)
74         ft_utils.execute_command(cmd)
75
76     def run_defcore_default(self):
77         """Run default defcore sys command."""
78         options = ["-v"] if not self.insecure else ["-v", self.insecure]
79         cmd = (["refstack-client", "test", "-c", self.confpath] +
80                options + ["--test-list",  self.defcorelist])
81         LOGGER.info("Starting Refstack_defcore test case: '%s'.", cmd)
82
83         with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
84                                "environment.log"), 'w+') as f_env:
85             f_env.write(
86                 ("Refstack environment:\n"
87                  "  SUT: {}\n  Scenario: {}\n  Node: {}\n  Date: {}\n").format(
88                     CONST.__getattribute__('INSTALLER_TYPE'),
89                     CONST.__getattribute__('DEPLOY_SCENARIO'),
90                     CONST.__getattribute__('NODE_NAME'),
91                     time.strftime("%a %b %d %H:%M:%S %Z %Y")))
92
93         with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
94                                "refstack.log"), 'w+') as f_stdout:
95             subprocess.call(cmd, shell=False, stdout=f_stdout,
96                             stderr=subprocess.STDOUT)
97
98     def parse_refstack_result(self):
99         """Parse Refstack results."""
100         try:
101             with open(os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
102                                    "refstack.log"), 'r') as logfile:
103                 output = logfile.read()
104
105             for match in re.findall(r"Ran: (\d+) tests in (\d+\.\d{4}) sec.",
106                                     output):
107                 num_tests = match[0]
108                 LOGGER.info("Ran: %s tests in %s sec.", num_tests, match[1])
109             for match in re.findall(r"(- Passed: )(\d+)", output):
110                 num_success = match[1]
111                 LOGGER.info("".join(match))
112             for match in re.findall(r"(- Skipped: )(\d+)", output):
113                 num_skipped = match[1]
114                 LOGGER.info("".join(match))
115             for match in re.findall(r"(- Failed: )(\d+)", output):
116                 num_failures = match[1]
117                 LOGGER.info("".join(match))
118             success_testcases = []
119             for match in re.findall(r"\{0\} (.*?)[. ]*ok", output):
120                 success_testcases.append(match)
121             failed_testcases = []
122             for match in re.findall(r"\{0\} (.*?)[. ]*FAILED", output):
123                 failed_testcases.append(match)
124             skipped_testcases = []
125             for match in re.findall(r"\{0\} (.*?)[. ]*SKIPPED:", output):
126                 skipped_testcases.append(match)
127
128             num_executed = int(num_tests) - int(num_skipped)
129
130             try:
131                 self.result = 100 * int(num_success) / int(num_executed)
132             except ZeroDivisionError:
133                 LOGGER.error("No test has been executed")
134
135             self.details = {"tests": int(num_tests),
136                             "failures": int(num_failures),
137                             "success": success_testcases,
138                             "errors": failed_testcases,
139                             "skipped": skipped_testcases}
140         except Exception:
141             self.result = 0
142
143         LOGGER.info("Testcase %s success_rate is %s%%",
144                     self.case_name, self.result)
145
146     @energy.enable_recording
147     def run(self, **kwargs):
148         """
149         Start RefstackClient testcase.
150
151         used for functest command line,
152         functest testcase run refstack_defcore
153         """
154         self.start_time = time.time()
155
156         try:
157             # Make sure that Tempest is configured
158             if not self.tempestconf:
159                 self.generate_conf()
160             self.run_defcore_default()
161             self.parse_refstack_result()
162             res = testcase.TestCase.EX_OK
163         except Exception:
164             LOGGER.exception("Error with run")
165             res = testcase.TestCase.EX_RUN_ERROR
166         finally:
167             self.tempestconf.clean()
168
169         self.stop_time = time.time()
170         return res
171
172     def _prep_test(self):
173         """Check that the config file exists."""
174         if not os.path.isfile(self.confpath):
175             LOGGER.error("Conf file not valid: %s", self.confpath)
176         if not os.path.isfile(self.testlist):
177             LOGGER.error("testlist file not valid: %s", self.testlist)
178
179     def main(self, **kwargs):
180         """
181         Execute RefstackClient testcase manually.
182
183         used for manually running,
184            python refstack_client.py -c <tempest_conf_path>
185            --testlist <testlist_path>
186            can generate a reference refstack_tempest.conf by
187            python tempest_conf.py
188         """
189         try:
190             self.confpath = kwargs['config']
191             self.testlist = kwargs['testlist']
192         except KeyError as exc:
193             LOGGER.error("Cannot run refstack client. Please check "
194                          "%s", exc)
195             return self.EX_RUN_ERROR
196         try:
197             self._prep_test()
198             self.run_defcore(self.confpath, self.testlist)
199             res = testcase.TestCase.EX_OK
200         except Exception as exc:
201             LOGGER.error('Error with run: %s', exc)
202             res = testcase.TestCase.EX_RUN_ERROR
203
204         return res
205
206     def create_snapshot(self):
207         """
208         Run the Tempest cleanup utility to initialize OS state.
209         For details, see https://docs.openstack.org/tempest/latest/cleanup.html
210
211         :return: TestCase.EX_OK
212         """
213         LOGGER.info("Initializing the saved state of the OpenStack deployment")
214
215         # Make sure that Tempest is configured
216         if not self.tempestconf:
217             self.generate_conf()
218
219         os_utils.init_tempest_cleanup(
220             self.tempestconf.DEPLOYMENT_DIR, 'tempest.conf',
221             os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
222                          "tempest-cleanup-init.log")
223         )
224
225         return super(RefstackClient, self).create_snapshot()
226
227     def clean(self):
228         """
229         Run the Tempest cleanup utility to delete and destroy OS resources.
230         For details, see https://docs.openstack.org/tempest/latest/cleanup.html
231         """
232         LOGGER.info("Destroying the resources created for tempest")
233
234         os_utils.perform_tempest_cleanup(
235             self.tempestconf.DEPLOYMENT_DIR, 'tempest.conf',
236             os.path.join(conf_utils.REFSTACK_RESULTS_DIR,
237                          "tempest-cleanup.log")
238         )
239
240         return super(RefstackClient, self).clean()
241
242
243 class RefstackClientParser(object):  # pylint: disable=too-few-public-methods
244     """Command line argument parser helper."""
245
246     def __init__(self):
247         """Initialize helper object."""
248         self.functest_test = pkg_resources.resource_filename(
249             'functest', 'opnfv_tests')
250         self.conf_path = pkg_resources.resource_filename(
251             'functest',
252             'opnfv_tests/openstack/refstack_client/refstack_tempest.conf')
253         self.defcore_list = pkg_resources.resource_filename(
254             'functest', 'opnfv_tests/openstack/refstack_client/defcore.txt')
255         self.confpath = os.path.join(self.functest_test,
256                                      self.conf_path)
257         self.defcorelist = os.path.join(self.functest_test,
258                                         self.defcore_list)
259         self.parser = argparse.ArgumentParser()
260         self.parser.add_argument(
261             '-c', '--config',
262             help='the file path of refstack_tempest.conf',
263             default=self.confpath)
264         self.parser.add_argument(
265             '-t', '--testlist',
266             help='Specify the file path or URL of a test list text file. '
267                  'This test list will contain specific test cases that '
268                  'should be tested.',
269             default=self.defcorelist)
270
271     def parse_args(self, argv=None):
272         """Parse command line arguments."""
273         return vars(self.parser.parse_args(argv))
274
275
276 def main():
277     """Run RefstackClient testcase with CLI."""
278     logging.basicConfig()
279     refstackclient = RefstackClient()
280     parser = RefstackClientParser()
281     args = parser.parse_args(sys.argv[1:])
282     try:
283         result = refstackclient.main(**args)
284         if result != testcase.TestCase.EX_OK:
285             return result
286     except Exception:
287         return testcase.TestCase.EX_RUN_ERROR