c17d7ada823863fbef383f4e451f8a52a8570009
[dpdk.git] / app / test / autotest_runner.py
1 #!/usr/bin/python
2
3 #   BSD LICENSE
4
5 #   Copyright(c) 2010-2012 Intel Corporation. All rights reserved.
6 #   All rights reserved.
7
8 #   Redistribution and use in source and binary forms, with or without 
9 #   modification, are permitted provided that the following conditions 
10 #   are met:
11
12 #     * Redistributions of source code must retain the above copyright 
13 #       notice, this list of conditions and the following disclaimer.
14 #     * Redistributions in binary form must reproduce the above copyright 
15 #       notice, this list of conditions and the following disclaimer in 
16 #       the documentation and/or other materials provided with the 
17 #       distribution.
18 #     * Neither the name of Intel Corporation nor the names of its 
19 #       contributors may be used to endorse or promote products derived 
20 #       from this software without specific prior written permission.
21
22 #   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
23 #   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
24 #   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
25 #   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
26 #   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
27 #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
28 #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
29 #   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
30 #   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
31 #   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
32 #   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
34
35 # The main logic behind running autotests in parallel
36
37 import multiprocessing, sys, pexpect, time, os, StringIO, csv
38
39 # wait for prompt
40 def wait_prompt(child):
41         try:
42                 child.sendline()
43                 result = child.expect(["RTE>>", pexpect.TIMEOUT, pexpect.EOF],
44                         timeout = 120)
45         except:
46                 return False
47         if result == 0:
48                 return True
49         else:
50                 return False
51
52 # run a test group
53 # each result tuple in results list consists of:
54 #   result value (0 or -1)
55 #   result string
56 #   test name
57 #   total test run time (double)
58 #   raw test log
59 #   test report (if not available, should be None)
60 #
61 # this function needs to be outside AutotestRunner class
62 # because otherwise Pool won't work (or rather it will require
63 # quite a bit of effort to make it work).
64 def run_test_group(cmdline, test_group):
65         results = []
66         child = None
67         start_time = time.time()
68         startuplog = None
69
70         # run test app
71         try:
72                 # prepare logging of init
73                 startuplog = StringIO.StringIO()
74
75                 print >>startuplog, "\n%s %s\n" % ("="*20, test_group["Prefix"])
76
77                 child = pexpect.spawn(cmdline, logfile=startuplog)
78
79                 # wait for target to boot
80                 if not wait_prompt(child):
81                         child.close()
82
83                         results.append((-1, "Fail [No prompt]", "Start %s" % test_group["Prefix"],
84                                 time.time() - start_time, startuplog.getvalue(), None))
85
86                         # mark all tests as failed
87                         for test in test_group["Tests"]:
88                                 results.append((-1, "Fail [No prompt]", test["Name"],
89                                 time.time() - start_time, "", None))
90                         # exit test
91                         return results
92
93         except:
94                 results.append((-1, "Fail [Can't run]", "Start %s" % test_group["Prefix"],
95                                 time.time() - start_time, startuplog.getvalue(), None))
96
97                 # mark all tests as failed
98                 for t in test_group["Tests"]:
99                         results.append((-1, "Fail [Can't run]", t["Name"],
100                                 time.time() - start_time, "", None))
101                 # exit test
102                 return results
103
104         # startup was successful
105         results.append((0, "Success", "Start %s" % test_group["Prefix"],
106                 time.time() - start_time, startuplog.getvalue(), None))
107
108         # run all tests in test group
109         for test in test_group["Tests"]:
110
111                 # create log buffer for each test
112                 # in multiprocessing environment, the logging would be
113                 # interleaved and will create a mess, hence the buffering
114                 logfile = StringIO.StringIO()
115                 child.logfile = logfile
116
117                 result = ()
118
119                 # make a note when the test started
120                 start_time = time.time()
121
122                 try:
123                         # print test name to log buffer
124                         print >>logfile, "\n%s %s\n" % ("-"*20, test["Name"])
125
126                         # run test function associated with the test
127                         result = test["Func"](child, test["Command"])
128
129                         # make a note when the test was finished
130                         end_time = time.time()
131
132                         # append test data to the result tuple
133                         result += (test["Name"], end_time - start_time,
134                                 logfile.getvalue())
135
136                         # call report function, if any defined, and supply it with
137                         # target and complete log for test run
138                         if test["Report"]:
139                                 report = test["Report"](self.target, log)
140
141                                 # append report to results tuple
142                                 result += (report,)
143                         else:
144                                 # report is None
145                                 result += (None,)
146                 except:
147                         # make a note when the test crashed
148                         end_time = time.time()
149
150                         # mark test as failed
151                         result = (-1, "Fail [Crash]", test["Name"],
152                                 end_time - start_time, logfile.getvalue(), None)
153                 finally:
154                         # append the results to the results list
155                         results.append(result)
156
157         # regardless of whether test has crashed, try quitting it
158         try:    
159                 child.sendline("quit")
160                 child.close()
161         # if the test crashed, just do nothing instead
162         except:
163                 # nop
164                 pass
165
166         # return test results
167         return results
168
169
170
171
172
173 # class representing an instance of autotests run
174 class AutotestRunner:
175         cmdline = ""
176         parallel_test_groups = []
177         non_parallel_test_groups = []
178         logfile = None
179         csvwriter = None
180         target = ""
181         start = None
182         n_tests = 0
183         fails = 0
184         log_buffers = []
185         blacklist = []
186         whitelist = []
187
188
189         def __init__(self, cmdline, target, blacklist, whitelist):
190                 self.cmdline = cmdline
191                 self.target = target
192                 self.blacklist = blacklist
193                 self.whitelist = whitelist
194
195                 # log file filename
196                 logfile = "%s.log" % target
197                 csvfile = "%s.csv" % target
198
199                 self.logfile = open(logfile, "w")
200                 csvfile = open(csvfile, "w")
201                 self.csvwriter = csv.writer(csvfile)
202                 
203                 # prepare results table
204                 self.csvwriter.writerow(["test_name","test_result","result_str"])
205
206
207
208         # set up cmdline string
209         def __get_cmdline(self, test):
210                 cmdline = self.cmdline
211
212                 # perform additional linuxapp adjustments
213                 if not "baremetal" in self.target:
214
215                         # append memory limitations for each test
216                         # otherwise tests won't run in parallel
217                         if not "i686" in self.target:
218                                 cmdline += " --socket-mem=%s"% test["Memory"]
219                         else:
220                                 # affinitize startup so that tests don't fail on i686
221                                 cmdline = "taskset 1 " + cmdline
222                                 cmdline += " -m " + str(sum(map(int,test["Memory"].split(","))))
223
224                         # set group prefix for autotest group
225                         # otherwise they won't run in parallel
226                         cmdline += " --file-prefix=%s"% test["Prefix"]
227
228                         return cmdline
229                 return cmdline
230
231
232
233         def add_parallel_test_group(self,test_group):
234                 self.parallel_test_groups.append(test_group)
235
236         def add_non_parallel_test_group(self,test_group):
237                 self.non_parallel_test_groups.append(test_group)
238                 
239         
240         def __process_results(self, results):
241                 # this iterates over individual test results
242                 for i, result in enumerate(results):
243                 
244                         # increase total number of tests that were run
245                         # do not include "start" test
246                         if i > 0:
247                                 self.n_tests += 1
248
249                         # unpack result tuple
250                         test_result, result_str, test_name, \
251                                 test_time, log, report = result
252
253                         # get total run time
254                         cur_time = time.time()
255                         total_time = int(cur_time - self.start)
256
257                         # print results, test run time and total time since start
258                         print ("%s:" % test_name).ljust(30),
259                         print result_str.ljust(29),
260                         print "[%02dm %02ds]" % (test_time / 60, test_time % 60),
261
262                         # don't print out total time every line, it's the same anyway
263                         if i == len(results) - 1:
264                                 print "[%02dm %02ds]" % (total_time / 60, total_time % 60)
265                         else:
266                                 print ""
267
268                         # if test failed and it wasn't a "start" test
269                         if test_result < 0 and not i == 0:
270                                 self.fails += 1
271                 
272                         # collect logs
273                         self.log_buffers.append(log)
274                 
275                         # create report if it exists
276                         if report:
277                                 try:
278                                         f = open("%s_%s_report.rst" % (self.target,test_name), "w")
279                                 except IOError:
280                                         print "Report for %s could not be created!" % test_name
281                                 else:
282                                         with f:
283                                                 f.write(report)
284                                                 
285                         # write test result to CSV file
286                         if i != 0:
287                                 self.csvwriter.writerow([test_name, test_result, result_str])
288
289
290
291
292         # this function iterates over test groups and removes each
293         # test that is not in whitelist/blacklist
294         def __filter_groups(self, test_groups):
295                 groups_to_remove = []
296
297                 # filter out tests from parallel test groups
298                 for i, test_group in enumerate(test_groups):
299
300                         # iterate over a copy so that we could safely delete individual tests
301                         for test in test_group["Tests"][:]:
302                                 test_id = test["Command"]
303
304                                 # dump tests are specified in full e.g. "Dump_mempool"
305                                 if "_autotest" in test_id:
306                                         test_id = test_id[:-len("_autotest")]
307                                 
308                                 # filter out blacklisted/whitelisted tests
309                                 if self.blacklist and test_id in self.blacklist:
310                                         test_group["Tests"].remove(test)
311                                         continue
312                                 if self.whitelist and test_id not in self.whitelist:
313                                         test_group["Tests"].remove(test)
314                                         continue
315
316                         # modify or remove original group
317                         if len(test_group["Tests"]) > 0:
318                                 test_groups[i] = test_group
319                         else:
320                                 # remember which groups should be deleted
321                                 # put the numbers backwards so that we start
322                                 # deleting from the end, not from the beginning
323                                 groups_to_remove.insert(0, i)
324                 
325                 # remove test groups that need to be removed
326                 for i in groups_to_remove:
327                         del test_groups[i]
328                 
329                 return test_groups
330                 
331
332
333         # iterate over test groups and run tests associated with them
334         def run_all_tests(self):
335                 # filter groups
336                 self.parallel_test_groups = \
337                         self.__filter_groups(self.parallel_test_groups)
338                 self.non_parallel_test_groups = \
339                         self.__filter_groups(self.non_parallel_test_groups)
340                 
341                 # create a pool of worker threads
342                 if not "baremetal" in self.target:
343                         pool = multiprocessing.Pool(processes=4)
344                 else:
345                         # we can't be sure running baremetal tests in parallel
346                         # will work, so let's stay on the safe side
347                         pool = multiprocessing.Pool(processes=1)
348                         
349                 results = []
350         
351                 # whatever happens, try to save as much logs as possible
352                 try:
353
354                         # create table header
355                         print ""
356                         print "Test name".ljust(30),
357                         print "Test result".ljust(29),
358                         print "Test".center(9),
359                         print "Total".center(9)
360                         print "=" * 80
361
362                         # make a note of tests start time
363                         self.start = time.time()
364
365                         # assign worker threads to run test groups
366                         for test_group in self.parallel_test_groups:
367                                 result = pool.apply_async(run_test_group,
368                                         [self.__get_cmdline(test_group), test_group])
369                                 results.append(result)
370
371                         # iterate while we have group execution results to get
372                         while len(results) > 0:
373
374                                 # iterate over a copy to be able to safely delete results
375                                 # this iterates over a list of group results
376                                 for group_result in results[:]:
377
378                                         # if the thread hasn't finished yet, continue
379                                         if not group_result.ready():
380                                                 continue
381
382                                         res = group_result.get()
383                                         
384                                         self.__process_results(res)
385
386                                         # remove result from results list once we're done with it
387                                         results.remove(group_result)
388
389                         # run non_parallel tests. they are run one by one, synchronously
390                         for test_group in self.non_parallel_test_groups:
391                                 group_result = run_test_group(self.__get_cmdline(test_group), test_group)
392                                         
393                                 self.__process_results(group_result)
394                 
395                         # get total run time
396                         cur_time = time.time()          
397                         total_time = int(cur_time - self.start)
398
399                         # print out summary
400                         print "=" * 80
401                         print "Total run time: %02dm %02ds" % (total_time / 60, total_time % 60)
402                         if self.fails != 0:
403                                 print "Number of failed tests: %s" % str(self.fails)
404
405                         # write summary to logfile
406                         self.logfile.write("Summary\n")
407                         self.logfile.write("Target: ".ljust(15) + "%s\n" % self.target)
408                         self.logfile.write("Tests: ".ljust(15) + "%i\n" % self.n_tests)
409                         self.logfile.write("Failed tests: ".ljust(15) + "%i\n" % self.fails)
410                 except:
411                         print "Exception occured"
412                         print sys.exc_info()
413
414                 # drop logs from all executions to a logfile
415                 for buf in self.log_buffers:
416                         self.logfile.write(buf.replace("\r",""))
417                 
418                 log_buffers = []
419