use of com.couchbase.client.core.deps.io.netty.channel.ChannelInitializer in project couchbase-jvm-clients by couchbase.
the class BaseEndpoint method reconnect.
/**
* This method performs the actual connecting logic.
*
* <p>It is called reconnect since it works both in the case where an initial attempt is made
* but also when the underlying channel is closed or the previous connect attempt was
* unsuccessful.</p>
*/
private void reconnect() {
if (disconnect.get()) {
return;
}
state.transition(EndpointState.CONNECTING);
final EndpointContext endpointContext = this.endpointContext.get();
final AtomicLong attemptStart = new AtomicLong();
Mono.defer((Supplier<Mono<Channel>>) () -> {
CoreEnvironment env = endpointContext.environment();
long connectTimeoutMs = env.timeoutConfig().connectTimeout().toMillis();
if (eventLoopGroup.isShutdown()) {
throw new IllegalStateException("Event Loop is already shut down, not pursuing connect attempt!");
}
final Bootstrap channelBootstrap = new Bootstrap().remoteAddress(remoteAddress()).group(eventLoopGroup).channel(channelFrom(eventLoopGroup)).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeoutMs).handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(final Channel ch) {
ChannelPipeline pipeline = ch.pipeline();
SecurityConfig config = env.securityConfig();
if (config.tlsEnabled()) {
try {
pipeline.addFirst(SslHandlerFactory.get(ch.alloc(), config, endpointContext));
} catch (Exception e) {
throw new SecurityException("Could not instantiate SSL Handler", e);
}
}
if (env.ioConfig().servicesToCapture().contains(serviceType)) {
pipeline.addLast(new TrafficCaptureHandler(endpointContext));
}
pipelineInitializer().init(BaseEndpoint.this, pipeline);
pipeline.addLast(new PipelineErrorHandler(BaseEndpoint.this));
}
});
if (env.ioConfig().tcpKeepAlivesEnabled() && !(eventLoopGroup instanceof DefaultEventLoopGroup)) {
channelBootstrap.option(ChannelOption.SO_KEEPALIVE, true);
if (eventLoopGroup instanceof EpollEventLoopGroup) {
channelBootstrap.option(EpollChannelOption.TCP_KEEPIDLE, (int) TimeUnit.MILLISECONDS.toSeconds(env.ioConfig().tcpKeepAliveTime().toMillis()));
}
}
state.transition(EndpointState.CONNECTING);
attemptStart.set(System.nanoTime());
return channelFutureIntoMono(channelBootstrap.connect());
}).timeout(endpointContext.environment().timeoutConfig().connectTimeout()).onErrorResume(throwable -> {
state.transition(EndpointState.DISCONNECTED);
if (disconnect.get()) {
endpointContext.environment().eventBus().publish(new EndpointConnectionAbortedEvent(Duration.ofNanos(System.nanoTime() - attemptStart.get()), endpointContext, ConnectTimings.toMap(channel)));
return Mono.empty();
} else {
return Mono.error(throwable);
}
}).retryWhen(Retry.any().exponentialBackoff(Duration.ofMillis(32), Duration.ofMillis(4096)).retryMax(Long.MAX_VALUE).doOnRetry(retryContext -> {
Throwable ex = retryContext.exception();
// We drop the severity for the BucketNotFoundException because it shows up when
// bootstrapping against MDS clusters and nodes with no kv service enabled on it
// that is bucket aware. If a bucket really does not exist we'll get an auth
// exception instead.
Event.Severity severity = ex instanceof BucketNotFoundException ? Event.Severity.DEBUG : Event.Severity.WARN;
Duration duration = ex instanceof TimeoutException ? endpointContext.environment().timeoutConfig().connectTimeout() : Duration.ofNanos(System.nanoTime() - attemptStart.get());
ex = annotateConnectException(ex);
endpointContext.environment().eventBus().publish(new EndpointConnectionFailedEvent(severity, duration, endpointContext, retryContext.iteration(), trimNettyFromStackTrace(ex)));
}).toReactorRetry()).subscribe(channel -> {
long now = System.nanoTime();
if (disconnect.get()) {
this.channel = null;
endpointContext.environment().eventBus().publish(new EndpointConnectionIgnoredEvent(Duration.ofNanos(now - attemptStart.get()), endpointContext, ConnectTimings.toMap(channel)));
closeChannel(channel);
} else {
this.channel = channel;
Optional<HostAndPort> localSocket = Optional.empty();
if (channel.localAddress() instanceof InetSocketAddress) {
// it will always be an inet socket address, but to safeguard for testing mocks...
InetSocketAddress so = (InetSocketAddress) channel.localAddress();
localSocket = Optional.of(new HostAndPort(so.getHostString(), so.getPort()));
}
EndpointContext newContext = new EndpointContext(endpointContext, endpointContext.remoteSocket(), endpointContext.circuitBreaker(), endpointContext.serviceType(), localSocket, endpointContext.bucket(), Optional.ofNullable(channel.attr(ChannelAttributes.CHANNEL_ID_KEY).get()));
this.endpointContext.get().environment().eventBus().publish(new EndpointConnectedEvent(Duration.ofNanos(now - attemptStart.get()), newContext, ConnectTimings.toMap(channel)));
this.endpointContext.set(newContext);
this.circuitBreaker.reset();
lastConnectedAt = now;
state.transition(EndpointState.CONNECTED);
}
}, error -> endpointContext.environment().eventBus().publish(new UnexpectedEndpointConnectionFailedEvent(Duration.ofNanos(System.nanoTime() - attemptStart.get()), endpointContext, error)));
}
use of com.couchbase.client.core.deps.io.netty.channel.ChannelInitializer in project couchbase-jvm-clients by couchbase.
the class BaseEndpointIntegrationTest method startLocalServer.
private LocalServerController startLocalServer(final DefaultEventLoopGroup eventLoopGroup) {
final LocalServerController localServerController = new LocalServerController();
ServerBootstrap bootstrap = new ServerBootstrap().group(eventLoopGroup).localAddress(new LocalAddress("server")).childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
localServerController.channel.set(ctx.channel());
localServerController.connectAttempts.incrementAndGet();
ctx.fireChannelActive();
}
});
}
}).channel(LocalServerChannel.class);
bootstrap.bind().awaitUninterruptibly();
return localServerController;
}
use of com.couchbase.client.core.deps.io.netty.channel.ChannelInitializer in project couchbase-jvm-clients by couchbase.
the class QueryMessageHandlerBackpressureTest method requestRecordsExplicitly.
/**
* This test makes sure that even if the server returns a good bunch of data, each individual
* chunk is requested by the caller explicitly.
*/
@Test
void requestRecordsExplicitly() throws Exception {
EndpointContext endpointContext = new EndpointContext(core.context(), new HostAndPort("127.0.0.1", 1234), NoopCircuitBreaker.INSTANCE, ServiceType.QUERY, Optional.empty(), Optional.empty(), Optional.empty());
BaseEndpoint endpoint = mock(BaseEndpoint.class);
when(endpoint.pipelined()).thenReturn(false);
Bootstrap client = new Bootstrap().channel(LocalChannel.class).group(new DefaultEventLoopGroup()).remoteAddress(new LocalAddress("s1")).handler(new ChannelInitializer<LocalChannel>() {
@Override
protected void initChannel(LocalChannel ch) {
ch.pipeline().addLast(new HttpClientCodec()).addLast(new QueryMessageHandler(endpoint, endpointContext));
}
});
Channel channel = client.connect().awaitUninterruptibly().channel();
final List<byte[]> rows = Collections.synchronizedList(new ArrayList<>());
QueryRequest request = new QueryRequest(Duration.ofSeconds(1), endpointContext, BestEffortRetryStrategy.INSTANCE, endpointContext.authenticator(), "select 1=1", "myquery".getBytes(UTF_8), true, null, null, null, null, null);
channel.writeAndFlush(request);
final QueryResponse response = request.response().get();
assertEquals(0, rows.size());
StepVerifier.create(response.rows().map(v -> new String(v.data(), UTF_8)), 0).thenRequest(1).expectNext("{\"foo\":1}").thenRequest(1).expectNext("{\"bar\":1}").thenRequest(2).expectNext("{\"faz\":1}", "{\"baz\":1}").thenRequest(4).expectNext("{\"fazz\":1}", "{\"bazz\":1}", "{\"fizz\":1}", "{\"bizz\":1}").expectComplete().verify();
}
Aggregations