Search in sources :

Example 6 with NodeInfo

use of com.couchbase.client.core.config.NodeInfo in project couchbase-jvm-clients by couchbase.

the class KeyValueBucketRefresher method fetchConfigPerNode.

/**
 * Helper method to fetch a config per node provided.
 *
 * <p>Note that the bucket config request sent here has a fail fast strategy, so that if nodes are offline they
 * do not circle the system forever (given they have a specific node target). Since the refresher polls every
 * fixed interval anyways, fresh requests will flood the system eventually and there is no point in keeping
 * the old ones around.</p>
 *
 * <p>Also, the timeout is set to the poll interval since it does not make sense to keep them around any
 * longer.</p>
 *
 * @param name the bucket name.
 * @param nodes the flux of nodes that can be used to fetch a config.
 * @return returns configs for each node if found.
 */
private Flux<ProposedBucketConfigContext> fetchConfigPerNode(final String name, final Flux<NodeInfo> nodes) {
    return nodes.flatMap(nodeInfo -> {
        CoreContext ctx = core.context();
        CarrierBucketConfigRequest request = new CarrierBucketConfigRequest(configRequestTimeout, ctx, new CollectionIdentifier(name, Optional.empty(), Optional.empty()), FailFastRetryStrategy.INSTANCE, nodeInfo.identifier());
        core.send(request);
        return Reactor.wrap(request, request.response(), true).filter(response -> {
            if (!response.status().success()) {
                eventBus.publish(new BucketConfigRefreshFailedEvent(core.context(), BucketConfigRefreshFailedEvent.RefresherType.KV, BucketConfigRefreshFailedEvent.Reason.INDIVIDUAL_REQUEST_FAILED, Optional.of(response)));
            }
            return response.status().success();
        }).map(response -> new ProposedBucketConfigContext(name, new String(response.content(), UTF_8), nodeInfo.hostname())).onErrorResume(t -> {
            eventBus.publish(new BucketConfigRefreshFailedEvent(core.context(), BucketConfigRefreshFailedEvent.RefresherType.KV, BucketConfigRefreshFailedEvent.Reason.INDIVIDUAL_REQUEST_FAILED, Optional.of(t)));
            return Mono.empty();
        });
    });
}
Also used : Disposable(reactor.core.Disposable) ArrayList(java.util.ArrayList) EventBus(com.couchbase.client.core.cnc.EventBus) ServiceType(com.couchbase.client.core.service.ServiceType) CoreContext(com.couchbase.client.core.CoreContext) Duration(java.time.Duration) Map(java.util.Map) Stability(com.couchbase.client.core.annotation.Stability) ProposedBucketConfigContext(com.couchbase.client.core.config.ProposedBucketConfigContext) BucketConfig(com.couchbase.client.core.config.BucketConfig) ConfigurationProvider(com.couchbase.client.core.config.ConfigurationProvider) Reactor(com.couchbase.client.core.Reactor) UTF_8(java.nio.charset.StandardCharsets.UTF_8) NodeInfo(com.couchbase.client.core.config.NodeInfo) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Mono(reactor.core.publisher.Mono) FailFastRetryStrategy(com.couchbase.client.core.retry.FailFastRetryStrategy) TimeUnit(java.util.concurrent.TimeUnit) Flux(reactor.core.publisher.Flux) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Optional(java.util.Optional) CollectionIdentifier(com.couchbase.client.core.io.CollectionIdentifier) BucketConfigRefreshFailedEvent(com.couchbase.client.core.cnc.events.config.BucketConfigRefreshFailedEvent) CarrierBucketConfigRequest(com.couchbase.client.core.msg.kv.CarrierBucketConfigRequest) Core(com.couchbase.client.core.Core) CoreContext(com.couchbase.client.core.CoreContext) ProposedBucketConfigContext(com.couchbase.client.core.config.ProposedBucketConfigContext) BucketConfigRefreshFailedEvent(com.couchbase.client.core.cnc.events.config.BucketConfigRefreshFailedEvent) CarrierBucketConfigRequest(com.couchbase.client.core.msg.kv.CarrierBucketConfigRequest) CollectionIdentifier(com.couchbase.client.core.io.CollectionIdentifier)

Example 7 with NodeInfo

use of com.couchbase.client.core.config.NodeInfo in project couchbase-jvm-clients by couchbase.

the class ReactiveBatchHelper method existsBytes.

/**
 * Performs the bulk logic of fetching a config and splitting up the observe requests.
 *
 * @param collection the collection on which the query should be performed.
 * @param ids the list of ids which should be checked.
 * @return a flux of all
 */
