You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ImportGitLabProjectAction.java 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2023 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.server.almintegration.ws.gitlab;
  21. import java.util.Optional;
  22. import javax.annotation.Nullable;
  23. import javax.inject.Inject;
  24. import org.sonar.alm.client.gitlab.GitLabBranch;
  25. import org.sonar.alm.client.gitlab.GitlabHttpClient;
  26. import org.sonar.alm.client.gitlab.Project;
  27. import org.sonar.api.server.ws.Change;
  28. import org.sonar.api.server.ws.Request;
  29. import org.sonar.api.server.ws.Response;
  30. import org.sonar.api.server.ws.WebService;
  31. import org.sonar.db.DbClient;
  32. import org.sonar.db.DbSession;
  33. import org.sonar.db.alm.pat.AlmPatDto;
  34. import org.sonar.db.alm.setting.ALM;
  35. import org.sonar.db.alm.setting.AlmSettingDto;
  36. import org.sonar.db.alm.setting.ProjectAlmSettingDto;
  37. import org.sonar.db.component.BranchDto;
  38. import org.sonar.db.project.ProjectDto;
  39. import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
  40. import org.sonar.server.almintegration.ws.ImportHelper;
  41. import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
  42. import org.sonar.server.component.ComponentCreationData;
  43. import org.sonar.server.component.ComponentCreationParameters;
  44. import org.sonar.server.component.ComponentUpdater;
  45. import org.sonar.server.component.NewComponent;
  46. import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
  47. import org.sonar.server.project.DefaultBranchNameResolver;
  48. import org.sonar.server.project.ProjectDefaultVisibility;
  49. import org.sonar.server.user.UserSession;
  50. import org.sonarqube.ws.Projects.CreateWsResponse;
  51. import static java.util.Objects.requireNonNull;
  52. import static org.sonar.api.resources.Qualifiers.PROJECT;
  53. import static org.sonar.db.project.CreationMethod.Category.ALM_IMPORT;
  54. import static org.sonar.db.project.CreationMethod.getCreationMethod;
  55. import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
  56. import static org.sonar.server.component.NewComponent.newComponentBuilder;
  57. import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
  58. import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
  59. import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
  60. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  61. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
  62. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
  63. public class ImportGitLabProjectAction implements AlmIntegrationsWsAction {
  64. public static final String PARAM_GITLAB_PROJECT_ID = "gitlabProjectId";
  65. private final DbClient dbClient;
  66. private final UserSession userSession;
  67. private final ProjectDefaultVisibility projectDefaultVisibility;
  68. private final GitlabHttpClient gitlabHttpClient;
  69. private final ComponentUpdater componentUpdater;
  70. private final ImportHelper importHelper;
  71. private final ProjectKeyGenerator projectKeyGenerator;
  72. private final NewCodeDefinitionResolver newCodeDefinitionResolver;
  73. private final DefaultBranchNameResolver defaultBranchNameResolver;
  74. @Inject
  75. public ImportGitLabProjectAction(DbClient dbClient, UserSession userSession,
  76. ProjectDefaultVisibility projectDefaultVisibility, GitlabHttpClient gitlabHttpClient,
  77. ComponentUpdater componentUpdater, ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
  78. DefaultBranchNameResolver defaultBranchNameResolver) {
  79. this.dbClient = dbClient;
  80. this.userSession = userSession;
  81. this.projectDefaultVisibility = projectDefaultVisibility;
  82. this.gitlabHttpClient = gitlabHttpClient;
  83. this.componentUpdater = componentUpdater;
  84. this.importHelper = importHelper;
  85. this.projectKeyGenerator = projectKeyGenerator;
  86. this.newCodeDefinitionResolver = newCodeDefinitionResolver;
  87. this.defaultBranchNameResolver = defaultBranchNameResolver;
  88. }
  89. @Override
  90. public void define(WebService.NewController context) {
  91. WebService.NewAction action = context.createAction("import_gitlab_project")
  92. .setDescription("Import a GitLab project to SonarQube, creating a new project and configuring MR decoration<br/>" +
  93. "Requires the 'Create Projects' permission")
  94. .setPost(true)
  95. .setSince("8.5")
  96. .setHandler(this)
  97. .setChangelog(
  98. new Change("10.3", String.format("Parameter %s becomes optional if you have only one configuration for GitLab", PARAM_ALM_SETTING)));
  99. action.createParam(ImportHelper.PARAM_ALM_SETTING)
  100. .setDescription("DevOps Platform configuration key. This parameter is optional if you have only one GitLab integration.");
  101. action.createParam(PARAM_GITLAB_PROJECT_ID)
  102. .setRequired(true)
  103. .setDescription("GitLab project ID");
  104. action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
  105. .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
  106. .setSince("10.1");
  107. action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
  108. .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
  109. .setSince("10.1");
  110. }
  111. @Override
  112. public void handle(Request request, Response response) throws Exception {
  113. CreateWsResponse createResponse = doHandle(request);
  114. writeProtobuf(createResponse, request, response);
  115. }
  116. private CreateWsResponse doHandle(Request request) {
  117. importHelper.checkProvisionProjectPermission();
  118. String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
  119. String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
  120. try (DbSession dbSession = dbClient.openSession(false)) {
  121. AlmSettingDto almSettingDto = importHelper.getAlmSettingDtoForAlm(request, ALM.GITLAB);
  122. String pat = getPat(dbSession, almSettingDto);
  123. long gitlabProjectId = request.mandatoryParamAsLong(PARAM_GITLAB_PROJECT_ID);
  124. String gitlabUrl = requireNonNull(almSettingDto.getUrl(), "DevOps Platform gitlabUrl cannot be null");
  125. Project gitlabProject = gitlabHttpClient.getProject(gitlabUrl, pat, gitlabProjectId);
  126. Optional<String> almMainBranchName = getAlmDefaultBranch(pat, gitlabProjectId, gitlabUrl);
  127. ComponentCreationData componentCreationData = createProject(dbSession, gitlabProject, almMainBranchName.orElse(null));
  128. ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
  129. BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
  130. populateMRSetting(dbSession, gitlabProjectId, projectDto, almSettingDto);
  131. checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
  132. if (newCodeDefinitionType != null) {
  133. newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
  134. almMainBranchName.orElse(defaultBranchNameResolver.getEffectiveMainBranchName()), newCodeDefinitionType, newCodeDefinitionValue);
  135. }
  136. componentUpdater.commitAndIndex(dbSession, componentCreationData);
  137. return ImportHelper.toCreateResponse(projectDto);
  138. }
  139. }
  140. private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
  141. String userUuid = importHelper.getUserUuid();
  142. Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
  143. return almPatDto.map(AlmPatDto::getPersonalAccessToken)
  144. .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey())));
  145. }
  146. private Optional<String> getAlmDefaultBranch(String pat, long gitlabProjectId, String gitlabUrl) {
  147. Optional<GitLabBranch> almMainBranch = gitlabHttpClient.getBranches(gitlabUrl, pat, gitlabProjectId).stream().filter(GitLabBranch::isDefault).findFirst();
  148. return almMainBranch.map(GitLabBranch::getName);
  149. }
  150. private void populateMRSetting(DbSession dbSession, Long gitlabProjectId, ProjectDto projectDto, AlmSettingDto almSettingDto) {
  151. dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, new ProjectAlmSettingDto()
  152. .setProjectUuid(projectDto.getUuid())
  153. .setAlmSettingUuid(almSettingDto.getUuid())
  154. .setAlmRepo(gitlabProjectId.toString())
  155. .setAlmSlug(null)
  156. .setMonorepo(false),
  157. almSettingDto.getKey(),
  158. projectDto.getName(), projectDto.getKey());
  159. }
  160. private ComponentCreationData createProject(DbSession dbSession, Project gitlabProject, @Nullable String mainBranchName) {
  161. boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
  162. String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(gitlabProject.getPathWithNamespace());
  163. NewComponent newProject = newComponentBuilder()
  164. .setKey(uniqueProjectKey)
  165. .setName(gitlabProject.getName())
  166. .setPrivate(visibility)
  167. .setQualifier(PROJECT)
  168. .build();
  169. ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
  170. .newComponent(newProject)
  171. .userUuid(userSession.getUuid())
  172. .userLogin(userSession.getLogin())
  173. .mainBranchName(mainBranchName)
  174. .creationMethod(getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession()))
  175. .build();
  176. return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
  177. }
  178. }