Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 1 | # 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 | |
joychen | f8f07e2 | 2013-07-12 17:45:51 -0700 | [diff] [blame] | 7 | import distutils.version |
Chris Sosa | 76e44b9 | 2013-01-31 12:11:38 -0800 | [diff] [blame] | 8 | import random |
| 9 | import re |
Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 10 | import subprocess |
Chris Sosa | 101fd86 | 2012-06-12 17:44:53 -0700 | [diff] [blame] | 11 | import time |
Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 12 | |
joychen | f8f07e2 | 2013-07-12 17:45:51 -0700 | [diff] [blame] | 13 | import devserver_constants |
Chris Sosa | 76e44b9 | 2013-01-31 12:11:38 -0800 | [diff] [blame] | 14 | import log_util |
| 15 | |
Gilad Arnold | abb352e | 2012-09-23 01:24:27 -0700 | [diff] [blame] | 16 | |
Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 17 | GSUTIL_ATTEMPTS = 5 |
Chris Sosa | 76e44b9 | 2013-01-31 12:11:38 -0800 | [diff] [blame] | 18 | UPLOADED_LIST = 'UPLOADED' |
| 19 | |
| 20 | |
| 21 | # Module-local log function. |
| 22 | def _Log(message, *args): |
| 23 | return log_util.LogWithTag('GSUTIL_UTIL', message, *args) |
Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 24 | |
| 25 | |
| 26 | class GSUtilError(Exception): |
Chris Sosa | 76e44b9 | 2013-01-31 12:11:38 -0800 | [diff] [blame] | 27 | """Exception raised when we run into an error running gsutil.""" |
| 28 | pass |
| 29 | |
| 30 | |
| 31 | class PatternNotSpecific(Exception): |
| 32 | """Raised when unexpectedly more than one item is returned for a pattern.""" |
Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 33 | pass |
| 34 | |
| 35 | |
| 36 | def GSUtilRun(cmd, err_msg): |
| 37 | """Runs a GSUTIL command up to GSUTIL_ATTEMPTS number of times. |
| 38 | |
Chris Sosa | 101fd86 | 2012-06-12 17:44:53 -0700 | [diff] [blame] | 39 | Attempts are tried with exponential backoff. |
| 40 | |
Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 41 | Returns: |
| 42 | stdout of the called gsutil command. |
| 43 | Raises: |
| 44 | subprocess.CalledProcessError if all attempt to run gsutil cmd fails. |
| 45 | """ |
| 46 | proc = None |
Chris Sosa | 101fd86 | 2012-06-12 17:44:53 -0700 | [diff] [blame] | 47 | sleep_timeout = 1 |
Chris Sosa | 407e8c5 | 2013-02-27 15:33:35 -0800 | [diff] [blame] | 48 | stderr = None |
Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 49 | for _attempt in range(GSUTIL_ATTEMPTS): |
Chris Sosa | 407e8c5 | 2013-02-27 15:33:35 -0800 | [diff] [blame] | 50 | proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, |
| 51 | stderr=subprocess.PIPE) |
| 52 | stdout, stderr = proc.communicate() |
Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 53 | if proc.returncode == 0: |
| 54 | return stdout |
Chris Sosa | 6de2930 | 2013-03-14 15:27:36 -0700 | [diff] [blame] | 55 | elif stderr and ('matched no objects' in stderr or |
| 56 | 'non-existent object' in stderr): |
Chris Sosa | 407e8c5 | 2013-02-27 15:33:35 -0800 | [diff] [blame] | 57 | # TODO(sosa): Note this is a heuristic that makes us not re-attempt |
| 58 | # unnecessarily. However, if it fails, the worst that can happen is just |
| 59 | # waiting longer than necessary. |
| 60 | break |
Chris Sosa | 6de2930 | 2013-03-14 15:27:36 -0700 | [diff] [blame] | 61 | elif proc.returncode == 127: |
| 62 | raise GSUtilError('gsutil tool not found in your path.') |
Chris Sosa | 101fd86 | 2012-06-12 17:44:53 -0700 | [diff] [blame] | 63 | |
| 64 | time.sleep(sleep_timeout) |
| 65 | sleep_timeout *= 2 |
| 66 | |
Chris Sosa | 407e8c5 | 2013-02-27 15:33:35 -0800 | [diff] [blame] | 67 | raise GSUtilError('%s GSUTIL cmd %s failed with return code %d:\n\n%s' % ( |
| 68 | err_msg, cmd, proc.returncode, stderr)) |
Chris Sosa | 47a7d4e | 2012-03-28 11:26:55 -0700 | [diff] [blame] | 69 | |
| 70 | |
| 71 | def DownloadFromGS(src, dst): |
| 72 | """Downloads object from gs_url |src| to |dst|. |
| 73 | |
| 74 | Raises: |
| 75 | GSUtilError: if an error occurs during the download. |
| 76 | """ |
| 77 | cmd = 'gsutil cp %s %s' % (src, dst) |
| 78 | msg = 'Failed to download "%s".' % src |
| 79 | GSUtilRun(cmd, msg) |
Chris Sosa | 76e44b9 | 2013-01-31 12:11:38 -0800 | [diff] [blame] | 80 | |
| 81 | |
| 82 | def _GetGSNamesFromList(filename_list, pattern): |
| 83 | """Given a list of filenames, returns the filenames that match pattern.""" |
| 84 | matches = [] |
| 85 | re_pattern = re.compile(pattern) |
| 86 | for filename in filename_list: |
| 87 | if re_pattern.match(filename): |
| 88 | matches.append(filename) |
| 89 | |
| 90 | return matches |
| 91 | |
| 92 | |
| 93 | def GetGSNamesWithWait(pattern, archive_url, err_str, single_item=True, |
| 94 | timeout=600, delay=10): |
| 95 | """Returns the google storage names specified by the given pattern. |
| 96 | |
| 97 | This method polls Google Storage until the target artifacts specified by the |
| 98 | pattern is available or until the timeout occurs. Because we may not know the |
| 99 | exact name of the target artifacts, the method accepts a filename pattern, |
| 100 | to identify whether an artifact whose name matches the pattern exists (e.g. |
| 101 | use pattern '_full_' to search for the full payload |
| 102 | 'chromeos_R17-1413.0.0-a1_x86-mario_full_dev.bin'). Returns the name only if |
| 103 | found before the timeout. |
| 104 | |
| 105 | Args: |
| 106 | pattern: Regular expression pattern to identify the target artifact. |
| 107 | archive_url: URL of the Google Storage bucket. |
| 108 | err_str: String to display in the error message on error. |
| 109 | single_item: Only a single item should be returned. |
| 110 | timeout/delay: optional and self-explanatory. |
| 111 | |
| 112 | Returns: |
| 113 | The list of artifacts matching the pattern in Google Storage bucket or None |
| 114 | if not found. |
| 115 | |
| 116 | Raises: |
| 117 | PatternNotSpecific: If caller sets single_item but multiple items match. |
| 118 | """ |
| 119 | deadline = time.time() + timeout |
Chris Sosa | 6de2930 | 2013-03-14 15:27:36 -0700 | [diff] [blame] | 120 | while True: |
Chris Sosa | 76e44b9 | 2013-01-31 12:11:38 -0800 | [diff] [blame] | 121 | uploaded_list = [] |
Chris Sosa | 76e44b9 | 2013-01-31 12:11:38 -0800 | [diff] [blame] | 122 | try: |
| 123 | cmd = 'gsutil cat %s/%s' % (archive_url, UPLOADED_LIST) |
| 124 | msg = 'Failed to get a list of uploaded files.' |
| 125 | uploaded_list = GSUtilRun(cmd, msg).splitlines() |
| 126 | except GSUtilError: |
| 127 | # For backward compatibility, falling back to use "gsutil ls" |
| 128 | # when the manifest file is not present. |
| 129 | cmd = 'gsutil ls %s/*' % archive_url |
| 130 | msg = 'Failed to list payloads.' |
| 131 | returned_list = GSUtilRun(cmd, msg).splitlines() |
| 132 | for item in returned_list: |
beeps | c3d0f87 | 2013-07-31 21:50:40 -0700 | [diff] [blame^] | 133 | try: |
| 134 | uploaded_list.append(item.rsplit('/', 1)[1]) |
| 135 | except IndexError: |
| 136 | pass |
Chris Sosa | 76e44b9 | 2013-01-31 12:11:38 -0800 | [diff] [blame] | 137 | |
| 138 | # Check if all target artifacts are available. |
| 139 | found_names = _GetGSNamesFromList(uploaded_list, pattern) |
| 140 | if found_names: |
| 141 | if single_item and len(found_names) > 1: |
| 142 | raise PatternNotSpecific( |
| 143 | 'Too many items %s returned by pattern %s in %s' % ( |
| 144 | str(found_names), pattern, archive_url)) |
| 145 | |
| 146 | return found_names |
| 147 | |
Chris Sosa | 6de2930 | 2013-03-14 15:27:36 -0700 | [diff] [blame] | 148 | # Don't delay past deadline. |
| 149 | to_delay = random.uniform(1.5 * delay, 2.5 * delay) |
| 150 | if to_delay < (deadline - time.time()): |
| 151 | _Log('Retrying in %f seconds...%s', to_delay, err_str) |
| 152 | time.sleep(to_delay) |
| 153 | else: |
| 154 | return None |
joychen | f8f07e2 | 2013-07-12 17:45:51 -0700 | [diff] [blame] | 155 | |
| 156 | |
| 157 | def GetLatestVersionFromGSDir(gsutil_dir): |
| 158 | """Returns most recent version number found in a GS directory. |
| 159 | |
| 160 | This lists out the contents of the given GS bucket or regex to GS buckets, |
| 161 | and tries to grab the newest version found in the directory names. |
| 162 | """ |
| 163 | cmd = 'gsutil ls %s' % gsutil_dir |
| 164 | msg = 'Failed to find most recent builds at %s' % gsutil_dir |
| 165 | dir_names = [p.split('/')[-2] for p in GSUtilRun(cmd, msg).splitlines()] |
| 166 | try: |
| 167 | versions = filter(lambda x: re.match(devserver_constants.VERSION_RE, x), |
| 168 | dir_names) |
| 169 | latest_version = max(versions, key=distutils.version.LooseVersion) |
| 170 | except ValueError: |
| 171 | raise GSUtilError(msg) |
| 172 | |
| 173 | return latest_version |