Merge "Refactor functest environment. Bugfixes: arg dependencies"
[functest.git] / testcases / VIM / OpenStack / CI / libraries / run_rally.py
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2015 Orange
4 # guyrodrigue.koffi@orange.com
5 # morgan.richomme@orange.com
6 # All rights reserved. This program and the accompanying materials
7 # are made available under the terms of the Apache License, Version 2.0
8 # which accompanies this distribution, and is available at
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 import re, json, os, urllib2, argparse, logging, yaml
12
13
14
15 """ get the date """
16 cmd = os.popen("date '+%d%m%Y_%H%M'")
17 test_date = cmd.read().rstrip()
18
19
20 """ tests configuration """
21 tests = ['authenticate', 'glance', 'cinder', 'heat', 'keystone', 'neutron', 'nova', 'quotas', 'requests', 'vm', 'tempest', 'all', 'smoke']
22 parser = argparse.ArgumentParser()
23 parser.add_argument("test_name", help="The name of the test you want to perform with rally. "
24                                       "Possible values are : "
25                                       "[ {d[0]} | {d[1]} | {d[2]} | {d[3]} | {d[4]} | {d[5]} | {d[6]} "
26                                       "| {d[7]} | {d[8]} | {d[9]} | {d[10]} | {d[11]} | {d[12]}]. The 'all' value performs all the  possible tests scenarios"
27                                       "except 'tempest'".format(d=tests))
28
29 parser.add_argument("-d", "--debug", help="Debug mode",  action="store_true")
30 parser.add_argument("test_mode", help="Tempest test mode", nargs='?', default="smoke")
31 args = parser.parse_args()
32 test_mode=args.test_mode
33
34 if not args.test_name == "tempest":
35     if not args.test_mode == "smoke":
36         parser.error("test_mode is only used with tempest")
37
38 """ logging configuration """
39 logger = logging.getLogger('run_rally')
40 logger.setLevel(logging.DEBUG)
41
42 ch = logging.StreamHandler()
43 if args.debug:
44     ch.setLevel(logging.DEBUG)
45 else:
46     ch.setLevel(logging.INFO)
47
48 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
49 ch.setFormatter(formatter)
50 logger.addHandler(ch)
51
52 HOME = os.environ['HOME']+"/"
53 with open(args.repo_path+"testcases/config_functest.yaml") as f:
54     functest_yaml = yaml.safe_load(f)
55 f.close()
56
57 HOME = os.environ['HOME']+"/"
58 SCENARIOS_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_scn")
59 RESULTS_DIR = HOME + functest_yaml.get("general").get("directories").get("dir_rally_res") + test_date + "/"
60
61
62
63
64 def get_tempest_id(cmd_raw):
65     """
66     get task id from command rally result
67     :param cmd_raw:
68     :return: task_id as string
69     """
70     taskid_re = re.compile('^Verification UUID: (.*)$')
71     for line in cmd_raw.splitlines(True):
72         line = line.strip()
73     match = taskid_re.match(line)
74
75     if match:
76         return match.group(1)
77     return None
78
79 def get_task_id(cmd_raw):
80     """
81     get task id from command rally result
82     :param cmd_raw:
83     :return: task_id as string
84     """
85     taskid_re = re.compile('^Task +(.*): started$')
86     for line in cmd_raw.splitlines(True):
87         line = line.strip()
88         match = taskid_re.match(line)
89         if match:
90             return match.group(1)
91     return None
92
93
94 def task_succeed(json_raw):
95     """
96     Parse JSON from rally JSON results
97     :param json_raw:
98     :return: Bool
99     """
100     rally_report = json.loads(json_raw)
101     rally_report = rally_report[0]
102     if rally_report is None:
103         return False
104     if rally_report.get('result') is None:
105         return False
106
107     for result in rally_report.get('result'):
108         if len(result.get('error')) > 0:
109             return False
110
111     return True
112
113 def run_tempest():
114     """
115     the function dedicated to Tempest (functional tests for OpenStack)
116     :param test_mode: Tempest mode smoke (default), full, ..
117     :return: void
118     """
119     logger.info('starting {} Tempest ...'.format(test_mode))
120
121     cmd_line = "rally verify start {}".format(test_mode)
122     logger.debug('running command line : {}'.format(cmd_line))
123     cmd = os.popen(cmd_line)
124     task_id = get_tempest_id(cmd.read())
125     logger.debug('task_id : {}'.format(task_id))
126
127     if task_id is None:
128         logger.error("failed to retrieve task_id")
129     exit(-1)
130
131     """ check for result directory and create it otherwise """
132     if not os.path.exists(RESULTS_DIR):
133         logger.debug('does not exists, we create it'.format(RESULTS_DIR))
134         os.makedirs(RESULTS_DIR)
135
136     """ write log report file """
137     report_file_name = '{}opnfv-tempest.log'.format(RESULTS_DIR)
138     cmd_line = "rally verify detailed {} > {} ".format(task_id, report_file_name)
139     logger.debug('running command line : {}'.format(cmd_line))
140     os.popen(cmd_line)
141
142
143 def run_task(test_name):
144     """
145     the "main" function of the script who lunch rally for a task
146     :param test_name: name for the rally test
147     :return: void
148     """
149     logger.info('starting {} test ...'.format(test_name))
150
151     """ check directory for scenarios test files or retrieve from git otherwise"""
152     proceed_test = True
153     test_file_name = '{}opnfv-{}.json'.format(SCENARIOS_DIR, test_name)
154     if not os.path.exists(test_file_name):
155         logger.debug('{} does not exists'.format(test_file_name))
156         proceed_test = retrieve_test_cases_file(test_name, SCENARIOS_DIR)
157
158     """ we do the test only if we have a scenario test file """
159     if proceed_test:
160         logger.debug('Scenario fetched from : {}'.format(test_file_name))
161         cmd_line = "rally task start --abort-on-sla-failure %s" % test_file_name
162         logger.debug('running command line : {}'.format(cmd_line))
163         cmd = os.popen(cmd_line)
164         task_id = get_task_id(cmd.read())
165         logger.debug('task_id : {}'.format(task_id))
166
167         if task_id is None:
168             logger.error("failed to retrieve task_id")
169             exit(-1)
170
171         """ check for result directory and create it otherwise """
172         if not os.path.exists(RESULTS_DIR):
173             logger.debug('does not exists, we create it'.format(RESULTS_DIR))
174             os.makedirs(RESULTS_DIR)
175
176         """ write html report file """
177         report_file_name = '{}opnfv-{}.html'.format(RESULTS_DIR, test_name)
178         cmd_line = "rally task report %s --out %s" % (task_id, report_file_name)
179         logger.debug('running command line : {}'.format(cmd_line))
180         os.popen(cmd_line)
181
182         """ get and save rally operation JSON result """
183         cmd_line = "rally task results %s" % task_id
184         logger.debug('running command line : {}'.format(cmd_line))
185         cmd = os.popen(cmd_line)
186         json_results = cmd.read()
187         with open('{}opnfv-{}.json'.format(RESULTS_DIR, test_name), 'w') as f:
188             logger.debug('saving json file')
189             f.write(json_results)
190             logger.debug('saving json file2')
191
192         """ parse JSON operation result """
193         if task_succeed(json_results):
194             print 'Test OK'
195         else:
196             print 'Test KO'
197     else:
198         logger.error('{} test failed, unable to fetch a scenario test file'.format(test_name))
199
200
201 def retrieve_test_cases_file(test_name, tests_path):
202     """
203     Retrieve from github the sample test files
204     :return: Boolean that indicates the retrieval status
205     """
206
207     """ do not add the "/" at the end """
208     url_base = "https://git.opnfv.org/cgit/functest/plain/testcases/VIM/OpenStack/CI/suites"
209
210     test_file_name = 'opnfv-{}.json'.format(test_name)
211     logger.info('fetching {}/{} ...'.format(url_base, test_file_name))
212
213     try:
214         response = urllib2.urlopen('{}/{}'.format(url_base, test_file_name))
215     except (urllib2.HTTPError, urllib2.URLError):
216         return False
217     file_raw = response.read()
218
219     """ check if the test path exist otherwise we create it """
220     if not os.path.exists(tests_path):
221         os.makedirs(tests_path)
222
223     with open('{}/{}'.format(tests_path, test_file_name), 'w') as f:
224         f.write(file_raw)
225     return True
226
227
228 def main():
229     """ configure script """
230     if not (args.test_name in tests):
231         logger.error('argument not valid')
232         exit(-1)
233
234     if args.test_name == "all":
235         for test_name in tests:
236             if not (test_name == 'all' or test_name == 'tempest' or test_name == 'heat' or test_name == 'smoke' or test_name == 'vm' ):
237                 print(test_name)
238                 run_task(test_name)
239     else:
240         print(args.test_name)
241         if args.test_name == 'tempest':
242             run_tempest()
243         else:
244             run_task(args.test_name)
245
246 if __name__ == '__main__':
247     main()