You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

291 lines
10 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #!/usr/bin/env python
  2. # Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style license
  5. # that can be found in the LICENSE file in the root of the source
  6. # tree. An additional intellectual property rights grant can be found
  7. # in the file PATENTS. All contributing project authors may
  8. # be found in the AUTHORS file in the root of the source tree.
  9. """Script for publishing WebRTC AAR on Bintray.
  10. Set BINTRAY_USER and BINTRAY_API_KEY environment variables before running
  11. this script for authentication.
  12. """
  13. import argparse
  14. import json
  15. import logging
  16. import os
  17. import re
  18. import shutil
  19. import subprocess
  20. import sys
  21. import tempfile
  22. import time
  23. SCRIPT_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))
  24. CHECKOUT_ROOT = os.path.abspath(os.path.join(SCRIPT_DIR, os.pardir, os.pardir))
  25. sys.path.append(os.path.join(CHECKOUT_ROOT, 'third_party'))
  26. import requests
  27. import jinja2
  28. sys.path.append(os.path.join(CHECKOUT_ROOT, 'tools_webrtc'))
  29. from android.build_aar import BuildAar
  30. ARCHS = ['armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64']
  31. MAVEN_REPOSITORY = 'https://google.bintray.com/webrtc'
  32. API = 'https://api.bintray.com'
  33. PACKAGE_PATH = 'google/webrtc/google-webrtc'
  34. CONTENT_API = API + '/content/' + PACKAGE_PATH
  35. PACKAGES_API = API + '/packages/' + PACKAGE_PATH
  36. GROUP_ID = 'org/webrtc'
  37. ARTIFACT_ID = 'google-webrtc'
  38. COMMIT_POSITION_REGEX = r'^Cr-Commit-Position: refs/heads/master@{#(\d+)}$'
  39. API_TIMEOUT_SECONDS = 10.0
  40. UPLOAD_TRIES = 3
  41. # The sleep time is increased exponentially.
  42. UPLOAD_RETRY_BASE_SLEEP_SECONDS = 2.0
  43. GRADLEW_BIN = os.path.join(CHECKOUT_ROOT,
  44. 'examples/androidtests/third_party/gradle/gradlew')
  45. ADB_BIN = os.path.join(CHECKOUT_ROOT,
  46. 'third_party/android_sdk/public/platform-tools/adb')
  47. AAR_PROJECT_DIR = os.path.join(CHECKOUT_ROOT, 'examples/aarproject')
  48. AAR_PROJECT_GRADLE = os.path.join(AAR_PROJECT_DIR, 'build.gradle')
  49. AAR_PROJECT_APP_GRADLE = os.path.join(AAR_PROJECT_DIR, 'app', 'build.gradle')
  50. AAR_PROJECT_DEPENDENCY = "implementation 'org.webrtc:google-webrtc:1.0.+'"
  51. AAR_PROJECT_VERSION_DEPENDENCY = "implementation 'org.webrtc:google-webrtc:%s'"
  52. def _ParseArgs():
  53. parser = argparse.ArgumentParser(description='Releases WebRTC on Bintray.')
  54. parser.add_argument('--use-goma', action='store_true', default=False,
  55. help='Use goma.')
  56. parser.add_argument('--skip-tests', action='store_true', default=False,
  57. help='Skips running the tests.')
  58. parser.add_argument('--publish', action='store_true', default=False,
  59. help='Automatically publishes the library if the tests pass.')
  60. parser.add_argument('--build-dir', default=None,
  61. help='Temporary directory to store the build files. If not specified, '
  62. 'a new directory will be created.')
  63. parser.add_argument('--verbose', action='store_true', default=False,
  64. help='Debug logging.')
  65. return parser.parse_args()
  66. def _GetCommitHash():
  67. commit_hash = subprocess.check_output(
  68. ['git', 'rev-parse', 'HEAD'], cwd=CHECKOUT_ROOT).strip()
  69. return commit_hash
  70. def _GetCommitPos():
  71. commit_message = subprocess.check_output(
  72. ['git', 'rev-list', '--format=%B', '--max-count=1', 'HEAD'],
  73. cwd=CHECKOUT_ROOT)
  74. commit_pos_match = re.search(
  75. COMMIT_POSITION_REGEX, commit_message, re.MULTILINE)
  76. if not commit_pos_match:
  77. raise Exception('Commit position not found in the commit message: %s'
  78. % commit_message)
  79. return commit_pos_match.group(1)
  80. def _UploadFile(user, password, filename, version, target_file):
  81. # URL is of format:
  82. # <repository_api>/<version>/<group_id>/<artifact_id>/<version>/<target_file>
  83. # Example:
  84. # https://api.bintray.com/content/google/webrtc/google-webrtc/1.0.19742/org/webrtc/google-webrtc/1.0.19742/google-webrtc-1.0.19742.aar
  85. target_dir = version + '/' + GROUP_ID + '/' + ARTIFACT_ID + '/' + version
  86. target_path = target_dir + '/' + target_file
  87. url = CONTENT_API + '/' + target_path
  88. logging.info('Uploading %s to %s', filename, url)
  89. with open(filename) as fh:
  90. file_data = fh.read()
  91. for attempt in xrange(UPLOAD_TRIES):
  92. try:
  93. response = requests.put(url, data=file_data, auth=(user, password),
  94. timeout=API_TIMEOUT_SECONDS)
  95. break
  96. except requests.exceptions.Timeout as e:
  97. logging.warning('Timeout while uploading: %s', e)
  98. time.sleep(UPLOAD_RETRY_BASE_SLEEP_SECONDS ** attempt)
  99. else:
  100. raise Exception('Failed to upload %s' % filename)
  101. if not response.ok:
  102. raise Exception('Failed to upload %s. Response: %s' % (filename, response))
  103. logging.info('Uploaded %s: %s', filename, response)
  104. def _GeneratePom(target_file, version, commit):
  105. env = jinja2.Environment(
  106. loader=jinja2.PackageLoader('release_aar'),
  107. )
  108. template = env.get_template('pom.jinja')
  109. pom = template.render(version=version, commit=commit)
  110. with open(target_file, 'w') as fh:
  111. fh.write(pom)
  112. def _TestAAR(tmp_dir, username, password, version):
  113. """Runs AppRTCMobile tests using the AAR. Returns true if the tests pass."""
  114. logging.info('Testing library.')
  115. env = jinja2.Environment(
  116. loader=jinja2.PackageLoader('release_aar'),
  117. )
  118. gradle_backup = os.path.join(tmp_dir, 'build.gradle.backup')
  119. app_gradle_backup = os.path.join(tmp_dir, 'app-build.gradle.backup')
  120. # Make backup copies of the project files before modifying them.
  121. shutil.copy2(AAR_PROJECT_GRADLE, gradle_backup)
  122. shutil.copy2(AAR_PROJECT_APP_GRADLE, app_gradle_backup)
  123. try:
  124. maven_repository_template = env.get_template('maven-repository.jinja')
  125. maven_repository = maven_repository_template.render(
  126. url=MAVEN_REPOSITORY, username=username, password=password)
  127. # Append Maven repository to build file to download unpublished files.
  128. with open(AAR_PROJECT_GRADLE, 'a') as gradle_file:
  129. gradle_file.write(maven_repository)
  130. # Read app build file.
  131. with open(AAR_PROJECT_APP_GRADLE, 'r') as gradle_app_file:
  132. gradle_app = gradle_app_file.read()
  133. if AAR_PROJECT_DEPENDENCY not in gradle_app:
  134. raise Exception(
  135. '%s not found in the build file.' % AAR_PROJECT_DEPENDENCY)
  136. # Set version to the version to be tested.
  137. target_dependency = AAR_PROJECT_VERSION_DEPENDENCY % version
  138. gradle_app = gradle_app.replace(AAR_PROJECT_DEPENDENCY, target_dependency)
  139. # Write back.
  140. with open(AAR_PROJECT_APP_GRADLE, 'w') as gradle_app_file:
  141. gradle_app_file.write(gradle_app)
  142. # Uninstall any existing version of AppRTCMobile.
  143. logging.info('Uninstalling previous AppRTCMobile versions. It is okay for '
  144. 'these commands to fail if AppRTCMobile is not installed.')
  145. subprocess.call([ADB_BIN, 'uninstall', 'org.appspot.apprtc'])
  146. subprocess.call([ADB_BIN, 'uninstall', 'org.appspot.apprtc.test'])
  147. # Run tests.
  148. try:
  149. # First clean the project.
  150. subprocess.check_call([GRADLEW_BIN, 'clean'], cwd=AAR_PROJECT_DIR)
  151. # Then run the tests.
  152. subprocess.check_call([GRADLEW_BIN, 'connectedDebugAndroidTest'],
  153. cwd=AAR_PROJECT_DIR)
  154. except subprocess.CalledProcessError:
  155. logging.exception('Test failure.')
  156. return False # Clean or tests failed
  157. return True # Tests pass
  158. finally:
  159. # Restore backups.
  160. shutil.copy2(gradle_backup, AAR_PROJECT_GRADLE)
  161. shutil.copy2(app_gradle_backup, AAR_PROJECT_APP_GRADLE)
  162. def _PublishAAR(user, password, version, additional_args):
  163. args = {
  164. 'publish_wait_for_secs': 0 # Publish asynchronously.
  165. }
  166. args.update(additional_args)
  167. url = CONTENT_API + '/' + version + '/publish'
  168. response = requests.post(url, data=json.dumps(args), auth=(user, password),
  169. timeout=API_TIMEOUT_SECONDS)
  170. if not response.ok:
  171. raise Exception('Failed to publish. Response: %s' % response)
  172. def _DeleteUnpublishedVersion(user, password, version):
  173. url = PACKAGES_API + '/versions/' + version
  174. response = requests.get(url, auth=(user, password),
  175. timeout=API_TIMEOUT_SECONDS)
  176. if not response.ok:
  177. raise Exception('Failed to get version info. Response: %s' % response)
  178. version_info = json.loads(response.content)
  179. if version_info['published']:
  180. logging.info('Version has already been published, not deleting.')
  181. return
  182. logging.info('Deleting unpublished version.')
  183. response = requests.delete(url, auth=(user, password),
  184. timeout=API_TIMEOUT_SECONDS)
  185. if not response.ok:
  186. raise Exception('Failed to delete version. Response: %s' % response)
  187. def ReleaseAar(use_goma, skip_tests, publish, build_dir):
  188. version = '1.0.' + _GetCommitPos()
  189. commit = _GetCommitHash()
  190. logging.info('Releasing AAR version %s with hash %s', version, commit)
  191. user = os.environ.get('BINTRAY_USER', None)
  192. api_key = os.environ.get('BINTRAY_API_KEY', None)
  193. if not user or not api_key:
  194. raise Exception('Environment variables BINTRAY_USER and BINTRAY_API_KEY '
  195. 'must be defined.')
  196. # If build directory is not specified, create a temporary directory.
  197. use_tmp_dir = not build_dir
  198. if use_tmp_dir:
  199. build_dir = tempfile.mkdtemp()
  200. try:
  201. base_name = ARTIFACT_ID + '-' + version
  202. aar_file = os.path.join(build_dir, base_name + '.aar')
  203. third_party_licenses_file = os.path.join(build_dir, 'LICENSE.md')
  204. pom_file = os.path.join(build_dir, base_name + '.pom')
  205. logging.info('Building at %s', build_dir)
  206. BuildAar(ARCHS, aar_file,
  207. use_goma=use_goma,
  208. ext_build_dir=os.path.join(build_dir, 'aar-build'))
  209. _GeneratePom(pom_file, version, commit)
  210. _UploadFile(user, api_key, aar_file, version, base_name + '.aar')
  211. _UploadFile(user, api_key, third_party_licenses_file, version,
  212. 'THIRD_PARTY_LICENSES.md')
  213. _UploadFile(user, api_key, pom_file, version, base_name + '.pom')
  214. tests_pass = skip_tests or _TestAAR(build_dir, user, api_key, version)
  215. if not tests_pass:
  216. logging.info('Discarding library.')
  217. _PublishAAR(user, api_key, version, {'discard': True})
  218. _DeleteUnpublishedVersion(user, api_key, version)
  219. raise Exception('Test failure. Discarded library.')
  220. if publish:
  221. logging.info('Publishing library.')
  222. _PublishAAR(user, api_key, version, {})
  223. else:
  224. logging.info('Note: The library has not not been published automatically.'
  225. ' Please do so manually if desired.')
  226. finally:
  227. if use_tmp_dir:
  228. shutil.rmtree(build_dir, True)
  229. def main():
  230. args = _ParseArgs()
  231. logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO)
  232. ReleaseAar(args.use_goma, args.skip_tests, args.publish, args.build_dir)
  233. if __name__ == '__main__':
  234. sys.exit(main())