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.ce.task.projectanalysis.step;
22 import java.util.Optional;
23 import javax.annotation.Nullable;
24 import org.sonar.api.measures.CoreMetrics;
25 import org.sonar.api.utils.log.Logger;
26 import org.sonar.api.utils.log.Loggers;
27 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
28 import org.sonar.ce.task.projectanalysis.analysis.Branch;
29 import org.sonar.ce.task.projectanalysis.component.Component;
30 import org.sonar.ce.task.projectanalysis.component.ComponentVisitor;
31 import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
32 import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
33 import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
34 import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
35 import org.sonar.ce.task.projectanalysis.event.Event;
36 import org.sonar.ce.task.projectanalysis.event.EventRepository;
37 import org.sonar.ce.task.projectanalysis.measure.Measure;
38 import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
39 import org.sonar.ce.task.projectanalysis.measure.QualityGateStatus;
40 import org.sonar.ce.task.projectanalysis.metric.Metric;
41 import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
42 import org.sonar.ce.task.step.ComputationStep;
43 import org.sonar.server.notification.NotificationService;
44 import org.sonar.server.qualitygate.notification.QGChangeNotification;
46 import static java.util.Collections.singleton;
49 * This step must be executed after computation of quality gate measure {@link QualityGateMeasuresStep}
51 public class QualityGateEventsStep implements ComputationStep {
52 private static final Logger LOGGER = Loggers.get(QualityGateEventsStep.class);
54 private final TreeRootHolder treeRootHolder;
55 private final MetricRepository metricRepository;
56 private final MeasureRepository measureRepository;
57 private final EventRepository eventRepository;
58 private final NotificationService notificationService;
59 private final AnalysisMetadataHolder analysisMetadataHolder;
61 public QualityGateEventsStep(TreeRootHolder treeRootHolder,
62 MetricRepository metricRepository, MeasureRepository measureRepository, EventRepository eventRepository,
63 NotificationService notificationService, AnalysisMetadataHolder analysisMetadataHolder) {
64 this.treeRootHolder = treeRootHolder;
65 this.metricRepository = metricRepository;
66 this.measureRepository = measureRepository;
67 this.eventRepository = eventRepository;
68 this.notificationService = notificationService;
69 this.analysisMetadataHolder = analysisMetadataHolder;
73 public void execute(ComputationStep.Context context) {
74 // no notification on pull requests as there is no real Quality Gate on those
75 if (analysisMetadataHolder.isPullRequest()) {
78 new DepthTraversalTypeAwareCrawler(
79 new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, ComponentVisitor.Order.PRE_ORDER) {
81 public void visitProject(Component project) {
82 executeForProject(project);
84 }).visit(treeRootHolder.getRoot());
87 private void executeForProject(Component project) {
88 Metric metric = metricRepository.getByKey(CoreMetrics.ALERT_STATUS_KEY);
89 Optional<Measure> rawStatus = measureRepository.getRawMeasure(project, metric);
90 if (!rawStatus.isPresent() || !rawStatus.get().hasQualityGateStatus()) {
94 checkQualityGateStatusChange(project, metric, rawStatus.get().getQualityGateStatus());
97 private void checkQualityGateStatusChange(Component project, Metric metric, QualityGateStatus rawStatus) {
98 Optional<Measure> baseMeasure = measureRepository.getBaseMeasure(project, metric);
99 if (!baseMeasure.isPresent()) {
100 checkNewQualityGate(project, rawStatus);
104 if (!baseMeasure.get().hasQualityGateStatus()) {
105 LOGGER.warn(String.format("Previous Quality gate status for project %s is not a supported value. Can not compute Quality Gate event", project.getDbKey()));
106 checkNewQualityGate(project, rawStatus);
109 QualityGateStatus baseStatus = baseMeasure.get().getQualityGateStatus();
111 if (baseStatus.getStatus() != rawStatus.getStatus()) {
112 // The QualityGate status has changed
113 createEvent(project, rawStatus.getStatus().getLabel(), rawStatus.getText());
114 boolean isNewKo = rawStatus.getStatus() == Measure.Level.OK;
115 notifyUsers(project, rawStatus, isNewKo);
119 private void checkNewQualityGate(Component project, QualityGateStatus rawStatus) {
120 if (rawStatus.getStatus() != Measure.Level.OK) {
121 // There were no defined alerts before, so this one is a new one
122 createEvent(project, rawStatus.getStatus().getLabel(), rawStatus.getText());
123 notifyUsers(project, rawStatus, true);
128 * @param rawStatus OK or ERROR + optional text
130 private void notifyUsers(Component project, QualityGateStatus rawStatus, boolean isNewAlert) {
131 QGChangeNotification notification = new QGChangeNotification();
133 .setDefaultMessage(String.format("Alert on %s: %s", project.getName(), rawStatus.getStatus().getLabel()))
134 .setFieldValue("projectName", project.getName())
135 .setFieldValue("projectKey", project.getKey())
136 .setFieldValue("projectVersion", project.getProjectAttributes().getProjectVersion())
137 .setFieldValue("alertName", rawStatus.getStatus().getLabel())
138 .setFieldValue("alertText", rawStatus.getText())
139 .setFieldValue("alertLevel", rawStatus.getStatus().toString())
140 .setFieldValue("isNewAlert", Boolean.toString(isNewAlert));
141 Branch branch = analysisMetadataHolder.getBranch();
142 if (!branch.isMain()) {
143 notification.setFieldValue("branch", branch.getName());
145 notificationService.deliverEmails(singleton(notification));
147 // compatibility with old API
148 notificationService.deliver(notification);
151 private void createEvent(Component project, String name, @Nullable String description) {
152 eventRepository.add(project, Event.createAlert(name, null, description));
156 public String getDescription() {
157 return "Generate Quality gate events";