Example usage for io.netty.channel ChannelHandlerContext executor

List of usage examples for io.netty.channel ChannelHandlerContext executor

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext executor.

Prototype

EventExecutor executor();

Source Link

Document

Returns the EventExecutor which is used to execute an arbitrary task.

Usage

From source file:org.dcache.xrootd.door.ConcurrentXrootdRequestHandler.java

License:Open Source License

@Override
protected ChannelFuture respond(ChannelHandlerContext ctx, Object response) {
    CDC cdc = new CDC();
    ChannelPromise promise = ctx.newPromise();
    ctx.executor().execute(() -> {
        try (CDC ignored = cdc.restore()) {
            ctx.writeAndFlush(response).addListener(future -> {
                if (!future.isSuccess()) {
                    exceptionCaught(ctx, future.cause());
                }/*from ww w . j a va2 s .  com*/
            }).addListener(new ChannelPromiseNotifier(promise));
        }
    });
    return promise;
}

From source file:org.eclipse.milo.opcua.stack.client.handlers.UaTcpClientAcknowledgeHandler.java

License:Open Source License

private void onAcknowledge(ChannelHandlerContext ctx, ByteBuf buffer) {
    if (helloTimeout != null && !helloTimeout.cancel()) {
        helloTimeout = null;// ww  w.j  a v a 2s.  co m
        handshakeFuture.completeExceptionally(
                new UaException(StatusCodes.Bad_Timeout, "timed out waiting for acknowledge"));
        ctx.close();
        return;
    }

    logger.debug("Received Acknowledge message on channel={}.", ctx.channel());

    buffer.skipBytes(3 + 1 + 4); // Skip messageType, chunkType, and messageSize

    AcknowledgeMessage acknowledge = AcknowledgeMessage.decode(buffer);

    long remoteProtocolVersion = acknowledge.getProtocolVersion();
    long remoteReceiveBufferSize = acknowledge.getReceiveBufferSize();
    long remoteSendBufferSize = acknowledge.getSendBufferSize();
    long remoteMaxMessageSize = acknowledge.getMaxMessageSize();
    long remoteMaxChunkCount = acknowledge.getMaxChunkCount();

    if (PROTOCOL_VERSION > remoteProtocolVersion) {
        logger.warn("Client protocol version ({}) does not match server protocol version ({}).",
                PROTOCOL_VERSION, remoteProtocolVersion);
    }

    ChannelConfig config = client.getChannelConfig();

    /* Our receive buffer size is determined by the remote send buffer size. */
    long localReceiveBufferSize = Math.min(remoteSendBufferSize, config.getMaxChunkSize());

    /* Our send buffer size is determined by the remote receive buffer size. */
    long localSendBufferSize = Math.min(remoteReceiveBufferSize, config.getMaxChunkSize());

    /* Max message size the remote can send us; not influenced by remote configuration. */
    long localMaxMessageSize = config.getMaxMessageSize();

    /* Max chunk count the remote can send us; not influenced by remote configuration. */
    long localMaxChunkCount = config.getMaxChunkCount();

    ChannelParameters parameters = new ChannelParameters(Ints.saturatedCast(localMaxMessageSize),
            Ints.saturatedCast(localReceiveBufferSize), Ints.saturatedCast(localSendBufferSize),
            Ints.saturatedCast(localMaxChunkCount), Ints.saturatedCast(remoteMaxMessageSize),
            Ints.saturatedCast(remoteReceiveBufferSize), Ints.saturatedCast(remoteSendBufferSize),
            Ints.saturatedCast(remoteMaxChunkCount));

    ctx.channel().attr(KEY_AWAITING_HANDSHAKE).set(awaitingHandshake);

    ctx.executor().execute(() -> {
        int maxArrayLength = client.getChannelConfig().getMaxArrayLength();
        int maxStringLength = client.getChannelConfig().getMaxStringLength();

        SerializationQueue serializationQueue = new SerializationQueue(client.getConfig().getExecutor(),
                parameters, maxArrayLength, maxStringLength);

        UaTcpClientMessageHandler handler = new UaTcpClientMessageHandler(client, secureChannel,
                serializationQueue, handshakeFuture);

        ctx.pipeline().addLast(handler);
    });
}

From source file:org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientAcknowledgeHandler.java

License:Open Source License

