- add sources.
[platform/framework/web/crosswalk.git] / src / build / android / buildbot / bb_device_steps.py
1 #!/usr/bin/env python
2 # Copyright (c) 2013 The Chromium Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 import collections
7 import glob
8 import hashlib
9 import json
10 import multiprocessing
11 import os
12 import random
13 import re
14 import shutil
15 import sys
16
17 import bb_utils
18 import bb_annotations
19
20 sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
21 import provision_devices
22 from pylib import android_commands
23 from pylib import constants
24 from pylib.gtest import gtest_config
25
26 CHROME_SRC_DIR = bb_utils.CHROME_SRC
27 DIR_BUILD_ROOT = os.path.dirname(CHROME_SRC_DIR)
28 CHROME_OUT_DIR = bb_utils.CHROME_OUT_DIR
29 sys.path.append(os.path.join(
30     CHROME_SRC_DIR, 'third_party', 'android_testrunner'))
31 import errors
32
33
34 SLAVE_SCRIPTS_DIR = os.path.join(bb_utils.BB_BUILD_DIR, 'scripts', 'slave')
35 LOGCAT_DIR = os.path.join(bb_utils.CHROME_OUT_DIR, 'logcat')
36 GS_URL = 'https://storage.googleapis.com'
37
38 # Describes an instrumation test suite:
39 #   test: Name of test we're running.
40 #   apk: apk to be installed.
41 #   apk_package: package for the apk to be installed.
42 #   test_apk: apk to run tests on.
43 #   test_data: data folder in format destination:source.
44 #   host_driven_root: The host-driven test root directory.
45 #   annotation: Annotation of the tests to include.
46 #   exclude_annotation: The annotation of the tests to exclude.
47 I_TEST = collections.namedtuple('InstrumentationTest', [
48     'name', 'apk', 'apk_package', 'test_apk', 'test_data', 'host_driven_root',
49     'annotation', 'exclude_annotation', 'extra_flags'])
50
51
52 def SrcPath(*path):
53   return os.path.join(CHROME_SRC_DIR, *path)
54
55
56 def I(name, apk, apk_package, test_apk, test_data, host_driven_root=None,
57       annotation=None, exclude_annotation=None, extra_flags=None):
58   return I_TEST(name, apk, apk_package, test_apk, test_data, host_driven_root,
59                 annotation, exclude_annotation, extra_flags)
60
61 INSTRUMENTATION_TESTS = dict((suite.name, suite) for suite in [
62     I('ContentShell',
63       'ContentShell.apk',
64       'org.chromium.content_shell_apk',
65       'ContentShellTest',
66       'content:content/test/data/android/device_files'),
67     I('ChromiumTestShell',
68       'ChromiumTestShell.apk',
69       'org.chromium.chrome.testshell',
70       'ChromiumTestShellTest',
71       'chrome:chrome/test/data/android/device_files',
72       constants.CHROMIUM_TEST_SHELL_HOST_DRIVEN_DIR),
73     I('AndroidWebView',
74       'AndroidWebView.apk',
75       'org.chromium.android_webview.shell',
76       'AndroidWebViewTest',
77       'webview:android_webview/test/data/device_files'),
78     ])
79
80 VALID_TESTS = set(['chromedriver', 'gpu', 'ui', 'unit', 'webkit',
81                    'webkit_layout', 'webrtc_chromium', 'webrtc_native'])
82
83 RunCmd = bb_utils.RunCmd
84
85
86 def _GetRevision(options):
87   """Get the SVN revision number.
88
89   Args:
90     options: options object.
91
92   Returns:
93     The revision number.
94   """
95   revision = options.build_properties.get('got_revision')
96   if not revision:
97     revision = options.build_properties.get('revision', 'testing')
98   return revision
99
100
101 # multiprocessing map_async requires a top-level function for pickle library.
102 def RebootDeviceSafe(device):
103   """Reboot a device, wait for it to start, and squelch timeout exceptions."""
104   try:
105     android_commands.AndroidCommands(device).Reboot(True)
106   except errors.DeviceUnresponsiveError as e:
107     return e
108
109
110 def RebootDevices():
111   """Reboot all attached and online devices."""
112   # Early return here to avoid presubmit dependence on adb,
113   # which might not exist in this checkout.
114   if bb_utils.TESTING:
115     return
116   devices = android_commands.GetAttachedDevices(emulator=False)
117   print 'Rebooting: %s' % devices
118   if devices:
119     pool = multiprocessing.Pool(len(devices))
120     results = pool.map_async(RebootDeviceSafe, devices).get(99999)
121
122     for device, result in zip(devices, results):
123       if result:
124         print '%s failed to startup.' % device
125
126     if any(results):
127       bb_annotations.PrintWarning()
128     else:
129       print 'Reboots complete.'
130
131
132 def RunTestSuites(options, suites):
133   """Manages an invocation of test_runner.py for gtests.
134
135   Args:
136     options: options object.
137     suites: List of suite names to run.
138   """
139   args = ['--verbose']
140   if options.target == 'Release':
141     args.append('--release')
142   if options.asan:
143     args.append('--tool=asan')
144   for suite in suites:
145     bb_annotations.PrintNamedStep(suite)
146     cmd = ['build/android/test_runner.py', 'gtest', '-s', suite] + args
147     if suite == 'content_browsertests':
148       cmd.append('--num_retries=1')
149     RunCmd(cmd)
150
151
152 def RunChromeDriverTests(options):
153   """Run all the steps for running chromedriver tests."""
154   bb_annotations.PrintNamedStep('chromedriver_annotation')
155   RunCmd(['chrome/test/chromedriver/run_buildbot_steps.py',
156           '--android-packages=%s,%s,%s' %
157           (constants.PACKAGE_INFO['chromium_test_shell'].package,
158            constants.PACKAGE_INFO['chrome_stable'].package,
159            constants.PACKAGE_INFO['chrome_beta'].package),
160           '--revision=%s' % _GetRevision(options),
161           '--update-log'])
162
163
164 def InstallApk(options, test, print_step=False):
165   """Install an apk to all phones.
166
167   Args:
168     options: options object
169     test: An I_TEST namedtuple
170     print_step: Print a buildbot step
171   """
172   if print_step:
173     bb_annotations.PrintNamedStep('install_%s' % test.name.lower())
174
175   args = ['--apk', test.apk, '--apk_package', test.apk_package]
176   if options.target == 'Release':
177     args.append('--release')
178
179   RunCmd(['build/android/adb_install_apk.py'] + args, halt_on_failure=True)
180
181
182 def RunInstrumentationSuite(options, test, flunk_on_failure=True,
183                             python_only=False, official_build=False):
184   """Manages an invocation of test_runner.py for instrumentation tests.
185
186   Args:
187     options: options object
188     test: An I_TEST namedtuple
189     flunk_on_failure: Flunk the step if tests fail.
190     Python: Run only host driven Python tests.
191     official_build: Run official-build tests.
192   """
193   bb_annotations.PrintNamedStep('%s_instrumentation_tests' % test.name.lower())
194
195   InstallApk(options, test)
196   args = ['--test-apk', test.test_apk, '--test_data', test.test_data,
197           '--verbose']
198   if options.target == 'Release':
199     args.append('--release')
200   if options.asan:
201     args.append('--tool=asan')
202   if options.flakiness_server:
203     args.append('--flakiness-dashboard-server=%s' %
204                 options.flakiness_server)
205   if options.coverage_bucket:
206     args.append('--coverage-dir=%s' % options.coverage_dir)
207   if test.host_driven_root:
208     args.append('--host-driven-root=%s' % test.host_driven_root)
209   if test.annotation:
210     args.extend(['-A', test.annotation])
211   if test.exclude_annotation:
212     args.extend(['-E', test.exclude_annotation])
213   if test.extra_flags:
214     args.extend(test.extra_flags)
215   if python_only:
216     args.append('-p')
217   if official_build:
218     # The option needs to be assigned 'True' as it does not have an action
219     # associated with it.
220     args.append('--official-build')
221
222   RunCmd(['build/android/test_runner.py', 'instrumentation'] + args,
223          flunk_on_failure=flunk_on_failure)
224
225
226 def RunWebkitLint(target):
227   """Lint WebKit's TestExpectation files."""
228   bb_annotations.PrintNamedStep('webkit_lint')
229   RunCmd([SrcPath('webkit/tools/layout_tests/run_webkit_tests.py'),
230           '--lint-test-files',
231           '--chromium',
232           '--target', target])
233
234
235 def RunWebkitLayoutTests(options):
236   """Run layout tests on an actual device."""
237   bb_annotations.PrintNamedStep('webkit_tests')
238   cmd_args = [
239       '--no-show-results',
240       '--no-new-test-results',
241       '--full-results-html',
242       '--clobber-old-results',
243       '--exit-after-n-failures', '5000',
244       '--exit-after-n-crashes-or-timeouts', '100',
245       '--debug-rwt-logging',
246       '--results-directory', '../layout-test-results',
247       '--target', options.target,
248       '--builder-name', options.build_properties.get('buildername', ''),
249       '--build-number', str(options.build_properties.get('buildnumber', '')),
250       '--master-name', 'ChromiumWebkit',  # TODO: Get this from the cfg.
251       '--build-name', options.build_properties.get('buildername', ''),
252       '--platform=android']
253
254   for flag in 'test_results_server', 'driver_name', 'additional_drt_flag':
255     if flag in options.factory_properties:
256       cmd_args.extend(['--%s' % flag.replace('_', '-'),
257                        options.factory_properties.get(flag)])
258
259   for f in options.factory_properties.get('additional_expectations', []):
260     cmd_args.extend(
261         ['--additional-expectations=%s' % os.path.join(CHROME_SRC_DIR, *f)])
262
263   # TODO(dpranke): Remove this block after
264   # https://codereview.chromium.org/12927002/ lands.
265   for f in options.factory_properties.get('additional_expectations_files', []):
266     cmd_args.extend(
267         ['--additional-expectations=%s' % os.path.join(CHROME_SRC_DIR, *f)])
268
269   exit_code = RunCmd([SrcPath('webkit/tools/layout_tests/run_webkit_tests.py')]
270                      + cmd_args)
271   if exit_code == 255: # test_run_results.UNEXPECTED_ERROR_EXIT_STATUS
272     bb_annotations.PrintMsg('?? (crashed or hung)')
273   elif exit_code == 254: # test_run_results.NO_DEVICES_EXIT_STATUS
274     bb_annotations.PrintMsg('?? (no devices found)')
275   elif exit_code == 253: # test_run_results.NO_TESTS_EXIT_STATUS
276     bb_annotations.PrintMsg('?? (no tests found)')
277   else:
278     full_results_path = os.path.join('..', 'layout-test-results',
279                                      'full_results.json')
280     if os.path.exists(full_results_path):
281       full_results = json.load(open(full_results_path))
282       unexpected_passes, unexpected_failures, unexpected_flakes = (
283           _ParseLayoutTestResults(full_results))
284       if unexpected_failures:
285         _PrintDashboardLink('failed', unexpected_failures,
286                             max_tests=25)
287       elif unexpected_passes:
288         _PrintDashboardLink('unexpected passes', unexpected_passes,
289                             max_tests=10)
290       if unexpected_flakes:
291         _PrintDashboardLink('unexpected flakes', unexpected_flakes,
292                             max_tests=10)
293
294       if exit_code == 0 and (unexpected_passes or unexpected_flakes):
295         # If exit_code != 0, RunCmd() will have already printed an error.
296         bb_annotations.PrintWarning()
297     else:
298       bb_annotations.PrintError()
299       bb_annotations.PrintMsg('?? (results missing)')
300
301   if options.factory_properties.get('archive_webkit_results', False):
302     bb_annotations.PrintNamedStep('archive_webkit_results')
303     base = 'https://storage.googleapis.com/chromium-layout-test-archives'
304     builder_name = options.build_properties.get('buildername', '')
305     build_number = str(options.build_properties.get('buildnumber', ''))
306     results_link = '%s/%s/%s/layout-test-results/results.html' % (
307         base, EscapeBuilderName(builder_name), build_number)
308     bb_annotations.PrintLink('results', results_link)
309     bb_annotations.PrintLink('(zip)', '%s/%s/%s/layout-test-results.zip' % (
310         base, EscapeBuilderName(builder_name), build_number))
311     gs_bucket = 'gs://chromium-layout-test-archives'
312     RunCmd([os.path.join(SLAVE_SCRIPTS_DIR, 'chromium',
313                          'archive_layout_test_results.py'),
314             '--results-dir', '../../layout-test-results',
315             '--build-dir', CHROME_OUT_DIR,
316             '--build-number', build_number,
317             '--builder-name', builder_name,
318             '--gs-bucket', gs_bucket],
319             cwd=DIR_BUILD_ROOT)
320
321
322 def _ParseLayoutTestResults(results):
323   """Extract the failures from the test run."""
324   # Cloned from third_party/WebKit/Tools/Scripts/print-json-test-results
325   tests = _ConvertTrieToFlatPaths(results['tests'])
326   failures = {}
327   flakes = {}
328   passes = {}
329   for (test, result) in tests.iteritems():
330     if result.get('is_unexpected'):
331       actual_results = result['actual'].split()
332       expected_results = result['expected'].split()
333       if len(actual_results) > 1:
334         # We report the first failure type back, even if the second
335         # was more severe.
336         if actual_results[1] in expected_results:
337           flakes[test] = actual_results[0]
338         else:
339           failures[test] = actual_results[0]
340       elif actual_results[0] == 'PASS':
341         passes[test] = result
342       else:
343         failures[test] = actual_results[0]
344
345   return (passes, failures, flakes)
346
347
348 def _ConvertTrieToFlatPaths(trie, prefix=None):
349   """Flatten the trie of failures into a list."""
350   # Cloned from third_party/WebKit/Tools/Scripts/print-json-test-results
351   result = {}
352   for name, data in trie.iteritems():
353     if prefix:
354       name = prefix + '/' + name
355
356     if len(data) and 'actual' not in data and 'expected' not in data:
357       result.update(_ConvertTrieToFlatPaths(data, name))
358     else:
359       result[name] = data
360
361   return result
362
363
364 def _PrintDashboardLink(link_text, tests, max_tests):
365   """Add a link to the flakiness dashboard in the step annotations."""
366   if len(tests) > max_tests:
367     test_list_text = ' '.join(tests[:max_tests]) + ' and more'
368   else:
369     test_list_text = ' '.join(tests)
370
371   dashboard_base = ('http://test-results.appspot.com'
372                     '/dashboards/flakiness_dashboard.html#'
373                     'master=ChromiumWebkit&tests=')
374
375   bb_annotations.PrintLink('%d %s: %s' %
376                            (len(tests), link_text, test_list_text),
377                            dashboard_base + ','.join(tests))
378
379
380 def EscapeBuilderName(builder_name):
381   return re.sub('[ ()]', '_', builder_name)
382
383
384 def SpawnLogcatMonitor():
385   shutil.rmtree(LOGCAT_DIR, ignore_errors=True)
386   bb_utils.SpawnCmd([
387       os.path.join(CHROME_SRC_DIR, 'build', 'android', 'adb_logcat_monitor.py'),
388       LOGCAT_DIR])
389
390   # Wait for logcat_monitor to pull existing logcat
391   RunCmd(['sleep', '5'])
392
393
394 def ProvisionDevices(options):
395   bb_annotations.PrintNamedStep('provision_devices')
396
397   if not bb_utils.TESTING:
398     # Restart adb to work around bugs, sleep to wait for usb discovery.
399     adb = android_commands.AndroidCommands()
400     adb.RestartAdbServer()
401     RunCmd(['sleep', '1'])
402
403   if options.reboot:
404     RebootDevices()
405   provision_cmd = ['build/android/provision_devices.py', '-t', options.target]
406   if options.auto_reconnect:
407     provision_cmd.append('--auto-reconnect')
408   RunCmd(provision_cmd)
409
410
411 def DeviceStatusCheck(options):
412   bb_annotations.PrintNamedStep('device_status_check')
413   cmd = ['build/android/buildbot/bb_device_status_check.py']
414   if options.restart_usb:
415     cmd.append('--restart-usb')
416   RunCmd(cmd, halt_on_failure=True)
417
418
419 def GetDeviceSetupStepCmds():
420   return [
421       ('provision_devices', ProvisionDevices),
422       ('device_status_check', DeviceStatusCheck),
423   ]
424
425
426 def RunUnitTests(options):
427   RunTestSuites(options, gtest_config.STABLE_TEST_SUITES)
428
429
430 def RunInstrumentationTests(options):
431   for test in INSTRUMENTATION_TESTS.itervalues():
432     RunInstrumentationSuite(options, test)
433
434
435 def RunWebkitTests(options):
436   RunTestSuites(options, ['webkit_unit_tests'])
437   RunWebkitLint(options.target)
438
439
440 def RunWebRTCChromiumTests(options):
441   RunTestSuites(options, gtest_config.WEBRTC_CHROMIUM_TEST_SUITES)
442
443
444 def RunWebRTCNativeTests(options):
445   RunTestSuites(options, gtest_config.WEBRTC_NATIVE_TEST_SUITES)
446
447
448 def RunGPUTests(options):
449   InstallApk(options, INSTRUMENTATION_TESTS['ContentShell'], False)
450
451   bb_annotations.PrintNamedStep('gpu_tests')
452   RunCmd(['content/test/gpu/run_gpu_test',
453           '--browser=android-content-shell', 'pixel'])
454
455   bb_annotations.PrintNamedStep('webgl_conformance_tests')
456   RunCmd(['content/test/gpu/run_gpu_test',
457           '--browser=android-content-shell', 'webgl_conformance',
458           '--webgl-conformance-version=1.0.1'])
459
460
461 def GetTestStepCmds():
462   return [
463       ('chromedriver', RunChromeDriverTests),
464       ('gpu', RunGPUTests),
465       ('unit', RunUnitTests),
466       ('ui', RunInstrumentationTests),
467       ('webkit', RunWebkitTests),
468       ('webkit_layout', RunWebkitLayoutTests),
469       ('webrtc_chromium', RunWebRTCChromiumTests),
470       ('webrtc_native', RunWebRTCNativeTests),
471   ]
472
473
474 def UploadHTML(options, gs_base_dir, dir_to_upload, link_text,
475                link_rel_path='index.html', gs_url=GS_URL):
476   """Uploads directory at |dir_to_upload| to Google Storage and output a link.
477
478   Args:
479     options: Command line options.
480     gs_base_dir: The Google Storage base directory (e.g.
481       'chromium-code-coverage/java')
482     dir_to_upload: Absolute path to the directory to be uploaded.
483     link_text: Link text to be displayed on the step.
484     link_rel_path: Link path relative to |dir_to_upload|.
485     gs_url: Google storage URL.
486   """
487   revision = _GetRevision(options)
488   bot_id = options.build_properties.get('buildername', 'testing')
489   randhash = hashlib.sha1(str(random.random())).hexdigest()
490   gs_path = '%s/%s/%s/%s' % (gs_base_dir, bot_id, revision, randhash)
491   RunCmd([bb_utils.GSUTIL_PATH, 'cp', '-R', dir_to_upload, 'gs://%s' % gs_path])
492   bb_annotations.PrintLink(link_text,
493                            '%s/%s/%s' % (gs_url, gs_path, link_rel_path))
494
495
496 def GenerateJavaCoverageReport(options):
497   """Generates an HTML coverage report using EMMA and uploads it."""
498   bb_annotations.PrintNamedStep('java_coverage_report')
499
500   coverage_html = os.path.join(options.coverage_dir, 'coverage_html')
501   RunCmd(['build/android/generate_emma_html.py',
502           '--coverage-dir', options.coverage_dir,
503           '--metadata-dir', os.path.join(CHROME_OUT_DIR, options.target),
504           '--cleanup',
505           '--output', os.path.join(coverage_html, 'index.html')])
506   return coverage_html
507
508
509 def LogcatDump(options):
510   # Print logcat, kill logcat monitor
511   bb_annotations.PrintNamedStep('logcat_dump')
512   logcat_file = os.path.join(CHROME_OUT_DIR, options.target, 'full_log')
513   with open(logcat_file, 'w') as f:
514     RunCmd([
515         os.path.join(CHROME_SRC_DIR, 'build', 'android',
516                      'adb_logcat_printer.py'),
517         LOGCAT_DIR], stdout=f)
518   RunCmd(['cat', logcat_file])
519
520
521 def GenerateTestReport(options):
522   bb_annotations.PrintNamedStep('test_report')
523   for report in glob.glob(
524       os.path.join(CHROME_OUT_DIR, options.target, 'test_logs', '*.log')):
525     RunCmd(['cat', report])
526     os.remove(report)
527
528
529 def MainTestWrapper(options):
530   try:
531     # Spawn logcat monitor
532     SpawnLogcatMonitor()
533
534     # Run all device setup steps
535     for _, cmd in GetDeviceSetupStepCmds():
536       cmd(options)
537
538     if options.install:
539       test_obj = INSTRUMENTATION_TESTS[options.install]
540       InstallApk(options, test_obj, print_step=True)
541
542     if options.test_filter:
543       bb_utils.RunSteps(options.test_filter, GetTestStepCmds(), options)
544
545     if options.coverage_bucket:
546       coverage_html = GenerateJavaCoverageReport(options)
547       UploadHTML(options, '%s/java' % options.coverage_bucket, coverage_html,
548                  'Coverage Report')
549
550     if options.experimental:
551       RunTestSuites(options, gtest_config.EXPERIMENTAL_TEST_SUITES)
552
553   finally:
554     # Run all post test steps
555     LogcatDump(options)
556     GenerateTestReport(options)
557     # KillHostHeartbeat() has logic to check if heartbeat process is running,
558     # and kills only if it finds the process is running on the host.
559     provision_devices.KillHostHeartbeat()
560
561
562 def GetDeviceStepsOptParser():
563   parser = bb_utils.GetParser()
564   parser.add_option('--experimental', action='store_true',
565                     help='Run experiemental tests')
566   parser.add_option('-f', '--test-filter', metavar='<filter>', default=[],
567                     action='append',
568                     help=('Run a test suite. Test suites: "%s"' %
569                           '", "'.join(VALID_TESTS)))
570   parser.add_option('--asan', action='store_true', help='Run tests with asan.')
571   parser.add_option('--install', metavar='<apk name>',
572                     help='Install an apk by name')
573   parser.add_option('--reboot', action='store_true',
574                     help='Reboot devices before running tests')
575   parser.add_option('--coverage-bucket',
576                     help=('Bucket name to store coverage results. Coverage is '
577                           'only run if this is set.'))
578   parser.add_option('--restart-usb', action='store_true',
579                     help='Restart usb ports before device status check.')
580   parser.add_option(
581       '--flakiness-server',
582       help=('The flakiness dashboard server to which the results should be '
583             'uploaded.'))
584   parser.add_option(
585       '--auto-reconnect', action='store_true',
586       help='Push script to device which restarts adbd on disconnections.')
587   parser.add_option(
588       '--logcat-dump-output',
589       help='The logcat dump output will be "tee"-ed into this file')
590
591   return parser
592
593
594 def main(argv):
595   parser = GetDeviceStepsOptParser()
596   options, args = parser.parse_args(argv[1:])
597
598   if args:
599     return sys.exit('Unused args %s' % args)
600
601   unknown_tests = set(options.test_filter) - VALID_TESTS
602   if unknown_tests:
603     return sys.exit('Unknown tests %s' % list(unknown_tests))
604
605   setattr(options, 'target', options.factory_properties.get('target', 'Debug'))
606   if options.coverage_bucket:
607     setattr(options, 'coverage_dir',
608             os.path.join(CHROME_OUT_DIR, options.target, 'coverage'))
609
610   MainTestWrapper(options)
611
612
613 if __name__ == '__main__':
614   sys.exit(main(sys.argv))