gitlab_api.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import os
  2. import re
  3. import argparse
  4. import tempfile
  5. import tarfile
  6. import zipfile
  7. import gitlab
  8. class Gitlab(object):
  9. JOB_NAME_PATTERN = re.compile(r"(\w+)(\s+(\d+)/(\d+))?")
  10. def __init__(self, project_id=None):
  11. config_data_from_env = os.getenv("PYTHON_GITLAB_CONFIG")
  12. if config_data_from_env:
  13. # prefer to load config from env variable
  14. with tempfile.NamedTemporaryFile("w", delete=False) as temp_file:
  15. temp_file.write(config_data_from_env)
  16. config_files = [temp_file.name]
  17. else:
  18. # otherwise try to use config file at local filesystem
  19. config_files = None
  20. self.gitlab_inst = gitlab.Gitlab.from_config(config_files=config_files)
  21. self.gitlab_inst.auth()
  22. if project_id:
  23. self.project = self.gitlab_inst.projects.get(project_id)
  24. else:
  25. self.project = None
  26. def get_project_id(self, name, namespace=None):
  27. """
  28. search project ID by name
  29. :param name: project name
  30. :param namespace: namespace to match when we have multiple project with same name
  31. :return: project ID
  32. """
  33. projects = self.gitlab_inst.projects.list(search=name)
  34. for project in projects:
  35. if namespace is None:
  36. if len(projects) == 1:
  37. project_id = project.id
  38. break
  39. if project.namespace["path"] == namespace:
  40. project_id = project.id
  41. break
  42. else:
  43. raise ValueError("Can't find project")
  44. return project_id
  45. def download_artifacts(self, job_id, destination):
  46. """
  47. download full job artifacts and extract to destination.
  48. :param job_id: Gitlab CI job ID
  49. :param destination: extract artifacts to path.
  50. """
  51. job = self.project.jobs.get(job_id)
  52. with tempfile.NamedTemporaryFile(delete=False) as temp_file:
  53. job.artifacts(streamed=True, action=temp_file.write)
  54. with zipfile.ZipFile(temp_file.name, "r") as archive_file:
  55. archive_file.extractall(destination)
  56. def download_artifact(self, job_id, artifact_path, destination=None):
  57. """
  58. download specific path of job artifacts and extract to destination.
  59. :param job_id: Gitlab CI job ID
  60. :param artifact_path: list of path in artifacts (relative path to artifact root path)
  61. :param destination: destination of artifact. Do not save to file if destination is None
  62. :return: A list of artifact file raw data.
  63. """
  64. job = self.project.jobs.get(job_id)
  65. raw_data_list = []
  66. for a_path in artifact_path:
  67. try:
  68. data = job.artifact(a_path)
  69. except gitlab.GitlabGetError as e:
  70. print("Failed to download '{}' form job {}".format(a_path, job_id))
  71. raise e
  72. raw_data_list.append(data)
  73. if destination:
  74. file_path = os.path.join(destination, a_path)
  75. try:
  76. os.makedirs(os.path.dirname(file_path))
  77. except OSError:
  78. # already exists
  79. pass
  80. with open(file_path, "wb") as f:
  81. f.write(data)
  82. return raw_data_list
  83. def find_job_id(self, job_name, pipeline_id=None, job_status="success"):
  84. """
  85. Get Job ID from job name of specific pipeline
  86. :param job_name: job name
  87. :param pipeline_id: If None, will get pipeline id from CI pre-defined variable.
  88. :param job_status: status of job. One pipeline could have multiple jobs with same name after retry.
  89. job_status is used to filter these jobs.
  90. :return: a list of job IDs (parallel job will generate multiple jobs)
  91. """
  92. job_id_list = []
  93. if pipeline_id is None:
  94. pipeline_id = os.getenv("CI_PIPELINE_ID")
  95. pipeline = self.project.pipelines.get(pipeline_id)
  96. jobs = pipeline.jobs.list(all=True)
  97. for job in jobs:
  98. match = self.JOB_NAME_PATTERN.match(job.name)
  99. if match:
  100. if match.group(1) == job_name and job.status == job_status:
  101. job_id_list.append({"id": job.id, "parallel_num": match.group(3)})
  102. return job_id_list
  103. def download_archive(self, ref, destination, project_id=None):
  104. """
  105. Download archive of certain commit of a repository and extract to destination path
  106. :param ref: commit or branch name
  107. :param destination: destination path of extracted archive file
  108. :param project_id: download project of current instance if project_id is None
  109. :return: root path name of archive file
  110. """
  111. if project_id is None:
  112. project = self.project
  113. else:
  114. project = self.gitlab_inst.projects.get(project_id)
  115. with tempfile.NamedTemporaryFile(delete=False) as temp_file:
  116. try:
  117. project.repository_archive(sha=ref, streamed=True, action=temp_file.write)
  118. except gitlab.GitlabGetError as e:
  119. print("Failed to archive from project {}".format(project_id))
  120. raise e
  121. print("archive size: {:.03f}MB".format(float(os.path.getsize(temp_file.name)) / (1024 * 1024)))
  122. with tarfile.open(temp_file.name, "r") as archive_file:
  123. root_name = archive_file.getnames()[0]
  124. archive_file.extractall(destination)
  125. return os.path.join(os.path.realpath(destination), root_name)
  126. if __name__ == '__main__':
  127. parser = argparse.ArgumentParser()
  128. parser.add_argument("action")
  129. parser.add_argument("project_id", type=int)
  130. parser.add_argument("--pipeline_id", "-i", type=int, default=None)
  131. parser.add_argument("--ref", "-r", default="master")
  132. parser.add_argument("--job_id", "-j", type=int, default=None)
  133. parser.add_argument("--job_name", "-n", default=None)
  134. parser.add_argument("--project_name", "-m", default=None)
  135. parser.add_argument("--destination", "-d", default=None)
  136. parser.add_argument("--artifact_path", "-a", nargs="*", default=None)
  137. args = parser.parse_args()
  138. gitlab_inst = Gitlab(args.project_id)
  139. if args.action == "download_artifacts":
  140. gitlab_inst.download_artifacts(args.job_id, args.destination)
  141. if args.action == "download_artifact":
  142. gitlab_inst.download_artifact(args.job_id, args.artifact_path, args.destination)
  143. elif args.action == "find_job_id":
  144. job_ids = gitlab_inst.find_job_id(args.job_name, args.pipeline_id)
  145. print(";".join([",".join([str(j["id"]), j["parallel_num"]]) for j in job_ids]))
  146. elif args.action == "download_archive":
  147. gitlab_inst.download_archive(args.ref, args.destination)
  148. elif args.action == "get_project_id":
  149. ret = gitlab_inst.get_project_id(args.project_name)
  150. print("project id: {}".format(ret))