github_release.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #!/usr/bin/python3
  2. """
  3. Creates Github Releases and uploads assets
  4. """
  5. import argparse
  6. import logging
  7. import os
  8. import shutil
  9. import hashlib
  10. import requests
  11. import tarfile
  12. from os import listdir
  13. from os.path import isfile, join, splitext
  14. import re
  15. import subprocess
  16. from github import Github, GithubException, UnknownObjectException
  17. FORMAT = "%(levelname)s - %(asctime)s: %(message)s"
  18. logging.basicConfig(format=FORMAT, level=logging.INFO)
  19. CLOUDFLARED_REPO = os.environ.get("GITHUB_REPO", "cloudflare/cloudflared")
  20. GITHUB_CONFLICT_CODE = "already_exists"
  21. BASE_KV_URL = 'https://api.cloudflare.com/client/v4/accounts/'
  22. UPDATER_PREFIX = 'update'
  23. def get_sha256(filename):
  24. """ get the sha256 of a file """
  25. sha256_hash = hashlib.sha256()
  26. with open(filename,"rb") as f:
  27. for byte_block in iter(lambda: f.read(4096),b""):
  28. sha256_hash.update(byte_block)
  29. return sha256_hash.hexdigest()
  30. def send_hash(pkg_hash, name, version, account, namespace, api_token):
  31. """ send the checksum of a file to workers kv """
  32. key = '{0}_{1}_{2}'.format(UPDATER_PREFIX, version, name)
  33. headers = {
  34. "Content-Type": "application/json",
  35. "Authorization": "Bearer " + api_token,
  36. }
  37. response = requests.put(
  38. BASE_KV_URL + account + "/storage/kv/namespaces/" + namespace + "/values/" + key,
  39. headers=headers,
  40. data=pkg_hash
  41. )
  42. if response.status_code != 200:
  43. jsonResponse = response.json()
  44. errors = jsonResponse["errors"]
  45. if len(errors) > 0:
  46. raise Exception("failed to upload checksum: {0}", errors[0])
  47. def assert_tag_exists(repo, version):
  48. """ Raise exception if repo does not contain a tag matching version """
  49. tags = repo.get_tags()
  50. if not tags or tags[0].name != version:
  51. raise Exception("Tag {} not found".format(version))
  52. def get_or_create_release(repo, version, dry_run=False):
  53. """
  54. Get a Github Release matching the version tag or create a new one.
  55. If a conflict occurs on creation, attempt to fetch the Release on last time
  56. """
  57. try:
  58. release = repo.get_release(version)
  59. logging.info("Release %s found", version)
  60. return release
  61. except UnknownObjectException:
  62. logging.info("Release %s not found", version)
  63. # We don't want to create a new release tag if one doesn't already exist
  64. assert_tag_exists(repo, version)
  65. if dry_run:
  66. logging.info("Skipping Release creation because of dry-run")
  67. return
  68. try:
  69. logging.info("Creating release %s", version)
  70. return repo.create_git_release(version, version, "")
  71. except GithubException as e:
  72. errors = e.data.get("errors", [])
  73. if e.status == 422 and any(
  74. [err.get("code") == GITHUB_CONFLICT_CODE for err in errors]
  75. ):
  76. logging.warning(
  77. "Conflict: Release was likely just made by a different build: %s",
  78. e.data,
  79. )
  80. return repo.get_release(version)
  81. raise e
  82. def parse_args():
  83. """ Parse and validate args """
  84. parser = argparse.ArgumentParser(
  85. description="Creates Github Releases and uploads assets."
  86. )
  87. parser.add_argument(
  88. "--api-key", default=os.environ.get("API_KEY"), help="Github API key"
  89. )
  90. parser.add_argument(
  91. "--release-version",
  92. metavar="version",
  93. default=os.environ.get("VERSION"),
  94. help="Release version",
  95. )
  96. parser.add_argument(
  97. "--path", default=os.environ.get("ASSET_PATH"), help="Asset path"
  98. )
  99. parser.add_argument(
  100. "--name", default=os.environ.get("ASSET_NAME"), help="Asset Name"
  101. )
  102. parser.add_argument(
  103. "--namespace-id", default=os.environ.get("KV_NAMESPACE"), help="workersKV namespace id"
  104. )
  105. parser.add_argument(
  106. "--kv-account-id", default=os.environ.get("KV_ACCOUNT"), help="workersKV account id"
  107. )
  108. parser.add_argument(
  109. "--kv-api-token", default=os.environ.get("KV_API_TOKEN"), help="workersKV API Token"
  110. )
  111. parser.add_argument(
  112. "--dry-run", action="store_true", help="Do not create release or upload asset"
  113. )
  114. args = parser.parse_args()
  115. is_valid = True
  116. if not args.release_version:
  117. logging.error("Missing release version")
  118. is_valid = False
  119. if not args.path:
  120. logging.error("Missing asset path")
  121. is_valid = False
  122. if not args.name and not os.path.isdir(args.path):
  123. logging.error("Missing asset name")
  124. is_valid = False
  125. if not args.api_key:
  126. logging.error("Missing API key")
  127. is_valid = False
  128. if not args.namespace_id:
  129. logging.error("Missing KV namespace id")
  130. is_valid = False
  131. if not args.kv_account_id:
  132. logging.error("Missing KV account id")
  133. is_valid = False
  134. if not args.kv_api_token:
  135. logging.error("Missing KV API token")
  136. is_valid = False
  137. if is_valid:
  138. return args
  139. parser.print_usage()
  140. exit(1)
  141. def upload_asset(release, filepath, filename, release_version, kv_account_id, namespace_id, kv_api_token):
  142. logging.info("Uploading asset: %s", filename)
  143. assets = release.get_assets()
  144. uploaded = False
  145. for asset in assets:
  146. if asset.name == filename:
  147. uploaded = True
  148. break
  149. if uploaded:
  150. logging.info("asset already uploaded, skipping upload")
  151. return
  152. release.upload_asset(filepath, name=filename)
  153. # check and extract if the file is a tar and gzipped file (as is the case with the macos builds)
  154. binary_path = filepath
  155. if binary_path.endswith("tgz"):
  156. try:
  157. shutil.rmtree('cfd')
  158. except OSError:
  159. pass
  160. zipfile = tarfile.open(binary_path, "r:gz")
  161. zipfile.extractall('cfd') # specify which folder to extract to
  162. zipfile.close()
  163. binary_path = os.path.join(os.getcwd(), 'cfd', 'cloudflared')
  164. # send the sha256 (the checksum) to workers kv
  165. logging.info("Uploading sha256 checksum for: %s", filename)
  166. pkg_hash = get_sha256(binary_path)
  167. send_hash(pkg_hash, filename, release_version, kv_account_id, namespace_id, kv_api_token)
  168. def move_asset(filepath, filename):
  169. # create the artifacts directory if it doesn't exist
  170. artifact_path = os.path.join(os.getcwd(), 'artifacts')
  171. if not os.path.isdir(artifact_path):
  172. os.mkdir(artifact_path)
  173. # copy the binary to the path
  174. copy_path = os.path.join(artifact_path, filename)
  175. try:
  176. shutil.copy(filepath, copy_path)
  177. except shutil.SameFileError:
  178. pass # the macOS release copy fails with being the same file (already in the artifacts directory)
  179. def get_binary_version(binary_path):
  180. """
  181. Sample output from go version -m <binary>:
  182. ...
  183. build -compiler=gc
  184. build -ldflags="-X \"main.Version=2024.8.3-6-gec072691\" -X \"main.BuildTime=2024-09-10-1027 UTC\" "
  185. build CGO_ENABLED=1
  186. ...
  187. This function parses the above output to retrieve the following substring 2024.8.3-6-gec072691.
  188. To do this a start and end indexes are computed and the a slice is extracted from the output using them.
  189. """
  190. needle = "main.Version="
  191. cmd = ['go','version', '-m', binary_path]
  192. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  193. output, _ = process.communicate()
  194. version_info = output.decode()
  195. # Find start of needle
  196. needle_index = version_info.find(needle)
  197. # Find backward slash relative to the beggining of the needle
  198. relative_end_index = version_info[needle_index:].find("\\")
  199. # Calculate needle position plus needle length to find version beggining
  200. start_index = needle_index + len(needle)
  201. # Calculate needle position plus relative position of the backward slash
  202. end_index = needle_index + relative_end_index
  203. return version_info[start_index:end_index]
  204. def assert_asset_version(binary_path, release_version):
  205. """
  206. Asserts that the artifacts have the correct release_version.
  207. The artifacts that are checked must not have an extension expecting .exe and .tgz.
  208. In the occurrence of any other extension the function exits early.
  209. """
  210. try:
  211. shutil.rmtree('tmp')
  212. except OSError:
  213. pass
  214. _, ext = os.path.splitext(binary_path)
  215. if ext == '.exe' or ext == '':
  216. binary_version = get_binary_version(binary_path)
  217. elif ext == '.tgz':
  218. tar = tarfile.open(binary_path, "r:gz")
  219. tar.extractall("tmp")
  220. tar.close()
  221. binary_path = os.path.join(os.getcwd(), 'tmp', 'cloudflared')
  222. binary_version = get_binary_version(binary_path)
  223. else:
  224. return
  225. if binary_version != release_version:
  226. logging.error(f"Version mismatch {binary_path}, binary_version {binary_version} release_version {release_version}")
  227. exit(1)
  228. def main():
  229. """ Attempts to upload Asset to Github Release. Creates Release if it doesn't exist """
  230. try:
  231. args = parse_args()
  232. if args.dry_run:
  233. if os.path.isdir(args.path):
  234. onlyfiles = [f for f in listdir(args.path) if isfile(join(args.path, f))]
  235. for filename in onlyfiles:
  236. binary_path = os.path.join(args.path, filename)
  237. logging.info("binary: " + binary_path)
  238. assert_asset_version(binary_path, args.release_version)
  239. elif os.path.isfile(args.path):
  240. logging.info("binary: " + binary_path)
  241. else:
  242. logging.error("dryrun failed")
  243. return
  244. else:
  245. client = Github(args.api_key)
  246. repo = client.get_repo(CLOUDFLARED_REPO)
  247. if os.path.isdir(args.path):
  248. onlyfiles = [f for f in listdir(args.path) if isfile(join(args.path, f))]
  249. for filename in onlyfiles:
  250. binary_path = os.path.join(args.path, filename)
  251. assert_asset_version(binary_path, args.release_version)
  252. release = get_or_create_release(repo, args.release_version, args.dry_run)
  253. for filename in onlyfiles:
  254. binary_path = os.path.join(args.path, filename)
  255. upload_asset(release, binary_path, filename, args.release_version, args.kv_account_id, args.namespace_id,
  256. args.kv_api_token)
  257. move_asset(binary_path, filename)
  258. else:
  259. raise Exception("the argument path must be a directory")
  260. except Exception as e:
  261. logging.exception(e)
  262. exit(1)
  263. main()