Search in sources :

Example 1 with Task

use of io.dingodb.raft.entity.Task in project dingo by dingodb.

the class RaftRawKVStore method applyOperation.

private void applyOperation(final KVOperation op, final KVStoreClosure closure) {
    if (!isLeader()) {
        closure.setError(Errors.NOT_LEADER);
        closure.run(new Status(RaftError.EPERM, "Not leader"));
        return;
    }
    final Task task = new Task();
    task.setData(ByteBuffer.wrap(Serializers.getDefault().writeObject(op)));
    task.setDone(new KVClosureAdapter(closure, op));
    this.node.apply(task);
}
Also used : Status(io.dingodb.raft.Status) Task(io.dingodb.raft.entity.Task)

Example 2 with Task

use of io.dingodb.raft.entity.Task in project dingo by dingodb.

the class NodeImpl method apply.

@Override
public void apply(final Task task) {
    if (this.shutdownLatch != null) {
        Utils.runClosureInThread(task.getDone(), new Status(RaftError.ENODESHUTDOWN, "Node is shutting down."));
        throw new IllegalStateException("Node is shutting down");
    }
    Requires.requireNonNull(task, "Null task");
    final LogEntry entry = new LogEntry();
    entry.setData(task.getData());
    int retryTimes = 0;
    try {
        final EventTranslator<LogEntryAndClosure> translator = (event, sequence) -> {
            event.reset();
            event.done = task.getDone();
            event.entry = entry;
            event.expectedTerm = task.getExpectedTerm();
        };
        this.applyQueue.publishEvent(translator);
    /*
            while (true) {
                if (this.applyQueue.tryPublishEvent(translator)) {
                    break;
                } else {
                    retryTimes++;
                    if (retryTimes > MAX_APPLY_RETRY_TIMES) {
                        Utils.runClosureInThread(task.getDone(),
                            new Status(RaftError.EBUSY, "Node is busy, has too many tasks."));
                        LOG.warn("Node {} applyQueue is overload.", getNodeId());
                        this.metrics.recordTimes("apply-task-overload-times", 1);
                        return;
                    }
                    ThreadHelper.onSpinWait();
                }
            }
             */
    } catch (final Exception e) {
        LOG.error("Fail to apply task.", e);
        Utils.runClosureInThread(task.getDone(), new Status(RaftError.EPERM, "Node is down."));
    }
}
Also used : Status(io.dingodb.raft.Status) FSMCallerOptions(io.dingodb.raft.option.FSMCallerOptions) RpcRequestClosure(io.dingodb.raft.rpc.RpcRequestClosure) StringUtils(org.apache.commons.lang.StringUtils) Describer(io.dingodb.raft.util.Describer) LongHeldDetectingReadWriteLock(io.dingodb.raft.util.concurrent.LongHeldDetectingReadWriteLock) ThreadHelper(io.dingodb.raft.util.ThreadHelper) LogManager(io.dingodb.raft.storage.LogManager) RaftClientService(io.dingodb.raft.rpc.RaftClientService) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) SynchronizedClosure(io.dingodb.raft.closure.SynchronizedClosure) LogManagerOptions(io.dingodb.raft.option.LogManagerOptions) Set(java.util.Set) Configuration(io.dingodb.raft.conf.Configuration) Utils(io.dingodb.raft.util.Utils) RaftOutter(io.dingodb.raft.entity.RaftOutter) EnumOutter(io.dingodb.raft.entity.EnumOutter) CountDownLatch(java.util.concurrent.CountDownLatch) RaftTimerFactory(io.dingodb.raft.util.timer.RaftTimerFactory) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) LogId(io.dingodb.raft.entity.LogId) JRaftServiceLoader(io.dingodb.raft.util.JRaftServiceLoader) SystemPropertyUtil(io.dingodb.raft.util.SystemPropertyUtil) JRaftUtils(io.dingodb.raft.JRaftUtils) LogExceptionHandler(io.dingodb.raft.util.LogExceptionHandler) ArrayList(java.util.ArrayList) JRaftServiceFactory(io.dingodb.raft.JRaftServiceFactory) ReadOnlyOption(io.dingodb.raft.option.ReadOnlyOption) BootstrapOptions(io.dingodb.raft.option.BootstrapOptions) LogStorage(io.dingodb.raft.storage.LogStorage) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) EventHandler(com.lmax.disruptor.EventHandler) LinkedHashSet(java.util.LinkedHashSet) DisruptorMetricSet(io.dingodb.raft.util.DisruptorMetricSet) DefaultRaftClientService(io.dingodb.raft.rpc.impl.core.DefaultRaftClientService) SnapshotExecutorImpl(io.dingodb.raft.storage.snapshot.SnapshotExecutorImpl) NodeManager(io.dingodb.raft.NodeManager) BallotBoxOptions(io.dingodb.raft.option.BallotBoxOptions) Lock(java.util.concurrent.locks.Lock) Ballot(io.dingodb.raft.entity.Ballot) PeerId(io.dingodb.raft.entity.PeerId) ReadOnlyServiceOptions(io.dingodb.raft.option.ReadOnlyServiceOptions) ConfigurationManager(io.dingodb.raft.conf.ConfigurationManager) SnapshotExecutor(io.dingodb.raft.storage.SnapshotExecutor) Disruptor(com.lmax.disruptor.dsl.Disruptor) RaftServerService(io.dingodb.raft.rpc.RaftServerService) ThreadId(io.dingodb.raft.util.ThreadId) ScheduledFuture(java.util.concurrent.ScheduledFuture) LoggerFactory(org.slf4j.LoggerFactory) ClosureQueueImpl(io.dingodb.raft.closure.ClosureQueueImpl) ByteBuffer(java.nio.ByteBuffer) RaftMetaStorageOptions(io.dingodb.raft.option.RaftMetaStorageOptions) SignalHelper(io.dingodb.raft.util.SignalHelper) BlockingWaitStrategy(com.lmax.disruptor.BlockingWaitStrategy) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CatchUpClosure(io.dingodb.raft.closure.CatchUpClosure) Task(io.dingodb.raft.entity.Task) RaftOptions(io.dingodb.raft.option.RaftOptions) Collection(java.util.Collection) Status(io.dingodb.raft.Status) ReplicatorGroupOptions(io.dingodb.raft.option.ReplicatorGroupOptions) Collectors(java.util.stream.Collectors) FSMCaller(io.dingodb.raft.FSMCaller) DisruptorBuilder(io.dingodb.raft.util.DisruptorBuilder) RpcResponseClosureAdapter(io.dingodb.raft.rpc.RpcResponseClosureAdapter) List(java.util.List) NodeId(io.dingodb.raft.entity.NodeId) RpcResponseClosure(io.dingodb.raft.rpc.RpcResponseClosure) RaftException(io.dingodb.raft.error.RaftException) Requires(io.dingodb.raft.util.Requires) RaftError(io.dingodb.raft.error.RaftError) UserLog(io.dingodb.raft.entity.UserLog) LogEntry(io.dingodb.raft.entity.LogEntry) HashSet(java.util.HashSet) RaftMetaStorage(io.dingodb.raft.storage.RaftMetaStorage) SnapshotExecutorOptions(io.dingodb.raft.option.SnapshotExecutorOptions) ConfigurationEntry(io.dingodb.raft.conf.ConfigurationEntry) ReadOnlyService(io.dingodb.raft.ReadOnlyService) OnlyForTest(io.dingodb.raft.util.OnlyForTest) ReadIndexClosure(io.dingodb.raft.closure.ReadIndexClosure) LogIndexOutOfBoundsException(io.dingodb.raft.error.LogIndexOutOfBoundsException) Logger(org.slf4j.Logger) NamedThreadFactory(io.dingodb.raft.util.NamedThreadFactory) ClosureQueue(io.dingodb.raft.closure.ClosureQueue) RingBuffer(com.lmax.disruptor.RingBuffer) Closure(io.dingodb.raft.Closure) ProducerType(com.lmax.disruptor.dsl.ProducerType) Node(io.dingodb.raft.Node) Platform(io.dingodb.raft.util.Platform) NodeOptions(io.dingodb.raft.option.NodeOptions) LogNotFoundException(io.dingodb.raft.error.LogNotFoundException) ReplicatorGroup(io.dingodb.raft.ReplicatorGroup) TimeUnit(java.util.concurrent.TimeUnit) JRaftSignalHandler(io.dingodb.raft.util.JRaftSignalHandler) RpcFactoryHelper(io.dingodb.raft.util.RpcFactoryHelper) EventTranslator(com.lmax.disruptor.EventTranslator) LogManagerImpl(io.dingodb.raft.storage.impl.LogManagerImpl) RepeatedTimer(io.dingodb.raft.util.RepeatedTimer) Message(com.google.protobuf.Message) RpcRequests(io.dingodb.raft.rpc.RpcRequests) LeaderChangeContext(io.dingodb.raft.entity.LeaderChangeContext) EventFactory(com.lmax.disruptor.EventFactory) LogEntry(io.dingodb.raft.entity.LogEntry) RaftException(io.dingodb.raft.error.RaftException) LogIndexOutOfBoundsException(io.dingodb.raft.error.LogIndexOutOfBoundsException) LogNotFoundException(io.dingodb.raft.error.LogNotFoundException)

