blob: ee515e60255ca5482de0bd922af1611c6717b120 [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)
95 req_json = json_format.MessageToJson(req)
96 counter_key = params['board']
97 counter_key += '' if params['model'] in [None, 'None'] else (
98 '_' + params['model'])
99 counter[counter_key] += 1
100 req_name = counter_key
101 if counter[counter_key] > 1:
102 req_name += '_' + str(counter[counter_key] - 1)
103 requests.append('"%s": %s' % (req_name, req_json))
104 executed_tasks.append(task)
Xinan Lin083ba8f2020-02-06 13:55:18 -0800105 if params.get('task_id'):
Xinan Lindf0698a2020-02-05 22:38:11 -0800106 task_executions.append(analytics.ExecutionTask(params['task_id']))
Xinan Lin9e4917d2019-11-04 10:58:47 -0800107 except (ValueError, BuildbucketRunError):
108 logging.debug('Failed to process task: %r', params)
109 if not requests:
110 return []
111 try:
112 requests_json = '{ "requests": { %s } }' % ', '.join(requests)
113 req_build = self._build_request(requests_json,
114 _suite_bb_tag(suite))
115 logging.debug('Raw request to buildbucket: %r', req_build)
linxinane5eb4552019-08-26 05:44:45 +0000116
Xinan Lin9e4917d2019-11-04 10:58:47 -0800117 if (self.running_env == constants.RunningEnv.ENV_STANDALONE or
118 self.running_env == constants.RunningEnv.ENV_DEVELOPMENT_SERVER):
119 # If running locally, use the staging service account.
120 sa_key = self._gen_service_account_key(
121 file_getter.STAGING_CLIENT_SECRETS_FILE)
122 cred = prpc_client.service_account_credentials(
123 service_account_key=sa_key)
124 else:
125 cred = prpc_client.service_account_credentials()
126 #TODO(linxinan): only add the tasks returned from bb to executed_tasks.
Xinan Lin57e2d962020-03-30 17:24:53 -0700127 resp = self.client.ScheduleBuild(
128 req_build, credentials=cred, timeout=PRPC_TIMEOUT_SEC)
Xinan Lin9e4917d2019-11-04 10:58:47 -0800129 logging.debug('Response from buildbucket: %r', resp)
Xinan Lindf0698a2020-02-05 22:38:11 -0800130 for t in task_executions:
131 t.update_result(resp)
132 try:
133 if not t.upload():
134 logging.warning('Failed to insert row: %r', t)
135 # For any exceptions from BQ, only log it.
136 except Exception as e: #pylint: disable=broad-except
137 logging.exception('Failed to insert row: %r, got error: %s',
138 t, str(e))
Xinan Lin9e4917d2019-11-04 10:58:47 -0800139 return executed_tasks
140 except Exception as e:
141 logging.debug('Failed to process tasks: %r', tasks)
142 logging.exception(str(e))
143 return []
Xinan Lin3ba18a02019-08-13 15:44:55 -0700144
Xinan Linc61196b2019-08-13 10:37:30 -0700145 def dummy_run(self):
146 """Perform a dummy run of prpc call to cros_test_platform-dev."""
147
Xinan Lin9e4917d2019-11-04 10:58:47 -0800148 requests_json = '{ "requests": { "dummy": {} } }'
149 req_build = self._build_request(requests_json, tags=None)
Xinan Linc61196b2019-08-13 10:37:30 -0700150 # Use the staging service account to authorize the request.
151 sa_key = self._gen_service_account_key(
152 file_getter.STAGING_CLIENT_SECRETS_FILE)
153 cred = prpc_client.service_account_credentials(service_account_key=sa_key)
Xinan Lin57e2d962020-03-30 17:24:53 -0700154 return self.client.ScheduleBuild(
155 req_build, credentials=cred, timeout=PRPC_TIMEOUT_SEC)
Xinan Linc61196b2019-08-13 10:37:30 -0700156
Xinan Lin9e4917d2019-11-04 10:58:47 -0800157 def _build_request(self, reqs_json, tags):
Xinan Lin3ba18a02019-08-13 15:44:55 -0700158 """Generate ScheduleBuildRequest for calling buildbucket.
Xinan Linc61196b2019-08-13 10:37:30 -0700159
Xinan Lin3ba18a02019-08-13 15:44:55 -0700160 Args:
Xinan Lin9e4917d2019-11-04 10:58:47 -0800161 reqs_json: A json string of requests.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700162 tags: A list of tags for the buildbucket build.
Xinan Linc61196b2019-08-13 10:37:30 -0700163
Xinan Lin3ba18a02019-08-13 15:44:55 -0700164 Returns:
165 A ScheduleBuildRequest instance.
166 """
Xinan Lin9e4917d2019-11-04 10:58:47 -0800167 requests_struct = struct_pb2.Struct()
168 recipe_struct = json_format.Parse(reqs_json, requests_struct)
Xinan Linc61196b2019-08-13 10:37:30 -0700169 return rpc_pb2.ScheduleBuildRequest(builder=self.builder,
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700170 properties=recipe_struct,
Xinan Lin081b5d32020-03-23 17:37:55 -0700171 request_id=str(uuid.uuid1()),
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700172 tags=tags)
Xinan Linc61196b2019-08-13 10:37:30 -0700173
174 def _gen_service_account_key(self, sa):
Xinan Lin3ba18a02019-08-13 15:44:55 -0700175 """Generate credentials to authorize the call.
Xinan Linc61196b2019-08-13 10:37:30 -0700176
Xinan Lin3ba18a02019-08-13 15:44:55 -0700177 Args:
178 sa: A string of the path to the service account json file.
Xinan Linc61196b2019-08-13 10:37:30 -0700179
Xinan Lin3ba18a02019-08-13 15:44:55 -0700180 Returns:
181 A service account key.
182 """
Xinan Linc61196b2019-08-13 10:37:30 -0700183 service_credentials = service_account.ServiceAccountCredentials
Xinan Lin3ba18a02019-08-13 15:44:55 -0700184 key = service_credentials.from_json_keyfile_name(sa, self.scope)
Xinan Linc61196b2019-08-13 10:37:30 -0700185 return auth.ServiceAccountKey(
186 client_email=key.service_account_email,
187 private_key=key._private_key_pkcs8_pem,
188 private_key_id=key._private_key_id)
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700189
190
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700191def _form_test_platform_request(task_params):
192 """Generate ScheduleBuildRequest for calling buildbucket.
193
194 Args:
195 task_params: dict containing the parameters of a task got from suite
196 queue.
197
198 Returns:
199 A request_pb2 instance.
200 """
201 build = _infer_build_from_task_params(task_params)
202 if build == 'None':
203 raise BuildbucketRunError('No proper build in task params: %r' %
204 task_params)
205 pool = _infer_pool_from_task_params(task_params)
206 timeout = _infer_timeout_from_task_params(task_params)
207
208 request = request_pb2.Request()
209 params = request.params
210
Xinan Lin4757d6f2020-03-24 22:20:31 -0700211 params.scheduling.CopyFrom(_scheduling_for_pool(pool))
212 if (task_params.get('qs_account') not in ['None', None]
213 and params.scheduling.unmanaged_pool):
214 params.scheduling.qs_account = task_params.get('qs_account')
215 # Quota Scheduler has no concept of priority.
216 if 'priority' in task_params and not params.scheduling.qs_account:
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700217 params.scheduling.priority = int(task_params['priority'])
218
219 params.software_dependencies.add().chromeos_build = build
220 params.software_attributes.build_target.name = task_params['board']
Aviv Keshetc679faf2019-11-27 17:52:50 -0800221
222 gs_url = GS_PREFIX + task_params['test_source_build']
223 params.metadata.test_metadata_url = gs_url
224 params.metadata.debug_symbols_archive_url = gs_url
225
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700226 params.time.maximum_duration.FromTimedelta(timeout)
227
228 for key, value in _request_tags(task_params, build, pool).iteritems():
229 params.decorations.tags.append('%s:%s' % (key, value))
230
231 if task_params['model'] != 'None':
232 params.hardware_attributes.model = task_params['model']
233
234 if task_params['job_retry'] == 'True':
235 params.retry.allow = True
236 params.retry.max = constants.Buildbucket.MAX_RETRY
237
238 fw_rw_build = task_params.get(build_lib.BuildVersionKey.FW_RW_VERSION)
239 fw_ro_build = task_params.get(build_lib.BuildVersionKey.FW_RO_VERSION)
240 # Skip firmware field if None(unspecified) or 'None'(no such build).
241 if fw_ro_build not in (None, 'None'):
242 build = params.software_dependencies.add()
243 build.ro_firmware_build = fw_ro_build
244 if fw_rw_build not in (None, 'None'):
245 build = params.software_dependencies.add()
246 build.rw_firmware_build = fw_rw_build
247
248 request.test_plan.suite.add().name = task_params['suite']
249 return request
250
251
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700252def _scheduling_for_pool(pool):
253 """Assign appropriate pool name to scheduling instance.
254
255 Args:
256 pool: string pool name (e.g. 'bvt', 'quota').
257
258 Returns:
259 scheduling: A request_pb2.Request.Params.Scheduling instance.
260 """
261 mp = request_pb2.Request.Params.Scheduling.ManagedPool
262 if mp.DESCRIPTOR.values_by_name.get(pool) is not None:
263 return request_pb2.Request.Params.Scheduling(managed_pool=mp.Value(pool))
264
265 DUT_POOL_PREFIX = r'DUT_POOL_(?P<munged_pool>.+)'
266 match = re.match(DUT_POOL_PREFIX, pool)
267 if match:
268 pool = string.lower(match.group('munged_pool'))
269 if NONSTANDARD_POOL_NAMES.get(pool):
Xinan Lin9e4917d2019-11-04 10:58:47 -0800270 return request_pb2.Request.Params.Scheduling(
271 managed_pool=NONSTANDARD_POOL_NAMES.get(pool))
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700272 return request_pb2.Request.Params.Scheduling(unmanaged_pool=pool)
273
274
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700275# Also see: A copy of this function in swarming_lib.py.
276def _infer_build_from_task_params(task_params):
277 """Infer the build to install on the DUT for the scheduled task.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700278
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700279 Args:
280 task_params: The parameters of a task loaded from suite queue.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700281
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700282 Returns:
283 A string representing the build to run.
284 """
285 cros_build = task_params[build_lib.BuildVersionKey.CROS_VERSION]
286 android_build = task_params[build_lib.BuildVersionKey.ANDROID_BUILD_VERSION]
287 testbed_build = task_params[build_lib.BuildVersionKey.TESTBED_BUILD_VERSION]
288 return cros_build or android_build or testbed_build
289
290
291def _infer_pool_from_task_params(task_params):
292 """Infer the pool to use for the scheduled task.
293
294 Args:
295 task_params: The parameters of a task loaded from suite queue.
296
297 Returns:
298 A string pool to schedule task in.
299 """
300 if task_params.get('override_qs_account'):
301 return 'DUT_POOL_QUOTA'
302 return task_params.get('override_pool') or task_params['pool']
303
304
305def _infer_timeout_from_task_params(task_params):
306 """Infer the timeout for the scheduled task.
307
308 Args:
309 task_params: The parameters of a task loaded from suite queue.
310
311 Returns:
312 A datetime.timedelta instance for the timeout.
313 """
314 timeout_mins = int(task_params['timeout_mins'])
315 # timeout's unit is hour.
316 if task_params.get('timeout'):
317 timeout_mins = max(int(task_params['timeout'])*60, timeout_mins)
318 if timeout_mins > constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS:
319 timeout_mins = constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS
320 return datetime.timedelta(minutes=timeout_mins)
321
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700322
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700323def _request_tags(task_params, build, pool):
324 """Infer tags to include in cros_test_platform request.
325
326 Args:
327 task_params: suite task parameters.
328 build: The build included in the request. Must not be None.
329 pool: The DUT pool used for the request. Must not be None.
330
331 Returns:
332 A dict of tags.
333 """
334 tags = {
335 'build': build,
336 'label-pool': pool,
337 }
Xinan Linfb63d572019-09-24 15:49:04 -0700338 if task_params.get('board') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700339 tags['label-board'] = task_params['board']
Xinan Linfb63d572019-09-24 15:49:04 -0700340 if task_params.get('model') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700341 tags['label-model'] = task_params['model']
Xinan Linfb63d572019-09-24 15:49:04 -0700342 if task_params.get('suite') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700343 tags['suite'] = task_params['suite']
Xinan Linc8647112020-02-04 16:45:56 -0800344 # Add user configured dimensions.
345 if task_params.get('dimensions') not in (None, 'None'):
346 for label in task_params.get('dimensions').split(','):
347 key, value = _get_key_val_from_label(label)
348 if all([key, value]) and not key in tags:
349 tags[key] = value
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700350 return tags
351
352
Xinan Linc8647112020-02-04 16:45:56 -0800353def _get_key_val_from_label(label):
354 """A helper to get key and value from the label.
355
356 Args:
357 label: A string of label, should be in the form of
358 key:value, e.g. 'pool:ChromeOSSkylab'.
359 """
360 res = label.split(':')
361 if len(res) == 2:
362 return res[0], res[1]
363 logging.warning('Failed to parse the label, %s', label)
364
365
Xinan Lin9e4917d2019-11-04 10:58:47 -0800366def _suite_bb_tag(suite):
367 """Convert suite name to a buildbucket tag.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700368
369 Args:
370 request: A request_pb2.Request.
371
372 Returns:
373 [bb_common_pb2.StringPair] tags to include the buildbucket request.
374 """
Xinan Lin9e4917d2019-11-04 10:58:47 -0800375 return [bb_common_pb2.StringPair(key='suite', value=suite)]