gitlab_api.py 7.0 KB

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