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 dbClient.issueDao().selectIssueImpactGroupsByComponent(dbSession, c));
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)
153 public List<String> getChildrenTextValues() {
154 List<ComponentDto> children = componentIndex.getChildren(currentComponent);
155 return children.stream()
156 .flatMap(c -> matrix.getMeasure(c, currentFormula.getMetric().getKey()).stream())
157 .map(LiveMeasureDto::getTextValue)
158 .filter(Objects::nonNull)
163 * Some child components may not have the measures 'SECURITY_HOTSPOTS_TO_REVIEW_STATUS' and 'SECURITY_HOTSPOTS_REVIEWED_STATUS' saved for them,
164 * so we may need to calculate them based on 'SECURITY_HOTSPOTS_REVIEWED' and 'SECURITY_HOTSPOTS'.
167 public long getChildrenHotspotsReviewed() {
168 return getChildrenHotspotsReviewed(SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY, SECURITY_HOTSPOTS_REVIEWED_KEY, SECURITY_HOTSPOTS_KEY);
172 * Some child components may not have the measure 'SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY'. We assume that 'SECURITY_HOTSPOTS_KEY' has the same value.
175 public long getChildrenHotspotsToReview() {
176 return componentIndex.getChildren(currentComponent)
178 .map(c -> matrix.getMeasure(c, SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY).or(() -> matrix.getMeasure(c, SECURITY_HOTSPOTS_KEY)))
179 .mapToLong(lmOpt -> lmOpt.flatMap(lm -> Optional.ofNullable(lm.getValue())).orElse(0D).longValue())
184 public long getChildrenNewHotspotsReviewed() {
185 return getChildrenHotspotsReviewed(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY, NEW_SECURITY_HOTSPOTS_REVIEWED_KEY, NEW_SECURITY_HOTSPOTS_KEY);
189 * 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.
192 public long getChildrenNewHotspotsToReview() {
193 return componentIndex.getChildren(currentComponent)
195 .map(c -> matrix.getMeasure(c, NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY).or(() -> matrix.getMeasure(c, NEW_SECURITY_HOTSPOTS_KEY)))
196 .mapToLong(lmOpt -> lmOpt.flatMap(lm -> Optional.ofNullable(lm.getValue())).orElse(0D).longValue())
200 private long getChildrenHotspotsReviewed(String metricKey, String percMetricKey, String hotspotsMetricKey) {
201 return componentIndex.getChildren(currentComponent)
203 .mapToLong(c -> getHotspotsReviewed(c, metricKey, percMetricKey, hotspotsMetricKey))
207 private long getHotspotsReviewed(ComponentDto c, String metricKey, String percMetricKey, String hotspotsMetricKey) {
208 Optional<LiveMeasureDto> measure = matrix.getMeasure(c, metricKey);
209 return measure.map(lm -> Optional.ofNullable(lm.getValue()).orElse(0D).longValue())
210 .orElseGet(() -> matrix.getMeasure(c, percMetricKey)
211 .flatMap(percentage -> matrix.getMeasure(c, hotspotsMetricKey)
213 double perc = Optional.ofNullable(percentage.getValue()).orElse(0D) / 100D;
214 double toReview = Optional.ofNullable(hotspots.getValue()).orElse(0D);
215 double reviewed = (toReview * perc) / (1D - perc);
216 return Math.round(reviewed);
224 public ComponentDto getComponent() {
225 return currentComponent;
229 public DebtRatingGrid getDebtRatingGrid() {
230 return debtRatingGrid;
234 public Optional<Double> getValue(Metric metric) {
235 Optional<LiveMeasureDto> measure = matrix.getMeasure(currentComponent, metric.getKey());
236 return measure.map(LiveMeasureDto::getValue);
240 public Optional<String> getText(Metric metric) {
241 Optional<LiveMeasureDto> measure = matrix.getMeasure(currentComponent, metric.getKey());
242 return measure.map(LiveMeasureDto::getTextValue);
246 public void setValue(double value) {
247 String metricKey = currentFormula.getMetric().getKey();
248 matrix.setValue(currentComponent, metricKey, value);
252 public void setValue(Rating value) {
253 String metricKey = currentFormula.getMetric().getKey();
254 matrix.setValue(currentComponent, metricKey, value);
258 public void setValue(String value) {
259 String metricKey = currentFormula.getMetric().getKey();
260 matrix.setValue(currentComponent, metricKey, value);