Search in sources :

Example 16 with CoreEnvironment

use of com.couchbase.client.core.env.CoreEnvironment in project couchbase-jvm-clients by couchbase.

the class MemcacheProtocolVerificationHandlerTest method shouldCloseOnInvalidResponses.

/**
 * Verifies that invalid responses are not let through.
 *
 * @param inputHolder the bad input packets.
 */
@ParameterizedTest(name = "{0}")
@MethodSource
void shouldCloseOnInvalidResponses(final InputHolder inputHolder) {
    SimpleEventBus eventBus = new SimpleEventBus(true);
    CoreEnvironment env = mock(CoreEnvironment.class);
    EndpointContext ctx = mock(EndpointContext.class);
    when(ctx.environment()).thenReturn(env);
    when(env.eventBus()).thenReturn(eventBus);
    final EmbeddedChannel channel = new EmbeddedChannel(new MemcacheProtocolVerificationHandler(ctx));
    try {
        channel.writeInbound(inputHolder.input);
        assertFalse(channel.isOpen());
        InvalidPacketDetectedEvent event = (InvalidPacketDetectedEvent) eventBus.publishedEvents().get(0);
        assertEquals(Event.Severity.ERROR, event.severity());
        assertEquals(Event.Category.IO.path(), event.category());
        assertTrue(event.description().contains("Invalid Packet detected:"));
    } finally {
        channel.finishAndReleaseAll();
    }
}
Also used : CoreEnvironment(com.couchbase.client.core.env.CoreEnvironment) EndpointContext(com.couchbase.client.core.endpoint.EndpointContext) SimpleEventBus(com.couchbase.client.core.cnc.SimpleEventBus) EmbeddedChannel(com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel) InvalidPacketDetectedEvent(com.couchbase.client.core.cnc.events.io.InvalidPacketDetectedEvent) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 17 with CoreEnvironment

use of com.couchbase.client.core.env.CoreEnvironment in project couchbase-jvm-clients by couchbase.

the class SaslListMechanismsHandlerTest method failConnectIfPromiseTimesOut.

/**
 * This test makes sure that the timer fires if the connect future is not completed
 * otherwise.
 */
@Test
void failConnectIfPromiseTimesOut() throws Exception {
    channel = new EmbeddedChannel();
    eventBus = new SimpleEventBus(true);
    CoreEnvironment env = mock(CoreEnvironment.class);
    TimeoutConfig timeoutConfig = mock(TimeoutConfig.class);
    when(env.eventBus()).thenReturn(eventBus);
    when(env.timeoutConfig()).thenReturn(timeoutConfig);
    when(timeoutConfig.connectTimeout()).thenReturn(Duration.ofMillis(100));
    CoreContext coreContext = new CoreContext(mock(Core.class), 1, env, mock(Authenticator.class));
    EndpointContext endpointContext = new EndpointContext(coreContext, new HostAndPort("127.0.0.1", 1234), null, ServiceType.KV, Optional.empty(), Optional.empty(), Optional.empty());
    SaslListMechanismsHandler handler = new SaslListMechanismsHandler(endpointContext);
    channel.pipeline().addLast(handler);
    final ChannelFuture connect = channel.connect(new InetSocketAddress("1.2.3.4", 1234));
    channel.pipeline().fireChannelActive();
    Thread.sleep(Duration.ofMillis(100).toMillis() + 5);
    channel.runScheduledPendingTasks();
    assertTrue(connect.isDone());
    assertTrue(connect.cause() instanceof TimeoutException);
    assertEquals("SASL Mechanism listing timed out after 100ms", connect.cause().getMessage());
}
Also used : ChannelFuture(com.couchbase.client.core.deps.io.netty.channel.ChannelFuture) TimeoutConfig(com.couchbase.client.core.env.TimeoutConfig) CoreContext(com.couchbase.client.core.CoreContext) CoreEnvironment(com.couchbase.client.core.env.CoreEnvironment) EndpointContext(com.couchbase.client.core.endpoint.EndpointContext) InetSocketAddress(java.net.InetSocketAddress) EmbeddedChannel(com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel) HostAndPort(com.couchbase.client.core.util.HostAndPort) SimpleEventBus(com.couchbase.client.core.cnc.SimpleEventBus) Authenticator(com.couchbase.client.core.env.Authenticator) Core(com.couchbase.client.core.Core) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.jupiter.api.Test)

