blob: 0cd8e3dc59fdadd50a857769edb0f7ac0bc06743 [file] [log] [blame]
Kuang-che Wu6e4beca2018-06-27 17:45:02 +08001# -*- coding: utf-8 -*-
Kuang-che Wu708310b2018-03-28 17:24:34 +08002# Copyright 2018 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5"""Android utility.
6
7Terminology used in this module:
8 "product-variant" is sometimes called "target" and sometimes "flavor".
9 I prefer to use "flavor" in the code because
10 - "target" is too general
11 - sometimes, it is not in the form of "product-variant", for example,
12 "cts_arm_64"
13"""
14
15from __future__ import print_function
16import json
17import logging
18import os
Kuang-che Wud1d45b42018-07-05 00:46:45 +080019import tempfile
Kuang-che Wu708310b2018-03-28 17:24:34 +080020
21from bisect_kit import cli
Kuang-che Wud1d45b42018-07-05 00:46:45 +080022from bisect_kit import codechange
Kuang-che Wue121fae2018-11-09 16:18:39 +080023from bisect_kit import errors
Kuang-che Wud1d45b42018-07-05 00:46:45 +080024from bisect_kit import git_util
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080025from bisect_kit import repo_util
Kuang-che Wu708310b2018-03-28 17:24:34 +080026from bisect_kit import util
27
28logger = logging.getLogger(__name__)
29
30ANDROID_URL_BASE = ('https://android-build.googleplex.com/'
31 'builds/branch/{branch}')
32BUILD_IDS_BETWEEN_URL_TEMPLATE = (
33 ANDROID_URL_BASE + '/build-ids/between/{end}/{start}')
34BUILD_INFO_URL_TEMPLATE = ANDROID_URL_BASE + '/builds?id={build_id}'
35
36
37def is_android_build_id(s):
38 """Is an Android build id."""
39 # Build ID is always a number
40 return s.isdigit()
41
42
43def argtype_android_build_id(s):
44 if not is_android_build_id(s):
45 msg = 'invalid android build id (%s)' % s
46 raise cli.ArgTypeError(msg, '9876543')
47 return s
48
49
50def fetch_android_build_data(url):
51 """Fetches file from android build server.
52
53 Args:
54 url: URL to fetch
55
56 Returns:
57 file content (str). None if failed.
58 """
Kuang-che Wuacb6efd2018-04-25 18:52:58 +080059 # Fetching android build data directly will fail without authentication.
Kuang-che Wu708310b2018-03-28 17:24:34 +080060 # Following code is just serving as demo purpose. You should modify or hook
61 # it with your own implementation.
62 logger.warn('fetch_android_build_data need to be hooked')
63 import urllib2
64 try:
65 return urllib2.urlopen(url).read()
Kuang-che Wue121fae2018-11-09 16:18:39 +080066 except urllib2.URLError as e:
Kuang-che Wu708310b2018-03-28 17:24:34 +080067 logger.exception('failed to fetch "%s"', url)
Kuang-che Wue121fae2018-11-09 16:18:39 +080068 raise errors.ExternalError(str(e))
Kuang-che Wu708310b2018-03-28 17:24:34 +080069
70
71def is_good_build(branch, flavor, build_id):
72 """Determine a build_id was succeeded.
73
74 Args:
75 branch: The Android branch from which to retrieve the builds.
76 flavor: Target name of the Android image in question.
77 E.g. "cheets_x86-userdebug" or "cheets_arm-user".
78 build_id: Android build id
79
80 Returns:
81 True if the given build was successful.
82 """
83
84 url = BUILD_INFO_URL_TEMPLATE.format(branch=branch, build_id=build_id)
85 build = json.loads(fetch_android_build_data(url).decode('utf-8'))
86 for target in build[0]['targets']:
87 if target['target']['name'] == flavor and target.get('successful'):
88 return True
89 return False
90
91
92def get_build_ids_between(branch, start, end):
93 """Returns a list of build IDs.
94
95 Args:
96 branch: The Android branch from which to retrieve the builds.
97 start: The starting point build ID. (inclusive)
98 end: The ending point build ID. (inclusive)
99
100 Returns:
101 A list of build IDs. (str)
102 """
103 # TODO(kcwu): remove pagination hack after b/68239878 fixed
104 build_id_set = set()
105 tmp_end = end
106 while True:
107 url = BUILD_IDS_BETWEEN_URL_TEMPLATE.format(
108 branch=branch, start=start, end=tmp_end)
109 query_result = json.loads(fetch_android_build_data(url).decode('utf-8'))
110 found_new = set(map(int, query_result['ids'])) - build_id_set
111 if not found_new:
112 break
113 build_id_set.update(found_new)
114 tmp_end = min(build_id_set)
115
116 logger.debug('Found %d builds in the range.', len(build_id_set))
117
118 return map(str, sorted(build_id_set))
119
120
121def lunch(android_root, flavor, *args, **kwargs):
122 """Helper to run commands with Android lunch env.
123
124 Args:
125 android_root: root path of Android tree
126 flavor: lunch flavor
127 args: command to run
128 kwargs: extra arguments passed to util.Popen
129 """
130 util.check_call('./android_lunch_helper.sh', android_root, flavor, *args,
131 **kwargs)
132
133
134def fetch_artifact(flavor, build_id, filename, dest):
135 """Fetches Android build artifact.
136
137 Args:
138 flavor: Android build flavor
139 build_id: Android build id
140 filename: artifact name
141 dest: local path to store the fetched artifact
142 """
Kuang-che Wuc7ee6c82019-01-16 17:05:49 +0800143 service_account_args = []
144 # These arguments are for bisector service and not required for users of
145 # bisect-kit using personal account.
146 if os.environ.get('ANDROID_CLOUD_SERVICE_ACCOUNT_EMAIL'):
147 assert os.environ.get('ANDROID_CLOUD_SERVICE_ACCOUNT_KEY')
148 service_account_args += [
149 '--email',
150 os.environ.get('ANDROID_CLOUD_SERVICE_ACCOUNT_EMAIL'),
151 '--apiary_service_account_private_key_path',
152 os.environ.get('ANDROID_CLOUD_SERVICE_ACCOUNT_KEY'),
153 ]
154
Kuang-che Wu708310b2018-03-28 17:24:34 +0800155 util.check_call('/google/data/ro/projects/android/fetch_artifact', '--target',
Kuang-che Wuc7ee6c82019-01-16 17:05:49 +0800156 flavor, '--bid', build_id, filename, dest,
157 *service_account_args)
Kuang-che Wu708310b2018-03-28 17:24:34 +0800158
159
160def fetch_manifest(android_root, flavor, build_id):
161 """Fetches Android repo manifest of given build.
162
163 Args:
164 android_root: root path of Android tree. Fetched manifest file will be
165 stored inside.
166 flavor: Android build flavor
167 build_id: Android build id
168
169 Returns:
170 the local filename of manifest (relative to android_root/.repo/manifests/)
171 """
172 # Assume manifest is flavor independent, thus not encoded into the file name.
173 manifest_name = 'manifest_%s.xml' % build_id
174 manifest_path = os.path.join(android_root, '.repo', 'manifests',
175 manifest_name)
176 if not os.path.exists(manifest_path):
177 fetch_artifact(flavor, build_id, manifest_name, manifest_path)
178 return manifest_name
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800179
180
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800181def lookup_build_timestamp(flavor, build_id):
182 """Lookup timestamp of Android prebuilt.
183
184 Args:
185 flavor: Android build flavor
186 build_id: Android build id
187
188 Returns:
189 timestamp
190 """
191 tmp_fn = tempfile.mktemp()
192 try:
193 fetch_artifact(flavor, build_id, 'BUILD_INFO', tmp_fn)
194 data = json.load(open(tmp_fn))
195 return int(data['sync_start_time'])
196 finally:
197 if os.path.exists(tmp_fn):
198 os.unlink(tmp_fn)
199
200
201class AndroidSpecManager(codechange.SpecManager):
202 """Repo manifest related operations.
203
204 This class fetches and enumerates android manifest files, parses them,
205 and sync to disk state according to them.
206 """
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800207
208 def __init__(self, config):
209 self.config = config
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800210 self.manifest_dir = os.path.join(self.config['android_root'], '.repo',
211 'manifests')
212
213 def collect_float_spec(self, old, new):
214 result = []
215 path = 'default.xml'
216
217 commits = []
218 old_timestamp = lookup_build_timestamp(self.config['flavor'], old)
219 new_timestamp = lookup_build_timestamp(self.config['flavor'], new)
220 for timestamp, git_rev in git_util.get_history(self.manifest_dir, path):
221 if timestamp < old_timestamp:
222 commits = []
223 commits.append((timestamp, git_rev))
224 if timestamp > new_timestamp:
225 break
226
227 for timestamp, git_rev in commits:
228 result.append(
229 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
230 return result
231
232 def collect_fixed_spec(self, old, new):
233 result = []
234 revlist = get_build_ids_between(self.config['branch'], int(old), int(new))
235 for rev in revlist:
236 manifest_name = fetch_manifest(self.config['android_root'],
237 self.config['flavor'], rev)
238 path = os.path.join(self.manifest_dir, manifest_name)
239 timestamp = lookup_build_timestamp(self.config['flavor'], rev)
240 result.append(
241 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
242 return result
243
244 def _load_manifest_content(self, spec):
245 if spec.spec_type == codechange.SPEC_FIXED:
246 manifest_name = fetch_manifest(self.config['branch'],
247 self.config['flavor'], spec.name)
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800248 content = open(os.path.join(self.manifest_dir, manifest_name)).read()
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800249 else:
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800250 content = git_util.get_file_from_revision(self.manifest_dir, spec.name,
251 spec.path)
252 return content
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800253
254 def parse_spec(self, spec):
255 logging.debug('parse_spec %s', spec.name)
256 manifest_content = self._load_manifest_content(spec)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800257 parser = repo_util.ManifestParser(self.manifest_dir)
258 root = parser.parse_single_xml(manifest_content, allow_include=False)
259 spec.entries = parser.process_parsed_result(root)
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800260 if spec.spec_type == codechange.SPEC_FIXED:
261 assert spec.is_static()
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800262
263 def sync_disk_state(self, rev):
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800264 manifest_name = fetch_manifest(self.config['android_root'],
265 self.config['flavor'], rev)
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800266 repo_util.sync(
267 self.config['android_root'],
268 manifest_name=manifest_name,
269 current_branch=True)