Java Code Examples for org.apache.ratis.util.Preconditions#assertTrue()

The following examples show how to use org.apache.ratis.util.Preconditions#assertTrue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RaftServerMetrics.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
/**
 * Get the commit index gauge for the given peer of the server
 * @param server
 * @param peerServer
 * @return Metric Gauge holding the value of commit index of the peer
 */
@VisibleForTesting
public static Gauge getPeerCommitIndexGauge(RaftServerImpl server,
    RaftServerImpl peerServer) {

  RaftServerMetrics serverMetrics =
      metricsMap.get(server.getMemberId().toString());
  if (serverMetrics == null) {
    return null;
  }

  String followerCommitIndexKey = String.format(
      LEADER_METRIC_PEER_COMMIT_INDEX,
      peerServer.getPeer().getId().toString());

  SortedMap<String, Gauge> map =
      serverMetrics.registry.getGauges((s, metric) ->
          s.contains(followerCommitIndexKey));

  Preconditions.assertTrue(map.size() <= 1);
  return map.get(map.firstKey());
}
 
Example 2
Source File: BaseStateMachine.java    From ratis with Apache License 2.0 6 votes vote down vote up
protected boolean updateLastAppliedTermIndex(long term, long index) {
  final TermIndex newTI = TermIndex.newTermIndex(term, index);
  final TermIndex oldTI = lastAppliedTermIndex.getAndSet(newTI);
  if (!newTI.equals(oldTI)) {
    LOG.trace("{}: update lastAppliedTermIndex from {} to {}", getId(), oldTI, newTI);
    if (oldTI != null) {
      Preconditions.assertTrue(newTI.compareTo(oldTI) >= 0,
          () -> getId() + ": Failed updateLastAppliedTermIndex: newTI = "
              + newTI + " < oldTI = " + oldTI);
    }
    return true;
  }

  synchronized (transactionFutures) {
    for(long i; !transactionFutures.isEmpty() && (i = transactionFutures.firstKey()) <= index; ) {
      transactionFutures.remove(i).complete(null);
    }
  }
  return false;
}
 
Example 3
Source File: PeerConfiguration.java    From ratis with Apache License 2.0 6 votes vote down vote up
boolean hasMajority(Collection<RaftPeerId> others, RaftPeerId selfId) {
  Preconditions.assertTrue(!others.contains(selfId));
  int num = 0;
  if (contains(selfId)) {
    num++;
  }
  for (RaftPeerId other : others) {
    if (contains(other)) {
      num++;
    }
    if (num > size() / 2) {
      return true;
    }
  }
  return false;
}
 
Example 4
Source File: RaftGroup.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
private RaftGroup(RaftGroupId groupId, Collection<RaftPeer> peers) {
  this.groupId = Objects.requireNonNull(groupId, "groupId == null");
  Preconditions.assertTrue(!groupId.equals(EMPTY_GROUP.getGroupId()),
      () -> "Group Id " + groupId + " is reserved for the empty group.");

  if (peers == null || peers.isEmpty()) {
    this.peers = Collections.emptyMap();
  } else {
    final Map<RaftPeerId, RaftPeer> map = new HashMap<>();
    peers.forEach(p -> map.put(p.getId(), p));
    this.peers = Collections.unmodifiableMap(map);
  }
}
 
Example 5
Source File: RaftClientImpl.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
@Override
public GroupInfoReply getGroupInfo(RaftGroupId raftGroupId, RaftPeerId server) throws IOException {
  Objects.requireNonNull(server, "server == null");
  RaftGroupId rgi = raftGroupId == null ? groupId : raftGroupId;
  final RaftClientReply reply = sendRequest(new GroupInfoRequest(clientId, server, rgi, nextCallId()));
  Preconditions.assertTrue(reply instanceof GroupInfoReply, () -> "Unexpected reply: " + reply);
  return (GroupInfoReply)reply;
}
 
Example 6
Source File: LogSegment.java    From ratis with Apache License 2.0 5 votes vote down vote up
static LogSegment loadSegment(RaftStorage storage, File file,
    long start, long end, boolean isOpen,
    boolean keepEntryInCache, Consumer<LogEntryProto> logConsumer)
    throws IOException {
  final LogSegment segment = isOpen ?
      LogSegment.newOpenSegment(storage, start) :
      LogSegment.newCloseSegment(storage, start, end);

  final int entryCount = readSegmentFile(file, start, end, isOpen, entry -> {
    segment.append(keepEntryInCache || isOpen, entry);
    if (logConsumer != null) {
      logConsumer.accept(entry);
    }
  });
  LOG.info("Successfully read {} entries from segment file {}", entryCount, file);

  if (entryCount == 0) {
    // The segment does not have any entries, delete the file.
    FileUtils.deleteFile(file);
    return null;
  } else if (file.length() > segment.getTotalSize()) {
    // The segment has extra padding, truncate it.
    FileUtils.truncateFile(file, segment.getTotalSize());
  }

  Preconditions.assertTrue(start == segment.getStartIndex());
  if (!segment.records.isEmpty()) {
    Preconditions.assertTrue(start == segment.records.get(0).getTermIndex().getIndex());
  }
  if (!isOpen) {
    Preconditions.assertTrue(segment.getEndIndex() == end);
  }
  return segment;
}
 
