3 * Copyright (C) 2009-2020 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 String label = String.format("%s (was %s)", rawStatus.getStatus().getColorName(), baseStatus.getStatus().getColorName());
114 createEvent(project, label, rawStatus.getText());
115 boolean isNewKo = rawStatus.getStatus() == Measure.Level.OK;
116 notifyUsers(project, label, rawStatus, isNewKo);
120 private void checkNewQualityGate(Component project, QualityGateStatus rawStatus) {
121 if (rawStatus.getStatus() != Measure.Level.OK) {
122 // There were no defined alerts before, so this one is a new one
123 createEvent(project, rawStatus.getStatus().getColorName(), rawStatus.getText());
124 notifyUsers(project, rawStatus.getStatus().getColorName(), rawStatus, true);
129 * @param label "Red (was Green)"
130 * @param rawStatus OK or ERROR + optional text
132 private void notifyUsers(Component project, String label, QualityGateStatus rawStatus, boolean isNewAlert) {
133 QGChangeNotification notification = new QGChangeNotification();
135 .setDefaultMessage(String.format("Alert on %s: %s", project.getName(), label))
136 .setFieldValue("projectName", project.getName())
137 .setFieldValue("projectKey", project.getKey())
138 .setFieldValue("projectVersion", project.getProjectAttributes().getProjectVersion())
139 .setFieldValue("alertName", label)
140 .setFieldValue("alertText", rawStatus.getText())
141 .setFieldValue("alertLevel", rawStatus.getStatus().toString())
142 .setFieldValue("isNewAlert", Boolean.toString(isNewAlert));
143 Branch branch = analysisMetadataHolder.getBranch();
144 if (!branch.isMain()) {
145 notification.setFieldValue("branch", branch.getName());
147 notificationService.deliverEmails(singleton(notification));
149 // compatibility with old API
150 notificationService.deliver(notification);
153 private void createEvent(Component project, String name, @Nullable String description) {
154 eventRepository.add(project, Event.createAlert(name, null, description));
158 public String getDescription() {
159 return "Generate Quality gate events";