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 checkNotNullValue(value, type);
66 Integer days = NewCodePeriodParser.parseDays(value);
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 Instant targetDate = DateUtils.addDays(Instant.ofEpochMilli(referenceDate), -days);
108 LOG.debug("Resolving new code period by {} days: {}", days, supplierToString(() -> logDate(targetDate)));
109 SnapshotDto snapshot = findNearestSnapshotToTargetDate(snapshots, targetDate);
110 return newPeriod(NewCodePeriodType.NUMBER_OF_DAYS, String.valueOf((int) days), Instant.ofEpochMilli(snapshot.getCreatedAt()));
113 private Period resolvePreviousVersion(DbSession dbSession, String currentVersion, List<EventDto> versions, String mostRecentVersion) {
114 EventDto previousVersion = versions.get(currentVersion.equals(mostRecentVersion) ? 1 : 0);
115 LOG.debug("Resolving new code period by previous version: {}", previousVersion.getName());
116 return newPeriod(dbSession, previousVersion);
119 private Period findOldestAnalysis(DbSession dbSession, String projectUuid) {
120 LOG.debug("Resolving first analysis as new code period as there is only one existing version");
121 Optional<Period> period = dbClient.snapshotDao().selectOldestSnapshot(dbSession, projectUuid)
122 .map(dto -> newPeriod(NewCodePeriodType.PREVIOUS_VERSION, null, Instant.ofEpochMilli(dto.getCreatedAt())));
123 ensureNotOnFirstAnalysis(period.isPresent());
127 private Period newPeriod(DbSession dbSession, EventDto previousVersion) {
128 Optional<Period> period = dbClient.snapshotDao().selectByUuid(dbSession, previousVersion.getAnalysisUuid())
129 .map(dto -> newPeriod(NewCodePeriodType.PREVIOUS_VERSION, dto.getProjectVersion(), Instant.ofEpochMilli(dto.getCreatedAt())));
130 if (!period.isPresent()) {
131 throw new IllegalStateException(format("Analysis '%s' for version event '%s' has been deleted",
132 previousVersion.getAnalysisUuid(), previousVersion.getName()));
137 private static Period newPeriod(NewCodePeriodType type, @Nullable String value, Instant instant) {
138 return new Period(type.name(), value, instant.toEpochMilli());
141 private static Object supplierToString(Supplier<String> s) {
142 return new Object() {
144 public String toString() {
150 private static SnapshotQuery createCommonQuery(String projectUuid) {
151 return new SnapshotQuery().setComponentUuid(projectUuid).setStatus(STATUS_PROCESSED);
154 private static SnapshotDto findNearestSnapshotToTargetDate(List<SnapshotDto> snapshots, Instant targetDate) {
155 // FIXME shouldn't this be the first analysis after targetDate?
156 Duration bestDuration = null;
157 SnapshotDto nearest = null;
159 ensureNotOnFirstAnalysis(!snapshots.isEmpty());
161 for (SnapshotDto snapshot : snapshots) {
162 Instant createdAt = Instant.ofEpochMilli(snapshot.getCreatedAt());
163 Duration duration = Duration.between(targetDate, createdAt).abs();
164 if (bestDuration == null || duration.compareTo(bestDuration) <= 0) {
165 bestDuration = duration;
172 private static void checkPeriodProperty(boolean test, String propertyValue, String testDescription, Object... args) {
174 LOG.debug("Invalid code period '{}': {}", propertyValue, supplierToString(() -> format(testDescription, args)));
175 throw MessageException.of(format("Invalid new code period. '%s' is not one of: " +
176 "integer > 0, date before current analysis j, \"previous_version\", or version string that exists in the project' \n" +
177 "Please contact a project administrator to correct this setting", propertyValue));
181 private static void ensureNotOnFirstAnalysis(boolean expression) {
182 checkState(expression, "Attempting to resolve period while no analysis exist for project");
185 private static void checkNotNullValue(@Nullable String value, NewCodePeriodType type) {
186 checkNotNull(value, "Value can't be null with type %s", type);
189 private static String logDate(Instant instant) {
190 return DateUtils.formatDate(instant.truncatedTo(ChronoUnit.SECONDS));