3 * Copyright (C) 2009-2019 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.notifications.Notification;
26 import org.sonar.api.utils.log.Logger;
27 import org.sonar.api.utils.log.Loggers;
28 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
29 import org.sonar.ce.task.projectanalysis.analysis.Branch;
30 import org.sonar.ce.task.projectanalysis.component.Component;
31 import org.sonar.ce.task.projectanalysis.component.ComponentVisitor;
32 import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
33 import org.sonar.ce.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
34 import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
35 import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter;
36 import org.sonar.ce.task.projectanalysis.event.Event;
37 import org.sonar.ce.task.projectanalysis.event.EventRepository;
38 import org.sonar.ce.task.projectanalysis.measure.Measure;
39 import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
40 import org.sonar.ce.task.projectanalysis.measure.QualityGateStatus;
41 import org.sonar.ce.task.projectanalysis.metric.Metric;
42 import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
43 import org.sonar.ce.task.step.ComputationStep;
44 import org.sonar.server.notification.NotificationService;
47 * This step must be executed after computation of quality gate measure {@link QualityGateMeasuresStep}
49 public class QualityGateEventsStep implements ComputationStep {
50 private static final Logger LOGGER = Loggers.get(QualityGateEventsStep.class);
52 private final TreeRootHolder treeRootHolder;
53 private final MetricRepository metricRepository;
54 private final MeasureRepository measureRepository;
55 private final EventRepository eventRepository;
56 private final NotificationService notificationService;
57 private final AnalysisMetadataHolder analysisMetadataHolder;
59 public QualityGateEventsStep(TreeRootHolder treeRootHolder,
60 MetricRepository metricRepository, MeasureRepository measureRepository, EventRepository eventRepository,
61 NotificationService notificationService, AnalysisMetadataHolder analysisMetadataHolder) {
62 this.treeRootHolder = treeRootHolder;
63 this.metricRepository = metricRepository;
64 this.measureRepository = measureRepository;
65 this.eventRepository = eventRepository;
66 this.notificationService = notificationService;
67 this.analysisMetadataHolder = analysisMetadataHolder;
71 public void execute(ComputationStep.Context context) {
72 // no notification on short living branch and pull request as there is no real Quality Gate on those
73 if (analysisMetadataHolder.isShortLivingBranch() || analysisMetadataHolder.isPullRequest()) {
76 new DepthTraversalTypeAwareCrawler(
77 new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT, ComponentVisitor.Order.PRE_ORDER) {
79 public void visitProject(Component project) {
80 executeForProject(project);
82 }).visit(treeRootHolder.getRoot());
85 private void executeForProject(Component project) {
86 Metric metric = metricRepository.getByKey(CoreMetrics.ALERT_STATUS_KEY);
87 Optional<Measure> rawStatus = measureRepository.getRawMeasure(project, metric);
88 if (!rawStatus.isPresent() || !rawStatus.get().hasQualityGateStatus()) {
92 checkQualityGateStatusChange(project, metric, rawStatus.get().getQualityGateStatus());
95 private void checkQualityGateStatusChange(Component project, Metric metric, QualityGateStatus rawStatus) {
96 Optional<Measure> baseMeasure = measureRepository.getBaseMeasure(project, metric);
97 if (!baseMeasure.isPresent()) {
98 checkNewQualityGate(project, rawStatus);
102 if (!baseMeasure.get().hasQualityGateStatus()) {
103 LOGGER.warn(String.format("Previous Quality gate status for project %s is not a supported value. Can not compute Quality Gate event", project.getDbKey()));
104 checkNewQualityGate(project, rawStatus);
107 QualityGateStatus baseStatus = baseMeasure.get().getQualityGateStatus();
109 if (baseStatus.getStatus() != rawStatus.getStatus()) {
110 // The QualityGate status has changed
111 String label = String.format("%s (was %s)", rawStatus.getStatus().getColorName(), baseStatus.getStatus().getColorName());
112 createEvent(project, label, rawStatus.getText());
113 boolean isNewKo = rawStatus.getStatus() == Measure.Level.OK;
114 notifyUsers(project, label, rawStatus, isNewKo);
118 private void checkNewQualityGate(Component project, QualityGateStatus rawStatus) {
119 if (rawStatus.getStatus() != Measure.Level.OK) {
120 // There were no defined alerts before, so this one is a new one
121 createEvent(project, rawStatus.getStatus().getColorName(), rawStatus.getText());
122 notifyUsers(project, rawStatus.getStatus().getColorName(), rawStatus, true);
127 * @param label "Red (was Orange)"
128 * @param rawStatus OK, WARN or ERROR + optional text
130 private void notifyUsers(Component project, String label, QualityGateStatus rawStatus, boolean isNewAlert) {
131 Notification notification = new Notification("alerts")
132 .setDefaultMessage(String.format("Alert on %s: %s", project.getName(), label))
133 .setFieldValue("projectName", project.getName())
134 .setFieldValue("projectKey", project.getKey())
135 .setFieldValue("projectVersion", project.getProjectAttributes().getVersion())
136 .setFieldValue("alertName", label)
137 .setFieldValue("alertText", rawStatus.getText())
138 .setFieldValue("alertLevel", rawStatus.getStatus().toString())
139 .setFieldValue("isNewAlert", Boolean.toString(isNewAlert));
140 Branch branch = analysisMetadataHolder.getBranch();
141 if (!branch.isMain()) {
142 notification.setFieldValue("branch", branch.getName());
144 notificationService.deliver(notification);
147 private void createEvent(Component project, String name, @Nullable String description) {
148 eventRepository.add(project, Event.createAlert(name, null, description));
152 public String getDescription() {
153 return "Generate Quality gate events";