blob: 5fff21aa2a9fc7c8200fa559964649c43244119d [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
joychenf8f07e22013-07-12 17:45:51 -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}
291
292 def _LookupChannel(self, board, channel='stable'):
293 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700294 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700295 _Log("Checking channel '%s' for latest '%s' image", channel, board)
joychenf8f07e22013-07-12 17:45:51 -0700296 channel_dir = devserver_constants.GS_CHANNEL_DIR % {'channel':channel,
297 'board':board}
joychen562699a2013-08-13 15:22:14 -0700298 latest_version = gsutil_util.GetLatestVersionFromGSDir(
299 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700300
joychen121fc9b2013-08-02 14:30:30 -0700301 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700302 image_url = devserver_constants.IMAGE_DIR % {
303 'board':board,
304 'suffix':RELEASE,
305 'version':'R*' + latest_version}
joychenf8f07e22013-07-12 17:45:51 -0700306 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
307
308 # There should only be one match on cros-image-archive.
309 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
310
311 return devserver_constants.IMAGE_DIR % {'board':board,
312 'suffix':RELEASE,
313 'version':full_version}
314
315 def _LookupVersion(self, board, version):
316 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700317 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700318 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
joychenf8f07e22013-07-12 17:45:51 -0700319 image_url = devserver_constants.IMAGE_DIR % {'board':board,
320 'suffix':RELEASE,
321 'version':version + '*'}
322 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
323
joychen121fc9b2013-08-02 14:30:30 -0700324 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700325 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
326 return devserver_constants.IMAGE_DIR % {'board':board,
327 'suffix':RELEASE,
328 'version':full_version}
329
330 def _ResolveVersionToUrl(self, board, version):
joychen121fc9b2013-08-02 14:30:30 -0700331 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700332
333 Args:
334 board: as specified in the original call. (i.e. x86-generic, parrot)
335 version: as entered in the original call. can be
336 {TBD, 0. some custom alias as defined in a config file}
337 1. latest
338 2. latest-{channel}
339 3. latest-official-{board suffix}
340 4. version prefix (i.e. RX-Y.X, RX-Y, RX)
joychen3cb228e2013-06-12 12:13:13 -0700341
342 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700343 Location where the image dir is actually found on GS
joychen3cb228e2013-06-12 12:13:13 -0700344
345 """
joychen121fc9b2013-08-02 14:30:30 -0700346 # TODO(joychen): Convert separate calls to a dict + error out bad paths.
joychen3cb228e2013-06-12 12:13:13 -0700347
joychenf8f07e22013-07-12 17:45:51 -0700348 # Only the last segment of the alias is variable relative to the rest.
349 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700350
joychenf8f07e22013-07-12 17:45:51 -0700351 if re.match(devserver_constants.VERSION_RE, version):
352 # This is supposed to be a complete version number on GS. Return it.
353 return devserver_constants.IMAGE_DIR % {'board':board,
354 'suffix':RELEASE,
355 'version':version}
356 elif version == LATEST_OFFICIAL:
357 # latest-official --> LATEST build in board-release
358 return self._LookupOfficial(board)
359 elif version_tuple[0] == LATEST_OFFICIAL:
360 # latest-official-{suffix} --> LATEST build in board-{suffix}
361 return self._LookupOfficial(board, version_tuple[1])
362 elif version == LATEST:
363 # latest --> latest build on stable channel
364 return self._LookupChannel(board)
365 elif version_tuple[0] == LATEST:
366 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
367 # latest-R* --> most recent qualifying build
368 return self._LookupVersion(board, version_tuple[1])
369 else:
370 # latest-{channel} --> latest build within that channel
371 return self._LookupChannel(board, version_tuple[1])
joychen3cb228e2013-06-12 12:13:13 -0700372 else:
373 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700374 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700375
joychen5260b9a2013-07-16 14:48:01 -0700376 @staticmethod
377 def _Symlink(link, target):
378 """Symlinks link to target, and removes whatever link was there before."""
379 _Log("Linking to %s from %s", link, target)
380 if os.path.lexists(link):
381 os.unlink(link)
382 os.symlink(target, link)
383
joychen121fc9b2013-08-02 14:30:30 -0700384 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700385 """Get the version of the latest image built for board by build_image
386
387 Updates the symlink reference within the xBuddy static dir to point to
388 the real image dir in the local /build/images directory.
389
390 Args:
joychenc3944cb2013-08-19 10:42:07 -0700391 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700392
393 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700394 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700395
396 Raises:
397 XBuddyException if neither test nor dev image was found in latest built
398 directory.
joychen3cb228e2013-06-12 12:13:13 -0700399 """
joychen921e1fb2013-06-28 11:12:20 -0700400 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700401 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700402 raise XBuddyException('No builds found for %s. Did you run build_image?' %
403 board)
404
joychen121fc9b2013-08-02 14:30:30 -0700405 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700406 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700407
joychenc3944cb2013-08-19 10:42:07 -0700408 @staticmethod
409 def _FindAny(local_dir):
410 """Returns the image_type for ANY given the local_dir."""
411 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
412 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
413 if os.path.exists(dev_image):
414 return 'dev'
415
416 if os.path.exists(test_image):
417 return 'test'
418
419 raise XBuddyException('No images found in %s' % local_dir)
420
421 @staticmethod
422 def _InterpretPath(path):
joychen121fc9b2013-08-02 14:30:30 -0700423 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700424
joychen121fc9b2013-08-02 14:30:30 -0700425 Args:
426 path: the path xBuddy Get was called with.
joychen3cb228e2013-06-12 12:13:13 -0700427
428 Return:
Chris Sosa75490802013-09-30 17:21:45 -0700429 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 12:13:13 -0700430
431 Raises:
432 XBuddyException: if the path can't be resolved into valid components
433 """
joychen121fc9b2013-08-02 14:30:30 -0700434 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700435
436 # Required parts of path parsing.
437 try:
438 # Determine if image is explicitly local or remote.
joychen121fc9b2013-08-02 14:30:30 -0700439 is_local = True
440 if path_list[0] in (REMOTE, LOCAL):
joychen18737f32013-08-16 17:18:12 -0700441 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700442
joychen121fc9b2013-08-02 14:30:30 -0700443 # Set board.
joychen7df67f72013-07-18 14:21:12 -0700444 board = path_list.pop(0)
joychen7df67f72013-07-18 14:21:12 -0700445
joychen121fc9b2013-08-02 14:30:30 -0700446 # Set defaults.
joychen3cb228e2013-06-12 12:13:13 -0700447 version = LATEST
joychen921e1fb2013-06-28 11:12:20 -0700448 image_type = GS_ALIASES[0]
joychen7df67f72013-07-18 14:21:12 -0700449 except IndexError:
450 msg = "Specify at least the board in your xBuddy call. Your path: %s"
451 raise XBuddyException(msg % os.path.join(path_list))
joychen3cb228e2013-06-12 12:13:13 -0700452
joychen121fc9b2013-08-02 14:30:30 -0700453 # Read as much of the xBuddy path as possible.
joychen7df67f72013-07-18 14:21:12 -0700454 try:
joychen121fc9b2013-08-02 14:30:30 -0700455 # Override default if terminal is a valid artifact alias or a version.
joychen7df67f72013-07-18 14:21:12 -0700456 terminal = path_list[-1]
457 if terminal in GS_ALIASES + LOCAL_ALIASES:
458 image_type = terminal
459 version = path_list[-2]
460 else:
461 version = terminal
462 except IndexError:
463 # This path doesn't have an alias or a version. That's fine.
464 _Log("Some parts of the path not specified. Using defaults.")
465
joychen346531c2013-07-24 16:55:56 -0700466 _Log("Get artifact '%s' in '%s/%s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700467 image_type, board, version, is_local)
468
469 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700470
joychen921e1fb2013-06-28 11:12:20 -0700471 def _SyncRegistryWithBuildImages(self):
joychen5260b9a2013-07-16 14:48:01 -0700472 """ Crawl images_dir for build_ids of images generated from build_image.
473
474 This will find images and symlink them in xBuddy's static dir so that
475 xBuddy's cache can serve them.
476 If xBuddy's _manage_builds option is on, then a timestamp will also be
477 generated, and xBuddy will clear them from the directory they are in, as
478 necessary.
479 """
joychen921e1fb2013-06-28 11:12:20 -0700480 build_ids = []
481 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700482 # Ensure we have directories to track all boards in build/images
483 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700484 board_dir = os.path.join(self.images_dir, b)
485 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700486 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700487
joychen121fc9b2013-08-02 14:30:30 -0700488 # Check currently registered images.
joychen921e1fb2013-06-28 11:12:20 -0700489 for f in os.listdir(self._timestamp_folder):
490 build_id = Timestamp.TimestampToBuild(f)
491 if build_id in build_ids:
492 build_ids.remove(build_id)
493
joychen121fc9b2013-08-02 14:30:30 -0700494 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700495 for build_id in build_ids:
496 link = os.path.join(self.static_dir, build_id)
497 target = os.path.join(self.images_dir, build_id)
498 XBuddy._Symlink(link, target)
499 if self._manage_builds:
500 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700501
502 def _ListBuildTimes(self):
joychen3cb228e2013-06-12 12:13:13 -0700503 """ Returns the currently cached builds and their last access timestamp.
504
505 Returns:
506 list of tuples that matches xBuddy build/version to timestamps in long
507 """
joychen121fc9b2013-08-02 14:30:30 -0700508 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700509 build_dict = {}
510
joychen7df67f72013-07-18 14:21:12 -0700511 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700512 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
513 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700514 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700515 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700516 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
517 return return_tup
518
Chris Sosa75490802013-09-30 17:21:45 -0700519 def _Download(self, gs_url, artifacts):
520 """Download the artifacts from the given gs_url.
521
522 Raises:
523 build_artifact.ArtifactDownloadError: If we failed to download the
524 artifact.
525 """
joychen3cb228e2013-06-12 12:13:13 -0700526 with XBuddy._staging_thread_count_lock:
527 XBuddy._staging_thread_count += 1
528 try:
Chris Sosa75490802013-09-30 17:21:45 -0700529 _Log("Downloading %s from %s", artifacts, gs_url)
530 downloader.Downloader(self.static_dir, gs_url).Download(artifacts, [])
joychen3cb228e2013-06-12 12:13:13 -0700531 finally:
532 with XBuddy._staging_thread_count_lock:
533 XBuddy._staging_thread_count -= 1
534
Chris Sosa75490802013-09-30 17:21:45 -0700535 def CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700536 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700537 if not self._manage_builds:
538 return
joychen921e1fb2013-06-28 11:12:20 -0700539 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700540 _Log('In cache now: %s', cached_builds)
541
joychen562699a2013-08-13 15:22:14 -0700542 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700543 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700544 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700545
546 time_file = os.path.join(self._timestamp_folder,
547 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700548 os.unlink(time_file)
549 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700550 try:
joychen121fc9b2013-08-02 14:30:30 -0700551 # Handle symlinks, in the case of links to local builds if enabled.
552 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700553 target = os.readlink(clear_dir)
554 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700555
556 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700557 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700558 shutil.rmtree(target)
559 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700560 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700561 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700562
joychen121fc9b2013-08-02 14:30:30 -0700563 except Exception as err:
564 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700565
Chris Sosa75490802013-09-30 17:21:45 -0700566 def _GetFromGS(self, build_id, image_type):
567 """Check if the artifact is available locally. Download from GS if not.
568
569 Raises:
570 build_artifact.ArtifactDownloadError: If we failed to download the
571 artifact.
572 """
joychenf8f07e22013-07-12 17:45:51 -0700573 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
joychen921e1fb2013-06-28 11:12:20 -0700574 build_id)
575
joychen121fc9b2013-08-02 14:30:30 -0700576 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700577 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700578 file_loc = os.path.join(self.static_dir, build_id, file_name)
579 cached = os.path.exists(file_loc)
580
joychen921e1fb2013-06-28 11:12:20 -0700581 if not cached:
Chris Sosa75490802013-09-30 17:21:45 -0700582 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
583 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 11:12:20 -0700584 else:
585 _Log('Image already cached.')
586
Chris Sosa75490802013-09-30 17:21:45 -0700587 def _GetArtifact(self, path_list, board=None, lookup_only=False):
joychen346531c2013-07-24 16:55:56 -0700588 """Interpret an xBuddy path and return directory/file_name to resource.
589
Chris Sosa75490802013-09-30 17:21:45 -0700590 Note board can be passed that in but by default if self._board is set,
591 that is used rather than board.
592
joychen346531c2013-07-24 16:55:56 -0700593 Returns:
joychenc3944cb2013-08-19 10:42:07 -0700594 build_id to the directory
joychen346531c2013-07-24 16:55:56 -0700595 file_name of the artifact
joychen346531c2013-07-24 16:55:56 -0700596
597 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700598 XBuddyException: if the path could not be translated
Chris Sosa75490802013-09-30 17:21:45 -0700599 build_artifact.ArtifactDownloadError: if we failed to download the
600 artifact.
joychen346531c2013-07-24 16:55:56 -0700601 """
joychen121fc9b2013-08-02 14:30:30 -0700602 path = '/'.join(path_list)
joychenb0dfe552013-07-30 10:02:06 -0700603 # Rewrite the path if there is an appropriate default.
Chris Sosa75490802013-09-30 17:21:45 -0700604 path = self._LookupAlias(path, self._board if self._board else board)
joychenb0dfe552013-07-30 10:02:06 -0700605
joychen121fc9b2013-08-02 14:30:30 -0700606 # Parse the path.
joychen7df67f72013-07-18 14:21:12 -0700607 image_type, board, version, is_local = self._InterpretPath(path)
joychen921e1fb2013-06-28 11:12:20 -0700608
joychen7df67f72013-07-18 14:21:12 -0700609 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700610 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700611 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700612 # Get the latest local image for the given board.
613 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700614
joychenc3944cb2013-08-19 10:42:07 -0700615 build_id = os.path.join(board, version)
616 artifact_dir = os.path.join(self.static_dir, build_id)
617 if image_type == ANY:
618 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700619
joychenc3944cb2013-08-19 10:42:07 -0700620 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
621 artifact_path = os.path.join(artifact_dir, file_name)
622 if not os.path.exists(artifact_path):
623 raise XBuddyException('Local %s artifact not in static_dir at %s' %
624 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700625
joychen921e1fb2013-06-28 11:12:20 -0700626 else:
joychen121fc9b2013-08-02 14:30:30 -0700627 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700628 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700629 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700630 (image_type, GS_ALIASES))
joychenc3944cb2013-08-19 10:42:07 -0700631 build_id = self._ResolveVersionToUrl(board, version)
Chris Sosa75490802013-09-30 17:21:45 -0700632 _Log('Resolved version %s to %s.', version, build_id)
633 file_name = GS_ALIAS_TO_FILENAME[image_type]
634 if not lookup_only:
635 self._GetFromGS(build_id, image_type)
joychenf8f07e22013-07-12 17:45:51 -0700636
joychenc3944cb2013-08-19 10:42:07 -0700637 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700638
639 ############################ BEGIN PUBLIC METHODS
640
641 def List(self):
642 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700643 self._SyncRegistryWithBuildImages()
644 builds = self._ListBuildTimes()
645 return_string = ''
646 for build, timestamp in builds:
647 return_string += '<b>' + build + '</b> '
648 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
649 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700650
651 def Capacity(self):
652 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700653 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700654
Chris Sosa75490802013-09-30 17:21:45 -0700655 def Translate(self, path_list, board=None):
joychen346531c2013-07-24 16:55:56 -0700656 """Translates an xBuddy path to a real path to artifact if it exists.
657
joychen121fc9b2013-08-02 14:30:30 -0700658 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700659
joychen7c2054a2013-07-25 11:14:07 -0700660 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700661 build_id: Path to the image or update directory on the devserver.
662 e.g. 'x86-generic/R26-4000.0.0'
663 The returned path is always the path to the directory within
664 static_dir, so it is always the build_id of the image.
665 file_name: The file name of the artifact. Can take any of the file
666 values in devserver_constants.
667 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
668 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700669
joychen121fc9b2013-08-02 14:30:30 -0700670 Raises:
671 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700672 """
673 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700674 build_id, file_name = self._GetArtifact(path_list, board=board,
675 lookup_only=True)
joychen346531c2013-07-24 16:55:56 -0700676
joychen121fc9b2013-08-02 14:30:30 -0700677 _Log('Returning path to payload: %s/%s', build_id, file_name)
678 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700679
Chris Sosa75490802013-09-30 17:21:45 -0700680 def StageTestAritfactsForUpdate(self, path_list):
681 """Stages test artifacts for update and returns build_id.
682
683 Raises:
684 XBuddyException: if the path could not be translated
685 build_artifact.ArtifactDownloadError: if we failed to download the test
686 artifacts.
687 """
688 build_id, file_name = self.Translate(path_list)
689 if file_name == devserver_constants.TEST_IMAGE_FILE:
690 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
691 build_id)
692 artifacts = [FULL, STATEFUL]
693 self._Download(gs_url, artifacts)
694 return build_id
695
joychen562699a2013-08-13 15:22:14 -0700696 def Get(self, path_list):
joychen921e1fb2013-06-28 11:12:20 -0700697 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700698
699 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700700
joychen3cb228e2013-06-12 12:13:13 -0700701 Args:
joychen921e1fb2013-06-28 11:12:20 -0700702 path_list: [board, version, alias] as split from the xbuddy call url
joychen3cb228e2013-06-12 12:13:13 -0700703
704 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700705 build_id: Path to the image or update directory on the devserver.
706 e.g. 'x86-generic/R26-4000.0.0'
707 The returned path is always the path to the directory within
708 static_dir, so it is always the build_id of the image.
709 file_name: The file name of the artifact. Can take any of the file
710 values in devserver_constants.
711 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
712 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700713
714 Raises:
Chris Sosa75490802013-09-30 17:21:45 -0700715 XBuddyException: if the path could not be translated
716 build_artifact.ArtifactDownloadError: if we failed to download the
717 artifact.
joychen3cb228e2013-06-12 12:13:13 -0700718 """
joychen7df67f72013-07-18 14:21:12 -0700719 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700720 build_id, file_name = self._GetArtifact(path_list)
joychen921e1fb2013-06-28 11:12:20 -0700721 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700722 #TODO (joyc): run in sep thread
Chris Sosa75490802013-09-30 17:21:45 -0700723 self.CleanCache()
joychen3cb228e2013-06-12 12:13:13 -0700724
joychen121fc9b2013-08-02 14:30:30 -0700725 _Log('Returning path to payload: %s/%s', build_id, file_name)
726 return build_id, file_name