You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

QualityGateEventsStep.java 7.0KB

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