private void onAcknowledge(ChannelHandlerContext ctx, ByteBuf buffer) {
    if (helloTimeout != null && !helloTimeout.cancel()) {
        helloTimeout = null;/*from ww w.jav a  2  s .co  m*/
        handshakeFuture.completeExceptionally(
                new UaException(StatusCodes.Bad_Timeout, "timed out waiting for acknowledge"));
        ctx.close();
        return;
    }

    logger.debug("Received Acknowledge message on channel={}.", ctx.channel());

    buffer.skipBytes(3 + 1 + 4); // Skip messageType, chunkType, and messageSize

    AcknowledgeMessage acknowledge = AcknowledgeMessage.decode(buffer);

    long remoteProtocolVersion = acknowledge.getProtocolVersion();
    long remoteReceiveBufferSize = acknowledge.getReceiveBufferSize();
    long remoteSendBufferSize = acknowledge.getSendBufferSize();
    long remoteMaxMessageSize = acknowledge.getMaxMessageSize();
    long remoteMaxChunkCount = acknowledge.getMaxChunkCount();

    if (PROTOCOL_VERSION > remoteProtocolVersion) {
        logger.warn("Client protocol version ({}) does not match server protocol version ({}).",
                PROTOCOL_VERSION, remoteProtocolVersion);
    }

    MessageLimits messageLimits = config.getMessageLimits();

    /* Our receive buffer size is determined by the remote send buffer size. */
    long localReceiveBufferSize = Math.min(remoteSendBufferSize, messageLimits.getMaxChunkSize());

    /* Our send buffer size is determined by the remote receive buffer size. */
    long localSendBufferSize = Math.min(remoteReceiveBufferSize, messageLimits.getMaxChunkSize());

    /* Max message size the remote can send us; not influenced by remote configuration. */
    long localMaxMessageSize = messageLimits.getMaxMessageSize();

    /* Max chunk count the remote can send us; not influenced by remote configuration. */
    long localMaxChunkCount = messageLimits.getMaxChunkCount();

    ChannelParameters parameters = new ChannelParameters(Ints.saturatedCast(localMaxMessageSize),
            Ints.saturatedCast(localReceiveBufferSize), Ints.saturatedCast(localSendBufferSize),
            Ints.saturatedCast(localMaxChunkCount), Ints.saturatedCast(remoteMaxMessageSize),
            Ints.saturatedCast(remoteReceiveBufferSize), Ints.saturatedCast(remoteSendBufferSize),
            Ints.saturatedCast(remoteMaxChunkCount));

    ctx.channel().attr(KEY_AWAITING_HANDSHAKE).set(awaitingHandshake);

    ctx.executor().execute(() -> {
        SerializationQueue serializationQueue = new SerializationQueue(config.getExecutor(), parameters,
                config.getEncodingLimits());

        UascClientMessageHandler handler = new UascClientMessageHandler(config, secureChannel,
                serializationQueue, handshakeFuture);

        ctx.pipeline().addLast(handler);
    });
}

From source file:org.eclipse.milo.opcua.stack.client.transport.uasc.UascClientMessageHandler.java

License:Open Source License

private void installSecurityToken(ChannelHandlerContext ctx, OpenSecureChannelResponse response) {
    ChannelSecurity.SecurityKeys newKeys = null;
    if (response.getServerProtocolVersion().longValue() < PROTOCOL_VERSION) {
        throw new UaRuntimeException(StatusCodes.Bad_ProtocolVersionUnsupported,
                "server protocol version unsupported: " + response.getServerProtocolVersion());
    }//w  w w  .j  a v a2s . com

    ChannelSecurityToken newToken = response.getSecurityToken();

    if (secureChannel.isSymmetricSigningEnabled()) {
        secureChannel.setRemoteNonce(response.getServerNonce());

        newKeys = ChannelSecurity.generateKeyPair(secureChannel, secureChannel.getLocalNonce(),
                secureChannel.getRemoteNonce());
    }

    ChannelSecurity oldSecrets = secureChannel.getChannelSecurity();
    ChannelSecurity.SecurityKeys oldKeys = oldSecrets != null ? oldSecrets.getCurrentKeys() : null;
    ChannelSecurityToken oldToken = oldSecrets != null ? oldSecrets.getCurrentToken() : null;

    secureChannel.setChannelSecurity(new ChannelSecurity(newKeys, newToken, oldKeys, oldToken));

    DateTime createdAt = response.getSecurityToken().getCreatedAt();
    long revisedLifetime = response.getSecurityToken().getRevisedLifetime().longValue();

    if (revisedLifetime > 0) {
        long renewAt = (long) (revisedLifetime * 0.75);
        renewFuture = ctx.executor().schedule(
                () -> sendOpenSecureChannelRequest(ctx, SecurityTokenRequestType.Renew), renewAt,
                TimeUnit.MILLISECONDS);
    } else {
        logger.warn("Server revised secure channel lifetime to 0; renewal will not occur.");
    }

    ctx.executor().execute(() -> {
        // SecureChannel is ready; remove the acknowledge handler.
        if (ctx.pipeline().get(UascClientAcknowledgeHandler.class) != null) {
            ctx.pipeline().remove(UascClientAcknowledgeHandler.class);
        }
    });

    ChannelSecurity channelSecurity = secureChannel.getChannelSecurity();

    long currentTokenId = channelSecurity.getCurrentToken().getTokenId().longValue();

    long previousTokenId = channelSecurity.getPreviousToken().map(t -> t.getTokenId().longValue()).orElse(-1L);

    logger.debug("SecureChannel id={}, currentTokenId={}, previousTokenId={}, lifetime={}ms, createdAt={}",
            secureChannel.getChannelId(), currentTokenId, previousTokenId, revisedLifetime, createdAt);
}

