3 * Copyright (C) 2009-2019 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.period;
22 import java.time.Duration;
23 import java.time.Instant;
24 import java.time.temporal.ChronoUnit;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.function.Supplier;
28 import javax.annotation.Nullable;
29 import org.sonar.api.utils.DateUtils;
30 import org.sonar.api.utils.MessageException;
31 import org.sonar.api.utils.log.Logger;
32 import org.sonar.api.utils.log.Loggers;
33 import org.sonar.db.DbClient;
34 import org.sonar.db.DbSession;
35 import org.sonar.db.component.SnapshotDto;
36 import org.sonar.db.component.SnapshotQuery;
37 import org.sonar.db.event.EventDto;
38 import org.sonar.db.newcodeperiod.NewCodePeriodDto;
39 import org.sonar.db.newcodeperiod.NewCodePeriodParser;
40 import org.sonar.db.newcodeperiod.NewCodePeriodType;
42 import static com.google.common.base.Preconditions.checkNotNull;
43 import static com.google.common.base.Preconditions.checkState;
44 import static java.lang.String.format;
45 import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED;
46 import static org.sonar.db.component.SnapshotQuery.SORT_FIELD.BY_DATE;
47 import static org.sonar.db.component.SnapshotQuery.SORT_ORDER.ASC;
49 public class NewCodePeriodResolver {
50 private static final Logger LOG = Loggers.get(NewCodePeriodResolver.class);
52 private final DbClient dbClient;
54 public NewCodePeriodResolver(DbClient dbClient) {
55 this.dbClient = dbClient;
58 public Period resolve(DbSession dbSession, String branchUuid, NewCodePeriodDto newCodePeriodDto, long referenceDate, String projectVersion) {
59 return toPeriod(newCodePeriodDto.getType(), newCodePeriodDto.getValue(), dbSession, projectVersion, branchUuid, referenceDate);
62 private Period toPeriod(NewCodePeriodType type, @Nullable String value, DbSession dbSession, String projectVersion, String rootUuid, long referenceDate) {
65 Integer days = NewCodePeriodParser.parseDays(value);
66 checkNotNullValue(value, type);
67 return resolveByDays(dbSession, rootUuid, days, value, referenceDate);
68 case PREVIOUS_VERSION:
69 return resolveByPreviousVersion(dbSession, rootUuid, projectVersion);
70 case SPECIFIC_ANALYSIS:
71 checkNotNullValue(value, type);
72 return resolveBySpecificAnalysis(dbSession, rootUuid, value);
74 throw new IllegalStateException("Unexpected type: " + type);
78 private Period resolveBySpecificAnalysis(DbSession dbSession, String rootUuid, String value) {
79 SnapshotDto baseline = dbClient.snapshotDao().selectByUuid(dbSession, value)
80 .filter(t -> t.getComponentUuid().equals(rootUuid))
81 .orElseThrow(() -> new IllegalStateException("Analysis '" + value + "' of project '" + rootUuid
82 + "' defined as the baseline does not exist"));
83 LOG.debug("Resolving new code period with a specific analysis");
84 return newPeriod(NewCodePeriodType.SPECIFIC_ANALYSIS, value, Instant.ofEpochMilli(baseline.getCreatedAt()));
87 private Period resolveByPreviousVersion(DbSession dbSession, String projectUuid, String projectVersion) {
88 List<EventDto> versions = dbClient.eventDao().selectVersionsByMostRecentFirst(dbSession, projectUuid);
89 if (versions.isEmpty()) {
90 return findOldestAnalysis(dbSession, projectUuid);
93 String mostRecentVersion = Optional.ofNullable(versions.iterator().next().getName())
94 .orElseThrow(() -> new IllegalStateException("selectVersionsByMostRecentFirst returned a DTO which didn't have a name"));
96 if (versions.size() == 1) {
97 return findOldestAnalysis(dbSession, projectUuid);
99 return resolvePreviousVersion(dbSession, projectVersion, versions, mostRecentVersion);
102 private Period resolveByDays(DbSession dbSession, String rootUuid, Integer days, String value, long referenceDate) {
103 checkPeriodProperty(days > 0, value, "number of days is <= 0");
104 List<SnapshotDto> snapshots = dbClient.snapshotDao().selectAnalysesByQuery(dbSession, createCommonQuery(rootUuid)
105 .setCreatedBefore(referenceDate).setSort(BY_DATE, ASC));
107 ensureNotOnFirstAnalysis(!snapshots.isEmpty());
108 Instant targetDate = DateUtils.addDays(Instant.ofEpochMilli(referenceDate), -days);
109 LOG.debug("Resolving new code period by {} days: {}", days, supplierToString(() -> logDate(targetDate)));
110 SnapshotDto snapshot = findNearestSnapshotToTargetDate(snapshots, targetDate);
111 return newPeriod(NewCodePeriodType.NUMBER_OF_DAYS, String.valueOf((int) days), Instant.ofEpochMilli(snapshot.getCreatedAt()));
114 private Period resolvePreviousVersion(DbSession dbSession, String currentVersion, List<EventDto> versions, String mostRecentVersion) {
115 EventDto previousVersion = versions.get(currentVersion.equals(mostRecentVersion) ? 1 : 0);
116 LOG.debug("Resolving new code period by previous version: {}", previousVersion.getName());
117 return newPeriod(dbSession, previousVersion);
120 private Period findOldestAnalysis(DbSession dbSession, String projectUuid) {
121 LOG.debug("Resolving first analysis as new code period as there is only one existing version");
122 Optional<Period> period = dbClient.snapshotDao().selectOldestSnapshot(dbSession, projectUuid)
123 .map(dto -> newPeriod(NewCodePeriodType.PREVIOUS_VERSION, null, Instant.ofEpochMilli(dto.getCreatedAt())));
124 ensureNotOnFirstAnalysis(period.isPresent());
128 private Period newPeriod(DbSession dbSession, EventDto previousVersion) {
129 Optional<Period> period = dbClient.snapshotDao().selectByUuid(dbSession, previousVersion.getAnalysisUuid())
130 .map(dto -> newPeriod(NewCodePeriodType.PREVIOUS_VERSION, dto.getProjectVersion(), Instant.ofEpochMilli(dto.getCreatedAt())));
131 if (!period.isPresent()) {
132 throw new IllegalStateException(format("Analysis '%s' for version event '%s' has been deleted",
133 previousVersion.getAnalysisUuid(), previousVersion.getName()));
138 private static Period newPeriod(NewCodePeriodType type, @Nullable String value, Instant instant) {
139 return new Period(type.name(), value, instant.toEpochMilli());
142 private static Object supplierToString(Supplier<String> s) {
143 return new Object() {
145 public String toString() {
151 private static SnapshotQuery createCommonQuery(String projectUuid) {
152 return new SnapshotQuery().setComponentUuid(projectUuid).setStatus(STATUS_PROCESSED);
155 private static SnapshotDto findNearestSnapshotToTargetDate(List<SnapshotDto> snapshots, Instant targetDate) {
156 // FIXME shouldn't this be the first analysis after targetDate?
157 Duration bestDuration = null;
158 SnapshotDto nearest = null;
159 for (SnapshotDto snapshot : snapshots) {
160 Instant createdAt = Instant.ofEpochMilli(snapshot.getCreatedAt());
161 Duration duration = Duration.between(targetDate, createdAt).abs();
162 if (bestDuration == null || duration.compareTo(bestDuration) <= 0) {
163 bestDuration = duration;
170 private static void checkPeriodProperty(boolean test, String propertyValue, String testDescription, Object... args) {
172 LOG.debug("Invalid code period '{}': {}", propertyValue, supplierToString(() -> format(testDescription, args)));
173 throw MessageException.of(format("Invalid new code period. '%s' is not one of: " +
174 "integer > 0, date before current analysis j, \"previous_version\", or version string that exists in the project' \n" +
175 "Please contact a project administrator to correct this setting", propertyValue));
179 private static void ensureNotOnFirstAnalysis(boolean expression) {
180 checkState(expression, "Attempting to resolve period while no analysis exist for project");
183 private static void checkNotNullValue(@Nullable String value, NewCodePeriodType type) {
184 checkNotNull(value, "Value can't be null with type %s", type);
187 private static String logDate(Instant instant) {
188 return DateUtils.formatDate(instant.truncatedTo(ChronoUnit.SECONDS));