artifacts_handler.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. import argparse
  4. import fnmatch
  5. import glob
  6. import os
  7. import typing as t
  8. from enum import Enum
  9. from pathlib import Path
  10. from zipfile import ZipFile
  11. import urllib3
  12. from minio import Minio
  13. class ArtifactType(str, Enum):
  14. MAP_AND_ELF_FILES = 'map_and_elf_files'
  15. BUILD_DIR_WITHOUT_MAP_AND_ELF_FILES = 'build_dir_without_map_and_elf_files'
  16. LOGS = 'logs'
  17. SIZE_REPORTS = 'size_reports'
  18. TYPE_PATTERNS_DICT = {
  19. ArtifactType.MAP_AND_ELF_FILES: [
  20. '**/build*/**/*.map',
  21. '**/build*/**/*.elf',
  22. ],
  23. ArtifactType.BUILD_DIR_WITHOUT_MAP_AND_ELF_FILES: [
  24. '**/build*/build_log.txt',
  25. '**/build*/**/*.bin',
  26. '**/build*/flasher_args.json',
  27. '**/build*/flash_project_args',
  28. '**/build*/config/sdkconfig.json',
  29. '**/build*/project_description.json',
  30. 'list_job_*.txt',
  31. ],
  32. ArtifactType.LOGS: [
  33. '**/build*/build_log.txt',
  34. ],
  35. ArtifactType.SIZE_REPORTS: [
  36. '**/build*/size.json',
  37. 'size_info.txt',
  38. ],
  39. }
  40. def getenv(env_var: str) -> str:
  41. try:
  42. return os.environ[env_var]
  43. except KeyError as e:
  44. raise Exception(f'Environment variable {env_var} not set') from e
  45. def _download_files(
  46. pipeline_id: int,
  47. *,
  48. artifact_type: t.Optional[ArtifactType] = None,
  49. job_name: t.Optional[str] = None,
  50. job_id: t.Optional[int] = None,
  51. ) -> None:
  52. if artifact_type:
  53. prefix = f'{pipeline_id}/{artifact_type.value}/'
  54. else:
  55. prefix = f'{pipeline_id}/'
  56. for obj in client.list_objects(getenv('IDF_S3_BUCKET'), prefix=prefix, recursive=True):
  57. obj_name = obj.object_name
  58. obj_p = Path(obj_name)
  59. # <pipeline_id>/<action_type>/<job_name>/<job_id>.zip
  60. if len(obj_p.parts) != 4:
  61. print(f'Invalid object name: {obj_name}')
  62. continue
  63. if job_name:
  64. # could be a pattern
  65. if not fnmatch.fnmatch(obj_p.parts[2], job_name):
  66. print(f'Job name {job_name} does not match {obj_p.parts[2]}')
  67. continue
  68. if job_id:
  69. if obj_p.parts[3] != f'{job_id}.zip':
  70. print(f'Job ID {job_id} does not match {obj_p.parts[3]}')
  71. continue
  72. client.fget_object(getenv('IDF_S3_BUCKET'), obj_name, obj_name)
  73. print(f'Downloaded {obj_name}')
  74. if obj_name.endswith('.zip'):
  75. with ZipFile(obj_name, 'r') as zr:
  76. zr.extractall()
  77. print(f'Extracted {obj_name}')
  78. os.remove(obj_name)
  79. def _upload_files(
  80. pipeline_id: int,
  81. *,
  82. artifact_type: ArtifactType,
  83. job_name: str,
  84. job_id: str,
  85. ) -> None:
  86. has_file = False
  87. with ZipFile(f'{job_id}.zip', 'w') as zw:
  88. for pattern in TYPE_PATTERNS_DICT[artifact_type]:
  89. for file in glob.glob(pattern, recursive=True):
  90. zw.write(file)
  91. has_file = True
  92. try:
  93. if has_file:
  94. obj_name = f'{pipeline_id}/{artifact_type.value}/{job_name.split(" ")[0]}/{job_id}.zip'
  95. print(f'Created archive file: {job_id}.zip, uploading as {obj_name}')
  96. client.fput_object(getenv('IDF_S3_BUCKET'), obj_name, f'{job_id}.zip')
  97. url = client.get_presigned_url('GET', getenv('IDF_S3_BUCKET'), obj_name)
  98. print(f'Please download the archive file which includes {artifact_type.value} from {url}')
  99. finally:
  100. os.remove(f'{job_id}.zip')
  101. if __name__ == '__main__':
  102. parser = argparse.ArgumentParser(
  103. description='Download or upload files from/to S3, the object name would be '
  104. '[PIPELINE_ID]/[ACTION_TYPE]/[JOB_NAME]/[JOB_ID].zip.'
  105. '\n'
  106. 'For example: 123456/binaries/build_pytest_examples_esp32/123456789.zip',
  107. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  108. )
  109. common_args = argparse.ArgumentParser(add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  110. common_args.add_argument('--pipeline-id', type=int, help='Pipeline ID')
  111. common_args.add_argument(
  112. '--type', type=str, nargs='+', choices=[a.value for a in ArtifactType], help='Types of files to download'
  113. )
  114. action = parser.add_subparsers(dest='action', help='Download or Upload')
  115. download = action.add_parser('download', help='Download files from S3', parents=[common_args])
  116. upload = action.add_parser('upload', help='Upload files to S3', parents=[common_args])
  117. download.add_argument('--job-name', type=str, help='Job name pattern')
  118. download.add_argument('--job-id', type=int, help='Job ID')
  119. upload.add_argument('--job-name', type=str, help='Job name')
  120. upload.add_argument('--job-id', type=int, help='Job ID')
  121. args = parser.parse_args()
  122. client = Minio(
  123. getenv('IDF_S3_SERVER').replace('https://', ''),
  124. access_key=getenv('IDF_S3_ACCESS_KEY'),
  125. secret_key=getenv('IDF_S3_SECRET_KEY'),
  126. http_client=urllib3.PoolManager(
  127. timeout=urllib3.Timeout.DEFAULT_TIMEOUT,
  128. retries=urllib3.Retry(
  129. total=5,
  130. backoff_factor=0.2,
  131. status_forcelist=[500, 502, 503, 504],
  132. ),
  133. ),
  134. )
  135. ci_pipeline_id = args.pipeline_id or getenv('CI_PIPELINE_ID') # required
  136. if args.action == 'download':
  137. method = _download_files
  138. ci_job_name = args.job_name # optional
  139. ci_job_id = args.job_id # optional
  140. else:
  141. method = _upload_files # type: ignore
  142. ci_job_name = args.job_name or getenv('CI_JOB_NAME') # required
  143. ci_job_id = args.job_id or getenv('CI_JOB_ID') # required
  144. if args.type:
  145. types = [ArtifactType(t) for t in args.type]
  146. else:
  147. types = list(ArtifactType)
  148. print(f'{"Pipeline ID":15}: {ci_pipeline_id}')
  149. if ci_job_name:
  150. print(f'{"Job name":15}: {ci_job_name}')
  151. if ci_job_id:
  152. print(f'{"Job ID":15}: {ci_job_id}')
  153. for _t in types:
  154. method(ci_pipeline_id, artifact_type=_t, job_name=ci_job_name, job_id=ci_job_id) # type: ignore