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