blob: 5567a6075a22293baec0e5af1373ebc0ee0d4cbb [file] [log] [blame]
Chris Sosa47a7d4e2012-03-28 11:26:55 -07001# Copyright (c) 2012 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
5"""Module containing gsutil helper methods."""
6
7import subprocess
8
9GSUTIL_ATTEMPTS = 5
10
11
12class GSUtilError(Exception):
13 """Exception raises when we run into an error running gsutil."""
14 pass
15
16
17def GSUtilRun(cmd, err_msg):
18 """Runs a GSUTIL command up to GSUTIL_ATTEMPTS number of times.
19
20 Returns:
21 stdout of the called gsutil command.
22 Raises:
23 subprocess.CalledProcessError if all attempt to run gsutil cmd fails.
24 """
25 proc = None
26 for _attempt in range(GSUTIL_ATTEMPTS):
27 # Note processes can hang when capturing from stderr. This command
28 # specifically doesn't pipe stderr.
29 proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
30 stdout, _stderr = proc.communicate()
31 if proc.returncode == 0:
32 return stdout
33 else:
34 raise GSUtilError('%s GSUTIL cmd %s failed with return code %d' % (
35 err_msg, cmd, proc.returncode))
36
37
38def DownloadFromGS(src, dst):
39 """Downloads object from gs_url |src| to |dst|.
40
41 Raises:
42 GSUtilError: if an error occurs during the download.
43 """
44 cmd = 'gsutil cp %s %s' % (src, dst)
45 msg = 'Failed to download "%s".' % src
46 GSUtilRun(cmd, msg)