blob: 586fb10dbbb326c506313830fa7b1cadf61d758e [file] [log] [blame]
borenet@google.com6b5388e2013-01-23 20:54:29 +00001#!/usr/bin/python
2
3# Copyright (c) 2013 The Chromium Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7
8"""
9submit_try: Submit a try request.
10
11This is a thin wrapper around the try request utilities in depot_tools which
12adds some validation and supports both git and svn.
13"""
14
15
borenet@google.com6b5388e2013-01-23 20:54:29 +000016import httplib
17import json
18import os
rmistry@google.comf5c4fc82013-04-09 11:46:46 +000019import re
borenet@google.comd4ba6e72014-01-08 21:00:30 +000020import shutil
borenet@google.com6b5388e2013-01-23 20:54:29 +000021import subprocess
borenet@google.coma74302d2013-03-18 18:18:26 +000022import svn
borenet@google.com6b5388e2013-01-23 20:54:29 +000023import sys
borenet@google.comd4ba6e72014-01-08 21:00:30 +000024import tempfile
borenet@google.comfe7533e2013-03-11 20:09:40 +000025
epoger@google.comfd040112013-08-20 16:21:55 +000026import buildbot_globals
borenet@google.com6b5388e2013-01-23 20:54:29 +000027
28
29# Alias which can be used to run a try on every builder.
30ALL_BUILDERS = 'all'
rmistry@google.comf5c4fc82013-04-09 11:46:46 +000031# Alias which can be used to run a try on all compile builders.
32COMPILE_BUILDERS = 'compile'
33# Alias which can be used to run a try on all builders that are run in the CQ.
34CQ_BUILDERS = 'cq'
35# Alias which can be used to specify a regex to choose builders.
36REGEX = 'regex'
37
38ALL_ALIASES = [ALL_BUILDERS, COMPILE_BUILDERS, CQ_BUILDERS, REGEX]
borenet@google.com6b5388e2013-01-23 20:54:29 +000039
40# Contact information for the build master.
epoger@google.comc192aa42013-08-21 17:35:59 +000041SKIA_BUILD_MASTER_HOST = str(buildbot_globals.Get('public_master_host'))
42SKIA_BUILD_MASTER_PORT = str(buildbot_globals.Get('public_external_port'))
borenet@google.com6b5388e2013-01-23 20:54:29 +000043
44# All try builders have this suffix.
borenet@google.com99da6012013-05-02 12:14:35 +000045TRYBOT_SUFFIX = '-Trybot'
borenet@google.com6b5388e2013-01-23 20:54:29 +000046
borenet@google.com6b5388e2013-01-23 20:54:29 +000047# String for matching the svn url of the try server inside codereview.settings.
48TRYSERVER_SVN_URL = 'TRYSERVER_SVN_URL: '
49
50# Strings used for matching svn config properties.
borenet@google.coma74302d2013-03-18 18:18:26 +000051URL_STR = 'URL'
52REPO_ROOT_STR = 'Repository Root'
borenet@google.com6b5388e2013-01-23 20:54:29 +000053
54
55def FindDepotTools():
56 """ Find depot_tools on the local machine and return its location. """
57 which_cmd = 'where' if os.name == 'nt' else 'which'
58 cmd = [which_cmd, 'gcl']
59 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
60 if proc.wait() != 0:
61 raise Exception('Couldn\'t find depot_tools in PATH!')
borenet@google.com6c55b512013-01-24 21:38:51 +000062 gcl = proc.communicate()[0].split('\n')[0].rstrip()
borenet@google.com6b5388e2013-01-23 20:54:29 +000063 depot_tools_dir = os.path.dirname(gcl)
64 return depot_tools_dir
65
66
67def GetCheckoutRoot(is_svn=True):
68 """ Determine where the local checkout is rooted.
69
70 is_svn: boolean; whether we're in an SVN checkout. If False, assume we're in
71 a git checkout.
72 """
73 if is_svn:
borenet@google.coma74302d2013-03-18 18:18:26 +000074 repo = svn.Svn(os.curdir)
75 svn_info = repo.GetInfo()
76 url = svn_info.get(URL_STR, None)
77 repo_root = svn_info.get(REPO_ROOT_STR, None)
borenet@google.com6b5388e2013-01-23 20:54:29 +000078 if not url or not repo_root:
79 raise Exception('Couldn\'t find checkout root!')
80 if url == repo_root:
81 return 'svn'
82 return url[len(repo_root)+1:]
83 else:
84 cmd = ['git', 'rev-parse', '--show-toplevel']
85 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
86 stderr=subprocess.STDOUT)
87 if proc.wait() != 0:
88 raise Exception('Couldn\'t find checkout root!')
89 return os.path.basename(proc.communicate()[0])
90
91
92def GetTryRepo():
borenet@google.com6f0f5b42014-01-09 21:41:39 +000093 """Determine the TRYSERVER_SVN_URL from the codereview.settings file."""
94 codereview_settings_file = os.path.join(os.path.dirname(__file__), os.pardir,
95 'codereview.settings')
96 with open(codereview_settings_file) as f:
97 for line in f:
98 if line.startswith(TRYSERVER_SVN_URL):
99 return line[len(TRYSERVER_SVN_URL):].rstrip()
borenet@google.com6b5388e2013-01-23 20:54:29 +0000100 raise Exception('Couldn\'t determine the TRYSERVER_SVN_URL. Make sure it is '
borenet@google.com6f0f5b42014-01-09 21:41:39 +0000101 'defined in the %s file.' % codereview_settings_file)
borenet@google.com6b5388e2013-01-23 20:54:29 +0000102
103
rmistry@google.comf5c4fc82013-04-09 11:46:46 +0000104def RetrieveTrybotList(json_filename):
borenet@google.com6b5388e2013-01-23 20:54:29 +0000105 """ Retrieve the list of known trybots from the build master, stripping
106 TRYBOT_SUFFIX from the name. """
107 trybots = []
108 connection = httplib.HTTPConnection(SKIA_BUILD_MASTER_HOST,
rmistry@google.comf5c4fc82013-04-09 11:46:46 +0000109 SKIA_BUILD_MASTER_PORT)
110 connection.request('GET', '/json/%s' % json_filename)
borenet@google.com6b5388e2013-01-23 20:54:29 +0000111 response = connection.getresponse()
112 builders = json.load(response)
113
114 for builder in builders:
115 if builder.endswith(TRYBOT_SUFFIX):
116 trybots.append(builder[:-len(TRYBOT_SUFFIX)])
117 return trybots
118
119
borenet@google.coma5d621f2013-01-25 20:55:35 +0000120def ValidateArgs(argv, trybots, is_svn=True):
borenet@google.com6b5388e2013-01-23 20:54:29 +0000121 """ Parse and validate command-line arguments. If the arguments are valid,
122 returns a tuple of (<changelist name>, <list of trybots>).
123
124 trybots: A list of the known try builders.
125 """
borenet@google.com6b5388e2013-01-23 20:54:29 +0000126
borenet@google.coma5d621f2013-01-25 20:55:35 +0000127 class CollectedArgs(object):
128 def __init__(self, bots, changelist, revision):
129 self._bots = bots
130 self._changelist = changelist
131 self._revision = revision
132
133 @property
134 def bots(self):
135 for bot in self._bots:
136 yield bot
137
138 @property
139 def changelist(self):
140 return self._changelist
141
142 @property
143 def revision(self):
144 return self._revision
145
146 usage = (
147"""submit_try: Submit a try request.
148submit_try %s--bot <buildername> [<buildername> ...]
149
rmistry@google.comf5c4fc82013-04-09 11:46:46 +0000150-b, --bot Builder(s) or Alias on which to run the try. Required.
151 Allowed aliases: %s
borenet@google.coma5d621f2013-01-25 20:55:35 +0000152-h, --help Show this message.
153-r <revision#> Revision from which to run the try.
rmistry@google.comf5c4fc82013-04-09 11:46:46 +0000154-l, --list_bots List the available try builders and aliases and exit.
155""" % ('<changelist> ' if is_svn else '', ALL_ALIASES))
borenet@google.coma5d621f2013-01-25 20:55:35 +0000156
157 def Error(msg=None):
158 if msg:
159 print msg
160 print usage
161 sys.exit(1)
162
163 using_bots = None
164 changelist = None
165 revision = None
166
167 while argv:
168 arg = argv.pop(0)
169 if arg == '-h' or arg == '--help':
170 Error()
171 elif arg == '-l' or arg == '--list_bots':
borenet@google.com4b897fa2013-12-02 20:27:16 +0000172 format_args = ['\n '.join(sorted(trybots))] + ALL_ALIASES
rmistry@google.comf5c4fc82013-04-09 11:46:46 +0000173 print (
174"""
175submit_try: Available builders:\n %s
176
177Can also use the following aliases to run on groups of builders-
178 %s: Will run against all trybots.
179 %s: Will run against all compile trybots.
180 %s: Will run against the same trybots as the commit queue.
181 %s: You will be prompted to enter a regex to select builders with.
182
183""" % tuple(format_args))
borenet@google.coma5d621f2013-01-25 20:55:35 +0000184 sys.exit(0)
borenet@google.com02009c72013-04-01 17:59:16 +0000185 elif arg == '-b' or arg == '--bot':
borenet@google.coma5d621f2013-01-25 20:55:35 +0000186 if using_bots:
187 Error('--bot specified multiple times.')
188 if len(argv) < 1:
189 Error('You must specify a builder with "--bot".')
190 using_bots = []
191 while argv and not argv[0].startswith('-'):
epoger@google.com50d68622013-04-03 18:35:35 +0000192 for bot in argv.pop(0).split(','):
rmistry@google.comf5c4fc82013-04-09 11:46:46 +0000193 if bot in ALL_ALIASES:
epoger@google.com50d68622013-04-03 18:35:35 +0000194 if using_bots:
rmistry@google.comf5c4fc82013-04-09 11:46:46 +0000195 Error('Cannot specify "%s" with additional builder names or '
196 'aliases.' % bot)
197 if bot == ALL_BUILDERS:
borenet@google.com6fb77562013-07-12 18:11:04 +0000198 are_you_sure = raw_input('Running a try on every bot is very '
199 'expensive. You may be able to get '
200 'enough information by running on a '
201 'smaller set of bots. Are you sure you '
202 'want to run your try job on all of the '
203 'trybots? [y,n]: ')
204 if are_you_sure == 'y':
205 using_bots = trybots
rmistry@google.comf5c4fc82013-04-09 11:46:46 +0000206 elif bot == COMPILE_BUILDERS:
borenet@google.com6fb77562013-07-12 18:11:04 +0000207 using_bots = [t for t in trybots if t.startswith('Build')]
rmistry@google.comf5c4fc82013-04-09 11:46:46 +0000208 elif bot == CQ_BUILDERS:
209 using_bots = RetrieveTrybotList(json_filename='cqtrybots')
210 elif bot == REGEX:
211 while True:
212 regex = raw_input("Enter your trybot regex: ")
213 p = re.compile(regex)
214 using_bots = [t for t in trybots if p.match(t)]
215 print '\n\nTrybots that match your regex:\n%s\n\n' % '\n'.join(
216 using_bots)
217 if raw_input('Re-enter regex? [y,n]: ') == 'n':
218 break
epoger@google.com50d68622013-04-03 18:35:35 +0000219 break
220 else:
221 if not bot in trybots:
222 Error('Unrecognized builder: %s' % bot)
223 using_bots.append(bot)
borenet@google.coma5d621f2013-01-25 20:55:35 +0000224 elif arg == '-r':
225 if len(argv) < 1:
226 Error('You must specify a revision with "-r".')
227 revision = argv.pop(0)
228 else:
229 if changelist or not is_svn:
230 Error('Unknown argument: %s' % arg)
231 changelist = arg
232 if is_svn and not changelist:
233 Error('You must specify a changelist name.')
234 if not using_bots:
235 Error('You must specify one or more builders using --bot.')
236 return CollectedArgs(bots=using_bots, changelist=changelist,
237 revision=revision)
borenet@google.com6b5388e2013-01-23 20:54:29 +0000238
239
240def SubmitTryRequest(args, is_svn=True):
241 """ Submits a try request for the given changelist on the given list of
242 trybots.
243
244 args: Object whose properties are derived from command-line arguments. If
245 is_svn is True, it should contain:
246 - changelist: string; the name of the changelist to try.
247 - bot: list of strings; the names of the try builders to run.
248 - revision: optional, int; the revision number from which to run the try.
249 If is_svn is False, it should contain:
250 - bot: list of strings; the names of the try builders to run.
251 - revision: optional, int; the revision number from which to run the try.
252 is_svn: boolean; are we in an SVN repo?
253 """
borenet@google.coma5d621f2013-01-25 20:55:35 +0000254 botlist = ','.join(['%s%s' % (bot, TRYBOT_SUFFIX) for bot in args.bots])
borenet@google.com6b5388e2013-01-23 20:54:29 +0000255 if is_svn:
borenet@google.com6c55b512013-01-24 21:38:51 +0000256 gcl_cmd = 'gcl.bat' if os.name == 'nt' else 'gcl'
257 try_args = [gcl_cmd, 'try', args.changelist,
258 '--root', GetCheckoutRoot(is_svn),
borenet@google.com6b5388e2013-01-23 20:54:29 +0000259 '--bot', botlist]
260 if args.revision:
261 try_args.extend(['-r', args.revision])
borenet@google.com6c55b512013-01-24 21:38:51 +0000262 print ' '.join(try_args)
263 proc = subprocess.Popen(try_args, stdout=subprocess.PIPE,
264 stderr=subprocess.STDOUT)
265 if proc.wait() != 0:
266 raise Exception('Failed to submit try request: %s' % (
267 proc.communicate()[0]))
268 print proc.communicate()[0]
borenet@google.com6b5388e2013-01-23 20:54:29 +0000269 else:
borenet@google.comd4ba6e72014-01-08 21:00:30 +0000270 # Create the diff file.
271 cmd = ['git.bat' if os.name == 'nt' else 'git', 'diff', 'origin/master']
272 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
273 if proc.wait() != 0:
274 raise Exception('Failed to capture git diff!')
275
276 temp_dir = tempfile.mkdtemp()
277 try:
278 diff_file = os.path.join(temp_dir, 'patch.diff')
279 with open(diff_file, 'wb') as f:
280 f.write(proc.communicate()[0])
281
282 # Find depot_tools. This is needed to import trychange.
283 sys.path.append(FindDepotTools())
284 import trychange
285 try_args = ['--use_svn',
286 '--svn_repo', GetTryRepo(),
287 '--root', GetCheckoutRoot(is_svn),
288 '--bot', botlist,
289 '--diff', diff_file,
290 ]
291 if args.revision:
292 try_args.extend(['-r', args.revision])
293
294 # Submit the try request.
295 trychange.TryChange(try_args, None, False)
296 finally:
297 shutil.rmtree(temp_dir)
borenet@google.com6b5388e2013-01-23 20:54:29 +0000298
299
300def main():
301 # Retrieve the list of active try builders from the build master.
rmistry@google.comf5c4fc82013-04-09 11:46:46 +0000302 trybots = RetrieveTrybotList(json_filename='trybots')
borenet@google.com6b5388e2013-01-23 20:54:29 +0000303
304 # Determine if we're in an SVN checkout.
305 is_svn = os.path.isdir('.svn')
306
307 # Parse and validate the command-line arguments.
borenet@google.coma5d621f2013-01-25 20:55:35 +0000308 args = ValidateArgs(sys.argv[1:], trybots=trybots, is_svn=is_svn)
borenet@google.com6b5388e2013-01-23 20:54:29 +0000309
310 # Submit the try request.
311 SubmitTryRequest(args, is_svn=is_svn)
312
313
314if __name__ == '__main__':
epoger@google.com50d68622013-04-03 18:35:35 +0000315 sys.exit(main())