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.

LiveMeasureComputerImpl.java 7.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2024 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.measure.live;
  21. import java.util.ArrayList;
  22. import java.util.Collection;
  23. import java.util.HashSet;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Optional;
  27. import java.util.Set;
  28. import java.util.function.Function;
  29. import java.util.stream.Collectors;
  30. import javax.annotation.CheckForNull;
  31. import org.slf4j.LoggerFactory;
  32. import org.sonar.api.config.Configuration;
  33. import org.sonar.api.measures.Metric;
  34. import org.sonar.db.DbClient;
  35. import org.sonar.db.DbSession;
  36. import org.sonar.db.component.BranchDto;
  37. import org.sonar.db.component.ComponentDto;
  38. import org.sonar.db.component.SnapshotDto;
  39. import org.sonar.db.measure.LiveMeasureComparator;
  40. import org.sonar.db.measure.LiveMeasureDto;
  41. import org.sonar.db.metric.MetricDto;
  42. import org.sonar.db.project.ProjectDto;
  43. import org.sonar.server.es.Indexers;
  44. import org.sonar.server.qualitygate.EvaluatedQualityGate;
  45. import org.sonar.server.qualitygate.QualityGate;
  46. import org.sonar.server.qualitygate.changeevent.QGChangeEvent;
  47. import org.sonar.server.setting.ProjectConfigurationLoader;
  48. import static java.util.Collections.emptyList;
  49. import static java.util.Collections.singleton;
  50. import static java.util.stream.Collectors.groupingBy;
  51. import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY;
  52. public class LiveMeasureComputerImpl implements LiveMeasureComputer {
  53. private final DbClient dbClient;
  54. private final MeasureUpdateFormulaFactory formulaFactory;
  55. private final ComponentIndexFactory componentIndexFactory;
  56. private final LiveQualityGateComputer qGateComputer;
  57. private final ProjectConfigurationLoader projectConfigurationLoader;
  58. private final Indexers projectIndexer;
  59. private final LiveMeasureTreeUpdater treeUpdater;
  60. public LiveMeasureComputerImpl(DbClient dbClient, MeasureUpdateFormulaFactory formulaFactory, ComponentIndexFactory componentIndexFactory,
  61. LiveQualityGateComputer qGateComputer, ProjectConfigurationLoader projectConfigurationLoader, Indexers projectIndexer, LiveMeasureTreeUpdater treeUpdater) {
  62. this.dbClient = dbClient;
  63. this.formulaFactory = formulaFactory;
  64. this.componentIndexFactory = componentIndexFactory;
  65. this.qGateComputer = qGateComputer;
  66. this.projectConfigurationLoader = projectConfigurationLoader;
  67. this.projectIndexer = projectIndexer;
  68. this.treeUpdater = treeUpdater;
  69. }
  70. @Override
  71. public List<QGChangeEvent> refresh(DbSession dbSession, Collection<ComponentDto> components) {
  72. if (components.isEmpty()) {
  73. return emptyList();
  74. }
  75. List<QGChangeEvent> result = new ArrayList<>();
  76. Map<String, List<ComponentDto>> componentsByProjectUuid = components.stream().collect(groupingBy(ComponentDto::branchUuid));
  77. for (List<ComponentDto> groupedComponents : componentsByProjectUuid.values()) {
  78. Optional<QGChangeEvent> qgChangeEvent = refreshComponentsOnSameProject(dbSession, groupedComponents);
  79. qgChangeEvent.ifPresent(result::add);
  80. }
  81. return result;
  82. }
  83. private Optional<QGChangeEvent> refreshComponentsOnSameProject(DbSession dbSession, List<ComponentDto> touchedComponents) {
  84. ComponentIndex components = componentIndexFactory.create(dbSession, touchedComponents);
  85. ComponentDto branchComponent = components.getBranch();
  86. Optional<SnapshotDto> lastAnalysis = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, branchComponent.uuid());
  87. if (lastAnalysis.isEmpty()) {
  88. return Optional.empty();
  89. }
  90. BranchDto branch = loadBranch(dbSession, branchComponent);
  91. ProjectDto project = loadProject(dbSession, branch.getProjectUuid());
  92. Configuration config = projectConfigurationLoader.loadBranchConfiguration(dbSession, branch);
  93. QualityGate qualityGate = qGateComputer.loadQualityGate(dbSession, project, branch);
  94. MeasureMatrix matrix = loadMeasureMatrix(dbSession, components.getAllUuids(), qualityGate);
  95. treeUpdater.update(dbSession, lastAnalysis.get(), config, components, branch, matrix);
  96. Metric.Level previousStatus = loadPreviousStatus(dbSession, branchComponent);
  97. EvaluatedQualityGate evaluatedQualityGate = qGateComputer.refreshGateStatus(branchComponent, qualityGate, matrix, config);
  98. persistAndIndex(dbSession, matrix, branch);
  99. return Optional.of(new QGChangeEvent(project, branch, lastAnalysis.get(), config, previousStatus, () -> Optional.of(evaluatedQualityGate)));
  100. }
  101. private MeasureMatrix loadMeasureMatrix(DbSession dbSession, Set<String> componentUuids, QualityGate qualityGate) {
  102. Collection<String> metricKeys = getKeysOfAllInvolvedMetrics(qualityGate);
  103. Map<String, MetricDto> metricsPerUuid = dbClient.metricDao().selectByKeys(dbSession, metricKeys).stream().collect(Collectors.toMap(MetricDto::getUuid, Function.identity()));
  104. List<LiveMeasureDto> measures = dbClient.liveMeasureDao().selectByComponentUuidsAndMetricUuids(dbSession, componentUuids, metricsPerUuid.keySet());
  105. return new MeasureMatrix(componentUuids, metricsPerUuid.values(), measures);
  106. }
  107. private void persistAndIndex(DbSession dbSession, MeasureMatrix matrix, BranchDto branch) {
  108. // persist the measures that have been created or updated
  109. matrix.getChanged().sorted(LiveMeasureComparator.INSTANCE).forEach(m -> dbClient.liveMeasureDao().insertOrUpdate(dbSession, m));
  110. projectIndexer.commitAndIndexBranches(dbSession, singleton(branch), Indexers.BranchEvent.MEASURE_CHANGE);
  111. }
  112. @CheckForNull
  113. private Metric.Level loadPreviousStatus(DbSession dbSession, ComponentDto branchComponent) {
  114. Optional<LiveMeasureDto> measure = dbClient.liveMeasureDao().selectMeasure(dbSession, branchComponent.uuid(), ALERT_STATUS_KEY);
  115. if (measure.isEmpty()) {
  116. return null;
  117. }
  118. try {
  119. return Metric.Level.valueOf(measure.get().getTextValue());
  120. } catch (IllegalArgumentException e) {
  121. LoggerFactory.getLogger(LiveMeasureComputerImpl.class).trace("Failed to parse value of metric '{}'", ALERT_STATUS_KEY, e);
  122. return null;
  123. }
  124. }
  125. private Set<String> getKeysOfAllInvolvedMetrics(QualityGate gate) {
  126. Set<String> metricKeys = new HashSet<>();
  127. for (Metric<?> metric : formulaFactory.getFormulaMetrics()) {
  128. metricKeys.add(metric.getKey());
  129. }
  130. metricKeys.addAll(qGateComputer.getMetricsRelatedTo(gate));
  131. return metricKeys;
  132. }
  133. private BranchDto loadBranch(DbSession dbSession, ComponentDto branchComponent) {
  134. return dbClient.branchDao().selectByUuid(dbSession, branchComponent.uuid())
  135. .orElseThrow(() -> new IllegalStateException("Branch not found: " + branchComponent.uuid()));
  136. }
  137. private ProjectDto loadProject(DbSession dbSession, String uuid) {
  138. return dbClient.projectDao().selectByUuid(dbSession, uuid)
  139. .orElseThrow(() -> new IllegalStateException("Project not found: " + uuid));
  140. }
  141. }