org.apache.ratis.proto.RaftProtos.RaftPeerRole Java Examples

The following examples show how to use org.apache.ratis.proto.RaftProtos.RaftPeerRole. 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: ArithmeticStateMachine.java    From ratis with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Message> applyTransaction(TransactionContext trx) {
  final LogEntryProto entry = trx.getLogEntry();
  final AssignmentMessage assignment = new AssignmentMessage(entry.getStateMachineLogEntry().getLogData());

  final long index = entry.getIndex();
  final Double result;
  try(final AutoCloseableLock writeLock = writeLock()) {
    result = assignment.evaluate(variables);
    updateLastAppliedTermIndex(entry.getTerm(), index);
  }
  final Expression r = Expression.Utils.double2Expression(result);
  final CompletableFuture<Message> f = CompletableFuture.completedFuture(Expression.Utils.toMessage(r));

  final RaftPeerRole role = trx.getServerRole();
  if (role == RaftPeerRole.LEADER) {
    LOG.info("{}:{}-{}: {} = {}", role, getId(), index, assignment, r);
  } else {
    LOG.debug("{}:{}-{}: {} = {}", role, getId(), index, assignment, r);
  }
  if (LOG.isTraceEnabled()) {
    LOG.trace("{}-{}: variables={}", getId(), index, variables);
  }
  return f;
}
 
Example #2
Source File: TransactionContext.java    From ratis with Apache License 2.0 6 votes vote down vote up
public TransactionContext build() {
  Objects.requireNonNull(serverRole, "serverRole == null");
  Objects.requireNonNull(stateMachine, "stateMachine == null");
  if (clientRequest != null) {
    Preconditions.assertTrue(serverRole == RaftPeerRole.LEADER,
        () -> "serverRole MUST be LEADER since clientRequest != null, serverRole is " + serverRole);
    Preconditions.assertNull(logEntry, () -> "logEntry MUST be null since clientRequest != null");
    if (stateMachineLogEntry == null) {
      stateMachineLogEntry = ServerProtoUtils.toStateMachineLogEntryProto(clientRequest, logData, stateMachineData);
    }
    return new TransactionContextImpl(stateMachine, clientRequest, stateMachineLogEntry, stateMachineContext);
  } else {
    Objects.requireNonNull(logEntry, "logEntry MUST NOT be null since clientRequest == null");
    Preconditions.assertTrue(logEntry.hasStateMachineLogEntry(),
        () -> "Unexpected logEntry: stateMachineLogEntry not found, logEntry=" + logEntry);
    return new TransactionContextImpl(serverRole, stateMachine, logEntry);
  }
}
 
Example #3
Source File: ArithmeticStateMachine.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Message> applyTransaction(TransactionContext trx) {
  final LogEntryProto entry = trx.getLogEntry();
  final AssignmentMessage assignment = new AssignmentMessage(entry.getStateMachineLogEntry().getLogData());

  final long index = entry.getIndex();
  final Double result;
  try(AutoCloseableLock writeLock = writeLock()) {
    result = assignment.evaluate(variables);
    updateLastAppliedTermIndex(entry.getTerm(), index);
  }
  final Expression r = Expression.Utils.double2Expression(result);
  final CompletableFuture<Message> f = CompletableFuture.completedFuture(Expression.Utils.toMessage(r));

  final RaftPeerRole role = trx.getServerRole();
  if (role == RaftPeerRole.LEADER) {
    LOG.info("{}:{}-{}: {} = {}", role, getId(), index, assignment, r);
  } else {
    LOG.debug("{}:{}-{}: {} = {}", role, getId(), index, assignment, r);
  }
  if (LOG.isTraceEnabled()) {
    LOG.trace("{}-{}: variables={}", getId(), index, variables);
  }
  return f;
}
 
