blob: 09f36d0e6bcb575c04a971d51ee94297f46e7240 [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
10import logging
11import re
12
Xixuan Wu5d6063e2017-09-05 16:15:07 -070013import apiclient
14
xixuanbea010f2017-03-27 10:10:19 -070015# Bare branches
16BARE_BRANCHES = ['factory', 'firmware']
17
18# Definition of os types.
19OS_TYPE_CROS = 'cros'
20OS_TYPE_BRILLO = 'brillo'
21OS_TYPE_ANDROID = 'android'
22OS_TYPES = [OS_TYPE_CROS, OS_TYPE_BRILLO, OS_TYPE_ANDROID]
23OS_TYPES_LAUNCH_CONTROL = [OS_TYPE_BRILLO, OS_TYPE_ANDROID]
24
Xixuan Wu5d6063e2017-09-05 16:15:07 -070025# Launch control build's target's information
xixuanbea010f2017-03-27 10:10:19 -070026LaunchControlBuildTargetInfo = collections.namedtuple(
27 'LaunchControlBuildTargetInfo',
28 [
Xixuan Wu5d6063e2017-09-05 16:15:07 -070029 'target',
30 'type',
xixuanbea010f2017-03-27 10:10:19 -070031 ])
32
Xixuan Wu5d6063e2017-09-05 16:15:07 -070033# ChromeOS build config's information
xixuanbea010f2017-03-27 10:10:19 -070034CrOSBuildConfigInfo = collections.namedtuple(
35 'CrOSBuildConfigInfo',
36 [
Xixuan Wu5d6063e2017-09-05 16:15:07 -070037 'board',
38 'type',
xixuanbea010f2017-03-27 10:10:19 -070039 ])
40
xixuanbea010f2017-03-27 10:10:19 -070041# The default build type for fetching latest build.
42_DEFAULT_BUILD_SUFFIX = '-paladin'
43
44# The default setting of board for fetching latest build.
45_DEFAULT_MASTER = 'master'
46
47# The path for storing the latest build.
48_GS_LATEST_MASTER_PATTERN = '%(board)s%(suffix)s/%(name)s'
49
50# The gs bucket to fetch the latest build.
51_GS_BUCKET = 'chromeos-image-archive'
52
53# The file in Google Storage to fetch the latest build.
54_LATEST_MASTER = 'LATEST-master'
55
56# Special android target to board map.
57_ANDROID_TARGET_TO_BOARD_MAP = {
58 'seed_l8150': 'gm4g_sprout',
59 'bat_land': 'bat'
60}
61
62# CrOS build name patter
63_CROS_BUILD_PATTERN = '%(board)s-%(build_type)s/R%(milestone)s-%(manifest)s'
64
65# Android build name pattern
66_ANDROID_BUILD_PATTERN = '%(branch)s/%(target)s/%(build_id)s'
67
68# The pattern for Launch Control target
69_LAUNCH_CONTROL_TARGET_PATTERN = r'(?P<build_target>.+)-(?P<build_type>[^-]+)'
70
71# The pattern for CrOS build config
72_CROS_BUILD_CONFIG_PATTERN = r'-([^-]+)(?:-group)?'
Xixuan Wu5d6063e2017-09-05 16:15:07 -070073
74
75class NoBuildError(Exception):
76 """Raised when failing to get the required build from Google Storage."""
77
78
79class BuildType(object):
80 """Representing the type of test source build.
81
82 This is used to identify the test source build for testing.
83 """
84 FIRMWARE_RW = 'firmware_rw'
85 FIRMWARE_RO = 'firmware_ro'
86 CROS = 'cros'
87
88
89class BuildVersionKey(object):
90 """Keys referring to the builds to install in run_suites."""
91
92 CROS_VERSION = 'cros_version'
93 ANDROID_BUILD_VERSION = 'android_version'
94 TESTBED_BUILD_VERSION = 'testbed_version'
95 FW_RW_VERSION = 'fwrw_version'
96 FW_RO_VERSION = 'fwro_version'
97
98
99class AndroidBuild(collections.namedtuple(
100 '_AndroidBuildBase', ['branch', 'target', 'build_id']), object):
101 """Class for constructing android build string."""
102
103 def __str__(self):
104 return _ANDROID_BUILD_PATTERN % {'branch': self.branch,
105 'target': self.target,
106 'build_id': self.build_id}
107
108
109class CrOSBuild(collections.namedtuple(
110 '_CrOSBuildBase',
111 ['board', 'build_type', 'milestone', 'manifest']), object):
112 """Class for constructing ChromeOS build string."""
113
114 def __str__(self):
115 return _CROS_BUILD_PATTERN % {'board': self.board,
116 'build_type': self.build_type,
117 'milestone': self.milestone,
118 'manifest': self.manifest}
119
120
121def get_latest_cros_build_from_gs(storage_client, board=None, suffix=None):
122 """Get latest build for given board from Google Storage.
123
124 Args:
125 storage_client: a rest_client.StorageRestClient object.
126 board: the board to fetch latest build. Default is 'master'.
127 suffix: suffix represents build channel, like '-release'.
128 Default is '-paladin'.
129
130 Returns:
131 a ChromeOS version string, e.g. '59.0.000.0'.
132
133 Raises:
134 HttpError if error happens in interacting with Google Storage.
135 """
136 board = board if board is not None else _DEFAULT_MASTER
137 suffix = suffix if suffix is not None else _DEFAULT_BUILD_SUFFIX
138 file_to_check = _GS_LATEST_MASTER_PATTERN % {
139 'board': board,
140 'suffix': suffix,
141 'name': _LATEST_MASTER}
142
143 try:
144 return storage_client.read_object(_GS_BUCKET, file_to_check)
145 except apiclient.errors.HttpError as e:
146 raise NoBuildError(
147 'Cannot find latest build for board %s, suffix %s: %s' %
148 (board, suffix, str(e)))
149
150
151def get_cros_builds_since_date_from_db(db_client, since_date):
152 """Get branch builds for ChromeOS boards.
153
154 Args:
155 db_client: a cloud_sql_client.CIDBClient object, to read cidb
156 build infos.
157 since_date: a datetime.datetime object in UTC to indicate since when CrOS
158 builds will be fetched.
159
160 Returns:
161 a branch build dict:
162 key: a tuple of (board, build_type, milestone), like:
163 ('wolf', 'release', '58')
164 value: the latest manifest for the given tuple, like:
165 '9242.0.0'.
166 """
167 # CIDB use UTC timezone
168 all_branch_builds = db_client.get_passed_builds_since_date(since_date)
169
170 branch_build_dict = {}
171 for build in all_branch_builds:
172 try:
173 build_config_info = parse_cros_build_config(build.board,
174 build.build_config)
175 except ValueError as e:
176 logging.warning('Failed to parse build config: %s: %s',
177 build.build_config, e)
178 continue
179
180 if build.board != build_config_info.board:
181 logging.warning('Non-matched build_config and board: %s, %s',
182 build.board, build.board)
183 continue
184
185 build_key = (build.board, build_config_info.type, build.milestone)
186 cur_manifest = branch_build_dict.get(build_key)
187 if cur_manifest is not None:
188 branch_build_dict[build_key] = max(
189 [cur_manifest, build.platform], key=version.LooseVersion)
190 else:
191 branch_build_dict[build_key] = build.platform
192
193 return branch_build_dict
194
195
196def get_latest_launch_control_build(android_client, branch, target):
197 """Get the latest launch control build from Android Build API.
198
199 Args:
200 android_client: a rest_client.AndroidBuildRestClient object.
201 branch: the launch control branch.
202 target: the launch control target.
203
204 Returns:
205 a string latest launch control build id.
206
207 Raises:
208 NoBuildError if no latest launch control build is found.
209 """
210 try:
211 latest_build_id = android_client.get_latest_build_id(branch, target)
212 if latest_build_id is None:
213 raise NoBuildError('No latest builds is found.')
214
215 return latest_build_id
216 except apiclient.errors.HttpError as e:
217 raise NoBuildError('HttpError happened in getting the latest launch '
218 'control build for '
219 '%s,%s: %s' % (branch, target, str(e)))
220
221
222def get_launch_control_builds_by_branch_targets(
223 android_client, android_board_list, launch_control_branch_targets):
224 """Get latest launch_control_builds for android boards.
225
226 For every tasks in this event, if it has settings of launch control
227 branch & target, get the latest launch control build for it.
228
229 Args:
230 android_client: a rest_client.AndroidBuildRestClient object to
231 interact with android build API.
232 android_board_list: a list of Android boards.
233 launch_control_branch_targets: a dict of branch:targets, see property
234 launch_control_branch_targets in base_event.py.
235
236 Returns:
237 a launch control build dict:
238 key: an android board, like 'shamu'.
239 value: a list involves the latest builds for each pair
240 (branch, target) of this board, like:
241 [u'git_nyc-mr2-release/shamu-userdebug/3844975',
242 u'git_nyc-mr1-release/shamu-userdebug/3783920']
243 """
244 launch_control_dict = {}
245 board_to_builds_dict = {}
246 for branch, targets in launch_control_branch_targets.iteritems():
247 for t in targets:
248 try:
249 board = parse_launch_control_target(t).target
250 except ValueError:
251 logging.warning(
252 'Failed to parse launch control target: %s', t)
253 continue
254
255 if board not in android_board_list:
256 continue
257
258 # Use dict here to reduce the times to call AndroidBuild API
259 if launch_control_dict.get((branch, t)) is None:
260 try:
261 build_id = get_latest_launch_control_build(
262 android_client, branch, t)
263 except NoBuildError as e:
264 logging.warning(e)
265 continue
266
267 build = str(AndroidBuild(branch, t, build_id))
268 launch_control_dict[(branch, t)] = build
269 board_to_builds_dict.setdefault(board, []).append(
270 build)
271
272 for board, in board_to_builds_dict.iteritems():
273 mapped_board = get_board_by_android_target(board)
274 if mapped_board != board:
275 logging.debug('Map board %s to %s', board, mapped_board)
276 if board_to_builds_dict.get(mapped_board) is None:
277 del board_to_builds_dict[board]
278 else:
279 board_to_builds_dict[board] = board_to_builds_dict[
280 mapped_board]
281
282 return board_to_builds_dict
283
284
285def parse_launch_control_target(target):
286 """Parse the build target and type from a Launch Control target.
287
288 The Launch Control target has the format of build_target-build_type, e.g.,
289 shamu-eng or dragonboard-userdebug. This method extracts the build target
290 and type from the target name.
291
292 Args:
293 target: Name of a Launch Control target, e.g., shamu-userdebug.
294
295 Returns:
296 a LaunchControlBuildTargetInfo object whose value is like
297 (target='shamu',
298 type='userdebug')
299
300 Raises:
301 ValueError: if target is not valid.
302 """
303 match = re.match(_LAUNCH_CONTROL_TARGET_PATTERN, target)
304 if not match:
305 raise ValueError('target format is not valid')
306
307 return LaunchControlBuildTargetInfo(match.group('build_target'),
308 match.group('build_type'))
309
310
311def parse_cros_build_config(board, build_config):
312 """Parse build_type from a given builder for a given board.
313
314 Args:
315 board: the prefix of a ChromeOS build_config, representing board.
316 build_config: a ChromeOS build_config name, like 'kevin-release'.
317
318 Returns:
319 a CrOSBuildConfigInfo object whose value is like
320 (board='kevin',
321 type='release')
322
323 Raises:
324 ValueError: if build_config is in invalid form.
325 """
326 if build_config[0:len(board)] != board:
327 raise ValueError('build_config cannot be parsed: %s' % build_config)
328
329 match = re.match(_CROS_BUILD_CONFIG_PATTERN, build_config[len(board):])
330 if not match:
331 raise ValueError('build_config %s is not matched %s' % (
332 build_config, _CROS_BUILD_CONFIG_PATTERN))
333
334 return CrOSBuildConfigInfo(board, match.groups()[0])
335
336
337def get_board_by_android_target(target):
338 """Map a android target to a android board.
339
340 # Mapping between an android board name and a build target. This is for
341 # special case handling for certain Android board that the board name and
342 # build target name does not match.
343 # This comes from server/site_utils.py in autotest module.
344
345 Args:
346 target: an android target.
347
348 Returns:
349 a string android board mapped by ANDROID_TARGET_TO_BOARD_MAP.
350 """
351 return _ANDROID_TARGET_TO_BOARD_MAP.get(target, target)