]> source.dussan.org Git - sonarqube.git/blob
bf2346048744e942a40877f236628dd6f2fa1bbb
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2019 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.api.posttask;
21
22 import java.util.Collection;
23 import java.util.Date;
24 import java.util.Map;
25 import java.util.Optional;
26 import java.util.Set;
27 import javax.annotation.CheckForNull;
28 import javax.annotation.Nullable;
29 import org.sonar.api.ce.posttask.Analysis;
30 import org.sonar.api.ce.posttask.Branch;
31 import org.sonar.api.ce.posttask.CeTask;
32 import org.sonar.api.ce.posttask.Organization;
33 import org.sonar.api.ce.posttask.PostProjectAnalysisTask;
34 import org.sonar.api.ce.posttask.Project;
35 import org.sonar.api.ce.posttask.QualityGate;
36 import org.sonar.api.ce.posttask.ScannerContext;
37 import org.sonar.api.utils.System2;
38 import org.sonar.api.utils.log.Logger;
39 import org.sonar.api.utils.log.Loggers;
40 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
41 import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
42 import org.sonar.ce.task.projectanalysis.qualitygate.Condition;
43 import org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus;
44 import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateHolder;
45 import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatus;
46 import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatusHolder;
47 import org.sonar.ce.task.step.ComputationStepExecutor;
48 import org.sonar.core.util.stream.MoreCollectors;
49
50 import static java.lang.String.format;
51 import static java.util.Objects.requireNonNull;
52 import static java.util.Optional.empty;
53 import static java.util.Optional.of;
54 import static java.util.Optional.ofNullable;
55 import static org.sonar.api.ce.posttask.CeTask.Status.FAILED;
56 import static org.sonar.api.ce.posttask.CeTask.Status.SUCCESS;
57 import static org.sonar.db.component.BranchType.PULL_REQUEST;
58
59 /**
60  * Responsible for calling {@link PostProjectAnalysisTask} implementations (if any).
61  */
62 public class PostProjectAnalysisTasksExecutor implements ComputationStepExecutor.Listener {
63   private static final PostProjectAnalysisTask[] NO_POST_PROJECT_ANALYSIS_TASKS = new PostProjectAnalysisTask[0];
64
65   private static final Logger LOG = Loggers.get(PostProjectAnalysisTasksExecutor.class);
66
67   private final org.sonar.ce.task.CeTask ceTask;
68   private final AnalysisMetadataHolder analysisMetadataHolder;
69   private final QualityGateHolder qualityGateHolder;
70   private final QualityGateStatusHolder qualityGateStatusHolder;
71   private final PostProjectAnalysisTask[] postProjectAnalysisTasks;
72   private final BatchReportReader reportReader;
73   private final System2 system2;
74
75   /**
76    * Constructor used by Pico when there is no {@link PostProjectAnalysisTask} in the container.
77    */
78   public PostProjectAnalysisTasksExecutor(org.sonar.ce.task.CeTask ceTask,
79                                           AnalysisMetadataHolder analysisMetadataHolder,
80                                           QualityGateHolder qualityGateHolder, QualityGateStatusHolder qualityGateStatusHolder,
81                                           BatchReportReader reportReader, System2 system2) {
82     this(ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader, system2, null);
83   }
84
85   public PostProjectAnalysisTasksExecutor(org.sonar.ce.task.CeTask ceTask,
86                                           AnalysisMetadataHolder analysisMetadataHolder,
87                                           QualityGateHolder qualityGateHolder, QualityGateStatusHolder qualityGateStatusHolder,
88                                           BatchReportReader reportReader, System2 system2,
89                                           @Nullable PostProjectAnalysisTask[] postProjectAnalysisTasks) {
90     this.analysisMetadataHolder = analysisMetadataHolder;
91     this.qualityGateHolder = qualityGateHolder;
92     this.qualityGateStatusHolder = qualityGateStatusHolder;
93     this.ceTask = ceTask;
94     this.reportReader = reportReader;
95     this.postProjectAnalysisTasks = postProjectAnalysisTasks == null ? NO_POST_PROJECT_ANALYSIS_TASKS : postProjectAnalysisTasks;
96     this.system2 = system2;
97   }
98
99   @Override
100   public void finished(boolean allStepsExecuted) {
101     if (postProjectAnalysisTasks.length == 0) {
102       return;
103     }
104
105     ProjectAnalysisImpl projectAnalysis = createProjectAnalysis(allStepsExecuted ? SUCCESS : FAILED);
106     for (PostProjectAnalysisTask postProjectAnalysisTask : postProjectAnalysisTasks) {
107       executeTask(projectAnalysis, postProjectAnalysisTask);
108     }
109   }
110
111   private static void executeTask(ProjectAnalysisImpl projectAnalysis, PostProjectAnalysisTask postProjectAnalysisTask) {
112     try {
113       postProjectAnalysisTask.finished(projectAnalysis);
114     } catch (Exception e) {
115       LOG.error("Execution of task " + postProjectAnalysisTask.getClass() + " failed", e);
116     }
117   }
118
119   private ProjectAnalysisImpl createProjectAnalysis(CeTask.Status status) {
120     return new ProjectAnalysisImpl(
121       createOrganization(),
122       new CeTaskImpl(this.ceTask.getUuid(), status),
123       createProject(this.ceTask),
124       getAnalysis().orElse(null),
125       getAnalysis().map(a -> a.getDate().getTime()).orElse(system2.now()),
126       ScannerContextImpl.from(reportReader.readContextProperties()),
127       status == SUCCESS ? createQualityGate() : null,
128       createBranch(),
129       reportReader.readMetadata().getScmRevisionId()
130     );
131   }
132
133   @CheckForNull
134   private Organization createOrganization() {
135     if (!analysisMetadataHolder.isOrganizationsEnabled()) {
136       return null;
137     }
138     org.sonar.ce.task.projectanalysis.analysis.Organization organization = analysisMetadataHolder.getOrganization();
139     return new OrganizationImpl(organization.getName(), organization.getKey());
140   }
141
142   private Optional<Analysis> getAnalysis() {
143     Long analysisDate = getAnalysisDate();
144
145     if (analysisDate != null) {
146       return of(new AnalysisImpl(analysisMetadataHolder.getUuid(), analysisDate));
147     } else {
148       return empty();
149     }
150   }
151
152   private static Project createProject(org.sonar.ce.task.CeTask ceTask) {
153     return ceTask.getMainComponent()
154       .map(c -> new ProjectImpl(
155         c.getUuid(),
156         c.getKey().orElseThrow(() -> new IllegalStateException("Missing project key")),
157         c.getName().orElseThrow(() -> new IllegalStateException("Missing project name"))))
158       .orElseThrow(() -> new IllegalStateException("Report processed for a task of a deleted component"));
159   }
160
161   @CheckForNull
162   private Long getAnalysisDate() {
163     if (this.analysisMetadataHolder.hasAnalysisDateBeenSet()) {
164       return this.analysisMetadataHolder.getAnalysisDate();
165     }
166     return null;
167   }
168
169   @CheckForNull
170   private QualityGate createQualityGate() {
171     Optional<org.sonar.ce.task.projectanalysis.qualitygate.QualityGate> qualityGateOptional = this.qualityGateHolder.getQualityGate();
172     if (qualityGateOptional.isPresent()) {
173       org.sonar.ce.task.projectanalysis.qualitygate.QualityGate qualityGate = qualityGateOptional.get();
174
175       return new QualityGateImpl(
176         String.valueOf(qualityGate.getId()),
177         qualityGate.getName(),
178         convert(qualityGateStatusHolder.getStatus()),
179         convert(qualityGate.getConditions(), qualityGateStatusHolder.getStatusPerConditions()));
180     }
181     return null;
182   }
183
184   @CheckForNull
185   private BranchImpl createBranch() {
186     org.sonar.ce.task.projectanalysis.analysis.Branch analysisBranch = analysisMetadataHolder.getBranch();
187     if (!analysisBranch.isLegacyFeature()) {
188       String branchKey = analysisBranch.getType() == PULL_REQUEST ? analysisBranch.getPullRequestKey() : analysisBranch.getName();
189       return new BranchImpl(analysisBranch.isMain(), branchKey, Branch.Type.valueOf(analysisBranch.getType().name()));
190     }
191     return null;
192   }
193
194   private static QualityGate.Status convert(QualityGateStatus status) {
195     switch (status) {
196       case OK:
197         return QualityGate.Status.OK;
198       case ERROR:
199         return QualityGate.Status.ERROR;
200       default:
201         throw new IllegalArgumentException(format(
202           "Unsupported value '%s' of QualityGateStatus can not be converted to QualityGate.Status",
203           status));
204     }
205   }
206
207   private static Collection<QualityGate.Condition> convert(Set<Condition> conditions, Map<Condition, ConditionStatus> statusPerConditions) {
208     return conditions.stream()
209       .map(new ConditionToCondition(statusPerConditions)::apply)
210       .collect(MoreCollectors.toList(statusPerConditions.size()));
211   }
212
213   private static class ProjectAnalysisImpl implements PostProjectAnalysisTask.ProjectAnalysis {
214     @Nullable
215     private final Organization organization;
216     private final CeTask ceTask;
217     private final Project project;
218     private final long date;
219     private final ScannerContext scannerContext;
220     @Nullable
221     private final QualityGate qualityGate;
222     @Nullable
223     private final Branch branch;
224     @Nullable
225     private final Analysis analysis;
226     private final String scmRevisionId;
227
228     private ProjectAnalysisImpl(@Nullable Organization organization, CeTask ceTask, Project project,
229       @Nullable Analysis analysis, long date,
230       ScannerContext scannerContext, @Nullable QualityGate qualityGate, @Nullable Branch branch, String scmRevisionId) {
231       this.organization = organization;
232       this.ceTask = requireNonNull(ceTask, "ceTask can not be null");
233       this.project = requireNonNull(project, "project can not be null");
234       this.analysis = analysis;
235       this.date = date;
236       this.scannerContext = requireNonNull(scannerContext, "scannerContext can not be null");
237       this.qualityGate = qualityGate;
238       this.branch = branch;
239       this.scmRevisionId = scmRevisionId;
240     }
241
242     @Override
243     public Optional<Organization> getOrganization() {
244       return Optional.ofNullable(organization);
245     }
246
247     @Override
248     public CeTask getCeTask() {
249       return ceTask;
250     }
251
252     @Override
253     public Project getProject() {
254       return project;
255     }
256
257     @Override
258     public Optional<Branch> getBranch() {
259       return ofNullable(branch);
260     }
261
262     @Override
263     @CheckForNull
264     public QualityGate getQualityGate() {
265       return qualityGate;
266     }
267
268     @Override
269     public Date getDate() {
270       return new Date(date);
271     }
272
273     @Override
274     public Optional<Date> getAnalysisDate() {
275       return analysis == null ? empty() : ofNullable(analysis.getDate());
276     }
277
278     @Override
279     public Optional<Analysis> getAnalysis() {
280       return ofNullable(analysis);
281     }
282
283     @Override
284     public ScannerContext getScannerContext() {
285       return scannerContext;
286     }
287
288     @Override
289     public String getScmRevisionId() {
290       return scmRevisionId;
291     }
292
293     @Override
294     public String toString() {
295       return "ProjectAnalysis{" +
296         "ceTask=" + ceTask +
297         ", project=" + project +
298         ", date=" + date +
299         ", scannerContext=" + scannerContext +
300         ", qualityGate=" + qualityGate +
301         ", analysis=" + analysis +
302         '}';
303     }
304   }
305
306   private static class AnalysisImpl implements Analysis {
307
308     private final String analysisUuid;
309     private final long date;
310
311     private AnalysisImpl(String analysisUuid, long date) {
312       this.analysisUuid = analysisUuid;
313       this.date = date;
314     }
315
316     @Override
317     public String getAnalysisUuid() {
318       return analysisUuid;
319     }
320
321     @Override
322     public Date getDate() {
323       return new Date(date);
324     }
325   }
326
327   private static class OrganizationImpl implements Organization {
328     private final String name;
329     private final String key;
330
331     private OrganizationImpl(String name, String key) {
332       this.name = requireNonNull(name, "name can't be null");
333       this.key = requireNonNull(key, "key can't be null");
334     }
335
336     @Override
337     public String getName() {
338       return name;
339     }
340
341     @Override
342     public String getKey() {
343       return key;
344     }
345   }
346 }