Example 3 with Task

use of io.dingodb.raft.entity.Task in project dingo by dingodb.

the class NodeImpl method executeApplyingTasks.

private void executeApplyingTasks(final List<LogEntryAndClosure> tasks) {
    this.writeLock.lock();
    try {
        final int size = tasks.size();
        if (this.state != State.STATE_LEADER) {
            final Status st = new Status();
            if (this.state != State.STATE_TRANSFERRING) {
                st.setError(RaftError.EPERM, "Is not leader.");
            } else {
                st.setError(RaftError.EBUSY, "Is transferring leadership.");
            }
            LOG.debug("Node {} can't apply, status={}.", getNodeId(), st);
            final List<Closure> dones = tasks.stream().map(ele -> ele.done).collect(Collectors.toList());
            Utils.runInThread(() -> {
                for (final Closure done : dones) {
                    done.run(st);
                }
            });
            return;
        }
        final List<LogEntry> entries = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            final LogEntryAndClosure task = tasks.get(i);
            if (task.expectedTerm != -1 && task.expectedTerm != this.currTerm) {
                LOG.debug("Node {} can't apply task whose expectedTerm={} doesn't match currTerm={}.", getNodeId(), task.expectedTerm, this.currTerm);
                if (task.done != null) {
                    final Status st = new Status(RaftError.EPERM, "expected_term=%d doesn't match current_term=%d", task.expectedTerm, this.currTerm);
                    Utils.runClosureInThread(task.done, st);
                    task.reset();
                }
                continue;
            }
            if (!this.ballotBox.appendPendingTask(this.conf.getConf(), this.conf.isStable() ? null : this.conf.getOldConf(), task.done)) {
                Utils.runClosureInThread(task.done, new Status(RaftError.EINTERNAL, "Fail to append task."));
                task.reset();
                continue;
            }
            // set task entry info before adding to list.
            task.entry.getId().setTerm(this.currTerm);
            task.entry.setType(EnumOutter.EntryType.ENTRY_TYPE_DATA);
            entries.add(task.entry);
            task.reset();
        }
        this.logManager.appendEntries(entries, new LeaderStableClosure(entries));
        // update conf.first
        checkAndSetConfiguration(true);
    } finally {
        this.writeLock.unlock();
    }
}
Also used : Status(io.dingodb.raft.Status) FSMCallerOptions(io.dingodb.raft.option.FSMCallerOptions) RpcRequestClosure(io.dingodb.raft.rpc.RpcRequestClosure) StringUtils(org.apache.commons.lang.StringUtils) Describer(io.dingodb.raft.util.Describer) LongHeldDetectingReadWriteLock(io.dingodb.raft.util.concurrent.LongHeldDetectingReadWriteLock) ThreadHelper(io.dingodb.raft.util.ThreadHelper) LogManager(io.dingodb.raft.storage.LogManager) RaftClientService(io.dingodb.raft.rpc.RaftClientService) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) SynchronizedClosure(io.dingodb.raft.closure.SynchronizedClosure) LogManagerOptions(io.dingodb.raft.option.LogManagerOptions) Set(java.util.Set) Configuration(io.dingodb.raft.conf.Configuration) Utils(io.dingodb.raft.util.Utils) RaftOutter(io.dingodb.raft.entity.RaftOutter) EnumOutter(io.dingodb.raft.entity.EnumOutter) CountDownLatch(java.util.concurrent.CountDownLatch) RaftTimerFactory(io.dingodb.raft.util.timer.RaftTimerFactory) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) LogId(io.dingodb.raft.entity.LogId) JRaftServiceLoader(io.dingodb.raft.util.JRaftServiceLoader) SystemPropertyUtil(io.dingodb.raft.util.SystemPropertyUtil) JRaftUtils(io.dingodb.raft.JRaftUtils) LogExceptionHandler(io.dingodb.raft.util.LogExceptionHandler) ArrayList(java.util.ArrayList) JRaftServiceFactory(io.dingodb.raft.JRaftServiceFactory) ReadOnlyOption(io.dingodb.raft.option.ReadOnlyOption) BootstrapOptions(io.dingodb.raft.option.BootstrapOptions) LogStorage(io.dingodb.raft.storage.LogStorage) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) EventHandler(com.lmax.disruptor.EventHandler) LinkedHashSet(java.util.LinkedHashSet) DisruptorMetricSet(io.dingodb.raft.util.DisruptorMetricSet) DefaultRaftClientService(io.dingodb.raft.rpc.impl.core.DefaultRaftClientService) SnapshotExecutorImpl(io.dingodb.raft.storage.snapshot.SnapshotExecutorImpl) NodeManager(io.dingodb.raft.NodeManager) BallotBoxOptions(io.dingodb.raft.option.BallotBoxOptions) Lock(java.util.concurrent.locks.Lock) Ballot(io.dingodb.raft.entity.Ballot) PeerId(io.dingodb.raft.entity.PeerId) ReadOnlyServiceOptions(io.dingodb.raft.option.ReadOnlyServiceOptions) ConfigurationManager(io.dingodb.raft.conf.ConfigurationManager) SnapshotExecutor(io.dingodb.raft.storage.SnapshotExecutor) Disruptor(com.lmax.disruptor.dsl.Disruptor) RaftServerService(io.dingodb.raft.rpc.RaftServerService) ThreadId(io.dingodb.raft.util.ThreadId) ScheduledFuture(java.util.concurrent.ScheduledFuture) LoggerFactory(org.slf4j.LoggerFactory) ClosureQueueImpl(io.dingodb.raft.closure.ClosureQueueImpl) ByteBuffer(java.nio.ByteBuffer) RaftMetaStorageOptions(io.dingodb.raft.option.RaftMetaStorageOptions) SignalHelper(io.dingodb.raft.util.SignalHelper) BlockingWaitStrategy(com.lmax.disruptor.BlockingWaitStrategy) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CatchUpClosure(io.dingodb.raft.closure.CatchUpClosure) Task(io.dingodb.raft.entity.Task) RaftOptions(io.dingodb.raft.option.RaftOptions) Collection(java.util.Collection) Status(io.dingodb.raft.Status) ReplicatorGroupOptions(io.dingodb.raft.option.ReplicatorGroupOptions) Collectors(java.util.stream.Collectors) FSMCaller(io.dingodb.raft.FSMCaller) DisruptorBuilder(io.dingodb.raft.util.DisruptorBuilder) RpcResponseClosureAdapter(io.dingodb.raft.rpc.RpcResponseClosureAdapter) List(java.util.List) NodeId(io.dingodb.raft.entity.NodeId) RpcResponseClosure(io.dingodb.raft.rpc.RpcResponseClosure) RaftException(io.dingodb.raft.error.RaftException) Requires(io.dingodb.raft.util.Requires) RaftError(io.dingodb.raft.error.RaftError) UserLog(io.dingodb.raft.entity.UserLog) LogEntry(io.dingodb.raft.entity.LogEntry) HashSet(java.util.HashSet) RaftMetaStorage(io.dingodb.raft.storage.RaftMetaStorage) SnapshotExecutorOptions(io.dingodb.raft.option.SnapshotExecutorOptions) ConfigurationEntry(io.dingodb.raft.conf.ConfigurationEntry) ReadOnlyService(io.dingodb.raft.ReadOnlyService) OnlyForTest(io.dingodb.raft.util.OnlyForTest) ReadIndexClosure(io.dingodb.raft.closure.ReadIndexClosure) LogIndexOutOfBoundsException(io.dingodb.raft.error.LogIndexOutOfBoundsException) Logger(org.slf4j.Logger) NamedThreadFactory(io.dingodb.raft.util.NamedThreadFactory) ClosureQueue(io.dingodb.raft.closure.ClosureQueue) RingBuffer(com.lmax.disruptor.RingBuffer) Closure(io.dingodb.raft.Closure) ProducerType(com.lmax.disruptor.dsl.ProducerType) Node(io.dingodb.raft.Node) Platform(io.dingodb.raft.util.Platform) NodeOptions(io.dingodb.raft.option.NodeOptions) LogNotFoundException(io.dingodb.raft.error.LogNotFoundException) ReplicatorGroup(io.dingodb.raft.ReplicatorGroup) TimeUnit(java.util.concurrent.TimeUnit) JRaftSignalHandler(io.dingodb.raft.util.JRaftSignalHandler) RpcFactoryHelper(io.dingodb.raft.util.RpcFactoryHelper) EventTranslator(com.lmax.disruptor.EventTranslator) LogManagerImpl(io.dingodb.raft.storage.impl.LogManagerImpl) RepeatedTimer(io.dingodb.raft.util.RepeatedTimer) Message(com.google.protobuf.Message) RpcRequests(io.dingodb.raft.rpc.RpcRequests) LeaderChangeContext(io.dingodb.raft.entity.LeaderChangeContext) EventFactory(com.lmax.disruptor.EventFactory) RpcRequestClosure(io.dingodb.raft.rpc.RpcRequestClosure) SynchronizedClosure(io.dingodb.raft.closure.SynchronizedClosure) CatchUpClosure(io.dingodb.raft.closure.CatchUpClosure) RpcResponseClosure(io.dingodb.raft.rpc.RpcResponseClosure) ReadIndexClosure(io.dingodb.raft.closure.ReadIndexClosure) Closure(io.dingodb.raft.Closure) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) LogEntry(io.dingodb.raft.entity.LogEntry)