private static Flux<byte[]> existsBytes(final Collection collection, final java.util.Collection<String> ids) {
    final Core core = collection.core();
    final CoreEnvironment env = core.context().environment();
    BucketConfig config = core.clusterConfig().bucketConfig(collection.bucketName());
    if (core.configurationProvider().bucketConfigLoadInProgress() || config == null) {
        // and then try again. In a steady state this should not happen.
        return Mono.delay(Duration.ofMillis(100), env.scheduler()).flatMapMany(ign -> existsBytes(collection, ids));
    }
    long start = System.nanoTime();
    if (!(config instanceof CouchbaseBucketConfig)) {
        throw new IllegalStateException("Only couchbase (and ephemeral) buckets are supported at this point!");
    }
    Map<NodeIdentifier, Map<byte[], Short>> nodeEntries = new HashMap<>(config.nodes().size());
    for (NodeInfo node : config.nodes()) {
        nodeEntries.put(node.identifier(), new HashMap<>(ids.size() / config.nodes().size()));
    }
    CouchbaseBucketConfig cbc = (CouchbaseBucketConfig) config;
    CollectionIdentifier ci = new CollectionIdentifier(collection.bucketName(), Optional.of(collection.scopeName()), Optional.of(collection.name()));
    for (String id : ids) {
        byte[] encodedId = id.getBytes(StandardCharsets.UTF_8);
        int partitionId = KeyValueLocator.partitionForKey(encodedId, cbc.numberOfPartitions());
        int nodeId = cbc.nodeIndexForActive(partitionId, false);
        NodeInfo nodeInfo = cbc.nodeAtIndex(nodeId);
        nodeEntries.get(nodeInfo.identifier()).put(encodedId, (short) partitionId);
    }
    List<Mono<MultiObserveViaCasResponse>> responses = new ArrayList<>(nodeEntries.size());
    List<MultiObserveViaCasRequest> requests = new ArrayList<>(nodeEntries.size());
    for (Map.Entry<NodeIdentifier, Map<byte[], Short>> node : nodeEntries.entrySet()) {
        if (node.getValue().isEmpty()) {
            // service enabled and 2) have keys that we need to fetch
            continue;
        }
        MultiObserveViaCasRequest request = new MultiObserveViaCasRequest(env.timeoutConfig().kvTimeout(), core.context(), env.retryStrategy(), ci, node.getKey(), node.getValue(), PMGET_PREDICATE);
        core.send(request);
        requests.add(request);
        responses.add(Reactor.wrap(request, request.response(), true));
    }
    return Flux.merge(responses).flatMap(response -> Flux.fromIterable(response.observed().keySet())).onErrorMap(throwable -> {
        BatchErrorContext ctx = new BatchErrorContext(Collections.unmodifiableList(requests));
        return new BatchHelperFailureException("Failed to perform BatchHelper bulk operation", throwable, ctx);
    }).doOnComplete(() -> core.context().environment().eventBus().publish(new BatchHelperExistsCompletedEvent(Duration.ofNanos(System.nanoTime() - start), new BatchErrorContext(Collections.unmodifiableList(requests)))));
}
Also used : GetResult(com.couchbase.client.java.kv.GetResult) NodeIdentifier(com.couchbase.client.core.node.NodeIdentifier) Tuples(reactor.util.function.Tuples) Tuple2(reactor.util.function.Tuple2) HashMap(java.util.HashMap) CouchbaseBucketConfig(com.couchbase.client.core.config.CouchbaseBucketConfig) ArrayList(java.util.ArrayList) Collection(com.couchbase.client.java.Collection) KeyValueLocator(com.couchbase.client.core.node.KeyValueLocator) Duration(java.time.Duration) Map(java.util.Map) Stability(com.couchbase.client.core.annotation.Stability) BucketConfig(com.couchbase.client.core.config.BucketConfig) Reactor(com.couchbase.client.core.Reactor) Predicate(java.util.function.Predicate) NodeInfo(com.couchbase.client.core.config.NodeInfo) ObserveViaCasResponse(com.couchbase.client.core.msg.kv.ObserveViaCasResponse) MultiObserveViaCasRequest(com.couchbase.client.core.msg.kv.MultiObserveViaCasRequest) Mono(reactor.core.publisher.Mono) CoreEnvironment(com.couchbase.client.core.env.CoreEnvironment) StandardCharsets(java.nio.charset.StandardCharsets) MultiObserveViaCasResponse(com.couchbase.client.core.msg.kv.MultiObserveViaCasResponse) Flux(reactor.core.publisher.Flux) List(java.util.List) Optional(java.util.Optional) CollectionIdentifier(com.couchbase.client.core.io.CollectionIdentifier) BatchHelperExistsCompletedEvent(com.couchbase.client.java.cnc.evnts.BatchHelperExistsCompletedEvent) Core(com.couchbase.client.core.Core) Collections(java.util.Collections) CoreEnvironment(com.couchbase.client.core.env.CoreEnvironment) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MultiObserveViaCasRequest(com.couchbase.client.core.msg.kv.MultiObserveViaCasRequest) CouchbaseBucketConfig(com.couchbase.client.core.config.CouchbaseBucketConfig) BucketConfig(com.couchbase.client.core.config.BucketConfig) Core(com.couchbase.client.core.Core) CouchbaseBucketConfig(com.couchbase.client.core.config.CouchbaseBucketConfig) Mono(reactor.core.publisher.Mono) NodeInfo(com.couchbase.client.core.config.NodeInfo) NodeIdentifier(com.couchbase.client.core.node.NodeIdentifier) BatchHelperExistsCompletedEvent(com.couchbase.client.java.cnc.evnts.BatchHelperExistsCompletedEvent) HashMap(java.util.HashMap) Map(java.util.Map) CollectionIdentifier(com.couchbase.client.core.io.CollectionIdentifier)

