upload_to_google_storage.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. """Uploads files to Google Storage content addressed."""
  6. from __future__ import print_function
  7. import hashlib
  8. import optparse
  9. import os
  10. try:
  11. import Queue as queue
  12. except ImportError: # For Py3 compatibility
  13. import queue
  14. import re
  15. import stat
  16. import sys
  17. import tarfile
  18. import threading
  19. import time
  20. from download_from_google_storage import get_sha1
  21. from download_from_google_storage import Gsutil
  22. from download_from_google_storage import PrinterThread
  23. from download_from_google_storage import GSUTIL_DEFAULT_PATH
  24. USAGE_STRING = """%prog [options] target [target2 ...].
  25. Target is the file intended to be uploaded to Google Storage.
  26. If target is "-", then a list of files will be taken from standard input
  27. This script will generate a file (original filename).sha1 containing the
  28. sha1 sum of the uploaded file.
  29. It is recommended that the .sha1 file is checked into the repository,
  30. the original file removed from the repository, and a hook added to the
  31. DEPS file to call download_from_google_storage.py.
  32. Example usages
  33. --------------
  34. Scan the current directory and upload all files larger than 1MB:
  35. find . -name .svn -prune -o -size +1000k -type f -print0 | %prog -0 -b bkt -
  36. (Replace "bkt" with the name of a writable bucket.)
  37. """
  38. def get_md5(filename):
  39. md5_calculator = hashlib.md5()
  40. with open(filename, 'rb') as f:
  41. while True:
  42. chunk = f.read(1024*1024)
  43. if not chunk:
  44. break
  45. md5_calculator.update(chunk)
  46. return md5_calculator.hexdigest()
  47. def get_md5_cached(filename):
  48. """Don't calculate the MD5 if we can find a .md5 file."""
  49. # See if we can find an existing MD5 sum stored in a file.
  50. if os.path.exists('%s.md5' % filename):
  51. with open('%s.md5' % filename, 'rb') as f:
  52. md5_match = re.search('([a-z0-9]{32})', f.read().decode())
  53. if md5_match:
  54. return md5_match.group(1)
  55. else:
  56. md5_hash = get_md5(filename)
  57. with open('%s.md5' % filename, 'wb') as f:
  58. f.write(md5_hash.encode())
  59. return md5_hash
  60. def _upload_worker(
  61. thread_num, upload_queue, base_url, gsutil, md5_lock, force,
  62. use_md5, stdout_queue, ret_codes, gzip):
  63. while True:
  64. filename, sha1_sum = upload_queue.get()
  65. if not filename:
  66. break
  67. file_url = '%s/%s' % (base_url, sha1_sum)
  68. if gsutil.check_call('ls', file_url)[0] == 0 and not force:
  69. # File exists, check MD5 hash.
  70. _, out, _ = gsutil.check_call_with_retries('ls', '-L', file_url)
  71. etag_match = re.search(r'ETag:\s+\S+', out)
  72. if etag_match:
  73. stdout_queue.put(
  74. '%d> File with url %s already exists' % (thread_num, file_url))
  75. remote_md5 = etag_match.group(0).split()[1]
  76. # Calculate the MD5 checksum to match it to Google Storage's ETag.
  77. with md5_lock:
  78. if use_md5:
  79. local_md5 = get_md5_cached(filename)
  80. else:
  81. local_md5 = get_md5(filename)
  82. if local_md5 == remote_md5:
  83. stdout_queue.put(
  84. '%d> File %s already exists and MD5 matches, upload skipped' %
  85. (thread_num, filename))
  86. continue
  87. stdout_queue.put('%d> Uploading %s...' % (
  88. thread_num, filename))
  89. gsutil_args = ['-h', 'Cache-Control:public, max-age=31536000', 'cp']
  90. if gzip:
  91. gsutil_args.extend(['-z', gzip])
  92. gsutil_args.extend([filename, file_url])
  93. code, _, err = gsutil.check_call_with_retries(*gsutil_args)
  94. if code != 0:
  95. ret_codes.put(
  96. (code,
  97. 'Encountered error on uploading %s to %s\n%s' %
  98. (filename, file_url, err)))
  99. continue
  100. # Mark executable files with the header "x-goog-meta-executable: 1" which
  101. # the download script will check for to preserve the executable bit.
  102. if not sys.platform.startswith('win'):
  103. if os.stat(filename).st_mode & stat.S_IEXEC:
  104. code, _, err = gsutil.check_call_with_retries(
  105. 'setmeta', '-h', 'x-goog-meta-executable:1', file_url)
  106. if code != 0:
  107. ret_codes.put(
  108. (code,
  109. 'Encountered error on setting metadata on %s\n%s' %
  110. (file_url, err)))
  111. def get_targets(args, parser, use_null_terminator):
  112. if not args:
  113. parser.error('Missing target.')
  114. if len(args) == 1 and args[0] == '-':
  115. # Take stdin as a newline or null separated list of files.
  116. if use_null_terminator:
  117. return sys.stdin.read().split('\0')
  118. return sys.stdin.read().splitlines()
  119. return args
  120. def upload_to_google_storage(
  121. input_filenames, base_url, gsutil, force,
  122. use_md5, num_threads, skip_hashing, gzip):
  123. # We only want one MD5 calculation happening at a time to avoid HD thrashing.
  124. md5_lock = threading.Lock()
  125. # Start up all the worker threads plus the printer thread.
  126. all_threads = []
  127. ret_codes = queue.Queue()
  128. ret_codes.put((0, None))
  129. upload_queue = queue.Queue()
  130. upload_timer = time.time()
  131. stdout_queue = queue.Queue()
  132. printer_thread = PrinterThread(stdout_queue)
  133. printer_thread.daemon = True
  134. printer_thread.start()
  135. for thread_num in range(num_threads):
  136. t = threading.Thread(
  137. target=_upload_worker,
  138. args=[thread_num, upload_queue, base_url, gsutil, md5_lock,
  139. force, use_md5, stdout_queue, ret_codes, gzip])
  140. t.daemon = True
  141. t.start()
  142. all_threads.append(t)
  143. # We want to hash everything in a single thread since its faster.
  144. # The bottleneck is in disk IO, not CPU.
  145. hashing_start = time.time()
  146. has_missing_files = False
  147. for filename in input_filenames:
  148. if not os.path.exists(filename):
  149. stdout_queue.put('Main> Error: %s not found, skipping.' % filename)
  150. has_missing_files = True
  151. continue
  152. if os.path.exists('%s.sha1' % filename) and skip_hashing:
  153. stdout_queue.put(
  154. 'Main> Found hash for %s, sha1 calculation skipped.' % filename)
  155. with open(filename + '.sha1', 'rb') as f:
  156. sha1_file = f.read(1024)
  157. if not re.match('^([a-z0-9]{40})$', sha1_file.decode()):
  158. print('Invalid sha1 hash file %s.sha1' % filename, file=sys.stderr)
  159. return 1
  160. upload_queue.put((filename, sha1_file.decode()))
  161. continue
  162. stdout_queue.put('Main> Calculating hash for %s...' % filename)
  163. sha1_sum = get_sha1(filename)
  164. with open(filename + '.sha1', 'wb') as f:
  165. f.write(sha1_sum.encode())
  166. stdout_queue.put('Main> Done calculating hash for %s.' % filename)
  167. upload_queue.put((filename, sha1_sum))
  168. hashing_duration = time.time() - hashing_start
  169. # Wait for everything to finish.
  170. for _ in all_threads:
  171. upload_queue.put((None, None)) # To mark the end of the work queue.
  172. for t in all_threads:
  173. t.join()
  174. stdout_queue.put(None)
  175. printer_thread.join()
  176. # Print timing information.
  177. print('Hashing %s files took %1f seconds' % (
  178. len(input_filenames), hashing_duration))
  179. print('Uploading took %1f seconds' % (time.time() - upload_timer))
  180. # See if we ran into any errors.
  181. max_ret_code = 0
  182. for ret_code, message in ret_codes.queue:
  183. max_ret_code = max(ret_code, max_ret_code)
  184. if message:
  185. print(message, file=sys.stderr)
  186. if has_missing_files:
  187. print('One or more input files missing', file=sys.stderr)
  188. max_ret_code = max(1, max_ret_code)
  189. if not max_ret_code:
  190. print('Success!')
  191. return max_ret_code
  192. def create_archives(dirs):
  193. archive_names = []
  194. for name in dirs:
  195. tarname = '%s.tar.gz' % name
  196. with tarfile.open(tarname, 'w:gz') as tar:
  197. tar.add(name)
  198. archive_names.append(tarname)
  199. return archive_names
  200. def validate_archive_dirs(dirs):
  201. for d in dirs:
  202. # We don't allow .. in paths in our archives.
  203. if d == '..':
  204. return False
  205. # We only allow dirs.
  206. if not os.path.isdir(d):
  207. return False
  208. # We don't allow sym links in our archives.
  209. if os.path.islink(d):
  210. return False
  211. # We required that the subdirectories we are archiving are all just below
  212. # cwd.
  213. if d not in next(os.walk('.'))[1]:
  214. return False
  215. return True
  216. def main():
  217. parser = optparse.OptionParser(USAGE_STRING)
  218. parser.add_option('-b', '--bucket',
  219. help='Google Storage bucket to upload to.')
  220. parser.add_option('-e', '--boto', help='Specify a custom boto file.')
  221. parser.add_option('-a', '--archive', action='store_true',
  222. help='Archive directory as a tar.gz file')
  223. parser.add_option('-f', '--force', action='store_true',
  224. help='Force upload even if remote file exists.')
  225. parser.add_option('-g', '--gsutil_path', default=GSUTIL_DEFAULT_PATH,
  226. help='Path to the gsutil script.')
  227. parser.add_option('-m', '--use_md5', action='store_true',
  228. help='Generate MD5 files when scanning, and don\'t check '
  229. 'the MD5 checksum if a .md5 file is found.')
  230. parser.add_option('-t', '--num_threads', default=1, type='int',
  231. help='Number of uploader threads to run.')
  232. parser.add_option('-s', '--skip_hashing', action='store_true',
  233. help='Skip hashing if .sha1 file exists.')
  234. parser.add_option('-0', '--use_null_terminator', action='store_true',
  235. help='Use \\0 instead of \\n when parsing '
  236. 'the file list from stdin. This is useful if the input '
  237. 'is coming from "find ... -print0".')
  238. parser.add_option('-z', '--gzip', metavar='ext',
  239. help='Gzip files which end in ext. '
  240. 'ext is a comma-separated list')
  241. (options, args) = parser.parse_args()
  242. # Enumerate our inputs.
  243. input_filenames = get_targets(args, parser, options.use_null_terminator)
  244. if options.archive:
  245. if not validate_archive_dirs(input_filenames):
  246. parser.error('Only directories just below cwd are valid entries when '
  247. 'using the --archive argument. Entries can not contain .. '
  248. ' and entries can not be symlinks. Entries was %s' %
  249. input_filenames)
  250. return 1
  251. input_filenames = create_archives(input_filenames)
  252. # Make sure we can find a working instance of gsutil.
  253. if os.path.exists(GSUTIL_DEFAULT_PATH):
  254. gsutil = Gsutil(GSUTIL_DEFAULT_PATH, boto_path=options.boto)
  255. else:
  256. gsutil = None
  257. for path in os.environ["PATH"].split(os.pathsep):
  258. if os.path.exists(path) and 'gsutil' in os.listdir(path):
  259. gsutil = Gsutil(os.path.join(path, 'gsutil'), boto_path=options.boto)
  260. if not gsutil:
  261. parser.error('gsutil not found in %s, bad depot_tools checkout?' %
  262. GSUTIL_DEFAULT_PATH)
  263. base_url = 'gs://%s' % options.bucket
  264. return upload_to_google_storage(
  265. input_filenames, base_url, gsutil, options.force, options.use_md5,
  266. options.num_threads, options.skip_hashing, options.gzip)
  267. if __name__ == '__main__':
  268. try:
  269. sys.exit(main())
  270. except KeyboardInterrupt:
  271. sys.stderr.write('interrupted\n')
  272. sys.exit(1)