blob: ef53d441b55622f3785fc0b8c5a3497ef666ab5a [file] [log] [blame]
Xinan Lin3ba18a02019-08-13 15:44:55 -07001# Copyright 2019 The Chromium OS Authors. All rights reserved.
Xinan Linc61196b2019-08-13 10:37:30 -07002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Module for interacting with Buildbucket."""
Xinan Linc61196b2019-08-13 10:37:30 -07006
Xinan Lin9e4917d2019-11-04 10:58:47 -08007import collections
Xinan Lin3ba18a02019-08-13 15:44:55 -07008import datetime
linxinane5eb4552019-08-26 05:44:45 +00009import logging
Xinan Lin3ba18a02019-08-13 15:44:55 -070010import re
11import string
Xinan Lin081b5d32020-03-23 17:37:55 -070012import uuid
Xinan Lin3ba18a02019-08-13 15:44:55 -070013
Xinan Lindf0698a2020-02-05 22:38:11 -080014import analytics
Xinan Lin3ba18a02019-08-13 15:44:55 -070015import build_lib
Xinan Linc61196b2019-08-13 10:37:30 -070016import constants
17import file_getter
18
19from chromite.api.gen.test_platform import request_pb2
Xinan Linc61196b2019-08-13 10:37:30 -070020from components import auth
Xinan Lin3ba18a02019-08-13 15:44:55 -070021from components.prpc import client as prpc_client
Prathmesh Prabhu2382a182019-09-07 21:18:10 -070022from infra_libs.buildbucket.proto import common_pb2 as bb_common_pb2
Xinan Lin3ba18a02019-08-13 15:44:55 -070023from infra_libs.buildbucket.proto import rpc_pb2, build_pb2
Xinan Linc61196b2019-08-13 10:37:30 -070024from infra_libs.buildbucket.proto.rpc_prpc_pb2 import BuildsServiceDescription
25
26from oauth2client import service_account
Xinan Lin3ba18a02019-08-13 15:44:55 -070027
28from google.protobuf import json_format, struct_pb2
Xinan Linc61196b2019-08-13 10:37:30 -070029
30
Xinan Lin3ba18a02019-08-13 15:44:55 -070031_enum = request_pb2.Request.Params.Scheduling
Xinan Linc61196b2019-08-13 10:37:30 -070032NONSTANDARD_POOL_NAMES = {
Xinan Lin3ba18a02019-08-13 15:44:55 -070033 'cq': _enum.MANAGED_POOL_CQ,
34 'bvt': _enum.MANAGED_POOL_BVT,
35 'suites': _enum.MANAGED_POOL_SUITES,
36 'cts': _enum.MANAGED_POOL_CTS,
37 'cts-perbuild': _enum.MANAGED_POOL_CTS_PERBUILD,
38 'continuous': _enum.MANAGED_POOL_CONTINUOUS,
39 'arc-presubmit': _enum.MANAGED_POOL_ARC_PRESUBMIT,
40 'quota': _enum.MANAGED_POOL_QUOTA,
Xinan Linc61196b2019-08-13 10:37:30 -070041}
42
Xinan Lin3ba18a02019-08-13 15:44:55 -070043
Xinan Lin6e097382019-08-27 18:43:35 -070044GS_PREFIX = 'gs://chromeos-image-archive/'
45
46
Xinan Lin57e2d962020-03-30 17:24:53 -070047# The default prpc timeout(10 sec) is too short for the request_id
48# to propgate in buildbucket, and could not fully dedup the
49# ScheduleBuild request. Increase it while not hitting the default
50# GAE deadline(60 sec)
51PRPC_TIMEOUT_SEC = 55
52
53
Xinan Linc61196b2019-08-13 10:37:30 -070054def _get_client(address):
55 """Create a prpc client instance for given address."""
56 return prpc_client.Client(address, BuildsServiceDescription)
57
58
Xinan Lin3ba18a02019-08-13 15:44:55 -070059class BuildbucketRunError(Exception):
60 """Raised when interactions with buildbucket server fail."""
61
62
Xinan Linc61196b2019-08-13 10:37:30 -070063class TestPlatformClient(object):
64 """prpc client for cros_test_platform, aka frontdoor."""
65
66 def __init__(self, address, project, bucket, builder):
67 self.client = _get_client(address)
68 self.builder = build_pb2.BuilderID(project=project,
69 bucket=bucket,
70 builder=builder)
71 self.scope = 'https://www.googleapis.com/auth/userinfo.email'
72 self.running_env = constants.environment()
73
Xinan Lin9e4917d2019-11-04 10:58:47 -080074 def multirequest_run(self, tasks, suite):
75 """Call TestPlatform Builder to schedule a batch of tests.
Xinan Lin3ba18a02019-08-13 15:44:55 -070076
77 Args:
Xinan Lin9e4917d2019-11-04 10:58:47 -080078 tasks: The suite tasks to run.
79 suite: suite name for the batch request.
80
81 Returns:
82 List of executed tasks.
Xinan Lin3ba18a02019-08-13 15:44:55 -070083
84 Raises:
85 BuildbucketRunError: if failed to get build info from task parameters.
86 """
Xinan Lin9e4917d2019-11-04 10:58:47 -080087 requests = []
88 executed_tasks = []
89 counter = collections.defaultdict(int)
Xinan Lindf0698a2020-02-05 22:38:11 -080090 task_executions = []
Xinan Lin9e4917d2019-11-04 10:58:47 -080091 for task in tasks:
92 try:
93 params = task.extract_params()
94 req = _form_test_platform_request(params)
Xinan Linc54a7462020-04-17 15:39:01 -070095 if _should_skip(params):
96 continue
Xinan Lin9e4917d2019-11-04 10:58:47 -080097 req_json = json_format.MessageToJson(req)
98 counter_key = params['board']
99 counter_key += '' if params['model'] in [None, 'None'] else (
100 '_' + params['model'])
101 counter[counter_key] += 1
102 req_name = counter_key
103 if counter[counter_key] > 1:
104 req_name += '_' + str(counter[counter_key] - 1)
105 requests.append('"%s": %s' % (req_name, req_json))
106 executed_tasks.append(task)
Xinan Lin083ba8f2020-02-06 13:55:18 -0800107 if params.get('task_id'):
Xinan Lindf0698a2020-02-05 22:38:11 -0800108 task_executions.append(analytics.ExecutionTask(params['task_id']))
Xinan Lin9e4917d2019-11-04 10:58:47 -0800109 except (ValueError, BuildbucketRunError):
110 logging.debug('Failed to process task: %r', params)
111 if not requests:
112 return []
113 try:
114 requests_json = '{ "requests": { %s } }' % ', '.join(requests)
115 req_build = self._build_request(requests_json,
116 _suite_bb_tag(suite))
117 logging.debug('Raw request to buildbucket: %r', req_build)
linxinane5eb4552019-08-26 05:44:45 +0000118
Xinan Lin9e4917d2019-11-04 10:58:47 -0800119 if (self.running_env == constants.RunningEnv.ENV_STANDALONE or
120 self.running_env == constants.RunningEnv.ENV_DEVELOPMENT_SERVER):
121 # If running locally, use the staging service account.
122 sa_key = self._gen_service_account_key(
123 file_getter.STAGING_CLIENT_SECRETS_FILE)
124 cred = prpc_client.service_account_credentials(
125 service_account_key=sa_key)
126 else:
127 cred = prpc_client.service_account_credentials()
128 #TODO(linxinan): only add the tasks returned from bb to executed_tasks.
Xinan Lin57e2d962020-03-30 17:24:53 -0700129 resp = self.client.ScheduleBuild(
130 req_build, credentials=cred, timeout=PRPC_TIMEOUT_SEC)
Xinan Lin9e4917d2019-11-04 10:58:47 -0800131 logging.debug('Response from buildbucket: %r', resp)
Xinan Lindf0698a2020-02-05 22:38:11 -0800132 for t in task_executions:
133 t.update_result(resp)
134 try:
135 if not t.upload():
136 logging.warning('Failed to insert row: %r', t)
137 # For any exceptions from BQ, only log it.
138 except Exception as e: #pylint: disable=broad-except
139 logging.exception('Failed to insert row: %r, got error: %s',
140 t, str(e))
Xinan Lin9e4917d2019-11-04 10:58:47 -0800141 return executed_tasks
142 except Exception as e:
143 logging.debug('Failed to process tasks: %r', tasks)
144 logging.exception(str(e))
145 return []
Xinan Lin3ba18a02019-08-13 15:44:55 -0700146
Xinan Linc61196b2019-08-13 10:37:30 -0700147 def dummy_run(self):
148 """Perform a dummy run of prpc call to cros_test_platform-dev."""
149
Xinan Lin9e4917d2019-11-04 10:58:47 -0800150 requests_json = '{ "requests": { "dummy": {} } }'
151 req_build = self._build_request(requests_json, tags=None)
Xinan Linc61196b2019-08-13 10:37:30 -0700152 # Use the staging service account to authorize the request.
153 sa_key = self._gen_service_account_key(
154 file_getter.STAGING_CLIENT_SECRETS_FILE)
155 cred = prpc_client.service_account_credentials(service_account_key=sa_key)
Xinan Lin57e2d962020-03-30 17:24:53 -0700156 return self.client.ScheduleBuild(
157 req_build, credentials=cred, timeout=PRPC_TIMEOUT_SEC)
Xinan Linc61196b2019-08-13 10:37:30 -0700158
Xinan Lin9e4917d2019-11-04 10:58:47 -0800159 def _build_request(self, reqs_json, tags):
Xinan Lin3ba18a02019-08-13 15:44:55 -0700160 """Generate ScheduleBuildRequest for calling buildbucket.
Xinan Linc61196b2019-08-13 10:37:30 -0700161
Xinan Lin3ba18a02019-08-13 15:44:55 -0700162 Args:
Xinan Lin9e4917d2019-11-04 10:58:47 -0800163 reqs_json: A json string of requests.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700164 tags: A list of tags for the buildbucket build.
Xinan Linc61196b2019-08-13 10:37:30 -0700165
Xinan Lin3ba18a02019-08-13 15:44:55 -0700166 Returns:
167 A ScheduleBuildRequest instance.
168 """
Xinan Lin9e4917d2019-11-04 10:58:47 -0800169 requests_struct = struct_pb2.Struct()
170 recipe_struct = json_format.Parse(reqs_json, requests_struct)
Xinan Linc61196b2019-08-13 10:37:30 -0700171 return rpc_pb2.ScheduleBuildRequest(builder=self.builder,
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700172 properties=recipe_struct,
Xinan Lin081b5d32020-03-23 17:37:55 -0700173 request_id=str(uuid.uuid1()),
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700174 tags=tags)
Xinan Linc61196b2019-08-13 10:37:30 -0700175
176 def _gen_service_account_key(self, sa):
Xinan Lin3ba18a02019-08-13 15:44:55 -0700177 """Generate credentials to authorize the call.
Xinan Linc61196b2019-08-13 10:37:30 -0700178
Xinan Lin3ba18a02019-08-13 15:44:55 -0700179 Args:
180 sa: A string of the path to the service account json file.
Xinan Linc61196b2019-08-13 10:37:30 -0700181
Xinan Lin3ba18a02019-08-13 15:44:55 -0700182 Returns:
183 A service account key.
184 """
Xinan Linc61196b2019-08-13 10:37:30 -0700185 service_credentials = service_account.ServiceAccountCredentials
Xinan Lin3ba18a02019-08-13 15:44:55 -0700186 key = service_credentials.from_json_keyfile_name(sa, self.scope)
Xinan Linc61196b2019-08-13 10:37:30 -0700187 return auth.ServiceAccountKey(
188 client_email=key.service_account_email,
189 private_key=key._private_key_pkcs8_pem,
190 private_key_id=key._private_key_id)
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700191
192
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700193def _form_test_platform_request(task_params):
194 """Generate ScheduleBuildRequest for calling buildbucket.
195
196 Args:
197 task_params: dict containing the parameters of a task got from suite
198 queue.
199
200 Returns:
201 A request_pb2 instance.
202 """
203 build = _infer_build_from_task_params(task_params)
204 if build == 'None':
205 raise BuildbucketRunError('No proper build in task params: %r' %
206 task_params)
207 pool = _infer_pool_from_task_params(task_params)
208 timeout = _infer_timeout_from_task_params(task_params)
209
210 request = request_pb2.Request()
211 params = request.params
212
Xinan Lin4757d6f2020-03-24 22:20:31 -0700213 params.scheduling.CopyFrom(_scheduling_for_pool(pool))
214 if (task_params.get('qs_account') not in ['None', None]
215 and params.scheduling.unmanaged_pool):
216 params.scheduling.qs_account = task_params.get('qs_account')
217 # Quota Scheduler has no concept of priority.
218 if 'priority' in task_params and not params.scheduling.qs_account:
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700219 params.scheduling.priority = int(task_params['priority'])
220
221 params.software_dependencies.add().chromeos_build = build
222 params.software_attributes.build_target.name = task_params['board']
Aviv Keshetc679faf2019-11-27 17:52:50 -0800223
224 gs_url = GS_PREFIX + task_params['test_source_build']
225 params.metadata.test_metadata_url = gs_url
226 params.metadata.debug_symbols_archive_url = gs_url
227
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700228 params.time.maximum_duration.FromTimedelta(timeout)
229
230 for key, value in _request_tags(task_params, build, pool).iteritems():
231 params.decorations.tags.append('%s:%s' % (key, value))
232
233 if task_params['model'] != 'None':
234 params.hardware_attributes.model = task_params['model']
235
236 if task_params['job_retry'] == 'True':
237 params.retry.allow = True
238 params.retry.max = constants.Buildbucket.MAX_RETRY
239
240 fw_rw_build = task_params.get(build_lib.BuildVersionKey.FW_RW_VERSION)
241 fw_ro_build = task_params.get(build_lib.BuildVersionKey.FW_RO_VERSION)
242 # Skip firmware field if None(unspecified) or 'None'(no such build).
243 if fw_ro_build not in (None, 'None'):
244 build = params.software_dependencies.add()
245 build.ro_firmware_build = fw_ro_build
246 if fw_rw_build not in (None, 'None'):
247 build = params.software_dependencies.add()
248 build.rw_firmware_build = fw_rw_build
249
250 request.test_plan.suite.add().name = task_params['suite']
251 return request
252
253
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700254def _scheduling_for_pool(pool):
255 """Assign appropriate pool name to scheduling instance.
256
257 Args:
258 pool: string pool name (e.g. 'bvt', 'quota').
259
260 Returns:
261 scheduling: A request_pb2.Request.Params.Scheduling instance.
262 """
263 mp = request_pb2.Request.Params.Scheduling.ManagedPool
264 if mp.DESCRIPTOR.values_by_name.get(pool) is not None:
265 return request_pb2.Request.Params.Scheduling(managed_pool=mp.Value(pool))
266
267 DUT_POOL_PREFIX = r'DUT_POOL_(?P<munged_pool>.+)'
268 match = re.match(DUT_POOL_PREFIX, pool)
269 if match:
270 pool = string.lower(match.group('munged_pool'))
271 if NONSTANDARD_POOL_NAMES.get(pool):
Xinan Lin9e4917d2019-11-04 10:58:47 -0800272 return request_pb2.Request.Params.Scheduling(
273 managed_pool=NONSTANDARD_POOL_NAMES.get(pool))
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700274 return request_pb2.Request.Params.Scheduling(unmanaged_pool=pool)
275
276
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700277# Also see: A copy of this function in swarming_lib.py.
278def _infer_build_from_task_params(task_params):
279 """Infer the build to install on the DUT for the scheduled task.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700280
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700281 Args:
282 task_params: The parameters of a task loaded from suite queue.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700283
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700284 Returns:
285 A string representing the build to run.
286 """
287 cros_build = task_params[build_lib.BuildVersionKey.CROS_VERSION]
288 android_build = task_params[build_lib.BuildVersionKey.ANDROID_BUILD_VERSION]
289 testbed_build = task_params[build_lib.BuildVersionKey.TESTBED_BUILD_VERSION]
290 return cros_build or android_build or testbed_build
291
292
293def _infer_pool_from_task_params(task_params):
294 """Infer the pool to use for the scheduled task.
295
296 Args:
297 task_params: The parameters of a task loaded from suite queue.
298
299 Returns:
300 A string pool to schedule task in.
301 """
302 if task_params.get('override_qs_account'):
303 return 'DUT_POOL_QUOTA'
304 return task_params.get('override_pool') or task_params['pool']
305
306
307def _infer_timeout_from_task_params(task_params):
308 """Infer the timeout for the scheduled task.
309
310 Args:
311 task_params: The parameters of a task loaded from suite queue.
312
313 Returns:
314 A datetime.timedelta instance for the timeout.
315 """
316 timeout_mins = int(task_params['timeout_mins'])
317 # timeout's unit is hour.
318 if task_params.get('timeout'):
319 timeout_mins = max(int(task_params['timeout'])*60, timeout_mins)
320 if timeout_mins > constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS:
321 timeout_mins = constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS
322 return datetime.timedelta(minutes=timeout_mins)
323
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700324
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700325def _request_tags(task_params, build, pool):
326 """Infer tags to include in cros_test_platform request.
327
328 Args:
329 task_params: suite task parameters.
330 build: The build included in the request. Must not be None.
331 pool: The DUT pool used for the request. Must not be None.
332
333 Returns:
334 A dict of tags.
335 """
336 tags = {
337 'build': build,
338 'label-pool': pool,
339 }
Xinan Linfb63d572019-09-24 15:49:04 -0700340 if task_params.get('board') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700341 tags['label-board'] = task_params['board']
Xinan Linfb63d572019-09-24 15:49:04 -0700342 if task_params.get('model') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700343 tags['label-model'] = task_params['model']
Xinan Linfb63d572019-09-24 15:49:04 -0700344 if task_params.get('suite') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700345 tags['suite'] = task_params['suite']
Xinan Linc8647112020-02-04 16:45:56 -0800346 # Add user configured dimensions.
347 if task_params.get('dimensions') not in (None, 'None'):
348 for label in task_params.get('dimensions').split(','):
349 key, value = _get_key_val_from_label(label)
350 if all([key, value]) and not key in tags:
351 tags[key] = value
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700352 return tags
353
354
Xinan Linc8647112020-02-04 16:45:56 -0800355def _get_key_val_from_label(label):
356 """A helper to get key and value from the label.
357
358 Args:
359 label: A string of label, should be in the form of
360 key:value, e.g. 'pool:ChromeOSSkylab'.
361 """
362 res = label.split(':')
363 if len(res) == 2:
364 return res[0], res[1]
365 logging.warning('Failed to parse the label, %s', label)
366
367
Xinan Lin9e4917d2019-11-04 10:58:47 -0800368def _suite_bb_tag(suite):
369 """Convert suite name to a buildbucket tag.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700370
371 Args:
372 request: A request_pb2.Request.
373
374 Returns:
375 [bb_common_pb2.StringPair] tags to include the buildbucket request.
376 """
Xinan Lin9e4917d2019-11-04 10:58:47 -0800377 return [bb_common_pb2.StringPair(key='suite', value=suite)]
Xinan Linc54a7462020-04-17 15:39:01 -0700378
379
380def _should_skip(params):
381 """Decide whether to skip a task based on env and pool.
382
383 Suite request from staging may still have a small chance to run
384 in production. However, for unmanaged pools(e.g. wificell), which
385 usually are small, dev traffic is unacceptable.
386
387 Args:
388 params: dict containing the parameters of a task got from suite
389 queue.
390
391 Returns:
392 A boolean; true for suite targetting non-default pools from staging
393 env.
394 """
395 if constants.application_id() == constants.AppID.PROD_APP:
396 return False
397 return params['pool'] != 'suites'