From source file:org.eclipse.milo.opcua.stack.server.transport.RateLimitingHandler.java

License:Open Source License

@Override
protected void channelAccepted(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) {
    final InetAddress address = remoteAddress.getAddress();

    if (!enabled || address.isLoopbackAddress()) {
        return;// www .ja  va 2 s  .c om
    }

    connections.add(address);

    ctx.channel().closeFuture().addListener((ChannelFutureListener) future -> {
        connections.remove(address);

        if (connections.count(address) == 0) {
            logger.debug("Scheduling timestamp removal for " + address);

            ctx.executor().schedule(() -> {
                // If there's still no connections from the remote address after the rate limit window remove
                // the timestamps.
                // Removing them before the window elapses would allow a remote address to connect/disconnect
                // at an effectively unlimited rate.
                if (connections.count(address) == 0) {
                    timestamps.remove(address);
                    logger.debug("Removed timestamps for " + address);
                }
            }, rateLimitWindowMs, TimeUnit.MILLISECONDS);
        }
    });
}

From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerHelloHandler.java

License:Open Source License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    int helloDeadlineMs = Stack.ConnectionLimits.HELLO_DEADLINE_MS;

    logger.debug("Scheduling Hello deadline for +" + helloDeadlineMs + "ms");

    ctx.executor().schedule(() -> {
        if (!receivedHello) {
            long cumulativeDeadlinesMissed = CUMULATIVE_DEADLINES_MISSED.incrementAndGet();

            logger.debug("No Hello received after " + helloDeadlineMs + "ms; closing channel. "
                    + "cumulativeDeadlinesMissed=" + cumulativeDeadlinesMissed);

            ctx.close();/*w  w  w .  j  a va 2 s .co  m*/
        }
    }, helloDeadlineMs, TimeUnit.MILLISECONDS);

    super.channelActive(ctx);
}

From source file:org.eclipse.milo.opcua.stack.server.transport.uasc.UascServerHelloHandler.java

License:Open Source License

