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.

ListAction.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2023 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.server.issue.ws;
  21. import java.time.Clock;
  22. import com.google.common.base.Preconditions;
  23. import java.util.EnumSet;
  24. import java.util.List;
  25. import java.util.Optional;
  26. import javax.annotation.Nullable;
  27. import org.sonar.api.rules.RuleType;
  28. import org.sonar.api.server.ws.Request;
  29. import org.sonar.api.server.ws.Response;
  30. import org.sonar.api.server.ws.WebService;
  31. import org.sonar.api.utils.Paging;
  32. import org.sonar.api.web.UserRole;
  33. import org.sonar.db.DbClient;
  34. import org.sonar.db.DbSession;
  35. import org.sonar.db.Pagination;
  36. import org.sonar.db.component.BranchDto;
  37. import org.sonar.db.component.ComponentDto;
  38. import org.sonar.db.component.SnapshotDto;
  39. import org.sonar.db.issue.IssueDto;
  40. import org.sonar.db.issue.IssueListQuery;
  41. import org.sonar.db.project.ProjectDto;
  42. import org.sonar.server.component.ComponentFinder;
  43. import org.sonar.server.component.ComponentFinder.ProjectAndBranch;
  44. import org.sonar.server.user.UserSession;
  45. import org.sonarqube.ws.Common;
  46. import org.sonarqube.ws.Issues;
  47. import static com.google.common.base.Strings.isNullOrEmpty;
  48. import static java.lang.String.format;
  49. import static java.util.Collections.singletonList;
  50. import static org.sonar.api.measures.CoreMetrics.ANALYSIS_FROM_SONARQUBE_9_4_KEY;
  51. import static org.sonar.api.server.ws.WebService.Param.PAGE;
  52. import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
  53. import static org.sonar.api.utils.Paging.forPageIndex;
  54. import static org.sonar.db.newcodeperiod.NewCodePeriodType.REFERENCE_BRANCH;
  55. import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE;
  56. import static org.sonar.server.issue.index.IssueQueryFactory.ISSUE_STATUSES;
  57. import static org.sonar.server.ws.WsUtils.writeProtobuf;
  58. import static org.sonarqube.ws.WsUtils.checkArgument;
  59. import static org.sonarqube.ws.client.issue.IssuesWsParameters.ACTION_LIST;
  60. public class ListAction implements IssuesWsAction {
  61. private static final String PARAM_PROJECT = "project";
  62. private static final String PARAM_BRANCH = "branch";
  63. private static final String PARAM_PULL_REQUEST = "pullRequest";
  64. private static final String PARAM_COMPONENT = "component";
  65. private static final String PARAM_TYPES = "types";
  66. private static final String PARAM_RESOLVED = "resolved";
  67. private static final String PARAM_IN_NEW_CODE_PERIOD = "inNewCodePeriod";
  68. private final UserSession userSession;
  69. private final DbClient dbClient;
  70. private final Clock clock;
  71. private final SearchResponseLoader searchResponseLoader;
  72. private final SearchResponseFormat searchResponseFormat;
  73. private final ComponentFinder componentFinder;
  74. public ListAction(UserSession userSession, DbClient dbClient, Clock clock, SearchResponseLoader searchResponseLoader, SearchResponseFormat searchResponseFormat, ComponentFinder componentFinder) {
  75. this.userSession = userSession;
  76. this.dbClient = dbClient;
  77. this.clock = clock;
  78. this.searchResponseLoader = searchResponseLoader;
  79. this.searchResponseFormat = searchResponseFormat;
  80. this.componentFinder = componentFinder;
  81. }
  82. @Override
  83. public void define(WebService.NewController controller) {
  84. WebService.NewAction action = controller
  85. .createAction(ACTION_LIST)
  86. .setHandler(this)
  87. .setInternal(true)
  88. .setDescription("List issues. This endpoint is used in degraded mode, when issue indexation is running." +
  89. "<br>Either 'project' or 'component' parameter is required." +
  90. "<br>Total number of issues will be always equal to a page size, as this counting all issues is not supported. " +
  91. "<br>Requires the 'Browse' permission on the specified project. ")
  92. .setSince("10.2")
  93. .setResponseExample(getClass().getResource("list-example.json"));
  94. action.addPagingParams(100, MAX_PAGE_SIZE);
  95. action.createParam(PARAM_PROJECT)
  96. .setDescription("Project key")
  97. .setExampleValue("my-project-key");
  98. action.createParam(PARAM_BRANCH)
  99. .setDescription("Branch key. Not available in the community edition.")
  100. .setExampleValue("feature/my-new-feature");
  101. action.createParam(PARAM_PULL_REQUEST)
  102. .setDescription("Filter issues that belong to the specified pull request. Not available in the community edition.")
  103. .setExampleValue("42");
  104. action.createParam(PARAM_COMPONENT)
  105. .setDescription("Component key")
  106. .setExampleValue("my_project:my_file.js");
  107. action.createParam(PARAM_TYPES)
  108. .setDescription("Comma-separated list of issue types")
  109. .setExampleValue("BUG, VULNERABILITY")
  110. .setPossibleValues(RuleType.BUG.name(), RuleType.VULNERABILITY.name(), RuleType.CODE_SMELL.name());
  111. action.createParam(PARAM_IN_NEW_CODE_PERIOD)
  112. .setDescription("Filter issues created in the new code period of the project")
  113. .setExampleValue("true")
  114. .setDefaultValue(false)
  115. .setBooleanPossibleValues();
  116. action.createParam(PARAM_RESOLVED)
  117. .setDescription("Filter issues that are resolved or not, if not provided all issues will be returned")
  118. .setExampleValue("true")
  119. .setBooleanPossibleValues();
  120. }
  121. @Override
  122. public final void handle(Request request, Response response) {
  123. WsRequest wsRequest = toWsRequest(request);
  124. ProjectAndBranch projectAndBranch = validateRequest(wsRequest);
  125. List<IssueDto> issues = getIssueKeys(wsRequest, projectAndBranch);
  126. Issues.ListWsResponse wsResponse = formatResponse(wsRequest, issues);
  127. writeProtobuf(wsResponse, request, response);
  128. }
  129. private static WsRequest toWsRequest(Request request) {
  130. WsRequest wsRequest = new WsRequest();
  131. wsRequest.project(request.param(PARAM_PROJECT));
  132. wsRequest.component(request.param(PARAM_COMPONENT));
  133. wsRequest.branch(request.param(PARAM_BRANCH));
  134. wsRequest.pullRequest(request.param(PARAM_PULL_REQUEST));
  135. List<String> types = request.paramAsStrings(PARAM_TYPES);
  136. wsRequest.types(types == null ? List.of(RuleType.BUG.getDbConstant(), RuleType.VULNERABILITY.getDbConstant(), RuleType.CODE_SMELL.getDbConstant())
  137. : types.stream().map(RuleType::valueOf).map(RuleType::getDbConstant).toList());
  138. wsRequest.newCodePeriod(request.mandatoryParamAsBoolean(PARAM_IN_NEW_CODE_PERIOD));
  139. wsRequest.resolved(request.paramAsBoolean(PARAM_RESOLVED));
  140. wsRequest.page(request.mandatoryParamAsInt(PAGE));
  141. wsRequest.pageSize(request.mandatoryParamAsInt(PAGE_SIZE));
  142. return wsRequest;
  143. }
  144. private ProjectAndBranch validateRequest(WsRequest wsRequest) {
  145. checkArgument(!isNullOrEmpty(wsRequest.project) || !isNullOrEmpty(wsRequest.component),
  146. "Either '%s' or '%s' parameter must be provided", PARAM_PROJECT, PARAM_COMPONENT);
  147. Preconditions.checkArgument(isNullOrEmpty(wsRequest.branch) || isNullOrEmpty(wsRequest.pullRequest),
  148. "Only one of parameters '%s' and '%s' can be provided", PARAM_BRANCH, PARAM_PULL_REQUEST);
  149. ProjectAndBranch projectAndBranch;
  150. try (DbSession dbSession = dbClient.openSession(false)) {
  151. if (!isNullOrEmpty(wsRequest.component)) {
  152. projectAndBranch = checkComponentPermission(wsRequest, dbSession);
  153. } else {
  154. projectAndBranch = checkProjectAndBranchPermission(wsRequest, dbSession);
  155. }
  156. }
  157. return projectAndBranch;
  158. }
  159. private ProjectAndBranch checkComponentPermission(WsRequest wsRequest, DbSession dbSession) {
  160. ComponentDto componentDto = componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, wsRequest.component, wsRequest.branch, wsRequest.pullRequest);
  161. BranchDto branchDto = dbClient.branchDao().selectByUuid(dbSession, componentDto.branchUuid())
  162. .orElseThrow(() -> new IllegalStateException("Branch does not exist: " + componentDto.branchUuid()));
  163. ProjectDto projectDto = dbClient.projectDao().selectByUuid(dbSession, branchDto.getProjectUuid())
  164. .orElseThrow(() -> new IllegalArgumentException("Project does not exist: " + wsRequest.project));
  165. userSession.checkEntityPermission(UserRole.USER, projectDto);
  166. return new ProjectAndBranch(projectDto, branchDto);
  167. }
  168. private ProjectAndBranch checkProjectAndBranchPermission(WsRequest wsRequest, DbSession dbSession) {
  169. ProjectAndBranch projectAndBranch = componentFinder.getProjectAndBranch(dbSession, wsRequest.project, wsRequest.branch, wsRequest.pullRequest);
  170. userSession.checkEntityPermission(UserRole.USER, projectAndBranch.getProject());
  171. return projectAndBranch;
  172. }
  173. private List<IssueDto> getIssueKeys(WsRequest wsRequest, ProjectAndBranch projectAndBranch) {
  174. try (DbSession dbSession = dbClient.openSession(false)) {
  175. BranchDto branch = projectAndBranch.getBranch();
  176. IssueListQuery.IssueListQueryBuilder queryBuilder = IssueListQuery.IssueListQueryBuilder.newIssueListQueryBuilder()
  177. .project(wsRequest.project)
  178. .component(wsRequest.component)
  179. .branch(branch.getBranchKey())
  180. .pullRequest(branch.getPullRequestKey())
  181. .resolved(wsRequest.resolved)
  182. .statuses(ISSUE_STATUSES)
  183. .types(wsRequest.types);
  184. if (wsRequest.inNewCodePeriod) {
  185. setNewCodePeriod(dbSession, wsRequest, queryBuilder);
  186. }
  187. Pagination pagination = Pagination.forPage(wsRequest.page).andSize(wsRequest.pageSize);
  188. return dbClient.issueDao().selectByQuery(dbSession, queryBuilder.build(), pagination);
  189. }
  190. }
  191. private void setNewCodePeriod(DbSession dbSession, WsRequest wsRequest, IssueListQuery.IssueListQueryBuilder queryBuilder) {
  192. ComponentDto componentDto = dbClient.componentDao().selectByKeyAndBranch(dbSession, wsRequest.project, wsRequest.branch)
  193. .orElseThrow(() -> new IllegalStateException(format("Could not find component for project: %s, branch: %s", wsRequest.project, wsRequest.branch)));
  194. Optional<SnapshotDto> snapshot = getLastAnalysis(dbSession, componentDto);
  195. if (snapshot.isPresent() && isLastAnalysisFromReAnalyzedReferenceBranch(dbSession, snapshot.get())) {
  196. queryBuilder.newCodeOnReference(true);
  197. } else {
  198. // if last analysis has no period date, then no issue should be considered new.
  199. long createdAfterFromSnapshot = snapshot.map(SnapshotDto::getPeriodDate).orElse(clock.millis());
  200. queryBuilder.createdAfter(createdAfterFromSnapshot);
  201. }
  202. }
  203. private Optional<SnapshotDto> getLastAnalysis(DbSession dbSession, ComponentDto component) {
  204. return dbClient.snapshotDao().selectLastAnalysisByComponentUuid(dbSession, component.uuid());
  205. }
  206. private boolean isLastAnalysisFromReAnalyzedReferenceBranch(DbSession dbSession, SnapshotDto snapshot) {
  207. return isLastAnalysisUsingReferenceBranch(snapshot) &&
  208. isLastAnalysisFromSonarQube94Onwards(dbSession, snapshot.getRootComponentUuid());
  209. }
  210. private boolean isLastAnalysisFromSonarQube94Onwards(DbSession dbSession, String componentUuid) {
  211. return dbClient.liveMeasureDao().selectMeasure(dbSession, componentUuid, ANALYSIS_FROM_SONARQUBE_9_4_KEY).isPresent();
  212. }
  213. private static boolean isLastAnalysisUsingReferenceBranch(SnapshotDto snapshot) {
  214. return !isNullOrEmpty(snapshot.getPeriodMode()) && REFERENCE_BRANCH.name().equals(snapshot.getPeriodMode());
  215. }
  216. private Issues.ListWsResponse formatResponse(WsRequest request, List<IssueDto> issues) {
  217. Issues.ListWsResponse.Builder response = Issues.ListWsResponse.newBuilder();
  218. response.setPaging(Common.Paging.newBuilder()
  219. .setPageIndex(request.page)
  220. .setPageSize(issues.size())
  221. .build());
  222. List<String> issueKeys = issues.stream().map(IssueDto::getKey).toList();
  223. SearchResponseLoader.Collector collector = new SearchResponseLoader.Collector(issueKeys);
  224. collectLoggedInUser(collector);
  225. SearchResponseData preloadedData = new SearchResponseData(issues);
  226. EnumSet<SearchAdditionalField> additionalFields = EnumSet.of(SearchAdditionalField.ACTIONS, SearchAdditionalField.COMMENTS, SearchAdditionalField.TRANSITIONS);
  227. SearchResponseData data = searchResponseLoader.load(preloadedData, collector, additionalFields, null);
  228. Paging paging = forPageIndex(request.page)
  229. .withPageSize(request.pageSize)
  230. .andTotal(request.pageSize);
  231. return searchResponseFormat.formatList(additionalFields, data, paging);
  232. }
  233. private void collectLoggedInUser(SearchResponseLoader.Collector collector) {
  234. if (userSession.isLoggedIn()) {
  235. collector.addUserUuids(singletonList(userSession.getUuid()));
  236. }
  237. }
  238. private static class WsRequest {
  239. private String project = null;
  240. private String component = null;
  241. private String branch = null;
  242. private String pullRequest = null;
  243. private List<Integer> types = null;
  244. private boolean inNewCodePeriod = false;
  245. private Boolean resolved = null;
  246. private int page = 1;
  247. private int pageSize = 100;
  248. public WsRequest project(@Nullable String project) {
  249. this.project = project;
  250. return this;
  251. }
  252. public WsRequest component(@Nullable String component) {
  253. this.component = component;
  254. return this;
  255. }
  256. public WsRequest branch(@Nullable String branch) {
  257. this.branch = branch;
  258. return this;
  259. }
  260. public WsRequest pullRequest(@Nullable String pullRequest) {
  261. this.pullRequest = pullRequest;
  262. return this;
  263. }
  264. public WsRequest types(@Nullable List<Integer> types) {
  265. this.types = types;
  266. return this;
  267. }
  268. public WsRequest newCodePeriod(boolean newCodePeriod) {
  269. inNewCodePeriod = newCodePeriod;
  270. return this;
  271. }
  272. public WsRequest resolved(@Nullable Boolean resolved) {
  273. this.resolved = resolved;
  274. return this;
  275. }
  276. public WsRequest page(int page) {
  277. this.page = page;
  278. return this;
  279. }
  280. public WsRequest pageSize(int pageSize) {
  281. this.pageSize = pageSize;
  282. return this;
  283. }
  284. }
  285. }