Example 8 with NodeInfo

use of com.couchbase.client.core.config.NodeInfo in project couchbase-jvm-clients by couchbase.

the class KeyValueLocatorTest method pickCurrentIfNoFFMapAndNmvbSeen.

@Test
@SuppressWarnings("unchecked")
void pickCurrentIfNoFFMapAndNmvbSeen() {
    Locator locator = new KeyValueLocator();
    // Setup 2 nodes
    NodeInfo nodeInfo1 = new NodeInfo("http://foo:1234", "192.168.56.101:8091", Collections.EMPTY_MAP, null);
    NodeInfo nodeInfo2 = new NodeInfo("http://foo:1234", "192.168.56.102:8091", Collections.EMPTY_MAP, null);
    Node node1Mock = mock(Node.class);
    when(node1Mock.identifier()).thenReturn(new NodeIdentifier("192.168.56.101", 8091));
    Node node2Mock = mock(Node.class);
    when(node2Mock.identifier()).thenReturn(new NodeIdentifier("192.168.56.102", 8091));
    List<Node> nodes = new ArrayList<>(Arrays.asList(node1Mock, node2Mock));
    // Configure Cluster and Bucket config
    ClusterConfig configMock = mock(ClusterConfig.class);
    CouchbaseBucketConfig bucketMock = mock(CouchbaseBucketConfig.class);
    when(configMock.bucketConfig("bucket")).thenReturn(bucketMock);
    when(bucketMock.nodes()).thenReturn(Arrays.asList(nodeInfo1, nodeInfo2));
    when(bucketMock.numberOfPartitions()).thenReturn(1024);
    when(bucketMock.nodeAtIndex(0)).thenReturn(nodeInfo1);
    when(bucketMock.nodeAtIndex(1)).thenReturn(nodeInfo2);
    when(bucketMock.hasFastForwardMap()).thenReturn(false);
    // Fake a vbucket move in ffwd map from node 0 to node 1
    when(bucketMock.nodeIndexForActive(656, false)).thenReturn((short) 0);
    when(bucketMock.nodeIndexForActive(656, true)).thenReturn((short) 1);
    // Create Request
    GetRequest getRequest = mock(GetRequest.class);
    when(getRequest.bucket()).thenReturn("bucket");
    when(getRequest.key()).thenReturn("key".getBytes(UTF_8));
    RequestContext requestCtx = mock(RequestContext.class);
    when(getRequest.context()).thenReturn(requestCtx);
    when(getRequest.rejectedWithNotMyVbucket()).thenReturn(9);
    locator.dispatch(getRequest, nodes, configMock, null);
    verify(node1Mock, times(1)).send(getRequest);
    verify(node2Mock, never()).send(getRequest);
    when(getRequest.rejectedWithNotMyVbucket()).thenReturn(1);
    locator.dispatch(getRequest, nodes, configMock, null);
    verify(node1Mock, times(2)).send(getRequest);
    verify(node2Mock, never()).send(getRequest);
}
Also used : CouchbaseBucketConfig(com.couchbase.client.core.config.CouchbaseBucketConfig) NodeInfo(com.couchbase.client.core.config.NodeInfo) GetRequest(com.couchbase.client.core.msg.kv.GetRequest) ArrayList(java.util.ArrayList) RequestContext(com.couchbase.client.core.msg.RequestContext) ClusterConfig(com.couchbase.client.core.config.ClusterConfig) Test(org.junit.jupiter.api.Test)

Aggregations

NodeInfo (com.couchbase.client.core.config.NodeInfo)8 ArrayList (java.util.ArrayList)7 CouchbaseBucketConfig (com.couchbase.client.core.config.CouchbaseBucketConfig)5 Core (com.couchbase.client.core.Core)4 ClusterConfig (com.couchbase.client.core.config.ClusterConfig)4 RequestContext (com.couchbase.client.core.msg.RequestContext)4 GetRequest (com.couchbase.client.core.msg.kv.GetRequest)4 CoreContext (com.couchbase.client.core.CoreContext)3 Reactor (com.couchbase.client.core.Reactor)3 Stability (com.couchbase.client.core.annotation.Stability)3 BucketConfig (com.couchbase.client.core.config.BucketConfig)3 CollectionIdentifier (com.couchbase.client.core.io.CollectionIdentifier)3 Duration (java.time.Duration)3 List (java.util.List)3 Map (java.util.Map)3 Optional (java.util.Optional)3 Test (org.junit.jupiter.api.Test)3 Flux (reactor.core.publisher.Flux)3 Mono (reactor.core.publisher.Mono)3 EventBus (com.couchbase.client.core.cnc.EventBus)2