gitlab_api.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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):
  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. :return: a list of job IDs (parallel job will generate multiple jobs)
  89. """
  90. job_id_list = []
  91. if pipeline_id is None:
  92. pipeline_id = os.getenv("CI_PIPELINE_ID")
  93. pipeline = self.project.pipelines.get(pipeline_id)
  94. jobs = pipeline.jobs.list(all=True)
  95. for job in jobs:
  96. match = self.JOB_NAME_PATTERN.match(job.name)
  97. if match:
  98. if match.group(1) == job_name:
  99. job_id_list.append({"id": job.id, "parallel_num": match.group(3)})
  100. return job_id_list
  101. def download_archive(self, ref, destination, project_id=None):
  102. """
  103. Download archive of certain commit of a repository and extract to destination path
  104. :param ref: commit or branch name
  105. :param destination: destination path of extracted archive file
  106. :param project_id: download project of current instance if project_id is None
  107. :return: root path name of archive file
  108. """
  109. if project_id is None:
  110. project = self.project
  111. else:
  112. project = self.gitlab_inst.projects.get(project_id)
  113. with tempfile.NamedTemporaryFile(delete=False) as temp_file:
  114. try:
  115. project.repository_archive(sha=ref, streamed=True, action=temp_file.write)
  116. except gitlab.GitlabGetError as e:
  117. print("Failed to archive from project {}".format(project_id))
  118. raise e
  119. print("archive size: {:.03f}MB".format(float(os.path.getsize(temp_file.name)) / (1024 * 1024)))
  120. with tarfile.open(temp_file.name, "r") as archive_file:
  121. root_name = archive_file.getnames()[0]
  122. archive_file.extractall(destination)
  123. return os.path.join(os.path.realpath(destination), root_name)
  124. if __name__ == '__main__':
  125. parser = argparse.ArgumentParser()
  126. parser.add_argument("action")
  127. parser.add_argument("project_id", type=int)
  128. parser.add_argument("--pipeline_id", "-i", type=int, default=None)
  129. parser.add_argument("--ref", "-r", default="master")
  130. parser.add_argument("--job_id", "-j", type=int, default=None)
  131. parser.add_argument("--job_name", "-n", default=None)
  132. parser.add_argument("--project_name", "-m", default=None)
  133. parser.add_argument("--destination", "-d", default=None)
  134. parser.add_argument("--artifact_path", "-a", nargs="*", default=None)
  135. args = parser.parse_args()
  136. gitlab_inst = Gitlab(args.project_id)
  137. if args.action == "download_artifacts":
  138. gitlab_inst.download_artifacts(args.job_id, args.destination)
  139. if args.action == "download_artifact":
  140. gitlab_inst.download_artifact(args.job_id, args.artifact_path, args.destination)
  141. elif args.action == "find_job_id":
  142. job_ids = gitlab_inst.find_job_id(args.job_name, args.pipeline_id)
  143. print(";".join([",".join([str(j["id"]), j["parallel_num"]]) for j in job_ids]))
  144. elif args.action == "download_archive":
  145. gitlab_inst.download_archive(args.ref, args.destination)
  146. elif args.action == "get_project_id":
  147. ret = gitlab_inst.get_project_id(args.project_name)
  148. print("project id: {}".format(ret))