download_from_google_storage.py 28 KB

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