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