]> source.dussan.org Git - sonarqube.git/blob
4f7b971c215d61046184dea36c171fb0da041ca3
[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.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.AlmSettingDto;
33 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
34 import org.sonar.db.component.BranchDto;
35 import org.sonar.db.project.ProjectDto;
36 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
37 import org.sonar.server.almintegration.ws.ImportHelper;
38 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
39 import org.sonar.server.component.ComponentCreationData;
40 import org.sonar.server.component.ComponentUpdater;
41 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
42 import org.sonar.server.project.DefaultBranchNameResolver;
43 import org.sonar.server.project.ProjectDefaultVisibility;
44 import org.sonar.server.user.UserSession;
45 import org.sonarqube.ws.Projects.CreateWsResponse;
46
47 import static java.util.Objects.requireNonNull;
48 import static org.sonar.api.resources.Qualifiers.PROJECT;
49 import static org.sonar.server.almintegration.ws.ImportHelper.PARAM_ALM_SETTING;
50 import static org.sonar.server.almintegration.ws.ImportHelper.toCreateResponse;
51 import static org.sonar.server.component.NewComponent.newComponentBuilder;
52 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
53 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
54 import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
55 import static org.sonar.server.ws.WsUtils.writeProtobuf;
56 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
57 import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
58
59 public class ImportAzureProjectAction implements AlmIntegrationsWsAction {
60
61   private static final String PARAM_REPOSITORY_NAME = "repositoryName";
62   private static final String PARAM_PROJECT_NAME = "projectName";
63
64   private final DbClient dbClient;
65   private final UserSession userSession;
66   private final AzureDevOpsHttpClient azureDevOpsHttpClient;
67   private final ProjectDefaultVisibility projectDefaultVisibility;
68   private final ComponentUpdater componentUpdater;
69   private final ImportHelper importHelper;
70   private final ProjectKeyGenerator projectKeyGenerator;
71   private final NewCodeDefinitionResolver newCodeDefinitionResolver;
72   private final DefaultBranchNameResolver defaultBranchNameResolver;
73
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
90   @Override
91   public void define(WebService.NewController context) {
92     WebService.NewAction action = context.createAction("import_azure_project")
93       .setDescription("Create a SonarQube project with the information from the provided Azure DevOps project.<br/>" +
94         "Autoconfigure pull request decoration mechanism.<br/>" +
95         "Requires the 'Create Projects' permission")
96       .setPost(true)
97       .setInternal(true)
98       .setSince("8.6")
99       .setHandler(this);
100
101     action.createParam(PARAM_ALM_SETTING)
102       .setRequired(true)
103       .setMaximumLength(200)
104       .setDescription("DevOps Platform setting key");
105
106     action.createParam(PARAM_PROJECT_NAME)
107       .setRequired(true)
108       .setMaximumLength(200)
109       .setDescription("Azure project name");
110
111     action.createParam(PARAM_REPOSITORY_NAME)
112       .setRequired(true)
113       .setMaximumLength(200)
114       .setDescription("Azure repository name");
115
116     action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
117       .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
118       .setSince("10.1");
119
120     action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
121       .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
122       .setSince("10.1");
123   }
124
125   @Override
126   public void handle(Request request, Response response) {
127     CreateWsResponse createResponse = doHandle(request);
128     writeProtobuf(createResponse, request, response);
129   }
130
131   private CreateWsResponse doHandle(Request request) {
132     importHelper.checkProvisionProjectPermission();
133     AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
134
135     String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
136     String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
137
138     try (DbSession dbSession = dbClient.openSession(false)) {
139
140       String pat = getPat(dbSession, almSettingDto);
141
142       String projectName = request.mandatoryParam(PARAM_PROJECT_NAME);
143       String repositoryName = request.mandatoryParam(PARAM_REPOSITORY_NAME);
144
145       String url = requireNonNull(almSettingDto.getUrl(), "DevOps Platform url cannot be null");
146       GsonAzureRepo repo = azureDevOpsHttpClient.getRepo(url, pat, projectName, repositoryName);
147
148       ComponentCreationData componentCreationData = createProject(dbSession, repo);
149       ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
150       BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
151       populatePRSetting(dbSession, repo, projectDto, almSettingDto);
152
153       checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
154
155       if (newCodeDefinitionType != null) {
156         newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
157           Optional.ofNullable(repo.getDefaultBranchName()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName()),
158           newCodeDefinitionType, newCodeDefinitionValue);
159       }
160
161       componentUpdater.commitAndIndex(dbSession, componentCreationData);
162
163       return toCreateResponse(projectDto);
164     }
165   }
166
167   private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
168     String userUuid = importHelper.getUserUuid();
169     Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
170     return almPatDto.map(AlmPatDto::getPersonalAccessToken)
171       .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey())));
172   }
173
174   private ComponentCreationData createProject(DbSession dbSession, GsonAzureRepo repo) {
175     boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
176     String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(repo.getProject().getName(), repo.getName());
177     return componentUpdater.createWithoutCommit(dbSession, newComponentBuilder()
178       .setKey(uniqueProjectKey)
179       .setName(repo.getName())
180       .setPrivate(visibility)
181       .setQualifier(PROJECT)
182       .build(),
183       userSession.isLoggedIn() ? userSession.getUuid() : null,
184       userSession.isLoggedIn() ? userSession.getLogin() : null,
185       repo.getDefaultBranchName());
186   }
187
188   private void populatePRSetting(DbSession dbSession, GsonAzureRepo repo, ProjectDto projectDto, AlmSettingDto almSettingDto) {
189     ProjectAlmSettingDto projectAlmSettingDto = new ProjectAlmSettingDto()
190       .setAlmSettingUuid(almSettingDto.getUuid())
191       .setAlmRepo(repo.getName())
192       .setAlmSlug(repo.getProject().getName())
193       .setProjectUuid(projectDto.getUuid())
194       .setMonorepo(false);
195     dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, projectAlmSettingDto, almSettingDto.getKey(),
196       projectDto.getName(), projectDto.getKey());
197   }
198
199 }