]> source.dussan.org Git - sonarqube.git/blob
31f371d5bcdf017b6860c768dcebcd257a79daf7
[sonarqube.git] /
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
22 import java.util.Optional;
23 import javax.inject.Inject;
24 import org.sonar.alm.client.azure.AzureDevOpsHttpClient;
25 import org.sonar.alm.client.azure.GsonAzureRepo;
26 import org.sonar.api.server.ws.Change;
27 import org.sonar.api.server.ws.Request;
28 import org.sonar.api.server.ws.Response;
29 import org.sonar.api.server.ws.WebService;
30 import org.sonar.db.DbClient;
31 import org.sonar.db.DbSession;
32 import org.sonar.db.alm.pat.AlmPatDto;
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
50 import static java.util.Objects.requireNonNull;
51 import static org.sonar.api.resources.Qualifiers.PROJECT;
52 import static org.sonar.db.project.CreationMethod.Category.ALM_IMPORT;
53 import static org.sonar.db.project.CreationMethod.getCreationMethod;
54 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
55 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
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
64 public class ImportAzureProjectAction implements AlmIntegrationsWsAction {
65
66   private static final String PARAM_REPOSITORY_NAME = "repositoryName";
67   private static final String PARAM_PROJECT_NAME = "projectName";
68
69   private final DbClient dbClient;
70   private final UserSession userSession;
71   private final AzureDevOpsHttpClient azureDevOpsHttpClient;
72   private final ProjectDefaultVisibility projectDefaultVisibility;
73   private final ComponentUpdater componentUpdater;
74   private final ImportHelper importHelper;
75   private final ProjectKeyGenerator projectKeyGenerator;
76   private final NewCodeDefinitionResolver newCodeDefinitionResolver;
77   private final DefaultBranchNameResolver defaultBranchNameResolver;
78
79   @Inject
80   public ImportAzureProjectAction(DbClient dbClient, UserSession userSession, AzureDevOpsHttpClient azureDevOpsHttpClient,
81     ProjectDefaultVisibility projectDefaultVisibility, ComponentUpdater componentUpdater,
82     ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
83     DefaultBranchNameResolver defaultBranchNameResolver) {
84     this.dbClient = dbClient;
85     this.userSession = userSession;
86     this.azureDevOpsHttpClient = azureDevOpsHttpClient;
87     this.projectDefaultVisibility = projectDefaultVisibility;
88     this.componentUpdater = componentUpdater;
89     this.importHelper = importHelper;
90     this.projectKeyGenerator = projectKeyGenerator;
91     this.newCodeDefinitionResolver = newCodeDefinitionResolver;
92     this.defaultBranchNameResolver = defaultBranchNameResolver;
93   }
94
95   @Override
96   public void define(WebService.NewController context) {
97     WebService.NewAction action = context.createAction("import_azure_project")
98       .setDescription("Create a SonarQube project with the information from the provided Azure DevOps project.<br/>" +
99         "Autoconfigure pull request decoration mechanism.<br/>" +
100         "Requires the 'Create Projects' permission")
101       .setPost(true)
102       .setSince("8.6")
103       .setHandler(this)
104       .setChangelog(
105         new Change("10.3", "Endpoint visibility change from internal to public"));
106
107     action.createParam(PARAM_ALM_SETTING)
108       .setRequired(true)
109       .setMaximumLength(200)
110       .setDescription("DevOps Platform setting key");
111
112     action.createParam(PARAM_PROJECT_NAME)
113       .setRequired(true)
114       .setMaximumLength(200)
115       .setDescription("Azure project name");
116
117     action.createParam(PARAM_REPOSITORY_NAME)
118       .setRequired(true)
119       .setMaximumLength(200)
120       .setDescription("Azure repository name");
121
122     action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
123       .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
124       .setSince("10.1");
125
126     action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
127       .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
128       .setSince("10.1");
129   }
130
131   @Override
132   public void handle(Request request, Response response) {
133     CreateWsResponse createResponse = doHandle(request);
134     writeProtobuf(createResponse, request, response);
135   }
136
137   private CreateWsResponse doHandle(Request request) {
138     importHelper.checkProvisionProjectPermission();
139     AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
140
141     String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
142     String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
143
144     try (DbSession dbSession = dbClient.openSession(false)) {
145
146       String pat = getPat(dbSession, almSettingDto);
147
148       String projectName = request.mandatoryParam(PARAM_PROJECT_NAME);
149       String repositoryName = request.mandatoryParam(PARAM_REPOSITORY_NAME);
150
151       String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
152       GsonAzureRepo repo = azureDevOpsHttpClient.getRepo(url, pat, projectName, repositoryName);
153
154       ComponentCreationData componentCreationData = createProject(dbSession, repo);
155       ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
156       BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
157       populatePRSetting(dbSession, repo, projectDto, almSettingDto);
158
159       checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
160
161       if (newCodeDefinitionType != null) {
162         newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
163           Optional.ofNullable(repo.getDefaultBranchName()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
164           newCodeDefinitionType, newCodeDefinitionValue);
165       }
166
167       componentUpdater.commitAndIndex(dbSession, componentCreationData);
168
169       return toCreateResponse(projectDto);
170     }
171   }
172
173   private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
174     String userUuid = importHelper.getUserUuid();
175     Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
176     return almPatDto.map(AlmPatDto::getPersonalAccessToken)
177       .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey())));
178   }
179
180   private ComponentCreationData createProject(DbSession dbSession, GsonAzureRepo repo) {
181     boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
182     String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getName(), repo.getName());
183     NewComponent newProject = newComponentBuilder()
184       .setKey(uniqueProjectKey)
185       .setName(repo.getName())
186       .setPrivate(visibility)
187       .setQualifier(PROJECT)
188       .build();
189     ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
190       .newComponent(newProject)
191       .userUuid(userSession.getUuid())
192       .userLogin(userSession.getLogin())
193       .mainBranchName(repo.getDefaultBranchName())
194       .creationMethod(getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession()))
195       .build();
196     return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
197   }
198
199   private void populatePRSetting(DbSession dbSession, GsonAzureRepo repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
200     ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
201       .setAlmSettingUuid(almSettingDto.getUuid())
202       .setAlmRepo(repo.getName())
203       .setAlmSlug(repo.getProject().getName())
204       .setProjectUuid(projectDto.getUuid())
205       .setMonorepo(false);
206     dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
207       projectDto.getName(), projectDto.getKey());
208   }
209
210 }