gitlab_api.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. import argparse
  2. import os
  3. import re
  4. import tarfile
  5. import tempfile
  6. import time
  7. import zipfile
  8. from functools import wraps
  9. from typing import Any, Callable, Dict, List, Optional
  10. import gitlab
  11. TR = Callable[..., Any]
  12. def retry(func: TR) -> TR:
  13. """
  14. This wrapper will only catch several exception types associated with
  15. "network issues" and retry the whole function.
  16. """
  17. @wraps(func)
  18. def wrapper(self: 'Gitlab', *args: Any, **kwargs: Any) -> Any:
  19. retried = 0
  20. while True:
  21. try:
  22. res = func(self, *args, **kwargs)
  23. except (IOError, EOFError, gitlab.exceptions.GitlabError) as e:
  24. if isinstance(e, gitlab.exceptions.GitlabError):
  25. if e.response_code == 500:
  26. # retry on this error
  27. pass
  28. elif e.response_code == 404 and os.environ.get('LOCAL_GITLAB_HTTPS_HOST', None):
  29. # remove the environment variable "LOCAL_GITLAB_HTTPS_HOST" and retry
  30. os.environ.pop('LOCAL_GITLAB_HTTPS_HOST', None)
  31. else:
  32. # other GitlabErrors aren't retried
  33. raise e
  34. retried += 1
  35. if retried > self.DOWNLOAD_ERROR_MAX_RETRIES:
  36. raise e # get out of the loop
  37. else:
  38. print('Network failure in {}, retrying ({})'.format(getattr(func, '__name__', '(unknown callable)'), retried))
  39. time.sleep(2 ** retried) # wait a bit more after each retry
  40. continue
  41. else:
  42. break
  43. return res
  44. return wrapper
  45. class Gitlab(object):
  46. JOB_NAME_PATTERN = re.compile(r'(\w+)(\s+(\d+)/(\d+))?')
  47. DOWNLOAD_ERROR_MAX_RETRIES = 3
  48. def __init__(self, project_id: Optional[int] = None):
  49. config_data_from_env = os.getenv('PYTHON_GITLAB_CONFIG')
  50. if config_data_from_env:
  51. # prefer to load config from env variable
  52. with tempfile.NamedTemporaryFile('w', delete=False) as temp_file:
  53. temp_file.write(config_data_from_env)
  54. config_files = [temp_file.name] # type: Optional[List[str]]
  55. else:
  56. # otherwise try to use config file at local filesystem
  57. config_files = None
  58. self._init_gitlab_inst(project_id, config_files)
  59. @retry
  60. def _init_gitlab_inst(self, project_id: Optional[int], config_files: Optional[List[str]]) -> None:
  61. gitlab_id = os.getenv('LOCAL_GITLAB_HTTPS_HOST') # if None, will use the default gitlab server
  62. self.gitlab_inst = gitlab.Gitlab.from_config(gitlab_id=gitlab_id, config_files=config_files)
  63. self.gitlab_inst.auth()
  64. if project_id:
  65. self.project = self.gitlab_inst.projects.get(project_id)
  66. else:
  67. self.project = None
  68. @retry
  69. def get_project_id(self, name: str, namespace: Optional[str] = None) -> int:
  70. """
  71. search project ID by name
  72. :param name: project name
  73. :param namespace: namespace to match when we have multiple project with same name
  74. :return: project ID
  75. """
  76. projects = self.gitlab_inst.projects.list(search=name)
  77. res = []
  78. for project in projects:
  79. if namespace is None:
  80. if len(projects) == 1:
  81. res.append(project.id)
  82. break
  83. if project.namespace['path'] == namespace:
  84. if project.name == name:
  85. res.insert(0, project.id)
  86. else:
  87. res.append(project.id)
  88. if not res:
  89. raise ValueError("Can't find project")
  90. return int(res[0])
  91. @retry
  92. def download_artifacts(self, job_id: int, destination: str) -> None:
  93. """
  94. download full job artifacts and extract to destination.
  95. :param job_id: Gitlab CI job ID
  96. :param destination: extract artifacts to path.
  97. """
  98. job = self.project.jobs.get(job_id)
  99. with tempfile.NamedTemporaryFile(delete=False) as temp_file:
  100. job.artifacts(streamed=True, action=temp_file.write)
  101. with zipfile.ZipFile(temp_file.name, 'r') as archive_file:
  102. archive_file.extractall(destination)
  103. @retry
  104. def download_artifact(self, job_id: int, artifact_path: str, destination: Optional[str] = None) -> List[bytes]:
  105. """
  106. download specific path of job artifacts and extract to destination.
  107. :param job_id: Gitlab CI job ID
  108. :param artifact_path: list of path in artifacts (relative path to artifact root path)
  109. :param destination: destination of artifact. Do not save to file if destination is None
  110. :return: A list of artifact file raw data.
  111. """
  112. job = self.project.jobs.get(job_id)
  113. raw_data_list = []
  114. for a_path in artifact_path:
  115. try:
  116. data = job.artifact(a_path) # type: bytes
  117. except gitlab.GitlabGetError as e:
  118. print("Failed to download '{}' from job {}".format(a_path, job_id))
  119. raise e
  120. raw_data_list.append(data)
  121. if destination:
  122. file_path = os.path.join(destination, a_path)
  123. try:
  124. os.makedirs(os.path.dirname(file_path))
  125. except OSError:
  126. # already exists
  127. pass
  128. with open(file_path, 'wb') as f:
  129. f.write(data)
  130. return raw_data_list
  131. @retry
  132. def find_job_id(self, job_name: str, pipeline_id: Optional[str] = None, job_status: str = 'success') -> List[Dict]:
  133. """
  134. Get Job ID from job name of specific pipeline
  135. :param job_name: job name
  136. :param pipeline_id: If None, will get pipeline id from CI pre-defined variable.
  137. :param job_status: status of job. One pipeline could have multiple jobs with same name after retry.
  138. job_status is used to filter these jobs.
  139. :return: a list of job IDs (parallel job will generate multiple jobs)
  140. """
  141. job_id_list = []
  142. if pipeline_id is None:
  143. pipeline_id = os.getenv('CI_PIPELINE_ID')
  144. pipeline = self.project.pipelines.get(pipeline_id)
  145. jobs = pipeline.jobs.list(all=True)
  146. for job in jobs:
  147. match = self.JOB_NAME_PATTERN.match(job.name)
  148. if match:
  149. if match.group(1) == job_name and job.status == job_status:
  150. job_id_list.append({'id': job.id, 'parallel_num': match.group(3)})
  151. return job_id_list
  152. @retry
  153. def download_archive(self, ref: str, destination: str, project_id: Optional[int] = None) -> str:
  154. """
  155. Download archive of certain commit of a repository and extract to destination path
  156. :param ref: commit or branch name
  157. :param destination: destination path of extracted archive file
  158. :param project_id: download project of current instance if project_id is None
  159. :return: root path name of archive file
  160. """
  161. if project_id is None:
  162. project = self.project
  163. else:
  164. project = self.gitlab_inst.projects.get(project_id)
  165. with tempfile.NamedTemporaryFile(delete=False) as temp_file:
  166. try:
  167. project.repository_archive(sha=ref, streamed=True, action=temp_file.write)
  168. except gitlab.GitlabGetError as e:
  169. print('Failed to archive from project {}'.format(project_id))
  170. raise e
  171. print('archive size: {:.03f}MB'.format(float(os.path.getsize(temp_file.name)) / (1024 * 1024)))
  172. with tarfile.open(temp_file.name, 'r') as archive_file:
  173. root_name = archive_file.getnames()[0]
  174. archive_file.extractall(destination)
  175. return os.path.join(os.path.realpath(destination), root_name)
  176. def get_job_tags(self, job_id: int) -> str:
  177. """
  178. Get tags of a job
  179. :param job_id: job id
  180. :return: comma-separated tags of the job
  181. """
  182. job = self.project.jobs.get(job_id)
  183. return ','.join(job.tag_list)
  184. def main() -> None:
  185. parser = argparse.ArgumentParser()
  186. parser.add_argument('action')
  187. parser.add_argument('project_id', type=int)
  188. parser.add_argument('--pipeline_id', '-i', type=int, default=None)
  189. parser.add_argument('--ref', '-r', default='master')
  190. parser.add_argument('--job_id', '-j', type=int, default=None)
  191. parser.add_argument('--job_name', '-n', default=None)
  192. parser.add_argument('--project_name', '-m', default=None)
  193. parser.add_argument('--destination', '-d', default=None)
  194. parser.add_argument('--artifact_path', '-a', nargs='*', default=None)
  195. args = parser.parse_args()
  196. gitlab_inst = Gitlab(args.project_id)
  197. if args.action == 'download_artifacts':
  198. gitlab_inst.download_artifacts(args.job_id, args.destination)
  199. if args.action == 'download_artifact':
  200. gitlab_inst.download_artifact(args.job_id, args.artifact_path, args.destination)
  201. elif args.action == 'find_job_id':
  202. job_ids = gitlab_inst.find_job_id(args.job_name, args.pipeline_id)
  203. print(';'.join([','.join([str(j['id']), j['parallel_num']]) for j in job_ids]))
  204. elif args.action == 'download_archive':
  205. gitlab_inst.download_archive(args.ref, args.destination)
  206. elif args.action == 'get_project_id':
  207. ret = gitlab_inst.get_project_id(args.project_name)
  208. print('project id: {}'.format(ret))
  209. elif args.action == 'get_job_tags':
  210. ret = gitlab_inst.get_job_tags(args.job_id)
  211. print(ret)
  212. if __name__ == '__main__':
  213. main()