]> source.dussan.org Git - sonarqube.git/blob
1857c6205dd0e70747755d9f8cb9e3c0ff7f318c
[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   @CheckForNull
133   private Organization createOrganization() {
134     if (!analysisMetadataHolder.isOrganizationsEnabled()) {
135       return null;
136     }
137     org.sonar.ce.task.projectanalysis.analysis.Organization organization = analysisMetadataHolder.getOrganization();
138     return new OrganizationImpl(organization.getName(), organization.getKey());
139   }
140
141   private Optional<Analysis> getAnalysis() {
142     Long analysisDate = getAnalysisDate();
143
144     if (analysisDate != null) {
145       return of(new AnalysisImpl(analysisMetadataHolder.getUuid(), analysisDate, analysisMetadataHolder.getScmRevisionId()));
146     }
147     return empty();
148   }
149
150   private static Project createProject(org.sonar.ce.task.CeTask ceTask) {
151     return ceTask.getMainComponent()
152       .map(c -> new ProjectImpl(
153         c.getUuid(),
154         c.getKey().orElseThrow(() -> new IllegalStateException("Missing project key")),
155         c.getName().orElseThrow(() -> new IllegalStateException("Missing project name"))))
156       .orElseThrow(() -> new IllegalStateException("Report processed for a task of a deleted component"));
157   }
158
159   @CheckForNull
160   private Long getAnalysisDate() {
161     if (this.analysisMetadataHolder.hasAnalysisDateBeenSet()) {
162       return this.analysisMetadataHolder.getAnalysisDate();
163     }
164     return null;
165   }
166
167   @CheckForNull
168   private QualityGate createQualityGate() {
169     Optional<org.sonar.ce.task.projectanalysis.qualitygate.QualityGate> qualityGateOptional = this.qualityGateHolder.getQualityGate();
170     if (qualityGateOptional.isPresent()) {
171       org.sonar.ce.task.projectanalysis.qualitygate.QualityGate qualityGate = qualityGateOptional.get();
172
173       return new QualityGateImpl(
174         String.valueOf(qualityGate.getId()),
175         qualityGate.getName(),
176         convert(qualityGateStatusHolder.getStatus()),
177         convert(qualityGate.getConditions(), qualityGateStatusHolder.getStatusPerConditions()));
178     }
179     return null;
180   }
181
182   @CheckForNull
183   private BranchImpl createBranch() {
184     org.sonar.ce.task.projectanalysis.analysis.Branch analysisBranch = analysisMetadataHolder.getBranch();
185     if (!analysisBranch.isLegacyFeature()) {
186       String branchKey = analysisBranch.getType() == PULL_REQUEST ? analysisBranch.getPullRequestKey() : analysisBranch.getName();
187       return new BranchImpl(analysisBranch.isMain(), branchKey, Branch.Type.valueOf(analysisBranch.getType().name()));
188     }
189     return null;
190   }
191
192   private static QualityGate.Status convert(QualityGateStatus status) {
193     switch (status) {
194       case OK:
195         return QualityGate.Status.OK;
196       case ERROR:
197         return QualityGate.Status.ERROR;
198       default:
199         throw new IllegalArgumentException(format(
200           "Unsupported value '%s' of QualityGateStatus can not be converted to QualityGate.Status",
201           status));
202     }
203   }
204
205   private static Collection<QualityGate.Condition> convert(Set<Condition> conditions, Map<Condition, ConditionStatus> statusPerConditions) {
206     return conditions.stream()
207       .map(new ConditionToCondition(statusPerConditions)::apply)
208       .collect(MoreCollectors.toList(statusPerConditions.size()));
209   }
210
211   private static class ProjectAnalysisImpl implements PostProjectAnalysisTask.ProjectAnalysis {
212     @Nullable
213     private final Organization organization;
214     private final CeTask ceTask;
215     private final Project project;
216     private final long date;
217     private final ScannerContext scannerContext;
218     @Nullable
219     private final QualityGate qualityGate;
220     @Nullable
221     private final Branch branch;
222     @Nullable
223     private final Analysis analysis;
224     private final String scmRevisionId;
225
226     private ProjectAnalysisImpl(@Nullable Organization organization, CeTask ceTask, Project project,
227       @Nullable Analysis analysis, long date,
228       ScannerContext scannerContext, @Nullable QualityGate qualityGate, @Nullable Branch branch, String scmRevisionId) {
229       this.organization = organization;
230       this.ceTask = requireNonNull(ceTask, "ceTask can not be null");
231       this.project = requireNonNull(project, "project can not be null");
232       this.analysis = analysis;
233       this.date = date;
234       this.scannerContext = requireNonNull(scannerContext, "scannerContext can not be null");
235       this.qualityGate = qualityGate;
236       this.branch = branch;
237       this.scmRevisionId = scmRevisionId;
238     }
239
240     @Override
241     public Optional<Organization> getOrganization() {
242       return Optional.ofNullable(organization);
243     }
244
245     @Override
246     public CeTask getCeTask() {
247       return ceTask;
248     }
249
250     @Override
251     public Project getProject() {
252       return project;
253     }
254
255     @Override
256     public Optional<Branch> getBranch() {
257       return ofNullable(branch);
258     }
259
260     @Override
261     @CheckForNull
262     public QualityGate getQualityGate() {
263       return qualityGate;
264     }
265
266     @Override
267     public Date getDate() {
268       return new Date(date);
269     }
270
271     @Override
272     public Optional<Date> getAnalysisDate() {
273       return analysis == null ? empty() : ofNullable(analysis.getDate());
274     }
275
276     @Override
277     public Optional<Analysis> getAnalysis() {
278       return ofNullable(analysis);
279     }
280
281     @Override
282     public ScannerContext getScannerContext() {
283       return scannerContext;
284     }
285
286     @Override
287     public String getScmRevisionId() {
288       return scmRevisionId;
289     }
290
291     @Override
292     public String toString() {
293       return "ProjectAnalysis{" +
294         "ceTask=" + ceTask +
295         ", project=" + project +
296         ", date=" + date +
297         ", scannerContext=" + scannerContext +
298         ", qualityGate=" + qualityGate +
299         ", analysis=" + analysis +
300         '}';
301     }
302   }
303
304   private static class AnalysisImpl implements Analysis {
305
306     private final String analysisUuid;
307     private final long date;
308     private final Optional<String> revision;
309
310     private AnalysisImpl(String analysisUuid, long date, Optional<String> revision) {
311       this.analysisUuid = analysisUuid;
312       this.date = date;
313       this.revision = revision;
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     @Override
327     public Optional<String> getRevision() {
328       return revision;
329     }
330   }
331
332   private static class OrganizationImpl implements Organization {
333     private final String name;
334     private final String key;
335
336     private OrganizationImpl(String name, String key) {
337       this.name = requireNonNull(name, "name can't be null");
338       this.key = requireNonNull(key, "key can't be null");
339     }
340
341     @Override
342     public String getName() {
343       return name;
344     }
345
346     @Override
347     public String getKey() {
348       return key;
349     }
350   }
351 }