download_from_google_storage.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Download files from Google Storage based on SHA1 sums."""
  6. import hashlib
  7. import optparse
  8. import os
  9. import queue
  10. import re
  11. import shutil
  12. import stat
  13. import sys
  14. import tarfile
  15. import threading
  16. import time
  17. import subprocess2
  18. # Env vars that tempdir can be gotten from; minimally, this
  19. # needs to match python's tempfile module and match normal
  20. # unix standards.
  21. _TEMPDIR_ENV_VARS = ('TMPDIR', 'TEMP', 'TMP')
  22. GSUTIL_DEFAULT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  23. 'gsutil.py')
  24. # Maps sys.platform to what we actually want to call them.
  25. PLATFORM_MAPPING = {
  26. 'cygwin': 'win',
  27. 'darwin': 'mac',
  28. 'linux': 'linux', # Python 3.3+.
  29. 'linux2': 'linux', # Python < 3.3 uses "linux2" / "linux3".
  30. 'win32': 'win',
  31. 'aix': 'aix', # Python 3.8+
  32. 'zos': 'zos',
  33. }
  34. # (b/328065301): Remove when all GCS hooks are migrated to first class deps
  35. MIGRATION_TOGGLE_FILE_SUFFIX = '_is_first_class_gcs'
  36. def construct_migration_file_name(gcs_object_name):
  37. # Remove any forward slashes
  38. gcs_file_name = gcs_object_name.replace('/', '_')
  39. # Remove any dots
  40. gcs_file_name = gcs_file_name.replace('.', '_')
  41. return f'.{gcs_file_name}{MIGRATION_TOGGLE_FILE_SUFFIX}'
  42. def set_executable_bit(output_filename, file_url, gsutil):
  43. # Set executable bit.
  44. code, err = 0, ''
  45. if sys.platform == 'cygwin':
  46. # Under cygwin, mark all files as executable. The executable flag in
  47. # Google Storage will not be set when uploading from Windows, so if
  48. # this script is running under cygwin and we're downloading an
  49. # executable, it will be unrunnable from inside cygwin without this.
  50. st = os.stat(output_filename)
  51. os.chmod(output_filename, st.st_mode | stat.S_IEXEC)
  52. elif sys.platform != 'win32':
  53. # On non-Windows platforms, key off of the custom header
  54. # "x-goog-meta-executable".
  55. code, out, err = gsutil.check_call('stat', file_url)
  56. if re.search(r'executable:\s*1', out):
  57. st = os.stat(output_filename)
  58. os.chmod(output_filename, st.st_mode | stat.S_IEXEC)
  59. return code, err
  60. class InvalidFileError(IOError):
  61. pass
  62. class InvalidPlatformError(Exception):
  63. pass
  64. def GetNormalizedPlatform():
  65. """Returns the result of sys.platform accounting for cygwin.
  66. Under cygwin, this will always return "win32" like the native Python."""
  67. if sys.platform == 'cygwin':
  68. return 'win32'
  69. return sys.platform
  70. # Common utilities
  71. class Gsutil(object):
  72. """Call gsutil with some predefined settings. This is a convenience object,
  73. and is also immutable.
  74. HACK: This object is used directly by the external script
  75. `<depot_tools>/win_toolchain/get_toolchain_if_necessary.py`
  76. """
  77. MAX_TRIES = 5
  78. RETRY_BASE_DELAY = 5.0
  79. RETRY_DELAY_MULTIPLE = 1.3
  80. VPYTHON3 = ('vpython3.bat'
  81. if GetNormalizedPlatform() == 'win32' else 'vpython3')
  82. def __init__(self, path, boto_path=None):
  83. if not os.path.exists(path):
  84. raise FileNotFoundError('GSUtil not found in %s' % path)
  85. self.path = path
  86. self.boto_path = boto_path
  87. def get_sub_env(self):
  88. env = os.environ.copy()
  89. if self.boto_path == os.devnull:
  90. env['AWS_CREDENTIAL_FILE'] = ''
  91. env['BOTO_CONFIG'] = ''
  92. elif self.boto_path:
  93. env['AWS_CREDENTIAL_FILE'] = self.boto_path
  94. env['BOTO_CONFIG'] = self.boto_path
  95. if PLATFORM_MAPPING[sys.platform] != 'win':
  96. env.update((x, "/tmp") for x in _TEMPDIR_ENV_VARS)
  97. return env
  98. def call(self, *args):
  99. cmd = [self.VPYTHON3, self.path]
  100. cmd.extend(args)
  101. return subprocess2.call(cmd, env=self.get_sub_env())
  102. def check_call(self, *args):
  103. cmd = [self.VPYTHON3, self.path]
  104. cmd.extend(args)
  105. ((out, err), code) = subprocess2.communicate(cmd,
  106. stdout=subprocess2.PIPE,
  107. stderr=subprocess2.PIPE,
  108. env=self.get_sub_env())
  109. out = out.decode('utf-8', 'replace')
  110. err = err.decode('utf-8', 'replace')
  111. # Parse output.
  112. status_code_match = re.search('status=([0-9]+)', err)
  113. if status_code_match:
  114. return (int(status_code_match.group(1)), out, err)
  115. if ('ServiceException: 401 Anonymous' in err):
  116. return (401, out, err + '\nTry running "gsutil.py config" to log '
  117. ' into Google Cloud Storage.')
  118. if ('You are attempting to access protected data with '
  119. 'no configured credentials.' in err):
  120. return (403, out, err)
  121. if 'matched no objects' in err or 'No URLs matched' in err:
  122. return (404, out, err)
  123. return (code, out, err)
  124. def check_call_with_retries(self, *args):
  125. delay = self.RETRY_BASE_DELAY
  126. for i in range(self.MAX_TRIES):
  127. code, out, err = self.check_call(*args)
  128. if not code or i == self.MAX_TRIES - 1:
  129. break
  130. time.sleep(delay)
  131. delay *= self.RETRY_DELAY_MULTIPLE
  132. return code, out, err
  133. def check_platform(target):
  134. """Checks if any parent directory of target matches (win|mac|linux)."""
  135. assert os.path.isabs(target)
  136. root, target_name = os.path.split(target)
  137. if not target_name:
  138. return None
  139. if target_name in ('linux', 'mac', 'win'):
  140. return target_name
  141. return check_platform(root)
  142. def get_sha1(filename):
  143. sha1 = hashlib.sha1()
  144. with open(filename, 'rb') as f:
  145. while True:
  146. # Read in 1mb chunks, so it doesn't all have to be loaded into
  147. # memory.
  148. chunk = f.read(1024 * 1024)
  149. if not chunk:
  150. break
  151. sha1.update(chunk)
  152. return sha1.hexdigest()
  153. # Download-specific code starts here
  154. def enumerate_input(input_filename, directory, recursive, ignore_errors, output,
  155. sha1_file, auto_platform):
  156. if sha1_file:
  157. if not os.path.exists(input_filename):
  158. if not ignore_errors:
  159. raise FileNotFoundError(
  160. '{} not found when attempting enumerate files to download.'.
  161. format(input_filename))
  162. print('%s not found.' % input_filename, file=sys.stderr)
  163. with open(input_filename, 'rb') as f:
  164. sha1_match = re.match(b'^([A-Za-z0-9]{40})$', f.read(1024).rstrip())
  165. if sha1_match:
  166. yield (sha1_match.groups(1)[0].decode('utf-8'), output)
  167. return
  168. if not ignore_errors:
  169. raise InvalidFileError('No sha1 sum found in %s.' % input_filename)
  170. print('No sha1 sum found in %s.' % input_filename, file=sys.stderr)
  171. return
  172. if not directory:
  173. yield (input_filename, output)
  174. return
  175. for root, dirs, files in os.walk(input_filename):
  176. if not recursive:
  177. for item in dirs[:]:
  178. dirs.remove(item)
  179. else:
  180. for exclude in ['.svn', '.git']:
  181. if exclude in dirs:
  182. dirs.remove(exclude)
  183. for filename in files:
  184. full_path = os.path.join(root, filename)
  185. if full_path.endswith('.sha1'):
  186. if auto_platform:
  187. # Skip if the platform does not match.
  188. target_platform = check_platform(os.path.abspath(full_path))
  189. if not target_platform:
  190. err = ('--auto_platform passed in but no platform name '
  191. 'found in the path of %s' % full_path)
  192. if not ignore_errors:
  193. raise InvalidFileError(err)
  194. print(err, file=sys.stderr)
  195. continue
  196. current_platform = PLATFORM_MAPPING[sys.platform]
  197. if current_platform != target_platform:
  198. continue
  199. with open(full_path, 'rb') as f:
  200. sha1_match = re.match(b'^([A-Za-z0-9]{40})$',
  201. f.read(1024).rstrip())
  202. if sha1_match:
  203. yield (sha1_match.groups(1)[0].decode('utf-8'),
  204. full_path.replace('.sha1', ''))
  205. else:
  206. if not ignore_errors:
  207. raise InvalidFileError('No sha1 sum found in %s.' %
  208. filename)
  209. print('No sha1 sum found in %s.' % filename,
  210. file=sys.stderr)
  211. def _validate_tar_file(tar, prefix):
  212. def _validate(tarinfo):
  213. """Returns false if the tarinfo is something we explicitly forbid."""
  214. if tarinfo.issym() or tarinfo.islnk():
  215. # For links, check if the destination is valid.
  216. if os.path.isabs(tarinfo.linkname):
  217. return False
  218. link_target = os.path.normpath(
  219. os.path.join(os.path.dirname(tarinfo.name), tarinfo.linkname))
  220. if not link_target.startswith(prefix):
  221. return False
  222. if ('../' in tarinfo.name or '..\\' in tarinfo.name
  223. or not tarinfo.name.startswith(prefix)):
  224. return False
  225. return True
  226. return all(map(_validate, tar.getmembers()))
  227. def _downloader_worker_thread(thread_num,
  228. q,
  229. force,
  230. base_url,
  231. gsutil,
  232. out_q,
  233. ret_codes,
  234. verbose,
  235. extract,
  236. delete=True):
  237. while True:
  238. input_sha1_sum, output_filename = q.get()
  239. if input_sha1_sum is None:
  240. return
  241. working_dir = os.path.dirname(output_filename)
  242. if not working_dir:
  243. raise Exception(
  244. 'Unable to construct a working_dir from the output_filename.')
  245. migration_file_name = os.path.join(
  246. working_dir, construct_migration_file_name(input_sha1_sum))
  247. extract_dir = None
  248. if extract:
  249. if not output_filename.endswith('.tar.gz'):
  250. out_q.put('%d> Error: %s is not a tar.gz archive.' %
  251. (thread_num, output_filename))
  252. ret_codes.put(
  253. (1, '%s is not a tar.gz archive.' % (output_filename)))
  254. continue
  255. extract_dir = output_filename[:-len('.tar.gz')]
  256. if os.path.exists(output_filename) and not force:
  257. skip = get_sha1(output_filename) == input_sha1_sum
  258. if extract:
  259. # Additional condition for extract:
  260. # 1) extract_dir must exist
  261. # 2) .tmp flag file mustn't exist
  262. if not os.path.exists(extract_dir):
  263. out_q.put(
  264. '%d> Extract dir %s does not exist, re-downloading...' %
  265. (thread_num, extract_dir))
  266. skip = False
  267. # .tmp file is created just before extraction and removed just
  268. # after extraction. If such file exists, it means the process
  269. # was terminated mid-extraction and therefore needs to be
  270. # extracted again.
  271. elif os.path.exists(extract_dir + '.tmp'):
  272. out_q.put('%d> Detected tmp flag file for %s, '
  273. 're-downloading...' %
  274. (thread_num, output_filename))
  275. skip = False
  276. # (b/328065301): Remove when all GCS hooks are migrated to first
  277. # class deps
  278. # If the directory was created by a first class GCS
  279. # dep, remove the migration file and re-download using the
  280. # latest hook.
  281. is_first_class_gcs = os.path.exists(migration_file_name)
  282. if is_first_class_gcs:
  283. skip = False
  284. if skip:
  285. continue
  286. file_url = '%s/%s' % (base_url, input_sha1_sum)
  287. try:
  288. if delete:
  289. os.remove(
  290. output_filename) # Delete the file if it exists already.
  291. except OSError:
  292. if os.path.exists(output_filename):
  293. out_q.put('%d> Warning: deleting %s failed.' %
  294. (thread_num, output_filename))
  295. if verbose:
  296. out_q.put('%d> Downloading %s@%s...' %
  297. (thread_num, output_filename, input_sha1_sum))
  298. code, _, err = gsutil.check_call('cp', file_url, output_filename)
  299. if code != 0:
  300. if code == 404:
  301. out_q.put('%d> File %s for %s does not exist, skipping.' %
  302. (thread_num, file_url, output_filename))
  303. ret_codes.put((1, 'File %s for %s does not exist.' %
  304. (file_url, output_filename)))
  305. elif code == 401:
  306. out_q.put(
  307. '%d> Failed to fetch file %s for %s due to unauthorized '
  308. 'access, skipping. Try running `gsutil.py config`.' %
  309. (thread_num, file_url, output_filename))
  310. ret_codes.put((
  311. 1,
  312. 'Failed to fetch file %s for %s due to unauthorized access.'
  313. % (file_url, output_filename)))
  314. else:
  315. # Other error, probably auth related (bad ~/.boto, etc).
  316. out_q.put(
  317. '%d> Failed to fetch file %s for %s, skipping. [Err: %s]' %
  318. (thread_num, file_url, output_filename, err))
  319. ret_codes.put(
  320. (code, 'Failed to fetch file %s for %s. [Err: %s]' %
  321. (file_url, output_filename, err)))
  322. continue
  323. remote_sha1 = get_sha1(output_filename)
  324. if remote_sha1 != input_sha1_sum:
  325. msg = (
  326. '%d> ERROR remote sha1 (%s) does not match expected sha1 (%s).'
  327. % (thread_num, remote_sha1, input_sha1_sum))
  328. out_q.put(msg)
  329. ret_codes.put((20, msg))
  330. continue
  331. if extract:
  332. if not tarfile.is_tarfile(output_filename):
  333. out_q.put('%d> Error: %s is not a tar.gz archive.' %
  334. (thread_num, output_filename))
  335. ret_codes.put(
  336. (1, '%s is not a tar.gz archive.' % (output_filename)))
  337. continue
  338. with tarfile.open(output_filename, 'r:gz') as tar:
  339. dirname = os.path.dirname(os.path.abspath(output_filename))
  340. # If there are long paths inside the tarball we can get
  341. # extraction errors on windows due to the 260 path length limit
  342. # (this includes pwd). Use the extended path syntax.
  343. if sys.platform == 'win32':
  344. dirname = '\\\\?\\%s' % dirname
  345. if not _validate_tar_file(tar, os.path.basename(extract_dir)):
  346. out_q.put('%d> Error: %s contains files outside %s.' %
  347. (thread_num, output_filename, extract_dir))
  348. ret_codes.put(
  349. (1, '%s contains invalid entries.' % (output_filename)))
  350. continue
  351. if os.path.exists(extract_dir):
  352. try:
  353. shutil.rmtree(extract_dir)
  354. out_q.put('%d> Removed %s...' %
  355. (thread_num, extract_dir))
  356. except OSError:
  357. out_q.put('%d> Warning: Can\'t delete: %s' %
  358. (thread_num, extract_dir))
  359. ret_codes.put((1, 'Can\'t delete %s.' % (extract_dir)))
  360. continue
  361. out_q.put('%d> Extracting %d entries from %s to %s' %
  362. (thread_num, len(
  363. tar.getmembers()), output_filename, extract_dir))
  364. with open(extract_dir + '.tmp', 'a'):
  365. tar.extractall(path=dirname)
  366. os.remove(extract_dir + '.tmp')
  367. if os.path.exists(migration_file_name):
  368. os.remove(migration_file_name)
  369. code, err = set_executable_bit(output_filename, file_url, gsutil)
  370. if code != 0:
  371. out_q.put('%d> %s' % (thread_num, err))
  372. ret_codes.put((code, err))
  373. class PrinterThread(threading.Thread):
  374. def __init__(self, output_queue):
  375. super(PrinterThread, self).__init__()
  376. self.output_queue = output_queue
  377. self.did_print_anything = False
  378. def run(self):
  379. while True:
  380. line = self.output_queue.get()
  381. # It's plausible we want to print empty lines: Explicit `is None`.
  382. if line is None:
  383. break
  384. self.did_print_anything = True
  385. print(line)
  386. def _data_exists(input_sha1_sum, output_filename, extract):
  387. """Returns True if the data exists locally and matches the sha1.
  388. This conservatively returns False for error cases.
  389. Args:
  390. input_sha1_sum: Expected sha1 stored on disk.
  391. output_filename: The file to potentially download later. Its sha1 will
  392. be compared to input_sha1_sum.
  393. extract: Whether or not a downloaded file should be extracted. If the
  394. file is not extracted, this just compares the sha1 of the file. If
  395. the file is to be extracted, this only compares the sha1 of the
  396. target archive if the target directory already exists. The content
  397. of the target directory is not checked.
  398. """
  399. extract_dir = None
  400. if extract:
  401. if not output_filename.endswith('.tar.gz'):
  402. # This will cause an error later. Conservativly return False to not
  403. # bail out too early.
  404. return False
  405. extract_dir = output_filename[:-len('.tar.gz')]
  406. if os.path.exists(output_filename):
  407. if not extract or os.path.exists(extract_dir):
  408. if get_sha1(output_filename) == input_sha1_sum:
  409. return True
  410. return False
  411. def download_from_google_storage(input_filename, base_url, gsutil, num_threads,
  412. directory, recursive, force, output,
  413. ignore_errors, sha1_file, verbose,
  414. auto_platform, extract):
  415. # Tuples of sha1s and paths.
  416. input_data = list(
  417. enumerate_input(input_filename, directory, recursive, ignore_errors,
  418. output, sha1_file, auto_platform))
  419. # Sequentially check for the most common case and see if we can bail out
  420. # early before making any slow calls to gsutil.
  421. if directory:
  422. working_dir = input_filename
  423. elif os.path.dirname(output):
  424. working_dir = os.path.dirname(output)
  425. if not working_dir:
  426. raise Exception(
  427. 'Unable to construct a working_dir from the inputted directory'
  428. ' or sha1 file name.')
  429. # (b/328065301): Remove when all GCS hooks are migrated to first class deps
  430. # If the directory was created by a first class GCS
  431. # dep, remove the migration file and re-download using the
  432. # latest hook.
  433. is_first_class_gcs = False
  434. # Check all paths to see if they have an equivalent is_first_class_gcs file
  435. # If directory is False, there will be only one item in input_data
  436. for sha1, _ in input_data:
  437. migration_file_name = os.path.join(working_dir,
  438. construct_migration_file_name(sha1))
  439. if os.path.exists(migration_file_name):
  440. is_first_class_gcs = True
  441. if not force and not is_first_class_gcs and all(
  442. _data_exists(sha1, path, extract) for sha1, path in input_data):
  443. return 0
  444. # Call this once to ensure gsutil's update routine is called only once. Only
  445. # needs to be done if we'll process input data in parallel, which can lead
  446. # to a race in gsutil's self-update on the first call. Note, this causes a
  447. # network call, therefore any fast bailout should be done before this point.
  448. if len(input_data) > 1:
  449. gsutil.check_call('version')
  450. # Start up all the worker threads.
  451. all_threads = []
  452. download_start = time.time()
  453. stdout_queue = queue.Queue()
  454. work_queue = queue.Queue()
  455. ret_codes = queue.Queue()
  456. ret_codes.put((0, None))
  457. for thread_num in range(num_threads):
  458. t = threading.Thread(target=_downloader_worker_thread,
  459. args=[
  460. thread_num, work_queue, force, base_url,
  461. gsutil, stdout_queue, ret_codes, verbose,
  462. extract
  463. ])
  464. t.daemon = True
  465. t.start()
  466. all_threads.append(t)
  467. printer_thread = PrinterThread(stdout_queue)
  468. printer_thread.daemon = True
  469. printer_thread.start()
  470. # Populate our work queue.
  471. for sha1, path in input_data:
  472. work_queue.put((sha1, path))
  473. for _ in all_threads:
  474. work_queue.put((None, None)) # Used to tell worker threads to stop.
  475. # Wait for all downloads to finish.
  476. for t in all_threads:
  477. t.join()
  478. stdout_queue.put(None)
  479. printer_thread.join()
  480. # See if we ran into any errors.
  481. max_ret_code = 0
  482. for ret_code, message in ret_codes.queue:
  483. max_ret_code = max(ret_code, max_ret_code)
  484. if message:
  485. print(message, file=sys.stderr)
  486. # Only print summary if any work was done.
  487. if printer_thread.did_print_anything:
  488. print('Downloading %d files took %1f second(s)' %
  489. (len(input_data), time.time() - download_start))
  490. return max_ret_code
  491. def main(args):
  492. usage = ('usage: %prog [options] target\n'
  493. 'Target must be:\n'
  494. ' (default) a sha1 sum ([A-Za-z0-9]{40}).\n'
  495. ' (-s or --sha1_file) a .sha1 file, containing a sha1 sum on '
  496. 'the first line.\n'
  497. ' (-d or --directory) A directory to scan for .sha1 files.')
  498. parser = optparse.OptionParser(usage)
  499. parser.add_option('-o',
  500. '--output',
  501. help='Specify the output file name. Defaults to: '
  502. '(a) Given a SHA1 hash, the name is the SHA1 hash. '
  503. '(b) Given a .sha1 file or directory, the name will '
  504. 'match (.*).sha1.')
  505. parser.add_option('-b',
  506. '--bucket',
  507. help='Google Storage bucket to fetch from.')
  508. parser.add_option('-e', '--boto', help='Specify a custom boto file.')
  509. parser.add_option('-c',
  510. '--no_resume',
  511. action='store_true',
  512. help='DEPRECATED: Resume download if file is '
  513. 'partially downloaded.')
  514. parser.add_option('-f',
  515. '--force',
  516. action='store_true',
  517. help='Force download even if local file exists.')
  518. parser.add_option(
  519. '-i',
  520. '--ignore_errors',
  521. action='store_true',
  522. help='Don\'t throw error if we find an invalid .sha1 file.')
  523. parser.add_option('-r',
  524. '--recursive',
  525. action='store_true',
  526. help='Scan folders recursively for .sha1 files. '
  527. 'Must be used with -d/--directory')
  528. parser.add_option('-t',
  529. '--num_threads',
  530. default=0,
  531. type='int',
  532. help='Number of downloader threads to run.')
  533. parser.add_option('-d',
  534. '--directory',
  535. action='store_true',
  536. help='The target is a directory. '
  537. 'Cannot be used with -s/--sha1_file.')
  538. parser.add_option('-s',
  539. '--sha1_file',
  540. action='store_true',
  541. help='The target is a file containing a sha1 sum. '
  542. 'Cannot be used with -d/--directory.')
  543. parser.add_option('-g',
  544. '--config',
  545. action='store_true',
  546. help='Alias for "gsutil config". Run this if you want '
  547. 'to initialize your saved Google Storage '
  548. 'credentials. This will create a read-only '
  549. 'credentials file in ~/.boto.depot_tools.')
  550. parser.add_option('-n',
  551. '--no_auth',
  552. action='store_true',
  553. help='DEPRECATED: This flag has no effect.')
  554. parser.add_option('-p',
  555. '--platform',
  556. help='A regular expression that is compared against '
  557. 'Python\'s sys.platform. If this option is specified, '
  558. 'the download will happen only if there is a match.')
  559. parser.add_option('-a',
  560. '--auto_platform',
  561. action='store_true',
  562. help='Detects if any parent folder of the target matches '
  563. '(linux|mac|win). If so, the script will only '
  564. 'process files that are in the paths that '
  565. 'that matches the current platform.')
  566. parser.add_option('-u',
  567. '--extract',
  568. action='store_true',
  569. help='Extract a downloaded tar.gz file. '
  570. 'Leaves the tar.gz file around for sha1 verification'
  571. 'If a directory with the same name as the tar.gz '
  572. 'file already exists, is deleted (to get a '
  573. 'clean state in case of update.)')
  574. parser.add_option('-v',
  575. '--verbose',
  576. action='store_true',
  577. default=True,
  578. help='DEPRECATED: Defaults to True. Use --no-verbose '
  579. 'to suppress.')
  580. parser.add_option('-q',
  581. '--quiet',
  582. action='store_false',
  583. dest='verbose',
  584. help='Suppresses diagnostic and progress information.')
  585. (options, args) = parser.parse_args()
  586. # Make sure we should run at all based on platform matching.
  587. if options.platform:
  588. if options.auto_platform:
  589. parser.error('--platform can not be specified with --auto_platform')
  590. if not re.match(options.platform, GetNormalizedPlatform()):
  591. if options.verbose:
  592. print('The current platform doesn\'t match "%s", skipping.' %
  593. options.platform)
  594. return 0
  595. if options.no_auth:
  596. print('--no_auth is deprecated, this flag has no effect.')
  597. if 'NO_AUTH_BOTO_CONFIG' in os.environ:
  598. print(
  599. 'The NO_AUTH_BOTO_CONFIG environment variable is deprecated and ',
  600. 'has no effect. gsutil.py will always use any [GSUtil] or [Boto] ',
  601. 'settings in the .boto configuration file, regardless of ',
  602. 'whether you\'re logged in with luci-auth.')
  603. # Make sure gsutil exists where we expect it to.
  604. if os.path.exists(GSUTIL_DEFAULT_PATH):
  605. gsutil = Gsutil(GSUTIL_DEFAULT_PATH, boto_path=options.boto)
  606. else:
  607. parser.error('gsutil not found in %s, bad depot_tools checkout?' %
  608. GSUTIL_DEFAULT_PATH)
  609. # Passing in -g/--config will run our copy of GSUtil, then quit.
  610. if options.config:
  611. print('===Note from depot_tools===')
  612. print('If you do not have a project ID, enter "0" when asked for one.')
  613. print('===End note from depot_tools===')
  614. print()
  615. gsutil.check_call('version')
  616. return gsutil.call('config')
  617. if not args:
  618. parser.error('Missing target.')
  619. if len(args) > 1:
  620. parser.error('Too many targets.')
  621. if not options.bucket:
  622. parser.error('Missing bucket. Specify bucket with --bucket.')
  623. if options.sha1_file and options.directory:
  624. parser.error('Both --directory and --sha1_file are specified, '
  625. 'can only specify one.')
  626. if options.recursive and not options.directory:
  627. parser.error('--recursive specified but --directory not specified.')
  628. if options.output and options.directory:
  629. parser.error('--directory is specified, so --output has no effect.')
  630. if (not (options.sha1_file or options.directory) and options.auto_platform):
  631. parser.error('--auto_platform must be specified with either '
  632. '--sha1_file or --directory')
  633. input_filename = args[0]
  634. num_threads = options.num_threads
  635. if not num_threads:
  636. num_threads = max(
  637. int(os.environ.get('DOWNLOAD_FROM_GOOGLE_STORAGE_THREADS', 1)), 1)
  638. # Set output filename if not specified.
  639. if not options.output and not options.directory:
  640. if not options.sha1_file:
  641. # Target is a sha1 sum, so output filename would also be the sha1
  642. # sum.
  643. options.output = input_filename
  644. elif options.sha1_file:
  645. # Target is a .sha1 file.
  646. if not input_filename.endswith('.sha1'):
  647. parser.error(
  648. '--sha1_file is specified, but the input filename '
  649. 'does not end with .sha1, and no --output is specified. '
  650. 'Either make sure the input filename has a .sha1 '
  651. 'extension, or specify --output.')
  652. options.output = input_filename[:-5]
  653. else:
  654. parser.error('Unreachable state.')
  655. base_url = 'gs://%s' % options.bucket
  656. try:
  657. return download_from_google_storage(
  658. input_filename, base_url, gsutil, num_threads, options.directory,
  659. options.recursive, options.force, options.output,
  660. options.ignore_errors, options.sha1_file, options.verbose,
  661. options.auto_platform, options.extract)
  662. except FileNotFoundError as e:
  663. print("Fatal error: {}".format(e))
  664. return 1
  665. if __name__ == '__main__':
  666. sys.exit(main(sys.argv))