blob: a996dca5260da7336a08e1ce7ead4bf344033124 [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 Linc61196b2019-08-13 10:37:30 -070047def _get_client(address):
48 """Create a prpc client instance for given address."""
49 return prpc_client.Client(address, BuildsServiceDescription)
50
51
Xinan Lin3ba18a02019-08-13 15:44:55 -070052class BuildbucketRunError(Exception):
53 """Raised when interactions with buildbucket server fail."""
54
55
Xinan Linc61196b2019-08-13 10:37:30 -070056class TestPlatformClient(object):
57 """prpc client for cros_test_platform, aka frontdoor."""
58
59 def __init__(self, address, project, bucket, builder):
60 self.client = _get_client(address)
61 self.builder = build_pb2.BuilderID(project=project,
62 bucket=bucket,
63 builder=builder)
64 self.scope = 'https://www.googleapis.com/auth/userinfo.email'
65 self.running_env = constants.environment()
66
Xinan Lin9e4917d2019-11-04 10:58:47 -080067 def multirequest_run(self, tasks, suite):
68 """Call TestPlatform Builder to schedule a batch of tests.
Xinan Lin3ba18a02019-08-13 15:44:55 -070069
70 Args:
Xinan Lin9e4917d2019-11-04 10:58:47 -080071 tasks: The suite tasks to run.
72 suite: suite name for the batch request.
73
74 Returns:
75 List of executed tasks.
Xinan Lin3ba18a02019-08-13 15:44:55 -070076
77 Raises:
78 BuildbucketRunError: if failed to get build info from task parameters.
79 """
Xinan Lin9e4917d2019-11-04 10:58:47 -080080 requests = []
81 executed_tasks = []
82 counter = collections.defaultdict(int)
Xinan Lindf0698a2020-02-05 22:38:11 -080083 task_executions = []
Xinan Lin9e4917d2019-11-04 10:58:47 -080084 for task in tasks:
85 try:
86 params = task.extract_params()
87 req = _form_test_platform_request(params)
88 req_json = json_format.MessageToJson(req)
89 counter_key = params['board']
90 counter_key += '' if params['model'] in [None, 'None'] else (
91 '_' + params['model'])
92 counter[counter_key] += 1
93 req_name = counter_key
94 if counter[counter_key] > 1:
95 req_name += '_' + str(counter[counter_key] - 1)
96 requests.append('"%s": %s' % (req_name, req_json))
97 executed_tasks.append(task)
Xinan Lin083ba8f2020-02-06 13:55:18 -080098 if params.get('task_id'):
Xinan Lindf0698a2020-02-05 22:38:11 -080099 task_executions.append(analytics.ExecutionTask(params['task_id']))
Xinan Lin9e4917d2019-11-04 10:58:47 -0800100 except (ValueError, BuildbucketRunError):
101 logging.debug('Failed to process task: %r', params)
102 if not requests:
103 return []
104 try:
105 requests_json = '{ "requests": { %s } }' % ', '.join(requests)
106 req_build = self._build_request(requests_json,
107 _suite_bb_tag(suite))
108 logging.debug('Raw request to buildbucket: %r', req_build)
linxinane5eb4552019-08-26 05:44:45 +0000109
Xinan Lin9e4917d2019-11-04 10:58:47 -0800110 if (self.running_env == constants.RunningEnv.ENV_STANDALONE or
111 self.running_env == constants.RunningEnv.ENV_DEVELOPMENT_SERVER):
112 # If running locally, use the staging service account.
113 sa_key = self._gen_service_account_key(
114 file_getter.STAGING_CLIENT_SECRETS_FILE)
115 cred = prpc_client.service_account_credentials(
116 service_account_key=sa_key)
117 else:
118 cred = prpc_client.service_account_credentials()
119 #TODO(linxinan): only add the tasks returned from bb to executed_tasks.
120 resp = self.client.ScheduleBuild(req_build, credentials=cred)
121 logging.debug('Response from buildbucket: %r', resp)
Xinan Lindf0698a2020-02-05 22:38:11 -0800122 for t in task_executions:
123 t.update_result(resp)
124 try:
125 if not t.upload():
126 logging.warning('Failed to insert row: %r', t)
127 # For any exceptions from BQ, only log it.
128 except Exception as e: #pylint: disable=broad-except
129 logging.exception('Failed to insert row: %r, got error: %s',
130 t, str(e))
Xinan Lin9e4917d2019-11-04 10:58:47 -0800131 return executed_tasks
132 except Exception as e:
133 logging.debug('Failed to process tasks: %r', tasks)
134 logging.exception(str(e))
135 return []
Xinan Lin3ba18a02019-08-13 15:44:55 -0700136
Xinan Linc61196b2019-08-13 10:37:30 -0700137 def dummy_run(self):
138 """Perform a dummy run of prpc call to cros_test_platform-dev."""
139
Xinan Lin9e4917d2019-11-04 10:58:47 -0800140 requests_json = '{ "requests": { "dummy": {} } }'
141 req_build = self._build_request(requests_json, tags=None)
Xinan Linc61196b2019-08-13 10:37:30 -0700142 # Use the staging service account to authorize the request.
143 sa_key = self._gen_service_account_key(
144 file_getter.STAGING_CLIENT_SECRETS_FILE)
145 cred = prpc_client.service_account_credentials(service_account_key=sa_key)
Xinan Lin9e4917d2019-11-04 10:58:47 -0800146 return self.client.ScheduleBuild(req_build, credentials=cred)
Xinan Linc61196b2019-08-13 10:37:30 -0700147
Xinan Lin9e4917d2019-11-04 10:58:47 -0800148 def _build_request(self, reqs_json, tags):
Xinan Lin3ba18a02019-08-13 15:44:55 -0700149 """Generate ScheduleBuildRequest for calling buildbucket.
Xinan Linc61196b2019-08-13 10:37:30 -0700150
Xinan Lin3ba18a02019-08-13 15:44:55 -0700151 Args:
Xinan Lin9e4917d2019-11-04 10:58:47 -0800152 reqs_json: A json string of requests.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700153 tags: A list of tags for the buildbucket build.
Xinan Linc61196b2019-08-13 10:37:30 -0700154
Xinan Lin3ba18a02019-08-13 15:44:55 -0700155 Returns:
156 A ScheduleBuildRequest instance.
157 """
Xinan Lin9e4917d2019-11-04 10:58:47 -0800158 requests_struct = struct_pb2.Struct()
159 recipe_struct = json_format.Parse(reqs_json, requests_struct)
Xinan Linc61196b2019-08-13 10:37:30 -0700160 return rpc_pb2.ScheduleBuildRequest(builder=self.builder,
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700161 properties=recipe_struct,
Xinan Lin081b5d32020-03-23 17:37:55 -0700162 request_id=str(uuid.uuid1()),
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700163 tags=tags)
Xinan Linc61196b2019-08-13 10:37:30 -0700164
165 def _gen_service_account_key(self, sa):
Xinan Lin3ba18a02019-08-13 15:44:55 -0700166 """Generate credentials to authorize the call.
Xinan Linc61196b2019-08-13 10:37:30 -0700167
Xinan Lin3ba18a02019-08-13 15:44:55 -0700168 Args:
169 sa: A string of the path to the service account json file.
Xinan Linc61196b2019-08-13 10:37:30 -0700170
Xinan Lin3ba18a02019-08-13 15:44:55 -0700171 Returns:
172 A service account key.
173 """
Xinan Linc61196b2019-08-13 10:37:30 -0700174 service_credentials = service_account.ServiceAccountCredentials
Xinan Lin3ba18a02019-08-13 15:44:55 -0700175 key = service_credentials.from_json_keyfile_name(sa, self.scope)
Xinan Linc61196b2019-08-13 10:37:30 -0700176 return auth.ServiceAccountKey(
177 client_email=key.service_account_email,
178 private_key=key._private_key_pkcs8_pem,
179 private_key_id=key._private_key_id)
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700180
181
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700182def _form_test_platform_request(task_params):
183 """Generate ScheduleBuildRequest for calling buildbucket.
184
185 Args:
186 task_params: dict containing the parameters of a task got from suite
187 queue.
188
189 Returns:
190 A request_pb2 instance.
191 """
192 build = _infer_build_from_task_params(task_params)
193 if build == 'None':
194 raise BuildbucketRunError('No proper build in task params: %r' %
195 task_params)
196 pool = _infer_pool_from_task_params(task_params)
197 timeout = _infer_timeout_from_task_params(task_params)
198
199 request = request_pb2.Request()
200 params = request.params
201
Xinan Lin2e196412019-10-24 14:31:13 -0700202 if task_params.get('override_qs_account') or task_params.get('override_pool'):
203 logging.debug('Override qs account: %s. Override pool: %s.' %
204 (task_params.get('override_qs_account'),
205 task_params.get('override_pool')))
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700206 quota = task_params.get('override_qs_account')
207 if quota:
208 params.scheduling.quota_account = quota
209 else:
210 params.scheduling.CopyFrom(_scheduling_for_pool(pool))
211 if 'priority' in task_params:
212 params.scheduling.priority = int(task_params['priority'])
213
214 params.software_dependencies.add().chromeos_build = build
215 params.software_attributes.build_target.name = task_params['board']
Aviv Keshetc679faf2019-11-27 17:52:50 -0800216
217 gs_url = GS_PREFIX + task_params['test_source_build']
218 params.metadata.test_metadata_url = gs_url
219 params.metadata.debug_symbols_archive_url = gs_url
220
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700221 params.time.maximum_duration.FromTimedelta(timeout)
222
223 for key, value in _request_tags(task_params, build, pool).iteritems():
224 params.decorations.tags.append('%s:%s' % (key, value))
225
226 if task_params['model'] != 'None':
227 params.hardware_attributes.model = task_params['model']
228
229 if task_params['job_retry'] == 'True':
230 params.retry.allow = True
231 params.retry.max = constants.Buildbucket.MAX_RETRY
232
233 fw_rw_build = task_params.get(build_lib.BuildVersionKey.FW_RW_VERSION)
234 fw_ro_build = task_params.get(build_lib.BuildVersionKey.FW_RO_VERSION)
235 # Skip firmware field if None(unspecified) or 'None'(no such build).
236 if fw_ro_build not in (None, 'None'):
237 build = params.software_dependencies.add()
238 build.ro_firmware_build = fw_ro_build
239 if fw_rw_build not in (None, 'None'):
240 build = params.software_dependencies.add()
241 build.rw_firmware_build = fw_rw_build
242
243 request.test_plan.suite.add().name = task_params['suite']
244 return request
245
246
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700247def _scheduling_for_pool(pool):
248 """Assign appropriate pool name to scheduling instance.
249
250 Args:
251 pool: string pool name (e.g. 'bvt', 'quota').
252
253 Returns:
254 scheduling: A request_pb2.Request.Params.Scheduling instance.
255 """
256 mp = request_pb2.Request.Params.Scheduling.ManagedPool
257 if mp.DESCRIPTOR.values_by_name.get(pool) is not None:
258 return request_pb2.Request.Params.Scheduling(managed_pool=mp.Value(pool))
259
260 DUT_POOL_PREFIX = r'DUT_POOL_(?P<munged_pool>.+)'
261 match = re.match(DUT_POOL_PREFIX, pool)
262 if match:
263 pool = string.lower(match.group('munged_pool'))
264 if NONSTANDARD_POOL_NAMES.get(pool):
Xinan Lin9e4917d2019-11-04 10:58:47 -0800265 return request_pb2.Request.Params.Scheduling(
266 managed_pool=NONSTANDARD_POOL_NAMES.get(pool))
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700267 return request_pb2.Request.Params.Scheduling(unmanaged_pool=pool)
268
269
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700270# Also see: A copy of this function in swarming_lib.py.
271def _infer_build_from_task_params(task_params):
272 """Infer the build to install on the DUT for the scheduled task.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700273
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700274 Args:
275 task_params: The parameters of a task loaded from suite queue.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700276
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700277 Returns:
278 A string representing the build to run.
279 """
280 cros_build = task_params[build_lib.BuildVersionKey.CROS_VERSION]
281 android_build = task_params[build_lib.BuildVersionKey.ANDROID_BUILD_VERSION]
282 testbed_build = task_params[build_lib.BuildVersionKey.TESTBED_BUILD_VERSION]
283 return cros_build or android_build or testbed_build
284
285
286def _infer_pool_from_task_params(task_params):
287 """Infer the pool to use for the scheduled task.
288
289 Args:
290 task_params: The parameters of a task loaded from suite queue.
291
292 Returns:
293 A string pool to schedule task in.
294 """
295 if task_params.get('override_qs_account'):
296 return 'DUT_POOL_QUOTA'
297 return task_params.get('override_pool') or task_params['pool']
298
299
300def _infer_timeout_from_task_params(task_params):
301 """Infer the timeout for the scheduled task.
302
303 Args:
304 task_params: The parameters of a task loaded from suite queue.
305
306 Returns:
307 A datetime.timedelta instance for the timeout.
308 """
309 timeout_mins = int(task_params['timeout_mins'])
310 # timeout's unit is hour.
311 if task_params.get('timeout'):
312 timeout_mins = max(int(task_params['timeout'])*60, timeout_mins)
313 if timeout_mins > constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS:
314 timeout_mins = constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS
315 return datetime.timedelta(minutes=timeout_mins)
316
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700317
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700318def _request_tags(task_params, build, pool):
319 """Infer tags to include in cros_test_platform request.
320
321 Args:
322 task_params: suite task parameters.
323 build: The build included in the request. Must not be None.
324 pool: The DUT pool used for the request. Must not be None.
325
326 Returns:
327 A dict of tags.
328 """
329 tags = {
330 'build': build,
331 'label-pool': pool,
332 }
Xinan Linfb63d572019-09-24 15:49:04 -0700333 if task_params.get('board') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700334 tags['label-board'] = task_params['board']
Xinan Linfb63d572019-09-24 15:49:04 -0700335 if task_params.get('model') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700336 tags['label-model'] = task_params['model']
Xinan Linfb63d572019-09-24 15:49:04 -0700337 if task_params.get('suite') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700338 tags['suite'] = task_params['suite']
Xinan Linc8647112020-02-04 16:45:56 -0800339 # Add user configured dimensions.
340 if task_params.get('dimensions') not in (None, 'None'):
341 for label in task_params.get('dimensions').split(','):
342 key, value = _get_key_val_from_label(label)
343 if all([key, value]) and not key in tags:
344 tags[key] = value
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700345 return tags
346
347
Xinan Linc8647112020-02-04 16:45:56 -0800348def _get_key_val_from_label(label):
349 """A helper to get key and value from the label.
350
351 Args:
352 label: A string of label, should be in the form of
353 key:value, e.g. 'pool:ChromeOSSkylab'.
354 """
355 res = label.split(':')
356 if len(res) == 2:
357 return res[0], res[1]
358 logging.warning('Failed to parse the label, %s', label)
359
360
Xinan Lin9e4917d2019-11-04 10:58:47 -0800361def _suite_bb_tag(suite):
362 """Convert suite name to a buildbucket tag.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700363
364 Args:
365 request: A request_pb2.Request.
366
367 Returns:
368 [bb_common_pb2.StringPair] tags to include the buildbucket request.
369 """
Xinan Lin9e4917d2019-11-04 10:58:47 -0800370 return [bb_common_pb2.StringPair(key='suite', value=suite)]