Example #4
Source File: TransactionContext.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
public TransactionContext build() {
  Objects.requireNonNull(serverRole, "serverRole == null");
  Objects.requireNonNull(stateMachine, "stateMachine == null");
  if (clientRequest != null) {
    Preconditions.assertTrue(serverRole == RaftPeerRole.LEADER,
        () -> "serverRole MUST be LEADER since clientRequest != null, serverRole is " + serverRole);
    Preconditions.assertNull(logEntry, () -> "logEntry MUST be null since clientRequest != null");
    if (stateMachineLogEntry == null) {
      stateMachineLogEntry = ServerProtoUtils.toStateMachineLogEntryProto(clientRequest, logData, stateMachineData);
    }
    return new TransactionContextImpl(stateMachine, clientRequest, stateMachineLogEntry, stateMachineContext);
  } else {
    Objects.requireNonNull(logEntry, "logEntry MUST NOT be null since clientRequest == null");
    Preconditions.assertTrue(logEntry.hasStateMachineLogEntry(),
        () -> "Unexpected logEntry: stateMachineLogEntry not found, logEntry=" + logEntry);
    return new TransactionContextImpl(serverRole, stateMachine, logEntry);
  }
}
 
Example #5
Source File: TransactionContextImpl.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a {@link TransactionContext} from a client request.
 * Used by the state machine to start a transaction
 * and send the Log entry representing the transaction data
 * to be applied to the raft log.
 */
public TransactionContextImpl(
    StateMachine stateMachine, RaftClientRequest clientRequest,
    StateMachineLogEntryProto smLogEntryProto, Object stateMachineContext) {
  this(RaftPeerRole.LEADER, stateMachine);
  this.clientRequest = clientRequest;
  this.smLogEntryProto = smLogEntryProto != null? smLogEntryProto
      : ServerProtoUtils.toStateMachineLogEntryProto(clientRequest, null, null);
  this.stateMachineContext = stateMachineContext;
}
 
Example #6
Source File: TransactionContextImpl.java    From ratis with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a {@link TransactionContext} from a client request.
 * Used by the state machine to start a transaction
 * and send the Log entry representing the transaction data
 * to be applied to the raft log.
 */
public TransactionContextImpl(
    StateMachine stateMachine, RaftClientRequest clientRequest,
    StateMachineLogEntryProto smLogEntryProto, Object stateMachineContext) {
  this(RaftPeerRole.LEADER, stateMachine);
  this.clientRequest = clientRequest;
  this.smLogEntryProto = smLogEntryProto != null? smLogEntryProto
      : ServerProtoUtils.toStateMachineLogEntryProto(clientRequest, null, null);
  this.stateMachineContext = stateMachineContext;
}
 
Example #7
Source File: TransactionContextImpl.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
@Override
public LogEntryProto initLogEntry(long term, long index) {
  Preconditions.assertTrue(serverRole == RaftPeerRole.LEADER);
  Preconditions.assertNull(logEntry, "logEntry");
  Objects.requireNonNull(smLogEntryProto, "smLogEntryProto == null");
  return logEntry = ServerProtoUtils.toLogEntryProto(smLogEntryProto, term, index);
}
 
Example #8
Source File: TransactionContextImpl.java    From ratis with Apache License 2.0 5 votes vote down vote up
@Override
public LogEntryProto initLogEntry(long term, long index) {
  Preconditions.assertTrue(serverRole == RaftPeerRole.LEADER);
  Preconditions.assertNull(logEntry, "logEntry");
  Objects.requireNonNull(smLogEntryProto, "smLogEntryProto == null");
  return logEntry = ServerProtoUtils.toLogEntryProto(smLogEntryProto, term, index);
}
 
Example #9
Source File: OzoneManagerRatisServer.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Set the current server role and the leader peer id.
 */
private void setServerRole(RaftPeerRole currentRole,
    RaftPeerId leaderPeerId) {
  this.roleCheckLock.writeLock().lock();
  try {
    this.cachedPeerRole = Optional.ofNullable(currentRole);
    this.cachedLeaderPeerId = Optional.ofNullable(leaderPeerId);
  } finally {
    this.roleCheckLock.writeLock().unlock();
  }
}
 
