Search in sources :

Example 1 with EventBus

use of com.datastax.oss.driver.internal.core.context.EventBus in project java-driver by datastax.

the class ControlConnectionTestBase method setup.

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    adminEventLoopGroup = new DefaultEventLoopGroup(1);
    when(context.getNettyOptions()).thenReturn(nettyOptions);
    when(nettyOptions.adminEventExecutorGroup()).thenReturn(adminEventLoopGroup);
    eventBus = spy(new EventBus("test"));
    when(context.getEventBus()).thenReturn(eventBus);
    when(context.getChannelFactory()).thenReturn(channelFactory);
    channelFactoryFuture = new Exchanger<>();
    when(channelFactory.connect(any(Node.class), any(DriverChannelOptions.class))).thenAnswer(invocation -> {
        CompletableFuture<DriverChannel> channelFuture = new CompletableFuture<>();
        channelFactoryFuture.exchange(channelFuture, 100, TimeUnit.MILLISECONDS);
        return channelFuture;
    });
    when(context.getConfig()).thenReturn(config);
    when(config.getDefaultProfile()).thenReturn(defaultProfile);
    when(defaultProfile.getBoolean(DefaultDriverOption.RECONNECT_ON_INIT)).thenReturn(false);
    when(context.getReconnectionPolicy()).thenReturn(reconnectionPolicy);
    // Child classes only cover "runtime" reconnections when the driver is already initialized
    when(reconnectionPolicy.newControlConnectionSchedule(false)).thenReturn(reconnectionSchedule);
    // By default, set a large reconnection delay. Tests that care about reconnection will override
    // it.
    when(reconnectionSchedule.nextDelay()).thenReturn(Duration.ofDays(1));
    when(context.getLoadBalancingPolicyWrapper()).thenReturn(loadBalancingPolicyWrapper);
    when(context.getMetricsFactory()).thenReturn(metricsFactory);
    node1 = TestNodeFactory.newNode(1, context);
    node2 = TestNodeFactory.newNode(2, context);
    mockQueryPlan(node1, node2);
    when(metadataManager.refreshNodes()).thenReturn(CompletableFuture.completedFuture(null));
    when(metadataManager.refreshSchema(anyString(), anyBoolean(), anyBoolean())).thenReturn(CompletableFuture.completedFuture(null));
    when(context.getMetadataManager()).thenReturn(metadataManager);
    when(context.getConfig()).thenReturn(config);
    when(config.getDefaultProfile()).thenReturn(defaultProfile);
    when(defaultProfile.getBoolean(DefaultDriverOption.CONNECTION_WARN_INIT_ERROR)).thenReturn(false);
    controlConnection = new ControlConnection(context);
}
Also used : DriverChannel(com.datastax.oss.driver.internal.core.channel.DriverChannel) CompletableFuture(java.util.concurrent.CompletableFuture) DriverChannelOptions(com.datastax.oss.driver.internal.core.channel.DriverChannelOptions) Node(com.datastax.oss.driver.api.core.metadata.Node) DefaultNode(com.datastax.oss.driver.internal.core.metadata.DefaultNode) EventBus(com.datastax.oss.driver.internal.core.context.EventBus) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Before(org.junit.Before)

Example 2 with EventBus

use of com.datastax.oss.driver.internal.core.context.EventBus in project java-driver by datastax.

the class DefaultDriverConfigLoaderTest method setup.

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    when(context.getSessionName()).thenReturn("test");
    when(context.getNettyOptions()).thenReturn(nettyOptions);
    when(nettyOptions.adminEventExecutorGroup()).thenReturn(adminEventExecutorGroup);
    adminExecutor = new ScheduledTaskCapturingEventLoop(adminEventExecutorGroup);
    when(adminEventExecutorGroup.next()).thenReturn(adminExecutor);
    eventBus = spy(new EventBus("test"));
    when(context.getEventBus()).thenReturn(eventBus);
    // The already loaded config in the context.
    // In real life, it's the object managed by the loader, but in this test it's simpler to mock
    // it.
    when(context.getConfig()).thenReturn(config);
    when(config.getDefaultProfile()).thenReturn(defaultProfile);
    when(defaultProfile.getDuration(DefaultDriverOption.CONFIG_RELOAD_INTERVAL)).thenReturn(Duration.ofSeconds(12));
    configSource = new AtomicReference<>("int1 = 42");
}
Also used : EventBus(com.datastax.oss.driver.internal.core.context.EventBus) ScheduledTaskCapturingEventLoop(com.datastax.oss.driver.internal.core.util.concurrent.ScheduledTaskCapturingEventLoop) Before(org.junit.Before)

