Search in sources :

Example 16 with Region

use of com.alipay.sofa.jraft.rhea.metadata.Region in project sofa-jraft by sofastack.

the class DefaultRheaKVStore method internalContainsKey.

private void internalContainsKey(final byte[] key, final CompletableFuture<Boolean> future, final int retriesLeft, final Errors lastCause) {
    final Region region = this.pdClient.findRegionByKey(key, ErrorsHelper.isInvalidEpoch(lastCause));
    final RegionEngine regionEngine = getRegionEngine(region.getId(), true);
    final RetryRunner retryRunner = retryCause -> internalContainsKey(key, future, retriesLeft - 1, retryCause);
    final FailoverClosure<Boolean> closure = new FailoverClosureImpl<>(future, retriesLeft, retryRunner);
    if (regionEngine != null) {
        if (ensureOnValidEpoch(region, regionEngine, closure)) {
            getRawKVStore(regionEngine).containsKey(key, closure);
        }
    } else {
        final ContainsKeyRequest request = new ContainsKeyRequest();
        request.setKey(key);
        request.setRegionId(region.getId());
        request.setRegionEpoch(region.getRegionEpoch());
        this.rheaKVRpcService.callAsyncWithRpc(request, closure, lastCause);
    }
}
Also used : NamedThreadFactory(com.alipay.sofa.jraft.rhea.util.concurrent.NamedThreadFactory) PlacementDriverClient(com.alipay.sofa.jraft.rhea.client.pd.PlacementDriverClient) BatchingOptions(com.alipay.sofa.jraft.rhea.options.BatchingOptions) LoggerFactory(org.slf4j.LoggerFactory) FailoverClosure(com.alipay.sofa.jraft.rhea.client.failover.FailoverClosure) ExtSerializerSupports(com.alipay.sofa.jraft.rhea.rpc.ExtSerializerSupports) Region(com.alipay.sofa.jraft.rhea.metadata.Region) Lists(com.alipay.sofa.jraft.rhea.util.Lists) ListFailoverFuture(com.alipay.sofa.jraft.rhea.client.failover.impl.ListFailoverFuture) DescriberManager(com.alipay.sofa.jraft.rhea.DescriberManager) Map(java.util.Map) Constants(com.alipay.sofa.jraft.rhea.util.Constants) ApiExceptionHelper(com.alipay.sofa.jraft.rhea.errors.ApiExceptionHelper) ScanRequest(com.alipay.sofa.jraft.rhea.cmd.store.ScanRequest) Endpoint(com.alipay.sofa.jraft.util.Endpoint) MergeRequest(com.alipay.sofa.jraft.rhea.cmd.store.MergeRequest) ThreadFactory(java.util.concurrent.ThreadFactory) DeleteRequest(com.alipay.sofa.jraft.rhea.cmd.store.DeleteRequest) WaitStrategyType(com.alipay.sofa.jraft.rhea.util.concurrent.disruptor.WaitStrategyType) CASEntry(com.alipay.sofa.jraft.rhea.storage.CASEntry) DistributedLock(com.alipay.sofa.jraft.rhea.util.concurrent.DistributedLock) LogExceptionHandler(com.alipay.sofa.jraft.util.LogExceptionHandler) CASAllRequest(com.alipay.sofa.jraft.rhea.cmd.store.CASAllRequest) TaskDispatcher(com.alipay.sofa.jraft.rhea.util.concurrent.disruptor.TaskDispatcher) PeerId(com.alipay.sofa.jraft.entity.PeerId) RouteTable(com.alipay.sofa.jraft.RouteTable) PlacementDriverOptions(com.alipay.sofa.jraft.rhea.options.PlacementDriverOptions) KVStoreClosure(com.alipay.sofa.jraft.rhea.storage.KVStoreClosure) KVMetrics(com.alipay.sofa.jraft.rhea.metrics.KVMetrics) CompareAndPutRequest(com.alipay.sofa.jraft.rhea.cmd.store.CompareAndPutRequest) PutRequest(com.alipay.sofa.jraft.rhea.cmd.store.PutRequest) FakePlacementDriverClient(com.alipay.sofa.jraft.rhea.client.pd.FakePlacementDriverClient) ContainsKeyRequest(com.alipay.sofa.jraft.rhea.cmd.store.ContainsKeyRequest) RawKVStore(com.alipay.sofa.jraft.rhea.storage.RawKVStore) DeleteRangeRequest(com.alipay.sofa.jraft.rhea.cmd.store.DeleteRangeRequest) Strings(com.alipay.sofa.jraft.rhea.util.Strings) List(java.util.List) ResetSequenceRequest(com.alipay.sofa.jraft.rhea.cmd.store.ResetSequenceRequest) RegionEngine(com.alipay.sofa.jraft.rhea.RegionEngine) BoolFailoverFuture(com.alipay.sofa.jraft.rhea.client.failover.impl.BoolFailoverFuture) JRaftHelper(com.alipay.sofa.jraft.rhea.JRaftHelper) ZipStrategyManager(com.alipay.sofa.jraft.rhea.storage.zip.ZipStrategyManager) RemotePlacementDriverClient(com.alipay.sofa.jraft.rhea.client.pd.RemotePlacementDriverClient) FailoverClosureImpl(com.alipay.sofa.jraft.rhea.client.failover.impl.FailoverClosureImpl) RheaKVStoreOptions(com.alipay.sofa.jraft.rhea.options.RheaKVStoreOptions) Requires(com.alipay.sofa.jraft.util.Requires) Histogram(com.codahale.metrics.Histogram) RheaRuntimeException(com.alipay.sofa.jraft.rhea.errors.RheaRuntimeException) BatchPutRequest(com.alipay.sofa.jraft.rhea.cmd.store.BatchPutRequest) StackTraceUtil(com.alipay.sofa.jraft.rhea.util.StackTraceUtil) CompletableFuture(java.util.concurrent.CompletableFuture) FollowerStateListener(com.alipay.sofa.jraft.rhea.FollowerStateListener) Utils(com.alipay.sofa.jraft.util.Utils) ErrorsHelper(com.alipay.sofa.jraft.rhea.errors.ErrorsHelper) BatchDeleteRequest(com.alipay.sofa.jraft.rhea.cmd.store.BatchDeleteRequest) StateListenerContainer(com.alipay.sofa.jraft.rhea.StateListenerContainer) RetryCallable(com.alipay.sofa.jraft.rhea.client.failover.RetryCallable) GetRequest(com.alipay.sofa.jraft.rhea.cmd.store.GetRequest) Errors(com.alipay.sofa.jraft.rhea.errors.Errors) StateListener(com.alipay.sofa.jraft.rhea.StateListener) GetAndPutRequest(com.alipay.sofa.jraft.rhea.cmd.store.GetAndPutRequest) KeyLockRequest(com.alipay.sofa.jraft.rhea.cmd.store.KeyLockRequest) KeyUnlockRequest(com.alipay.sofa.jraft.rhea.cmd.store.KeyUnlockRequest) MapFailoverFuture(com.alipay.sofa.jraft.rhea.client.failover.impl.MapFailoverFuture) KVMetricNames(com.alipay.sofa.jraft.rhea.metrics.KVMetricNames) KVIterator(com.alipay.sofa.jraft.rhea.storage.KVIterator) NodeExecutor(com.alipay.sofa.jraft.rhea.storage.NodeExecutor) Dispatcher(com.alipay.sofa.jraft.rhea.util.concurrent.disruptor.Dispatcher) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) StoreEngine(com.alipay.sofa.jraft.rhea.StoreEngine) MultiGetRequest(com.alipay.sofa.jraft.rhea.cmd.store.MultiGetRequest) EventHandler(com.lmax.disruptor.EventHandler) PutIfAbsentRequest(com.alipay.sofa.jraft.rhea.cmd.store.PutIfAbsentRequest) Logger(org.slf4j.Logger) RetryRunner(com.alipay.sofa.jraft.rhea.client.failover.RetryRunner) GetSequenceRequest(com.alipay.sofa.jraft.rhea.cmd.store.GetSequenceRequest) RingBuffer(com.lmax.disruptor.RingBuffer) AffinityNamedThreadFactory(com.alipay.sofa.jraft.rhea.util.concurrent.AffinityNamedThreadFactory) ListRetryCallable(com.alipay.sofa.jraft.rhea.client.failover.ListRetryCallable) Status(com.alipay.sofa.jraft.Status) ByteArray(com.alipay.sofa.jraft.rhea.util.ByteArray) NodeExecuteRequest(com.alipay.sofa.jraft.rhea.cmd.store.NodeExecuteRequest) TimeUnit(java.util.concurrent.TimeUnit) StoreEngineOptions(com.alipay.sofa.jraft.rhea.options.StoreEngineOptions) Sequence(com.alipay.sofa.jraft.rhea.storage.Sequence) RpcOptions(com.alipay.sofa.jraft.rhea.options.RpcOptions) KVEntry(com.alipay.sofa.jraft.rhea.storage.KVEntry) Collections(java.util.Collections) LeaderStateListener(com.alipay.sofa.jraft.rhea.LeaderStateListener) EventFactory(com.lmax.disruptor.EventFactory) Disruptor(com.lmax.disruptor.dsl.Disruptor) BytesUtil(com.alipay.sofa.jraft.util.BytesUtil) FailoverClosureImpl(com.alipay.sofa.jraft.rhea.client.failover.impl.FailoverClosureImpl) Region(com.alipay.sofa.jraft.rhea.metadata.Region) RegionEngine(com.alipay.sofa.jraft.rhea.RegionEngine) RetryRunner(com.alipay.sofa.jraft.rhea.client.failover.RetryRunner) ContainsKeyRequest(com.alipay.sofa.jraft.rhea.cmd.store.ContainsKeyRequest)

