blob: 13a12850436cc05199544e8d901f6adbeda1b960 [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
joychen562699a2013-08-13 15:22:14 -07005import ConfigParser
joychen3cb228e2013-06-12 12:13:13 -07006import datetime
7import operator
8import os
joychenf8f07e22013-07-12 17:45:51 -07009import re
joychen3cb228e2013-06-12 12:13:13 -070010import shutil
joychenf8f07e22013-07-12 17:45:51 -070011import time
joychen3cb228e2013-06-12 12:13:13 -070012import threading
13
joychen921e1fb2013-06-28 11:12:20 -070014import build_util
joychen3cb228e2013-06-12 12:13:13 -070015import artifact_info
joychen3cb228e2013-06-12 12:13:13 -070016import common_util
17import devserver_constants
18import downloader
joychenf8f07e22013-07-12 17:45:51 -070019import gsutil_util
joychen3cb228e2013-06-12 12:13:13 -070020import log_util
21
22# Module-local log function.
23def _Log(message, *args):
24 return log_util.LogWithTag('XBUDDY', message, *args)
25
joychen562699a2013-08-13 15:22:14 -070026# xBuddy config constants
27CONFIG_FILE = 'xbuddy_config.ini'
28SHADOW_CONFIG_FILE = 'shadow_xbuddy_config.ini'
29PATH_REWRITES = 'PATH_REWRITES'
30GENERAL = 'GENERAL'
joychen921e1fb2013-06-28 11:12:20 -070031
joychen25d25972013-07-30 14:54:16 -070032# XBuddy aliases
33TEST = 'test'
34BASE = 'base'
35DEV = 'dev'
36FULL = 'full_payload'
37RECOVERY = 'recovery'
38STATEFUL = 'stateful'
39AUTOTEST = 'autotest'
40
joychen921e1fb2013-06-28 11:12:20 -070041# Local build constants
joychenc3944cb2013-08-19 10:42:07 -070042ANY = "ANY"
joychen7df67f72013-07-18 14:21:12 -070043LATEST = "latest"
44LOCAL = "local"
45REMOTE = "remote"
joychen921e1fb2013-06-28 11:12:20 -070046LOCAL_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070047 TEST,
48 BASE,
49 DEV,
joychenc3944cb2013-08-19 10:42:07 -070050 FULL,
51 ANY,
joychen921e1fb2013-06-28 11:12:20 -070052]
53
54LOCAL_FILE_NAMES = [
55 devserver_constants.TEST_IMAGE_FILE,
56 devserver_constants.BASE_IMAGE_FILE,
57 devserver_constants.IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070058 devserver_constants.UPDATE_FILE,
joychen921e1fb2013-06-28 11:12:20 -070059]
60
61LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
62
63# Google Storage constants
64GS_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070065 TEST,
66 BASE,
67 RECOVERY,
68 FULL,
69 STATEFUL,
70 AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -070071]
72
joychen921e1fb2013-06-28 11:12:20 -070073GS_FILE_NAMES = [
74 devserver_constants.TEST_IMAGE_FILE,
75 devserver_constants.BASE_IMAGE_FILE,
76 devserver_constants.RECOVERY_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070077 devserver_constants.UPDATE_FILE,
joychen121fc9b2013-08-02 14:30:30 -070078 devserver_constants.STATEFUL_FILE,
joychen3cb228e2013-06-12 12:13:13 -070079 devserver_constants.AUTOTEST_DIR,
80]
81
82ARTIFACTS = [
83 artifact_info.TEST_IMAGE,
84 artifact_info.BASE_IMAGE,
85 artifact_info.RECOVERY_IMAGE,
86 artifact_info.FULL_PAYLOAD,
87 artifact_info.STATEFUL_PAYLOAD,
88 artifact_info.AUTOTEST,
89]
90
joychen921e1fb2013-06-28 11:12:20 -070091GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
92GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 12:13:13 -070093
joychen921e1fb2013-06-28 11:12:20 -070094LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 12:13:13 -070095
joychenf8f07e22013-07-12 17:45:51 -070096RELEASE = "release"
joychen3cb228e2013-06-12 12:13:13 -070097
joychen3cb228e2013-06-12 12:13:13 -070098
99class XBuddyException(Exception):
100 """Exception classes used by this module."""
101 pass
102
103
104# no __init__ method
105#pylint: disable=W0232
106class Timestamp():
107 """Class to translate build path strings and timestamp filenames."""
108
109 _TIMESTAMP_DELIMITER = 'SLASH'
110 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
111
112 @staticmethod
113 def TimestampToBuild(timestamp_filename):
114 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
115
116 @staticmethod
117 def BuildToTimestamp(build_path):
118 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 11:12:20 -0700119
120 @staticmethod
121 def UpdateTimestamp(timestamp_dir, build_id):
122 """Update timestamp file of build with build_id."""
123 common_util.MkDirP(timestamp_dir)
joychen562699a2013-08-13 15:22:14 -0700124 _Log("Updating timestamp for %s", build_id)
joychen921e1fb2013-06-28 11:12:20 -0700125 time_file = os.path.join(timestamp_dir,
126 Timestamp.BuildToTimestamp(build_id))
127 with file(time_file, 'a'):
128 os.utime(time_file, None)
joychen3cb228e2013-06-12 12:13:13 -0700129#pylint: enable=W0232
130
131
joychen921e1fb2013-06-28 11:12:20 -0700132class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 12:13:13 -0700133 """Class that manages image retrieval and caching by the devserver.
134
135 Image retrieval by xBuddy path:
136 XBuddy accesses images and artifacts that it stores using an xBuddy
137 path of the form: board/version/alias
138 The primary xbuddy.Get call retrieves the correct artifact or url to where
139 the artifacts can be found.
140
141 Image caching:
142 Images and other artifacts are stored identically to how they would have
143 been if devserver's stage rpc was called and the xBuddy cache replaces
144 build versions on a LRU basis. Timestamps are maintained by last accessed
145 times of representative files in the a directory in the static serve
146 directory (XBUDDY_TIMESTAMP_DIR).
147
148 Private class members:
joychen121fc9b2013-08-02 14:30:30 -0700149 _true_values: used for interpreting boolean values
150 _staging_thread_count: track download requests
151 _timestamp_folder: directory with empty files standing in as timestamps
joychen921e1fb2013-06-28 11:12:20 -0700152 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 12:13:13 -0700153 """
154 _true_values = ['true', 't', 'yes', 'y']
155
156 # Number of threads that are staging images.
157 _staging_thread_count = 0
158 # Lock used to lock increasing/decreasing count.
159 _staging_thread_count_lock = threading.Lock()
160
joychenb0dfe552013-07-30 10:02:06 -0700161 def __init__(self, manage_builds=False, board=None, **kwargs):
joychen921e1fb2013-06-28 11:12:20 -0700162 super(XBuddy, self).__init__(**kwargs)
joychenb0dfe552013-07-30 10:02:06 -0700163
joychen562699a2013-08-13 15:22:14 -0700164 self.config = self._ReadConfig()
165 self._manage_builds = manage_builds or self._ManageBuilds()
166 self._board = board or self.GetDefaultBoardID()
joychenb0dfe552013-07-30 10:02:06 -0700167 _Log("Default board used by xBuddy: %s", self._board)
joychenb0dfe552013-07-30 10:02:06 -0700168
joychen921e1fb2013-06-28 11:12:20 -0700169 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 12:13:13 -0700170 Timestamp.XBUDDY_TIMESTAMP_DIR)
joychen7df67f72013-07-18 14:21:12 -0700171 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 12:13:13 -0700172
173 @classmethod
174 def ParseBoolean(cls, boolean_string):
175 """Evaluate a string to a boolean value"""
176 if boolean_string:
177 return boolean_string.lower() in cls._true_values
178 else:
179 return False
180
joychen562699a2013-08-13 15:22:14 -0700181 def _ReadConfig(self):
182 """Read xbuddy config from ini files.
183
184 Reads the base config from xbuddy_config.ini, and then merges in the
185 shadow config from shadow_xbuddy_config.ini
186
187 Returns:
188 The merged configuration.
189 Raises:
190 XBuddyException if the config file is missing.
191 """
192 xbuddy_config = ConfigParser.ConfigParser()
193 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
194 if os.path.exists(config_file):
195 xbuddy_config.read(config_file)
196 else:
197 raise XBuddyException('%s not found' % (CONFIG_FILE))
198
199 # Read the shadow file if there is one.
200 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
201 if os.path.exists(shadow_config_file):
202 shadow_xbuddy_config = ConfigParser.ConfigParser()
203 shadow_xbuddy_config.read(shadow_config_file)
204
205 # Merge shadow config in.
206 sections = shadow_xbuddy_config.sections()
207 for s in sections:
208 if not xbuddy_config.has_section(s):
209 xbuddy_config.add_section(s)
210 options = shadow_xbuddy_config.options(s)
211 for o in options:
212 val = shadow_xbuddy_config.get(s, o)
213 xbuddy_config.set(s, o, val)
214
215 return xbuddy_config
216
217 def _ManageBuilds(self):
218 """Checks if xBuddy is managing local builds using the current config."""
219 try:
220 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
221 except ConfigParser.Error:
222 return False
223
224 def _Capacity(self):
225 """Gets the xbuddy capacity from the current config."""
226 try:
227 return int(self.config.get(GENERAL, 'capacity'))
228 except ConfigParser.Error:
229 return 5
230
231 def _LookupAlias(self, alias, board):
232 """Given the full xbuddy config, look up an alias for path rewrite.
233
234 Args:
235 alias: The xbuddy path that could be one of the aliases in the
236 rewrite table.
237 board: The board to fill in with when paths are rewritten. Can be from
238 the update request xml or the default board from devserver.
239 Returns:
240 If a rewrite is found, a string with the current board substituted in.
241 If no rewrite is found, just return the original string.
242 """
243 if alias == '':
244 alias = 'update_default'
245
246 try:
247 val = self.config.get(PATH_REWRITES, alias)
248 except ConfigParser.Error:
249 # No alias lookup found. Return original path.
250 return alias
251
252 if not val.strip():
253 # The found value was an empty string.
254 return alias
255 else:
256 # Fill in the board.
joychenc3944cb2013-08-19 10:42:07 -0700257 rewrite = val.replace("BOARD", "%(board)s") % {
joychen562699a2013-08-13 15:22:14 -0700258 'board': board}
259 _Log("Path was rewritten to %s", rewrite)
260 return rewrite
261
joychenf8f07e22013-07-12 17:45:51 -0700262 def _LookupOfficial(self, board, suffix=RELEASE):
263 """Check LATEST-master for the version number of interest."""
264 _Log("Checking gs for latest %s-%s image", board, suffix)
265 latest_addr = devserver_constants.GS_LATEST_MASTER % {'board':board,
266 'suffix':suffix}
267 cmd = 'gsutil cat %s' % latest_addr
268 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700269 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700270 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700271
joychenf8f07e22013-07-12 17:45:51 -0700272 return devserver_constants.IMAGE_DIR % {'board':board,
273 'suffix':suffix,
274 'version':version}
275
276 def _LookupChannel(self, board, channel='stable'):
277 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700278 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700279 _Log("Checking channel '%s' for latest '%s' image", channel, board)
joychenf8f07e22013-07-12 17:45:51 -0700280 channel_dir = devserver_constants.GS_CHANNEL_DIR % {'channel':channel,
281 'board':board}
joychen562699a2013-08-13 15:22:14 -0700282 latest_version = gsutil_util.GetLatestVersionFromGSDir(
283 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700284
joychen121fc9b2013-08-02 14:30:30 -0700285 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700286 image_url = devserver_constants.IMAGE_DIR % {
287 'board':board,
288 'suffix':RELEASE,
289 'version':'R*' + latest_version}
joychenf8f07e22013-07-12 17:45:51 -0700290 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
291
292 # There should only be one match on cros-image-archive.
293 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
294
295 return devserver_constants.IMAGE_DIR % {'board':board,
296 'suffix':RELEASE,
297 'version':full_version}
298
299 def _LookupVersion(self, board, version):
300 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700301 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700302 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
joychenf8f07e22013-07-12 17:45:51 -0700303 image_url = devserver_constants.IMAGE_DIR % {'board':board,
304 'suffix':RELEASE,
305 'version':version + '*'}
306 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
307
joychen121fc9b2013-08-02 14:30:30 -0700308 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700309 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
310 return devserver_constants.IMAGE_DIR % {'board':board,
311 'suffix':RELEASE,
312 'version':full_version}
313
314 def _ResolveVersionToUrl(self, board, version):
joychen121fc9b2013-08-02 14:30:30 -0700315 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700316
317 Args:
318 board: as specified in the original call. (i.e. x86-generic, parrot)
319 version: as entered in the original call. can be
320 {TBD, 0. some custom alias as defined in a config file}
321 1. latest
322 2. latest-{channel}
323 3. latest-official-{board suffix}
324 4. version prefix (i.e. RX-Y.X, RX-Y, RX)
joychen3cb228e2013-06-12 12:13:13 -0700325
326 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700327 Location where the image dir is actually found on GS
joychen3cb228e2013-06-12 12:13:13 -0700328
329 """
joychen121fc9b2013-08-02 14:30:30 -0700330 # TODO(joychen): Convert separate calls to a dict + error out bad paths.
joychen3cb228e2013-06-12 12:13:13 -0700331
joychenf8f07e22013-07-12 17:45:51 -0700332 # Only the last segment of the alias is variable relative to the rest.
333 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700334
joychenf8f07e22013-07-12 17:45:51 -0700335 if re.match(devserver_constants.VERSION_RE, version):
336 # This is supposed to be a complete version number on GS. Return it.
337 return devserver_constants.IMAGE_DIR % {'board':board,
338 'suffix':RELEASE,
339 'version':version}
340 elif version == LATEST_OFFICIAL:
341 # latest-official --> LATEST build in board-release
342 return self._LookupOfficial(board)
343 elif version_tuple[0] == LATEST_OFFICIAL:
344 # latest-official-{suffix} --> LATEST build in board-{suffix}
345 return self._LookupOfficial(board, version_tuple[1])
346 elif version == LATEST:
347 # latest --> latest build on stable channel
348 return self._LookupChannel(board)
349 elif version_tuple[0] == LATEST:
350 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
351 # latest-R* --> most recent qualifying build
352 return self._LookupVersion(board, version_tuple[1])
353 else:
354 # latest-{channel} --> latest build within that channel
355 return self._LookupChannel(board, version_tuple[1])
joychen3cb228e2013-06-12 12:13:13 -0700356 else:
357 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700358 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700359
joychen5260b9a2013-07-16 14:48:01 -0700360 @staticmethod
361 def _Symlink(link, target):
362 """Symlinks link to target, and removes whatever link was there before."""
363 _Log("Linking to %s from %s", link, target)
364 if os.path.lexists(link):
365 os.unlink(link)
366 os.symlink(target, link)
367
joychen121fc9b2013-08-02 14:30:30 -0700368 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700369 """Get the version of the latest image built for board by build_image
370
371 Updates the symlink reference within the xBuddy static dir to point to
372 the real image dir in the local /build/images directory.
373
374 Args:
joychenc3944cb2013-08-19 10:42:07 -0700375 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700376
377 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700378 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700379
380 Raises:
381 XBuddyException if neither test nor dev image was found in latest built
382 directory.
joychen3cb228e2013-06-12 12:13:13 -0700383 """
joychen921e1fb2013-06-28 11:12:20 -0700384 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700385 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700386 raise XBuddyException('No builds found for %s. Did you run build_image?' %
387 board)
388
joychen121fc9b2013-08-02 14:30:30 -0700389 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700390 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700391
joychenc3944cb2013-08-19 10:42:07 -0700392 @staticmethod
393 def _FindAny(local_dir):
394 """Returns the image_type for ANY given the local_dir."""
395 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
396 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
397 if os.path.exists(dev_image):
398 return 'dev'
399
400 if os.path.exists(test_image):
401 return 'test'
402
403 raise XBuddyException('No images found in %s' % local_dir)
404
405 @staticmethod
406 def _InterpretPath(path):
joychen121fc9b2013-08-02 14:30:30 -0700407 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700408
joychen121fc9b2013-08-02 14:30:30 -0700409 Args:
410 path: the path xBuddy Get was called with.
joychen3cb228e2013-06-12 12:13:13 -0700411
412 Return:
joychenf8f07e22013-07-12 17:45:51 -0700413 tuple of (image_type, board, version)
joychen3cb228e2013-06-12 12:13:13 -0700414
415 Raises:
416 XBuddyException: if the path can't be resolved into valid components
417 """
joychen121fc9b2013-08-02 14:30:30 -0700418 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700419
420 # Required parts of path parsing.
421 try:
422 # Determine if image is explicitly local or remote.
joychen121fc9b2013-08-02 14:30:30 -0700423 is_local = True
424 if path_list[0] in (REMOTE, LOCAL):
joychen18737f32013-08-16 17:18:12 -0700425 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700426
joychen121fc9b2013-08-02 14:30:30 -0700427 # Set board.
joychen7df67f72013-07-18 14:21:12 -0700428 board = path_list.pop(0)
joychen7df67f72013-07-18 14:21:12 -0700429
joychen121fc9b2013-08-02 14:30:30 -0700430 # Set defaults.
joychen3cb228e2013-06-12 12:13:13 -0700431 version = LATEST
joychen921e1fb2013-06-28 11:12:20 -0700432 image_type = GS_ALIASES[0]
joychen7df67f72013-07-18 14:21:12 -0700433 except IndexError:
434 msg = "Specify at least the board in your xBuddy call. Your path: %s"
435 raise XBuddyException(msg % os.path.join(path_list))
joychen3cb228e2013-06-12 12:13:13 -0700436
joychen121fc9b2013-08-02 14:30:30 -0700437 # Read as much of the xBuddy path as possible.
joychen7df67f72013-07-18 14:21:12 -0700438 try:
joychen121fc9b2013-08-02 14:30:30 -0700439 # Override default if terminal is a valid artifact alias or a version.
joychen7df67f72013-07-18 14:21:12 -0700440 terminal = path_list[-1]
441 if terminal in GS_ALIASES + LOCAL_ALIASES:
442 image_type = terminal
443 version = path_list[-2]
444 else:
445 version = terminal
446 except IndexError:
447 # This path doesn't have an alias or a version. That's fine.
448 _Log("Some parts of the path not specified. Using defaults.")
449
joychen346531c2013-07-24 16:55:56 -0700450 _Log("Get artifact '%s' in '%s/%s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700451 image_type, board, version, is_local)
452
453 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700454
joychen921e1fb2013-06-28 11:12:20 -0700455 def _SyncRegistryWithBuildImages(self):
joychen5260b9a2013-07-16 14:48:01 -0700456 """ Crawl images_dir for build_ids of images generated from build_image.
457
458 This will find images and symlink them in xBuddy's static dir so that
459 xBuddy's cache can serve them.
460 If xBuddy's _manage_builds option is on, then a timestamp will also be
461 generated, and xBuddy will clear them from the directory they are in, as
462 necessary.
463 """
joychen921e1fb2013-06-28 11:12:20 -0700464 build_ids = []
465 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700466 # Ensure we have directories to track all boards in build/images
467 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700468 board_dir = os.path.join(self.images_dir, b)
469 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700470 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700471
joychen121fc9b2013-08-02 14:30:30 -0700472 # Check currently registered images.
joychen921e1fb2013-06-28 11:12:20 -0700473 for f in os.listdir(self._timestamp_folder):
474 build_id = Timestamp.TimestampToBuild(f)
475 if build_id in build_ids:
476 build_ids.remove(build_id)
477
joychen121fc9b2013-08-02 14:30:30 -0700478 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700479 for build_id in build_ids:
480 link = os.path.join(self.static_dir, build_id)
481 target = os.path.join(self.images_dir, build_id)
482 XBuddy._Symlink(link, target)
483 if self._manage_builds:
484 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700485
486 def _ListBuildTimes(self):
joychen3cb228e2013-06-12 12:13:13 -0700487 """ Returns the currently cached builds and their last access timestamp.
488
489 Returns:
490 list of tuples that matches xBuddy build/version to timestamps in long
491 """
joychen121fc9b2013-08-02 14:30:30 -0700492 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700493 build_dict = {}
494
joychen7df67f72013-07-18 14:21:12 -0700495 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700496 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
497 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700498 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700499 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700500 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
501 return return_tup
502
joychen3cb228e2013-06-12 12:13:13 -0700503 def _Download(self, gs_url, artifact):
504 """Download the single artifact from the given gs_url."""
505 with XBuddy._staging_thread_count_lock:
506 XBuddy._staging_thread_count += 1
507 try:
joychen7df67f72013-07-18 14:21:12 -0700508 _Log("Downloading '%s' from '%s'", artifact, gs_url)
joychen921e1fb2013-06-28 11:12:20 -0700509 downloader.Downloader(self.static_dir, gs_url).Download(
joychen18737f32013-08-16 17:18:12 -0700510 [artifact], [])
joychen3cb228e2013-06-12 12:13:13 -0700511 finally:
512 with XBuddy._staging_thread_count_lock:
513 XBuddy._staging_thread_count -= 1
514
515 def _CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700516 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700517 if not self._manage_builds:
518 return
joychen921e1fb2013-06-28 11:12:20 -0700519 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700520 _Log('In cache now: %s', cached_builds)
521
joychen562699a2013-08-13 15:22:14 -0700522 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700523 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700524 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700525
526 time_file = os.path.join(self._timestamp_folder,
527 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700528 os.unlink(time_file)
529 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700530 try:
joychen121fc9b2013-08-02 14:30:30 -0700531 # Handle symlinks, in the case of links to local builds if enabled.
532 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700533 target = os.readlink(clear_dir)
534 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700535
536 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700537 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700538 shutil.rmtree(target)
539 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700540 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700541 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700542
joychen121fc9b2013-08-02 14:30:30 -0700543 except Exception as err:
544 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700545
joychen346531c2013-07-24 16:55:56 -0700546 def _GetFromGS(self, build_id, image_type, lookup_only):
joychen121fc9b2013-08-02 14:30:30 -0700547 """Check if the artifact is available locally. Download from GS if not."""
joychenf8f07e22013-07-12 17:45:51 -0700548 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
joychen921e1fb2013-06-28 11:12:20 -0700549 build_id)
550
joychen121fc9b2013-08-02 14:30:30 -0700551 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700552 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700553 file_loc = os.path.join(self.static_dir, build_id, file_name)
554 cached = os.path.exists(file_loc)
555
joychen921e1fb2013-06-28 11:12:20 -0700556 if not cached:
joychen121fc9b2013-08-02 14:30:30 -0700557 if not lookup_only:
joychen346531c2013-07-24 16:55:56 -0700558 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
559 self._Download(gs_url, artifact)
joychen921e1fb2013-06-28 11:12:20 -0700560 else:
561 _Log('Image already cached.')
562
joychen562699a2013-08-13 15:22:14 -0700563 def _GetArtifact(self, path_list, board, lookup_only=False):
joychen346531c2013-07-24 16:55:56 -0700564 """Interpret an xBuddy path and return directory/file_name to resource.
565
566 Returns:
joychenc3944cb2013-08-19 10:42:07 -0700567 build_id to the directory
joychen346531c2013-07-24 16:55:56 -0700568 file_name of the artifact
joychen346531c2013-07-24 16:55:56 -0700569
570 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700571 XBuddyException: if the path could not be translated
joychen346531c2013-07-24 16:55:56 -0700572 """
joychen121fc9b2013-08-02 14:30:30 -0700573 path = '/'.join(path_list)
joychenb0dfe552013-07-30 10:02:06 -0700574 # Rewrite the path if there is an appropriate default.
joychen562699a2013-08-13 15:22:14 -0700575 path = self._LookupAlias(path, board)
joychenb0dfe552013-07-30 10:02:06 -0700576
joychen121fc9b2013-08-02 14:30:30 -0700577 # Parse the path.
joychen7df67f72013-07-18 14:21:12 -0700578 image_type, board, version, is_local = self._InterpretPath(path)
joychen921e1fb2013-06-28 11:12:20 -0700579
joychen7df67f72013-07-18 14:21:12 -0700580 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700581 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700582 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700583 # Get the latest local image for the given board.
584 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700585
joychenc3944cb2013-08-19 10:42:07 -0700586 build_id = os.path.join(board, version)
587 artifact_dir = os.path.join(self.static_dir, build_id)
588 if image_type == ANY:
589 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700590
joychenc3944cb2013-08-19 10:42:07 -0700591 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
592 artifact_path = os.path.join(artifact_dir, file_name)
593 if not os.path.exists(artifact_path):
594 raise XBuddyException('Local %s artifact not in static_dir at %s' %
595 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700596
joychen921e1fb2013-06-28 11:12:20 -0700597 else:
joychen121fc9b2013-08-02 14:30:30 -0700598 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700599 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700600 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700601 (image_type, GS_ALIASES))
joychen921e1fb2013-06-28 11:12:20 -0700602 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen921e1fb2013-06-28 11:12:20 -0700603
joychen121fc9b2013-08-02 14:30:30 -0700604 # Interpret the version (alias), and get gs address.
joychenc3944cb2013-08-19 10:42:07 -0700605 build_id = self._ResolveVersionToUrl(board, version)
606 _Log('Found on GS: %s', build_id)
607 self._GetFromGS(build_id, image_type, lookup_only)
joychenf8f07e22013-07-12 17:45:51 -0700608
joychenc3944cb2013-08-19 10:42:07 -0700609 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700610
611 ############################ BEGIN PUBLIC METHODS
612
613 def List(self):
614 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700615 self._SyncRegistryWithBuildImages()
616 builds = self._ListBuildTimes()
617 return_string = ''
618 for build, timestamp in builds:
619 return_string += '<b>' + build + '</b> '
620 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
621 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700622
623 def Capacity(self):
624 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700625 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700626
joychen562699a2013-08-13 15:22:14 -0700627 def Translate(self, path_list, board):
joychen346531c2013-07-24 16:55:56 -0700628 """Translates an xBuddy path to a real path to artifact if it exists.
629
joychen121fc9b2013-08-02 14:30:30 -0700630 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700631
joychen7c2054a2013-07-25 11:14:07 -0700632 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700633 build_id: Path to the image or update directory on the devserver.
634 e.g. 'x86-generic/R26-4000.0.0'
635 The returned path is always the path to the directory within
636 static_dir, so it is always the build_id of the image.
637 file_name: The file name of the artifact. Can take any of the file
638 values in devserver_constants.
639 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
640 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700641
joychen121fc9b2013-08-02 14:30:30 -0700642 Raises:
643 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700644 """
645 self._SyncRegistryWithBuildImages()
joychen121fc9b2013-08-02 14:30:30 -0700646 build_id, file_name = self._GetArtifact(path_list, board, lookup_only=True)
joychen346531c2013-07-24 16:55:56 -0700647
joychen121fc9b2013-08-02 14:30:30 -0700648 _Log('Returning path to payload: %s/%s', build_id, file_name)
649 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700650
joychen562699a2013-08-13 15:22:14 -0700651 def Get(self, path_list):
joychen921e1fb2013-06-28 11:12:20 -0700652 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700653
654 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700655
joychen3cb228e2013-06-12 12:13:13 -0700656 Args:
joychen921e1fb2013-06-28 11:12:20 -0700657 path_list: [board, version, alias] as split from the xbuddy call url
joychen3cb228e2013-06-12 12:13:13 -0700658
659 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700660 build_id: Path to the image or update directory on the devserver.
661 e.g. 'x86-generic/R26-4000.0.0'
662 The returned path is always the path to the directory within
663 static_dir, so it is always the build_id of the image.
664 file_name: The file name of the artifact. Can take any of the file
665 values in devserver_constants.
666 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
667 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700668
669 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700670 XBuddyException: if path is invalid
joychen3cb228e2013-06-12 12:13:13 -0700671 """
joychen7df67f72013-07-18 14:21:12 -0700672 self._SyncRegistryWithBuildImages()
joychen562699a2013-08-13 15:22:14 -0700673 build_id, file_name = self._GetArtifact(path_list, self._board)
joychen3cb228e2013-06-12 12:13:13 -0700674
joychen921e1fb2013-06-28 11:12:20 -0700675 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700676 #TODO (joyc): run in sep thread
677 self._CleanCache()
678
joychen121fc9b2013-08-02 14:30:30 -0700679 _Log('Returning path to payload: %s/%s', build_id, file_name)
680 return build_id, file_name