Example 18 with CoreEnvironment

use of com.couchbase.client.core.env.CoreEnvironment in project couchbase-jvm-clients by couchbase.

the class SelectBucketHandlerTest method setup.

@BeforeEach
void setup() {
    channel = new EmbeddedChannel();
    SimpleEventBus simpleEventBus = new SimpleEventBus(true);
    CoreEnvironment env = mock(CoreEnvironment.class);
    TimeoutConfig timeoutConfig = mock(TimeoutConfig.class);
    when(env.eventBus()).thenReturn(simpleEventBus);
    when(env.timeoutConfig()).thenReturn(timeoutConfig);
    when(timeoutConfig.connectTimeout()).thenReturn(Duration.ofMillis(10));
    CoreContext coreContext = new CoreContext(mock(Core.class), 1, env, mock(Authenticator.class));
    endpointContext = new EndpointContext(coreContext, new HostAndPort("127.0.0.1", 1234), null, ServiceType.KV, Optional.empty(), Optional.empty(), Optional.empty());
}
Also used : HostAndPort(com.couchbase.client.core.util.HostAndPort) TimeoutConfig(com.couchbase.client.core.env.TimeoutConfig) CoreContext(com.couchbase.client.core.CoreContext) CoreEnvironment(com.couchbase.client.core.env.CoreEnvironment) EndpointContext(com.couchbase.client.core.endpoint.EndpointContext) SimpleEventBus(com.couchbase.client.core.cnc.SimpleEventBus) EmbeddedChannel(com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel) Authenticator(com.couchbase.client.core.env.Authenticator) Core(com.couchbase.client.core.Core) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 19 with CoreEnvironment

use of com.couchbase.client.core.env.CoreEnvironment 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 20 with CoreEnvironment

use of com.couchbase.client.core.env.CoreEnvironment in project couchbase-jvm-clients by couchbase.

the class NodeTest method sendsEventsIntoEventBus.

