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

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