forked from coreos/dev-util
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gsutil_util.py
55 lines (40 loc) · 1.41 KB
/
gsutil_util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module containing gsutil helper methods."""
import subprocess
import time
GSUTIL_ATTEMPTS = 5
class GSUtilError(Exception):
"""Exception raises when we run into an error running gsutil."""
pass
def GSUtilRun(cmd, err_msg):
"""Runs a GSUTIL command up to GSUTIL_ATTEMPTS number of times.
Attempts are tried with exponential backoff.
Returns:
stdout of the called gsutil command.
Raises:
subprocess.CalledProcessError if all attempt to run gsutil cmd fails.
"""
proc = None
sleep_timeout = 1
for _attempt in range(GSUTIL_ATTEMPTS):
# Note processes can hang when capturing from stderr. This command
# specifically doesn't pipe stderr.
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
stdout, _stderr = proc.communicate()
if proc.returncode == 0:
return stdout
time.sleep(sleep_timeout)
sleep_timeout *= 2
else:
raise GSUtilError('%s GSUTIL cmd %s failed with return code %d' % (
err_msg, cmd, proc.returncode))
def DownloadFromGS(src, dst):
"""Downloads object from gs_url |src| to |dst|.
Raises:
GSUtilError: if an error occurs during the download.
"""
cmd = 'gsutil cp %s %s' % (src, dst)
msg = 'Failed to download "%s".' % src
GSUtilRun(cmd, msg)