blob: 384de4948b521dba138a3b0ffc1950020c0933ad [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
joychen921e1fb2013-06-28 11:12:20 -070019import build_util
joychen3cb228e2013-06-12 12:13:13 -070020import artifact_info
joychen3cb228e2013-06-12 12:13:13 -070021import common_util
22import devserver_constants
23import downloader
joychenf8f07e22013-07-12 17:45:51 -070024import gsutil_util
joychen3cb228e2013-06-12 12:13:13 -070025import log_util
26
27# Module-local log function.
28def _Log(message, *args):
29 return log_util.LogWithTag('XBUDDY', message, *args)
30
joychen562699a2013-08-13 15:22:14 -070031# xBuddy config constants
32CONFIG_FILE = 'xbuddy_config.ini'
33SHADOW_CONFIG_FILE = 'shadow_xbuddy_config.ini'
34PATH_REWRITES = 'PATH_REWRITES'
35GENERAL = 'GENERAL'
Gilad Arnold896c6d82015-03-13 16:20:29 -070036LOCATION_SUFFIXES = 'LOCATION_SUFFIXES'
joychen921e1fb2013-06-28 11:12:20 -070037
Chris Sosac2abc722013-08-26 17:11:22 -070038# Path for shadow config in chroot.
39CHROOT_SHADOW_DIR = '/mnt/host/source/src/platform/dev'
40
joychen25d25972013-07-30 14:54:16 -070041# XBuddy aliases
42TEST = 'test'
43BASE = 'base'
44DEV = 'dev'
45FULL = 'full_payload'
46RECOVERY = 'recovery'
47STATEFUL = 'stateful'
48AUTOTEST = 'autotest'
49
joychen921e1fb2013-06-28 11:12:20 -070050# Local build constants
joychenc3944cb2013-08-19 10:42:07 -070051ANY = "ANY"
joychen7df67f72013-07-18 14:21:12 -070052LATEST = "latest"
53LOCAL = "local"
54REMOTE = "remote"
Chris Sosa75490802013-09-30 17:21:45 -070055
56# TODO(sosa): Fix a lot of assumptions about these aliases. There is too much
57# implicit logic here that's unnecessary. What should be done:
58# 1) Collapse Alias logic to one set of aliases for xbuddy (not local/remote).
59# 2) Do not use zip when creating these dicts. Better to not rely on ordering.
60# 3) Move alias/artifact mapping to a central module rather than having it here.
61# 4) Be explicit when things are missing i.e. no dev images in image.zip.
62
joychen921e1fb2013-06-28 11:12:20 -070063LOCAL_ALIASES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080064 TEST,
65 DEV,
66 BASE,
67 RECOVERY,
68 FULL,
69 STATEFUL,
70 ANY,
joychen921e1fb2013-06-28 11:12:20 -070071]
72
73LOCAL_FILE_NAMES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080074 devserver_constants.TEST_IMAGE_FILE,
75 devserver_constants.IMAGE_FILE,
76 devserver_constants.BASE_IMAGE_FILE,
77 devserver_constants.RECOVERY_IMAGE_FILE,
78 devserver_constants.UPDATE_FILE,
79 devserver_constants.STATEFUL_FILE,
80 None, # For ANY.
joychen921e1fb2013-06-28 11:12:20 -070081]
82
83LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
84
85# Google Storage constants
86GS_ALIASES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080087 TEST,
88 BASE,
89 RECOVERY,
90 FULL,
91 STATEFUL,
92 AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -070093]
94
joychen921e1fb2013-06-28 11:12:20 -070095GS_FILE_NAMES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080096 devserver_constants.TEST_IMAGE_FILE,
97 devserver_constants.BASE_IMAGE_FILE,
98 devserver_constants.RECOVERY_IMAGE_FILE,
99 devserver_constants.UPDATE_FILE,
100 devserver_constants.STATEFUL_FILE,
101 devserver_constants.AUTOTEST_DIR,
joychen3cb228e2013-06-12 12:13:13 -0700102]
103
104ARTIFACTS = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800105 artifact_info.TEST_IMAGE,
106 artifact_info.BASE_IMAGE,
107 artifact_info.RECOVERY_IMAGE,
108 artifact_info.FULL_PAYLOAD,
109 artifact_info.STATEFUL_PAYLOAD,
110 artifact_info.AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -0700111]
112
joychen921e1fb2013-06-28 11:12:20 -0700113GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
114GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 12:13:13 -0700115
joychen921e1fb2013-06-28 11:12:20 -0700116LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 12:13:13 -0700117
Chris Sosaea734d92013-10-11 11:28:58 -0700118RELEASE = "-release"
joychen3cb228e2013-06-12 12:13:13 -0700119
joychen3cb228e2013-06-12 12:13:13 -0700120
121class XBuddyException(Exception):
122 """Exception classes used by this module."""
123 pass
124
125
126# no __init__ method
127#pylint: disable=W0232
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800128class Timestamp(object):
joychen3cb228e2013-06-12 12:13:13 -0700129 """Class to translate build path strings and timestamp filenames."""
130
131 _TIMESTAMP_DELIMITER = 'SLASH'
132 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
133
134 @staticmethod
135 def TimestampToBuild(timestamp_filename):
136 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
137
138 @staticmethod
139 def BuildToTimestamp(build_path):
140 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 11:12:20 -0700141
142 @staticmethod
143 def UpdateTimestamp(timestamp_dir, build_id):
144 """Update timestamp file of build with build_id."""
145 common_util.MkDirP(timestamp_dir)
joychen562699a2013-08-13 15:22:14 -0700146 _Log("Updating timestamp for %s", build_id)
joychen921e1fb2013-06-28 11:12:20 -0700147 time_file = os.path.join(timestamp_dir,
148 Timestamp.BuildToTimestamp(build_id))
149 with file(time_file, 'a'):
150 os.utime(time_file, None)
joychen3cb228e2013-06-12 12:13:13 -0700151#pylint: enable=W0232
152
153
joychen921e1fb2013-06-28 11:12:20 -0700154class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 12:13:13 -0700155 """Class that manages image retrieval and caching by the devserver.
156
157 Image retrieval by xBuddy path:
158 XBuddy accesses images and artifacts that it stores using an xBuddy
159 path of the form: board/version/alias
160 The primary xbuddy.Get call retrieves the correct artifact or url to where
161 the artifacts can be found.
162
163 Image caching:
164 Images and other artifacts are stored identically to how they would have
165 been if devserver's stage rpc was called and the xBuddy cache replaces
166 build versions on a LRU basis. Timestamps are maintained by last accessed
167 times of representative files in the a directory in the static serve
168 directory (XBUDDY_TIMESTAMP_DIR).
169
170 Private class members:
joychen121fc9b2013-08-02 14:30:30 -0700171 _true_values: used for interpreting boolean values
172 _staging_thread_count: track download requests
173 _timestamp_folder: directory with empty files standing in as timestamps
joychen921e1fb2013-06-28 11:12:20 -0700174 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 12:13:13 -0700175 """
176 _true_values = ['true', 't', 'yes', 'y']
177
178 # Number of threads that are staging images.
179 _staging_thread_count = 0
180 # Lock used to lock increasing/decreasing count.
181 _staging_thread_count_lock = threading.Lock()
182
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800183 def __init__(self, manage_builds=False, board=None, version=None,
184 images_dir=None, log_screen=True, **kwargs):
joychen921e1fb2013-06-28 11:12:20 -0700185 super(XBuddy, self).__init__(**kwargs)
joychenb0dfe552013-07-30 10:02:06 -0700186
Yiming Chenaab488e2014-11-17 14:49:31 -0800187 if not log_screen:
188 cherrypy.config.update({'log.screen': False})
189
joychen562699a2013-08-13 15:22:14 -0700190 self.config = self._ReadConfig()
191 self._manage_builds = manage_builds or self._ManageBuilds()
Chris Sosa75490802013-09-30 17:21:45 -0700192 self._board = board
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800193 self._version = version
joychen921e1fb2013-06-28 11:12:20 -0700194 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 12:13:13 -0700195 Timestamp.XBUDDY_TIMESTAMP_DIR)
Chris Sosa7cd23202013-10-15 17:22:57 -0700196 if images_dir:
197 self.images_dir = images_dir
198 else:
199 self.images_dir = os.path.join(self.GetSourceRoot(), 'src/build/images')
200
joychen7df67f72013-07-18 14:21:12 -0700201 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 12:13:13 -0700202
203 @classmethod
204 def ParseBoolean(cls, boolean_string):
205 """Evaluate a string to a boolean value"""
206 if boolean_string:
207 return boolean_string.lower() in cls._true_values
208 else:
209 return False
210
joychen562699a2013-08-13 15:22:14 -0700211 def _ReadConfig(self):
212 """Read xbuddy config from ini files.
213
214 Reads the base config from xbuddy_config.ini, and then merges in the
215 shadow config from shadow_xbuddy_config.ini
216
217 Returns:
218 The merged configuration.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800219
joychen562699a2013-08-13 15:22:14 -0700220 Raises:
221 XBuddyException if the config file is missing.
222 """
223 xbuddy_config = ConfigParser.ConfigParser()
224 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
225 if os.path.exists(config_file):
226 xbuddy_config.read(config_file)
227 else:
Yiming Chend9202142014-11-07 14:56:52 -0800228 # Get the directory of xbuddy.py file.
229 file_dir = os.path.dirname(os.path.realpath(__file__))
230 # Read the default xbuddy_config.ini from the directory.
231 xbuddy_config.read(os.path.join(file_dir, CONFIG_FILE))
joychen562699a2013-08-13 15:22:14 -0700232
233 # Read the shadow file if there is one.
Chris Sosac2abc722013-08-26 17:11:22 -0700234 if os.path.isdir(CHROOT_SHADOW_DIR):
235 shadow_config_file = os.path.join(CHROOT_SHADOW_DIR, SHADOW_CONFIG_FILE)
236 else:
237 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
238
239 _Log('Using shadow config file stored at %s', shadow_config_file)
joychen562699a2013-08-13 15:22:14 -0700240 if os.path.exists(shadow_config_file):
241 shadow_xbuddy_config = ConfigParser.ConfigParser()
242 shadow_xbuddy_config.read(shadow_config_file)
243
244 # Merge shadow config in.
245 sections = shadow_xbuddy_config.sections()
246 for s in sections:
247 if not xbuddy_config.has_section(s):
248 xbuddy_config.add_section(s)
249 options = shadow_xbuddy_config.options(s)
250 for o in options:
251 val = shadow_xbuddy_config.get(s, o)
252 xbuddy_config.set(s, o, val)
253
254 return xbuddy_config
255
256 def _ManageBuilds(self):
257 """Checks if xBuddy is managing local builds using the current config."""
258 try:
259 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
260 except ConfigParser.Error:
261 return False
262
263 def _Capacity(self):
264 """Gets the xbuddy capacity from the current config."""
265 try:
266 return int(self.config.get(GENERAL, 'capacity'))
267 except ConfigParser.Error:
268 return 5
269
Gilad Arnold38e828c2015-04-24 13:52:07 -0700270 def LookupAlias(self, alias, board=None, version=None):
joychen562699a2013-08-13 15:22:14 -0700271 """Given the full xbuddy config, look up an alias for path rewrite.
272
273 Args:
274 alias: The xbuddy path that could be one of the aliases in the
275 rewrite table.
276 board: The board to fill in with when paths are rewritten. Can be from
Gilad Arnold38e828c2015-04-24 13:52:07 -0700277 the update request xml or the default board from devserver. If None,
278 defers to the value given during XBuddy initialization.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800279 version: The version to fill in when rewriting paths. Could be a specific
Gilad Arnold38e828c2015-04-24 13:52:07 -0700280 version number or a version alias like LATEST. If None, defers to the
281 value given during XBuddy initialization, or LATEST.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800282
joychen562699a2013-08-13 15:22:14 -0700283 Returns:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700284 A pair (val, suffix) where val is the rewritten path, or the original
285 string if no rewrite was found; and suffix is the assigned location
286 suffix, or the default suffix if none was found.
joychen562699a2013-08-13 15:22:14 -0700287 """
joychen562699a2013-08-13 15:22:14 -0700288 try:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700289 suffix = self.config.get(LOCATION_SUFFIXES, alias)
290 except ConfigParser.Error:
291 suffix = RELEASE
292
293 try:
joychen562699a2013-08-13 15:22:14 -0700294 val = self.config.get(PATH_REWRITES, alias)
295 except ConfigParser.Error:
296 # No alias lookup found. Return original path.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700297 val = None
joychen562699a2013-08-13 15:22:14 -0700298
Gilad Arnold896c6d82015-03-13 16:20:29 -0700299 if not (val and val.strip()):
300 val = alias
joychen562699a2013-08-13 15:22:14 -0700301 else:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700302 # The found value is not an empty string.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800303 # Fill in the board and version.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700304 val = val.replace("BOARD", "%(board)s")
305 val = val.replace("VERSION", "%(version)s")
Gilad Arnold38e828c2015-04-24 13:52:07 -0700306 val = val % {'board': board or self._board,
307 'version': version or self._version or LATEST}
Gilad Arnold896c6d82015-03-13 16:20:29 -0700308
309 _Log("Path is %s, location suffix is %s", val, suffix)
310 return val, suffix
joychen562699a2013-08-13 15:22:14 -0700311
Simran Basi99e63c02014-05-20 10:39:52 -0700312 @staticmethod
313 def _ResolveImageDir(image_dir):
314 """Clean up and return the image dir to use.
315
316 Args:
317 image_dir: directory in Google Storage to use.
318
319 Returns:
320 |image_dir| if |image_dir| is not None. Otherwise, returns
321 devserver_constants.GS_IMAGE_DIR
322 """
323 image_dir = image_dir or devserver_constants.GS_IMAGE_DIR
324 # Remove trailing slashes.
325 return image_dir.rstrip('/')
326
Gilad Arnold896c6d82015-03-13 16:20:29 -0700327 def _LookupOfficial(self, board, suffix, image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700328 """Check LATEST-master for the version number of interest."""
329 _Log("Checking gs for latest %s-%s image", board, suffix)
Simran Basi99e63c02014-05-20 10:39:52 -0700330 image_dir = XBuddy._ResolveImageDir(image_dir)
331 latest_addr = (devserver_constants.GS_LATEST_MASTER %
332 {'image_dir': image_dir,
333 'board': board,
334 'suffix': suffix})
joychenf8f07e22013-07-12 17:45:51 -0700335 cmd = 'gsutil cat %s' % latest_addr
336 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700337 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700338 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700339
joychenf8f07e22013-07-12 17:45:51 -0700340 return devserver_constants.IMAGE_DIR % {'board':board,
341 'suffix':suffix,
342 'version':version}
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800343
Gilad Arnold896c6d82015-03-13 16:20:29 -0700344 def _LookupChannel(self, board, suffix, channel='stable',
345 image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700346 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700347 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700348 _Log("Checking channel '%s' for latest '%s' image", channel, board)
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800349 # Due to historical reasons, gs://chromeos-releases uses
350 # daisy-spring as opposed to the board name daisy_spring. Convert
351 # the board name for the lookup.
352 channel_dir = devserver_constants.GS_CHANNEL_DIR % {
353 'channel':channel,
354 'board':re.sub('_', '-', board)}
joychen562699a2013-08-13 15:22:14 -0700355 latest_version = gsutil_util.GetLatestVersionFromGSDir(
356 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700357
joychen121fc9b2013-08-02 14:30:30 -0700358 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700359 image_url = devserver_constants.IMAGE_DIR % {
Gilad Arnold896c6d82015-03-13 16:20:29 -0700360 'board': board,
361 'suffix': suffix,
362 'version': 'R*' + latest_version}
Simran Basi99e63c02014-05-20 10:39:52 -0700363 image_dir = XBuddy._ResolveImageDir(image_dir)
364 gs_url = os.path.join(image_dir, image_url)
joychenf8f07e22013-07-12 17:45:51 -0700365
366 # There should only be one match on cros-image-archive.
Simran Basi99e63c02014-05-20 10:39:52 -0700367 full_version = gsutil_util.GetLatestVersionFromGSDir(gs_url)
joychenf8f07e22013-07-12 17:45:51 -0700368
Gilad Arnold896c6d82015-03-13 16:20:29 -0700369 return devserver_constants.IMAGE_DIR % {'board': board,
370 'suffix': suffix,
371 'version': full_version}
joychenf8f07e22013-07-12 17:45:51 -0700372
Gilad Arnold896c6d82015-03-13 16:20:29 -0700373 def _LookupVersion(self, board, suffix, version):
joychenf8f07e22013-07-12 17:45:51 -0700374 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700375 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700376 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700377 image_url = devserver_constants.IMAGE_DIR % {'board': board,
378 'suffix': suffix,
379 'version': version + '*'}
joychenf8f07e22013-07-12 17:45:51 -0700380 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
381
joychen121fc9b2013-08-02 14:30:30 -0700382 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700383 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700384 return devserver_constants.IMAGE_DIR % {'board': board,
385 'suffix': suffix,
386 'version': full_version}
joychenf8f07e22013-07-12 17:45:51 -0700387
Gilad Arnold896c6d82015-03-13 16:20:29 -0700388 def _RemoteBuildId(self, board, suffix, version):
Chris Sosaea734d92013-10-11 11:28:58 -0700389 """Returns the remote build_id for the given board and version.
390
391 Raises:
392 XBuddyException: If we failed to resolve the version to a valid build_id.
393 """
Gilad Arnold896c6d82015-03-13 16:20:29 -0700394 build_id_as_is = devserver_constants.IMAGE_DIR % {'board': board,
395 'suffix': '',
396 'version': version}
397 build_id_suffix = devserver_constants.IMAGE_DIR % {'board': board,
398 'suffix': suffix,
399 'version': version}
Chris Sosaea734d92013-10-11 11:28:58 -0700400 # Return the first path that exists. We assume that what the user typed
401 # is better than with a default suffix added i.e. x86-generic/blah is
402 # more valuable than x86-generic-release/blah.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700403 for build_id in build_id_as_is, build_id_suffix:
Chris Sosaea734d92013-10-11 11:28:58 -0700404 cmd = 'gsutil ls %s/%s' % (devserver_constants.GS_IMAGE_DIR, build_id)
405 try:
406 version = gsutil_util.GSUtilRun(cmd, None)
407 return build_id
408 except gsutil_util.GSUtilError:
409 continue
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800410
411 raise XBuddyException('Could not find remote build_id for %s %s' % (
412 board, version))
Chris Sosaea734d92013-10-11 11:28:58 -0700413
Gilad Arnold896c6d82015-03-13 16:20:29 -0700414 def _ResolveBuildVersion(self, board, suffix, base_version):
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800415 """Check LATEST-<base_version> and returns a full build version."""
416 _Log('Checking gs for full version for %s of %s', base_version, board)
417 # TODO(garnold) We might want to accommodate version prefixes and pick the
418 # most recent found, as done in _LookupVersion().
419 latest_addr = (devserver_constants.GS_LATEST_BASE_VERSION %
420 {'image_dir': devserver_constants.GS_IMAGE_DIR,
421 'board': board,
Gilad Arnold896c6d82015-03-13 16:20:29 -0700422 'suffix': suffix,
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800423 'base_version': base_version})
424 cmd = 'gsutil cat %s' % latest_addr
425 msg = 'Failed to find build at %s' % latest_addr
426 # Full release + version is in the LATEST file.
427 return gsutil_util.GSUtilRun(cmd, msg)
428
Gilad Arnold896c6d82015-03-13 16:20:29 -0700429 def _ResolveVersionToBuildId(self, board, suffix, version, image_dir=None):
joychen121fc9b2013-08-02 14:30:30 -0700430 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700431
432 Args:
433 board: as specified in the original call. (i.e. x86-generic, parrot)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700434 suffix: The location suffix, to be added to board name.
joychen3cb228e2013-06-12 12:13:13 -0700435 version: as entered in the original call. can be
436 {TBD, 0. some custom alias as defined in a config file}
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800437 1. fully qualified build version or base version.
438 2. latest
439 3. latest-{channel}
440 4. latest-official-{board suffix}
441 5. version prefix (i.e. RX-Y.X, RX-Y, RX)
Simran Basi99e63c02014-05-20 10:39:52 -0700442 image_dir: image directory to check in Google Storage. If none,
443 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700444
445 Returns:
Chris Sosaea734d92013-10-11 11:28:58 -0700446 Location where the image dir is actually found on GS (build_id)
joychen3cb228e2013-06-12 12:13:13 -0700447
Chris Sosaea734d92013-10-11 11:28:58 -0700448 Raises:
449 XBuddyException: If we failed to resolve the version to a valid url.
joychen3cb228e2013-06-12 12:13:13 -0700450 """
joychenf8f07e22013-07-12 17:45:51 -0700451 # Only the last segment of the alias is variable relative to the rest.
452 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700453
joychenf8f07e22013-07-12 17:45:51 -0700454 if re.match(devserver_constants.VERSION_RE, version):
Gilad Arnold896c6d82015-03-13 16:20:29 -0700455 return self._RemoteBuildId(board, suffix, version)
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800456 elif re.match(devserver_constants.VERSION, version):
Gilad Arnold896c6d82015-03-13 16:20:29 -0700457 return self._RemoteBuildId(
458 board, suffix, self._ResolveBuildVersion(board, suffix, version))
joychenf8f07e22013-07-12 17:45:51 -0700459 elif version == LATEST_OFFICIAL:
460 # latest-official --> LATEST build in board-release
Gilad Arnold896c6d82015-03-13 16:20:29 -0700461 return self._LookupOfficial(board, suffix, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700462 elif version_tuple[0] == LATEST_OFFICIAL:
463 # latest-official-{suffix} --> LATEST build in board-{suffix}
Gilad Arnold896c6d82015-03-13 16:20:29 -0700464 return self._LookupOfficial(board, version_tuple[1],
465 image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700466 elif version == LATEST:
467 # latest --> latest build on stable channel
Gilad Arnold896c6d82015-03-13 16:20:29 -0700468 return self._LookupChannel(board, suffix, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700469 elif version_tuple[0] == LATEST:
470 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
471 # latest-R* --> most recent qualifying build
Gilad Arnold896c6d82015-03-13 16:20:29 -0700472 return self._LookupVersion(board, suffix, version_tuple[1])
joychenf8f07e22013-07-12 17:45:51 -0700473 else:
474 # latest-{channel} --> latest build within that channel
Gilad Arnold896c6d82015-03-13 16:20:29 -0700475 return self._LookupChannel(board, suffix, channel=version_tuple[1],
Simran Basi99e63c02014-05-20 10:39:52 -0700476 image_dir=image_dir)
joychen3cb228e2013-06-12 12:13:13 -0700477 else:
478 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700479 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700480
joychen5260b9a2013-07-16 14:48:01 -0700481 @staticmethod
482 def _Symlink(link, target):
483 """Symlinks link to target, and removes whatever link was there before."""
484 _Log("Linking to %s from %s", link, target)
485 if os.path.lexists(link):
486 os.unlink(link)
487 os.symlink(target, link)
488
joychen121fc9b2013-08-02 14:30:30 -0700489 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700490 """Get the version of the latest image built for board by build_image
491
492 Updates the symlink reference within the xBuddy static dir to point to
493 the real image dir in the local /build/images directory.
494
495 Args:
joychenc3944cb2013-08-19 10:42:07 -0700496 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700497
498 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700499 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700500
501 Raises:
502 XBuddyException if neither test nor dev image was found in latest built
503 directory.
joychen3cb228e2013-06-12 12:13:13 -0700504 """
joychen921e1fb2013-06-28 11:12:20 -0700505 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700506 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700507 raise XBuddyException('No builds found for %s. Did you run build_image?' %
508 board)
509
joychen121fc9b2013-08-02 14:30:30 -0700510 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700511 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700512
joychenc3944cb2013-08-19 10:42:07 -0700513 @staticmethod
514 def _FindAny(local_dir):
515 """Returns the image_type for ANY given the local_dir."""
joychenc3944cb2013-08-19 10:42:07 -0700516 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700517 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
518 # Prioritize test images over dev images.
joychenc3944cb2013-08-19 10:42:07 -0700519 if os.path.exists(test_image):
520 return 'test'
521
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700522 if os.path.exists(dev_image):
523 return 'dev'
524
joychenc3944cb2013-08-19 10:42:07 -0700525 raise XBuddyException('No images found in %s' % local_dir)
526
527 @staticmethod
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800528 def _InterpretPath(path, default_board=None, default_version=None):
joychen121fc9b2013-08-02 14:30:30 -0700529 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700530
joychen121fc9b2013-08-02 14:30:30 -0700531 Args:
532 path: the path xBuddy Get was called with.
Chris Sosa0eecf962014-02-03 14:14:39 -0800533 default_board: board to use in case board isn't in path.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800534 default_version: Version to use in case version isn't in path.
joychen3cb228e2013-06-12 12:13:13 -0700535
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800536 Returns:
Chris Sosa75490802013-09-30 17:21:45 -0700537 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 12:13:13 -0700538
539 Raises:
540 XBuddyException: if the path can't be resolved into valid components
541 """
joychen121fc9b2013-08-02 14:30:30 -0700542 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700543
Chris Sosa0eecf962014-02-03 14:14:39 -0800544 # Do the stuff that is well known first. We know that if paths have a
545 # image_type, it must be one of the GS/LOCAL aliases and it must be at the
546 # end. Similarly, local/remote are well-known and must start the path list.
547 is_local = True
548 if path_list and path_list[0] in (REMOTE, LOCAL):
549 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700550
Chris Sosa0eecf962014-02-03 14:14:39 -0800551 # Default image type is determined by remote vs. local.
552 if is_local:
553 image_type = ANY
554 else:
555 image_type = TEST
joychen7df67f72013-07-18 14:21:12 -0700556
Chris Sosa0eecf962014-02-03 14:14:39 -0800557 if path_list and path_list[-1] in GS_ALIASES + LOCAL_ALIASES:
558 image_type = path_list.pop(-1)
joychen3cb228e2013-06-12 12:13:13 -0700559
Chris Sosa0eecf962014-02-03 14:14:39 -0800560 # Now for the tricky part. We don't actually know at this point if the rest
561 # of the path is just a board | version (like R33-2341.0.0) or just a board
562 # or just a version. So we do our best to do the right thing.
563 board = default_board
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800564 version = default_version or LATEST
Chris Sosa0eecf962014-02-03 14:14:39 -0800565 if len(path_list) == 1:
566 path = path_list.pop(0)
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800567 # Treat this as a version if it's one we know (contains default or
568 # latest), or we were given an actual default board.
569 if default_version in path or LATEST in path or default_board is not None:
Chris Sosa0eecf962014-02-03 14:14:39 -0800570 version = path
joychen7df67f72013-07-18 14:21:12 -0700571 else:
Chris Sosa0eecf962014-02-03 14:14:39 -0800572 board = path
joychen7df67f72013-07-18 14:21:12 -0700573
Chris Sosa0eecf962014-02-03 14:14:39 -0800574 elif len(path_list) == 2:
575 # Assumes board/version.
576 board = path_list.pop(0)
577 version = path_list.pop(0)
578
579 if path_list:
580 raise XBuddyException("Path isn't valid. Could not figure out how to "
581 "parse remaining components: %s." % path_list)
582
583 _Log("Get artifact '%s' with board %s and version %s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700584 image_type, board, version, is_local)
585
586 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700587
joychen921e1fb2013-06-28 11:12:20 -0700588 def _SyncRegistryWithBuildImages(self):
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800589 """Crawl images_dir for build_ids of images generated from build_image.
joychen5260b9a2013-07-16 14:48:01 -0700590
591 This will find images and symlink them in xBuddy's static dir so that
592 xBuddy's cache can serve them.
593 If xBuddy's _manage_builds option is on, then a timestamp will also be
594 generated, and xBuddy will clear them from the directory they are in, as
595 necessary.
596 """
Yu-Ju Hong235d1b52014-04-16 11:01:47 -0700597 if not os.path.isdir(self.images_dir):
598 # Skip syncing if images_dir does not exist.
599 _Log('Cannot find %s; skip syncing image registry.', self.images_dir)
600 return
601
joychen921e1fb2013-06-28 11:12:20 -0700602 build_ids = []
603 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700604 # Ensure we have directories to track all boards in build/images
605 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700606 board_dir = os.path.join(self.images_dir, b)
607 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700608 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700609
joychen121fc9b2013-08-02 14:30:30 -0700610 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700611 for build_id in build_ids:
612 link = os.path.join(self.static_dir, build_id)
613 target = os.path.join(self.images_dir, build_id)
614 XBuddy._Symlink(link, target)
615 if self._manage_builds:
616 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700617
618 def _ListBuildTimes(self):
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800619 """Returns the currently cached builds and their last access timestamp.
joychen3cb228e2013-06-12 12:13:13 -0700620
621 Returns:
622 list of tuples that matches xBuddy build/version to timestamps in long
623 """
joychen121fc9b2013-08-02 14:30:30 -0700624 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700625 build_dict = {}
626
joychen7df67f72013-07-18 14:21:12 -0700627 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700628 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
629 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700630 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700631 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700632 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
633 return return_tup
634
Chris Sosa75490802013-09-30 17:21:45 -0700635 def _Download(self, gs_url, artifacts):
636 """Download the artifacts from the given gs_url.
637
638 Raises:
639 build_artifact.ArtifactDownloadError: If we failed to download the
640 artifact.
641 """
joychen3cb228e2013-06-12 12:13:13 -0700642 with XBuddy._staging_thread_count_lock:
643 XBuddy._staging_thread_count += 1
644 try:
Chris Sosa75490802013-09-30 17:21:45 -0700645 _Log("Downloading %s from %s", artifacts, gs_url)
646 downloader.Downloader(self.static_dir, gs_url).Download(artifacts, [])
joychen3cb228e2013-06-12 12:13:13 -0700647 finally:
648 with XBuddy._staging_thread_count_lock:
649 XBuddy._staging_thread_count -= 1
650
Chris Sosa75490802013-09-30 17:21:45 -0700651 def CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700652 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700653 if not self._manage_builds:
654 return
joychen921e1fb2013-06-28 11:12:20 -0700655 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700656 _Log('In cache now: %s', cached_builds)
657
joychen562699a2013-08-13 15:22:14 -0700658 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700659 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700660 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700661
662 time_file = os.path.join(self._timestamp_folder,
663 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700664 os.unlink(time_file)
665 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700666 try:
joychen121fc9b2013-08-02 14:30:30 -0700667 # Handle symlinks, in the case of links to local builds if enabled.
668 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700669 target = os.readlink(clear_dir)
670 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700671
672 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700673 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700674 shutil.rmtree(target)
675 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700676 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700677 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700678
joychen121fc9b2013-08-02 14:30:30 -0700679 except Exception as err:
680 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700681
Simran Basi99e63c02014-05-20 10:39:52 -0700682 def _GetFromGS(self, build_id, image_type, image_dir=None):
Chris Sosa75490802013-09-30 17:21:45 -0700683 """Check if the artifact is available locally. Download from GS if not.
684
Simran Basi99e63c02014-05-20 10:39:52 -0700685 Args:
686 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 image_type: Image type to download. Look at aliases at top of file for
689 options.
690 image_dir: Google Storage image archive to search in if requesting a
691 remote artifact. If none uses the default bucket.
692
Chris Sosa75490802013-09-30 17:21:45 -0700693 Raises:
694 build_artifact.ArtifactDownloadError: If we failed to download the
695 artifact.
696 """
Simran Basi99e63c02014-05-20 10:39:52 -0700697 image_dir = XBuddy._ResolveImageDir(image_dir)
698 gs_url = os.path.join(image_dir, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700699
joychen121fc9b2013-08-02 14:30:30 -0700700 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700701 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700702 file_loc = os.path.join(self.static_dir, build_id, file_name)
703 cached = os.path.exists(file_loc)
704
joychen921e1fb2013-06-28 11:12:20 -0700705 if not cached:
Chris Sosa75490802013-09-30 17:21:45 -0700706 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
707 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 11:12:20 -0700708 else:
709 _Log('Image already cached.')
710
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800711 def _GetArtifact(self, path_list, board=None, version=None,
712 lookup_only=False, image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700713 """Interpret an xBuddy path and return directory/file_name to resource.
714
Chris Sosa75490802013-09-30 17:21:45 -0700715 Note board can be passed that in but by default if self._board is set,
716 that is used rather than board.
717
Simran Basi99e63c02014-05-20 10:39:52 -0700718 Args:
719 path_list: [board, version, alias] as split from the xbuddy call url.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800720 board: Board whos artifacts we are looking for. Only used if no board was
721 given during XBuddy initialization.
722 version: Version whose artifacts we are looking for. Used if no version
723 was given during XBuddy initialization. If None, defers to LATEST.
Simran Basi99e63c02014-05-20 10:39:52 -0700724 lookup_only: If true just look up the artifact, if False stage it on
725 the devserver as well.
726 image_dir: Google Storage image archive to search in if requesting a
727 remote artifact. If none uses the default bucket.
728
joychen346531c2013-07-24 16:55:56 -0700729 Returns:
Simran Basi99e63c02014-05-20 10:39:52 -0700730 build_id: Path to the image or update directory on the devserver or
731 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
732 file_name: of the artifact in the build_id directory.
joychen346531c2013-07-24 16:55:56 -0700733
734 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700735 XBuddyException: if the path could not be translated
Chris Sosa75490802013-09-30 17:21:45 -0700736 build_artifact.ArtifactDownloadError: if we failed to download the
737 artifact.
joychen346531c2013-07-24 16:55:56 -0700738 """
joychen121fc9b2013-08-02 14:30:30 -0700739 path = '/'.join(path_list)
Chris Sosa0eecf962014-02-03 14:14:39 -0800740 default_board = self._board if self._board else board
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800741 default_version = self._version or version or LATEST
joychenb0dfe552013-07-30 10:02:06 -0700742 # Rewrite the path if there is an appropriate default.
Gilad Arnold38e828c2015-04-24 13:52:07 -0700743 path, suffix = self.LookupAlias(path, board=default_board,
744 version=default_version)
joychen121fc9b2013-08-02 14:30:30 -0700745 # Parse the path.
Chris Sosa0eecf962014-02-03 14:14:39 -0800746 image_type, board, version, is_local = self._InterpretPath(
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800747 path, default_board, default_version)
joychen7df67f72013-07-18 14:21:12 -0700748 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700749 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700750 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700751 # Get the latest local image for the given board.
752 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700753
joychenc3944cb2013-08-19 10:42:07 -0700754 build_id = os.path.join(board, version)
755 artifact_dir = os.path.join(self.static_dir, build_id)
756 if image_type == ANY:
757 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700758
joychenc3944cb2013-08-19 10:42:07 -0700759 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
760 artifact_path = os.path.join(artifact_dir, file_name)
761 if not os.path.exists(artifact_path):
762 raise XBuddyException('Local %s artifact not in static_dir at %s' %
763 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700764
joychen921e1fb2013-06-28 11:12:20 -0700765 else:
joychen121fc9b2013-08-02 14:30:30 -0700766 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700767 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700768 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700769 (image_type, GS_ALIASES))
Gilad Arnold896c6d82015-03-13 16:20:29 -0700770 build_id = self._ResolveVersionToBuildId(board, suffix, version,
Simran Basi99e63c02014-05-20 10:39:52 -0700771 image_dir=image_dir)
Chris Sosa75490802013-09-30 17:21:45 -0700772 _Log('Resolved version %s to %s.', version, build_id)
773 file_name = GS_ALIAS_TO_FILENAME[image_type]
774 if not lookup_only:
Simran Basi99e63c02014-05-20 10:39:52 -0700775 self._GetFromGS(build_id, image_type, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700776
joychenc3944cb2013-08-19 10:42:07 -0700777 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700778
779 ############################ BEGIN PUBLIC METHODS
780
781 def List(self):
782 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700783 self._SyncRegistryWithBuildImages()
784 builds = self._ListBuildTimes()
785 return_string = ''
786 for build, timestamp in builds:
787 return_string += '<b>' + build + '</b> '
788 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
789 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700790
791 def Capacity(self):
792 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700793 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700794
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800795 def Translate(self, path_list, board=None, version=None, image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700796 """Translates an xBuddy path to a real path to artifact if it exists.
797
joychen121fc9b2013-08-02 14:30:30 -0700798 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700799
Simran Basi99e63c02014-05-20 10:39:52 -0700800 Args:
801 path_list: [board, version, alias] as split from the xbuddy call url.
802 board: Board whos artifacts we are looking for. If None, use the board
803 XBuddy was initialized to use.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800804 version: Version whose artifacts we are looking for. If None, use the
805 version XBuddy was initialized with, or LATEST.
Simran Basi99e63c02014-05-20 10:39:52 -0700806 image_dir: image directory to check in Google Storage. If none,
807 the default bucket is used.
808
joychen7c2054a2013-07-25 11:14:07 -0700809 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700810 build_id: Path to the image or update directory on the devserver.
811 e.g. 'x86-generic/R26-4000.0.0'
812 The returned path is always the path to the directory within
813 static_dir, so it is always the build_id of the image.
814 file_name: The file name of the artifact. Can take any of the file
815 values in devserver_constants.
816 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
817 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700818
joychen121fc9b2013-08-02 14:30:30 -0700819 Raises:
820 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700821 """
822 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700823 build_id, file_name = self._GetArtifact(path_list, board=board,
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800824 version=version,
Simran Basi99e63c02014-05-20 10:39:52 -0700825 lookup_only=True,
826 image_dir=image_dir)
joychen346531c2013-07-24 16:55:56 -0700827
joychen121fc9b2013-08-02 14:30:30 -0700828 _Log('Returning path to payload: %s/%s', build_id, file_name)
829 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700830
Yu-Ju Hong1bdb7a92014-04-10 16:02:11 -0700831 def StageTestArtifactsForUpdate(self, path_list):
Chris Sosa75490802013-09-30 17:21:45 -0700832 """Stages test artifacts for update and returns build_id.
833
834 Raises:
835 XBuddyException: if the path could not be translated
836 build_artifact.ArtifactDownloadError: if we failed to download the test
837 artifacts.
838 """
839 build_id, file_name = self.Translate(path_list)
840 if file_name == devserver_constants.TEST_IMAGE_FILE:
841 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
842 build_id)
843 artifacts = [FULL, STATEFUL]
844 self._Download(gs_url, artifacts)
845 return build_id
846
Simran Basi99e63c02014-05-20 10:39:52 -0700847 def Get(self, path_list, image_dir=None):
joychen921e1fb2013-06-28 11:12:20 -0700848 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700849
850 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700851
joychen3cb228e2013-06-12 12:13:13 -0700852 Args:
Simran Basi99e63c02014-05-20 10:39:52 -0700853 path_list: [board, version, alias] as split from the xbuddy call url.
854 image_dir: image directory to check in Google Storage. If none,
855 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700856
857 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700858 build_id: Path to the image or update directory on the devserver.
Simran Basi99e63c02014-05-20 10:39:52 -0700859 e.g. 'x86-generic/R26-4000.0.0'
860 The returned path is always the path to the directory within
861 static_dir, so it is always the build_id of the image.
joychen121fc9b2013-08-02 14:30:30 -0700862 file_name: The file name of the artifact. Can take any of the file
Simran Basi99e63c02014-05-20 10:39:52 -0700863 values in devserver_constants.
864 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
865 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700866
867 Raises:
Chris Sosa75490802013-09-30 17:21:45 -0700868 XBuddyException: if the path could not be translated
869 build_artifact.ArtifactDownloadError: if we failed to download the
870 artifact.
joychen3cb228e2013-06-12 12:13:13 -0700871 """
joychen7df67f72013-07-18 14:21:12 -0700872 self._SyncRegistryWithBuildImages()
Simran Basi99e63c02014-05-20 10:39:52 -0700873 build_id, file_name = self._GetArtifact(path_list, image_dir=image_dir)
joychen921e1fb2013-06-28 11:12:20 -0700874 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700875 #TODO (joyc): run in sep thread
Chris Sosa75490802013-09-30 17:21:45 -0700876 self.CleanCache()
joychen3cb228e2013-06-12 12:13:13 -0700877
joychen121fc9b2013-08-02 14:30:30 -0700878 _Log('Returning path to payload: %s/%s', build_id, file_name)
879 return build_id, file_name