private void onHello(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException {
    logger.debug("[remote={}] Received Hello message.", ctx.channel().remoteAddress());

    receivedHello = true;//  w  w  w.  j  a  v a 2s  . co m

    final HelloMessage hello = TcpMessageDecoder.decodeHello(buffer);

    String endpointUrl = hello.getEndpointUrl();

    boolean endpointMatch = stackServer.getEndpointDescriptions().stream().anyMatch(endpoint -> Objects
            .equals(EndpointUtil.getPath(endpointUrl), EndpointUtil.getPath(endpoint.getEndpointUrl())));

    if (!endpointMatch) {
        throw new UaException(StatusCodes.Bad_TcpEndpointUrlInvalid,
                "unrecognized endpoint url: " + endpointUrl);
    }

    ctx.channel().attr(ENDPOINT_URL_KEY).set(endpointUrl);

    long remoteProtocolVersion = hello.getProtocolVersion();
    long remoteReceiveBufferSize = hello.getReceiveBufferSize();
    long remoteSendBufferSize = hello.getSendBufferSize();
    long remoteMaxMessageSize = hello.getMaxMessageSize();
    long remoteMaxChunkCount = hello.getMaxChunkCount();

    if (remoteProtocolVersion < PROTOCOL_VERSION) {
        throw new UaException(StatusCodes.Bad_ProtocolVersionUnsupported,
                "unsupported protocol version: " + remoteProtocolVersion);
    }

    MessageLimits config = stackServer.getConfig().getMessageLimits();

    /* Our receive buffer size is determined by the remote send buffer size. */
    long localReceiveBufferSize = Math.min(remoteSendBufferSize, config.getMaxChunkSize());

    /* Our send buffer size is determined by the remote receive buffer size. */
    long localSendBufferSize = Math.min(remoteReceiveBufferSize, config.getMaxChunkSize());

    /* Max chunk count the remote can send us; not influenced by remote configuration. */
    long localMaxChunkCount = config.getMaxChunkCount();

    /* Max message size the remote can send us. Determined by our max chunk count and receive buffer size. */
    long localMaxMessageSize = Math.min(localReceiveBufferSize * localMaxChunkCount,
            config.getMaxMessageSize());

    ChannelParameters parameters = new ChannelParameters(Ints.saturatedCast(localMaxMessageSize),
            Ints.saturatedCast(localReceiveBufferSize), Ints.saturatedCast(localSendBufferSize),
            Ints.saturatedCast(localMaxChunkCount), Ints.saturatedCast(remoteMaxMessageSize),
            Ints.saturatedCast(remoteReceiveBufferSize), Ints.saturatedCast(remoteSendBufferSize),
            Ints.saturatedCast(remoteMaxChunkCount));

    SerializationQueue serializationQueue = new SerializationQueue(stackServer.getConfig().getExecutor(),
            parameters, stackServer.getConfig().getEncodingLimits());

    ctx.pipeline().addLast(new UascServerAsymmetricHandler(stackServer, transportProfile, serializationQueue));
    ctx.pipeline().remove(this);

    logger.debug("[remote={}] Removed HelloHandler, added AsymmetricHandler.", ctx.channel().remoteAddress());

    AcknowledgeMessage acknowledge = new AcknowledgeMessage(PROTOCOL_VERSION, localReceiveBufferSize,
            localSendBufferSize, localMaxMessageSize, localMaxChunkCount);

    ByteBuf messageBuffer = TcpMessageEncoder.encode(acknowledge);

    // Using ctx.executor() is necessary to ensure this handler is removed
    // before the message can be written and another response arrives.
    ctx.executor().execute(() -> ctx.writeAndFlush(messageBuffer));

    logger.debug("[remote={}] Sent Acknowledge message.", ctx.channel().remoteAddress());
}

From source file:org.eclipse.neoscada.protocol.iec60870.server.data.DataModuleHandler.java

License:Open Source License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    logger.debug("Channel active - {}", ctx);

    // we may and must remember the channel context, to know were to send notifications to
    this.ctx = ctx;

    this.source = new DataModuleMessageSource(this.options, ctx.executor(), new ContextChannelWriter(ctx),
            this.dataModel, this.backgroundScanPeriod);
    this.messageChannel.addSource(this.source);

    this.spontHandler = new DataListenerImpl(this.source);
    this.messageChannel.startTimers();

    super.channelActive(ctx);
}

From source file:org.eclipse.scada.protocol.iec60870.server.data.DataModuleHandler.java

License:Open Source License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    logger.debug("Channel active - {}", ctx);

    // we may and must remember the channel context, to know were to send notifications to
    this.ctx = ctx;

    this.source = new DataModuleMessageSource(this.options, ctx.executor(), new ContextChannelWriter(ctx),
            this.dataModel, this.backgroundScanPeriod);
    this.messageChannel.addSource(this.source);

    this.spontHandler = new DataListenerImpl(this.source, new CauseOfTransmission(StandardCause.SPONTANEOUS));

    super.channelActive(ctx);
}

From source file:org.eclipse.scada.protocol.relp.RelpHandler.java

License:Open Source License

@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    // wait for "open" .. start timeout
    if (this.timeout > 0) {
        logger.debug("Adding timeout: {} seconds", this.timeout);
        this.timeoutTask = ctx.executor().schedule(new Runnable() {

            @Override/* ww  w. j av a 2s . c o m*/
            public void run() {
                processTimeout(ctx);
            }
        }, this.timeout, TimeUnit.MILLISECONDS);
    }
}