blob: 3c0075c993d6bbbd27401310361642444ff18d9d [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
joychen7df67f72013-07-18 14:21:12 -070042LATEST = "latest"
43LOCAL = "local"
44REMOTE = "remote"
joychen921e1fb2013-06-28 11:12:20 -070045LOCAL_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070046 TEST,
47 BASE,
48 DEV,
49 FULL
joychen921e1fb2013-06-28 11:12:20 -070050]
51
52LOCAL_FILE_NAMES = [
53 devserver_constants.TEST_IMAGE_FILE,
54 devserver_constants.BASE_IMAGE_FILE,
55 devserver_constants.IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070056 devserver_constants.UPDATE_FILE,
joychen921e1fb2013-06-28 11:12:20 -070057]
58
59LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
60
61# Google Storage constants
62GS_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070063 TEST,
64 BASE,
65 RECOVERY,
66 FULL,
67 STATEFUL,
68 AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -070069]
70
joychen921e1fb2013-06-28 11:12:20 -070071GS_FILE_NAMES = [
72 devserver_constants.TEST_IMAGE_FILE,
73 devserver_constants.BASE_IMAGE_FILE,
74 devserver_constants.RECOVERY_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070075 devserver_constants.UPDATE_FILE,
joychen121fc9b2013-08-02 14:30:30 -070076 devserver_constants.STATEFUL_FILE,
joychen3cb228e2013-06-12 12:13:13 -070077 devserver_constants.AUTOTEST_DIR,
78]
79
80ARTIFACTS = [
81 artifact_info.TEST_IMAGE,
82 artifact_info.BASE_IMAGE,
83 artifact_info.RECOVERY_IMAGE,
84 artifact_info.FULL_PAYLOAD,
85 artifact_info.STATEFUL_PAYLOAD,
86 artifact_info.AUTOTEST,
87]
88
joychen921e1fb2013-06-28 11:12:20 -070089GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
90GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 12:13:13 -070091
joychen921e1fb2013-06-28 11:12:20 -070092LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 12:13:13 -070093
joychenf8f07e22013-07-12 17:45:51 -070094RELEASE = "release"
joychen3cb228e2013-06-12 12:13:13 -070095
joychen3cb228e2013-06-12 12:13:13 -070096
97class XBuddyException(Exception):
98 """Exception classes used by this module."""
99 pass
100
101
102# no __init__ method
103#pylint: disable=W0232
104class Timestamp():
105 """Class to translate build path strings and timestamp filenames."""
106
107 _TIMESTAMP_DELIMITER = 'SLASH'
108 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
109
110 @staticmethod
111 def TimestampToBuild(timestamp_filename):
112 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
113
114 @staticmethod
115 def BuildToTimestamp(build_path):
116 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 11:12:20 -0700117
118 @staticmethod
119 def UpdateTimestamp(timestamp_dir, build_id):
120 """Update timestamp file of build with build_id."""
121 common_util.MkDirP(timestamp_dir)
joychen562699a2013-08-13 15:22:14 -0700122 _Log("Updating timestamp for %s", build_id)
joychen921e1fb2013-06-28 11:12:20 -0700123 time_file = os.path.join(timestamp_dir,
124 Timestamp.BuildToTimestamp(build_id))
125 with file(time_file, 'a'):
126 os.utime(time_file, None)
joychen3cb228e2013-06-12 12:13:13 -0700127#pylint: enable=W0232
128
129
joychen921e1fb2013-06-28 11:12:20 -0700130class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 12:13:13 -0700131 """Class that manages image retrieval and caching by the devserver.
132
133 Image retrieval by xBuddy path:
134 XBuddy accesses images and artifacts that it stores using an xBuddy
135 path of the form: board/version/alias
136 The primary xbuddy.Get call retrieves the correct artifact or url to where
137 the artifacts can be found.
138
139 Image caching:
140 Images and other artifacts are stored identically to how they would have
141 been if devserver's stage rpc was called and the xBuddy cache replaces
142 build versions on a LRU basis. Timestamps are maintained by last accessed
143 times of representative files in the a directory in the static serve
144 directory (XBUDDY_TIMESTAMP_DIR).
145
146 Private class members:
joychen121fc9b2013-08-02 14:30:30 -0700147 _true_values: used for interpreting boolean values
148 _staging_thread_count: track download requests
149 _timestamp_folder: directory with empty files standing in as timestamps
joychen921e1fb2013-06-28 11:12:20 -0700150 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 12:13:13 -0700151 """
152 _true_values = ['true', 't', 'yes', 'y']
153
154 # Number of threads that are staging images.
155 _staging_thread_count = 0
156 # Lock used to lock increasing/decreasing count.
157 _staging_thread_count_lock = threading.Lock()
158
joychenb0dfe552013-07-30 10:02:06 -0700159 def __init__(self, manage_builds=False, board=None, **kwargs):
joychen921e1fb2013-06-28 11:12:20 -0700160 super(XBuddy, self).__init__(**kwargs)
joychenb0dfe552013-07-30 10:02:06 -0700161
joychen562699a2013-08-13 15:22:14 -0700162 self.config = self._ReadConfig()
163 self._manage_builds = manage_builds or self._ManageBuilds()
164 self._board = board or self.GetDefaultBoardID()
joychenb0dfe552013-07-30 10:02:06 -0700165 _Log("Default board used by xBuddy: %s", self._board)
joychenb0dfe552013-07-30 10:02:06 -0700166
joychen921e1fb2013-06-28 11:12:20 -0700167 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 12:13:13 -0700168 Timestamp.XBUDDY_TIMESTAMP_DIR)
joychen7df67f72013-07-18 14:21:12 -0700169 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 12:13:13 -0700170
171 @classmethod
172 def ParseBoolean(cls, boolean_string):
173 """Evaluate a string to a boolean value"""
174 if boolean_string:
175 return boolean_string.lower() in cls._true_values
176 else:
177 return False
178
joychen562699a2013-08-13 15:22:14 -0700179 def _ReadConfig(self):
180 """Read xbuddy config from ini files.
181
182 Reads the base config from xbuddy_config.ini, and then merges in the
183 shadow config from shadow_xbuddy_config.ini
184
185 Returns:
186 The merged configuration.
187 Raises:
188 XBuddyException if the config file is missing.
189 """
190 xbuddy_config = ConfigParser.ConfigParser()
191 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
192 if os.path.exists(config_file):
193 xbuddy_config.read(config_file)
194 else:
195 raise XBuddyException('%s not found' % (CONFIG_FILE))
196
197 # Read the shadow file if there is one.
198 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
199 if os.path.exists(shadow_config_file):
200 shadow_xbuddy_config = ConfigParser.ConfigParser()
201 shadow_xbuddy_config.read(shadow_config_file)
202
203 # Merge shadow config in.
204 sections = shadow_xbuddy_config.sections()
205 for s in sections:
206 if not xbuddy_config.has_section(s):
207 xbuddy_config.add_section(s)
208 options = shadow_xbuddy_config.options(s)
209 for o in options:
210 val = shadow_xbuddy_config.get(s, o)
211 xbuddy_config.set(s, o, val)
212
213 return xbuddy_config
214
215 def _ManageBuilds(self):
216 """Checks if xBuddy is managing local builds using the current config."""
217 try:
218 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
219 except ConfigParser.Error:
220 return False
221
222 def _Capacity(self):
223 """Gets the xbuddy capacity from the current config."""
224 try:
225 return int(self.config.get(GENERAL, 'capacity'))
226 except ConfigParser.Error:
227 return 5
228
229 def _LookupAlias(self, alias, board):
230 """Given the full xbuddy config, look up an alias for path rewrite.
231
232 Args:
233 alias: The xbuddy path that could be one of the aliases in the
234 rewrite table.
235 board: The board to fill in with when paths are rewritten. Can be from
236 the update request xml or the default board from devserver.
237 Returns:
238 If a rewrite is found, a string with the current board substituted in.
239 If no rewrite is found, just return the original string.
240 """
241 if alias == '':
242 alias = 'update_default'
243
244 try:
245 val = self.config.get(PATH_REWRITES, alias)
246 except ConfigParser.Error:
247 # No alias lookup found. Return original path.
248 return alias
249
250 if not val.strip():
251 # The found value was an empty string.
252 return alias
253 else:
254 # Fill in the board.
255 rewrite = val.replace("BOARD", "%(board)s") % {
256 'board': board}
257 _Log("Path was rewritten to %s", rewrite)
258 return rewrite
259
joychenf8f07e22013-07-12 17:45:51 -0700260 def _LookupOfficial(self, board, suffix=RELEASE):
261 """Check LATEST-master for the version number of interest."""
262 _Log("Checking gs for latest %s-%s image", board, suffix)
263 latest_addr = devserver_constants.GS_LATEST_MASTER % {'board':board,
264 'suffix':suffix}
265 cmd = 'gsutil cat %s' % latest_addr
266 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700267 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700268 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700269
joychenf8f07e22013-07-12 17:45:51 -0700270 return devserver_constants.IMAGE_DIR % {'board':board,
271 'suffix':suffix,
272 'version':version}
273
274 def _LookupChannel(self, board, channel='stable'):
275 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700276 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700277 _Log("Checking channel '%s' for latest '%s' image", channel, board)
joychenf8f07e22013-07-12 17:45:51 -0700278 channel_dir = devserver_constants.GS_CHANNEL_DIR % {'channel':channel,
279 'board':board}
joychen562699a2013-08-13 15:22:14 -0700280 latest_version = gsutil_util.GetLatestVersionFromGSDir(
281 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700282
joychen121fc9b2013-08-02 14:30:30 -0700283 # Figure out release number from the version number.
joychenf8f07e22013-07-12 17:45:51 -0700284 image_url = devserver_constants.IMAGE_DIR % {'board':board,
285 'suffix':RELEASE,
286 'version':'R*'+latest_version}
287 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
288
289 # There should only be one match on cros-image-archive.
290 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
291
292 return devserver_constants.IMAGE_DIR % {'board':board,
293 'suffix':RELEASE,
294 'version':full_version}
295
296 def _LookupVersion(self, board, version):
297 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700298 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700299 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
joychenf8f07e22013-07-12 17:45:51 -0700300 image_url = devserver_constants.IMAGE_DIR % {'board':board,
301 'suffix':RELEASE,
302 'version':version + '*'}
303 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
304
joychen121fc9b2013-08-02 14:30:30 -0700305 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700306 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
307 return devserver_constants.IMAGE_DIR % {'board':board,
308 'suffix':RELEASE,
309 'version':full_version}
310
311 def _ResolveVersionToUrl(self, board, version):
joychen121fc9b2013-08-02 14:30:30 -0700312 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700313
314 Args:
315 board: as specified in the original call. (i.e. x86-generic, parrot)
316 version: as entered in the original call. can be
317 {TBD, 0. some custom alias as defined in a config file}
318 1. latest
319 2. latest-{channel}
320 3. latest-official-{board suffix}
321 4. version prefix (i.e. RX-Y.X, RX-Y, RX)
joychen3cb228e2013-06-12 12:13:13 -0700322
323 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700324 Location where the image dir is actually found on GS
joychen3cb228e2013-06-12 12:13:13 -0700325
326 """
joychen121fc9b2013-08-02 14:30:30 -0700327 # TODO(joychen): Convert separate calls to a dict + error out bad paths.
joychen3cb228e2013-06-12 12:13:13 -0700328
joychenf8f07e22013-07-12 17:45:51 -0700329 # Only the last segment of the alias is variable relative to the rest.
330 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700331
joychenf8f07e22013-07-12 17:45:51 -0700332 if re.match(devserver_constants.VERSION_RE, version):
333 # This is supposed to be a complete version number on GS. Return it.
334 return devserver_constants.IMAGE_DIR % {'board':board,
335 'suffix':RELEASE,
336 'version':version}
337 elif version == LATEST_OFFICIAL:
338 # latest-official --> LATEST build in board-release
339 return self._LookupOfficial(board)
340 elif version_tuple[0] == LATEST_OFFICIAL:
341 # latest-official-{suffix} --> LATEST build in board-{suffix}
342 return self._LookupOfficial(board, version_tuple[1])
343 elif version == LATEST:
344 # latest --> latest build on stable channel
345 return self._LookupChannel(board)
346 elif version_tuple[0] == LATEST:
347 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
348 # latest-R* --> most recent qualifying build
349 return self._LookupVersion(board, version_tuple[1])
350 else:
351 # latest-{channel} --> latest build within that channel
352 return self._LookupChannel(board, version_tuple[1])
joychen3cb228e2013-06-12 12:13:13 -0700353 else:
354 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700355 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700356
joychen5260b9a2013-07-16 14:48:01 -0700357 @staticmethod
358 def _Symlink(link, target):
359 """Symlinks link to target, and removes whatever link was there before."""
360 _Log("Linking to %s from %s", link, target)
361 if os.path.lexists(link):
362 os.unlink(link)
363 os.symlink(target, link)
364
joychen121fc9b2013-08-02 14:30:30 -0700365 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700366 """Get the version of the latest image built for board by build_image
367
368 Updates the symlink reference within the xBuddy static dir to point to
369 the real image dir in the local /build/images directory.
370
371 Args:
joychen121fc9b2013-08-02 14:30:30 -0700372 board: board that image was built for.jj
joychen921e1fb2013-06-28 11:12:20 -0700373
374 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700375 The discovered version of the image.
joychen3cb228e2013-06-12 12:13:13 -0700376 """
joychen921e1fb2013-06-28 11:12:20 -0700377 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700378 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700379 raise XBuddyException('No builds found for %s. Did you run build_image?' %
380 board)
381
joychen121fc9b2013-08-02 14:30:30 -0700382 # Assume that the version number is the name of the directory.
383 return os.path.basename(latest_local_dir)
joychen921e1fb2013-06-28 11:12:20 -0700384
joychen121fc9b2013-08-02 14:30:30 -0700385 def _InterpretPath(self, path):
386 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700387
joychen121fc9b2013-08-02 14:30:30 -0700388 Args:
389 path: the path xBuddy Get was called with.
joychen3cb228e2013-06-12 12:13:13 -0700390
391 Return:
joychenf8f07e22013-07-12 17:45:51 -0700392 tuple of (image_type, board, version)
joychen3cb228e2013-06-12 12:13:13 -0700393
394 Raises:
395 XBuddyException: if the path can't be resolved into valid components
396 """
joychen121fc9b2013-08-02 14:30:30 -0700397 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700398
399 # Required parts of path parsing.
400 try:
401 # Determine if image is explicitly local or remote.
joychen121fc9b2013-08-02 14:30:30 -0700402 is_local = True
403 if path_list[0] in (REMOTE, LOCAL):
joychen18737f32013-08-16 17:18:12 -0700404 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700405
joychen121fc9b2013-08-02 14:30:30 -0700406 # Set board.
joychen7df67f72013-07-18 14:21:12 -0700407 board = path_list.pop(0)
joychen7df67f72013-07-18 14:21:12 -0700408
joychen121fc9b2013-08-02 14:30:30 -0700409 # Set defaults.
joychen3cb228e2013-06-12 12:13:13 -0700410 version = LATEST
joychen921e1fb2013-06-28 11:12:20 -0700411 image_type = GS_ALIASES[0]
joychen7df67f72013-07-18 14:21:12 -0700412 except IndexError:
413 msg = "Specify at least the board in your xBuddy call. Your path: %s"
414 raise XBuddyException(msg % os.path.join(path_list))
joychen3cb228e2013-06-12 12:13:13 -0700415
joychen121fc9b2013-08-02 14:30:30 -0700416 # Read as much of the xBuddy path as possible.
joychen7df67f72013-07-18 14:21:12 -0700417 try:
joychen121fc9b2013-08-02 14:30:30 -0700418 # Override default if terminal is a valid artifact alias or a version.
joychen7df67f72013-07-18 14:21:12 -0700419 terminal = path_list[-1]
420 if terminal in GS_ALIASES + LOCAL_ALIASES:
421 image_type = terminal
422 version = path_list[-2]
423 else:
424 version = terminal
425 except IndexError:
426 # This path doesn't have an alias or a version. That's fine.
427 _Log("Some parts of the path not specified. Using defaults.")
428
joychen346531c2013-07-24 16:55:56 -0700429 _Log("Get artifact '%s' in '%s/%s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700430 image_type, board, version, is_local)
431
432 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700433
joychen921e1fb2013-06-28 11:12:20 -0700434 def _SyncRegistryWithBuildImages(self):
joychen5260b9a2013-07-16 14:48:01 -0700435 """ Crawl images_dir for build_ids of images generated from build_image.
436
437 This will find images and symlink them in xBuddy's static dir so that
438 xBuddy's cache can serve them.
439 If xBuddy's _manage_builds option is on, then a timestamp will also be
440 generated, and xBuddy will clear them from the directory they are in, as
441 necessary.
442 """
joychen921e1fb2013-06-28 11:12:20 -0700443 build_ids = []
444 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700445 # Ensure we have directories to track all boards in build/images
446 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700447 board_dir = os.path.join(self.images_dir, b)
448 build_ids.extend(['/'.join([b, v]) for v
449 in os.listdir(board_dir) if not v==LATEST])
450
joychen121fc9b2013-08-02 14:30:30 -0700451 # Check currently registered images.
joychen921e1fb2013-06-28 11:12:20 -0700452 for f in os.listdir(self._timestamp_folder):
453 build_id = Timestamp.TimestampToBuild(f)
454 if build_id in build_ids:
455 build_ids.remove(build_id)
456
joychen121fc9b2013-08-02 14:30:30 -0700457 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700458 for build_id in build_ids:
459 link = os.path.join(self.static_dir, build_id)
460 target = os.path.join(self.images_dir, build_id)
461 XBuddy._Symlink(link, target)
462 if self._manage_builds:
463 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700464
465 def _ListBuildTimes(self):
joychen3cb228e2013-06-12 12:13:13 -0700466 """ Returns the currently cached builds and their last access timestamp.
467
468 Returns:
469 list of tuples that matches xBuddy build/version to timestamps in long
470 """
joychen121fc9b2013-08-02 14:30:30 -0700471 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700472 build_dict = {}
473
joychen7df67f72013-07-18 14:21:12 -0700474 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700475 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
476 build_id = Timestamp.TimestampToBuild(f)
477 stale_time = datetime.timedelta(seconds = (time.time()-last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700478 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700479 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
480 return return_tup
481
joychen3cb228e2013-06-12 12:13:13 -0700482 def _Download(self, gs_url, artifact):
483 """Download the single artifact from the given gs_url."""
484 with XBuddy._staging_thread_count_lock:
485 XBuddy._staging_thread_count += 1
486 try:
joychen7df67f72013-07-18 14:21:12 -0700487 _Log("Downloading '%s' from '%s'", artifact, gs_url)
joychen921e1fb2013-06-28 11:12:20 -0700488 downloader.Downloader(self.static_dir, gs_url).Download(
joychen18737f32013-08-16 17:18:12 -0700489 [artifact], [])
joychen3cb228e2013-06-12 12:13:13 -0700490 finally:
491 with XBuddy._staging_thread_count_lock:
492 XBuddy._staging_thread_count -= 1
493
494 def _CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700495 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700496 if not self._manage_builds:
497 return
joychen921e1fb2013-06-28 11:12:20 -0700498 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700499 _Log('In cache now: %s', cached_builds)
500
joychen562699a2013-08-13 15:22:14 -0700501 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700502 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700503 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700504
505 time_file = os.path.join(self._timestamp_folder,
506 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700507 os.unlink(time_file)
508 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700509 try:
joychen121fc9b2013-08-02 14:30:30 -0700510 # Handle symlinks, in the case of links to local builds if enabled.
511 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700512 target = os.readlink(clear_dir)
513 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700514
515 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700516 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700517 shutil.rmtree(target)
518 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700519 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700520 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700521
joychen121fc9b2013-08-02 14:30:30 -0700522 except Exception as err:
523 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700524
joychen346531c2013-07-24 16:55:56 -0700525 def _GetFromGS(self, build_id, image_type, lookup_only):
joychen121fc9b2013-08-02 14:30:30 -0700526 """Check if the artifact is available locally. Download from GS if not."""
joychenf8f07e22013-07-12 17:45:51 -0700527 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
joychen921e1fb2013-06-28 11:12:20 -0700528 build_id)
529
joychen121fc9b2013-08-02 14:30:30 -0700530 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700531 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700532 file_loc = os.path.join(self.static_dir, build_id, file_name)
533 cached = os.path.exists(file_loc)
534
joychen921e1fb2013-06-28 11:12:20 -0700535 if not cached:
joychen121fc9b2013-08-02 14:30:30 -0700536 if not lookup_only:
joychen346531c2013-07-24 16:55:56 -0700537 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
538 self._Download(gs_url, artifact)
joychen921e1fb2013-06-28 11:12:20 -0700539 else:
540 _Log('Image already cached.')
541
joychen562699a2013-08-13 15:22:14 -0700542 def _GetArtifact(self, path_list, board, lookup_only=False):
joychen346531c2013-07-24 16:55:56 -0700543 """Interpret an xBuddy path and return directory/file_name to resource.
544
545 Returns:
546 image_url to the directory
547 file_name of the artifact
joychen346531c2013-07-24 16:55:56 -0700548
549 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700550 XBuddyException: if the path could not be translated
joychen346531c2013-07-24 16:55:56 -0700551 """
joychen121fc9b2013-08-02 14:30:30 -0700552 path = '/'.join(path_list)
joychenb0dfe552013-07-30 10:02:06 -0700553 # Rewrite the path if there is an appropriate default.
joychen562699a2013-08-13 15:22:14 -0700554 path = self._LookupAlias(path, board)
joychenb0dfe552013-07-30 10:02:06 -0700555
joychen121fc9b2013-08-02 14:30:30 -0700556 # Parse the path.
joychen7df67f72013-07-18 14:21:12 -0700557 image_type, board, version, is_local = self._InterpretPath(path)
joychen921e1fb2013-06-28 11:12:20 -0700558
joychen7df67f72013-07-18 14:21:12 -0700559 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700560 # Get a local image.
joychen921e1fb2013-06-28 11:12:20 -0700561 if image_type not in LOCAL_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700562 raise XBuddyException('Bad local image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700563 (image_type, LOCAL_ALIASES))
joychen921e1fb2013-06-28 11:12:20 -0700564 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
joychen7df67f72013-07-18 14:21:12 -0700565
566 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700567 # Get the latest local image for the given board.
568 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700569
joychenf8f07e22013-07-12 17:45:51 -0700570 image_url = os.path.join(board, version)
joychen121fc9b2013-08-02 14:30:30 -0700571
572 artifact_url = os.path.join(self.static_dir, image_url, file_name)
573 if not os.path.exists(artifact_url):
574 raise XBuddyException('Local artifact not in static_dir at %s/%s' %
575 (image_url, file_name))
576
joychen921e1fb2013-06-28 11:12:20 -0700577 else:
joychen121fc9b2013-08-02 14:30:30 -0700578 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700579 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700580 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700581 (image_type, GS_ALIASES))
joychen921e1fb2013-06-28 11:12:20 -0700582 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen921e1fb2013-06-28 11:12:20 -0700583
joychen121fc9b2013-08-02 14:30:30 -0700584 # Interpret the version (alias), and get gs address.
joychenf8f07e22013-07-12 17:45:51 -0700585 image_url = self._ResolveVersionToUrl(board, version)
joychen562699a2013-08-13 15:22:14 -0700586 _Log("Found on GS: %s", image_url)
joychen121fc9b2013-08-02 14:30:30 -0700587 self._GetFromGS(image_url, image_type, lookup_only)
joychenf8f07e22013-07-12 17:45:51 -0700588
joychen121fc9b2013-08-02 14:30:30 -0700589 return image_url, file_name
joychen3cb228e2013-06-12 12:13:13 -0700590
591 ############################ BEGIN PUBLIC METHODS
592
593 def List(self):
594 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700595 self._SyncRegistryWithBuildImages()
596 builds = self._ListBuildTimes()
597 return_string = ''
598 for build, timestamp in builds:
599 return_string += '<b>' + build + '</b> '
600 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
601 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700602
603 def Capacity(self):
604 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700605 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700606
joychen562699a2013-08-13 15:22:14 -0700607 def Translate(self, path_list, board):
joychen346531c2013-07-24 16:55:56 -0700608 """Translates an xBuddy path to a real path to artifact if it exists.
609
joychen121fc9b2013-08-02 14:30:30 -0700610 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700611
joychen7c2054a2013-07-25 11:14:07 -0700612 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700613 build_id: Path to the image or update directory on the devserver.
614 e.g. 'x86-generic/R26-4000.0.0'
615 The returned path is always the path to the directory within
616 static_dir, so it is always the build_id of the image.
617 file_name: The file name of the artifact. Can take any of the file
618 values in devserver_constants.
619 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
620 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700621
joychen121fc9b2013-08-02 14:30:30 -0700622 Raises:
623 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700624 """
625 self._SyncRegistryWithBuildImages()
joychen121fc9b2013-08-02 14:30:30 -0700626 build_id, file_name = self._GetArtifact(path_list, board, lookup_only=True)
joychen346531c2013-07-24 16:55:56 -0700627
joychen121fc9b2013-08-02 14:30:30 -0700628 _Log('Returning path to payload: %s/%s', build_id, file_name)
629 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700630
joychen562699a2013-08-13 15:22:14 -0700631 def Get(self, path_list):
joychen921e1fb2013-06-28 11:12:20 -0700632 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700633
634 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700635
joychen3cb228e2013-06-12 12:13:13 -0700636 Args:
joychen921e1fb2013-06-28 11:12:20 -0700637 path_list: [board, version, alias] as split from the xbuddy call url
joychen3cb228e2013-06-12 12:13:13 -0700638
639 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700640 build_id: Path to the image or update directory on the devserver.
641 e.g. 'x86-generic/R26-4000.0.0'
642 The returned path is always the path to the directory within
643 static_dir, so it is always the build_id of the image.
644 file_name: The file name of the artifact. Can take any of the file
645 values in devserver_constants.
646 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
647 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700648
649 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700650 XBuddyException: if path is invalid
joychen3cb228e2013-06-12 12:13:13 -0700651 """
joychen7df67f72013-07-18 14:21:12 -0700652 self._SyncRegistryWithBuildImages()
joychen562699a2013-08-13 15:22:14 -0700653 build_id, file_name = self._GetArtifact(path_list, self._board)
joychen3cb228e2013-06-12 12:13:13 -0700654
joychen921e1fb2013-06-28 11:12:20 -0700655 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700656 #TODO (joyc): run in sep thread
657 self._CleanCache()
658
joychen121fc9b2013-08-02 14:30:30 -0700659 _Log('Returning path to payload: %s/%s', build_id, file_name)
660 return build_id, file_name