blob: 36cc8b227310aaa930940be94f2838b3778f3c98 [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 Arnoldd04fcab2015-02-19 12:00:45 -0800270 def _LookupAlias(self, alias, board, version):
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
277 the update request xml or the default board from devserver.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800278 version: The version to fill in when rewriting paths. Could be a specific
279 version number or a version alias like LATEST.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800280
joychen562699a2013-08-13 15:22:14 -0700281 Returns:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700282 A pair (val, suffix) where val is the rewritten path, or the original
283 string if no rewrite was found; and suffix is the assigned location
284 suffix, or the default suffix if none was found.
joychen562699a2013-08-13 15:22:14 -0700285 """
joychen562699a2013-08-13 15:22:14 -0700286 try:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700287 suffix = self.config.get(LOCATION_SUFFIXES, alias)
288 except ConfigParser.Error:
289 suffix = RELEASE
290
291 try:
joychen562699a2013-08-13 15:22:14 -0700292 val = self.config.get(PATH_REWRITES, alias)
293 except ConfigParser.Error:
294 # No alias lookup found. Return original path.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700295 val = None
joychen562699a2013-08-13 15:22:14 -0700296
Gilad Arnold896c6d82015-03-13 16:20:29 -0700297 if not (val and val.strip()):
298 val = alias
joychen562699a2013-08-13 15:22:14 -0700299 else:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700300 # The found value is not an empty string.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800301 # Fill in the board and version.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700302 val = val.replace("BOARD", "%(board)s")
303 val = val.replace("VERSION", "%(version)s")
304 val = val % {'board': board, 'version': version}
305
306 _Log("Path is %s, location suffix is %s", val, suffix)
307 return val, suffix
joychen562699a2013-08-13 15:22:14 -0700308
Simran Basi99e63c02014-05-20 10:39:52 -0700309 @staticmethod
310 def _ResolveImageDir(image_dir):
311 """Clean up and return the image dir to use.
312
313 Args:
314 image_dir: directory in Google Storage to use.
315
316 Returns:
317 |image_dir| if |image_dir| is not None. Otherwise, returns
318 devserver_constants.GS_IMAGE_DIR
319 """
320 image_dir = image_dir or devserver_constants.GS_IMAGE_DIR
321 # Remove trailing slashes.
322 return image_dir.rstrip('/')
323
Gilad Arnold896c6d82015-03-13 16:20:29 -0700324 def _LookupOfficial(self, board, suffix, image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700325 """Check LATEST-master for the version number of interest."""
326 _Log("Checking gs for latest %s-%s image", board, suffix)
Simran Basi99e63c02014-05-20 10:39:52 -0700327 image_dir = XBuddy._ResolveImageDir(image_dir)
328 latest_addr = (devserver_constants.GS_LATEST_MASTER %
329 {'image_dir': image_dir,
330 'board': board,
331 'suffix': suffix})
joychenf8f07e22013-07-12 17:45:51 -0700332 cmd = 'gsutil cat %s' % latest_addr
333 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700334 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700335 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700336
joychenf8f07e22013-07-12 17:45:51 -0700337 return devserver_constants.IMAGE_DIR % {'board':board,
338 'suffix':suffix,
339 'version':version}
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800340
Gilad Arnold896c6d82015-03-13 16:20:29 -0700341 def _LookupChannel(self, board, suffix, channel='stable',
342 image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700343 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700344 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700345 _Log("Checking channel '%s' for latest '%s' image", channel, board)
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800346 # Due to historical reasons, gs://chromeos-releases uses
347 # daisy-spring as opposed to the board name daisy_spring. Convert
348 # the board name for the lookup.
349 channel_dir = devserver_constants.GS_CHANNEL_DIR % {
350 'channel':channel,
351 'board':re.sub('_', '-', board)}
joychen562699a2013-08-13 15:22:14 -0700352 latest_version = gsutil_util.GetLatestVersionFromGSDir(
353 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700354
joychen121fc9b2013-08-02 14:30:30 -0700355 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700356 image_url = devserver_constants.IMAGE_DIR % {
Gilad Arnold896c6d82015-03-13 16:20:29 -0700357 'board': board,
358 'suffix': suffix,
359 'version': 'R*' + latest_version}
Simran Basi99e63c02014-05-20 10:39:52 -0700360 image_dir = XBuddy._ResolveImageDir(image_dir)
361 gs_url = os.path.join(image_dir, image_url)
joychenf8f07e22013-07-12 17:45:51 -0700362
363 # There should only be one match on cros-image-archive.
Simran Basi99e63c02014-05-20 10:39:52 -0700364 full_version = gsutil_util.GetLatestVersionFromGSDir(gs_url)
joychenf8f07e22013-07-12 17:45:51 -0700365
Gilad Arnold896c6d82015-03-13 16:20:29 -0700366 return devserver_constants.IMAGE_DIR % {'board': board,
367 'suffix': suffix,
368 'version': full_version}
joychenf8f07e22013-07-12 17:45:51 -0700369
Gilad Arnold896c6d82015-03-13 16:20:29 -0700370 def _LookupVersion(self, board, suffix, version):
joychenf8f07e22013-07-12 17:45:51 -0700371 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700372 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700373 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700374 image_url = devserver_constants.IMAGE_DIR % {'board': board,
375 'suffix': suffix,
376 'version': version + '*'}
joychenf8f07e22013-07-12 17:45:51 -0700377 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
378
joychen121fc9b2013-08-02 14:30:30 -0700379 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700380 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700381 return devserver_constants.IMAGE_DIR % {'board': board,
382 'suffix': suffix,
383 'version': full_version}
joychenf8f07e22013-07-12 17:45:51 -0700384
Gilad Arnold896c6d82015-03-13 16:20:29 -0700385 def _RemoteBuildId(self, board, suffix, version):
Chris Sosaea734d92013-10-11 11:28:58 -0700386 """Returns the remote build_id for the given board and version.
387
388 Raises:
389 XBuddyException: If we failed to resolve the version to a valid build_id.
390 """
Gilad Arnold896c6d82015-03-13 16:20:29 -0700391 build_id_as_is = devserver_constants.IMAGE_DIR % {'board': board,
392 'suffix': '',
393 'version': version}
394 build_id_suffix = devserver_constants.IMAGE_DIR % {'board': board,
395 'suffix': suffix,
396 'version': version}
Chris Sosaea734d92013-10-11 11:28:58 -0700397 # Return the first path that exists. We assume that what the user typed
398 # is better than with a default suffix added i.e. x86-generic/blah is
399 # more valuable than x86-generic-release/blah.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700400 for build_id in build_id_as_is, build_id_suffix:
Chris Sosaea734d92013-10-11 11:28:58 -0700401 cmd = 'gsutil ls %s/%s' % (devserver_constants.GS_IMAGE_DIR, build_id)
402 try:
403 version = gsutil_util.GSUtilRun(cmd, None)
404 return build_id
405 except gsutil_util.GSUtilError:
406 continue
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800407
408 raise XBuddyException('Could not find remote build_id for %s %s' % (
409 board, version))
Chris Sosaea734d92013-10-11 11:28:58 -0700410
Gilad Arnold896c6d82015-03-13 16:20:29 -0700411 def _ResolveBuildVersion(self, board, suffix, base_version):
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800412 """Check LATEST-<base_version> and returns a full build version."""
413 _Log('Checking gs for full version for %s of %s', base_version, board)
414 # TODO(garnold) We might want to accommodate version prefixes and pick the
415 # most recent found, as done in _LookupVersion().
416 latest_addr = (devserver_constants.GS_LATEST_BASE_VERSION %
417 {'image_dir': devserver_constants.GS_IMAGE_DIR,
418 'board': board,
Gilad Arnold896c6d82015-03-13 16:20:29 -0700419 'suffix': suffix,
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800420 'base_version': base_version})
421 cmd = 'gsutil cat %s' % latest_addr
422 msg = 'Failed to find build at %s' % latest_addr
423 # Full release + version is in the LATEST file.
424 return gsutil_util.GSUtilRun(cmd, msg)
425
Gilad Arnold896c6d82015-03-13 16:20:29 -0700426 def _ResolveVersionToBuildId(self, board, suffix, version, image_dir=None):
joychen121fc9b2013-08-02 14:30:30 -0700427 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700428
429 Args:
430 board: as specified in the original call. (i.e. x86-generic, parrot)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700431 suffix: The location suffix, to be added to board name.
joychen3cb228e2013-06-12 12:13:13 -0700432 version: as entered in the original call. can be
433 {TBD, 0. some custom alias as defined in a config file}
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800434 1. fully qualified build version or base version.
435 2. latest
436 3. latest-{channel}
437 4. latest-official-{board suffix}
438 5. version prefix (i.e. RX-Y.X, RX-Y, RX)
Simran Basi99e63c02014-05-20 10:39:52 -0700439 image_dir: image directory to check in Google Storage. If none,
440 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700441
442 Returns:
Chris Sosaea734d92013-10-11 11:28:58 -0700443 Location where the image dir is actually found on GS (build_id)
joychen3cb228e2013-06-12 12:13:13 -0700444
Chris Sosaea734d92013-10-11 11:28:58 -0700445 Raises:
446 XBuddyException: If we failed to resolve the version to a valid url.
joychen3cb228e2013-06-12 12:13:13 -0700447 """
joychenf8f07e22013-07-12 17:45:51 -0700448 # Only the last segment of the alias is variable relative to the rest.
449 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700450
joychenf8f07e22013-07-12 17:45:51 -0700451 if re.match(devserver_constants.VERSION_RE, version):
Gilad Arnold896c6d82015-03-13 16:20:29 -0700452 return self._RemoteBuildId(board, suffix, version)
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800453 elif re.match(devserver_constants.VERSION, version):
Gilad Arnold896c6d82015-03-13 16:20:29 -0700454 return self._RemoteBuildId(
455 board, suffix, self._ResolveBuildVersion(board, suffix, version))
joychenf8f07e22013-07-12 17:45:51 -0700456 elif version == LATEST_OFFICIAL:
457 # latest-official --> LATEST build in board-release
Gilad Arnold896c6d82015-03-13 16:20:29 -0700458 return self._LookupOfficial(board, suffix, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700459 elif version_tuple[0] == LATEST_OFFICIAL:
460 # latest-official-{suffix} --> LATEST build in board-{suffix}
Gilad Arnold896c6d82015-03-13 16:20:29 -0700461 return self._LookupOfficial(board, version_tuple[1],
462 image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700463 elif version == LATEST:
464 # latest --> latest build on stable channel
Gilad Arnold896c6d82015-03-13 16:20:29 -0700465 return self._LookupChannel(board, suffix, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700466 elif version_tuple[0] == LATEST:
467 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
468 # latest-R* --> most recent qualifying build
Gilad Arnold896c6d82015-03-13 16:20:29 -0700469 return self._LookupVersion(board, suffix, version_tuple[1])
joychenf8f07e22013-07-12 17:45:51 -0700470 else:
471 # latest-{channel} --> latest build within that channel
Gilad Arnold896c6d82015-03-13 16:20:29 -0700472 return self._LookupChannel(board, suffix, channel=version_tuple[1],
Simran Basi99e63c02014-05-20 10:39:52 -0700473 image_dir=image_dir)
joychen3cb228e2013-06-12 12:13:13 -0700474 else:
475 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700476 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700477
joychen5260b9a2013-07-16 14:48:01 -0700478 @staticmethod
479 def _Symlink(link, target):
480 """Symlinks link to target, and removes whatever link was there before."""
481 _Log("Linking to %s from %s", link, target)
482 if os.path.lexists(link):
483 os.unlink(link)
484 os.symlink(target, link)
485
joychen121fc9b2013-08-02 14:30:30 -0700486 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700487 """Get the version of the latest image built for board by build_image
488
489 Updates the symlink reference within the xBuddy static dir to point to
490 the real image dir in the local /build/images directory.
491
492 Args:
joychenc3944cb2013-08-19 10:42:07 -0700493 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700494
495 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700496 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700497
498 Raises:
499 XBuddyException if neither test nor dev image was found in latest built
500 directory.
joychen3cb228e2013-06-12 12:13:13 -0700501 """
joychen921e1fb2013-06-28 11:12:20 -0700502 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700503 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700504 raise XBuddyException('No builds found for %s. Did you run build_image?' %
505 board)
506
joychen121fc9b2013-08-02 14:30:30 -0700507 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700508 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700509
joychenc3944cb2013-08-19 10:42:07 -0700510 @staticmethod
511 def _FindAny(local_dir):
512 """Returns the image_type for ANY given the local_dir."""
joychenc3944cb2013-08-19 10:42:07 -0700513 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700514 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
515 # Prioritize test images over dev images.
joychenc3944cb2013-08-19 10:42:07 -0700516 if os.path.exists(test_image):
517 return 'test'
518
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700519 if os.path.exists(dev_image):
520 return 'dev'
521
joychenc3944cb2013-08-19 10:42:07 -0700522 raise XBuddyException('No images found in %s' % local_dir)
523
524 @staticmethod
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800525 def _InterpretPath(path, default_board=None, default_version=None):
joychen121fc9b2013-08-02 14:30:30 -0700526 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700527
joychen121fc9b2013-08-02 14:30:30 -0700528 Args:
529 path: the path xBuddy Get was called with.
Chris Sosa0eecf962014-02-03 14:14:39 -0800530 default_board: board to use in case board isn't in path.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800531 default_version: Version to use in case version isn't in path.
joychen3cb228e2013-06-12 12:13:13 -0700532
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800533 Returns:
Chris Sosa75490802013-09-30 17:21:45 -0700534 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 12:13:13 -0700535
536 Raises:
537 XBuddyException: if the path can't be resolved into valid components
538 """
joychen121fc9b2013-08-02 14:30:30 -0700539 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700540
Chris Sosa0eecf962014-02-03 14:14:39 -0800541 # Do the stuff that is well known first. We know that if paths have a
542 # image_type, it must be one of the GS/LOCAL aliases and it must be at the
543 # end. Similarly, local/remote are well-known and must start the path list.
544 is_local = True
545 if path_list and path_list[0] in (REMOTE, LOCAL):
546 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700547
Chris Sosa0eecf962014-02-03 14:14:39 -0800548 # Default image type is determined by remote vs. local.
549 if is_local:
550 image_type = ANY
551 else:
552 image_type = TEST
joychen7df67f72013-07-18 14:21:12 -0700553
Chris Sosa0eecf962014-02-03 14:14:39 -0800554 if path_list and path_list[-1] in GS_ALIASES + LOCAL_ALIASES:
555 image_type = path_list.pop(-1)
joychen3cb228e2013-06-12 12:13:13 -0700556
Chris Sosa0eecf962014-02-03 14:14:39 -0800557 # Now for the tricky part. We don't actually know at this point if the rest
558 # of the path is just a board | version (like R33-2341.0.0) or just a board
559 # or just a version. So we do our best to do the right thing.
560 board = default_board
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800561 version = default_version or LATEST
Chris Sosa0eecf962014-02-03 14:14:39 -0800562 if len(path_list) == 1:
563 path = path_list.pop(0)
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800564 # Treat this as a version if it's one we know (contains default or
565 # latest), or we were given an actual default board.
566 if default_version in path or LATEST in path or default_board is not None:
Chris Sosa0eecf962014-02-03 14:14:39 -0800567 version = path
joychen7df67f72013-07-18 14:21:12 -0700568 else:
Chris Sosa0eecf962014-02-03 14:14:39 -0800569 board = path
joychen7df67f72013-07-18 14:21:12 -0700570
Chris Sosa0eecf962014-02-03 14:14:39 -0800571 elif len(path_list) == 2:
572 # Assumes board/version.
573 board = path_list.pop(0)
574 version = path_list.pop(0)
575
576 if path_list:
577 raise XBuddyException("Path isn't valid. Could not figure out how to "
578 "parse remaining components: %s." % path_list)
579
580 _Log("Get artifact '%s' with board %s and version %s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700581 image_type, board, version, is_local)
582
583 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700584
joychen921e1fb2013-06-28 11:12:20 -0700585 def _SyncRegistryWithBuildImages(self):
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800586 """Crawl images_dir for build_ids of images generated from build_image.
joychen5260b9a2013-07-16 14:48:01 -0700587
588 This will find images and symlink them in xBuddy's static dir so that
589 xBuddy's cache can serve them.
590 If xBuddy's _manage_builds option is on, then a timestamp will also be
591 generated, and xBuddy will clear them from the directory they are in, as
592 necessary.
593 """
Yu-Ju Hong235d1b52014-04-16 11:01:47 -0700594 if not os.path.isdir(self.images_dir):
595 # Skip syncing if images_dir does not exist.
596 _Log('Cannot find %s; skip syncing image registry.', self.images_dir)
597 return
598
joychen921e1fb2013-06-28 11:12:20 -0700599 build_ids = []
600 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700601 # Ensure we have directories to track all boards in build/images
602 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700603 board_dir = os.path.join(self.images_dir, b)
604 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700605 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700606
joychen121fc9b2013-08-02 14:30:30 -0700607 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700608 for build_id in build_ids:
609 link = os.path.join(self.static_dir, build_id)
610 target = os.path.join(self.images_dir, build_id)
611 XBuddy._Symlink(link, target)
612 if self._manage_builds:
613 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700614
615 def _ListBuildTimes(self):
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800616 """Returns the currently cached builds and their last access timestamp.
joychen3cb228e2013-06-12 12:13:13 -0700617
618 Returns:
619 list of tuples that matches xBuddy build/version to timestamps in long
620 """
joychen121fc9b2013-08-02 14:30:30 -0700621 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700622 build_dict = {}
623
joychen7df67f72013-07-18 14:21:12 -0700624 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700625 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
626 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700627 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700628 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700629 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
630 return return_tup
631
Chris Sosa75490802013-09-30 17:21:45 -0700632 def _Download(self, gs_url, artifacts):
633 """Download the artifacts from the given gs_url.
634
635 Raises:
636 build_artifact.ArtifactDownloadError: If we failed to download the
637 artifact.
638 """
joychen3cb228e2013-06-12 12:13:13 -0700639 with XBuddy._staging_thread_count_lock:
640 XBuddy._staging_thread_count += 1
641 try:
Chris Sosa75490802013-09-30 17:21:45 -0700642 _Log("Downloading %s from %s", artifacts, gs_url)
643 downloader.Downloader(self.static_dir, gs_url).Download(artifacts, [])
joychen3cb228e2013-06-12 12:13:13 -0700644 finally:
645 with XBuddy._staging_thread_count_lock:
646 XBuddy._staging_thread_count -= 1
647
Chris Sosa75490802013-09-30 17:21:45 -0700648 def CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700649 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700650 if not self._manage_builds:
651 return
joychen921e1fb2013-06-28 11:12:20 -0700652 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700653 _Log('In cache now: %s', cached_builds)
654
joychen562699a2013-08-13 15:22:14 -0700655 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700656 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700657 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700658
659 time_file = os.path.join(self._timestamp_folder,
660 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700661 os.unlink(time_file)
662 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700663 try:
joychen121fc9b2013-08-02 14:30:30 -0700664 # Handle symlinks, in the case of links to local builds if enabled.
665 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700666 target = os.readlink(clear_dir)
667 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700668
669 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700670 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700671 shutil.rmtree(target)
672 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700673 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700674 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700675
joychen121fc9b2013-08-02 14:30:30 -0700676 except Exception as err:
677 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700678
Simran Basi99e63c02014-05-20 10:39:52 -0700679 def _GetFromGS(self, build_id, image_type, image_dir=None):
Chris Sosa75490802013-09-30 17:21:45 -0700680 """Check if the artifact is available locally. Download from GS if not.
681
Simran Basi99e63c02014-05-20 10:39:52 -0700682 Args:
683 build_id: Path to the image or update directory on the devserver or
684 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
685 image_type: Image type to download. Look at aliases at top of file for
686 options.
687 image_dir: Google Storage image archive to search in if requesting a
688 remote artifact. If none uses the default bucket.
689
Chris Sosa75490802013-09-30 17:21:45 -0700690 Raises:
691 build_artifact.ArtifactDownloadError: If we failed to download the
692 artifact.
693 """
Simran Basi99e63c02014-05-20 10:39:52 -0700694 image_dir = XBuddy._ResolveImageDir(image_dir)
695 gs_url = os.path.join(image_dir, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700696
joychen121fc9b2013-08-02 14:30:30 -0700697 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700698 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700699 file_loc = os.path.join(self.static_dir, build_id, file_name)
700 cached = os.path.exists(file_loc)
701
joychen921e1fb2013-06-28 11:12:20 -0700702 if not cached:
Chris Sosa75490802013-09-30 17:21:45 -0700703 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
704 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 11:12:20 -0700705 else:
706 _Log('Image already cached.')
707
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800708 def _GetArtifact(self, path_list, board=None, version=None,
709 lookup_only=False, image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700710 """Interpret an xBuddy path and return directory/file_name to resource.
711
Chris Sosa75490802013-09-30 17:21:45 -0700712 Note board can be passed that in but by default if self._board is set,
713 that is used rather than board.
714
Simran Basi99e63c02014-05-20 10:39:52 -0700715 Args:
716 path_list: [board, version, alias] as split from the xbuddy call url.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800717 board: Board whos artifacts we are looking for. Only used if no board was
718 given during XBuddy initialization.
719 version: Version whose artifacts we are looking for. Used if no version
720 was given during XBuddy initialization. If None, defers to LATEST.
Simran Basi99e63c02014-05-20 10:39:52 -0700721 lookup_only: If true just look up the artifact, if False stage it on
722 the devserver as well.
723 image_dir: Google Storage image archive to search in if requesting a
724 remote artifact. If none uses the default bucket.
725
joychen346531c2013-07-24 16:55:56 -0700726 Returns:
Simran Basi99e63c02014-05-20 10:39:52 -0700727 build_id: Path to the image or update directory on the devserver or
728 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
729 file_name: of the artifact in the build_id directory.
joychen346531c2013-07-24 16:55:56 -0700730
731 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700732 XBuddyException: if the path could not be translated
Chris Sosa75490802013-09-30 17:21:45 -0700733 build_artifact.ArtifactDownloadError: if we failed to download the
734 artifact.
joychen346531c2013-07-24 16:55:56 -0700735 """
joychen121fc9b2013-08-02 14:30:30 -0700736 path = '/'.join(path_list)
Chris Sosa0eecf962014-02-03 14:14:39 -0800737 default_board = self._board if self._board else board
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800738 default_version = self._version or version or LATEST
joychenb0dfe552013-07-30 10:02:06 -0700739 # Rewrite the path if there is an appropriate default.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700740 path, suffix = self._LookupAlias(path, default_board, default_version)
joychen121fc9b2013-08-02 14:30:30 -0700741 # Parse the path.
Chris Sosa0eecf962014-02-03 14:14:39 -0800742 image_type, board, version, is_local = self._InterpretPath(
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800743 path, default_board, default_version)
joychen7df67f72013-07-18 14:21:12 -0700744 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700745 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700746 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700747 # Get the latest local image for the given board.
748 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700749
joychenc3944cb2013-08-19 10:42:07 -0700750 build_id = os.path.join(board, version)
751 artifact_dir = os.path.join(self.static_dir, build_id)
752 if image_type == ANY:
753 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700754
joychenc3944cb2013-08-19 10:42:07 -0700755 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
756 artifact_path = os.path.join(artifact_dir, file_name)
757 if not os.path.exists(artifact_path):
758 raise XBuddyException('Local %s artifact not in static_dir at %s' %
759 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700760
joychen921e1fb2013-06-28 11:12:20 -0700761 else:
joychen121fc9b2013-08-02 14:30:30 -0700762 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700763 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700764 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700765 (image_type, GS_ALIASES))
Gilad Arnold896c6d82015-03-13 16:20:29 -0700766 build_id = self._ResolveVersionToBuildId(board, suffix, version,
Simran Basi99e63c02014-05-20 10:39:52 -0700767 image_dir=image_dir)
Chris Sosa75490802013-09-30 17:21:45 -0700768 _Log('Resolved version %s to %s.', version, build_id)
769 file_name = GS_ALIAS_TO_FILENAME[image_type]
770 if not lookup_only:
Simran Basi99e63c02014-05-20 10:39:52 -0700771 self._GetFromGS(build_id, image_type, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700772
joychenc3944cb2013-08-19 10:42:07 -0700773 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700774
775 ############################ BEGIN PUBLIC METHODS
776
777 def List(self):
778 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700779 self._SyncRegistryWithBuildImages()
780 builds = self._ListBuildTimes()
781 return_string = ''
782 for build, timestamp in builds:
783 return_string += '<b>' + build + '</b> '
784 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
785 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700786
787 def Capacity(self):
788 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700789 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700790
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800791 def Translate(self, path_list, board=None, version=None, image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700792 """Translates an xBuddy path to a real path to artifact if it exists.
793
joychen121fc9b2013-08-02 14:30:30 -0700794 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700795
Simran Basi99e63c02014-05-20 10:39:52 -0700796 Args:
797 path_list: [board, version, alias] as split from the xbuddy call url.
798 board: Board whos artifacts we are looking for. If None, use the board
799 XBuddy was initialized to use.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800800 version: Version whose artifacts we are looking for. If None, use the
801 version XBuddy was initialized with, or LATEST.
Simran Basi99e63c02014-05-20 10:39:52 -0700802 image_dir: image directory to check in Google Storage. If none,
803 the default bucket is used.
804
joychen7c2054a2013-07-25 11:14:07 -0700805 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700806 build_id: Path to the image or update directory on the devserver.
807 e.g. 'x86-generic/R26-4000.0.0'
808 The returned path is always the path to the directory within
809 static_dir, so it is always the build_id of the image.
810 file_name: The file name of the artifact. Can take any of the file
811 values in devserver_constants.
812 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
813 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700814
joychen121fc9b2013-08-02 14:30:30 -0700815 Raises:
816 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700817 """
818 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700819 build_id, file_name = self._GetArtifact(path_list, board=board,
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800820 version=version,
Simran Basi99e63c02014-05-20 10:39:52 -0700821 lookup_only=True,
822 image_dir=image_dir)
joychen346531c2013-07-24 16:55:56 -0700823
joychen121fc9b2013-08-02 14:30:30 -0700824 _Log('Returning path to payload: %s/%s', build_id, file_name)
825 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700826
Yu-Ju Hong1bdb7a92014-04-10 16:02:11 -0700827 def StageTestArtifactsForUpdate(self, path_list):
Chris Sosa75490802013-09-30 17:21:45 -0700828 """Stages test artifacts for update and returns build_id.
829
830 Raises:
831 XBuddyException: if the path could not be translated
832 build_artifact.ArtifactDownloadError: if we failed to download the test
833 artifacts.
834 """
835 build_id, file_name = self.Translate(path_list)
836 if file_name == devserver_constants.TEST_IMAGE_FILE:
837 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
838 build_id)
839 artifacts = [FULL, STATEFUL]
840 self._Download(gs_url, artifacts)
841 return build_id
842
Simran Basi99e63c02014-05-20 10:39:52 -0700843 def Get(self, path_list, image_dir=None):
joychen921e1fb2013-06-28 11:12:20 -0700844 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700845
846 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700847
joychen3cb228e2013-06-12 12:13:13 -0700848 Args:
Simran Basi99e63c02014-05-20 10:39:52 -0700849 path_list: [board, version, alias] as split from the xbuddy call url.
850 image_dir: image directory to check in Google Storage. If none,
851 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700852
853 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700854 build_id: Path to the image or update directory on the devserver.
Simran Basi99e63c02014-05-20 10:39:52 -0700855 e.g. 'x86-generic/R26-4000.0.0'
856 The returned path is always the path to the directory within
857 static_dir, so it is always the build_id of the image.
joychen121fc9b2013-08-02 14:30:30 -0700858 file_name: The file name of the artifact. Can take any of the file
Simran Basi99e63c02014-05-20 10:39:52 -0700859 values in devserver_constants.
860 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
861 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700862
863 Raises:
Chris Sosa75490802013-09-30 17:21:45 -0700864 XBuddyException: if the path could not be translated
865 build_artifact.ArtifactDownloadError: if we failed to download the
866 artifact.
joychen3cb228e2013-06-12 12:13:13 -0700867 """
joychen7df67f72013-07-18 14:21:12 -0700868 self._SyncRegistryWithBuildImages()
Simran Basi99e63c02014-05-20 10:39:52 -0700869 build_id, file_name = self._GetArtifact(path_list, image_dir=image_dir)
joychen921e1fb2013-06-28 11:12:20 -0700870 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700871 #TODO (joyc): run in sep thread
Chris Sosa75490802013-09-30 17:21:45 -0700872 self.CleanCache()
joychen3cb228e2013-06-12 12:13:13 -0700873
joychen121fc9b2013-08-02 14:30:30 -0700874 _Log('Returning path to payload: %s/%s', build_id, file_name)
875 return build_id, file_name