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
·3271 lines (2751 loc) · 122 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.
Example usage using SVN revisions:
./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.
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 optparse
import os
import re
import shlex
import shutil
import StringIO
import sys
import time
import zipfile
sys.path.append(os.path.join(
os.path.dirname(__file__), os.path.pardir, 'telemetry'))
from bisect_results import BisectResults
import bisect_utils
import builder
import math_utils
import request_build
import source_control as source_control_module
from telemetry.util import cloud_storage
# Below is the map of "depot" names to information about each depot. Each depot
# is a repository, and in the process of bisecting, revision ranges in these
# repositories may also be bisected.
#
# Each depot information dictionary may contain:
# src: Path to the working directory.
# recurse: True if this repository will get bisected.
# depends: A list of other repositories that are actually part of the same
# repository in svn. If the repository has any dependent repositories
# (e.g. skia/src needs skia/include and skia/gyp to be updated), then
# they are specified here.
# svn: URL of SVN repository. 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 variable 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()
# The script is in chromium/src/tools/auto_bisect. Throughout this script,
# we use paths to other things in the chromium/src repository.
CROS_CHROMEOS_PATTERN = 'chromeos-base/chromeos-chrome'
# Possible return values from BisectPerformanceMetrics.RunTest.
BUILD_RESULT_SUCCEED = 0
BUILD_RESULT_FAIL = 1
BUILD_RESULT_SKIPPED = 2
# Maximum time in seconds to wait after posting build request to the try server.
# TODO: Change these values based on the actual time taken by buildbots on
# the try server.
MAX_MAC_BUILD_TIME = 14400
MAX_WIN_BUILD_TIME = 14400
MAX_LINUX_BUILD_TIME = 14400
# The confidence percentage at which confidence can be consider "high".
HIGH_CONFIDENCE = 95
# 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 try server.
# When a build requested is posted with a patch, bisect builders on try server,
# once build is produced, it reads SHA value from this file and appends it
# to build archive filename.
DEPS_SHA_PATCH = """diff --git DEPS.sha DEPS.sha
new file mode 100644
--- /dev/null
+++ 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 looks for a string like "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).02f%%"""
# 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:
- Use the test command given under 'BISECT JOB RESULTS' above.
- Consider using a profiler. Pass --profiler=list to list available profilers.
"""
REPRO_STEPS_TRYJOB = """
To reproduce on a performance try bot:
1. Edit run-perf-test.cfg
2. $ git try -b <bot> --svn_repo='svn://svn.chromium.org/chrome-try/try-perf'
Notes:
a) Follow the in-file instructions in run-perf-test.cfg.
b) run-perf-test.cfg is under tools/ or under third_party/WebKit/Tools.
c) Do your edits preferably under a new git branch.
d) --browser=release and --browser=android-chromium-testshell are supported
depending on the platform (desktop|android).
e) Strip any src/ directories from the head of relative path names.
f) Make sure to use the appropriate bot on step 3.
For more details please visit
https://sites.google.com/a/chromium.org/dev/developers/performance-try-bots"""
REPRO_STEPS_TRYJOB_TELEMETRY = """
To reproduce on a performance try bot:
%(command)s
(Where <bot-name> comes from tools/perf/run_benchmark --browser=list)
For more details please visit
https://sites.google.com/a/chromium.org/dev/developers/performance-try-bots
"""
RESULTS_THANKYOU = """
O O | Visit http://www.chromium.org/developers/core-principles for Chrome's
X | policy on perf regressions. Contact chrome-perf-dashboard-team with any
/ \ | questions or suggestions about bisecting. THANK YOU."""
# Git branch name used to run bisect try jobs.
BISECT_TRYJOB_BRANCH = 'bisect-tryjob'
# Git master branch name.
BISECT_MASTER_BRANCH = 'master'
# File to store 'git diff' content.
BISECT_PATCH_FILE = 'deps_patch.txt'
# SVN repo where the bisect try jobs are submitted.
SVN_REPO_URL = 'svn://svn.chromium.org/chrome-try/try-perf'
class RunGitError(Exception):
def __str__(self):
return '%s\nError executing git command.' % self.args[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 GetSHA1HexDigest(contents):
"""Returns SHA1 hex digest of the given string."""
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 bisect_utils.IsWindowsHost():
# Build archive for x64 is still stored with the "win32" suffix.
# See chromium_utils.PlatformName().
if bisect_utils.Is64BitWindows() and target_arch == 'x64':
return 'win32'
return 'win32'
if bisect_utils.IsLinuxHost():
# Android builds are also archived with the "full-build-linux prefix.
return 'linux'
if bisect_utils.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):
"""Returns the URL to download the build from."""
def GetGSRootFolderName(target_platform):
"""Returns the Google Cloud Storage root folder name."""
if bisect_utils.IsWindowsHost():
if bisect_utils.Is64BitWindows() and target_arch == 'x64':
return 'Win x64 Builder'
return 'Win Builder'
if bisect_utils.IsLinuxHost():
if target_platform == 'android':
return 'android_perf_rel'
return 'Linux Builder'
if bisect_utils.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 exists, 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 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 as e:
if e.errno != errno.EEXIST:
return False
return True
# This was copied from 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 fall back to the python zip module
# on Mac if the file size 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 ((bisect_utils.IsMacHost()
and os.path.getsize(filename) < 4 * 1024 * 1024 * 1024)
or bisect_utils.IsLinuxHost()):
unzip_cmd = ['unzip', '-o']
elif (bisect_utils.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 = bisect_utils.RunProcess(command)
os.chdir(saved_dir)
if result:
raise IOError('unzip failed: %s => %s' % (str(command), result))
else:
assert bisect_utils.IsWindowsHost() or bisect_utils.IsMacHost()
zf = zipfile.ZipFile(filename)
for name in zf.namelist():
if verbose:
print 'Extracting %s' % name
zf.extract(name, output_dir)
if bisect_utils.IsMacHost():
# Restore permission bits.
os.chmod(os.path.join(output_dir, name),
zf.getinfo(name).external_attr >> 16L)
def WriteStringToFile(text, file_name):
"""Writes text to a file, raising an RuntimeError on failure."""
try:
with open(file_name, 'wb') as f:
f.write(text)
except IOError:
raise RuntimeError('Error writing to file [%s]' % file_name )
def ReadStringFromFile(file_name):
"""Writes text to a file, raising an RuntimeError on failure."""
try:
with open(file_name) as f:
return f.read()
except IOError:
raise RuntimeError('Error reading file [%s]' % file_name )
def ChangeBackslashToSlashInPatch(diff_text):
"""Formats file paths in the given patch text to Unix-style paths."""
if not diff_text:
return None
diff_lines = diff_text.split('\n')
for i in range(len(diff_lines)):
line = diff_lines[i]
if line.startswith('--- ') or line.startswith('+++ '):
diff_lines[i] = line.replace('\\', '/')
return '\n'.join(diff_lines)
def _ParseRevisionsFromDEPSFileManually(deps_file_contents):
"""Parses the vars section of the DEPS file using regular expressions.
Args:
deps_file_contents: The DEPS file contents as a string.
Returns:
A dictionary in the format {depot: revision} if successful, otherwise None.
"""
# We'll parse the "vars" section of the DEPS file.
rxp = re.compile('vars = {(?P<vars_body>[^}]+)', re.MULTILINE)
re_results = rxp.search(deps_file_contents)
if not re_results:
return None
# We should be left with a series of entries in the vars component of
# the DEPS file with the following format:
# 'depot_name': 'revision',
vars_body = re_results.group('vars_body')
rxp = re.compile("'(?P<depot_body>[\w_-]+)':[\s]+'(?P<rev_body>[\w@]+)'",
re.MULTILINE)
re_results = rxp.findall(vars_body)
return dict(re_results)
def _WaitUntilBuildIsReady(
fetch_build, bot_name, builder_host, builder_port, build_request_id,
max_timeout):
"""Waits until build is produced by bisect builder on try server.
Args:
fetch_build: Function to check and download build from cloud storage.
bot_name: Builder bot name on try server.
builder_host Try server host name.
builder_port: Try server port.
build_request_id: A unique ID of the build request posted to try server.
max_timeout: Maximum time to wait for the build.
Returns:
Downloaded archive file path if exists, otherwise None.
"""
# Build number on the try server.
build_num = None
# Interval to check build on cloud storage.
poll_interval = 60
# Interval to check build status on try server in seconds.
status_check_interval = 600
last_status_check = time.time()
start_time = time.time()
while True:
# Checks for build on gs://chrome-perf and download if exists.
res = fetch_build()
if res:
return (res, 'Build successfully found')
elapsed_status_check = time.time() - last_status_check
# To avoid overloading try server with status check requests, we check
# build status for every 10 minutes.
if elapsed_status_check > status_check_interval:
last_status_check = time.time()
if not build_num:
# Get the build number on try server for the current build.
build_num = request_build.GetBuildNumFromBuilder(
build_request_id, bot_name, builder_host, builder_port)
# Check the status of build using the build number.
# Note: Build is treated as PENDING if build number is not found
# on the the try server.
build_status, status_link = request_build.GetBuildStatus(
build_num, bot_name, builder_host, builder_port)
if build_status == request_build.FAILED:
return (None, 'Failed to produce build, log: %s' % status_link)
elapsed_time = time.time() - start_time
if elapsed_time > max_timeout:
return (None, 'Timed out: %ss without build' % max_timeout)
print 'Time elapsed: %ss without build.' % elapsed_time
time.sleep(poll_interval)
# For some reason, mac bisect bots were not flushing stdout periodically.
# As a result buildbot command is timed-out. Flush stdout on all platforms
# while waiting for build.
sys.stdout.flush()
def _UpdateV8Branch(deps_content):
"""Updates V8 branch in DEPS file to process v8_bleeding_edge.
Check for "v8_branch" in DEPS file if exists update its value
with v8_bleeding_edge branch. Note: "v8_branch" is added to DEPS
variable from DEPS revision 254916, therefore check for "src/v8":
<v8 source path> in DEPS in order to support prior DEPS revisions
and update it.
Args:
deps_content: DEPS file contents to be modified.
Returns:
Modified DEPS file contents as a string.
"""
new_branch = r'branches/bleeding_edge'
v8_branch_pattern = re.compile(r'(?<="v8_branch": ")(.*)(?=")')
if re.search(v8_branch_pattern, deps_content):
deps_content = re.sub(v8_branch_pattern, new_branch, deps_content)
else:
# Replaces the branch assigned to "src/v8" key in DEPS file.
# Format of "src/v8" in DEPS:
# "src/v8":
# (Var("googlecode_url") % "v8") + "/trunk@" + Var("v8_revision"),
# So, "/trunk@" is replace with "/branches/bleeding_edge@"
v8_src_pattern = re.compile(
r'(?<="v8"\) \+ "/)(.*)(?=@" \+ Var\("v8_revision"\))', re.MULTILINE)
if re.search(v8_src_pattern, deps_content):
deps_content = re.sub(v8_src_pattern, new_branch, deps_content)
return deps_content
def _UpdateDEPSForAngle(revision, depot, deps_file):
"""Updates DEPS file with new revision for Angle repository.
This is a hack for Angle depot case because, in DEPS file "vars" dictionary
variable contains "angle_revision" key that holds git hash instead of
SVN revision.
And sometimes "angle_revision" key is not specified in "vars" variable,
in such cases check "deps" dictionary variable that matches
angle.git@[a-fA-F0-9]{40}$ and replace git hash.
"""
deps_var = DEPOT_DEPS_NAME[depot]['deps_var']
try:
deps_contents = ReadStringFromFile(deps_file)
# Check whether the depot and revision pattern in DEPS file vars variable
# e.g. "angle_revision": "fa63e947cb3eccf463648d21a05d5002c9b8adfa".
angle_rev_pattern = re.compile(r'(?<="%s": ")([a-fA-F0-9]{40})(?=")' %
deps_var, re.MULTILINE)
match = re.search(angle_rev_pattern % deps_var, deps_contents)
if match:
# Update the revision information for the given depot
new_data = re.sub(angle_rev_pattern, revision, deps_contents)
else:
# Check whether the depot and revision pattern in DEPS file deps
# variable. e.g.,
# "src/third_party/angle": Var("chromium_git") +
# "/angle/angle.git@fa63e947cb3eccf463648d21a05d5002c9b8adfa",.
angle_rev_pattern = re.compile(
r'(?<=angle\.git@)([a-fA-F0-9]{40})(?=")', re.MULTILINE)
match = re.search(angle_rev_pattern, deps_contents)
if not match:
print 'Could not find angle revision information in DEPS file.'
return False
new_data = re.sub(angle_rev_pattern, revision, deps_contents)
# Write changes to DEPS file
WriteStringToFile(new_data, deps_file)
return True
except IOError, e:
print 'Something went wrong while updating DEPS file, %s' % e
return False
def _TryParseHistogramValuesFromOutput(metric, text):
"""Attempts to parse a metric in the format HISTOGRAM <graph: <trace>.
Args:
metric: The metric as a list of [<trace>, <value>] strings.
text: The text to parse the metric values from.
Returns:
A list of floating point numbers found, [] if none were found.
"""
metric_formatted = 'HISTOGRAM %s: %s= ' % (metric[0], metric[1])
text_lines = text.split('\n')
values_list = []
for current_line in text_lines:
if metric_formatted in current_line:
current_line = current_line[len(metric_formatted):]
try:
histogram_values = eval(current_line)
for b in histogram_values['buckets']:
average_for_bucket = float(b['high'] + b['low']) * 0.5
# Extends the list with N-elements with the average for that bucket.
values_list.extend([average_for_bucket] * b['count'])
except Exception:
pass
return values_list
def _TryParseResultValuesFromOutput(metric, text):
"""Attempts to parse a metric in the format RESULT <graph>: <trace>= ...
Args:
metric: The metric as a list of [<trace>, <value>] string pairs.
text: The text to parse the metric values from.
Returns:
A list of floating point numbers found.
"""
# Format is: RESULT <graph>: <trace>= <value> <units>
metric_re = re.escape('RESULT %s: %s=' % (metric[0], metric[1]))
# The log will be parsed looking for format:
# <*>RESULT <graph_name>: <trace_name>= <value>
single_result_re = re.compile(
metric_re + '\s*(?P<VALUE>[-]?\d*(\.\d*)?)')
# The log will be parsed looking for format:
# <*>RESULT <graph_name>: <trace_name>= [<value>,value,value,...]
multi_results_re = re.compile(
metric_re + '\s*\[\s*(?P<VALUES>[-]?[\d\., ]+)\s*\]')
# The log will be parsed looking for format:
# <*>RESULT <graph_name>: <trace_name>= {<mean>, <std deviation>}
mean_stddev_re = re.compile(
metric_re +
'\s*\{\s*(?P<MEAN>[-]?\d*(\.\d*)?),\s*(?P<STDDEV>\d+(\.\d*)?)\s*\}')
text_lines = text.split('\n')
values_list = []
for current_line in text_lines:
# Parse the output from the performance test for the metric we're
# interested in.
single_result_match = single_result_re.search(current_line)
multi_results_match = multi_results_re.search(current_line)
mean_stddev_match = mean_stddev_re.search(current_line)
if (not single_result_match is None and
single_result_match.group('VALUE')):
values_list += [single_result_match.group('VALUE')]
elif (not multi_results_match is None and
multi_results_match.group('VALUES')):
metric_values = multi_results_match.group('VALUES')
values_list += metric_values.split(',')
elif (not mean_stddev_match is None and
mean_stddev_match.group('MEAN')):
values_list += [mean_stddev_match.group('MEAN')]
values_list = [float(v) for v in values_list
if bisect_utils.IsStringFloat(v)]
# If the metric is times/t, we need to sum the timings in order to get
# similar regression results as the try-bots.
metrics_to_sum = [
['times', 't'],
['times', 'page_load_time'],
['cold_times', 'page_load_time'],
['warm_times', 'page_load_time'],
]
if metric in metrics_to_sum:
if values_list:
values_list = [reduce(lambda x, y: float(x) + float(y), values_list)]
return values_list
def _ParseMetricValuesFromOutput(metric, text):
"""Parses output from performance_ui_tests and retrieves the results for
a given metric.
Args:
metric: The metric as a list of [<trace>, <value>] strings.
text: The text to parse the metric values from.
Returns:
A list of floating point numbers found.
"""
metric_values = _TryParseResultValuesFromOutput(metric, text)
if not metric_values:
metric_values = _TryParseHistogramValuesFromOutput(metric, text)
return metric_values
def _GenerateProfileIfNecessary(command_args):
"""Checks the command line of the performance test for dependencies on
profile generation, and runs tools/perf/generate_profile as necessary.
Args:
command_args: Command line being passed to performance test, as a list.
Returns:
False if profile generation was necessary and failed, otherwise True.
"""
if '--profile-dir' in ' '.join(command_args):
# If we were using python 2.7+, we could just use the argparse
# module's parse_known_args to grab --profile-dir. Since some of the
# bots still run 2.6, have to grab the arguments manually.
arg_dict = {}
args_to_parse = ['--profile-dir', '--browser']
for arg_to_parse in args_to_parse:
for i, current_arg in enumerate(command_args):
if arg_to_parse in current_arg:
current_arg_split = current_arg.split('=')
# Check 2 cases, --arg=<val> and --arg <val>
if len(current_arg_split) == 2:
arg_dict[arg_to_parse] = current_arg_split[1]
elif i + 1 < len(command_args):
arg_dict[arg_to_parse] = command_args[i+1]
path_to_generate = os.path.join('tools', 'perf', 'generate_profile')
if arg_dict.has_key('--profile-dir') and arg_dict.has_key('--browser'):
profile_path, profile_type = os.path.split(arg_dict['--profile-dir'])
return not bisect_utils.RunProcess(['python', path_to_generate,
'--profile-type-to-generate', profile_type,
'--browser', arg_dict['--browser'], '--output-dir', profile_path])
return False
return True
def _AddRevisionsIntoRevisionData(revisions, depot, sort, revision_data):
"""Adds new revisions to the revision_data dictionary and initializes them.
Args:
revisions: List of revisions to add.
depot: Depot that's currently in use (src, webkit, etc...)
sort: Sorting key for displaying revisions.
revision_data: A dictionary to add the new revisions into.
Existing revisions will have their sort keys adjusted.
"""
num_depot_revisions = len(revisions)
for _, v in revision_data.iteritems():
if v['sort'] > sort:
v['sort'] += num_depot_revisions
for i in xrange(num_depot_revisions):
r = revisions[i]
revision_data[r] = {
'revision' : r,
'depot' : depot,
'value' : None,
'perf_time' : 0,
'build_time' : 0,
'passed' : '?',
'sort' : i + sort + 1,
}
def _PrintThankYou():
print RESULTS_THANKYOU
def _PrintTableRow(column_widths, row_data):
"""Prints out a row in a formatted table that has columns aligned.
Args:
column_widths: A list of column width numbers.
row_data: A list of items for each column in this row.
"""
assert len(column_widths) == len(row_data)
text = ''
for i in xrange(len(column_widths)):
current_row_data = row_data[i].center(column_widths[i], ' ')
text += ('%%%ds' % column_widths[i]) % current_row_data
print text
def _PrintStepTime(revision_data_sorted):
"""Prints information about how long various steps took.
Args:
revision_data_sorted: The sorted list of revision data dictionaries."""
step_perf_time_avg = 0.0
step_build_time_avg = 0.0
step_count = 0.0
for _, current_data in revision_data_sorted:
if current_data['value']:
step_perf_time_avg += current_data['perf_time']
step_build_time_avg += current_data['build_time']
step_count += 1
if step_count:
step_perf_time_avg = step_perf_time_avg / step_count
step_build_time_avg = step_build_time_avg / step_count
print
print 'Average build time : %s' % datetime.timedelta(
seconds=int(step_build_time_avg))
print 'Average test time : %s' % datetime.timedelta(
seconds=int(step_perf_time_avg))
class DepotDirectoryRegistry(object):
def __init__(self, src_cwd):
self.depot_cwd = {}
for depot in DEPOT_NAMES:
# The working directory of each depot is just the path to the depot, but
# since we're already in 'src', we can skip that part.
path_in_src = DEPOT_DEPS_NAME[depot]['src'][4:]
self.AddDepot(depot, os.path.join(src_cwd, path_in_src))
self.AddDepot('chromium', src_cwd)
self.AddDepot('cros', os.path.join(src_cwd, 'tools', 'cros'))
def AddDepot(self, depot_name, depot_dir):
self.depot_cwd[depot_name] = depot_dir
def GetDepotDir(self, depot_name):
if depot_name in self.depot_cwd:
return self.depot_cwd[depot_name]
else:
assert False, ('Unknown depot [ %s ] encountered. Possibly a new one '
'was added without proper support?' % depot_name)
def ChangeToDepotDir(self, depot_name):
"""Given a depot, changes to the appropriate working directory.
Args:
depot_name: The name of the depot (see DEPOT_NAMES).
"""
os.chdir(self.GetDepotDir(depot_name))
def _PrepareBisectBranch(parent_branch, new_branch):
"""Creates a new branch to submit bisect try job.
Args:
parent_branch: Parent branch to be used to create new branch.
new_branch: New branch name.
"""
current_branch, returncode = bisect_utils.RunGit(
['rev-parse', '--abbrev-ref', 'HEAD'])
if returncode:
raise RunGitError('Must be in a git repository to send changes to trybots.')
current_branch = current_branch.strip()
# Make sure current branch is master.
if current_branch != parent_branch:
output, returncode = bisect_utils.RunGit(['checkout', '-f', parent_branch])
if returncode:
raise RunGitError('Failed to checkout branch: %s.' % output)
# Delete new branch if exists.
output, returncode = bisect_utils.RunGit(['branch', '--list' ])
if new_branch in output:
output, returncode = bisect_utils.RunGit(['branch', '-D', new_branch])
if returncode:
raise RunGitError('Deleting branch failed, %s', output)
# Check if the tree is dirty: make sure the index is up to date and then
# run diff-index.
bisect_utils.RunGit(['update-index', '--refresh', '-q'])
output, returncode = bisect_utils.RunGit(['diff-index', 'HEAD'])
if output:
raise RunGitError('Cannot send a try job with a dirty tree.')
# Create/check out the telemetry-tryjob branch, and edit the configs
# for the tryjob there.
output, returncode = bisect_utils.RunGit(['checkout', '-b', new_branch])
if returncode:
raise RunGitError('Failed to checkout branch: %s.' % output)
output, returncode = bisect_utils.RunGit(
['branch', '--set-upstream-to', parent_branch])
if returncode:
raise RunGitError('Error in git branch --set-upstream-to')
def _BuilderTryjob(git_revision, bot_name, bisect_job_name, patch=None):
"""Attempts to run a tryjob from the current directory.
Args:
git_revision: A Git hash revision.
bot_name: Name of the bisect bot to be used for try job.
bisect_job_name: Bisect try job name.
patch: A DEPS patch (used while bisecting 3rd party repositories).
"""
try:
# Temporary branch for running tryjob.
_PrepareBisectBranch(BISECT_MASTER_BRANCH, BISECT_TRYJOB_BRANCH)
patch_content = '/dev/null'
# Create a temporary patch file, if it fails raise an exception.
if patch:
WriteStringToFile(patch, BISECT_PATCH_FILE)
patch_content = BISECT_PATCH_FILE
try_cmd = ['try',
'-b', bot_name,
'-r', git_revision,
'-n', bisect_job_name,
'--svn_repo=%s' % SVN_REPO_URL,
'--diff=%s' % patch_content
]
# Execute try job to build revision.
output, returncode = bisect_utils.RunGit(try_cmd)
if returncode:
raise RunGitError('Could not execute tryjob: %s.\n Error: %s' % (
'git %s' % ' '.join(try_cmd), output))
print ('Try job successfully submitted.\n TryJob Details: %s\n%s' % (
'git %s' % ' '.join(try_cmd), output))
finally:
# Delete patch file if exists
try:
os.remove(BISECT_PATCH_FILE)
except OSError as e:
if e.errno != errno.ENOENT:
raise
# Checkout master branch and delete bisect-tryjob branch.
bisect_utils.RunGit(['checkout', '-f', BISECT_MASTER_BRANCH])
bisect_utils.RunGit(['branch', '-D', BISECT_TRYJOB_BRANCH])
class BisectPerformanceMetrics(object):
"""This class contains functionality to perform a bisection of a range of
revisions to narrow down where performance regressions may have occurred.
The main entry-point is the Run method.
"""
def __init__(self, source_control, opts):
super(BisectPerformanceMetrics, self).__init__()
self.opts = opts
self.source_control = source_control
# The src directory here is NOT the src/ directory for the repository
# where the bisect script is running from. Instead, it's the src/ directory
# inside the bisect/ directory which is created before running.
self.src_cwd = os.getcwd()
self.depot_registry = DepotDirectoryRegistry(self.src_cwd)
self.cleanup_commands = []
self.warnings = []
self.builder = builder.Builder.FromOpts(opts)
def PerformCleanup(self):
"""Performs cleanup when script is finished."""
os.chdir(self.src_cwd)
for c in self.cleanup_commands:
if c[0] == 'mv':
shutil.move(c[1], c[2])
else:
assert False, 'Invalid cleanup command.'
def GetRevisionList(self, depot, bad_revision, good_revision):
"""Retrieves a list of all the commits between the bad revision and
last known good revision."""
revision_work_list = []
if depot == 'cros':
revision_range_start = good_revision
revision_range_end = bad_revision
cwd = os.getcwd()
self.depot_registry.ChangeToDepotDir('cros')
# Print the commit timestamps for every commit in the revision time
# range. We'll sort them and bisect by that. There is a remote chance that
# 2 (or more) commits will share the exact same timestamp, but it's