blob: 27b1debc7e466ee686c29c507e8ad4f723ae8e7f [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,
Chris Sosa7cd23202013-10-15 17:22:57 -070062 STATEFUL,
joychenc3944cb2013-08-19 10:42:07 -070063 ANY,
joychen921e1fb2013-06-28 11:12:20 -070064]
65
66LOCAL_FILE_NAMES = [
67 devserver_constants.TEST_IMAGE_FILE,
joychen921e1fb2013-06-28 11:12:20 -070068 devserver_constants.IMAGE_FILE,
Chris Sosa75490802013-09-30 17:21:45 -070069 devserver_constants.BASE_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070070 devserver_constants.UPDATE_FILE,
Chris Sosa7cd23202013-10-15 17:22:57 -070071 devserver_constants.STATEFUL_FILE,
Chris Sosa75490802013-09-30 17:21:45 -070072 None, # For ANY.
joychen921e1fb2013-06-28 11:12:20 -070073]
74
75LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
76
77# Google Storage constants
78GS_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070079 TEST,
Chris Sosa75490802013-09-30 17:21:45 -070080 DEV,
joychen25d25972013-07-30 14:54:16 -070081 BASE,
82 RECOVERY,
83 FULL,
84 STATEFUL,
85 AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -070086]
87
joychen921e1fb2013-06-28 11:12:20 -070088GS_FILE_NAMES = [
89 devserver_constants.TEST_IMAGE_FILE,
90 devserver_constants.BASE_IMAGE_FILE,
91 devserver_constants.RECOVERY_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070092 devserver_constants.UPDATE_FILE,
joychen121fc9b2013-08-02 14:30:30 -070093 devserver_constants.STATEFUL_FILE,
joychen3cb228e2013-06-12 12:13:13 -070094 devserver_constants.AUTOTEST_DIR,
95]
96
97ARTIFACTS = [
98 artifact_info.TEST_IMAGE,
99 artifact_info.BASE_IMAGE,
100 artifact_info.RECOVERY_IMAGE,
101 artifact_info.FULL_PAYLOAD,
102 artifact_info.STATEFUL_PAYLOAD,
103 artifact_info.AUTOTEST,
104]
105
joychen921e1fb2013-06-28 11:12:20 -0700106GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
107GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 12:13:13 -0700108
joychen921e1fb2013-06-28 11:12:20 -0700109LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 12:13:13 -0700110
Chris Sosaea734d92013-10-11 11:28:58 -0700111RELEASE = "-release"
joychen3cb228e2013-06-12 12:13:13 -0700112
joychen3cb228e2013-06-12 12:13:13 -0700113
114class XBuddyException(Exception):
115 """Exception classes used by this module."""
116 pass
117
118
119# no __init__ method
120#pylint: disable=W0232
121class Timestamp():
122 """Class to translate build path strings and timestamp filenames."""
123
124 _TIMESTAMP_DELIMITER = 'SLASH'
125 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
126
127 @staticmethod
128 def TimestampToBuild(timestamp_filename):
129 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
130
131 @staticmethod
132 def BuildToTimestamp(build_path):
133 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 11:12:20 -0700134
135 @staticmethod
136 def UpdateTimestamp(timestamp_dir, build_id):
137 """Update timestamp file of build with build_id."""
138 common_util.MkDirP(timestamp_dir)
joychen562699a2013-08-13 15:22:14 -0700139 _Log("Updating timestamp for %s", build_id)
joychen921e1fb2013-06-28 11:12:20 -0700140 time_file = os.path.join(timestamp_dir,
141 Timestamp.BuildToTimestamp(build_id))
142 with file(time_file, 'a'):
143 os.utime(time_file, None)
joychen3cb228e2013-06-12 12:13:13 -0700144#pylint: enable=W0232
145
146
joychen921e1fb2013-06-28 11:12:20 -0700147class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 12:13:13 -0700148 """Class that manages image retrieval and caching by the devserver.
149
150 Image retrieval by xBuddy path:
151 XBuddy accesses images and artifacts that it stores using an xBuddy
152 path of the form: board/version/alias
153 The primary xbuddy.Get call retrieves the correct artifact or url to where
154 the artifacts can be found.
155
156 Image caching:
157 Images and other artifacts are stored identically to how they would have
158 been if devserver's stage rpc was called and the xBuddy cache replaces
159 build versions on a LRU basis. Timestamps are maintained by last accessed
160 times of representative files in the a directory in the static serve
161 directory (XBUDDY_TIMESTAMP_DIR).
162
163 Private class members:
joychen121fc9b2013-08-02 14:30:30 -0700164 _true_values: used for interpreting boolean values
165 _staging_thread_count: track download requests
166 _timestamp_folder: directory with empty files standing in as timestamps
joychen921e1fb2013-06-28 11:12:20 -0700167 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 12:13:13 -0700168 """
169 _true_values = ['true', 't', 'yes', 'y']
170
171 # Number of threads that are staging images.
172 _staging_thread_count = 0
173 # Lock used to lock increasing/decreasing count.
174 _staging_thread_count_lock = threading.Lock()
175
Chris Sosa7cd23202013-10-15 17:22:57 -0700176 def __init__(self, manage_builds=False, board=None, images_dir=None,
177 **kwargs):
joychen921e1fb2013-06-28 11:12:20 -0700178 super(XBuddy, self).__init__(**kwargs)
joychenb0dfe552013-07-30 10:02:06 -0700179
joychen562699a2013-08-13 15:22:14 -0700180 self.config = self._ReadConfig()
181 self._manage_builds = manage_builds or self._ManageBuilds()
Chris Sosa75490802013-09-30 17:21:45 -0700182 self._board = board
joychen921e1fb2013-06-28 11:12:20 -0700183 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 12:13:13 -0700184 Timestamp.XBUDDY_TIMESTAMP_DIR)
Chris Sosa7cd23202013-10-15 17:22:57 -0700185 if images_dir:
186 self.images_dir = images_dir
187 else:
188 self.images_dir = os.path.join(self.GetSourceRoot(), 'src/build/images')
189
joychen7df67f72013-07-18 14:21:12 -0700190 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 12:13:13 -0700191
192 @classmethod
193 def ParseBoolean(cls, boolean_string):
194 """Evaluate a string to a boolean value"""
195 if boolean_string:
196 return boolean_string.lower() in cls._true_values
197 else:
198 return False
199
joychen562699a2013-08-13 15:22:14 -0700200 def _ReadConfig(self):
201 """Read xbuddy config from ini files.
202
203 Reads the base config from xbuddy_config.ini, and then merges in the
204 shadow config from shadow_xbuddy_config.ini
205
206 Returns:
207 The merged configuration.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800208
joychen562699a2013-08-13 15:22:14 -0700209 Raises:
210 XBuddyException if the config file is missing.
211 """
212 xbuddy_config = ConfigParser.ConfigParser()
213 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
214 if os.path.exists(config_file):
215 xbuddy_config.read(config_file)
216 else:
217 raise XBuddyException('%s not found' % (CONFIG_FILE))
218
219 # Read the shadow file if there is one.
Chris Sosac2abc722013-08-26 17:11:22 -0700220 if os.path.isdir(CHROOT_SHADOW_DIR):
221 shadow_config_file = os.path.join(CHROOT_SHADOW_DIR, SHADOW_CONFIG_FILE)
222 else:
223 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
224
225 _Log('Using shadow config file stored at %s', shadow_config_file)
joychen562699a2013-08-13 15:22:14 -0700226 if os.path.exists(shadow_config_file):
227 shadow_xbuddy_config = ConfigParser.ConfigParser()
228 shadow_xbuddy_config.read(shadow_config_file)
229
230 # Merge shadow config in.
231 sections = shadow_xbuddy_config.sections()
232 for s in sections:
233 if not xbuddy_config.has_section(s):
234 xbuddy_config.add_section(s)
235 options = shadow_xbuddy_config.options(s)
236 for o in options:
237 val = shadow_xbuddy_config.get(s, o)
238 xbuddy_config.set(s, o, val)
239
240 return xbuddy_config
241
242 def _ManageBuilds(self):
243 """Checks if xBuddy is managing local builds using the current config."""
244 try:
245 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
246 except ConfigParser.Error:
247 return False
248
249 def _Capacity(self):
250 """Gets the xbuddy capacity from the current config."""
251 try:
252 return int(self.config.get(GENERAL, 'capacity'))
253 except ConfigParser.Error:
254 return 5
255
256 def _LookupAlias(self, alias, board):
257 """Given the full xbuddy config, look up an alias for path rewrite.
258
259 Args:
260 alias: The xbuddy path that could be one of the aliases in the
261 rewrite table.
262 board: The board to fill in with when paths are rewritten. Can be from
263 the update request xml or the default board from devserver.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800264
joychen562699a2013-08-13 15:22:14 -0700265 Returns:
266 If a rewrite is found, a string with the current board substituted in.
267 If no rewrite is found, just return the original string.
268 """
269 if alias == '':
270 alias = 'update_default'
271
272 try:
273 val = self.config.get(PATH_REWRITES, alias)
274 except ConfigParser.Error:
275 # No alias lookup found. Return original path.
276 return alias
277
278 if not val.strip():
279 # The found value was an empty string.
280 return alias
281 else:
282 # Fill in the board.
joychenc3944cb2013-08-19 10:42:07 -0700283 rewrite = val.replace("BOARD", "%(board)s") % {
joychen562699a2013-08-13 15:22:14 -0700284 'board': board}
285 _Log("Path was rewritten to %s", rewrite)
286 return rewrite
287
joychenf8f07e22013-07-12 17:45:51 -0700288 def _LookupOfficial(self, board, suffix=RELEASE):
289 """Check LATEST-master for the version number of interest."""
290 _Log("Checking gs for latest %s-%s image", board, suffix)
291 latest_addr = devserver_constants.GS_LATEST_MASTER % {'board':board,
292 'suffix':suffix}
293 cmd = 'gsutil cat %s' % latest_addr
294 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700295 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700296 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700297
joychenf8f07e22013-07-12 17:45:51 -0700298 return devserver_constants.IMAGE_DIR % {'board':board,
299 'suffix':suffix,
300 'version':version}
joychenf8f07e22013-07-12 17:45:51 -0700301 def _LookupChannel(self, board, channel='stable'):
302 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700303 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700304 _Log("Checking channel '%s' for latest '%s' image", channel, board)
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800305 # Due to historical reasons, gs://chromeos-releases uses
306 # daisy-spring as opposed to the board name daisy_spring. Convert
307 # the board name for the lookup.
308 channel_dir = devserver_constants.GS_CHANNEL_DIR % {
309 'channel':channel,
310 'board':re.sub('_', '-', board)}
joychen562699a2013-08-13 15:22:14 -0700311 latest_version = gsutil_util.GetLatestVersionFromGSDir(
312 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700313
joychen121fc9b2013-08-02 14:30:30 -0700314 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700315 image_url = devserver_constants.IMAGE_DIR % {
316 'board':board,
317 'suffix':RELEASE,
318 'version':'R*' + latest_version}
joychenf8f07e22013-07-12 17:45:51 -0700319 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
320
321 # There should only be one match on cros-image-archive.
322 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
323
324 return devserver_constants.IMAGE_DIR % {'board':board,
325 'suffix':RELEASE,
326 'version':full_version}
327
328 def _LookupVersion(self, board, version):
329 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700330 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700331 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
joychenf8f07e22013-07-12 17:45:51 -0700332 image_url = devserver_constants.IMAGE_DIR % {'board':board,
333 'suffix':RELEASE,
334 'version':version + '*'}
335 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
336
joychen121fc9b2013-08-02 14:30:30 -0700337 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700338 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
339 return devserver_constants.IMAGE_DIR % {'board':board,
340 'suffix':RELEASE,
341 'version':full_version}
342
Chris Sosaea734d92013-10-11 11:28:58 -0700343 def _RemoteBuildId(self, board, version):
344 """Returns the remote build_id for the given board and version.
345
346 Raises:
347 XBuddyException: If we failed to resolve the version to a valid build_id.
348 """
349 build_id_as_is = devserver_constants.IMAGE_DIR % {'board':board,
350 'suffix':'',
351 'version':version}
352 build_id_release = devserver_constants.IMAGE_DIR % {'board':board,
353 'suffix':RELEASE,
354 'version':version}
355 # Return the first path that exists. We assume that what the user typed
356 # is better than with a default suffix added i.e. x86-generic/blah is
357 # more valuable than x86-generic-release/blah.
358 for build_id in build_id_as_is, build_id_release:
359 cmd = 'gsutil ls %s/%s' % (devserver_constants.GS_IMAGE_DIR, build_id)
360 try:
361 version = gsutil_util.GSUtilRun(cmd, None)
362 return build_id
363 except gsutil_util.GSUtilError:
364 continue
365 else:
366 raise XBuddyException('Could not find remote build_id for %s %s' % (
367 board, version))
368
369 def _ResolveVersionToBuildId(self, board, version):
joychen121fc9b2013-08-02 14:30:30 -0700370 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700371
372 Args:
373 board: as specified in the original call. (i.e. x86-generic, parrot)
374 version: as entered in the original call. can be
375 {TBD, 0. some custom alias as defined in a config file}
376 1. latest
377 2. latest-{channel}
378 3. latest-official-{board suffix}
379 4. version prefix (i.e. RX-Y.X, RX-Y, RX)
joychen3cb228e2013-06-12 12:13:13 -0700380
381 Returns:
Chris Sosaea734d92013-10-11 11:28:58 -0700382 Location where the image dir is actually found on GS (build_id)
joychen3cb228e2013-06-12 12:13:13 -0700383
Chris Sosaea734d92013-10-11 11:28:58 -0700384 Raises:
385 XBuddyException: If we failed to resolve the version to a valid url.
joychen3cb228e2013-06-12 12:13:13 -0700386 """
joychenf8f07e22013-07-12 17:45:51 -0700387 # Only the last segment of the alias is variable relative to the rest.
388 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700389
joychenf8f07e22013-07-12 17:45:51 -0700390 if re.match(devserver_constants.VERSION_RE, version):
Chris Sosaea734d92013-10-11 11:28:58 -0700391 return self._RemoteBuildId(board, version)
joychenf8f07e22013-07-12 17:45:51 -0700392 elif version == LATEST_OFFICIAL:
393 # latest-official --> LATEST build in board-release
394 return self._LookupOfficial(board)
395 elif version_tuple[0] == LATEST_OFFICIAL:
396 # latest-official-{suffix} --> LATEST build in board-{suffix}
397 return self._LookupOfficial(board, version_tuple[1])
398 elif version == LATEST:
399 # latest --> latest build on stable channel
400 return self._LookupChannel(board)
401 elif version_tuple[0] == LATEST:
402 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
403 # latest-R* --> most recent qualifying build
404 return self._LookupVersion(board, version_tuple[1])
405 else:
406 # latest-{channel} --> latest build within that channel
407 return self._LookupChannel(board, version_tuple[1])
joychen3cb228e2013-06-12 12:13:13 -0700408 else:
409 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700410 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700411
joychen5260b9a2013-07-16 14:48:01 -0700412 @staticmethod
413 def _Symlink(link, target):
414 """Symlinks link to target, and removes whatever link was there before."""
415 _Log("Linking to %s from %s", link, target)
416 if os.path.lexists(link):
417 os.unlink(link)
418 os.symlink(target, link)
419
joychen121fc9b2013-08-02 14:30:30 -0700420 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700421 """Get the version of the latest image built for board by build_image
422
423 Updates the symlink reference within the xBuddy static dir to point to
424 the real image dir in the local /build/images directory.
425
426 Args:
joychenc3944cb2013-08-19 10:42:07 -0700427 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700428
429 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700430 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700431
432 Raises:
433 XBuddyException if neither test nor dev image was found in latest built
434 directory.
joychen3cb228e2013-06-12 12:13:13 -0700435 """
joychen921e1fb2013-06-28 11:12:20 -0700436 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700437 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700438 raise XBuddyException('No builds found for %s. Did you run build_image?' %
439 board)
440
joychen121fc9b2013-08-02 14:30:30 -0700441 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700442 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700443
joychenc3944cb2013-08-19 10:42:07 -0700444 @staticmethod
445 def _FindAny(local_dir):
446 """Returns the image_type for ANY given the local_dir."""
447 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
448 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
449 if os.path.exists(dev_image):
450 return 'dev'
451
452 if os.path.exists(test_image):
453 return 'test'
454
455 raise XBuddyException('No images found in %s' % local_dir)
456
457 @staticmethod
458 def _InterpretPath(path):
joychen121fc9b2013-08-02 14:30:30 -0700459 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700460
joychen121fc9b2013-08-02 14:30:30 -0700461 Args:
462 path: the path xBuddy Get was called with.
joychen3cb228e2013-06-12 12:13:13 -0700463
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800464 Returns:
Chris Sosa75490802013-09-30 17:21:45 -0700465 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 12:13:13 -0700466
467 Raises:
468 XBuddyException: if the path can't be resolved into valid components
469 """
joychen121fc9b2013-08-02 14:30:30 -0700470 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700471
472 # Required parts of path parsing.
473 try:
474 # Determine if image is explicitly local or remote.
joychen121fc9b2013-08-02 14:30:30 -0700475 is_local = True
476 if path_list[0] in (REMOTE, LOCAL):
joychen18737f32013-08-16 17:18:12 -0700477 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700478
joychen121fc9b2013-08-02 14:30:30 -0700479 # Set board.
joychen7df67f72013-07-18 14:21:12 -0700480 board = path_list.pop(0)
joychen7df67f72013-07-18 14:21:12 -0700481
joychen121fc9b2013-08-02 14:30:30 -0700482 # Set defaults.
joychen3cb228e2013-06-12 12:13:13 -0700483 version = LATEST
joychen921e1fb2013-06-28 11:12:20 -0700484 image_type = GS_ALIASES[0]
joychen7df67f72013-07-18 14:21:12 -0700485 except IndexError:
486 msg = "Specify at least the board in your xBuddy call. Your path: %s"
487 raise XBuddyException(msg % os.path.join(path_list))
joychen3cb228e2013-06-12 12:13:13 -0700488
joychen121fc9b2013-08-02 14:30:30 -0700489 # Read as much of the xBuddy path as possible.
joychen7df67f72013-07-18 14:21:12 -0700490 try:
joychen121fc9b2013-08-02 14:30:30 -0700491 # Override default if terminal is a valid artifact alias or a version.
joychen7df67f72013-07-18 14:21:12 -0700492 terminal = path_list[-1]
493 if terminal in GS_ALIASES + LOCAL_ALIASES:
494 image_type = terminal
495 version = path_list[-2]
496 else:
497 version = terminal
498 except IndexError:
499 # This path doesn't have an alias or a version. That's fine.
500 _Log("Some parts of the path not specified. Using defaults.")
501
joychen346531c2013-07-24 16:55:56 -0700502 _Log("Get artifact '%s' in '%s/%s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700503 image_type, board, version, is_local)
504
505 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700506
joychen921e1fb2013-06-28 11:12:20 -0700507 def _SyncRegistryWithBuildImages(self):
joychen5260b9a2013-07-16 14:48:01 -0700508 """ Crawl images_dir for build_ids of images generated from build_image.
509
510 This will find images and symlink them in xBuddy's static dir so that
511 xBuddy's cache can serve them.
512 If xBuddy's _manage_builds option is on, then a timestamp will also be
513 generated, and xBuddy will clear them from the directory they are in, as
514 necessary.
515 """
joychen921e1fb2013-06-28 11:12:20 -0700516 build_ids = []
517 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700518 # Ensure we have directories to track all boards in build/images
519 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700520 board_dir = os.path.join(self.images_dir, b)
521 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700522 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700523
joychen121fc9b2013-08-02 14:30:30 -0700524 # Check currently registered images.
joychen921e1fb2013-06-28 11:12:20 -0700525 for f in os.listdir(self._timestamp_folder):
526 build_id = Timestamp.TimestampToBuild(f)
527 if build_id in build_ids:
528 build_ids.remove(build_id)
529
joychen121fc9b2013-08-02 14:30:30 -0700530 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700531 for build_id in build_ids:
532 link = os.path.join(self.static_dir, build_id)
533 target = os.path.join(self.images_dir, build_id)
534 XBuddy._Symlink(link, target)
535 if self._manage_builds:
536 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700537
538 def _ListBuildTimes(self):
joychen3cb228e2013-06-12 12:13:13 -0700539 """ Returns the currently cached builds and their last access timestamp.
540
541 Returns:
542 list of tuples that matches xBuddy build/version to timestamps in long
543 """
joychen121fc9b2013-08-02 14:30:30 -0700544 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700545 build_dict = {}
546
joychen7df67f72013-07-18 14:21:12 -0700547 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700548 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
549 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700550 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700551 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700552 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
553 return return_tup
554
Chris Sosa75490802013-09-30 17:21:45 -0700555 def _Download(self, gs_url, artifacts):
556 """Download the artifacts from the given gs_url.
557
558 Raises:
559 build_artifact.ArtifactDownloadError: If we failed to download the
560 artifact.
561 """
joychen3cb228e2013-06-12 12:13:13 -0700562 with XBuddy._staging_thread_count_lock:
563 XBuddy._staging_thread_count += 1
564 try:
Chris Sosa75490802013-09-30 17:21:45 -0700565 _Log("Downloading %s from %s", artifacts, gs_url)
566 downloader.Downloader(self.static_dir, gs_url).Download(artifacts, [])
joychen3cb228e2013-06-12 12:13:13 -0700567 finally:
568 with XBuddy._staging_thread_count_lock:
569 XBuddy._staging_thread_count -= 1
570
Chris Sosa75490802013-09-30 17:21:45 -0700571 def CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700572 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700573 if not self._manage_builds:
574 return
joychen921e1fb2013-06-28 11:12:20 -0700575 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700576 _Log('In cache now: %s', cached_builds)
577
joychen562699a2013-08-13 15:22:14 -0700578 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700579 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700580 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700581
582 time_file = os.path.join(self._timestamp_folder,
583 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700584 os.unlink(time_file)
585 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700586 try:
joychen121fc9b2013-08-02 14:30:30 -0700587 # Handle symlinks, in the case of links to local builds if enabled.
588 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700589 target = os.readlink(clear_dir)
590 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700591
592 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700593 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700594 shutil.rmtree(target)
595 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700596 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700597 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700598
joychen121fc9b2013-08-02 14:30:30 -0700599 except Exception as err:
600 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700601
Chris Sosa75490802013-09-30 17:21:45 -0700602 def _GetFromGS(self, build_id, image_type):
603 """Check if the artifact is available locally. Download from GS if not.
604
605 Raises:
606 build_artifact.ArtifactDownloadError: If we failed to download the
607 artifact.
608 """
joychenf8f07e22013-07-12 17:45:51 -0700609 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
joychen921e1fb2013-06-28 11:12:20 -0700610 build_id)
611
joychen121fc9b2013-08-02 14:30:30 -0700612 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700613 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700614 file_loc = os.path.join(self.static_dir, build_id, file_name)
615 cached = os.path.exists(file_loc)
616
joychen921e1fb2013-06-28 11:12:20 -0700617 if not cached:
Chris Sosa75490802013-09-30 17:21:45 -0700618 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
619 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 11:12:20 -0700620 else:
621 _Log('Image already cached.')
622
Chris Sosa75490802013-09-30 17:21:45 -0700623 def _GetArtifact(self, path_list, board=None, lookup_only=False):
joychen346531c2013-07-24 16:55:56 -0700624 """Interpret an xBuddy path and return directory/file_name to resource.
625
Chris Sosa75490802013-09-30 17:21:45 -0700626 Note board can be passed that in but by default if self._board is set,
627 that is used rather than board.
628
joychen346531c2013-07-24 16:55:56 -0700629 Returns:
joychenc3944cb2013-08-19 10:42:07 -0700630 build_id to the directory
joychen346531c2013-07-24 16:55:56 -0700631 file_name of the artifact
joychen346531c2013-07-24 16:55:56 -0700632
633 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700634 XBuddyException: if the path could not be translated
Chris Sosa75490802013-09-30 17:21:45 -0700635 build_artifact.ArtifactDownloadError: if we failed to download the
636 artifact.
joychen346531c2013-07-24 16:55:56 -0700637 """
joychen121fc9b2013-08-02 14:30:30 -0700638 path = '/'.join(path_list)
joychenb0dfe552013-07-30 10:02:06 -0700639 # Rewrite the path if there is an appropriate default.
Chris Sosa75490802013-09-30 17:21:45 -0700640 path = self._LookupAlias(path, self._board if self._board else board)
joychenb0dfe552013-07-30 10:02:06 -0700641
joychen121fc9b2013-08-02 14:30:30 -0700642 # Parse the path.
joychen7df67f72013-07-18 14:21:12 -0700643 image_type, board, version, is_local = self._InterpretPath(path)
joychen921e1fb2013-06-28 11:12:20 -0700644
joychen7df67f72013-07-18 14:21:12 -0700645 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700646 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700647 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700648 # Get the latest local image for the given board.
649 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700650
joychenc3944cb2013-08-19 10:42:07 -0700651 build_id = os.path.join(board, version)
652 artifact_dir = os.path.join(self.static_dir, build_id)
653 if image_type == ANY:
654 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700655
joychenc3944cb2013-08-19 10:42:07 -0700656 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
657 artifact_path = os.path.join(artifact_dir, file_name)
658 if not os.path.exists(artifact_path):
659 raise XBuddyException('Local %s artifact not in static_dir at %s' %
660 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700661
joychen921e1fb2013-06-28 11:12:20 -0700662 else:
joychen121fc9b2013-08-02 14:30:30 -0700663 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700664 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700665 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700666 (image_type, GS_ALIASES))
Chris Sosaea734d92013-10-11 11:28:58 -0700667 build_id = self._ResolveVersionToBuildId(board, version)
Chris Sosa75490802013-09-30 17:21:45 -0700668 _Log('Resolved version %s to %s.', version, build_id)
669 file_name = GS_ALIAS_TO_FILENAME[image_type]
670 if not lookup_only:
671 self._GetFromGS(build_id, image_type)
joychenf8f07e22013-07-12 17:45:51 -0700672
joychenc3944cb2013-08-19 10:42:07 -0700673 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700674
675 ############################ BEGIN PUBLIC METHODS
676
677 def List(self):
678 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700679 self._SyncRegistryWithBuildImages()
680 builds = self._ListBuildTimes()
681 return_string = ''
682 for build, timestamp in builds:
683 return_string += '<b>' + build + '</b> '
684 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
685 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700686
687 def Capacity(self):
688 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700689 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700690
Chris Sosa75490802013-09-30 17:21:45 -0700691 def Translate(self, path_list, board=None):
joychen346531c2013-07-24 16:55:56 -0700692 """Translates an xBuddy path to a real path to artifact if it exists.
693
joychen121fc9b2013-08-02 14:30:30 -0700694 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700695
joychen7c2054a2013-07-25 11:14:07 -0700696 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700697 build_id: Path to the image or update directory on the devserver.
698 e.g. 'x86-generic/R26-4000.0.0'
699 The returned path is always the path to the directory within
700 static_dir, so it is always the build_id of the image.
701 file_name: The file name of the artifact. Can take any of the file
702 values in devserver_constants.
703 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
704 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700705
joychen121fc9b2013-08-02 14:30:30 -0700706 Raises:
707 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700708 """
709 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700710 build_id, file_name = self._GetArtifact(path_list, board=board,
711 lookup_only=True)
joychen346531c2013-07-24 16:55:56 -0700712
joychen121fc9b2013-08-02 14:30:30 -0700713 _Log('Returning path to payload: %s/%s', build_id, file_name)
714 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700715
Chris Sosa75490802013-09-30 17:21:45 -0700716 def StageTestAritfactsForUpdate(self, path_list):
717 """Stages test artifacts for update and returns build_id.
718
719 Raises:
720 XBuddyException: if the path could not be translated
721 build_artifact.ArtifactDownloadError: if we failed to download the test
722 artifacts.
723 """
724 build_id, file_name = self.Translate(path_list)
725 if file_name == devserver_constants.TEST_IMAGE_FILE:
726 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
727 build_id)
728 artifacts = [FULL, STATEFUL]
729 self._Download(gs_url, artifacts)
730 return build_id
731
joychen562699a2013-08-13 15:22:14 -0700732 def Get(self, path_list):
joychen921e1fb2013-06-28 11:12:20 -0700733 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700734
735 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700736
joychen3cb228e2013-06-12 12:13:13 -0700737 Args:
joychen921e1fb2013-06-28 11:12:20 -0700738 path_list: [board, version, alias] as split from the xbuddy call url
joychen3cb228e2013-06-12 12:13:13 -0700739
740 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700741 build_id: Path to the image or update directory on the devserver.
742 e.g. 'x86-generic/R26-4000.0.0'
743 The returned path is always the path to the directory within
744 static_dir, so it is always the build_id of the image.
745 file_name: The file name of the artifact. Can take any of the file
746 values in devserver_constants.
747 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
748 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700749
750 Raises:
Chris Sosa75490802013-09-30 17:21:45 -0700751 XBuddyException: if the path could not be translated
752 build_artifact.ArtifactDownloadError: if we failed to download the
753 artifact.
joychen3cb228e2013-06-12 12:13:13 -0700754 """
joychen7df67f72013-07-18 14:21:12 -0700755 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700756 build_id, file_name = self._GetArtifact(path_list)
joychen921e1fb2013-06-28 11:12:20 -0700757 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700758 #TODO (joyc): run in sep thread
Chris Sosa75490802013-09-30 17:21:45 -0700759 self.CleanCache()
joychen3cb228e2013-06-12 12:13:13 -0700760
joychen121fc9b2013-08-02 14:30:30 -0700761 _Log('Returning path to payload: %s/%s', build_id, file_name)
762 return build_id, file_name