blob: 26ea11f4ba6c01ae2ffa5b0f36ccc8443f782bff [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
Gilad Arnold5f46d8e2015-02-19 12:17:55 -08007from __future__ import print_function
8
Yiming Chenaab488e2014-11-17 14:49:31 -08009import cherrypy
joychen562699a2013-08-13 15:22:14 -070010import ConfigParser
joychen3cb228e2013-06-12 12:13:13 -070011import datetime
12import operator
13import os
joychenf8f07e22013-07-12 17:45:51 -070014import re
joychen3cb228e2013-06-12 12:13:13 -070015import shutil
joychenf8f07e22013-07-12 17:45:51 -070016import time
joychen3cb228e2013-06-12 12:13:13 -070017import threading
18
19import artifact_info
Gabe Black3b567202015-09-23 14:07:59 -070020import build_artifact
21import build_util
joychen3cb228e2013-06-12 12:13:13 -070022import common_util
23import devserver_constants
24import downloader
joychenf8f07e22013-07-12 17:45:51 -070025import gsutil_util
joychen3cb228e2013-06-12 12:13:13 -070026import log_util
27
28# Module-local log function.
29def _Log(message, *args):
30 return log_util.LogWithTag('XBUDDY', message, *args)
31
joychen562699a2013-08-13 15:22:14 -070032# xBuddy config constants
33CONFIG_FILE = 'xbuddy_config.ini'
34SHADOW_CONFIG_FILE = 'shadow_xbuddy_config.ini'
35PATH_REWRITES = 'PATH_REWRITES'
36GENERAL = 'GENERAL'
Gilad Arnold896c6d82015-03-13 16:20:29 -070037LOCATION_SUFFIXES = 'LOCATION_SUFFIXES'
joychen921e1fb2013-06-28 11:12:20 -070038
Chris Sosac2abc722013-08-26 17:11:22 -070039# Path for shadow config in chroot.
40CHROOT_SHADOW_DIR = '/mnt/host/source/src/platform/dev'
41
joychen25d25972013-07-30 14:54:16 -070042# XBuddy aliases
43TEST = 'test'
44BASE = 'base'
45DEV = 'dev'
46FULL = 'full_payload'
47RECOVERY = 'recovery'
48STATEFUL = 'stateful'
49AUTOTEST = 'autotest'
50
joychen921e1fb2013-06-28 11:12:20 -070051# Local build constants
joychenc3944cb2013-08-19 10:42:07 -070052ANY = "ANY"
joychen7df67f72013-07-18 14:21:12 -070053LATEST = "latest"
54LOCAL = "local"
55REMOTE = "remote"
Chris Sosa75490802013-09-30 17:21:45 -070056
57# TODO(sosa): Fix a lot of assumptions about these aliases. There is too much
58# implicit logic here that's unnecessary. What should be done:
59# 1) Collapse Alias logic to one set of aliases for xbuddy (not local/remote).
60# 2) Do not use zip when creating these dicts. Better to not rely on ordering.
61# 3) Move alias/artifact mapping to a central module rather than having it here.
62# 4) Be explicit when things are missing i.e. no dev images in image.zip.
63
joychen921e1fb2013-06-28 11:12:20 -070064LOCAL_ALIASES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080065 TEST,
66 DEV,
67 BASE,
68 RECOVERY,
69 FULL,
70 STATEFUL,
71 ANY,
joychen921e1fb2013-06-28 11:12:20 -070072]
73
74LOCAL_FILE_NAMES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080075 devserver_constants.TEST_IMAGE_FILE,
76 devserver_constants.IMAGE_FILE,
77 devserver_constants.BASE_IMAGE_FILE,
78 devserver_constants.RECOVERY_IMAGE_FILE,
79 devserver_constants.UPDATE_FILE,
80 devserver_constants.STATEFUL_FILE,
81 None, # For ANY.
joychen921e1fb2013-06-28 11:12:20 -070082]
83
84LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
85
86# Google Storage constants
87GS_ALIASES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080088 TEST,
89 BASE,
90 RECOVERY,
91 FULL,
92 STATEFUL,
93 AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -070094]
95
joychen921e1fb2013-06-28 11:12:20 -070096GS_FILE_NAMES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080097 devserver_constants.TEST_IMAGE_FILE,
98 devserver_constants.BASE_IMAGE_FILE,
99 devserver_constants.RECOVERY_IMAGE_FILE,
100 devserver_constants.UPDATE_FILE,
101 devserver_constants.STATEFUL_FILE,
102 devserver_constants.AUTOTEST_DIR,
joychen3cb228e2013-06-12 12:13:13 -0700103]
104
105ARTIFACTS = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800106 artifact_info.TEST_IMAGE,
107 artifact_info.BASE_IMAGE,
108 artifact_info.RECOVERY_IMAGE,
109 artifact_info.FULL_PAYLOAD,
110 artifact_info.STATEFUL_PAYLOAD,
111 artifact_info.AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -0700112]
113
joychen921e1fb2013-06-28 11:12:20 -0700114GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
115GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 12:13:13 -0700116
joychen921e1fb2013-06-28 11:12:20 -0700117LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 12:13:13 -0700118
Chris Sosaea734d92013-10-11 11:28:58 -0700119RELEASE = "-release"
joychen3cb228e2013-06-12 12:13:13 -0700120
joychen3cb228e2013-06-12 12:13:13 -0700121
122class XBuddyException(Exception):
123 """Exception classes used by this module."""
124 pass
125
126
127# no __init__ method
128#pylint: disable=W0232
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800129class Timestamp(object):
joychen3cb228e2013-06-12 12:13:13 -0700130 """Class to translate build path strings and timestamp filenames."""
131
132 _TIMESTAMP_DELIMITER = 'SLASH'
133 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
134
135 @staticmethod
136 def TimestampToBuild(timestamp_filename):
137 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
138
139 @staticmethod
140 def BuildToTimestamp(build_path):
141 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 11:12:20 -0700142
143 @staticmethod
144 def UpdateTimestamp(timestamp_dir, build_id):
145 """Update timestamp file of build with build_id."""
146 common_util.MkDirP(timestamp_dir)
joychen562699a2013-08-13 15:22:14 -0700147 _Log("Updating timestamp for %s", build_id)
joychen921e1fb2013-06-28 11:12:20 -0700148 time_file = os.path.join(timestamp_dir,
149 Timestamp.BuildToTimestamp(build_id))
150 with file(time_file, 'a'):
151 os.utime(time_file, None)
joychen3cb228e2013-06-12 12:13:13 -0700152#pylint: enable=W0232
153
154
joychen921e1fb2013-06-28 11:12:20 -0700155class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 12:13:13 -0700156 """Class that manages image retrieval and caching by the devserver.
157
158 Image retrieval by xBuddy path:
159 XBuddy accesses images and artifacts that it stores using an xBuddy
160 path of the form: board/version/alias
161 The primary xbuddy.Get call retrieves the correct artifact or url to where
162 the artifacts can be found.
163
164 Image caching:
165 Images and other artifacts are stored identically to how they would have
166 been if devserver's stage rpc was called and the xBuddy cache replaces
167 build versions on a LRU basis. Timestamps are maintained by last accessed
168 times of representative files in the a directory in the static serve
169 directory (XBUDDY_TIMESTAMP_DIR).
170
171 Private class members:
joychen121fc9b2013-08-02 14:30:30 -0700172 _true_values: used for interpreting boolean values
173 _staging_thread_count: track download requests
174 _timestamp_folder: directory with empty files standing in as timestamps
joychen921e1fb2013-06-28 11:12:20 -0700175 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 12:13:13 -0700176 """
177 _true_values = ['true', 't', 'yes', 'y']
178
179 # Number of threads that are staging images.
180 _staging_thread_count = 0
181 # Lock used to lock increasing/decreasing count.
182 _staging_thread_count_lock = threading.Lock()
183
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800184 def __init__(self, manage_builds=False, board=None, version=None,
185 images_dir=None, log_screen=True, **kwargs):
joychen921e1fb2013-06-28 11:12:20 -0700186 super(XBuddy, self).__init__(**kwargs)
joychenb0dfe552013-07-30 10:02:06 -0700187
Yiming Chenaab488e2014-11-17 14:49:31 -0800188 if not log_screen:
189 cherrypy.config.update({'log.screen': False})
190
joychen562699a2013-08-13 15:22:14 -0700191 self.config = self._ReadConfig()
192 self._manage_builds = manage_builds or self._ManageBuilds()
Chris Sosa75490802013-09-30 17:21:45 -0700193 self._board = board
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800194 self._version = version
joychen921e1fb2013-06-28 11:12:20 -0700195 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 12:13:13 -0700196 Timestamp.XBUDDY_TIMESTAMP_DIR)
Chris Sosa7cd23202013-10-15 17:22:57 -0700197 if images_dir:
198 self.images_dir = images_dir
199 else:
200 self.images_dir = os.path.join(self.GetSourceRoot(), 'src/build/images')
201
joychen7df67f72013-07-18 14:21:12 -0700202 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 12:13:13 -0700203
204 @classmethod
205 def ParseBoolean(cls, boolean_string):
206 """Evaluate a string to a boolean value"""
207 if boolean_string:
208 return boolean_string.lower() in cls._true_values
209 else:
210 return False
211
joychen562699a2013-08-13 15:22:14 -0700212 def _ReadConfig(self):
213 """Read xbuddy config from ini files.
214
215 Reads the base config from xbuddy_config.ini, and then merges in the
216 shadow config from shadow_xbuddy_config.ini
217
218 Returns:
219 The merged configuration.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800220
joychen562699a2013-08-13 15:22:14 -0700221 Raises:
222 XBuddyException if the config file is missing.
223 """
224 xbuddy_config = ConfigParser.ConfigParser()
225 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
226 if os.path.exists(config_file):
227 xbuddy_config.read(config_file)
228 else:
Yiming Chend9202142014-11-07 14:56:52 -0800229 # Get the directory of xbuddy.py file.
230 file_dir = os.path.dirname(os.path.realpath(__file__))
231 # Read the default xbuddy_config.ini from the directory.
232 xbuddy_config.read(os.path.join(file_dir, CONFIG_FILE))
joychen562699a2013-08-13 15:22:14 -0700233
234 # Read the shadow file if there is one.
Chris Sosac2abc722013-08-26 17:11:22 -0700235 if os.path.isdir(CHROOT_SHADOW_DIR):
236 shadow_config_file = os.path.join(CHROOT_SHADOW_DIR, SHADOW_CONFIG_FILE)
237 else:
238 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
239
240 _Log('Using shadow config file stored at %s', shadow_config_file)
joychen562699a2013-08-13 15:22:14 -0700241 if os.path.exists(shadow_config_file):
242 shadow_xbuddy_config = ConfigParser.ConfigParser()
243 shadow_xbuddy_config.read(shadow_config_file)
244
245 # Merge shadow config in.
246 sections = shadow_xbuddy_config.sections()
247 for s in sections:
248 if not xbuddy_config.has_section(s):
249 xbuddy_config.add_section(s)
250 options = shadow_xbuddy_config.options(s)
251 for o in options:
252 val = shadow_xbuddy_config.get(s, o)
253 xbuddy_config.set(s, o, val)
254
255 return xbuddy_config
256
257 def _ManageBuilds(self):
258 """Checks if xBuddy is managing local builds using the current config."""
259 try:
260 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
261 except ConfigParser.Error:
262 return False
263
264 def _Capacity(self):
265 """Gets the xbuddy capacity from the current config."""
266 try:
267 return int(self.config.get(GENERAL, 'capacity'))
268 except ConfigParser.Error:
269 return 5
270
Gilad Arnold38e828c2015-04-24 13:52:07 -0700271 def LookupAlias(self, alias, board=None, version=None):
joychen562699a2013-08-13 15:22:14 -0700272 """Given the full xbuddy config, look up an alias for path rewrite.
273
274 Args:
275 alias: The xbuddy path that could be one of the aliases in the
276 rewrite table.
277 board: The board to fill in with when paths are rewritten. Can be from
Gilad Arnold38e828c2015-04-24 13:52:07 -0700278 the update request xml or the default board from devserver. If None,
279 defers to the value given during XBuddy initialization.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800280 version: The version to fill in when rewriting paths. Could be a specific
Gilad Arnold38e828c2015-04-24 13:52:07 -0700281 version number or a version alias like LATEST. If None, defers to the
282 value given during XBuddy initialization, or LATEST.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800283
joychen562699a2013-08-13 15:22:14 -0700284 Returns:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700285 A pair (val, suffix) where val is the rewritten path, or the original
286 string if no rewrite was found; and suffix is the assigned location
287 suffix, or the default suffix if none was found.
joychen562699a2013-08-13 15:22:14 -0700288 """
joychen562699a2013-08-13 15:22:14 -0700289 try:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700290 suffix = self.config.get(LOCATION_SUFFIXES, alias)
291 except ConfigParser.Error:
292 suffix = RELEASE
293
294 try:
joychen562699a2013-08-13 15:22:14 -0700295 val = self.config.get(PATH_REWRITES, alias)
296 except ConfigParser.Error:
297 # No alias lookup found. Return original path.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700298 val = None
joychen562699a2013-08-13 15:22:14 -0700299
Gilad Arnold896c6d82015-03-13 16:20:29 -0700300 if not (val and val.strip()):
301 val = alias
joychen562699a2013-08-13 15:22:14 -0700302 else:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700303 # The found value is not an empty string.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800304 # Fill in the board and version.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700305 val = val.replace("BOARD", "%(board)s")
306 val = val.replace("VERSION", "%(version)s")
Gilad Arnold38e828c2015-04-24 13:52:07 -0700307 val = val % {'board': board or self._board,
308 'version': version or self._version or LATEST}
Gilad Arnold896c6d82015-03-13 16:20:29 -0700309
310 _Log("Path is %s, location suffix is %s", val, suffix)
311 return val, suffix
joychen562699a2013-08-13 15:22:14 -0700312
Simran Basi99e63c02014-05-20 10:39:52 -0700313 @staticmethod
314 def _ResolveImageDir(image_dir):
315 """Clean up and return the image dir to use.
316
317 Args:
318 image_dir: directory in Google Storage to use.
319
320 Returns:
321 |image_dir| if |image_dir| is not None. Otherwise, returns
322 devserver_constants.GS_IMAGE_DIR
323 """
324 image_dir = image_dir or devserver_constants.GS_IMAGE_DIR
325 # Remove trailing slashes.
326 return image_dir.rstrip('/')
327
Gilad Arnold896c6d82015-03-13 16:20:29 -0700328 def _LookupOfficial(self, board, suffix, image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700329 """Check LATEST-master for the version number of interest."""
330 _Log("Checking gs for latest %s-%s image", board, suffix)
Simran Basi99e63c02014-05-20 10:39:52 -0700331 image_dir = XBuddy._ResolveImageDir(image_dir)
332 latest_addr = (devserver_constants.GS_LATEST_MASTER %
333 {'image_dir': image_dir,
334 'board': board,
335 'suffix': suffix})
joychenf8f07e22013-07-12 17:45:51 -0700336 cmd = 'gsutil cat %s' % latest_addr
337 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700338 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700339 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700340
joychenf8f07e22013-07-12 17:45:51 -0700341 return devserver_constants.IMAGE_DIR % {'board':board,
342 'suffix':suffix,
343 'version':version}
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800344
Gilad Arnold896c6d82015-03-13 16:20:29 -0700345 def _LookupChannel(self, board, suffix, channel='stable',
346 image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700347 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700348 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700349 _Log("Checking channel '%s' for latest '%s' image", channel, board)
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800350 # Due to historical reasons, gs://chromeos-releases uses
351 # daisy-spring as opposed to the board name daisy_spring. Convert
352 # the board name for the lookup.
353 channel_dir = devserver_constants.GS_CHANNEL_DIR % {
354 'channel':channel,
355 'board':re.sub('_', '-', board)}
joychen562699a2013-08-13 15:22:14 -0700356 latest_version = gsutil_util.GetLatestVersionFromGSDir(
357 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700358
joychen121fc9b2013-08-02 14:30:30 -0700359 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700360 image_url = devserver_constants.IMAGE_DIR % {
Gilad Arnold896c6d82015-03-13 16:20:29 -0700361 'board': board,
362 'suffix': suffix,
363 'version': 'R*' + latest_version}
Simran Basi99e63c02014-05-20 10:39:52 -0700364 image_dir = XBuddy._ResolveImageDir(image_dir)
365 gs_url = os.path.join(image_dir, image_url)
joychenf8f07e22013-07-12 17:45:51 -0700366
367 # There should only be one match on cros-image-archive.
Simran Basi99e63c02014-05-20 10:39:52 -0700368 full_version = gsutil_util.GetLatestVersionFromGSDir(gs_url)
joychenf8f07e22013-07-12 17:45:51 -0700369
Gilad Arnold896c6d82015-03-13 16:20:29 -0700370 return devserver_constants.IMAGE_DIR % {'board': board,
371 'suffix': suffix,
372 'version': full_version}
joychenf8f07e22013-07-12 17:45:51 -0700373
Gilad Arnold896c6d82015-03-13 16:20:29 -0700374 def _LookupVersion(self, board, suffix, version):
joychenf8f07e22013-07-12 17:45:51 -0700375 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700376 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700377 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700378 image_url = devserver_constants.IMAGE_DIR % {'board': board,
379 'suffix': suffix,
380 'version': version + '*'}
joychenf8f07e22013-07-12 17:45:51 -0700381 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
382
joychen121fc9b2013-08-02 14:30:30 -0700383 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700384 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700385 return devserver_constants.IMAGE_DIR % {'board': board,
386 'suffix': suffix,
387 'version': full_version}
joychenf8f07e22013-07-12 17:45:51 -0700388
Gilad Arnold896c6d82015-03-13 16:20:29 -0700389 def _RemoteBuildId(self, board, suffix, version):
Chris Sosaea734d92013-10-11 11:28:58 -0700390 """Returns the remote build_id for the given board and version.
391
392 Raises:
393 XBuddyException: If we failed to resolve the version to a valid build_id.
394 """
Gilad Arnold896c6d82015-03-13 16:20:29 -0700395 build_id_as_is = devserver_constants.IMAGE_DIR % {'board': board,
396 'suffix': '',
397 'version': version}
398 build_id_suffix = devserver_constants.IMAGE_DIR % {'board': board,
399 'suffix': suffix,
400 'version': version}
Chris Sosaea734d92013-10-11 11:28:58 -0700401 # Return the first path that exists. We assume that what the user typed
402 # is better than with a default suffix added i.e. x86-generic/blah is
403 # more valuable than x86-generic-release/blah.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700404 for build_id in build_id_as_is, build_id_suffix:
Chris Sosaea734d92013-10-11 11:28:58 -0700405 cmd = 'gsutil ls %s/%s' % (devserver_constants.GS_IMAGE_DIR, build_id)
406 try:
407 version = gsutil_util.GSUtilRun(cmd, None)
408 return build_id
409 except gsutil_util.GSUtilError:
410 continue
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800411
412 raise XBuddyException('Could not find remote build_id for %s %s' % (
413 board, version))
Chris Sosaea734d92013-10-11 11:28:58 -0700414
Gilad Arnold896c6d82015-03-13 16:20:29 -0700415 def _ResolveBuildVersion(self, board, suffix, base_version):
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800416 """Check LATEST-<base_version> and returns a full build version."""
417 _Log('Checking gs for full version for %s of %s', base_version, board)
418 # TODO(garnold) We might want to accommodate version prefixes and pick the
419 # most recent found, as done in _LookupVersion().
420 latest_addr = (devserver_constants.GS_LATEST_BASE_VERSION %
421 {'image_dir': devserver_constants.GS_IMAGE_DIR,
422 'board': board,
Gilad Arnold896c6d82015-03-13 16:20:29 -0700423 'suffix': suffix,
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800424 'base_version': base_version})
425 cmd = 'gsutil cat %s' % latest_addr
426 msg = 'Failed to find build at %s' % latest_addr
427 # Full release + version is in the LATEST file.
428 return gsutil_util.GSUtilRun(cmd, msg)
429
Gilad Arnold896c6d82015-03-13 16:20:29 -0700430 def _ResolveVersionToBuildId(self, board, suffix, version, image_dir=None):
joychen121fc9b2013-08-02 14:30:30 -0700431 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700432
433 Args:
434 board: as specified in the original call. (i.e. x86-generic, parrot)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700435 suffix: The location suffix, to be added to board name.
joychen3cb228e2013-06-12 12:13:13 -0700436 version: as entered in the original call. can be
437 {TBD, 0. some custom alias as defined in a config file}
Ningning Xiab2a1af52016-04-22 11:14:42 -0700438 1. fully qualified build version.
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800439 2. latest
440 3. latest-{channel}
441 4. latest-official-{board suffix}
442 5. version prefix (i.e. RX-Y.X, RX-Y, RX)
Simran Basi99e63c02014-05-20 10:39:52 -0700443 image_dir: image directory to check in Google Storage. If none,
444 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700445
446 Returns:
Chris Sosaea734d92013-10-11 11:28:58 -0700447 Location where the image dir is actually found on GS (build_id)
joychen3cb228e2013-06-12 12:13:13 -0700448
Chris Sosaea734d92013-10-11 11:28:58 -0700449 Raises:
450 XBuddyException: If we failed to resolve the version to a valid url.
joychen3cb228e2013-06-12 12:13:13 -0700451 """
joychenf8f07e22013-07-12 17:45:51 -0700452 # Only the last segment of the alias is variable relative to the rest.
453 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700454
joychenf8f07e22013-07-12 17:45:51 -0700455 if re.match(devserver_constants.VERSION_RE, version):
Gilad Arnold896c6d82015-03-13 16:20:29 -0700456 return self._RemoteBuildId(board, suffix, version)
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800457 elif re.match(devserver_constants.VERSION, version):
Ningning Xiab2a1af52016-04-22 11:14:42 -0700458 raise XBuddyException('\'%s\' is not valid. Should provide the fully '
459 'qualified version with a version prefix \'RX-\' '
460 'due to crbug.com/585914' % version)
joychenf8f07e22013-07-12 17:45:51 -0700461 elif version == LATEST_OFFICIAL:
462 # latest-official --> LATEST build in board-release
Gilad Arnold896c6d82015-03-13 16:20:29 -0700463 return self._LookupOfficial(board, suffix, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700464 elif version_tuple[0] == LATEST_OFFICIAL:
465 # latest-official-{suffix} --> LATEST build in board-{suffix}
Gilad Arnold896c6d82015-03-13 16:20:29 -0700466 return self._LookupOfficial(board, version_tuple[1],
467 image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700468 elif version == LATEST:
469 # latest --> latest build on stable channel
Gilad Arnold896c6d82015-03-13 16:20:29 -0700470 return self._LookupChannel(board, suffix, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700471 elif version_tuple[0] == LATEST:
472 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
473 # latest-R* --> most recent qualifying build
Gilad Arnold896c6d82015-03-13 16:20:29 -0700474 return self._LookupVersion(board, suffix, version_tuple[1])
joychenf8f07e22013-07-12 17:45:51 -0700475 else:
476 # latest-{channel} --> latest build within that channel
Gilad Arnold896c6d82015-03-13 16:20:29 -0700477 return self._LookupChannel(board, suffix, channel=version_tuple[1],
Simran Basi99e63c02014-05-20 10:39:52 -0700478 image_dir=image_dir)
joychen3cb228e2013-06-12 12:13:13 -0700479 else:
480 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700481 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700482
joychen5260b9a2013-07-16 14:48:01 -0700483 @staticmethod
484 def _Symlink(link, target):
485 """Symlinks link to target, and removes whatever link was there before."""
486 _Log("Linking to %s from %s", link, target)
487 if os.path.lexists(link):
488 os.unlink(link)
489 os.symlink(target, link)
490
joychen121fc9b2013-08-02 14:30:30 -0700491 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700492 """Get the version of the latest image built for board by build_image
493
494 Updates the symlink reference within the xBuddy static dir to point to
495 the real image dir in the local /build/images directory.
496
497 Args:
joychenc3944cb2013-08-19 10:42:07 -0700498 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700499
500 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700501 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700502
503 Raises:
504 XBuddyException if neither test nor dev image was found in latest built
505 directory.
joychen3cb228e2013-06-12 12:13:13 -0700506 """
joychen921e1fb2013-06-28 11:12:20 -0700507 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700508 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700509 raise XBuddyException('No builds found for %s. Did you run build_image?' %
510 board)
511
joychen121fc9b2013-08-02 14:30:30 -0700512 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700513 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700514
joychenc3944cb2013-08-19 10:42:07 -0700515 @staticmethod
516 def _FindAny(local_dir):
517 """Returns the image_type for ANY given the local_dir."""
joychenc3944cb2013-08-19 10:42:07 -0700518 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700519 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
520 # Prioritize test images over dev images.
joychenc3944cb2013-08-19 10:42:07 -0700521 if os.path.exists(test_image):
522 return 'test'
523
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700524 if os.path.exists(dev_image):
525 return 'dev'
526
joychenc3944cb2013-08-19 10:42:07 -0700527 raise XBuddyException('No images found in %s' % local_dir)
528
529 @staticmethod
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800530 def _InterpretPath(path, default_board=None, default_version=None):
joychen121fc9b2013-08-02 14:30:30 -0700531 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700532
joychen121fc9b2013-08-02 14:30:30 -0700533 Args:
534 path: the path xBuddy Get was called with.
Chris Sosa0eecf962014-02-03 14:14:39 -0800535 default_board: board to use in case board isn't in path.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800536 default_version: Version to use in case version isn't in path.
joychen3cb228e2013-06-12 12:13:13 -0700537
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800538 Returns:
Chris Sosa75490802013-09-30 17:21:45 -0700539 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 12:13:13 -0700540
541 Raises:
542 XBuddyException: if the path can't be resolved into valid components
543 """
joychen121fc9b2013-08-02 14:30:30 -0700544 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700545
Chris Sosa0eecf962014-02-03 14:14:39 -0800546 # Do the stuff that is well known first. We know that if paths have a
547 # image_type, it must be one of the GS/LOCAL aliases and it must be at the
548 # end. Similarly, local/remote are well-known and must start the path list.
549 is_local = True
550 if path_list and path_list[0] in (REMOTE, LOCAL):
551 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700552
Chris Sosa0eecf962014-02-03 14:14:39 -0800553 # Default image type is determined by remote vs. local.
554 if is_local:
555 image_type = ANY
556 else:
557 image_type = TEST
joychen7df67f72013-07-18 14:21:12 -0700558
Chris Sosa0eecf962014-02-03 14:14:39 -0800559 if path_list and path_list[-1] in GS_ALIASES + LOCAL_ALIASES:
560 image_type = path_list.pop(-1)
joychen3cb228e2013-06-12 12:13:13 -0700561
Chris Sosa0eecf962014-02-03 14:14:39 -0800562 # Now for the tricky part. We don't actually know at this point if the rest
563 # of the path is just a board | version (like R33-2341.0.0) or just a board
564 # or just a version. So we do our best to do the right thing.
565 board = default_board
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800566 version = default_version or LATEST
Chris Sosa0eecf962014-02-03 14:14:39 -0800567 if len(path_list) == 1:
568 path = path_list.pop(0)
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800569 # Treat this as a version if it's one we know (contains default or
570 # latest), or we were given an actual default board.
571 if default_version in path or LATEST in path or default_board is not None:
Chris Sosa0eecf962014-02-03 14:14:39 -0800572 version = path
joychen7df67f72013-07-18 14:21:12 -0700573 else:
Chris Sosa0eecf962014-02-03 14:14:39 -0800574 board = path
joychen7df67f72013-07-18 14:21:12 -0700575
Chris Sosa0eecf962014-02-03 14:14:39 -0800576 elif len(path_list) == 2:
577 # Assumes board/version.
578 board = path_list.pop(0)
579 version = path_list.pop(0)
580
581 if path_list:
582 raise XBuddyException("Path isn't valid. Could not figure out how to "
583 "parse remaining components: %s." % path_list)
584
585 _Log("Get artifact '%s' with board %s and version %s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700586 image_type, board, version, is_local)
587
588 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700589
joychen921e1fb2013-06-28 11:12:20 -0700590 def _SyncRegistryWithBuildImages(self):
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800591 """Crawl images_dir for build_ids of images generated from build_image.
joychen5260b9a2013-07-16 14:48:01 -0700592
593 This will find images and symlink them in xBuddy's static dir so that
594 xBuddy's cache can serve them.
595 If xBuddy's _manage_builds option is on, then a timestamp will also be
596 generated, and xBuddy will clear them from the directory they are in, as
597 necessary.
598 """
Yu-Ju Hong235d1b52014-04-16 11:01:47 -0700599 if not os.path.isdir(self.images_dir):
600 # Skip syncing if images_dir does not exist.
601 _Log('Cannot find %s; skip syncing image registry.', self.images_dir)
602 return
603
joychen921e1fb2013-06-28 11:12:20 -0700604 build_ids = []
605 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700606 # Ensure we have directories to track all boards in build/images
607 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700608 board_dir = os.path.join(self.images_dir, b)
609 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700610 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700611
joychen121fc9b2013-08-02 14:30:30 -0700612 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700613 for build_id in build_ids:
614 link = os.path.join(self.static_dir, build_id)
615 target = os.path.join(self.images_dir, build_id)
616 XBuddy._Symlink(link, target)
617 if self._manage_builds:
618 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700619
620 def _ListBuildTimes(self):
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800621 """Returns the currently cached builds and their last access timestamp.
joychen3cb228e2013-06-12 12:13:13 -0700622
623 Returns:
624 list of tuples that matches xBuddy build/version to timestamps in long
625 """
joychen121fc9b2013-08-02 14:30:30 -0700626 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700627 build_dict = {}
628
joychen7df67f72013-07-18 14:21:12 -0700629 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700630 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
631 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700632 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700633 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700634 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
635 return return_tup
636
Chris Sosa75490802013-09-30 17:21:45 -0700637 def _Download(self, gs_url, artifacts):
638 """Download the artifacts from the given gs_url.
639
640 Raises:
641 build_artifact.ArtifactDownloadError: If we failed to download the
642 artifact.
643 """
joychen3cb228e2013-06-12 12:13:13 -0700644 with XBuddy._staging_thread_count_lock:
645 XBuddy._staging_thread_count += 1
646 try:
Chris Sosa75490802013-09-30 17:21:45 -0700647 _Log("Downloading %s from %s", artifacts, gs_url)
Gabe Black3b567202015-09-23 14:07:59 -0700648 dl = downloader.GoogleStorageDownloader(self.static_dir, gs_url)
649 factory = build_artifact.ChromeOSArtifactFactory(
650 dl.GetBuildDir(), artifacts, [], dl.GetBuild())
651 dl.Download(factory)
joychen3cb228e2013-06-12 12:13:13 -0700652 finally:
653 with XBuddy._staging_thread_count_lock:
654 XBuddy._staging_thread_count -= 1
655
Chris Sosa75490802013-09-30 17:21:45 -0700656 def CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700657 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700658 if not self._manage_builds:
659 return
joychen921e1fb2013-06-28 11:12:20 -0700660 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700661 _Log('In cache now: %s', cached_builds)
662
joychen562699a2013-08-13 15:22:14 -0700663 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700664 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700665 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700666
667 time_file = os.path.join(self._timestamp_folder,
668 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700669 os.unlink(time_file)
670 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700671 try:
joychen121fc9b2013-08-02 14:30:30 -0700672 # Handle symlinks, in the case of links to local builds if enabled.
673 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700674 target = os.readlink(clear_dir)
675 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700676
677 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700678 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700679 shutil.rmtree(target)
680 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700681 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700682 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700683
joychen121fc9b2013-08-02 14:30:30 -0700684 except Exception as err:
685 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700686
Simran Basi99e63c02014-05-20 10:39:52 -0700687 def _GetFromGS(self, build_id, image_type, image_dir=None):
Chris Sosa75490802013-09-30 17:21:45 -0700688 """Check if the artifact is available locally. Download from GS if not.
689
Simran Basi99e63c02014-05-20 10:39:52 -0700690 Args:
691 build_id: Path to the image or update directory on the devserver or
692 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
693 image_type: Image type to download. Look at aliases at top of file for
694 options.
695 image_dir: Google Storage image archive to search in if requesting a
696 remote artifact. If none uses the default bucket.
697
Chris Sosa75490802013-09-30 17:21:45 -0700698 Raises:
699 build_artifact.ArtifactDownloadError: If we failed to download the
700 artifact.
701 """
Simran Basi99e63c02014-05-20 10:39:52 -0700702 image_dir = XBuddy._ResolveImageDir(image_dir)
703 gs_url = os.path.join(image_dir, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700704
joychen121fc9b2013-08-02 14:30:30 -0700705 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700706 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700707 file_loc = os.path.join(self.static_dir, build_id, file_name)
708 cached = os.path.exists(file_loc)
709
joychen921e1fb2013-06-28 11:12:20 -0700710 if not cached:
Chris Sosa75490802013-09-30 17:21:45 -0700711 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
712 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 11:12:20 -0700713 else:
714 _Log('Image already cached.')
715
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800716 def _GetArtifact(self, path_list, board=None, version=None,
717 lookup_only=False, image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700718 """Interpret an xBuddy path and return directory/file_name to resource.
719
Chris Sosa75490802013-09-30 17:21:45 -0700720 Note board can be passed that in but by default if self._board is set,
721 that is used rather than board.
722
Simran Basi99e63c02014-05-20 10:39:52 -0700723 Args:
724 path_list: [board, version, alias] as split from the xbuddy call url.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800725 board: Board whos artifacts we are looking for. Only used if no board was
726 given during XBuddy initialization.
727 version: Version whose artifacts we are looking for. Used if no version
728 was given during XBuddy initialization. If None, defers to LATEST.
Simran Basi99e63c02014-05-20 10:39:52 -0700729 lookup_only: If true just look up the artifact, if False stage it on
730 the devserver as well.
731 image_dir: Google Storage image archive to search in if requesting a
732 remote artifact. If none uses the default bucket.
733
joychen346531c2013-07-24 16:55:56 -0700734 Returns:
Simran Basi99e63c02014-05-20 10:39:52 -0700735 build_id: Path to the image or update directory on the devserver or
736 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
737 file_name: of the artifact in the build_id directory.
joychen346531c2013-07-24 16:55:56 -0700738
739 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700740 XBuddyException: if the path could not be translated
Chris Sosa75490802013-09-30 17:21:45 -0700741 build_artifact.ArtifactDownloadError: if we failed to download the
742 artifact.
joychen346531c2013-07-24 16:55:56 -0700743 """
joychen121fc9b2013-08-02 14:30:30 -0700744 path = '/'.join(path_list)
Chris Sosa0eecf962014-02-03 14:14:39 -0800745 default_board = self._board if self._board else board
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800746 default_version = self._version or version or LATEST
joychenb0dfe552013-07-30 10:02:06 -0700747 # Rewrite the path if there is an appropriate default.
Gilad Arnold38e828c2015-04-24 13:52:07 -0700748 path, suffix = self.LookupAlias(path, board=default_board,
749 version=default_version)
joychen121fc9b2013-08-02 14:30:30 -0700750 # Parse the path.
Chris Sosa0eecf962014-02-03 14:14:39 -0800751 image_type, board, version, is_local = self._InterpretPath(
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800752 path, default_board, default_version)
joychen7df67f72013-07-18 14:21:12 -0700753 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700754 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700755 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700756 # Get the latest local image for the given board.
757 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700758
joychenc3944cb2013-08-19 10:42:07 -0700759 build_id = os.path.join(board, version)
760 artifact_dir = os.path.join(self.static_dir, build_id)
761 if image_type == ANY:
762 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700763
joychenc3944cb2013-08-19 10:42:07 -0700764 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
765 artifact_path = os.path.join(artifact_dir, file_name)
766 if not os.path.exists(artifact_path):
767 raise XBuddyException('Local %s artifact not in static_dir at %s' %
768 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700769
joychen921e1fb2013-06-28 11:12:20 -0700770 else:
joychen121fc9b2013-08-02 14:30:30 -0700771 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700772 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700773 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700774 (image_type, GS_ALIASES))
Gilad Arnold896c6d82015-03-13 16:20:29 -0700775 build_id = self._ResolveVersionToBuildId(board, suffix, version,
Simran Basi99e63c02014-05-20 10:39:52 -0700776 image_dir=image_dir)
Chris Sosa75490802013-09-30 17:21:45 -0700777 _Log('Resolved version %s to %s.', version, build_id)
778 file_name = GS_ALIAS_TO_FILENAME[image_type]
779 if not lookup_only:
Simran Basi99e63c02014-05-20 10:39:52 -0700780 self._GetFromGS(build_id, image_type, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700781
joychenc3944cb2013-08-19 10:42:07 -0700782 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700783
784 ############################ BEGIN PUBLIC METHODS
785
786 def List(self):
787 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700788 self._SyncRegistryWithBuildImages()
789 builds = self._ListBuildTimes()
790 return_string = ''
791 for build, timestamp in builds:
792 return_string += '<b>' + build + '</b> '
793 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
794 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700795
796 def Capacity(self):
797 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700798 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700799
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800800 def Translate(self, path_list, board=None, version=None, image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700801 """Translates an xBuddy path to a real path to artifact if it exists.
802
joychen121fc9b2013-08-02 14:30:30 -0700803 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700804
Simran Basi99e63c02014-05-20 10:39:52 -0700805 Args:
806 path_list: [board, version, alias] as split from the xbuddy call url.
807 board: Board whos artifacts we are looking for. If None, use the board
808 XBuddy was initialized to use.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800809 version: Version whose artifacts we are looking for. If None, use the
810 version XBuddy was initialized with, or LATEST.
Simran Basi99e63c02014-05-20 10:39:52 -0700811 image_dir: image directory to check in Google Storage. If none,
812 the default bucket is used.
813
joychen7c2054a2013-07-25 11:14:07 -0700814 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700815 build_id: Path to the image or update directory on the devserver.
816 e.g. 'x86-generic/R26-4000.0.0'
817 The returned path is always the path to the directory within
818 static_dir, so it is always the build_id of the image.
819 file_name: The file name of the artifact. Can take any of the file
820 values in devserver_constants.
821 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
822 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700823
joychen121fc9b2013-08-02 14:30:30 -0700824 Raises:
825 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700826 """
827 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700828 build_id, file_name = self._GetArtifact(path_list, board=board,
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800829 version=version,
Simran Basi99e63c02014-05-20 10:39:52 -0700830 lookup_only=True,
831 image_dir=image_dir)
joychen346531c2013-07-24 16:55:56 -0700832
joychen121fc9b2013-08-02 14:30:30 -0700833 _Log('Returning path to payload: %s/%s', build_id, file_name)
834 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700835
Yu-Ju Hong1bdb7a92014-04-10 16:02:11 -0700836 def StageTestArtifactsForUpdate(self, path_list):
Chris Sosa75490802013-09-30 17:21:45 -0700837 """Stages test artifacts for update and returns build_id.
838
839 Raises:
840 XBuddyException: if the path could not be translated
841 build_artifact.ArtifactDownloadError: if we failed to download the test
842 artifacts.
843 """
844 build_id, file_name = self.Translate(path_list)
845 if file_name == devserver_constants.TEST_IMAGE_FILE:
846 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
847 build_id)
848 artifacts = [FULL, STATEFUL]
849 self._Download(gs_url, artifacts)
850 return build_id
851
Simran Basi99e63c02014-05-20 10:39:52 -0700852 def Get(self, path_list, image_dir=None):
joychen921e1fb2013-06-28 11:12:20 -0700853 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700854
855 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700856
joychen3cb228e2013-06-12 12:13:13 -0700857 Args:
Simran Basi99e63c02014-05-20 10:39:52 -0700858 path_list: [board, version, alias] as split from the xbuddy call url.
859 image_dir: image directory to check in Google Storage. If none,
860 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700861
862 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700863 build_id: Path to the image or update directory on the devserver.
Simran Basi99e63c02014-05-20 10:39:52 -0700864 e.g. 'x86-generic/R26-4000.0.0'
865 The returned path is always the path to the directory within
866 static_dir, so it is always the build_id of the image.
joychen121fc9b2013-08-02 14:30:30 -0700867 file_name: The file name of the artifact. Can take any of the file
Simran Basi99e63c02014-05-20 10:39:52 -0700868 values in devserver_constants.
869 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
870 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700871
872 Raises:
Chris Sosa75490802013-09-30 17:21:45 -0700873 XBuddyException: if the path could not be translated
874 build_artifact.ArtifactDownloadError: if we failed to download the
875 artifact.
joychen3cb228e2013-06-12 12:13:13 -0700876 """
joychen7df67f72013-07-18 14:21:12 -0700877 self._SyncRegistryWithBuildImages()
Simran Basi99e63c02014-05-20 10:39:52 -0700878 build_id, file_name = self._GetArtifact(path_list, image_dir=image_dir)
joychen921e1fb2013-06-28 11:12:20 -0700879 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700880 #TODO (joyc): run in sep thread
Chris Sosa75490802013-09-30 17:21:45 -0700881 self.CleanCache()
joychen3cb228e2013-06-12 12:13:13 -0700882
joychen121fc9b2013-08-02 14:30:30 -0700883 _Log('Returning path to payload: %s/%s', build_id, file_name)
884 return build_id, file_name