upload_to_google_storage_first_class.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2024 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 and output DEPS blob."""
  6. import hashlib
  7. import optparse
  8. import os
  9. import json
  10. import tempfile
  11. import re
  12. import sys
  13. import tarfile
  14. from download_from_google_storage import Gsutil
  15. from download_from_google_storage import GSUTIL_DEFAULT_PATH
  16. from typing import List
  17. MISSING_GENERATION_MSG = (
  18. 'missing generation number, please retrieve from Cloud Storage'
  19. 'before saving to DEPS')
  20. USAGE_STRING = """%prog [options] target [target2 ...].
  21. Target(s) is the files or directies intended to be uploaded to Google Storage.
  22. If a single target is a directory, it will be compressed and uploaded as a
  23. tar.gz file.
  24. If target is "-", then a list of directories will be taken from standard input.
  25. The list of directories will be compressed together and uploaded as one tar.gz
  26. file.
  27. Example usage
  28. ------------
  29. ./upload_to_google_storage_first_class.py --bucket gsutil-upload-playground
  30. --object-name my_object_name hello_world.txt
  31. ./upload_to_google_storage_first_class.py --bucket gsutil-upload-playground
  32. --object-name my_object_name my_dir1
  33. ./upload_to_google_storage_first_class.py --bucket gsutil-upload-playground
  34. --object-name my_object_name my_dir1 my_dir2
  35. Scan the current directory and upload all files larger than 1MB:
  36. find . -name .svn -prune -o -size +1000k -type f -print0 |
  37. ./upload_to_google_storage_first_class.py --bucket gsutil-upload-playground
  38. --object-name my_object_name -
  39. """
  40. def get_targets(args: List[str], parser: optparse.OptionParser,
  41. use_null_terminator: bool) -> List[str]:
  42. """Get target(s) to upload to GCS"""
  43. if not args:
  44. parser.error('Missing target.')
  45. if len(args) == 1 and args[0] == '-':
  46. # Take stdin as a newline or null separated list of files.
  47. if use_null_terminator:
  48. return sys.stdin.read().split('\0')
  49. return sys.stdin.read().splitlines()
  50. return args
  51. def create_archive(dirs: List[str]) -> str:
  52. """Given a list of directories, compress them all into one tar file"""
  53. # tarfile name cannot have a forward slash or else an error will be
  54. # thrown
  55. _, filename = tempfile.mkstemp(suffix='.tar.gz')
  56. with tarfile.open(filename, 'w:gz') as tar:
  57. for d in dirs:
  58. tar.add(d)
  59. return filename
  60. def validate_archive_dirs(dirs: List[str]) -> bool:
  61. """Validate the list of directories"""
  62. for d in dirs:
  63. # We don't allow .. in paths in our archives.
  64. if d == '..':
  65. return False
  66. # We only allow dirs.
  67. if not os.path.isdir(d):
  68. return False
  69. # Symlinks must point to a target inside the dirs
  70. if os.path.islink(d) and not any(
  71. os.realpath(d).startswith(os.realpath(dir_prefix))
  72. for dir_prefix in dirs):
  73. return False
  74. # We required that the subdirectories we are archiving are all just
  75. # below cwd.
  76. if d not in next(os.walk('.'))[1]:
  77. return False
  78. return True
  79. def get_sha256sum(filename: str) -> str:
  80. """Get the sha256sum of the file"""
  81. sha = hashlib.sha256()
  82. with open(filename, 'rb') as f:
  83. while True:
  84. # Read in 1mb chunks, so it doesn't all have to be loaded into
  85. # memory.
  86. chunk = f.read(1024 * 1024)
  87. if not chunk:
  88. break
  89. sha.update(chunk)
  90. return sha.hexdigest()
  91. def upload_to_google_storage(file: str, base_url: str, object_name: str,
  92. gsutil: Gsutil, force: bool, gzip: str,
  93. dry_run: bool) -> str:
  94. """Upload file to GCS"""
  95. file_url = '%s/%s' % (base_url, object_name)
  96. if gsutil.check_call('ls', file_url)[0] == 0 and not force:
  97. # File exists, check MD5 hash.
  98. _, out, _ = gsutil.check_call_with_retries('ls', '-L', file_url)
  99. etag_match = re.search(r'ETag:\s+\S+', out)
  100. if etag_match:
  101. raise Exception('File with url %s already exists' % file_url)
  102. if dry_run:
  103. return
  104. print("Uploading %s as %s" % (file, file_url))
  105. gsutil_args = ['-h', 'Cache-Control:public, max-age=31536000', 'cp', '-v']
  106. if gzip:
  107. gsutil_args.extend(['-z', gzip])
  108. gsutil_args.extend([file, file_url])
  109. code, _, err = gsutil.check_call_with_retries(*gsutil_args)
  110. if code != 0:
  111. raise Exception(
  112. code, 'Encountered error on uploading %s to %s\n%s' %
  113. (file, file_url, err))
  114. pattern = re.escape(file_url) + '#(?P<generation>\d+)'
  115. # The geneartion number is printed as part of the progress / status info
  116. # which gsutil outputs to stderr to keep separated from any final output
  117. # data.
  118. for line in err.strip().splitlines():
  119. m = re.search(pattern, line)
  120. if m:
  121. return m.group('generation')
  122. print('Warning: generation number could not be parsed from status'
  123. f'info: {err}')
  124. return MISSING_GENERATION_MSG
  125. def construct_deps_blob(bucket: str, object_name: str, file: str,
  126. generation: str) -> dict:
  127. """Output a blob hint that would need be added to a DEPS file"""
  128. return {
  129. 'path': {
  130. 'dep_type':
  131. 'gcs',
  132. 'bucket':
  133. bucket,
  134. 'objects': [{
  135. 'object_name': object_name,
  136. 'sha256sum': get_sha256sum(file),
  137. 'size_bytes': os.path.getsize(file),
  138. 'generation': int(generation),
  139. }],
  140. }
  141. }
  142. def main():
  143. parser = optparse.OptionParser(USAGE_STRING)
  144. parser.add_option('-b',
  145. '--bucket',
  146. help='Google Storage bucket to upload to.')
  147. parser.add_option('-p',
  148. '--prefix',
  149. help='Prefix that goes before object-name (i.e. in '
  150. 'between bucket and object name).')
  151. parser.add_option('-o',
  152. '--object-name',
  153. help='Optional object name of uploaded tar file. '
  154. 'If empty, the sha256sum will be the object name.')
  155. parser.add_option('-d',
  156. '--dry-run',
  157. action='store_true',
  158. help='Check if file already exists on GS without '
  159. 'uploading it and output DEP blob.')
  160. parser.add_option('-c',
  161. '--config',
  162. action='store_true',
  163. help='Alias for "gsutil config". Run this if you want '
  164. 'to initialize your saved Google Storage '
  165. 'credentials. This will create a read-only '
  166. 'credentials file in ~/.boto.depot_tools.')
  167. parser.add_option('-e', '--boto', help='Specify a custom boto file.')
  168. parser.add_option('-f',
  169. '--force',
  170. action='store_true',
  171. help='Force upload even if remote file exists.')
  172. parser.add_option('-g',
  173. '--gsutil_path',
  174. default=GSUTIL_DEFAULT_PATH,
  175. help='Path to the gsutil script.')
  176. parser.add_option('-0',
  177. '--use_null_terminator',
  178. action='store_true',
  179. help='Use \\0 instead of \\n when parsing '
  180. 'the file list from stdin. This is useful if the input '
  181. 'is coming from "find ... -print0".')
  182. parser.add_option('-z',
  183. '--gzip',
  184. metavar='ext',
  185. help='For files which end in <ext> gzip them before '
  186. 'upload. '
  187. 'ext is a comma-separated list')
  188. (options, args) = parser.parse_args()
  189. # Enumerate our inputs.
  190. input_filenames = get_targets(args, parser, options.use_null_terminator)
  191. # Allow uploading the entire directory
  192. if len(input_filenames) == 1 and input_filenames[0] in ('.', './'):
  193. input_filenames = next(os.walk('.'))[1]
  194. if len(input_filenames) > 1 or (len(input_filenames) == 1
  195. and os.path.isdir(input_filenames[0])):
  196. if not validate_archive_dirs(input_filenames):
  197. parser.error(
  198. 'Only directories just below cwd are valid entries. '
  199. 'Entries cannot contain .. and entries can not be symlinks. '
  200. 'Entries was %s' % input_filenames)
  201. return 1
  202. file = create_archive(input_filenames)
  203. else:
  204. file = input_filenames[0]
  205. object_name = options.object_name
  206. if not object_name:
  207. object_name = get_sha256sum(file)
  208. if options.prefix:
  209. object_name = f'{options.prefix}/{object_name}'
  210. # Make sure we can find a working instance of gsutil.
  211. if os.path.exists(GSUTIL_DEFAULT_PATH):
  212. gsutil = Gsutil(GSUTIL_DEFAULT_PATH, boto_path=options.boto)
  213. else:
  214. gsutil = None
  215. for path in os.environ["PATH"].split(os.pathsep):
  216. if os.path.exists(path) and 'gsutil' in os.listdir(path):
  217. gsutil = Gsutil(os.path.join(path, 'gsutil'),
  218. boto_path=options.boto)
  219. if not gsutil:
  220. parser.error('gsutil not found in %s, bad depot_tools checkout?' %
  221. GSUTIL_DEFAULT_PATH)
  222. # Passing in -g/--config will run our copy of GSUtil, then quit.
  223. if options.config:
  224. print('===Note from depot_tools===')
  225. print('If you do not have a project ID, enter "0" when asked for one.')
  226. print('===End note from depot_tools===')
  227. print()
  228. gsutil.check_call('version')
  229. return gsutil.call('config')
  230. assert '/' not in options.bucket, "Slashes not allowed in bucket name"
  231. base_url = f'gs://{options.bucket}'
  232. generation = upload_to_google_storage(file, base_url, object_name, gsutil,
  233. options.force, options.gzip,
  234. options.dry_run)
  235. print(
  236. json.dumps(construct_deps_blob(options.bucket, object_name, file,
  237. generation),
  238. indent=2))
  239. if __name__ == '__main__':
  240. try:
  241. sys.exit(main())
  242. except KeyboardInterrupt:
  243. sys.stderr.write('interrupted\n')
  244. sys.exit(1)