run_benchmark should have an option to specify the number of runs
[WebKit-https.git] / Tools / Scripts / webkitpy / benchmark_runner / benchmark_runner.py
1 #!/usr/bin/env python
2
3 import json
4 import logging
5 import shutil
6 import signal
7 import subprocess
8 import tempfile
9 import time
10 import types
11 import os
12 import urlparse
13
14 from benchmark_builder.benchmark_builder_factory import BenchmarkBuilderFactory
15 from browser_driver.browser_driver_factory import BrowserDriverFactory
16 from http_server_driver.http_server_driver_factory import HTTPServerDriverFactory
17 from utils import loadModule, getPathFromProjectRoot
18 from utils import timeout
19
20
21 _log = logging.getLogger(__name__)
22
23
24 class BenchmarkRunner(object):
25
26     def __init__(self, planFile, localCopy, countOverride, buildDir, outputFile, platform, browser):
27         _log.info('Initializing benchmark running')
28         try:
29             planFile = self._findPlanFile(planFile)
30             with open(planFile, 'r') as fp:
31                 self.planName = os.path.split(os.path.splitext(planFile)[0])[1]
32                 self.plan = json.load(fp)
33                 if localCopy:
34                     self.plan['local_copy'] = localCopy
35                 if countOverride:
36                     self.plan['count'] = countOverride
37                 self.browserDriver = BrowserDriverFactory.create([platform, browser])
38                 self.httpServerDriver = HTTPServerDriverFactory.create([self.plan['http_server_driver']])
39                 self.buildDir = os.path.abspath(buildDir) if buildDir else None
40                 self.outputFile = outputFile
41         except IOError:
42             _log.error('Can not open plan file: %s' % planFile)
43             raise
44         except ValueError:
45             _log.error('Plan file:%s may not follow JSON format' % planFile)
46             raise
47
48     def _findPlanFile(self, planFile):
49         if not os.path.exists(planFile):
50             absPath = os.path.join(os.path.dirname(__file__), 'data/plans', planFile)
51             if os.path.exists(absPath):
52                 return absPath
53             if not absPath.endswith('.plan'):
54                 absPath += '.plan'
55             if os.path.exists(absPath):
56                 return absPath
57         return planFile
58
59     def execute(self):
60         _log.info('Start to execute the plan')
61         _log.info('Start a new benchmark')
62         results = []
63         benchmarkBuilder = BenchmarkBuilderFactory.create([self.plan['benchmark_builder']])
64
65         if not self.plan.get('local_copy') and not self.plan.get('remote_archive'):
66             _log.error('Either local_copy or remote_archive must be specified in the plan')
67             return 2
68
69         webRoot = benchmarkBuilder.prepare(self.planName, self.plan.get('local_copy'), self.plan.get('remote_archive'),
70             self.plan.get('benchmark_patch'), self.plan.get('create_script'))
71         for x in xrange(int(self.plan['count'])):
72             _log.info('Start the iteration %d of current benchmark' % (x + 1))
73             self.httpServerDriver.serve(webRoot)
74             self.browserDriver.prepareEnv()
75             url = urlparse.urljoin(self.httpServerDriver.baseUrl(), self.planName + '/' + self.plan['entry_point'])
76             self.browserDriver.launchUrl(url, self.buildDir)
77             try:
78                 with timeout(self.plan['timeout']):
79                     result = json.loads(self.httpServerDriver.fetchResult())
80                 assert(not self.httpServerDriver.getReturnCode())
81                 assert(result)
82                 results.append(result)
83             except:
84                 _log.error('No result or server crashes. Something went wrong. Will skip current benchmark.')
85                 self.browserDriver.closeBrowsers()
86                 self.httpServerDriver.killServer()
87                 benchmarkBuilder.clean()
88                 return 1
89             finally:
90                 self.browserDriver.closeBrowsers()
91                 _log.info('End of %d iteration of current benchmark' % (x + 1))
92         results = self.wrap(results)
93         self.dump(results, self.outputFile if self.outputFile else self.plan['output_file'])
94         benchmarkBuilder.clean()
95         return 0
96
97     @classmethod
98     def dump(cls, results, outputFile):
99         _log.info('Dumping the results to file')
100         try:
101             with open(outputFile, 'w') as fp:
102                 json.dump(results, fp)
103         except IOError:
104             _log.error('Cannot open output file: %s' % outputFile)
105             _log.error('Results are:\n %s', json.dumps(results))
106
107     @classmethod
108     def wrap(cls, dicts):
109         _log.info('Merging following results:\n%s', json.dumps(dicts))
110         if not dicts:
111             return None
112         ret = {}
113         for dic in dicts:
114             ret = cls.merge(ret, dic)
115         _log.info('Results after merging:\n%s', json.dumps(ret))
116         return ret
117
118     @classmethod
119     def merge(cls, a, b):
120         assert(isinstance(a, type(b)))
121         argType = type(a)
122         # special handle for list type, and should be handle before equal check
123         if argType == types.ListType and len(a) and (type(a[0]) == types.StringType or type(a[0]) == types.UnicodeType):
124             return a
125         if argType == types.DictType:
126             result = {}
127             for key, value in a.items():
128                 if key in b:
129                     result[key] = cls.merge(value, b[key])
130                 else:
131                     result[key] = value
132             for key, value in b.items():
133                 if key not in result:
134                     result[key] = value
135             return result
136         # for other types
137         return a + b