Example usage for io.netty.channel.local LocalChannel attr

List of usage examples for io.netty.channel.local LocalChannel attr

Introduction

In this page you can find the example usage for io.netty.channel.local LocalChannel attr.

Prototype

@SuppressWarnings("unchecked")
    @Override
    public <T> Attribute<T> attr(AttributeKey<T> key) 

Source Link

Usage

From source file:org.opendaylight.usc.plugin.UscDemultiplexer.java

License:Open Source License

@Override
protected void channelRead0(ChannelHandlerContext ctx, UscFrame frame) throws Exception {
    LOG.trace("UscDemultiplexer.channelRead: " + frame);

    if (frame instanceof UscControl) {
        UscControl controlMsg = (UscControl) frame;
        if (controlMsg.getControlCode() == UscControl.ControlCode.ECHO) {
            SocketAddress remoteAddress = ctx.channel().remoteAddress();
            promiseMap.get(remoteAddress).set(new Throwable("Success"));
            LOG.trace("channelRead0: promiseMap = " + promiseMap);
            return;
        }//from   ww w  .j  ava 2  s  . c  om
    }

    final UscHeader header = frame.getHeader();
    final int sessionId = header.getSessionId();
    final UscChannelImpl connection = ctx.channel().attr(UscPlugin.CHANNEL).get();

    final UscSessionImpl session = connection.getSession(sessionId);
    final LocalChannel serverChannel = session.getServerChannel();
    if (frame instanceof UscError) {
        // propagate exception to the client channel
        UscSessionException ex = new UscSessionException(((UscError) frame).getErrorCode());

        serverChannel.writeAndFlush(ex);
        plugin.sendEvent(new UscSessionErrorEvent(session, ex));
    } else if (frame instanceof UscData) {

        if (serverChannel != null) {
            LOG.trace("write session " + sessionId + " to " + serverChannel + ": " + frame.getPayload());

            ByteBuf payload = frame.getPayload();

            plugin.sendEvent(new UscSessionTransactionEvent(session, payload.readableBytes(), 0));

            serverChannel.writeAndFlush(payload);
        } else {
            UscChannelException ex = new UscChannelException(
                    "write unknown session " + sessionId + "; discard");
            plugin.sendEvent(new UscChannelErrorEvent(session.getChannel(), ex));

            throw ex;
        }
    } else if (frame instanceof UscControl) {
        UscControl controlMsg = (UscControl) frame;
        Channel clientChannel = serverChannel.attr(UscPlugin.CLIENT_CHANNEL).get();
        if (controlMsg.getControlCode() == UscControl.ControlCode.TERMINATION_REQUEST) {
            LOG.trace("UscDemultiplexer received control message TERMINATION_REQUEST");
            clientChannel.close();

            // send back TERMINATION_RESPONSE
            UscControl data = new UscControl(session.getPort(), session.getSessionId(), 2);
            ctx.channel().writeAndFlush(data);
        } else if (controlMsg.getControlCode() == UscControl.ControlCode.TERMINATION_RESPONSE) {
            LOG.trace("UscDemultiplexer received control message TERMINATION_RESPONSE");
            if (clientChannel != null) {
                SettableFuture<Boolean> status = plugin.getCloseFuture().get(clientChannel);
                status.set(true);
                LOG.trace("UscDemultiplexer: termination status is " + status.get());
            }
        }
    } else {
        LOG.trace("UscDemultiplexer.channelRead: unexpected UscFrame object " + frame);
        UscChannelException ex = new UscChannelException("unexpected UscFrame object " + frame);
        plugin.sendEvent(new UscChannelErrorEvent(session.getChannel(), ex));

        throw ex;
    }
}

From source file:org.opendaylight.usc.plugin.UscPlugin.java

License:Open Source License

