3 * Copyright (C) 2009-2023 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.List;
23 import java.util.Objects;
24 import java.util.Optional;
25 import java.util.stream.Collectors;
26 import org.sonar.api.config.Configuration;
27 import org.sonar.api.measures.Metric;
28 import org.sonar.db.DbClient;
29 import org.sonar.db.DbSession;
30 import org.sonar.db.component.BranchDto;
31 import org.sonar.db.component.BranchType;
32 import org.sonar.db.component.ComponentDto;
33 import org.sonar.db.component.SnapshotDto;
34 import org.sonar.db.measure.LiveMeasureDto;
35 import org.sonar.server.measure.DebtRatingGrid;
36 import org.sonar.server.measure.Rating;
38 import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_KEY;
39 import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_KEY;
40 import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY;
41 import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY;
42 import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_KEY;
43 import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_KEY;
44 import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY;
45 import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY;
46 import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH;
48 public class LiveMeasureTreeUpdaterImpl implements LiveMeasureTreeUpdater {
49 private final DbClient dbClient;
50 private final MeasureUpdateFormulaFactory formulaFactory;
52 public LiveMeasureTreeUpdaterImpl(DbClient dbClient, MeasureUpdateFormulaFactory formulaFactory) {
53 this.dbClient = dbClient;
54 this.formulaFactory = formulaFactory;
58 public void update(DbSession dbSession, SnapshotDto lastAnalysis, Configuration config, ComponentIndex components, BranchDto branch, MeasureMatrix measures) {
59 long beginningOfLeak = getBeginningOfLeakPeriod(lastAnalysis, branch);
60 boolean shouldUseLeakFormulas = shouldUseLeakFormulas(lastAnalysis, branch);
62 // 1. set new measure from issues to each component from touched components to the root
63 updateMatrixWithIssues(dbSession, measures, components, config, shouldUseLeakFormulas, beginningOfLeak);
65 // 2. aggregate new measures up the component tree
66 updateMatrixWithHierarchy(measures, components, config, shouldUseLeakFormulas);
69 private void updateMatrixWithHierarchy(MeasureMatrix matrix, ComponentIndex components, Configuration config, boolean useLeakFormulas) {
70 DebtRatingGrid debtRatingGrid = new DebtRatingGrid(config);
71 FormulaContextImpl context = new FormulaContextImpl(matrix, components, debtRatingGrid);
72 components.getSortedTree().forEach(c -> {
73 for (MeasureUpdateFormula formula : formulaFactory.getFormulas()) {
74 if (useLeakFormulas || !formula.isOnLeak()) {
75 context.change(c, formula);
77 formula.computeHierarchy(context);
78 } catch (RuntimeException e) {
79 throw new IllegalStateException("Fail to compute " + formula.getMetric().getKey() + " on "
80 + context.getComponent().getKey() + " (uuid: " + context.getComponent().uuid() + ")", e);
87 private void updateMatrixWithIssues(DbSession dbSession, MeasureMatrix matrix, ComponentIndex components, Configuration config, boolean useLeakFormulas, long beginningOfLeak) {
88 DebtRatingGrid debtRatingGrid = new DebtRatingGrid(config);
89 FormulaContextImpl context = new FormulaContextImpl(matrix, components, debtRatingGrid);
91 components.getSortedTree().forEach(c -> {
92 IssueCounter issueCounter = new IssueCounter(dbClient.issueDao().selectIssueGroupsByComponent(dbSession, c, beginningOfLeak));
93 for (MeasureUpdateFormula formula : formulaFactory.getFormulas()) {
94 // use formulas when the leak period is defined, it's a PR, or the formula is not about the leak period
95 if (useLeakFormulas || !formula.isOnLeak()) {
96 context.change(c, formula);
98 formula.compute(context, issueCounter);
99 } catch (RuntimeException e) {
100 throw new IllegalStateException("Fail to compute " + formula.getMetric().getKey() + " on "
101 + context.getComponent().getKey() + " (uuid: " + context.getComponent().uuid() + ")", e);
108 private static long getBeginningOfLeakPeriod(SnapshotDto lastAnalysis, BranchDto branch) {
111 } else if (REFERENCE_BRANCH.name().equals(lastAnalysis.getPeriodMode())) {
114 return Optional.ofNullable(lastAnalysis.getPeriodDate()).orElse(Long.MAX_VALUE);
118 private static boolean isPR(BranchDto branch) {
119 return branch.getBranchType() == BranchType.PULL_REQUEST;
122 private static boolean shouldUseLeakFormulas(SnapshotDto lastAnalysis, BranchDto branch) {
123 return lastAnalysis.getPeriodDate() != null || isPR(branch) || REFERENCE_BRANCH.name().equals(lastAnalysis.getPeriodMode());
126 public static class FormulaContextImpl implements MeasureUpdateFormula.Context {
127 private final MeasureMatrix matrix;
128 private final ComponentIndex componentIndex;
129 private final DebtRatingGrid debtRatingGrid;
130 private ComponentDto currentComponent;
131 private MeasureUpdateFormula currentFormula;
133 public FormulaContextImpl(MeasureMatrix matrix, ComponentIndex componentIndex, DebtRatingGrid debtRatingGrid) {
134 this.matrix = matrix;
135 this.componentIndex = componentIndex;
136 this.debtRatingGrid = debtRatingGrid;
139 void change(ComponentDto component, MeasureUpdateFormula formula) {
140 this.currentComponent = component;
141 this.currentFormula = formula;
144 public List<Double> getChildrenValues() {
145 List<ComponentDto> children = componentIndex.getChildren(currentComponent);
146 return children.stream()
147 .flatMap(c -> matrix.getMeasure(c, currentFormula.getMetric().getKey()).stream())
148 .map(LiveMeasureDto::getValue)
149 .filter(Objects::nonNull)
150 .collect(Collectors.toList());
154 * Some child components may not have the measures 'SECURITY_HOTSPOTS_TO_REVIEW_STATUS' and 'SECURITY_HOTSPOTS_REVIEWED_STATUS' saved for them,
155 * so we may need to calculate them based on 'SECURITY_HOTSPOTS_REVIEWED' and 'SECURITY_HOTSPOTS'.
158 public long getChildrenHotspotsReviewed() {
159 return getChildrenHotspotsReviewed(SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY, SECURITY_HOTSPOTS_REVIEWED_KEY, SECURITY_HOTSPOTS_KEY);
163 * Some child components may not have the measure 'SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY'. We assume that 'SECURITY_HOTSPOTS_KEY' has the same value.
166 public long getChildrenHotspotsToReview() {
167 return componentIndex.getChildren(currentComponent)
169 .map(c -> matrix.getMeasure(c, SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY).or(() -> matrix.getMeasure(c, SECURITY_HOTSPOTS_KEY)))
170 .mapToLong(lmOpt -> lmOpt.flatMap(lm -> Optional.ofNullable(lm.getValue())).orElse(0D).longValue())
175 public long getChildrenNewHotspotsReviewed() {
176 return getChildrenHotspotsReviewed(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY, NEW_SECURITY_HOTSPOTS_REVIEWED_KEY, NEW_SECURITY_HOTSPOTS_KEY);
180 * Some child components may not have the measure 'NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY'. We assume that 'NEW_SECURITY_HOTSPOTS_KEY' has the same value.
183 public long getChildrenNewHotspotsToReview() {
184 return componentIndex.getChildren(currentComponent)
186 .map(c -> matrix.getMeasure(c, NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY).or(() -> matrix.getMeasure(c, NEW_SECURITY_HOTSPOTS_KEY)))
187 .mapToLong(lmOpt -> lmOpt.flatMap(lm -> Optional.ofNullable(lm.getValue())).orElse(0D).longValue())
191 private long getChildrenHotspotsReviewed(String metricKey, String percMetricKey, String hotspotsMetricKey) {
192 return componentIndex.getChildren(currentComponent)
194 .mapToLong(c -> getHotspotsReviewed(c, metricKey, percMetricKey, hotspotsMetricKey))
198 private long getHotspotsReviewed(ComponentDto c, String metricKey, String percMetricKey, String hotspotsMetricKey) {
199 Optional<LiveMeasureDto> measure = matrix.getMeasure(c, metricKey);
200 return measure.map(lm -> Optional.ofNullable(lm.getValue()).orElse(0D).longValue())
201 .orElseGet(() -> matrix.getMeasure(c, percMetricKey)
202 .flatMap(percentage -> matrix.getMeasure(c, hotspotsMetricKey)
204 double perc = Optional.ofNullable(percentage.getValue()).orElse(0D) / 100D;
205 double toReview = Optional.ofNullable(hotspots.getValue()).orElse(0D);
206 double reviewed = (toReview * perc) / (1D - perc);
207 return Math.round(reviewed);
215 public ComponentDto getComponent() {
216 return currentComponent;
220 public DebtRatingGrid getDebtRatingGrid() {
221 return debtRatingGrid;
225 public Optional<Double> getValue(Metric metric) {
226 Optional<LiveMeasureDto> measure = matrix.getMeasure(currentComponent, metric.getKey());
227 return measure.map(LiveMeasureDto::getValue);
231 public Optional<String> getText(Metric metric) {
232 Optional<LiveMeasureDto> measure = matrix.getMeasure(currentComponent, metric.getKey());
233 return measure.map(LiveMeasureDto::getTextValue);
237 public void setValue(double value) {
238 String metricKey = currentFormula.getMetric().getKey();
239 matrix.setValue(currentComponent, metricKey, value);
243 public void setValue(Rating value) {
244 String metricKey = currentFormula.getMetric().getKey();
245 matrix.setValue(currentComponent, metricKey, value);