3 * Copyright (C) 2009-2024 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 org.sonar.api.config.Configuration;
26 import org.sonar.api.measures.Metric;
27 import org.sonar.db.DbClient;
28 import org.sonar.db.DbSession;
29 import org.sonar.db.component.BranchDto;
30 import org.sonar.db.component.BranchType;
31 import org.sonar.db.component.ComponentDto;
32 import org.sonar.db.component.SnapshotDto;
33 import org.sonar.db.measure.LiveMeasureDto;
34 import org.sonar.server.measure.DebtRatingGrid;
35 import org.sonar.server.measure.Rating;
37 import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_KEY;
38 import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_KEY;
39 import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY;
40 import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY;
41 import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_KEY;
42 import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_KEY;
43 import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY;
44 import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY;
45 import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH;
47 public class LiveMeasureTreeUpdaterImpl implements LiveMeasureTreeUpdater {
48 private final DbClient dbClient;
49 private final MeasureUpdateFormulaFactory formulaFactory;
51 public LiveMeasureTreeUpdaterImpl(DbClient dbClient, MeasureUpdateFormulaFactory formulaFactory) {
52 this.dbClient = dbClient;
53 this.formulaFactory = formulaFactory;
57 public void update(DbSession dbSession, SnapshotDto lastAnalysis, Configuration config, ComponentIndex components, BranchDto branch, MeasureMatrix measures) {
58 long beginningOfLeak = getBeginningOfLeakPeriod(lastAnalysis, branch);
59 boolean shouldUseLeakFormulas = shouldUseLeakFormulas(lastAnalysis, branch);
61 // 1. set new measure from issues to each component from touched components to the root
62 updateMatrixWithIssues(dbSession, measures, components, config, shouldUseLeakFormulas, beginningOfLeak);
64 // 2. aggregate new measures up the component tree
65 updateMatrixWithHierarchy(measures, components, config, shouldUseLeakFormulas);
68 private void updateMatrixWithHierarchy(MeasureMatrix matrix, ComponentIndex components, Configuration config, boolean useLeakFormulas) {
69 DebtRatingGrid debtRatingGrid = new DebtRatingGrid(config);
70 FormulaContextImpl context = new FormulaContextImpl(matrix, components, debtRatingGrid);
71 components.getSortedTree().forEach(c -> {
72 for (MeasureUpdateFormula formula : formulaFactory.getFormulas()) {
73 if (useLeakFormulas || !formula.isOnLeak()) {
74 context.change(c, formula);
76 formula.computeHierarchy(context);
77 } catch (RuntimeException e) {
78 throw new IllegalStateException("Fail to compute " + formula.getMetric().getKey() + " on "
79 + context.getComponent().getKey() + " (uuid: " + context.getComponent().uuid() + ")", e);
86 private void updateMatrixWithIssues(DbSession dbSession, MeasureMatrix matrix, ComponentIndex components, Configuration config, boolean useLeakFormulas, long beginningOfLeak) {
87 DebtRatingGrid debtRatingGrid = new DebtRatingGrid(config);
88 FormulaContextImpl context = new FormulaContextImpl(matrix, components, debtRatingGrid);
90 components.getSortedTree().forEach(c -> {
91 IssueCounter issueCounter = new IssueCounter(dbClient.issueDao().selectIssueGroupsByComponent(dbSession, c, beginningOfLeak));
92 for (MeasureUpdateFormula formula : formulaFactory.getFormulas()) {
93 // use formulas when the leak period is defined, it's a PR, or the formula is not about the leak period
94 if (useLeakFormulas || !formula.isOnLeak()) {
95 context.change(c, formula);
97 formula.compute(context, issueCounter);
98 } catch (RuntimeException e) {
99 throw new IllegalStateException("Fail to compute " + formula.getMetric().getKey() + " on "
100 + context.getComponent().getKey() + " (uuid: " + context.getComponent().uuid() + ")", e);
107 private static long getBeginningOfLeakPeriod(SnapshotDto lastAnalysis, BranchDto branch) {
110 } else if (REFERENCE_BRANCH.name().equals(lastAnalysis.getPeriodMode())) {
113 return Optional.ofNullable(lastAnalysis.getPeriodDate()).orElse(Long.MAX_VALUE);
117 private static boolean isPR(BranchDto branch) {
118 return branch.getBranchType() == BranchType.PULL_REQUEST;
121 private static boolean shouldUseLeakFormulas(SnapshotDto lastAnalysis, BranchDto branch) {
122 return lastAnalysis.getPeriodDate() != null || isPR(branch) || REFERENCE_BRANCH.name().equals(lastAnalysis.getPeriodMode());
125 public static class FormulaContextImpl implements MeasureUpdateFormula.Context {
126 private final MeasureMatrix matrix;
127 private final ComponentIndex componentIndex;
128 private final DebtRatingGrid debtRatingGrid;
129 private ComponentDto currentComponent;
130 private MeasureUpdateFormula currentFormula;
132 public FormulaContextImpl(MeasureMatrix matrix, ComponentIndex componentIndex, DebtRatingGrid debtRatingGrid) {
133 this.matrix = matrix;
134 this.componentIndex = componentIndex;
135 this.debtRatingGrid = debtRatingGrid;
138 void change(ComponentDto component, MeasureUpdateFormula formula) {
139 this.currentComponent = component;
140 this.currentFormula = formula;
143 public List<Double> getChildrenValues() {
144 List<ComponentDto> children = componentIndex.getChildren(currentComponent);
145 return children.stream()
146 .flatMap(c -> matrix.getMeasure(c, currentFormula.getMetric().getKey()).stream())
147 .map(LiveMeasureDto::getValue)
148 .filter(Objects::nonNull)
153 * Some child components may not have the measures 'SECURITY_HOTSPOTS_TO_REVIEW_STATUS' and 'SECURITY_HOTSPOTS_REVIEWED_STATUS' saved for them,
154 * so we may need to calculate them based on 'SECURITY_HOTSPOTS_REVIEWED' and 'SECURITY_HOTSPOTS'.
157 public long getChildrenHotspotsReviewed() {
158 return getChildrenHotspotsReviewed(SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY, SECURITY_HOTSPOTS_REVIEWED_KEY, SECURITY_HOTSPOTS_KEY);
162 * Some child components may not have the measure 'SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY'. We assume that 'SECURITY_HOTSPOTS_KEY' has the same value.
165 public long getChildrenHotspotsToReview() {
166 return componentIndex.getChildren(currentComponent)
168 .map(c -> matrix.getMeasure(c, SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY).or(() -> matrix.getMeasure(c, SECURITY_HOTSPOTS_KEY)))
169 .mapToLong(lmOpt -> lmOpt.flatMap(lm -> Optional.ofNullable(lm.getValue())).orElse(0D).longValue())
174 public long getChildrenNewHotspotsReviewed() {
175 return getChildrenHotspotsReviewed(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY, NEW_SECURITY_HOTSPOTS_REVIEWED_KEY, NEW_SECURITY_HOTSPOTS_KEY);
179 * 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.
182 public long getChildrenNewHotspotsToReview() {
183 return componentIndex.getChildren(currentComponent)
185 .map(c -> matrix.getMeasure(c, NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY).or(() -> matrix.getMeasure(c, NEW_SECURITY_HOTSPOTS_KEY)))
186 .mapToLong(lmOpt -> lmOpt.flatMap(lm -> Optional.ofNullable(lm.getValue())).orElse(0D).longValue())
190 private long getChildrenHotspotsReviewed(String metricKey, String percMetricKey, String hotspotsMetricKey) {
191 return componentIndex.getChildren(currentComponent)
193 .mapToLong(c -> getHotspotsReviewed(c, metricKey, percMetricKey, hotspotsMetricKey))
197 private long getHotspotsReviewed(ComponentDto c, String metricKey, String percMetricKey, String hotspotsMetricKey) {
198 Optional<LiveMeasureDto> measure = matrix.getMeasure(c, metricKey);
199 return measure.map(lm -> Optional.ofNullable(lm.getValue()).orElse(0D).longValue())
200 .orElseGet(() -> matrix.getMeasure(c, percMetricKey)
201 .flatMap(percentage -> matrix.getMeasure(c, hotspotsMetricKey)
203 double perc = Optional.ofNullable(percentage.getValue()).orElse(0D) / 100D;
204 double toReview = Optional.ofNullable(hotspots.getValue()).orElse(0D);
205 double reviewed = (toReview * perc) / (1D - perc);
206 return Math.round(reviewed);
214 public ComponentDto getComponent() {
215 return currentComponent;
219 public DebtRatingGrid getDebtRatingGrid() {
220 return debtRatingGrid;
224 public Optional<Double> getValue(Metric metric) {
225 Optional<LiveMeasureDto> measure = matrix.getMeasure(currentComponent, metric.getKey());
226 return measure.map(LiveMeasureDto::getValue);
230 public Optional<String> getText(Metric metric) {
231 Optional<LiveMeasureDto> measure = matrix.getMeasure(currentComponent, metric.getKey());
232 return measure.map(LiveMeasureDto::getTextValue);
236 public void setValue(double value) {
237 String metricKey = currentFormula.getMetric().getKey();
238 matrix.setValue(currentComponent, metricKey, value);
242 public void setValue(Rating value) {
243 String metricKey = currentFormula.getMetric().getKey();
244 matrix.setValue(currentComponent, metricKey, value);