Example 3 with EventBus

use of com.datastax.oss.driver.internal.core.context.EventBus in project java-driver by datastax.

the class ChannelFactoryTestBase method setup.

@Before
public void setup() throws InterruptedException {
    MockitoAnnotations.initMocks(this);
    serverGroup = new DefaultEventLoopGroup(1);
    clientGroup = new DefaultEventLoopGroup(1);
    when(context.getConfig()).thenReturn(driverConfig);
    when(driverConfig.getDefaultProfile()).thenReturn(defaultProfile);
    when(defaultProfile.isDefined(DefaultDriverOption.AUTH_PROVIDER_CLASS)).thenReturn(false);
    when(defaultProfile.getDuration(DefaultDriverOption.CONNECTION_INIT_QUERY_TIMEOUT)).thenReturn(Duration.ofMillis(TIMEOUT_MILLIS));
    when(defaultProfile.getDuration(DefaultDriverOption.CONNECTION_SET_KEYSPACE_TIMEOUT)).thenReturn(Duration.ofMillis(TIMEOUT_MILLIS));
    when(defaultProfile.getInt(DefaultDriverOption.CONNECTION_MAX_REQUESTS)).thenReturn(1);
    when(defaultProfile.getDuration(DefaultDriverOption.HEARTBEAT_INTERVAL)).thenReturn(Duration.ofSeconds(30));
    when(defaultProfile.getDuration(DefaultDriverOption.CONNECTION_CONNECT_TIMEOUT)).thenReturn(Duration.ofSeconds(5));
    when(context.getProtocolVersionRegistry()).thenReturn(protocolVersionRegistry);
    when(context.getNettyOptions()).thenReturn(nettyOptions);
    when(nettyOptions.ioEventLoopGroup()).thenReturn(clientGroup);
    when(nettyOptions.channelClass()).thenAnswer((Answer<Object>) i -> LocalChannel.class);
    when(nettyOptions.allocator()).thenReturn(ByteBufAllocator.DEFAULT);
    when(context.getFrameCodec()).thenReturn(FrameCodec.defaultClient(new ByteBufPrimitiveCodec(ByteBufAllocator.DEFAULT), Compressor.none()));
    when(context.getSslHandlerFactory()).thenReturn(Optional.empty());
    when(context.getEventBus()).thenReturn(eventBus);
    when(context.getWriteCoalescer()).thenReturn(new PassThroughWriteCoalescer(null));
    when(context.getCompressor()).thenReturn(compressor);
    // Start local server
    ServerBootstrap serverBootstrap = new ServerBootstrap().group(serverGroup).channel(LocalServerChannel.class).localAddress(SERVER_ADDRESS.resolve()).childHandler(new ServerInitializer());
    ChannelFuture channelFuture = serverBootstrap.bind().sync();
    serverAcceptChannel = (LocalServerChannel) channelFuture.sync().channel();
}
Also used : LocalServerChannel(io.netty.channel.local.LocalServerChannel) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) Mock(org.mockito.Mock) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) RunWith(org.junit.runner.RunWith) TimeoutException(java.util.concurrent.TimeoutException) InternalDriverContext(com.datastax.oss.driver.internal.core.context.InternalDriverContext) CompletableFuture(java.util.concurrent.CompletableFuture) NettyOptions(com.datastax.oss.driver.internal.core.context.NettyOptions) DataProviderRunner(com.tngtech.java.junit.dataprovider.DataProviderRunner) DriverConfig(com.datastax.oss.driver.api.core.config.DriverConfig) NodeMetricUpdater(com.datastax.oss.driver.internal.core.metrics.NodeMetricUpdater) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) MockitoAnnotations(org.mockito.MockitoAnnotations) Answer(org.mockito.stubbing.Answer) Compressor(com.datastax.oss.protocol.internal.Compressor) DefaultDriverOption(com.datastax.oss.driver.api.core.config.DefaultDriverOption) Message(com.datastax.oss.protocol.internal.Message) ByteBuf(io.netty.buffer.ByteBuf) ProtocolVersionRegistry(com.datastax.oss.driver.internal.core.ProtocolVersionRegistry) LocalChannel(io.netty.channel.local.LocalChannel) EventBus(com.datastax.oss.driver.internal.core.context.EventBus) ByteBufPrimitiveCodec(com.datastax.oss.driver.internal.core.protocol.ByteBufPrimitiveCodec) Duration(java.time.Duration) After(org.junit.After) DriverExecutionProfile(com.datastax.oss.driver.api.core.config.DriverExecutionProfile) ProtocolVersion(com.datastax.oss.driver.api.core.ProtocolVersion) Ready(com.datastax.oss.protocol.internal.response.Ready) Before(org.junit.Before) ChannelInitializer(io.netty.channel.ChannelInitializer) FrameCodec(com.datastax.oss.protocol.internal.FrameCodec) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Mockito.when(org.mockito.Mockito.when) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) TimeUnit(java.util.concurrent.TimeUnit) Assertions.fail(org.assertj.core.api.Assertions.fail) EndPoint(com.datastax.oss.driver.api.core.metadata.EndPoint) TestResponses(com.datastax.oss.driver.internal.core.TestResponses) Frame(com.datastax.oss.protocol.internal.Frame) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Optional(java.util.Optional) Startup(com.datastax.oss.protocol.internal.request.Startup) Options(com.datastax.oss.protocol.internal.request.Options) Collections(java.util.Collections) Exchanger(java.util.concurrent.Exchanger) ChannelFuture(io.netty.channel.ChannelFuture) LocalChannel(io.netty.channel.local.LocalChannel) ByteBufPrimitiveCodec(com.datastax.oss.driver.internal.core.protocol.ByteBufPrimitiveCodec) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Before(org.junit.Before)

