blob: e723fef625ef83132760f3139600e9718074d798 [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.
208 Raises:
209 XBuddyException if the config file is missing.
210 """
211 xbuddy_config = ConfigParser.ConfigParser()
212 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
213 if os.path.exists(config_file):
214 xbuddy_config.read(config_file)
215 else:
216 raise XBuddyException('%s not found' % (CONFIG_FILE))
217
218 # Read the shadow file if there is one.
Chris Sosac2abc722013-08-26 17:11:22 -0700219 if os.path.isdir(CHROOT_SHADOW_DIR):
220 shadow_config_file = os.path.join(CHROOT_SHADOW_DIR, SHADOW_CONFIG_FILE)
221 else:
222 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
223
224 _Log('Using shadow config file stored at %s', shadow_config_file)
joychen562699a2013-08-13 15:22:14 -0700225 if os.path.exists(shadow_config_file):
226 shadow_xbuddy_config = ConfigParser.ConfigParser()
227 shadow_xbuddy_config.read(shadow_config_file)
228
229 # Merge shadow config in.
230 sections = shadow_xbuddy_config.sections()
231 for s in sections:
232 if not xbuddy_config.has_section(s):
233 xbuddy_config.add_section(s)
234 options = shadow_xbuddy_config.options(s)
235 for o in options:
236 val = shadow_xbuddy_config.get(s, o)
237 xbuddy_config.set(s, o, val)
238
239 return xbuddy_config
240
241 def _ManageBuilds(self):
242 """Checks if xBuddy is managing local builds using the current config."""
243 try:
244 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
245 except ConfigParser.Error:
246 return False
247
248 def _Capacity(self):
249 """Gets the xbuddy capacity from the current config."""
250 try:
251 return int(self.config.get(GENERAL, 'capacity'))
252 except ConfigParser.Error:
253 return 5
254
255 def _LookupAlias(self, alias, board):
256 """Given the full xbuddy config, look up an alias for path rewrite.
257
258 Args:
259 alias: The xbuddy path that could be one of the aliases in the
260 rewrite table.
261 board: The board to fill in with when paths are rewritten. Can be from
262 the update request xml or the default board from devserver.
263 Returns:
264 If a rewrite is found, a string with the current board substituted in.
265 If no rewrite is found, just return the original string.
266 """
267 if alias == '':
268 alias = 'update_default'
269
270 try:
271 val = self.config.get(PATH_REWRITES, alias)
272 except ConfigParser.Error:
273 # No alias lookup found. Return original path.
274 return alias
275
276 if not val.strip():
277 # The found value was an empty string.
278 return alias
279 else:
280 # Fill in the board.
joychenc3944cb2013-08-19 10:42:07 -0700281 rewrite = val.replace("BOARD", "%(board)s") % {
joychen562699a2013-08-13 15:22:14 -0700282 'board': board}
283 _Log("Path was rewritten to %s", rewrite)
284 return rewrite
285
joychenf8f07e22013-07-12 17:45:51 -0700286 def _LookupOfficial(self, board, suffix=RELEASE):
287 """Check LATEST-master for the version number of interest."""
288 _Log("Checking gs for latest %s-%s image", board, suffix)
289 latest_addr = devserver_constants.GS_LATEST_MASTER % {'board':board,
290 'suffix':suffix}
291 cmd = 'gsutil cat %s' % latest_addr
292 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700293 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700294 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700295
joychenf8f07e22013-07-12 17:45:51 -0700296 return devserver_constants.IMAGE_DIR % {'board':board,
297 'suffix':suffix,
298 'version':version}
joychenf8f07e22013-07-12 17:45:51 -0700299 def _LookupChannel(self, board, channel='stable'):
300 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700301 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700302 _Log("Checking channel '%s' for latest '%s' image", channel, board)
joychenf8f07e22013-07-12 17:45:51 -0700303 channel_dir = devserver_constants.GS_CHANNEL_DIR % {'channel':channel,
304 'board':board}
joychen562699a2013-08-13 15:22:14 -0700305 latest_version = gsutil_util.GetLatestVersionFromGSDir(
306 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700307
joychen121fc9b2013-08-02 14:30:30 -0700308 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700309 image_url = devserver_constants.IMAGE_DIR % {
310 'board':board,
311 'suffix':RELEASE,
312 'version':'R*' + latest_version}
joychenf8f07e22013-07-12 17:45:51 -0700313 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
314
315 # There should only be one match on cros-image-archive.
316 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
317
318 return devserver_constants.IMAGE_DIR % {'board':board,
319 'suffix':RELEASE,
320 'version':full_version}
321
322 def _LookupVersion(self, board, version):
323 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700324 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700325 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
joychenf8f07e22013-07-12 17:45:51 -0700326 image_url = devserver_constants.IMAGE_DIR % {'board':board,
327 'suffix':RELEASE,
328 'version':version + '*'}
329 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
330
joychen121fc9b2013-08-02 14:30:30 -0700331 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700332 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
333 return devserver_constants.IMAGE_DIR % {'board':board,
334 'suffix':RELEASE,
335 'version':full_version}
336
Chris Sosaea734d92013-10-11 11:28:58 -0700337 def _RemoteBuildId(self, board, version):
338 """Returns the remote build_id for the given board and version.
339
340 Raises:
341 XBuddyException: If we failed to resolve the version to a valid build_id.
342 """
343 build_id_as_is = devserver_constants.IMAGE_DIR % {'board':board,
344 'suffix':'',
345 'version':version}
346 build_id_release = devserver_constants.IMAGE_DIR % {'board':board,
347 'suffix':RELEASE,
348 'version':version}
349 # Return the first path that exists. We assume that what the user typed
350 # is better than with a default suffix added i.e. x86-generic/blah is
351 # more valuable than x86-generic-release/blah.
352 for build_id in build_id_as_is, build_id_release:
353 cmd = 'gsutil ls %s/%s' % (devserver_constants.GS_IMAGE_DIR, build_id)
354 try:
355 version = gsutil_util.GSUtilRun(cmd, None)
356 return build_id
357 except gsutil_util.GSUtilError:
358 continue
359 else:
360 raise XBuddyException('Could not find remote build_id for %s %s' % (
361 board, version))
362
363 def _ResolveVersionToBuildId(self, board, version):
joychen121fc9b2013-08-02 14:30:30 -0700364 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700365
366 Args:
367 board: as specified in the original call. (i.e. x86-generic, parrot)
368 version: as entered in the original call. can be
369 {TBD, 0. some custom alias as defined in a config file}
370 1. latest
371 2. latest-{channel}
372 3. latest-official-{board suffix}
373 4. version prefix (i.e. RX-Y.X, RX-Y, RX)
joychen3cb228e2013-06-12 12:13:13 -0700374
375 Returns:
Chris Sosaea734d92013-10-11 11:28:58 -0700376 Location where the image dir is actually found on GS (build_id)
joychen3cb228e2013-06-12 12:13:13 -0700377
Chris Sosaea734d92013-10-11 11:28:58 -0700378 Raises:
379 XBuddyException: If we failed to resolve the version to a valid url.
joychen3cb228e2013-06-12 12:13:13 -0700380 """
joychenf8f07e22013-07-12 17:45:51 -0700381 # Only the last segment of the alias is variable relative to the rest.
382 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700383
joychenf8f07e22013-07-12 17:45:51 -0700384 if re.match(devserver_constants.VERSION_RE, version):
Chris Sosaea734d92013-10-11 11:28:58 -0700385 return self._RemoteBuildId(board, version)
joychenf8f07e22013-07-12 17:45:51 -0700386 elif version == LATEST_OFFICIAL:
387 # latest-official --> LATEST build in board-release
388 return self._LookupOfficial(board)
389 elif version_tuple[0] == LATEST_OFFICIAL:
390 # latest-official-{suffix} --> LATEST build in board-{suffix}
391 return self._LookupOfficial(board, version_tuple[1])
392 elif version == LATEST:
393 # latest --> latest build on stable channel
394 return self._LookupChannel(board)
395 elif version_tuple[0] == LATEST:
396 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
397 # latest-R* --> most recent qualifying build
398 return self._LookupVersion(board, version_tuple[1])
399 else:
400 # latest-{channel} --> latest build within that channel
401 return self._LookupChannel(board, version_tuple[1])
joychen3cb228e2013-06-12 12:13:13 -0700402 else:
403 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700404 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700405
joychen5260b9a2013-07-16 14:48:01 -0700406 @staticmethod
407 def _Symlink(link, target):
408 """Symlinks link to target, and removes whatever link was there before."""
409 _Log("Linking to %s from %s", link, target)
410 if os.path.lexists(link):
411 os.unlink(link)
412 os.symlink(target, link)
413
joychen121fc9b2013-08-02 14:30:30 -0700414 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700415 """Get the version of the latest image built for board by build_image
416
417 Updates the symlink reference within the xBuddy static dir to point to
418 the real image dir in the local /build/images directory.
419
420 Args:
joychenc3944cb2013-08-19 10:42:07 -0700421 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700422
423 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700424 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700425
426 Raises:
427 XBuddyException if neither test nor dev image was found in latest built
428 directory.
joychen3cb228e2013-06-12 12:13:13 -0700429 """
joychen921e1fb2013-06-28 11:12:20 -0700430 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700431 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700432 raise XBuddyException('No builds found for %s. Did you run build_image?' %
433 board)
434
joychen121fc9b2013-08-02 14:30:30 -0700435 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700436 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700437
joychenc3944cb2013-08-19 10:42:07 -0700438 @staticmethod
439 def _FindAny(local_dir):
440 """Returns the image_type for ANY given the local_dir."""
441 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
442 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
443 if os.path.exists(dev_image):
444 return 'dev'
445
446 if os.path.exists(test_image):
447 return 'test'
448
449 raise XBuddyException('No images found in %s' % local_dir)
450
451 @staticmethod
452 def _InterpretPath(path):
joychen121fc9b2013-08-02 14:30:30 -0700453 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700454
joychen121fc9b2013-08-02 14:30:30 -0700455 Args:
456 path: the path xBuddy Get was called with.
joychen3cb228e2013-06-12 12:13:13 -0700457
458 Return:
Chris Sosa75490802013-09-30 17:21:45 -0700459 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 12:13:13 -0700460
461 Raises:
462 XBuddyException: if the path can't be resolved into valid components
463 """
joychen121fc9b2013-08-02 14:30:30 -0700464 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700465
466 # Required parts of path parsing.
467 try:
468 # Determine if image is explicitly local or remote.
joychen121fc9b2013-08-02 14:30:30 -0700469 is_local = True
470 if path_list[0] in (REMOTE, LOCAL):
joychen18737f32013-08-16 17:18:12 -0700471 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700472
joychen121fc9b2013-08-02 14:30:30 -0700473 # Set board.
joychen7df67f72013-07-18 14:21:12 -0700474 board = path_list.pop(0)
joychen7df67f72013-07-18 14:21:12 -0700475
joychen121fc9b2013-08-02 14:30:30 -0700476 # Set defaults.
joychen3cb228e2013-06-12 12:13:13 -0700477 version = LATEST
joychen921e1fb2013-06-28 11:12:20 -0700478 image_type = GS_ALIASES[0]
joychen7df67f72013-07-18 14:21:12 -0700479 except IndexError:
480 msg = "Specify at least the board in your xBuddy call. Your path: %s"
481 raise XBuddyException(msg % os.path.join(path_list))
joychen3cb228e2013-06-12 12:13:13 -0700482
joychen121fc9b2013-08-02 14:30:30 -0700483 # Read as much of the xBuddy path as possible.
joychen7df67f72013-07-18 14:21:12 -0700484 try:
joychen121fc9b2013-08-02 14:30:30 -0700485 # Override default if terminal is a valid artifact alias or a version.
joychen7df67f72013-07-18 14:21:12 -0700486 terminal = path_list[-1]
487 if terminal in GS_ALIASES + LOCAL_ALIASES:
488 image_type = terminal
489 version = path_list[-2]
490 else:
491 version = terminal
492 except IndexError:
493 # This path doesn't have an alias or a version. That's fine.
494 _Log("Some parts of the path not specified. Using defaults.")
495
joychen346531c2013-07-24 16:55:56 -0700496 _Log("Get artifact '%s' in '%s/%s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700497 image_type, board, version, is_local)
498
499 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700500
joychen921e1fb2013-06-28 11:12:20 -0700501 def _SyncRegistryWithBuildImages(self):
joychen5260b9a2013-07-16 14:48:01 -0700502 """ Crawl images_dir for build_ids of images generated from build_image.
503
504 This will find images and symlink them in xBuddy's static dir so that
505 xBuddy's cache can serve them.
506 If xBuddy's _manage_builds option is on, then a timestamp will also be
507 generated, and xBuddy will clear them from the directory they are in, as
508 necessary.
509 """
joychen921e1fb2013-06-28 11:12:20 -0700510 build_ids = []
511 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700512 # Ensure we have directories to track all boards in build/images
513 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700514 board_dir = os.path.join(self.images_dir, b)
515 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700516 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700517
joychen121fc9b2013-08-02 14:30:30 -0700518 # Check currently registered images.
joychen921e1fb2013-06-28 11:12:20 -0700519 for f in os.listdir(self._timestamp_folder):
520 build_id = Timestamp.TimestampToBuild(f)
521 if build_id in build_ids:
522 build_ids.remove(build_id)
523
joychen121fc9b2013-08-02 14:30:30 -0700524 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700525 for build_id in build_ids:
526 link = os.path.join(self.static_dir, build_id)
527 target = os.path.join(self.images_dir, build_id)
528 XBuddy._Symlink(link, target)
529 if self._manage_builds:
530 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700531
532 def _ListBuildTimes(self):
joychen3cb228e2013-06-12 12:13:13 -0700533 """ Returns the currently cached builds and their last access timestamp.
534
535 Returns:
536 list of tuples that matches xBuddy build/version to timestamps in long
537 """
joychen121fc9b2013-08-02 14:30:30 -0700538 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700539 build_dict = {}
540
joychen7df67f72013-07-18 14:21:12 -0700541 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700542 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
543 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700544 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700545 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700546 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
547 return return_tup
548
Chris Sosa75490802013-09-30 17:21:45 -0700549 def _Download(self, gs_url, artifacts):
550 """Download the artifacts from the given gs_url.
551
552 Raises:
553 build_artifact.ArtifactDownloadError: If we failed to download the
554 artifact.
555 """
joychen3cb228e2013-06-12 12:13:13 -0700556 with XBuddy._staging_thread_count_lock:
557 XBuddy._staging_thread_count += 1
558 try:
Chris Sosa75490802013-09-30 17:21:45 -0700559 _Log("Downloading %s from %s", artifacts, gs_url)
560 downloader.Downloader(self.static_dir, gs_url).Download(artifacts, [])
joychen3cb228e2013-06-12 12:13:13 -0700561 finally:
562 with XBuddy._staging_thread_count_lock:
563 XBuddy._staging_thread_count -= 1
564
Chris Sosa75490802013-09-30 17:21:45 -0700565 def CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700566 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700567 if not self._manage_builds:
568 return
joychen921e1fb2013-06-28 11:12:20 -0700569 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700570 _Log('In cache now: %s', cached_builds)
571
joychen562699a2013-08-13 15:22:14 -0700572 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700573 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700574 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700575
576 time_file = os.path.join(self._timestamp_folder,
577 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700578 os.unlink(time_file)
579 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700580 try:
joychen121fc9b2013-08-02 14:30:30 -0700581 # Handle symlinks, in the case of links to local builds if enabled.
582 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700583 target = os.readlink(clear_dir)
584 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700585
586 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700587 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700588 shutil.rmtree(target)
589 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700590 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700591 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700592
joychen121fc9b2013-08-02 14:30:30 -0700593 except Exception as err:
594 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700595
Chris Sosa75490802013-09-30 17:21:45 -0700596 def _GetFromGS(self, build_id, image_type):
597 """Check if the artifact is available locally. Download from GS if not.
598
599 Raises:
600 build_artifact.ArtifactDownloadError: If we failed to download the
601 artifact.
602 """
joychenf8f07e22013-07-12 17:45:51 -0700603 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
joychen921e1fb2013-06-28 11:12:20 -0700604 build_id)
605
joychen121fc9b2013-08-02 14:30:30 -0700606 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700607 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700608 file_loc = os.path.join(self.static_dir, build_id, file_name)
609 cached = os.path.exists(file_loc)
610
joychen921e1fb2013-06-28 11:12:20 -0700611 if not cached:
Chris Sosa75490802013-09-30 17:21:45 -0700612 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
613 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 11:12:20 -0700614 else:
615 _Log('Image already cached.')
616
Chris Sosa75490802013-09-30 17:21:45 -0700617 def _GetArtifact(self, path_list, board=None, lookup_only=False):
joychen346531c2013-07-24 16:55:56 -0700618 """Interpret an xBuddy path and return directory/file_name to resource.
619
Chris Sosa75490802013-09-30 17:21:45 -0700620 Note board can be passed that in but by default if self._board is set,
621 that is used rather than board.
622
joychen346531c2013-07-24 16:55:56 -0700623 Returns:
joychenc3944cb2013-08-19 10:42:07 -0700624 build_id to the directory
joychen346531c2013-07-24 16:55:56 -0700625 file_name of the artifact
joychen346531c2013-07-24 16:55:56 -0700626
627 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700628 XBuddyException: if the path could not be translated
Chris Sosa75490802013-09-30 17:21:45 -0700629 build_artifact.ArtifactDownloadError: if we failed to download the
630 artifact.
joychen346531c2013-07-24 16:55:56 -0700631 """
joychen121fc9b2013-08-02 14:30:30 -0700632 path = '/'.join(path_list)
joychenb0dfe552013-07-30 10:02:06 -0700633 # Rewrite the path if there is an appropriate default.
Chris Sosa75490802013-09-30 17:21:45 -0700634 path = self._LookupAlias(path, self._board if self._board else board)
joychenb0dfe552013-07-30 10:02:06 -0700635
joychen121fc9b2013-08-02 14:30:30 -0700636 # Parse the path.
joychen7df67f72013-07-18 14:21:12 -0700637 image_type, board, version, is_local = self._InterpretPath(path)
joychen921e1fb2013-06-28 11:12:20 -0700638
joychen7df67f72013-07-18 14:21:12 -0700639 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700640 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700641 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700642 # Get the latest local image for the given board.
643 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700644
joychenc3944cb2013-08-19 10:42:07 -0700645 build_id = os.path.join(board, version)
646 artifact_dir = os.path.join(self.static_dir, build_id)
647 if image_type == ANY:
648 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700649
joychenc3944cb2013-08-19 10:42:07 -0700650 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
651 artifact_path = os.path.join(artifact_dir, file_name)
652 if not os.path.exists(artifact_path):
653 raise XBuddyException('Local %s artifact not in static_dir at %s' %
654 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700655
joychen921e1fb2013-06-28 11:12:20 -0700656 else:
joychen121fc9b2013-08-02 14:30:30 -0700657 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700658 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700659 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700660 (image_type, GS_ALIASES))
Chris Sosaea734d92013-10-11 11:28:58 -0700661 build_id = self._ResolveVersionToBuildId(board, version)
Chris Sosa75490802013-09-30 17:21:45 -0700662 _Log('Resolved version %s to %s.', version, build_id)
663 file_name = GS_ALIAS_TO_FILENAME[image_type]
664 if not lookup_only:
665 self._GetFromGS(build_id, image_type)
joychenf8f07e22013-07-12 17:45:51 -0700666
joychenc3944cb2013-08-19 10:42:07 -0700667 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700668
669 ############################ BEGIN PUBLIC METHODS
670
671 def List(self):
672 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700673 self._SyncRegistryWithBuildImages()
674 builds = self._ListBuildTimes()
675 return_string = ''
676 for build, timestamp in builds:
677 return_string += '<b>' + build + '</b> '
678 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
679 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700680
681 def Capacity(self):
682 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700683 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700684
Chris Sosa75490802013-09-30 17:21:45 -0700685 def Translate(self, path_list, board=None):
joychen346531c2013-07-24 16:55:56 -0700686 """Translates an xBuddy path to a real path to artifact if it exists.
687
joychen121fc9b2013-08-02 14:30:30 -0700688 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700689
joychen7c2054a2013-07-25 11:14:07 -0700690 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700691 build_id: Path to the image or update directory on the devserver.
692 e.g. 'x86-generic/R26-4000.0.0'
693 The returned path is always the path to the directory within
694 static_dir, so it is always the build_id of the image.
695 file_name: The file name of the artifact. Can take any of the file
696 values in devserver_constants.
697 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
698 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700699
joychen121fc9b2013-08-02 14:30:30 -0700700 Raises:
701 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700702 """
703 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700704 build_id, file_name = self._GetArtifact(path_list, board=board,
705 lookup_only=True)
joychen346531c2013-07-24 16:55:56 -0700706
joychen121fc9b2013-08-02 14:30:30 -0700707 _Log('Returning path to payload: %s/%s', build_id, file_name)
708 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700709
Chris Sosa75490802013-09-30 17:21:45 -0700710 def StageTestAritfactsForUpdate(self, path_list):
711 """Stages test artifacts for update and returns build_id.
712
713 Raises:
714 XBuddyException: if the path could not be translated
715 build_artifact.ArtifactDownloadError: if we failed to download the test
716 artifacts.
717 """
718 build_id, file_name = self.Translate(path_list)
719 if file_name == devserver_constants.TEST_IMAGE_FILE:
720 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
721 build_id)
722 artifacts = [FULL, STATEFUL]
723 self._Download(gs_url, artifacts)
724 return build_id
725
joychen562699a2013-08-13 15:22:14 -0700726 def Get(self, path_list):
joychen921e1fb2013-06-28 11:12:20 -0700727 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700728
729 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700730
joychen3cb228e2013-06-12 12:13:13 -0700731 Args:
joychen921e1fb2013-06-28 11:12:20 -0700732 path_list: [board, version, alias] as split from the xbuddy call url
joychen3cb228e2013-06-12 12:13:13 -0700733
734 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700735 build_id: Path to the image or update directory on the devserver.
736 e.g. 'x86-generic/R26-4000.0.0'
737 The returned path is always the path to the directory within
738 static_dir, so it is always the build_id of the image.
739 file_name: The file name of the artifact. Can take any of the file
740 values in devserver_constants.
741 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
742 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700743
744 Raises:
Chris Sosa75490802013-09-30 17:21:45 -0700745 XBuddyException: if the path could not be translated
746 build_artifact.ArtifactDownloadError: if we failed to download the
747 artifact.
joychen3cb228e2013-06-12 12:13:13 -0700748 """
joychen7df67f72013-07-18 14:21:12 -0700749 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700750 build_id, file_name = self._GetArtifact(path_list)
joychen921e1fb2013-06-28 11:12:20 -0700751 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700752 #TODO (joyc): run in sep thread
Chris Sosa75490802013-09-30 17:21:45 -0700753 self.CleanCache()
joychen3cb228e2013-06-12 12:13:13 -0700754
joychen121fc9b2013-08-02 14:30:30 -0700755 _Log('Returning path to payload: %s/%s', build_id, file_name)
756 return build_id, file_name