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