download_optimization_profile.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. #!/usr/bin/env vpython3
  2. # Copyright 2018 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. """This script is used to update local profiles (AFDO, PGO or orderfiles)
  6. This uses profiles of Chrome, or orderfiles for compiling or linking. Though the
  7. profiles are available externally, the bucket they sit in is otherwise
  8. unreadable by non-Googlers. Gsutil usage with this bucket is therefore quite
  9. awkward: you can't do anything but `cp` certain files with an external account,
  10. and you can't even do that if you're not yet authenticated.
  11. No authentication is necessary if you pull these profiles directly over https.
  12. """
  13. from __future__ import print_function
  14. import argparse
  15. import contextlib
  16. import os
  17. import subprocess
  18. import sys
  19. from urllib.request import urlopen
  20. GS_HTTP_URL = 'https://storage.googleapis.com'
  21. def ReadUpToDateProfileName(newest_profile_name_path):
  22. with open(newest_profile_name_path) as f:
  23. return f.read().strip()
  24. def ReadLocalProfileName(local_profile_name_path):
  25. try:
  26. with open(local_profile_name_path) as f:
  27. return f.read().strip()
  28. except IOError:
  29. # Assume it either didn't exist, or we couldn't read it. In either case, we
  30. # should probably grab a new profile (and, in doing so, make this file sane
  31. # again)
  32. return None
  33. def WriteLocalProfileName(name, local_profile_name_path):
  34. with open(local_profile_name_path, 'w') as f:
  35. f.write(name)
  36. def CheckCallOrExit(cmd):
  37. proc = subprocess.Popen(cmd,
  38. stdout=subprocess.PIPE,
  39. stderr=subprocess.PIPE,
  40. encoding='utf-8')
  41. stdout, stderr = proc.communicate()
  42. exit_code = proc.wait()
  43. if not exit_code:
  44. return
  45. complaint_lines = [
  46. '## %s failed with exit code %d' % (cmd[0], exit_code),
  47. '## Full command: %s' % cmd,
  48. '## Stdout:\n' + stdout,
  49. '## Stderr:\n' + stderr,
  50. ]
  51. print('\n'.join(complaint_lines), file=sys.stderr)
  52. sys.exit(1)
  53. def RetrieveProfile(desired_profile_name, out_path, gs_url_base):
  54. # vpython is > python 2.7.9, so we can expect urllib to validate HTTPS certs
  55. # properly.
  56. ext = os.path.splitext(desired_profile_name)[1]
  57. if ext in ['.bz2', '.xz']:
  58. # For extension that requires explicit decompression, decompression will
  59. # change the eventual file names by dropping the extension, and that's why
  60. # an extra extension is appended here to make sure that the decompressed
  61. # file path matches the |out_path| passed in as parameter.
  62. out_path += ext
  63. gs_prefix = 'gs://'
  64. if not desired_profile_name.startswith(gs_prefix):
  65. gs_url = '/'.join([GS_HTTP_URL, gs_url_base, desired_profile_name])
  66. else:
  67. gs_url = '/'.join([GS_HTTP_URL, desired_profile_name[len(gs_prefix):]])
  68. with contextlib.closing(urlopen(gs_url)) as u:
  69. with open(out_path, 'wb') as f:
  70. while True:
  71. buf = u.read(4096)
  72. if not buf:
  73. break
  74. f.write(buf)
  75. if ext == '.bz2':
  76. # NOTE: we can't use Python's bzip module, since it doesn't support
  77. # multi-stream bzip files. It will silently succeed and give us a garbage
  78. # profile.
  79. # bzip2 removes the compressed file on success.
  80. CheckCallOrExit(['bzip2', '-d', out_path])
  81. elif ext == '.xz':
  82. # ...And we can't use the `lzma` module, since it was introduced in python3.
  83. # xz removes the compressed file on success.
  84. CheckCallOrExit(['xz', '-d', out_path])
  85. def main():
  86. parser = argparse.ArgumentParser(
  87. description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  88. parser.add_argument(
  89. '--newest_state',
  90. required=True,
  91. help='Path to the file with name of the newest profile. '
  92. 'We use this file to track the name of the newest profile '
  93. 'we should pull.')
  94. parser.add_argument(
  95. '--local_state',
  96. required=True,
  97. help='Path of the file storing name of the local profile. '
  98. 'We use this file to track the most recent profile we\'ve '
  99. 'successfully pulled.')
  100. parser.add_argument(
  101. '--gs_url_base',
  102. required=True,
  103. help='The base GS URL to search for the profile.')
  104. parser.add_argument(
  105. '--output_name',
  106. required=True,
  107. help='Output name of the downloaded and uncompressed profile.')
  108. parser.add_argument(
  109. '-f',
  110. '--force',
  111. action='store_true',
  112. help='Fetch a profile even if the local one is current.')
  113. args = parser.parse_args()
  114. up_to_date_profile = ReadUpToDateProfileName(args.newest_state)
  115. if not args.force:
  116. local_profile_name = ReadLocalProfileName(args.local_state)
  117. # In a perfect world, the local profile should always exist if we
  118. # successfully read local_profile_name. If it's gone, though, the user
  119. # probably removed it as a way to get us to download it again.
  120. if local_profile_name == up_to_date_profile \
  121. and os.path.exists(args.output_name):
  122. return 0
  123. new_tmpfile = args.output_name + '.new'
  124. RetrieveProfile(up_to_date_profile, new_tmpfile, args.gs_url_base)
  125. os.rename(new_tmpfile, args.output_name)
  126. WriteLocalProfileName(up_to_date_profile, args.local_state)
  127. if __name__ == '__main__':
  128. sys.exit(main())