Example 7
Source File: LogInputStream.java    From ratis with Apache License 2.0 5 votes vote down vote up
public LogInputStream(File log, long startIndex, long endIndex,
    boolean isOpen) {
  if (isOpen) {
    Preconditions.assertTrue(endIndex == INVALID_LOG_INDEX);
  } else {
    Preconditions.assertTrue(endIndex >= startIndex);
  }

  this.logFile = log;
  this.startIndex = startIndex;
  this.endIndex = endIndex;
  this.isOpen = isOpen;
  this.state = new OpenCloseState(getName());
}
 
Example 8
Source File: SimpleStateMachine4Testing.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
<T> CompletableFuture<T> collect(Type type, T value) {
  final BlockingQueue<Runnable> q = get(type);
  if (q == null) {
    return CompletableFuture.completedFuture(value);
  }

  final CompletableFuture<T> future = new CompletableFuture<>();
  final boolean offered = q.offer(() -> future.complete(value));
  Preconditions.assertTrue(offered);
  return future;
}
 
Example 9
Source File: FileStoreBaseTest.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
ByteBuffer randomBytes(int length, Random random) {
  Preconditions.assertTrue(length <= buffer.length);
  random.nextBytes(buffer);
  final ByteBuffer b = ByteBuffer.wrap(buffer);
  b.limit(length);
  return b;
}
 
Example 10
Source File: ReplicationManager.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if more than 50% of the container replicas with unique
 * originNodeId are in QUASI_CLOSED state.
 *
 * @param container Container to check
 * @param replicas Set of ContainerReplicas
 * @return true if we can force close the container, false otherwise
 */
private boolean canForceCloseContainer(final ContainerInfo container,
    final Set<ContainerReplica> replicas) {
  Preconditions.assertTrue(container.getState() ==
      LifeCycleState.QUASI_CLOSED);
  final int replicationFactor = container.getReplicationFactor().getNumber();
  final long uniqueQuasiClosedReplicaCount = replicas.stream()
      .filter(r -> r.getState() == State.QUASI_CLOSED)
      .map(ContainerReplica::getOriginDatanodeId)
      .distinct()
      .count();
  return uniqueQuasiClosedReplicaCount > (replicationFactor / 2);
}
 
Example 11
Source File: PendingRequests.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
PendingRequest add(Permit permit, RaftClientRequest request, TransactionContext entry) {
  // externally synced for now
  Preconditions.assertTrue(request.is(RaftClientRequestProto.TypeCase.WRITE));
  final long index = entry.getLogEntry().getIndex();
  LOG.debug("{}: addPendingRequest at index={}, request={}", name, index, request);
  final PendingRequest pending = new PendingRequest(index, request, entry);
  return pendingRequests.put(permit, index, pending);
}
 
Example 12
Source File: SegmentedRaftLogCache.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
/**
 * finalize the current open segment, and start a new open segment
 */
void rollOpenSegment(boolean createNewOpen) {
  Preconditions.assertTrue(openSegment != null
      && openSegment.numOfEntries() > 0);
  final long nextIndex = openSegment.getEndIndex() + 1;
  openSegment.close();
  closedSegments.add(openSegment);
  clearOpenSegment();
  if (createNewOpen) {
    addOpenSegment(nextIndex);
  }
}
 
Example 13
Source File: MiniRaftCluster.java    From ratis with Apache License 2.0 4 votes vote down vote up
public RaftServerProxy putNewServer(RaftPeerId id, RaftGroup group, boolean format) {
  final RaftServerProxy s = newRaftServer(id, group, format);
  Preconditions.assertTrue(servers.put(id, s) == null);
  peers.put(id, toRaftPeer(s));
  return s;
}
 
Example 14
Source File: RaftClientRequest.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
public WriteRequestTypeProto getWrite() {
  Preconditions.assertTrue(is(WRITE));
  return (WriteRequestTypeProto)proto;
}
 
Example 15
Source File: RaftConfiguration.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
/** @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));
  return conf.hasMajority(others, selfId) &&
      (oldConf == null || oldConf.hasMajority(others, selfId));
}
 
Example 16
Source File: RaftClientRequest.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
public StaleReadRequestTypeProto getStaleRead() {
  Preconditions.assertTrue(is(STALEREAD));
  return (StaleReadRequestTypeProto)proto;
}
 
Example 17
Source File: NullValue.java    From ratis with Apache License 2.0 4 votes vote down vote up
@Override
public int toBytes(byte[] buf, int offset) {
  Preconditions.assertTrue(offset + length() <= buf.length);
  buf[offset++] = Type.NULL.byteValue();
  return length();
}
 
Example 18
Source File: RaftClientRequest.java    From ratis with Apache License 2.0 4 votes vote down vote up
public StaleReadRequestTypeProto getStaleRead() {
  Preconditions.assertTrue(is(STALEREAD));
  return (StaleReadRequestTypeProto)proto;
}
 
Example 19
Source File: PendingRequests.java    From ratis with Apache License 2.0 4 votes vote down vote up
void put(long index, PendingRequest p) {
  LOG.debug("{}: PendingRequests.put {} -> {}", name, index, p);
  final PendingRequest previous = map.put(index, p);
  Preconditions.assertTrue(previous == null);
}
 
Example 20
Source File: SegmentedRaftLogCache.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
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);
  openSegment.appendToOpenSegment(entry);
}