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