179287d7a20b38304deddc10016cd848ccd641a0
[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, 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.plan = json.load(fp)
32                 self.browserDriver = BrowserDriverFactory.create([platform, browser])
33                 self.httpServerDriver = HTTPServerDriverFactory.create([self.plan['http_server_driver']])
34                 self.buildDir = os.path.abspath(buildDir) if buildDir else None
35                 self.outputFile = outputFile
36         except IOError:
37             _log.error('Can not open plan file: %s' % planFile)
38             raise
39         except ValueError:
40             _log.error('Plan file:%s may not follow JSON format' % planFile)
41             raise
42
43     def _findPlanFile(self, planFile):
44         if not os.path.exists(planFile):
45             absPath = os.path.join(os.path.dirname(__file__), 'data/plans', planFile)
46             if os.path.exists(absPath):
47                 return absPath
48             if not absPath.endswith('.plan'):
49                 absPath += '.plan'
50             if os.path.exists(absPath):
51                 return absPath
52         return planFile
53
54     def execute(self):
55         _log.info('Start to execute the plan')
56         _log.info('Start a new benchmark')
57         results = []
58         benchmarkBuilder = BenchmarkBuilderFactory.create([self.plan['benchmark_builder']])
59         webRoot = benchmarkBuilder.prepare(self.plan['original_benchmark'], self.plan['benchmark_patch'] if 'benchmark_patch' in self.plan else None)
60         for x in xrange(int(self.plan['count'])):
61             _log.info('Start the iteration %d of current benchmark' % (x + 1))
62             self.httpServerDriver.serve(webRoot)
63             self.browserDriver.prepareEnv()
64             self.browserDriver.launchUrl(urlparse.urljoin(self.httpServerDriver.baseUrl(), self.plan['entry_point']), self.buildDir)
65             try:
66                 with timeout(self.plan['timeout']):
67                     result = json.loads(self.httpServerDriver.fetchResult())
68                 assert(not self.httpServerDriver.getReturnCode())
69                 assert(result)
70                 results.append(result)
71             except:
72                 _log.error('No result or server crashes. Something went wrong. Will skip current benchmark.')
73                 self.browserDriver.closeBrowsers()
74                 self.httpServerDriver.killServer()
75                 benchmarkBuilder.clean()
76                 return 1
77             finally:
78                 self.browserDriver.closeBrowsers()
79                 _log.info('End of %d iteration of current benchmark' % (x + 1))
80         results = self.wrap(results)
81         self.dump(results, self.outputFile if self.outputFile else self.plan['output_file'])
82         benchmarkBuilder.clean()
83         return 0
84
85     @classmethod
86     def dump(cls, results, outputFile):
87         _log.info('Dumping the results to file')
88         try:
89             with open(outputFile, 'w') as fp:
90                 json.dump(results, fp)
91         except IOError:
92             _log.error('Cannot open output file: %s' % outputFile)
93             _log.error('Results are:\n %s', json.dumps(results))
94
95     @classmethod
96     def wrap(cls, dicts):
97         _log.info('Merging following results:\n%s', json.dumps(dicts))
98         if not dicts:
99             return None
100         ret = {}
101         for dic in dicts:
102             ret = cls.merge(ret, dic)
103         _log.info('Results after merging:\n%s', json.dumps(ret))
104         return ret
105
106     @classmethod
107     def merge(cls, a, b):
108         assert(isinstance(a, type(b)))
109         argType = type(a)
110         # special handle for list type, and should be handle before equal check
111         if argType == types.ListType and len(a) and (type(a[0]) == types.StringType or type(a[0]) == types.UnicodeType):
112             return a
113         if argType == types.DictType:
114             result = {}
115             for key, value in a.items():
116                 if key in b:
117                     result[key] = cls.merge(value, b[key])
118                 else:
119                     result[key] = value
120             for key, value in b.items():
121                 if key not in result:
122                     result[key] = value
123             return result
124         # for other types
125         return a + b