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