3 * Copyright (C) 2009-2021 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.server.measure.live;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.Objects;
28 import java.util.Optional;
30 import javax.annotation.CheckForNull;
31 import org.sonar.api.config.Configuration;
32 import org.sonar.api.measures.Metric;
33 import org.sonar.api.utils.log.Loggers;
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.BranchType;
38 import org.sonar.db.component.ComponentDto;
39 import org.sonar.db.component.SnapshotDto;
40 import org.sonar.db.measure.LiveMeasureComparator;
41 import org.sonar.db.measure.LiveMeasureDto;
42 import org.sonar.db.metric.MetricDto;
43 import org.sonar.db.project.ProjectDto;
44 import org.sonar.server.es.ProjectIndexer;
45 import org.sonar.server.es.ProjectIndexers;
46 import org.sonar.server.measure.DebtRatingGrid;
47 import org.sonar.server.measure.Rating;
48 import org.sonar.server.qualitygate.EvaluatedQualityGate;
49 import org.sonar.server.qualitygate.QualityGate;
50 import org.sonar.server.qualitygate.changeevent.QGChangeEvent;
51 import org.sonar.server.setting.ProjectConfigurationLoader;
53 import static com.google.common.base.Preconditions.checkState;
54 import static java.util.Collections.emptyList;
55 import static java.util.Collections.singleton;
56 import static java.util.stream.Collectors.groupingBy;
57 import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY;
58 import static org.sonar.core.util.stream.MoreCollectors.toArrayList;
59 import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
61 public class LiveMeasureComputerImpl implements LiveMeasureComputer {
63 private final DbClient dbClient;
64 private final IssueMetricFormulaFactory formulaFactory;
65 private final LiveQualityGateComputer qGateComputer;
66 private final ProjectConfigurationLoader projectConfigurationLoader;
67 private final ProjectIndexers projectIndexer;
69 public LiveMeasureComputerImpl(DbClient dbClient, IssueMetricFormulaFactory formulaFactory,
70 LiveQualityGateComputer qGateComputer, ProjectConfigurationLoader projectConfigurationLoader, ProjectIndexers projectIndexer) {
71 this.dbClient = dbClient;
72 this.formulaFactory = formulaFactory;
73 this.qGateComputer = qGateComputer;
74 this.projectConfigurationLoader = projectConfigurationLoader;
75 this.projectIndexer = projectIndexer;
79 public List<QGChangeEvent> refresh(DbSession dbSession, Collection<ComponentDto> components) {
80 if (components.isEmpty()) {
84 List<QGChangeEvent> result = new ArrayList<>();
85 Map<String, List<ComponentDto>> componentsByProjectUuid = components.stream().collect(groupingBy(ComponentDto::projectUuid));
86 for (List<ComponentDto> groupedComponents : componentsByProjectUuid.values()) {
87 Optional<QGChangeEvent> qgChangeEvent = refreshComponentsOnSameProject(dbSession, groupedComponents);
88 qgChangeEvent.ifPresent(result::add);
93 private Optional<QGChangeEvent> refreshComponentsOnSameProject(DbSession dbSession, List<ComponentDto> touchedComponents) {
94 // load all the components to be refreshed, including their ancestors
95 List<ComponentDto> components = loadTreeOfComponents(dbSession, touchedComponents);
96 ComponentDto branchComponent = findBranchComponent(components);
97 BranchDto branch = loadBranch(dbSession, branchComponent);
98 ProjectDto project = loadProject(dbSession, branch.getProjectUuid());
99 Optional<SnapshotDto> lastAnalysis = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, branchComponent.uuid());
100 if (!lastAnalysis.isPresent()) {
101 return Optional.empty();
104 QualityGate qualityGate = qGateComputer.loadQualityGate(dbSession, project, branch);
105 Collection<String> metricKeys = getKeysOfAllInvolvedMetrics(qualityGate);
107 List<MetricDto> metrics = dbClient.metricDao().selectByKeys(dbSession, metricKeys);
108 Map<String, MetricDto> metricsPerId = metrics.stream()
109 .collect(uniqueIndex(MetricDto::getUuid));
110 List<String> componentUuids = components.stream().map(ComponentDto::uuid).collect(toArrayList(components.size()));
111 List<LiveMeasureDto> dbMeasures = dbClient.liveMeasureDao().selectByComponentUuidsAndMetricUuids(dbSession, componentUuids, metricsPerId.keySet());
112 // previous status must be load now as MeasureMatrix mutate the LiveMeasureDto which are passed to it
113 Metric.Level previousStatus = loadPreviousStatus(metrics, dbMeasures);
115 Configuration config = projectConfigurationLoader.loadProjectConfiguration(dbSession, branchComponent);
116 DebtRatingGrid debtRatingGrid = new DebtRatingGrid(config);
118 MeasureMatrix matrix = new MeasureMatrix(components, metricsPerId.values(), dbMeasures);
119 FormulaContextImpl context = new FormulaContextImpl(matrix, debtRatingGrid);
120 long beginningOfLeak = getBeginningOfLeakPeriod(lastAnalysis, branch);
122 components.forEach(c -> {
123 IssueCounter issueCounter = new IssueCounter(dbClient.issueDao().selectIssueGroupsByBaseComponent(dbSession, c, beginningOfLeak));
124 for (IssueMetricFormula formula : formulaFactory.getFormulas()) {
125 // use formulas when the leak period is defined, it's a PR, or the formula is not about the leak period
126 if (shouldUseLeakFormulas(lastAnalysis.get(), branch) || !formula.isOnLeak()) {
127 context.change(c, formula);
129 formula.compute(context, issueCounter);
130 } catch (RuntimeException e) {
131 throw new IllegalStateException("Fail to compute " + formula.getMetric().getKey() + " on " + context.getComponent().getDbKey(), e);
137 EvaluatedQualityGate evaluatedQualityGate = qGateComputer.refreshGateStatus(branchComponent, qualityGate, matrix);
139 // persist the measures that have been created or updated
140 matrix.getChanged().sorted(LiveMeasureComparator.INSTANCE)
141 .forEach(m -> dbClient.liveMeasureDao().insertOrUpdate(dbSession, m));
142 projectIndexer.commitAndIndexComponents(dbSession, singleton(branchComponent), ProjectIndexer.Cause.MEASURE_CHANGE);
145 new QGChangeEvent(project, branch, lastAnalysis.get(), config, previousStatus, () -> Optional.of(evaluatedQualityGate)));
148 private static long getBeginningOfLeakPeriod(Optional<SnapshotDto> lastAnalysis, BranchDto branch) {
152 Optional<Long> beginningOfLeakPeriod = lastAnalysis.map(SnapshotDto::getPeriodDate);
153 return beginningOfLeakPeriod.orElse(Long.MAX_VALUE);
157 private static boolean isPR(BranchDto branch) {
158 return branch.getBranchType() == BranchType.PULL_REQUEST;
161 private static boolean shouldUseLeakFormulas(SnapshotDto lastAnalysis, BranchDto branch) {
162 return lastAnalysis.getPeriodDate() != null || isPR(branch);
166 private static Metric.Level loadPreviousStatus(List<MetricDto> metrics, List<LiveMeasureDto> dbMeasures) {
167 MetricDto alertStatusMetric = metrics.stream()
168 .filter(m -> ALERT_STATUS_KEY.equals(m.getKey()))
170 .orElseThrow(() -> new IllegalStateException(String.format("Metric with key %s is not registered", ALERT_STATUS_KEY)));
171 return dbMeasures.stream()
172 .filter(m -> m.getMetricUuid().equals(alertStatusMetric.getUuid()))
173 .map(LiveMeasureDto::getTextValue)
174 .filter(Objects::nonNull)
177 return Metric.Level.valueOf(m);
178 } catch (IllegalArgumentException e) {
179 Loggers.get(LiveMeasureComputerImpl.class)
180 .trace("Failed to parse value of metric '{}'", m, e);
184 .filter(Objects::nonNull)
189 private List<ComponentDto> loadTreeOfComponents(DbSession dbSession, List<ComponentDto> touchedComponents) {
190 Set<String> componentUuids = new HashSet<>();
191 for (ComponentDto component : touchedComponents) {
192 componentUuids.add(component.uuid());
193 // ancestors, excluding self
194 componentUuids.addAll(component.getUuidPathAsList());
196 // Contrary to the formulas in Compute Engine,
197 // measures do not aggregate values of descendant components.
198 // As a consequence nodes do not need to be sorted. Formulas can be applied
199 // on components in any order.
200 return dbClient.componentDao().selectByUuids(dbSession, componentUuids);
203 private Set<String> getKeysOfAllInvolvedMetrics(QualityGate gate) {
204 Set<String> metricKeys = new HashSet<>();
205 for (Metric metric : formulaFactory.getFormulaMetrics()) {
206 metricKeys.add(metric.getKey());
208 metricKeys.addAll(qGateComputer.getMetricsRelatedTo(gate));
212 private static ComponentDto findBranchComponent(Collection<ComponentDto> components) {
213 return components.stream().filter(ComponentDto::isRootProject).findFirst()
214 .orElseThrow(() -> new IllegalStateException("No project found in " + components));
217 private BranchDto loadBranch(DbSession dbSession, ComponentDto branchComponent) {
218 return dbClient.branchDao().selectByUuid(dbSession, branchComponent.uuid())
219 .orElseThrow(() -> new IllegalStateException("Branch not found: " + branchComponent.uuid()));
222 private ProjectDto loadProject(DbSession dbSession, String uuid) {
223 return dbClient.projectDao().selectByUuid(dbSession, uuid)
224 .orElseThrow(() -> new IllegalStateException("Project not found: " + uuid));
227 private static class FormulaContextImpl implements IssueMetricFormula.Context {
228 private final MeasureMatrix matrix;
229 private final DebtRatingGrid debtRatingGrid;
230 private ComponentDto currentComponent;
231 private IssueMetricFormula currentFormula;
233 private FormulaContextImpl(MeasureMatrix matrix, DebtRatingGrid debtRatingGrid) {
234 this.matrix = matrix;
235 this.debtRatingGrid = debtRatingGrid;
238 private void change(ComponentDto component, IssueMetricFormula formula) {
239 this.currentComponent = component;
240 this.currentFormula = formula;
244 public ComponentDto getComponent() {
245 return currentComponent;
249 public DebtRatingGrid getDebtRatingGrid() {
250 return debtRatingGrid;
254 public Optional<Double> getValue(Metric metric) {
255 Optional<LiveMeasureDto> measure = matrix.getMeasure(currentComponent, metric.getKey());
256 return measure.map(LiveMeasureDto::getValue);
260 public Optional<Double> getLeakValue(Metric metric) {
261 Optional<LiveMeasureDto> measure = matrix.getMeasure(currentComponent, metric.getKey());
262 return measure.map(LiveMeasureDto::getVariation);
266 public void setValue(double value) {
267 String metricKey = currentFormula.getMetric().getKey();
268 checkState(!currentFormula.isOnLeak(), "Formula of metric %s accepts only leak values", metricKey);
269 matrix.setValue(currentComponent, metricKey, value);
273 public void setLeakValue(double value) {
274 String metricKey = currentFormula.getMetric().getKey();
275 checkState(currentFormula.isOnLeak(), "Formula of metric %s does not accept leak values", metricKey);
276 matrix.setLeakValue(currentComponent, metricKey, value);
280 public void setValue(Rating value) {
281 String metricKey = currentFormula.getMetric().getKey();
282 checkState(!currentFormula.isOnLeak(), "Formula of metric %s accepts only leak values", metricKey);
283 matrix.setValue(currentComponent, metricKey, value);
287 public void setLeakValue(Rating value) {
288 String metricKey = currentFormula.getMetric().getKey();
289 checkState(currentFormula.isOnLeak(), "Formula of metric %s does not accept leak values", metricKey);
290 matrix.setLeakValue(currentComponent, metricKey, value);