blob: cb8fdbcd21f3fd4ed19274f24b3a5af8e1ea9bdd [file] [log] [blame]
joychen3cb228e2013-06-12 19:13:131# 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 Sosa0eecf96e2014-02-03 22:14:395"""Main module for parsing and interpreting XBuddy paths for the devserver."""
6
joychen562699a2013-08-13 22:22:147import ConfigParser
joychen3cb228e2013-06-12 19:13:138import datetime
9import operator
10import os
joychenf8f07e22013-07-13 00:45:5111import re
joychen3cb228e2013-06-12 19:13:1312import shutil
joychenf8f07e22013-07-13 00:45:5113import time
joychen3cb228e2013-06-12 19:13:1314import threading
15
joychen921e1fb2013-06-28 18:12:2016import build_util
joychen3cb228e2013-06-12 19:13:1317import artifact_info
joychen3cb228e2013-06-12 19:13:1318import common_util
19import devserver_constants
20import downloader
joychenf8f07e22013-07-13 00:45:5121import gsutil_util
joychen3cb228e2013-06-12 19:13:1322import log_util
23
24# Module-local log function.
25def _Log(message, *args):
26 return log_util.LogWithTag('XBUDDY', message, *args)
27
joychen562699a2013-08-13 22:22:1428# xBuddy config constants
29CONFIG_FILE = 'xbuddy_config.ini'
30SHADOW_CONFIG_FILE = 'shadow_xbuddy_config.ini'
31PATH_REWRITES = 'PATH_REWRITES'
32GENERAL = 'GENERAL'
joychen921e1fb2013-06-28 18:12:2033
Chris Sosac2abc722013-08-27 00:11:2234# Path for shadow config in chroot.
35CHROOT_SHADOW_DIR = '/mnt/host/source/src/platform/dev'
36
joychen25d25972013-07-30 21:54:1637# XBuddy aliases
38TEST = 'test'
39BASE = 'base'
40DEV = 'dev'
41FULL = 'full_payload'
42RECOVERY = 'recovery'
43STATEFUL = 'stateful'
44AUTOTEST = 'autotest'
45
joychen921e1fb2013-06-28 18:12:2046# Local build constants
joychenc3944cb2013-08-19 17:42:0747ANY = "ANY"
joychen7df67f72013-07-18 21:21:1248LATEST = "latest"
49LOCAL = "local"
50REMOTE = "remote"
Chris Sosa75490802013-10-01 00:21:4551
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 18:12:2059LOCAL_ALIASES = [
joychen25d25972013-07-30 21:54:1660 TEST,
joychen25d25972013-07-30 21:54:1661 DEV,
Chris Sosa75490802013-10-01 00:21:4562 BASE,
joychenc3944cb2013-08-19 17:42:0763 FULL,
Chris Sosa7cd23202013-10-16 00:22:5764 STATEFUL,
joychenc3944cb2013-08-19 17:42:0765 ANY,
joychen921e1fb2013-06-28 18:12:2066]
67
68LOCAL_FILE_NAMES = [
69 devserver_constants.TEST_IMAGE_FILE,
joychen921e1fb2013-06-28 18:12:2070 devserver_constants.IMAGE_FILE,
Chris Sosa75490802013-10-01 00:21:4571 devserver_constants.BASE_IMAGE_FILE,
joychen7c2054a2013-07-25 18:14:0772 devserver_constants.UPDATE_FILE,
Chris Sosa7cd23202013-10-16 00:22:5773 devserver_constants.STATEFUL_FILE,
Chris Sosa75490802013-10-01 00:21:4574 None, # For ANY.
joychen921e1fb2013-06-28 18:12:2075]
76
77LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
78
79# Google Storage constants
80GS_ALIASES = [
joychen25d25972013-07-30 21:54:1681 TEST,
joychen25d25972013-07-30 21:54:1682 BASE,
83 RECOVERY,
84 FULL,
85 STATEFUL,
86 AUTOTEST,
joychen3cb228e2013-06-12 19:13:1387]
88
joychen921e1fb2013-06-28 18:12:2089GS_FILE_NAMES = [
90 devserver_constants.TEST_IMAGE_FILE,
91 devserver_constants.BASE_IMAGE_FILE,
92 devserver_constants.RECOVERY_IMAGE_FILE,
joychen7c2054a2013-07-25 18:14:0793 devserver_constants.UPDATE_FILE,
joychen121fc9b2013-08-02 21:30:3094 devserver_constants.STATEFUL_FILE,
joychen3cb228e2013-06-12 19:13:1395 devserver_constants.AUTOTEST_DIR,
96]
97
98ARTIFACTS = [
99 artifact_info.TEST_IMAGE,
100 artifact_info.BASE_IMAGE,
101 artifact_info.RECOVERY_IMAGE,
102 artifact_info.FULL_PAYLOAD,
103 artifact_info.STATEFUL_PAYLOAD,
104 artifact_info.AUTOTEST,
105]
106
joychen921e1fb2013-06-28 18:12:20107GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
108GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 19:13:13109
joychen921e1fb2013-06-28 18:12:20110LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 19:13:13111
Chris Sosaea734d92013-10-11 18:28:58112RELEASE = "-release"
joychen3cb228e2013-06-12 19:13:13113
joychen3cb228e2013-06-12 19:13:13114
115class XBuddyException(Exception):
116 """Exception classes used by this module."""
117 pass
118
119
120# no __init__ method
121#pylint: disable=W0232
122class Timestamp():
123 """Class to translate build path strings and timestamp filenames."""
124
125 _TIMESTAMP_DELIMITER = 'SLASH'
126 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
127
128 @staticmethod
129 def TimestampToBuild(timestamp_filename):
130 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
131
132 @staticmethod
133 def BuildToTimestamp(build_path):
134 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 18:12:20135
136 @staticmethod
137 def UpdateTimestamp(timestamp_dir, build_id):
138 """Update timestamp file of build with build_id."""
139 common_util.MkDirP(timestamp_dir)
joychen562699a2013-08-13 22:22:14140 _Log("Updating timestamp for %s", build_id)
joychen921e1fb2013-06-28 18:12:20141 time_file = os.path.join(timestamp_dir,
142 Timestamp.BuildToTimestamp(build_id))
143 with file(time_file, 'a'):
144 os.utime(time_file, None)
joychen3cb228e2013-06-12 19:13:13145#pylint: enable=W0232
146
147
joychen921e1fb2013-06-28 18:12:20148class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 19:13:13149 """Class that manages image retrieval and caching by the devserver.
150
151 Image retrieval by xBuddy path:
152 XBuddy accesses images and artifacts that it stores using an xBuddy
153 path of the form: board/version/alias
154 The primary xbuddy.Get call retrieves the correct artifact or url to where
155 the artifacts can be found.
156
157 Image caching:
158 Images and other artifacts are stored identically to how they would have
159 been if devserver's stage rpc was called and the xBuddy cache replaces
160 build versions on a LRU basis. Timestamps are maintained by last accessed
161 times of representative files in the a directory in the static serve
162 directory (XBUDDY_TIMESTAMP_DIR).
163
164 Private class members:
joychen121fc9b2013-08-02 21:30:30165 _true_values: used for interpreting boolean values
166 _staging_thread_count: track download requests
167 _timestamp_folder: directory with empty files standing in as timestamps
joychen921e1fb2013-06-28 18:12:20168 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 19:13:13169 """
170 _true_values = ['true', 't', 'yes', 'y']
171
172 # Number of threads that are staging images.
173 _staging_thread_count = 0
174 # Lock used to lock increasing/decreasing count.
175 _staging_thread_count_lock = threading.Lock()
176
Chris Sosa7cd23202013-10-16 00:22:57177 def __init__(self, manage_builds=False, board=None, images_dir=None,
178 **kwargs):
joychen921e1fb2013-06-28 18:12:20179 super(XBuddy, self).__init__(**kwargs)
joychenb0dfe552013-07-30 17:02:06180
joychen562699a2013-08-13 22:22:14181 self.config = self._ReadConfig()
182 self._manage_builds = manage_builds or self._ManageBuilds()
Chris Sosa75490802013-10-01 00:21:45183 self._board = board
joychen921e1fb2013-06-28 18:12:20184 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 19:13:13185 Timestamp.XBUDDY_TIMESTAMP_DIR)
Chris Sosa7cd23202013-10-16 00:22:57186 if images_dir:
187 self.images_dir = images_dir
188 else:
189 self.images_dir = os.path.join(self.GetSourceRoot(), 'src/build/images')
190
joychen7df67f72013-07-18 21:21:12191 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 19:13:13192
193 @classmethod
194 def ParseBoolean(cls, boolean_string):
195 """Evaluate a string to a boolean value"""
196 if boolean_string:
197 return boolean_string.lower() in cls._true_values
198 else:
199 return False
200
joychen562699a2013-08-13 22:22:14201 def _ReadConfig(self):
202 """Read xbuddy config from ini files.
203
204 Reads the base config from xbuddy_config.ini, and then merges in the
205 shadow config from shadow_xbuddy_config.ini
206
207 Returns:
208 The merged configuration.
Yu-Ju Hongc54658c2014-01-22 17:18:07209
joychen562699a2013-08-13 22:22:14210 Raises:
211 XBuddyException if the config file is missing.
212 """
213 xbuddy_config = ConfigParser.ConfigParser()
214 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
215 if os.path.exists(config_file):
216 xbuddy_config.read(config_file)
217 else:
218 raise XBuddyException('%s not found' % (CONFIG_FILE))
219
220 # Read the shadow file if there is one.
Chris Sosac2abc722013-08-27 00:11:22221 if os.path.isdir(CHROOT_SHADOW_DIR):
222 shadow_config_file = os.path.join(CHROOT_SHADOW_DIR, SHADOW_CONFIG_FILE)
223 else:
224 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
225
226 _Log('Using shadow config file stored at %s', shadow_config_file)
joychen562699a2013-08-13 22:22:14227 if os.path.exists(shadow_config_file):
228 shadow_xbuddy_config = ConfigParser.ConfigParser()
229 shadow_xbuddy_config.read(shadow_config_file)
230
231 # Merge shadow config in.
232 sections = shadow_xbuddy_config.sections()
233 for s in sections:
234 if not xbuddy_config.has_section(s):
235 xbuddy_config.add_section(s)
236 options = shadow_xbuddy_config.options(s)
237 for o in options:
238 val = shadow_xbuddy_config.get(s, o)
239 xbuddy_config.set(s, o, val)
240
241 return xbuddy_config
242
243 def _ManageBuilds(self):
244 """Checks if xBuddy is managing local builds using the current config."""
245 try:
246 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
247 except ConfigParser.Error:
248 return False
249
250 def _Capacity(self):
251 """Gets the xbuddy capacity from the current config."""
252 try:
253 return int(self.config.get(GENERAL, 'capacity'))
254 except ConfigParser.Error:
255 return 5
256
257 def _LookupAlias(self, alias, board):
258 """Given the full xbuddy config, look up an alias for path rewrite.
259
260 Args:
261 alias: The xbuddy path that could be one of the aliases in the
262 rewrite table.
263 board: The board to fill in with when paths are rewritten. Can be from
264 the update request xml or the default board from devserver.
Yu-Ju Hongc54658c2014-01-22 17:18:07265
joychen562699a2013-08-13 22:22:14266 Returns:
267 If a rewrite is found, a string with the current board substituted in.
268 If no rewrite is found, just return the original string.
269 """
joychen562699a2013-08-13 22:22:14270 try:
271 val = self.config.get(PATH_REWRITES, alias)
272 except ConfigParser.Error:
273 # No alias lookup found. Return original path.
274 return alias
275
276 if not val.strip():
277 # The found value was an empty string.
278 return alias
279 else:
280 # Fill in the board.
joychenc3944cb2013-08-19 17:42:07281 rewrite = val.replace("BOARD", "%(board)s") % {
joychen562699a2013-08-13 22:22:14282 'board': board}
283 _Log("Path was rewritten to %s", rewrite)
284 return rewrite
285
joychenf8f07e22013-07-13 00:45:51286 def _LookupOfficial(self, board, suffix=RELEASE):
287 """Check LATEST-master for the version number of interest."""
288 _Log("Checking gs for latest %s-%s image", board, suffix)
289 latest_addr = devserver_constants.GS_LATEST_MASTER % {'board':board,
290 'suffix':suffix}
291 cmd = 'gsutil cat %s' % latest_addr
292 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 21:30:30293 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-13 00:45:51294 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 19:13:13295
joychenf8f07e22013-07-13 00:45:51296 return devserver_constants.IMAGE_DIR % {'board':board,
297 'suffix':suffix,
298 'version':version}
joychenf8f07e22013-07-13 00:45:51299 def _LookupChannel(self, board, channel='stable'):
300 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 21:30:30301 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 21:21:12302 _Log("Checking channel '%s' for latest '%s' image", channel, board)
Yu-Ju Hongc54658c2014-01-22 17:18:07303 # Due to historical reasons, gs://chromeos-releases uses
304 # daisy-spring as opposed to the board name daisy_spring. Convert
305 # the board name for the lookup.
306 channel_dir = devserver_constants.GS_CHANNEL_DIR % {
307 'channel':channel,
308 'board':re.sub('_', '-', board)}
joychen562699a2013-08-13 22:22:14309 latest_version = gsutil_util.GetLatestVersionFromGSDir(
310 channel_dir, with_release=False)
joychenf8f07e22013-07-13 00:45:51311
joychen121fc9b2013-08-02 21:30:30312 # Figure out release number from the version number.
joychenc3944cb2013-08-19 17:42:07313 image_url = devserver_constants.IMAGE_DIR % {
314 'board':board,
315 'suffix':RELEASE,
316 'version':'R*' + latest_version}
joychenf8f07e22013-07-13 00:45:51317 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
318
319 # There should only be one match on cros-image-archive.
320 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
321
322 return devserver_constants.IMAGE_DIR % {'board':board,
323 'suffix':RELEASE,
324 'version':full_version}
325
326 def _LookupVersion(self, board, version):
327 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 21:30:30328 # Build the pattern for GS to match.
joychen7df67f72013-07-18 21:21:12329 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
joychenf8f07e22013-07-13 00:45:51330 image_url = devserver_constants.IMAGE_DIR % {'board':board,
331 'suffix':RELEASE,
332 'version':version + '*'}
333 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
334
joychen121fc9b2013-08-02 21:30:30335 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-13 00:45:51336 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
337 return devserver_constants.IMAGE_DIR % {'board':board,
338 'suffix':RELEASE,
339 'version':full_version}
340
Chris Sosaea734d92013-10-11 18:28:58341 def _RemoteBuildId(self, board, version):
342 """Returns the remote build_id for the given board and version.
343
344 Raises:
345 XBuddyException: If we failed to resolve the version to a valid build_id.
346 """
347 build_id_as_is = devserver_constants.IMAGE_DIR % {'board':board,
348 'suffix':'',
349 'version':version}
350 build_id_release = devserver_constants.IMAGE_DIR % {'board':board,
351 'suffix':RELEASE,
352 'version':version}
353 # Return the first path that exists. We assume that what the user typed
354 # is better than with a default suffix added i.e. x86-generic/blah is
355 # more valuable than x86-generic-release/blah.
356 for build_id in build_id_as_is, build_id_release:
357 cmd = 'gsutil ls %s/%s' % (devserver_constants.GS_IMAGE_DIR, build_id)
358 try:
359 version = gsutil_util.GSUtilRun(cmd, None)
360 return build_id
361 except gsutil_util.GSUtilError:
362 continue
363 else:
364 raise XBuddyException('Could not find remote build_id for %s %s' % (
365 board, version))
366
367 def _ResolveVersionToBuildId(self, board, version):
joychen121fc9b2013-08-02 21:30:30368 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 19:13:13369
370 Args:
371 board: as specified in the original call. (i.e. x86-generic, parrot)
372 version: as entered in the original call. can be
373 {TBD, 0. some custom alias as defined in a config file}
374 1. latest
375 2. latest-{channel}
376 3. latest-official-{board suffix}
377 4. version prefix (i.e. RX-Y.X, RX-Y, RX)
joychen3cb228e2013-06-12 19:13:13378
379 Returns:
Chris Sosaea734d92013-10-11 18:28:58380 Location where the image dir is actually found on GS (build_id)
joychen3cb228e2013-06-12 19:13:13381
Chris Sosaea734d92013-10-11 18:28:58382 Raises:
383 XBuddyException: If we failed to resolve the version to a valid url.
joychen3cb228e2013-06-12 19:13:13384 """
joychenf8f07e22013-07-13 00:45:51385 # Only the last segment of the alias is variable relative to the rest.
386 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 19:13:13387
joychenf8f07e22013-07-13 00:45:51388 if re.match(devserver_constants.VERSION_RE, version):
Chris Sosaea734d92013-10-11 18:28:58389 return self._RemoteBuildId(board, version)
joychenf8f07e22013-07-13 00:45:51390 elif version == LATEST_OFFICIAL:
391 # latest-official --> LATEST build in board-release
392 return self._LookupOfficial(board)
393 elif version_tuple[0] == LATEST_OFFICIAL:
394 # latest-official-{suffix} --> LATEST build in board-{suffix}
395 return self._LookupOfficial(board, version_tuple[1])
396 elif version == LATEST:
397 # latest --> latest build on stable channel
398 return self._LookupChannel(board)
399 elif version_tuple[0] == LATEST:
400 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
401 # latest-R* --> most recent qualifying build
402 return self._LookupVersion(board, version_tuple[1])
403 else:
404 # latest-{channel} --> latest build within that channel
405 return self._LookupChannel(board, version_tuple[1])
joychen3cb228e2013-06-12 19:13:13406 else:
407 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 18:12:20408 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 19:13:13409
joychen5260b9a2013-07-16 21:48:01410 @staticmethod
411 def _Symlink(link, target):
412 """Symlinks link to target, and removes whatever link was there before."""
413 _Log("Linking to %s from %s", link, target)
414 if os.path.lexists(link):
415 os.unlink(link)
416 os.symlink(target, link)
417
joychen121fc9b2013-08-02 21:30:30418 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 18:12:20419 """Get the version of the latest image built for board by build_image
420
421 Updates the symlink reference within the xBuddy static dir to point to
422 the real image dir in the local /build/images directory.
423
424 Args:
joychenc3944cb2013-08-19 17:42:07425 board: board that image was built for.
joychen921e1fb2013-06-28 18:12:20426
427 Returns:
joychen121fc9b2013-08-02 21:30:30428 The discovered version of the image.
joychenc3944cb2013-08-19 17:42:07429
430 Raises:
431 XBuddyException if neither test nor dev image was found in latest built
432 directory.
joychen3cb228e2013-06-12 19:13:13433 """
joychen921e1fb2013-06-28 18:12:20434 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 17:02:06435 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 18:12:20436 raise XBuddyException('No builds found for %s. Did you run build_image?' %
437 board)
438
joychen121fc9b2013-08-02 21:30:30439 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 17:42:07440 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 18:12:20441
joychenc3944cb2013-08-19 17:42:07442 @staticmethod
443 def _FindAny(local_dir):
444 """Returns the image_type for ANY given the local_dir."""
445 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
446 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
447 if os.path.exists(dev_image):
448 return 'dev'
449
450 if os.path.exists(test_image):
451 return 'test'
452
453 raise XBuddyException('No images found in %s' % local_dir)
454
455 @staticmethod
Chris Sosa0eecf96e2014-02-03 22:14:39456 def _InterpretPath(path, default_board=None):
joychen121fc9b2013-08-02 21:30:30457 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 18:12:20458
joychen121fc9b2013-08-02 21:30:30459 Args:
460 path: the path xBuddy Get was called with.
Chris Sosa0eecf96e2014-02-03 22:14:39461 default_board: board to use in case board isn't in path.
joychen3cb228e2013-06-12 19:13:13462
Yu-Ju Hongc54658c2014-01-22 17:18:07463 Returns:
Chris Sosa75490802013-10-01 00:21:45464 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 19:13:13465
466 Raises:
467 XBuddyException: if the path can't be resolved into valid components
468 """
joychen121fc9b2013-08-02 21:30:30469 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 21:21:12470
Chris Sosa0eecf96e2014-02-03 22:14:39471 # Do the stuff that is well known first. We know that if paths have a
472 # image_type, it must be one of the GS/LOCAL aliases and it must be at the
473 # end. Similarly, local/remote are well-known and must start the path list.
474 is_local = True
475 if path_list and path_list[0] in (REMOTE, LOCAL):
476 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 21:21:12477
Chris Sosa0eecf96e2014-02-03 22:14:39478 # Default image type is determined by remote vs. local.
479 if is_local:
480 image_type = ANY
481 else:
482 image_type = TEST
joychen7df67f72013-07-18 21:21:12483
Chris Sosa0eecf96e2014-02-03 22:14:39484 if path_list and path_list[-1] in GS_ALIASES + LOCAL_ALIASES:
485 image_type = path_list.pop(-1)
joychen3cb228e2013-06-12 19:13:13486
Chris Sosa0eecf96e2014-02-03 22:14:39487 # Now for the tricky part. We don't actually know at this point if the rest
488 # of the path is just a board | version (like R33-2341.0.0) or just a board
489 # or just a version. So we do our best to do the right thing.
490 board = default_board
491 version = LATEST
492 if len(path_list) == 1:
493 path = path_list.pop(0)
494 # If it's a version we know (contains latest), go for that, otherwise only
495 # treat it as a version if we were given an actual default board.
496 if LATEST in path or default_board is not None:
497 version = path
joychen7df67f72013-07-18 21:21:12498 else:
Chris Sosa0eecf96e2014-02-03 22:14:39499 board = path
joychen7df67f72013-07-18 21:21:12500
Chris Sosa0eecf96e2014-02-03 22:14:39501 elif len(path_list) == 2:
502 # Assumes board/version.
503 board = path_list.pop(0)
504 version = path_list.pop(0)
505
506 if path_list:
507 raise XBuddyException("Path isn't valid. Could not figure out how to "
508 "parse remaining components: %s." % path_list)
509
510 _Log("Get artifact '%s' with board %s and version %s'. Locally? %s",
joychen7df67f72013-07-18 21:21:12511 image_type, board, version, is_local)
512
513 return image_type, board, version, is_local
joychen3cb228e2013-06-12 19:13:13514
joychen921e1fb2013-06-28 18:12:20515 def _SyncRegistryWithBuildImages(self):
joychen5260b9a2013-07-16 21:48:01516 """ Crawl images_dir for build_ids of images generated from build_image.
517
518 This will find images and symlink them in xBuddy's static dir so that
519 xBuddy's cache can serve them.
520 If xBuddy's _manage_builds option is on, then a timestamp will also be
521 generated, and xBuddy will clear them from the directory they are in, as
522 necessary.
523 """
joychen921e1fb2013-06-28 18:12:20524 build_ids = []
525 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 21:48:01526 # Ensure we have directories to track all boards in build/images
527 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 18:12:20528 board_dir = os.path.join(self.images_dir, b)
529 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 17:42:07530 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 18:12:20531
joychen121fc9b2013-08-02 21:30:30532 # Check currently registered images.
joychen921e1fb2013-06-28 18:12:20533 for f in os.listdir(self._timestamp_folder):
534 build_id = Timestamp.TimestampToBuild(f)
535 if build_id in build_ids:
536 build_ids.remove(build_id)
537
joychen121fc9b2013-08-02 21:30:30538 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 21:48:01539 for build_id in build_ids:
540 link = os.path.join(self.static_dir, build_id)
541 target = os.path.join(self.images_dir, build_id)
542 XBuddy._Symlink(link, target)
543 if self._manage_builds:
544 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 18:12:20545
546 def _ListBuildTimes(self):
joychen3cb228e2013-06-12 19:13:13547 """ Returns the currently cached builds and their last access timestamp.
548
549 Returns:
550 list of tuples that matches xBuddy build/version to timestamps in long
551 """
joychen121fc9b2013-08-02 21:30:30552 # Update currently cached builds.
joychen3cb228e2013-06-12 19:13:13553 build_dict = {}
554
joychen7df67f72013-07-18 21:21:12555 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 19:13:13556 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
557 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 17:42:07558 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 18:12:20559 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 19:13:13560 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
561 return return_tup
562
Chris Sosa75490802013-10-01 00:21:45563 def _Download(self, gs_url, artifacts):
564 """Download the artifacts from the given gs_url.
565
566 Raises:
567 build_artifact.ArtifactDownloadError: If we failed to download the
568 artifact.
569 """
joychen3cb228e2013-06-12 19:13:13570 with XBuddy._staging_thread_count_lock:
571 XBuddy._staging_thread_count += 1
572 try:
Chris Sosa75490802013-10-01 00:21:45573 _Log("Downloading %s from %s", artifacts, gs_url)
574 downloader.Downloader(self.static_dir, gs_url).Download(artifacts, [])
joychen3cb228e2013-06-12 19:13:13575 finally:
576 with XBuddy._staging_thread_count_lock:
577 XBuddy._staging_thread_count -= 1
578
Chris Sosa75490802013-10-01 00:21:45579 def CleanCache(self):
joychen562699a2013-08-13 22:22:14580 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 21:30:30581 if not self._manage_builds:
582 return
joychen921e1fb2013-06-28 18:12:20583 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 19:13:13584 _Log('In cache now: %s', cached_builds)
585
joychen562699a2013-08-13 22:22:14586 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 19:13:13587 b_path = cached_builds[b]
joychen7df67f72013-07-18 21:21:12588 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 19:13:13589
590 time_file = os.path.join(self._timestamp_folder,
591 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 18:12:20592 os.unlink(time_file)
593 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 19:13:13594 try:
joychen121fc9b2013-08-02 21:30:30595 # Handle symlinks, in the case of links to local builds if enabled.
596 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 21:48:01597 target = os.readlink(clear_dir)
598 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 18:12:20599
600 os.unlink(clear_dir)
joychen5260b9a2013-07-16 21:48:01601 if os.path.exists(target):
joychen921e1fb2013-06-28 18:12:20602 shutil.rmtree(target)
603 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 21:48:01604 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 19:13:13605 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 18:12:20606
joychen121fc9b2013-08-02 21:30:30607 except Exception as err:
608 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 19:13:13609
Chris Sosa75490802013-10-01 00:21:45610 def _GetFromGS(self, build_id, image_type):
611 """Check if the artifact is available locally. Download from GS if not.
612
613 Raises:
614 build_artifact.ArtifactDownloadError: If we failed to download the
615 artifact.
616 """
joychenf8f07e22013-07-13 00:45:51617 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
joychen921e1fb2013-06-28 18:12:20618 build_id)
619
joychen121fc9b2013-08-02 21:30:30620 # Stage image if not found in cache.
joychen921e1fb2013-06-28 18:12:20621 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 23:55:56622 file_loc = os.path.join(self.static_dir, build_id, file_name)
623 cached = os.path.exists(file_loc)
624
joychen921e1fb2013-06-28 18:12:20625 if not cached:
Chris Sosa75490802013-10-01 00:21:45626 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
627 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 18:12:20628 else:
629 _Log('Image already cached.')
630
Chris Sosa75490802013-10-01 00:21:45631 def _GetArtifact(self, path_list, board=None, lookup_only=False):
joychen346531c2013-07-24 23:55:56632 """Interpret an xBuddy path and return directory/file_name to resource.
633
Chris Sosa75490802013-10-01 00:21:45634 Note board can be passed that in but by default if self._board is set,
635 that is used rather than board.
636
joychen346531c2013-07-24 23:55:56637 Returns:
joychenc3944cb2013-08-19 17:42:07638 build_id to the directory
joychen346531c2013-07-24 23:55:56639 file_name of the artifact
joychen346531c2013-07-24 23:55:56640
641 Raises:
joychen121fc9b2013-08-02 21:30:30642 XBuddyException: if the path could not be translated
Chris Sosa75490802013-10-01 00:21:45643 build_artifact.ArtifactDownloadError: if we failed to download the
644 artifact.
joychen346531c2013-07-24 23:55:56645 """
joychen121fc9b2013-08-02 21:30:30646 path = '/'.join(path_list)
Chris Sosa0eecf96e2014-02-03 22:14:39647 default_board = self._board if self._board else board
joychenb0dfe552013-07-30 17:02:06648 # Rewrite the path if there is an appropriate default.
Chris Sosa0eecf96e2014-02-03 22:14:39649 path = self._LookupAlias(path, default_board)
joychen121fc9b2013-08-02 21:30:30650 # Parse the path.
Chris Sosa0eecf96e2014-02-03 22:14:39651 image_type, board, version, is_local = self._InterpretPath(
652 path, default_board)
joychen7df67f72013-07-18 21:21:12653 if is_local:
joychen121fc9b2013-08-02 21:30:30654 # Get a local image.
joychen7df67f72013-07-18 21:21:12655 if version == LATEST:
joychen121fc9b2013-08-02 21:30:30656 # Get the latest local image for the given board.
657 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 21:21:12658
joychenc3944cb2013-08-19 17:42:07659 build_id = os.path.join(board, version)
660 artifact_dir = os.path.join(self.static_dir, build_id)
661 if image_type == ANY:
662 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 21:30:30663
joychenc3944cb2013-08-19 17:42:07664 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
665 artifact_path = os.path.join(artifact_dir, file_name)
666 if not os.path.exists(artifact_path):
667 raise XBuddyException('Local %s artifact not in static_dir at %s' %
668 (image_type, artifact_path))
joychen121fc9b2013-08-02 21:30:30669
joychen921e1fb2013-06-28 18:12:20670 else:
joychen121fc9b2013-08-02 21:30:30671 # Get a remote image.
joychen921e1fb2013-06-28 18:12:20672 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 21:21:12673 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 18:12:20674 (image_type, GS_ALIASES))
Chris Sosaea734d92013-10-11 18:28:58675 build_id = self._ResolveVersionToBuildId(board, version)
Chris Sosa75490802013-10-01 00:21:45676 _Log('Resolved version %s to %s.', version, build_id)
677 file_name = GS_ALIAS_TO_FILENAME[image_type]
678 if not lookup_only:
679 self._GetFromGS(build_id, image_type)
joychenf8f07e22013-07-13 00:45:51680
joychenc3944cb2013-08-19 17:42:07681 return build_id, file_name
joychen3cb228e2013-06-12 19:13:13682
683 ############################ BEGIN PUBLIC METHODS
684
685 def List(self):
686 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 18:12:20687 self._SyncRegistryWithBuildImages()
688 builds = self._ListBuildTimes()
689 return_string = ''
690 for build, timestamp in builds:
691 return_string += '<b>' + build + '</b> '
692 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
693 return return_string
joychen3cb228e2013-06-12 19:13:13694
695 def Capacity(self):
696 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 22:22:14697 return str(self._Capacity())
joychen3cb228e2013-06-12 19:13:13698
Chris Sosa75490802013-10-01 00:21:45699 def Translate(self, path_list, board=None):
joychen346531c2013-07-24 23:55:56700 """Translates an xBuddy path to a real path to artifact if it exists.
701
joychen121fc9b2013-08-02 21:30:30702 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 23:55:56703
joychen7c2054a2013-07-25 18:14:07704 Returns:
joychen121fc9b2013-08-02 21:30:30705 build_id: Path to the image or update directory on the devserver.
706 e.g. 'x86-generic/R26-4000.0.0'
707 The returned path is always the path to the directory within
708 static_dir, so it is always the build_id of the image.
709 file_name: The file name of the artifact. Can take any of the file
710 values in devserver_constants.
711 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
712 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 18:14:07713
joychen121fc9b2013-08-02 21:30:30714 Raises:
715 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 23:55:56716 """
717 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-10-01 00:21:45718 build_id, file_name = self._GetArtifact(path_list, board=board,
719 lookup_only=True)
joychen346531c2013-07-24 23:55:56720
joychen121fc9b2013-08-02 21:30:30721 _Log('Returning path to payload: %s/%s', build_id, file_name)
722 return build_id, file_name
joychen346531c2013-07-24 23:55:56723
Chris Sosa75490802013-10-01 00:21:45724 def StageTestAritfactsForUpdate(self, path_list):
725 """Stages test artifacts for update and returns build_id.
726
727 Raises:
728 XBuddyException: if the path could not be translated
729 build_artifact.ArtifactDownloadError: if we failed to download the test
730 artifacts.
731 """
732 build_id, file_name = self.Translate(path_list)
733 if file_name == devserver_constants.TEST_IMAGE_FILE:
734 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
735 build_id)
736 artifacts = [FULL, STATEFUL]
737 self._Download(gs_url, artifacts)
738 return build_id
739
joychen562699a2013-08-13 22:22:14740 def Get(self, path_list):
joychen921e1fb2013-06-28 18:12:20741 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 19:13:13742
743 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 21:30:30744
joychen3cb228e2013-06-12 19:13:13745 Args:
joychen921e1fb2013-06-28 18:12:20746 path_list: [board, version, alias] as split from the xbuddy call url
joychen3cb228e2013-06-12 19:13:13747
748 Returns:
joychen121fc9b2013-08-02 21:30:30749 build_id: Path to the image or update directory on the devserver.
750 e.g. 'x86-generic/R26-4000.0.0'
751 The returned path is always the path to the directory within
752 static_dir, so it is always the build_id of the image.
753 file_name: The file name of the artifact. Can take any of the file
754 values in devserver_constants.
755 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
756 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 19:13:13757
758 Raises:
Chris Sosa75490802013-10-01 00:21:45759 XBuddyException: if the path could not be translated
760 build_artifact.ArtifactDownloadError: if we failed to download the
761 artifact.
joychen3cb228e2013-06-12 19:13:13762 """
joychen7df67f72013-07-18 21:21:12763 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-10-01 00:21:45764 build_id, file_name = self._GetArtifact(path_list)
joychen921e1fb2013-06-28 18:12:20765 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 19:13:13766 #TODO (joyc): run in sep thread
Chris Sosa75490802013-10-01 00:21:45767 self.CleanCache()
joychen3cb228e2013-06-12 19:13:13768
joychen121fc9b2013-08-02 21:30:30769 _Log('Returning path to payload: %s/%s', build_id, file_name)
770 return build_id, file_name