]> source.dussan.org Git - sonarqube.git/blob
e3155575f716990e0d2894b0a0daf6000315b631
[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.gitlab;
21
22 import java.util.Optional;
23 import javax.annotation.Nullable;
24 import javax.inject.Inject;
25 import org.sonar.alm.client.gitlab.GitLabBranch;
26 import org.sonar.alm.client.gitlab.GitlabHttpClient;
27 import org.sonar.alm.client.gitlab.Project;
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.AlmSettingDto;
35 import org.sonar.db.alm.setting.ProjectAlmSettingDto;
36 import org.sonar.db.component.BranchDto;
37 import org.sonar.db.project.ProjectDto;
38 import org.sonar.server.almintegration.ws.AlmIntegrationsWsAction;
39 import org.sonar.server.almintegration.ws.ImportHelper;
40 import org.sonar.server.almintegration.ws.ProjectKeyGenerator;
41 import org.sonar.server.component.ComponentCreationData;
42 import org.sonar.server.component.ComponentCreationParameters;
43 import org.sonar.server.component.ComponentUpdater;
44 import org.sonar.server.component.NewComponent;
45 import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
46 import org.sonar.server.project.DefaultBranchNameResolver;
47 import org.sonar.server.project.ProjectDefaultVisibility;
48 import org.sonar.server.user.UserSession;
49 import org.sonarqube.ws.Projects.CreateWsResponse;
50
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.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
63 public class ImportGitLabProjectAction implements AlmIntegrationsWsAction {
64
65   public static final String PARAM_GITLAB_PROJECT_ID = "gitlabProjectId";
66
67   private final DbClient dbClient;
68   private final UserSession userSession;
69   private final ProjectDefaultVisibility projectDefaultVisibility;
70   private final GitlabHttpClient gitlabHttpClient;
71   private final ComponentUpdater componentUpdater;
72   private final ImportHelper importHelper;
73   private final ProjectKeyGenerator projectKeyGenerator;
74   private final NewCodeDefinitionResolver newCodeDefinitionResolver;
75   private final DefaultBranchNameResolver defaultBranchNameResolver;
76
77   @Inject
78   public ImportGitLabProjectAction(DbClient dbClient, UserSession userSession,
79     ProjectDefaultVisibility projectDefaultVisibility, GitlabHttpClient gitlabHttpClient,
80     ComponentUpdater componentUpdater, ImportHelper importHelper, ProjectKeyGenerator projectKeyGenerator, NewCodeDefinitionResolver newCodeDefinitionResolver,
81     DefaultBranchNameResolver defaultBranchNameResolver) {
82     this.dbClient = dbClient;
83     this.userSession = userSession;
84     this.projectDefaultVisibility = projectDefaultVisibility;
85     this.gitlabHttpClient = gitlabHttpClient;
86     this.componentUpdater = componentUpdater;
87     this.importHelper = importHelper;
88     this.projectKeyGenerator = projectKeyGenerator;
89     this.newCodeDefinitionResolver = newCodeDefinitionResolver;
90     this.defaultBranchNameResolver = defaultBranchNameResolver;
91   }
92
93   @Override
94   public void define(WebService.NewController context) {
95     WebService.NewAction action = context.createAction("import_gitlab_project")
96       .setDescription("Import a GitLab project to SonarQube, creating a new project and configuring MR decoration<br/>" +
97                       "Requires the 'Create Projects' permission")
98       .setPost(true)
99       .setSince("8.5")
100       .setHandler(this);
101
102     action.createParam(ImportHelper.PARAM_ALM_SETTING)
103       .setRequired(true)
104       .setDescription("DevOps Platform setting key");
105     action.createParam(PARAM_GITLAB_PROJECT_ID)
106       .setRequired(true)
107       .setDescription("GitLab project ID");
108
109     action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
110       .setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
111       .setSince("10.1");
112
113     action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
114       .setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
115       .setSince("10.1");
116   }
117
118   @Override
119   public void handle(Request request, Response response) throws Exception {
120     CreateWsResponse createResponse = doHandle(request);
121     writeProtobuf(createResponse, request, response);
122   }
123
124   private CreateWsResponse doHandle(Request request) {
125     importHelper.checkProvisionProjectPermission();
126
127     String newCodeDefinitionType = request.param(PARAM_NEW_CODE_DEFINITION_TYPE);
128     String newCodeDefinitionValue = request.param(PARAM_NEW_CODE_DEFINITION_VALUE);
129
130     try (DbSession dbSession = dbClient.openSession(false)) {
131       AlmSettingDto almSettingDto = importHelper.getAlmSetting(request);
132       String pat = getPat(dbSession, almSettingDto);
133
134       long gitlabProjectId = request.mandatoryParamAsLong(PARAM_GITLAB_PROJECT_ID);
135
136       String gitlabUrl = requireNonNull(almSettingDto.getUrl(), "DevOps Platform gitlabUrl cannot be null");
137       Project gitlabProject = gitlabHttpClient.getProject(gitlabUrl, pat, gitlabProjectId);
138
139       Optional<String> almMainBranchName = getAlmDefaultBranch(pat, gitlabProjectId, gitlabUrl);
140
141       ComponentCreationData componentCreationData = createProject(dbSession, gitlabProject, almMainBranchName.orElse(null));
142       ProjectDto projectDto = Optional.ofNullable(componentCreationData.projectDto()).orElseThrow();
143       BranchDto mainBranchDto = Optional.ofNullable(componentCreationData.mainBranchDto()).orElseThrow();
144       populateMRSetting(dbSession, gitlabProjectId, projectDto, almSettingDto);
145
146       checkNewCodeDefinitionParam(newCodeDefinitionType, newCodeDefinitionValue);
147
148       if (newCodeDefinitionType != null) {
149         newCodeDefinitionResolver.createNewCodeDefinition(dbSession, projectDto.getUuid(), mainBranchDto.getUuid(),
150           almMainBranchName.orElse(defaultBranchNameResolver.getEffectiveMainBranchName()), newCodeDefinitionType, newCodeDefinitionValue);
151       }
152
153       componentUpdater.commitAndIndex(dbSession, componentCreationData);
154
155       return ImportHelper.toCreateResponse(projectDto);
156     }
157   }
158
159   private String getPat(DbSession dbSession, AlmSettingDto almSettingDto) {
160     String userUuid = importHelper.getUserUuid();
161     Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
162     return almPatDto.map(AlmPatDto::getPersonalAccessToken)
163       .orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingDto.getKey())));
164   }
165
166   private Optional<String> getAlmDefaultBranch(String pat, long gitlabProjectId, String gitlabUrl) {
167     Optional<GitLabBranch> almMainBranch = gitlabHttpClient.getBranches(gitlabUrl, pat, gitlabProjectId).stream().filter(GitLabBranch::isDefault).findFirst();
168     return almMainBranch.map(GitLabBranch::getName);
169   }
170
171   private void populateMRSetting(DbSession dbSession, Long gitlabProjectId, ProjectDto projectDto, AlmSettingDto almSettingDto) {
172     dbClient.projectAlmSettingDao().insertOrUpdate(dbSession, new ProjectAlmSettingDto()
173         .setProjectUuid(projectDto.getUuid())
174         .setAlmSettingUuid(almSettingDto.getUuid())
175         .setAlmRepo(gitlabProjectId.toString())
176         .setAlmSlug(null)
177         .setMonorepo(false),
178       almSettingDto.getKey(),
179       projectDto.getName(), projectDto.getKey());
180   }
181
182   private ComponentCreationData createProject(DbSession dbSession, Project gitlabProject, @Nullable String mainBranchName) {
183     boolean visibility = projectDefaultVisibility.get(dbSession).isPrivate();
184     String uniqueProjectKey = projectKeyGenerator.generateUniqueProjectKey(gitlabProject.getPathWithNamespace());
185     NewComponent newProject = newComponentBuilder()
186       .setKey(uniqueProjectKey)
187       .setName(gitlabProject.getName())
188       .setPrivate(visibility)
189       .setQualifier(PROJECT)
190       .build();
191     ComponentCreationParameters componentCreationParameters = ComponentCreationParameters.builder()
192       .newComponent(newProject)
193       .userUuid(userSession.getUuid())
194       .userLogin(userSession.getLogin())
195       .mainBranchName(mainBranchName)
196       .creationMethod(getCreationMethod(ALM_IMPORT, userSession.isAuthenticatedBrowserSession()))
197       .build();
198     return componentUpdater.createWithoutCommit(dbSession, componentCreationParameters);
199   }
200
201 }