upload_to_google_storage_first_class.py 9.0 KB

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