blob: d086789d874b493c013645a1c089f7c59c79c511 [file] [log] [blame]
xixuanbea010f2017-03-27 10:10:19 -07001# Copyright 2017 The Chromium OS Authors. All rights reserved.
2# 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 ChromeOS & Android build related logic in suite scheduler."""
Xixuan Wu5d6063e2017-09-05 16:15:07 -07006# pylint: disable=g-bad-import-order
xixuanbea010f2017-03-27 10:10:19 -07007
Xixuan Wu5d6063e2017-09-05 16:15:07 -07008from distutils import version
xixuanbea010f2017-03-27 10:10:19 -07009import collections
Xixuan Wu244e0ec2018-05-23 14:49:55 -070010import json
xixuanbea010f2017-03-27 10:10:19 -070011import logging
12import re
13
Xixuan Wu5d6063e2017-09-05 16:15:07 -070014import apiclient
15
xixuanbea010f2017-03-27 10:10:19 -070016# Bare branches
17BARE_BRANCHES = ['factory', 'firmware']
18
19# Definition of os types.
20OS_TYPE_CROS = 'cros'
21OS_TYPE_BRILLO = 'brillo'
22OS_TYPE_ANDROID = 'android'
23OS_TYPES = [OS_TYPE_CROS, OS_TYPE_BRILLO, OS_TYPE_ANDROID]
24OS_TYPES_LAUNCH_CONTROL = [OS_TYPE_BRILLO, OS_TYPE_ANDROID]
25
Xixuan Wu5d6063e2017-09-05 16:15:07 -070026# Launch control build's target's information
xixuanbea010f2017-03-27 10:10:19 -070027LaunchControlBuildTargetInfo = collections.namedtuple(
28 'LaunchControlBuildTargetInfo',
29 [
Xixuan Wu5d6063e2017-09-05 16:15:07 -070030 'target',
31 'type',
xixuanbea010f2017-03-27 10:10:19 -070032 ])
33
Xixuan Wu5d6063e2017-09-05 16:15:07 -070034# ChromeOS build config's information
xixuanbea010f2017-03-27 10:10:19 -070035CrOSBuildConfigInfo = collections.namedtuple(
36 'CrOSBuildConfigInfo',
37 [
Xixuan Wu5d6063e2017-09-05 16:15:07 -070038 'board',
39 'type',
xixuanbea010f2017-03-27 10:10:19 -070040 ])
41
xixuanbea010f2017-03-27 10:10:19 -070042# The default build type for fetching latest build.
Xixuan Wu7899db52018-05-29 14:19:06 -070043_DEFAULT_BUILD_SUFFIX = '-release'
xixuanbea010f2017-03-27 10:10:19 -070044
45# The default setting of board for fetching latest build.
46_DEFAULT_MASTER = 'master'
47
48# The path for storing the latest build.
49_GS_LATEST_MASTER_PATTERN = '%(board)s%(suffix)s/%(name)s'
50
51# The gs bucket to fetch the latest build.
52_GS_BUCKET = 'chromeos-image-archive'
53
54# The file in Google Storage to fetch the latest build.
55_LATEST_MASTER = 'LATEST-master'
56
Xixuan Wu244e0ec2018-05-23 14:49:55 -070057# The bucket for ChromeOS build release boards. Maintained by GoldenEye.
58_GE_RELEASE_BUILD_BUCKET = 'chromeos-build-release-console'
59
xixuanbea010f2017-03-27 10:10:19 -070060# Special android target to board map.
61_ANDROID_TARGET_TO_BOARD_MAP = {
62 'seed_l8150': 'gm4g_sprout',
63 'bat_land': 'bat'
64}
65
66# CrOS build name patter
67_CROS_BUILD_PATTERN = '%(board)s-%(build_type)s/R%(milestone)s-%(manifest)s'
68
69# Android build name pattern
70_ANDROID_BUILD_PATTERN = '%(branch)s/%(target)s/%(build_id)s'
71
72# The pattern for Launch Control target
73_LAUNCH_CONTROL_TARGET_PATTERN = r'(?P<build_target>.+)-(?P<build_type>[^-]+)'
74
75# The pattern for CrOS build config
76_CROS_BUILD_CONFIG_PATTERN = r'-([^-]+)(?:-group)?'
Xixuan Wu5d6063e2017-09-05 16:15:07 -070077
78
79class NoBuildError(Exception):
80 """Raised when failing to get the required build from Google Storage."""
81
82
83class BuildType(object):
84 """Representing the type of test source build.
85
86 This is used to identify the test source build for testing.
87 """
88 FIRMWARE_RW = 'firmware_rw'
89 FIRMWARE_RO = 'firmware_ro'
90 CROS = 'cros'
91
92
93class BuildVersionKey(object):
94 """Keys referring to the builds to install in run_suites."""
95
96 CROS_VERSION = 'cros_version'
97 ANDROID_BUILD_VERSION = 'android_version'
98 TESTBED_BUILD_VERSION = 'testbed_version'
99 FW_RW_VERSION = 'fwrw_version'
100 FW_RO_VERSION = 'fwro_version'
101
102
103class AndroidBuild(collections.namedtuple(
104 '_AndroidBuildBase', ['branch', 'target', 'build_id']), object):
105 """Class for constructing android build string."""
106
107 def __str__(self):
108 return _ANDROID_BUILD_PATTERN % {'branch': self.branch,
109 'target': self.target,
110 'build_id': self.build_id}
111
112
113class CrOSBuild(collections.namedtuple(
114 '_CrOSBuildBase',
115 ['board', 'build_type', 'milestone', 'manifest']), object):
116 """Class for constructing ChromeOS build string."""
117
118 def __str__(self):
119 return _CROS_BUILD_PATTERN % {'board': self.board,
120 'build_type': self.build_type,
121 'milestone': self.milestone,
122 'manifest': self.manifest}
123
124
125def get_latest_cros_build_from_gs(storage_client, board=None, suffix=None):
126 """Get latest build for given board from Google Storage.
127
128 Args:
129 storage_client: a rest_client.StorageRestClient object.
130 board: the board to fetch latest build. Default is 'master'.
131 suffix: suffix represents build channel, like '-release'.
132 Default is '-paladin'.
133
134 Returns:
135 a ChromeOS version string, e.g. '59.0.000.0'.
136
137 Raises:
138 HttpError if error happens in interacting with Google Storage.
139 """
140 board = board if board is not None else _DEFAULT_MASTER
141 suffix = suffix if suffix is not None else _DEFAULT_BUILD_SUFFIX
142 file_to_check = _GS_LATEST_MASTER_PATTERN % {
143 'board': board,
144 'suffix': suffix,
145 'name': _LATEST_MASTER}
146
147 try:
148 return storage_client.read_object(_GS_BUCKET, file_to_check)
149 except apiclient.errors.HttpError as e:
150 raise NoBuildError(
151 'Cannot find latest build for board %s, suffix %s: %s' %
152 (board, suffix, str(e)))
153
154
Xixuan Wu244e0ec2018-05-23 14:49:55 -0700155def get_board_family_mapping_from_gs(storage_client):
156 """Get board_family to boards mapping from Google Storage.
157
158 Args:
159 storage_client: a rest_client.StorageRestClient object.
160
161 Returns:
162 a dictionary of mapping between board family name to boards, e.g.
163 {'nyan': ['nyan', 'nyan_big', 'nyan_blaze', ..]}
164
165 Raises:
166 HttpError if error happens in interacting with Google Storage.
167 """
168 try:
169 boards = storage_client.read_object(_GE_RELEASE_BUILD_BUCKET, 'boards.json')
170 json_object = json.loads(boards)
171 board_family = {}
172 for board in json_object['boards']:
173 group = board['reference_group']
174 if not group:
175 continue
176
177 # This is to change boards like nyan-blaze to nyan_blaze, which is
178 # actually used in lab.
179 board_name = board['public_codename'].replace('-', '_')
180 if group not in board_family:
181 board_family[group] = []
182
183 board_family[group].append(board_name)
184
185 logging.info('Successfully get following board families from GS: %r',
186 board_family.keys())
187 return board_family
188 except apiclient.errors.HttpError as e:
189 logging.error('Cannot load boards.json in bucket %s: %s',
190 _GE_RELEASE_BUILD_BUCKET, str(e))
191 raise
192
193
Craig Bergstrom58263d32018-04-26 14:11:35 -0600194def buildinfo_list_to_branch_build_dict(cros_board_list, buildinfo_list):
195 """Validate and convert a list of BuildInfo to branch build dict.
Xixuan Wu5d6063e2017-09-05 16:15:07 -0700196
197 Args:
Xixuan Wu6fb16272017-10-19 13:16:00 -0700198 cros_board_list: The board list including all CrOS boards.
Craig Bergstrom58263d32018-04-26 14:11:35 -0600199 buildinfo_list: A list of BuildInfo objects obtained from CIDB.
Xixuan Wu5d6063e2017-09-05 16:15:07 -0700200
201 Returns:
Craig Bergstrom58263d32018-04-26 14:11:35 -0600202 A branch build dict:
203 key: a tuple of (board, build_type, milestone), like:
204 ('wolf', 'release', '58')
205 value: the latest manifest for the given tuple, like:
206 '9242.0.0'.
Xixuan Wu5d6063e2017-09-05 16:15:07 -0700207 """
Xixuan Wu5d6063e2017-09-05 16:15:07 -0700208 branch_build_dict = {}
Craig Bergstrom58263d32018-04-26 14:11:35 -0600209 for build in buildinfo_list:
Xixuan Wu5d6063e2017-09-05 16:15:07 -0700210 try:
211 build_config_info = parse_cros_build_config(build.board,
212 build.build_config)
213 except ValueError as e:
214 logging.warning('Failed to parse build config: %s: %s',
215 build.build_config, e)
216 continue
217
218 if build.board != build_config_info.board:
219 logging.warning('Non-matched build_config and board: %s, %s',
220 build.board, build.board)
221 continue
222
Xixuan Wu6fb16272017-10-19 13:16:00 -0700223 if build.board not in cros_board_list:
224 logging.warning('%s is not a valid CrOS board.', build.board)
225 continue
226
Xixuan Wu5d6063e2017-09-05 16:15:07 -0700227 build_key = (build.board, build_config_info.type, build.milestone)
228 cur_manifest = branch_build_dict.get(build_key)
229 if cur_manifest is not None:
230 branch_build_dict[build_key] = max(
231 [cur_manifest, build.platform], key=version.LooseVersion)
232 else:
233 branch_build_dict[build_key] = build.platform
234
235 return branch_build_dict
236
237
Craig Bergstrom58263d32018-04-26 14:11:35 -0600238def get_cros_builds_since_date_from_db(db_client, cros_board_list, since_date):
239 """Get branch builds for ChromeOS boards.
240
241 Args:
242 db_client: a cloud_sql_client.CIDBClient object, to read cidb
243 build infos.
244 cros_board_list: The board list including all CrOS boards.
245 since_date: a datetime.datetime object in UTC to indicate since when CrOS
246 builds will be fetched.
247
248 Returns:
249 a two-tuple of branch build dicts. Each branch build dict has
250 keys and value described below. The first build_dict describes
251 successful builds and the second describes builds that failed
252 but met the relaxed success requirement (a successful 'HWTest [sanity]'
253 stage).
254 key: a tuple of (board, build_type, milestone), like:
255 ('wolf', 'release', '58')
256 value: the latest manifest for the given tuple, like:
257 '9242.0.0'.
258 """
259 # CIDB use UTC timezone
260 all_branch_builds = db_client.get_passed_builds_since_date(since_date)
261 relaxed_builds = db_client.get_relaxed_pased_builds_since_date(since_date)
262
263 branch_builds_dict = buildinfo_list_to_branch_build_dict(
264 cros_board_list, all_branch_builds)
265 relaxed_builds_dict = buildinfo_list_to_branch_build_dict(
Xixuan Wu384f9132018-08-28 15:48:26 -0700266 cros_board_list, relaxed_builds + all_branch_builds)
Craig Bergstrom58263d32018-04-26 14:11:35 -0600267
268 return branch_builds_dict, relaxed_builds_dict
269
270
Xixuan Wu5d6063e2017-09-05 16:15:07 -0700271def get_latest_launch_control_build(android_client, branch, target):
272 """Get the latest launch control build from Android Build API.
273
274 Args:
275 android_client: a rest_client.AndroidBuildRestClient object.
276 branch: the launch control branch.
277 target: the launch control target.
278
279 Returns:
280 a string latest launch control build id.
281
282 Raises:
283 NoBuildError if no latest launch control build is found.
284 """
285 try:
286 latest_build_id = android_client.get_latest_build_id(branch, target)
287 if latest_build_id is None:
288 raise NoBuildError('No latest builds is found.')
289
290 return latest_build_id
291 except apiclient.errors.HttpError as e:
292 raise NoBuildError('HttpError happened in getting the latest launch '
293 'control build for '
294 '%s,%s: %s' % (branch, target, str(e)))
295
296
297def get_launch_control_builds_by_branch_targets(
298 android_client, android_board_list, launch_control_branch_targets):
299 """Get latest launch_control_builds for android boards.
300
301 For every tasks in this event, if it has settings of launch control
302 branch & target, get the latest launch control build for it.
303
304 Args:
305 android_client: a rest_client.AndroidBuildRestClient object to
306 interact with android build API.
307 android_board_list: a list of Android boards.
308 launch_control_branch_targets: a dict of branch:targets, see property
309 launch_control_branch_targets in base_event.py.
310
311 Returns:
312 a launch control build dict:
313 key: an android board, like 'shamu'.
314 value: a list involves the latest builds for each pair
315 (branch, target) of this board, like:
316 [u'git_nyc-mr2-release/shamu-userdebug/3844975',
317 u'git_nyc-mr1-release/shamu-userdebug/3783920']
318 """
319 launch_control_dict = {}
320 board_to_builds_dict = {}
321 for branch, targets in launch_control_branch_targets.iteritems():
322 for t in targets:
323 try:
324 board = parse_launch_control_target(t).target
325 except ValueError:
326 logging.warning(
327 'Failed to parse launch control target: %s', t)
328 continue
329
330 if board not in android_board_list:
331 continue
332
333 # Use dict here to reduce the times to call AndroidBuild API
334 if launch_control_dict.get((branch, t)) is None:
335 try:
336 build_id = get_latest_launch_control_build(
337 android_client, branch, t)
338 except NoBuildError as e:
339 logging.warning(e)
340 continue
341
342 build = str(AndroidBuild(branch, t, build_id))
343 launch_control_dict[(branch, t)] = build
344 board_to_builds_dict.setdefault(board, []).append(
345 build)
346
347 for board, in board_to_builds_dict.iteritems():
348 mapped_board = get_board_by_android_target(board)
349 if mapped_board != board:
350 logging.debug('Map board %s to %s', board, mapped_board)
351 if board_to_builds_dict.get(mapped_board) is None:
352 del board_to_builds_dict[board]
353 else:
354 board_to_builds_dict[board] = board_to_builds_dict[
355 mapped_board]
356
357 return board_to_builds_dict
358
359
360def parse_launch_control_target(target):
361 """Parse the build target and type from a Launch Control target.
362
363 The Launch Control target has the format of build_target-build_type, e.g.,
364 shamu-eng or dragonboard-userdebug. This method extracts the build target
365 and type from the target name.
366
367 Args:
368 target: Name of a Launch Control target, e.g., shamu-userdebug.
369
370 Returns:
371 a LaunchControlBuildTargetInfo object whose value is like
372 (target='shamu',
373 type='userdebug')
374
375 Raises:
376 ValueError: if target is not valid.
377 """
378 match = re.match(_LAUNCH_CONTROL_TARGET_PATTERN, target)
379 if not match:
380 raise ValueError('target format is not valid')
381
382 return LaunchControlBuildTargetInfo(match.group('build_target'),
383 match.group('build_type'))
384
385
386def parse_cros_build_config(board, build_config):
387 """Parse build_type from a given builder for a given board.
388
389 Args:
390 board: the prefix of a ChromeOS build_config, representing board.
391 build_config: a ChromeOS build_config name, like 'kevin-release'.
392
393 Returns:
394 a CrOSBuildConfigInfo object whose value is like
395 (board='kevin',
396 type='release')
397
398 Raises:
399 ValueError: if build_config is in invalid form.
400 """
401 if build_config[0:len(board)] != board:
402 raise ValueError('build_config cannot be parsed: %s' % build_config)
403
404 match = re.match(_CROS_BUILD_CONFIG_PATTERN, build_config[len(board):])
405 if not match:
406 raise ValueError('build_config %s is not matched %s' % (
407 build_config, _CROS_BUILD_CONFIG_PATTERN))
408
409 return CrOSBuildConfigInfo(board, match.groups()[0])
410
411
412def get_board_by_android_target(target):
413 """Map a android target to a android board.
414
415 # Mapping between an android board name and a build target. This is for
416 # special case handling for certain Android board that the board name and
417 # build target name does not match.
418 # This comes from server/site_utils.py in autotest module.
419
420 Args:
421 target: an android target.
422
423 Returns:
424 a string android board mapped by ANDROID_TARGET_TO_BOARD_MAP.
425 """
426 return _ANDROID_TARGET_TO_BOARD_MAP.get(target, target)