blob: 860d92d80c7bd63e794d7e8117aceaf3245407c3 [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
Xixuan Wu6fb16272017-10-19 13:16:00 -0700151def get_cros_builds_since_date_from_db(db_client, cros_board_list, since_date):
Xixuan Wu5d6063e2017-09-05 16:15:07 -0700152 """Get branch builds for ChromeOS boards.
153
154 Args:
155 db_client: a cloud_sql_client.CIDBClient object, to read cidb
156 build infos.
Xixuan Wu6fb16272017-10-19 13:16:00 -0700157 cros_board_list: The board list including all CrOS boards.
Xixuan Wu5d6063e2017-09-05 16:15:07 -0700158 since_date: a datetime.datetime object in UTC to indicate since when CrOS
159 builds will be fetched.
160
161 Returns:
162 a branch build dict:
163 key: a tuple of (board, build_type, milestone), like:
164 ('wolf', 'release', '58')
165 value: the latest manifest for the given tuple, like:
166 '9242.0.0'.
167 """
168 # CIDB use UTC timezone
169 all_branch_builds = db_client.get_passed_builds_since_date(since_date)
170
171 branch_build_dict = {}
172 for build in all_branch_builds:
173 try:
174 build_config_info = parse_cros_build_config(build.board,
175 build.build_config)
176 except ValueError as e:
177 logging.warning('Failed to parse build config: %s: %s',
178 build.build_config, e)
179 continue
180
181 if build.board != build_config_info.board:
182 logging.warning('Non-matched build_config and board: %s, %s',
183 build.board, build.board)
184 continue
185
Xixuan Wu6fb16272017-10-19 13:16:00 -0700186 if build.board not in cros_board_list:
187 logging.warning('%s is not a valid CrOS board.', build.board)
188 continue
189
Xixuan Wu5d6063e2017-09-05 16:15:07 -0700190 build_key = (build.board, build_config_info.type, build.milestone)
191 cur_manifest = branch_build_dict.get(build_key)
192 if cur_manifest is not None:
193 branch_build_dict[build_key] = max(
194 [cur_manifest, build.platform], key=version.LooseVersion)
195 else:
196 branch_build_dict[build_key] = build.platform
197
198 return branch_build_dict
199
200
201def get_latest_launch_control_build(android_client, branch, target):
202 """Get the latest launch control build from Android Build API.
203
204 Args:
205 android_client: a rest_client.AndroidBuildRestClient object.
206 branch: the launch control branch.
207 target: the launch control target.
208
209 Returns:
210 a string latest launch control build id.
211
212 Raises:
213 NoBuildError if no latest launch control build is found.
214 """
215 try:
216 latest_build_id = android_client.get_latest_build_id(branch, target)
217 if latest_build_id is None:
218 raise NoBuildError('No latest builds is found.')
219
220 return latest_build_id
221 except apiclient.errors.HttpError as e:
222 raise NoBuildError('HttpError happened in getting the latest launch '
223 'control build for '
224 '%s,%s: %s' % (branch, target, str(e)))
225
226
227def get_launch_control_builds_by_branch_targets(
228 android_client, android_board_list, launch_control_branch_targets):
229 """Get latest launch_control_builds for android boards.
230
231 For every tasks in this event, if it has settings of launch control
232 branch & target, get the latest launch control build for it.
233
234 Args:
235 android_client: a rest_client.AndroidBuildRestClient object to
236 interact with android build API.
237 android_board_list: a list of Android boards.
238 launch_control_branch_targets: a dict of branch:targets, see property
239 launch_control_branch_targets in base_event.py.
240
241 Returns:
242 a launch control build dict:
243 key: an android board, like 'shamu'.
244 value: a list involves the latest builds for each pair
245 (branch, target) of this board, like:
246 [u'git_nyc-mr2-release/shamu-userdebug/3844975',
247 u'git_nyc-mr1-release/shamu-userdebug/3783920']
248 """
249 launch_control_dict = {}
250 board_to_builds_dict = {}
251 for branch, targets in launch_control_branch_targets.iteritems():
252 for t in targets:
253 try:
254 board = parse_launch_control_target(t).target
255 except ValueError:
256 logging.warning(
257 'Failed to parse launch control target: %s', t)
258 continue
259
260 if board not in android_board_list:
261 continue
262
263 # Use dict here to reduce the times to call AndroidBuild API
264 if launch_control_dict.get((branch, t)) is None:
265 try:
266 build_id = get_latest_launch_control_build(
267 android_client, branch, t)
268 except NoBuildError as e:
269 logging.warning(e)
270 continue
271
272 build = str(AndroidBuild(branch, t, build_id))
273 launch_control_dict[(branch, t)] = build
274 board_to_builds_dict.setdefault(board, []).append(
275 build)
276
277 for board, in board_to_builds_dict.iteritems():
278 mapped_board = get_board_by_android_target(board)
279 if mapped_board != board:
280 logging.debug('Map board %s to %s', board, mapped_board)
281 if board_to_builds_dict.get(mapped_board) is None:
282 del board_to_builds_dict[board]
283 else:
284 board_to_builds_dict[board] = board_to_builds_dict[
285 mapped_board]
286
287 return board_to_builds_dict
288
289
290def parse_launch_control_target(target):
291 """Parse the build target and type from a Launch Control target.
292
293 The Launch Control target has the format of build_target-build_type, e.g.,
294 shamu-eng or dragonboard-userdebug. This method extracts the build target
295 and type from the target name.
296
297 Args:
298 target: Name of a Launch Control target, e.g., shamu-userdebug.
299
300 Returns:
301 a LaunchControlBuildTargetInfo object whose value is like
302 (target='shamu',
303 type='userdebug')
304
305 Raises:
306 ValueError: if target is not valid.
307 """
308 match = re.match(_LAUNCH_CONTROL_TARGET_PATTERN, target)
309 if not match:
310 raise ValueError('target format is not valid')
311
312 return LaunchControlBuildTargetInfo(match.group('build_target'),
313 match.group('build_type'))
314
315
316def parse_cros_build_config(board, build_config):
317 """Parse build_type from a given builder for a given board.
318
319 Args:
320 board: the prefix of a ChromeOS build_config, representing board.
321 build_config: a ChromeOS build_config name, like 'kevin-release'.
322
323 Returns:
324 a CrOSBuildConfigInfo object whose value is like
325 (board='kevin',
326 type='release')
327
328 Raises:
329 ValueError: if build_config is in invalid form.
330 """
331 if build_config[0:len(board)] != board:
332 raise ValueError('build_config cannot be parsed: %s' % build_config)
333
334 match = re.match(_CROS_BUILD_CONFIG_PATTERN, build_config[len(board):])
335 if not match:
336 raise ValueError('build_config %s is not matched %s' % (
337 build_config, _CROS_BUILD_CONFIG_PATTERN))
338
339 return CrOSBuildConfigInfo(board, match.groups()[0])
340
341
342def get_board_by_android_target(target):
343 """Map a android target to a android board.
344
345 # Mapping between an android board name and a build target. This is for
346 # special case handling for certain Android board that the board name and
347 # build target name does not match.
348 # This comes from server/site_utils.py in autotest module.
349
350 Args:
351 target: an android target.
352
353 Returns:
354 a string android board mapped by ANDROID_TARGET_TO_BOARD_MAP.
355 """
356 return _ANDROID_TARGET_TO_BOARD_MAP.get(target, target)