Skip to content

Commit

Permalink
Refactor ZonedDateTime.now in millis resolution (elastic#38577)
Browse files Browse the repository at this point in the history
In different places across the code base the ZonedDateTime in
milliseconds resolution has to be used for testing. Refactoring this to
a single place to avoid code duplication

closes elastic#38511
closes elastic#38581
  • Loading branch information
pgomulka authored Feb 8, 2019
1 parent 5988b44 commit c921a87
Show file tree
Hide file tree
Showing 6 changed files with 33 additions and 43 deletions.
17 changes: 17 additions & 0 deletions server/src/main/java/org/elasticsearch/common/time/DateUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,12 @@
import org.elasticsearch.common.logging.DeprecationLogger;
import org.joda.time.DateTimeZone;

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -139,4 +142,18 @@ public static long toMilliSeconds(long nanoSecondsSinceEpoch) {

return nanoSecondsSinceEpoch / 1_000_000;
}

/**
* Returns the current UTC date-time with milliseconds precision.
* In Java 9+ (as opposed to Java 8) the {@code Clock} implementation uses system's best clock implementation (which could mean
* that the precision of the clock can be milliseconds, microseconds or nanoseconds), whereas in Java 8
* {@code System.currentTimeMillis()} is always used. To account for these differences, this method defines a new {@code Clock}
* which will offer a value for {@code ZonedDateTime.now()} set to always have milliseconds precision.
*
* @return {@link ZonedDateTime} instance for the current date-time with milliseconds precision in UTC
*/
public static ZonedDateTime nowWithMillisResolution() {
Clock millisResolutionClock = Clock.tick(Clock.systemUTC(), Duration.ofMillis(1));
return ZonedDateTime.now(millisResolutionClock);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package org.elasticsearch.protocol.xpack.watcher;

import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.time.DateUtils;
import org.elasticsearch.common.xcontent.DeprecationHandler;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.ToXContent;
Expand All @@ -23,9 +24,6 @@

import java.io.IOException;
import java.io.InputStream;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.HashMap;
Expand Down Expand Up @@ -126,15 +124,15 @@ private static BytesReference simpleWatch() {

private static WatchStatus randomWatchStatus() {
long version = randomLongBetween(-1, Long.MAX_VALUE);
WatchStatus.State state = new WatchStatus.State(randomBoolean(), nowWithMillisResolution());
WatchStatus.State state = new WatchStatus.State(randomBoolean(), DateUtils.nowWithMillisResolution());
ExecutionState executionState = randomFrom(ExecutionState.values());
ZonedDateTime lastChecked = rarely() ? null : nowWithMillisResolution();
ZonedDateTime lastMetCondition = rarely() ? null : nowWithMillisResolution();
ZonedDateTime lastChecked = rarely() ? null : DateUtils.nowWithMillisResolution();
ZonedDateTime lastMetCondition = rarely() ? null : DateUtils.nowWithMillisResolution();
int size = randomIntBetween(0, 5);
Map<String, ActionStatus> actionMap = new HashMap<>();
for (int i = 0; i < size; i++) {
ActionStatus.AckStatus ack = new ActionStatus.AckStatus(
nowWithMillisResolution(),
DateUtils.nowWithMillisResolution(),
randomFrom(ActionStatus.AckStatus.State.values())
);
ActionStatus actionStatus = new ActionStatus(
Expand All @@ -154,16 +152,16 @@ private static WatchStatus randomWatchStatus() {
}

private static ActionStatus.Throttle randomThrottle() {
return new ActionStatus.Throttle(nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20));
return new ActionStatus.Throttle(DateUtils.nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20));
}

private static ActionStatus.Execution randomExecution() {
if (randomBoolean()) {
return null;
} else if (randomBoolean()) {
return ActionStatus.Execution.failure(nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20));
return ActionStatus.Execution.failure(DateUtils.nowWithMillisResolution(), randomAlphaOfLengthBetween(10, 20));
} else {
return ActionStatus.Execution.successful(nowWithMillisResolution());
return ActionStatus.Execution.successful(DateUtils.nowWithMillisResolution());
}
}

Expand Down Expand Up @@ -229,8 +227,4 @@ private static ActionStatus.Execution convertHlrcToInternal(org.elasticsearch.cl
private static ActionStatus.Throttle convertHlrcToInternal(org.elasticsearch.client.watcher.ActionStatus.Throttle throttle) {
return new ActionStatus.Throttle(throttle.timestamp(), throttle.reason());
}

private static ZonedDateTime nowWithMillisResolution() {
return Instant.ofEpochMilli(Clock.systemUTC().millis()).atZone(ZoneOffset.UTC);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.time.DateUtils;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
Expand All @@ -17,9 +18,6 @@
import org.elasticsearch.xpack.core.ml.job.config.RuleCondition;

import java.io.IOException;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.EnumSet;
import java.util.List;
Expand All @@ -29,7 +27,7 @@
public class ScheduledEventTests extends AbstractSerializingTestCase<ScheduledEvent> {

public static ScheduledEvent createScheduledEvent(String calendarId) {
ZonedDateTime start = nowWithMillisResolution();
ZonedDateTime start = DateUtils.nowWithMillisResolution();
return new ScheduledEvent(randomAlphaOfLength(10), start, start.plusSeconds(randomIntBetween(1, 10000)),
calendarId, null);
}
Expand Down Expand Up @@ -120,8 +118,4 @@ public void testLenientParser() throws IOException {
ScheduledEvent.LENIENT_PARSER.apply(parser, null);
}
}

private static ZonedDateTime nowWithMillisResolution() {
return Instant.ofEpochMilli(Clock.systemUTC().millis()).atZone(ZoneOffset.UTC);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,6 @@
import org.elasticsearch.xpack.sql.session.Configuration;
import org.elasticsearch.xpack.sql.util.DateUtils;

import java.time.Clock;
import java.time.Duration;
import java.time.ZonedDateTime;

public class TestUtils {

private TestUtils() {}
Expand All @@ -23,16 +19,4 @@ private TestUtils() {}
Protocol.REQUEST_TIMEOUT, Protocol.PAGE_TIMEOUT, null, Mode.PLAIN,
null, null, null);

/**
* Returns the current UTC date-time with milliseconds precision.
* In Java 9+ (as opposed to Java 8) the {@code Clock} implementation uses system's best clock implementation (which could mean
* that the precision of the clock can be milliseconds, microseconds or nanoseconds), whereas in Java 8
* {@code System.currentTimeMillis()} is always used. To account for these differences, this method defines a new {@code Clock}
* which will offer a value for {@code ZonedDateTime.now()} set to always have milliseconds precision.
*
* @return {@link ZonedDateTime} instance for the current date-time with milliseconds precision in UTC
*/
public static final ZonedDateTime now() {
return ZonedDateTime.now(Clock.tick(Clock.system(DateUtils.UTC), Duration.ofMillis(1)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.sql.SqlIllegalArgumentException;
import org.elasticsearch.xpack.sql.TestUtils;
import org.elasticsearch.xpack.sql.expression.Literal;
import org.elasticsearch.xpack.sql.tree.Location;
import org.elasticsearch.xpack.sql.tree.Source;
Expand Down Expand Up @@ -157,7 +156,8 @@ public void testConversionToDate() {
assertEquals(date(18000000L), conversion.convert("1970-01-01T03:10:20-05:00"));

// double check back and forth conversion
ZonedDateTime zdt = TestUtils.now();

ZonedDateTime zdt = org.elasticsearch.common.time.DateUtils.nowWithMillisResolution();
Conversion forward = conversionFor(DATE, KEYWORD);
Conversion back = conversionFor(KEYWORD, DATE);
assertEquals(DateUtils.asDateOnly(zdt), back.convert(forward.convert(zdt)));
Expand Down Expand Up @@ -205,7 +205,8 @@ public void testConversionToDateTime() {
assertEquals(dateTime(18000000L), conversion.convert("1970-01-01T00:00:00-05:00"));

// double check back and forth conversion
ZonedDateTime dt = TestUtils.now();

ZonedDateTime dt = org.elasticsearch.common.time.DateUtils.nowWithMillisResolution();
Conversion forward = conversionFor(DATETIME, KEYWORD);
Conversion back = conversionFor(KEYWORD, DATETIME);
assertEquals(dt, back.convert(forward.convert(dt)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import org.elasticsearch.client.Client;
import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.time.DateUtils;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.common.xcontent.XContentBuilder;
Expand Down Expand Up @@ -276,7 +277,6 @@ public void testConfigureIndexInMapAndAction() {
fieldName + "] or [ctx.payload._doc." + fieldName + "]"));
}

@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/38581")
public void testIndexActionExecuteSingleDoc() throws Exception {
boolean customId = randomBoolean();
boolean docIdAsParam = customId && randomBoolean();
Expand All @@ -287,7 +287,7 @@ public void testIndexActionExecuteSingleDoc() throws Exception {
refreshPolicy);
ExecutableIndexAction executable = new ExecutableIndexAction(action, logger, client, TimeValue.timeValueSeconds(30),
TimeValue.timeValueSeconds(30));
ZonedDateTime executionTime = ZonedDateTime.now(ZoneOffset.UTC);
ZonedDateTime executionTime = DateUtils.nowWithMillisResolution();
Payload payload;

if (customId && docIdAsParam == false) {
Expand Down

0 comments on commit c921a87

Please sign in to comment.