3 * Copyright (C) 2009-2019 SonarSource SA
4 * mailto:info AT sonarsource DOT com
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.
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.
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.
20 package org.sonar.ce.task.projectanalysis.step;
22 import com.google.common.base.Joiner;
23 import java.util.ArrayList;
24 import java.util.Date;
25 import java.util.List;
27 import java.util.Optional;
28 import java.util.stream.Collectors;
29 import org.sonar.api.utils.MessageException;
30 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
31 import org.sonar.ce.task.projectanalysis.component.Component;
32 import org.sonar.ce.task.projectanalysis.component.ComponentVisitor;
33 import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
34 import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
35 import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
36 import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
37 import org.sonar.ce.task.step.ComputationStep;
38 import org.sonar.db.DbClient;
39 import org.sonar.db.DbSession;
40 import org.sonar.db.component.BranchDto;
41 import org.sonar.db.component.BranchType;
42 import org.sonar.db.component.ComponentDao;
43 import org.sonar.db.component.ComponentDto;
44 import org.sonar.db.component.SnapshotDto;
46 import static com.google.common.base.Preconditions.checkState;
47 import static java.lang.String.format;
48 import static org.sonar.api.utils.DateUtils.formatDateTime;
51 * Validate project and modules. It will fail in the following cases :
53 * <li>module key is not valid</li>
54 * <li>module key already exists in another project (same module key cannot exists in different projects)</li>
55 * <li>module key is already used as a project key</li>
56 * <li>date of the analysis is before last analysis</li>
57 * <li>short living branch or PR targets a branch that still contains modules</li>
60 public class ValidateProjectStep implements ComputationStep {
62 private static final Joiner MESSAGES_JOINER = Joiner.on("\n o ");
64 private final DbClient dbClient;
65 private final TreeRootHolder treeRootHolder;
66 private final AnalysisMetadataHolder analysisMetadataHolder;
68 public ValidateProjectStep(DbClient dbClient, TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder) {
69 this.dbClient = dbClient;
70 this.treeRootHolder = treeRootHolder;
71 this.analysisMetadataHolder = analysisMetadataHolder;
75 public void execute(ComputationStep.Context context) {
76 try (DbSession dbSession = dbClient.openSession(false)) {
77 validateTargetBranch(dbSession);
78 Component root = treeRootHolder.getRoot();
79 List<ComponentDto> baseModules = dbClient.componentDao().selectEnabledModulesFromProjectKey(dbSession, root.getDbKey());
80 Map<String, ComponentDto> baseModulesByKey = baseModules.stream().collect(Collectors.toMap(ComponentDto::getDbKey, x -> x));
81 ValidateProjectsVisitor visitor = new ValidateProjectsVisitor(dbSession, dbClient.componentDao(), baseModulesByKey);
82 new DepthTraversalTypeAwareCrawler(visitor).visit(root);
84 if (!visitor.validationMessages.isEmpty()) {
85 throw MessageException.of("Validation of project failed:\n o " + MESSAGES_JOINER.join(visitor.validationMessages));
90 private void validateTargetBranch(DbSession session) {
91 if (!analysisMetadataHolder.isShortLivingBranch() && !analysisMetadataHolder.isPullRequest()) {
94 String mergeBranchUuid = analysisMetadataHolder.getBranch().getMergeBranchUuid().get();
95 int moduleCount = dbClient.componentDao().countEnabledModulesByProjectUuid(session, mergeBranchUuid);
96 if (moduleCount > 0) {
97 Optional<BranchDto> opt = dbClient.branchDao().selectByUuid(session, mergeBranchUuid);
98 checkState(opt.isPresent(), "Merge branch '%s' does not exist", mergeBranchUuid);
99 String type = analysisMetadataHolder.getBranch().getType() == BranchType.PULL_REQUEST ? "pull request" : "short-lived branch";
100 throw MessageException.of(String.format(
101 "Due to an upgrade, you need first to re-analyze the target branch '%s' before analyzing this %s.", opt.get().getKey(), type));
106 public String getDescription() {
107 return "Validate project";
110 private class ValidateProjectsVisitor extends TypeAwareVisitorAdapter {
111 private final DbSession session;
112 private final ComponentDao componentDao;
113 private final Map<String, ComponentDto> baseModulesByKey;
114 private final List<String> validationMessages = new ArrayList<>();
116 public ValidateProjectsVisitor(DbSession session, ComponentDao componentDao, Map<String, ComponentDto> baseModulesByKey) {
117 super(CrawlerDepthLimit.PROJECT, ComponentVisitor.Order.PRE_ORDER);
118 this.session = session;
119 this.componentDao = componentDao;
120 this.baseModulesByKey = baseModulesByKey;
124 public void visitProject(Component rawProject) {
125 String rawProjectKey = rawProject.getDbKey();
126 Optional<ComponentDto> baseProject = loadBaseComponent(rawProjectKey);
127 validateAnalysisDate(baseProject);
130 private void validateAnalysisDate(Optional<ComponentDto> baseProject) {
131 if (baseProject.isPresent()) {
132 Optional<SnapshotDto> snapshotDto = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(session, baseProject.get().uuid());
133 long currentAnalysisDate = analysisMetadataHolder.getAnalysisDate();
134 Long lastAnalysisDate = snapshotDto.map(SnapshotDto::getCreatedAt).orElse(null);
135 if (lastAnalysisDate != null && currentAnalysisDate <= lastAnalysisDate) {
136 validationMessages.add(format("Date of analysis cannot be older than the date of the last known analysis on this project. Value: \"%s\". " +
137 "Latest analysis: \"%s\". It's only possible to rebuild the past in a chronological order.",
138 formatDateTime(new Date(currentAnalysisDate)), formatDateTime(new Date(lastAnalysisDate))));
143 private Optional<ComponentDto> loadBaseComponent(String rawComponentKey) {
144 ComponentDto baseComponent = baseModulesByKey.get(rawComponentKey);
145 if (baseComponent == null) {
146 // Load component from key to be able to detect issue (try to analyze a module, etc.)
147 return componentDao.selectByKey(session, rawComponentKey);
149 return Optional.of(baseComponent);