nightly.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. import os
  2. import sys
  3. from zipfile import ZipFile, ZIP_DEFLATED
  4. from b2sdk.v2 import InMemoryAccountInfo, B2Api
  5. from datetime import datetime
  6. import json
  7. UPLOAD_FOLDER = "nightly/"
  8. info = InMemoryAccountInfo()
  9. b2_api = B2Api(info)
  10. application_key_id = os.environ['APPID']
  11. application_key = os.environ['APPKEY']
  12. bucket_name = os.environ['BUCKET']
  13. days_to_keep = os.environ['DAYS_TO_KEEP']
  14. def auth() -> bool:
  15. try:
  16. realm = b2_api.account_info.get_realm()
  17. return True # Already authenticated
  18. except:
  19. pass # Not yet authenticated
  20. err = b2_api.authorize_account("production", application_key_id, application_key)
  21. return err == None
  22. def get_bucket():
  23. if not auth(): sys.exit(1)
  24. return b2_api.get_bucket_by_name(bucket_name)
  25. def remove_prefix(text: str, prefix: str) -> str:
  26. return text[text.startswith(prefix) and len(prefix):]
  27. def create_and_upload_artifact_zip(platform: str, artifact: str) -> int:
  28. now = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
  29. destination_zip_name = "odin-{}-nightly+{}.zip".format(platform, now.strftime("%Y-%m-%d"))
  30. source_zip_name = artifact
  31. if not artifact.endswith(".zip"):
  32. print(f"Creating archive {destination_zip_name} from {artifact} and uploading to {bucket_name}")
  33. source_zip_name = destination_zip_name
  34. with ZipFile(source_zip_name, mode='w', compression=ZIP_DEFLATED, compresslevel=9) as z:
  35. for root, directory, filenames in os.walk(artifact):
  36. for file in filenames:
  37. file_path = os.path.join(root, file)
  38. zip_path = os.path.join("dist", os.path.relpath(file_path, artifact))
  39. z.write(file_path, zip_path)
  40. if not os.path.exists(source_zip_name):
  41. print(f"Error: Newly created ZIP archive {source_zip_name} not found.")
  42. return 1
  43. print("Uploading {} to {}".format(source_zip_name, UPLOAD_FOLDER + destination_zip_name))
  44. bucket = get_bucket()
  45. res = bucket.upload_local_file(
  46. source_zip_name, # Local file to upload
  47. "nightly/" + destination_zip_name, # B2 destination path
  48. )
  49. return 0
  50. def prune_artifacts():
  51. print(f"Looking for binaries to delete older than {days_to_keep} days")
  52. bucket = get_bucket()
  53. for file, _ in bucket.ls(UPLOAD_FOLDER, latest_only=False):
  54. # Timestamp is in milliseconds
  55. date = datetime.fromtimestamp(file.upload_timestamp / 1_000.0).replace(hour=0, minute=0, second=0, microsecond=0)
  56. now = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
  57. delta = now - date
  58. if delta.days > int(days_to_keep):
  59. print("Deleting {}".format(file.file_name))
  60. file.delete()
  61. return 0
  62. def update_nightly_json():
  63. print(f"Updating nightly.json with files {days_to_keep} days or newer")
  64. files_by_date = {}
  65. bucket = get_bucket()
  66. for file, _ in bucket.ls(UPLOAD_FOLDER, latest_only=True):
  67. # Timestamp is in milliseconds
  68. date = datetime.fromtimestamp(file.upload_timestamp / 1_000.0).replace(hour=0, minute=0, second=0, microsecond=0).strftime('%Y-%m-%d')
  69. name = remove_prefix(file.file_name, UPLOAD_FOLDER)
  70. sha1 = file.content_sha1
  71. size = file.size
  72. url = bucket.get_download_url(file.file_name)
  73. if date not in files_by_date.keys():
  74. files_by_date[date] = []
  75. files_by_date[date].append({
  76. 'name': name,
  77. 'url': url,
  78. 'sha1': sha1,
  79. 'sizeInBytes': size,
  80. })
  81. now = datetime.utcnow().isoformat()
  82. nightly = json.dumps({
  83. 'last_updated' : now,
  84. 'files': files_by_date
  85. }, sort_keys=True, indent=4, ensure_ascii=False).encode('utf-8')
  86. res = bucket.upload_bytes(
  87. nightly, # JSON bytes
  88. "nightly.json", # B2 destination path
  89. )
  90. return 0
  91. if __name__ == "__main__":
  92. if len(sys.argv) == 1:
  93. print("Usage: {} <verb> [arguments]".format(sys.argv[0]))
  94. print("\tartifact <platform prefix> <artifact path>\n\t\tCreates and uploads a platform artifact zip.")
  95. print("\tprune\n\t\tDeletes old artifacts from bucket")
  96. print("\tjson\n\t\tUpdate and upload nightly.json")
  97. sys.exit(1)
  98. else:
  99. command = sys.argv[1].lower()
  100. if command == "artifact":
  101. if len(sys.argv) != 4:
  102. print("Usage: {} artifact <platform prefix> <artifact path>".format(sys.argv[0]))
  103. print("Error: Expected artifact command to be given platform prefix and artifact path.\n")
  104. sys.exit(1)
  105. res = create_and_upload_artifact_zip(sys.argv[2], sys.argv[3])
  106. sys.exit(res)
  107. elif command == "prune":
  108. res = prune_artifacts()
  109. sys.exit(res)
  110. elif command == "json":
  111. res = update_nightly_json()
  112. sys.exit(res)