blob: fb85a2ad59e4deb6aa236aa49c3f73ae24034c7a [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,
Gabe Black0d3286e2014-07-30 15:30:03 -070063 RECOVERY,
joychenc3944cb2013-08-19 10:42:07 -070064 FULL,
Chris Sosa7cd23202013-10-15 17:22:57 -070065 STATEFUL,
joychenc3944cb2013-08-19 10:42:07 -070066 ANY,
joychen921e1fb2013-06-28 11:12:20 -070067]
68
69LOCAL_FILE_NAMES = [
70 devserver_constants.TEST_IMAGE_FILE,
joychen921e1fb2013-06-28 11:12:20 -070071 devserver_constants.IMAGE_FILE,
Chris Sosa75490802013-09-30 17:21:45 -070072 devserver_constants.BASE_IMAGE_FILE,
Gabe Black0d3286e2014-07-30 15:30:03 -070073 devserver_constants.RECOVERY_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070074 devserver_constants.UPDATE_FILE,
Chris Sosa7cd23202013-10-15 17:22:57 -070075 devserver_constants.STATEFUL_FILE,
Chris Sosa75490802013-09-30 17:21:45 -070076 None, # For ANY.
joychen921e1fb2013-06-28 11:12:20 -070077]
78
79LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
80
81# Google Storage constants
82GS_ALIASES = [
joychen25d25972013-07-30 14:54:16 -070083 TEST,
84 BASE,
85 RECOVERY,
86 FULL,
87 STATEFUL,
88 AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -070089]
90
joychen921e1fb2013-06-28 11:12:20 -070091GS_FILE_NAMES = [
92 devserver_constants.TEST_IMAGE_FILE,
93 devserver_constants.BASE_IMAGE_FILE,
94 devserver_constants.RECOVERY_IMAGE_FILE,
joychen7c2054a2013-07-25 11:14:07 -070095 devserver_constants.UPDATE_FILE,
joychen121fc9b2013-08-02 14:30:30 -070096 devserver_constants.STATEFUL_FILE,
joychen3cb228e2013-06-12 12:13:13 -070097 devserver_constants.AUTOTEST_DIR,
98]
99
100ARTIFACTS = [
101 artifact_info.TEST_IMAGE,
102 artifact_info.BASE_IMAGE,
103 artifact_info.RECOVERY_IMAGE,
104 artifact_info.FULL_PAYLOAD,
105 artifact_info.STATEFUL_PAYLOAD,
106 artifact_info.AUTOTEST,
107]
108
joychen921e1fb2013-06-28 11:12:20 -0700109GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
110GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 12:13:13 -0700111
joychen921e1fb2013-06-28 11:12:20 -0700112LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 12:13:13 -0700113
Chris Sosaea734d92013-10-11 11:28:58 -0700114RELEASE = "-release"
joychen3cb228e2013-06-12 12:13:13 -0700115
joychen3cb228e2013-06-12 12:13:13 -0700116
117class XBuddyException(Exception):
118 """Exception classes used by this module."""
119 pass
120
121
122# no __init__ method
123#pylint: disable=W0232
124class Timestamp():
125 """Class to translate build path strings and timestamp filenames."""
126
127 _TIMESTAMP_DELIMITER = 'SLASH'
128 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
129
130 @staticmethod
131 def TimestampToBuild(timestamp_filename):
132 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
133
134 @staticmethod
135 def BuildToTimestamp(build_path):
136 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 11:12:20 -0700137
138 @staticmethod
139 def UpdateTimestamp(timestamp_dir, build_id):
140 """Update timestamp file of build with build_id."""
141 common_util.MkDirP(timestamp_dir)
joychen562699a2013-08-13 15:22:14 -0700142 _Log("Updating timestamp for %s", build_id)
joychen921e1fb2013-06-28 11:12:20 -0700143 time_file = os.path.join(timestamp_dir,
144 Timestamp.BuildToTimestamp(build_id))
145 with file(time_file, 'a'):
146 os.utime(time_file, None)
joychen3cb228e2013-06-12 12:13:13 -0700147#pylint: enable=W0232
148
149
joychen921e1fb2013-06-28 11:12:20 -0700150class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 12:13:13 -0700151 """Class that manages image retrieval and caching by the devserver.
152
153 Image retrieval by xBuddy path:
154 XBuddy accesses images and artifacts that it stores using an xBuddy
155 path of the form: board/version/alias
156 The primary xbuddy.Get call retrieves the correct artifact or url to where
157 the artifacts can be found.
158
159 Image caching:
160 Images and other artifacts are stored identically to how they would have
161 been if devserver's stage rpc was called and the xBuddy cache replaces
162 build versions on a LRU basis. Timestamps are maintained by last accessed
163 times of representative files in the a directory in the static serve
164 directory (XBUDDY_TIMESTAMP_DIR).
165
166 Private class members:
joychen121fc9b2013-08-02 14:30:30 -0700167 _true_values: used for interpreting boolean values
168 _staging_thread_count: track download requests
169 _timestamp_folder: directory with empty files standing in as timestamps
joychen921e1fb2013-06-28 11:12:20 -0700170 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 12:13:13 -0700171 """
172 _true_values = ['true', 't', 'yes', 'y']
173
174 # Number of threads that are staging images.
175 _staging_thread_count = 0
176 # Lock used to lock increasing/decreasing count.
177 _staging_thread_count_lock = threading.Lock()
178
Chris Sosa7cd23202013-10-15 17:22:57 -0700179 def __init__(self, manage_builds=False, board=None, images_dir=None,
180 **kwargs):
joychen921e1fb2013-06-28 11:12:20 -0700181 super(XBuddy, self).__init__(**kwargs)
joychenb0dfe552013-07-30 10:02:06 -0700182
joychen562699a2013-08-13 15:22:14 -0700183 self.config = self._ReadConfig()
184 self._manage_builds = manage_builds or self._ManageBuilds()
Chris Sosa75490802013-09-30 17:21:45 -0700185 self._board = board
joychen921e1fb2013-06-28 11:12:20 -0700186 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 12:13:13 -0700187 Timestamp.XBUDDY_TIMESTAMP_DIR)
Chris Sosa7cd23202013-10-15 17:22:57 -0700188 if images_dir:
189 self.images_dir = images_dir
190 else:
191 self.images_dir = os.path.join(self.GetSourceRoot(), 'src/build/images')
192
joychen7df67f72013-07-18 14:21:12 -0700193 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 12:13:13 -0700194
195 @classmethod
196 def ParseBoolean(cls, boolean_string):
197 """Evaluate a string to a boolean value"""
198 if boolean_string:
199 return boolean_string.lower() in cls._true_values
200 else:
201 return False
202
joychen562699a2013-08-13 15:22:14 -0700203 def _ReadConfig(self):
204 """Read xbuddy config from ini files.
205
206 Reads the base config from xbuddy_config.ini, and then merges in the
207 shadow config from shadow_xbuddy_config.ini
208
209 Returns:
210 The merged configuration.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800211
joychen562699a2013-08-13 15:22:14 -0700212 Raises:
213 XBuddyException if the config file is missing.
214 """
215 xbuddy_config = ConfigParser.ConfigParser()
216 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
217 if os.path.exists(config_file):
218 xbuddy_config.read(config_file)
219 else:
220 raise XBuddyException('%s not found' % (CONFIG_FILE))
221
222 # Read the shadow file if there is one.
Chris Sosac2abc722013-08-26 17:11:22 -0700223 if os.path.isdir(CHROOT_SHADOW_DIR):
224 shadow_config_file = os.path.join(CHROOT_SHADOW_DIR, SHADOW_CONFIG_FILE)
225 else:
226 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
227
228 _Log('Using shadow config file stored at %s', shadow_config_file)
joychen562699a2013-08-13 15:22:14 -0700229 if os.path.exists(shadow_config_file):
230 shadow_xbuddy_config = ConfigParser.ConfigParser()
231 shadow_xbuddy_config.read(shadow_config_file)
232
233 # Merge shadow config in.
234 sections = shadow_xbuddy_config.sections()
235 for s in sections:
236 if not xbuddy_config.has_section(s):
237 xbuddy_config.add_section(s)
238 options = shadow_xbuddy_config.options(s)
239 for o in options:
240 val = shadow_xbuddy_config.get(s, o)
241 xbuddy_config.set(s, o, val)
242
243 return xbuddy_config
244
245 def _ManageBuilds(self):
246 """Checks if xBuddy is managing local builds using the current config."""
247 try:
248 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
249 except ConfigParser.Error:
250 return False
251
252 def _Capacity(self):
253 """Gets the xbuddy capacity from the current config."""
254 try:
255 return int(self.config.get(GENERAL, 'capacity'))
256 except ConfigParser.Error:
257 return 5
258
259 def _LookupAlias(self, alias, board):
260 """Given the full xbuddy config, look up an alias for path rewrite.
261
262 Args:
263 alias: The xbuddy path that could be one of the aliases in the
264 rewrite table.
265 board: The board to fill in with when paths are rewritten. Can be from
266 the update request xml or the default board from devserver.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800267
joychen562699a2013-08-13 15:22:14 -0700268 Returns:
269 If a rewrite is found, a string with the current board substituted in.
270 If no rewrite is found, just return the original string.
271 """
joychen562699a2013-08-13 15:22:14 -0700272 try:
273 val = self.config.get(PATH_REWRITES, alias)
274 except ConfigParser.Error:
275 # No alias lookup found. Return original path.
276 return alias
277
278 if not val.strip():
279 # The found value was an empty string.
280 return alias
281 else:
282 # Fill in the board.
joychenc3944cb2013-08-19 10:42:07 -0700283 rewrite = val.replace("BOARD", "%(board)s") % {
joychen562699a2013-08-13 15:22:14 -0700284 'board': board}
285 _Log("Path was rewritten to %s", rewrite)
286 return rewrite
287
Simran Basi99e63c02014-05-20 10:39:52 -0700288 @staticmethod
289 def _ResolveImageDir(image_dir):
290 """Clean up and return the image dir to use.
291
292 Args:
293 image_dir: directory in Google Storage to use.
294
295 Returns:
296 |image_dir| if |image_dir| is not None. Otherwise, returns
297 devserver_constants.GS_IMAGE_DIR
298 """
299 image_dir = image_dir or devserver_constants.GS_IMAGE_DIR
300 # Remove trailing slashes.
301 return image_dir.rstrip('/')
302
303 def _LookupOfficial(self, board, suffix=RELEASE, image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700304 """Check LATEST-master for the version number of interest."""
305 _Log("Checking gs for latest %s-%s image", board, suffix)
Simran Basi99e63c02014-05-20 10:39:52 -0700306 image_dir = XBuddy._ResolveImageDir(image_dir)
307 latest_addr = (devserver_constants.GS_LATEST_MASTER %
308 {'image_dir': image_dir,
309 'board': board,
310 'suffix': suffix})
joychenf8f07e22013-07-12 17:45:51 -0700311 cmd = 'gsutil cat %s' % latest_addr
312 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700313 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700314 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700315
joychenf8f07e22013-07-12 17:45:51 -0700316 return devserver_constants.IMAGE_DIR % {'board':board,
317 'suffix':suffix,
318 'version':version}
Simran Basi99e63c02014-05-20 10:39:52 -0700319 def _LookupChannel(self, board, channel='stable', image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700320 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700321 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700322 _Log("Checking channel '%s' for latest '%s' image", channel, board)
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800323 # Due to historical reasons, gs://chromeos-releases uses
324 # daisy-spring as opposed to the board name daisy_spring. Convert
325 # the board name for the lookup.
326 channel_dir = devserver_constants.GS_CHANNEL_DIR % {
327 'channel':channel,
328 'board':re.sub('_', '-', board)}
joychen562699a2013-08-13 15:22:14 -0700329 latest_version = gsutil_util.GetLatestVersionFromGSDir(
330 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700331
joychen121fc9b2013-08-02 14:30:30 -0700332 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700333 image_url = devserver_constants.IMAGE_DIR % {
334 'board':board,
335 'suffix':RELEASE,
336 'version':'R*' + latest_version}
Simran Basi99e63c02014-05-20 10:39:52 -0700337 image_dir = XBuddy._ResolveImageDir(image_dir)
338 gs_url = os.path.join(image_dir, image_url)
joychenf8f07e22013-07-12 17:45:51 -0700339
340 # There should only be one match on cros-image-archive.
Simran Basi99e63c02014-05-20 10:39:52 -0700341 full_version = gsutil_util.GetLatestVersionFromGSDir(gs_url)
joychenf8f07e22013-07-12 17:45:51 -0700342
343 return devserver_constants.IMAGE_DIR % {'board':board,
344 'suffix':RELEASE,
345 'version':full_version}
346
347 def _LookupVersion(self, board, version):
348 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700349 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700350 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
joychenf8f07e22013-07-12 17:45:51 -0700351 image_url = devserver_constants.IMAGE_DIR % {'board':board,
352 'suffix':RELEASE,
353 'version':version + '*'}
354 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
355
joychen121fc9b2013-08-02 14:30:30 -0700356 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700357 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
358 return devserver_constants.IMAGE_DIR % {'board':board,
359 'suffix':RELEASE,
360 'version':full_version}
361
Chris Sosaea734d92013-10-11 11:28:58 -0700362 def _RemoteBuildId(self, board, version):
363 """Returns the remote build_id for the given board and version.
364
365 Raises:
366 XBuddyException: If we failed to resolve the version to a valid build_id.
367 """
368 build_id_as_is = devserver_constants.IMAGE_DIR % {'board':board,
369 'suffix':'',
370 'version':version}
371 build_id_release = devserver_constants.IMAGE_DIR % {'board':board,
372 'suffix':RELEASE,
373 'version':version}
374 # Return the first path that exists. We assume that what the user typed
375 # is better than with a default suffix added i.e. x86-generic/blah is
376 # more valuable than x86-generic-release/blah.
377 for build_id in build_id_as_is, build_id_release:
378 cmd = 'gsutil ls %s/%s' % (devserver_constants.GS_IMAGE_DIR, build_id)
379 try:
380 version = gsutil_util.GSUtilRun(cmd, None)
381 return build_id
382 except gsutil_util.GSUtilError:
383 continue
384 else:
385 raise XBuddyException('Could not find remote build_id for %s %s' % (
386 board, version))
387
Simran Basi99e63c02014-05-20 10:39:52 -0700388 def _ResolveVersionToBuildId(self, board, version, image_dir=None):
joychen121fc9b2013-08-02 14:30:30 -0700389 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700390
391 Args:
392 board: as specified in the original call. (i.e. x86-generic, parrot)
393 version: as entered in the original call. can be
394 {TBD, 0. some custom alias as defined in a config file}
395 1. latest
396 2. latest-{channel}
397 3. latest-official-{board suffix}
398 4. version prefix (i.e. RX-Y.X, RX-Y, RX)
Simran Basi99e63c02014-05-20 10:39:52 -0700399 image_dir: image directory to check in Google Storage. If none,
400 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700401
402 Returns:
Chris Sosaea734d92013-10-11 11:28:58 -0700403 Location where the image dir is actually found on GS (build_id)
joychen3cb228e2013-06-12 12:13:13 -0700404
Chris Sosaea734d92013-10-11 11:28:58 -0700405 Raises:
406 XBuddyException: If we failed to resolve the version to a valid url.
joychen3cb228e2013-06-12 12:13:13 -0700407 """
joychenf8f07e22013-07-12 17:45:51 -0700408 # Only the last segment of the alias is variable relative to the rest.
409 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700410
joychenf8f07e22013-07-12 17:45:51 -0700411 if re.match(devserver_constants.VERSION_RE, version):
Chris Sosaea734d92013-10-11 11:28:58 -0700412 return self._RemoteBuildId(board, version)
joychenf8f07e22013-07-12 17:45:51 -0700413 elif version == LATEST_OFFICIAL:
414 # latest-official --> LATEST build in board-release
Simran Basi99e63c02014-05-20 10:39:52 -0700415 return self._LookupOfficial(board, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700416 elif version_tuple[0] == LATEST_OFFICIAL:
417 # latest-official-{suffix} --> LATEST build in board-{suffix}
Simran Basi99e63c02014-05-20 10:39:52 -0700418 return self._LookupOfficial(board, version_tuple[1], image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700419 elif version == LATEST:
420 # latest --> latest build on stable channel
Simran Basi99e63c02014-05-20 10:39:52 -0700421 return self._LookupChannel(board, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700422 elif version_tuple[0] == LATEST:
423 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
424 # latest-R* --> most recent qualifying build
425 return self._LookupVersion(board, version_tuple[1])
426 else:
427 # latest-{channel} --> latest build within that channel
Simran Basi99e63c02014-05-20 10:39:52 -0700428 return self._LookupChannel(board, version_tuple[1],
429 image_dir=image_dir)
joychen3cb228e2013-06-12 12:13:13 -0700430 else:
431 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700432 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700433
joychen5260b9a2013-07-16 14:48:01 -0700434 @staticmethod
435 def _Symlink(link, target):
436 """Symlinks link to target, and removes whatever link was there before."""
437 _Log("Linking to %s from %s", link, target)
438 if os.path.lexists(link):
439 os.unlink(link)
440 os.symlink(target, link)
441
joychen121fc9b2013-08-02 14:30:30 -0700442 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700443 """Get the version of the latest image built for board by build_image
444
445 Updates the symlink reference within the xBuddy static dir to point to
446 the real image dir in the local /build/images directory.
447
448 Args:
joychenc3944cb2013-08-19 10:42:07 -0700449 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700450
451 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700452 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700453
454 Raises:
455 XBuddyException if neither test nor dev image was found in latest built
456 directory.
joychen3cb228e2013-06-12 12:13:13 -0700457 """
joychen921e1fb2013-06-28 11:12:20 -0700458 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700459 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700460 raise XBuddyException('No builds found for %s. Did you run build_image?' %
461 board)
462
joychen121fc9b2013-08-02 14:30:30 -0700463 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700464 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700465
joychenc3944cb2013-08-19 10:42:07 -0700466 @staticmethod
467 def _FindAny(local_dir):
468 """Returns the image_type for ANY given the local_dir."""
joychenc3944cb2013-08-19 10:42:07 -0700469 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700470 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
471 # Prioritize test images over dev images.
joychenc3944cb2013-08-19 10:42:07 -0700472 if os.path.exists(test_image):
473 return 'test'
474
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700475 if os.path.exists(dev_image):
476 return 'dev'
477
joychenc3944cb2013-08-19 10:42:07 -0700478 raise XBuddyException('No images found in %s' % local_dir)
479
480 @staticmethod
Chris Sosa0eecf962014-02-03 14:14:39 -0800481 def _InterpretPath(path, default_board=None):
joychen121fc9b2013-08-02 14:30:30 -0700482 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700483
joychen121fc9b2013-08-02 14:30:30 -0700484 Args:
485 path: the path xBuddy Get was called with.
Chris Sosa0eecf962014-02-03 14:14:39 -0800486 default_board: board to use in case board isn't in path.
joychen3cb228e2013-06-12 12:13:13 -0700487
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800488 Returns:
Chris Sosa75490802013-09-30 17:21:45 -0700489 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 12:13:13 -0700490
491 Raises:
492 XBuddyException: if the path can't be resolved into valid components
493 """
joychen121fc9b2013-08-02 14:30:30 -0700494 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700495
Chris Sosa0eecf962014-02-03 14:14:39 -0800496 # Do the stuff that is well known first. We know that if paths have a
497 # image_type, it must be one of the GS/LOCAL aliases and it must be at the
498 # end. Similarly, local/remote are well-known and must start the path list.
499 is_local = True
500 if path_list and path_list[0] in (REMOTE, LOCAL):
501 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700502
Chris Sosa0eecf962014-02-03 14:14:39 -0800503 # Default image type is determined by remote vs. local.
504 if is_local:
505 image_type = ANY
506 else:
507 image_type = TEST
joychen7df67f72013-07-18 14:21:12 -0700508
Chris Sosa0eecf962014-02-03 14:14:39 -0800509 if path_list and path_list[-1] in GS_ALIASES + LOCAL_ALIASES:
510 image_type = path_list.pop(-1)
joychen3cb228e2013-06-12 12:13:13 -0700511
Chris Sosa0eecf962014-02-03 14:14:39 -0800512 # Now for the tricky part. We don't actually know at this point if the rest
513 # of the path is just a board | version (like R33-2341.0.0) or just a board
514 # or just a version. So we do our best to do the right thing.
515 board = default_board
516 version = LATEST
517 if len(path_list) == 1:
518 path = path_list.pop(0)
519 # If it's a version we know (contains latest), go for that, otherwise only
520 # treat it as a version if we were given an actual default board.
521 if LATEST in path or default_board is not None:
522 version = path
joychen7df67f72013-07-18 14:21:12 -0700523 else:
Chris Sosa0eecf962014-02-03 14:14:39 -0800524 board = path
joychen7df67f72013-07-18 14:21:12 -0700525
Chris Sosa0eecf962014-02-03 14:14:39 -0800526 elif len(path_list) == 2:
527 # Assumes board/version.
528 board = path_list.pop(0)
529 version = path_list.pop(0)
530
531 if path_list:
532 raise XBuddyException("Path isn't valid. Could not figure out how to "
533 "parse remaining components: %s." % path_list)
534
535 _Log("Get artifact '%s' with board %s and version %s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700536 image_type, board, version, is_local)
537
538 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700539
joychen921e1fb2013-06-28 11:12:20 -0700540 def _SyncRegistryWithBuildImages(self):
joychen5260b9a2013-07-16 14:48:01 -0700541 """ Crawl images_dir for build_ids of images generated from build_image.
542
543 This will find images and symlink them in xBuddy's static dir so that
544 xBuddy's cache can serve them.
545 If xBuddy's _manage_builds option is on, then a timestamp will also be
546 generated, and xBuddy will clear them from the directory they are in, as
547 necessary.
548 """
Yu-Ju Hong235d1b52014-04-16 11:01:47 -0700549 if not os.path.isdir(self.images_dir):
550 # Skip syncing if images_dir does not exist.
551 _Log('Cannot find %s; skip syncing image registry.', self.images_dir)
552 return
553
joychen921e1fb2013-06-28 11:12:20 -0700554 build_ids = []
555 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700556 # Ensure we have directories to track all boards in build/images
557 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700558 board_dir = os.path.join(self.images_dir, b)
559 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700560 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700561
joychen121fc9b2013-08-02 14:30:30 -0700562 # Check currently registered images.
joychen921e1fb2013-06-28 11:12:20 -0700563 for f in os.listdir(self._timestamp_folder):
564 build_id = Timestamp.TimestampToBuild(f)
565 if build_id in build_ids:
566 build_ids.remove(build_id)
567
joychen121fc9b2013-08-02 14:30:30 -0700568 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700569 for build_id in build_ids:
570 link = os.path.join(self.static_dir, build_id)
571 target = os.path.join(self.images_dir, build_id)
572 XBuddy._Symlink(link, target)
573 if self._manage_builds:
574 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700575
576 def _ListBuildTimes(self):
joychen3cb228e2013-06-12 12:13:13 -0700577 """ Returns the currently cached builds and their last access timestamp.
578
579 Returns:
580 list of tuples that matches xBuddy build/version to timestamps in long
581 """
joychen121fc9b2013-08-02 14:30:30 -0700582 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700583 build_dict = {}
584
joychen7df67f72013-07-18 14:21:12 -0700585 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700586 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
587 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700588 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700589 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700590 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
591 return return_tup
592
Chris Sosa75490802013-09-30 17:21:45 -0700593 def _Download(self, gs_url, artifacts):
594 """Download the artifacts from the given gs_url.
595
596 Raises:
597 build_artifact.ArtifactDownloadError: If we failed to download the
598 artifact.
599 """
joychen3cb228e2013-06-12 12:13:13 -0700600 with XBuddy._staging_thread_count_lock:
601 XBuddy._staging_thread_count += 1
602 try:
Chris Sosa75490802013-09-30 17:21:45 -0700603 _Log("Downloading %s from %s", artifacts, gs_url)
604 downloader.Downloader(self.static_dir, gs_url).Download(artifacts, [])
joychen3cb228e2013-06-12 12:13:13 -0700605 finally:
606 with XBuddy._staging_thread_count_lock:
607 XBuddy._staging_thread_count -= 1
608
Chris Sosa75490802013-09-30 17:21:45 -0700609 def CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700610 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700611 if not self._manage_builds:
612 return
joychen921e1fb2013-06-28 11:12:20 -0700613 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700614 _Log('In cache now: %s', cached_builds)
615
joychen562699a2013-08-13 15:22:14 -0700616 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700617 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700618 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700619
620 time_file = os.path.join(self._timestamp_folder,
621 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700622 os.unlink(time_file)
623 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700624 try:
joychen121fc9b2013-08-02 14:30:30 -0700625 # Handle symlinks, in the case of links to local builds if enabled.
626 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700627 target = os.readlink(clear_dir)
628 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700629
630 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700631 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700632 shutil.rmtree(target)
633 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700634 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700635 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700636
joychen121fc9b2013-08-02 14:30:30 -0700637 except Exception as err:
638 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700639
Simran Basi99e63c02014-05-20 10:39:52 -0700640 def _GetFromGS(self, build_id, image_type, image_dir=None):
Chris Sosa75490802013-09-30 17:21:45 -0700641 """Check if the artifact is available locally. Download from GS if not.
642
Simran Basi99e63c02014-05-20 10:39:52 -0700643 Args:
644 build_id: Path to the image or update directory on the devserver or
645 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
646 image_type: Image type to download. Look at aliases at top of file for
647 options.
648 image_dir: Google Storage image archive to search in if requesting a
649 remote artifact. If none uses the default bucket.
650
Chris Sosa75490802013-09-30 17:21:45 -0700651 Raises:
652 build_artifact.ArtifactDownloadError: If we failed to download the
653 artifact.
654 """
Simran Basi99e63c02014-05-20 10:39:52 -0700655 image_dir = XBuddy._ResolveImageDir(image_dir)
656 gs_url = os.path.join(image_dir, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700657
joychen121fc9b2013-08-02 14:30:30 -0700658 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700659 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700660 file_loc = os.path.join(self.static_dir, build_id, file_name)
661 cached = os.path.exists(file_loc)
662
joychen921e1fb2013-06-28 11:12:20 -0700663 if not cached:
Chris Sosa75490802013-09-30 17:21:45 -0700664 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
665 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 11:12:20 -0700666 else:
667 _Log('Image already cached.')
668
Simran Basi99e63c02014-05-20 10:39:52 -0700669 def _GetArtifact(self, path_list, board=None, lookup_only=False,
670 image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700671 """Interpret an xBuddy path and return directory/file_name to resource.
672
Chris Sosa75490802013-09-30 17:21:45 -0700673 Note board can be passed that in but by default if self._board is set,
674 that is used rather than board.
675
Simran Basi99e63c02014-05-20 10:39:52 -0700676 Args:
677 path_list: [board, version, alias] as split from the xbuddy call url.
678 board: Board whos artifacts we are looking for. If None, use the board
679 XBuddy was initialized to use.
680 lookup_only: If true just look up the artifact, if False stage it on
681 the devserver as well.
682 image_dir: Google Storage image archive to search in if requesting a
683 remote artifact. If none uses the default bucket.
684
joychen346531c2013-07-24 16:55:56 -0700685 Returns:
Simran Basi99e63c02014-05-20 10:39:52 -0700686 build_id: Path to the image or update directory on the devserver or
687 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
688 file_name: of the artifact in the build_id directory.
joychen346531c2013-07-24 16:55:56 -0700689
690 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700691 XBuddyException: if the path could not be translated
Chris Sosa75490802013-09-30 17:21:45 -0700692 build_artifact.ArtifactDownloadError: if we failed to download the
693 artifact.
joychen346531c2013-07-24 16:55:56 -0700694 """
joychen121fc9b2013-08-02 14:30:30 -0700695 path = '/'.join(path_list)
Chris Sosa0eecf962014-02-03 14:14:39 -0800696 default_board = self._board if self._board else board
joychenb0dfe552013-07-30 10:02:06 -0700697 # Rewrite the path if there is an appropriate default.
Chris Sosa0eecf962014-02-03 14:14:39 -0800698 path = self._LookupAlias(path, default_board)
joychen121fc9b2013-08-02 14:30:30 -0700699 # Parse the path.
Chris Sosa0eecf962014-02-03 14:14:39 -0800700 image_type, board, version, is_local = self._InterpretPath(
701 path, default_board)
joychen7df67f72013-07-18 14:21:12 -0700702 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700703 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700704 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700705 # Get the latest local image for the given board.
706 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700707
joychenc3944cb2013-08-19 10:42:07 -0700708 build_id = os.path.join(board, version)
709 artifact_dir = os.path.join(self.static_dir, build_id)
710 if image_type == ANY:
711 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700712
joychenc3944cb2013-08-19 10:42:07 -0700713 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
714 artifact_path = os.path.join(artifact_dir, file_name)
715 if not os.path.exists(artifact_path):
716 raise XBuddyException('Local %s artifact not in static_dir at %s' %
717 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700718
joychen921e1fb2013-06-28 11:12:20 -0700719 else:
joychen121fc9b2013-08-02 14:30:30 -0700720 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700721 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700722 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700723 (image_type, GS_ALIASES))
Simran Basi99e63c02014-05-20 10:39:52 -0700724 build_id = self._ResolveVersionToBuildId(board, version,
725 image_dir=image_dir)
Chris Sosa75490802013-09-30 17:21:45 -0700726 _Log('Resolved version %s to %s.', version, build_id)
727 file_name = GS_ALIAS_TO_FILENAME[image_type]
728 if not lookup_only:
Simran Basi99e63c02014-05-20 10:39:52 -0700729 self._GetFromGS(build_id, image_type, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700730
joychenc3944cb2013-08-19 10:42:07 -0700731 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700732
733 ############################ BEGIN PUBLIC METHODS
734
735 def List(self):
736 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700737 self._SyncRegistryWithBuildImages()
738 builds = self._ListBuildTimes()
739 return_string = ''
740 for build, timestamp in builds:
741 return_string += '<b>' + build + '</b> '
742 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
743 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700744
745 def Capacity(self):
746 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700747 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700748
Simran Basi99e63c02014-05-20 10:39:52 -0700749 def Translate(self, path_list, board=None, image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700750 """Translates an xBuddy path to a real path to artifact if it exists.
751
joychen121fc9b2013-08-02 14:30:30 -0700752 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700753
Simran Basi99e63c02014-05-20 10:39:52 -0700754 Args:
755 path_list: [board, version, alias] as split from the xbuddy call url.
756 board: Board whos artifacts we are looking for. If None, use the board
757 XBuddy was initialized to use.
758 image_dir: image directory to check in Google Storage. If none,
759 the default bucket is used.
760
joychen7c2054a2013-07-25 11:14:07 -0700761 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700762 build_id: Path to the image or update directory on the devserver.
763 e.g. 'x86-generic/R26-4000.0.0'
764 The returned path is always the path to the directory within
765 static_dir, so it is always the build_id of the image.
766 file_name: The file name of the artifact. Can take any of the file
767 values in devserver_constants.
768 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
769 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700770
joychen121fc9b2013-08-02 14:30:30 -0700771 Raises:
772 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700773 """
774 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700775 build_id, file_name = self._GetArtifact(path_list, board=board,
Simran Basi99e63c02014-05-20 10:39:52 -0700776 lookup_only=True,
777 image_dir=image_dir)
joychen346531c2013-07-24 16:55:56 -0700778
joychen121fc9b2013-08-02 14:30:30 -0700779 _Log('Returning path to payload: %s/%s', build_id, file_name)
780 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700781
Yu-Ju Hong1bdb7a92014-04-10 16:02:11 -0700782 def StageTestArtifactsForUpdate(self, path_list):
Chris Sosa75490802013-09-30 17:21:45 -0700783 """Stages test artifacts for update and returns build_id.
784
785 Raises:
786 XBuddyException: if the path could not be translated
787 build_artifact.ArtifactDownloadError: if we failed to download the test
788 artifacts.
789 """
790 build_id, file_name = self.Translate(path_list)
791 if file_name == devserver_constants.TEST_IMAGE_FILE:
792 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
793 build_id)
794 artifacts = [FULL, STATEFUL]
795 self._Download(gs_url, artifacts)
796 return build_id
797
Simran Basi99e63c02014-05-20 10:39:52 -0700798 def Get(self, path_list, image_dir=None):
joychen921e1fb2013-06-28 11:12:20 -0700799 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700800
801 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700802
joychen3cb228e2013-06-12 12:13:13 -0700803 Args:
Simran Basi99e63c02014-05-20 10:39:52 -0700804 path_list: [board, version, alias] as split from the xbuddy call url.
805 image_dir: image directory to check in Google Storage. If none,
806 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700807
808 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700809 build_id: Path to the image or update directory on the devserver.
Simran Basi99e63c02014-05-20 10:39:52 -0700810 e.g. 'x86-generic/R26-4000.0.0'
811 The returned path is always the path to the directory within
812 static_dir, so it is always the build_id of the image.
joychen121fc9b2013-08-02 14:30:30 -0700813 file_name: The file name of the artifact. Can take any of the file
Simran Basi99e63c02014-05-20 10:39:52 -0700814 values in devserver_constants.
815 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
816 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700817
818 Raises:
Chris Sosa75490802013-09-30 17:21:45 -0700819 XBuddyException: if the path could not be translated
820 build_artifact.ArtifactDownloadError: if we failed to download the
821 artifact.
joychen3cb228e2013-06-12 12:13:13 -0700822 """
joychen7df67f72013-07-18 14:21:12 -0700823 self._SyncRegistryWithBuildImages()
Simran Basi99e63c02014-05-20 10:39:52 -0700824 build_id, file_name = self._GetArtifact(path_list, image_dir=image_dir)
joychen921e1fb2013-06-28 11:12:20 -0700825 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700826 #TODO (joyc): run in sep thread
Chris Sosa75490802013-09-30 17:21:45 -0700827 self.CleanCache()
joychen3cb228e2013-06-12 12:13:13 -0700828
joychen121fc9b2013-08-02 14:30:30 -0700829 _Log('Returning path to payload: %s/%s', build_id, file_name)
830 return build_id, file_name