protected UscPlugin(LocalAddress localAddr) {
    LOG.debug("UscPlugin " + this + "started");
    localServerAddr = localAddr;//  w  ww.ja  va  2 s  .  com

    final ServerBootstrap localServerBootstrap = new ServerBootstrap();
    localServerBootstrap.group(localGroup);
    localServerBootstrap.channel(LocalServerChannel.class);
    localServerBootstrap.childHandler(new ChannelInitializer<LocalChannel>() {
        @Override
        public void initChannel(final LocalChannel serverChannel) throws Exception {
            ChannelPipeline p = serverChannel.pipeline();
            p.addLast(new LoggingHandler("localServerBootstrp Handler 4", LogLevel.TRACE));

            // call this first so that the attribute will be visible
            // to the outside once the localAddress is set
            serverChannel.attr(SESSION).setIfAbsent(SettableFuture.<UscSessionImpl>create());

            // register the child channel by address for lookup
            // outside
            LocalAddress localAddress = serverChannel.remoteAddress();
            serverChannels.putIfAbsent(localAddress, SettableFuture.<LocalChannel>create());
            serverChannels.get(localAddress).set(serverChannel);

            p.addLast(new LoggingHandler("localServerBootstrp Handler 3", LogLevel.TRACE));

            // add remote device handler for route remote request
            p.addLast(remoteDeviceHandler);
            p.addLast(new LoggingHandler("localServerBootstrp Handler 2", LogLevel.TRACE));
            p.addLast(getMultiplexer());
            p.addLast(new LoggingHandler("localServerBootstrp Handler 1", LogLevel.TRACE));
        }
    });

    // Start the server.
    final ChannelFuture serverChannelFuture = localServerBootstrap.bind(localServerAddr);
    LOG.debug("serverChannel: " + serverChannelFuture);
}

From source file:org.opendaylight.usc.plugin.UscPlugin.java

License:Open Source License