Example 4 with EventBus

use of com.datastax.oss.driver.internal.core.context.EventBus in project java-driver by datastax.

the class NodeMetadataIT method should_expose_node_metadata.

@Test
public void should_expose_node_metadata() {
    try (CqlSession session = SessionUtils.newSession(ccmRule)) {
        Node node = getUniqueNode(session);
        // Run a few basic checks given what we know about our test environment:
        assertThat(node.getEndPoint()).isNotNull();
        InetSocketAddress connectAddress = (InetSocketAddress) node.getEndPoint().resolve();
        node.getBroadcastAddress().ifPresent(broadcastAddress -> assertThat(broadcastAddress.getAddress()).isEqualTo(connectAddress.getAddress()));
        assertThat(node.getListenAddress().get().getAddress()).isEqualTo(connectAddress.getAddress());
        assertThat(node.getDatacenter()).isEqualTo("dc1");
        assertThat(node.getRack()).isEqualTo("r1");
        if (!CcmBridge.DSE_ENABLEMENT) {
            // CcmBridge does not report accurate C* versions for DSE, only approximated values
            assertThat(node.getCassandraVersion()).isEqualTo(ccmRule.getCassandraVersion());
        }
        assertThat(node.getState()).isSameAs(NodeState.UP);
        assertThat(node.getDistance()).isSameAs(NodeDistance.LOCAL);
        assertThat(node.getHostId()).isNotNull();
        assertThat(node.getSchemaVersion()).isNotNull();
        long upTime1 = node.getUpSinceMillis();
        assertThat(upTime1).isGreaterThan(-1);
        // Note: open connections and reconnection status are covered in NodeStateIT
        // Force the node down and back up to check that upSinceMillis gets updated
        EventBus eventBus = ((InternalDriverContext) session.getContext()).getEventBus();
        eventBus.fire(TopologyEvent.forceDown(node.getBroadcastRpcAddress().get()));
        await().pollInterval(500, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS).until(() -> node.getState() == NodeState.FORCED_DOWN);
        assertThat(node.getUpSinceMillis()).isEqualTo(-1);
        eventBus.fire(TopologyEvent.forceUp(node.getBroadcastRpcAddress().get()));
        await().pollInterval(500, TimeUnit.MILLISECONDS).atMost(60, TimeUnit.SECONDS).until(() -> node.getState() == NodeState.UP);
        assertThat(node.getUpSinceMillis()).isGreaterThan(upTime1);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Node(com.datastax.oss.driver.api.core.metadata.Node) EventBus(com.datastax.oss.driver.internal.core.context.EventBus) CqlSession(com.datastax.oss.driver.api.core.CqlSession) InternalDriverContext(com.datastax.oss.driver.internal.core.context.InternalDriverContext) Test(org.junit.Test)

Example 5 with EventBus

use of com.datastax.oss.driver.internal.core.context.EventBus in project java-driver by datastax.

the class MetricsITBase method should_evict_down_node_metrics_when_timeout_fires.

@Test
public void should_evict_down_node_metrics_when_timeout_fires() throws Exception {
    // given
    Duration expireAfter = Duration.ofSeconds(1);
    DriverConfigLoader loader = allMetricsEnabled().withDuration(DefaultDriverOption.METRICS_NODE_EXPIRE_AFTER, expireAfter).build();
    AbstractMetricUpdater.MIN_EXPIRE_AFTER = expireAfter;
    try (CqlSession session = CqlSession.builder().addContactEndPoints(simulacron().getContactPoints()).withConfigLoader(loader).withMetricRegistry(newMetricRegistry()).build()) {
        queryAllNodes(session);
        DefaultNode node1 = findNode(session, 0);
        DefaultNode node2 = findNode(session, 1);
        DefaultNode node3 = findNode(session, 2);
        EventBus eventBus = ((InternalDriverContext) session.getContext()).getEventBus();
        // trigger node1 UP -> DOWN
        eventBus.fire(NodeStateEvent.changed(NodeState.UP, NodeState.DOWN, node1));
        Thread.sleep(expireAfter.toMillis());
        // then node-level metrics should be evicted from node1, but
        // node2 and node3 metrics should not have been evicted
        await().untilAsserted(() -> assertNodeMetricsEvicted(session, node1));
        assertNodeMetricsNotEvicted(session, node2);
        assertNodeMetricsNotEvicted(session, node3);
    } finally {
        AbstractMetricUpdater.MIN_EXPIRE_AFTER = Duration.ofMinutes(5);
    }
}
Also used : DefaultNode(com.datastax.oss.driver.internal.core.metadata.DefaultNode) Duration(java.time.Duration) DriverConfigLoader(com.datastax.oss.driver.api.core.config.DriverConfigLoader) EventBus(com.datastax.oss.driver.internal.core.context.EventBus) CqlSession(com.datastax.oss.driver.api.core.CqlSession) InternalDriverContext(com.datastax.oss.driver.internal.core.context.InternalDriverContext) Test(org.junit.Test)

Aggregations

EventBus (com.datastax.oss.driver.internal.core.context.EventBus)11 Before (org.junit.Before)8 DefaultEventLoopGroup (io.netty.channel.DefaultEventLoopGroup)6 Node (com.datastax.oss.driver.api.core.metadata.Node)5 DefaultNode (com.datastax.oss.driver.internal.core.metadata.DefaultNode)5 InternalDriverContext (com.datastax.oss.driver.internal.core.context.InternalDriverContext)4 CqlSession (com.datastax.oss.driver.api.core.CqlSession)3 Duration (java.time.Duration)3 Test (org.junit.Test)3 DriverConfigLoader (com.datastax.oss.driver.api.core.config.DriverConfigLoader)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 ProtocolVersion (com.datastax.oss.driver.api.core.ProtocolVersion)1 DefaultDriverOption (com.datastax.oss.driver.api.core.config.DefaultDriverOption)1 DriverConfig (com.datastax.oss.driver.api.core.config.DriverConfig)1 DriverExecutionProfile (com.datastax.oss.driver.api.core.config.DriverExecutionProfile)1 EndPoint (com.datastax.oss.driver.api.core.metadata.EndPoint)1 Metadata (com.datastax.oss.driver.api.core.metadata.Metadata)1 ProtocolVersionRegistry (com.datastax.oss.driver.internal.core.ProtocolVersionRegistry)1 TestResponses (com.datastax.oss.driver.internal.core.TestResponses)1 DriverChannel (com.datastax.oss.driver.internal.core.channel.DriverChannel)1