Example 4 with Task

use of io.dingodb.raft.entity.Task in project dingo by dingodb.

the class StoreEngine method applySplit.

public void applySplit(final String regionId, final String newRegionId, final KVStoreClosure closure) {
    Requires.requireNonNull(regionId, "regionId");
    Requires.requireNonNull(newRegionId, "newRegionId");
    if (this.regionEngineTable.containsKey(newRegionId)) {
        closure.setError(Errors.CONFLICT_REGION_ID);
        closure.run(new Status(-1, "Conflict region id %d", newRegionId));
        return;
    }
    if (!this.splitting.compareAndSet(false, true)) {
        closure.setError(Errors.SERVER_BUSY);
        closure.run(new Status(-1, "Server is busy now"));
        return;
    }
    final RegionEngine parentEngine = getRegionEngine(regionId);
    if (parentEngine == null) {
        closure.setError(Errors.NO_REGION_FOUND);
        closure.run(new Status(-1, "RegionEngine[%s] not found", regionId));
        this.splitting.set(false);
        return;
    }
    if (!parentEngine.isLeader()) {
        closure.setError(Errors.NOT_LEADER);
        closure.run(new Status(-1, "RegionEngine[%s] not leader", regionId));
        this.splitting.set(false);
        return;
    }
    final Region parentRegion = parentEngine.getRegion();
    final byte[] startKey = BytesUtil.nullToEmpty(parentRegion.getStartKey());
    final byte[] endKey = parentRegion.getEndKey();
    ApproximateKVStats stats = this.rawKVStore.getApproximateKVStatsInRange(startKey, endKey);
    final long approximateKeys = stats.keysCnt;
    final long approximateBytes = stats.sizeInBytes / 1024 / 1024;
    final long leastKeysOnSplit = this.storeOpts.getLeastKeysOnSplit();
    boolean isSplitOK = (approximateBytes >= 64 || approximateKeys > leastKeysOnSplit);
    LOG.info("Region:{} Split Condition is {}!. Disk Used:{} >= 64M, Write Keys:{} >= Expected Keys:{}", parentEngine, isSplitOK, approximateBytes, approximateKeys, leastKeysOnSplit);
    if (!isSplitOK) {
        closure.setError(Errors.TOO_SMALL_TO_SPLIT);
        closure.run(new Status(-1, "RegionEngine[%s]'s split condition is not OK!. " + "Write Keys:%d bytes(M): %d, Expected: keys:%d, bytes: 64M", regionId, approximateKeys, approximateBytes, leastKeysOnSplit));
        this.splitting.set(false);
        return;
    }
    final byte[] splitKey = this.rawKVStore.jumpOver(startKey, approximateKeys >> 1);
    if (splitKey == null) {
        closure.setError(Errors.STORAGE_ERROR);
        closure.run(new Status(-1, "Fail to scan split key"));
        this.splitting.set(false);
        return;
    }
    final KVOperation op = KVOperation.createRangeSplit(splitKey, regionId, newRegionId);
    LOG.info("Store receive region split instruction: Old Region:{}, oldStartKey:{}, oldEndKey:{}, " + "approximateKeys:{}, newRegionId:{}, splitKey:{}", parentEngine.toString(), startKey != null ? BytesUtil.toHex(startKey) : "null", endKey != null ? BytesUtil.toHex(endKey) : "null", approximateKeys, newRegionId, splitKey != null ? BytesUtil.toHex(splitKey) : "null");
    final Task task = new Task();
    task.setData(ByteBuffer.wrap(Serializers.getDefault().writeObject(op)));
    task.setDone(new KVClosureAdapter(closure, op));
    parentEngine.getNode().apply(task);
}
Also used : Status(io.dingodb.raft.Status) Task(io.dingodb.raft.entity.Task) KVClosureAdapter(io.dingodb.store.row.storage.KVClosureAdapter) KVOperation(io.dingodb.store.row.storage.KVOperation) Region(io.dingodb.store.row.metadata.Region)

