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.ArrayList;
23 import java.util.Collection;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.Optional;
29 import javax.annotation.CheckForNull;
30 import org.sonar.api.config.Configuration;
31 import org.sonar.api.measures.Metric;
32 import org.slf4j.LoggerFactory;
33 import org.sonar.db.DbClient;
34 import org.sonar.db.DbSession;
35 import org.sonar.db.component.BranchDto;
36 import org.sonar.db.component.ComponentDto;
37 import org.sonar.db.component.SnapshotDto;
38 import org.sonar.db.measure.LiveMeasureComparator;
39 import org.sonar.db.measure.LiveMeasureDto;
40 import org.sonar.db.metric.MetricDto;
41 import org.sonar.db.project.ProjectDto;
42 import org.sonar.server.es.ProjectIndexer;
43 import org.sonar.server.es.ProjectIndexers;
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;
49 import static java.util.Collections.emptyList;
50 import static java.util.Collections.singleton;
51 import static java.util.stream.Collectors.groupingBy;
52 import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY;
53 import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
55 public class LiveMeasureComputerImpl implements LiveMeasureComputer {
57 private final DbClient dbClient;
58 private final MeasureUpdateFormulaFactory formulaFactory;
59 private final ComponentIndexFactory componentIndexFactory;
60 private final LiveQualityGateComputer qGateComputer;
61 private final ProjectConfigurationLoader projectConfigurationLoader;
62 private final ProjectIndexers projectIndexer;
63 private final LiveMeasureTreeUpdater treeUpdater;
65 public LiveMeasureComputerImpl(DbClient dbClient, MeasureUpdateFormulaFactory formulaFactory, ComponentIndexFactory componentIndexFactory,
66 LiveQualityGateComputer qGateComputer, ProjectConfigurationLoader projectConfigurationLoader, ProjectIndexers projectIndexer, LiveMeasureTreeUpdater treeUpdater) {
67 this.dbClient = dbClient;
68 this.formulaFactory = formulaFactory;
69 this.componentIndexFactory = componentIndexFactory;
70 this.qGateComputer = qGateComputer;
71 this.projectConfigurationLoader = projectConfigurationLoader;
72 this.projectIndexer = projectIndexer;
73 this.treeUpdater = treeUpdater;
77 public List<QGChangeEvent> refresh(DbSession dbSession, Collection<ComponentDto> components) {
78 if (components.isEmpty()) {
82 List<QGChangeEvent> result = new ArrayList<>();
83 Map<String, List<ComponentDto>> componentsByProjectUuid = components.stream().collect(groupingBy(ComponentDto::branchUuid));
84 for (List<ComponentDto> groupedComponents : componentsByProjectUuid.values()) {
85 Optional<QGChangeEvent> qgChangeEvent = refreshComponentsOnSameProject(dbSession, groupedComponents);
86 qgChangeEvent.ifPresent(result::add);
91 private Optional<QGChangeEvent> refreshComponentsOnSameProject(DbSession dbSession, List<ComponentDto> touchedComponents) {
92 ComponentIndex components = componentIndexFactory.create(dbSession, touchedComponents);
93 ComponentDto branchComponent = components.getBranch();
94 Optional<SnapshotDto> lastAnalysis = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, branchComponent.uuid());
95 if (lastAnalysis.isEmpty()) {
96 return Optional.empty();
99 BranchDto branch = loadBranch(dbSession, branchComponent);
100 ProjectDto project = loadProject(dbSession, branch.getProjectUuid());
101 Configuration config = projectConfigurationLoader.loadBranchConfiguration(dbSession, branch);
102 QualityGate qualityGate = qGateComputer.loadQualityGate(dbSession, project, branch);
103 MeasureMatrix matrix = loadMeasureMatrix(dbSession, components.getAllUuids(), qualityGate);
105 treeUpdater.update(dbSession, lastAnalysis.get(), config, components, branch, matrix);
107 Metric.Level previousStatus = loadPreviousStatus(dbSession, branchComponent);
108 EvaluatedQualityGate evaluatedQualityGate = qGateComputer.refreshGateStatus(branchComponent, qualityGate, matrix, config);
109 persistAndIndex(dbSession, matrix, branchComponent);
111 return Optional.of(new QGChangeEvent(project, branch, lastAnalysis.get(), config, previousStatus, () -> Optional.of(evaluatedQualityGate)));
114 private MeasureMatrix loadMeasureMatrix(DbSession dbSession, Set<String> componentUuids, QualityGate qualityGate) {
115 Collection<String> metricKeys = getKeysOfAllInvolvedMetrics(qualityGate);
116 Map<String, MetricDto> metricsPerUuid = dbClient.metricDao().selectByKeys(dbSession, metricKeys).stream().collect(uniqueIndex(MetricDto::getUuid));
117 List<LiveMeasureDto> measures = dbClient.liveMeasureDao().selectByComponentUuidsAndMetricUuids(dbSession, componentUuids, metricsPerUuid.keySet());
118 return new MeasureMatrix(componentUuids, metricsPerUuid.values(), measures);
121 private void persistAndIndex(DbSession dbSession, MeasureMatrix matrix, ComponentDto branchComponent) {
122 // persist the measures that have been created or updated
123 matrix.getChanged().sorted(LiveMeasureComparator.INSTANCE).forEach(m -> dbClient.liveMeasureDao().insertOrUpdate(dbSession, m));
124 projectIndexer.commitAndIndexComponents(dbSession, singleton(branchComponent), ProjectIndexer.Cause.MEASURE_CHANGE);
128 private Metric.Level loadPreviousStatus(DbSession dbSession, ComponentDto branchComponent) {
129 Optional<LiveMeasureDto> measure = dbClient.liveMeasureDao().selectMeasure(dbSession, branchComponent.uuid(), ALERT_STATUS_KEY);
130 if (measure.isEmpty()) {
135 return Metric.Level.valueOf(measure.get().getTextValue());
136 } catch (IllegalArgumentException e) {
137 LoggerFactory.getLogger(LiveMeasureComputerImpl.class).trace("Failed to parse value of metric '{}'", ALERT_STATUS_KEY, e);
142 private Set<String> getKeysOfAllInvolvedMetrics(QualityGate gate) {
143 Set<String> metricKeys = new HashSet<>();
144 for (Metric<?> metric : formulaFactory.getFormulaMetrics()) {
145 metricKeys.add(metric.getKey());
147 metricKeys.addAll(qGateComputer.getMetricsRelatedTo(gate));
151 private BranchDto loadBranch(DbSession dbSession, ComponentDto branchComponent) {
152 return dbClient.branchDao().selectByUuid(dbSession, branchComponent.uuid())
153 .orElseThrow(() -> new IllegalStateException("Branch not found: " + branchComponent.uuid()));
156 private ProjectDto loadProject(DbSession dbSession, String uuid) {
157 return dbClient.projectDao().selectByUuid(dbSession, uuid)
158 .orElseThrow(() -> new IllegalStateException("Project not found: " + uuid));