3 * Copyright (C) 2009-2021 SonarSource SA
4 * mailto:info AT sonarsource DOT com
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.
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.
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.
20 package org.sonar.ce.task.projectanalysis.issue;
22 import com.google.common.collect.ImmutableList;
23 import java.time.temporal.ChronoUnit;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Date;
28 import java.util.List;
30 import java.util.Optional;
31 import org.apache.ibatis.session.ResultContext;
32 import org.apache.ibatis.session.ResultHandler;
33 import org.sonar.api.config.Configuration;
34 import org.sonar.api.rule.RuleKey;
35 import org.sonar.api.rule.RuleStatus;
36 import org.sonar.api.utils.System2;
37 import org.sonar.api.utils.log.Loggers;
38 import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolder;
39 import org.sonar.core.issue.DefaultIssue;
40 import org.sonar.core.issue.FieldDiffs;
41 import org.sonar.db.DbClient;
42 import org.sonar.db.DbSession;
43 import org.sonar.db.issue.IssueChangeDto;
44 import org.sonar.db.issue.IssueDto;
45 import org.sonar.db.issue.IssueMapper;
47 import static com.google.common.base.Preconditions.checkState;
48 import static java.util.Collections.emptyList;
49 import static java.util.stream.Collectors.groupingBy;
50 import static java.util.stream.Collectors.toList;
51 import static org.sonar.api.issue.Issue.STATUS_CLOSED;
52 import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
54 public class ComponentIssuesLoader {
55 private static final int DEFAULT_CLOSED_ISSUES_MAX_AGE = 30;
56 private static final String PROPERTY_CLOSED_ISSUE_MAX_AGE = "sonar.issuetracking.closedissues.maxage";
58 private final DbClient dbClient;
59 private final RuleRepository ruleRepository;
60 private final ActiveRulesHolder activeRulesHolder;
61 private final System2 system2;
62 private final int closedIssueMaxAge;
64 public ComponentIssuesLoader(DbClient dbClient, RuleRepository ruleRepository, ActiveRulesHolder activeRulesHolder,
65 Configuration configuration, System2 system2) {
66 this.dbClient = dbClient;
67 this.activeRulesHolder = activeRulesHolder;
68 this.ruleRepository = ruleRepository;
69 this.system2 = system2;
70 this.closedIssueMaxAge = configuration.get(PROPERTY_CLOSED_ISSUE_MAX_AGE)
71 .map(ComponentIssuesLoader::safelyParseClosedIssueMaxAge)
73 .orElse(DEFAULT_CLOSED_ISSUES_MAX_AGE);
76 private static Integer safelyParseClosedIssueMaxAge(String str) {
78 return Integer.parseInt(str);
79 } catch (NumberFormatException e) {
80 Loggers.get(ComponentIssuesLoader.class)
81 .warn("Value of property {} should be an integer >= 0: {}", PROPERTY_CLOSED_ISSUE_MAX_AGE, str);
86 public List<DefaultIssue> loadOpenIssues(String componentUuid) {
87 try (DbSession dbSession = dbClient.openSession(false)) {
88 return loadOpenIssues(componentUuid, dbSession);
92 public List<DefaultIssue> loadOpenIssuesWithChanges(String componentUuid) {
93 try (DbSession dbSession = dbClient.openSession(false)) {
94 List<DefaultIssue> result = loadOpenIssues(componentUuid, dbSession);
96 return loadChanges(dbSession, result);
100 public List<DefaultIssue> loadChanges(DbSession dbSession, Collection<DefaultIssue> issues) {
101 Map<String, List<IssueChangeDto>> changeDtoByIssueKey = dbClient.issueChangeDao()
102 .selectByIssueKeys(dbSession, issues.stream().map(DefaultIssue::key).collect(toList()))
104 .collect(groupingBy(IssueChangeDto::getIssueKey));
106 issues.forEach(i -> setChanges(changeDtoByIssueKey, i));
107 return new ArrayList<>(issues);
111 * Loads the most recent diff changes of the specified issues which contain the latest status and resolution of the
114 public void loadLatestDiffChangesForReopeningOfClosedIssues(Collection<DefaultIssue> issues) {
115 if (issues.isEmpty()) {
119 try (DbSession dbSession = dbClient.openSession(false)) {
120 loadLatestDiffChangesForReopeningOfClosedIssues(dbSession, issues);
125 * To be efficient both in term of memory and speed:
127 * <li>only diff changes are loaded from DB, sorted by issue and then change creation date</li>
128 * <li>data from DB is streamed</li>
129 * <li>only the latest change(s) with status and resolution are added to the {@link DefaultIssue} objects</li>
132 private void loadLatestDiffChangesForReopeningOfClosedIssues(DbSession dbSession, Collection<DefaultIssue> issues) {
133 Map<String, DefaultIssue> issuesByKey = issues.stream().collect(uniqueIndex(DefaultIssue::key));
135 dbClient.issueChangeDao()
136 .scrollDiffChangesOfIssues(dbSession, issuesByKey.keySet(), new ResultHandler<IssueChangeDto>() {
137 private DefaultIssue currentIssue = null;
138 private boolean previousStatusFound = false;
139 private boolean previousResolutionFound = false;
142 public void handleResult(ResultContext<? extends IssueChangeDto> resultContext) {
143 IssueChangeDto issueChangeDto = resultContext.getResultObject();
144 if (currentIssue == null || !currentIssue.key().equals(issueChangeDto.getIssueKey())) {
145 currentIssue = issuesByKey.get(issueChangeDto.getIssueKey());
146 previousStatusFound = false;
147 previousResolutionFound = false;
150 if (currentIssue != null) {
151 FieldDiffs fieldDiffs = issueChangeDto.toFieldDiffs();
152 boolean hasPreviousStatus = fieldDiffs.get("status") != null;
153 boolean hasPreviousResolution = fieldDiffs.get("resolution") != null;
154 if ((!previousStatusFound && hasPreviousStatus) || (!previousResolutionFound && hasPreviousResolution)) {
155 currentIssue.addChange(fieldDiffs);
157 previousStatusFound |= hasPreviousStatus;
158 previousResolutionFound |= hasPreviousResolution;
164 private List<DefaultIssue> loadOpenIssues(String componentUuid, DbSession dbSession) {
165 List<DefaultIssue> result = new ArrayList<>();
166 dbSession.getMapper(IssueMapper.class).scrollNonClosedByComponentUuid(componentUuid, resultContext -> {
167 DefaultIssue issue = (resultContext.getResultObject()).toDefaultIssue();
168 Rule rule = ruleRepository.getByKey(issue.ruleKey());
170 // TODO this field should be set outside this class
171 if ((!rule.isExternal() && !isActive(issue.ruleKey())) || rule.getStatus() == RuleStatus.REMOVED) {
172 issue.setOnDisabledRule(true);
173 // TODO to be improved, why setOnDisabledRule(true) is not enough ?
174 issue.setBeingClosed(true);
176 issue.setSelectedAt(System.currentTimeMillis());
179 return Collections.unmodifiableList(result);
182 private static void setChanges(Map<String, List<IssueChangeDto>> changeDtoByIssueKey, DefaultIssue i) {
183 changeDtoByIssueKey.computeIfAbsent(i.key(), k -> emptyList())
184 .forEach(c -> addChangeOrComment(i, c));
187 private static void addChangeOrComment(DefaultIssue i, IssueChangeDto c) {
188 switch (c.getChangeType()) {
189 case IssueChangeDto.TYPE_FIELD_CHANGE:
190 i.addChange(c.toFieldDiffs());
192 case IssueChangeDto.TYPE_COMMENT:
193 i.addComment(c.toComment());
196 throw new IllegalStateException("Unknown change type: " + c.getChangeType());
200 private boolean isActive(RuleKey ruleKey) {
201 return activeRulesHolder.get(ruleKey).isPresent();
205 * Load closed issues for the specified Component, which have at least one line diff in changelog AND are
206 * neither hotspots nor manual vulnerabilities.
208 * Closed issues do not have a line number in DB (it is unset when the issue is closed), this method
209 * returns {@link DefaultIssue} objects which line number is populated from the most recent diff logging
210 * the removal of the line. Closed issues which do not have such diff are not loaded.
212 * To not depend on purge configuration of closed issues, only issues which close date is less than 30 days ago at
213 * 00H00 are returned.
215 public List<DefaultIssue> loadClosedIssues(String componentUuid) {
216 if (closedIssueMaxAge == 0) {
220 Date date = new Date(system2.now());
221 long closeDateAfter = date.toInstant()
222 .minus(closedIssueMaxAge, ChronoUnit.DAYS)
223 .truncatedTo(ChronoUnit.DAYS)
225 try (DbSession dbSession = dbClient.openSession(false)) {
226 return loadClosedIssues(dbSession, componentUuid, closeDateAfter);
230 private static List<DefaultIssue> loadClosedIssues(DbSession dbSession, String componentUuid, long closeDateAfter) {
231 ClosedIssuesResultHandler handler = new ClosedIssuesResultHandler();
232 dbSession.getMapper(IssueMapper.class).scrollClosedByComponentUuid(componentUuid, closeDateAfter, handler);
233 return ImmutableList.copyOf(handler.issues);
236 private static class ClosedIssuesResultHandler implements ResultHandler<IssueDto> {
237 private final List<DefaultIssue> issues = new ArrayList<>();
238 private String previousIssueKey = null;
241 public void handleResult(ResultContext<? extends IssueDto> resultContext) {
242 IssueDto resultObject = resultContext.getResultObject();
244 // issue are ordered by most recent change first, only the first row for a given issue is of interest
245 if (previousIssueKey != null && previousIssueKey.equals(resultObject.getKey())) {
249 FieldDiffs fieldDiffs = FieldDiffs.parse(resultObject.getClosedChangeData()
250 .orElseThrow(() -> new IllegalStateException("Close change data should be populated")));
251 checkState(Optional.ofNullable(fieldDiffs.get("status"))
252 .map(FieldDiffs.Diff::newValue)
253 .filter(STATUS_CLOSED::equals)
254 .isPresent(), "Close change data should have a status diff with new value %s", STATUS_CLOSED);
255 Integer line = Optional.ofNullable(fieldDiffs.get("line"))
256 .map(diff -> (String) diff.oldValue())
257 .filter(str -> !str.isEmpty())
258 .map(Integer::parseInt)
261 previousIssueKey = resultObject.getKey();
262 DefaultIssue issue = resultObject.toDefaultIssue();
264 issue.setSelectedAt(System.currentTimeMillis());