Elffuss BraidHub

kikocis/java-driver public

JAVA-444: Add Java process information to UUIDs.makeNode() hash.

(cherry-picked from 2.1)
Changesetbc9af5c6adcd86604efe1d6184040ebf7f5bf0a42956d485bc1d5f497107c0e9
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-09 22:28 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2016-06-16 20:05 -07:00
Parents4ba3297e30af

Browse the files at this changeset

10 files changed

modified changelog/README.md +1 −0
@@ -54,6 +54,7 @@
5454 - [improvement] JAVA-963: Automatically register PercentileTracker from components that use it.
5555 - [new feature] JAVA-1019: SchemaBuilder support for CREATE/ALTER/DROP KEYSPACE.
5656 - [bug] JAVA-727: Allow monotonic timestamp generators to drift in the future + use microsecond precision when possible.
57+- [improvement] JAVA-444: Add Java process information to UUIDs.makeNode() hash.
5758
5859
5960 ### 3.0.2
modified driver-core/pom.xml +7 −0
@@ -60,6 +60,12 @@
6060 <version>${jnr-ffi.version}</version>
6161 </dependency>
6262
63+ <dependency>
64+ <groupId>com.github.jnr</groupId>
65+ <artifactId>jnr-posix</artifactId>
66+ <version>${jnr-posix.version}</version>
67+ </dependency>
68+
6369 <!-- Compression libraries for the protocol. -->
6470 <!-- Each of them is only a mandatory runtime dependency if you want to use the compression it offers -->
6571
@@ -338,6 +344,7 @@
338344 <include>**/SSL*Test.java</include>
339345 <include>**/ControlConnectionTest.java</include>
340346 <include>**/ExtendedPeerCheckDisabledTest.java</include>
347+ <include>**/UUIDsPID*.java</include>
341348 </includes>
342349 </configuration>
343350 </plugin>
modified driver-core/src/main/java/com/datastax/driver/core/Clock.java +1 −1
@@ -48,7 +48,7 @@
4848 private static final String USE_NATIVE_CLOCK_SYSTEM_PROPERTY = "com.datastax.driver.USE_NATIVE_CLOCK";
4949
5050 static Clock newInstance() {
51- if (Native.isLibCLoaded() && SystemProperties.getBoolean(USE_NATIVE_CLOCK_SYSTEM_PROPERTY, true)) {
51+ if (Native.isGettimeofdayAvailable() && SystemProperties.getBoolean(USE_NATIVE_CLOCK_SYSTEM_PROPERTY, true)) {
5252 LOGGER.info("Using native clock to generate timestamps.");
5353 return new NativeClock();
5454 } else {
modified driver-core/src/main/java/com/datastax/driver/core/Native.java +173 −38
@@ -24,25 +24,49 @@
2424 import org.slf4j.Logger;
2525 import org.slf4j.LoggerFactory;
2626
27+import java.lang.reflect.Method;
28+
2729 /**
28- * Helper class to deal with native system call through JNR.
30+ * Helper class to deal with native system calls through the
31+ * <a href="https://github.com/jnr/jnr-ffi">JNR library</a>.
32+ * <p/>
33+ * The driver can benefit from native system calls to improve its performance and accuracy
34+ * in some situations.
35+ * <p/>
36+ * Currently, the following features may be used by the driver when available:
37+ * <ol>
38+ * <li>{@link #currentTimeMicros()}: thanks to a system call to {@code gettimeofday()},
39+ * the driver is able to generate timestamps with true microsecond precision
40+ * (see {@link AtomicMonotonicTimestampGenerator} or {@link ThreadLocalMonotonicTimestampGenerator} for
41+ * more information);</li>
42+ * <li>{@link #processId()}: thanks to a system call to {@code getpid()},
43+ * the driver has access to the JVM's process ID it is running under – which
44+ * makes time-based UUID generation easier and more reliable (see {@link com.datastax.driver.core.utils.UUIDs UUIDs}
45+ * for more information).</li>
46+ * </ol>
47+ * <p/>
48+ * The availability of the aforementioned system calls depends on the underlying operation system's
49+ * capabilities. For instance, {@code gettimeofday()} is not available under Windows systems.
50+ * You can check if any of the system calls exposed through this class is available
51+ * by calling {@link #isGettimeofdayAvailable()} or {@link #isGetpidAvailable()}.
52+ * <p/>
53+ * Note: This class is public because it needs to be accessible from other packages of the Java driver,
54+ * but it is not meant to be used directly by client code.
55+ *
56+ * @see <a href="https://github.com/jnr/jnr-ffi">JNR library on Github</a>
2957 */
30-class Native {
58+public final class Native {
3159
3260 private static final Logger LOGGER = LoggerFactory.getLogger(Native.class);
3361
34- /**
35- * Interface for LIBC calls through JNR.
36- * Note that this interface must be declared public.
37- */
38- public interface LibC {
62+ private static class LibCLoader {
3963
4064 /**
4165 * Timeval struct.
4266 *
4367 * @see <a href="http://man7.org/linux/man-pages/man2/settimeofday.2.html">GETTIMEOFDAY(2)</a>
4468 */
45- class Timeval extends Struct {
69+ static class Timeval extends Struct {
4670
4771 public final time_t tv_sec = new time_t();
4872
@@ -54,56 +78,167 @@
5478 }
5579
5680 /**
57- * JNR call to {@code gettimeofday}.
58- *
59- * @param tv Timeval struct
60- * @param unused Timezone struct (unused)
61- * @return 0 for success, or -1 for failure
62- * @see <a href="http://man7.org/linux/man-pages/man2/settimeofday.2.html">GETTIMEOFDAY(2)</a>
81+ * Interface for LIBC calls through JNR.
82+ * Note that this interface must be declared public.
6383 */
64- int gettimeofday(@Out @Transient Timeval tv, Pointer unused);
84+ public interface LibC {
85+
86+ /**
87+ * JNR call to {@code gettimeofday}.
88+ *
89+ * @param tv Timeval struct
90+ * @param unused Timezone struct (unused)
91+ * @return 0 for success, or -1 for failure
92+ * @see <a href="http://man7.org/linux/man-pages/man2/settimeofday.2.html">GETTIMEOFDAY(2)</a>
93+ */
94+ int gettimeofday(@Out @Transient Timeval tv, Pointer unused);
95+
96+ }
97+
98+ private static final LibC LIB_C;
99+
100+ private static final Runtime LIB_C_RUNTIME;
101+
102+ private static final boolean GETTIMEOFDAY_AVAILABLE;
103+
104+ static {
105+ LibC libc;
106+ Runtime runtime = null;
107+ try {
108+ libc = LibraryLoader.create(LibC.class).load("c");
109+ runtime = Runtime.getRuntime(libc);
110+ } catch (Throwable t) {
111+ libc = null; // dereference proxy to library if runtime could not be loaded
112+ if (LOGGER.isDebugEnabled())
113+ LOGGER.debug("Could not load JNR C Library, native system calls through this library will not be available", t);
114+ else
115+ LOGGER.info("Could not load JNR C Library, native system calls through this library will not be available " +
116+ "(set this logger level to DEBUG to see the full stack trace).");
117+
118+ }
119+ LIB_C = libc;
120+ LIB_C_RUNTIME = runtime;
121+ boolean gettimeofday = false;
122+ if (LIB_C_RUNTIME != null) {
123+ try {
124+ gettimeofday = LIB_C.gettimeofday(new Timeval(LIB_C_RUNTIME), null) == 0;
125+ } catch (Throwable t) {
126+ if (LOGGER.isDebugEnabled())
127+ LOGGER.debug("Native calls to gettimeofday() not available on this system.", t);
128+ else
129+ LOGGER.info("Native calls to gettimeofday() not available on this system " +
130+ "(set this logger level to DEBUG to see the full stack trace).");
131+ }
132+ }
133+ GETTIMEOFDAY_AVAILABLE = gettimeofday;
134+ }
135+
65136 }
66137
67- private static final LibC LIB_C;
138+ private static class PosixLoader {
68139
69- private static final Runtime LIB_C_RUNTIME;
140+ public static final jnr.posix.POSIX POSIX;
70141
71- static {
72- LibC libc = null;
73- Runtime runtime = null;
142+ private static final boolean GETPID_AVAILABLE;
143+
144+ static {
145+ jnr.posix.POSIX posix;
146+ try {
147+ // use reflection below to get the classloader a chance to load this class
148+ Class<?> posixHandler = Class.forName("jnr.posix.POSIXHandler");
149+ Class<?> defaultPosixHandler = Class.forName("jnr.posix.util.DefaultPOSIXHandler");
150+ Class<?> posixFactory = Class.forName("jnr.posix.POSIXFactory");
151+ Method getPOSIX = posixFactory.getMethod("getPOSIX", posixHandler, Boolean.TYPE);
152+ posix = (jnr.posix.POSIX) getPOSIX.invoke(null, defaultPosixHandler.newInstance(), true);
153+ } catch (Throwable t) {
154+ posix = null;
155+ if (LOGGER.isDebugEnabled())
156+ LOGGER.debug("Could not load JNR POSIX Library, native system calls through this library will not be available.", t);
157+ else
158+ LOGGER.info("Could not load JNR POSIX Library, native system calls through this library will not be available " +
159+ "(set this logger level to DEBUG to see the full stack trace).");
160+ }
161+ POSIX = posix;
162+ boolean getpid = false;
163+ if (POSIX != null) {
164+ try {
165+ POSIX.getpid();
166+ getpid = true;
167+ } catch (Throwable t) {
168+ if (LOGGER.isDebugEnabled())
169+ LOGGER.debug("Native calls to getpid() not available on this system.", t);
170+ else
171+ LOGGER.info("Native calls to getpid() not available on this system " +
172+ "(set this logger level to DEBUG to see the full stack trace).");
173+ }
174+ }
175+ GETPID_AVAILABLE = getpid;
176+ }
177+
178+ }
179+
180+ /**
181+ * Returns {@code true} if JNR C library is loaded and
182+ * a call to {@code gettimeofday} is possible through this library
183+ * on this system, and {@code false} otherwise.
184+ *
185+ * @return {@code true} if JNR C library is loaded and
186+ * a call to {@code gettimeofday} is possible.
187+ */
188+ public static boolean isGettimeofdayAvailable() {
74189 try {
75- libc = LibraryLoader.create(LibC.class).load("c");
76- runtime = Runtime.getRuntime(libc);
77- } catch (Throwable t) {
78- if (LOGGER.isDebugEnabled())
79- LOGGER.debug("Could not load JNR LibC Library, native calls will not be available", t);
80- else
81- LOGGER.info("Could not load JNR LibC Library, native calls will not be available (set this logger level to DEBUG to see the full stack trace)");
190+ return LibCLoader.GETTIMEOFDAY_AVAILABLE;
191+ } catch (NoClassDefFoundError e) {
192+ return false;
82193 }
83- LIB_C = libc;
84- LIB_C_RUNTIME = runtime;
85194 }
86195
87196 /**
88- * Returns true if LibC could be loaded with JNR.
197+ * Returns {@code true} if JNR POSIX library is loaded and
198+ * a call to {@code getpid} is possible through this library
199+ * on this system, and {@code false} otherwise.
89200 *
90- * @return true if LibC could be loaded with JNR, false otherwise.
201+ * @return {@code true} if JNR POSIX library is loaded and
202+ * a call to {@code getpid} is possible.
91203 */
92- static boolean isLibCLoaded() {
93- return LIB_C_RUNTIME != null;
204+ public static boolean isGetpidAvailable() {
205+ try {
206+ return PosixLoader.GETPID_AVAILABLE;
207+ } catch (NoClassDefFoundError e) {
208+ return false;
209+ }
210+
94211 }
95212
96213 /**
97214 * Returns the current timestamp with microsecond precision
98- * via a system call to {@code gettimeofday}.
215+ * via a system call to {@code gettimeofday}, through JNR C library.
99216 *
100217 * @return the current timestamp with microsecond precision.
218+ * @throws UnsupportedOperationException if JNR C library is not loaded or {@code gettimeofday} is not available.
219+ * @throws IllegalStateException if the call to {@code gettimeofday} did not complete with return code 0.
101220 */
102- static long currentTimeMicros() {
103- LibC.Timeval tv = new LibC.Timeval(LIB_C_RUNTIME);
104- if (LIB_C.gettimeofday(tv, null) != 0)
105- LOGGER.error("gettimeofday failed");
221+ public static long currentTimeMicros() {
222+ if (!isGettimeofdayAvailable())
223+ throw new UnsupportedOperationException("JNR C library not loaded or gettimeofday not available");
224+ LibCLoader.Timeval tv = new LibCLoader.Timeval(LibCLoader.LIB_C_RUNTIME);
225+ int res = LibCLoader.LIB_C.gettimeofday(tv, null);
226+ if (res != 0)
227+ throw new IllegalStateException("Call to gettimeofday failed with result " + res);
106228 return tv.tv_sec.get() * 1000000 + tv.tv_usec.get();
107229 }
108230
231+ /**
232+ * Returns the JVM's process identifier (PID)
233+ * via a system call to {@code getpid}.
234+ *
235+ * @return the JVM's process identifier (PID).
236+ * @throws UnsupportedOperationException if JNR POSIX library is not loaded or {@code getpid} is not available.
237+ */
238+ public static int processId() {
239+ if (!isGetpidAvailable())
240+ throw new UnsupportedOperationException("JNR POSIX library not loaded or getpid not available");
241+ return PosixLoader.POSIX.getpid();
242+ }
243+
109244 }
modified driver-core/src/main/java/com/datastax/driver/core/utils/UUIDs.java +96 −27
@@ -15,8 +15,12 @@
1515 */
1616 package com.datastax.driver.core.utils;
1717
18+import com.datastax.driver.core.Native;
1819 import com.google.common.base.Charsets;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
1922
23+import java.lang.management.ManagementFactory;
2024 import java.net.InetAddress;
2125 import java.net.NetworkInterface;
2226 import java.net.SocketException;
@@ -27,17 +31,43 @@
2731 import java.util.concurrent.atomic.AtomicLong;
2832
2933 /**
30- * Utility methods to work with UUID and most specifically with time-based ones
31- * (version 1).
34+ * Utility methods to help working with UUIDs, and more specifically, with time-based UUIDs
35+ * (also known as Version 1 UUIDs).
36+ * <h3>Notes on the algorithm used to generate time-based UUIDs</h3>
37+ * The algorithm follows roughly the description in RFC-4122, but with the following adaptations:
38+ * <ol>
39+ * <li>Since Java does not provide direct access to the host's MAC address, that information
40+ * is replaced with a digest of all IP addresses available on the host;</li>
41+ * <li>The process ID (PID) isn't easily available to Java either, so it is determined by one of the
42+ * following methods, in the order they are listed below:
43+ * <ol>
44+ * <li>If the System property <code>{@value PID_SYSTEM_PROPERTY}</code> is set then the value to use as a PID
45+ * will be read from that property;</li>
46+ * <li>Otherwise, if a native call to {@link Native#processId() getpid()} is possible, then the PID
47+ * will be read from that call;</li>
48+ * <li>Otherwise, an attempt will be made to read the PID from JMX's
49+ * {@link ManagementFactory#getRuntimeMXBean() RuntimeMXBean}, which is a well-known,
50+ * yet undocumented "hack", since most JVMs tend to use the JVM's PID as part of that MXBean name;</li>
51+ * <li>If all of the above fails, a random integer will be generated and used as a surrogate PID.</li>
52+ * </ol>
53+ * </li>
54+ * </ol>
55+ *
56+ * @jira_ticket JAVA-444
57+ * @see <a href="http://www.ietf.org/rfc/rfc4122.txt">A Universally Unique IDentifier (UUID) URN Namespace (RFC 4122)</a>
3258 */
3359 public final class UUIDs {
3460
61+ /**
62+ * The System property to use to force the value of the process ID (PID).
63+ */
64+ public static final String PID_SYSTEM_PROPERTY = "com.datastax.driver.PID";
65+
66+ private static final Logger LOGGER = LoggerFactory.getLogger(UUIDs.class);
67+
3568 private UUIDs() {
3669 }
3770
38- ;
39-
40- // http://www.ietf.org/rfc/rfc4122.txt
4171 private static final long START_EPOCH = makeEpoch();
4272 private static final long CLOCK_SEQ_AND_NODE = makeClockSeqAndNode();
4373
@@ -94,6 +124,7 @@
94124 update(digest, props.getProperty("os.arch"));
95125 update(digest, props.getProperty("os.name"));
96126 update(digest, props.getProperty("os.version"));
127+ update(digest, getProcessPiece());
97128
98129 byte[] hash = digest.digest();
99130
@@ -108,6 +139,43 @@
108139 }
109140 }
110141
142+ private static String getProcessPiece() {
143+ Integer pid = null;
144+ String pidProperty = System.getProperty(PID_SYSTEM_PROPERTY);
145+ if (pidProperty != null) {
146+ try {
147+ pid = Integer.parseInt(pidProperty);
148+ LOGGER.info("PID obtained from System property {}: {}", PID_SYSTEM_PROPERTY, pid);
149+ } catch (NumberFormatException e) {
150+ LOGGER.warn("Incorrect integer specified for PID in System property {}: {}", PID_SYSTEM_PROPERTY, pidProperty);
151+ }
152+ }
153+ if (pid == null && Native.isGetpidAvailable()) {
154+ try {
155+ pid = Native.processId();
156+ LOGGER.info("PID obtained through native call to getpid(): {}", pid);
157+ } catch (Exception e) {
158+ LOGGER.warn("Native call to getpid() failed", e);
159+ }
160+ }
161+ if (pid == null) {
162+ try {
163+ String pidJmx = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
164+ pid = Integer.parseInt(pidJmx);
165+ LOGGER.info("PID obtained through JMX: {}", pid);
166+ } catch (Exception e) {
167+ LOGGER.warn("Failed to obtain PID from JMX", e);
168+ }
169+ }
170+ if (pid == null) {
171+ pid = new java.util.Random().nextInt();
172+ LOGGER.warn("Could not determine PID, falling back to a random integer: {}", pid);
173+ }
174+ ClassLoader loader = UUIDs.class.getClassLoader();
175+ int loaderId = loader != null ? System.identityHashCode(loader) : 0;
176+ return Integer.toHexString(pid) + Integer.toHexString(loaderId);
177+ }
178+
111179 private static void update(MessageDigest digest, String value) {
112180 if (value != null)
113181 digest.update(value.getBytes(Charsets.UTF_8));
@@ -138,7 +206,7 @@
138206 /**
139207 * Creates a new time-based (version 1) UUID.
140208 * <p/>
141- * UUID generated by this method are suitable for use with the
209+ * UUIDs generated by this method are suitable for use with the
142210 * {@code timeuuid} Cassandra type. In particular the generated UUID
143211 * includes the timestamp of its generation.
144212 * <p/>
@@ -162,29 +230,30 @@
162230 * Creates a "fake" time-based UUID that sorts as the smallest possible
163231 * version 1 UUID generated at the provided timestamp.
164232 * <p/>
165- * Such created UUID are useful in queries to select a time range of a
233+ * Such created UUIDs are useful in queries to select a time range of a
166234 * {@code timeuuid} column.
167235 * <p/>
168- * The UUID created by this method <b>are not unique</b> and as such are
236+ * The UUIDs created by this method <b>are not unique</b> and as such are
169237 * <b>not</b> suitable for anything else than querying a specific time
170- * range. In particular, you should not insert such UUID. "True" UUID from
238+ * range. In particular, you should not insert such UUIDs. "True" UUIDs from
171239 * user-provided timestamps are not supported (see {@link #timeBased()}
172240 * for more explanations).
173241 * <p/>
174- * Also, the timestamp to provide as parameter must be a unix timestamp (as
175- * returned by {@link System#currentTimeMillis} or {@link java.util.Date#getTime}),
176- * not a UUID 100-nanoseconds interval since 15 October 1582. In other
177- * words, given a UUID {@code uuid}, you should never do
242+ * Also, the timestamp to provide as a parameter must be a Unix timestamp (as
243+ * returned by {@link System#currentTimeMillis} or {@link java.util.Date#getTime}), and
244+ * <em>not</em> a count of 100-nanosecond intervals since 00:00:00.00, 15 October 1582 (as required by RFC-4122).
245+ * <p/>
246+ * In other words, given a UUID {@code uuid}, you should never call
178247 * {@code startOf(uuid.timestamp())} but rather
179248 * {@code startOf(unixTimestamp(uuid))}.
180249 * <p/>
181- * Lastly, please note that Cassandra's timeuuid sorting is not compatible
182- * with {@link UUID#compareTo} and hence the UUID created by this method
250+ * Lastly, please note that Cassandra's {@code timeuuid} sorting is not compatible
251+ * with {@link UUID#compareTo} and hence the UUIDs created by this method
183252 * are not necessarily lower bound for that latter method.
184253 *
185- * @param timestamp the unix timestamp for which the created UUID must be a
254+ * @param timestamp the Unix timestamp for which the created UUID must be a
186255 * lower bound.
187- * @return the smallest (for Cassandra timeuuid sorting) UUID of {@code timestamp}.
256+ * @return the smallest (for Cassandra {@code timeuuid} sorting) UUID of {@code timestamp}.
188257 */
189258 public static UUID startOf(long timestamp) {
190259 return new UUID(makeMSB(fromUnixTimestamp(timestamp)), MIN_CLOCK_SEQ_AND_NODE);
@@ -196,9 +265,9 @@
196265 * <p/>
197266 * See {@link #startOf(long)} for explanations about the intended usage of such UUID.
198267 *
199- * @param timestamp the unix timestamp for which the created UUID must be an
268+ * @param timestamp the Unix timestamp for which the created UUID must be an
200269 * upper bound.
201- * @return the biggest (for Cassandra timeuuid sorting) UUID of {@code timestamp}.
270+ * @return the biggest (for Cassandra {@code timeuuid} sorting) UUID of {@code timestamp}.
202271 */
203272 public static UUID endOf(long timestamp) {
204273 long uuidTstamp = fromUnixTimestamp(timestamp + 1) - 1;
@@ -206,20 +275,20 @@
206275 }
207276
208277 /**
209- * Return the unix timestamp contained by the provided time-based UUID.
278+ * Return the Unix timestamp contained by the provided time-based UUID.
210279 * <p/>
211- * This method is not equivalent to {@code uuid.timestamp()}. More
280+ * This method is not equivalent to {@link UUID#timestamp()}. More
212281 * precisely, a version 1 UUID stores a timestamp that represents the
213282 * number of 100-nanoseconds intervals since midnight, 15 October 1582 and
214- * that is what {@code uuid.timestamp()} returns. This method however
215- * converts that timestamp to the equivalent unix timestamp in
283+ * that is what {@link UUID#timestamp()} returns. This method however
284+ * converts that timestamp to the equivalent Unix timestamp in
216285 * milliseconds, i.e. a timestamp representing a number of milliseconds
217- * since midnight, January 1, 1970 UTC. In particular the timestamps
218- * returned by this method are comparable to the timestamp returned by
286+ * since midnight, January 1, 1970 UTC. In particular, the timestamps
287+ * returned by this method are comparable to the timestamps returned by
219288 * {@link System#currentTimeMillis}, {@link java.util.Date#getTime}, etc.
220289 *
221290 * @param uuid the UUID to return the timestamp of.
222- * @return the unix timestamp of {@code uuid}.
291+ * @return the Unix timestamp of {@code uuid}.
223292 * @throws IllegalArgumentException if {@code uuid} is not a version 1 UUID.
224293 */
225294 public static long unixTimestamp(UUID uuid) {
@@ -231,7 +300,7 @@
231300 }
232301
233302 /*
234- * Note that currently we use System.currentTimeMillis() for a base time in
303+ * Note that currently we use {@link System#currentTimeMillis} for a base time in
235304 * milliseconds, and then if we are in the same milliseconds that the
236305 * previous generation, we increment the number of nanoseconds.
237306 * However, since the precision is 100-nanoseconds intervals, we can only
added driver-core/src/test/java/com/datastax/driver/core/ClockFactoryTest.java +48 −0
@@ -0,0 +1,48 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import org.testng.SkipException;
19+import org.testng.annotations.Test;
20+
21+import static org.assertj.core.api.Assertions.assertThat;
22+
23+public class ClockFactoryTest {
24+
25+ final String osName = System.getProperty("os.name");
26+
27+ @Test(groups = "unit")
28+ public void should_use_native_clock_on_unix_platforms() {
29+ // Cowardly assume any non-windows platform will support gettimeofday. If we find one that doesn't,
30+ // we will have learned something.
31+ if (osName.startsWith("Windows")) {
32+ throw new SkipException("Skipping test for Windows platforms.");
33+ }
34+ Clock clock = ClockFactory.newInstance();
35+ assertThat(clock).isInstanceOf(NativeClock.class);
36+ assertThat(clock.currentTimeMicros()).isGreaterThan(0);
37+ }
38+
39+ @Test(groups = "unit")
40+ public void should_fallback_on_system_clock_on_windows_platforms() {
41+ if (!osName.startsWith("Windows")) {
42+ throw new SkipException("Skipping test for non-Windows platforms.");
43+ }
44+ Clock clock = ClockFactory.newInstance();
45+ assertThat(clock).isInstanceOf(SystemClock.class);
46+ assertThat(clock.currentTimeMicros()).isGreaterThan(0);
47+ }
48+}
added driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDFromPropertyTest.java +48 −0
@@ -0,0 +1,48 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.utils;
17+
18+import com.datastax.driver.core.MemoryAppender;
19+import org.apache.log4j.Level;
20+import org.apache.log4j.Logger;
21+import org.testng.annotations.Test;
22+
23+import static org.assertj.core.api.Assertions.assertThat;
24+
25+public class UUIDsPIDFromPropertyTest {
26+
27+ private static final Logger logger = Logger.getLogger(UUIDs.class);
28+
29+ @Test(groups = "isolated")
30+ public void should_obtain_pid_from_system_property() {
31+ // If the com.datastax.driver.PID property is set, it should be used and this should be logged.
32+ MemoryAppender appender = new MemoryAppender();
33+ Level originalLevel = logger.getLevel();
34+ try {
35+ logger.setLevel(Level.INFO);
36+ logger.addAppender(appender);
37+ int pid = 8675;
38+ System.setProperty(UUIDs.PID_SYSTEM_PROPERTY, "" + pid);
39+ UUIDs.timeBased();
40+ assertThat(appender.get())
41+ .containsOnlyOnce(String.format("PID obtained from System property %s: %d",
42+ UUIDs.PID_SYSTEM_PROPERTY, pid));
43+ } finally {
44+ logger.removeAppender(appender);
45+ logger.setLevel(originalLevel);
46+ }
47+ }
48+}
added driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDNativeTest.java +45 −0
@@ -0,0 +1,45 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.utils;
17+
18+import com.datastax.driver.core.MemoryAppender;
19+import org.apache.log4j.Level;
20+import org.apache.log4j.Logger;
21+import org.testng.annotations.Test;
22+
23+import static org.assertj.core.api.Assertions.assertThat;
24+
25+public class UUIDsPIDNativeTest {
26+
27+ private static final Logger logger = Logger.getLogger(UUIDs.class);
28+
29+ @Test(groups = "isolated")
30+ public void should_obtain_pid_through_native_call() {
31+ // In the general case the JNR call should *just* work as most systems should support POSIX getpid.
32+ MemoryAppender appender = new MemoryAppender();
33+ Level originalLevel = logger.getLevel();
34+ try {
35+ logger.setLevel(Level.INFO);
36+ logger.addAppender(appender);
37+ UUIDs.timeBased();
38+
39+ assertThat(appender.get()).containsOnlyOnce("PID obtained through native call to getpid()");
40+ } finally {
41+ logger.removeAppender(appender);
42+ logger.setLevel(originalLevel);
43+ }
44+ }
45+}
added driver-core/src/test/java/com/datastax/driver/core/utils/UUIDsPIDPropertyInvalidTest.java +49 −0
@@ -0,0 +1,49 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.utils;
17+
18+import com.datastax.driver.core.MemoryAppender;
19+import org.apache.log4j.Level;
20+import org.apache.log4j.Logger;
21+import org.testng.annotations.Test;
22+
23+import static org.assertj.core.api.Assertions.assertThat;
24+
25+public class UUIDsPIDPropertyInvalidTest {
26+
27+ private static final Logger logger = Logger.getLogger(UUIDs.class);
28+
29+ @Test(groups = "isolated")
30+ public void should_fallback_on_native_call_if_system_property_invalid() {
31+ // If the com.datastax.driver.PID property is set, but is invalid, it should fallback onto native getpid().
32+ MemoryAppender appender = new MemoryAppender();
33+ Level originalLevel = logger.getLevel();
34+ try {
35+ logger.setLevel(Level.INFO);
36+ logger.addAppender(appender);
37+ String pid = "NOT_A_PID";
38+ System.setProperty(UUIDs.PID_SYSTEM_PROPERTY, pid);
39+ UUIDs.timeBased();
40+ assertThat(appender.get())
41+ .containsOnlyOnce(String.format("Incorrect integer specified for PID in System property %s: %s",
42+ UUIDs.PID_SYSTEM_PROPERTY, pid))
43+ .containsOnlyOnce("PID obtained through native call to getpid()");
44+ } finally {
45+ logger.removeAppender(appender);
46+ logger.setLevel(originalLevel);
47+ }
48+ }
49+}
modified pom.xml +1 −0
@@ -63,6 +63,7 @@
6363 <jsr353-api.version>1.0</jsr353-api.version>
6464 <jsr353-ri.version>1.0.4</jsr353-ri.version>
6565 <jnr-ffi.version>2.0.7</jnr-ffi.version>
66+ <jnr-posix.version>3.0.27</jnr-posix.version>
6667 <!-- test dependency versions -->
6768 <testng.version>6.8.8</testng.version>
6869 <assertj.version>1.7.0</assertj.version>