public ChannelFuture connect(Bootstrap clientBootstrap, final InetSocketAddress address, boolean remote)
        throws InterruptedException, ExecutionException, Exception {

    LOG.trace("Attempt to connect to " + address + ",remote is " + remote);
    boolean remoteDevice = false;

    // Connect to USC Agent to the device if one's not already created
    UscChannelImpl connection = null;//  ww w . jav a 2 s .c  om
    Channel directChannel = null;
    UscDevice device = new UscDevice(address.getAddress(), address.getPort());
    UscRouteBrokerService routeBroker = UscServiceUtils.getService(UscRouteBrokerService.class);
    Exception connectException = null;

    if (remote) {
        if (routeBroker != null) {
            if (routeBroker.existRemoteChannel(
                    new UscRemoteChannelIdentifier(device.getInetAddress(), getChannelType()))) {
                remoteDevice = true;
                LOG.trace("Find remote channel for device " + device);
            } else {
                remote = false;
                LOG.warn("remote channel is not found for device " + device + ", try to connect from local.");
            }
        } else {
            LOG.error("Broker service is null, try to connect from local.");
            remote = false;
        }
    }
    if (!remote) {
        if (getChannelType() == ChannelType.DTLS || getChannelType() == ChannelType.UDP) {
            try {
                connection = connectionManager.getConnection(
                        new UscDevice(address.getAddress(), address.getPort()), getChannelType());
            } catch (Exception e) {
                LOG.error("Failed to get udp agent connection, try to directly connect.error is "
                        + e.getMessage());
                connectException = e;
            }

            LOG.trace("Returned connection is " + connection);
            Channel channel = connection.getChannel();
            UscDemultiplexer handler = (UscDemultiplexer) channel.pipeline().get("UscDemultiplexer");
            SocketAddress remoteAddress = channel.remoteAddress();
            if (!handler.promiseMap.containsKey(remoteAddress)) {
                handler.promiseMap.putIfAbsent(remoteAddress, SettableFuture.<Throwable>create());

                UscControl echoControl = new UscControl(address.getPort(), 1,
                        UscControl.ControlCode.ECHO.getCode());
                channel.writeAndFlush(echoControl);
                LOG.trace("Send a ECHO message to see if the usc agent port is reachable.");
            }

            Throwable e = null;
            e = handler.promiseMap.get(remoteAddress).get(5000, TimeUnit.MILLISECONDS);

            if (e != null) {
                LOG.trace("connect: handler.promise is " + e);
                if (e != null && e instanceof PortUnreachableException) {
                    LOG.trace("connect: caught exception PortUnreachableException");
                    channel.close();
                    connectionManager.removeConnection(connection);
                    connection = null;
                    LOG.trace("connect: start connecting to " + address.getAddress() + (":") + address.getPort()
                            + " directly.");
                    try {
                        directChannel = connectToDeviceDirectly(
                                new UscDevice(address.getAddress(), address.getPort()));
                    } catch (Exception ex) {
                        LOG.error("Failed to get direct connection, try to remote connect.error is "
                                + e.getMessage());
                        connectException = ex;
                    }
                }
            }
        } else {
            try {
                connection = connectionManager.getConnection(
                        new UscDevice(address.getAddress(), address.getPort()), getChannelType());
            } catch (Exception e) {
                LOG.error("Failed to get agent connection, try to directly connect.error is " + e.getMessage());
                try {
                    directChannel = connectToDeviceDirectly(
                            new UscDevice(address.getAddress(), address.getPort()));
                } catch (Exception ex) {
                    LOG.error("Failed to get direct connection, try to remote connect.error is "
                            + e.getMessage());
                    connectException = ex;
                }
            }
        }
    }
    if (connectException != null) {
        if (routeBroker != null) {
            if (routeBroker.existRemoteChannel(
                    new UscRemoteChannelIdentifier(device.getInetAddress(), getChannelType()))) {
                remoteDevice = true;
                LOG.trace("Found remote channel for device " + device);
            } else {
                LOG.warn("Failed to find remote channel in device table!");
                throw connectException;
            }
        } else {
            LOG.warn("Broker service is null, can't find exist remote channel, throw exception dirctly.");
            throw connectException;
        }
    }

    final ChannelFuture clientChannelFuture = clientBootstrap.connect(localServerAddr);
    clientChannelFuture.channel().pipeline().addLast(uscExceptionHandler);

    // sync to ensure that localAddress is not null
    final Channel clientChannel = clientChannelFuture.sync().channel();
    SocketAddress localAddress = clientChannel.localAddress();
    serverChannels.putIfAbsent(localAddress, SettableFuture.<LocalChannel>create());

    // wait for the peer to populate
    LocalChannel serverChannel = serverChannels.get(localAddress).get();

    LOG.trace("connect: serverChannel = " + serverChannel);

    assert serverChannel != null;
    // remove the entry from the map as its purpose is complete
    serverChannels.remove(localAddress);

    if (connection != null) {
        UscSessionImpl session = connection.addSession(address.getPort(), serverChannel);

        LOG.trace("clientChannel set session " + session);
        // these attributes are used by unit test cases
        clientChannel.attr(SESSION).setIfAbsent(SettableFuture.<UscSessionImpl>create());
        clientChannel.attr(SESSION).get().set(session);

        // these attributes are used by UscMultiplexer
        serverChannel.attr(SESSION).get().set(session);

        // this attribute is used by UscDemultiplexer
        serverChannel.attr(CLIENT_CHANNEL).set(clientChannel);
        LOG.info("Connected with channel for " + session);
    } else if (directChannel != null) {
        clientChannel.attr(LOCAL_SERVER_CHANNEL).set(serverChannel);
        serverChannel.attr(DIRECT_CHANNEL).set(directChannel);
        serverChannel.attr(CLIENT_CHANNEL).set(clientChannel);
        directChannel.attr(LOCAL_SERVER_CHANNEL).set(serverChannel);
        LOG.info("Connected channel using direct way for " + device);
    }

    if (remoteDevice) {
        UscRemoteChannelIdentifier remoteChannel = new UscRemoteChannelIdentifier(device.getInetAddress(),
                getChannelType());
        UscRouteIdentifier routeId = new UscRouteIdentifier(remoteChannel, serverChannel.hashCode(),
                address.getPort());
        clientChannel.attr(ROUTE_IDENTIFIER).setIfAbsent(routeId);
        serverChannel.attr(ROUTE_IDENTIFIER).setIfAbsent(routeId);
        sendEvent(new UscChannelCreateEvent(remoteChannel.getIp(), true, remoteChannel.getRemoteChannelType()));
        // register local session for routing to remote device
        routeBroker.addLocalSession(routeId, serverChannel);
        if (directChannel != null) {
            // direct connection only has one session
            directChannel.attr(ROUTE_IDENTIFIER).set(routeId);
        }
        LOG.info("Initialized local remote channel for " + routeId);
    }
    return clientChannelFuture;
}