@Test
void sendsEventsIntoEventBus() {
    Core core = mock(Core.class);
    SimpleEventBus eventBus = new SimpleEventBus(true, Collections.singletonList(NodeStateChangedEvent.class));
    CoreEnvironment env = CoreEnvironment.builder().eventBus(eventBus).build();
    CoreContext ctx = new CoreContext(core, 1, env, mock(Authenticator.class));
    try {
        Node node = new Node(ctx, mock(NodeIdentifier.class), NO_ALTERNATE) {

            @Override
            protected Service createService(ServiceType serviceType, int port, Optional<String> bucket) {
                Service s = mock(Service.class);
                when(s.type()).thenReturn(serviceType);
                when(s.states()).thenReturn(DirectProcessor.create());
                when(s.state()).thenReturn(ServiceState.IDLE);
                return s;
            }
        };
        node.addService(ServiceType.QUERY, 2, Optional.empty()).block();
        node.addService(ServiceType.KV, 1, Optional.of("bucket")).block();
        node.addService(ServiceType.KV, 1, Optional.of("bucket")).block();
        node.removeService(ServiceType.KV, Optional.of("bucket")).block();
        node.removeService(ServiceType.QUERY, Optional.empty()).block();
        node.removeService(ServiceType.QUERY, Optional.empty()).block();
        node.disconnect().block();
        node.disconnect().block();
        node.addService(ServiceType.QUERY, 2, Optional.empty()).block();
        node.removeService(ServiceType.QUERY, Optional.empty()).block();
        List<Event> events = eventBus.publishedEvents();
        assertTrue(events.remove(0) instanceof NodeConnectedEvent);
        assertTrue(events.get(0) instanceof ServiceAddedEvent);
        assertTrue(events.get(1) instanceof ServiceAddedEvent);
        assertTrue(events.get(2) instanceof ServiceAddIgnoredEvent);
        assertTrue(events.get(3) instanceof ServiceRemovedEvent);
        assertTrue(events.get(4) instanceof ServiceRemovedEvent);
        assertTrue(events.get(5) instanceof ServiceRemoveIgnoredEvent);
        assertTrue(events.get(6) instanceof NodeDisconnectedEvent);
        assertTrue(events.get(7) instanceof NodeDisconnectIgnoredEvent);
        assertTrue(events.get(8) instanceof ServiceAddIgnoredEvent);
        assertTrue(events.get(9) instanceof ServiceRemoveIgnoredEvent);
    } finally {
        env.shutdown();
    }
}
Also used : ServiceAddedEvent(com.couchbase.client.core.cnc.events.service.ServiceAddedEvent) ServiceRemoveIgnoredEvent(com.couchbase.client.core.cnc.events.service.ServiceRemoveIgnoredEvent) CoreContext(com.couchbase.client.core.CoreContext) NodeConnectedEvent(com.couchbase.client.core.cnc.events.node.NodeConnectedEvent) Optional(java.util.Optional) CoreEnvironment(com.couchbase.client.core.env.CoreEnvironment) ServiceAddIgnoredEvent(com.couchbase.client.core.cnc.events.service.ServiceAddIgnoredEvent) Service(com.couchbase.client.core.service.Service) NodeStateChangedEvent(com.couchbase.client.core.cnc.events.node.NodeStateChangedEvent) ServiceRemovedEvent(com.couchbase.client.core.cnc.events.service.ServiceRemovedEvent) ServiceType(com.couchbase.client.core.service.ServiceType) NodeDisconnectedEvent(com.couchbase.client.core.cnc.events.node.NodeDisconnectedEvent) SimpleEventBus(com.couchbase.client.core.cnc.SimpleEventBus) NodeDisconnectIgnoredEvent(com.couchbase.client.core.cnc.events.node.NodeDisconnectIgnoredEvent) ServiceAddIgnoredEvent(com.couchbase.client.core.cnc.events.service.ServiceAddIgnoredEvent) ServiceRemovedEvent(com.couchbase.client.core.cnc.events.service.ServiceRemovedEvent) NodeStateChangedEvent(com.couchbase.client.core.cnc.events.node.NodeStateChangedEvent) Event(com.couchbase.client.core.cnc.Event) ServiceRemoveIgnoredEvent(com.couchbase.client.core.cnc.events.service.ServiceRemoveIgnoredEvent) NodeConnectedEvent(com.couchbase.client.core.cnc.events.node.NodeConnectedEvent) ServiceAddedEvent(com.couchbase.client.core.cnc.events.service.ServiceAddedEvent) NodeDisconnectedEvent(com.couchbase.client.core.cnc.events.node.NodeDisconnectedEvent) NodeDisconnectIgnoredEvent(com.couchbase.client.core.cnc.events.node.NodeDisconnectIgnoredEvent) Authenticator(com.couchbase.client.core.env.Authenticator) Core(com.couchbase.client.core.Core) Test(org.junit.jupiter.api.Test)

Aggregations

CoreEnvironment (com.couchbase.client.core.env.CoreEnvironment)30 Core (com.couchbase.client.core.Core)20 CoreContext (com.couchbase.client.core.CoreContext)20 Test (org.junit.jupiter.api.Test)15 Authenticator (com.couchbase.client.core.env.Authenticator)13 SimpleEventBus (com.couchbase.client.core.cnc.SimpleEventBus)9 EndpointContext (com.couchbase.client.core.endpoint.EndpointContext)8 HostAndPort (com.couchbase.client.core.util.HostAndPort)7 BeforeEach (org.junit.jupiter.api.BeforeEach)7 EmbeddedChannel (com.couchbase.client.core.deps.io.netty.channel.embedded.EmbeddedChannel)6 Stability (com.couchbase.client.core.annotation.Stability)5 TimeoutConfig (com.couchbase.client.core.env.TimeoutConfig)5 Duration (java.time.Duration)5 List (java.util.List)5 Map (java.util.Map)5 Flux (reactor.core.publisher.Flux)5 Mono (reactor.core.publisher.Mono)5 Reactor (com.couchbase.client.core.Reactor)4 BucketConfig (com.couchbase.client.core.config.BucketConfig)4 CouchbaseBucketConfig (com.couchbase.client.core.config.CouchbaseBucketConfig)4