OLD | NEW |
1 # Copyright (c) 2013 The Chromium Authors. All rights reserved. | 1 # Copyright (c) 2013 The Chromium Authors. All rights reserved. |
2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
4 | 4 |
5 """Implements test sharding logic.""" | 5 """Implements test sharding logic.""" |
6 | 6 |
7 import logging | 7 import logging |
8 import sys | |
9 import threading | 8 import threading |
10 | 9 |
11 from pylib import android_commands | 10 from pylib import android_commands |
12 from pylib import forwarder | 11 from pylib import forwarder |
| 12 from pylib.utils import reraiser_thread |
13 | 13 |
14 import test_result | 14 import test_result |
15 | 15 |
16 | 16 |
17 class _Worker(threading.Thread): | 17 class _TasksDoneException(Exception): |
18 """Runs tests from the test_queue using the given runner in a separate thread. | 18 pass |
19 | 19 |
20 Places results in the out_results. | 20 |
21 """ | 21 class _Test(object): |
22 def __init__(self, runner, test_queue, out_results, out_retry): | 22 """Holds a test with additional metadata.""" |
23 """Initializes the worker. | 23 def __init__(self, test, tries=0): |
| 24 """Initializes the _Test object. |
24 | 25 |
25 Args: | 26 Args: |
26 runner: A TestRunner object used to run the tests. | 27 test: the test. |
27 test_queue: A list from which to get tests to run. | 28 tries: number of tries so far. |
28 out_results: A list to add TestResults to. | |
29 out_retry: A list to add tests to retry. | |
30 """ | 29 """ |
31 super(_Worker, self).__init__() | 30 self.test = test |
32 self.daemon = True | 31 self.tries = tries |
33 self._exc_info = None | |
34 self._runner = runner | |
35 self._test_queue = test_queue | |
36 self._out_results = out_results | |
37 self._out_retry = out_retry | |
38 | 32 |
39 #override | |
40 def run(self): | |
41 """Run tests from the queue in a seperate thread until it is empty. | |
42 | 33 |
43 Adds TestResults objects to the out_results list and may add tests to the | 34 class _TestQueue(object): |
44 out_retry list. | 35 """A queue that implements specific blocking semantics. |
| 36 |
| 37 Args: |
| 38 items: items to put in the queue. |
| 39 """ |
| 40 def __init__(self, items=[]): |
| 41 self._lock = threading.Lock() |
| 42 self._items = list(items) |
| 43 self._incomplete_count = len(self._items) |
| 44 self._can_pop = threading.Event() |
| 45 self._can_pop.set() |
| 46 |
| 47 def pop(self): |
| 48 """Pop an item from the queue. |
| 49 |
| 50 Waits until an item is avaliable or all items have been handled. |
| 51 |
| 52 Returns: |
| 53 An item or None if all items have been handled. |
45 """ | 54 """ |
| 55 while True: |
| 56 self._can_pop.wait() |
| 57 with self._lock: |
| 58 if self._incomplete_count == 0: |
| 59 return None |
| 60 try: |
| 61 return self._items.pop() |
| 62 except IndexError: |
| 63 self._can_pop.clear() |
| 64 |
| 65 def add(self, item): |
| 66 """Add an item to the queue. |
| 67 |
| 68 Args: |
| 69 item: An item to add. |
| 70 """ |
| 71 with self._lock: |
| 72 self._items.append(item) |
| 73 self._can_pop.set() |
| 74 self._incomplete_count += 1 |
| 75 |
| 76 def task_done(self): |
| 77 """Indicate that a queue item has been fully handled.""" |
| 78 with self._lock: |
| 79 self._incomplete_count -= 1 |
| 80 if self._incomplete_count == 0: |
| 81 self._can_pop.set() |
| 82 assert self._incomplete_count >= 0 |
| 83 |
| 84 def __iter__(self): |
| 85 """Iterate through items in the queue until all items have been handled.""" |
| 86 while True: |
| 87 r = self.pop() |
| 88 if r is None: |
| 89 break |
| 90 yield r |
| 91 |
| 92 |
| 93 def _RunTestsFromQueue(runner, test_queue, out_results): |
| 94 """Runs tests from the test_queue until empty using the given runner. |
| 95 |
| 96 Adds TestResults objects to the out_results list and may add tests to the |
| 97 out_retry list. |
| 98 |
| 99 Args: |
| 100 runner: A TestRunner object used to run the tests. |
| 101 test_queue: A _TestQueue from which to get _Test objects to run. |
| 102 out_results: A list to add TestResults to. |
| 103 """ |
| 104 for test in test_queue: |
| 105 if not android_commands.IsDeviceAttached(runner.device): |
| 106 raise android_commands.errors.DeviceUnresponsiveError( |
| 107 'Device %s is unresponsive.' % runner.device) |
46 try: | 108 try: |
47 while True: | 109 result, retry = runner.RunTest(test.test) |
48 test = self._test_queue.pop() | 110 # TODO(frankf): Don't break TestResults encapsulation. |
49 result, retry = self._runner.Run(test) | 111 out_results.append(test_result.TestResults.FromRun(ok=result.ok)) |
50 self._out_results.append(result) | 112 if retry: |
51 if retry: | 113 if test.tries == 2: |
52 self._out_retry.append(retry) | 114 # Out of retries, store results. |
53 except IndexError: | 115 result.ok = [] |
54 pass | 116 out_results.append(result) |
| 117 else: |
| 118 # Retry, don't store results. |
| 119 logging.warning('****Retrying test, retry #%s.' % (test.tries + 1)) |
| 120 test_queue.add(_Test(test=retry, tries=test.tries + 1)) |
| 121 except android_commands.errors.DeviceUnresponsiveError: |
| 122 test_queue.add(test) |
55 except: | 123 except: |
56 self._exc_info = sys.exc_info() | 124 test_queue.add(test) |
57 raise | 125 raise |
| 126 finally: |
| 127 test_queue.task_done() |
58 | 128 |
59 def ReraiseIfException(self): | 129 |
60 """Reraise exception if an exception was raised in the thread.""" | 130 def _SetUp(runner_factory, device, out_runners): |
61 if self._exc_info: | 131 """Creates a test runner for each device and calls SetUp() in parallel. |
62 raise self._exc_info[0], self._exc_info[1], self._exc_info[2] | 132 |
| 133 Note: if a device is unresponsive the corresponding TestRunner will not be |
| 134 added to out_runners. |
| 135 |
| 136 Args: |
| 137 runner_factory: callable that takes a device and returns a TestRunner. |
| 138 device: the device serial number to set up. |
| 139 out_runners: list to add the successfully set up TestRunner object. |
| 140 """ |
| 141 try: |
| 142 logging.warning('*****Creating shard for %s.', device) |
| 143 runner = runner_factory(device) |
| 144 runner.SetUp() |
| 145 out_runners.append(runner) |
| 146 except android_commands.errors.DeviceUnresponsiveError as e: |
| 147 logging.warning('****Failed to create shard for %s: [%s]', (device, e)) |
63 | 148 |
64 | 149 |
65 def _RunAllTests(runners, tests): | 150 def _RunAllTests(runners, tests): |
66 """Run all tests using the given TestRunners. | 151 """Run all tests using the given TestRunners. |
67 | 152 |
68 Args: | 153 Args: |
69 runners: a list of TestRunner objects. | 154 runners: a list of TestRunner objects. |
70 tests: a list of Tests to run using the given TestRunners. | 155 tests: a list of Tests to run using the given TestRunners. |
71 | 156 |
72 Returns: | 157 Returns: |
73 Tuple: (list of TestResults, list of tests to retry) | 158 A TestResults object. |
74 """ | 159 """ |
75 tests_queue = list(tests) | 160 logging.warning('****Running %s tests with %s test runners.' % |
76 workers = [] | 161 (len(tests), len(runners))) |
| 162 tests_queue = _TestQueue([_Test(t) for t in tests]) |
77 results = [] | 163 results = [] |
78 retry = [] | 164 workers = reraiser_thread.ReraiserThreadGroup([reraiser_thread.ReraiserThread( |
79 for r in runners: | 165 _RunTestsFromQueue, [r, tests_queue, results]) for r in runners]) |
80 worker = _Worker(r, tests_queue, results, retry) | 166 workers.StartAll() |
81 worker.start() | 167 workers.JoinAll() |
82 workers.append(worker) | 168 return test_result.TestResults.FromTestResults(results) |
83 while workers: | |
84 for w in workers[:]: | |
85 # Allow the main thread to periodically check for keyboard interrupts. | |
86 w.join(0.1) | |
87 if not w.isAlive(): | |
88 w.ReraiseIfException() | |
89 workers.remove(w) | |
90 return (results, retry) | |
91 | 169 |
92 | 170 |
93 def _CreateRunners(runner_factory, devices): | 171 def _CreateRunners(runner_factory, devices): |
94 """Creates a test runner for each device. | 172 """Creates a test runner for each device and calls SetUp() in parallel. |
95 | 173 |
96 Note: if a device is unresponsive the corresponding TestRunner will not be | 174 Note: if a device is unresponsive the corresponding TestRunner will not be |
97 included in the returned list. | 175 included in the returned list. |
98 | 176 |
99 Args: | 177 Args: |
100 runner_factory: callable that takes a device and returns a TestRunner. | 178 runner_factory: callable that takes a device and returns a TestRunner. |
101 devices: list of device serial numbers as strings. | 179 devices: list of device serial numbers as strings. |
102 | 180 |
103 Returns: | 181 Returns: |
104 A list of TestRunner objects. | 182 A list of TestRunner objects. |
105 """ | 183 """ |
| 184 logging.warning('****Creating %s test runners.' % len(devices)) |
106 test_runners = [] | 185 test_runners = [] |
107 for index, device in enumerate(devices): | 186 threads = reraiser_thread.ReraiserThreadGroup( |
108 logging.warning('*' * 80) | 187 [reraiser_thread.ReraiserThread(_SetUp, [runner_factory, d, test_runners]) |
109 logging.warning('Creating shard %d for %s', index, device) | 188 for d in devices]) |
110 logging.warning('*' * 80) | 189 threads.StartAll() |
111 try: | 190 threads.JoinAll() |
112 test_runners.append(runner_factory(device)) | |
113 except android_commands.errors.DeviceUnresponsiveError as e: | |
114 logging.warning('****Failed to create a shard: [%s]', e) | |
115 return test_runners | 191 return test_runners |
116 | 192 |
117 | 193 |
118 def ShardAndRunTests(runner_factory, devices, tests, build_type='Debug', | 194 def _TearDownRunners(runners): |
119 tries=3): | 195 """Calls TearDown() for each test runner in parallel. |
| 196 Args: |
| 197 runners: a list of TestRunner objects. |
| 198 """ |
| 199 threads = reraiser_thread.ReraiserThreadGroup( |
| 200 [reraiser_thread.ReraiserThread(runner.TearDown) |
| 201 for runner in runners]) |
| 202 threads.StartAll() |
| 203 threads.JoinAll() |
| 204 |
| 205 |
| 206 def ShardAndRunTests(runner_factory, devices, tests, build_type='Debug'): |
120 """Run all tests on attached devices, retrying tests that don't pass. | 207 """Run all tests on attached devices, retrying tests that don't pass. |
121 | 208 |
122 Args: | 209 Args: |
123 runner_factory: callable that takes a device and returns a TestRunner. | 210 runner_factory: callable that takes a device and returns a TestRunner. |
124 devices: list of attached device serial numbers as strings. | 211 devices: list of attached device serial numbers as strings. |
125 tests: list of tests to run. | 212 tests: list of tests to run. |
126 build_type: either 'Debug' or 'Release'. | 213 build_type: either 'Debug' or 'Release'. |
127 tries: number of tries before accepting failure. | 214 tries: number of tries before accepting failure. |
128 | 215 |
129 Returns: | 216 Returns: |
130 A test_result.TestResults object. | 217 A test_result.TestResults object. |
131 """ | 218 """ |
132 final_results = test_result.TestResults() | |
133 results = test_result.TestResults() | |
134 forwarder.Forwarder.KillHost(build_type) | 219 forwarder.Forwarder.KillHost(build_type) |
135 try_count = 0 | 220 runners = _CreateRunners(runner_factory, devices) |
136 while tests: | 221 try: |
137 devices = set(devices).intersection(android_commands.GetAttachedDevices()) | 222 return _RunAllTests(runners, tests) |
138 if not devices: | 223 finally: |
139 # There are no visible devices attached, this is unrecoverable. | |
140 msg = 'No devices attached and visible to run tests!' | |
141 logging.critical(msg) | |
142 raise Exception(msg) | |
143 if try_count >= tries: | |
144 # We've retried too many times, return the TestResults up to this point. | |
145 results.ok = final_results.ok | |
146 final_results = results | |
147 break | |
148 try_count += 1 | |
149 runners = _CreateRunners(runner_factory, devices) | |
150 try: | 224 try: |
151 results_list, tests = _RunAllTests(runners, tests) | 225 _TearDownRunners(runners) |
152 results = test_result.TestResults.FromTestResults(results_list) | |
153 final_results.ok += results.ok | |
154 except android_commands.errors.DeviceUnresponsiveError as e: | 226 except android_commands.errors.DeviceUnresponsiveError as e: |
155 logging.warning('****Failed to run test: [%s]', e) | 227 logging.warning('****Device unresponsive during TearDown: [%s]', e) |
156 forwarder.Forwarder.KillHost(build_type) | 228 finally: |
157 return final_results | 229 forwarder.Forwarder.KillHost(build_type) |
OLD | NEW |