blob: e635f9da2bd5105d6d048811cf93874193ed9c84 [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
Chris Sosa0eecf962014-02-03 14:14:39 -08005"""Main module for parsing and interpreting XBuddy paths for the devserver."""
6
joychen562699a2013-08-13 15:22:14 -07007import ConfigParser
joychen3cb228e2013-06-12 12:13:13 -07008import datetime
9import operator
10import os
joychenf8f07e22013-07-12 17:45:51 -070011import re
joychen3cb228e2013-06-12 12:13:13 -070012import shutil
joychenf8f07e22013-07-12 17:45:51 -070013import time
joychen3cb228e2013-06-12 12:13:13 -070014import threading
15
joychen921e1fb2013-06-28 11:12:20 -070016import build_util
joychen3cb228e2013-06-12 12:13:13 -070017import artifact_info
joychen3cb228e2013-06-12 12:13:13 -070018import common_util
19import devserver_constants
20import downloader
joychenf8f07e22013-07-12 17:45:51 -070021import gsutil_util
joychen3cb228e2013-06-12 12:13:13 -070022import log_util
23
24# Module-local log function.
25def _Log(message, *args):
26 return log_util.LogWithTag('XBUDDY', message, *args)
27
joychen562699a2013-08-13 15:22:14 -070028# xBuddy config constants
29CONFIG_FILE = 'xbuddy_config.ini'
30SHADOW_CONFIG_FILE = 'shadow_xbuddy_config.ini'
31PATH_REWRITES = 'PATH_REWRITES'
32GENERAL = 'GENERAL'
joychen921e1fb2013-06-28 11:12:20 -070033
Chris Sosac2abc722013-08-26 17:11:22 -070034# Path for shadow config in chroot.
35CHROOT_SHADOW_DIR = '/mnt/host/source/src/platform/dev'
36
joychen25d25972013-07-30 14:54:16 -070037# XBuddy aliases
38TEST = 'test'
39BASE = 'base'
40DEV = 'dev'
41FULL = 'full_payload'
42RECOVERY = 'recovery'
43STATEFUL = 'stateful'
44AUTOTEST = 'autotest'
45
joychen921e1fb2013-06-28 11:12:20 -070046# Local build constants
joychenc3944cb2013-08-19 10:42:07 -070047ANY = "ANY"
joychen7df67f72013-07-18 14:21:12 -070048LATEST = "latest"
49LOCAL = "local"
50REMOTE = "remote"
Chris Sosa75490802013-09-30 17:21:45 -070051
52# TODO(sosa): Fix a lot of assumptions about these aliases. There is too much
53# implicit logic here that's unnecessary. What should be done:
54# 1) Collapse Alias logic to one set of aliases for xbuddy (not local/remote).
55# 2) Do not use zip when creating these dicts. Better to not rely on ordering.
56# 3) Move alias/artifact mapping to a central module rather than having it here.
57# 4) Be explicit when things are missing i.e. no dev images in image.zip.
58
joychen921e1fb2013-06-28 11:12:20 -070059LOCAL_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070060 TEST,
joychen25d25972013-07-30 14:54:16 -070061 DEV,
Chris Sosa75490802013-09-30 17:21:45 -070062 BASE,
joychenc3944cb2013-08-19 10:42:07 -070063 FULL,
Chris Sosa7cd23202013-10-15 17:22:57 -070064 STATEFUL,
joychenc3944cb2013-08-19 10:42:07 -070065 ANY,
joychen921e1fb2013-06-28 11:12:20 -070066]
67
68LOCAL_FILE_NAMES = [
69 devserver_constants.TEST_IMAGE_FILE,
joychen921e1fb2013-06-28 11:12:20 -070070 devserver_constants.IMAGE_FILE,
Chris Sosa75490802013-09-30 17:21:45 -070071 devserver_constants.BASE_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070072 devserver_constants.UPDATE_FILE,
Chris Sosa7cd23202013-10-15 17:22:57 -070073 devserver_constants.STATEFUL_FILE,
Chris Sosa75490802013-09-30 17:21:45 -070074 None, # For ANY.
joychen921e1fb2013-06-28 11:12:20 -070075]
76
77LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
78
79# Google Storage constants
80GS_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070081 TEST,
82 BASE,
83 RECOVERY,
84 FULL,
85 STATEFUL,
86 AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -070087]
88
joychen921e1fb2013-06-28 11:12:20 -070089GS_FILE_NAMES = [
90 devserver_constants.TEST_IMAGE_FILE,
91 devserver_constants.BASE_IMAGE_FILE,
92 devserver_constants.RECOVERY_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070093 devserver_constants.UPDATE_FILE,
joychen121fc9b2013-08-02 14:30:30 -070094 devserver_constants.STATEFUL_FILE,
joychen3cb228e2013-06-12 12:13:13 -070095 devserver_constants.AUTOTEST_DIR,
96]
97
98ARTIFACTS = [
99 artifact_info.TEST_IMAGE,
100 artifact_info.BASE_IMAGE,
101 artifact_info.RECOVERY_IMAGE,
102 artifact_info.FULL_PAYLOAD,
103 artifact_info.STATEFUL_PAYLOAD,
104 artifact_info.AUTOTEST,
105]
106
joychen921e1fb2013-06-28 11:12:20 -0700107GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
108GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 12:13:13 -0700109
joychen921e1fb2013-06-28 11:12:20 -0700110LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 12:13:13 -0700111
Chris Sosaea734d92013-10-11 11:28:58 -0700112RELEASE = "-release"
joychen3cb228e2013-06-12 12:13:13 -0700113
joychen3cb228e2013-06-12 12:13:13 -0700114
115class XBuddyException(Exception):
116 """Exception classes used by this module."""
117 pass
118
119
120# no __init__ method
121#pylint: disable=W0232
122class Timestamp():
123 """Class to translate build path strings and timestamp filenames."""
124
125 _TIMESTAMP_DELIMITER = 'SLASH'
126 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
127
128 @staticmethod
129 def TimestampToBuild(timestamp_filename):
130 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
131
132 @staticmethod
133 def BuildToTimestamp(build_path):
134 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 11:12:20 -0700135
136 @staticmethod
137 def UpdateTimestamp(timestamp_dir, build_id):
138 """Update timestamp file of build with build_id."""
139 common_util.MkDirP(timestamp_dir)
joychen562699a2013-08-13 15:22:14 -0700140 _Log("Updating timestamp for %s", build_id)
joychen921e1fb2013-06-28 11:12:20 -0700141 time_file = os.path.join(timestamp_dir,
142 Timestamp.BuildToTimestamp(build_id))
143 with file(time_file, 'a'):
144 os.utime(time_file, None)
joychen3cb228e2013-06-12 12:13:13 -0700145#pylint: enable=W0232
146
147
joychen921e1fb2013-06-28 11:12:20 -0700148class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 12:13:13 -0700149 """Class that manages image retrieval and caching by the devserver.
150
151 Image retrieval by xBuddy path:
152 XBuddy accesses images and artifacts that it stores using an xBuddy
153 path of the form: board/version/alias
154 The primary xbuddy.Get call retrieves the correct artifact or url to where
155 the artifacts can be found.
156
157 Image caching:
158 Images and other artifacts are stored identically to how they would have
159 been if devserver's stage rpc was called and the xBuddy cache replaces
160 build versions on a LRU basis. Timestamps are maintained by last accessed
161 times of representative files in the a directory in the static serve
162 directory (XBUDDY_TIMESTAMP_DIR).
163
164 Private class members:
joychen121fc9b2013-08-02 14:30:30 -0700165 _true_values: used for interpreting boolean values
166 _staging_thread_count: track download requests
167 _timestamp_folder: directory with empty files standing in as timestamps
joychen921e1fb2013-06-28 11:12:20 -0700168 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 12:13:13 -0700169 """
170 _true_values = ['true', 't', 'yes', 'y']
171
172 # Number of threads that are staging images.
173 _staging_thread_count = 0
174 # Lock used to lock increasing/decreasing count.
175 _staging_thread_count_lock = threading.Lock()
176
Chris Sosa7cd23202013-10-15 17:22:57 -0700177 def __init__(self, manage_builds=False, board=None, images_dir=None,
178 **kwargs):
joychen921e1fb2013-06-28 11:12:20 -0700179 super(XBuddy, self).__init__(**kwargs)
joychenb0dfe552013-07-30 10:02:06 -0700180
joychen562699a2013-08-13 15:22:14 -0700181 self.config = self._ReadConfig()
182 self._manage_builds = manage_builds or self._ManageBuilds()
Chris Sosa75490802013-09-30 17:21:45 -0700183 self._board = board
joychen921e1fb2013-06-28 11:12:20 -0700184 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 12:13:13 -0700185 Timestamp.XBUDDY_TIMESTAMP_DIR)
Chris Sosa7cd23202013-10-15 17:22:57 -0700186 if images_dir:
187 self.images_dir = images_dir
188 else:
189 self.images_dir = os.path.join(self.GetSourceRoot(), 'src/build/images')
190
joychen7df67f72013-07-18 14:21:12 -0700191 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 12:13:13 -0700192
193 @classmethod
194 def ParseBoolean(cls, boolean_string):
195 """Evaluate a string to a boolean value"""
196 if boolean_string:
197 return boolean_string.lower() in cls._true_values
198 else:
199 return False
200
joychen562699a2013-08-13 15:22:14 -0700201 def _ReadConfig(self):
202 """Read xbuddy config from ini files.
203
204 Reads the base config from xbuddy_config.ini, and then merges in the
205 shadow config from shadow_xbuddy_config.ini
206
207 Returns:
208 The merged configuration.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800209
joychen562699a2013-08-13 15:22:14 -0700210 Raises:
211 XBuddyException if the config file is missing.
212 """
213 xbuddy_config = ConfigParser.ConfigParser()
214 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
215 if os.path.exists(config_file):
216 xbuddy_config.read(config_file)
217 else:
218 raise XBuddyException('%s not found' % (CONFIG_FILE))
219
220 # Read the shadow file if there is one.
Chris Sosac2abc722013-08-26 17:11:22 -0700221 if os.path.isdir(CHROOT_SHADOW_DIR):
222 shadow_config_file = os.path.join(CHROOT_SHADOW_DIR, SHADOW_CONFIG_FILE)
223 else:
224 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
225
226 _Log('Using shadow config file stored at %s', shadow_config_file)
joychen562699a2013-08-13 15:22:14 -0700227 if os.path.exists(shadow_config_file):
228 shadow_xbuddy_config = ConfigParser.ConfigParser()
229 shadow_xbuddy_config.read(shadow_config_file)
230
231 # Merge shadow config in.
232 sections = shadow_xbuddy_config.sections()
233 for s in sections:
234 if not xbuddy_config.has_section(s):
235 xbuddy_config.add_section(s)
236 options = shadow_xbuddy_config.options(s)
237 for o in options:
238 val = shadow_xbuddy_config.get(s, o)
239 xbuddy_config.set(s, o, val)
240
241 return xbuddy_config
242
243 def _ManageBuilds(self):
244 """Checks if xBuddy is managing local builds using the current config."""
245 try:
246 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
247 except ConfigParser.Error:
248 return False
249
250 def _Capacity(self):
251 """Gets the xbuddy capacity from the current config."""
252 try:
253 return int(self.config.get(GENERAL, 'capacity'))
254 except ConfigParser.Error:
255 return 5
256
257 def _LookupAlias(self, alias, board):
258 """Given the full xbuddy config, look up an alias for path rewrite.
259
260 Args:
261 alias: The xbuddy path that could be one of the aliases in the
262 rewrite table.
263 board: The board to fill in with when paths are rewritten. Can be from
264 the update request xml or the default board from devserver.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800265
joychen562699a2013-08-13 15:22:14 -0700266 Returns:
267 If a rewrite is found, a string with the current board substituted in.
268 If no rewrite is found, just return the original string.
269 """
joychen562699a2013-08-13 15:22:14 -0700270 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
Simran Basi99e63c02014-05-20 10:39:52 -0700286 @staticmethod
287 def _ResolveImageDir(image_dir):
288 """Clean up and return the image dir to use.
289
290 Args:
291 image_dir: directory in Google Storage to use.
292
293 Returns:
294 |image_dir| if |image_dir| is not None. Otherwise, returns
295 devserver_constants.GS_IMAGE_DIR
296 """
297 image_dir = image_dir or devserver_constants.GS_IMAGE_DIR
298 # Remove trailing slashes.
299 return image_dir.rstrip('/')
300
301 def _LookupOfficial(self, board, suffix=RELEASE, image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700302 """Check LATEST-master for the version number of interest."""
303 _Log("Checking gs for latest %s-%s image", board, suffix)
Simran Basi99e63c02014-05-20 10:39:52 -0700304 image_dir = XBuddy._ResolveImageDir(image_dir)
305 latest_addr = (devserver_constants.GS_LATEST_MASTER %
306 {'image_dir': image_dir,
307 'board': board,
308 'suffix': suffix})
joychenf8f07e22013-07-12 17:45:51 -0700309 cmd = 'gsutil cat %s' % latest_addr
310 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700311 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700312 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700313
joychenf8f07e22013-07-12 17:45:51 -0700314 return devserver_constants.IMAGE_DIR % {'board':board,
315 'suffix':suffix,
316 'version':version}
Simran Basi99e63c02014-05-20 10:39:52 -0700317 def _LookupChannel(self, board, channel='stable', image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700318 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700319 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700320 _Log("Checking channel '%s' for latest '%s' image", channel, board)
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800321 # Due to historical reasons, gs://chromeos-releases uses
322 # daisy-spring as opposed to the board name daisy_spring. Convert
323 # the board name for the lookup.
324 channel_dir = devserver_constants.GS_CHANNEL_DIR % {
325 'channel':channel,
326 'board':re.sub('_', '-', board)}
joychen562699a2013-08-13 15:22:14 -0700327 latest_version = gsutil_util.GetLatestVersionFromGSDir(
328 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700329
joychen121fc9b2013-08-02 14:30:30 -0700330 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700331 image_url = devserver_constants.IMAGE_DIR % {
332 'board':board,
333 'suffix':RELEASE,
334 'version':'R*' + latest_version}
Simran Basi99e63c02014-05-20 10:39:52 -0700335 image_dir = XBuddy._ResolveImageDir(image_dir)
336 gs_url = os.path.join(image_dir, image_url)
joychenf8f07e22013-07-12 17:45:51 -0700337
338 # There should only be one match on cros-image-archive.
Simran Basi99e63c02014-05-20 10:39:52 -0700339 full_version = gsutil_util.GetLatestVersionFromGSDir(gs_url)
joychenf8f07e22013-07-12 17:45:51 -0700340
341 return devserver_constants.IMAGE_DIR % {'board':board,
342 'suffix':RELEASE,
343 'version':full_version}
344
345 def _LookupVersion(self, board, version):
346 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700347 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700348 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
joychenf8f07e22013-07-12 17:45:51 -0700349 image_url = devserver_constants.IMAGE_DIR % {'board':board,
350 'suffix':RELEASE,
351 'version':version + '*'}
352 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
353
joychen121fc9b2013-08-02 14:30:30 -0700354 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700355 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
356 return devserver_constants.IMAGE_DIR % {'board':board,
357 'suffix':RELEASE,
358 'version':full_version}
359
Chris Sosaea734d92013-10-11 11:28:58 -0700360 def _RemoteBuildId(self, board, version):
361 """Returns the remote build_id for the given board and version.
362
363 Raises:
364 XBuddyException: If we failed to resolve the version to a valid build_id.
365 """
366 build_id_as_is = devserver_constants.IMAGE_DIR % {'board':board,
367 'suffix':'',
368 'version':version}
369 build_id_release = devserver_constants.IMAGE_DIR % {'board':board,
370 'suffix':RELEASE,
371 'version':version}
372 # Return the first path that exists. We assume that what the user typed
373 # is better than with a default suffix added i.e. x86-generic/blah is
374 # more valuable than x86-generic-release/blah.
375 for build_id in build_id_as_is, build_id_release:
376 cmd = 'gsutil ls %s/%s' % (devserver_constants.GS_IMAGE_DIR, build_id)
377 try:
378 version = gsutil_util.GSUtilRun(cmd, None)
379 return build_id
380 except gsutil_util.GSUtilError:
381 continue
382 else:
383 raise XBuddyException('Could not find remote build_id for %s %s' % (
384 board, version))
385
Simran Basi99e63c02014-05-20 10:39:52 -0700386 def _ResolveVersionToBuildId(self, board, version, image_dir=None):
joychen121fc9b2013-08-02 14:30:30 -0700387 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700388
389 Args:
390 board: as specified in the original call. (i.e. x86-generic, parrot)
391 version: as entered in the original call. can be
392 {TBD, 0. some custom alias as defined in a config file}
393 1. latest
394 2. latest-{channel}
395 3. latest-official-{board suffix}
396 4. version prefix (i.e. RX-Y.X, RX-Y, RX)
Simran Basi99e63c02014-05-20 10:39:52 -0700397 image_dir: image directory to check in Google Storage. If none,
398 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700399
400 Returns:
Chris Sosaea734d92013-10-11 11:28:58 -0700401 Location where the image dir is actually found on GS (build_id)
joychen3cb228e2013-06-12 12:13:13 -0700402
Chris Sosaea734d92013-10-11 11:28:58 -0700403 Raises:
404 XBuddyException: If we failed to resolve the version to a valid url.
joychen3cb228e2013-06-12 12:13:13 -0700405 """
joychenf8f07e22013-07-12 17:45:51 -0700406 # Only the last segment of the alias is variable relative to the rest.
407 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700408
joychenf8f07e22013-07-12 17:45:51 -0700409 if re.match(devserver_constants.VERSION_RE, version):
Chris Sosaea734d92013-10-11 11:28:58 -0700410 return self._RemoteBuildId(board, version)
joychenf8f07e22013-07-12 17:45:51 -0700411 elif version == LATEST_OFFICIAL:
412 # latest-official --> LATEST build in board-release
Simran Basi99e63c02014-05-20 10:39:52 -0700413 return self._LookupOfficial(board, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700414 elif version_tuple[0] == LATEST_OFFICIAL:
415 # latest-official-{suffix} --> LATEST build in board-{suffix}
Simran Basi99e63c02014-05-20 10:39:52 -0700416 return self._LookupOfficial(board, version_tuple[1], image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700417 elif version == LATEST:
418 # latest --> latest build on stable channel
Simran Basi99e63c02014-05-20 10:39:52 -0700419 return self._LookupChannel(board, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700420 elif version_tuple[0] == LATEST:
421 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
422 # latest-R* --> most recent qualifying build
423 return self._LookupVersion(board, version_tuple[1])
424 else:
425 # latest-{channel} --> latest build within that channel
Simran Basi99e63c02014-05-20 10:39:52 -0700426 return self._LookupChannel(board, version_tuple[1],
427 image_dir=image_dir)
joychen3cb228e2013-06-12 12:13:13 -0700428 else:
429 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700430 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700431
joychen5260b9a2013-07-16 14:48:01 -0700432 @staticmethod
433 def _Symlink(link, target):
434 """Symlinks link to target, and removes whatever link was there before."""
435 _Log("Linking to %s from %s", link, target)
436 if os.path.lexists(link):
437 os.unlink(link)
438 os.symlink(target, link)
439
joychen121fc9b2013-08-02 14:30:30 -0700440 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700441 """Get the version of the latest image built for board by build_image
442
443 Updates the symlink reference within the xBuddy static dir to point to
444 the real image dir in the local /build/images directory.
445
446 Args:
joychenc3944cb2013-08-19 10:42:07 -0700447 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700448
449 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700450 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700451
452 Raises:
453 XBuddyException if neither test nor dev image was found in latest built
454 directory.
joychen3cb228e2013-06-12 12:13:13 -0700455 """
joychen921e1fb2013-06-28 11:12:20 -0700456 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700457 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700458 raise XBuddyException('No builds found for %s. Did you run build_image?' %
459 board)
460
joychen121fc9b2013-08-02 14:30:30 -0700461 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700462 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700463
joychenc3944cb2013-08-19 10:42:07 -0700464 @staticmethod
465 def _FindAny(local_dir):
466 """Returns the image_type for ANY given the local_dir."""
joychenc3944cb2013-08-19 10:42:07 -0700467 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700468 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
469 # Prioritize test images over dev images.
joychenc3944cb2013-08-19 10:42:07 -0700470 if os.path.exists(test_image):
471 return 'test'
472
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700473 if os.path.exists(dev_image):
474 return 'dev'
475
joychenc3944cb2013-08-19 10:42:07 -0700476 raise XBuddyException('No images found in %s' % local_dir)
477
478 @staticmethod
Chris Sosa0eecf962014-02-03 14:14:39 -0800479 def _InterpretPath(path, default_board=None):
joychen121fc9b2013-08-02 14:30:30 -0700480 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700481
joychen121fc9b2013-08-02 14:30:30 -0700482 Args:
483 path: the path xBuddy Get was called with.
Chris Sosa0eecf962014-02-03 14:14:39 -0800484 default_board: board to use in case board isn't in path.
joychen3cb228e2013-06-12 12:13:13 -0700485
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800486 Returns:
Chris Sosa75490802013-09-30 17:21:45 -0700487 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 12:13:13 -0700488
489 Raises:
490 XBuddyException: if the path can't be resolved into valid components
491 """
joychen121fc9b2013-08-02 14:30:30 -0700492 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700493
Chris Sosa0eecf962014-02-03 14:14:39 -0800494 # Do the stuff that is well known first. We know that if paths have a
495 # image_type, it must be one of the GS/LOCAL aliases and it must be at the
496 # end. Similarly, local/remote are well-known and must start the path list.
497 is_local = True
498 if path_list and path_list[0] in (REMOTE, LOCAL):
499 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700500
Chris Sosa0eecf962014-02-03 14:14:39 -0800501 # Default image type is determined by remote vs. local.
502 if is_local:
503 image_type = ANY
504 else:
505 image_type = TEST
joychen7df67f72013-07-18 14:21:12 -0700506
Chris Sosa0eecf962014-02-03 14:14:39 -0800507 if path_list and path_list[-1] in GS_ALIASES + LOCAL_ALIASES:
508 image_type = path_list.pop(-1)
joychen3cb228e2013-06-12 12:13:13 -0700509
Chris Sosa0eecf962014-02-03 14:14:39 -0800510 # Now for the tricky part. We don't actually know at this point if the rest
511 # of the path is just a board | version (like R33-2341.0.0) or just a board
512 # or just a version. So we do our best to do the right thing.
513 board = default_board
514 version = LATEST
515 if len(path_list) == 1:
516 path = path_list.pop(0)
517 # If it's a version we know (contains latest), go for that, otherwise only
518 # treat it as a version if we were given an actual default board.
519 if LATEST in path or default_board is not None:
520 version = path
joychen7df67f72013-07-18 14:21:12 -0700521 else:
Chris Sosa0eecf962014-02-03 14:14:39 -0800522 board = path
joychen7df67f72013-07-18 14:21:12 -0700523
Chris Sosa0eecf962014-02-03 14:14:39 -0800524 elif len(path_list) == 2:
525 # Assumes board/version.
526 board = path_list.pop(0)
527 version = path_list.pop(0)
528
529 if path_list:
530 raise XBuddyException("Path isn't valid. Could not figure out how to "
531 "parse remaining components: %s." % path_list)
532
533 _Log("Get artifact '%s' with board %s and version %s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700534 image_type, board, version, is_local)
535
536 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700537
joychen921e1fb2013-06-28 11:12:20 -0700538 def _SyncRegistryWithBuildImages(self):
joychen5260b9a2013-07-16 14:48:01 -0700539 """ Crawl images_dir for build_ids of images generated from build_image.
540
541 This will find images and symlink them in xBuddy's static dir so that
542 xBuddy's cache can serve them.
543 If xBuddy's _manage_builds option is on, then a timestamp will also be
544 generated, and xBuddy will clear them from the directory they are in, as
545 necessary.
546 """
Yu-Ju Hong235d1b52014-04-16 11:01:47 -0700547 if not os.path.isdir(self.images_dir):
548 # Skip syncing if images_dir does not exist.
549 _Log('Cannot find %s; skip syncing image registry.', self.images_dir)
550 return
551
joychen921e1fb2013-06-28 11:12:20 -0700552 build_ids = []
553 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700554 # Ensure we have directories to track all boards in build/images
555 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700556 board_dir = os.path.join(self.images_dir, b)
557 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700558 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700559
joychen121fc9b2013-08-02 14:30:30 -0700560 # Check currently registered images.
joychen921e1fb2013-06-28 11:12:20 -0700561 for f in os.listdir(self._timestamp_folder):
562 build_id = Timestamp.TimestampToBuild(f)
563 if build_id in build_ids:
564 build_ids.remove(build_id)
565
joychen121fc9b2013-08-02 14:30:30 -0700566 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700567 for build_id in build_ids:
568 link = os.path.join(self.static_dir, build_id)
569 target = os.path.join(self.images_dir, build_id)
570 XBuddy._Symlink(link, target)
571 if self._manage_builds:
572 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700573
574 def _ListBuildTimes(self):
joychen3cb228e2013-06-12 12:13:13 -0700575 """ Returns the currently cached builds and their last access timestamp.
576
577 Returns:
578 list of tuples that matches xBuddy build/version to timestamps in long
579 """
joychen121fc9b2013-08-02 14:30:30 -0700580 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700581 build_dict = {}
582
joychen7df67f72013-07-18 14:21:12 -0700583 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700584 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
585 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700586 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700587 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700588 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
589 return return_tup
590
Chris Sosa75490802013-09-30 17:21:45 -0700591 def _Download(self, gs_url, artifacts):
592 """Download the artifacts from the given gs_url.
593
594 Raises:
595 build_artifact.ArtifactDownloadError: If we failed to download the
596 artifact.
597 """
joychen3cb228e2013-06-12 12:13:13 -0700598 with XBuddy._staging_thread_count_lock:
599 XBuddy._staging_thread_count += 1
600 try:
Chris Sosa75490802013-09-30 17:21:45 -0700601 _Log("Downloading %s from %s", artifacts, gs_url)
602 downloader.Downloader(self.static_dir, gs_url).Download(artifacts, [])
joychen3cb228e2013-06-12 12:13:13 -0700603 finally:
604 with XBuddy._staging_thread_count_lock:
605 XBuddy._staging_thread_count -= 1
606
Chris Sosa75490802013-09-30 17:21:45 -0700607 def CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700608 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700609 if not self._manage_builds:
610 return
joychen921e1fb2013-06-28 11:12:20 -0700611 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700612 _Log('In cache now: %s', cached_builds)
613
joychen562699a2013-08-13 15:22:14 -0700614 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700615 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700616 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700617
618 time_file = os.path.join(self._timestamp_folder,
619 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700620 os.unlink(time_file)
621 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700622 try:
joychen121fc9b2013-08-02 14:30:30 -0700623 # Handle symlinks, in the case of links to local builds if enabled.
624 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700625 target = os.readlink(clear_dir)
626 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700627
628 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700629 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700630 shutil.rmtree(target)
631 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700632 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700633 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700634
joychen121fc9b2013-08-02 14:30:30 -0700635 except Exception as err:
636 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700637
Simran Basi99e63c02014-05-20 10:39:52 -0700638 def _GetFromGS(self, build_id, image_type, image_dir=None):
Chris Sosa75490802013-09-30 17:21:45 -0700639 """Check if the artifact is available locally. Download from GS if not.
640
Simran Basi99e63c02014-05-20 10:39:52 -0700641 Args:
642 build_id: Path to the image or update directory on the devserver or
643 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
644 image_type: Image type to download. Look at aliases at top of file for
645 options.
646 image_dir: Google Storage image archive to search in if requesting a
647 remote artifact. If none uses the default bucket.
648
Chris Sosa75490802013-09-30 17:21:45 -0700649 Raises:
650 build_artifact.ArtifactDownloadError: If we failed to download the
651 artifact.
652 """
Simran Basi99e63c02014-05-20 10:39:52 -0700653 image_dir = XBuddy._ResolveImageDir(image_dir)
654 gs_url = os.path.join(image_dir, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700655
joychen121fc9b2013-08-02 14:30:30 -0700656 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700657 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700658 file_loc = os.path.join(self.static_dir, build_id, file_name)
659 cached = os.path.exists(file_loc)
660
joychen921e1fb2013-06-28 11:12:20 -0700661 if not cached:
Chris Sosa75490802013-09-30 17:21:45 -0700662 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
663 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 11:12:20 -0700664 else:
665 _Log('Image already cached.')
666
Simran Basi99e63c02014-05-20 10:39:52 -0700667 def _GetArtifact(self, path_list, board=None, lookup_only=False,
668 image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700669 """Interpret an xBuddy path and return directory/file_name to resource.
670
Chris Sosa75490802013-09-30 17:21:45 -0700671 Note board can be passed that in but by default if self._board is set,
672 that is used rather than board.
673
Simran Basi99e63c02014-05-20 10:39:52 -0700674 Args:
675 path_list: [board, version, alias] as split from the xbuddy call url.
676 board: Board whos artifacts we are looking for. If None, use the board
677 XBuddy was initialized to use.
678 lookup_only: If true just look up the artifact, if False stage it on
679 the devserver as well.
680 image_dir: Google Storage image archive to search in if requesting a
681 remote artifact. If none uses the default bucket.
682
joychen346531c2013-07-24 16:55:56 -0700683 Returns:
Simran Basi99e63c02014-05-20 10:39:52 -0700684 build_id: Path to the image or update directory on the devserver or
685 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
686 file_name: of the artifact in the build_id directory.
joychen346531c2013-07-24 16:55:56 -0700687
688 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700689 XBuddyException: if the path could not be translated
Chris Sosa75490802013-09-30 17:21:45 -0700690 build_artifact.ArtifactDownloadError: if we failed to download the
691 artifact.
joychen346531c2013-07-24 16:55:56 -0700692 """
joychen121fc9b2013-08-02 14:30:30 -0700693 path = '/'.join(path_list)
Chris Sosa0eecf962014-02-03 14:14:39 -0800694 default_board = self._board if self._board else board
joychenb0dfe552013-07-30 10:02:06 -0700695 # Rewrite the path if there is an appropriate default.
Chris Sosa0eecf962014-02-03 14:14:39 -0800696 path = self._LookupAlias(path, default_board)
joychen121fc9b2013-08-02 14:30:30 -0700697 # Parse the path.
Chris Sosa0eecf962014-02-03 14:14:39 -0800698 image_type, board, version, is_local = self._InterpretPath(
699 path, default_board)
joychen7df67f72013-07-18 14:21:12 -0700700 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700701 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700702 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700703 # Get the latest local image for the given board.
704 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700705
joychenc3944cb2013-08-19 10:42:07 -0700706 build_id = os.path.join(board, version)
707 artifact_dir = os.path.join(self.static_dir, build_id)
708 if image_type == ANY:
709 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700710
joychenc3944cb2013-08-19 10:42:07 -0700711 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
712 artifact_path = os.path.join(artifact_dir, file_name)
713 if not os.path.exists(artifact_path):
714 raise XBuddyException('Local %s artifact not in static_dir at %s' %
715 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700716
joychen921e1fb2013-06-28 11:12:20 -0700717 else:
joychen121fc9b2013-08-02 14:30:30 -0700718 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700719 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700720 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700721 (image_type, GS_ALIASES))
Simran Basi99e63c02014-05-20 10:39:52 -0700722 build_id = self._ResolveVersionToBuildId(board, version,
723 image_dir=image_dir)
Chris Sosa75490802013-09-30 17:21:45 -0700724 _Log('Resolved version %s to %s.', version, build_id)
725 file_name = GS_ALIAS_TO_FILENAME[image_type]
726 if not lookup_only:
Simran Basi99e63c02014-05-20 10:39:52 -0700727 self._GetFromGS(build_id, image_type, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700728
joychenc3944cb2013-08-19 10:42:07 -0700729 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700730
731 ############################ BEGIN PUBLIC METHODS
732
733 def List(self):
734 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700735 self._SyncRegistryWithBuildImages()
736 builds = self._ListBuildTimes()
737 return_string = ''
738 for build, timestamp in builds:
739 return_string += '<b>' + build + '</b> '
740 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
741 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700742
743 def Capacity(self):
744 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700745 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700746
Simran Basi99e63c02014-05-20 10:39:52 -0700747 def Translate(self, path_list, board=None, image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700748 """Translates an xBuddy path to a real path to artifact if it exists.
749
joychen121fc9b2013-08-02 14:30:30 -0700750 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700751
Simran Basi99e63c02014-05-20 10:39:52 -0700752 Args:
753 path_list: [board, version, alias] as split from the xbuddy call url.
754 board: Board whos artifacts we are looking for. If None, use the board
755 XBuddy was initialized to use.
756 image_dir: image directory to check in Google Storage. If none,
757 the default bucket is used.
758
joychen7c2054a2013-07-25 11:14:07 -0700759 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700760 build_id: Path to the image or update directory on the devserver.
761 e.g. 'x86-generic/R26-4000.0.0'
762 The returned path is always the path to the directory within
763 static_dir, so it is always the build_id of the image.
764 file_name: The file name of the artifact. Can take any of the file
765 values in devserver_constants.
766 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
767 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700768
joychen121fc9b2013-08-02 14:30:30 -0700769 Raises:
770 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700771 """
772 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700773 build_id, file_name = self._GetArtifact(path_list, board=board,
Simran Basi99e63c02014-05-20 10:39:52 -0700774 lookup_only=True,
775 image_dir=image_dir)
joychen346531c2013-07-24 16:55:56 -0700776
joychen121fc9b2013-08-02 14:30:30 -0700777 _Log('Returning path to payload: %s/%s', build_id, file_name)
778 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700779
Yu-Ju Hong1bdb7a92014-04-10 16:02:11 -0700780 def StageTestArtifactsForUpdate(self, path_list):
Chris Sosa75490802013-09-30 17:21:45 -0700781 """Stages test artifacts for update and returns build_id.
782
783 Raises:
784 XBuddyException: if the path could not be translated
785 build_artifact.ArtifactDownloadError: if we failed to download the test
786 artifacts.
787 """
788 build_id, file_name = self.Translate(path_list)
789 if file_name == devserver_constants.TEST_IMAGE_FILE:
790 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
791 build_id)
792 artifacts = [FULL, STATEFUL]
793 self._Download(gs_url, artifacts)
794 return build_id
795
Simran Basi99e63c02014-05-20 10:39:52 -0700796 def Get(self, path_list, image_dir=None):
joychen921e1fb2013-06-28 11:12:20 -0700797 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700798
799 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700800
joychen3cb228e2013-06-12 12:13:13 -0700801 Args:
Simran Basi99e63c02014-05-20 10:39:52 -0700802 path_list: [board, version, alias] as split from the xbuddy call url.
803 image_dir: image directory to check in Google Storage. If none,
804 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700805
806 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700807 build_id: Path to the image or update directory on the devserver.
Simran Basi99e63c02014-05-20 10:39:52 -0700808 e.g. 'x86-generic/R26-4000.0.0'
809 The returned path is always the path to the directory within
810 static_dir, so it is always the build_id of the image.
joychen121fc9b2013-08-02 14:30:30 -0700811 file_name: The file name of the artifact. Can take any of the file
Simran Basi99e63c02014-05-20 10:39:52 -0700812 values in devserver_constants.
813 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
814 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700815
816 Raises:
Chris Sosa75490802013-09-30 17:21:45 -0700817 XBuddyException: if the path could not be translated
818 build_artifact.ArtifactDownloadError: if we failed to download the
819 artifact.
joychen3cb228e2013-06-12 12:13:13 -0700820 """
joychen7df67f72013-07-18 14:21:12 -0700821 self._SyncRegistryWithBuildImages()
Simran Basi99e63c02014-05-20 10:39:52 -0700822 build_id, file_name = self._GetArtifact(path_list, image_dir=image_dir)
joychen921e1fb2013-06-28 11:12:20 -0700823 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700824 #TODO (joyc): run in sep thread
Chris Sosa75490802013-09-30 17:21:45 -0700825 self.CleanCache()
joychen3cb228e2013-06-12 12:13:13 -0700826
joychen121fc9b2013-08-02 14:30:30 -0700827 _Log('Returning path to payload: %s/%s', build_id, file_name)
828 return build_id, file_name