Example 17 with Region

use of com.alipay.sofa.jraft.rhea.metadata.Region in project sofa-jraft by sofastack.

the class StoreEngine method initAllRegionEngine.

private boolean initAllRegionEngine(final StoreEngineOptions opts, final Store store) {
    Requires.requireNonNull(opts, "opts");
    Requires.requireNonNull(store, "store");
    String baseRaftDataPath = opts.getRaftDataPath();
    if (Strings.isNotBlank(baseRaftDataPath)) {
        try {
            FileUtils.forceMkdir(new File(baseRaftDataPath));
        } catch (final Throwable t) {
            LOG.error("Fail to make dir for raftDataPath: {}.", baseRaftDataPath);
            return false;
        }
    } else {
        baseRaftDataPath = "";
    }
    final Endpoint serverAddress = opts.getServerAddress();
    final List<RegionEngineOptions> rOptsList = opts.getRegionEngineOptionsList();
    final List<Region> regionList = store.getRegions();
    Requires.requireTrue(rOptsList.size() == regionList.size());
    for (int i = 0; i < rOptsList.size(); i++) {
        final RegionEngineOptions rOpts = rOptsList.get(i);
        if (!inConfiguration(rOpts.getServerAddress().toString(), rOpts.getInitialServerList())) {
            continue;
        }
        final Region region = regionList.get(i);
        if (Strings.isBlank(rOpts.getRaftDataPath())) {
            final String childPath = "raft_data_region_" + region.getId() + "_" + serverAddress.getPort();
            rOpts.setRaftDataPath(Paths.get(baseRaftDataPath, childPath).toString());
        }
        Requires.requireNonNull(region.getRegionEpoch(), "regionEpoch");
        final RegionEngine engine = new RegionEngine(region, this);
        if (engine.init(rOpts)) {
            final RegionKVService regionKVService = new DefaultRegionKVService(engine);
            registerRegionKVService(regionKVService);
            this.regionEngineTable.put(region.getId(), engine);
        } else {
            LOG.error("Fail to init [RegionEngine: {}].", region);
            return false;
        }
    }
    return true;
}
Also used : Endpoint(com.alipay.sofa.jraft.util.Endpoint) Region(com.alipay.sofa.jraft.rhea.metadata.Region) RegionEngineOptions(com.alipay.sofa.jraft.rhea.options.RegionEngineOptions) File(java.io.File) Endpoint(com.alipay.sofa.jraft.util.Endpoint)

