forked from sanyaade-mobiledev/chromium.src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbisect-perf-regression.py
executable file
·4155 lines (3426 loc) · 149 KB
/
bisect-perf-regression.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Performance Test Bisect Tool
This script bisects a series of changelists using binary search. It starts at
a bad revision where a performance metric has regressed, and asks for a last
known-good revision. It will then binary search across this revision range by
syncing, building, and running a performance test. If the change is
suspected to occur as a result of WebKit/V8 changes, the script will
further bisect changes to those depots and attempt to narrow down the revision
range.
An example usage (using svn cl's):
./tools/bisect-perf-regression.py -c\
"out/Release/performance_ui_tests --gtest_filter=ShutdownTest.SimpleUserQuit"\
-g 168222 -b 168232 -m shutdown/simple-user-quit
Be aware that if you're using the git workflow and specify an svn revision,
the script will attempt to find the git SHA1 where svn changes up to that
revision were merged in.
An example usage (using git hashes):
./tools/bisect-perf-regression.py -c\
"out/Release/performance_ui_tests --gtest_filter=ShutdownTest.SimpleUserQuit"\
-g 1f6e67861535121c5c819c16a666f2436c207e7b\
-b b732f23b4f81c382db0b23b9035f3dadc7d925bb\
-m shutdown/simple-user-quit
"""
import copy
import datetime
import errno
import hashlib
import math
import optparse
import os
import re
import shlex
import shutil
import StringIO
import subprocess
import sys
import time
import zipfile
sys.path.append(os.path.join(os.path.dirname(__file__), 'telemetry'))
from auto_bisect import bisect_utils
from auto_bisect import post_perf_builder_job as bisect_builder
from telemetry.util import cloud_storage
# The additional repositories that might need to be bisected.
# If the repository has any dependant repositories (such as skia/src needs
# skia/include and skia/gyp to be updated), specify them in the 'depends'
# so that they're synced appropriately.
# Format is:
# src: path to the working directory.
# recurse: True if this repositry will get bisected.
# depends: A list of other repositories that are actually part of the same
# repository in svn.
# svn: Needed for git workflow to resolve hashes to svn revisions.
# from: Parent depot that must be bisected before this is bisected.
# deps_var: Key name in vars varible in DEPS file that has revision information.
DEPOT_DEPS_NAME = {
'chromium' : {
"src" : "src",
"recurse" : True,
"depends" : None,
"from" : ['cros', 'android-chrome'],
'viewvc': 'http://src.chromium.org/viewvc/chrome?view=revision&revision=',
'deps_var': 'chromium_rev'
},
'webkit' : {
"src" : "src/third_party/WebKit",
"recurse" : True,
"depends" : None,
"from" : ['chromium'],
'viewvc': 'http://src.chromium.org/viewvc/blink?view=revision&revision=',
'deps_var': 'webkit_revision'
},
'angle' : {
"src" : "src/third_party/angle",
"src_old" : "src/third_party/angle_dx11",
"recurse" : True,
"depends" : None,
"from" : ['chromium'],
"platform": 'nt',
'deps_var': 'angle_revision'
},
'v8' : {
"src" : "src/v8",
"recurse" : True,
"depends" : None,
"from" : ['chromium'],
"custom_deps": bisect_utils.GCLIENT_CUSTOM_DEPS_V8,
'viewvc': 'https://code.google.com/p/v8/source/detail?r=',
'deps_var': 'v8_revision'
},
'v8_bleeding_edge' : {
"src" : "src/v8_bleeding_edge",
"recurse" : True,
"depends" : None,
"svn": "https://v8.googlecode.com/svn/branches/bleeding_edge",
"from" : ['v8'],
'viewvc': 'https://code.google.com/p/v8/source/detail?r=',
'deps_var': 'v8_revision'
},
'skia/src' : {
"src" : "src/third_party/skia/src",
"recurse" : True,
"svn" : "http://skia.googlecode.com/svn/trunk/src",
"depends" : ['skia/include', 'skia/gyp'],
"from" : ['chromium'],
'viewvc': 'https://code.google.com/p/skia/source/detail?r=',
'deps_var': 'skia_revision'
},
'skia/include' : {
"src" : "src/third_party/skia/include",
"recurse" : False,
"svn" : "http://skia.googlecode.com/svn/trunk/include",
"depends" : None,
"from" : ['chromium'],
'viewvc': 'https://code.google.com/p/skia/source/detail?r=',
'deps_var': 'None'
},
'skia/gyp' : {
"src" : "src/third_party/skia/gyp",
"recurse" : False,
"svn" : "http://skia.googlecode.com/svn/trunk/gyp",
"depends" : None,
"from" : ['chromium'],
'viewvc': 'https://code.google.com/p/skia/source/detail?r=',
'deps_var': 'None'
},
}
DEPOT_NAMES = DEPOT_DEPS_NAME.keys()
CROS_SDK_PATH = os.path.join('..', 'cros', 'chromite', 'bin', 'cros_sdk')
CROS_VERSION_PATTERN = 'new version number from %s'
CROS_CHROMEOS_PATTERN = 'chromeos-base/chromeos-chrome'
CROS_TEST_KEY_PATH = os.path.join('..', 'cros', 'chromite', 'ssh_keys',
'testing_rsa')
CROS_SCRIPT_KEY_PATH = os.path.join('..', 'cros', 'src', 'scripts',
'mod_for_test_scripts', 'ssh_keys',
'testing_rsa')
BUILD_RESULT_SUCCEED = 0
BUILD_RESULT_FAIL = 1
BUILD_RESULT_SKIPPED = 2
# Maximum time in seconds to wait after posting build request to tryserver.
# TODO: Change these values based on the actual time taken by buildbots on
# the tryserver.
MAX_MAC_BUILD_TIME = 14400
MAX_WIN_BUILD_TIME = 14400
MAX_LINUX_BUILD_TIME = 14400
# Patch template to add a new file, DEPS.sha under src folder.
# This file contains SHA1 value of the DEPS changes made while bisecting
# dependency repositories. This patch send along with DEPS patch to tryserver.
# When a build requested is posted with a patch, bisect builders on tryserver,
# once build is produced, it reads SHA value from this file and appends it
# to build archive filename.
DEPS_SHA_PATCH = """diff --git src/DEPS.sha src/DEPS.sha
new file mode 100644
--- /dev/null
+++ src/DEPS.sha
@@ -0,0 +1 @@
+%(deps_sha)s
"""
# The possible values of the --bisect_mode flag, which determines what to
# use when classifying a revision as "good" or "bad".
BISECT_MODE_MEAN = 'mean'
BISECT_MODE_STD_DEV = 'std_dev'
BISECT_MODE_RETURN_CODE = 'return_code'
# The perf dashboard specifically looks for the string
# "Estimated Confidence: 95%" to decide whether or not
# to cc the author(s). If you change this, please update the perf
# dashboard as well.
RESULTS_BANNER = """
===== BISECT JOB RESULTS =====
Status: %(status)s
Test Command: %(command)s
Test Metric: %(metrics)s
Relative Change: %(change)s
Estimated Confidence: %(confidence)d%%"""
# The perf dashboard specifically looks for the string
# "Author : " to parse out who to cc on a bug. If you change the
# formatting here, please update the perf dashboard as well.
RESULTS_REVISION_INFO = """
===== SUSPECTED CL(s) =====
Subject : %(subject)s
Author : %(author)s%(email_info)s%(commit_info)s
Commit : %(cl)s
Date : %(cl_date)s"""
REPRO_STEPS_LOCAL = """
==== INSTRUCTIONS TO REPRODUCE ====
To run locally:
$%(command)s"""
REPRO_STEPS_TRYJOB = """
To reproduce on Performance trybot:
1. Create new git branch or check out existing branch.
2. Edit tools/run-perf-test.cfg (instructions in file) or \
third_party/WebKit/Tools/run-perf-test.cfg.
a) Take care to strip any src/ directories from the head of \
relative path names.
b) On desktop, only --browser=release is supported, on android \
--browser=android-chromium-testshell.
c) Test command to use: %(command)s
3. Upload your patch. --bypass-hooks is necessary to upload the changes you \
committed locally to run-perf-test.cfg.
Note: *DO NOT* commit run-perf-test.cfg changes to the project repository.
$ git cl upload --bypass-hooks
4. Send your try job to the tryserver. \
[Please make sure to use appropriate bot to reproduce]
$ git cl try -m tryserver.chromium.perf -b <bot>
For more details please visit \nhttps://sites.google.com/a/chromium.org/dev/\
developers/performance-try-bots"""
RESULTS_THANKYOU = """
===== THANK YOU FOR CHOOSING BISECT AIRLINES =====
Visit http://www.chromium.org/developers/core-principles for Chrome's policy
on perf regressions.
Contact chrome-perf-dashboard-team with any questions or suggestions about
bisecting.
. .------.
. .---. \ \==)
. |PERF\ \ \\
. | ---------'-------'-----------.
. . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 `-.
. \______________.-------._______________)
. / /
. / /
. / /==)
. ._______."""
def _AddAdditionalDepotInfo(depot_info):
"""Adds additional depot info to the global depot variables."""
global DEPOT_DEPS_NAME
global DEPOT_NAMES
DEPOT_DEPS_NAME = dict(DEPOT_DEPS_NAME.items() +
depot_info.items())
DEPOT_NAMES = DEPOT_DEPS_NAME.keys()
def CalculateTruncatedMean(data_set, truncate_percent):
"""Calculates the truncated mean of a set of values.
Note that this isn't just the mean of the set of values with the highest
and lowest values discarded; the non-discarded values are also weighted
differently depending how many values are discarded.
Args:
data_set: Non-empty list of values.
truncate_percent: The % from the upper and lower portions of the data set
to discard, expressed as a value in [0, 1].
Returns:
The truncated mean as a float.
Raises:
TypeError: The data set was empty after discarding values.
"""
if len(data_set) > 2:
data_set = sorted(data_set)
discard_num_float = len(data_set) * truncate_percent
discard_num_int = int(math.floor(discard_num_float))
kept_weight = len(data_set) - discard_num_float * 2
data_set = data_set[discard_num_int:len(data_set)-discard_num_int]
weight_left = 1.0 - (discard_num_float - discard_num_int)
if weight_left < 1:
# If the % to discard leaves a fractional portion, need to weight those
# values.
unweighted_vals = data_set[1:len(data_set)-1]
weighted_vals = [data_set[0], data_set[len(data_set)-1]]
weighted_vals = [w * weight_left for w in weighted_vals]
data_set = weighted_vals + unweighted_vals
else:
kept_weight = len(data_set)
truncated_mean = reduce(lambda x, y: float(x) + float(y),
data_set) / kept_weight
return truncated_mean
def CalculateMean(values):
"""Calculates the arithmetic mean of a list of values."""
return CalculateTruncatedMean(values, 0.0)
def CalculateConfidence(good_results_lists, bad_results_lists):
"""Calculates a confidence percentage.
This is calculated based on how distinct the "good" and "bad" values are,
and how noisy the results are. More precisely, the confidence is the quotient
of the difference between the closest values across the good and bad groups
and the sum of the standard deviations of the good and bad groups.
TODO(qyearsley): Replace this confidence function with a function that
uses a Student's t-test. The confidence would be (1 - p-value), where
p-value is the probability of obtaining the given a set of good and bad
values just by chance.
Args:
good_results_lists: A list of lists of "good" result numbers.
bad_results_lists: A list of lists of "bad" result numbers.
Returns:
A number between in the range [0, 100].
"""
# Get the distance between the two groups.
means_good = map(CalculateMean, good_results_lists)
means_bad = map(CalculateMean, bad_results_lists)
bounds_good = (min(means_good), max(means_good))
bounds_bad = (min(means_bad), max(means_bad))
dist_between_groups = min(
math.fabs(bounds_bad[1] - bounds_good[0]),
math.fabs(bounds_bad[0] - bounds_good[1]))
# Get the sum of the standard deviations of the two groups.
good_results_flattened = sum(good_results_lists, [])
bad_results_flattened = sum(bad_results_lists, [])
stddev_good = CalculateStandardDeviation(good_results_flattened)
stddev_bad = CalculateStandardDeviation(bad_results_flattened)
stddev_sum = stddev_good + stddev_bad
confidence = dist_between_groups / (max(0.0001, stddev_sum))
confidence = int(min(1.0, max(confidence, 0.0)) * 100.0)
return confidence
def CalculateStandardDeviation(values):
"""Calculates the sample standard deviation of the given list of values."""
if len(values) == 1:
return 0.0
mean = CalculateMean(values)
differences_from_mean = [float(x) - mean for x in values]
squared_differences = [float(x * x) for x in differences_from_mean]
variance = sum(squared_differences) / (len(values) - 1)
std_dev = math.sqrt(variance)
return std_dev
def CalculateRelativeChange(before, after):
"""Returns the relative change of before and after, relative to before.
There are several different ways to define relative difference between
two numbers; sometimes it is defined as relative to the smaller number,
or to the mean of the two numbers. This version returns the difference
relative to the first of the two numbers.
Args:
before: A number representing an earlier value.
after: Another number, representing a later value.
Returns:
A non-negative floating point number; 0.1 represents a 10% change.
"""
if before == after:
return 0.0
if before == 0:
return float('nan')
difference = after - before
return math.fabs(difference / before)
def CalculatePooledStandardError(work_sets):
numerator = 0.0
denominator1 = 0.0
denominator2 = 0.0
for current_set in work_sets:
std_dev = CalculateStandardDeviation(current_set)
numerator += (len(current_set) - 1) * std_dev ** 2
denominator1 += len(current_set) - 1
denominator2 += 1.0 / len(current_set)
if denominator1:
return math.sqrt(numerator / denominator1) * math.sqrt(denominator2)
return 0.0
def CalculateStandardError(values):
"""Calculates the standard error of a list of values."""
if len(values) <= 1:
return 0.0
std_dev = CalculateStandardDeviation(values)
return std_dev / math.sqrt(len(values))
def IsStringFloat(string_to_check):
"""Checks whether or not the given string can be converted to a floating
point number.
Args:
string_to_check: Input string to check if it can be converted to a float.
Returns:
True if the string can be converted to a float.
"""
try:
float(string_to_check)
return True
except ValueError:
return False
def IsStringInt(string_to_check):
"""Checks whether or not the given string can be converted to a integer.
Args:
string_to_check: Input string to check if it can be converted to an int.
Returns:
True if the string can be converted to an int.
"""
try:
int(string_to_check)
return True
except ValueError:
return False
def IsWindowsHost():
"""Checks whether or not the script is running on Windows.
Returns:
True if running on Windows.
"""
return sys.platform == 'cygwin' or sys.platform.startswith('win')
def Is64BitWindows():
"""Returns whether or not Windows is a 64-bit version.
Returns:
True if Windows is 64-bit, False if 32-bit.
"""
platform = os.environ['PROCESSOR_ARCHITECTURE']
try:
platform = os.environ['PROCESSOR_ARCHITEW6432']
except KeyError:
# Must not be running in WoW64, so PROCESSOR_ARCHITECTURE is correct
pass
return platform in ['AMD64', 'I64']
def IsLinuxHost():
"""Checks whether or not the script is running on Linux.
Returns:
True if running on Linux.
"""
return sys.platform.startswith('linux')
def IsMacHost():
"""Checks whether or not the script is running on Mac.
Returns:
True if running on Mac.
"""
return sys.platform.startswith('darwin')
def GetSHA1HexDigest(contents):
"""Returns secured hash containing hexadecimal for the given contents."""
return hashlib.sha1(contents).hexdigest()
def GetZipFileName(build_revision=None, target_arch='ia32', patch_sha=None):
"""Gets the archive file name for the given revision."""
def PlatformName():
"""Return a string to be used in paths for the platform."""
if IsWindowsHost():
# Build archive for x64 is still stored with 'win32'suffix
# (chromium_utils.PlatformName()).
if Is64BitWindows() and target_arch == 'x64':
return 'win32'
return 'win32'
if IsLinuxHost():
# Android builds too are archived with full-build-linux* prefix.
return 'linux'
if IsMacHost():
return 'mac'
raise NotImplementedError('Unknown platform "%s".' % sys.platform)
base_name = 'full-build-%s' % PlatformName()
if not build_revision:
return base_name
if patch_sha:
build_revision = '%s_%s' % (build_revision , patch_sha)
return '%s_%s.zip' % (base_name, build_revision)
def GetRemoteBuildPath(build_revision, target_platform='chromium',
target_arch='ia32', patch_sha=None):
"""Compute the url to download the build from."""
def GetGSRootFolderName(target_platform):
"""Gets Google Cloud Storage root folder names"""
if IsWindowsHost():
if Is64BitWindows() and target_arch == 'x64':
return 'Win x64 Builder'
return 'Win Builder'
if IsLinuxHost():
if target_platform == 'android':
return 'android_perf_rel'
return 'Linux Builder'
if IsMacHost():
return 'Mac Builder'
raise NotImplementedError('Unsupported Platform "%s".' % sys.platform)
base_filename = GetZipFileName(
build_revision, target_arch, patch_sha)
builder_folder = GetGSRootFolderName(target_platform)
return '%s/%s' % (builder_folder, base_filename)
def FetchFromCloudStorage(bucket_name, source_path, destination_path):
"""Fetches file(s) from the Google Cloud Storage.
Args:
bucket_name: Google Storage bucket name.
source_path: Source file path.
destination_path: Destination file path.
Returns:
Downloaded file path if exisits, otherwise None.
"""
target_file = os.path.join(destination_path, os.path.basename(source_path))
try:
if cloud_storage.Exists(bucket_name, source_path):
print 'Fetching file from gs//%s/%s ...' % (bucket_name, source_path)
cloud_storage.Get(bucket_name, source_path, destination_path)
if os.path.exists(target_file):
return target_file
else:
print ('File gs://%s/%s not found in cloud storage.' % (
bucket_name, source_path))
except Exception as e:
print 'Something went wrong while fetching file from cloud: %s' % e
if os.path.exists(target_file):
os.remove(target_file)
return None
# This is copied from Chromium's project build/scripts/common/chromium_utils.py.
def MaybeMakeDirectory(*path):
"""Creates an entire path, if it doesn't already exist."""
file_path = os.path.join(*path)
try:
os.makedirs(file_path)
except OSError, e:
if e.errno != errno.EEXIST:
return False
return True
# This is copied from Chromium's project build/scripts/common/chromium_utils.py.
def ExtractZip(filename, output_dir, verbose=True):
""" Extract the zip archive in the output directory."""
MaybeMakeDirectory(output_dir)
# On Linux and Mac, we use the unzip command as it will
# handle links and file bits (executable), which is much
# easier then trying to do that with ZipInfo options.
#
# The Mac Version of unzip unfortunately does not support Zip64, whereas
# the python module does, so we have to fallback to the python zip module
# on Mac if the filesize is greater than 4GB.
#
# On Windows, try to use 7z if it is installed, otherwise fall back to python
# zip module and pray we don't have files larger than 512MB to unzip.
unzip_cmd = None
if ((IsMacHost() and os.path.getsize(filename) < 4 * 1024 * 1024 * 1024)
or IsLinuxHost()):
unzip_cmd = ['unzip', '-o']
elif IsWindowsHost() and os.path.exists('C:\\Program Files\\7-Zip\\7z.exe'):
unzip_cmd = ['C:\\Program Files\\7-Zip\\7z.exe', 'x', '-y']
if unzip_cmd:
# Make sure path is absolute before changing directories.
filepath = os.path.abspath(filename)
saved_dir = os.getcwd()
os.chdir(output_dir)
command = unzip_cmd + [filepath]
result = RunProcess(command)
os.chdir(saved_dir)
if result:
raise IOError('unzip failed: %s => %s' % (str(command), result))
else:
assert IsWindowsHost() or IsMacHost()
zf = zipfile.ZipFile(filename)
for name in zf.namelist():
if verbose:
print 'Extracting %s' % name
zf.extract(name, output_dir)
if IsMacHost():
# Restore permission bits.
os.chmod(os.path.join(output_dir, name),
zf.getinfo(name).external_attr >> 16L)
def RunProcess(command):
"""Runs an arbitrary command.
If output from the call is needed, use RunProcessAndRetrieveOutput instead.
Args:
command: A list containing the command and args to execute.
Returns:
The return code of the call.
"""
# On Windows, use shell=True to get PATH interpretation.
shell = IsWindowsHost()
return subprocess.call(command, shell=shell)
def RunProcessAndRetrieveOutput(command, cwd=None):
"""Runs an arbitrary command, returning its output and return code.
Since output is collected via communicate(), there will be no output until
the call terminates. If you need output while the program runs (ie. so
that the buildbot doesn't terminate the script), consider RunProcess().
Args:
command: A list containing the command and args to execute.
cwd: A directory to change to while running the command. The command can be
relative to this directory. If this is None, the command will be run in
the current directory.
Returns:
A tuple of the output and return code.
"""
if cwd:
original_cwd = os.getcwd()
os.chdir(cwd)
# On Windows, use shell=True to get PATH interpretation.
shell = IsWindowsHost()
proc = subprocess.Popen(command, shell=shell, stdout=subprocess.PIPE)
(output, _) = proc.communicate()
if cwd:
os.chdir(original_cwd)
return (output, proc.returncode)
def RunGit(command, cwd=None):
"""Run a git subcommand, returning its output and return code.
Args:
command: A list containing the args to git.
cwd: A directory to change to while running the git command (optional).
Returns:
A tuple of the output and return code.
"""
command = ['git'] + command
return RunProcessAndRetrieveOutput(command, cwd=cwd)
def CheckRunGit(command, cwd=None):
"""Run a git subcommand, returning its output and return code. Asserts if
the return code of the call is non-zero.
Args:
command: A list containing the args to git.
Returns:
A tuple of the output and return code.
"""
(output, return_code) = RunGit(command, cwd=cwd)
assert not return_code, 'An error occurred while running'\
' "git %s"' % ' '.join(command)
return output
def SetBuildSystemDefault(build_system, use_goma, goma_dir):
"""Sets up any environment variables needed to build with the specified build
system.
Args:
build_system: A string specifying build system. Currently only 'ninja' or
'make' are supported."""
if build_system == 'ninja':
gyp_var = os.getenv('GYP_GENERATORS')
if not gyp_var or not 'ninja' in gyp_var:
if gyp_var:
os.environ['GYP_GENERATORS'] = gyp_var + ',ninja'
else:
os.environ['GYP_GENERATORS'] = 'ninja'
if IsWindowsHost():
os.environ['GYP_DEFINES'] = 'component=shared_library '\
'incremental_chrome_dll=1 disable_nacl=1 fastbuild=1 '\
'chromium_win_pch=0'
elif build_system == 'make':
os.environ['GYP_GENERATORS'] = 'make'
else:
raise RuntimeError('%s build not supported.' % build_system)
if use_goma:
os.environ['GYP_DEFINES'] = '%s %s' % (os.getenv('GYP_DEFINES', ''),
'use_goma=1')
if goma_dir:
os.environ['GYP_DEFINES'] += ' gomadir=%s' % goma_dir
def BuildWithMake(threads, targets, build_type='Release'):
cmd = ['make', 'BUILDTYPE=%s' % build_type]
if threads:
cmd.append('-j%d' % threads)
cmd += targets
return_code = RunProcess(cmd)
return not return_code
def BuildWithNinja(threads, targets, build_type='Release'):
cmd = ['ninja', '-C', os.path.join('out', build_type)]
if threads:
cmd.append('-j%d' % threads)
cmd += targets
return_code = RunProcess(cmd)
return not return_code
def BuildWithVisualStudio(targets, build_type='Release'):
path_to_devenv = os.path.abspath(
os.path.join(os.environ['VS100COMNTOOLS'], '..', 'IDE', 'devenv.com'))
path_to_sln = os.path.join(os.getcwd(), 'chrome', 'chrome.sln')
cmd = [path_to_devenv, '/build', build_type, path_to_sln]
for t in targets:
cmd.extend(['/Project', t])
return_code = RunProcess(cmd)
return not return_code
def WriteStringToFile(text, file_name):
try:
with open(file_name, "wb") as f:
f.write(text)
except IOError as e:
raise RuntimeError('Error writing to file [%s]' % file_name )
def ReadStringFromFile(file_name):
try:
with open(file_name) as f:
return f.read()
except IOError as e:
raise RuntimeError('Error reading file [%s]' % file_name )
def ChangeBackslashToSlashInPatch(diff_text):
"""Formats file paths in the given text to unix-style paths."""
if diff_text:
diff_lines = diff_text.split('\n')
for i in range(len(diff_lines)):
if (diff_lines[i].startswith('--- ') or
diff_lines[i].startswith('+++ ')):
diff_lines[i] = diff_lines[i].replace('\\', '/')
return '\n'.join(diff_lines)
return None
class Builder(object):
"""Builder is used by the bisect script to build relevant targets and deploy.
"""
def __init__(self, opts):
"""Performs setup for building with target build system.
Args:
opts: Options parsed from command line.
"""
if IsWindowsHost():
if not opts.build_preference:
opts.build_preference = 'msvs'
if opts.build_preference == 'msvs':
if not os.getenv('VS100COMNTOOLS'):
raise RuntimeError(
'Path to visual studio could not be determined.')
else:
SetBuildSystemDefault(opts.build_preference, opts.use_goma,
opts.goma_dir)
else:
if not opts.build_preference:
if 'ninja' in os.getenv('GYP_GENERATORS'):
opts.build_preference = 'ninja'
else:
opts.build_preference = 'make'
SetBuildSystemDefault(opts.build_preference, opts.use_goma, opts.goma_dir)
if not bisect_utils.SetupPlatformBuildEnvironment(opts):
raise RuntimeError('Failed to set platform environment.')
@staticmethod
def FromOpts(opts):
builder = None
if opts.target_platform == 'cros':
builder = CrosBuilder(opts)
elif opts.target_platform == 'android':
builder = AndroidBuilder(opts)
elif opts.target_platform == 'android-chrome':
builder = AndroidChromeBuilder(opts)
else:
builder = DesktopBuilder(opts)
return builder
def Build(self, depot, opts):
raise NotImplementedError()
def GetBuildOutputDirectory(self, opts, src_dir=None):
"""Returns the path to the build directory, relative to the checkout root.
Assumes that the current working directory is the checkout root.
"""
src_dir = src_dir or 'src'
if opts.build_preference == 'ninja' or IsLinuxHost():
return os.path.join(src_dir, 'out')
if IsMacHost():
return os.path.join(src_dir, 'xcodebuild')
if IsWindowsHost():
return os.path.join(src_dir, 'build')
raise NotImplementedError('Unexpected platform %s' % sys.platform)
class DesktopBuilder(Builder):
"""DesktopBuilder is used to build Chromium on linux/mac/windows."""
def __init__(self, opts):
super(DesktopBuilder, self).__init__(opts)
def Build(self, depot, opts):
"""Builds chromium_builder_perf target using options passed into
the script.
Args:
depot: Current depot being bisected.
opts: The options parsed from the command line.
Returns:
True if build was successful.
"""
targets = ['chromium_builder_perf']
threads = None
if opts.use_goma:
threads = 64
build_success = False
if opts.build_preference == 'make':
build_success = BuildWithMake(threads, targets, opts.target_build_type)
elif opts.build_preference == 'ninja':
build_success = BuildWithNinja(threads, targets, opts.target_build_type)
elif opts.build_preference == 'msvs':
assert IsWindowsHost(), 'msvs is only supported on Windows.'
build_success = BuildWithVisualStudio(targets, opts.target_build_type)
else:
assert False, 'No build system defined.'
return build_success
class AndroidBuilder(Builder):
"""AndroidBuilder is used to build on android."""
def __init__(self, opts):
super(AndroidBuilder, self).__init__(opts)
def _GetTargets(self):
return ['chrome_shell_apk', 'cc_perftests_apk', 'android_tools']
def Build(self, depot, opts):
"""Builds the android content shell and other necessary tools using options
passed into the script.
Args:
depot: Current depot being bisected.
opts: The options parsed from the command line.
Returns:
True if build was successful.
"""
threads = None
if opts.use_goma:
threads = 64
build_success = False
if opts.build_preference == 'ninja':
build_success = BuildWithNinja(
threads, self._GetTargets(), opts.target_build_type)
else:
assert False, 'No build system defined.'
return build_success
class AndroidChromeBuilder(AndroidBuilder):
"""AndroidBuilder is used to build on android's chrome."""
def __init__(self, opts):
super(AndroidChromeBuilder, self).__init__(opts)
def _GetTargets(self):
return AndroidBuilder._GetTargets(self) + ['chrome_apk']
class CrosBuilder(Builder):
"""CrosBuilder is used to build and image ChromeOS/Chromium when cros is the
target platform."""
def __init__(self, opts):
super(CrosBuilder, self).__init__(opts)
def ImageToTarget(self, opts):
"""Installs latest image to target specified by opts.cros_remote_ip.
Args:
opts: Program options containing cros_board and cros_remote_ip.
Returns:
True if successful.
"""
try:
# Keys will most likely be set to 0640 after wiping the chroot.
os.chmod(CROS_SCRIPT_KEY_PATH, 0600)
os.chmod(CROS_TEST_KEY_PATH, 0600)
cmd = [CROS_SDK_PATH, '--', './bin/cros_image_to_target.py',
'--remote=%s' % opts.cros_remote_ip,
'--board=%s' % opts.cros_board, '--test', '--verbose']
return_code = RunProcess(cmd)
return not return_code
except OSError, e:
return False
def BuildPackages(self, opts, depot):
"""Builds packages for cros.
Args:
opts: Program options containing cros_board.
depot: The depot being bisected.
Returns:
True if successful.
"""
cmd = [CROS_SDK_PATH]
if depot != 'cros':
path_to_chrome = os.path.join(os.getcwd(), '..')
cmd += ['--chrome_root=%s' % path_to_chrome]
cmd += ['--']
if depot != 'cros':
cmd += ['CHROME_ORIGIN=LOCAL_SOURCE']