blob: 48d0f9570ddd532afea9e39bee6025989cc84900 [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 """
143 util.check_call('/google/data/ro/projects/android/fetch_artifact', '--target',
144 flavor, '--bid', build_id, filename, dest)
145
146
147def fetch_manifest(android_root, flavor, build_id):
148 """Fetches Android repo manifest of given build.
149
150 Args:
151 android_root: root path of Android tree. Fetched manifest file will be
152 stored inside.
153 flavor: Android build flavor
154 build_id: Android build id
155
156 Returns:
157 the local filename of manifest (relative to android_root/.repo/manifests/)
158 """
159 # Assume manifest is flavor independent, thus not encoded into the file name.
160 manifest_name = 'manifest_%s.xml' % build_id
161 manifest_path = os.path.join(android_root, '.repo', 'manifests',
162 manifest_name)
163 if not os.path.exists(manifest_path):
164 fetch_artifact(flavor, build_id, manifest_name, manifest_path)
165 return manifest_name
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800166
167
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800168def lookup_build_timestamp(flavor, build_id):
169 """Lookup timestamp of Android prebuilt.
170
171 Args:
172 flavor: Android build flavor
173 build_id: Android build id
174
175 Returns:
176 timestamp
177 """
178 tmp_fn = tempfile.mktemp()
179 try:
180 fetch_artifact(flavor, build_id, 'BUILD_INFO', tmp_fn)
181 data = json.load(open(tmp_fn))
182 return int(data['sync_start_time'])
183 finally:
184 if os.path.exists(tmp_fn):
185 os.unlink(tmp_fn)
186
187
188class AndroidSpecManager(codechange.SpecManager):
189 """Repo manifest related operations.
190
191 This class fetches and enumerates android manifest files, parses them,
192 and sync to disk state according to them.
193 """
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800194
195 def __init__(self, config):
196 self.config = config
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800197 self.manifest_dir = os.path.join(self.config['android_root'], '.repo',
198 'manifests')
199
200 def collect_float_spec(self, old, new):
201 result = []
202 path = 'default.xml'
203
204 commits = []
205 old_timestamp = lookup_build_timestamp(self.config['flavor'], old)
206 new_timestamp = lookup_build_timestamp(self.config['flavor'], new)
207 for timestamp, git_rev in git_util.get_history(self.manifest_dir, path):
208 if timestamp < old_timestamp:
209 commits = []
210 commits.append((timestamp, git_rev))
211 if timestamp > new_timestamp:
212 break
213
214 for timestamp, git_rev in commits:
215 result.append(
216 codechange.Spec(codechange.SPEC_FLOAT, git_rev, timestamp, path))
217 return result
218
219 def collect_fixed_spec(self, old, new):
220 result = []
221 revlist = get_build_ids_between(self.config['branch'], int(old), int(new))
222 for rev in revlist:
223 manifest_name = fetch_manifest(self.config['android_root'],
224 self.config['flavor'], rev)
225 path = os.path.join(self.manifest_dir, manifest_name)
226 timestamp = lookup_build_timestamp(self.config['flavor'], rev)
227 result.append(
228 codechange.Spec(codechange.SPEC_FIXED, rev, timestamp, path))
229 return result
230
231 def _load_manifest_content(self, spec):
232 if spec.spec_type == codechange.SPEC_FIXED:
233 manifest_name = fetch_manifest(self.config['branch'],
234 self.config['flavor'], spec.name)
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800235 content = open(os.path.join(self.manifest_dir, manifest_name)).read()
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800236 else:
Kuang-che Wu89ac2e72018-07-25 17:39:07 +0800237 content = git_util.get_file_from_revision(self.manifest_dir, spec.name,
238 spec.path)
239 return content
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800240
241 def parse_spec(self, spec):
242 logging.debug('parse_spec %s', spec.name)
243 manifest_content = self._load_manifest_content(spec)
Kuang-che Wue4bae0b2018-07-19 12:10:14 +0800244 parser = repo_util.ManifestParser(self.manifest_dir)
245 root = parser.parse_single_xml(manifest_content, allow_include=False)
246 spec.entries = parser.process_parsed_result(root)
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800247 if spec.spec_type == codechange.SPEC_FIXED:
248 assert spec.is_static()
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800249
250 def sync_disk_state(self, rev):
Kuang-che Wud1d45b42018-07-05 00:46:45 +0800251 manifest_name = fetch_manifest(self.config['android_root'],
252 self.config['flavor'], rev)
Kuang-che Wuacb6efd2018-04-25 18:52:58 +0800253 repo_util.sync(
254 self.config['android_root'],
255 manifest_name=manifest_name,
256 current_branch=True)