You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ratis.apache.org by sz...@apache.org on 2017/03/31 06:56:46 UTC
[1/2] incubator-ratis git commit: Revert "RATIS-52. Refactor
RaftUtils into different classes. Contributed by Enis Soztutar"
Repository: incubator-ratis
Updated Branches:
refs/heads/master 43ad0def6 -> 771e8adc4
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-grpc/src/main/java/org/apache/ratis/grpc/server/GRpcLogAppender.java
----------------------------------------------------------------------
diff --git a/ratis-grpc/src/main/java/org/apache/ratis/grpc/server/GRpcLogAppender.java b/ratis-grpc/src/main/java/org/apache/ratis/grpc/server/GRpcLogAppender.java
index 656adc2..e29da00 100644
--- a/ratis-grpc/src/main/java/org/apache/ratis/grpc/server/GRpcLogAppender.java
+++ b/ratis-grpc/src/main/java/org/apache/ratis/grpc/server/GRpcLogAppender.java
@@ -31,7 +31,7 @@ import org.apache.ratis.server.impl.LogAppender;
import org.apache.ratis.server.impl.RaftServerImpl;
import org.apache.ratis.statemachine.SnapshotInfo;
import org.apache.ratis.util.CodeInjectionForTesting;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import static org.apache.ratis.grpc.RaftGRpcService.GRPC_SEND_SERVER_REQUEST;
@@ -130,7 +130,7 @@ public class GRpcLogAppender extends LogAppender {
// together and protected by the lock
pending = createRequest();
if (pending != null) {
- Preconditions.assertTrue(pendingRequests.offer(pending));
+ RaftUtils.assertTrue(pendingRequests.offer(pending));
updateNextIndex(pending);
}
}
@@ -261,7 +261,7 @@ public class GRpcLogAppender extends LogAppender {
+ " but the pending queue is empty");
if (request.getEntriesCount() == 0) {
- Preconditions.assertTrue(!request.hasPreviousLog() ||
+ RaftUtils.assertTrue(!request.hasPreviousLog() ||
replyNextIndex - 1 == request.getPreviousLog().getIndex(),
"reply's next index is %s, request's previous is %s",
replyNextIndex, request.getPreviousLog());
@@ -269,7 +269,7 @@ public class GRpcLogAppender extends LogAppender {
// check if the reply and the pending request is consistent
final long lastEntryIndex = request
.getEntries(request.getEntriesCount() - 1).getIndex();
- Preconditions.assertTrue(replyNextIndex == lastEntryIndex + 1,
+ RaftUtils.assertTrue(replyNextIndex == lastEntryIndex + 1,
"reply's next index is %s, request's last entry index is %s",
replyNextIndex, lastEntryIndex);
follower.updateMatchIndex(lastEntryIndex);
@@ -284,7 +284,7 @@ public class GRpcLogAppender extends LogAppender {
private synchronized void onInconsistency(AppendEntriesReplyProto reply) {
AppendEntriesRequestProto request = pendingRequests.peek();
- Preconditions.assertTrue(request.hasPreviousLog());
+ RaftUtils.assertTrue(request.hasPreviousLog());
if (request.getPreviousLog().getIndex() >= reply.getNextIndex()) {
clearPendingRequests(reply.getNextIndex());
}
@@ -305,7 +305,7 @@ public class GRpcLogAppender extends LogAppender {
synchronized void removePending(InstallSnapshotReplyProto reply) {
int index = pending.poll();
- Preconditions.assertTrue(index == reply.getRequestIndex());
+ RaftUtils.assertTrue(index == reply.getRequestIndex());
}
boolean isDone() {
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftReconfigurationWithGRpc.java
----------------------------------------------------------------------
diff --git a/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftReconfigurationWithGRpc.java b/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftReconfigurationWithGRpc.java
index 822b923..4f54fa8 100644
--- a/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftReconfigurationWithGRpc.java
+++ b/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftReconfigurationWithGRpc.java
@@ -20,13 +20,13 @@ package org.apache.ratis.grpc;
import org.apache.log4j.Level;
import org.apache.ratis.grpc.server.RaftServerProtocolService;
import org.apache.ratis.server.impl.RaftReconfigurationBaseTest;
-import org.apache.ratis.util.LogUtils;
+import org.apache.ratis.util.RaftUtils;
import java.io.IOException;
public class TestRaftReconfigurationWithGRpc extends RaftReconfigurationBaseTest {
static {
- LogUtils.setLogLevel(RaftServerProtocolService.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerProtocolService.LOG, Level.DEBUG);
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftStream.java
----------------------------------------------------------------------
diff --git a/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftStream.java b/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftStream.java
index 16bc221..4bae5a9 100644
--- a/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftStream.java
+++ b/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftStream.java
@@ -20,7 +20,6 @@ package org.apache.ratis.grpc;
import org.apache.log4j.Level;
import org.apache.ratis.RaftTestUtil;
import org.apache.ratis.conf.RaftProperties;
-import org.apache.ratis.util.LogUtils;
import org.apache.ratis.util.SizeInBytes;
import org.apache.ratis.grpc.client.AppendStreamer;
import org.apache.ratis.grpc.client.RaftOutputStream;
@@ -28,6 +27,7 @@ import org.apache.ratis.protocol.ClientId;
import org.apache.ratis.server.impl.RaftServerImpl;
import org.apache.ratis.server.storage.RaftLog;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
+import org.apache.ratis.util.RaftUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
@@ -47,7 +47,7 @@ import static org.junit.Assert.fail;
public class TestRaftStream {
static {
- LogUtils.setLogLevel(AppendStreamer.LOG, Level.ALL);
+ RaftUtils.setLogLevel(AppendStreamer.LOG, Level.ALL);
}
static final Logger LOG = LoggerFactory.getLogger(TestRaftStream.class);
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftWithGrpc.java
----------------------------------------------------------------------
diff --git a/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftWithGrpc.java b/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftWithGrpc.java
index d7b72c2..bfaf819 100644
--- a/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftWithGrpc.java
+++ b/ratis-grpc/src/test/java/org/apache/ratis/grpc/TestRaftWithGrpc.java
@@ -21,7 +21,7 @@ import org.apache.log4j.Level;
import org.apache.ratis.RaftBasicTests;
import org.apache.ratis.server.impl.BlockRequestHandlingInjection;
import org.apache.ratis.server.impl.RaftServerImpl;
-import org.apache.ratis.util.LogUtils;
+import org.apache.ratis.util.RaftUtils;
import org.junit.Assert;
import org.junit.Test;
@@ -29,7 +29,7 @@ import java.io.IOException;
public class TestRaftWithGrpc extends RaftBasicTests {
static {
- LogUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
}
private final MiniRaftClusterWithGRpc cluster;
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-hadoop/src/test/java/org/apache/ratis/hadooprpc/TestRaftReconfigurationWithHadoopRpc.java
----------------------------------------------------------------------
diff --git a/ratis-hadoop/src/test/java/org/apache/ratis/hadooprpc/TestRaftReconfigurationWithHadoopRpc.java b/ratis-hadoop/src/test/java/org/apache/ratis/hadooprpc/TestRaftReconfigurationWithHadoopRpc.java
index df432fc..7a36fa1 100644
--- a/ratis-hadoop/src/test/java/org/apache/ratis/hadooprpc/TestRaftReconfigurationWithHadoopRpc.java
+++ b/ratis-hadoop/src/test/java/org/apache/ratis/hadooprpc/TestRaftReconfigurationWithHadoopRpc.java
@@ -22,7 +22,9 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.Client;
import org.apache.log4j.Level;
import org.apache.ratis.MiniRaftCluster;
+import org.apache.ratis.client.RaftClient;
import org.apache.ratis.server.impl.RaftReconfigurationBaseTest;
+import org.apache.ratis.util.RaftUtils;
import java.io.IOException;
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-hadoop/src/test/java/org/apache/ratis/hadooprpc/TestRaftWithHadoopRpc.java
----------------------------------------------------------------------
diff --git a/ratis-hadoop/src/test/java/org/apache/ratis/hadooprpc/TestRaftWithHadoopRpc.java b/ratis-hadoop/src/test/java/org/apache/ratis/hadooprpc/TestRaftWithHadoopRpc.java
index 124e7ee..5c03129 100644
--- a/ratis-hadoop/src/test/java/org/apache/ratis/hadooprpc/TestRaftWithHadoopRpc.java
+++ b/ratis-hadoop/src/test/java/org/apache/ratis/hadooprpc/TestRaftWithHadoopRpc.java
@@ -22,7 +22,7 @@ import org.apache.ratis.RaftBasicTests;
import org.apache.ratis.client.RaftClient;
import org.apache.ratis.server.impl.BlockRequestHandlingInjection;
import org.apache.ratis.server.impl.RaftServerImpl;
-import org.apache.ratis.util.LogUtils;
+import org.apache.ratis.util.RaftUtils;
import org.junit.Test;
import java.io.IOException;
@@ -31,9 +31,9 @@ import static org.apache.ratis.hadooprpc.MiniRaftClusterWithHadoopRpc.sendServer
public class TestRaftWithHadoopRpc extends RaftBasicTests {
static {
- LogUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
- LogUtils.setLogLevel(MiniRaftClusterWithHadoopRpc.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(MiniRaftClusterWithHadoopRpc.LOG, Level.DEBUG);
}
private final MiniRaftClusterWithHadoopRpc cluster;
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-netty/src/main/java/org/apache/ratis/netty/NettyRpcProxy.java
----------------------------------------------------------------------
diff --git a/ratis-netty/src/main/java/org/apache/ratis/netty/NettyRpcProxy.java b/ratis-netty/src/main/java/org/apache/ratis/netty/NettyRpcProxy.java
index 5b3492b..8b64784 100644
--- a/ratis-netty/src/main/java/org/apache/ratis/netty/NettyRpcProxy.java
+++ b/ratis-netty/src/main/java/org/apache/ratis/netty/NettyRpcProxy.java
@@ -28,9 +28,9 @@ import org.apache.ratis.shaded.io.netty.handler.codec.protobuf.ProtobufVarint32L
import org.apache.ratis.shaded.proto.RaftProtos.RaftRpcRequestProto;
import org.apache.ratis.shaded.proto.netty.NettyProtos.RaftNettyServerReplyProto;
import org.apache.ratis.shaded.proto.netty.NettyProtos.RaftNettyServerRequestProto;
-import org.apache.ratis.util.IOUtils;
import org.apache.ratis.util.PeerProxyMap;
import org.apache.ratis.util.ProtoUtils;
+import org.apache.ratis.util.RaftUtils;
import java.io.Closeable;
import java.io.IOException;
@@ -51,7 +51,7 @@ public class NettyRpcProxy implements Closeable {
try {
return new NettyRpcProxy(peer, group);
} catch (InterruptedException e) {
- throw IOUtils.toInterruptedIOException("Failed connecting to " + peer, e);
+ throw RaftUtils.toInterruptedIOException("Failed connecting to " + peer, e);
}
}
@@ -170,10 +170,10 @@ public class NettyRpcProxy implements Closeable {
channelFuture.sync();
return reply.get();
} catch (InterruptedException e) {
- throw IOUtils.toInterruptedIOException(ProtoUtils.toString(request)
+ throw RaftUtils.toInterruptedIOException(ProtoUtils.toString(request)
+ " sending from " + peer + " is interrupted.", e);
} catch (ExecutionException e) {
- throw IOUtils.toIOException(e);
+ throw RaftUtils.toIOException(e);
}
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-netty/src/test/java/org/apache/ratis/netty/TestRaftWithNetty.java
----------------------------------------------------------------------
diff --git a/ratis-netty/src/test/java/org/apache/ratis/netty/TestRaftWithNetty.java b/ratis-netty/src/test/java/org/apache/ratis/netty/TestRaftWithNetty.java
index afb7c2b..a48e608 100644
--- a/ratis-netty/src/test/java/org/apache/ratis/netty/TestRaftWithNetty.java
+++ b/ratis-netty/src/test/java/org/apache/ratis/netty/TestRaftWithNetty.java
@@ -22,15 +22,15 @@ import org.apache.ratis.RaftBasicTests;
import org.apache.ratis.client.RaftClient;
import org.apache.ratis.server.impl.BlockRequestHandlingInjection;
import org.apache.ratis.server.impl.RaftServerImpl;
-import org.apache.ratis.util.LogUtils;
+import org.apache.ratis.util.RaftUtils;
import org.junit.Test;
import java.io.IOException;
public class TestRaftWithNetty extends RaftBasicTests {
static {
- LogUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
}
private final MiniRaftClusterWithNetty cluster;
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/impl/ConfigurationManager.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/ConfigurationManager.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/ConfigurationManager.java
index 6aed1d7..85b41d0 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/ConfigurationManager.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/ConfigurationManager.java
@@ -17,7 +17,7 @@
*/
package org.apache.ratis.server.impl;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.util.*;
@@ -44,7 +44,7 @@ public class ConfigurationManager {
public synchronized void addConfiguration(long logIndex,
RaftConfiguration conf) {
- Preconditions.assertTrue(configurations.isEmpty() ||
+ RaftUtils.assertTrue(configurations.isEmpty() ||
configurations.lastEntry().getKey() < logIndex);
configurations.put(logIndex, conf);
this.currentConf = conf;
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderElection.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderElection.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderElection.java
index d026db6..db899f1 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderElection.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderElection.java
@@ -24,8 +24,8 @@ import org.apache.ratis.shaded.proto.RaftProtos.RequestVoteReplyProto;
import org.apache.ratis.shaded.proto.RaftProtos.RequestVoteRequestProto;
import org.apache.ratis.statemachine.SnapshotInfo;
import org.apache.ratis.util.Daemon;
-import org.apache.ratis.util.Preconditions;
import org.apache.ratis.util.ProtoUtils;
+import org.apache.ratis.util.RaftUtils;
import org.apache.ratis.util.Timestamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -91,7 +91,7 @@ class LeaderElection extends Daemon {
}
private void initExecutor() {
- Preconditions.assertTrue(!others.isEmpty());
+ RaftUtils.assertTrue(!others.isEmpty());
executor = Executors.newFixedThreadPool(others.size(), Daemon::new);
service = new ExecutorCompletionService<>(executor);
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderState.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderState.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderState.java
index 22da9ac..f6c9ade 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderState.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/LeaderState.java
@@ -181,7 +181,7 @@ public class LeaderState {
* Start bootstrapping new peers
*/
PendingRequest startSetConfiguration(SetConfigurationRequest request) {
- Preconditions.assertTrue(running && !inStagingState());
+ RaftUtils.assertTrue(running && !inStagingState());
RaftPeer[] peersInNewConf = request.getPeersInNewConf();
Collection<RaftPeer> peersToBootStrap = RaftConfiguration
@@ -247,7 +247,7 @@ public class LeaderState {
* Update the RpcSender list based on the current configuration
*/
private void updateSenders(RaftConfiguration conf) {
- Preconditions.assertTrue(conf.isStable() && !inStagingState());
+ RaftUtils.assertTrue(conf.isStable() && !inStagingState());
Iterator<LogAppender> iterator = senders.iterator();
while (iterator.hasNext()) {
LogAppender sender = iterator.next();
@@ -313,7 +313,7 @@ public class LeaderState {
LOG.warn("Failed to persist new votedFor/term.", e);
// the failure should happen while changing the state to follower
// thus the in-memory state should have been updated
- Preconditions.assertTrue(!running);
+ RaftUtils.assertTrue(!running);
}
}
}
@@ -347,7 +347,7 @@ public class LeaderState {
*/
private BootStrapProgress checkProgress(FollowerInfo follower,
long committed) {
- Preconditions.assertTrue(!follower.isAttendingVote());
+ RaftUtils.assertTrue(!follower.isAttendingVote());
final Timestamp progressTime = new Timestamp().addTimeMs(-server.getMaxTimeoutMs());
final Timestamp timeoutTime = new Timestamp().addTimeMs(-3*server.getMaxTimeoutMs());
if (follower.getLastRpcResponseTime().compareTo(timeoutTime) < 0) {
@@ -363,7 +363,7 @@ public class LeaderState {
}
private Collection<BootStrapProgress> checkAllProgress(long committed) {
- Preconditions.assertTrue(inStagingState());
+ RaftUtils.assertTrue(inStagingState());
return senders.stream()
.filter(sender -> !sender.getFollower().isAttendingVote())
.map(sender -> checkProgress(sender.getFollower(), committed))
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/impl/LogAppender.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/LogAppender.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/LogAppender.java
index 5417e92..4ae4726 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/LogAppender.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/LogAppender.java
@@ -27,9 +27,8 @@ import org.apache.ratis.shaded.com.google.protobuf.ByteString;
import org.apache.ratis.shaded.proto.RaftProtos.*;
import org.apache.ratis.statemachine.SnapshotInfo;
import org.apache.ratis.util.Daemon;
-import org.apache.ratis.util.IOUtils;
-import org.apache.ratis.util.Preconditions;
import org.apache.ratis.util.ProtoUtils;
+import org.apache.ratis.util.RaftUtils;
import org.apache.ratis.util.Timestamp;
import org.slf4j.Logger;
@@ -142,7 +141,7 @@ public class LogAppender extends Daemon {
if (previous == null) {
// if previous is null, nextIndex must be equal to the log start
// index (otherwise we will install snapshot).
- Preconditions.assertTrue(follower.getNextIndex() == raftLog.getStartIndex(),
+ RaftUtils.assertTrue(follower.getNextIndex() == raftLog.getStartIndex(),
"follower's next index %s, local log start index %s",
follower.getNextIndex(), raftLog.getStartIndex());
SnapshotInfo snapshot = server.getState().getLatestSnapshot();
@@ -313,7 +312,7 @@ public class LogAppender extends Daemon {
throws IOException {
FileChunkProto.Builder builder = FileChunkProto.newBuilder()
.setOffset(offset).setChunkIndex(chunkIndex);
- IOUtils.readFully(in, buf, 0, length);
+ RaftUtils.readFully(in, buf, 0, length);
Path relativePath = server.getState().getStorage().getStorageDir()
.relativizeToRoot(fileInfo.getPath());
builder.setFilename(relativePath.toString());
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/impl/PeerConfiguration.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/PeerConfiguration.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/PeerConfiguration.java
index 82f546b..704a7d2 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/PeerConfiguration.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/PeerConfiguration.java
@@ -21,7 +21,7 @@ import java.util.*;
import org.apache.ratis.protocol.RaftPeer;
import org.apache.ratis.protocol.RaftPeerId;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
/**
* The peer configuration of a raft cluster.
@@ -38,7 +38,7 @@ class PeerConfiguration {
map.put(p.getId(), p);
}
this.peers = Collections.unmodifiableMap(map);
- Preconditions.assertTrue(!this.peers.isEmpty());
+ RaftUtils.assertTrue(!this.peers.isEmpty());
}
Collection<RaftPeer> getPeers() {
@@ -73,7 +73,7 @@ class PeerConfiguration {
}
boolean hasMajority(Collection<RaftPeerId> others, RaftPeerId selfId) {
- Preconditions.assertTrue(!others.contains(selfId));
+ RaftUtils.assertTrue(!others.contains(selfId));
int num = 0;
if (contains(selfId)) {
num++;
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/impl/PendingRequest.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/PendingRequest.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/PendingRequest.java
index 5a99dcc..f5581b9 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/PendingRequest.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/PendingRequest.java
@@ -22,7 +22,7 @@ import org.apache.ratis.protocol.RaftClientReply;
import org.apache.ratis.protocol.RaftClientRequest;
import org.apache.ratis.protocol.SetConfigurationRequest;
import org.apache.ratis.statemachine.TransactionContext;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.util.concurrent.CompletableFuture;
@@ -61,12 +61,12 @@ public class PendingRequest implements Comparable<PendingRequest> {
}
synchronized void setException(Throwable e) {
- Preconditions.assertTrue(e != null);
+ RaftUtils.assertTrue(e != null);
future.completeExceptionally(e);
}
synchronized void setReply(RaftClientReply r) {
- Preconditions.assertTrue(r != null);
+ RaftUtils.assertTrue(r != null);
future.complete(r);
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/impl/PendingRequests.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/PendingRequests.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/PendingRequests.java
index 6200604..d4b74f2 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/PendingRequests.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/PendingRequests.java
@@ -19,7 +19,7 @@ package org.apache.ratis.server.impl;
import org.apache.ratis.protocol.*;
import org.apache.ratis.statemachine.TransactionContext;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import java.io.IOException;
@@ -44,8 +44,8 @@ class PendingRequests {
PendingRequest addPendingRequest(long index, RaftClientRequest request,
TransactionContext entry) {
// externally synced for now
- Preconditions.assertTrue(!request.isReadOnly());
- Preconditions.assertTrue(last == null || index == last.getIndex() + 1);
+ RaftUtils.assertTrue(!request.isReadOnly());
+ RaftUtils.assertTrue(last == null || index == last.getIndex() + 1);
return add(index, request, entry);
}
@@ -58,7 +58,7 @@ class PendingRequests {
}
PendingRequest addConfRequest(SetConfigurationRequest request) {
- Preconditions.assertTrue(pendingSetConf == null);
+ RaftUtils.assertTrue(pendingSetConf == null);
pendingSetConf = new PendingRequest(request);
return pendingSetConf;
}
@@ -76,7 +76,7 @@ class PendingRequests {
}
void failSetConfiguration(RaftException e) {
- Preconditions.assertTrue(pendingSetConf != null);
+ RaftUtils.assertTrue(pendingSetConf != null);
pendingSetConf.setException(e);
pendingSetConf = null;
}
@@ -92,7 +92,7 @@ class PendingRequests {
CompletableFuture<Message> stateMachineFuture) {
final PendingRequest pending = pendingRequests.get(index);
if (pending != null) {
- Preconditions.assertTrue(pending.getIndex() == index);
+ RaftUtils.assertTrue(pending.getIndex() == index);
stateMachineFuture.whenComplete((reply, exception) -> {
if (exception == null) {
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftConfiguration.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftConfiguration.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftConfiguration.java
index 6ce7ecd..a70abf9 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftConfiguration.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftConfiguration.java
@@ -19,7 +19,7 @@ package org.apache.ratis.server.impl;
import org.apache.ratis.protocol.RaftPeer;
import org.apache.ratis.protocol.RaftPeerId;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
@@ -51,7 +51,7 @@ public class RaftConfiguration {
public Builder setConf(PeerConfiguration conf) {
Objects.requireNonNull(conf);
- Preconditions.assertTrue(this.conf == null, "conf is already set.");
+ RaftUtils.assertTrue(this.conf == null, "conf is already set.");
this.conf = conf;
return this;
}
@@ -66,9 +66,9 @@ public class RaftConfiguration {
Builder setConf(RaftConfiguration transitionalConf) {
Objects.requireNonNull(transitionalConf);
- Preconditions.assertTrue(transitionalConf.isTransitional());
+ RaftUtils.assertTrue(transitionalConf.isTransitional());
- Preconditions.assertTrue(!forceTransitional);
+ RaftUtils.assertTrue(!forceTransitional);
forceStable = true;
return setConf(transitionalConf.conf);
}
@@ -76,7 +76,7 @@ public class RaftConfiguration {
public Builder setOldConf(PeerConfiguration oldConf) {
Objects.requireNonNull(oldConf);
- Preconditions.assertTrue(this.oldConf == null, "oldConf is already set.");
+ RaftUtils.assertTrue(this.oldConf == null, "oldConf is already set.");
this.oldConf = oldConf;
return this;
}
@@ -91,17 +91,17 @@ public class RaftConfiguration {
Builder setOldConf(RaftConfiguration stableConf) {
Objects.requireNonNull(stableConf);
- Preconditions.assertTrue(stableConf.isStable());
+ RaftUtils.assertTrue(stableConf.isStable());
- Preconditions.assertTrue(!forceStable);
+ RaftUtils.assertTrue(!forceStable);
forceTransitional = true;
return setOldConf(stableConf.conf);
}
public Builder setLogEntryIndex(long logEntryIndex) {
- Preconditions.assertTrue(
+ RaftUtils.assertTrue(
logEntryIndex != RaftServerConstants.INVALID_LOG_INDEX);
- Preconditions.assertTrue(
+ RaftUtils.assertTrue(
this.logEntryIndex == RaftServerConstants.INVALID_LOG_INDEX,
"logEntryIndex is already set.");
this.logEntryIndex = logEntryIndex;
@@ -111,10 +111,10 @@ public class RaftConfiguration {
/** Build a {@link RaftConfiguration}. */
public RaftConfiguration build() {
if (forceTransitional) {
- Preconditions.assertTrue(oldConf != null);
+ RaftUtils.assertTrue(oldConf != null);
}
if (forceStable) {
- Preconditions.assertTrue(oldConf == null);
+ RaftUtils.assertTrue(oldConf == null);
}
return new RaftConfiguration(conf, oldConf, logEntryIndex);
}
@@ -204,7 +204,7 @@ public class RaftConfiguration {
/** @return true if the self id together with the others are in the majority. */
boolean hasMajority(Collection<RaftPeerId> others, RaftPeerId selfId) {
- Preconditions.assertTrue(!others.contains(selfId));
+ RaftUtils.assertTrue(!others.contains(selfId));
return conf.hasMajority(others, selfId) &&
(oldConf == null || oldConf.hasMajority(others, selfId));
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
index 5c42cf4..082c1bf 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/RaftServerImpl.java
@@ -32,10 +32,9 @@ import org.apache.ratis.statemachine.SnapshotInfo;
import org.apache.ratis.statemachine.StateMachine;
import org.apache.ratis.statemachine.TransactionContext;
import org.apache.ratis.util.CodeInjectionForTesting;
-import org.apache.ratis.util.IOUtils;
import org.apache.ratis.util.LifeCycle;
-import org.apache.ratis.util.Preconditions;
import org.apache.ratis.util.ProtoUtils;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -95,7 +94,7 @@ public class RaftServerImpl implements RaftServer {
this.lifeCycle = new LifeCycle(id);
minTimeoutMs = RaftServerConfigKeys.Rpc.timeoutMin(properties).toInt(TimeUnit.MILLISECONDS);
maxTimeoutMs = RaftServerConfigKeys.Rpc.timeoutMax(properties).toInt(TimeUnit.MILLISECONDS);
- Preconditions.assertTrue(maxTimeoutMs > minTimeoutMs,
+ RaftUtils.assertTrue(maxTimeoutMs > minTimeoutMs,
"max timeout: %s, min timeout: %s", maxTimeoutMs, minTimeoutMs);
this.properties = properties;
this.stateMachine = stateMachine;
@@ -287,7 +286,7 @@ public class RaftServerImpl implements RaftServer {
}
synchronized void changeToLeader() {
- Preconditions.assertTrue(isCandidate());
+ RaftUtils.assertTrue(isCandidate());
shutdownElectionDaemon();
role = Role.LEADER;
state.becomeLeader();
@@ -306,7 +305,7 @@ public class RaftServerImpl implements RaftServer {
}
synchronized void changeToCandidate() {
- Preconditions.assertTrue(isFollower());
+ RaftUtils.assertTrue(isFollower());
shutdownHeartbeatMonitor();
role = Role.CANDIDATE;
// start election
@@ -411,7 +410,7 @@ public class RaftServerImpl implements RaftServer {
// state machine. We should call cancelTransaction() for failed requests
TransactionContext entry = stateMachine.startTransaction(request);
if (entry.getException().isPresent()) {
- throw IOUtils.asIOException(entry.getException().get());
+ throw RaftUtils.asIOException(entry.getException().get());
}
return appendTransaction(request, entry);
@@ -431,7 +430,7 @@ public class RaftServerImpl implements RaftServer {
} catch (InterruptedException e) {
final String s = id + ": Interrupted when waiting for reply, request=" + request;
LOG.info(s, e);
- throw IOUtils.toInterruptedIOException(s, e);
+ throw RaftUtils.toInterruptedIOException(s, e);
} catch (ExecutionException e) {
final Throwable cause = e.getCause();
if (cause == null) {
@@ -441,7 +440,7 @@ public class RaftServerImpl implements RaftServer {
cause instanceof StateMachineException) {
return new RaftClientReply(request, (RaftException) cause);
} else {
- throw IOUtils.asIOException(cause);
+ throw RaftUtils.asIOException(cause);
}
}
}
@@ -575,23 +574,23 @@ public class RaftServerImpl implements RaftServer {
final long index0 = entries[0].getIndex();
if (previous == null || previous.getTerm() == 0) {
- Preconditions.assertTrue(index0 == 0,
+ RaftUtils.assertTrue(index0 == 0,
"Unexpected Index: previous is null but entries[%s].getIndex()=%s",
0, index0);
} else {
- Preconditions.assertTrue(previous.getIndex() == index0 - 1,
+ RaftUtils.assertTrue(previous.getIndex() == index0 - 1,
"Unexpected Index: previous is %s but entries[%s].getIndex()=%s",
previous, 0, index0);
}
for (int i = 0; i < entries.length; i++) {
final long t = entries[i].getTerm();
- Preconditions.assertTrue(expectedTerm >= t,
+ RaftUtils.assertTrue(expectedTerm >= t,
"Unexpected Term: entries[%s].getTerm()=%s but expectedTerm=%s",
i, t, expectedTerm);
final long indexi = entries[i].getIndex();
- Preconditions.assertTrue(indexi == index0 + i,
+ RaftUtils.assertTrue(indexi == index0 + i,
"Unexpected Index: entries[%s].getIndex()=%s but entries[0].getIndex()=%s",
i, indexi, index0);
}
@@ -744,7 +743,7 @@ public class RaftServerImpl implements RaftServer {
// Check and append the snapshot chunk. We simply put this in lock
// considering a follower peer requiring a snapshot installation does not
// have a lot of requests
- Preconditions.assertTrue(
+ RaftUtils.assertTrue(
state.getLog().getNextIndex() <= lastIncludedIndex,
"%s log's next id is %s, last included index in snapshot is %s",
getId(), state.getLog().getNextIndex(), lastIncludedIndex);
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/impl/ServerState.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/ServerState.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/ServerState.java
index be14f71..5cd0ee9 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/ServerState.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/ServerState.java
@@ -28,8 +28,8 @@ import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
import org.apache.ratis.statemachine.SnapshotInfo;
import org.apache.ratis.statemachine.StateMachine;
import org.apache.ratis.statemachine.TransactionContext;
-import org.apache.ratis.util.Preconditions;
import org.apache.ratis.util.ProtoUtils;
+import org.apache.ratis.util.RaftUtils;
import java.io.Closeable;
import java.io.IOException;
@@ -214,7 +214,7 @@ public class ServerState implements Closeable {
// leader and term later
return true;
}
- Preconditions.assertTrue(this.leaderId.equals(leaderId),
+ RaftUtils.assertTrue(this.leaderId.equals(leaderId),
"selfId:%s, this.leaderId:%s, received leaderId:%s",
selfId, this.leaderId, leaderId);
return true;
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/impl/StateMachineUpdater.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/impl/StateMachineUpdater.java b/ratis-server/src/main/java/org/apache/ratis/server/impl/StateMachineUpdater.java
index 5a94303..b4fc705 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/impl/StateMachineUpdater.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/impl/StateMachineUpdater.java
@@ -35,7 +35,7 @@ import org.apache.ratis.statemachine.TransactionContext;
import org.apache.ratis.util.Daemon;
import org.apache.ratis.util.ExitUtils;
import org.apache.ratis.util.LifeCycle;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -126,15 +126,15 @@ class StateMachineUpdater implements Runnable {
}
final long committedIndex = raftLog.getLastCommittedIndex();
- Preconditions.assertTrue(lastAppliedIndex < committedIndex);
+ RaftUtils.assertTrue(lastAppliedIndex < committedIndex);
if (state == State.RELOAD) {
- Preconditions.assertTrue(stateMachine.getLifeCycleState() == LifeCycle.State.PAUSED);
+ RaftUtils.assertTrue(stateMachine.getLifeCycleState() == LifeCycle.State.PAUSED);
stateMachine.reinitialize(server.getId(), properties, storage);
SnapshotInfo snapshot = stateMachine.getLatestSnapshot();
- Preconditions.assertTrue(snapshot != null && snapshot.getIndex() > lastAppliedIndex,
+ RaftUtils.assertTrue(snapshot != null && snapshot.getIndex() > lastAppliedIndex,
"Snapshot: %s, lastAppliedIndex: %s", snapshot, lastAppliedIndex);
lastAppliedIndex = snapshot.getIndex();
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/LogInputStream.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/LogInputStream.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/LogInputStream.java
index 0edea13..4a36430 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/LogInputStream.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/LogInputStream.java
@@ -25,8 +25,7 @@ import java.io.File;
import java.io.IOException;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
-import org.apache.ratis.util.IOUtils;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -73,9 +72,9 @@ public class LogInputStream implements Closeable {
public LogInputStream(File log, long startIndex, long endIndex,
boolean isOpen) {
if (isOpen) {
- Preconditions.assertTrue(endIndex == INVALID_LOG_INDEX);
+ RaftUtils.assertTrue(endIndex == INVALID_LOG_INDEX);
} else {
- Preconditions.assertTrue(endIndex >= startIndex);
+ RaftUtils.assertTrue(endIndex >= startIndex);
}
this.logFile = log;
@@ -85,12 +84,12 @@ public class LogInputStream implements Closeable {
}
private void init() throws IOException {
- Preconditions.assertTrue(state == State.UNINIT);
+ RaftUtils.assertTrue(state == State.UNINIT);
try {
reader = new LogReader(logFile);
// read the log header
String header = reader.readLogHeader();
- Preconditions.assertTrue(SegmentedRaftLog.HEADER_STR.equals(header),
+ RaftUtils.assertTrue(SegmentedRaftLog.HEADER_STR.equals(header),
"Corrupted log header: %s", header);
state = State.OPEN;
} finally {
@@ -120,9 +119,9 @@ public class LogInputStream implements Closeable {
init();
} catch (Throwable e) {
LOG.error("caught exception initializing " + this, e);
- throw IOUtils.asIOException(e);
+ throw RaftUtils.asIOException(e);
}
- Preconditions.assertTrue(state != State.UNINIT);
+ RaftUtils.assertTrue(state != State.UNINIT);
return nextEntry();
case OPEN:
entry = reader.readEntry();
@@ -150,7 +149,7 @@ public class LogInputStream implements Closeable {
}
long scanNextEntry() throws IOException {
- Preconditions.assertTrue(state == State.OPEN);
+ RaftUtils.assertTrue(state == State.OPEN);
return reader.scanEntry();
}
@@ -203,7 +202,7 @@ public class LogInputStream implements Closeable {
try {
return scanEditLog(in, maxTxIdToScan);
} finally {
- IOUtils.cleanup(LOG, in);
+ RaftUtils.cleanup(LOG, in);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/LogOutputStream.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/LogOutputStream.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/LogOutputStream.java
index db0789e..8563549 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/LogOutputStream.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/LogOutputStream.java
@@ -22,8 +22,8 @@ import org.apache.ratis.server.RaftServerConfigKeys;
import org.apache.ratis.server.impl.RaftServerConstants;
import org.apache.ratis.shaded.com.google.protobuf.CodedOutputStream;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
-import org.apache.ratis.util.IOUtils;
import org.apache.ratis.util.PureJavaCrc32C;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -126,7 +126,7 @@ public class LogOutputStream implements Closeable {
fc.truncate(fc.position());
}
} finally {
- IOUtils.cleanup(LOG, fc, out);
+ RaftUtils.cleanup(LOG, fc, out);
fc = null;
out = null;
}
@@ -151,7 +151,7 @@ public class LogOutputStream implements Closeable {
int size = (int) Math.min(BUFFER_SIZE, targetSize - allocated);
ByteBuffer buffer = fill.slice();
buffer.limit(size);
- IOUtils.writeFully(fc, buffer, preallocatedPos);
+ RaftUtils.writeFully(fc, buffer, preallocatedPos);
preallocatedPos += size;
allocated += size;
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/LogReader.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/LogReader.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/LogReader.java
index 48a00e1..829bd3a 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/LogReader.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/LogReader.java
@@ -22,9 +22,8 @@ import org.apache.ratis.server.impl.RaftServerConstants;
import org.apache.ratis.shaded.com.google.protobuf.CodedInputStream;
import org.apache.ratis.shaded.com.google.protobuf.CodedOutputStream;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
-import org.apache.ratis.util.IOUtils;
-import org.apache.ratis.util.Preconditions;
import org.apache.ratis.util.PureJavaCrc32C;
+import org.apache.ratis.util.RaftUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
@@ -197,9 +196,9 @@ public class LogReader implements Closeable {
// want to reposition the mark one byte before the error
if (numRead != -1) {
in.reset();
- IOUtils.skipFully(in, idx);
+ RaftUtils.skipFully(in, idx);
in.mark(temp.length + 1);
- IOUtils.skipFully(in, 1);
+ RaftUtils.skipFully(in, 1);
}
}
}
@@ -247,7 +246,7 @@ public class LogReader implements Closeable {
checkBufferSize(totalLength);
in.reset();
in.mark(maxOpSize);
- IOUtils.readFully(in, temp, 0, totalLength);
+ RaftUtils.readFully(in, temp, 0, totalLength);
// verify checksum
checksum.reset();
@@ -266,7 +265,7 @@ public class LogReader implements Closeable {
}
private void checkBufferSize(int entryLength) {
- Preconditions.assertTrue(entryLength <= maxOpSize);
+ RaftUtils.assertTrue(entryLength <= maxOpSize);
int length = temp.length;
if (length < entryLength) {
while (length < entryLength) {
@@ -282,11 +281,11 @@ public class LogReader implements Closeable {
void skipFully(long length) throws IOException {
limiter.clearLimit();
- IOUtils.skipFully(limiter, length);
+ RaftUtils.skipFully(limiter, length);
}
@Override
public void close() throws IOException {
- IOUtils.cleanup(null, in);
+ RaftUtils.cleanup(null, in);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/LogSegment.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/LogSegment.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/LogSegment.java
index 46f9f4f..89c0ff5 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/LogSegment.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/LogSegment.java
@@ -22,7 +22,7 @@ import org.apache.ratis.server.impl.ServerProtoUtils;
import org.apache.ratis.shaded.com.google.protobuf.CodedOutputStream;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
import org.apache.ratis.util.FileUtils;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.io.File;
import java.io.IOException;
@@ -85,12 +85,12 @@ class LogSegment implements Comparable<Long> {
}
static LogSegment newOpenSegment(long start) {
- Preconditions.assertTrue(start >= 0);
+ RaftUtils.assertTrue(start >= 0);
return new LogSegment(true, start, start - 1);
}
private static LogSegment newCloseSegment(long start, long end) {
- Preconditions.assertTrue(start >= 0 && end >= start);
+ RaftUtils.assertTrue(start >= 0 && end >= start);
return new LogSegment(false, start, end);
}
@@ -104,7 +104,7 @@ class LogSegment implements Comparable<Long> {
LogEntryProto prev = null;
while ((next = in.nextEntry()) != null) {
if (prev != null) {
- Preconditions.assertTrue(next.getIndex() == prev.getIndex() + 1,
+ RaftUtils.assertTrue(next.getIndex() == prev.getIndex() + 1,
"gap between entry %s and entry %s", prev, next);
}
segment.append(next);
@@ -123,9 +123,9 @@ class LogSegment implements Comparable<Long> {
FileUtils.truncateFile(file, segment.getTotalSize());
}
- Preconditions.assertTrue(start == segment.records.get(0).entry.getIndex());
+ RaftUtils.assertTrue(start == segment.records.get(0).entry.getIndex());
if (!isOpen) {
- Preconditions.assertTrue(segment.getEndIndex() == end);
+ RaftUtils.assertTrue(segment.getEndIndex() == end);
}
return segment;
}
@@ -147,26 +147,26 @@ class LogSegment implements Comparable<Long> {
}
void appendToOpenSegment(LogEntryProto... entries) {
- Preconditions.assertTrue(isOpen(),
+ RaftUtils.assertTrue(isOpen(),
"The log segment %s is not open for append", this.toString());
append(entries);
}
private void append(LogEntryProto... entries) {
- Preconditions.assertTrue(entries != null && entries.length > 0);
+ RaftUtils.assertTrue(entries != null && entries.length > 0);
final long term = entries[0].getTerm();
if (records.isEmpty()) {
- Preconditions.assertTrue(entries[0].getIndex() == startIndex,
+ RaftUtils.assertTrue(entries[0].getIndex() == startIndex,
"gap between start index %s and first entry to append %s",
startIndex, entries[0].getIndex());
}
for (LogEntryProto entry : entries) {
// all these entries should be of the same term
- Preconditions.assertTrue(entry.getTerm() == term,
+ RaftUtils.assertTrue(entry.getTerm() == term,
"expected term:%s, term of the entry:%s", term, entry.getTerm());
final LogRecord currentLast = getLastRecord();
if (currentLast != null) {
- Preconditions.assertTrue(
+ RaftUtils.assertTrue(
entry.getIndex() == currentLast.entry.getIndex() + 1,
"gap between entries %s and %s", entry.getIndex(),
currentLast.entry.getIndex());
@@ -198,7 +198,7 @@ class LogSegment implements Comparable<Long> {
* Remove records from the given index (inclusive)
*/
void truncate(long fromIndex) {
- Preconditions.assertTrue(fromIndex >= startIndex && fromIndex <= endIndex);
+ RaftUtils.assertTrue(fromIndex >= startIndex && fromIndex <= endIndex);
LogRecord record = records.get((int) (fromIndex - startIndex));
for (long index = endIndex; index >= fromIndex; index--) {
records.remove((int)(index - startIndex));
@@ -209,7 +209,7 @@ class LogSegment implements Comparable<Long> {
}
void close() {
- Preconditions.assertTrue(isOpen());
+ RaftUtils.assertTrue(isOpen());
isOpen = false;
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/MemoryRaftLog.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/MemoryRaftLog.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/MemoryRaftLog.java
index a49db9a..17914cd 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/MemoryRaftLog.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/MemoryRaftLog.java
@@ -27,7 +27,7 @@ import org.apache.ratis.server.impl.ServerProtoUtils;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
import org.apache.ratis.util.AutoCloseableLock;
import org.apache.ratis.util.CodeInjectionForTesting;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
/**
* A simple RaftLog implementation in memory. Used only for testing.
@@ -65,7 +65,7 @@ public class MemoryRaftLog extends RaftLog {
void truncate(long index) {
checkLogState();
try(AutoCloseableLock writeLock = writeLock()) {
- Preconditions.assertTrue(index >= 0);
+ RaftUtils.assertTrue(index >= 0);
final int truncateIndex = (int) index;
for (int i = entries.size() - 1; i >= truncateIndex; i--) {
entries.remove(i);
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/MetaFile.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/MetaFile.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/MetaFile.java
index 0e4ccbd..ff010e1 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/MetaFile.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/MetaFile.java
@@ -18,7 +18,7 @@
package org.apache.ratis.server.storage;
import org.apache.ratis.util.AtomicFileOutputStream;
-import org.apache.ratis.util.IOUtils;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -123,7 +123,7 @@ class MetaFile {
LOG.warn("Cannot load term/votedFor properties from {}", file, e);
throw e;
} finally {
- IOUtils.cleanup(LOG, br);
+ RaftUtils.cleanup(LOG, br);
}
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLog.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLog.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLog.java
index 40e3b34..243da73 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLog.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLog.java
@@ -32,8 +32,8 @@ import org.apache.ratis.server.protocol.TermIndex;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
import org.apache.ratis.statemachine.TransactionContext;
import org.apache.ratis.util.AutoCloseableLock;
-import org.apache.ratis.util.Preconditions;
import org.apache.ratis.util.ProtoUtils;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -70,7 +70,7 @@ public abstract class RaftLog implements Closeable {
}
public void checkLogState() {
- Preconditions.assertTrue(isOpen,
+ RaftUtils.assertTrue(isOpen,
"The RaftLog has not been opened or has been closed");
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLogCache.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLogCache.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLogCache.java
index 0a21846..2b9972c 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLogCache.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLogCache.java
@@ -30,7 +30,7 @@ import org.apache.ratis.server.storage.LogSegment.LogRecord;
import org.apache.ratis.server.storage.LogSegment.SegmentFileInfo;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
/**
* In-memory RaftLog Cache. Currently we provide a simple implementation that
@@ -57,10 +57,10 @@ class RaftLogCache {
private void validateAdding(LogSegment segment) {
final LogSegment lastClosed = getLastClosedSegment();
if (!segment.isOpen()) {
- Preconditions.assertTrue(lastClosed == null ||
+ RaftUtils.assertTrue(lastClosed == null ||
areConsecutiveSegments(lastClosed, segment));
} else {
- Preconditions.assertTrue(openSegment == null &&
+ RaftUtils.assertTrue(openSegment == null &&
(lastClosed == null || areConsecutiveSegments(lastClosed, segment)));
}
}
@@ -168,7 +168,7 @@ class RaftLogCache {
void appendEntry(LogEntryProto entry) {
// SegmentedRaftLog does the segment creation/rolling work. Here we just
// simply append the entry into the open segment.
- Preconditions.assertTrue(openSegment != null);
+ RaftUtils.assertTrue(openSegment != null);
openSegment.appendToOpenSegment(entry);
}
@@ -176,7 +176,7 @@ class RaftLogCache {
* finalize the current open segment, and start a new open segment
*/
void rollOpenSegment(boolean createNewOpen) {
- Preconditions.assertTrue(openSegment != null
+ RaftUtils.assertTrue(openSegment != null
&& openSegment.numOfEntries() > 0);
final long nextIndex = openSegment.getEndIndex() + 1;
openSegment.close();
@@ -211,7 +211,7 @@ class RaftLogCache {
Collections.singletonList(deleteOpenSegment()));
} else {
openSegment.truncate(index);
- Preconditions.assertTrue(!openSegment.isOpen());
+ RaftUtils.assertTrue(!openSegment.isOpen());
SegmentFileInfo info = new SegmentFileInfo(openSegment.getStartIndex(),
oldEnd, true, openSegment.getTotalSize(),
openSegment.getEndIndex());
@@ -280,7 +280,7 @@ class RaftLogCache {
// the start index is smaller than the first closed segment's start
// index. We no longer keep the log entry (because of the snapshot) or
// the start index is invalid.
- Preconditions.assertTrue(segmentIndex == 0);
+ RaftUtils.assertTrue(segmentIndex == 0);
throw new IndexOutOfBoundsException();
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLogWorker.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLogWorker.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLogWorker.java
index 5add8ae..d0fc3ce 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLogWorker.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftLogWorker.java
@@ -34,8 +34,7 @@ import org.apache.ratis.server.storage.SegmentedRaftLog.Task;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
import org.apache.ratis.util.ExitUtils;
import org.apache.ratis.util.FileUtils;
-import org.apache.ratis.util.IOUtils;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -84,7 +83,7 @@ class RaftLogWorker implements Runnable {
lastWrittenIndex = latestIndex;
flushedIndex = latestIndex;
if (openSegmentFile != null) {
- Preconditions.assertTrue(openSegmentFile.exists());
+ RaftUtils.assertTrue(openSegmentFile.exists());
out = new LogOutputStream(openSegmentFile, true, properties);
}
workerThread.start();
@@ -123,7 +122,7 @@ class RaftLogWorker implements Runnable {
LOG.debug("add task {}", task);
try {
if (!queue.offer(task, 1, TimeUnit.SECONDS)) {
- Preconditions.assertTrue(isAlive(),
+ RaftUtils.assertTrue(isAlive(),
"the worker thread is not alive");
queue.put(task);
}
@@ -226,8 +225,8 @@ class RaftLogWorker implements Runnable {
@Override
public void execute() throws IOException {
- Preconditions.assertTrue(out != null);
- Preconditions.assertTrue(lastWrittenIndex + 1 == entry.getIndex(),
+ RaftUtils.assertTrue(out != null);
+ RaftUtils.assertTrue(lastWrittenIndex + 1 == entry.getIndex(),
"lastWrittenIndex == %s, entry == %s", lastWrittenIndex, entry);
out.write(entry);
lastWrittenIndex = entry.getIndex();
@@ -252,19 +251,19 @@ class RaftLogWorker implements Runnable {
@Override
public void execute() throws IOException {
- IOUtils.cleanup(null, out);
+ RaftUtils.cleanup(null, out);
out = null;
- Preconditions.assertTrue(segmentToClose != null);
+ RaftUtils.assertTrue(segmentToClose != null);
File openFile = storage.getStorageDir()
.getOpenLogFile(segmentToClose.getStartIndex());
- Preconditions.assertTrue(openFile.exists(),
+ RaftUtils.assertTrue(openFile.exists(),
"File %s does not exist.", openFile);
if (segmentToClose.numOfEntries() > 0) {
// finalize the current open segment
File dstFile = storage.getStorageDir().getClosedLogFile(
segmentToClose.getStartIndex(), segmentToClose.getEndIndex());
- Preconditions.assertTrue(!dstFile.exists());
+ RaftUtils.assertTrue(!dstFile.exists());
NativeIO.renameTo(openFile, dstFile);
} else { // delete the file of the empty segment
@@ -289,9 +288,9 @@ class RaftLogWorker implements Runnable {
@Override
void execute() throws IOException {
File openFile = storage.getStorageDir().getOpenLogFile(newStartIndex);
- Preconditions.assertTrue(!openFile.exists(), "open file %s exists for %s",
+ RaftUtils.assertTrue(!openFile.exists(), "open file %s exists for %s",
openFile.getAbsolutePath(), RaftLogWorker.this.toString());
- Preconditions.assertTrue(out == null && pendingFlushNum == 0);
+ RaftUtils.assertTrue(out == null && pendingFlushNum == 0);
out = new LogOutputStream(openFile, false, properties);
}
@@ -310,7 +309,7 @@ class RaftLogWorker implements Runnable {
@Override
void execute() throws IOException {
- IOUtils.cleanup(null, out);
+ RaftUtils.cleanup(null, out);
out = null;
if (segments.toTruncate != null) {
File fileToTruncate = segments.toTruncate.isOpen ?
@@ -324,7 +323,7 @@ class RaftLogWorker implements Runnable {
// rename the file
File dstFile = storage.getStorageDir().getClosedLogFile(
segments.toTruncate.startIndex, segments.toTruncate.newEndIndex);
- Preconditions.assertTrue(!dstFile.exists());
+ RaftUtils.assertTrue(!dstFile.exists());
NativeIO.renameTo(fileToTruncate, dstFile);
// update lastWrittenIndex
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftStorage.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftStorage.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftStorage.java
index db8a196..a7bc47c 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftStorage.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/RaftStorage.java
@@ -24,7 +24,7 @@ import org.apache.ratis.server.storage.RaftStorageDirectory.StorageState;
import org.apache.ratis.statemachine.SnapshotInfo;
import org.apache.ratis.statemachine.StateMachineStorage;
import org.apache.ratis.util.FileUtils;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -54,7 +54,7 @@ public class RaftStorage implements Closeable {
storageDir.lock();
format();
state = storageDir.analyzeStorage(false);
- Preconditions.assertTrue(state == StorageState.NORMAL);
+ RaftUtils.assertTrue(state == StorageState.NORMAL);
} else {
state = analyzeAndRecoverStorage(true); // metaFile is initialized here
if (state != StorageState.NORMAL) {
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/SegmentedRaftLog.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/SegmentedRaftLog.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/SegmentedRaftLog.java
index 2fd4dd2..fc35535 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/SegmentedRaftLog.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/SegmentedRaftLog.java
@@ -27,7 +27,7 @@ import org.apache.ratis.server.storage.RaftStorageDirectory.LogPathAndIndex;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
import org.apache.ratis.util.AutoCloseableLock;
import org.apache.ratis.util.CodeInjectionForTesting;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.io.File;
import java.io.IOException;
@@ -213,7 +213,7 @@ public class SegmentedRaftLog extends RaftLog {
// the term changes
final long currentTerm = currentOpenSegment.getLastRecord().entry
.getTerm();
- Preconditions.assertTrue(currentTerm < entry.getTerm(),
+ RaftUtils.assertTrue(currentTerm < entry.getTerm(),
"open segment's term %s is larger than the new entry's term %s",
currentTerm, entry.getTerm());
cache.rollOpenSegment(true);
@@ -249,7 +249,7 @@ public class SegmentedRaftLog extends RaftLog {
long truncateIndex = -1;
for (; iter.hasNext() && index < entries.length; index++) {
LogEntryProto storedEntry = iter.next();
- Preconditions.assertTrue(
+ RaftUtils.assertTrue(
storedEntry.getIndex() == entries[index].getIndex(),
"The stored entry's index %s is not consistent with" +
" the received entries[%s]'s index %s", storedEntry.getIndex(),
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/main/java/org/apache/ratis/server/storage/SnapshotManager.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/main/java/org/apache/ratis/server/storage/SnapshotManager.java b/ratis-server/src/main/java/org/apache/ratis/server/storage/SnapshotManager.java
index bd25d07..0b4e8fa 100644
--- a/ratis-server/src/main/java/org/apache/ratis/server/storage/SnapshotManager.java
+++ b/ratis-server/src/main/java/org/apache/ratis/server/storage/SnapshotManager.java
@@ -29,9 +29,8 @@ import org.apache.ratis.shaded.proto.RaftProtos.InstallSnapshotRequestProto;
import org.apache.ratis.statemachine.SnapshotInfo;
import org.apache.ratis.statemachine.StateMachine;
import org.apache.ratis.util.FileUtils;
-import org.apache.ratis.util.IOUtils;
import org.apache.ratis.util.MD5FileUtil;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -90,7 +89,7 @@ public class SnapshotManager {
// create the temp snapshot file and put padding inside
out = new FileOutputStream(tmpSnapshotFile);
} else {
- Preconditions.assertTrue(tmpSnapshotFile.exists());
+ RaftUtils.assertTrue(tmpSnapshotFile.exists());
out = new FileOutputStream(tmpSnapshotFile, true);
FileChannel fc = out.getChannel();
fc.position(chunk.getOffset());
@@ -99,7 +98,7 @@ public class SnapshotManager {
// write data to the file
out.write(chunk.getData().toByteArray());
} finally {
- IOUtils.cleanup(null, out);
+ RaftUtils.cleanup(null, out);
}
// rename the temp snapshot file if this is the last chunk. also verify
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/test/java/org/apache/ratis/MiniRaftCluster.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/test/java/org/apache/ratis/MiniRaftCluster.java b/ratis-server/src/test/java/org/apache/ratis/MiniRaftCluster.java
index 8c4a7c6..2a5f314 100644
--- a/ratis-server/src/test/java/org/apache/ratis/MiniRaftCluster.java
+++ b/ratis-server/src/test/java/org/apache/ratis/MiniRaftCluster.java
@@ -17,19 +17,6 @@
*/
package org.apache.ratis;
-import java.io.File;
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-import java.util.stream.StreamSupport;
-
import org.apache.ratis.client.ClientFactory;
import org.apache.ratis.client.RaftClient;
import org.apache.ratis.conf.Parameters;
@@ -38,24 +25,28 @@ import org.apache.ratis.protocol.RaftPeer;
import org.apache.ratis.protocol.RaftPeerId;
import org.apache.ratis.rpc.RpcType;
import org.apache.ratis.server.RaftServerConfigKeys;
-import org.apache.ratis.server.impl.DelayLocalExecutionInjection;
-import org.apache.ratis.server.impl.LeaderState;
-import org.apache.ratis.server.impl.RaftConfiguration;
-import org.apache.ratis.server.impl.RaftServerImpl;
+import org.apache.ratis.server.impl.*;
import org.apache.ratis.server.storage.MemoryRaftLog;
import org.apache.ratis.server.storage.RaftLog;
import org.apache.ratis.statemachine.BaseStateMachine;
import org.apache.ratis.statemachine.StateMachine;
import org.apache.ratis.util.ExitUtils;
import org.apache.ratis.util.FileUtils;
-import org.apache.ratis.util.CollectionUtils;
import org.apache.ratis.util.NetUtils;
-import org.apache.ratis.util.Preconditions;
-import org.apache.ratis.util.ReflectionUtils;
+import org.apache.ratis.util.RaftUtils;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.io.File;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
+
public abstract class MiniRaftCluster {
public static final Logger LOG = LoggerFactory.getLogger(MiniRaftCluster.class);
public static final DelayLocalExecutionInjection logSyncDelay =
@@ -126,7 +117,7 @@ public abstract class MiniRaftCluster {
private static void formatDir(String dirStr) {
final File serverDir = new File(dirStr);
- Preconditions.assertTrue(FileUtils.fullyDelete(serverDir),
+ RaftUtils.assertTrue(FileUtils.fullyDelete(serverDir),
"Failed to format directory %s", dirStr);
LOG.info("Formatted directory {}", dirStr);
}
@@ -161,14 +152,14 @@ public abstract class MiniRaftCluster {
public MiniRaftCluster initServers() {
if (servers.isEmpty()) {
- putNewServers(CollectionUtils.as(conf.getPeers(), RaftPeer::getId), true);
+ putNewServers(RaftUtils.as(conf.getPeers(), RaftPeer::getId), true);
}
return this;
}
private RaftServerImpl putNewServer(RaftPeerId id, boolean format) {
final RaftServerImpl s = newRaftServer(id, format);
- Preconditions.assertTrue(servers.put(id, s) == null);
+ RaftUtils.assertTrue(servers.put(id, s) == null);
return s;
}
@@ -237,7 +228,7 @@ public abstract class MiniRaftCluster {
STATEMACHINE_CLASS_KEY,
STATEMACHINE_CLASS_DEFAULT,
StateMachine.class);
- return ReflectionUtils.newInstance(smClass);
+ return RaftUtils.newInstance(smClass);
}
public static Collection<RaftPeer> toRaftPeers(
@@ -262,7 +253,7 @@ public abstract class MiniRaftCluster {
// create and add new RaftServers
final Collection<RaftServerImpl> newServers = putNewServers(
- CollectionUtils.as(Arrays.asList(ids), RaftPeerId::new), true);
+ RaftUtils.as(Arrays.asList(ids), RaftPeerId::new), true);
newServers.forEach(s -> startServer(s, startNewPeer));
final Collection<RaftPeer> newPeers = toRaftPeers(newServers);
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/test/java/org/apache/ratis/RaftNotLeaderExceptionBaseTest.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/test/java/org/apache/ratis/RaftNotLeaderExceptionBaseTest.java b/ratis-server/src/test/java/org/apache/ratis/RaftNotLeaderExceptionBaseTest.java
index d60f8eb..54cfa4d 100644
--- a/ratis-server/src/test/java/org/apache/ratis/RaftNotLeaderExceptionBaseTest.java
+++ b/ratis-server/src/test/java/org/apache/ratis/RaftNotLeaderExceptionBaseTest.java
@@ -30,7 +30,7 @@ import org.apache.ratis.protocol.RaftPeerId;
import org.apache.ratis.server.impl.RaftServerImpl;
import org.apache.ratis.server.simulation.RequestHandler;
import org.apache.ratis.server.storage.RaftLog;
-import org.apache.ratis.util.LogUtils;
+import org.apache.ratis.util.RaftUtils;
import org.junit.*;
import org.junit.rules.Timeout;
import org.slf4j.Logger;
@@ -44,10 +44,10 @@ import static org.apache.ratis.server.impl.RaftServerConstants.DEFAULT_CALLID;
public abstract class RaftNotLeaderExceptionBaseTest {
static {
- LogUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftLog.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftLog.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
}
public static final Logger LOG =
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/test/java/org/apache/ratis/server/impl/RaftReconfigurationBaseTest.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/test/java/org/apache/ratis/server/impl/RaftReconfigurationBaseTest.java b/ratis-server/src/test/java/org/apache/ratis/server/impl/RaftReconfigurationBaseTest.java
index dc17a43..bf7de9f 100644
--- a/ratis-server/src/test/java/org/apache/ratis/server/impl/RaftReconfigurationBaseTest.java
+++ b/ratis-server/src/test/java/org/apache/ratis/server/impl/RaftReconfigurationBaseTest.java
@@ -29,7 +29,7 @@ import org.apache.ratis.protocol.*;
import org.apache.ratis.server.RaftServerConfigKeys;
import org.apache.ratis.server.simulation.RequestHandler;
import org.apache.ratis.server.storage.RaftLog;
-import org.apache.ratis.util.LogUtils;
+import org.apache.ratis.util.RaftUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -54,9 +54,9 @@ import static org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto.LogEntryBod
public abstract class RaftReconfigurationBaseTest {
static {
- LogUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
}
static final Logger LOG = LoggerFactory.getLogger(RaftReconfigurationBaseTest.class);
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/test/java/org/apache/ratis/server/simulation/SimulatedRequestReply.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/test/java/org/apache/ratis/server/simulation/SimulatedRequestReply.java b/ratis-server/src/test/java/org/apache/ratis/server/simulation/SimulatedRequestReply.java
index 528cc1a..48c9d55 100644
--- a/ratis-server/src/test/java/org/apache/ratis/server/simulation/SimulatedRequestReply.java
+++ b/ratis-server/src/test/java/org/apache/ratis/server/simulation/SimulatedRequestReply.java
@@ -21,8 +21,7 @@ import org.apache.ratis.RaftTestUtil;
import org.apache.ratis.protocol.RaftPeerId;
import org.apache.ratis.protocol.RaftRpcMessage;
import org.apache.ratis.server.RaftServerConfigKeys;
-import org.apache.ratis.util.IOUtils;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import org.apache.ratis.util.Timestamp;
import java.io.IOException;
@@ -44,7 +43,7 @@ class SimulatedRequestReply<REQUEST extends RaftRpcMessage,
private final IOException ioe;
ReplyOrException(REPLY reply, IOException ioe) {
- Preconditions.assertTrue(reply == null ^ ioe == null);
+ RaftUtils.assertTrue(reply == null ^ ioe == null);
this.reply = reply;
this.ioe = ioe;
}
@@ -121,7 +120,7 @@ class SimulatedRequestReply<REQUEST extends RaftRpcMessage,
RaftTestUtil.block(q.blockSendRequestTo::get);
return q.request(request);
} catch (InterruptedException e) {
- throw IOUtils.toInterruptedIOException("", e);
+ throw RaftUtils.toInterruptedIOException("", e);
}
}
@@ -137,7 +136,7 @@ class SimulatedRequestReply<REQUEST extends RaftRpcMessage,
RaftTestUtil.delay(q.delayTakeRequestTo::get);
request = q.takeRequest();
- Preconditions.assertTrue(qid.equals(request.getReplierId()));
+ RaftUtils.assertTrue(qid.equals(request.getReplierId()));
// block request for testing
final EventQueue<REQUEST, REPLY> reqQ = queues.get(request.getRequestorId());
@@ -146,7 +145,7 @@ class SimulatedRequestReply<REQUEST extends RaftRpcMessage,
RaftTestUtil.block(reqQ.blockTakeRequestFrom::get);
}
} catch (InterruptedException e) {
- throw IOUtils.toInterruptedIOException("", e);
+ throw RaftUtils.toInterruptedIOException("", e);
}
return request;
}
@@ -154,9 +153,9 @@ class SimulatedRequestReply<REQUEST extends RaftRpcMessage,
public void sendReply(REQUEST request, REPLY reply, IOException ioe)
throws IOException {
if (reply != null) {
- Preconditions.assertTrue(
+ RaftUtils.assertTrue(
request.getRequestorId().equals(reply.getRequestorId()));
- Preconditions.assertTrue(
+ RaftUtils.assertTrue(
request.getReplierId().equals(reply.getReplierId()));
}
simulateLatency();
@@ -188,7 +187,7 @@ class SimulatedRequestReply<REQUEST extends RaftRpcMessage,
try {
Thread.sleep(randomSleepMs);
} catch (InterruptedException ie) {
- throw IOUtils.toInterruptedIOException("", ie);
+ throw RaftUtils.toInterruptedIOException("", ie);
}
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/test/java/org/apache/ratis/server/simulation/TestRaftWithSimulatedRpc.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/test/java/org/apache/ratis/server/simulation/TestRaftWithSimulatedRpc.java b/ratis-server/src/test/java/org/apache/ratis/server/simulation/TestRaftWithSimulatedRpc.java
index c1136b7..5332064 100644
--- a/ratis-server/src/test/java/org/apache/ratis/server/simulation/TestRaftWithSimulatedRpc.java
+++ b/ratis-server/src/test/java/org/apache/ratis/server/simulation/TestRaftWithSimulatedRpc.java
@@ -20,15 +20,17 @@ package org.apache.ratis.server.simulation;
import org.apache.log4j.Level;
import org.apache.ratis.RaftBasicTests;
import org.apache.ratis.client.RaftClient;
+import org.apache.ratis.conf.RaftProperties;
import org.apache.ratis.server.impl.RaftServerImpl;
-import org.apache.ratis.util.LogUtils;
+import org.apache.ratis.util.RaftUtils;
import java.io.IOException;
+import java.util.concurrent.ThreadLocalRandom;
public class TestRaftWithSimulatedRpc extends RaftBasicTests {
static {
- LogUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
}
private final MiniRaftClusterWithSimulatedRpc cluster;
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/test/java/org/apache/ratis/server/storage/TestSegmentedRaftLog.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/test/java/org/apache/ratis/server/storage/TestSegmentedRaftLog.java b/ratis-server/src/test/java/org/apache/ratis/server/storage/TestSegmentedRaftLog.java
index ccf7690..1fcb54b 100644
--- a/ratis-server/src/test/java/org/apache/ratis/server/storage/TestSegmentedRaftLog.java
+++ b/ratis-server/src/test/java/org/apache/ratis/server/storage/TestSegmentedRaftLog.java
@@ -22,7 +22,6 @@ import org.apache.ratis.MiniRaftCluster;
import org.apache.ratis.RaftTestUtil;
import org.apache.ratis.RaftTestUtil.SimpleOperation;
import org.apache.ratis.conf.RaftProperties;
-import org.apache.ratis.util.LogUtils;
import org.apache.ratis.util.SizeInBytes;
import org.apache.ratis.protocol.ClientId;
import org.apache.ratis.protocol.RaftPeerId;
@@ -33,6 +32,7 @@ import org.apache.ratis.server.impl.RaftServerTestUtil;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
import org.apache.ratis.util.FileUtils;
import org.apache.ratis.util.ProtoUtils;
+import org.apache.ratis.util.RaftUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@@ -48,7 +48,7 @@ import java.util.function.Supplier;
public class TestSegmentedRaftLog {
static {
- LogUtils.setLogLevel(RaftLogWorker.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftLogWorker.LOG, Level.DEBUG);
}
private static final RaftPeerId peerId = new RaftPeerId("s0");
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/test/java/org/apache/ratis/statemachine/RaftSnapshotBaseTest.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/test/java/org/apache/ratis/statemachine/RaftSnapshotBaseTest.java b/ratis-server/src/test/java/org/apache/ratis/statemachine/RaftSnapshotBaseTest.java
index f5e2378..68ab8c3 100644
--- a/ratis-server/src/test/java/org/apache/ratis/statemachine/RaftSnapshotBaseTest.java
+++ b/ratis-server/src/test/java/org/apache/ratis/statemachine/RaftSnapshotBaseTest.java
@@ -36,7 +36,7 @@ import org.apache.ratis.server.storage.RaftStorageDirectory;
import org.apache.ratis.server.storage.RaftStorageDirectory.LogPathAndIndex;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
import org.apache.ratis.util.FileUtils;
-import org.apache.ratis.util.LogUtils;
+import org.apache.ratis.util.RaftUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@@ -51,10 +51,10 @@ import static org.apache.ratis.server.impl.RaftServerConstants.DEFAULT_CALLID;
public abstract class RaftSnapshotBaseTest {
static {
- LogUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftLog.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftLog.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
}
static final Logger LOG = LoggerFactory.getLogger(RaftSnapshotBaseTest.class);
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/test/java/org/apache/ratis/statemachine/SimpleStateMachine4Testing.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/test/java/org/apache/ratis/statemachine/SimpleStateMachine4Testing.java b/ratis-server/src/test/java/org/apache/ratis/statemachine/SimpleStateMachine4Testing.java
index 6cb0234..44c420c 100644
--- a/ratis-server/src/test/java/org/apache/ratis/statemachine/SimpleStateMachine4Testing.java
+++ b/ratis-server/src/test/java/org/apache/ratis/statemachine/SimpleStateMachine4Testing.java
@@ -36,7 +36,7 @@ import org.apache.ratis.shaded.proto.RaftProtos.SMLogEntryProto;
import org.apache.ratis.util.Daemon;
import org.apache.ratis.util.LifeCycle;
import org.apache.ratis.util.MD5FileUtil;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -197,7 +197,7 @@ public class SimpleStateMachine4Testing extends BaseStateMachine {
termIndexTracker.update(ServerProtoUtils.toTermIndex(entry));
}
}
- Preconditions.assertTrue(
+ RaftUtils.assertTrue(
!list.isEmpty() && endIndex == list.get(list.size() - 1).getIndex(),
"endIndex=%s, list=%s", endIndex, list);
this.endIndexLastCkpt = endIndex;
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/test/java/org/apache/ratis/statemachine/TermIndexTracker.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/test/java/org/apache/ratis/statemachine/TermIndexTracker.java b/ratis-server/src/test/java/org/apache/ratis/statemachine/TermIndexTracker.java
index bb359d7..a282d97 100644
--- a/ratis-server/src/test/java/org/apache/ratis/statemachine/TermIndexTracker.java
+++ b/ratis-server/src/test/java/org/apache/ratis/statemachine/TermIndexTracker.java
@@ -18,7 +18,7 @@
package org.apache.ratis.statemachine;
import org.apache.ratis.server.protocol.TermIndex;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.util.Objects;
@@ -53,7 +53,7 @@ class TermIndexTracker {
*/
public synchronized void update(TermIndex termIndex) {
Objects.requireNonNull(termIndex);
- Preconditions.assertTrue(termIndex.compareTo(current) >= 0);
+ RaftUtils.assertTrue(termIndex.compareTo(current) >= 0);
this.current = termIndex;
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-server/src/test/java/org/apache/ratis/statemachine/TestStateMachine.java
----------------------------------------------------------------------
diff --git a/ratis-server/src/test/java/org/apache/ratis/statemachine/TestStateMachine.java b/ratis-server/src/test/java/org/apache/ratis/statemachine/TestStateMachine.java
index c1f79a3..b81e367 100644
--- a/ratis-server/src/test/java/org/apache/ratis/statemachine/TestStateMachine.java
+++ b/ratis-server/src/test/java/org/apache/ratis/statemachine/TestStateMachine.java
@@ -28,7 +28,7 @@ import org.apache.ratis.server.RaftServerConfigKeys;
import org.apache.ratis.server.impl.RaftServerImpl;
import org.apache.ratis.server.simulation.MiniRaftClusterWithSimulatedRpc;
import org.apache.ratis.shaded.proto.RaftProtos.SMLogEntryProto;
-import org.apache.ratis.util.LogUtils;
+import org.apache.ratis.util.RaftUtils;
import org.junit.*;
import org.junit.rules.Timeout;
@@ -50,8 +50,8 @@ import static org.junit.Assert.*;
*/
public class TestStateMachine {
static {
- LogUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
}
public static final int NUM_SERVERS = 5;
[2/2] incubator-ratis git commit: Revert "RATIS-52. Refactor
RaftUtils into different classes. Contributed by Enis Soztutar"
Posted by sz...@apache.org.
Revert "RATIS-52. Refactor RaftUtils into different classes. Contributed by Enis Soztutar"
This reverts commit 43ad0def61944b108bb4f2a474a60a4c566d9821.
Project: http://git-wip-us.apache.org/repos/asf/incubator-ratis/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-ratis/commit/771e8adc
Tree: http://git-wip-us.apache.org/repos/asf/incubator-ratis/tree/771e8adc
Diff: http://git-wip-us.apache.org/repos/asf/incubator-ratis/diff/771e8adc
Branch: refs/heads/master
Commit: 771e8adc40c36f310feac445beab1cff287dc69d
Parents: 43ad0de
Author: Tsz-Wo Nicholas Sze <sz...@hortonworks.com>
Authored: Fri Mar 31 14:56:30 2017 +0800
Committer: Tsz-Wo Nicholas Sze <sz...@hortonworks.com>
Committed: Fri Mar 31 14:56:30 2017 +0800
----------------------------------------------------------------------
.../ratis/client/impl/ClientProtoUtils.java | 4 +-
.../ratis/client/impl/RaftClientImpl.java | 7 +-
.../java/org/apache/ratis/RaftConfigKeys.java | 12 +-
.../org/apache/ratis/io/nativeio/NativeIO.java | 19 +-
.../ratis/io/nativeio/NativeIOException.java | 4 +-
.../org/apache/ratis/protocol/ClientId.java | 4 +-
.../org/apache/ratis/protocol/RaftPeerId.java | 4 +-
.../org/apache/ratis/rpc/SupportedRpcType.java | 7 +-
.../ratis/util/AtomicFileOutputStream.java | 2 +-
.../org/apache/ratis/util/CollectionUtils.java | 63 ---
.../java/org/apache/ratis/util/FileUtils.java | 2 +-
.../java/org/apache/ratis/util/IOUtils.java | 144 -------
.../java/org/apache/ratis/util/LifeCycle.java | 14 +-
.../java/org/apache/ratis/util/LogUtils.java | 36 --
.../java/org/apache/ratis/util/MD5FileUtil.java | 6 +-
.../org/apache/ratis/util/PlatformUtils.java | 74 ----
.../org/apache/ratis/util/Preconditions.java | 75 ----
.../java/org/apache/ratis/util/RaftUtils.java | 386 +++++++++++++++++++
.../org/apache/ratis/util/ReflectionUtils.java | 220 -----------
.../arithmetic/ArithmeticStateMachine.java | 4 +-
.../arithmetic/expression/BinaryExpression.java | 6 +-
.../arithmetic/expression/DoubleValue.java | 6 +-
.../arithmetic/expression/Expression.java | 8 +-
.../arithmetic/expression/NullValue.java | 4 +-
.../arithmetic/expression/UnaryExpression.java | 6 +-
.../arithmetic/expression/Variable.java | 6 +-
.../java/org/apache/ratis/TestBatchAppend.java | 8 +-
.../org/apache/ratis/TestRestartRaftPeer.java | 10 +-
.../examples/arithmetic/TestArithmetic.java | 4 +-
.../TestRaftStateMachineException.java | 10 +-
.../org/apache/ratis/grpc/RaftGrpcUtil.java | 9 +-
.../ratis/grpc/client/AppendStreamer.java | 11 +-
.../apache/ratis/grpc/client/GrpcClientRpc.java | 6 +-
.../grpc/client/RaftClientProtocolService.java | 8 +-
.../ratis/grpc/server/GRpcLogAppender.java | 12 +-
.../grpc/TestRaftReconfigurationWithGRpc.java | 4 +-
.../org/apache/ratis/grpc/TestRaftStream.java | 4 +-
.../org/apache/ratis/grpc/TestRaftWithGrpc.java | 4 +-
.../TestRaftReconfigurationWithHadoopRpc.java | 2 +
.../ratis/hadooprpc/TestRaftWithHadoopRpc.java | 8 +-
.../org/apache/ratis/netty/NettyRpcProxy.java | 8 +-
.../apache/ratis/netty/TestRaftWithNetty.java | 6 +-
.../ratis/server/impl/ConfigurationManager.java | 4 +-
.../ratis/server/impl/LeaderElection.java | 4 +-
.../apache/ratis/server/impl/LeaderState.java | 10 +-
.../apache/ratis/server/impl/LogAppender.java | 7 +-
.../ratis/server/impl/PeerConfiguration.java | 6 +-
.../ratis/server/impl/PendingRequest.java | 6 +-
.../ratis/server/impl/PendingRequests.java | 12 +-
.../ratis/server/impl/RaftConfiguration.java | 24 +-
.../ratis/server/impl/RaftServerImpl.java | 25 +-
.../apache/ratis/server/impl/ServerState.java | 4 +-
.../ratis/server/impl/StateMachineUpdater.java | 8 +-
.../ratis/server/storage/LogInputStream.java | 19 +-
.../ratis/server/storage/LogOutputStream.java | 6 +-
.../apache/ratis/server/storage/LogReader.java | 15 +-
.../apache/ratis/server/storage/LogSegment.java | 26 +-
.../ratis/server/storage/MemoryRaftLog.java | 4 +-
.../apache/ratis/server/storage/MetaFile.java | 4 +-
.../apache/ratis/server/storage/RaftLog.java | 4 +-
.../ratis/server/storage/RaftLogCache.java | 14 +-
.../ratis/server/storage/RaftLogWorker.java | 27 +-
.../ratis/server/storage/RaftStorage.java | 4 +-
.../ratis/server/storage/SegmentedRaftLog.java | 6 +-
.../ratis/server/storage/SnapshotManager.java | 7 +-
.../java/org/apache/ratis/MiniRaftCluster.java | 41 +-
.../ratis/RaftNotLeaderExceptionBaseTest.java | 10 +-
.../impl/RaftReconfigurationBaseTest.java | 8 +-
.../simulation/SimulatedRequestReply.java | 17 +-
.../simulation/TestRaftWithSimulatedRpc.java | 8 +-
.../server/storage/TestSegmentedRaftLog.java | 4 +-
.../statemachine/RaftSnapshotBaseTest.java | 10 +-
.../SimpleStateMachine4Testing.java | 4 +-
.../ratis/statemachine/TermIndexTracker.java | 4 +-
.../ratis/statemachine/TestStateMachine.java | 6 +-
75 files changed, 673 insertions(+), 922 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-client/src/main/java/org/apache/ratis/client/impl/ClientProtoUtils.java
----------------------------------------------------------------------
diff --git a/ratis-client/src/main/java/org/apache/ratis/client/impl/ClientProtoUtils.java b/ratis-client/src/main/java/org/apache/ratis/client/impl/ClientProtoUtils.java
index a6e99c6..ddecad6 100644
--- a/ratis-client/src/main/java/org/apache/ratis/client/impl/ClientProtoUtils.java
+++ b/ratis-client/src/main/java/org/apache/ratis/client/impl/ClientProtoUtils.java
@@ -21,7 +21,7 @@ import org.apache.ratis.shaded.com.google.protobuf.ByteString;
import org.apache.ratis.shaded.proto.RaftProtos.*;
import org.apache.ratis.protocol.*;
import org.apache.ratis.util.ProtoUtils;
-import org.apache.ratis.util.ReflectionUtils;
+import org.apache.ratis.util.RaftUtils;
import java.util.Arrays;
@@ -143,7 +143,7 @@ public class ClientProtoUtils {
} else {
try {
Class<?> clazz = Class.forName(className);
- final Exception e = ReflectionUtils.instantiateException(
+ final Exception e = RaftUtils.instantiateException(
clazz.asSubclass(Exception.class), errorMsg, null);
sme = new StateMachineException(serverId, e);
} catch (Exception e) {
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-client/src/main/java/org/apache/ratis/client/impl/RaftClientImpl.java
----------------------------------------------------------------------
diff --git a/ratis-client/src/main/java/org/apache/ratis/client/impl/RaftClientImpl.java b/ratis-client/src/main/java/org/apache/ratis/client/impl/RaftClientImpl.java
index 2125ce0..eae42a5 100644
--- a/ratis-client/src/main/java/org/apache/ratis/client/impl/RaftClientImpl.java
+++ b/ratis-client/src/main/java/org/apache/ratis/client/impl/RaftClientImpl.java
@@ -19,10 +19,9 @@ package org.apache.ratis.client.impl;
import org.apache.ratis.client.RaftClient;
import org.apache.ratis.client.RaftClientRpc;
-import org.apache.ratis.util.IOUtils;
-import org.apache.ratis.util.CollectionUtils;
import org.apache.ratis.util.TimeDuration;
import org.apache.ratis.protocol.*;
+import org.apache.ratis.util.RaftUtils;
import java.io.IOException;
import java.io.InterruptedIOException;
@@ -109,7 +108,7 @@ final class RaftClientImpl implements RaftClient {
retryInterval.sleep();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
- throw IOUtils.toInterruptedIOException(
+ throw RaftUtils.toInterruptedIOException(
"Interrupted when sending " + request, ie);
}
}
@@ -159,7 +158,7 @@ final class RaftClientImpl implements RaftClient {
newLeader, ioe);
final RaftPeerId oldLeader = request.getServerId();
if (newLeader == null && oldLeader.equals(leaderId)) {
- newLeader = CollectionUtils.next(oldLeader, CollectionUtils.as(peers, RaftPeer::getId));
+ newLeader = RaftUtils.next(oldLeader, RaftUtils.as(peers, RaftPeer::getId));
}
if (newLeader != null && oldLeader.equals(leaderId)) {
LOG.debug("{}: change Leader from {} to {}", clientId, oldLeader, newLeader);
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/RaftConfigKeys.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/RaftConfigKeys.java b/ratis-common/src/main/java/org/apache/ratis/RaftConfigKeys.java
index 665a7f5..b67acaf 100644
--- a/ratis-common/src/main/java/org/apache/ratis/RaftConfigKeys.java
+++ b/ratis-common/src/main/java/org/apache/ratis/RaftConfigKeys.java
@@ -17,14 +17,12 @@
*/
package org.apache.ratis;
-import static org.apache.ratis.conf.ConfUtils.get;
-import static org.apache.ratis.conf.ConfUtils.printAll;
-import static org.apache.ratis.conf.ConfUtils.set;
-
import org.apache.ratis.conf.RaftProperties;
import org.apache.ratis.rpc.RpcType;
import org.apache.ratis.rpc.SupportedRpcType;
-import org.apache.ratis.util.ReflectionUtils;
+import org.apache.ratis.util.RaftUtils;
+
+import static org.apache.ratis.conf.ConfUtils.*;
public interface RaftConfigKeys {
String PREFIX = "raft";
@@ -44,8 +42,8 @@ public interface RaftConfigKeys {
}
// Try using it as a class name
- return ReflectionUtils.newInstance(
- ReflectionUtils.getClass(t, properties, RpcType.class));
+ return RaftUtils.newInstance(
+ RaftUtils.getClass(t, properties, RpcType.class));
}
static void setType(RaftProperties properties, RpcType type) {
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/io/nativeio/NativeIO.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/io/nativeio/NativeIO.java b/ratis-common/src/main/java/org/apache/ratis/io/nativeio/NativeIO.java
index 921fb32..e096e84 100644
--- a/ratis-common/src/main/java/org/apache/ratis/io/nativeio/NativeIO.java
+++ b/ratis-common/src/main/java/org/apache/ratis/io/nativeio/NativeIO.java
@@ -18,9 +18,8 @@
package org.apache.ratis.io.nativeio;
import org.apache.ratis.protocol.AlreadyExistsException;
-import org.apache.ratis.util.IOUtils;
import org.apache.ratis.util.NativeCodeLoader;
-import org.apache.ratis.util.PlatformUtils;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Unsafe;
@@ -184,7 +183,7 @@ public class NativeIO {
private static native void chmodImpl(String path, int mode) throws IOException;
public static void chmod(String path, int mode) throws IOException {
- if (!PlatformUtils.WINDOWS) {
+ if (!RaftUtils.WINDOWS) {
chmodImpl(path, mode);
} else {
try {
@@ -322,12 +321,12 @@ public class NativeIO {
}
Stat(String owner, String group, int mode) {
- if (!PlatformUtils.WINDOWS) {
+ if (!RaftUtils.WINDOWS) {
this.owner = owner;
} else {
this.owner = stripDomain(owner);
}
- if (!PlatformUtils.WINDOWS) {
+ if (!RaftUtils.WINDOWS) {
this.group = group;
} else {
this.group = stripDomain(group);
@@ -605,7 +604,7 @@ public class NativeIO {
*/
public static FileInputStream getShareDeleteFileInputStream(File f)
throws IOException {
- if (!PlatformUtils.WINDOWS) {
+ if (!RaftUtils.WINDOWS) {
// On Linux the default FileInputStream shares delete permission
// on the file opened.
//
@@ -633,7 +632,7 @@ public class NativeIO {
*/
public static FileInputStream getShareDeleteFileInputStream(File f, long seekOffset)
throws IOException {
- if (!PlatformUtils.WINDOWS) {
+ if (!RaftUtils.WINDOWS) {
RandomAccessFile rf = new RandomAccessFile(f, "r");
if (seekOffset > 0) {
rf.seek(seekOffset);
@@ -667,7 +666,7 @@ public class NativeIO {
*/
public static FileOutputStream getCreateForWriteFileOutputStream(File f, int permissions)
throws IOException {
- if (!PlatformUtils.WINDOWS) {
+ if (!RaftUtils.WINDOWS) {
// Use the native wrapper around open(2)
try {
FileDescriptor fd = NativeIO.POSIX.open(f.getAbsolutePath(),
@@ -771,7 +770,7 @@ public class NativeIO {
* @param dst The destination path
*/
public static void copyFileUnbuffered(File src, File dst) throws IOException {
- if (nativeLoaded && PlatformUtils.WINDOWS) {
+ if (nativeLoaded && RaftUtils.WINDOWS) {
copyFileUnbuffered0(src.getAbsolutePath(), dst.getAbsolutePath());
} else {
FileInputStream fis = null;
@@ -792,7 +791,7 @@ public class NativeIO {
position += transferred;
}
} finally {
- IOUtils.cleanup(LOG, output, fos, input, fis);
+ RaftUtils.cleanup(LOG, output, fos, input, fis);
}
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/io/nativeio/NativeIOException.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/io/nativeio/NativeIOException.java b/ratis-common/src/main/java/org/apache/ratis/io/nativeio/NativeIOException.java
index 15f69cf..58b83e7 100644
--- a/ratis-common/src/main/java/org/apache/ratis/io/nativeio/NativeIOException.java
+++ b/ratis-common/src/main/java/org/apache/ratis/io/nativeio/NativeIOException.java
@@ -19,7 +19,7 @@ package org.apache.ratis.io.nativeio;
import java.io.IOException;
-import org.apache.ratis.util.PlatformUtils;
+import org.apache.ratis.util.RaftUtils;
/**
@@ -61,7 +61,7 @@ public class NativeIOException extends IOException {
@Override
public String toString() {
- if (PlatformUtils.WINDOWS)
+ if (RaftUtils.WINDOWS)
return errorCode + ": " + super.getMessage();
else
return errno.toString() + ": " + super.getMessage();
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/protocol/ClientId.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/protocol/ClientId.java b/ratis-common/src/main/java/org/apache/ratis/protocol/ClientId.java
index 310e207..7e15ee3 100644
--- a/ratis-common/src/main/java/org/apache/ratis/protocol/ClientId.java
+++ b/ratis-common/src/main/java/org/apache/ratis/protocol/ClientId.java
@@ -17,7 +17,7 @@
*/
package org.apache.ratis.protocol;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.nio.ByteBuffer;
import java.util.Objects;
@@ -43,7 +43,7 @@ public class ClientId {
public ClientId(byte[] data) {
Objects.requireNonNull(data, "data == null");
- Preconditions.assertTrue(data.length == BYTE_LENGTH,
+ RaftUtils.assertTrue(data.length == BYTE_LENGTH,
"data.length = %s != BYTE_LENGTH = %s", data.length, BYTE_LENGTH);
ByteBuffer buffer = ByteBuffer.wrap(data);
this.uuid = new UUID(buffer.getLong(), buffer.getLong());
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/protocol/RaftPeerId.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/protocol/RaftPeerId.java b/ratis-common/src/main/java/org/apache/ratis/protocol/RaftPeerId.java
index dff355e..92d9846 100644
--- a/ratis-common/src/main/java/org/apache/ratis/protocol/RaftPeerId.java
+++ b/ratis-common/src/main/java/org/apache/ratis/protocol/RaftPeerId.java
@@ -18,7 +18,7 @@
package org.apache.ratis.protocol;
import org.apache.ratis.shaded.com.google.protobuf.ByteString;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
@@ -37,7 +37,7 @@ public class RaftPeerId {
public RaftPeerId(String id) {
Objects.requireNonNull(id, "id == null");
- Preconditions.assertTrue(!id.isEmpty(), "id is an empty string.");
+ RaftUtils.assertTrue(!id.isEmpty(), "id is an empty string.");
this.id = id.getBytes(StandardCharsets.UTF_8);
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/rpc/SupportedRpcType.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/rpc/SupportedRpcType.java b/ratis-common/src/main/java/org/apache/ratis/rpc/SupportedRpcType.java
index 665b2f4..f1d8fac 100644
--- a/ratis-common/src/main/java/org/apache/ratis/rpc/SupportedRpcType.java
+++ b/ratis-common/src/main/java/org/apache/ratis/rpc/SupportedRpcType.java
@@ -19,7 +19,7 @@ package org.apache.ratis.rpc;
import org.apache.ratis.conf.Parameters;
import org.apache.ratis.conf.RaftProperties;
-import org.apache.ratis.util.ReflectionUtils;
+import org.apache.ratis.util.RaftUtils;
/** The RPC types supported. */
public enum SupportedRpcType implements RpcType {
@@ -42,9 +42,8 @@ public enum SupportedRpcType implements RpcType {
@Override
public RpcFactory newFactory(RaftProperties properties, Parameters parameters) {
- final Class<? extends RpcFactory> clazz = ReflectionUtils.getClass(
+ final Class<? extends RpcFactory> clazz = RaftUtils.getClass(
factoryClassName, properties, RpcFactory.class);
- return ReflectionUtils.newInstance(clazz,
- RpcFactory.class, ARG_CLASSES, parameters);
+ return RaftUtils.newInstance(clazz, ARG_CLASSES, parameters);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/util/AtomicFileOutputStream.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/AtomicFileOutputStream.java b/ratis-common/src/main/java/org/apache/ratis/util/AtomicFileOutputStream.java
index e181e44..e8e267e 100644
--- a/ratis-common/src/main/java/org/apache/ratis/util/AtomicFileOutputStream.java
+++ b/ratis-common/src/main/java/org/apache/ratis/util/AtomicFileOutputStream.java
@@ -83,7 +83,7 @@ public class AtomicFileOutputStream extends FilterOutputStream {
} else {
if (!triedToClose) {
// If we failed when flushing, try to close it to not leak an FD
- IOUtils.cleanup(LOG, out);
+ RaftUtils.cleanup(LOG, out);
}
// close wasn't successful, try to delete the tmp file
if (!tmpFile.delete()) {
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/util/CollectionUtils.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/CollectionUtils.java b/ratis-common/src/main/java/org/apache/ratis/util/CollectionUtils.java
deleted file mode 100644
index 05fa2fb..0000000
--- a/ratis-common/src/main/java/org/apache/ratis/util/CollectionUtils.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * *
- * * Licensed to the Apache Software Foundation (ASF) under one
- * * or more contributor license agreements. See the NOTICE file
- * * distributed with this work for additional information
- * * regarding copyright ownership. The ASF licenses this file
- * * to you under the Apache License, Version 2.0 (the
- * * "License"); you may not use this file except in compliance
- * * with the License. You may obtain a copy of the License at
- * *
- * * http://www.apache.org/licenses/LICENSE-2.0
- * *
- * * Unless required by applicable law or agreed to in writing, software
- * * distributed under the License is distributed on an "AS IS" BASIS,
- * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * * See the License for the specific language governing permissions and
- * * limitations under the License.
- *
- */
-
-package org.apache.ratis.util;
-
-import java.util.Iterator;
-import java.util.Objects;
-import java.util.function.Function;
-
-public interface CollectionUtils {
- /**
- * @return the next element in the iteration right after the given element;
- * if the given element is not in the iteration, return the first one
- */
- static <T> T next(final T given, final Iterable<T> iteration) {
- Objects.requireNonNull(given, "given == null");
- final Iterator<T> i = Objects.requireNonNull(iteration, "iteration == null").iterator();
- Preconditions.assertTrue(i.hasNext(), "iteration is empty.");
-
- final T first = i.next();
- for(T current = first; i.hasNext(); ) {
- final T next = i.next();
- if (given.equals(current)) {
- return next;
- }
- current = next;
- }
- return first;
- }
-
- static <INPUT, OUTPUT> Iterable<OUTPUT> as(
- Iterable<INPUT> iteration, Function<INPUT, OUTPUT> converter) {
- return () -> new Iterator<OUTPUT>() {
- final Iterator<INPUT> i = iteration.iterator();
- @Override
- public boolean hasNext() {
- return i.hasNext();
- }
-
- @Override
- public OUTPUT next() {
- return converter.apply(i.next());
- }
- };
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/util/FileUtils.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/FileUtils.java b/ratis-common/src/main/java/org/apache/ratis/util/FileUtils.java
index 732e4c8..5dc509d 100644
--- a/ratis-common/src/main/java/org/apache/ratis/util/FileUtils.java
+++ b/ratis-common/src/main/java/org/apache/ratis/util/FileUtils.java
@@ -193,7 +193,7 @@ public class FileUtils {
* On Windows, true if process has write access on the path
*/
public static boolean canWrite(File f) {
- if (PlatformUtils.WINDOWS) {
+ if (RaftUtils.WINDOWS) {
try {
return NativeIO.Windows.access(f.getCanonicalPath(),
NativeIO.Windows.AccessRight.ACCESS_WRITE);
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/util/IOUtils.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/IOUtils.java b/ratis-common/src/main/java/org/apache/ratis/util/IOUtils.java
deleted file mode 100644
index ba5e78e..0000000
--- a/ratis-common/src/main/java/org/apache/ratis/util/IOUtils.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * *
- * * Licensed to the Apache Software Foundation (ASF) under one
- * * or more contributor license agreements. See the NOTICE file
- * * distributed with this work for additional information
- * * regarding copyright ownership. The ASF licenses this file
- * * to you under the Apache License, Version 2.0 (the
- * * "License"); you may not use this file except in compliance
- * * with the License. You may obtain a copy of the License at
- * *
- * * http://www.apache.org/licenses/LICENSE-2.0
- * *
- * * Unless required by applicable law or agreed to in writing, software
- * * distributed under the License is distributed on an "AS IS" BASIS,
- * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * * See the License for the specific language governing permissions and
- * * limitations under the License.
- *
- */
-
-package org.apache.ratis.util;
-
-import java.io.Closeable;
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InterruptedIOException;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
-import java.util.concurrent.ExecutionException;
-
-import org.slf4j.Logger;
-
-/**
- * IO related utility methods.
- */
-public interface IOUtils {
- static InterruptedIOException toInterruptedIOException(
- String message, InterruptedException e) {
- final InterruptedIOException iioe = new InterruptedIOException(message);
- iioe.initCause(e);
- return iioe;
- }
-
- static IOException asIOException(Throwable t) {
- return t instanceof IOException? (IOException)t : new IOException(t);
- }
-
- static IOException toIOException(ExecutionException e) {
- final Throwable cause = e.getCause();
- return cause != null? asIOException(cause): new IOException(e);
- }
-
- static void readFully(InputStream in, int buffSize) throws IOException {
- final byte buf[] = new byte[buffSize];
- for(int bytesRead = in.read(buf); bytesRead >= 0; ) {
- bytesRead = in.read(buf);
- }
- }
-
- /**
- * Reads len bytes in a loop.
- *
- * @param in InputStream to read from
- * @param buf The buffer to fill
- * @param off offset from the buffer
- * @param len the length of bytes to read
- * @throws IOException if it could not read requested number of bytes
- * for any reason (including EOF)
- */
- static void readFully(InputStream in, byte[] buf, int off, int len)
- throws IOException {
- for(int toRead = len; toRead > 0; ) {
- final int ret = in.read(buf, off, toRead);
- if (ret < 0) {
- throw new IOException( "Premature EOF from inputStream");
- }
- toRead -= ret;
- off += ret;
- }
- }
-
- /**
- * Write a ByteBuffer to a FileChannel at a given offset,
- * handling short writes.
- *
- * @param fc The FileChannel to write to
- * @param buf The input buffer
- * @param offset The offset in the file to start writing at
- * @throws IOException On I/O error
- */
- static void writeFully(FileChannel fc, ByteBuffer buf, long offset)
- throws IOException {
- do {
- offset += fc.write(buf, offset);
- } while (buf.remaining() > 0);
- }
-
- /**
- * Similar to readFully(). Skips bytes in a loop.
- * @param in The InputStream to skip bytes from
- * @param len number of bytes to skip.
- * @throws IOException if it could not skip requested number of bytes
- * for any reason (including EOF)
- */
- static void skipFully(InputStream in, long len) throws IOException {
- long amt = len;
- while (amt > 0) {
- long ret = in.skip(amt);
- if (ret == 0) {
- // skip may return 0 even if we're not at EOF. Luckily, we can
- // use the read() method to figure out if we're at the end.
- int b = in.read();
- if (b == -1) {
- throw new EOFException( "Premature EOF from inputStream after " +
- "skipping " + (len - amt) + " byte(s).");
- }
- ret = 1;
- }
- amt -= ret;
- }
- }
-
- /**
- * Close the Closeable objects and <b>ignore</b> any {@link Throwable} or
- * null pointers. Must only be used for cleanup in exception handlers.
- *
- * @param log the log to record problems to at debug level. Can be null.
- * @param closeables the objects to close
- */
- static void cleanup(Logger log, Closeable... closeables) {
- for (Closeable c : closeables) {
- if (c != null) {
- try {
- c.close();
- } catch(Throwable e) {
- if (log != null && log.isDebugEnabled()) {
- log.debug("Exception in closing " + c, e);
- }
- }
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/util/LifeCycle.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/LifeCycle.java b/ratis-common/src/main/java/org/apache/ratis/util/LifeCycle.java
index 5246aba..166f0dc 100644
--- a/ratis-common/src/main/java/org/apache/ratis/util/LifeCycle.java
+++ b/ratis-common/src/main/java/org/apache/ratis/util/LifeCycle.java
@@ -17,16 +17,12 @@
*/
package org.apache.ratis.util;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicReference;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicReference;
+
/**
* The life cycle of a machine.
* <pre>
@@ -108,7 +104,7 @@ public class LifeCycle {
LOG.trace("TRACE", new Throwable());
}
- Preconditions.assertTrue(isValid(from, to),
+ RaftUtils.assertTrue(isValid(from, to),
"ILLEGAL TRANSITION: In %s, %s -> %s", name, from, to);
}
}
@@ -175,7 +171,7 @@ public class LifeCycle {
startImpl.run();
transition(State.RUNNING);
} catch (Throwable t) {
- transition(ReflectionUtils.isInstance(t, exceptionClasses)?
+ transition(RaftUtils.isInstance(t, exceptionClasses)?
State.NEW: State.EXCEPTION);
throw t;
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/util/LogUtils.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/LogUtils.java b/ratis-common/src/main/java/org/apache/ratis/util/LogUtils.java
deleted file mode 100644
index addc2ff..0000000
--- a/ratis-common/src/main/java/org/apache/ratis/util/LogUtils.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * *
- * * Licensed to the Apache Software Foundation (ASF) under one
- * * or more contributor license agreements. See the NOTICE file
- * * distributed with this work for additional information
- * * regarding copyright ownership. The ASF licenses this file
- * * to you under the Apache License, Version 2.0 (the
- * * "License"); you may not use this file except in compliance
- * * with the License. You may obtain a copy of the License at
- * *
- * * http://www.apache.org/licenses/LICENSE-2.0
- * *
- * * Unless required by applicable law or agreed to in writing, software
- * * distributed under the License is distributed on an "AS IS" BASIS,
- * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * * See the License for the specific language governing permissions and
- * * limitations under the License.
- *
- */
-
-package org.apache.ratis.util;
-
-import org.apache.log4j.Level;
-import org.apache.log4j.LogManager;
-import org.slf4j.Logger;
-
-/**
- * Logging (as in log4j) related utility methods.
- */
-public interface LogUtils {
-
- static void setLogLevel(Logger logger, Level level) {
- LogManager.getLogger(logger.getName()).setLevel(level);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/util/MD5FileUtil.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/MD5FileUtil.java b/ratis-common/src/main/java/org/apache/ratis/util/MD5FileUtil.java
index a5ded8c..35c7136 100644
--- a/ratis-common/src/main/java/org/apache/ratis/util/MD5FileUtil.java
+++ b/ratis-common/src/main/java/org/apache/ratis/util/MD5FileUtil.java
@@ -73,7 +73,7 @@ public abstract class MD5FileUtil {
} catch (IOException ioe) {
throw new IOException("Error reading md5 file at " + md5File, ioe);
} finally {
- IOUtils.cleanup(LOG, reader);
+ RaftUtils.cleanup(LOG, reader);
}
Matcher matcher = LINE_REGEX.matcher(md5Line);
@@ -118,11 +118,11 @@ public abstract class MD5FileUtil {
try {
MessageDigest digester = MD5Hash.getDigester();
DigestInputStream dis = new DigestInputStream(in, digester);
- IOUtils.readFully(dis, 128*1024);
+ RaftUtils.readFully(dis, 128*1024);
return new MD5Hash(digester.digest());
} finally {
- IOUtils.cleanup(LOG, in);
+ RaftUtils.cleanup(LOG, in);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/util/PlatformUtils.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/PlatformUtils.java b/ratis-common/src/main/java/org/apache/ratis/util/PlatformUtils.java
deleted file mode 100644
index 6d4bf54..0000000
--- a/ratis-common/src/main/java/org/apache/ratis/util/PlatformUtils.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * *
- * * Licensed to the Apache Software Foundation (ASF) under one
- * * or more contributor license agreements. See the NOTICE file
- * * distributed with this work for additional information
- * * regarding copyright ownership. The ASF licenses this file
- * * to you under the Apache License, Version 2.0 (the
- * * "License"); you may not use this file except in compliance
- * * with the License. You may obtain a copy of the License at
- * *
- * * http://www.apache.org/licenses/LICENSE-2.0
- * *
- * * Unless required by applicable law or agreed to in writing, software
- * * distributed under the License is distributed on an "AS IS" BASIS,
- * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * * See the License for the specific language governing permissions and
- * * limitations under the License.
- *
- */
-
-package org.apache.ratis.util;
-
-/**
- * Platform and architecture related utility methods.
- */
-public class PlatformUtils {
-
- private PlatformUtils() {
- // Utility class, cannot instantiate
- }
-
- public static final boolean PPC_64
- = System.getProperties().getProperty("os.arch").contains("ppc64");
- /**
- * Get the type of the operating system, as determined from parsing
- * the <code>os.name</code> property.
- */
- private static final OSType osType = getOSType();
- public static final boolean OTHER = (osType == OSType.OS_TYPE_OTHER);
- public static final boolean LINUX = (osType == OSType.OS_TYPE_LINUX);
- public static final boolean FREEBSD = (osType == OSType.OS_TYPE_FREEBSD);
- public static final boolean MAC = (osType == OSType.OS_TYPE_MAC);
- public static final boolean SOLARIS = (osType == OSType.OS_TYPE_SOLARIS);
- // Helper static vars for each platform
- public static final boolean WINDOWS = (osType == OSType.OS_TYPE_WIN);
-
- private static OSType getOSType() {
- String osName = System.getProperty("os.name");
- if (osName.startsWith("Windows")) {
- return OSType.OS_TYPE_WIN;
- } else if (osName.contains("SunOS") || osName.contains("Solaris")) {
- return OSType.OS_TYPE_SOLARIS;
- } else if (osName.contains("Mac")) {
- return OSType.OS_TYPE_MAC;
- } else if (osName.contains("FreeBSD")) {
- return OSType.OS_TYPE_FREEBSD;
- } else if (osName.startsWith("Linux")) {
- return OSType.OS_TYPE_LINUX;
- } else {
- // Some other form of Unix
- return OSType.OS_TYPE_OTHER;
- }
- }
-
- // OSType detection
- public enum OSType {
- OS_TYPE_LINUX,
- OS_TYPE_WIN,
- OS_TYPE_SOLARIS,
- OS_TYPE_MAC,
- OS_TYPE_FREEBSD,
- OS_TYPE_OTHER
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/util/Preconditions.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/Preconditions.java b/ratis-common/src/main/java/org/apache/ratis/util/Preconditions.java
deleted file mode 100644
index f1d55b0..0000000
--- a/ratis-common/src/main/java/org/apache/ratis/util/Preconditions.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * *
- * * Licensed to the Apache Software Foundation (ASF) under one
- * * or more contributor license agreements. See the NOTICE file
- * * distributed with this work for additional information
- * * regarding copyright ownership. The ASF licenses this file
- * * to you under the Apache License, Version 2.0 (the
- * * "License"); you may not use this file except in compliance
- * * with the License. You may obtain a copy of the License at
- * *
- * * http://www.apache.org/licenses/LICENSE-2.0
- * *
- * * Unless required by applicable law or agreed to in writing, software
- * * distributed under the License is distributed on an "AS IS" BASIS,
- * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * * See the License for the specific language governing permissions and
- * * limitations under the License.
- *
- */
-
-package org.apache.ratis.util;
-
-import java.util.function.Supplier;
-
-public interface Preconditions {
- /**
- * Assert if the given value is true.
- * @param value the value to be asserted.
- * @throws IllegalStateException if the given value is false.
- */
- static void assertTrue(boolean value) {
- if (!value) {
- throw new IllegalStateException();
- }
- }
-
- /**
- * Assert if the given value is true.
- * @param value the value to be asserted.
- * @param message The exception message.
- * @throws IllegalStateException with the given message if the given value is false.
- */
- static void assertTrue(boolean value, Object message) {
- if (!value) {
- throw new IllegalStateException(String.valueOf(message));
- }
- }
-
- /**
- * Assert if the given value is true.
- * @param value the value to be asserted.
- * @param format exception message format.
- * @param args exception message arguments.
- * @throws IllegalStateException if the given value is false.
- * The exception message is constructed by {@link String#format(String, Object...)}
- * with the given format and arguments.
- */
- static void assertTrue(boolean value, String format, Object... args) {
- if (!value) {
- throw new IllegalStateException(String.format(format, args));
- }
- }
-
- /**
- * Assert if the given value is true.
- * @param value the value to be asserted.
- * @param message The exception message supplier.
- * @throws IllegalStateException with the given message if the given value is false.
- */
- static void assertTrue(boolean value, Supplier<Object> message) {
- if (!value) {
- throw new IllegalStateException(String.valueOf(message.get()));
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/util/RaftUtils.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/RaftUtils.java b/ratis-common/src/main/java/org/apache/ratis/util/RaftUtils.java
new file mode 100644
index 0000000..ae3e857
--- /dev/null
+++ b/ratis-common/src/main/java/org/apache/ratis/util/RaftUtils.java
@@ -0,0 +1,386 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ratis.util;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.LogManager;
+import org.apache.ratis.conf.RaftProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.*;
+import java.lang.reflect.Constructor;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+public abstract class RaftUtils {
+ public static final Logger LOG = LoggerFactory.getLogger(RaftUtils.class);
+
+ // OSType detection
+ public enum OSType {
+ OS_TYPE_LINUX,
+ OS_TYPE_WIN,
+ OS_TYPE_SOLARIS,
+ OS_TYPE_MAC,
+ OS_TYPE_FREEBSD,
+ OS_TYPE_OTHER
+ }
+
+ /**
+ * Get the type of the operating system, as determined from parsing
+ * the <code>os.name</code> property.
+ */
+ private static final OSType osType = getOSType();
+
+ private static OSType getOSType() {
+ String osName = System.getProperty("os.name");
+ if (osName.startsWith("Windows")) {
+ return OSType.OS_TYPE_WIN;
+ } else if (osName.contains("SunOS") || osName.contains("Solaris")) {
+ return OSType.OS_TYPE_SOLARIS;
+ } else if (osName.contains("Mac")) {
+ return OSType.OS_TYPE_MAC;
+ } else if (osName.contains("FreeBSD")) {
+ return OSType.OS_TYPE_FREEBSD;
+ } else if (osName.startsWith("Linux")) {
+ return OSType.OS_TYPE_LINUX;
+ } else {
+ // Some other form of Unix
+ return OSType.OS_TYPE_OTHER;
+ }
+ }
+
+ // Helper static vars for each platform
+ public static final boolean WINDOWS = (osType == OSType.OS_TYPE_WIN);
+ public static final boolean SOLARIS = (osType == OSType.OS_TYPE_SOLARIS);
+ public static final boolean MAC = (osType == OSType.OS_TYPE_MAC);
+ public static final boolean FREEBSD = (osType == OSType.OS_TYPE_FREEBSD);
+ public static final boolean LINUX = (osType == OSType.OS_TYPE_LINUX);
+ public static final boolean OTHER = (osType == OSType.OS_TYPE_OTHER);
+
+ public static final boolean PPC_64
+ = System.getProperties().getProperty("os.arch").contains("ppc64");
+
+ public static final Class<?>[] EMPTY_CLASSES = {};
+ /**
+ * Cache of constructors for each class. Pins the classes so they
+ * can't be garbage collected until ReflectionUtils can be collected.
+ */
+ private static final Map<List<Class<?>>, Constructor<?>> CONSTRUCTOR_CACHE
+ = new ConcurrentHashMap<>();
+
+ public static InterruptedIOException toInterruptedIOException(
+ String message, InterruptedException e) {
+ final InterruptedIOException iioe = new InterruptedIOException(message);
+ iioe.initCause(e);
+ return iioe;
+ }
+
+ public static IOException asIOException(Throwable t) {
+ return t instanceof IOException? (IOException)t : new IOException(t);
+ }
+
+ public static IOException toIOException(ExecutionException e) {
+ final Throwable cause = e.getCause();
+ return cause != null? asIOException(cause): new IOException(e);
+ }
+
+ /** Is the given object an instance of one of the given classes? */
+ public static boolean isInstance(Object obj, Class<?>... classes) {
+ for(Class<?> c : classes) {
+ if (c.isInstance(obj)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Create an object for the given class using its default constructor.
+ */
+ public static <T> T newInstance(Class<T> clazz) {
+ return newInstance(clazz, EMPTY_CLASSES);
+ }
+
+ /**
+ * Create an object for the given class using the specified constructor.
+ *
+ * @param clazz class of which an object is created
+ * @param argClasses argument classes of the constructor
+ * @param args actual arguments to be passed to the constructor
+ * @param <T> class type of clazz
+ * @return a new object
+ */
+ public static <T> T newInstance(Class<T> clazz, Class<?>[] argClasses, Object... args) {
+ Objects.requireNonNull(clazz, "clazz == null");
+ try {
+ final List<Class<?>> key = new ArrayList<>();
+ key.add(clazz);
+ key.addAll(Arrays.asList(argClasses));
+
+ @SuppressWarnings("unchecked")
+ Constructor<T> ctor = (Constructor<T>) CONSTRUCTOR_CACHE.get(key);
+ if (ctor == null) {
+ ctor = clazz.getDeclaredConstructor(argClasses);
+ ctor.setAccessible(true);
+ CONSTRUCTOR_CACHE.put(key, ctor);
+ }
+ return ctor.newInstance(args);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public static <BASE> Class<? extends BASE> getClass(
+ String subClassName, RaftProperties properties, Class<BASE> base) {
+ try {
+ return properties.getClassByName(subClassName).asSubclass(base);
+ } catch (ClassNotFoundException e) {
+ throw new IllegalArgumentException("Failed to get class "
+ + subClassName + " as a subclass of " + base, e);
+ }
+ }
+
+ /**
+ * Create a memoized supplier which gets a value by invoking the initializer once
+ * and then keeps returning the same value as its supplied results.
+ *
+ * @param initializer to supply at most one non-null value.
+ * @param <T> The supplier result type.
+ * @return a memoized supplier which is thread-safe.
+ */
+ public static <T> Supplier<T> memoize(Supplier<T> initializer) {
+ Objects.requireNonNull(initializer, "initializer == null");
+ return new Supplier<T>() {
+ private volatile T value = null;
+
+ @Override
+ public T get() {
+ T v = value;
+ if (v == null) {
+ synchronized (this) {
+ v = value;
+ if (v == null) {
+ v = value = Objects.requireNonNull(initializer.get(),
+ "initializer.get() returns null");
+ }
+ }
+ }
+ return v;
+ }
+ };
+ }
+
+ public static void setLogLevel(Logger logger, Level level) {
+ LogManager.getLogger(logger.getName()).setLevel(level);
+ }
+
+
+ public static void readFully(InputStream in, int buffSize) throws IOException {
+ final byte buf[] = new byte[buffSize];
+ for(int bytesRead = in.read(buf); bytesRead >= 0; ) {
+ bytesRead = in.read(buf);
+ }
+ }
+
+ /**
+ * Reads len bytes in a loop.
+ *
+ * @param in InputStream to read from
+ * @param buf The buffer to fill
+ * @param off offset from the buffer
+ * @param len the length of bytes to read
+ * @throws IOException if it could not read requested number of bytes
+ * for any reason (including EOF)
+ */
+ public static void readFully(InputStream in, byte[] buf, int off, int len)
+ throws IOException {
+ for(int toRead = len; toRead > 0; ) {
+ final int ret = in.read(buf, off, toRead);
+ if (ret < 0) {
+ throw new IOException( "Premature EOF from inputStream");
+ }
+ toRead -= ret;
+ off += ret;
+ }
+ }
+
+ /**
+ * Write a ByteBuffer to a FileChannel at a given offset,
+ * handling short writes.
+ *
+ * @param fc The FileChannel to write to
+ * @param buf The input buffer
+ * @param offset The offset in the file to start writing at
+ * @throws IOException On I/O error
+ */
+ public static void writeFully(FileChannel fc, ByteBuffer buf, long offset)
+ throws IOException {
+ do {
+ offset += fc.write(buf, offset);
+ } while (buf.remaining() > 0);
+ }
+
+ /**
+ * Similar to readFully(). Skips bytes in a loop.
+ * @param in The InputStream to skip bytes from
+ * @param len number of bytes to skip.
+ * @throws IOException if it could not skip requested number of bytes
+ * for any reason (including EOF)
+ */
+ public static void skipFully(InputStream in, long len) throws IOException {
+ long amt = len;
+ while (amt > 0) {
+ long ret = in.skip(amt);
+ if (ret == 0) {
+ // skip may return 0 even if we're not at EOF. Luckily, we can
+ // use the read() method to figure out if we're at the end.
+ int b = in.read();
+ if (b == -1) {
+ throw new EOFException( "Premature EOF from inputStream after " +
+ "skipping " + (len - amt) + " byte(s).");
+ }
+ ret = 1;
+ }
+ amt -= ret;
+ }
+ }
+
+ /**
+ * Close the Closeable objects and <b>ignore</b> any {@link Throwable} or
+ * null pointers. Must only be used for cleanup in exception handlers.
+ *
+ * @param log the log to record problems to at debug level. Can be null.
+ * @param closeables the objects to close
+ */
+ public static void cleanup(Logger log, Closeable... closeables) {
+ for (Closeable c : closeables) {
+ if (c != null) {
+ try {
+ c.close();
+ } catch(Throwable e) {
+ if (log != null && log.isDebugEnabled()) {
+ log.debug("Exception in closing " + c, e);
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * @return the next element in the iteration right after the given element;
+ * if the given element is not in the iteration, return the first one
+ */
+ public static <T> T next(final T given, final Iterable<T> iteration) {
+ Objects.requireNonNull(given, "given == null");
+ final Iterator<T> i = Objects.requireNonNull(iteration, "iteration == null").iterator();
+ assertTrue(i.hasNext(), "iteration is empty.");
+
+ final T first = i.next();
+ for(T current = first; i.hasNext(); ) {
+ final T next = i.next();
+ if (given.equals(current)) {
+ return next;
+ }
+ current = next;
+ }
+ return first;
+ }
+
+ public static <INPUT, OUTPUT> Iterable<OUTPUT> as(
+ Iterable<INPUT> iteration, Function<INPUT, OUTPUT> converter) {
+ return () -> new Iterator<OUTPUT>() {
+ final Iterator<INPUT> i = iteration.iterator();
+ @Override
+ public boolean hasNext() {
+ return i.hasNext();
+ }
+
+ @Override
+ public OUTPUT next() {
+ return converter.apply(i.next());
+ }
+ };
+ }
+
+ /**
+ * Assert if the given value is true.
+ * @param value the value to be asserted.
+ * @throws IllegalStateException if the given value is false.
+ */
+ public static void assertTrue(boolean value) {
+ if (!value) {
+ throw new IllegalStateException();
+ }
+ }
+
+ /**
+ * Assert if the given value is true.
+ * @param value the value to be asserted.
+ * @param message The exception message.
+ * @throws IllegalStateException with the given message if the given value is false.
+ */
+ public static void assertTrue(boolean value, Object message) {
+ if (!value) {
+ throw new IllegalStateException(String.valueOf(message));
+ }
+ }
+
+ /**
+ * Assert if the given value is true.
+ * @param value the value to be asserted.
+ * @param format exception message format.
+ * @param args exception message arguments.
+ * @throws IllegalStateException if the given value is false.
+ * The exception message is constructed by {@link String#format(String, Object...)}
+ * with the given format and arguments.
+ */
+ public static void assertTrue(boolean value, String format, Object... args) {
+ if (!value) {
+ throw new IllegalStateException(String.format(format, args));
+ }
+ }
+
+ /**
+ * Assert if the given value is true.
+ * @param value the value to be asserted.
+ * @param message The exception message supplier.
+ * @throws IllegalStateException with the given message if the given value is false.
+ */
+ public static void assertTrue(boolean value, Supplier<Object> message) {
+ if (!value) {
+ throw new IllegalStateException(String.valueOf(message.get()));
+ }
+ }
+
+ public static Exception instantiateException(Class<? extends Exception> cls,
+ String message, Exception from) throws Exception {
+ Constructor<? extends Exception> cn = cls.getConstructor(String.class);
+ cn.setAccessible(true);
+ Exception ex = cn.newInstance(message);
+ if (from != null) {
+ ex.initCause(from);
+ }
+ return ex;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-common/src/main/java/org/apache/ratis/util/ReflectionUtils.java
----------------------------------------------------------------------
diff --git a/ratis-common/src/main/java/org/apache/ratis/util/ReflectionUtils.java b/ratis-common/src/main/java/org/apache/ratis/util/ReflectionUtils.java
deleted file mode 100644
index 5c7ada6..0000000
--- a/ratis-common/src/main/java/org/apache/ratis/util/ReflectionUtils.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * *
- * * Licensed to the Apache Software Foundation (ASF) under one
- * * or more contributor license agreements. See the NOTICE file
- * * distributed with this work for additional information
- * * regarding copyright ownership. The ASF licenses this file
- * * to you under the Apache License, Version 2.0 (the
- * * "License"); you may not use this file except in compliance
- * * with the License. You may obtain a copy of the License at
- * *
- * * http://www.apache.org/licenses/LICENSE-2.0
- * *
- * * Unless required by applicable law or agreed to in writing, software
- * * distributed under the License is distributed on an "AS IS" BASIS,
- * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * * See the License for the specific language governing permissions and
- * * limitations under the License.
- *
- */
-
-package org.apache.ratis.util;
-
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.function.Supplier;
-
-import org.apache.ratis.conf.RaftProperties;
-
-/**
- * Reflection related utility methods.
- */
-public class ReflectionUtils {
-
- private ReflectionUtils() {
- // Utility class, cannot instantiate
- }
-
- private static final Class<?>[] EMPTY_CLASSES = {};
-
- /**
- * Cache of constructors for each class. Pins the classes so they
- * can't be garbage collected until ReflectionUtils can be collected.
- */
- private static final Map<List<Class<?>>, Constructor<?>> CONSTRUCTOR_CACHE
- = new ConcurrentHashMap<>();
-
- /**
- * Create an object for the given class using its default constructor.
- */
- public static <T> T newInstance(Class<T> clazz) {
- return newInstance(clazz, EMPTY_CLASSES);
- }
-
- /**
- * Create an object for the given class using its default constructor.
- */
- public static <T> T newInstance(String className) {
- return newInstance(className, EMPTY_CLASSES);
- }
-
- /**
- * Create an object for the given class using the specified constructor.
- *
- * @param clazz class of which an object is created
- * @param argClasses argument classes of the constructor
- * @param args actual arguments to be passed to the constructor
- * @param <T> class type of clazz
- * @return a new object
- */
- public static <T> T newInstance(Class<T> clazz, Class<?>[] argClasses, Object... args) {
- Objects.requireNonNull(clazz, "clazz == null");
- try {
- final List<Class<?>> key = new ArrayList<>();
- key.add(clazz);
- key.addAll(Arrays.asList(argClasses));
-
- @SuppressWarnings("unchecked")
- Constructor<T> ctor = (Constructor<T>) CONSTRUCTOR_CACHE.get(key);
- if (ctor == null) {
- ctor = clazz.getDeclaredConstructor(argClasses);
- ctor.setAccessible(true);
- CONSTRUCTOR_CACHE.put(key, ctor);
- }
- return instantiate(clazz.getName(), ctor, args);
- } catch (NoSuchMethodException e) {
- throw new UnsupportedOperationException(
- "Unable to find suitable constructor for class " + clazz.getName(), e);
- }
- }
-
- @SuppressWarnings("unchecked")
- public static <T> T newInstance(String className, Class<? >[] argClasses,
- Object... args) {
- try {
- Class<? extends T> resultType = (Class<? extends T>) Class.forName(className);
- return newInstance(resultType, argClasses, args);
- } catch (ClassNotFoundException e) {
- throw new UnsupportedOperationException(
- "Unable to find " + className, e);
- }
- }
-
- public static <T> T newInstance(Class<T> type, Object... params) {
- return newInstance(type, findConstructor(type, params), params);
- }
-
- private static <T> T instantiate(final String className, Constructor<T> ctor, Object[] ctorArgs) {
- try {
- ctor.setAccessible(true);
- return ctor.newInstance(ctorArgs);
- } catch (IllegalAccessException e) {
- throw new UnsupportedOperationException(
- "Unable to access specified class " + className, e);
- } catch (InstantiationException e) {
- throw new UnsupportedOperationException(
- "Unable to instantiate specified class " + className, e);
- } catch (InvocationTargetException e) {
- throw new UnsupportedOperationException(
- "Constructor threw an exception for " + className, e);
- }
- }
-
- @SuppressWarnings("unchecked")
- public static <T> Constructor<T> findConstructor(Class<T> type, Object... paramTypes) {
- Constructor<T>[] constructors = (Constructor<T>[]) type.getDeclaredConstructors();
- for (Constructor<T> ctor : constructors) {
- Class<?>[] ctorParamTypes = ctor.getParameterTypes();
- if (ctorParamTypes.length != paramTypes.length) {
- continue;
- }
-
- boolean match = true;
- for (int i = 0; i < ctorParamTypes.length && match; ++i) {
- Class<?> paramType = paramTypes[i].getClass();
- match = (!ctorParamTypes[i].isPrimitive()) ? ctorParamTypes[i].isAssignableFrom(paramType) :
- ((int.class.equals(ctorParamTypes[i]) && Integer.class.equals(paramType)) ||
- (long.class.equals(ctorParamTypes[i]) && Long.class.equals(paramType)) ||
- (double.class.equals(ctorParamTypes[i]) && Double.class.equals(paramType)) ||
- (char.class.equals(ctorParamTypes[i]) && Character.class.equals(paramType)) ||
- (short.class.equals(ctorParamTypes[i]) && Short.class.equals(paramType)) ||
- (boolean.class.equals(ctorParamTypes[i]) && Boolean.class.equals(paramType)) ||
- (byte.class.equals(ctorParamTypes[i]) && Byte.class.equals(paramType)));
- }
-
- if (match) {
- return ctor;
- }
- }
- throw new UnsupportedOperationException(
- "Unable to find suitable constructor for class " + type.getName());
- }
-
- /** Is the given object an instance of one of the given classes? */
- public static boolean isInstance(Object obj, Class<?>... classes) {
- for(Class<?> c : classes) {
- if (c.isInstance(obj)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Create a memoized supplier which gets a value by invoking the initializer once
- * and then keeps returning the same value as its supplied results.
- *
- * @param initializer to supply at most one non-null value.
- * @param <T> The supplier result type.
- * @return a memoized supplier which is thread-safe.
- */
- public static <T> Supplier<T> memoize(Supplier<T> initializer) {
- Objects.requireNonNull(initializer, "initializer == null");
- return new Supplier<T>() {
- private volatile T value = null;
-
- @Override
- public T get() {
- T v = value;
- if (v == null) {
- synchronized (this) {
- v = value;
- if (v == null) {
- v = value = Objects.requireNonNull(initializer.get(),
- "initializer.get() returns null");
- }
- }
- }
- return v;
- }
- };
- }
-
- public static <BASE> Class<? extends BASE> getClass(
- String subClassName, RaftProperties properties, Class<BASE> base) {
- try {
- return properties.getClassByName(subClassName).asSubclass(base);
- } catch (ClassNotFoundException e) {
- throw new IllegalArgumentException("Failed to get class "
- + subClassName + " as a subclass of " + base, e);
- }
- }
-
- public static Exception instantiateException(Class<? extends Exception> cls,
- String message, Exception from) throws Exception {
- Constructor<? extends Exception> cn = cls.getConstructor(String.class);
- cn.setAccessible(true);
- Exception ex = cn.newInstance(message);
- if (from != null) {
- ex.initCause(from);
- }
- return ex;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/ArithmeticStateMachine.java
----------------------------------------------------------------------
diff --git a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/ArithmeticStateMachine.java b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/ArithmeticStateMachine.java
index 53e8ab7..89580df 100644
--- a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/ArithmeticStateMachine.java
+++ b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/ArithmeticStateMachine.java
@@ -29,7 +29,7 @@ import org.apache.ratis.server.storage.RaftStorage;
import org.apache.ratis.shaded.proto.RaftProtos.LogEntryProto;
import org.apache.ratis.statemachine.*;
import org.apache.ratis.util.AutoCloseableLock;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -175,7 +175,7 @@ public class ArithmeticStateMachine extends BaseStateMachine {
final TermIndex newTI = TermIndex.newTermIndex(term, index);
final TermIndex oldTI = latestTermIndex.getAndSet(newTI);
if (oldTI != null) {
- Preconditions.assertTrue(newTI.compareTo(oldTI) >= 0);
+ RaftUtils.assertTrue(newTI.compareTo(oldTI) >= 0);
}
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/BinaryExpression.java
----------------------------------------------------------------------
diff --git a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/BinaryExpression.java b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/BinaryExpression.java
index 121bb7a..6486cfd 100644
--- a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/BinaryExpression.java
+++ b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/BinaryExpression.java
@@ -17,7 +17,7 @@
*/
package org.apache.ratis.examples.arithmetic.expression;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.util.Map;
@@ -43,7 +43,7 @@ public class BinaryExpression implements Expression {
static final Op[] VALUES = Op.values();
static Op valueOf(byte b) {
- Preconditions.assertTrue(b < VALUES.length);
+ RaftUtils.assertTrue(b < VALUES.length);
return VALUES[b];
}
}
@@ -52,7 +52,7 @@ public class BinaryExpression implements Expression {
private final Expression left, right;
BinaryExpression(byte[] buf, final int offset) {
- Preconditions.assertTrue(buf[offset] == Type.BINARY.byteValue());
+ RaftUtils.assertTrue(buf[offset] == Type.BINARY.byteValue());
op = Op.valueOf(buf[offset + 1]);
left = Utils.bytes2Expression(buf, offset + 2);
right = Utils.bytes2Expression(buf, offset + 2 + left.length());
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/DoubleValue.java
----------------------------------------------------------------------
diff --git a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/DoubleValue.java b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/DoubleValue.java
index 66862f0..1753186 100644
--- a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/DoubleValue.java
+++ b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/DoubleValue.java
@@ -17,7 +17,7 @@
*/
package org.apache.ratis.examples.arithmetic.expression;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.util.Map;
@@ -33,12 +33,12 @@ public class DoubleValue implements Expression {
DoubleValue(byte[] buf, int offset) {
this(Utils.bytes2double(buf, offset + 1));
- Preconditions.assertTrue(buf[offset] == Type.DOUBLE.byteValue());
+ RaftUtils.assertTrue(buf[offset] == Type.DOUBLE.byteValue());
}
@Override
public int toBytes(byte[] buf, int offset) {
- Preconditions.assertTrue(offset + length() <= buf.length);
+ RaftUtils.assertTrue(offset + length() <= buf.length);
buf[offset++] = Type.DOUBLE.byteValue();
Utils.double2bytes(value, buf, offset);
return length();
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/Expression.java
----------------------------------------------------------------------
diff --git a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/Expression.java b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/Expression.java
index 12818f7..2d5a490 100644
--- a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/Expression.java
+++ b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/Expression.java
@@ -21,7 +21,7 @@ import static org.apache.ratis.util.ProtoUtils.toByteString;
import org.apache.ratis.examples.arithmetic.Evaluable;
import org.apache.ratis.protocol.Message;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
public interface Expression extends Evaluable {
enum Type {
@@ -34,8 +34,8 @@ public interface Expression extends Evaluable {
private static final Type[] VALUES = Type.values();
static Type valueOf(byte b) {
- Preconditions.assertTrue(b >= 0);
- Preconditions.assertTrue(b < VALUES.length);
+ RaftUtils.assertTrue(b >= 0);
+ RaftUtils.assertTrue(b < VALUES.length);
return VALUES[b];
}
}
@@ -49,7 +49,7 @@ public interface Expression extends Evaluable {
return () -> {
final byte[] buf = new byte[e.length()];
final int length = e.toBytes(buf, 0);
- Preconditions.assertTrue(length == buf.length);
+ RaftUtils.assertTrue(length == buf.length);
return toByteString(buf);
};
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/NullValue.java
----------------------------------------------------------------------
diff --git a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/NullValue.java b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/NullValue.java
index 6f589fa..9167839 100644
--- a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/NullValue.java
+++ b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/NullValue.java
@@ -17,7 +17,7 @@
*/
package org.apache.ratis.examples.arithmetic.expression;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.util.Map;
@@ -33,7 +33,7 @@ public class NullValue implements Expression {
@Override
public int toBytes(byte[] buf, int offset) {
- Preconditions.assertTrue(offset + length() <= buf.length);
+ RaftUtils.assertTrue(offset + length() <= buf.length);
buf[offset++] = Type.NULL.byteValue();
return length();
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/UnaryExpression.java
----------------------------------------------------------------------
diff --git a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/UnaryExpression.java b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/UnaryExpression.java
index abe329d..2311064 100644
--- a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/UnaryExpression.java
+++ b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/UnaryExpression.java
@@ -17,7 +17,7 @@
*/
package org.apache.ratis.examples.arithmetic.expression;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import java.util.Map;
@@ -43,7 +43,7 @@ public class UnaryExpression implements Expression {
static final Op[] VALUES = Op.values();
static Op valueOf(byte b) {
- Preconditions.assertTrue(b < VALUES.length);
+ RaftUtils.assertTrue(b < VALUES.length);
return VALUES[b];
}
}
@@ -52,7 +52,7 @@ public class UnaryExpression implements Expression {
final Expression expression;
UnaryExpression(byte[] buf, int offset) {
- Preconditions.assertTrue(buf[offset] == Type.UNARY.byteValue());
+ RaftUtils.assertTrue(buf[offset] == Type.UNARY.byteValue());
op = Op.valueOf(buf[offset + 1]);
expression = Utils.bytes2Expression(buf, offset + 2);
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/Variable.java
----------------------------------------------------------------------
diff --git a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/Variable.java b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/Variable.java
index 248b24a..4c5608b 100644
--- a/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/Variable.java
+++ b/ratis-examples/src/main/java/org/apache/ratis/examples/arithmetic/expression/Variable.java
@@ -21,7 +21,7 @@ import java.util.Map;
import java.util.regex.Pattern;
import org.apache.ratis.examples.arithmetic.AssignmentMessage;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
public class Variable implements Expression {
static final int LENGTH_LIMIT = 32;
@@ -38,7 +38,7 @@ public class Variable implements Expression {
}
static String extractString(byte[] buf, int offset) {
- Preconditions.assertTrue(buf[offset] == Type.VARIABLE.byteValue());
+ RaftUtils.assertTrue(buf[offset] == Type.VARIABLE.byteValue());
final int length = buf[offset + 1];
final byte[] stringBytes = new byte[length];
System.arraycopy(buf, offset + 2, stringBytes, 0, length);
@@ -46,7 +46,7 @@ public class Variable implements Expression {
}
static byte[] copyBytes(byte[] buf, int offset) {
- Preconditions.assertTrue(buf[offset] == Type.VARIABLE.byteValue());
+ RaftUtils.assertTrue(buf[offset] == Type.VARIABLE.byteValue());
final int length = buf[offset + 1];
final byte[] copy = new byte[length + 2];
System.arraycopy(buf, offset, copy, 0, copy.length);
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-examples/src/test/java/org/apache/ratis/TestBatchAppend.java
----------------------------------------------------------------------
diff --git a/ratis-examples/src/test/java/org/apache/ratis/TestBatchAppend.java b/ratis-examples/src/test/java/org/apache/ratis/TestBatchAppend.java
index b494b67..cc69984 100644
--- a/ratis-examples/src/test/java/org/apache/ratis/TestBatchAppend.java
+++ b/ratis-examples/src/test/java/org/apache/ratis/TestBatchAppend.java
@@ -21,7 +21,6 @@ import org.apache.log4j.Level;
import org.apache.ratis.RaftTestUtil.SimpleMessage;
import org.apache.ratis.client.RaftClient;
import org.apache.ratis.conf.RaftProperties;
-import org.apache.ratis.util.LogUtils;
import org.apache.ratis.util.SizeInBytes;
import org.apache.ratis.examples.RaftExamplesTestUtil;
import org.apache.ratis.protocol.RaftPeerId;
@@ -30,6 +29,7 @@ import org.apache.ratis.server.impl.RaftServerImpl;
import org.apache.ratis.server.simulation.RequestHandler;
import org.apache.ratis.statemachine.SimpleStateMachine4Testing;
import org.apache.ratis.statemachine.StateMachine;
+import org.apache.ratis.util.RaftUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Rule;
@@ -56,9 +56,9 @@ import java.util.stream.Stream;
public class TestBatchAppend {
static Logger LOG = LoggerFactory.getLogger(TestBatchAppend.class);
static {
- LogUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
}
@Parameterized.Parameters
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-examples/src/test/java/org/apache/ratis/TestRestartRaftPeer.java
----------------------------------------------------------------------
diff --git a/ratis-examples/src/test/java/org/apache/ratis/TestRestartRaftPeer.java b/ratis-examples/src/test/java/org/apache/ratis/TestRestartRaftPeer.java
index 346d7c0..34aec44 100644
--- a/ratis-examples/src/test/java/org/apache/ratis/TestRestartRaftPeer.java
+++ b/ratis-examples/src/test/java/org/apache/ratis/TestRestartRaftPeer.java
@@ -21,7 +21,6 @@ import org.apache.log4j.Level;
import org.apache.ratis.RaftTestUtil.SimpleMessage;
import org.apache.ratis.client.RaftClient;
import org.apache.ratis.conf.RaftProperties;
-import org.apache.ratis.util.LogUtils;
import org.apache.ratis.util.SizeInBytes;
import org.apache.ratis.examples.RaftExamplesTestUtil;
import org.apache.ratis.protocol.RaftPeerId;
@@ -31,6 +30,7 @@ import org.apache.ratis.server.simulation.RequestHandler;
import org.apache.ratis.server.storage.RaftLog;
import org.apache.ratis.statemachine.SimpleStateMachine4Testing;
import org.apache.ratis.statemachine.StateMachine;
+import org.apache.ratis.util.RaftUtils;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
@@ -51,10 +51,10 @@ import java.util.Collection;
public class TestRestartRaftPeer {
static Logger LOG = LoggerFactory.getLogger(TestRestartRaftPeer.class);
static {
- LogUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftLog.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftLog.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
}
@Parameterized.Parameters
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-examples/src/test/java/org/apache/ratis/examples/arithmetic/TestArithmetic.java
----------------------------------------------------------------------
diff --git a/ratis-examples/src/test/java/org/apache/ratis/examples/arithmetic/TestArithmetic.java b/ratis-examples/src/test/java/org/apache/ratis/examples/arithmetic/TestArithmetic.java
index 5ffb70f..f4bcd0a 100644
--- a/ratis-examples/src/test/java/org/apache/ratis/examples/arithmetic/TestArithmetic.java
+++ b/ratis-examples/src/test/java/org/apache/ratis/examples/arithmetic/TestArithmetic.java
@@ -26,7 +26,7 @@ import org.apache.ratis.examples.RaftExamplesTestUtil;
import org.apache.ratis.examples.arithmetic.expression.*;
import org.apache.ratis.protocol.RaftClientReply;
import org.apache.ratis.protocol.RaftPeerId;
-import org.apache.ratis.util.LogUtils;
+import org.apache.ratis.util.RaftUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -38,7 +38,7 @@ import java.util.Collection;
@RunWith(Parameterized.class)
public class TestArithmetic {
static {
- LogUtils.setLogLevel(ArithmeticStateMachine.LOG, Level.ALL);
+ RaftUtils.setLogLevel(ArithmeticStateMachine.LOG, Level.ALL);
}
@Parameterized.Parameters
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-examples/src/test/java/org/apache/ratis/statemachine/TestRaftStateMachineException.java
----------------------------------------------------------------------
diff --git a/ratis-examples/src/test/java/org/apache/ratis/statemachine/TestRaftStateMachineException.java b/ratis-examples/src/test/java/org/apache/ratis/statemachine/TestRaftStateMachineException.java
index c3b0184..447f2ea 100644
--- a/ratis-examples/src/test/java/org/apache/ratis/statemachine/TestRaftStateMachineException.java
+++ b/ratis-examples/src/test/java/org/apache/ratis/statemachine/TestRaftStateMachineException.java
@@ -28,7 +28,7 @@ import org.apache.ratis.protocol.StateMachineException;
import org.apache.ratis.server.impl.RaftServerImpl;
import org.apache.ratis.server.simulation.RequestHandler;
import org.apache.ratis.server.storage.RaftLog;
-import org.apache.ratis.util.LogUtils;
+import org.apache.ratis.util.RaftUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -43,10 +43,10 @@ import static org.junit.Assert.fail;
@RunWith(Parameterized.class)
public class TestRaftStateMachineException {
static {
- LogUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftLog.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
- LogUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftServerImpl.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftLog.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RequestHandler.LOG, Level.DEBUG);
+ RaftUtils.setLogLevel(RaftClient.LOG, Level.DEBUG);
}
protected static class StateMachineWithException extends SimpleStateMachine4Testing {
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-grpc/src/main/java/org/apache/ratis/grpc/RaftGrpcUtil.java
----------------------------------------------------------------------
diff --git a/ratis-grpc/src/main/java/org/apache/ratis/grpc/RaftGrpcUtil.java b/ratis-grpc/src/main/java/org/apache/ratis/grpc/RaftGrpcUtil.java
index b89c297..fb3cc11 100644
--- a/ratis-grpc/src/main/java/org/apache/ratis/grpc/RaftGrpcUtil.java
+++ b/ratis-grpc/src/main/java/org/apache/ratis/grpc/RaftGrpcUtil.java
@@ -20,8 +20,7 @@ package org.apache.ratis.grpc;
import org.apache.ratis.shaded.io.grpc.Metadata;
import org.apache.ratis.shaded.io.grpc.Status;
import org.apache.ratis.shaded.io.grpc.StatusRuntimeException;
-import org.apache.ratis.util.IOUtils;
-import org.apache.ratis.util.ReflectionUtils;
+import org.apache.ratis.util.RaftUtils;
import org.apache.ratis.util.StringUtils;
import java.io.IOException;
@@ -46,9 +45,9 @@ public class RaftGrpcUtil {
if (className != null) {
try {
Class<?> clazz = Class.forName(className);
- final Exception unwrapped = ReflectionUtils.instantiateException(
+ final Exception unwrapped = RaftUtils.instantiateException(
clazz.asSubclass(Exception.class), status.getDescription(), se);
- return IOUtils.asIOException(unwrapped);
+ return RaftUtils.asIOException(unwrapped);
} catch (Exception e) {
return new IOException(se);
}
@@ -62,7 +61,7 @@ public class RaftGrpcUtil {
if (t instanceof StatusRuntimeException) {
e = RaftGrpcUtil.unwrapException((StatusRuntimeException) t);
} else {
- e = IOUtils.asIOException(t);
+ e = RaftUtils.asIOException(t);
}
return e;
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/AppendStreamer.java
----------------------------------------------------------------------
diff --git a/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/AppendStreamer.java b/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/AppendStreamer.java
index c92820c..d42f4e1 100644
--- a/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/AppendStreamer.java
+++ b/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/AppendStreamer.java
@@ -18,8 +18,6 @@
package org.apache.ratis.grpc.client;
import org.apache.ratis.conf.RaftProperties;
-import org.apache.ratis.util.CollectionUtils;
-import org.apache.ratis.util.Preconditions;
import org.apache.ratis.util.TimeDuration;
import org.apache.ratis.grpc.GrpcConfigKeys;
import org.apache.ratis.grpc.RaftGrpcUtil;
@@ -30,6 +28,7 @@ import org.apache.ratis.shaded.proto.RaftProtos.RaftClientRequestProto;
import org.apache.ratis.shaded.proto.RaftProtos.RaftRpcRequestProto;
import org.apache.ratis.util.Daemon;
import org.apache.ratis.util.PeerProxyMap;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -115,7 +114,7 @@ public class AppendStreamer implements Closeable {
if (oldLeader == null) {
leaderId = peers.keySet().iterator().next();
} else {
- leaderId = CollectionUtils.next(oldLeader, peers.keySet());
+ leaderId = RaftUtils.next(oldLeader, peers.keySet());
}
}
LOG.debug("{} switches leader from {} to {}. suggested leader: {}", this,
@@ -258,7 +257,7 @@ public class AppendStreamer implements Closeable {
RaftClientRequestProto pending = Objects.requireNonNull(
ackQueue.peek());
if (reply.getRpcReply().getSuccess()) {
- Preconditions.assertTrue(pending.getRpcRequest().getCallId() ==
+ RaftUtils.assertTrue(pending.getRpcRequest().getCallId() ==
reply.getRpcReply().getCallId());
ackQueue.poll();
LOG.trace("{} received success ack for request {}", this,
@@ -312,7 +311,7 @@ public class AppendStreamer implements Closeable {
private void handleNotLeader(NotLeaderException nle,
RaftPeerId oldLeader) {
- Preconditions.assertTrue(Thread.holdsLock(AppendStreamer.this));
+ RaftUtils.assertTrue(Thread.holdsLock(AppendStreamer.this));
// handle NotLeaderException: refresh leader and RaftConfiguration
refreshPeers(nle.getPeers());
@@ -320,7 +319,7 @@ public class AppendStreamer implements Closeable {
}
private void handleError(Throwable t, ResponseHandler handler) {
- Preconditions.assertTrue(Thread.holdsLock(AppendStreamer.this));
+ RaftUtils.assertTrue(Thread.holdsLock(AppendStreamer.this));
final IOException e = RaftGrpcUtil.unwrapIOException(t);
exceptionAndRetry.addException(handler.targetId, e);
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/GrpcClientRpc.java
----------------------------------------------------------------------
diff --git a/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/GrpcClientRpc.java b/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/GrpcClientRpc.java
index b28415c..3f7343a 100644
--- a/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/GrpcClientRpc.java
+++ b/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/GrpcClientRpc.java
@@ -25,8 +25,8 @@ import org.apache.ratis.shaded.io.grpc.stub.StreamObserver;
import org.apache.ratis.shaded.proto.RaftProtos.RaftClientReplyProto;
import org.apache.ratis.shaded.proto.RaftProtos.RaftClientRequestProto;
import org.apache.ratis.shaded.proto.RaftProtos.SetConfigurationRequestProto;
-import org.apache.ratis.util.IOUtils;
import org.apache.ratis.util.PeerProxyMap;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -71,7 +71,7 @@ public class GrpcClientRpc implements RaftClientRpc {
if (t instanceof StatusRuntimeException) {
e = RaftGrpcUtil.unwrapException((StatusRuntimeException) t);
} else {
- e = IOUtils.asIOException(t);
+ e = RaftUtils.asIOException(t);
}
replyFuture.completeExceptionally(e);
}
@@ -94,7 +94,7 @@ public class GrpcClientRpc implements RaftClientRpc {
throw new InterruptedIOException(
"Interrupted while waiting for response of request " + request);
} catch (ExecutionException e) {
- throw IOUtils.toIOException(e);
+ throw RaftUtils.toIOException(e);
}
}
}
http://git-wip-us.apache.org/repos/asf/incubator-ratis/blob/771e8adc/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/RaftClientProtocolService.java
----------------------------------------------------------------------
diff --git a/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/RaftClientProtocolService.java b/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/RaftClientProtocolService.java
index 97e32c1..5ebeb66 100644
--- a/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/RaftClientProtocolService.java
+++ b/ratis-grpc/src/main/java/org/apache/ratis/grpc/client/RaftClientProtocolService.java
@@ -27,7 +27,7 @@ import org.apache.ratis.client.impl.ClientProtoUtils;
import org.apache.ratis.grpc.RaftGrpcUtil;
import org.apache.ratis.protocol.RaftClientAsynchronousProtocol;
import org.apache.ratis.protocol.RaftClientReply;
-import org.apache.ratis.util.Preconditions;
+import org.apache.ratis.util.RaftUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -126,14 +126,14 @@ public class RaftClientProtocolService extends RaftClientProtocolServiceImplBase
} else {
final long replySeq = reply.getCallId();
synchronized (pendingList) {
- Preconditions.assertTrue(!pendingList.isEmpty(),
+ RaftUtils.assertTrue(!pendingList.isEmpty(),
"PendingList is empty when handling onNext for callId %s",
replySeq);
final long headSeqNum = pendingList.get(0).callId;
// we assume the callId is consecutive for a stream RPC call
final PendingAppend pendingForReply = pendingList.get(
(int) (replySeq - headSeqNum));
- Preconditions.assertTrue(pendingForReply != null &&
+ RaftUtils.assertTrue(pendingForReply != null &&
pendingForReply.callId == replySeq,
"pending for reply is: %s, the pending list: %s",
pendingForReply, pendingList);
@@ -162,7 +162,7 @@ public class RaftClientProtocolService extends RaftClientProtocolServiceImplBase
private void sendReadyReplies(Collection<PendingAppend> readySet) {
readySet.forEach(ready -> {
- Preconditions.assertTrue(ready.isReady());
+ RaftUtils.assertTrue(ready.isReady());
if (ready == COMPLETED) {
responseObserver.onCompleted();
} else {