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.

ImportAzureProjectAction.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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.azure;
  21. import java.util.Optional;
  22. import javax.inject.Inject;
  23. import org.sonar.alm.client.azure.AzureDevOpsHttpClient;
  24. import org.sonar.alm.client.azure.GsonAzureRepo;
  25. import org.sonar.api.server.ws.Change;
  26. import org.sonar.api.server.ws.Request;
  27. import org.sonar.api.server.ws.Response;
  28. import org.sonar.api.server.ws.WebService;
  29. import org.sonar.db.DbClient;
  30. import org.sonar.db.DbSession;
  31. import org.sonar.db.alm.pat.AlmPatDto;
  32. import org.sonar.db.alm.setting.ALM;
  33. import org.sonar.db.alm.setting.AlmSettingDto;
  34. import org.sonar.db.alm.setting.ProjectAlmSettingDto;
  35. import org.sonar.db.component.BranchDto;
  36. import org.sonar.db.project.ProjectDto;
  37. import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
  38. import org.sonar.server.almintegration.ws.ImportHelper;
  39. import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
  40. import org.sonar.server.component.ComponentCreationData;
  41. import org.sonar.server.component.ComponentCreationParameters;
  42. import org.sonar.server.component.ComponentUpdater;
  43. import org.sonar.server.component.NewComponent;
  44. import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
  45. import org.sonar.server.project.DefaultBranchNameResolver;
  46. import org.sonar.server.project.ProjectDefaultVisibility;
  47. import org.sonar.server.user.UserSession;
  48. import org.sonarqube.ws.Projects.CreateWsResponse;
  49. import static java.util.Objects.requireNonNull;
  50. import static org.sonar.api.resources.Qualifiers.PROJECT;
  51. import static org.sonar.db.project.CreationMethod.Category.ALM_IMPORT;
  52. import static org.sonar.db.project.CreationMethod.getCreationMethod;
  53. import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
  54. import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
  55. import static org.sonar.server.component.NewComponent.newComponentBuilder;
  56. import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
  57. import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
  58. import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
  59. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  60. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
  61. import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
  62. public class ImportAzureProjectAction implements AlmIntegrationsWsAction {
  63. private static final String PARAM_REPOSITORY_NAME = "repositoryName";
  64. private static final String PARAM_PROJECT_NAME = "projectName";
  65. private final DbClient dbClient;
  66. private final UserSession userSession;
  67. private final AzureDevOpsHttpClient azureDevOpsHttpClient;
  68. private final ProjectDefaultVisibility projectDefaultVisibility;
  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 ImportAzureProjectAction(DbClient dbClient, UserSession userSession, AzureDevOpsHttpClient azureDevOpsHttpClient,
  76. ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater,
  77. ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
  78. DefaultBranchNameResolver defaultBranchNameResolver) {
  79. this.dbClient = dbClient;
  80. this.userSession = userSession;
  81. this.azureDevOpsHttpClient = azureDevOpsHttpClient;
  82. this.projectDefaultVisibility = projectDefaultVisibility;
  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_azure_project")
  92. .setDescription("Create a SonarQube project with the information from the provided Azure DevOps project.<br/>" +
  93. "Autoconfigure pull request decoration mechanism.<br/>" +
  94. "Requires the 'Create Projects' permission")
  95. .setPost(true)
  96. .setSince("8.6")
  97. .setHandler(this)
  98. .setChangelog(
  99. new Change("10.3", String.format("Parameter %s becomes optional if you have only one configuration for Azure", PARAM_ALM_SETTING)),
  100. new Change("10.3", "Endpoint visibility change from internal to public"));
  101. action.createParam(PARAM_ALM_SETTING)
  102. .setMaximumLength(200)
  103. .setDescription("DevOps Platform configuration key. This parameter is optional if you have only one Azure integration.");
  104. action.createParam(PARAM_PROJECT_NAME)
  105. .setRequired(true)
  106. .setMaximumLength(200)
  107. .setDescription("Azure project name");
  108. action.createParam(PARAM_REPOSITORY_NAME)
  109. .setRequired(true)
  110. .setMaximumLength(200)
  111. .setDescription("Azure repository name");
  112. action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
  113. .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
  114. .setSince("10.1");
  115. action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
  116. .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
  117. .setSince("10.1");
  118. }
  119. @Override
  120. public void handle(Request request, Response response) {
  121. CreateWsResponse createResponse = doHandle(request);
  122. writeProtobuf(createResponse, request, response);
  123. }
  124. private CreateWsResponse doHandle(Request request) {
  125. importHelper.checkProvisionProjectPermission();
  126. AlmSettingDto almSettingDto = importHelper.getAlmSettingDtoForAlm(request, ALM.AZURE_DEVOPS);
  127. String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
  128. String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
  129. try (DbSession dbSession = dbClient.openSession(false)) {
  130. String pat = getPat(dbSession, almSettingDto);
  131. String projectName = request.mandatoryParam(PARAM_PROJECT_NAME);
  132. String repositoryName = request.mandatoryParam(PARAM_REPOSITORY_NAME);
  133. String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
  134. GsonAzureRepo repo = azureDevOpsHttpClient.getRepo(url, pat, projectName, repositoryName);
  135. ComponentCreationData componentCreationData = createProject(dbSession, repo);
  136. ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
  137. BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
  138. populatePRSetting(dbSession, repo, projectDto, almSettingDto);
  139. checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
  140. if (newCodeDefinitionType != null) {
  141. newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
  142. Optional.ofNullable(repo.getDefaultBranchName()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
  143. newCodeDefinitionType, newCodeDefinitionValue);
  144. }
  145. componentUpdater.commitAndIndex(dbSession, componentCreationData);
  146. return toCreateResponse(projectDto);
  147. }
  148. }
  149. private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
  150. String userUuid = importHelper.getUserUuid();
  151. Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
  152. return almPatDto.map(AlmPatDto::getPersonalAccessToken)
  153. .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey())));
  154. }
  155. private ComponentCreationData createProject(DbSession dbSession, GsonAzureRepo repo) {
  156. boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
  157. String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getName(), repo.getName());
  158. NewComponent newProject = newComponentBuilder()
  159. .setKey(uniqueProjectKey)
  160. .setName(repo.getName())
  161. .setPrivate(visibility)
  162. .setQualifier(PROJECT)
  163. .build();
  164. ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
  165. .newComponent(newProject)
  166. .userUuid(userSession.getUuid())
  167. .userLogin(userSession.getLogin())
  168. .mainBranchName(repo.getDefaultBranchName())
  169. .creationMethod(getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession()))
  170. .build();
  171. return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
  172. }
  173. private void populatePRSetting(DbSession dbSession, GsonAzureRepo repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
  174. ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
  175. .setAlmSettingUuid(almSettingDto.getUuid())
  176. .setAlmRepo(repo.getName())
  177. .setAlmSlug(repo.getProject().getName())
  178. .setProjectUuid(projectDto.getUuid())
  179. .setMonorepo(false);
  180. dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
  181. projectDto.getName(), projectDto.getKey());
  182. }
  183. }