blob: 4d97dcde171a951623733e775ea5f9a1fa9ffce4 [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 Lin4757d6f2020-03-24 22:20:31 -0700202 params.scheduling.CopyFrom(_scheduling_for_pool(pool))
203 if (task_params.get('qs_account') not in ['None', None]
204 and params.scheduling.unmanaged_pool):
205 params.scheduling.qs_account = task_params.get('qs_account')
206 # Quota Scheduler has no concept of priority.
207 if 'priority' in task_params and not params.scheduling.qs_account:
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700208 params.scheduling.priority = int(task_params['priority'])
209
210 params.software_dependencies.add().chromeos_build = build
211 params.software_attributes.build_target.name = task_params['board']
Aviv Keshetc679faf2019-11-27 17:52:50 -0800212
213 gs_url = GS_PREFIX + task_params['test_source_build']
214 params.metadata.test_metadata_url = gs_url
215 params.metadata.debug_symbols_archive_url = gs_url
216
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700217 params.time.maximum_duration.FromTimedelta(timeout)
218
219 for key, value in _request_tags(task_params, build, pool).iteritems():
220 params.decorations.tags.append('%s:%s' % (key, value))
221
222 if task_params['model'] != 'None':
223 params.hardware_attributes.model = task_params['model']
224
225 if task_params['job_retry'] == 'True':
226 params.retry.allow = True
227 params.retry.max = constants.Buildbucket.MAX_RETRY
228
229 fw_rw_build = task_params.get(build_lib.BuildVersionKey.FW_RW_VERSION)
230 fw_ro_build = task_params.get(build_lib.BuildVersionKey.FW_RO_VERSION)
231 # Skip firmware field if None(unspecified) or 'None'(no such build).
232 if fw_ro_build not in (None, 'None'):
233 build = params.software_dependencies.add()
234 build.ro_firmware_build = fw_ro_build
235 if fw_rw_build not in (None, 'None'):
236 build = params.software_dependencies.add()
237 build.rw_firmware_build = fw_rw_build
238
239 request.test_plan.suite.add().name = task_params['suite']
240 return request
241
242
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700243def _scheduling_for_pool(pool):
244 """Assign appropriate pool name to scheduling instance.
245
246 Args:
247 pool: string pool name (e.g. 'bvt', 'quota').
248
249 Returns:
250 scheduling: A request_pb2.Request.Params.Scheduling instance.
251 """
252 mp = request_pb2.Request.Params.Scheduling.ManagedPool
253 if mp.DESCRIPTOR.values_by_name.get(pool) is not None:
254 return request_pb2.Request.Params.Scheduling(managed_pool=mp.Value(pool))
255
256 DUT_POOL_PREFIX = r'DUT_POOL_(?P<munged_pool>.+)'
257 match = re.match(DUT_POOL_PREFIX, pool)
258 if match:
259 pool = string.lower(match.group('munged_pool'))
260 if NONSTANDARD_POOL_NAMES.get(pool):
Xinan Lin9e4917d2019-11-04 10:58:47 -0800261 return request_pb2.Request.Params.Scheduling(
262 managed_pool=NONSTANDARD_POOL_NAMES.get(pool))
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700263 return request_pb2.Request.Params.Scheduling(unmanaged_pool=pool)
264
265
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700266# Also see: A copy of this function in swarming_lib.py.
267def _infer_build_from_task_params(task_params):
268 """Infer the build to install on the DUT for the scheduled task.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700269
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700270 Args:
271 task_params: The parameters of a task loaded from suite queue.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700272
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700273 Returns:
274 A string representing the build to run.
275 """
276 cros_build = task_params[build_lib.BuildVersionKey.CROS_VERSION]
277 android_build = task_params[build_lib.BuildVersionKey.ANDROID_BUILD_VERSION]
278 testbed_build = task_params[build_lib.BuildVersionKey.TESTBED_BUILD_VERSION]
279 return cros_build or android_build or testbed_build
280
281
282def _infer_pool_from_task_params(task_params):
283 """Infer the pool to use for the scheduled task.
284
285 Args:
286 task_params: The parameters of a task loaded from suite queue.
287
288 Returns:
289 A string pool to schedule task in.
290 """
291 if task_params.get('override_qs_account'):
292 return 'DUT_POOL_QUOTA'
293 return task_params.get('override_pool') or task_params['pool']
294
295
296def _infer_timeout_from_task_params(task_params):
297 """Infer the timeout for the scheduled task.
298
299 Args:
300 task_params: The parameters of a task loaded from suite queue.
301
302 Returns:
303 A datetime.timedelta instance for the timeout.
304 """
305 timeout_mins = int(task_params['timeout_mins'])
306 # timeout's unit is hour.
307 if task_params.get('timeout'):
308 timeout_mins = max(int(task_params['timeout'])*60, timeout_mins)
309 if timeout_mins > constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS:
310 timeout_mins = constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS
311 return datetime.timedelta(minutes=timeout_mins)
312
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700313
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700314def _request_tags(task_params, build, pool):
315 """Infer tags to include in cros_test_platform request.
316
317 Args:
318 task_params: suite task parameters.
319 build: The build included in the request. Must not be None.
320 pool: The DUT pool used for the request. Must not be None.
321
322 Returns:
323 A dict of tags.
324 """
325 tags = {
326 'build': build,
327 'label-pool': pool,
328 }
Xinan Linfb63d572019-09-24 15:49:04 -0700329 if task_params.get('board') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700330 tags['label-board'] = task_params['board']
Xinan Linfb63d572019-09-24 15:49:04 -0700331 if task_params.get('model') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700332 tags['label-model'] = task_params['model']
Xinan Linfb63d572019-09-24 15:49:04 -0700333 if task_params.get('suite') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700334 tags['suite'] = task_params['suite']
Xinan Linc8647112020-02-04 16:45:56 -0800335 # Add user configured dimensions.
336 if task_params.get('dimensions') not in (None, 'None'):
337 for label in task_params.get('dimensions').split(','):
338 key, value = _get_key_val_from_label(label)
339 if all([key, value]) and not key in tags:
340 tags[key] = value
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700341 return tags
342
343
Xinan Linc8647112020-02-04 16:45:56 -0800344def _get_key_val_from_label(label):
345 """A helper to get key and value from the label.
346
347 Args:
348 label: A string of label, should be in the form of
349 key:value, e.g. 'pool:ChromeOSSkylab'.
350 """
351 res = label.split(':')
352 if len(res) == 2:
353 return res[0], res[1]
354 logging.warning('Failed to parse the label, %s', label)
355
356
Xinan Lin9e4917d2019-11-04 10:58:47 -0800357def _suite_bb_tag(suite):
358 """Convert suite name to a buildbucket tag.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700359
360 Args:
361 request: A request_pb2.Request.
362
363 Returns:
364 [bb_common_pb2.StringPair] tags to include the buildbucket request.
365 """
Xinan Lin9e4917d2019-11-04 10:58:47 -0800366 return [bb_common_pb2.StringPair(key='suite', value=suite)]