blob: d0bd8e3410e691070fbe7c9d926d92e2d1d92006 [file] [log] [blame]
joychen3cb228e2013-06-12 12:13:13 -07001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Chris Sosa0eecf962014-02-03 14:14:39 -08005"""Main module for parsing and interpreting XBuddy paths for the devserver."""
6
Gilad Arnold5f46d8e2015-02-19 12:17:55 -08007from __future__ import print_function
8
Yiming Chenaab488e2014-11-17 14:49:31 -08009import cherrypy
joychen562699a2013-08-13 15:22:14 -070010import ConfigParser
joychen3cb228e2013-06-12 12:13:13 -070011import datetime
12import operator
13import os
joychenf8f07e22013-07-12 17:45:51 -070014import re
joychen3cb228e2013-06-12 12:13:13 -070015import shutil
joychenf8f07e22013-07-12 17:45:51 -070016import time
joychen3cb228e2013-06-12 12:13:13 -070017import threading
18
19import artifact_info
Gabe Black3b567202015-09-23 14:07:59 -070020import build_artifact
21import build_util
joychen3cb228e2013-06-12 12:13:13 -070022import common_util
23import devserver_constants
24import downloader
joychenf8f07e22013-07-12 17:45:51 -070025import gsutil_util
joychen3cb228e2013-06-12 12:13:13 -070026import log_util
27
28# Module-local log function.
29def _Log(message, *args):
30 return log_util.LogWithTag('XBUDDY', message, *args)
31
joychen562699a2013-08-13 15:22:14 -070032# xBuddy config constants
33CONFIG_FILE = 'xbuddy_config.ini'
34SHADOW_CONFIG_FILE = 'shadow_xbuddy_config.ini'
35PATH_REWRITES = 'PATH_REWRITES'
36GENERAL = 'GENERAL'
Gilad Arnold896c6d82015-03-13 16:20:29 -070037LOCATION_SUFFIXES = 'LOCATION_SUFFIXES'
joychen921e1fb2013-06-28 11:12:20 -070038
Chris Sosac2abc722013-08-26 17:11:22 -070039# Path for shadow config in chroot.
40CHROOT_SHADOW_DIR = '/mnt/host/source/src/platform/dev'
41
joychen25d25972013-07-30 14:54:16 -070042# XBuddy aliases
43TEST = 'test'
44BASE = 'base'
45DEV = 'dev'
46FULL = 'full_payload'
47RECOVERY = 'recovery'
48STATEFUL = 'stateful'
49AUTOTEST = 'autotest'
Mike Frysingera0e6a282016-09-01 17:29:08 -040050FACTORY_SHIM = 'factory_shim'
joychen25d25972013-07-30 14:54:16 -070051
joychen921e1fb2013-06-28 11:12:20 -070052# Local build constants
joychenc3944cb2013-08-19 10:42:07 -070053ANY = "ANY"
joychen7df67f72013-07-18 14:21:12 -070054LATEST = "latest"
55LOCAL = "local"
56REMOTE = "remote"
Chris Sosa75490802013-09-30 17:21:45 -070057
58# TODO(sosa): Fix a lot of assumptions about these aliases. There is too much
59# implicit logic here that's unnecessary. What should be done:
60# 1) Collapse Alias logic to one set of aliases for xbuddy (not local/remote).
61# 2) Do not use zip when creating these dicts. Better to not rely on ordering.
62# 3) Move alias/artifact mapping to a central module rather than having it here.
63# 4) Be explicit when things are missing i.e. no dev images in image.zip.
64
joychen921e1fb2013-06-28 11:12:20 -070065LOCAL_ALIASES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080066 TEST,
67 DEV,
68 BASE,
69 RECOVERY,
Mike Frysingera0e6a282016-09-01 17:29:08 -040070 FACTORY_SHIM,
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080071 FULL,
72 STATEFUL,
73 ANY,
joychen921e1fb2013-06-28 11:12:20 -070074]
75
76LOCAL_FILE_NAMES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080077 devserver_constants.TEST_IMAGE_FILE,
78 devserver_constants.IMAGE_FILE,
79 devserver_constants.BASE_IMAGE_FILE,
80 devserver_constants.RECOVERY_IMAGE_FILE,
Mike Frysingera0e6a282016-09-01 17:29:08 -040081 devserver_constants.FACTORY_SHIM_IMAGE_FILE,
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080082 devserver_constants.UPDATE_FILE,
83 devserver_constants.STATEFUL_FILE,
84 None, # For ANY.
joychen921e1fb2013-06-28 11:12:20 -070085]
86
87LOCAL_ALIAS_TO_FILENAME = dict(zip(LOCAL_ALIASES, LOCAL_FILE_NAMES))
88
89# Google Storage constants
90GS_ALIASES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080091 TEST,
92 BASE,
93 RECOVERY,
Mike Frysingera0e6a282016-09-01 17:29:08 -040094 FACTORY_SHIM,
Gilad Arnold5f46d8e2015-02-19 12:17:55 -080095 FULL,
96 STATEFUL,
97 AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -070098]
99
joychen921e1fb2013-06-28 11:12:20 -0700100GS_FILE_NAMES = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800101 devserver_constants.TEST_IMAGE_FILE,
102 devserver_constants.BASE_IMAGE_FILE,
103 devserver_constants.RECOVERY_IMAGE_FILE,
Mike Frysingera0e6a282016-09-01 17:29:08 -0400104 devserver_constants.FACTORY_SHIM_IMAGE_FILE,
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800105 devserver_constants.UPDATE_FILE,
106 devserver_constants.STATEFUL_FILE,
107 devserver_constants.AUTOTEST_DIR,
joychen3cb228e2013-06-12 12:13:13 -0700108]
109
110ARTIFACTS = [
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800111 artifact_info.TEST_IMAGE,
112 artifact_info.BASE_IMAGE,
113 artifact_info.RECOVERY_IMAGE,
Mike Frysingera0e6a282016-09-01 17:29:08 -0400114 artifact_info.FACTORY_SHIM_IMAGE,
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800115 artifact_info.FULL_PAYLOAD,
116 artifact_info.STATEFUL_PAYLOAD,
117 artifact_info.AUTOTEST,
joychen3cb228e2013-06-12 12:13:13 -0700118]
119
joychen921e1fb2013-06-28 11:12:20 -0700120GS_ALIAS_TO_FILENAME = dict(zip(GS_ALIASES, GS_FILE_NAMES))
121GS_ALIAS_TO_ARTIFACT = dict(zip(GS_ALIASES, ARTIFACTS))
joychen3cb228e2013-06-12 12:13:13 -0700122
joychen921e1fb2013-06-28 11:12:20 -0700123LATEST_OFFICIAL = "latest-official"
joychen3cb228e2013-06-12 12:13:13 -0700124
Chris Sosaea734d92013-10-11 11:28:58 -0700125RELEASE = "-release"
joychen3cb228e2013-06-12 12:13:13 -0700126
joychen3cb228e2013-06-12 12:13:13 -0700127
128class XBuddyException(Exception):
129 """Exception classes used by this module."""
130 pass
131
132
133# no __init__ method
134#pylint: disable=W0232
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800135class Timestamp(object):
joychen3cb228e2013-06-12 12:13:13 -0700136 """Class to translate build path strings and timestamp filenames."""
137
138 _TIMESTAMP_DELIMITER = 'SLASH'
139 XBUDDY_TIMESTAMP_DIR = 'xbuddy_UpdateTimestamps'
140
141 @staticmethod
142 def TimestampToBuild(timestamp_filename):
143 return timestamp_filename.replace(Timestamp._TIMESTAMP_DELIMITER, '/')
144
145 @staticmethod
146 def BuildToTimestamp(build_path):
147 return build_path.replace('/', Timestamp._TIMESTAMP_DELIMITER)
joychen921e1fb2013-06-28 11:12:20 -0700148
149 @staticmethod
150 def UpdateTimestamp(timestamp_dir, build_id):
151 """Update timestamp file of build with build_id."""
152 common_util.MkDirP(timestamp_dir)
joychen562699a2013-08-13 15:22:14 -0700153 _Log("Updating timestamp for %s", build_id)
joychen921e1fb2013-06-28 11:12:20 -0700154 time_file = os.path.join(timestamp_dir,
155 Timestamp.BuildToTimestamp(build_id))
156 with file(time_file, 'a'):
157 os.utime(time_file, None)
joychen3cb228e2013-06-12 12:13:13 -0700158#pylint: enable=W0232
159
160
joychen921e1fb2013-06-28 11:12:20 -0700161class XBuddy(build_util.BuildObject):
joychen3cb228e2013-06-12 12:13:13 -0700162 """Class that manages image retrieval and caching by the devserver.
163
164 Image retrieval by xBuddy path:
165 XBuddy accesses images and artifacts that it stores using an xBuddy
166 path of the form: board/version/alias
167 The primary xbuddy.Get call retrieves the correct artifact or url to where
168 the artifacts can be found.
169
170 Image caching:
171 Images and other artifacts are stored identically to how they would have
172 been if devserver's stage rpc was called and the xBuddy cache replaces
173 build versions on a LRU basis. Timestamps are maintained by last accessed
174 times of representative files in the a directory in the static serve
175 directory (XBUDDY_TIMESTAMP_DIR).
176
177 Private class members:
joychen121fc9b2013-08-02 14:30:30 -0700178 _true_values: used for interpreting boolean values
179 _staging_thread_count: track download requests
180 _timestamp_folder: directory with empty files standing in as timestamps
joychen921e1fb2013-06-28 11:12:20 -0700181 for each image currently cached by xBuddy
joychen3cb228e2013-06-12 12:13:13 -0700182 """
183 _true_values = ['true', 't', 'yes', 'y']
184
185 # Number of threads that are staging images.
186 _staging_thread_count = 0
187 # Lock used to lock increasing/decreasing count.
188 _staging_thread_count_lock = threading.Lock()
189
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800190 def __init__(self, manage_builds=False, board=None, version=None,
191 images_dir=None, log_screen=True, **kwargs):
joychen921e1fb2013-06-28 11:12:20 -0700192 super(XBuddy, self).__init__(**kwargs)
joychenb0dfe552013-07-30 10:02:06 -0700193
Yiming Chenaab488e2014-11-17 14:49:31 -0800194 if not log_screen:
195 cherrypy.config.update({'log.screen': False})
196
joychen562699a2013-08-13 15:22:14 -0700197 self.config = self._ReadConfig()
198 self._manage_builds = manage_builds or self._ManageBuilds()
Chris Sosa75490802013-09-30 17:21:45 -0700199 self._board = board
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800200 self._version = version
joychen921e1fb2013-06-28 11:12:20 -0700201 self._timestamp_folder = os.path.join(self.static_dir,
joychen3cb228e2013-06-12 12:13:13 -0700202 Timestamp.XBUDDY_TIMESTAMP_DIR)
Chris Sosa7cd23202013-10-15 17:22:57 -0700203 if images_dir:
204 self.images_dir = images_dir
205 else:
206 self.images_dir = os.path.join(self.GetSourceRoot(), 'src/build/images')
207
joychen7df67f72013-07-18 14:21:12 -0700208 common_util.MkDirP(self._timestamp_folder)
joychen3cb228e2013-06-12 12:13:13 -0700209
210 @classmethod
211 def ParseBoolean(cls, boolean_string):
212 """Evaluate a string to a boolean value"""
213 if boolean_string:
214 return boolean_string.lower() in cls._true_values
215 else:
216 return False
217
joychen562699a2013-08-13 15:22:14 -0700218 def _ReadConfig(self):
219 """Read xbuddy config from ini files.
220
221 Reads the base config from xbuddy_config.ini, and then merges in the
222 shadow config from shadow_xbuddy_config.ini
223
224 Returns:
225 The merged configuration.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800226
joychen562699a2013-08-13 15:22:14 -0700227 Raises:
228 XBuddyException if the config file is missing.
229 """
230 xbuddy_config = ConfigParser.ConfigParser()
231 config_file = os.path.join(self.devserver_dir, CONFIG_FILE)
232 if os.path.exists(config_file):
233 xbuddy_config.read(config_file)
234 else:
Yiming Chend9202142014-11-07 14:56:52 -0800235 # Get the directory of xbuddy.py file.
236 file_dir = os.path.dirname(os.path.realpath(__file__))
237 # Read the default xbuddy_config.ini from the directory.
238 xbuddy_config.read(os.path.join(file_dir, CONFIG_FILE))
joychen562699a2013-08-13 15:22:14 -0700239
240 # Read the shadow file if there is one.
Chris Sosac2abc722013-08-26 17:11:22 -0700241 if os.path.isdir(CHROOT_SHADOW_DIR):
242 shadow_config_file = os.path.join(CHROOT_SHADOW_DIR, SHADOW_CONFIG_FILE)
243 else:
244 shadow_config_file = os.path.join(self.devserver_dir, SHADOW_CONFIG_FILE)
245
246 _Log('Using shadow config file stored at %s', shadow_config_file)
joychen562699a2013-08-13 15:22:14 -0700247 if os.path.exists(shadow_config_file):
248 shadow_xbuddy_config = ConfigParser.ConfigParser()
249 shadow_xbuddy_config.read(shadow_config_file)
250
251 # Merge shadow config in.
252 sections = shadow_xbuddy_config.sections()
253 for s in sections:
254 if not xbuddy_config.has_section(s):
255 xbuddy_config.add_section(s)
256 options = shadow_xbuddy_config.options(s)
257 for o in options:
258 val = shadow_xbuddy_config.get(s, o)
259 xbuddy_config.set(s, o, val)
260
261 return xbuddy_config
262
263 def _ManageBuilds(self):
264 """Checks if xBuddy is managing local builds using the current config."""
265 try:
266 return self.ParseBoolean(self.config.get(GENERAL, 'manage_builds'))
267 except ConfigParser.Error:
268 return False
269
270 def _Capacity(self):
271 """Gets the xbuddy capacity from the current config."""
272 try:
273 return int(self.config.get(GENERAL, 'capacity'))
274 except ConfigParser.Error:
275 return 5
276
Gilad Arnold38e828c2015-04-24 13:52:07 -0700277 def LookupAlias(self, alias, board=None, version=None):
joychen562699a2013-08-13 15:22:14 -0700278 """Given the full xbuddy config, look up an alias for path rewrite.
279
280 Args:
281 alias: The xbuddy path that could be one of the aliases in the
282 rewrite table.
283 board: The board to fill in with when paths are rewritten. Can be from
Gilad Arnold38e828c2015-04-24 13:52:07 -0700284 the update request xml or the default board from devserver. If None,
285 defers to the value given during XBuddy initialization.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800286 version: The version to fill in when rewriting paths. Could be a specific
Gilad Arnold38e828c2015-04-24 13:52:07 -0700287 version number or a version alias like LATEST. If None, defers to the
288 value given during XBuddy initialization, or LATEST.
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800289
joychen562699a2013-08-13 15:22:14 -0700290 Returns:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700291 A pair (val, suffix) where val is the rewritten path, or the original
292 string if no rewrite was found; and suffix is the assigned location
293 suffix, or the default suffix if none was found.
joychen562699a2013-08-13 15:22:14 -0700294 """
joychen562699a2013-08-13 15:22:14 -0700295 try:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700296 suffix = self.config.get(LOCATION_SUFFIXES, alias)
297 except ConfigParser.Error:
298 suffix = RELEASE
299
300 try:
joychen562699a2013-08-13 15:22:14 -0700301 val = self.config.get(PATH_REWRITES, alias)
302 except ConfigParser.Error:
303 # No alias lookup found. Return original path.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700304 val = None
joychen562699a2013-08-13 15:22:14 -0700305
Gilad Arnold896c6d82015-03-13 16:20:29 -0700306 if not (val and val.strip()):
307 val = alias
joychen562699a2013-08-13 15:22:14 -0700308 else:
Gilad Arnold896c6d82015-03-13 16:20:29 -0700309 # The found value is not an empty string.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800310 # Fill in the board and version.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700311 val = val.replace("BOARD", "%(board)s")
312 val = val.replace("VERSION", "%(version)s")
Gilad Arnold38e828c2015-04-24 13:52:07 -0700313 val = val % {'board': board or self._board,
314 'version': version or self._version or LATEST}
Gilad Arnold896c6d82015-03-13 16:20:29 -0700315
316 _Log("Path is %s, location suffix is %s", val, suffix)
317 return val, suffix
joychen562699a2013-08-13 15:22:14 -0700318
Simran Basi99e63c02014-05-20 10:39:52 -0700319 @staticmethod
320 def _ResolveImageDir(image_dir):
321 """Clean up and return the image dir to use.
322
323 Args:
324 image_dir: directory in Google Storage to use.
325
326 Returns:
327 |image_dir| if |image_dir| is not None. Otherwise, returns
328 devserver_constants.GS_IMAGE_DIR
329 """
330 image_dir = image_dir or devserver_constants.GS_IMAGE_DIR
331 # Remove trailing slashes.
332 return image_dir.rstrip('/')
333
Gilad Arnold896c6d82015-03-13 16:20:29 -0700334 def _LookupOfficial(self, board, suffix, image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700335 """Check LATEST-master for the version number of interest."""
336 _Log("Checking gs for latest %s-%s image", board, suffix)
Simran Basi99e63c02014-05-20 10:39:52 -0700337 image_dir = XBuddy._ResolveImageDir(image_dir)
338 latest_addr = (devserver_constants.GS_LATEST_MASTER %
339 {'image_dir': image_dir,
340 'board': board,
341 'suffix': suffix})
joychenf8f07e22013-07-12 17:45:51 -0700342 cmd = 'gsutil cat %s' % latest_addr
343 msg = 'Failed to find build at %s' % latest_addr
joychen121fc9b2013-08-02 14:30:30 -0700344 # Full release + version is in the LATEST file.
joychenf8f07e22013-07-12 17:45:51 -0700345 version = gsutil_util.GSUtilRun(cmd, msg)
joychen3cb228e2013-06-12 12:13:13 -0700346
joychenf8f07e22013-07-12 17:45:51 -0700347 return devserver_constants.IMAGE_DIR % {'board':board,
348 'suffix':suffix,
349 'version':version}
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800350
Gilad Arnold896c6d82015-03-13 16:20:29 -0700351 def _LookupChannel(self, board, suffix, channel='stable',
352 image_dir=None):
joychenf8f07e22013-07-12 17:45:51 -0700353 """Check the channel folder for the version number of interest."""
joychen121fc9b2013-08-02 14:30:30 -0700354 # Get all names in channel dir. Get 10 highest directories by version.
joychen7df67f72013-07-18 14:21:12 -0700355 _Log("Checking channel '%s' for latest '%s' image", channel, board)
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800356 # Due to historical reasons, gs://chromeos-releases uses
357 # daisy-spring as opposed to the board name daisy_spring. Convert
358 # the board name for the lookup.
359 channel_dir = devserver_constants.GS_CHANNEL_DIR % {
360 'channel':channel,
361 'board':re.sub('_', '-', board)}
joychen562699a2013-08-13 15:22:14 -0700362 latest_version = gsutil_util.GetLatestVersionFromGSDir(
363 channel_dir, with_release=False)
joychenf8f07e22013-07-12 17:45:51 -0700364
joychen121fc9b2013-08-02 14:30:30 -0700365 # Figure out release number from the version number.
joychenc3944cb2013-08-19 10:42:07 -0700366 image_url = devserver_constants.IMAGE_DIR % {
Gilad Arnold896c6d82015-03-13 16:20:29 -0700367 'board': board,
368 'suffix': suffix,
369 'version': 'R*' + latest_version}
Simran Basi99e63c02014-05-20 10:39:52 -0700370 image_dir = XBuddy._ResolveImageDir(image_dir)
371 gs_url = os.path.join(image_dir, image_url)
joychenf8f07e22013-07-12 17:45:51 -0700372
373 # There should only be one match on cros-image-archive.
Simran Basi99e63c02014-05-20 10:39:52 -0700374 full_version = gsutil_util.GetLatestVersionFromGSDir(gs_url)
joychenf8f07e22013-07-12 17:45:51 -0700375
Gilad Arnold896c6d82015-03-13 16:20:29 -0700376 return devserver_constants.IMAGE_DIR % {'board': board,
377 'suffix': suffix,
378 'version': full_version}
joychenf8f07e22013-07-12 17:45:51 -0700379
Gilad Arnold896c6d82015-03-13 16:20:29 -0700380 def _LookupVersion(self, board, suffix, version):
joychenf8f07e22013-07-12 17:45:51 -0700381 """Search GS image releases for the highest match to a version prefix."""
joychen121fc9b2013-08-02 14:30:30 -0700382 # Build the pattern for GS to match.
joychen7df67f72013-07-18 14:21:12 -0700383 _Log("Checking gs for latest '%s' image with prefix '%s'", board, version)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700384 image_url = devserver_constants.IMAGE_DIR % {'board': board,
385 'suffix': suffix,
386 'version': version + '*'}
joychenf8f07e22013-07-12 17:45:51 -0700387 image_dir = os.path.join(devserver_constants.GS_IMAGE_DIR, image_url)
388
joychen121fc9b2013-08-02 14:30:30 -0700389 # Grab the newest version of the ones matched.
joychenf8f07e22013-07-12 17:45:51 -0700390 full_version = gsutil_util.GetLatestVersionFromGSDir(image_dir)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700391 return devserver_constants.IMAGE_DIR % {'board': board,
392 'suffix': suffix,
393 'version': full_version}
joychenf8f07e22013-07-12 17:45:51 -0700394
Gilad Arnold896c6d82015-03-13 16:20:29 -0700395 def _RemoteBuildId(self, board, suffix, version):
Chris Sosaea734d92013-10-11 11:28:58 -0700396 """Returns the remote build_id for the given board and version.
397
398 Raises:
399 XBuddyException: If we failed to resolve the version to a valid build_id.
400 """
Gilad Arnold896c6d82015-03-13 16:20:29 -0700401 build_id_as_is = devserver_constants.IMAGE_DIR % {'board': board,
402 'suffix': '',
403 'version': version}
404 build_id_suffix = devserver_constants.IMAGE_DIR % {'board': board,
405 'suffix': suffix,
406 'version': version}
Chris Sosaea734d92013-10-11 11:28:58 -0700407 # Return the first path that exists. We assume that what the user typed
408 # is better than with a default suffix added i.e. x86-generic/blah is
409 # more valuable than x86-generic-release/blah.
Gilad Arnold896c6d82015-03-13 16:20:29 -0700410 for build_id in build_id_as_is, build_id_suffix:
Chris Sosaea734d92013-10-11 11:28:58 -0700411 cmd = 'gsutil ls %s/%s' % (devserver_constants.GS_IMAGE_DIR, build_id)
412 try:
413 version = gsutil_util.GSUtilRun(cmd, None)
414 return build_id
415 except gsutil_util.GSUtilError:
416 continue
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800417
418 raise XBuddyException('Could not find remote build_id for %s %s' % (
419 board, version))
Chris Sosaea734d92013-10-11 11:28:58 -0700420
Gilad Arnold896c6d82015-03-13 16:20:29 -0700421 def _ResolveBuildVersion(self, board, suffix, base_version):
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800422 """Check LATEST-<base_version> and returns a full build version."""
423 _Log('Checking gs for full version for %s of %s', base_version, board)
424 # TODO(garnold) We might want to accommodate version prefixes and pick the
425 # most recent found, as done in _LookupVersion().
426 latest_addr = (devserver_constants.GS_LATEST_BASE_VERSION %
427 {'image_dir': devserver_constants.GS_IMAGE_DIR,
428 'board': board,
Gilad Arnold896c6d82015-03-13 16:20:29 -0700429 'suffix': suffix,
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800430 'base_version': base_version})
431 cmd = 'gsutil cat %s' % latest_addr
432 msg = 'Failed to find build at %s' % latest_addr
433 # Full release + version is in the LATEST file.
434 return gsutil_util.GSUtilRun(cmd, msg)
435
Gilad Arnold896c6d82015-03-13 16:20:29 -0700436 def _ResolveVersionToBuildId(self, board, suffix, version, image_dir=None):
joychen121fc9b2013-08-02 14:30:30 -0700437 """Handle version aliases for remote payloads in GS.
joychen3cb228e2013-06-12 12:13:13 -0700438
439 Args:
440 board: as specified in the original call. (i.e. x86-generic, parrot)
Gilad Arnold896c6d82015-03-13 16:20:29 -0700441 suffix: The location suffix, to be added to board name.
joychen3cb228e2013-06-12 12:13:13 -0700442 version: as entered in the original call. can be
443 {TBD, 0. some custom alias as defined in a config file}
Ningning Xiab2a1af52016-04-22 11:14:42 -0700444 1. fully qualified build version.
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800445 2. latest
446 3. latest-{channel}
447 4. latest-official-{board suffix}
448 5. version prefix (i.e. RX-Y.X, RX-Y, RX)
Simran Basi99e63c02014-05-20 10:39:52 -0700449 image_dir: image directory to check in Google Storage. If none,
450 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700451
452 Returns:
Chris Sosaea734d92013-10-11 11:28:58 -0700453 Location where the image dir is actually found on GS (build_id)
joychen3cb228e2013-06-12 12:13:13 -0700454
Chris Sosaea734d92013-10-11 11:28:58 -0700455 Raises:
456 XBuddyException: If we failed to resolve the version to a valid url.
joychen3cb228e2013-06-12 12:13:13 -0700457 """
joychenf8f07e22013-07-12 17:45:51 -0700458 # Only the last segment of the alias is variable relative to the rest.
459 version_tuple = version.rsplit('-', 1)
joychen3cb228e2013-06-12 12:13:13 -0700460
joychenf8f07e22013-07-12 17:45:51 -0700461 if re.match(devserver_constants.VERSION_RE, version):
Gilad Arnold896c6d82015-03-13 16:20:29 -0700462 return self._RemoteBuildId(board, suffix, version)
Gilad Arnold869e8ab2015-02-19 23:34:49 -0800463 elif re.match(devserver_constants.VERSION, version):
Ningning Xiab2a1af52016-04-22 11:14:42 -0700464 raise XBuddyException('\'%s\' is not valid. Should provide the fully '
465 'qualified version with a version prefix \'RX-\' '
466 'due to crbug.com/585914' % version)
joychenf8f07e22013-07-12 17:45:51 -0700467 elif version == LATEST_OFFICIAL:
468 # latest-official --> LATEST build in board-release
Gilad Arnold896c6d82015-03-13 16:20:29 -0700469 return self._LookupOfficial(board, suffix, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700470 elif version_tuple[0] == LATEST_OFFICIAL:
471 # latest-official-{suffix} --> LATEST build in board-{suffix}
Gilad Arnold896c6d82015-03-13 16:20:29 -0700472 return self._LookupOfficial(board, version_tuple[1],
473 image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700474 elif version == LATEST:
475 # latest --> latest build on stable channel
Gilad Arnold896c6d82015-03-13 16:20:29 -0700476 return self._LookupChannel(board, suffix, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700477 elif version_tuple[0] == LATEST:
478 if re.match(devserver_constants.VERSION_RE, version_tuple[1]):
479 # latest-R* --> most recent qualifying build
Gilad Arnold896c6d82015-03-13 16:20:29 -0700480 return self._LookupVersion(board, suffix, version_tuple[1])
joychenf8f07e22013-07-12 17:45:51 -0700481 else:
482 # latest-{channel} --> latest build within that channel
Gilad Arnold896c6d82015-03-13 16:20:29 -0700483 return self._LookupChannel(board, suffix, channel=version_tuple[1],
Simran Basi99e63c02014-05-20 10:39:52 -0700484 image_dir=image_dir)
joychen3cb228e2013-06-12 12:13:13 -0700485 else:
486 # The given version doesn't match any known patterns.
joychen921e1fb2013-06-28 11:12:20 -0700487 raise XBuddyException("Version %s unknown. Can't find on GS." % version)
joychen3cb228e2013-06-12 12:13:13 -0700488
joychen5260b9a2013-07-16 14:48:01 -0700489 @staticmethod
490 def _Symlink(link, target):
491 """Symlinks link to target, and removes whatever link was there before."""
492 _Log("Linking to %s from %s", link, target)
493 if os.path.lexists(link):
494 os.unlink(link)
495 os.symlink(target, link)
496
joychen121fc9b2013-08-02 14:30:30 -0700497 def _GetLatestLocalVersion(self, board):
joychen921e1fb2013-06-28 11:12:20 -0700498 """Get the version of the latest image built for board by build_image
499
500 Updates the symlink reference within the xBuddy static dir to point to
501 the real image dir in the local /build/images directory.
502
503 Args:
joychenc3944cb2013-08-19 10:42:07 -0700504 board: board that image was built for.
joychen921e1fb2013-06-28 11:12:20 -0700505
506 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700507 The discovered version of the image.
joychenc3944cb2013-08-19 10:42:07 -0700508
509 Raises:
510 XBuddyException if neither test nor dev image was found in latest built
511 directory.
joychen3cb228e2013-06-12 12:13:13 -0700512 """
joychen921e1fb2013-06-28 11:12:20 -0700513 latest_local_dir = self.GetLatestImageDir(board)
joychenb0dfe552013-07-30 10:02:06 -0700514 if not latest_local_dir or not os.path.exists(latest_local_dir):
joychen921e1fb2013-06-28 11:12:20 -0700515 raise XBuddyException('No builds found for %s. Did you run build_image?' %
516 board)
517
joychen121fc9b2013-08-02 14:30:30 -0700518 # Assume that the version number is the name of the directory.
joychenc3944cb2013-08-19 10:42:07 -0700519 return os.path.basename(latest_local_dir.rstrip('/'))
joychen921e1fb2013-06-28 11:12:20 -0700520
joychenc3944cb2013-08-19 10:42:07 -0700521 @staticmethod
522 def _FindAny(local_dir):
523 """Returns the image_type for ANY given the local_dir."""
joychenc3944cb2013-08-19 10:42:07 -0700524 test_image = os.path.join(local_dir, devserver_constants.TEST_IMAGE_FILE)
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700525 dev_image = os.path.join(local_dir, devserver_constants.IMAGE_FILE)
526 # Prioritize test images over dev images.
joychenc3944cb2013-08-19 10:42:07 -0700527 if os.path.exists(test_image):
528 return 'test'
529
Yu-Ju Hongc23c79b2014-03-17 12:40:33 -0700530 if os.path.exists(dev_image):
531 return 'dev'
532
joychenc3944cb2013-08-19 10:42:07 -0700533 raise XBuddyException('No images found in %s' % local_dir)
534
535 @staticmethod
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800536 def _InterpretPath(path, default_board=None, default_version=None):
joychen121fc9b2013-08-02 14:30:30 -0700537 """Split and return the pieces of an xBuddy path name
joychen921e1fb2013-06-28 11:12:20 -0700538
joychen121fc9b2013-08-02 14:30:30 -0700539 Args:
540 path: the path xBuddy Get was called with.
Chris Sosa0eecf962014-02-03 14:14:39 -0800541 default_board: board to use in case board isn't in path.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800542 default_version: Version to use in case version isn't in path.
joychen3cb228e2013-06-12 12:13:13 -0700543
Yu-Ju Hongc54658c2014-01-22 09:18:07 -0800544 Returns:
Chris Sosa75490802013-09-30 17:21:45 -0700545 tuple of (image_type, board, version, whether the path is local)
joychen3cb228e2013-06-12 12:13:13 -0700546
547 Raises:
548 XBuddyException: if the path can't be resolved into valid components
549 """
joychen121fc9b2013-08-02 14:30:30 -0700550 path_list = filter(None, path.split('/'))
joychen7df67f72013-07-18 14:21:12 -0700551
Chris Sosa0eecf962014-02-03 14:14:39 -0800552 # Do the stuff that is well known first. We know that if paths have a
553 # image_type, it must be one of the GS/LOCAL aliases and it must be at the
554 # end. Similarly, local/remote are well-known and must start the path list.
555 is_local = True
556 if path_list and path_list[0] in (REMOTE, LOCAL):
557 is_local = (path_list.pop(0) == LOCAL)
joychen7df67f72013-07-18 14:21:12 -0700558
Chris Sosa0eecf962014-02-03 14:14:39 -0800559 # Default image type is determined by remote vs. local.
560 if is_local:
561 image_type = ANY
562 else:
563 image_type = TEST
joychen7df67f72013-07-18 14:21:12 -0700564
Chris Sosa0eecf962014-02-03 14:14:39 -0800565 if path_list and path_list[-1] in GS_ALIASES + LOCAL_ALIASES:
566 image_type = path_list.pop(-1)
joychen3cb228e2013-06-12 12:13:13 -0700567
Chris Sosa0eecf962014-02-03 14:14:39 -0800568 # Now for the tricky part. We don't actually know at this point if the rest
569 # of the path is just a board | version (like R33-2341.0.0) or just a board
570 # or just a version. So we do our best to do the right thing.
571 board = default_board
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800572 version = default_version or LATEST
Chris Sosa0eecf962014-02-03 14:14:39 -0800573 if len(path_list) == 1:
574 path = path_list.pop(0)
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800575 # Treat this as a version if it's one we know (contains default or
576 # latest), or we were given an actual default board.
577 if default_version in path or LATEST in path or default_board is not None:
Chris Sosa0eecf962014-02-03 14:14:39 -0800578 version = path
joychen7df67f72013-07-18 14:21:12 -0700579 else:
Chris Sosa0eecf962014-02-03 14:14:39 -0800580 board = path
joychen7df67f72013-07-18 14:21:12 -0700581
Chris Sosa0eecf962014-02-03 14:14:39 -0800582 elif len(path_list) == 2:
583 # Assumes board/version.
584 board = path_list.pop(0)
585 version = path_list.pop(0)
586
587 if path_list:
588 raise XBuddyException("Path isn't valid. Could not figure out how to "
589 "parse remaining components: %s." % path_list)
590
591 _Log("Get artifact '%s' with board %s and version %s'. Locally? %s",
joychen7df67f72013-07-18 14:21:12 -0700592 image_type, board, version, is_local)
593
594 return image_type, board, version, is_local
joychen3cb228e2013-06-12 12:13:13 -0700595
joychen921e1fb2013-06-28 11:12:20 -0700596 def _SyncRegistryWithBuildImages(self):
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800597 """Crawl images_dir for build_ids of images generated from build_image.
joychen5260b9a2013-07-16 14:48:01 -0700598
599 This will find images and symlink them in xBuddy's static dir so that
600 xBuddy's cache can serve them.
601 If xBuddy's _manage_builds option is on, then a timestamp will also be
602 generated, and xBuddy will clear them from the directory they are in, as
603 necessary.
604 """
Yu-Ju Hong235d1b52014-04-16 11:01:47 -0700605 if not os.path.isdir(self.images_dir):
606 # Skip syncing if images_dir does not exist.
607 _Log('Cannot find %s; skip syncing image registry.', self.images_dir)
608 return
609
joychen921e1fb2013-06-28 11:12:20 -0700610 build_ids = []
611 for b in os.listdir(self.images_dir):
joychen5260b9a2013-07-16 14:48:01 -0700612 # Ensure we have directories to track all boards in build/images
613 common_util.MkDirP(os.path.join(self.static_dir, b))
joychen921e1fb2013-06-28 11:12:20 -0700614 board_dir = os.path.join(self.images_dir, b)
615 build_ids.extend(['/'.join([b, v]) for v
joychenc3944cb2013-08-19 10:42:07 -0700616 in os.listdir(board_dir) if not v == LATEST])
joychen921e1fb2013-06-28 11:12:20 -0700617
joychen121fc9b2013-08-02 14:30:30 -0700618 # Symlink undiscovered images, and update timestamps if manage_builds is on.
joychen5260b9a2013-07-16 14:48:01 -0700619 for build_id in build_ids:
620 link = os.path.join(self.static_dir, build_id)
621 target = os.path.join(self.images_dir, build_id)
622 XBuddy._Symlink(link, target)
623 if self._manage_builds:
624 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700625
626 def _ListBuildTimes(self):
Gilad Arnold5f46d8e2015-02-19 12:17:55 -0800627 """Returns the currently cached builds and their last access timestamp.
joychen3cb228e2013-06-12 12:13:13 -0700628
629 Returns:
630 list of tuples that matches xBuddy build/version to timestamps in long
631 """
joychen121fc9b2013-08-02 14:30:30 -0700632 # Update currently cached builds.
joychen3cb228e2013-06-12 12:13:13 -0700633 build_dict = {}
634
joychen7df67f72013-07-18 14:21:12 -0700635 for f in os.listdir(self._timestamp_folder):
joychen3cb228e2013-06-12 12:13:13 -0700636 last_accessed = os.path.getmtime(os.path.join(self._timestamp_folder, f))
637 build_id = Timestamp.TimestampToBuild(f)
joychenc3944cb2013-08-19 10:42:07 -0700638 stale_time = datetime.timedelta(seconds=(time.time() - last_accessed))
joychen921e1fb2013-06-28 11:12:20 -0700639 build_dict[build_id] = stale_time
joychen3cb228e2013-06-12 12:13:13 -0700640 return_tup = sorted(build_dict.iteritems(), key=operator.itemgetter(1))
641 return return_tup
642
Chris Sosa75490802013-09-30 17:21:45 -0700643 def _Download(self, gs_url, artifacts):
644 """Download the artifacts from the given gs_url.
645
646 Raises:
647 build_artifact.ArtifactDownloadError: If we failed to download the
648 artifact.
649 """
joychen3cb228e2013-06-12 12:13:13 -0700650 with XBuddy._staging_thread_count_lock:
651 XBuddy._staging_thread_count += 1
652 try:
Chris Sosa75490802013-09-30 17:21:45 -0700653 _Log("Downloading %s from %s", artifacts, gs_url)
Gabe Black3b567202015-09-23 14:07:59 -0700654 dl = downloader.GoogleStorageDownloader(self.static_dir, gs_url)
655 factory = build_artifact.ChromeOSArtifactFactory(
656 dl.GetBuildDir(), artifacts, [], dl.GetBuild())
657 dl.Download(factory)
joychen3cb228e2013-06-12 12:13:13 -0700658 finally:
659 with XBuddy._staging_thread_count_lock:
660 XBuddy._staging_thread_count -= 1
661
Chris Sosa75490802013-09-30 17:21:45 -0700662 def CleanCache(self):
joychen562699a2013-08-13 15:22:14 -0700663 """Delete all builds besides the newest N builds"""
joychen121fc9b2013-08-02 14:30:30 -0700664 if not self._manage_builds:
665 return
joychen921e1fb2013-06-28 11:12:20 -0700666 cached_builds = [e[0] for e in self._ListBuildTimes()]
joychen3cb228e2013-06-12 12:13:13 -0700667 _Log('In cache now: %s', cached_builds)
668
joychen562699a2013-08-13 15:22:14 -0700669 for b in range(self._Capacity(), len(cached_builds)):
joychen3cb228e2013-06-12 12:13:13 -0700670 b_path = cached_builds[b]
joychen7df67f72013-07-18 14:21:12 -0700671 _Log("Clearing '%s' from cache", b_path)
joychen3cb228e2013-06-12 12:13:13 -0700672
673 time_file = os.path.join(self._timestamp_folder,
674 Timestamp.BuildToTimestamp(b_path))
joychen921e1fb2013-06-28 11:12:20 -0700675 os.unlink(time_file)
676 clear_dir = os.path.join(self.static_dir, b_path)
joychen3cb228e2013-06-12 12:13:13 -0700677 try:
joychen121fc9b2013-08-02 14:30:30 -0700678 # Handle symlinks, in the case of links to local builds if enabled.
679 if os.path.islink(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700680 target = os.readlink(clear_dir)
681 _Log('Deleting locally built image at %s', target)
joychen921e1fb2013-06-28 11:12:20 -0700682
683 os.unlink(clear_dir)
joychen5260b9a2013-07-16 14:48:01 -0700684 if os.path.exists(target):
joychen921e1fb2013-06-28 11:12:20 -0700685 shutil.rmtree(target)
686 elif os.path.exists(clear_dir):
joychen5260b9a2013-07-16 14:48:01 -0700687 _Log('Deleting downloaded image at %s', clear_dir)
joychen3cb228e2013-06-12 12:13:13 -0700688 shutil.rmtree(clear_dir)
joychen921e1fb2013-06-28 11:12:20 -0700689
joychen121fc9b2013-08-02 14:30:30 -0700690 except Exception as err:
691 raise XBuddyException('Failed to clear %s: %s' % (clear_dir, err))
joychen3cb228e2013-06-12 12:13:13 -0700692
Simran Basi99e63c02014-05-20 10:39:52 -0700693 def _GetFromGS(self, build_id, image_type, image_dir=None):
Chris Sosa75490802013-09-30 17:21:45 -0700694 """Check if the artifact is available locally. Download from GS if not.
695
Simran Basi99e63c02014-05-20 10:39:52 -0700696 Args:
697 build_id: Path to the image or update directory on the devserver or
698 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
699 image_type: Image type to download. Look at aliases at top of file for
700 options.
701 image_dir: Google Storage image archive to search in if requesting a
702 remote artifact. If none uses the default bucket.
703
Chris Sosa75490802013-09-30 17:21:45 -0700704 Raises:
705 build_artifact.ArtifactDownloadError: If we failed to download the
706 artifact.
707 """
Simran Basi99e63c02014-05-20 10:39:52 -0700708 image_dir = XBuddy._ResolveImageDir(image_dir)
709 gs_url = os.path.join(image_dir, build_id)
joychen921e1fb2013-06-28 11:12:20 -0700710
joychen121fc9b2013-08-02 14:30:30 -0700711 # Stage image if not found in cache.
joychen921e1fb2013-06-28 11:12:20 -0700712 file_name = GS_ALIAS_TO_FILENAME[image_type]
joychen346531c2013-07-24 16:55:56 -0700713 file_loc = os.path.join(self.static_dir, build_id, file_name)
714 cached = os.path.exists(file_loc)
715
joychen921e1fb2013-06-28 11:12:20 -0700716 if not cached:
Chris Sosa75490802013-09-30 17:21:45 -0700717 artifact = GS_ALIAS_TO_ARTIFACT[image_type]
718 self._Download(gs_url, [artifact])
joychen921e1fb2013-06-28 11:12:20 -0700719 else:
720 _Log('Image already cached.')
721
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800722 def _GetArtifact(self, path_list, board=None, version=None,
723 lookup_only=False, image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700724 """Interpret an xBuddy path and return directory/file_name to resource.
725
Chris Sosa75490802013-09-30 17:21:45 -0700726 Note board can be passed that in but by default if self._board is set,
727 that is used rather than board.
728
Simran Basi99e63c02014-05-20 10:39:52 -0700729 Args:
730 path_list: [board, version, alias] as split from the xbuddy call url.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800731 board: Board whos artifacts we are looking for. Only used if no board was
732 given during XBuddy initialization.
733 version: Version whose artifacts we are looking for. Used if no version
734 was given during XBuddy initialization. If None, defers to LATEST.
Simran Basi99e63c02014-05-20 10:39:52 -0700735 lookup_only: If true just look up the artifact, if False stage it on
736 the devserver as well.
737 image_dir: Google Storage image archive to search in if requesting a
738 remote artifact. If none uses the default bucket.
739
joychen346531c2013-07-24 16:55:56 -0700740 Returns:
Simran Basi99e63c02014-05-20 10:39:52 -0700741 build_id: Path to the image or update directory on the devserver or
742 in Google Storage. e.g. 'x86-generic/R26-4000.0.0'
743 file_name: of the artifact in the build_id directory.
joychen346531c2013-07-24 16:55:56 -0700744
745 Raises:
joychen121fc9b2013-08-02 14:30:30 -0700746 XBuddyException: if the path could not be translated
Chris Sosa75490802013-09-30 17:21:45 -0700747 build_artifact.ArtifactDownloadError: if we failed to download the
748 artifact.
joychen346531c2013-07-24 16:55:56 -0700749 """
joychen121fc9b2013-08-02 14:30:30 -0700750 path = '/'.join(path_list)
Chris Sosa0eecf962014-02-03 14:14:39 -0800751 default_board = self._board if self._board else board
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800752 default_version = self._version or version or LATEST
joychenb0dfe552013-07-30 10:02:06 -0700753 # Rewrite the path if there is an appropriate default.
Gilad Arnold38e828c2015-04-24 13:52:07 -0700754 path, suffix = self.LookupAlias(path, board=default_board,
755 version=default_version)
joychen121fc9b2013-08-02 14:30:30 -0700756 # Parse the path.
Chris Sosa0eecf962014-02-03 14:14:39 -0800757 image_type, board, version, is_local = self._InterpretPath(
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800758 path, default_board, default_version)
joychen7df67f72013-07-18 14:21:12 -0700759 if is_local:
joychen121fc9b2013-08-02 14:30:30 -0700760 # Get a local image.
joychen7df67f72013-07-18 14:21:12 -0700761 if version == LATEST:
joychen121fc9b2013-08-02 14:30:30 -0700762 # Get the latest local image for the given board.
763 version = self._GetLatestLocalVersion(board)
joychen7df67f72013-07-18 14:21:12 -0700764
joychenc3944cb2013-08-19 10:42:07 -0700765 build_id = os.path.join(board, version)
766 artifact_dir = os.path.join(self.static_dir, build_id)
767 if image_type == ANY:
768 image_type = self._FindAny(artifact_dir)
joychen121fc9b2013-08-02 14:30:30 -0700769
joychenc3944cb2013-08-19 10:42:07 -0700770 file_name = LOCAL_ALIAS_TO_FILENAME[image_type]
771 artifact_path = os.path.join(artifact_dir, file_name)
772 if not os.path.exists(artifact_path):
773 raise XBuddyException('Local %s artifact not in static_dir at %s' %
774 (image_type, artifact_path))
joychen121fc9b2013-08-02 14:30:30 -0700775
joychen921e1fb2013-06-28 11:12:20 -0700776 else:
joychen121fc9b2013-08-02 14:30:30 -0700777 # Get a remote image.
joychen921e1fb2013-06-28 11:12:20 -0700778 if image_type not in GS_ALIASES:
joychen7df67f72013-07-18 14:21:12 -0700779 raise XBuddyException('Bad remote image type: %s. Use one of: %s' %
joychen921e1fb2013-06-28 11:12:20 -0700780 (image_type, GS_ALIASES))
Gilad Arnold896c6d82015-03-13 16:20:29 -0700781 build_id = self._ResolveVersionToBuildId(board, suffix, version,
Simran Basi99e63c02014-05-20 10:39:52 -0700782 image_dir=image_dir)
Chris Sosa75490802013-09-30 17:21:45 -0700783 _Log('Resolved version %s to %s.', version, build_id)
784 file_name = GS_ALIAS_TO_FILENAME[image_type]
785 if not lookup_only:
Simran Basi99e63c02014-05-20 10:39:52 -0700786 self._GetFromGS(build_id, image_type, image_dir=image_dir)
joychenf8f07e22013-07-12 17:45:51 -0700787
joychenc3944cb2013-08-19 10:42:07 -0700788 return build_id, file_name
joychen3cb228e2013-06-12 12:13:13 -0700789
790 ############################ BEGIN PUBLIC METHODS
791
792 def List(self):
793 """Lists the currently available images & time since last access."""
joychen921e1fb2013-06-28 11:12:20 -0700794 self._SyncRegistryWithBuildImages()
795 builds = self._ListBuildTimes()
796 return_string = ''
797 for build, timestamp in builds:
798 return_string += '<b>' + build + '</b> '
799 return_string += '(time since last access: ' + str(timestamp) + ')<br>'
800 return return_string
joychen3cb228e2013-06-12 12:13:13 -0700801
802 def Capacity(self):
803 """Returns the number of images cached by xBuddy."""
joychen562699a2013-08-13 15:22:14 -0700804 return str(self._Capacity())
joychen3cb228e2013-06-12 12:13:13 -0700805
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800806 def Translate(self, path_list, board=None, version=None, image_dir=None):
joychen346531c2013-07-24 16:55:56 -0700807 """Translates an xBuddy path to a real path to artifact if it exists.
808
joychen121fc9b2013-08-02 14:30:30 -0700809 Equivalent to the Get call, minus downloading and updating timestamps,
joychen346531c2013-07-24 16:55:56 -0700810
Simran Basi99e63c02014-05-20 10:39:52 -0700811 Args:
812 path_list: [board, version, alias] as split from the xbuddy call url.
813 board: Board whos artifacts we are looking for. If None, use the board
814 XBuddy was initialized to use.
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800815 version: Version whose artifacts we are looking for. If None, use the
816 version XBuddy was initialized with, or LATEST.
Simran Basi99e63c02014-05-20 10:39:52 -0700817 image_dir: image directory to check in Google Storage. If none,
818 the default bucket is used.
819
joychen7c2054a2013-07-25 11:14:07 -0700820 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700821 build_id: Path to the image or update directory on the devserver.
822 e.g. 'x86-generic/R26-4000.0.0'
823 The returned path is always the path to the directory within
824 static_dir, so it is always the build_id of the image.
825 file_name: The file name of the artifact. Can take any of the file
826 values in devserver_constants.
827 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
828 specified 'test' or 'full_payload' artifacts, respectively.
joychen7c2054a2013-07-25 11:14:07 -0700829
joychen121fc9b2013-08-02 14:30:30 -0700830 Raises:
831 XBuddyException: if the path couldn't be translated
joychen346531c2013-07-24 16:55:56 -0700832 """
833 self._SyncRegistryWithBuildImages()
Chris Sosa75490802013-09-30 17:21:45 -0700834 build_id, file_name = self._GetArtifact(path_list, board=board,
Gilad Arnoldd04fcab2015-02-19 12:00:45 -0800835 version=version,
Simran Basi99e63c02014-05-20 10:39:52 -0700836 lookup_only=True,
837 image_dir=image_dir)
joychen346531c2013-07-24 16:55:56 -0700838
joychen121fc9b2013-08-02 14:30:30 -0700839 _Log('Returning path to payload: %s/%s', build_id, file_name)
840 return build_id, file_name
joychen346531c2013-07-24 16:55:56 -0700841
Yu-Ju Hong1bdb7a92014-04-10 16:02:11 -0700842 def StageTestArtifactsForUpdate(self, path_list):
Chris Sosa75490802013-09-30 17:21:45 -0700843 """Stages test artifacts for update and returns build_id.
844
845 Raises:
846 XBuddyException: if the path could not be translated
847 build_artifact.ArtifactDownloadError: if we failed to download the test
848 artifacts.
849 """
850 build_id, file_name = self.Translate(path_list)
851 if file_name == devserver_constants.TEST_IMAGE_FILE:
852 gs_url = os.path.join(devserver_constants.GS_IMAGE_DIR,
853 build_id)
854 artifacts = [FULL, STATEFUL]
855 self._Download(gs_url, artifacts)
856 return build_id
857
Simran Basi99e63c02014-05-20 10:39:52 -0700858 def Get(self, path_list, image_dir=None):
joychen921e1fb2013-06-28 11:12:20 -0700859 """The full xBuddy call, returns resource specified by path_list.
joychen3cb228e2013-06-12 12:13:13 -0700860
861 Please see devserver.py:xbuddy for full documentation.
joychen121fc9b2013-08-02 14:30:30 -0700862
joychen3cb228e2013-06-12 12:13:13 -0700863 Args:
Simran Basi99e63c02014-05-20 10:39:52 -0700864 path_list: [board, version, alias] as split from the xbuddy call url.
865 image_dir: image directory to check in Google Storage. If none,
866 the default bucket is used.
joychen3cb228e2013-06-12 12:13:13 -0700867
868 Returns:
joychen121fc9b2013-08-02 14:30:30 -0700869 build_id: Path to the image or update directory on the devserver.
Simran Basi99e63c02014-05-20 10:39:52 -0700870 e.g. 'x86-generic/R26-4000.0.0'
871 The returned path is always the path to the directory within
872 static_dir, so it is always the build_id of the image.
joychen121fc9b2013-08-02 14:30:30 -0700873 file_name: The file name of the artifact. Can take any of the file
Simran Basi99e63c02014-05-20 10:39:52 -0700874 values in devserver_constants.
875 e.g. 'chromiumos_test_image.bin' or 'update.gz' if the path list
876 specified 'test' or 'full_payload' artifacts, respectively.
joychen3cb228e2013-06-12 12:13:13 -0700877
878 Raises:
Chris Sosa75490802013-09-30 17:21:45 -0700879 XBuddyException: if the path could not be translated
880 build_artifact.ArtifactDownloadError: if we failed to download the
881 artifact.
joychen3cb228e2013-06-12 12:13:13 -0700882 """
joychen7df67f72013-07-18 14:21:12 -0700883 self._SyncRegistryWithBuildImages()
Simran Basi99e63c02014-05-20 10:39:52 -0700884 build_id, file_name = self._GetArtifact(path_list, image_dir=image_dir)
joychen921e1fb2013-06-28 11:12:20 -0700885 Timestamp.UpdateTimestamp(self._timestamp_folder, build_id)
joychen3cb228e2013-06-12 12:13:13 -0700886 #TODO (joyc): run in sep thread
Chris Sosa75490802013-09-30 17:21:45 -0700887 self.CleanCache()
joychen3cb228e2013-06-12 12:13:13 -0700888
joychen121fc9b2013-08-02 14:30:30 -0700889 _Log('Returning path to payload: %s/%s', build_id, file_name)
890 return build_id, file_name