download_from_google_storage.py 31 KB

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