private State serverState() { if (mServer.state() == CopycatServer.State.LEADER) { return State.PRIMARY; } else { return State.SECONDARY; } }
@Override public synchronized void stopInternal() throws InterruptedException, IOException { LOG.info("Shutting down raft journal"); mRaftJournalWriter.close(); try { mServer.shutdown().get(2, TimeUnit.SECONDS); } catch (ExecutionException e) { throw new RuntimeException("Failed to shut down Raft server", e); } catch (TimeoutException e) { LOG.info("Timed out shutting down raft server"); } LOG.info("Journal shutdown complete"); }
private synchronized void initServer() { LOG.debug("Creating journal with max segment size {}", mConf.getMaxLogSize()); Storage storage = Storage.builder() .withDirectory(mConf.getPath()) .withStorageLevel(StorageLevel.valueOf(mConf.getStorageLevel().name())) .withMinorCompactionInterval(Duration.ofDays(200)) .withMaxSegmentSize((int) mConf.getMaxLogSize()) .build(); if (mStateMachine != null) { mStateMachine.close(); mServer = CopycatServer.builder(getLocalAddress(mConf)) .withStorage(storage) .withElectionTimeout(Duration.ofMillis(mConf.getElectionTimeoutMs())) .withHeartbeatInterval(Duration.ofMillis(mConf.getHeartbeatIntervalMs())) .withSnapshotAllowed(mSnapshotAllowed) .withSerializer(createSerializer()) .withTransport(new NettyTransport()) .withStateMachine(new OnceSupplier<>(mStateMachine)) .build(); mPrimarySelector.init(mServer);
int port = socket.getLocalPort(); CopycatServer server = CopycatServer .builder(new Address(NetworkAddressUtils.getConnectHost(ServiceType.MASTER_RAFT, ServerConfiguration.global()), port)) .withSnapshotAllowed(new AtomicBoolean(false)) .withTransport(new NettyTransport()) .withSerializer(RaftJournalSystem.createSerializer()) .withType(Type.PASSIVE) .withStorage(Storage.builder().withStorageLevel(StorageLevel.MEMORY).build()) .withStateMachine(() -> new EchoJournalStateMachine(lastUpdate)).build(); server.join(RaftJournalConfiguration.defaults(serviceType) .getClusterAddresses().stream() .map(addr -> new Address(addr.getHostName(), addr.getPort())) CommonUtils.sleepMs(100); server.leave().get(); } catch (Exception e) { System.out.println("Failed to read journal");
/** * Applies a journal entry commit to the state machine. * * This method is automatically discovered by the Copycat framework. * * @param commit the commit */ public synchronized void applyJournalEntryCommand(Commit<JournalEntryCommand> commit) { JournalEntry entry; try { entry = JournalEntry.parseFrom(commit.command().getSerializedJournalEntry()); } catch (Exception e) { ProcessUtils.fatalError(LOG, e, "Encountered invalid journal entry in commit: {}.", commit); System.exit(-1); throw new IllegalStateException(e); // We should never reach here. } try { applyEntry(entry); } finally { Preconditions.checkState(commit.index() > mLastAppliedCommitIndex); mLastAppliedCommitIndex = commit.index(); commit.close(); } }
mServer.shutdown().get(); } catch (ExecutionException e) { LOG.error("Fatal error: failed to leave Raft cluster while stepping down", e); LOG.info("Bootstrapping new Raft server"); try { mServer.bootstrap(getClusterAddresses(mConf)).get(); } catch (InterruptedException e) { Thread.currentThread().interrupt();
/** * Registers an operation with a void return value. */ @SuppressWarnings("unchecked") private void registerVoidMethod(Class type, Method method) { executor.register(type, wrapVoidMethod(method)); }
/** * Registers an operation with a non-void return value. */ @SuppressWarnings("unchecked") private void registerValueMethod(Class type, Method method) { executor.register(type, wrapValueMethod(method)); }
@Override public synchronized void startInternal() throws InterruptedException, IOException { LOG.info("Starting Raft journal system"); long startTime = System.currentTimeMillis(); try { mServer.bootstrap(getClusterAddresses(mConf)).get(); } catch (ExecutionException e) { String errorMessage = ExceptionMessage.FAILED_RAFT_BOOTSTRAP.getMessage( Arrays.toString(getClusterAddresses(mConf).toArray()), e.getCause().toString()); throw new IOException(errorMessage, e.getCause()); } LOG.info("Started Raft Journal System in {}ms. Cluster addresses: {}. Local address: {}", System.currentTimeMillis() - startTime, getClusterAddresses(mConf), getLocalAddress(mConf)); }
/** * Applies a journal entry commit to the state machine. * * This method is automatically discovered by the Copycat framework. * * @param commit the commit */ public void applyJournalEntryCommand(Commit<JournalEntryCommand> commit) { JournalEntry entry; try { entry = JournalEntry.parseFrom(commit.command().getSerializedJournalEntry()); } catch (Throwable t) { ProcessUtils.fatalError(LOG, t, "Encountered invalid journal entry in commit: {}.", commit); throw new IllegalStateException(); } applyEntry(entry); }
/** * Initializes the state machine. */ private void init() { stateMachine.init(executor); }
/** * @param server reference to the server backing this selector */ public void init(CopycatServer server) { mServer = Preconditions.checkNotNull(server, "server"); if (mStateListener != null) { mStateListener.close(); } // We must register the callback before initializing mState in case the state changes // immediately after initializing mState. mStateListener = server.onStateChange(state -> { setState(serverState()); }); setState(serverState()); }
/** * Configures the state machine. * <p> * By default, this method will configure state machine operations by extracting public methods with * a single {@link Commit} parameter via reflection. Override this method to explicitly register * state machine operations via the provided {@link StateMachineExecutor}. * * @param executor The state machine executor. */ protected void configure(StateMachineExecutor executor) { registerOperations(); }
public static void uncheck(ThrowableRunnable runnable) { try { runnable.run(); } catch (Throwable e) { throw new UncheckedException(e); } } }
/** * Registers an operation with a void return value. */ @SuppressWarnings("unchecked") private void registerVoidMethod(Class type, Method method) { executor.register(type, wrapVoidMethod(method)); }
/** * Registers an operation with a non-void return value. */ @SuppressWarnings("unchecked") private void registerValueMethod(Class type, Method method) { executor.register(type, wrapValueMethod(method)); }
/** * Registers an operation with a void return value. */ @SuppressWarnings("unchecked") private void registerVoidMethod(Class type, Method method) { executor.register(type, wrapVoidMethod(method)); }
/** * Registers an operation with a non-void return value. */ @SuppressWarnings("unchecked") private void registerValueMethod(Class type, Method method) { executor.register(type, wrapValueMethod(method)); }