blob: d04d96ead2b9447ab55bd9ef873ada0b4cb1d21e [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
5import datetime
6import operator
7import os
joychenf8f07e22013-07-12 17:45:51 -07008import re
joychen3cb228e2013-06-12 12:13:13 -07009import shutil
joychenf8f07e22013-07-12 17:45:51 -070010import time
joychen3cb228e2013-06-12 12:13:13 -070011import threading
12
joychen921e1fb2013-06-28 11:12:20 -070013import build_util
joychen3cb228e2013-06-12 12:13:13 -070014import artifact_info
15import build_artifact
16import 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
joychen3cb228e2013-06-12 12:13:13 -070026_XBUDDY_CAPACITY = 5
joychen921e1fb2013-06-28 11:12:20 -070027
28# Local build constants
joychen7df67f72013-07-18 14:21:12 -070029LATEST = "latest"
30LOCAL = "local"
31REMOTE = "remote"
joychen921e1fb2013-06-28 11:12:20 -070032LOCAL_ALIASES = [
33 'test',
34 'base',
35 'dev',
36]
37
38LOCAL_FILE_NAMES = [
39 devserver_constants.TEST_IMAGE_FILE,
joychenf8f07e22013-07-12 17:45:51 -070040
joychen921e1fb2013-06-28 11:12:20 -070041 devserver_constants.BASE_IMAGE_FILE,
42 devserver_constants.IMAGE_FILE,
43]
44
45LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
46
47# Google Storage constants
48GS_ALIASES = [
joychen3cb228e2013-06-12 12:13:13 -070049 'test',
50 'base',
51 'recovery',
52 'full_payload',
53 'stateful',
54 'autotest',
55]
56
57# TODO(joyc) these should become devserver constants.
58# currently, storage locations are embedded in the artifact classes defined in
59# build_artifact
60
joychen921e1fb2013-06-28 11:12:20 -070061GS_FILE_NAMES = [
62 devserver_constants.TEST_IMAGE_FILE,
63 devserver_constants.BASE_IMAGE_FILE,
64 devserver_constants.RECOVERY_IMAGE_FILE,
joychen3cb228e2013-06-12 12:13:13 -070065 devserver_constants.ROOT_UPDATE_FILE,
66 build_artifact.STATEFUL_UPDATE_FILE,
67 devserver_constants.AUTOTEST_DIR,
68]
69
70ARTIFACTS = [
71 artifact_info.TEST_IMAGE,
72 artifact_info.BASE_IMAGE,
73 artifact_info.RECOVERY_IMAGE,
74 artifact_info.FULL_PAYLOAD,
75 artifact_info.STATEFUL_PAYLOAD,
76 artifact_info.AUTOTEST,
77]
78
joychen921e1fb2013-06-28 11:12:20 -070079GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
80GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 12:13:13 -070081
joychen921e1fb2013-06-28 11:12:20 -070082LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 12:13:13 -070083
joychenf8f07e22013-07-12 17:45:51 -070084RELEASE = "release"
joychen3cb228e2013-06-12 12:13:13 -070085
joychen3cb228e2013-06-12 12:13:13 -070086
87class XBuddyException(Exception):
88 """Exception classes used by this module."""
89 pass
90
91
92# no __init__ method
93#pylint: disable=W0232
94class Timestamp():
95 """Class to translate build path strings and timestamp filenames."""
96
97 _TIMESTAMP_DELIMITER = 'SLASH'
98 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
99
100 @staticmethod
101 def TimestampToBuild(timestamp_filename):
102 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
103
104 @staticmethod
105 def BuildToTimestamp(build_path):
106 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 11:12:20 -0700107
108 @staticmethod
109 def UpdateTimestamp(timestamp_dir, build_id):
110 """Update timestamp file of build with build_id."""
111 common_util.MkDirP(timestamp_dir)
112 time_file = os.path.join(timestamp_dir,
113 Timestamp.BuildToTimestamp(build_id))
114 with file(time_file, 'a'):
115 os.utime(time_file, None)
joychen3cb228e2013-06-12 12:13:13 -0700116#pylint: enable=W0232
117
118
joychen921e1fb2013-06-28 11:12:20 -0700119class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 12:13:13 -0700120 """Class that manages image retrieval and caching by the devserver.
121
122 Image retrieval by xBuddy path:
123 XBuddy accesses images and artifacts that it stores using an xBuddy
124 path of the form: board/version/alias
125 The primary xbuddy.Get call retrieves the correct artifact or url to where
126 the artifacts can be found.
127
128 Image caching:
129 Images and other artifacts are stored identically to how they would have
130 been if devserver's stage rpc was called and the xBuddy cache replaces
131 build versions on a LRU basis. Timestamps are maintained by last accessed
132 times of representative files in the a directory in the static serve
133 directory (XBUDDY_TIMESTAMP_DIR).
134
135 Private class members:
136 _true_values - used for interpreting boolean values
137 _staging_thread_count - track download requests
joychen921e1fb2013-06-28 11:12:20 -0700138 _timestamp_folder - directory with empty files standing in as timestamps
139 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 12:13:13 -0700140 """
141 _true_values = ['true', 't', 'yes', 'y']
142
143 # Number of threads that are staging images.
144 _staging_thread_count = 0
145 # Lock used to lock increasing/decreasing count.
146 _staging_thread_count_lock = threading.Lock()
147
joychen5260b9a2013-07-16 14:48:01 -0700148 def __init__(self, manage_builds=False, **kwargs):
joychen921e1fb2013-06-28 11:12:20 -0700149 super(XBuddy, self).__init__(**kwargs)
joychen5260b9a2013-07-16 14:48:01 -0700150 self._manage_builds = manage_builds
joychen921e1fb2013-06-28 11:12:20 -0700151 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 12:13:13 -0700152 Timestamp.XBUDDY_TIMESTAMP_DIR)
joychen7df67f72013-07-18 14:21:12 -0700153 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 12:13:13 -0700154
155 @classmethod
156 def ParseBoolean(cls, boolean_string):
157 """Evaluate a string to a boolean value"""
158 if boolean_string:
159 return boolean_string.lower() in cls._true_values
160 else:
161 return False
162
joychenf8f07e22013-07-12 17:45:51 -0700163 def _LookupOfficial(self, board, suffix=RELEASE):
164 """Check LATEST-master for the version number of interest."""
165 _Log("Checking gs for latest %s-%s image", board, suffix)
166 latest_addr = devserver_constants.GS_LATEST_MASTER % {'board':board,
167 'suffix':suffix}
168 cmd = 'gsutil cat %s' % latest_addr
169 msg = 'Failed to find build at %s' % latest_addr
170 # Full release + version is in the LATEST file
171 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700172
joychenf8f07e22013-07-12 17:45:51 -0700173 return devserver_constants.IMAGE_DIR % {'board':board,
174 'suffix':suffix,
175 'version':version}
176
177 def _LookupChannel(self, board, channel='stable'):
178 """Check the channel folder for the version number of interest."""
179 # Get all names in channel dir. Get 10 highest directories by version
joychen7df67f72013-07-18 14:21:12 -0700180 _Log("Checking channel '%s' for latest '%s' image", channel, board)
joychenf8f07e22013-07-12 17:45:51 -0700181 channel_dir = devserver_constants.GS_CHANNEL_DIR % {'channel':channel,
182 'board':board}
183 latest_version = gsutil_util.GetLatestVersionFromGSDir(channel_dir)
184
185 # Figure out release number from the version number
186 image_url = devserver_constants.IMAGE_DIR % {'board':board,
187 'suffix':RELEASE,
188 'version':'R*'+latest_version}
189 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
190
191 # There should only be one match on cros-image-archive.
192 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
193
194 return devserver_constants.IMAGE_DIR % {'board':board,
195 'suffix':RELEASE,
196 'version':full_version}
197
198 def _LookupVersion(self, board, version):
199 """Search GS image releases for the highest match to a version prefix."""
200 # Build the pattern for GS to match
joychen7df67f72013-07-18 14:21:12 -0700201 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
joychenf8f07e22013-07-12 17:45:51 -0700202 image_url = devserver_constants.IMAGE_DIR % {'board':board,
203 'suffix':RELEASE,
204 'version':version + '*'}
205 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
206
207 # grab the newest version of the ones matched
208 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
209 return devserver_constants.IMAGE_DIR % {'board':board,
210 'suffix':RELEASE,
211 'version':full_version}
212
213 def _ResolveVersionToUrl(self, board, version):
joychen3cb228e2013-06-12 12:13:13 -0700214 """
joychen921e1fb2013-06-28 11:12:20 -0700215 Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700216
217 Args:
218 board: as specified in the original call. (i.e. x86-generic, parrot)
219 version: as entered in the original call. can be
220 {TBD, 0. some custom alias as defined in a config file}
221 1. latest
222 2. latest-{channel}
223 3. latest-official-{board suffix}
224 4. version prefix (i.e. RX-Y.X, RX-Y, RX)
joychen3cb228e2013-06-12 12:13:13 -0700225
226 Returns:
joychenf8f07e22013-07-12 17:45:51 -0700227 image_url is where the image dir is actually found on GS
joychen3cb228e2013-06-12 12:13:13 -0700228
229 """
joychenf8f07e22013-07-12 17:45:51 -0700230 # TODO (joychen) Convert separate calls to a dict + error out bad paths
joychen3cb228e2013-06-12 12:13:13 -0700231
joychenf8f07e22013-07-12 17:45:51 -0700232 # Only the last segment of the alias is variable relative to the rest.
233 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700234
joychenf8f07e22013-07-12 17:45:51 -0700235 if re.match(devserver_constants.VERSION_RE, version):
236 # This is supposed to be a complete version number on GS. Return it.
237 return devserver_constants.IMAGE_DIR % {'board':board,
238 'suffix':RELEASE,
239 'version':version}
240 elif version == LATEST_OFFICIAL:
241 # latest-official --> LATEST build in board-release
242 return self._LookupOfficial(board)
243 elif version_tuple[0] == LATEST_OFFICIAL:
244 # latest-official-{suffix} --> LATEST build in board-{suffix}
245 return self._LookupOfficial(board, version_tuple[1])
246 elif version == LATEST:
247 # latest --> latest build on stable channel
248 return self._LookupChannel(board)
249 elif version_tuple[0] == LATEST:
250 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
251 # latest-R* --> most recent qualifying build
252 return self._LookupVersion(board, version_tuple[1])
253 else:
254 # latest-{channel} --> latest build within that channel
255 return self._LookupChannel(board, version_tuple[1])
joychen3cb228e2013-06-12 12:13:13 -0700256 else:
257 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700258 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700259
joychen5260b9a2013-07-16 14:48:01 -0700260 @staticmethod
261 def _Symlink(link, target):
262 """Symlinks link to target, and removes whatever link was there before."""
263 _Log("Linking to %s from %s", link, target)
264 if os.path.lexists(link):
265 os.unlink(link)
266 os.symlink(target, link)
267
joychen921e1fb2013-06-28 11:12:20 -0700268 def _GetLatestLocalVersion(self, board, file_name):
269 """Get the version of the latest image built for board by build_image
270
271 Updates the symlink reference within the xBuddy static dir to point to
272 the real image dir in the local /build/images directory.
273
274 Args:
275 board - board-suffix
276 file_name - the filename of the image we have cached
277
278 Returns:
279 version - the discovered version of the image.
joychen3cb228e2013-06-12 12:13:13 -0700280 """
joychen921e1fb2013-06-28 11:12:20 -0700281 latest_local_dir = self.GetLatestImageDir(board)
joychen7df67f72013-07-18 14:21:12 -0700282 if not latest_local_dir and os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700283 raise XBuddyException('No builds found for %s. Did you run build_image?' %
284 board)
285
286 # assume that the version number is the name of the directory
287 version = os.path.basename(latest_local_dir)
288
289 path_to_image = os.path.join(latest_local_dir, file_name)
290 if not os.path.exists(path_to_image):
291 raise XBuddyException('%s not found in %s. Did you run build_image?' %
292 (file_name, latest_local_dir))
joychen921e1fb2013-06-28 11:12:20 -0700293 return version
294
295 def _InterpretPath(self, path_list):
296 """
297 Split and return the pieces of an xBuddy path name
joychen3cb228e2013-06-12 12:13:13 -0700298
299 input:
joychen921e1fb2013-06-28 11:12:20 -0700300 path_list: the segments of the path xBuddy Get was called with.
301 Documentation of path_list can be found in devserver.py:xbuddy
joychen3cb228e2013-06-12 12:13:13 -0700302
303 Return:
joychenf8f07e22013-07-12 17:45:51 -0700304 tuple of (image_type, board, version)
joychen3cb228e2013-06-12 12:13:13 -0700305
306 Raises:
307 XBuddyException: if the path can't be resolved into valid components
308 """
joychen7df67f72013-07-18 14:21:12 -0700309 path_list = list(path_list)
310
311 # Required parts of path parsing.
312 try:
313 # Determine if image is explicitly local or remote.
314 is_local = False
315 if path_list[0] == LOCAL:
316 path_list.pop(0)
317 is_local = True
318 elif path_list[0] == REMOTE:
319 path_list.pop(0)
320 _Log(str(path_list))
321
322 # Set board
323 board = path_list.pop(0)
324 _Log(str(path_list))
325
326 # Set defaults
joychen3cb228e2013-06-12 12:13:13 -0700327 version = LATEST
joychen921e1fb2013-06-28 11:12:20 -0700328 image_type = GS_ALIASES[0]
joychen7df67f72013-07-18 14:21:12 -0700329 except IndexError:
330 msg = "Specify at least the board in your xBuddy call. Your path: %s"
331 raise XBuddyException(msg % os.path.join(path_list))
joychen3cb228e2013-06-12 12:13:13 -0700332
joychen7df67f72013-07-18 14:21:12 -0700333 # Read as much of the xBuddy path as possible
334 try:
335 # Override default if terminal is a valid artifact alias or a version
336 terminal = path_list[-1]
337 if terminal in GS_ALIASES + LOCAL_ALIASES:
338 image_type = terminal
339 version = path_list[-2]
340 else:
341 version = terminal
342 except IndexError:
343 # This path doesn't have an alias or a version. That's fine.
344 _Log("Some parts of the path not specified. Using defaults.")
345
346 _Log("Get artifact '%s' in {%s/%s}. Locally? %s",
347 image_type, board, version, is_local)
348
349 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700350
joychen921e1fb2013-06-28 11:12:20 -0700351 def _SyncRegistryWithBuildImages(self):
joychen5260b9a2013-07-16 14:48:01 -0700352 """ Crawl images_dir for build_ids of images generated from build_image.
353
354 This will find images and symlink them in xBuddy's static dir so that
355 xBuddy's cache can serve them.
356 If xBuddy's _manage_builds option is on, then a timestamp will also be
357 generated, and xBuddy will clear them from the directory they are in, as
358 necessary.
359 """
joychen921e1fb2013-06-28 11:12:20 -0700360 build_ids = []
361 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700362 # Ensure we have directories to track all boards in build/images
363 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700364 board_dir = os.path.join(self.images_dir, b)
365 build_ids.extend(['/'.join([b, v]) for v
366 in os.listdir(board_dir) if not v==LATEST])
367
368 # Check currently registered images
369 for f in os.listdir(self._timestamp_folder):
370 build_id = Timestamp.TimestampToBuild(f)
371 if build_id in build_ids:
372 build_ids.remove(build_id)
373
joychen5260b9a2013-07-16 14:48:01 -0700374 # Symlink undiscovered images, and update timestamps if manage_builds is on
375 for build_id in build_ids:
376 link = os.path.join(self.static_dir, build_id)
377 target = os.path.join(self.images_dir, build_id)
378 XBuddy._Symlink(link, target)
379 if self._manage_builds:
380 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700381
382 def _ListBuildTimes(self):
joychen3cb228e2013-06-12 12:13:13 -0700383 """ Returns the currently cached builds and their last access timestamp.
384
385 Returns:
386 list of tuples that matches xBuddy build/version to timestamps in long
387 """
388 # update currently cached builds
389 build_dict = {}
390
joychen7df67f72013-07-18 14:21:12 -0700391 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700392 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
393 build_id = Timestamp.TimestampToBuild(f)
394 stale_time = datetime.timedelta(seconds = (time.time()-last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700395 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700396 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
397 return return_tup
398
joychen3cb228e2013-06-12 12:13:13 -0700399 def _Download(self, gs_url, artifact):
400 """Download the single artifact from the given gs_url."""
401 with XBuddy._staging_thread_count_lock:
402 XBuddy._staging_thread_count += 1
403 try:
joychen7df67f72013-07-18 14:21:12 -0700404 _Log("Downloading '%s' from '%s'", artifact, gs_url)
joychen921e1fb2013-06-28 11:12:20 -0700405 downloader.Downloader(self.static_dir, gs_url).Download(
joychen3cb228e2013-06-12 12:13:13 -0700406 [artifact])
407 finally:
408 with XBuddy._staging_thread_count_lock:
409 XBuddy._staging_thread_count -= 1
410
411 def _CleanCache(self):
412 """Delete all builds besides the first _XBUDDY_CAPACITY builds"""
joychen921e1fb2013-06-28 11:12:20 -0700413 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700414 _Log('In cache now: %s', cached_builds)
415
416 for b in range(_XBUDDY_CAPACITY, len(cached_builds)):
417 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700418 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700419
420 time_file = os.path.join(self._timestamp_folder,
421 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700422 os.unlink(time_file)
423 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700424 try:
joychen5260b9a2013-07-16 14:48:01 -0700425 # handle symlinks, in the case of links to local builds if enabled
426 if self._manage_builds and os.path.islink(clear_dir):
427 target = os.readlink(clear_dir)
428 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700429
430 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700431 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700432 shutil.rmtree(target)
433 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700434 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700435 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700436
joychen3cb228e2013-06-12 12:13:13 -0700437 except Exception:
438 raise XBuddyException('Failed to clear build in %s.' % clear_dir)
439
joychen921e1fb2013-06-28 11:12:20 -0700440 def _GetFromGS(self, build_id, image_type):
441 """Check if the artifact is available locally. Download from GS if not."""
joychenf8f07e22013-07-12 17:45:51 -0700442 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
joychen921e1fb2013-06-28 11:12:20 -0700443 build_id)
444
445 # stage image if not found in cache
446 file_name = GS_ALIAS_TO_FILENAME[image_type]
447 cached = os.path.exists(os.path.join(self.static_dir,
448 build_id,
449 file_name))
450 if not cached:
451 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
joychen921e1fb2013-06-28 11:12:20 -0700452 self._Download(gs_url, artifact)
453 else:
454 _Log('Image already cached.')
455
456 def _GetArtifact(self, path):
457 """Interpret an xBuddy path and return directory/file_name to resource."""
joychen7df67f72013-07-18 14:21:12 -0700458 image_type, board, version, is_local = self._InterpretPath(path)
joychen921e1fb2013-06-28 11:12:20 -0700459
joychen7df67f72013-07-18 14:21:12 -0700460 if is_local:
joychen921e1fb2013-06-28 11:12:20 -0700461 # Get a local image
462 if image_type not in LOCAL_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700463 raise XBuddyException('Bad local image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700464 (image_type, LOCAL_ALIASES))
joychen921e1fb2013-06-28 11:12:20 -0700465 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
joychen7df67f72013-07-18 14:21:12 -0700466
467 if version == LATEST:
468 # Get the latest local image for the given board
469 version = self._GetLatestLocalVersion(board, file_name)
470 else:
471 # An exact version path in build/images was specified for this board
472 local_file = os.path.join(self.images_dir, board, version, file_name)
473 if not os.path.exists(local_file):
474 raise XBuddyException('File not found in local dir: %s', local_file)
475
joychenf8f07e22013-07-12 17:45:51 -0700476 image_url = os.path.join(board, version)
joychen921e1fb2013-06-28 11:12:20 -0700477 else:
478 # Get a remote image
479 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700480 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700481 (image_type, GS_ALIASES))
joychen921e1fb2013-06-28 11:12:20 -0700482 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen921e1fb2013-06-28 11:12:20 -0700483
joychenf8f07e22013-07-12 17:45:51 -0700484 # Interpret the version (alias), and get gs address
485 image_url = self._ResolveVersionToUrl(board, version)
joychenf8f07e22013-07-12 17:45:51 -0700486 self._GetFromGS(image_url, image_type)
487
joychenf8f07e22013-07-12 17:45:51 -0700488 return image_url, file_name
joychen3cb228e2013-06-12 12:13:13 -0700489
490 ############################ BEGIN PUBLIC METHODS
491
492 def List(self):
493 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700494 self._SyncRegistryWithBuildImages()
495 builds = self._ListBuildTimes()
496 return_string = ''
497 for build, timestamp in builds:
498 return_string += '<b>' + build + '</b> '
499 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
500 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700501
502 def Capacity(self):
503 """Returns the number of images cached by xBuddy."""
504 return str(_XBUDDY_CAPACITY)
505
joychen921e1fb2013-06-28 11:12:20 -0700506 def Get(self, path_list, return_dir=False):
507 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700508
509 Please see devserver.py:xbuddy for full documentation.
510 Args:
joychen921e1fb2013-06-28 11:12:20 -0700511 path_list: [board, version, alias] as split from the xbuddy call url
joychen3cb228e2013-06-12 12:13:13 -0700512 return_dir: boolean, if set to true, returns the dir name instead.
513
514 Returns:
515 Path to the image or update directory on the devserver.
joychenf8f07e22013-07-12 17:45:51 -0700516 e.g. http://host/static/x86-generic/
joychen3cb228e2013-06-12 12:13:13 -0700517 R26-4000.0.0/chromium-test-image.bin
518 or
joychenf8f07e22013-07-12 17:45:51 -0700519 http://host/static/x86-generic/R26-4000.0.0/
joychen3cb228e2013-06-12 12:13:13 -0700520
521 Raises:
522 XBuddyException if path is invalid or XBuddy's cache fails
523 """
joychen7df67f72013-07-18 14:21:12 -0700524 self._SyncRegistryWithBuildImages()
joychen921e1fb2013-06-28 11:12:20 -0700525 build_id, file_name = self._GetArtifact(path_list)
joychen3cb228e2013-06-12 12:13:13 -0700526
joychen921e1fb2013-06-28 11:12:20 -0700527 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700528
529 #TODO (joyc): run in sep thread
530 self._CleanCache()
531
joychen921e1fb2013-06-28 11:12:20 -0700532 return_url = os.path.join('static', build_id)
joychen3cb228e2013-06-12 12:13:13 -0700533 if not return_dir:
534 return_url = os.path.join(return_url, file_name)
535
536 _Log('Returning path to payload: %s', return_url)
537 return return_url