blob: 936b8b1de216482398cfc20b359c51d0b22ce3e9 [file] [log] [blame]
joychen3cb228e2013-06-12 12:13:13 -07001# Copyright (c) 2013 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
Chris Sosa0eecf962014-02-03 14:14:39 -08005"""Main module for parsing and interpreting XBuddy paths for the devserver."""
6
joychen562699a2013-08-13 15:22:14 -07007import ConfigParser
joychen3cb228e2013-06-12 12:13:13 -07008import datetime
9import operator
10import os
joychenf8f07e22013-07-12 17:45:51 -070011import re
joychen3cb228e2013-06-12 12:13:13 -070012import shutil
joychenf8f07e22013-07-12 17:45:51 -070013import time
joychen3cb228e2013-06-12 12:13:13 -070014import threading
15
joychen921e1fb2013-06-28 11:12:20 -070016import build_util
joychen3cb228e2013-06-12 12:13:13 -070017import artifact_info
joychen3cb228e2013-06-12 12:13:13 -070018import common_util
19import devserver_constants
20import downloader
joychenf8f07e22013-07-12 17:45:51 -070021import gsutil_util
joychen3cb228e2013-06-12 12:13:13 -070022import log_util
23
24# Module-local log function.
25def _Log(message, *args):
26 return log_util.LogWithTag('XBUDDY', message, *args)
27
joychen562699a2013-08-13 15:22:14 -070028# xBuddy config constants
29CONFIG_FILE = 'xbuddy_config.ini'
30SHADOW_CONFIG_FILE = 'shadow_xbuddy_config.ini'
31PATH_REWRITES = 'PATH_REWRITES'
32GENERAL = 'GENERAL'
joychen921e1fb2013-06-28 11:12:20 -070033
Chris Sosac2abc722013-08-26 17:11:22 -070034# Path for shadow config in chroot.
35CHROOT_SHADOW_DIR = '/mnt/host/source/src/platform/dev'
36
joychen25d25972013-07-30 14:54:16 -070037# XBuddy aliases
38TEST = 'test'
39BASE = 'base'
40DEV = 'dev'
41FULL = 'full_payload'
42RECOVERY = 'recovery'
43STATEFUL = 'stateful'
44AUTOTEST = 'autotest'
45
joychen921e1fb2013-06-28 11:12:20 -070046# Local build constants
joychenc3944cb2013-08-19 10:42:07 -070047ANY = "ANY"
joychen7df67f72013-07-18 14:21:12 -070048LATEST = "latest"
49LOCAL = "local"
50REMOTE = "remote"
Chris Sosa75490802013-09-30 17:21:45 -070051
52# TODO(sosa): Fix a lot of assumptions about these aliases. There is too much
53# implicit logic here that's unnecessary. What should be done:
54# 1) Collapse Alias logic to one set of aliases for xbuddy (not local/remote).
55# 2) Do not use zip when creating these dicts. Better to not rely on ordering.
56# 3) Move alias/artifact mapping to a central module rather than having it here.
57# 4) Be explicit when things are missing i.e. no dev images in image.zip.
58
joychen921e1fb2013-06-28 11:12:20 -070059LOCAL_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070060 TEST,
joychen25d25972013-07-30 14:54:16 -070061 DEV,
Chris Sosa75490802013-09-30 17:21:45 -070062 BASE,
Gabe Black0d3286e2014-07-30 15:30:03 -070063 RECOVERY,
joychenc3944cb2013-08-19 10:42:07 -070064 FULL,
Chris Sosa7cd23202013-10-15 17:22:57 -070065 STATEFUL,
joychenc3944cb2013-08-19 10:42:07 -070066 ANY,
joychen921e1fb2013-06-28 11:12:20 -070067]
68
69LOCAL_FILE_NAMES = [
70 devserver_constants.TEST_IMAGE_FILE,
joychen921e1fb2013-06-28 11:12:20 -070071 devserver_constants.IMAGE_FILE,
Chris Sosa75490802013-09-30 17:21:45 -070072 devserver_constants.BASE_IMAGE_FILE,
Gabe Black0d3286e2014-07-30 15:30:03 -070073 devserver_constants.RECOVERY_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070074 devserver_constants.UPDATE_FILE,
Chris Sosa7cd23202013-10-15 17:22:57 -070075 devserver_constants.STATEFUL_FILE,
Chris Sosa75490802013-09-30 17:21:45 -070076 None, # For ANY.
joychen921e1fb2013-06-28 11:12:20 -070077]
78
79LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
80
81# Google Storage constants
82GS_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070083 TEST,
84 BASE,
85 RECOVERY,
86 FULL,
87 STATEFUL,
88 AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -070089]
90
joychen921e1fb2013-06-28 11:12:20 -070091GS_FILE_NAMES = [
92 devserver_constants.TEST_IMAGE_FILE,
93 devserver_constants.BASE_IMAGE_FILE,
94 devserver_constants.RECOVERY_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070095 devserver_constants.UPDATE_FILE,
joychen121fc9b2013-08-02 14:30:30 -070096 devserver_constants.STATEFUL_FILE,
joychen3cb228e2013-06-12 12:13:13 -070097 devserver_constants.AUTOTEST_DIR,
98]
99
100ARTIFACTS = [
101 artifact_info.TEST_IMAGE,
102 artifact_info.BASE_IMAGE,
103 artifact_info.RECOVERY_IMAGE,
104 artifact_info.FULL_PAYLOAD,
105 artifact_info.STATEFUL_PAYLOAD,
106 artifact_info.AUTOTEST,
107]
108
joychen921e1fb2013-06-28 11:12:20 -0700109GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
110GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 12:13:13 -0700111
joychen921e1fb2013-06-28 11:12:20 -0700112LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 12:13:13 -0700113
Chris Sosaea734d92013-10-11 11:28:58 -0700114RELEASE = "-release"
joychen3cb228e2013-06-12 12:13:13 -0700115
joychen3cb228e2013-06-12 12:13:13 -0700116
117class XBuddyException(Exception):
118 """Exception classes used by this module."""
119 pass
120
121
122# no __init__ method
123#pylint: disable=W0232
124class Timestamp():
125 """Class to translate build path strings and timestamp filenames."""
126
127 _TIMESTAMP_DELIMITER = 'SLASH'
128 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
129
130 @staticmethod
131 def TimestampToBuild(timestamp_filename):
132 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
133
134 @staticmethod
135 def BuildToTimestamp(build_path):
136 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 11:12:20 -0700137
138 @staticmethod
139 def UpdateTimestamp(timestamp_dir, build_id):
140 """Update timestamp file of build with build_id."""
141 common_util.MkDirP(timestamp_dir)
joychen562699a2013-08-13 15:22:14 -0700142 _Log("Updating timestamp for %s", build_id)
joychen921e1fb2013-06-28 11:12:20 -0700143 time_file = os.path.join(timestamp_dir,
144 Timestamp.BuildToTimestamp(build_id))
145 with file(time_file, 'a'):
146 os.utime(time_file, None)
joychen3cb228e2013-06-12 12:13:13 -0700147#pylint: enable=W0232
148
149
joychen921e1fb2013-06-28 11:12:20 -0700150class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 12:13:13 -0700151 """Class that manages image retrieval and caching by the devserver.
152
153 Image retrieval by xBuddy path:
154 XBuddy accesses images and artifacts that it stores using an xBuddy
155 path of the form: board/version/alias
156 The primary xbuddy.Get call retrieves the correct artifact or url to where
157 the artifacts can be found.
158
159 Image caching:
160 Images and other artifacts are stored identically to how they would have
161 been if devserver's stage rpc was called and the xBuddy cache replaces
162 build versions on a LRU basis. Timestamps are maintained by last accessed
163 times of representative files in the a directory in the static serve
164 directory (XBUDDY_TIMESTAMP_DIR).
165
166 Private class members:
joychen121fc9b2013-08-02 14:30:30 -0700167 _true_values: used for interpreting boolean values
168 _staging_thread_count: track download requests
169 _timestamp_folder: directory with empty files standing in as timestamps
joychen921e1fb2013-06-28 11:12:20 -0700170 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 12:13:13 -0700171 """
172 _true_values = ['true', 't', 'yes', 'y']
173
174 # Number of threads that are staging images.
175 _staging_thread_count = 0
176 # Lock used to lock increasing/decreasing count.
177 _staging_thread_count_lock = threading.Lock()
178
Chris Sosa7cd23202013-10-15 17:22:57 -0700179 def __init__(self, manage_builds=False, board=None, images_dir=None,
180 **kwargs):
joychen921e1fb2013-06-28 11:12:20 -0700181 super(XBuddy, self).__init__(**kwargs)
joychenb0dfe552013-07-30 10:02:06 -0700182
joychen562699a2013-08-13 15:22:14 -0700183 self.config = self._ReadConfig()
184 self._manage_builds = manage_builds or self._ManageBuilds()
Chris Sosa75490802013-09-30 17:21:45 -0700185 self._board = board
joychen921e1fb2013-06-28 11:12:20 -0700186 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 12:13:13 -0700187 Timestamp.XBUDDY_TIMESTAMP_DIR)
Chris Sosa7cd23202013-10-15 17:22:57 -0700188 if images_dir:
189 self.images_dir = images_dir
190 else:
191 self.images_dir = os.path.join(self.GetSourceRoot(), 'src/build/images')
192
joychen7df67f72013-07-18 14:21:12 -0700193 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 12:13:13 -0700194
195 @classmethod
196 def ParseBoolean(cls, boolean_string):
197 """Evaluate a string to a boolean value"""
198 if boolean_string:
199 return boolean_string.lower() in cls._true_values
200 else:
201 return False
202
joychen562699a2013-08-13 15:22:14 -0700203 def _ReadConfig(self):
204 """Read xbuddy config from ini files.
205
206 Reads the base config from xbuddy_config.ini, and then merges in the
207 shadow config from shadow_xbuddy_config.ini
208
209 Returns:
210 The merged configuration.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800211
joychen562699a2013-08-13 15:22:14 -0700212 Raises:
213 XBuddyException if the config file is missing.
214 """
215 xbuddy_config = ConfigParser.ConfigParser()
216 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
217 if os.path.exists(config_file):
218 xbuddy_config.read(config_file)
219 else:
Yiming Chend9202142014-11-07 14:56:52 -0800220 # Get the directory of xbuddy.py file.
221 file_dir = os.path.dirname(os.path.realpath(__file__))
222 # Read the default xbuddy_config.ini from the directory.
223 xbuddy_config.read(os.path.join(file_dir, CONFIG_FILE))
joychen562699a2013-08-13 15:22:14 -0700224
225 # Read the shadow file if there is one.
Chris Sosac2abc722013-08-26 17:11:22 -0700226 if os.path.isdir(CHROOT_SHADOW_DIR):
227 shadow_config_file = os.path.join(CHROOT_SHADOW_DIR, SHADOW_CONFIG_FILE)
228 else:
229 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
230
231 _Log('Using shadow config file stored at %s', shadow_config_file)
joychen562699a2013-08-13 15:22:14 -0700232 if os.path.exists(shadow_config_file):
233 shadow_xbuddy_config = ConfigParser.ConfigParser()
234 shadow_xbuddy_config.read(shadow_config_file)
235
236 # Merge shadow config in.
237 sections = shadow_xbuddy_config.sections()
238 for s in sections:
239 if not xbuddy_config.has_section(s):
240 xbuddy_config.add_section(s)
241 options = shadow_xbuddy_config.options(s)
242 for o in options:
243 val = shadow_xbuddy_config.get(s, o)
244 xbuddy_config.set(s, o, val)
245
246 return xbuddy_config
247
248 def _ManageBuilds(self):
249 """Checks if xBuddy is managing local builds using the current config."""
250 try:
251 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
252 except ConfigParser.Error:
253 return False
254
255 def _Capacity(self):
256 """Gets the xbuddy capacity from the current config."""
257 try:
258 return int(self.config.get(GENERAL, 'capacity'))
259 except ConfigParser.Error:
260 return 5
261
262 def _LookupAlias(self, alias, board):
263 """Given the full xbuddy config, look up an alias for path rewrite.
264
265 Args:
266 alias: The xbuddy path that could be one of the aliases in the
267 rewrite table.
268 board: The board to fill in with when paths are rewritten. Can be from
269 the update request xml or the default board from devserver.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800270
joychen562699a2013-08-13 15:22:14 -0700271 Returns:
272 If a rewrite is found, a string with the current board substituted in.
273 If no rewrite is found, just return the original string.
274 """
joychen562699a2013-08-13 15:22:14 -0700275 try:
276 val = self.config.get(PATH_REWRITES, alias)
277 except ConfigParser.Error:
278 # No alias lookup found. Return original path.
279 return alias
280
281 if not val.strip():
282 # The found value was an empty string.
283 return alias
284 else:
285 # Fill in the board.
joychenc3944cb2013-08-19 10:42:07 -0700286 rewrite = val.replace("BOARD", "%(board)s") % {
joychen562699a2013-08-13 15:22:14 -0700287 'board': board}
288 _Log("Path was rewritten to %s", rewrite)
289 return rewrite
290
Simran Basi99e63c02014-05-20 10:39:52 -0700291 @staticmethod
292 def _ResolveImageDir(image_dir):
293 """Clean up and return the image dir to use.
294
295 Args:
296 image_dir: directory in Google Storage to use.
297
298 Returns:
299 |image_dir| if |image_dir| is not None. Otherwise, returns
300 devserver_constants.GS_IMAGE_DIR
301 """
302 image_dir = image_dir or devserver_constants.GS_IMAGE_DIR
303 # Remove trailing slashes.
304 return image_dir.rstrip('/')
305
306 def _LookupOfficial(self, board, suffix=RELEASE, image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700307 """Check LATEST-master for the version number of interest."""
308 _Log("Checking gs for latest %s-%s image", board, suffix)
Simran Basi99e63c02014-05-20 10:39:52 -0700309 image_dir = XBuddy._ResolveImageDir(image_dir)
310 latest_addr = (devserver_constants.GS_LATEST_MASTER %
311 {'image_dir': image_dir,
312 'board': board,
313 'suffix': suffix})
joychenf8f07e22013-07-12 17:45:51 -0700314 cmd = 'gsutil cat %s' % latest_addr
315 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700316 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700317 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700318
joychenf8f07e22013-07-12 17:45:51 -0700319 return devserver_constants.IMAGE_DIR % {'board':board,
320 'suffix':suffix,
321 'version':version}
Simran Basi99e63c02014-05-20 10:39:52 -0700322 def _LookupChannel(self, board, channel='stable', image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700323 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700324 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700325 _Log("Checking channel '%s' for latest '%s' image", channel, board)
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800326 # Due to historical reasons, gs://chromeos-releases uses
327 # daisy-spring as opposed to the board name daisy_spring. Convert
328 # the board name for the lookup.
329 channel_dir = devserver_constants.GS_CHANNEL_DIR % {
330 'channel':channel,
331 'board':re.sub('_', '-', board)}
joychen562699a2013-08-13 15:22:14 -0700332 latest_version = gsutil_util.GetLatestVersionFromGSDir(
333 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700334
joychen121fc9b2013-08-02 14:30:30 -0700335 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700336 image_url = devserver_constants.IMAGE_DIR % {
337 'board':board,
338 'suffix':RELEASE,
339 'version':'R*' + latest_version}
Simran Basi99e63c02014-05-20 10:39:52 -0700340 image_dir = XBuddy._ResolveImageDir(image_dir)
341 gs_url = os.path.join(image_dir, image_url)
joychenf8f07e22013-07-12 17:45:51 -0700342
343 # There should only be one match on cros-image-archive.
Simran Basi99e63c02014-05-20 10:39:52 -0700344 full_version = gsutil_util.GetLatestVersionFromGSDir(gs_url)
joychenf8f07e22013-07-12 17:45:51 -0700345
346 return devserver_constants.IMAGE_DIR % {'board':board,
347 'suffix':RELEASE,
348 'version':full_version}
349
350 def _LookupVersion(self, board, version):
351 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700352 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700353 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
joychenf8f07e22013-07-12 17:45:51 -0700354 image_url = devserver_constants.IMAGE_DIR % {'board':board,
355 'suffix':RELEASE,
356 'version':version + '*'}
357 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
358
joychen121fc9b2013-08-02 14:30:30 -0700359 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700360 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
361 return devserver_constants.IMAGE_DIR % {'board':board,
362 'suffix':RELEASE,
363 'version':full_version}
364
Chris Sosaea734d92013-10-11 11:28:58 -0700365 def _RemoteBuildId(self, board, version):
366 """Returns the remote build_id for the given board and version.
367
368 Raises:
369 XBuddyException: If we failed to resolve the version to a valid build_id.
370 """
371 build_id_as_is = devserver_constants.IMAGE_DIR % {'board':board,
372 'suffix':'',
373 'version':version}
374 build_id_release = devserver_constants.IMAGE_DIR % {'board':board,
375 'suffix':RELEASE,
376 'version':version}
377 # Return the first path that exists. We assume that what the user typed
378 # is better than with a default suffix added i.e. x86-generic/blah is
379 # more valuable than x86-generic-release/blah.
380 for build_id in build_id_as_is, build_id_release:
381 cmd = 'gsutil ls %s/%s' % (devserver_constants.GS_IMAGE_DIR, build_id)
382 try:
383 version = gsutil_util.GSUtilRun(cmd, None)
384 return build_id
385 except gsutil_util.GSUtilError:
386 continue
387 else:
388 raise XBuddyException('Could not find remote build_id for %s %s' % (
389 board, version))
390
Simran Basi99e63c02014-05-20 10:39:52 -0700391 def _ResolveVersionToBuildId(self, board, version, image_dir=None):
joychen121fc9b2013-08-02 14:30:30 -0700392 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700393
394 Args:
395 board: as specified in the original call. (i.e. x86-generic, parrot)
396 version: as entered in the original call. can be
397 {TBD, 0. some custom alias as defined in a config file}
398 1. latest
399 2. latest-{channel}
400 3. latest-official-{board suffix}
401 4. version prefix (i.e. RX-Y.X, RX-Y, RX)
Simran Basi99e63c02014-05-20 10:39:52 -0700402 image_dir: image directory to check in Google Storage. If none,
403 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700404
405 Returns:
Chris Sosaea734d92013-10-11 11:28:58 -0700406 Location where the image dir is actually found on GS (build_id)
joychen3cb228e2013-06-12 12:13:13 -0700407
Chris Sosaea734d92013-10-11 11:28:58 -0700408 Raises:
409 XBuddyException: If we failed to resolve the version to a valid url.
joychen3cb228e2013-06-12 12:13:13 -0700410 """
joychenf8f07e22013-07-12 17:45:51 -0700411 # Only the last segment of the alias is variable relative to the rest.
412 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700413
joychenf8f07e22013-07-12 17:45:51 -0700414 if re.match(devserver_constants.VERSION_RE, version):
Chris Sosaea734d92013-10-11 11:28:58 -0700415 return self._RemoteBuildId(board, version)
joychenf8f07e22013-07-12 17:45:51 -0700416 elif version == LATEST_OFFICIAL:
417 # latest-official --> LATEST build in board-release
Simran Basi99e63c02014-05-20 10:39:52 -0700418 return self._LookupOfficial(board, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700419 elif version_tuple[0] == LATEST_OFFICIAL:
420 # latest-official-{suffix} --> LATEST build in board-{suffix}
Simran Basi99e63c02014-05-20 10:39:52 -0700421 return self._LookupOfficial(board, version_tuple[1], image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700422 elif version == LATEST:
423 # latest --> latest build on stable channel
Simran Basi99e63c02014-05-20 10:39:52 -0700424 return self._LookupChannel(board, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700425 elif version_tuple[0] == LATEST:
426 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
427 # latest-R* --> most recent qualifying build
428 return self._LookupVersion(board, version_tuple[1])
429 else:
430 # latest-{channel} --> latest build within that channel
Simran Basi99e63c02014-05-20 10:39:52 -0700431 return self._LookupChannel(board, version_tuple[1],
432 image_dir=image_dir)
joychen3cb228e2013-06-12 12:13:13 -0700433 else:
434 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700435 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700436
joychen5260b9a2013-07-16 14:48:01 -0700437 @staticmethod
438 def _Symlink(link, target):
439 """Symlinks link to target, and removes whatever link was there before."""
440 _Log("Linking to %s from %s", link, target)
441 if os.path.lexists(link):
442 os.unlink(link)
443 os.symlink(target, link)
444
joychen121fc9b2013-08-02 14:30:30 -0700445 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700446 """Get the version of the latest image built for board by build_image
447
448 Updates the symlink reference within the xBuddy static dir to point to
449 the real image dir in the local /build/images directory.
450
451 Args:
joychenc3944cb2013-08-19 10:42:07 -0700452 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700453
454 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700455 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700456
457 Raises:
458 XBuddyException if neither test nor dev image was found in latest built
459 directory.
joychen3cb228e2013-06-12 12:13:13 -0700460 """
joychen921e1fb2013-06-28 11:12:20 -0700461 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700462 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700463 raise XBuddyException('No builds found for %s. Did you run build_image?' %
464 board)
465
joychen121fc9b2013-08-02 14:30:30 -0700466 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700467 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700468
joychenc3944cb2013-08-19 10:42:07 -0700469 @staticmethod
470 def _FindAny(local_dir):
471 """Returns the image_type for ANY given the local_dir."""
joychenc3944cb2013-08-19 10:42:07 -0700472 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700473 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
474 # Prioritize test images over dev images.
joychenc3944cb2013-08-19 10:42:07 -0700475 if os.path.exists(test_image):
476 return 'test'
477
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700478 if os.path.exists(dev_image):
479 return 'dev'
480
joychenc3944cb2013-08-19 10:42:07 -0700481 raise XBuddyException('No images found in %s' % local_dir)
482
483 @staticmethod
Chris Sosa0eecf962014-02-03 14:14:39 -0800484 def _InterpretPath(path, default_board=None):
joychen121fc9b2013-08-02 14:30:30 -0700485 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700486
joychen121fc9b2013-08-02 14:30:30 -0700487 Args:
488 path: the path xBuddy Get was called with.
Chris Sosa0eecf962014-02-03 14:14:39 -0800489 default_board: board to use in case board isn't in path.
joychen3cb228e2013-06-12 12:13:13 -0700490
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800491 Returns:
Chris Sosa75490802013-09-30 17:21:45 -0700492 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 12:13:13 -0700493
494 Raises:
495 XBuddyException: if the path can't be resolved into valid components
496 """
joychen121fc9b2013-08-02 14:30:30 -0700497 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700498
Chris Sosa0eecf962014-02-03 14:14:39 -0800499 # Do the stuff that is well known first. We know that if paths have a
500 # image_type, it must be one of the GS/LOCAL aliases and it must be at the
501 # end. Similarly, local/remote are well-known and must start the path list.
502 is_local = True
503 if path_list and path_list[0] in (REMOTE, LOCAL):
504 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700505
Chris Sosa0eecf962014-02-03 14:14:39 -0800506 # Default image type is determined by remote vs. local.
507 if is_local:
508 image_type = ANY
509 else:
510 image_type = TEST
joychen7df67f72013-07-18 14:21:12 -0700511
Chris Sosa0eecf962014-02-03 14:14:39 -0800512 if path_list and path_list[-1] in GS_ALIASES + LOCAL_ALIASES:
513 image_type = path_list.pop(-1)
joychen3cb228e2013-06-12 12:13:13 -0700514
Chris Sosa0eecf962014-02-03 14:14:39 -0800515 # Now for the tricky part. We don't actually know at this point if the rest
516 # of the path is just a board | version (like R33-2341.0.0) or just a board
517 # or just a version. So we do our best to do the right thing.
518 board = default_board
519 version = LATEST
520 if len(path_list) == 1:
521 path = path_list.pop(0)
522 # If it's a version we know (contains latest), go for that, otherwise only
523 # treat it as a version if we were given an actual default board.
524 if LATEST in path or default_board is not None:
525 version = path
joychen7df67f72013-07-18 14:21:12 -0700526 else:
Chris Sosa0eecf962014-02-03 14:14:39 -0800527 board = path
joychen7df67f72013-07-18 14:21:12 -0700528
Chris Sosa0eecf962014-02-03 14:14:39 -0800529 elif len(path_list) == 2:
530 # Assumes board/version.
531 board = path_list.pop(0)
532 version = path_list.pop(0)
533
534 if path_list:
535 raise XBuddyException("Path isn't valid. Could not figure out how to "
536 "parse remaining components: %s." % path_list)
537
538 _Log("Get artifact '%s' with board %s and version %s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700539 image_type, board, version, is_local)
540
541 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700542
joychen921e1fb2013-06-28 11:12:20 -0700543 def _SyncRegistryWithBuildImages(self):
joychen5260b9a2013-07-16 14:48:01 -0700544 """ Crawl images_dir for build_ids of images generated from build_image.
545
546 This will find images and symlink them in xBuddy's static dir so that
547 xBuddy's cache can serve them.
548 If xBuddy's _manage_builds option is on, then a timestamp will also be
549 generated, and xBuddy will clear them from the directory they are in, as
550 necessary.
551 """
Yu-Ju Hong235d1b52014-04-16 11:01:47 -0700552 if not os.path.isdir(self.images_dir):
553 # Skip syncing if images_dir does not exist.
554 _Log('Cannot find %s; skip syncing image registry.', self.images_dir)
555 return
556
joychen921e1fb2013-06-28 11:12:20 -0700557 build_ids = []
558 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700559 # Ensure we have directories to track all boards in build/images
560 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700561 board_dir = os.path.join(self.images_dir, b)
562 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700563 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700564
joychen121fc9b2013-08-02 14:30:30 -0700565 # Check currently registered images.
joychen921e1fb2013-06-28 11:12:20 -0700566 for f in os.listdir(self._timestamp_folder):
567 build_id = Timestamp.TimestampToBuild(f)
568 if build_id in build_ids:
569 build_ids.remove(build_id)
570
joychen121fc9b2013-08-02 14:30:30 -0700571 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700572 for build_id in build_ids:
573 link = os.path.join(self.static_dir, build_id)
574 target = os.path.join(self.images_dir, build_id)
575 XBuddy._Symlink(link, target)
576 if self._manage_builds:
577 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700578
579 def _ListBuildTimes(self):
joychen3cb228e2013-06-12 12:13:13 -0700580 """ Returns the currently cached builds and their last access timestamp.
581
582 Returns:
583 list of tuples that matches xBuddy build/version to timestamps in long
584 """
joychen121fc9b2013-08-02 14:30:30 -0700585 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700586 build_dict = {}
587
joychen7df67f72013-07-18 14:21:12 -0700588 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700589 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
590 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700591 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700592 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700593 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
594 return return_tup
595
Chris Sosa75490802013-09-30 17:21:45 -0700596 def _Download(self, gs_url, artifacts):
597 """Download the artifacts from the given gs_url.
598
599 Raises:
600 build_artifact.ArtifactDownloadError: If we failed to download the
601 artifact.
602 """
joychen3cb228e2013-06-12 12:13:13 -0700603 with XBuddy._staging_thread_count_lock:
604 XBuddy._staging_thread_count += 1
605 try:
Chris Sosa75490802013-09-30 17:21:45 -0700606 _Log("Downloading %s from %s", artifacts, gs_url)
607 downloader.Downloader(self.static_dir, gs_url).Download(artifacts, [])
joychen3cb228e2013-06-12 12:13:13 -0700608 finally:
609 with XBuddy._staging_thread_count_lock:
610 XBuddy._staging_thread_count -= 1
611
Chris Sosa75490802013-09-30 17:21:45 -0700612 def CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700613 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700614 if not self._manage_builds:
615 return
joychen921e1fb2013-06-28 11:12:20 -0700616 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700617 _Log('In cache now: %s', cached_builds)
618
joychen562699a2013-08-13 15:22:14 -0700619 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700620 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700621 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700622
623 time_file = os.path.join(self._timestamp_folder,
624 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700625 os.unlink(time_file)
626 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700627 try:
joychen121fc9b2013-08-02 14:30:30 -0700628 # Handle symlinks, in the case of links to local builds if enabled.
629 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700630 target = os.readlink(clear_dir)
631 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700632
633 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700634 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700635 shutil.rmtree(target)
636 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700637 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700638 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700639
joychen121fc9b2013-08-02 14:30:30 -0700640 except Exception as err:
641 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700642
Simran Basi99e63c02014-05-20 10:39:52 -0700643 def _GetFromGS(self, build_id, image_type, image_dir=None):
Chris Sosa75490802013-09-30 17:21:45 -0700644 """Check if the artifact is available locally. Download from GS if not.
645
Simran Basi99e63c02014-05-20 10:39:52 -0700646 Args:
647 build_id: Path to the image or update directory on the devserver or
648 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
649 image_type: Image type to download. Look at aliases at top of file for
650 options.
651 image_dir: Google Storage image archive to search in if requesting a
652 remote artifact. If none uses the default bucket.
653
Chris Sosa75490802013-09-30 17:21:45 -0700654 Raises:
655 build_artifact.ArtifactDownloadError: If we failed to download the
656 artifact.
657 """
Simran Basi99e63c02014-05-20 10:39:52 -0700658 image_dir = XBuddy._ResolveImageDir(image_dir)
659 gs_url = os.path.join(image_dir, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700660
joychen121fc9b2013-08-02 14:30:30 -0700661 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700662 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700663 file_loc = os.path.join(self.static_dir, build_id, file_name)
664 cached = os.path.exists(file_loc)
665
joychen921e1fb2013-06-28 11:12:20 -0700666 if not cached:
Chris Sosa75490802013-09-30 17:21:45 -0700667 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
668 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 11:12:20 -0700669 else:
670 _Log('Image already cached.')
671
Simran Basi99e63c02014-05-20 10:39:52 -0700672 def _GetArtifact(self, path_list, board=None, lookup_only=False,
673 image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700674 """Interpret an xBuddy path and return directory/file_name to resource.
675
Chris Sosa75490802013-09-30 17:21:45 -0700676 Note board can be passed that in but by default if self._board is set,
677 that is used rather than board.
678
Simran Basi99e63c02014-05-20 10:39:52 -0700679 Args:
680 path_list: [board, version, alias] as split from the xbuddy call url.
681 board: Board whos artifacts we are looking for. If None, use the board
682 XBuddy was initialized to use.
683 lookup_only: If true just look up the artifact, if False stage it on
684 the devserver as well.
685 image_dir: Google Storage image archive to search in if requesting a
686 remote artifact. If none uses the default bucket.
687
joychen346531c2013-07-24 16:55:56 -0700688 Returns:
Simran Basi99e63c02014-05-20 10:39:52 -0700689 build_id: Path to the image or update directory on the devserver or
690 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
691 file_name: of the artifact in the build_id directory.
joychen346531c2013-07-24 16:55:56 -0700692
693 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700694 XBuddyException: if the path could not be translated
Chris Sosa75490802013-09-30 17:21:45 -0700695 build_artifact.ArtifactDownloadError: if we failed to download the
696 artifact.
joychen346531c2013-07-24 16:55:56 -0700697 """
joychen121fc9b2013-08-02 14:30:30 -0700698 path = '/'.join(path_list)
Chris Sosa0eecf962014-02-03 14:14:39 -0800699 default_board = self._board if self._board else board
joychenb0dfe552013-07-30 10:02:06 -0700700 # Rewrite the path if there is an appropriate default.
Chris Sosa0eecf962014-02-03 14:14:39 -0800701 path = self._LookupAlias(path, default_board)
joychen121fc9b2013-08-02 14:30:30 -0700702 # Parse the path.
Chris Sosa0eecf962014-02-03 14:14:39 -0800703 image_type, board, version, is_local = self._InterpretPath(
704 path, default_board)
joychen7df67f72013-07-18 14:21:12 -0700705 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700706 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700707 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700708 # Get the latest local image for the given board.
709 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700710
joychenc3944cb2013-08-19 10:42:07 -0700711 build_id = os.path.join(board, version)
712 artifact_dir = os.path.join(self.static_dir, build_id)
713 if image_type == ANY:
714 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700715
joychenc3944cb2013-08-19 10:42:07 -0700716 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
717 artifact_path = os.path.join(artifact_dir, file_name)
718 if not os.path.exists(artifact_path):
719 raise XBuddyException('Local %s artifact not in static_dir at %s' %
720 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700721
joychen921e1fb2013-06-28 11:12:20 -0700722 else:
joychen121fc9b2013-08-02 14:30:30 -0700723 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700724 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700725 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700726 (image_type, GS_ALIASES))
Simran Basi99e63c02014-05-20 10:39:52 -0700727 build_id = self._ResolveVersionToBuildId(board, version,
728 image_dir=image_dir)
Chris Sosa75490802013-09-30 17:21:45 -0700729 _Log('Resolved version %s to %s.', version, build_id)
730 file_name = GS_ALIAS_TO_FILENAME[image_type]
731 if not lookup_only:
Simran Basi99e63c02014-05-20 10:39:52 -0700732 self._GetFromGS(build_id, image_type, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700733
joychenc3944cb2013-08-19 10:42:07 -0700734 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700735
736 ############################ BEGIN PUBLIC METHODS
737
738 def List(self):
739 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700740 self._SyncRegistryWithBuildImages()
741 builds = self._ListBuildTimes()
742 return_string = ''
743 for build, timestamp in builds:
744 return_string += '<b>' + build + '</b> '
745 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
746 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700747
748 def Capacity(self):
749 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700750 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700751
Simran Basi99e63c02014-05-20 10:39:52 -0700752 def Translate(self, path_list, board=None, image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700753 """Translates an xBuddy path to a real path to artifact if it exists.
754
joychen121fc9b2013-08-02 14:30:30 -0700755 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700756
Simran Basi99e63c02014-05-20 10:39:52 -0700757 Args:
758 path_list: [board, version, alias] as split from the xbuddy call url.
759 board: Board whos artifacts we are looking for. If None, use the board
760 XBuddy was initialized to use.
761 image_dir: image directory to check in Google Storage. If none,
762 the default bucket is used.
763
joychen7c2054a2013-07-25 11:14:07 -0700764 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700765 build_id: Path to the image or update directory on the devserver.
766 e.g. 'x86-generic/R26-4000.0.0'
767 The returned path is always the path to the directory within
768 static_dir, so it is always the build_id of the image.
769 file_name: The file name of the artifact. Can take any of the file
770 values in devserver_constants.
771 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
772 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700773
joychen121fc9b2013-08-02 14:30:30 -0700774 Raises:
775 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700776 """
777 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700778 build_id, file_name = self._GetArtifact(path_list, board=board,
Simran Basi99e63c02014-05-20 10:39:52 -0700779 lookup_only=True,
780 image_dir=image_dir)
joychen346531c2013-07-24 16:55:56 -0700781
joychen121fc9b2013-08-02 14:30:30 -0700782 _Log('Returning path to payload: %s/%s', build_id, file_name)
783 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700784
Yu-Ju Hong1bdb7a92014-04-10 16:02:11 -0700785 def StageTestArtifactsForUpdate(self, path_list):
Chris Sosa75490802013-09-30 17:21:45 -0700786 """Stages test artifacts for update and returns build_id.
787
788 Raises:
789 XBuddyException: if the path could not be translated
790 build_artifact.ArtifactDownloadError: if we failed to download the test
791 artifacts.
792 """
793 build_id, file_name = self.Translate(path_list)
794 if file_name == devserver_constants.TEST_IMAGE_FILE:
795 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
796 build_id)
797 artifacts = [FULL, STATEFUL]
798 self._Download(gs_url, artifacts)
799 return build_id
800
Simran Basi99e63c02014-05-20 10:39:52 -0700801 def Get(self, path_list, image_dir=None):
joychen921e1fb2013-06-28 11:12:20 -0700802 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700803
804 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700805
joychen3cb228e2013-06-12 12:13:13 -0700806 Args:
Simran Basi99e63c02014-05-20 10:39:52 -0700807 path_list: [board, version, alias] as split from the xbuddy call url.
808 image_dir: image directory to check in Google Storage. If none,
809 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700810
811 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700812 build_id: Path to the image or update directory on the devserver.
Simran Basi99e63c02014-05-20 10:39:52 -0700813 e.g. 'x86-generic/R26-4000.0.0'
814 The returned path is always the path to the directory within
815 static_dir, so it is always the build_id of the image.
joychen121fc9b2013-08-02 14:30:30 -0700816 file_name: The file name of the artifact. Can take any of the file
Simran Basi99e63c02014-05-20 10:39:52 -0700817 values in devserver_constants.
818 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
819 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700820
821 Raises:
Chris Sosa75490802013-09-30 17:21:45 -0700822 XBuddyException: if the path could not be translated
823 build_artifact.ArtifactDownloadError: if we failed to download the
824 artifact.
joychen3cb228e2013-06-12 12:13:13 -0700825 """
joychen7df67f72013-07-18 14:21:12 -0700826 self._SyncRegistryWithBuildImages()
Simran Basi99e63c02014-05-20 10:39:52 -0700827 build_id, file_name = self._GetArtifact(path_list, image_dir=image_dir)
joychen921e1fb2013-06-28 11:12:20 -0700828 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700829 #TODO (joyc): run in sep thread
Chris Sosa75490802013-09-30 17:21:45 -0700830 self.CleanCache()
joychen3cb228e2013-06-12 12:13:13 -0700831
joychen121fc9b2013-08-02 14:30:30 -0700832 _Log('Returning path to payload: %s/%s', build_id, file_name)
833 return build_id, file_name