Aggregations

Status (io.dingodb.raft.Status)4 Task (io.dingodb.raft.entity.Task)4 Message (com.google.protobuf.Message)2 BlockingWaitStrategy (com.lmax.disruptor.BlockingWaitStrategy)2 EventFactory (com.lmax.disruptor.EventFactory)2 EventHandler (com.lmax.disruptor.EventHandler)2 EventTranslator (com.lmax.disruptor.EventTranslator)2 RingBuffer (com.lmax.disruptor.RingBuffer)2 Disruptor (com.lmax.disruptor.dsl.Disruptor)2 ProducerType (com.lmax.disruptor.dsl.ProducerType)2 Closure (io.dingodb.raft.Closure)2 FSMCaller (io.dingodb.raft.FSMCaller)2 JRaftServiceFactory (io.dingodb.raft.JRaftServiceFactory)2 JRaftUtils (io.dingodb.raft.JRaftUtils)2 Node (io.dingodb.raft.Node)2 NodeManager (io.dingodb.raft.NodeManager)2 ReadOnlyService (io.dingodb.raft.ReadOnlyService)2 ReplicatorGroup (io.dingodb.raft.ReplicatorGroup)2 CatchUpClosure (io.dingodb.raft.closure.CatchUpClosure)2 ClosureQueue (io.dingodb.raft.closure.ClosureQueue)2