Example 18 with Region

use of com.alipay.sofa.jraft.rhea.metadata.Region in project sofa-jraft by sofastack.

the class StoreEngine method applySplit.

public void applySplit(final Long regionId, final Long 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();
    final long approximateKeys = this.rawKVStore.getApproximateKeysInRange(startKey, endKey);
    final long leastKeysOnSplit = this.storeOpts.getLeastKeysOnSplit();
    if (approximateKeys < leastKeysOnSplit) {
        closure.setError(Errors.TOO_SMALL_TO_SPLIT);
        closure.run(new Status(-1, "RegionEngine[%s]'s keys less than %d", regionId, 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);
    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(com.alipay.sofa.jraft.Status) Task(com.alipay.sofa.jraft.entity.Task) KVClosureAdapter(com.alipay.sofa.jraft.rhea.storage.KVClosureAdapter) KVOperation(com.alipay.sofa.jraft.rhea.storage.KVOperation) Region(com.alipay.sofa.jraft.rhea.metadata.Region)

Example 19 with Region

use of com.alipay.sofa.jraft.rhea.metadata.Region in project sofa-jraft by sofastack.

the class RocksKVStoreSnapshotFile method doSnapshotLoad.

@Override
void doSnapshotLoad(final String snapshotPath, final LocalFileMeta meta, final Region region) throws Exception {
    if (RegionHelper.isMultiGroup(region)) {
        final Region snapshotRegion = readMetadata(meta, Region.class);
        if (!RegionHelper.isSameRange(region, snapshotRegion)) {
            throw new StorageException("Invalid snapshot region: " + snapshotRegion + " current region is: " + region);
        }
        this.kvStore.readSstSnapshot(snapshotPath);
        return;
    }
    if (this.kvStore.isFastSnapshot()) {
        this.kvStore.readSnapshot(snapshotPath);
        return;
    }
    final RocksDBBackupInfo rocksBackupInfo = readMetadata(meta, RocksDBBackupInfo.class);
    this.kvStore.restoreBackup(snapshotPath, rocksBackupInfo);
}
Also used : Region(com.alipay.sofa.jraft.rhea.metadata.Region) StorageException(com.alipay.sofa.jraft.rhea.errors.StorageException)

Example 20 with Region

use of com.alipay.sofa.jraft.rhea.metadata.Region in project sofa-jraft by sofastack.

the class SnapshotBenchmark method doSstSnapshotSave.

private void doSstSnapshotSave(final String snapshotPath) throws Exception {
    FileUtils.forceMkdir(new File(snapshotPath));
    final List<Region> regions = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
        final Region r = new Region();
        r.setId(i);
        r.setStartKey(BytesUtil.writeUtf8("benchmark_" + i));
        if (i < 9) {
            r.setEndKey(BytesUtil.writeUtf8("benchmark_" + (i + 1)));
        }
        regions.add(r);
    }
    final ExecutorService executor = Executors.newFixedThreadPool(10);
    final List<Future<?>> futures = Lists.newArrayList();
    for (final Region r : regions) {
        final Future<?> f = executor.submit(() -> {
            try {
                KVStoreAccessHelper.saveSnapshot(this.kvStore, Paths.get(snapshotPath, String.valueOf(r.getId())).toString(), r);
            } catch (final Exception e) {
                e.printStackTrace();
            }
        });
        futures.add(f);
    }
    for (final Future<?> f : futures) {
        try {
            f.get();
        } catch (final InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
    executor.shutdownNow();
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) Region(com.alipay.sofa.jraft.rhea.metadata.Region) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException) File(java.io.File) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

Region (com.alipay.sofa.jraft.rhea.metadata.Region)67 KVEntry (com.alipay.sofa.jraft.rhea.storage.KVEntry)35 List (java.util.List)35 Map (java.util.Map)35 Status (com.alipay.sofa.jraft.Status)34 Lists (com.alipay.sofa.jraft.rhea.util.Lists)34 BytesUtil (com.alipay.sofa.jraft.util.BytesUtil)34 Endpoint (com.alipay.sofa.jraft.util.Endpoint)33 KVIterator (com.alipay.sofa.jraft.rhea.storage.KVIterator)31 KVStoreClosure (com.alipay.sofa.jraft.rhea.storage.KVStoreClosure)31 RawKVStore (com.alipay.sofa.jraft.rhea.storage.RawKVStore)31 Sequence (com.alipay.sofa.jraft.rhea.storage.Sequence)31 ByteArray (com.alipay.sofa.jraft.rhea.util.ByteArray)31 DistributedLock (com.alipay.sofa.jraft.rhea.util.concurrent.DistributedLock)31 TimeUnit (java.util.concurrent.TimeUnit)31 CASEntry (com.alipay.sofa.jraft.rhea.storage.CASEntry)30 Requires (com.alipay.sofa.jraft.util.Requires)30 Logger (org.slf4j.Logger)30 LoggerFactory (org.slf4j.LoggerFactory)30 RegionEngine (com.alipay.sofa.jraft.rhea.RegionEngine)29