Example #10
Source File: OzoneManagerRatisServer.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Get the gorup info (peer role and leader peer id) from Ratis server and
 * update the OM server role.
 */
public void updateServerRole() {
  try {
    GroupInfoReply groupInfo = getGroupInfo();
    RoleInfoProto roleInfoProto = groupInfo.getRoleInfoProto();
    RaftPeerRole thisNodeRole = roleInfoProto.getRole();

    if (thisNodeRole.equals(RaftPeerRole.LEADER)) {
      setServerRole(thisNodeRole, raftPeerId);

    } else if (thisNodeRole.equals(RaftPeerRole.FOLLOWER)) {
      ByteString leaderNodeId = roleInfoProto.getFollowerInfo()
          .getLeaderInfo().getId().getId();
      // There may be a chance, here we get leaderNodeId as null. For
      // example, in 3 node OM Ratis, if 2 OM nodes are down, there will
      // be no leader.
      RaftPeerId leaderPeerId = null;
      if (leaderNodeId != null && !leaderNodeId.isEmpty()) {
        leaderPeerId = RaftPeerId.valueOf(leaderNodeId);
      }

      setServerRole(thisNodeRole, leaderPeerId);

    } else {
      setServerRole(thisNodeRole, null);

    }
  } catch (IOException e) {
    LOG.error("Failed to retrieve RaftPeerRole. Setting cached role to " +
        "{} and resetting leader info.", RaftPeerRole.UNRECOGNIZED, e);
    setServerRole(null, null);
  }
}
 
Example #11
Source File: OzoneManagerRatisServer.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Check the cached leader status.
 * @return true if cached role is Leader, false otherwise.
 */
private boolean checkCachedPeerRoleIsLeader() {
  this.roleCheckLock.readLock().lock();
  try {
    if (cachedPeerRole.isPresent() &&
        cachedPeerRole.get() == RaftPeerRole.LEADER) {
      return true;
    }
    return false;
  } finally {
    this.roleCheckLock.readLock().unlock();
  }
}
 
Example #12
Source File: RoleInfo.java    From ratis with Apache License 2.0 4 votes vote down vote up
RaftPeerRole getCurrentRole() {
  return role;
}
 
Example #13
Source File: RoleInfo.java    From ratis with Apache License 2.0 4 votes vote down vote up
boolean isFollower() {
  return role == RaftPeerRole.FOLLOWER;
}
 
Example #14
Source File: RoleInfo.java    From ratis with Apache License 2.0 4 votes vote down vote up
void transitionRole(RaftPeerRole newRole) {
  this.role = newRole;
  this.transitionTime.set(Timestamp.currentTime());
}
 
Example #15
Source File: RoleInfo.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
boolean isFollower() {
  return role == RaftPeerRole.FOLLOWER;
}
 
Example #16
Source File: RoleInfo.java    From ratis with Apache License 2.0 4 votes vote down vote up
boolean isCandidate() {
  return role == RaftPeerRole.CANDIDATE;
}
 
Example #17
Source File: TransactionContextImpl.java    From ratis with Apache License 2.0 4 votes vote down vote up
@Override
public RaftPeerRole getServerRole() {
  return serverRole;
}
 
Example #18
Source File: TransactionContextImpl.java    From ratis with Apache License 2.0 4 votes vote down vote up
/**
 * Construct a {@link TransactionContext} from a {@link LogEntryProto}.
 * Used by followers for applying committed entries to the state machine.
 * @param logEntry the log entry to be applied
 */
public TransactionContextImpl(RaftPeerRole serverRole, StateMachine stateMachine, LogEntryProto logEntry) {
  this(serverRole, stateMachine);
  this.logEntry = logEntry;
  this.smLogEntryProto = logEntry.getStateMachineLogEntry();
}
 
Example #19
Source File: TransactionContextImpl.java    From ratis with Apache License 2.0 4 votes vote down vote up
private TransactionContextImpl(RaftPeerRole serverRole, StateMachine stateMachine) {
  this.serverRole = serverRole;
  this.stateMachine = stateMachine;
}
 
