blob: aebb2b8fb41330b68632104d6af5cf14600b9b9a [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.
Xinan Linc61196b2019-08-13 10:37:30 -07004"""Module for interacting with Buildbucket."""
Xinan Linc61196b2019-08-13 10:37:30 -07005
Xinan Lin9e4917d2019-11-04 10:58:47 -08006import collections
Xinan Lin3ba18a02019-08-13 15:44:55 -07007import datetime
linxinane5eb4552019-08-26 05:44:45 +00008import logging
Xinan Lin3ba18a02019-08-13 15:44:55 -07009import re
10import string
Xinan Lin081b5d32020-03-23 17:37:55 -070011import uuid
Xinan Lin3ba18a02019-08-13 15:44:55 -070012
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
Jacob Kopczynski408f3fd2020-08-07 13:31:59 -070018from chromite.api.gen.test_platform import request_pb2 as ctp_request
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
Xinan Linc61196b2019-08-13 10:37:30 -070029
Xinan Lin6e097382019-08-27 18:43:35 -070030GS_PREFIX = 'gs://chromeos-image-archive/'
31
Xinan Lin57e2d962020-03-30 17:24:53 -070032# The default prpc timeout(10 sec) is too short for the request_id
33# to propgate in buildbucket, and could not fully dedup the
34# ScheduleBuild request. Increase it while not hitting the default
35# GAE deadline(60 sec)
36PRPC_TIMEOUT_SEC = 55
37
38
Xinan Linc61196b2019-08-13 10:37:30 -070039def _get_client(address):
40 """Create a prpc client instance for given address."""
41 return prpc_client.Client(address, BuildsServiceDescription)
42
43
Xinan Lin3ba18a02019-08-13 15:44:55 -070044class BuildbucketRunError(Exception):
45 """Raised when interactions with buildbucket server fail."""
46
47
Xinan Linc61196b2019-08-13 10:37:30 -070048class TestPlatformClient(object):
49 """prpc client for cros_test_platform, aka frontdoor."""
Xinan Linc61196b2019-08-13 10:37:30 -070050 def __init__(self, address, project, bucket, builder):
51 self.client = _get_client(address)
52 self.builder = build_pb2.BuilderID(project=project,
53 bucket=bucket,
54 builder=builder)
55 self.scope = 'https://www.googleapis.com/auth/userinfo.email'
56 self.running_env = constants.environment()
57
Xinan Lin9e4917d2019-11-04 10:58:47 -080058 def multirequest_run(self, tasks, suite):
Xinan Lin1e8e7912020-07-31 09:52:16 -070059 """Call cros_test_platform Builder to schedule a batch of suite tests.
Xinan Lin3ba18a02019-08-13 15:44:55 -070060
61 Args:
Xinan Lin9e4917d2019-11-04 10:58:47 -080062 tasks: The suite tasks to run.
63 suite: suite name for the batch request.
64
65 Returns:
66 List of executed tasks.
Xinan Lin3ba18a02019-08-13 15:44:55 -070067
68 Raises:
69 BuildbucketRunError: if failed to get build info from task parameters.
70 """
Xinan Lin9e4917d2019-11-04 10:58:47 -080071 requests = []
72 executed_tasks = []
73 counter = collections.defaultdict(int)
Xinan Lindf0698a2020-02-05 22:38:11 -080074 task_executions = []
Xinan Lin9e4917d2019-11-04 10:58:47 -080075 for task in tasks:
76 try:
77 params = task.extract_params()
Xinan Linc54a7462020-04-17 15:39:01 -070078 if _should_skip(params):
79 continue
Xinan Lin8bb5b4b2020-07-21 23:17:55 -070080 req = _form_test_platform_request(params)
Xinan Lin9e4917d2019-11-04 10:58:47 -080081 req_json = json_format.MessageToJson(req)
82 counter_key = params['board']
Prathmesh Prabhuaf0857f2020-06-20 00:16:32 -070083 counter_key += '' if params['model'] in [None, 'None'
84 ] else ('_' + params['model'])
Xinan Lin9e4917d2019-11-04 10:58:47 -080085 counter[counter_key] += 1
86 req_name = counter_key
87 if counter[counter_key] > 1:
88 req_name += '_' + str(counter[counter_key] - 1)
89 requests.append('"%s": %s' % (req_name, req_json))
90 executed_tasks.append(task)
Xinan Lin083ba8f2020-02-06 13:55:18 -080091 if params.get('task_id'):
Xinan Lindf0698a2020-02-05 22:38:11 -080092 task_executions.append(analytics.ExecutionTask(params['task_id']))
Xinan Lin9e4917d2019-11-04 10:58:47 -080093 except (ValueError, BuildbucketRunError):
Xinan Linba3b9322020-04-24 15:08:12 -070094 logging.error('Failed to process task: %r', params)
Xinan Lin9e4917d2019-11-04 10:58:47 -080095 if not requests:
96 return []
97 try:
98 requests_json = '{ "requests": { %s } }' % ', '.join(requests)
Dhanya Ganeshedb78cb2020-07-20 19:40:50 +000099 req_build = self._build_request(requests_json, _bb_tags(suite))
Xinan Lin9e4917d2019-11-04 10:58:47 -0800100 logging.debug('Raw request to buildbucket: %r', req_build)
linxinane5eb4552019-08-26 05:44:45 +0000101
Prathmesh Prabhuaf0857f2020-06-20 00:16:32 -0700102 if (self.running_env == constants.RunningEnv.ENV_STANDALONE
103 or self.running_env == constants.RunningEnv.ENV_DEVELOPMENT_SERVER):
Xinan Lin9e4917d2019-11-04 10:58:47 -0800104 # If running locally, use the staging service account.
105 sa_key = self._gen_service_account_key(
106 file_getter.STAGING_CLIENT_SECRETS_FILE)
107 cred = prpc_client.service_account_credentials(
108 service_account_key=sa_key)
109 else:
110 cred = prpc_client.service_account_credentials()
Prathmesh Prabhuaf0857f2020-06-20 00:16:32 -0700111 resp = self.client.ScheduleBuild(req_build,
112 credentials=cred,
113 timeout=PRPC_TIMEOUT_SEC)
Xinan Lin9e4917d2019-11-04 10:58:47 -0800114 logging.debug('Response from buildbucket: %r', resp)
Xinan Lindf0698a2020-02-05 22:38:11 -0800115 for t in task_executions:
116 t.update_result(resp)
117 try:
118 if not t.upload():
119 logging.warning('Failed to insert row: %r', t)
120 # For any exceptions from BQ, only log it.
Prathmesh Prabhuaf0857f2020-06-20 00:16:32 -0700121 except Exception as e: #pylint: disable=broad-except
122 logging.exception('Failed to insert row: %r, got error: %s', t,
123 str(e))
Xinan Lin9e4917d2019-11-04 10:58:47 -0800124 return executed_tasks
125 except Exception as e:
126 logging.debug('Failed to process tasks: %r', tasks)
127 logging.exception(str(e))
128 return []
Xinan Lin3ba18a02019-08-13 15:44:55 -0700129
Xinan Linc61196b2019-08-13 10:37:30 -0700130 def dummy_run(self):
131 """Perform a dummy run of prpc call to cros_test_platform-dev."""
132
Xinan Lin9e4917d2019-11-04 10:58:47 -0800133 requests_json = '{ "requests": { "dummy": {} } }'
134 req_build = self._build_request(requests_json, tags=None)
Xinan Linc61196b2019-08-13 10:37:30 -0700135 # Use the staging service account to authorize the request.
136 sa_key = self._gen_service_account_key(
137 file_getter.STAGING_CLIENT_SECRETS_FILE)
138 cred = prpc_client.service_account_credentials(service_account_key=sa_key)
Prathmesh Prabhuaf0857f2020-06-20 00:16:32 -0700139 return self.client.ScheduleBuild(req_build,
140 credentials=cred,
141 timeout=PRPC_TIMEOUT_SEC)
Xinan Linc61196b2019-08-13 10:37:30 -0700142
Xinan Lin9e4917d2019-11-04 10:58:47 -0800143 def _build_request(self, reqs_json, tags):
Xinan Lin3ba18a02019-08-13 15:44:55 -0700144 """Generate ScheduleBuildRequest for calling buildbucket.
Xinan Linc61196b2019-08-13 10:37:30 -0700145
Xinan Lin3ba18a02019-08-13 15:44:55 -0700146 Args:
Xinan Lin9e4917d2019-11-04 10:58:47 -0800147 reqs_json: A json string of requests.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700148 tags: A list of tags for the buildbucket build.
Xinan Linc61196b2019-08-13 10:37:30 -0700149
Xinan Lin3ba18a02019-08-13 15:44:55 -0700150 Returns:
151 A ScheduleBuildRequest instance.
152 """
Xinan Lin9e4917d2019-11-04 10:58:47 -0800153 requests_struct = struct_pb2.Struct()
154 recipe_struct = json_format.Parse(reqs_json, requests_struct)
Xinan Linc61196b2019-08-13 10:37:30 -0700155 return rpc_pb2.ScheduleBuildRequest(builder=self.builder,
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700156 properties=recipe_struct,
Xinan Lin081b5d32020-03-23 17:37:55 -0700157 request_id=str(uuid.uuid1()),
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700158 tags=tags)
Xinan Linc61196b2019-08-13 10:37:30 -0700159
160 def _gen_service_account_key(self, sa):
Xinan Lin3ba18a02019-08-13 15:44:55 -0700161 """Generate credentials to authorize the call.
Xinan Linc61196b2019-08-13 10:37:30 -0700162
Xinan Lin3ba18a02019-08-13 15:44:55 -0700163 Args:
164 sa: A string of the path to the service account json file.
Xinan Linc61196b2019-08-13 10:37:30 -0700165
Xinan Lin3ba18a02019-08-13 15:44:55 -0700166 Returns:
167 A service account key.
168 """
Xinan Linc61196b2019-08-13 10:37:30 -0700169 service_credentials = service_account.ServiceAccountCredentials
Xinan Lin3ba18a02019-08-13 15:44:55 -0700170 key = service_credentials.from_json_keyfile_name(sa, self.scope)
Prathmesh Prabhuaf0857f2020-06-20 00:16:32 -0700171 return auth.ServiceAccountKey(client_email=key.service_account_email,
172 private_key=key._private_key_pkcs8_pem,
173 private_key_id=key._private_key_id)
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700174
175
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700176def _form_test_platform_request(task_params):
Jacob Kopczynski408f3fd2020-08-07 13:31:59 -0700177 """Generates test_platform.Request proto to send to buildbucket.
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700178
179 Args:
Jacob Kopczynski408f3fd2020-08-07 13:31:59 -0700180 task_params: dict containing the parameters of a task from the suite queue.
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700181
182 Returns:
Jacob Kopczynski408f3fd2020-08-07 13:31:59 -0700183 A ctp_request.Request instance.
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700184 """
185 build = _infer_build_from_task_params(task_params)
186 if build == 'None':
187 raise BuildbucketRunError('No proper build in task params: %r' %
188 task_params)
189 pool = _infer_pool_from_task_params(task_params)
190 timeout = _infer_timeout_from_task_params(task_params)
191
Jacob Kopczynski408f3fd2020-08-07 13:31:59 -0700192 request = ctp_request.Request()
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700193 params = request.params
194
Xinan Lin4757d6f2020-03-24 22:20:31 -0700195 params.scheduling.CopyFrom(_scheduling_for_pool(pool))
Prathmesh Prabhu46156ff2020-06-20 00:18:52 -0700196 if task_params.get('qs_account') not in ['None', None]:
Xinan Lin4757d6f2020-03-24 22:20:31 -0700197 params.scheduling.qs_account = task_params.get('qs_account')
198 # Quota Scheduler has no concept of priority.
Xinan Lin8bb5b4b2020-07-21 23:17:55 -0700199 if (task_params.get('priority') not in ['None', None]
200 and not params.scheduling.qs_account):
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700201 params.scheduling.priority = int(task_params['priority'])
202
203 params.software_dependencies.add().chromeos_build = build
204 params.software_attributes.build_target.name = task_params['board']
Aviv Keshetc679faf2019-11-27 17:52:50 -0800205
206 gs_url = GS_PREFIX + task_params['test_source_build']
207 params.metadata.test_metadata_url = gs_url
208 params.metadata.debug_symbols_archive_url = gs_url
209
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700210 params.time.maximum_duration.FromTimedelta(timeout)
211
212 for key, value in _request_tags(task_params, build, pool).iteritems():
213 params.decorations.tags.append('%s:%s' % (key, value))
214
Xinan Lin7bf266a2020-06-10 23:54:26 -0700215 for d in _infer_user_defined_dimensions(task_params):
216 params.freeform_attributes.swarming_dimensions.append(d)
Xinan Linba3b9322020-04-24 15:08:12 -0700217
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700218 if task_params['model'] != 'None':
219 params.hardware_attributes.model = task_params['model']
220
221 if task_params['job_retry'] == 'True':
222 params.retry.allow = True
223 params.retry.max = constants.Buildbucket.MAX_RETRY
224
225 fw_rw_build = task_params.get(build_lib.BuildVersionKey.FW_RW_VERSION)
226 fw_ro_build = task_params.get(build_lib.BuildVersionKey.FW_RO_VERSION)
227 # Skip firmware field if None(unspecified) or 'None'(no such build).
228 if fw_ro_build not in (None, 'None'):
229 build = params.software_dependencies.add()
230 build.ro_firmware_build = fw_ro_build
231 if fw_rw_build not in (None, 'None'):
232 build = params.software_dependencies.add()
233 build.rw_firmware_build = fw_rw_build
234
235 request.test_plan.suite.add().name = task_params['suite']
236 return request
237
238
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700239def _scheduling_for_pool(pool):
240 """Assign appropriate pool name to scheduling instance.
241
242 Args:
Xinan Lin1516edb2020-07-05 23:13:54 -0700243 pool: string pool name (e.g. 'MANAGED_POOL_QUOTA', 'wificell').
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700244
245 Returns:
Jacob Kopczynski408f3fd2020-08-07 13:31:59 -0700246 scheduling: A ctp_request.Request.Params.Scheduling instance.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700247 """
Jacob Kopczynski408f3fd2020-08-07 13:31:59 -0700248 mp = ctp_request.Request.Params.Scheduling.ManagedPool
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700249 if mp.DESCRIPTOR.values_by_name.get(pool) is not None:
Jacob Kopczynski408f3fd2020-08-07 13:31:59 -0700250 return ctp_request.Request.Params.Scheduling(managed_pool=mp.Value(pool))
251 return ctp_request.Request.Params.Scheduling(unmanaged_pool=pool)
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700252
253
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700254# Also see: A copy of this function in swarming_lib.py.
255def _infer_build_from_task_params(task_params):
256 """Infer the build to install on the DUT for the scheduled task.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700257
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700258 Args:
259 task_params: The parameters of a task loaded from suite queue.
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700260
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700261 Returns:
262 A string representing the build to run.
263 """
264 cros_build = task_params[build_lib.BuildVersionKey.CROS_VERSION]
265 android_build = task_params[build_lib.BuildVersionKey.ANDROID_BUILD_VERSION]
266 testbed_build = task_params[build_lib.BuildVersionKey.TESTBED_BUILD_VERSION]
267 return cros_build or android_build or testbed_build
268
269
270def _infer_pool_from_task_params(task_params):
271 """Infer the pool to use for the scheduled task.
272
273 Args:
274 task_params: The parameters of a task loaded from suite queue.
275
276 Returns:
277 A string pool to schedule task in.
278 """
279 if task_params.get('override_qs_account'):
280 return 'DUT_POOL_QUOTA'
281 return task_params.get('override_pool') or task_params['pool']
282
283
284def _infer_timeout_from_task_params(task_params):
285 """Infer the timeout for the scheduled task.
286
287 Args:
288 task_params: The parameters of a task loaded from suite queue.
289
290 Returns:
291 A datetime.timedelta instance for the timeout.
292 """
293 timeout_mins = int(task_params['timeout_mins'])
294 # timeout's unit is hour.
295 if task_params.get('timeout'):
Prathmesh Prabhuaf0857f2020-06-20 00:16:32 -0700296 timeout_mins = max(int(task_params['timeout']) * 60, timeout_mins)
Prathmesh Prabhu06852fe2019-09-09 07:58:43 -0700297 if timeout_mins > constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS:
298 timeout_mins = constants.Buildbucket.MAX_BUILDBUCKET_TIMEOUT_MINS
299 return datetime.timedelta(minutes=timeout_mins)
300
Prathmesh Prabhu1918a8f2019-09-07 21:37:37 -0700301
Xinan Linba3b9322020-04-24 15:08:12 -0700302def _infer_user_defined_dimensions(task_params):
303 """Infer the dimensions defined by users.
304
305 Args:
306 task_params: The parameters of a task loaded from suite queue.
307
308 Returns:
309 A list of strings; an empty list if no dimensions set.
310
311 Raises:
312 ValueError: if dimension is not valid.
313 """
314 result = []
315 if task_params.get('dimensions') in (None, 'None'):
316 return result
317 for d in task_params.get('dimensions').split(','):
318 if len(d.split(':')) != 2:
319 raise ValueError(
320 'Job %s has invalid dimensions: %s' %
321 (task_params.get('name'), task_params.get('dimensions')))
322 result.append(d)
323 return result
324
325
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700326def _request_tags(task_params, build, pool):
327 """Infer tags to include in cros_test_platform request.
328
329 Args:
330 task_params: suite task parameters.
331 build: The build included in the request. Must not be None.
332 pool: The DUT pool used for the request. Must not be None.
333
334 Returns:
335 A dict of tags.
336 """
337 tags = {
Prathmesh Prabhuaf0857f2020-06-20 00:16:32 -0700338 'build': build,
339 'label-pool': pool,
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700340 }
Xinan Linfb63d572019-09-24 15:49:04 -0700341 if task_params.get('board') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700342 tags['label-board'] = task_params['board']
Xinan Linfb63d572019-09-24 15:49:04 -0700343 if task_params.get('model') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700344 tags['label-model'] = task_params['model']
Xinan Linfb63d572019-09-24 15:49:04 -0700345 if task_params.get('suite') not in (None, 'None'):
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700346 tags['suite'] = task_params['suite']
347 return tags
348
349
Xinan Linc8647112020-02-04 16:45:56 -0800350def _get_key_val_from_label(label):
351 """A helper to get key and value from the label.
352
353 Args:
354 label: A string of label, should be in the form of
355 key:value, e.g. 'pool:ChromeOSSkylab'.
356 """
357 res = label.split(':')
358 if len(res) == 2:
359 return res[0], res[1]
360 logging.warning('Failed to parse the label, %s', label)
361
362
Dhanya Ganeshedb78cb2020-07-20 19:40:50 +0000363def _bb_tags(suite):
364 """Get all the tags required for Buildbucket.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700365
366 Args:
Dhanya Ganeshedb78cb2020-07-20 19:40:50 +0000367 suite: A string of suite name being scheduled.
Prathmesh Prabhu2382a182019-09-07 21:18:10 -0700368
369 Returns:
370 [bb_common_pb2.StringPair] tags to include the buildbucket request.
371 """
Dhanya Ganeshedb78cb2020-07-20 19:40:50 +0000372 return [bb_common_pb2.StringPair(key='suite', value=suite),
373 bb_common_pb2.StringPair(key='user_agent',
374 value='suite_scheduler')]
Xinan Linc54a7462020-04-17 15:39:01 -0700375
376
377def _should_skip(params):
378 """Decide whether to skip a task based on env and pool.
379
380 Suite request from staging may still have a small chance to run
381 in production. However, for unmanaged pools(e.g. wificell), which
382 usually are small, dev traffic is unacceptable.
383
384 Args:
385 params: dict containing the parameters of a task got from suite
386 queue.
387
388 Returns:
389 A boolean; true for suite targetting non-default pools from staging
390 env.
391 """
392 if constants.application_id() == constants.AppID.PROD_APP:
393 return False
Xinan Lin0d7910d2020-07-21 11:06:45 -0700394 return params['pool'] != 'MANAGED_POOL_QUOTA'