blob: bb8ec46a13f8ae2ea638fc2ea84c222c8e4a03a6 [file] [log] [blame]
Gilad Arnold950569b2013-08-27 14:38:01 -07001#!/usr/bin/python
Chris Sosa968a1062013-08-02 17:42:50 -07002
Chris Sosa47a7d4e2012-03-28 11:26:55 -07003# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Module containing classes that wrap artifact downloads."""
8
Chris Sosa47a7d4e2012-03-28 11:26:55 -07009import os
Dan Shi6e50c722013-08-19 15:05:06 -070010import pickle
Gilad Arnold950569b2013-08-27 14:38:01 -070011import re
Chris Sosa47a7d4e2012-03-28 11:26:55 -070012import shutil
13import subprocess
14
Chris Sosa76e44b92013-01-31 12:11:38 -080015import artifact_info
16import common_util
joychen3cb228e2013-06-12 12:13:13 -070017import devserver_constants
Chris Sosa47a7d4e2012-03-28 11:26:55 -070018import gsutil_util
Gilad Arnoldc65330c2012-09-20 15:17:48 -070019import log_util
Chris Sosa47a7d4e2012-03-28 11:26:55 -070020
21
Chris Sosa76e44b92013-01-31 12:11:38 -080022_AU_BASE = 'au'
23_NTON_DIR_SUFFIX = '_nton'
24_MTON_DIR_SUFFIX = '_mton'
25
26############ Actual filenames of artifacts in Google Storage ############
27
28AU_SUITE_FILE = 'au_control.tar.bz2'
Chris Sosa968a1062013-08-02 17:42:50 -070029PAYGEN_AU_SUITE_FILE_TEMPLATE = 'paygen_au_%(channel)s_control.tar.bz2'
Chris Sosa76e44b92013-01-31 12:11:38 -080030AUTOTEST_FILE = 'autotest.tar'
31AUTOTEST_COMPRESSED_FILE = 'autotest.tar.bz2'
32DEBUG_SYMBOLS_FILE = 'debug.tgz'
Gilad Arnold950569b2013-08-27 14:38:01 -070033FACTORY_FILE = 'ChromeOS-factory*zip'
Chris Sosa76e44b92013-01-31 12:11:38 -080034FIRMWARE_FILE = 'firmware_from_source.tar.bz2'
35IMAGE_FILE = 'image.zip'
Chris Sosa76e44b92013-01-31 12:11:38 -080036TEST_SUITES_FILE = 'test_suites.tar.bz2'
37
38_build_artifact_locks = common_util.LockDict()
Chris Sosa47a7d4e2012-03-28 11:26:55 -070039
40
41class ArtifactDownloadError(Exception):
42 """Error used to signify an issue processing an artifact."""
43 pass
44
45
Gilad Arnoldc65330c2012-09-20 15:17:48 -070046class BuildArtifact(log_util.Loggable):
Chris Sosa47a7d4e2012-03-28 11:26:55 -070047 """Wrapper around an artifact to download from gsutil.
48
49 The purpose of this class is to download objects from Google Storage
50 and install them to a local directory. There are two main functions, one to
51 download/prepare the artifacts in to a temporary staging area and the second
52 to stage it into its final destination.
Chris Sosa76e44b92013-01-31 12:11:38 -080053
Gilad Arnold950569b2013-08-27 14:38:01 -070054 IMPORTANT! (i) `name' is a glob expression by default (and not a regex), be
55 attentive when adding new artifacts; (ii) name matching semantics differ
56 between a glob (full name string match) and a regex (partial match).
57
Chris Sosa76e44b92013-01-31 12:11:38 -080058 Class members:
Gilad Arnold950569b2013-08-27 14:38:01 -070059 archive_url: An archive URL.
60 name: Name given for artifact; in fact, it is a pattern that captures the
61 names of files contained in the artifact. This can either be an
62 ordinary shell-style glob (the default), or a regular expression (if
63 is_regex_name is True).
64 is_regex_name: Whether the name value is a regex (default: glob).
Chris Sosa76e44b92013-01-31 12:11:38 -080065 build: The version of the build i.e. R26-2342.0.0.
66 marker_name: Name used to define the lock marker for the artifacts to
67 prevent it from being re-downloaded. By default based on name
68 but can be overriden by children.
Dan Shi6e50c722013-08-19 15:05:06 -070069 exception_file_path: Path to a file containing the serialized exception,
70 which was raised in Process method. The file is located
71 in the parent folder of install_dir, since the
72 install_dir will be deleted if the build does not
73 existed.
joychen0a8e34e2013-06-24 17:58:36 -070074 install_path: Path to artifact.
Chris Sosa76e44b92013-01-31 12:11:38 -080075 install_dir: The final location where the artifact should be staged to.
76 single_name: If True the name given should only match one item. Note, if not
77 True, self.name will become a list of items returned.
Gilad Arnold1638d822013-11-07 23:38:16 -080078 installed_files: A list of files that were the final result of downloading
79 and setting up the artifact.
80 store_installed_files: Whether the list of installed files is stored in the
81 marker file.
Chris Sosa47a7d4e2012-03-28 11:26:55 -070082 """
Gilad Arnold950569b2013-08-27 14:38:01 -070083
84 def __init__(self, install_dir, archive_url, name, build,
85 is_regex_name=False):
86 """Constructor.
87
88 Args:
Chris Sosa76e44b92013-01-31 12:11:38 -080089 install_dir: Where to install the artifact.
90 archive_url: The Google Storage path to find the artifact.
91 name: Identifying name to be used to find/store the artifact.
92 build: The name of the build e.g. board/release.
Gilad Arnold950569b2013-08-27 14:38:01 -070093 is_regex_name: Whether the name pattern is a regex (default: glob).
Chris Sosa47a7d4e2012-03-28 11:26:55 -070094 """
Chris Sosa6a3697f2013-01-29 16:44:43 -080095 super(BuildArtifact, self).__init__()
Chris Sosa47a7d4e2012-03-28 11:26:55 -070096
Chris Sosa76e44b92013-01-31 12:11:38 -080097 # In-memory lock to keep the devserver from colliding with itself while
98 # attempting to stage the same artifact.
99 self._process_lock = None
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700100
Chris Sosa76e44b92013-01-31 12:11:38 -0800101 self.archive_url = archive_url
102 self.name = name
Gilad Arnold950569b2013-08-27 14:38:01 -0700103 self.is_regex_name = is_regex_name
Chris Sosa76e44b92013-01-31 12:11:38 -0800104 self.build = build
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700105
Chris Sosa76e44b92013-01-31 12:11:38 -0800106 self.marker_name = '.' + self._SanitizeName(name)
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700107
Dan Shi6e50c722013-08-19 15:05:06 -0700108 exception_file_name = ('.' + self._SanitizeName(build) + self.marker_name +
109 '.exception')
110 # The exception file needs to be located in parent folder, since the
111 # install_dir will be deleted is the build does not exist.
112 self.exception_file_path = os.path.join(os.path.dirname(install_dir),
Gilad Arnold950569b2013-08-27 14:38:01 -0700113 exception_file_name)
Dan Shi6e50c722013-08-19 15:05:06 -0700114
joychen0a8e34e2013-06-24 17:58:36 -0700115 self.install_path = None
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700116
Chris Sosa76e44b92013-01-31 12:11:38 -0800117 self.install_dir = install_dir
118
119 self.single_name = True
120
Gilad Arnold1638d822013-11-07 23:38:16 -0800121 self.installed_files = []
122 self.store_installed_files = True
123
Chris Sosa76e44b92013-01-31 12:11:38 -0800124 @staticmethod
125 def _SanitizeName(name):
126 """Sanitizes name to be used for creating a file on the filesystem.
127
128 '.','/' and '*' have special meaning in FS lingo. Replace them with words.
Gilad Arnold950569b2013-08-27 14:38:01 -0700129
130 Args:
131 name: A file name/path.
132 Returns:
133 The sanitized name/path.
Chris Sosa76e44b92013-01-31 12:11:38 -0800134 """
135 return name.replace('*', 'STAR').replace('.', 'DOT').replace('/', 'SLASH')
136
Dan Shif8eb0d12013-08-01 17:52:06 -0700137 def ArtifactStaged(self):
Gilad Arnold1638d822013-11-07 23:38:16 -0800138 """Returns True if artifact is already staged.
139
140 This checks for (1) presence of the artifact marker file, and (2) the
141 presence of each installed file listed in this marker. Both must hold for
142 the artifact to be considered staged. Note that this method is safe for use
143 even if the artifacts were not stageed by this instance, as it is assumed
144 that any BuildArtifact instance that did the staging wrote the list of
145 files actually installed into the marker.
146 """
147 marker_file = os.path.join(self.install_dir, self.marker_name)
148
149 # If the marker is missing, it's definitely not staged.
150 if not os.path.exists(marker_file):
151 return False
152
153 # We want to ensure that every file listed in the marker is actually there.
154 if self.store_installed_files:
155 with open(marker_file) as f:
156 files = [line.strip() for line in f]
157
158 # Check to see if any of the purportedly installed files are missing, in
159 # which case the marker is outdated and should be removed.
160 missing_files = [fname for fname in files if not os.path.exists(fname)]
161 if missing_files:
162 self._Log('***ATTENTION*** %s files listed in %s are missing:\n%s',
163 'All' if len(files) == len(missing_files) else 'Some',
164 marker_file, '\n'.join(missing_files))
165 os.remove(marker_file)
166 return False
167
168 return True
Chris Sosa76e44b92013-01-31 12:11:38 -0800169
170 def _MarkArtifactStaged(self):
171 """Marks the artifact as staged."""
172 with open(os.path.join(self.install_dir, self.marker_name), 'w') as f:
Gilad Arnold1638d822013-11-07 23:38:16 -0800173 f.write('\n'.join(self.installed_files))
Chris Sosa76e44b92013-01-31 12:11:38 -0800174
Chris Sosac4e87842013-08-16 18:04:14 -0700175 def WaitForArtifactToExist(self, timeout, update_name=True):
176 """Waits for artifact to exist and sets self.name to appropriate name.
177
178 Args:
Gilad Arnold950569b2013-08-27 14:38:01 -0700179 timeout: How long to wait for artifact to become available.
Chris Sosac4e87842013-08-16 18:04:14 -0700180 update_name: If False, don't actually update self.name.
Gilad Arnold950569b2013-08-27 14:38:01 -0700181 Raises:
182 ArtifactDownloadError: An error occurred when obtaining artifact.
Chris Sosac4e87842013-08-16 18:04:14 -0700183 """
Chris Sosa76e44b92013-01-31 12:11:38 -0800184 names = gsutil_util.GetGSNamesWithWait(
Gilad Arnold950569b2013-08-27 14:38:01 -0700185 self.name, self.archive_url, str(self), timeout=timeout,
186 is_regex_pattern=self.is_regex_name)
Chris Sosa76e44b92013-01-31 12:11:38 -0800187 if not names:
188 raise ArtifactDownloadError('Could not find %s in Google Storage' %
189 self.name)
190
191 if self.single_name:
192 if len(names) > 1:
193 raise ArtifactDownloadError('Too many artifacts match %s' % self.name)
194
Chris Sosac4e87842013-08-16 18:04:14 -0700195 new_name = names[0]
Chris Sosa76e44b92013-01-31 12:11:38 -0800196 else:
Chris Sosac4e87842013-08-16 18:04:14 -0700197 new_name = names
198
199 if update_name:
200 self.name = new_name
Chris Sosa76e44b92013-01-31 12:11:38 -0800201
202 def _Download(self):
joychen0a8e34e2013-06-24 17:58:36 -0700203 """Downloads artifact from Google Storage to a local directory."""
Chris Sosa76e44b92013-01-31 12:11:38 -0800204 gs_path = '/'.join([self.archive_url, self.name])
joychen0a8e34e2013-06-24 17:58:36 -0700205 self.install_path = os.path.join(self.install_dir, self.name)
206 gsutil_util.DownloadFromGS(gs_path, self.install_path)
Chris Sosa76e44b92013-01-31 12:11:38 -0800207
joychen0a8e34e2013-06-24 17:58:36 -0700208 def _Setup(self):
Gilad Arnold1638d822013-11-07 23:38:16 -0800209 """Process the downloaded content, update the list of installed files."""
210 # In this primitive case, what was downloaded (has to be a single file) is
211 # what's installed.
212 self.installed_files = [self.install_path]
joychen0a8e34e2013-06-24 17:58:36 -0700213
Dan Shi6e50c722013-08-19 15:05:06 -0700214 def _ClearException(self):
215 """Delete any existing exception saved for this artifact."""
216 if os.path.exists(self.exception_file_path):
217 os.remove(self.exception_file_path)
218
219 def _SaveException(self, e):
220 """Save the exception to a file for downloader.IsStaged to retrieve.
221
Gilad Arnold950569b2013-08-27 14:38:01 -0700222 Args:
223 e: Exception object to be saved.
Dan Shi6e50c722013-08-19 15:05:06 -0700224 """
225 with open(self.exception_file_path, 'w') as f:
226 pickle.dump(e, f)
227
228 def GetException(self):
229 """Retrieve any exception that was raised in Process method.
230
Gilad Arnold950569b2013-08-27 14:38:01 -0700231 Returns:
232 An Exception object that was raised when trying to process the artifact.
233 Return None if no exception was found.
Dan Shi6e50c722013-08-19 15:05:06 -0700234 """
235 if not os.path.exists(self.exception_file_path):
236 return None
237 with open(self.exception_file_path, 'r') as f:
238 return pickle.load(f)
Chris Sosa76e44b92013-01-31 12:11:38 -0800239
240 def Process(self, no_wait):
241 """Main call point to all artifacts. Downloads and Stages artifact.
242
243 Downloads and Stages artifact from Google Storage to the install directory
244 specified in the constructor. It multi-thread safe and does not overwrite
245 the artifact if it's already been downloaded or being downloaded. After
246 processing, leaves behind a marker to indicate to future invocations that
247 the artifact has already been staged based on the name of the artifact.
248
249 Do not override as it modifies important private variables, ensures thread
250 safety, and maintains cache semantics.
251
252 Note: this may be a blocking call when the artifact is already in the
253 process of being staged.
254
255 Args:
256 no_wait: If True, don't block waiting for artifact to exist if we fail to
257 immediately find it.
258
259 Raises:
260 ArtifactDownloadError: If the artifact fails to download from Google
261 Storage for any reason or that the regexp
262 defined by name is not specific enough.
263 """
264 if not self._process_lock:
265 self._process_lock = _build_artifact_locks.lock(
266 os.path.join(self.install_dir, self.name))
267
268 with self._process_lock:
269 common_util.MkDirP(self.install_dir)
Dan Shif8eb0d12013-08-01 17:52:06 -0700270 if not self.ArtifactStaged():
Dan Shi6e50c722013-08-19 15:05:06 -0700271 try:
272 # Delete any existing exception saved for this artifact.
273 self._ClearException()
274 # If the artifact should already have been uploaded, don't waste
275 # cycles waiting around for it to exist.
276 timeout = 1 if no_wait else 10
277 self.WaitForArtifactToExist(timeout)
278 self._Download()
279 self._Setup()
280 self._MarkArtifactStaged()
281 except Exception as e:
282 # Save the exception to a file for downloader.IsStaged to retrieve.
283 self._SaveException(e)
284 raise
Chris Sosa76e44b92013-01-31 12:11:38 -0800285 else:
286 self._Log('%s is already staged.', self)
287
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700288 def __str__(self):
289 """String representation for the download."""
Chris Sosa76e44b92013-01-31 12:11:38 -0800290 return '->'.join(['%s/%s' % (self.archive_url, self.name),
Gilad Arnold950569b2013-08-27 14:38:01 -0700291 self.install_dir])
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700292
Chris Sosab26b1202013-08-16 16:40:55 -0700293 def __repr__(self):
294 return str(self)
295
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700296
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700297class AUTestPayloadBuildArtifact(BuildArtifact):
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700298 """Wrapper for AUTest delta payloads which need additional setup."""
Gilad Arnold950569b2013-08-27 14:38:01 -0700299
joychen0a8e34e2013-06-24 17:58:36 -0700300 def _Setup(self):
301 super(AUTestPayloadBuildArtifact, self)._Setup()
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700302
Chris Sosa76e44b92013-01-31 12:11:38 -0800303 # Rename to update.gz.
304 install_path = os.path.join(self.install_dir, self.name)
joychen3cb228e2013-06-12 12:13:13 -0700305 new_install_path = os.path.join(self.install_dir,
joychen7c2054a2013-07-25 11:14:07 -0700306 devserver_constants.UPDATE_FILE)
Chris Sosa76e44b92013-01-31 12:11:38 -0800307 shutil.move(install_path, new_install_path)
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700308
Gilad Arnold1638d822013-11-07 23:38:16 -0800309 # Reflect the rename in the list of installed files.
310 self.installed_files.remove(install_path)
311 self.installed_files = [new_install_path]
312
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700313
Chris Sosa76e44b92013-01-31 12:11:38 -0800314# TODO(sosa): Change callers to make this artifact more sane.
315class DeltaPayloadsArtifact(BuildArtifact):
316 """Delta payloads from the archive_url.
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700317
Chris Sosa76e44b92013-01-31 12:11:38 -0800318 This artifact is super strange. It custom handles directories and
319 pulls in all delta payloads. We can't specify exactly what we want
320 because unlike other artifacts, this one does not conform to something a
321 client might know. The client doesn't know the version of n-1 or whether it
322 was even generated.
Gilad Arnold950569b2013-08-27 14:38:01 -0700323
324 IMPORTANT! Note that this artifact simply ignores the `name' argument because
325 that name is derived internally in accordance with sub-artifacts. Also note
326 the different types of names (in fact, file name patterns) used for the
327 different sub-artifacts.
Chris Sosa76e44b92013-01-31 12:11:38 -0800328 """
Gilad Arnold950569b2013-08-27 14:38:01 -0700329
Chris Sosa76e44b92013-01-31 12:11:38 -0800330 def __init__(self, *args):
331 super(DeltaPayloadsArtifact, self).__init__(*args)
Gilad Arnold950569b2013-08-27 14:38:01 -0700332 # Override the name field, we know what it should be.
333 self.name = '*_delta_*'
334 self.is_regex_name = False
335 self.single_name = False # Expect multiple deltas
336
337 # We use a regular glob for the N-to-N delta payload.
338 nton_name = 'chromeos_%s*_delta_*' % self.build
339 # We use a regular expression for the M-to-N delta payload.
340 mton_name = ('chromeos_(?!%s).*_delta_.*' % re.escape(self.build))
341
Chris Sosa76e44b92013-01-31 12:11:38 -0800342 nton_install_dir = os.path.join(self.install_dir, _AU_BASE,
343 self.build + _NTON_DIR_SUFFIX)
344 mton_install_dir = os.path.join(self.install_dir, _AU_BASE,
Gilad Arnold950569b2013-08-27 14:38:01 -0700345 self.build + _MTON_DIR_SUFFIX)
Chris Sosa76e44b92013-01-31 12:11:38 -0800346 self._sub_artifacts = [
347 AUTestPayloadBuildArtifact(mton_install_dir, self.archive_url,
Gilad Arnold950569b2013-08-27 14:38:01 -0700348 mton_name, self.build, is_regex_name=True),
Chris Sosa76e44b92013-01-31 12:11:38 -0800349 AUTestPayloadBuildArtifact(nton_install_dir, self.archive_url,
350 nton_name, self.build)]
Yu-Ju Honge61cbe92012-07-10 14:10:26 -0700351
Chris Sosa76e44b92013-01-31 12:11:38 -0800352 def _Download(self):
joychen0a8e34e2013-06-24 17:58:36 -0700353 """With sub-artifacts we do everything in _Setup()."""
Chris Sosa76e44b92013-01-31 12:11:38 -0800354 pass
Yu-Ju Honge61cbe92012-07-10 14:10:26 -0700355
joychen0a8e34e2013-06-24 17:58:36 -0700356 def _Setup(self):
Chris Sosa76e44b92013-01-31 12:11:38 -0800357 """Process each sub-artifact. Only error out if none can be found."""
358 for artifact in self._sub_artifacts:
359 try:
360 artifact.Process(no_wait=True)
361 # Setup symlink so that AU will work for this payload.
Gilad Arnold1638d822013-11-07 23:38:16 -0800362 stateful_update_symlink = os.path.join(
363 artifact.install_dir, devserver_constants.STATEFUL_FILE)
Chris Sosa76e44b92013-01-31 12:11:38 -0800364 os.symlink(
joychen25d25972013-07-30 14:54:16 -0700365 os.path.join(os.pardir, os.pardir,
joychen121fc9b2013-08-02 14:30:30 -0700366 devserver_constants.STATEFUL_FILE),
Gilad Arnold1638d822013-11-07 23:38:16 -0800367 stateful_update_symlink)
368
369 # Aggregate sub-artifact file lists, including stateful symlink.
370 self.installed_files += artifact.installed_files
371 self.installed_files.append(stateful_update_symlink)
Chris Sosa76e44b92013-01-31 12:11:38 -0800372 except ArtifactDownloadError as e:
373 self._Log('Could not process %s: %s', artifact, e)
Yu-Ju Honge61cbe92012-07-10 14:10:26 -0700374
Chris Sosa76e44b92013-01-31 12:11:38 -0800375
376class BundledBuildArtifact(BuildArtifact):
377 """A single build artifact bundle e.g. zip file or tar file."""
Chris Sosa76e44b92013-01-31 12:11:38 -0800378
Gilad Arnold950569b2013-08-27 14:38:01 -0700379 def __init__(self, install_dir, archive_url, name, build,
380 is_regex_name=False, files_to_extract=None, exclude=None):
381 """Takes BuildArtifact args with some additional ones.
382
383 Args:
384 install_dir: See superclass.
385 archive_url: See superclass.
386 name: See superclass.
387 build: See superclass.
388 is_regex_name: See superclass.
389 files_to_extract: A list of files to extract. If set to None, extract
390 all files.
391 exclude: A list of files to exclude. If None, no files are excluded.
Chris Sosa76e44b92013-01-31 12:11:38 -0800392 """
Gilad Arnold950569b2013-08-27 14:38:01 -0700393 super(BundledBuildArtifact, self).__init__(
394 install_dir, archive_url, name, build, is_regex_name=is_regex_name)
Chris Sosa76e44b92013-01-31 12:11:38 -0800395 self._files_to_extract = files_to_extract
396 self._exclude = exclude
397
398 # We modify the marker so that it is unique to what was staged.
399 if files_to_extract:
400 self.marker_name = self._SanitizeName(
401 '_'.join(['.' + self.name] + files_to_extract))
402
403 def _Extract(self):
404 """Extracts the bundle into install_dir. Must be overridden.
405
406 If set, uses files_to_extract to only extract those items. If set, use
Gilad Arnold1638d822013-11-07 23:38:16 -0800407 exclude to exclude specific files. In any case, this must return the list
408 of files extracted (absolute paths).
Chris Sosa76e44b92013-01-31 12:11:38 -0800409 """
410 raise NotImplementedError()
411
joychen0a8e34e2013-06-24 17:58:36 -0700412 def _Setup(self):
Gilad Arnold1638d822013-11-07 23:38:16 -0800413 extract_result = self._Extract()
414 if self.store_installed_files:
415 # List both the archive and the extracted files.
416 self.installed_files.append(self.install_path)
417 self.installed_files.extend(extract_result)
Chris Sosa76e44b92013-01-31 12:11:38 -0800418
419
420class TarballBuildArtifact(BundledBuildArtifact):
421 """Artifact for tar and tarball files."""
422
423 def _Extract(self):
424 """Extracts a tarball using tar.
425
426 Detects whether the tarball is compressed or not based on the file
427 extension and extracts the tarball into the install_path.
428 """
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700429 try:
Gilad Arnold1638d822013-11-07 23:38:16 -0800430 return common_util.ExtractTarball(self.install_path, self.install_dir,
431 files_to_extract=self._files_to_extract,
432 excluded_files=self._exclude,
433 return_extracted_files=True)
Simran Basi4baad082013-02-14 13:39:18 -0800434 except common_util.CommonUtilError as e:
435 raise ArtifactDownloadError(str(e))
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700436
437
Gilad Arnoldc65330c2012-09-20 15:17:48 -0700438class AutotestTarballBuildArtifact(TarballBuildArtifact):
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700439 """Wrapper around the autotest tarball to download from gsutil."""
440
Gilad Arnolde57e2332013-11-14 17:07:11 -0800441 def __init__(self, *args, **dargs):
442 super(AutotestTarballBuildArtifact, self).__init__(*args, **dargs)
Gilad Arnold1638d822013-11-07 23:38:16 -0800443 # We don't store/check explicit file lists in Autotest tarball markers;
444 # this can get huge and unwieldy, and generally make little sense.
445 self.store_installed_files = False
446
joychen0a8e34e2013-06-24 17:58:36 -0700447 def _Setup(self):
Chris Sosa76e44b92013-01-31 12:11:38 -0800448 """Extracts the tarball into the install path excluding test suites."""
joychen0a8e34e2013-06-24 17:58:36 -0700449 super(AutotestTarballBuildArtifact, self)._Setup()
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700450
Chris Sosa76e44b92013-01-31 12:11:38 -0800451 # Deal with older autotest packages that may not be bundled.
joychen3cb228e2013-06-12 12:13:13 -0700452 autotest_dir = os.path.join(self.install_dir,
453 devserver_constants.AUTOTEST_DIR)
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700454 autotest_pkgs_dir = os.path.join(autotest_dir, 'packages')
455 if not os.path.exists(autotest_pkgs_dir):
456 os.makedirs(autotest_pkgs_dir)
457
458 if not os.path.exists(os.path.join(autotest_pkgs_dir, 'packages.checksum')):
Chris Sosa76e44b92013-01-31 12:11:38 -0800459 cmd = ['autotest/utils/packager.py', 'upload', '--repository',
460 autotest_pkgs_dir, '--all']
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700461 try:
joychen0a8e34e2013-06-24 17:58:36 -0700462 subprocess.check_call(cmd, cwd=self.install_dir)
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700463 except subprocess.CalledProcessError, e:
Chris Sosa76e44b92013-01-31 12:11:38 -0800464 raise ArtifactDownloadError(
465 'Failed to create autotest packages!:\n%s' % e)
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700466 else:
Gilad Arnoldf5843132012-09-25 00:31:20 -0700467 self._Log('Using pre-generated packages from autotest')
Chris Sosa47a7d4e2012-03-28 11:26:55 -0700468
Chris Masone816e38c2012-05-02 12:22:36 -0700469
Chris Sosa76e44b92013-01-31 12:11:38 -0800470class ZipfileBuildArtifact(BundledBuildArtifact):
471 """A downloadable artifact that is a zipfile."""
Chris Masone816e38c2012-05-02 12:22:36 -0700472
Gilad Arnold1638d822013-11-07 23:38:16 -0800473 def _RunUnzip(self, list_only):
474 # Unzip is weird. It expects its args before any excludes and expects its
475 # excludes in a list following the -x.
476 cmd = ['unzip', '-qql' if list_only else '-o', self.install_path]
477 if not list_only:
478 cmd += ['-d', self.install_dir]
479
Chris Sosa76e44b92013-01-31 12:11:38 -0800480 if self._files_to_extract:
481 cmd.extend(self._files_to_extract)
Chris Masone816e38c2012-05-02 12:22:36 -0700482
Chris Sosa76e44b92013-01-31 12:11:38 -0800483 if self._exclude:
484 cmd.append('-x')
485 cmd.extend(self._exclude)
Gilad Arnold6f99b982012-09-12 10:49:40 -0700486
487 try:
Gilad Arnold1638d822013-11-07 23:38:16 -0800488 return subprocess.check_output(cmd).strip('\n').splitlines()
Gilad Arnold6f99b982012-09-12 10:49:40 -0700489 except subprocess.CalledProcessError, e:
Chris Sosa76e44b92013-01-31 12:11:38 -0800490 raise ArtifactDownloadError(
491 'An error occurred when attempting to unzip %s:\n%s' %
joychen0a8e34e2013-06-24 17:58:36 -0700492 (self.install_path, e))
Gilad Arnold6f99b982012-09-12 10:49:40 -0700493
Gilad Arnold1638d822013-11-07 23:38:16 -0800494 def _Extract(self):
495 """Extracts files into the install path."""
496 file_list = [os.path.join(self.install_dir, line[30:].strip())
497 for line in self._RunUnzip(True)
498 if not line.endswith('/')]
499 if file_list:
500 self._RunUnzip(False)
501
502 return file_list
503
Gilad Arnold6f99b982012-09-12 10:49:40 -0700504
Chris Sosa76e44b92013-01-31 12:11:38 -0800505class ImplDescription(object):
506 """Data wrapper that describes an artifact's implementation."""
Gilad Arnold950569b2013-08-27 14:38:01 -0700507
508 def __init__(self, artifact_class, name, *additional_args,
509 **additional_dargs):
510 """Constructor.
Chris Sosa76e44b92013-01-31 12:11:38 -0800511
512 Args:
513 artifact_class: BuildArtifact class to use for the artifact.
514 name: name to use to identify artifact (see BuildArtifact.name)
Gilad Arnold950569b2013-08-27 14:38:01 -0700515 *additional_args: Additional arguments to pass to artifact_class.
516 **additional_dargs: Additional named arguments to pass to artifact_class.
Chris Sosa76e44b92013-01-31 12:11:38 -0800517 """
518 self.artifact_class = artifact_class
519 self.name = name
520 self.additional_args = additional_args
Gilad Arnold950569b2013-08-27 14:38:01 -0700521 self.additional_dargs = additional_dargs
Chris Sosa76e44b92013-01-31 12:11:38 -0800522
Chris Sosa968a1062013-08-02 17:42:50 -0700523 def __repr__(self):
524 return '%s_%s' % (self.artifact_class, self.name)
525
Chris Sosa76e44b92013-01-31 12:11:38 -0800526
527# Maps artifact names to their implementation description.
528# Please note, it is good practice to use constants for these names if you're
529# going to re-use the names ANYWHERE else in the devserver code.
530ARTIFACT_IMPLEMENTATION_MAP = {
Gilad Arnold950569b2013-08-27 14:38:01 -0700531 artifact_info.FULL_PAYLOAD:
532 ImplDescription(AUTestPayloadBuildArtifact, '*_full_*'),
533 artifact_info.DELTA_PAYLOADS:
534 ImplDescription(DeltaPayloadsArtifact, 'DONTCARE'),
535 artifact_info.STATEFUL_PAYLOAD:
536 ImplDescription(BuildArtifact, devserver_constants.STATEFUL_FILE),
Chris Sosa76e44b92013-01-31 12:11:38 -0800537
Gilad Arnold950569b2013-08-27 14:38:01 -0700538 artifact_info.BASE_IMAGE:
539 ImplDescription(ZipfileBuildArtifact, IMAGE_FILE,
Gilad Arnold69878b42013-09-18 13:39:22 -0700540 files_to_extract=[devserver_constants.BASE_IMAGE_FILE]),
Gilad Arnold950569b2013-08-27 14:38:01 -0700541 artifact_info.RECOVERY_IMAGE:
542 ImplDescription(ZipfileBuildArtifact, IMAGE_FILE,
Gilad Arnold69878b42013-09-18 13:39:22 -0700543 files_to_extract=[devserver_constants.RECOVERY_IMAGE_FILE]),
Chris Sosa75490802013-09-30 17:21:45 -0700544 artifact_info.DEV_IMAGE:
545 ImplDescription(ZipfileBuildArtifact, IMAGE_FILE,
546 files_to_extract=[devserver_constants.IMAGE_FILE]),
Gilad Arnold950569b2013-08-27 14:38:01 -0700547 artifact_info.TEST_IMAGE:
548 ImplDescription(ZipfileBuildArtifact, IMAGE_FILE,
Gilad Arnold69878b42013-09-18 13:39:22 -0700549 files_to_extract=[devserver_constants.TEST_IMAGE_FILE]),
Chris Sosa76e44b92013-01-31 12:11:38 -0800550
Gilad Arnold950569b2013-08-27 14:38:01 -0700551 artifact_info.AUTOTEST:
552 ImplDescription(AutotestTarballBuildArtifact, AUTOTEST_FILE,
553 files_to_extract=None,
554 exclude=['autotest/test_suites']),
555 artifact_info.TEST_SUITES:
556 ImplDescription(TarballBuildArtifact, TEST_SUITES_FILE),
557 artifact_info.AU_SUITE:
558 ImplDescription(TarballBuildArtifact, AU_SUITE_FILE),
Chris Sosa76e44b92013-01-31 12:11:38 -0800559
Gilad Arnold950569b2013-08-27 14:38:01 -0700560 artifact_info.FIRMWARE:
561 ImplDescription(BuildArtifact, FIRMWARE_FILE),
562 artifact_info.SYMBOLS:
563 ImplDescription(TarballBuildArtifact, DEBUG_SYMBOLS_FILE,
564 files_to_extract=['debug/breakpad']),
beepsc3d0f872013-07-31 21:50:40 -0700565
Gilad Arnold950569b2013-08-27 14:38:01 -0700566 artifact_info.FACTORY_IMAGE:
567 ImplDescription(ZipfileBuildArtifact, FACTORY_FILE,
Gilad Arnold69878b42013-09-18 13:39:22 -0700568 files_to_extract=[devserver_constants.FACTORY_IMAGE_FILE])
Chris Sosa76e44b92013-01-31 12:11:38 -0800569}
570
Chris Sosa968a1062013-08-02 17:42:50 -0700571# Add all the paygen_au artifacts in one go.
572ARTIFACT_IMPLEMENTATION_MAP.update({
Gilad Arnold950569b2013-08-27 14:38:01 -0700573 artifact_info.PAYGEN_AU_SUITE_TEMPLATE % {'channel': c}:
574 ImplDescription(
575 TarballBuildArtifact, PAYGEN_AU_SUITE_FILE_TEMPLATE % {'channel': c})
576 for c in devserver_constants.CHANNELS
Chris Sosa968a1062013-08-02 17:42:50 -0700577})
578
Chris Sosa76e44b92013-01-31 12:11:38 -0800579
580class ArtifactFactory(object):
581 """A factory class that generates build artifacts from artifact names."""
582
Chris Sosa6b0c6172013-08-05 17:01:33 -0700583 def __init__(self, download_dir, archive_url, artifacts, files,
584 build):
Chris Sosa76e44b92013-01-31 12:11:38 -0800585 """Initalizes the member variables for the factory.
586
587 Args:
Gilad Arnold950569b2013-08-27 14:38:01 -0700588 download_dir: A directory to which artifacts are downloaded.
Chris Sosa76e44b92013-01-31 12:11:38 -0800589 archive_url: the Google Storage url of the bucket where the debug
590 symbols for the desired build are stored.
Chris Sosa6b0c6172013-08-05 17:01:33 -0700591 artifacts: List of artifacts to stage. These artifacts must be
592 defined in artifact_info.py and have a mapping in the
593 ARTIFACT_IMPLEMENTATION_MAP.
594 files: List of files to stage. These files are just downloaded and staged
595 as files into the download_dir.
Chris Sosa76e44b92013-01-31 12:11:38 -0800596 build: The name of the build.
597 """
joychen0a8e34e2013-06-24 17:58:36 -0700598 self.download_dir = download_dir
Chris Sosa76e44b92013-01-31 12:11:38 -0800599 self.archive_url = archive_url
Chris Sosa6b0c6172013-08-05 17:01:33 -0700600 self.artifacts = artifacts
601 self.files = files
Chris Sosa76e44b92013-01-31 12:11:38 -0800602 self.build = build
603
604 @staticmethod
Chris Sosa6b0c6172013-08-05 17:01:33 -0700605 def _GetDescriptionComponents(name, is_artifact):
Gilad Arnold950569b2013-08-27 14:38:01 -0700606 """Returns components for constructing a BuildArtifact.
Chris Sosa6b0c6172013-08-05 17:01:33 -0700607
Gilad Arnold950569b2013-08-27 14:38:01 -0700608 Args:
609 name: The artifact name / file pattern.
610 is_artifact: Whether this is a named (True) or file (False) artifact.
611 Returns:
612 A tuple consisting of the BuildArtifact subclass, name, and additional
613 list- and named-arguments.
614 Raises:
615 KeyError: if artifact doesn't exist in ARTIFACT_IMPLEMENTATION_MAP.
Chris Sosa6b0c6172013-08-05 17:01:33 -0700616 """
617
618 if is_artifact:
619 description = ARTIFACT_IMPLEMENTATION_MAP[name]
620 else:
621 description = ImplDescription(BuildArtifact, name)
622
Chris Sosa76e44b92013-01-31 12:11:38 -0800623 return (description.artifact_class, description.name,
Gilad Arnold950569b2013-08-27 14:38:01 -0700624 description.additional_args, description.additional_dargs)
Chris Sosa76e44b92013-01-31 12:11:38 -0800625
Chris Sosa6b0c6172013-08-05 17:01:33 -0700626 def _Artifacts(self, names, is_artifact):
Gilad Arnold950569b2013-08-27 14:38:01 -0700627 """Returns the BuildArtifacts from |names|.
Chris Sosa6b0c6172013-08-05 17:01:33 -0700628
629 If is_artifact is true, then these names define artifacts that must exist in
630 the ARTIFACT_IMPLEMENTATION_MAP. Otherwise, treat as filenames to stage as
631 basic BuildArtifacts.
632
Gilad Arnold950569b2013-08-27 14:38:01 -0700633 Args:
634 names: A sequence of artifact names.
635 is_artifact: Whether this is a named (True) or file (False) artifact.
636 Returns:
637 An iterable of BuildArtifacts.
638 Raises:
639 KeyError: if artifact doesn't exist in ARTIFACT_IMPLEMENTATION_MAP.
Chris Sosa6b0c6172013-08-05 17:01:33 -0700640 """
Chris Sosa76e44b92013-01-31 12:11:38 -0800641 artifacts = []
Chris Sosa6b0c6172013-08-05 17:01:33 -0700642 for name in names:
Gilad Arnold950569b2013-08-27 14:38:01 -0700643 artifact_class, path, args, dargs = self._GetDescriptionComponents(
Chris Sosa6b0c6172013-08-05 17:01:33 -0700644 name, is_artifact)
joychen0a8e34e2013-06-24 17:58:36 -0700645 artifacts.append(artifact_class(self.download_dir, self.archive_url, path,
Gilad Arnold950569b2013-08-27 14:38:01 -0700646 self.build, *args, **dargs))
Chris Sosa76e44b92013-01-31 12:11:38 -0800647
648 return artifacts
649
650 def RequiredArtifacts(self):
Gilad Arnold950569b2013-08-27 14:38:01 -0700651 """Returns BuildArtifacts for the factory's artifacts.
Chris Sosa6b0c6172013-08-05 17:01:33 -0700652
Gilad Arnold950569b2013-08-27 14:38:01 -0700653 Returns:
654 An iterable of BuildArtifacts.
655 Raises:
656 KeyError: if artifact doesn't exist in ARTIFACT_IMPLEMENTATION_MAP.
Chris Sosa6b0c6172013-08-05 17:01:33 -0700657 """
658 artifacts = []
659 if self.artifacts:
660 artifacts.extend(self._Artifacts(self.artifacts, True))
661 if self.files:
662 artifacts.extend(self._Artifacts(self.files, False))
663
664 return artifacts
Chris Sosa76e44b92013-01-31 12:11:38 -0800665
666 def OptionalArtifacts(self):
Gilad Arnold950569b2013-08-27 14:38:01 -0700667 """Returns BuildArtifacts that should be cached.
Chris Sosa6b0c6172013-08-05 17:01:33 -0700668
Gilad Arnold950569b2013-08-27 14:38:01 -0700669 Returns:
670 An iterable of BuildArtifacts.
671 Raises:
672 KeyError: if an optional artifact doesn't exist in
673 ARTIFACT_IMPLEMENTATION_MAP yet defined in
674 artifact_info.REQUESTED_TO_OPTIONAL_MAP.
Chris Sosa6b0c6172013-08-05 17:01:33 -0700675 """
Chris Sosa76e44b92013-01-31 12:11:38 -0800676 optional_names = set()
677 for artifact_name, optional_list in (
678 artifact_info.REQUESTED_TO_OPTIONAL_MAP.iteritems()):
679 # We are already downloading it.
Chris Sosa6b0c6172013-08-05 17:01:33 -0700680 if artifact_name in self.artifacts:
Chris Sosa76e44b92013-01-31 12:11:38 -0800681 optional_names = optional_names.union(optional_list)
682
Chris Sosa6b0c6172013-08-05 17:01:33 -0700683 return self._Artifacts(optional_names - set(self.artifacts), True)
Chris Sosa968a1062013-08-02 17:42:50 -0700684
685
686# A simple main to verify correctness of the artifact map when making simple
687# name changes.
688if __name__ == '__main__':
689 print 'ARTIFACT IMPLEMENTATION MAP (for debugging)'
690 print 'FORMAT: ARTIFACT -> IMPLEMENTATION (<class>_file)'
691 for key, value in sorted(ARTIFACT_IMPLEMENTATION_MAP.items()):
692 print '%s -> %s' % (key, value)