Example #20
Source File: TransactionContext.java    From ratis with Apache License 2.0 4 votes vote down vote up
public Builder setServerRole(RaftPeerRole serverRole) {
  this.serverRole = serverRole;
  return this;
}
 
Example #21
Source File: TransactionContext.java    From ratis with Apache License 2.0 4 votes vote down vote up
/** @return the role of the server when this context is created. */
RaftPeerRole getServerRole();
 
Example #22
Source File: RoleInfo.java    From ratis with Apache License 2.0 4 votes vote down vote up
boolean isLeader() {
  return role == RaftPeerRole.LEADER;
}
 
Example #23
Source File: RaftServerTestUtil.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
public static RaftPeerRole getRole(RaftServerImpl server) {
  return server.getRole().getRaftPeerRole();
}
 
Example #24
Source File: RoleInfo.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
boolean isLeader() {
  return role == RaftPeerRole.LEADER;
}
 
Example #25
Source File: RoleInfo.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
boolean isCandidate() {
  return role == RaftPeerRole.CANDIDATE;
}
 
Example #26
Source File: ContainerStateMachine.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Override
public TransactionContext startTransaction(RaftClientRequest request)
    throws IOException {
  long startTime = Time.monotonicNowNanos();
  final ContainerCommandRequestProto proto =
      message2ContainerCommandRequestProto(request.getMessage());
  Preconditions.checkArgument(request.getRaftGroupId().equals(gid));
  try {
    dispatcher.validateContainerCommand(proto);
  } catch (IOException ioe) {
    if (ioe instanceof ContainerNotOpenException) {
      metrics.incNumContainerNotOpenVerifyFailures();
    } else {
      metrics.incNumStartTransactionVerifyFailures();
      LOG.error("startTransaction validation failed on leader", ioe);
    }
    TransactionContext ctxt = TransactionContext.newBuilder()
        .setClientRequest(request)
        .setStateMachine(this)
        .setServerRole(RaftPeerRole.LEADER)
        .build();
    ctxt.setException(ioe);
    return ctxt;
  }
  if (proto.getCmdType() == Type.WriteChunk) {
    final WriteChunkRequestProto write = proto.getWriteChunk();
    // create the log entry proto
    final WriteChunkRequestProto commitWriteChunkProto =
        WriteChunkRequestProto.newBuilder()
            .setBlockID(write.getBlockID())
            .setChunkData(write.getChunkData())
            // skipping the data field as it is
            // already set in statemachine data proto
            .build();
    ContainerCommandRequestProto commitContainerCommandProto =
        ContainerCommandRequestProto
            .newBuilder(proto)
            .setWriteChunk(commitWriteChunkProto)
            .setTraceID(proto.getTraceID())
            .build();

    return TransactionContext.newBuilder()
        .setClientRequest(request)
        .setStateMachine(this)
        .setServerRole(RaftPeerRole.LEADER)
        .setStateMachineContext(startTime)
        .setStateMachineData(write.getData())
        .setLogData(commitContainerCommandProto.toByteString())
        .build();
  } else {
    return TransactionContext.newBuilder()
        .setClientRequest(request)
        .setStateMachine(this)
        .setServerRole(RaftPeerRole.LEADER)
        .setStateMachineContext(startTime)
        .setLogData(proto.toByteString())
        .build();
  }

}
 
Example #27
Source File: RoleInfo.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
RaftPeerRole getCurrentRole() {
  return role;
}
 
Example #28
Source File: RoleInfo.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
void transitionRole(RaftPeerRole newRole) {
  this.role = newRole;
  this.transitionTime.set(Timestamp.currentTime());
}
 
Example #29
Source File: RoleInfo.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
RaftPeerRole getRaftPeerRole() {
  return role;
}
 
Example #30
Source File: TransactionContextImpl.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
@Override
public RaftPeerRole getServerRole() {
  return serverRole;
}