You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ValidateProjectStep.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. /*
  2. * SonarQube, open source software quality management tool.
  3. * Copyright (C) 2008-2014 SonarSource
  4. * mailto:contact AT sonarsource DOT com
  5. *
  6. * SonarQube 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. * SonarQube 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.computation.step;
  21. import com.google.common.base.Function;
  22. import com.google.common.base.Joiner;
  23. import com.google.common.collect.FluentIterable;
  24. import java.util.ArrayList;
  25. import java.util.Date;
  26. import java.util.List;
  27. import java.util.Map;
  28. import javax.annotation.CheckForNull;
  29. import javax.annotation.Nonnull;
  30. import javax.annotation.Nullable;
  31. import org.sonar.api.CoreProperties;
  32. import org.sonar.api.config.Settings;
  33. import org.sonar.api.utils.MessageException;
  34. import org.sonar.batch.protocol.output.BatchReport;
  35. import org.sonar.db.component.ComponentDto;
  36. import org.sonar.core.component.ComponentKeys;
  37. import org.sonar.db.component.SnapshotDto;
  38. import org.sonar.db.DbSession;
  39. import org.sonar.server.component.db.ComponentDao;
  40. import org.sonar.server.computation.batch.BatchReportReader;
  41. import org.sonar.server.computation.component.Component;
  42. import org.sonar.server.computation.component.DepthTraversalTypeAwareVisitor;
  43. import org.sonar.server.computation.component.TreeRootHolder;
  44. import org.sonar.server.db.DbClient;
  45. import static org.sonar.api.utils.DateUtils.formatDateTime;
  46. /**
  47. * Validate project and modules. It will fail in the following cases :
  48. * <ol>
  49. * <li>property {@link org.sonar.api.CoreProperties#CORE_PREVENT_AUTOMATIC_PROJECT_CREATION} is set to true and project does not exists</li>
  50. * <li>branch is not valid</li>
  51. * <li>project or module key is not valid</li>
  52. * <li>module key already exists in another project (same module key cannot exists in different projects)</li>
  53. * <li>module key is already used as a project key</li>
  54. * <li>date of the analysis is before last analysis</li>
  55. * </ol>
  56. */
  57. public class ValidateProjectStep implements ComputationStep {
  58. private static final Joiner MESSAGES_JOINER = Joiner.on("\n o ");
  59. private final DbClient dbClient;
  60. private final Settings settings;
  61. private final BatchReportReader reportReader;
  62. private final TreeRootHolder treeRootHolder;
  63. public ValidateProjectStep(DbClient dbClient, Settings settings, BatchReportReader reportReader, TreeRootHolder treeRootHolder) {
  64. this.dbClient = dbClient;
  65. this.settings = settings;
  66. this.reportReader = reportReader;
  67. this.treeRootHolder = treeRootHolder;
  68. }
  69. @Override
  70. public void execute() {
  71. DbSession session = dbClient.openSession(false);
  72. try {
  73. List<ComponentDto> baseModules = dbClient.componentDao().selectModulesFromProjectKey(session, treeRootHolder.getRoot().getKey());
  74. Map<String, ComponentDto> baseModulesByKey = FluentIterable.from(baseModules).uniqueIndex(ComponentDtoToKey.INSTANCE);
  75. ValidateProjectsVisitor visitor = new ValidateProjectsVisitor(session, dbClient.componentDao(),
  76. settings.getBoolean(CoreProperties.CORE_PREVENT_AUTOMATIC_PROJECT_CREATION), baseModulesByKey);
  77. visitor.visit(treeRootHolder.getRoot());
  78. if (!visitor.validationMessages.isEmpty()) {
  79. throw MessageException.of("Validation of project failed:\n o " + MESSAGES_JOINER.join(visitor.validationMessages));
  80. }
  81. } finally {
  82. session.close();
  83. }
  84. }
  85. @Override
  86. public String getDescription() {
  87. return "Validate project and modules keys";
  88. }
  89. private class ValidateProjectsVisitor extends DepthTraversalTypeAwareVisitor {
  90. private final DbSession session;
  91. private final ComponentDao componentDao;
  92. private final boolean preventAutomaticProjectCreation;
  93. private final Map<String, ComponentDto> baseModulesByKey;
  94. private final List<String> validationMessages = new ArrayList<>();
  95. private Component rawProject;
  96. public ValidateProjectsVisitor(DbSession session, ComponentDao componentDao, boolean preventAutomaticProjectCreation, Map<String, ComponentDto> baseModulesByKey) {
  97. super(Component.Type.MODULE, Order.PRE_ORDER);
  98. this.session = session;
  99. this.componentDao = componentDao;
  100. this.preventAutomaticProjectCreation = preventAutomaticProjectCreation;
  101. this.baseModulesByKey = baseModulesByKey;
  102. }
  103. @Override
  104. public void visitProject(Component rawProject) {
  105. this.rawProject = rawProject;
  106. validateBranch();
  107. validateBatchKey(rawProject);
  108. String rawProjectKey = rawProject.getKey();
  109. ComponentDto baseProject = loadBaseComponent(rawProjectKey);
  110. validateWhenProvisioningEnforced(baseProject, rawProjectKey);
  111. validateProjectKey(baseProject, rawProjectKey);
  112. validateAnalysisDate(baseProject);
  113. }
  114. private void validateWhenProvisioningEnforced(@Nullable ComponentDto baseProject, String rawProjectKey) {
  115. if (baseProject == null && preventAutomaticProjectCreation) {
  116. validationMessages.add(String.format("Unable to scan non-existing project '%s'", rawProjectKey));
  117. }
  118. }
  119. private void validateProjectKey(@Nullable ComponentDto baseProject, String rawProjectKey) {
  120. if (baseProject != null && !baseProject.projectUuid().equals(baseProject.uuid())) {
  121. // Project key is already used as a module of another project
  122. ComponentDto anotherBaseProject = componentDao.selectByUuid(session, baseProject.projectUuid());
  123. validationMessages.add(String.format("The project \"%s\" is already defined in SonarQube but as a module of project \"%s\". "
  124. + "If you really want to stop directly analysing project \"%s\", please first delete it from SonarQube and then relaunch the analysis of project \"%s\".",
  125. rawProjectKey, anotherBaseProject.key(), anotherBaseProject.key(), rawProjectKey));
  126. }
  127. }
  128. private void validateAnalysisDate(@Nullable ComponentDto baseProject) {
  129. if (baseProject != null) {
  130. SnapshotDto snapshotDto = dbClient.snapshotDao().selectLastSnapshotByComponentId(session, baseProject.getId());
  131. long currentAnalysisDate = reportReader.readMetadata().getAnalysisDate();
  132. Long lastAnalysisDate = snapshotDto != null ? snapshotDto.getCreatedAt() : null;
  133. if (lastAnalysisDate != null && currentAnalysisDate <= snapshotDto.getCreatedAt()) {
  134. validationMessages.add(String.format("Date of analysis cannot be older than the date of the last known analysis on this project. Value: \"%s\". " +
  135. "Latest analysis: \"%s\". It's only possible to rebuild the past in a chronological order.",
  136. formatDateTime(new Date(currentAnalysisDate)), formatDateTime(new Date(lastAnalysisDate))));
  137. }
  138. }
  139. }
  140. @Override
  141. public void visitModule(Component rawModule) {
  142. String rawProjectKey = rawProject.getKey();
  143. String rawModuleKey = rawModule.getKey();
  144. validateBatchKey(rawModule);
  145. ComponentDto baseModule = loadBaseComponent(rawModuleKey);
  146. if (baseModule == null) {
  147. return;
  148. }
  149. validateModuleIsNotAlreadyUsedAsProject(baseModule, rawProjectKey, rawModuleKey);
  150. validateModuleKeyIsNotAlreadyUsedInAnotherProject(baseModule, rawModuleKey);
  151. }
  152. private void validateModuleIsNotAlreadyUsedAsProject(ComponentDto baseModule, String rawProjectKey, String rawModuleKey) {
  153. if (baseModule.projectUuid().equals(baseModule.uuid())) {
  154. // module is actually a project
  155. validationMessages.add(String.format("The project \"%s\" is already defined in SonarQube but not as a module of project \"%s\". "
  156. + "If you really want to stop directly analysing project \"%s\", please first delete it from SonarQube and then relaunch the analysis of project \"%s\".",
  157. rawModuleKey, rawProjectKey, rawModuleKey, rawProjectKey));
  158. }
  159. }
  160. private void validateModuleKeyIsNotAlreadyUsedInAnotherProject(ComponentDto baseModule, String rawModuleKey) {
  161. if (!baseModule.projectUuid().equals(baseModule.uuid()) && !baseModule.projectUuid().equals(rawProject.getUuid())) {
  162. ComponentDto projectModule = componentDao.selectByUuid(session, baseModule.projectUuid());
  163. validationMessages.add(String.format("Module \"%s\" is already part of project \"%s\"", rawModuleKey, projectModule.key()));
  164. }
  165. }
  166. private void validateBatchKey(Component rawComponent) {
  167. String batchKey = reportReader.readComponent(rawComponent.getRef()).getKey();
  168. if (!ComponentKeys.isValidModuleKey(batchKey)) {
  169. validationMessages.add(String.format("\"%s\" is not a valid project or module key. "
  170. + "Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.", batchKey));
  171. }
  172. }
  173. @CheckForNull
  174. private void validateBranch() {
  175. BatchReport.Metadata metadata = reportReader.readMetadata();
  176. if (!metadata.hasBranch()) {
  177. return;
  178. }
  179. String branch = metadata.getBranch();
  180. if (!ComponentKeys.isValidBranch(branch)) {
  181. validationMessages.add(String.format("\"%s\" is not a valid branch name. "
  182. + "Allowed characters are alphanumeric, '-', '_', '.' and '/'.", branch));
  183. }
  184. }
  185. private ComponentDto loadBaseComponent(String rawComponentKey) {
  186. ComponentDto baseComponent = baseModulesByKey.get(rawComponentKey);
  187. if (baseComponent == null) {
  188. // Load component from key to be able to detect issue (try to analyze a module, etc.)
  189. return componentDao.selectNullableByKey(session, rawComponentKey);
  190. }
  191. return baseComponent;
  192. }
  193. }
  194. private enum ComponentDtoToKey implements Function<ComponentDto, String> {
  195. INSTANCE;
  196. @Override
  197. public String apply(@Nonnull ComponentDto input) {
  198. return input.key();
  199. }
  200. }
  201. }