blob: 7b5c8573ff984033d2beb1daa2ffbf7dcb8e372f [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
Chris Sosac2abc722013-08-26 17:11:22 -070032# Path for shadow config in chroot.
33CHROOT_SHADOW_DIR = '/mnt/host/source/src/platform/dev'
34
joychen25d25972013-07-30 14:54:16 -070035# XBuddy aliases
36TEST = 'test'
37BASE = 'base'
38DEV = 'dev'
39FULL = 'full_payload'
40RECOVERY = 'recovery'
41STATEFUL = 'stateful'
42AUTOTEST = 'autotest'
43
joychen921e1fb2013-06-28 11:12:20 -070044# Local build constants
joychenc3944cb2013-08-19 10:42:07 -070045ANY = "ANY"
joychen7df67f72013-07-18 14:21:12 -070046LATEST = "latest"
47LOCAL = "local"
48REMOTE = "remote"
Chris Sosa75490802013-09-30 17:21:45 -070049
50# TODO(sosa): Fix a lot of assumptions about these aliases. There is too much
51# implicit logic here that's unnecessary. What should be done:
52# 1) Collapse Alias logic to one set of aliases for xbuddy (not local/remote).
53# 2) Do not use zip when creating these dicts. Better to not rely on ordering.
54# 3) Move alias/artifact mapping to a central module rather than having it here.
55# 4) Be explicit when things are missing i.e. no dev images in image.zip.
56
joychen921e1fb2013-06-28 11:12:20 -070057LOCAL_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070058 TEST,
joychen25d25972013-07-30 14:54:16 -070059 DEV,
Chris Sosa75490802013-09-30 17:21:45 -070060 BASE,
joychenc3944cb2013-08-19 10:42:07 -070061 FULL,
62 ANY,
joychen921e1fb2013-06-28 11:12:20 -070063]
64
65LOCAL_FILE_NAMES = [
66 devserver_constants.TEST_IMAGE_FILE,
joychen921e1fb2013-06-28 11:12:20 -070067 devserver_constants.IMAGE_FILE,
Chris Sosa75490802013-09-30 17:21:45 -070068 devserver_constants.BASE_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070069 devserver_constants.UPDATE_FILE,
Chris Sosa75490802013-09-30 17:21:45 -070070 None, # For ANY.
joychen921e1fb2013-06-28 11:12:20 -070071]
72
73LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
74
75# Google Storage constants
76GS_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070077 TEST,
Chris Sosa75490802013-09-30 17:21:45 -070078 DEV,
joychen25d25972013-07-30 14:54:16 -070079 BASE,
80 RECOVERY,
81 FULL,
82 STATEFUL,
83 AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -070084]
85
joychen921e1fb2013-06-28 11:12:20 -070086GS_FILE_NAMES = [
87 devserver_constants.TEST_IMAGE_FILE,
88 devserver_constants.BASE_IMAGE_FILE,
89 devserver_constants.RECOVERY_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070090 devserver_constants.UPDATE_FILE,
joychen121fc9b2013-08-02 14:30:30 -070091 devserver_constants.STATEFUL_FILE,
joychen3cb228e2013-06-12 12:13:13 -070092 devserver_constants.AUTOTEST_DIR,
93]
94
95ARTIFACTS = [
96 artifact_info.TEST_IMAGE,
97 artifact_info.BASE_IMAGE,
98 artifact_info.RECOVERY_IMAGE,
99 artifact_info.FULL_PAYLOAD,
100 artifact_info.STATEFUL_PAYLOAD,
101 artifact_info.AUTOTEST,
102]
103
joychen921e1fb2013-06-28 11:12:20 -0700104GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
105GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 12:13:13 -0700106
joychen921e1fb2013-06-28 11:12:20 -0700107LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 12:13:13 -0700108
Chris Sosaea734d92013-10-11 11:28:58 -0700109RELEASE = "-release"
joychen3cb228e2013-06-12 12:13:13 -0700110
joychen3cb228e2013-06-12 12:13:13 -0700111
112class XBuddyException(Exception):
113 """Exception classes used by this module."""
114 pass
115
116
117# no __init__ method
118#pylint: disable=W0232
119class Timestamp():
120 """Class to translate build path strings and timestamp filenames."""
121
122 _TIMESTAMP_DELIMITER = 'SLASH'
123 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
124
125 @staticmethod
126 def TimestampToBuild(timestamp_filename):
127 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
128
129 @staticmethod
130 def BuildToTimestamp(build_path):
131 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 11:12:20 -0700132
133 @staticmethod
134 def UpdateTimestamp(timestamp_dir, build_id):
135 """Update timestamp file of build with build_id."""
136 common_util.MkDirP(timestamp_dir)
joychen562699a2013-08-13 15:22:14 -0700137 _Log("Updating timestamp for %s", build_id)
joychen921e1fb2013-06-28 11:12:20 -0700138 time_file = os.path.join(timestamp_dir,
139 Timestamp.BuildToTimestamp(build_id))
140 with file(time_file, 'a'):
141 os.utime(time_file, None)
joychen3cb228e2013-06-12 12:13:13 -0700142#pylint: enable=W0232
143
144
joychen921e1fb2013-06-28 11:12:20 -0700145class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 12:13:13 -0700146 """Class that manages image retrieval and caching by the devserver.
147
148 Image retrieval by xBuddy path:
149 XBuddy accesses images and artifacts that it stores using an xBuddy
150 path of the form: board/version/alias
151 The primary xbuddy.Get call retrieves the correct artifact or url to where
152 the artifacts can be found.
153
154 Image caching:
155 Images and other artifacts are stored identically to how they would have
156 been if devserver's stage rpc was called and the xBuddy cache replaces
157 build versions on a LRU basis. Timestamps are maintained by last accessed
158 times of representative files in the a directory in the static serve
159 directory (XBUDDY_TIMESTAMP_DIR).
160
161 Private class members:
joychen121fc9b2013-08-02 14:30:30 -0700162 _true_values: used for interpreting boolean values
163 _staging_thread_count: track download requests
164 _timestamp_folder: directory with empty files standing in as timestamps
joychen921e1fb2013-06-28 11:12:20 -0700165 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 12:13:13 -0700166 """
167 _true_values = ['true', 't', 'yes', 'y']
168
169 # Number of threads that are staging images.
170 _staging_thread_count = 0
171 # Lock used to lock increasing/decreasing count.
172 _staging_thread_count_lock = threading.Lock()
173
joychenb0dfe552013-07-30 10:02:06 -0700174 def __init__(self, manage_builds=False, board=None, **kwargs):
joychen921e1fb2013-06-28 11:12:20 -0700175 super(XBuddy, self).__init__(**kwargs)
joychenb0dfe552013-07-30 10:02:06 -0700176
joychen562699a2013-08-13 15:22:14 -0700177 self.config = self._ReadConfig()
178 self._manage_builds = manage_builds or self._ManageBuilds()
Chris Sosa75490802013-09-30 17:21:45 -0700179 self._board = board
joychen921e1fb2013-06-28 11:12:20 -0700180 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 12:13:13 -0700181 Timestamp.XBUDDY_TIMESTAMP_DIR)
joychen7df67f72013-07-18 14:21:12 -0700182 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 12:13:13 -0700183
184 @classmethod
185 def ParseBoolean(cls, boolean_string):
186 """Evaluate a string to a boolean value"""
187 if boolean_string:
188 return boolean_string.lower() in cls._true_values
189 else:
190 return False
191
joychen562699a2013-08-13 15:22:14 -0700192 def _ReadConfig(self):
193 """Read xbuddy config from ini files.
194
195 Reads the base config from xbuddy_config.ini, and then merges in the
196 shadow config from shadow_xbuddy_config.ini
197
198 Returns:
199 The merged configuration.
200 Raises:
201 XBuddyException if the config file is missing.
202 """
203 xbuddy_config = ConfigParser.ConfigParser()
204 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
205 if os.path.exists(config_file):
206 xbuddy_config.read(config_file)
207 else:
208 raise XBuddyException('%s not found' % (CONFIG_FILE))
209
210 # Read the shadow file if there is one.
Chris Sosac2abc722013-08-26 17:11:22 -0700211 if os.path.isdir(CHROOT_SHADOW_DIR):
212 shadow_config_file = os.path.join(CHROOT_SHADOW_DIR, SHADOW_CONFIG_FILE)
213 else:
214 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
215
216 _Log('Using shadow config file stored at %s', shadow_config_file)
joychen562699a2013-08-13 15:22:14 -0700217 if os.path.exists(shadow_config_file):
218 shadow_xbuddy_config = ConfigParser.ConfigParser()
219 shadow_xbuddy_config.read(shadow_config_file)
220
221 # Merge shadow config in.
222 sections = shadow_xbuddy_config.sections()
223 for s in sections:
224 if not xbuddy_config.has_section(s):
225 xbuddy_config.add_section(s)
226 options = shadow_xbuddy_config.options(s)
227 for o in options:
228 val = shadow_xbuddy_config.get(s, o)
229 xbuddy_config.set(s, o, val)
230
231 return xbuddy_config
232
233 def _ManageBuilds(self):
234 """Checks if xBuddy is managing local builds using the current config."""
235 try:
236 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
237 except ConfigParser.Error:
238 return False
239
240 def _Capacity(self):
241 """Gets the xbuddy capacity from the current config."""
242 try:
243 return int(self.config.get(GENERAL, 'capacity'))
244 except ConfigParser.Error:
245 return 5
246
247 def _LookupAlias(self, alias, board):
248 """Given the full xbuddy config, look up an alias for path rewrite.
249
250 Args:
251 alias: The xbuddy path that could be one of the aliases in the
252 rewrite table.
253 board: The board to fill in with when paths are rewritten. Can be from
254 the update request xml or the default board from devserver.
255 Returns:
256 If a rewrite is found, a string with the current board substituted in.
257 If no rewrite is found, just return the original string.
258 """
259 if alias == '':
260 alias = 'update_default'
261
262 try:
263 val = self.config.get(PATH_REWRITES, alias)
264 except ConfigParser.Error:
265 # No alias lookup found. Return original path.
266 return alias
267
268 if not val.strip():
269 # The found value was an empty string.
270 return alias
271 else:
272 # Fill in the board.
joychenc3944cb2013-08-19 10:42:07 -0700273 rewrite = val.replace("BOARD", "%(board)s") % {
joychen562699a2013-08-13 15:22:14 -0700274 'board': board}
275 _Log("Path was rewritten to %s", rewrite)
276 return rewrite
277
joychenf8f07e22013-07-12 17:45:51 -0700278 def _LookupOfficial(self, board, suffix=RELEASE):
279 """Check LATEST-master for the version number of interest."""
280 _Log("Checking gs for latest %s-%s image", board, suffix)
281 latest_addr = devserver_constants.GS_LATEST_MASTER % {'board':board,
282 'suffix':suffix}
283 cmd = 'gsutil cat %s' % latest_addr
284 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700285 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700286 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700287
joychenf8f07e22013-07-12 17:45:51 -0700288 return devserver_constants.IMAGE_DIR % {'board':board,
289 'suffix':suffix,
290 'version':version}
joychenf8f07e22013-07-12 17:45:51 -0700291 def _LookupChannel(self, board, channel='stable'):
292 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700293 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700294 _Log("Checking channel '%s' for latest '%s' image", channel, board)
joychenf8f07e22013-07-12 17:45:51 -0700295 channel_dir = devserver_constants.GS_CHANNEL_DIR % {'channel':channel,
296 'board':board}
joychen562699a2013-08-13 15:22:14 -0700297 latest_version = gsutil_util.GetLatestVersionFromGSDir(
298 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700299
joychen121fc9b2013-08-02 14:30:30 -0700300 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700301 image_url = devserver_constants.IMAGE_DIR % {
302 'board':board,
303 'suffix':RELEASE,
304 'version':'R*' + latest_version}
joychenf8f07e22013-07-12 17:45:51 -0700305 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
306
307 # There should only be one match on cros-image-archive.
308 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
309
310 return devserver_constants.IMAGE_DIR % {'board':board,
311 'suffix':RELEASE,
312 'version':full_version}
313
314 def _LookupVersion(self, board, version):
315 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700316 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700317 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
joychenf8f07e22013-07-12 17:45:51 -0700318 image_url = devserver_constants.IMAGE_DIR % {'board':board,
319 'suffix':RELEASE,
320 'version':version + '*'}
321 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
322
joychen121fc9b2013-08-02 14:30:30 -0700323 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700324 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
325 return devserver_constants.IMAGE_DIR % {'board':board,
326 'suffix':RELEASE,
327 'version':full_version}
328
Chris Sosaea734d92013-10-11 11:28:58 -0700329 def _RemoteBuildId(self, board, version):
330 """Returns the remote build_id for the given board and version.
331
332 Raises:
333 XBuddyException: If we failed to resolve the version to a valid build_id.
334 """
335 build_id_as_is = devserver_constants.IMAGE_DIR % {'board':board,
336 'suffix':'',
337 'version':version}
338 build_id_release = devserver_constants.IMAGE_DIR % {'board':board,
339 'suffix':RELEASE,
340 'version':version}
341 # Return the first path that exists. We assume that what the user typed
342 # is better than with a default suffix added i.e. x86-generic/blah is
343 # more valuable than x86-generic-release/blah.
344 for build_id in build_id_as_is, build_id_release:
345 cmd = 'gsutil ls %s/%s' % (devserver_constants.GS_IMAGE_DIR, build_id)
346 try:
347 version = gsutil_util.GSUtilRun(cmd, None)
348 return build_id
349 except gsutil_util.GSUtilError:
350 continue
351 else:
352 raise XBuddyException('Could not find remote build_id for %s %s' % (
353 board, version))
354
355 def _ResolveVersionToBuildId(self, board, version):
joychen121fc9b2013-08-02 14:30:30 -0700356 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700357
358 Args:
359 board: as specified in the original call. (i.e. x86-generic, parrot)
360 version: as entered in the original call. can be
361 {TBD, 0. some custom alias as defined in a config file}
362 1. latest
363 2. latest-{channel}
364 3. latest-official-{board suffix}
365 4. version prefix (i.e. RX-Y.X, RX-Y, RX)
joychen3cb228e2013-06-12 12:13:13 -0700366
367 Returns:
Chris Sosaea734d92013-10-11 11:28:58 -0700368 Location where the image dir is actually found on GS (build_id)
joychen3cb228e2013-06-12 12:13:13 -0700369
Chris Sosaea734d92013-10-11 11:28:58 -0700370 Raises:
371 XBuddyException: If we failed to resolve the version to a valid url.
joychen3cb228e2013-06-12 12:13:13 -0700372 """
joychenf8f07e22013-07-12 17:45:51 -0700373 # Only the last segment of the alias is variable relative to the rest.
374 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700375
joychenf8f07e22013-07-12 17:45:51 -0700376 if re.match(devserver_constants.VERSION_RE, version):
Chris Sosaea734d92013-10-11 11:28:58 -0700377 return self._RemoteBuildId(board, version)
joychenf8f07e22013-07-12 17:45:51 -0700378 elif version == LATEST_OFFICIAL:
379 # latest-official --> LATEST build in board-release
380 return self._LookupOfficial(board)
381 elif version_tuple[0] == LATEST_OFFICIAL:
382 # latest-official-{suffix} --> LATEST build in board-{suffix}
383 return self._LookupOfficial(board, version_tuple[1])
384 elif version == LATEST:
385 # latest --> latest build on stable channel
386 return self._LookupChannel(board)
387 elif version_tuple[0] == LATEST:
388 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
389 # latest-R* --> most recent qualifying build
390 return self._LookupVersion(board, version_tuple[1])
391 else:
392 # latest-{channel} --> latest build within that channel
393 return self._LookupChannel(board, version_tuple[1])
joychen3cb228e2013-06-12 12:13:13 -0700394 else:
395 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700396 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700397
joychen5260b9a2013-07-16 14:48:01 -0700398 @staticmethod
399 def _Symlink(link, target):
400 """Symlinks link to target, and removes whatever link was there before."""
401 _Log("Linking to %s from %s", link, target)
402 if os.path.lexists(link):
403 os.unlink(link)
404 os.symlink(target, link)
405
joychen121fc9b2013-08-02 14:30:30 -0700406 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700407 """Get the version of the latest image built for board by build_image
408
409 Updates the symlink reference within the xBuddy static dir to point to
410 the real image dir in the local /build/images directory.
411
412 Args:
joychenc3944cb2013-08-19 10:42:07 -0700413 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700414
415 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700416 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700417
418 Raises:
419 XBuddyException if neither test nor dev image was found in latest built
420 directory.
joychen3cb228e2013-06-12 12:13:13 -0700421 """
joychen921e1fb2013-06-28 11:12:20 -0700422 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700423 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700424 raise XBuddyException('No builds found for %s. Did you run build_image?' %
425 board)
426
joychen121fc9b2013-08-02 14:30:30 -0700427 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700428 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700429
joychenc3944cb2013-08-19 10:42:07 -0700430 @staticmethod
431 def _FindAny(local_dir):
432 """Returns the image_type for ANY given the local_dir."""
433 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
434 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
435 if os.path.exists(dev_image):
436 return 'dev'
437
438 if os.path.exists(test_image):
439 return 'test'
440
441 raise XBuddyException('No images found in %s' % local_dir)
442
443 @staticmethod
444 def _InterpretPath(path):
joychen121fc9b2013-08-02 14:30:30 -0700445 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700446
joychen121fc9b2013-08-02 14:30:30 -0700447 Args:
448 path: the path xBuddy Get was called with.
joychen3cb228e2013-06-12 12:13:13 -0700449
450 Return:
Chris Sosa75490802013-09-30 17:21:45 -0700451 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 12:13:13 -0700452
453 Raises:
454 XBuddyException: if the path can't be resolved into valid components
455 """
joychen121fc9b2013-08-02 14:30:30 -0700456 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700457
458 # Required parts of path parsing.
459 try:
460 # Determine if image is explicitly local or remote.
joychen121fc9b2013-08-02 14:30:30 -0700461 is_local = True
462 if path_list[0] in (REMOTE, LOCAL):
joychen18737f32013-08-16 17:18:12 -0700463 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700464
joychen121fc9b2013-08-02 14:30:30 -0700465 # Set board.
joychen7df67f72013-07-18 14:21:12 -0700466 board = path_list.pop(0)
joychen7df67f72013-07-18 14:21:12 -0700467
joychen121fc9b2013-08-02 14:30:30 -0700468 # Set defaults.
joychen3cb228e2013-06-12 12:13:13 -0700469 version = LATEST
joychen921e1fb2013-06-28 11:12:20 -0700470 image_type = GS_ALIASES[0]
joychen7df67f72013-07-18 14:21:12 -0700471 except IndexError:
472 msg = "Specify at least the board in your xBuddy call. Your path: %s"
473 raise XBuddyException(msg % os.path.join(path_list))
joychen3cb228e2013-06-12 12:13:13 -0700474
joychen121fc9b2013-08-02 14:30:30 -0700475 # Read as much of the xBuddy path as possible.
joychen7df67f72013-07-18 14:21:12 -0700476 try:
joychen121fc9b2013-08-02 14:30:30 -0700477 # Override default if terminal is a valid artifact alias or a version.
joychen7df67f72013-07-18 14:21:12 -0700478 terminal = path_list[-1]
479 if terminal in GS_ALIASES + LOCAL_ALIASES:
480 image_type = terminal
481 version = path_list[-2]
482 else:
483 version = terminal
484 except IndexError:
485 # This path doesn't have an alias or a version. That's fine.
486 _Log("Some parts of the path not specified. Using defaults.")
487
joychen346531c2013-07-24 16:55:56 -0700488 _Log("Get artifact '%s' in '%s/%s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700489 image_type, board, version, is_local)
490
491 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700492
joychen921e1fb2013-06-28 11:12:20 -0700493 def _SyncRegistryWithBuildImages(self):
joychen5260b9a2013-07-16 14:48:01 -0700494 """ Crawl images_dir for build_ids of images generated from build_image.
495
496 This will find images and symlink them in xBuddy's static dir so that
497 xBuddy's cache can serve them.
498 If xBuddy's _manage_builds option is on, then a timestamp will also be
499 generated, and xBuddy will clear them from the directory they are in, as
500 necessary.
501 """
joychen921e1fb2013-06-28 11:12:20 -0700502 build_ids = []
503 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700504 # Ensure we have directories to track all boards in build/images
505 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700506 board_dir = os.path.join(self.images_dir, b)
507 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700508 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700509
joychen121fc9b2013-08-02 14:30:30 -0700510 # Check currently registered images.
joychen921e1fb2013-06-28 11:12:20 -0700511 for f in os.listdir(self._timestamp_folder):
512 build_id = Timestamp.TimestampToBuild(f)
513 if build_id in build_ids:
514 build_ids.remove(build_id)
515
joychen121fc9b2013-08-02 14:30:30 -0700516 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700517 for build_id in build_ids:
518 link = os.path.join(self.static_dir, build_id)
519 target = os.path.join(self.images_dir, build_id)
520 XBuddy._Symlink(link, target)
521 if self._manage_builds:
522 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700523
524 def _ListBuildTimes(self):
joychen3cb228e2013-06-12 12:13:13 -0700525 """ Returns the currently cached builds and their last access timestamp.
526
527 Returns:
528 list of tuples that matches xBuddy build/version to timestamps in long
529 """
joychen121fc9b2013-08-02 14:30:30 -0700530 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700531 build_dict = {}
532
joychen7df67f72013-07-18 14:21:12 -0700533 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700534 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
535 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700536 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700537 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700538 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
539 return return_tup
540
Chris Sosa75490802013-09-30 17:21:45 -0700541 def _Download(self, gs_url, artifacts):
542 """Download the artifacts from the given gs_url.
543
544 Raises:
545 build_artifact.ArtifactDownloadError: If we failed to download the
546 artifact.
547 """
joychen3cb228e2013-06-12 12:13:13 -0700548 with XBuddy._staging_thread_count_lock:
549 XBuddy._staging_thread_count += 1
550 try:
Chris Sosa75490802013-09-30 17:21:45 -0700551 _Log("Downloading %s from %s", artifacts, gs_url)
552 downloader.Downloader(self.static_dir, gs_url).Download(artifacts, [])
joychen3cb228e2013-06-12 12:13:13 -0700553 finally:
554 with XBuddy._staging_thread_count_lock:
555 XBuddy._staging_thread_count -= 1
556
Chris Sosa75490802013-09-30 17:21:45 -0700557 def CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700558 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700559 if not self._manage_builds:
560 return
joychen921e1fb2013-06-28 11:12:20 -0700561 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700562 _Log('In cache now: %s', cached_builds)
563
joychen562699a2013-08-13 15:22:14 -0700564 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700565 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700566 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700567
568 time_file = os.path.join(self._timestamp_folder,
569 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700570 os.unlink(time_file)
571 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700572 try:
joychen121fc9b2013-08-02 14:30:30 -0700573 # Handle symlinks, in the case of links to local builds if enabled.
574 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700575 target = os.readlink(clear_dir)
576 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700577
578 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700579 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700580 shutil.rmtree(target)
581 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700582 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700583 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700584
joychen121fc9b2013-08-02 14:30:30 -0700585 except Exception as err:
586 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700587
Chris Sosa75490802013-09-30 17:21:45 -0700588 def _GetFromGS(self, build_id, image_type):
589 """Check if the artifact is available locally. Download from GS if not.
590
591 Raises:
592 build_artifact.ArtifactDownloadError: If we failed to download the
593 artifact.
594 """
joychenf8f07e22013-07-12 17:45:51 -0700595 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
joychen921e1fb2013-06-28 11:12:20 -0700596 build_id)
597
joychen121fc9b2013-08-02 14:30:30 -0700598 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700599 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700600 file_loc = os.path.join(self.static_dir, build_id, file_name)
601 cached = os.path.exists(file_loc)
602
joychen921e1fb2013-06-28 11:12:20 -0700603 if not cached:
Chris Sosa75490802013-09-30 17:21:45 -0700604 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
605 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 11:12:20 -0700606 else:
607 _Log('Image already cached.')
608
Chris Sosa75490802013-09-30 17:21:45 -0700609 def _GetArtifact(self, path_list, board=None, lookup_only=False):
joychen346531c2013-07-24 16:55:56 -0700610 """Interpret an xBuddy path and return directory/file_name to resource.
611
Chris Sosa75490802013-09-30 17:21:45 -0700612 Note board can be passed that in but by default if self._board is set,
613 that is used rather than board.
614
joychen346531c2013-07-24 16:55:56 -0700615 Returns:
joychenc3944cb2013-08-19 10:42:07 -0700616 build_id to the directory
joychen346531c2013-07-24 16:55:56 -0700617 file_name of the artifact
joychen346531c2013-07-24 16:55:56 -0700618
619 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700620 XBuddyException: if the path could not be translated
Chris Sosa75490802013-09-30 17:21:45 -0700621 build_artifact.ArtifactDownloadError: if we failed to download the
622 artifact.
joychen346531c2013-07-24 16:55:56 -0700623 """
joychen121fc9b2013-08-02 14:30:30 -0700624 path = '/'.join(path_list)
joychenb0dfe552013-07-30 10:02:06 -0700625 # Rewrite the path if there is an appropriate default.
Chris Sosa75490802013-09-30 17:21:45 -0700626 path = self._LookupAlias(path, self._board if self._board else board)
joychenb0dfe552013-07-30 10:02:06 -0700627
joychen121fc9b2013-08-02 14:30:30 -0700628 # Parse the path.
joychen7df67f72013-07-18 14:21:12 -0700629 image_type, board, version, is_local = self._InterpretPath(path)
joychen921e1fb2013-06-28 11:12:20 -0700630
joychen7df67f72013-07-18 14:21:12 -0700631 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700632 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700633 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700634 # Get the latest local image for the given board.
635 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700636
joychenc3944cb2013-08-19 10:42:07 -0700637 build_id = os.path.join(board, version)
638 artifact_dir = os.path.join(self.static_dir, build_id)
639 if image_type == ANY:
640 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700641
joychenc3944cb2013-08-19 10:42:07 -0700642 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
643 artifact_path = os.path.join(artifact_dir, file_name)
644 if not os.path.exists(artifact_path):
645 raise XBuddyException('Local %s artifact not in static_dir at %s' %
646 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700647
joychen921e1fb2013-06-28 11:12:20 -0700648 else:
joychen121fc9b2013-08-02 14:30:30 -0700649 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700650 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700651 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700652 (image_type, GS_ALIASES))
Chris Sosaea734d92013-10-11 11:28:58 -0700653 build_id = self._ResolveVersionToBuildId(board, version)
Chris Sosa75490802013-09-30 17:21:45 -0700654 _Log('Resolved version %s to %s.', version, build_id)
655 file_name = GS_ALIAS_TO_FILENAME[image_type]
656 if not lookup_only:
657 self._GetFromGS(build_id, image_type)
joychenf8f07e22013-07-12 17:45:51 -0700658
joychenc3944cb2013-08-19 10:42:07 -0700659 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700660
661 ############################ BEGIN PUBLIC METHODS
662
663 def List(self):
664 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700665 self._SyncRegistryWithBuildImages()
666 builds = self._ListBuildTimes()
667 return_string = ''
668 for build, timestamp in builds:
669 return_string += '<b>' + build + '</b> '
670 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
671 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700672
673 def Capacity(self):
674 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700675 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700676
Chris Sosa75490802013-09-30 17:21:45 -0700677 def Translate(self, path_list, board=None):
joychen346531c2013-07-24 16:55:56 -0700678 """Translates an xBuddy path to a real path to artifact if it exists.
679
joychen121fc9b2013-08-02 14:30:30 -0700680 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700681
joychen7c2054a2013-07-25 11:14:07 -0700682 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700683 build_id: Path to the image or update directory on the devserver.
684 e.g. 'x86-generic/R26-4000.0.0'
685 The returned path is always the path to the directory within
686 static_dir, so it is always the build_id of the image.
687 file_name: The file name of the artifact. Can take any of the file
688 values in devserver_constants.
689 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
690 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700691
joychen121fc9b2013-08-02 14:30:30 -0700692 Raises:
693 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700694 """
695 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700696 build_id, file_name = self._GetArtifact(path_list, board=board,
697 lookup_only=True)
joychen346531c2013-07-24 16:55:56 -0700698
joychen121fc9b2013-08-02 14:30:30 -0700699 _Log('Returning path to payload: %s/%s', build_id, file_name)
700 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700701
Chris Sosa75490802013-09-30 17:21:45 -0700702 def StageTestAritfactsForUpdate(self, path_list):
703 """Stages test artifacts for update and returns build_id.
704
705 Raises:
706 XBuddyException: if the path could not be translated
707 build_artifact.ArtifactDownloadError: if we failed to download the test
708 artifacts.
709 """
710 build_id, file_name = self.Translate(path_list)
711 if file_name == devserver_constants.TEST_IMAGE_FILE:
712 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
713 build_id)
714 artifacts = [FULL, STATEFUL]
715 self._Download(gs_url, artifacts)
716 return build_id
717
joychen562699a2013-08-13 15:22:14 -0700718 def Get(self, path_list):
joychen921e1fb2013-06-28 11:12:20 -0700719 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700720
721 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700722
joychen3cb228e2013-06-12 12:13:13 -0700723 Args:
joychen921e1fb2013-06-28 11:12:20 -0700724 path_list: [board, version, alias] as split from the xbuddy call url
joychen3cb228e2013-06-12 12:13:13 -0700725
726 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700727 build_id: Path to the image or update directory on the devserver.
728 e.g. 'x86-generic/R26-4000.0.0'
729 The returned path is always the path to the directory within
730 static_dir, so it is always the build_id of the image.
731 file_name: The file name of the artifact. Can take any of the file
732 values in devserver_constants.
733 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
734 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700735
736 Raises:
Chris Sosa75490802013-09-30 17:21:45 -0700737 XBuddyException: if the path could not be translated
738 build_artifact.ArtifactDownloadError: if we failed to download the
739 artifact.
joychen3cb228e2013-06-12 12:13:13 -0700740 """
joychen7df67f72013-07-18 14:21:12 -0700741 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700742 build_id, file_name = self._GetArtifact(path_list)
joychen921e1fb2013-06-28 11:12:20 -0700743 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700744 #TODO (joyc): run in sep thread
Chris Sosa75490802013-09-30 17:21:45 -0700745 self.CleanCache()
joychen3cb228e2013-06-12 12:13:13 -0700746
joychen121fc9b2013-08-02 14:30:30 -0700747 _Log('Returning path to payload: %s/%s', build_id, file_name)
748 return build_id, file_name