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