blob: 5ec338d713597f5e045f34ce5f33556dbfe6f26a [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
12
Xinan Lindf0698a2020-02-05 22:38:11 -080013import analytics
Xinan Lin3ba18a02019-08-13 15:44:55 -070014import build_lib
Xinan Linc61196b2019-08-13 10:37:30 -070015import constants
16import file_getter
17
18from chromite.api.gen.test_platform import request_pb2
Xinan Linc61196b2019-08-13 10:37:30 -070019from components import auth
Xinan Lin3ba18a02019-08-13 15:44:55 -070020from components.prpc import client as prpc_client
Prathmesh Prabhu2382a182019-09-07 21:18:10 -070021from infra_libs.buildbucket.proto import common_pb2 as bb_common_pb2
Xinan Lin3ba18a02019-08-13 15:44:55 -070022from infra_libs.buildbucket.proto import rpc_pb2, build_pb2
Xinan Linc61196b2019-08-13 10:37:30 -070023from infra_libs.buildbucket.proto.rpc_prpc_pb2 import BuildsServiceDescription
24
25from oauth2client import service_account
Xinan Lin3ba18a02019-08-13 15:44:55 -070026
27from google.protobuf import json_format, struct_pb2
Xinan Linc61196b2019-08-13 10:37:30 -070028
29
Xinan Lin3ba18a02019-08-13 15:44:55 -070030_enum = request_pb2.Request.Params.Scheduling
Xinan Linc61196b2019-08-13 10:37:30 -070031NONSTANDARD_POOL_NAMES = {
Xinan Lin3ba18a02019-08-13 15:44:55 -070032 'cq': _enum.MANAGED_POOL_CQ,
33 'bvt': _enum.MANAGED_POOL_BVT,
34 'suites': _enum.MANAGED_POOL_SUITES,
35 'cts': _enum.MANAGED_POOL_CTS,
36 'cts-perbuild': _enum.MANAGED_POOL_CTS_PERBUILD,
37 'continuous': _enum.MANAGED_POOL_CONTINUOUS,
38 'arc-presubmit': _enum.MANAGED_POOL_ARC_PRESUBMIT,
39 'quota': _enum.MANAGED_POOL_QUOTA,
Xinan Linc61196b2019-08-13 10:37:30 -070040}
41
Xinan Lin3ba18a02019-08-13 15:44:55 -070042
Xinan Lin6e097382019-08-27 18:43:35 -070043GS_PREFIX = 'gs://chromeos-image-archive/'
44
45
Xinan Linc61196b2019-08-13 10:37:30 -070046def _get_client(address):
47 """Create a prpc client instance for given address."""
48 return prpc_client.Client(address, BuildsServiceDescription)
49
50
Xinan Lin3ba18a02019-08-13 15:44:55 -070051class BuildbucketRunError(Exception):
52 """Raised when interactions with buildbucket server fail."""
53
54
Xinan Linc61196b2019-08-13 10:37:30 -070055class TestPlatformClient(object):
56 """prpc client for cros_test_platform, aka frontdoor."""
57
58 def __init__(self, address, project, bucket, builder):
59 self.client = _get_client(address)
60 self.builder = build_pb2.BuilderID(project=project,
61 bucket=bucket,
62 builder=builder)
63 self.scope = 'https://www.googleapis.com/auth/userinfo.email'
64 self.running_env = constants.environment()
65
Xinan Lin9e4917d2019-11-04 10:58:47 -080066 def multirequest_run(self, tasks, suite):
67 """Call TestPlatform Builder to schedule a batch of tests.
Xinan Lin3ba18a02019-08-13 15:44:55 -070068
69 Args:
Xinan Lin9e4917d2019-11-04 10:58:47 -080070 tasks: The suite tasks to run.
71 suite: suite name for the batch request.
72
73 Returns:
74 List of executed tasks.
Xinan Lin3ba18a02019-08-13 15:44:55 -070075
76 Raises:
77 BuildbucketRunError: if failed to get build info from task parameters.
78 """
Xinan Lin9e4917d2019-11-04 10:58:47 -080079 requests = []
80 executed_tasks = []
81 counter = collections.defaultdict(int)
Xinan Lindf0698a2020-02-05 22:38:11 -080082 task_executions = []
Xinan Lin9e4917d2019-11-04 10:58:47 -080083 for task in tasks:
84 try:
85 params = task.extract_params()
86 req = _form_test_platform_request(params)
87 req_json = json_format.MessageToJson(req)
88 counter_key = params['board']
89 counter_key += '' if params['model'] in [None, 'None'] else (
90 '_' + params['model'])
91 counter[counter_key] += 1
92 req_name = counter_key
93 if counter[counter_key] > 1:
94 req_name += '_' + str(counter[counter_key] - 1)
95 requests.append('"%s": %s' % (req_name, req_json))
96 executed_tasks.append(task)
Xinan Lindf0698a2020-02-05 22:38:11 -080097 if params['task_id']:
98 task_executions.append(analytics.ExecutionTask(params['task_id']))
Xinan Lin9e4917d2019-11-04 10:58:47 -080099 except (ValueError, BuildbucketRunError):
100 logging.debug('Failed to process task: %r', params)
101 if not requests:
102 return []
103 try:
104 requests_json = '{ "requests": { %s } }' % ', '.join(requests)
105 req_build = self._build_request(requests_json,
106 _suite_bb_tag(suite))
107 logging.debug('Raw request to buildbucket: %r', req_build)
linxinane5eb4552019-08-26 05:44:45 +0000108
Xinan Lin9e4917d2019-11-04 10:58:47 -0800109 if (self.running_env == constants.RunningEnv.ENV_STANDALONE or
110 self.running_env == constants.RunningEnv.ENV_DEVELOPMENT_SERVER):
111 # If running locally, use the staging service account.
112 sa_key = self._gen_service_account_key(
113 file_getter.STAGING_CLIENT_SECRETS_FILE)
114 cred = prpc_client.service_account_credentials(
115 service_account_key=sa_key)
116 else:
117 cred = prpc_client.service_account_credentials()
118 #TODO(linxinan): only add the tasks returned from bb to executed_tasks.
119 resp = self.client.ScheduleBuild(req_build, credentials=cred)
120 logging.debug('Response from buildbucket: %r', resp)
Xinan Lindf0698a2020-02-05 22:38:11 -0800121 for t in task_executions:
122 t.update_result(resp)
123 try:
124 if not t.upload():
125 logging.warning('Failed to insert row: %r', t)
126 # For any exceptions from BQ, only log it.
127 except Exception as e: #pylint: disable=broad-except
128 logging.exception('Failed to insert row: %r, got error: %s',
129 t, str(e))
Xinan Lin9e4917d2019-11-04 10:58:47 -0800130 return executed_tasks
131 except Exception as e:
132 logging.debug('Failed to process tasks: %r', tasks)
133 logging.exception(str(e))
134 return []
Xinan Lin3ba18a02019-08-13 15:44:55 -0700135
Xinan Linc61196b2019-08-13 10:37:30 -0700136 def dummy_run(self):
137 """Perform a dummy run of prpc call to cros_test_platform-dev."""
138
Xinan Lin9e4917d2019-11-04 10:58:47 -0800139 requests_json = '{ "requests": { "dummy": {} } }'
140 req_build = self._build_request(requests_json, tags=None)
Xinan Linc61196b2019-08-13 10:37:30 -0700141 # Use the staging service account to authorize the request.
142 sa_key = self._gen_service_account_key(
143 file_getter.STAGING_CLIENT_SECRETS_FILE)
144 cred = prpc_client.service_account_credentials(service_account_key=sa_key)
Xinan Lin9e4917d2019-11-04 10:58:47 -0800145 return self.client.ScheduleBuild(req_build, credentials=cred)
Xinan Linc61196b2019-08-13 10:37:30 -0700146
Xinan Lin9e4917d2019-11-04 10:58:47 -0800147 def _build_request(self, reqs_json, tags):
Xinan Lin3ba18a02019-08-13 15:44:55 -0700148 """Generate ScheduleBuildRequest for calling buildbucket.
Xinan Linc61196b2019-08-13 10:37:30 -0700149
Xinan Lin3ba18a02019-08-13 15:44:55 -0700150 Args:
Xinan Lin9e4917d2019-11-04 10:58:47 -0800151 reqs_json: A json string of requests.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700152 tags: A list of tags for the buildbucket build.
Xinan Linc61196b2019-08-13 10:37:30 -0700153
Xinan Lin3ba18a02019-08-13 15:44:55 -0700154 Returns:
155 A ScheduleBuildRequest instance.
156 """
Xinan Lin9e4917d2019-11-04 10:58:47 -0800157 requests_struct = struct_pb2.Struct()
158 recipe_struct = json_format.Parse(reqs_json, requests_struct)
Xinan Linc61196b2019-08-13 10:37:30 -0700159 return rpc_pb2.ScheduleBuildRequest(builder=self.builder,
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700160 properties=recipe_struct,
161 tags=tags)
Xinan Linc61196b2019-08-13 10:37:30 -0700162
163 def _gen_service_account_key(self, sa):
Xinan Lin3ba18a02019-08-13 15:44:55 -0700164 """Generate credentials to authorize the call.
Xinan Linc61196b2019-08-13 10:37:30 -0700165
Xinan Lin3ba18a02019-08-13 15:44:55 -0700166 Args:
167 sa: A string of the path to the service account json file.
Xinan Linc61196b2019-08-13 10:37:30 -0700168
Xinan Lin3ba18a02019-08-13 15:44:55 -0700169 Returns:
170 A service account key.
171 """
Xinan Linc61196b2019-08-13 10:37:30 -0700172 service_credentials = service_account.ServiceAccountCredentials
Xinan Lin3ba18a02019-08-13 15:44:55 -0700173 key = service_credentials.from_json_keyfile_name(sa, self.scope)
Xinan Linc61196b2019-08-13 10:37:30 -0700174 return auth.ServiceAccountKey(
175 client_email=key.service_account_email,
176 private_key=key._private_key_pkcs8_pem,
177 private_key_id=key._private_key_id)
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700178
179
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700180def _form_test_platform_request(task_params):
181 """Generate ScheduleBuildRequest for calling buildbucket.
182
183 Args:
184 task_params: dict containing the parameters of a task got from suite
185 queue.
186
187 Returns:
188 A request_pb2 instance.
189 """
190 build = _infer_build_from_task_params(task_params)
191 if build == 'None':
192 raise BuildbucketRunError('No proper build in task params: %r' %
193 task_params)
194 pool = _infer_pool_from_task_params(task_params)
195 timeout = _infer_timeout_from_task_params(task_params)
196
197 request = request_pb2.Request()
198 params = request.params
199
Xinan Lin2e196412019-10-24 14:31:13 -0700200 if task_params.get('override_qs_account') or task_params.get('override_pool'):
201 logging.debug('Override qs account: %s. Override pool: %s.' %
202 (task_params.get('override_qs_account'),
203 task_params.get('override_pool')))
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700204 quota = task_params.get('override_qs_account')
205 if quota:
206 params.scheduling.quota_account = quota
207 else:
208 params.scheduling.CopyFrom(_scheduling_for_pool(pool))
209 if 'priority' in task_params:
210 params.scheduling.priority = int(task_params['priority'])
211
212 params.software_dependencies.add().chromeos_build = build
213 params.software_attributes.build_target.name = task_params['board']
Aviv Keshetc679faf2019-11-27 17:52:50 -0800214
215 gs_url = GS_PREFIX + task_params['test_source_build']
216 params.metadata.test_metadata_url = gs_url
217 params.metadata.debug_symbols_archive_url = gs_url
218
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700219 params.time.maximum_duration.FromTimedelta(timeout)
220
221 for key, value in _request_tags(task_params, build, pool).iteritems():
222 params.decorations.tags.append('%s:%s' % (key, value))
223
224 if task_params['model'] != 'None':
225 params.hardware_attributes.model = task_params['model']
226
227 if task_params['job_retry'] == 'True':
228 params.retry.allow = True
229 params.retry.max = constants.Buildbucket.MAX_RETRY
230
231 fw_rw_build = task_params.get(build_lib.BuildVersionKey.FW_RW_VERSION)
232 fw_ro_build = task_params.get(build_lib.BuildVersionKey.FW_RO_VERSION)
233 # Skip firmware field if None(unspecified) or 'None'(no such build).
234 if fw_ro_build not in (None, 'None'):
235 build = params.software_dependencies.add()
236 build.ro_firmware_build = fw_ro_build
237 if fw_rw_build not in (None, 'None'):
238 build = params.software_dependencies.add()
239 build.rw_firmware_build = fw_rw_build
240
241 request.test_plan.suite.add().name = task_params['suite']
242 return request
243
244
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700245def _scheduling_for_pool(pool):
246 """Assign appropriate pool name to scheduling instance.
247
248 Args:
249 pool: string pool name (e.g. 'bvt', 'quota').
250
251 Returns:
252 scheduling: A request_pb2.Request.Params.Scheduling instance.
253 """
254 mp = request_pb2.Request.Params.Scheduling.ManagedPool
255 if mp.DESCRIPTOR.values_by_name.get(pool) is not None:
256 return request_pb2.Request.Params.Scheduling(managed_pool=mp.Value(pool))
257
258 DUT_POOL_PREFIX = r'DUT_POOL_(?P<munged_pool>.+)'
259 match = re.match(DUT_POOL_PREFIX, pool)
260 if match:
261 pool = string.lower(match.group('munged_pool'))
262 if NONSTANDARD_POOL_NAMES.get(pool):
Xinan Lin9e4917d2019-11-04 10:58:47 -0800263 return request_pb2.Request.Params.Scheduling(
264 managed_pool=NONSTANDARD_POOL_NAMES.get(pool))
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700265 return request_pb2.Request.Params.Scheduling(unmanaged_pool=pool)
266
267
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700268# Also see: A copy of this function in swarming_lib.py.
269def _infer_build_from_task_params(task_params):
270 """Infer the build to install on the DUT for the scheduled task.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700271
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700272 Args:
273 task_params: The parameters of a task loaded from suite queue.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700274
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700275 Returns:
276 A string representing the build to run.
277 """
278 cros_build = task_params[build_lib.BuildVersionKey.CROS_VERSION]
279 android_build = task_params[build_lib.BuildVersionKey.ANDROID_BUILD_VERSION]
280 testbed_build = task_params[build_lib.BuildVersionKey.TESTBED_BUILD_VERSION]
281 return cros_build or android_build or testbed_build
282
283
284def _infer_pool_from_task_params(task_params):
285 """Infer the pool to use for the scheduled task.
286
287 Args:
288 task_params: The parameters of a task loaded from suite queue.
289
290 Returns:
291 A string pool to schedule task in.
292 """
293 if task_params.get('override_qs_account'):
294 return 'DUT_POOL_QUOTA'
295 return task_params.get('override_pool') or task_params['pool']
296
297
298def _infer_timeout_from_task_params(task_params):
299 """Infer the timeout for the scheduled task.
300
301 Args:
302 task_params: The parameters of a task loaded from suite queue.
303
304 Returns:
305 A datetime.timedelta instance for the timeout.
306 """
307 timeout_mins = int(task_params['timeout_mins'])
308 # timeout's unit is hour.
309 if task_params.get('timeout'):
310 timeout_mins = max(int(task_params['timeout'])*60, timeout_mins)
311 if timeout_mins > constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS:
312 timeout_mins = constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS
313 return datetime.timedelta(minutes=timeout_mins)
314
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700315
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700316def _request_tags(task_params, build, pool):
317 """Infer tags to include in cros_test_platform request.
318
319 Args:
320 task_params: suite task parameters.
321 build: The build included in the request. Must not be None.
322 pool: The DUT pool used for the request. Must not be None.
323
324 Returns:
325 A dict of tags.
326 """
327 tags = {
328 'build': build,
329 'label-pool': pool,
330 }
Xinan Linfb63d572019-09-24 15:49:04 -0700331 if task_params.get('board') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700332 tags['label-board'] = task_params['board']
Xinan Linfb63d572019-09-24 15:49:04 -0700333 if task_params.get('model') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700334 tags['label-model'] = task_params['model']
Xinan Linfb63d572019-09-24 15:49:04 -0700335 if task_params.get('suite') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700336 tags['suite'] = task_params['suite']
Xinan Linc8647112020-02-04 16:45:56 -0800337 # Add user configured dimensions.
338 if task_params.get('dimensions') not in (None, 'None'):
339 for label in task_params.get('dimensions').split(','):
340 key, value = _get_key_val_from_label(label)
341 if all([key, value]) and not key in tags:
342 tags[key] = value
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700343 return tags
344
345
Xinan Linc8647112020-02-04 16:45:56 -0800346def _get_key_val_from_label(label):
347 """A helper to get key and value from the label.
348
349 Args:
350 label: A string of label, should be in the form of
351 key:value, e.g. 'pool:ChromeOSSkylab'.
352 """
353 res = label.split(':')
354 if len(res) == 2:
355 return res[0], res[1]
356 logging.warning('Failed to parse the label, %s', label)
357
358
Xinan Lin9e4917d2019-11-04 10:58:47 -0800359def _suite_bb_tag(suite):
360 """Convert suite name to a buildbucket tag.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700361
362 Args:
363 request: A request_pb2.Request.
364
365 Returns:
366 [bb_common_pb2.StringPair] tags to include the buildbucket request.
367 """
Xinan Lin9e4917d2019-11-04 10:58:47 -0800368 return [bb_common_pb2.StringPair(key='suite', value=suite)]