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