github_message.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. #!/usr/bin/python3
  2. """
  3. Create Github Releases Notes with binary checksums from Workers KV
  4. """
  5. import argparse
  6. import logging
  7. import os
  8. import requests
  9. from github import Github, UnknownObjectException
  10. FORMAT = "%(levelname)s - %(asctime)s: %(message)s"
  11. logging.basicConfig(format=FORMAT, level=logging.INFO)
  12. CLOUDFLARED_REPO = os.environ.get("GITHUB_REPO", "cloudflare/cloudflared")
  13. GITHUB_CONFLICT_CODE = "already_exists"
  14. BASE_KV_URL = 'https://api.cloudflare.com/client/v4/accounts/'
  15. def kv_get_keys(prefix, account, namespace, api_token):
  16. """ get the KV keys for a given prefix """
  17. response = requests.get(
  18. BASE_KV_URL + account + "/storage/kv/namespaces/" +
  19. namespace + "/keys" + "?prefix=" + prefix,
  20. headers={
  21. "Content-Type": "application/json",
  22. "Authorization": "Bearer " + api_token,
  23. },
  24. )
  25. if response.status_code != 200:
  26. jsonResponse = response.json()
  27. errors = jsonResponse["errors"]
  28. if len(errors) > 0:
  29. raise Exception("failed to get checksums: {0}", errors[0])
  30. return response.json()["result"]
  31. def kv_get_value(key, account, namespace, api_token):
  32. """ get the KV value for a provided key """
  33. response = requests.get(
  34. BASE_KV_URL + account + "/storage/kv/namespaces/" + namespace + "/values/" + key,
  35. headers={
  36. "Content-Type": "application/json",
  37. "Authorization": "Bearer " + api_token,
  38. },
  39. )
  40. if response.status_code != 200:
  41. jsonResponse = response.json()
  42. errors = jsonResponse["errors"]
  43. if len(errors) > 0:
  44. raise Exception("failed to get checksums: {0}", errors[0])
  45. return response.text
  46. def update_or_add_message(msg, name, sha):
  47. """
  48. updates or builds the github version message for each new asset's sha256.
  49. Searches the existing message string to update or create.
  50. """
  51. new_text = '{0}: {1}\n'.format(name, sha)
  52. start = msg.find(name)
  53. if (start != -1):
  54. end = msg.find("\n", start)
  55. if (end != -1):
  56. return msg.replace(msg[start:end+1], new_text)
  57. back = msg.rfind("```")
  58. if (back != -1):
  59. return '{0}{1}```'.format(msg[:back], new_text)
  60. return '{0} \n### SHA256 Checksums:\n```\n{1}```'.format(msg, new_text)
  61. def get_release(repo, version):
  62. """ Get a Github Release matching the version tag. """
  63. try:
  64. release = repo.get_release(version)
  65. logging.info("Release %s found", version)
  66. return release
  67. except UnknownObjectException:
  68. logging.info("Release %s not found", version)
  69. def parse_args():
  70. """ Parse and validate args """
  71. parser = argparse.ArgumentParser(
  72. description="Updates a Github Release with checksums from KV"
  73. )
  74. parser.add_argument(
  75. "--api-key", default=os.environ.get("API_KEY"), help="Github API key"
  76. )
  77. parser.add_argument(
  78. "--kv-namespace-id", default=os.environ.get("KV_NAMESPACE"), help="workers KV namespace id"
  79. )
  80. parser.add_argument(
  81. "--kv-account-id", default=os.environ.get("KV_ACCOUNT"), help="workers KV account id"
  82. )
  83. parser.add_argument(
  84. "--kv-api-token", default=os.environ.get("KV_API_TOKEN"), help="workers KV API Token"
  85. )
  86. parser.add_argument(
  87. "--release-version",
  88. metavar="version",
  89. default=os.environ.get("VERSION"),
  90. help="Release version",
  91. )
  92. parser.add_argument(
  93. "--dry-run", action="store_true", help="Do not modify the release message"
  94. )
  95. args = parser.parse_args()
  96. is_valid = True
  97. if not args.release_version:
  98. logging.error("Missing release version")
  99. is_valid = False
  100. if not args.api_key:
  101. logging.error("Missing API key")
  102. is_valid = False
  103. if not args.kv_namespace_id:
  104. logging.error("Missing KV namespace id")
  105. is_valid = False
  106. if not args.kv_account_id:
  107. logging.error("Missing KV account id")
  108. is_valid = False
  109. if not args.kv_api_token:
  110. logging.error("Missing KV API token")
  111. is_valid = False
  112. if is_valid:
  113. return args
  114. parser.print_usage()
  115. exit(1)
  116. def main():
  117. """ Attempts to update the Github Release message with the github asset's checksums """
  118. try:
  119. args = parse_args()
  120. client = Github(args.api_key)
  121. repo = client.get_repo(CLOUDFLARED_REPO)
  122. release = get_release(repo, args.release_version)
  123. msg = ""
  124. prefix = f"update_{args.release_version}_"
  125. keys = kv_get_keys(prefix, args.kv_account_id,
  126. args.kv_namespace_id, args.kv_api_token)
  127. for key in [k["name"] for k in keys]:
  128. checksum = kv_get_value(
  129. key, args.kv_account_id, args.kv_namespace_id, args.kv_api_token)
  130. binary_name = key[len(prefix):]
  131. msg = update_or_add_message(msg, binary_name, checksum)
  132. if args.dry_run:
  133. logging.info("Skipping release message update because of dry-run")
  134. logging.info(f"Github message:\n{msg}")
  135. return
  136. # update the release body text
  137. release.update_release(args.release_version, msg)
  138. except Exception as e:
  139. logging.exception(e)
  140. exit(1)
  141. main()