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.

ReportPublisher.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 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.scanner.report;
  21. import java.io.File;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.io.UnsupportedEncodingException;
  25. import java.io.Writer;
  26. import java.net.URL;
  27. import java.nio.charset.StandardCharsets;
  28. import java.nio.file.Files;
  29. import java.nio.file.Path;
  30. import java.util.LinkedHashMap;
  31. import java.util.Map;
  32. import javax.annotation.Nullable;
  33. import okhttp3.HttpUrl;
  34. import org.apache.commons.io.FileUtils;
  35. import org.picocontainer.Startable;
  36. import org.sonar.api.platform.Server;
  37. import org.sonar.api.utils.MessageException;
  38. import org.sonar.api.utils.TempFolder;
  39. import org.sonar.api.utils.ZipUtils;
  40. import org.sonar.api.utils.log.Logger;
  41. import org.sonar.api.utils.log.Loggers;
  42. import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
  43. import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
  44. import org.sonar.scanner.fs.InputModuleHierarchy;
  45. import org.sonar.scanner.protocol.output.ScannerReportReader;
  46. import org.sonar.scanner.protocol.output.ScannerReportWriter;
  47. import org.sonar.scanner.scan.ScanProperties;
  48. import org.sonar.scanner.scan.branch.BranchConfiguration;
  49. import org.sonar.scanner.scan.branch.BranchType;
  50. import org.sonarqube.ws.Ce;
  51. import org.sonarqube.ws.MediaTypes;
  52. import org.sonarqube.ws.client.HttpException;
  53. import org.sonarqube.ws.client.PostRequest;
  54. import org.sonarqube.ws.client.WsResponse;
  55. import static java.net.URLEncoder.encode;
  56. import static org.apache.commons.lang.StringUtils.EMPTY;
  57. import static org.apache.commons.lang.StringUtils.isBlank;
  58. import static org.sonar.core.util.FileUtils.deleteQuietly;
  59. import static org.sonar.scanner.scan.branch.BranchType.PULL_REQUEST;
  60. public class ReportPublisher implements Startable {
  61. private static final int DEFAULT_WRITE_TIMEOUT = 30_000;
  62. private static final Logger LOG = Loggers.get(ReportPublisher.class);
  63. private static final String CHARACTERISTIC = "characteristic";
  64. private static final String DASHBOARD = "dashboard";
  65. private static final String BRANCH = "branch";
  66. private static final String ID = "id";
  67. private final DefaultScannerWsClient wsClient;
  68. private final AnalysisContextReportPublisher contextPublisher;
  69. private final InputModuleHierarchy moduleHierarchy;
  70. private final GlobalAnalysisMode analysisMode;
  71. private final TempFolder temp;
  72. private final ReportPublisherStep[] publishers;
  73. private final Server server;
  74. private final BranchConfiguration branchConfiguration;
  75. private final ScanProperties properties;
  76. private final CeTaskReportDataHolder ceTaskReportDataHolder;
  77. private Path reportDir;
  78. private ScannerReportWriter writer;
  79. private ScannerReportReader reader;
  80. public ReportPublisher(ScanProperties properties, DefaultScannerWsClient wsClient, Server server, AnalysisContextReportPublisher contextPublisher,
  81. InputModuleHierarchy moduleHierarchy, GlobalAnalysisMode analysisMode, TempFolder temp, ReportPublisherStep[] publishers, BranchConfiguration branchConfiguration,
  82. CeTaskReportDataHolder ceTaskReportDataHolder) {
  83. this.wsClient = wsClient;
  84. this.server = server;
  85. this.contextPublisher = contextPublisher;
  86. this.moduleHierarchy = moduleHierarchy;
  87. this.analysisMode = analysisMode;
  88. this.temp = temp;
  89. this.publishers = publishers;
  90. this.branchConfiguration = branchConfiguration;
  91. this.properties = properties;
  92. this.ceTaskReportDataHolder = ceTaskReportDataHolder;
  93. }
  94. @Override
  95. public void start() {
  96. reportDir = moduleHierarchy.root().getWorkDir().resolve("scanner-report");
  97. writer = new ScannerReportWriter(reportDir.toFile());
  98. reader = new ScannerReportReader(reportDir.toFile());
  99. contextPublisher.init(writer);
  100. if (!analysisMode.isMediumTest()) {
  101. String publicUrl = server.getPublicRootUrl();
  102. if (HttpUrl.parse(publicUrl) == null) {
  103. throw MessageException.of("Failed to parse public URL set in SonarQube server: " + publicUrl);
  104. }
  105. }
  106. }
  107. @Override
  108. public void stop() {
  109. if (!properties.shouldKeepReport()) {
  110. deleteQuietly(reportDir);
  111. }
  112. }
  113. public Path getReportDir() {
  114. return reportDir;
  115. }
  116. public ScannerReportWriter getWriter() {
  117. return writer;
  118. }
  119. public ScannerReportReader getReader() {
  120. return reader;
  121. }
  122. public void execute() {
  123. File report = generateReportFile();
  124. if (properties.shouldKeepReport()) {
  125. LOG.info("Analysis report generated in " + reportDir);
  126. }
  127. if (!analysisMode.isMediumTest()) {
  128. String taskId = upload(report);
  129. prepareAndDumpMetadata(taskId);
  130. }
  131. logSuccess();
  132. }
  133. private void logSuccess() {
  134. if (analysisMode.isMediumTest()) {
  135. LOG.info("ANALYSIS SUCCESSFUL");
  136. } else if (!properties.shouldWaitForQualityGate()) {
  137. LOG.info("ANALYSIS SUCCESSFUL, you can browse {}", ceTaskReportDataHolder.getDashboardUrl());
  138. LOG.info("Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report");
  139. LOG.info("More about the report processing at {}", ceTaskReportDataHolder.getCeTaskUrl());
  140. }
  141. }
  142. private File generateReportFile() {
  143. try {
  144. long startTime = System.currentTimeMillis();
  145. for (ReportPublisherStep publisher : publishers) {
  146. publisher.publish(writer);
  147. }
  148. long stopTime = System.currentTimeMillis();
  149. LOG.info("Analysis report generated in {}ms, dir size={}", stopTime - startTime, FileUtils.byteCountToDisplaySize(FileUtils.sizeOfDirectory(reportDir.toFile())));
  150. startTime = System.currentTimeMillis();
  151. File reportZip = temp.newFile("scanner-report", ".zip");
  152. ZipUtils.zipDir(reportDir.toFile(), reportZip);
  153. stopTime = System.currentTimeMillis();
  154. LOG.info("Analysis report compressed in {}ms, zip size={}", stopTime - startTime, FileUtils.byteCountToDisplaySize(FileUtils.sizeOf(reportZip)));
  155. return reportZip;
  156. } catch (IOException e) {
  157. throw new IllegalStateException("Unable to prepare analysis report", e);
  158. }
  159. }
  160. /**
  161. * Uploads the report file to server and returns the generated task id
  162. */
  163. String upload(File report) {
  164. LOG.debug("Upload report");
  165. long startTime = System.currentTimeMillis();
  166. PostRequest.Part filePart = new PostRequest.Part(MediaTypes.ZIP, report);
  167. PostRequest post = new PostRequest("api/ce/submit")
  168. .setMediaType(MediaTypes.PROTOBUF)
  169. .setParam("projectKey", moduleHierarchy.root().key())
  170. .setParam("projectName", moduleHierarchy.root().getOriginalName())
  171. .setPart("report", filePart);
  172. String branchName = branchConfiguration.branchName();
  173. if (branchName != null) {
  174. if (branchConfiguration.branchType() != PULL_REQUEST) {
  175. post.setParam(CHARACTERISTIC, "branch=" + branchName);
  176. post.setParam(CHARACTERISTIC, "branchType=" + branchConfiguration.branchType().name());
  177. } else {
  178. post.setParam(CHARACTERISTIC, "pullRequest=" + branchConfiguration.pullRequestKey());
  179. }
  180. }
  181. WsResponse response;
  182. try {
  183. post.setWriteTimeOutInMs(DEFAULT_WRITE_TIMEOUT);
  184. response = wsClient.call(post).failIfNotSuccessful();
  185. } catch (HttpException e) {
  186. throw MessageException.of(String.format("Failed to upload report - %s", DefaultScannerWsClient.createErrorMessage(e)));
  187. }
  188. try (InputStream protobuf = response.contentStream()) {
  189. return Ce.SubmitResponse.parser().parseFrom(protobuf).getTaskId();
  190. } catch (Exception e) {
  191. throw new RuntimeException(e);
  192. } finally {
  193. long stopTime = System.currentTimeMillis();
  194. LOG.info("Analysis report uploaded in " + (stopTime - startTime) + "ms");
  195. }
  196. }
  197. void prepareAndDumpMetadata(String taskId) {
  198. Map<String, String> metadata = new LinkedHashMap<>();
  199. metadata.put("projectKey", moduleHierarchy.root().key());
  200. metadata.put("serverUrl", server.getPublicRootUrl());
  201. metadata.put("serverVersion", server.getVersion());
  202. properties.branch().ifPresent(branch -> metadata.put("branch", branch));
  203. URL dashboardUrl = buildDashboardUrl(server.getPublicRootUrl(), moduleHierarchy.root().key());
  204. metadata.put("dashboardUrl", dashboardUrl.toExternalForm());
  205. URL taskUrl = HttpUrl.parse(server.getPublicRootUrl()).newBuilder()
  206. .addPathSegment("api").addPathSegment("ce").addPathSegment("task")
  207. .addQueryParameter(ID, taskId)
  208. .build()
  209. .url();
  210. metadata.put("ceTaskId", taskId);
  211. metadata.put("ceTaskUrl", taskUrl.toExternalForm());
  212. ceTaskReportDataHolder.init(taskId, taskUrl.toExternalForm(), dashboardUrl.toExternalForm());
  213. dumpMetadata(metadata);
  214. }
  215. private URL buildDashboardUrl(String publicUrl, String effectiveKey) {
  216. HttpUrl httpUrl = HttpUrl.parse(publicUrl);
  217. if (onPullRequest(branchConfiguration)) {
  218. return httpUrl.newBuilder()
  219. .addPathSegment(DASHBOARD)
  220. .addEncodedQueryParameter(ID, encoded(effectiveKey))
  221. .addEncodedQueryParameter("pullRequest", encoded(branchConfiguration.pullRequestKey()))
  222. .build()
  223. .url();
  224. }
  225. if (onBranch(branchConfiguration)) {
  226. return httpUrl.newBuilder()
  227. .addPathSegment(DASHBOARD)
  228. .addEncodedQueryParameter(ID, encoded(effectiveKey))
  229. .addEncodedQueryParameter(BRANCH, encoded(branchConfiguration.branchName()))
  230. .build()
  231. .url();
  232. }
  233. if (onMainBranch(branchConfiguration)) {
  234. return httpUrl.newBuilder()
  235. .addPathSegment(DASHBOARD)
  236. .addEncodedQueryParameter(ID, encoded(effectiveKey))
  237. .build()
  238. .url();
  239. }
  240. return httpUrl.newBuilder().build().url();
  241. }
  242. private static boolean onPullRequest(BranchConfiguration branchConfiguration) {
  243. return branchConfiguration.branchName() != null && (branchConfiguration.branchType() == PULL_REQUEST);
  244. }
  245. private static boolean onBranch(BranchConfiguration branchConfiguration) {
  246. return branchConfiguration.branchName() != null && (branchConfiguration.branchType() == BranchType.BRANCH);
  247. }
  248. private static boolean onMainBranch(BranchConfiguration branchConfiguration) {
  249. return branchConfiguration.branchName() == null;
  250. }
  251. private static String encoded(@Nullable String queryParameter) {
  252. if (isBlank(queryParameter)) {
  253. return EMPTY;
  254. }
  255. try {
  256. return encode(queryParameter, StandardCharsets.UTF_8.name());
  257. } catch (UnsupportedEncodingException e) {
  258. throw new IllegalStateException("Unable to urlencode " + queryParameter, e);
  259. }
  260. }
  261. private void dumpMetadata(Map<String, String> metadata) {
  262. Path file = properties.metadataFilePath();
  263. try {
  264. Files.createDirectories(file.getParent());
  265. try (Writer output = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
  266. for (Map.Entry<String, String> entry : metadata.entrySet()) {
  267. output.write(entry.getKey());
  268. output.write("=");
  269. output.write(entry.getValue());
  270. output.write("\n");
  271. }
  272. }
  273. LOG.debug("Report metadata written to {}", file);
  274. } catch (IOException e) {
  275. throw new IllegalStateException("Unable to dump " + file, e);
  276. }
  277. }
  278. }