Java Code Examples for org.jboss.netty.channel.Channel#close()

The following examples show how to use org.jboss.netty.channel.Channel#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NettyClient.java    From jstorm with Apache License 2.0 6 votes vote down vote up
/**
 * Avoid channel double close
 */
void closeChannel(final Channel channel) {
    synchronized (channelClosing) {
        if (closingChannel.contains(channel)) {
            LOG.info(channel.toString() + " has already been closed");
            return;
        }

        closingChannel.add(channel);
    }

    LOG.debug(channel.toString() + " begin to close");
    ChannelFuture closeFuture = channel.close();
    closeFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {

            synchronized (channelClosing) {
                closingChannel.remove(channel);
            }
            LOG.debug(channel.toString() + " closed.");
        }
    });
}
 
Example 2
Source File: RemoteSyncChannelHandler.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@Override
protected void handleError(ErrorMessage error, Channel channel) {            
    ErrorType errType = ErrorType.GENERIC;
    for (ErrorType e : ErrorType.values()) {
        if (e.getValue() == error.getError().getErrorCode()) {
            errType = e;
            break;
        }
    }
    SyncException ex = 
            SyncException.newInstance(errType, 
                                      error.getError().getMessage(), 
                                      null);
    if (ChannelState.CONNECTED.equals(channelState) ||
        ChannelState.OPEN.equals(channelState) ||
        ErrorType.AUTH.equals(errType)) {
        syncManager.channelDisconnected(ex);
        channel.close();
    } else {
        SyncReply reply = new SyncReply(null, null, false, ex, 0);
        syncManager.dispatchReply(error.getHeader().getTransactionId(), 
                                  reply);
    }
}
 
Example 3
Source File: AbstractRPCChannelHandler.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@LogMessageDoc(level="WARN",
               message="Failed to authenticate connection from {remote}: {message}",
               explanation="Challenge/Response authentication failed",
               recommendation="Check the included error message, and " + 
                       "verify the shared secret is correctly-configured")
protected void handshake(HelloMessage request, Channel channel) {
    try {
        switch (getAuthScheme()) {
            case CHALLENGE_RESPONSE:
                handshakeChallengeResponse(request, channel);
                break;
            case NO_AUTH:
                // shouldn't get here
                break;
        }
    } catch (AuthException e) {
        logger.warn("[{}->{}] Failed to authenticate connection: {}",
                    new Object[]{getLocalNodeIdString(), 
                                 getRemoteNodeIdString(), 
                                 e.getMessage()});
        channel.write(getError(request.getHeader().getTransactionId(), 
                               e, MessageType.HELLO));
        channel.close();
    }
}
 
Example 4
Source File: ClientBootstrap.java    From android-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts a new connection with the specified {@code remoteAddress} and
 * the specified {@code localAddress}.  If the specified local address is
 * {@code null}, the local address of a new channel is determined
 * automatically.
 *
 * @return a future object which notifies when this connection attempt
 *         succeeds or fails
 *
 * @throws ChannelPipelineException
 *         if this bootstrap's {@link #setPipelineFactory(ChannelPipelineFactory) pipelineFactory}
 *            failed to create a new {@link ChannelPipeline}
 */
public ChannelFuture connect(final SocketAddress remoteAddress, final SocketAddress localAddress) {

    if (remoteAddress == null) {
        throw new NullPointerException("remoteAddress");
    }

    ChannelPipeline pipeline;
    try {
        pipeline = getPipelineFactory().getPipeline();
    } catch (Exception e) {
        throw new ChannelPipelineException("Failed to initialize a pipeline.", e);
    }

    // Set the options.
    Channel ch = getFactory().newChannel(pipeline);
    boolean success = false;
    try {
        ch.getConfig().setOptions(getOptions());
        success = true;
    } finally {
        if (!success) {
            ch.close();
        }
    }

    // Bind.
    if (localAddress != null) {
        ch.bind(localAddress);
    }

    // Connect.
    return ch.connect(remoteAddress);
}
 
Example 5
Source File: DefaultPinpointClientHandler.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private void closeChannel() {
    Channel channel = this.channel;
    if (channel != null) {
        sendClosedPacket(channel);

        ChannelFuture closeFuture = channel.close();
        closeFuture.addListener(new WriteFailFutureListener(logger, "close() event failed.", "close() event success."));
        closeFuture.awaitUninterruptibly();
    }
}
 
Example 6
Source File: Connection.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private Channel newChannel(ChannelPipeline pipeline) {
    // Set the options.
    final Channel ch = this.channelFactory.newChannel(pipeline);
    boolean success = false;
    try {
        ch.getConfig().setOptions(socketOption.toMap());
        success = true;
    } finally {
        if (!success) {
            ch.close();
        }
    }
    return ch;
}
 
Example 7
Source File: NetworkFailureHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent event) throws Exception {
	// Suspend incoming traffic until connected to the remote host.
	final Channel sourceChannel = event.getChannel();
	sourceChannel.setReadable(false);

	boolean isBlocked = blocked.get();
	LOG.debug("Attempt to open proxy channel from [{}] to [{}:{}] in state [blocked = {}]",
		sourceChannel.getLocalAddress(),
		remoteHost,
		remotePort,
		isBlocked);

	if (isBlocked) {
		sourceChannel.close();
		return;
	}

	// Start the connection attempt.
	ClientBootstrap targetConnectionBootstrap = new ClientBootstrap(channelFactory);
	targetConnectionBootstrap.getPipeline().addLast(TARGET_CHANNEL_HANDLER_NAME, new TargetChannelHandler(event.getChannel(), blocked));
	ChannelFuture connectFuture = targetConnectionBootstrap.connect(new InetSocketAddress(remoteHost, remotePort));
	sourceToTargetChannels.put(sourceChannel, connectFuture.getChannel());

	connectFuture.addListener(future -> {
		if (future.isSuccess()) {
			// Connection attempt succeeded:
			// Begin to accept incoming traffic.
			sourceChannel.setReadable(true);
		} else {
			// Close the connection if the connection attempt has failed.
			sourceChannel.close();
		}
	});
}
 
Example 8
Source File: NetworkFailureHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent event) throws Exception {
	// Suspend incoming traffic until connected to the remote host.
	final Channel sourceChannel = event.getChannel();
	sourceChannel.setReadable(false);

	boolean isBlocked = blocked.get();
	LOG.debug("Attempt to open proxy channel from [{}] to [{}:{}] in state [blocked = {}]",
		sourceChannel.getLocalAddress(),
		remoteHost,
		remotePort,
		isBlocked);

	if (isBlocked) {
		sourceChannel.close();
		return;
	}

	// Start the connection attempt.
	ClientBootstrap targetConnectionBootstrap = new ClientBootstrap(channelFactory);
	targetConnectionBootstrap.getPipeline().addLast(TARGET_CHANNEL_HANDLER_NAME, new TargetChannelHandler(event.getChannel(), blocked));
	ChannelFuture connectFuture = targetConnectionBootstrap.connect(new InetSocketAddress(remoteHost, remotePort));
	sourceToTargetChannels.put(sourceChannel, connectFuture.getChannel());

	connectFuture.addListener(future -> {
		if (future.isSuccess()) {
			// Connection attempt succeeded:
			// Begin to accept incoming traffic.
			sourceChannel.setReadable(true);
		} else {
			// Close the connection if the connection attempt has failed.
			sourceChannel.close();
		}
	});
}
 
Example 9
Source File: RPCChannelHandler.java    From floodlight_with_topoguard with Apache License 2.0 4 votes vote down vote up
@Override
@LogMessageDoc(level="ERROR",
          message="[{id}->{id}] Attempted connection from unrecognized " +
                  "floodlight node {id}; disconnecting",
          explanation="A unknown node connected.  This can happen " +
                  "transiently if new nodes join the cluster.",
          recommendation="If the problem persists, verify your cluster" +
            "configuration and that you don't have unauthorized agents " +
            "in your network.")
protected void handleHello(HelloMessage hello, Channel channel) {
    if (!hello.isSetNodeId()) {
        // this is a client connection.  Don't set this up as a node
        // connection
        isClientConnection = true;
        return;
    }
    remoteNode = syncManager.getClusterConfig().getNode(hello.getNodeId());
    if (remoteNode == null) {
        logger.error("[{}->{}] Attempted connection from unrecognized " +
                     "floodlight node {}; disconnecting",
                     new Object[]{getLocalNodeIdString(),
                                  getRemoteNodeIdString(),
                                  hello.getNodeId()});
        channel.close();
        return;
    }
    rpcService.nodeConnected(remoteNode.getNodeId(), channel);

    FullSyncRequestMessage srm = new FullSyncRequestMessage();
    AsyncMessageHeader header = new AsyncMessageHeader();
    header.setTransactionId(getTransactionId());
    srm.setHeader(header);
    SyncMessage bsm = new SyncMessage(MessageType.FULL_SYNC_REQUEST);
    channel.write(bsm);

    // XXX - TODO - if last connection was longer ago than the tombstone
    // timeout, then we need to do a complete flush and reload of our
    // state.  This is complex though since this applies across entire
    // partitions and not just single nodes.  We'd need to identify the
    // partition and nuke the smaller half (or lower priority in the case
    // of an even split).  Downstream listeners would need to be able to
    // handle a state nuke as well. A simple way to nuke would be to ensure
    // floodlight is restarted in the smaller partition.
}
 
Example 10
Source File: BgpControllerImplTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Peer1 has Node NLRI (MpReach) and Peer2 has node NLRI with different MpReach
 * and MpUnReach with IsIsNonPseudonode.
 */
@Test
public void testBgpUpdateMessage9() throws InterruptedException {
    // Initiate the connections
    peer1.peerChannelHandler.asNumber = 200;
    peer1.peerChannelHandler.version = 4;
    peer1.peerChannelHandler.holdTime = 120;

    short afi = 16388;
    byte res = 0;
    byte safi = (byte) 0x80;

    bgpControllerImpl.getConfig().setLsCapability(true);
    BgpValueType tempTlv1 = new MultiProtocolExtnCapabilityTlv(afi, res, safi);
    peer1.peerChannelHandler.capabilityTlv.add(tempTlv1);
    Channel channel = peer1.connectFrom(connectToSocket, new InetSocketAddress("127.0.0.30", 0));
    TimeUnit.MILLISECONDS.sleep(1000);

    //Get peer1
    BgpId bgpId = new BgpId(IpAddress.valueOf("127.0.0.30"));
    BgpPeerImpl peer = (BgpPeerImpl) bgpControllerImpl.getPeer(bgpId);

    LinkedList<BgpValueType> subTlvs = new LinkedList<>();
    BgpValueType tlv = AutonomousSystemTlv.of(2478);
    subTlvs.add(tlv);
    tlv = BgpLSIdentifierTlv.of(33686018);
    subTlvs.add(tlv);

    NodeDescriptors nodeDes = new NodeDescriptors(subTlvs, (short) 0x10, (short) 256);
    BgpNodeLSIdentifier key = new BgpNodeLSIdentifier(nodeDes);
    RouteDistinguisher rd = new RouteDistinguisher((long) 0x0A);
    VpnAdjRibIn vpnAdj = peer.vpnAdjRib();

    //In Adj-RIB, vpnNodeTree should contain specified rd
    assertThat(vpnAdj.vpnNodeTree().containsKey(rd), is(true));

    Map<BgpNodeLSIdentifier, PathAttrNlriDetails> treeValue = vpnAdj.vpnNodeTree().get(rd);
    //In Adj-RIB, vpnNodeTree should contain specified rd with specified value
    assertThat(treeValue.containsKey(key), is(true));

    BgpLocalRibImpl obj = (BgpLocalRibImpl) bgpControllerImpl.bgpLocalRibVpn();
    //In Local-RIB, vpnNodeTree should contain specified rd
    assertThat(obj.vpnNodeTree().containsKey(rd), is(true));

    Map<BgpNodeLSIdentifier, PathAttrNlriDetailsLocalRib> value = obj.vpnNodeTree().get(rd);
    //In Local-RIB, vpnNodeTree should contain specified rd with specified value
    assertThat(value.containsKey(key), is(true));

    peer2.peerChannelHandler.asNumber = 200;
    peer2.peerChannelHandler.version = 4;
    peer2.peerChannelHandler.holdTime = 120;

    bgpControllerImpl.getConfig().setLsCapability(true);
    tempTlv1 = new MultiProtocolExtnCapabilityTlv(afi, res, safi);
    peer2.peerChannelHandler.capabilityTlv.add(tempTlv1);
    peer2.connectFrom(connectToSocket, new InetSocketAddress("127.0.0.50", 0));
    TimeUnit.MILLISECONDS.sleep(1000);

    //Get peer2
    bgpId = new BgpId(IpAddress.valueOf("127.0.0.50"));
    peer = (BgpPeerImpl) bgpControllerImpl.getPeer(bgpId);
    key = new BgpNodeLSIdentifier(nodeDes);
    vpnAdj = peer.vpnAdjRib();

    //In Adj-RIB, vpnNodeTree should be empty
    assertThat(vpnAdj.vpnNodeTree().isEmpty(), is(true));

    //peer1 disconnects
    channel.disconnect();
    channel.close();

    obj = (BgpLocalRibImpl) bgpControllerImpl.bgpLocalRibVpn();
    TimeUnit.MILLISECONDS.sleep(200);

    //In Local-RIB, vpnNodeTree should be empty
    assertThat(obj.vpnNodeTree().isEmpty(), is(true));
}
 
Example 11
Source File: HealthCheckManager.java    From pinpoint with Apache License 2.0 4 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (isStopped) {
        return;
    }

    if (timeout.isCancelled()) {
        registerTask(this);
        return;
    }

    for (Channel channel : channelGroup) {
        PinpointServer pinpointServer = getPinpointServer(channel);
        if (pinpointServer == null) {
            continue;
        }

        HealthCheckState healthCheckState = pinpointServer.getHealthCheckState();
        switch (healthCheckState) {
            case RECEIVED:
                if (isDebug) {
                    logger.debug("ping write. channel:{}, packet:{}.", channel, PING_PACKET);
                }
                channel.write(PING_PACKET).addListener(writeFailListener);
                break;
            case RECEIVED_LEGACY:
                if (isDebug) {
                    logger.debug("ping write. channel:{}, packet:{}.", channel, LEGACY_PING_PACKET);
                }
                channel.write(LEGACY_PING_PACKET).addListener(writeFailListener);
                break;
            case WAIT:
                if (hasExpiredReceivingPing(pinpointServer)) {
                    logger.warn("expired while waiting to receive ping. channel:{} will be closed", channel);
                    channel.close();
                }
                break;
        }
    }

    if (!isStopped) {
        registerTask(this);
    }
}
 
Example 12
Source File: NettyClient.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try{
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
        
        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // 关闭旧的连接
                Channel oldChannel = NettyClient.this.channel; // copy reference
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + " client-side timeout "
                    + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
                    + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    }finally{
        if (! isConnected()) {
            future.cancel();
        }
    }
}
 
Example 13
Source File: NettyTcpClientTransport.java    From msgpack-rpc-java with Apache License 2.0 4 votes vote down vote up
@Override
protected void closeChannel(Channel c) {
    c.close();
}
 
Example 14
Source File: BgpControllerImplTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Peer1 has Node NLRI and Peer2 has Node NLRI with different MpReach and MpUnReach.
 */
@Test
public void testBgpUpdateMessage5() throws InterruptedException, TestUtilsException {
    // Initiate the connections
    peer1.peerChannelHandler.asNumber = 200;
    peer1.peerChannelHandler.version = 4;
    peer1.peerChannelHandler.holdTime = 120;

    short afi = 16388;
    byte res = 0;
    byte safi = 71;

    bgpControllerImpl.getConfig().setLsCapability(true);
    BgpValueType tempTlv1 = new MultiProtocolExtnCapabilityTlv(afi, res, safi);
    peer1.peerChannelHandler.capabilityTlv.add(tempTlv1);
    Channel channel = peer1.connectFrom(connectToSocket, new InetSocketAddress("127.0.0.99", 0));
    TimeUnit.MILLISECONDS.sleep(1000);

    //Get peer1
    BgpId bgpId = new BgpId(IpAddress.valueOf("127.0.0.99"));
    BgpPeerImpl peer = (BgpPeerImpl) bgpControllerImpl.getPeer(bgpId);

    LinkedList<BgpValueType> subTlvs = new LinkedList<>();
    BgpValueType tlv = null;
    tlv = AutonomousSystemTlv.of(2478);
    subTlvs.add(tlv);
    tlv = BgpLSIdentifierTlv.of(33686018);
    subTlvs.add(tlv);
    NodeDescriptors nodeDes = new NodeDescriptors(subTlvs, (short) 0x10, (short) 256);
    BgpNodeLSIdentifier key = new BgpNodeLSIdentifier(nodeDes);
    TimeUnit.MILLISECONDS.sleep(500);
    AdjRibIn adj = peer.adjRib();

    //In Adj-RIB, nodeTree should contain specified key
    assertThat(adj.nodeTree().containsKey(key), is(true));

    BgpLocalRibImpl obj = (BgpLocalRibImpl) bgpControllerImpl.bgpLocalRib();
    //In Local-RIB, nodeTree should contain specified key
    assertThat(obj.nodeTree().containsKey(key), is(true));

    peer2.peerChannelHandler.asNumber = 200;
    peer2.peerChannelHandler.version = 4;
    peer2.peerChannelHandler.holdTime = 120;

    bgpControllerImpl.getConfig().setLsCapability(true);
    tempTlv1 = new MultiProtocolExtnCapabilityTlv(afi, res, safi);
    peer2.peerChannelHandler.capabilityTlv.add(tempTlv1);
    peer2.connectFrom(connectToSocket, new InetSocketAddress("127.0.0.92", 0));
    TimeUnit.MILLISECONDS.sleep(1000);

    //Get peer2
    bgpId = new BgpId(IpAddress.valueOf("127.0.0.92"));
    peer = (BgpPeerImpl) bgpControllerImpl.getPeer(bgpId);
    adj = peer.adjRib();

    //In Adj-RIB, nodetree should be empty
    assertThat(adj.nodeTree().isEmpty(), is(true));

    //peer1 disconnects
    channel.disconnect();
    channel.close();

    obj = (BgpLocalRibImpl) bgpControllerImpl.bgpLocalRib();
    TimeUnit.MILLISECONDS.sleep(200);

    //In Local-RIB, nodeTree should be empty
    assertThat(obj.nodeTree().isEmpty(), is(true));
}
 
Example 15
Source File: NettyClient.java    From anima with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void doConnect() throws Throwable {
	long start = System.currentTimeMillis();
       ChannelFuture future = bootstrap.connect(getConnectAddress());
       try{
           boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
           
           if (ret && future.isSuccess()) {
               Channel newChannel = future.getChannel();
               newChannel.setInterestOps(Channel.OP_READ_WRITE);
               try {

                   Channel oldChannel = NettyClient.this.channel; 
                   if (oldChannel != null) {
                       try {
                           if (logger.isInfoEnabled()) {
                               logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                           }
                           oldChannel.close();
                       } finally {
                           NettyChannel.removeChannelIfDisconnected(oldChannel);
                       }
                   }
               } finally {
                   if (NettyClient.this.isClosed()) {
                       try {
                           if (logger.isInfoEnabled()) {
                               logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                           }
                           newChannel.close();
                       } finally {
                           NettyClient.this.channel = null;
                           NettyChannel.removeChannelIfDisconnected(newChannel);
                       }
                   } else {
                       NettyClient.this.channel = newChannel;
                   }
               }
           } else if (future.getCause() != null) {
               throw new RemotingException(this, "client failed to connect to server "
                       + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
           } else {
               throw new RemotingException(this, "client failed to connect to server "
                       + getRemoteAddress() + " client-side timeout "
                       + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client");
           }
       }finally{
           if (! isConnected()) {
               future.cancel();
           }
       }
}
 
Example 16
Source File: RaopAudioHandler.java    From Android-Airplay-Server with MIT License 4 votes vote down vote up
/**
 * Creates an UDP socket and handler pipeline for RTP channels
 * 
 * @param local local end-point address
 * @param remote remote end-point address
 * @param channelType channel type. Determines which handlers are put into the pipeline
 * @return open data-gram channel
 */
private Channel createRtpChannel(final SocketAddress local, final SocketAddress remote, final RaopRtpChannelType channelType) {
	/* Create bootstrap helper for a data-gram socket using NIO */
	//final ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(new NioDatagramChannelFactory(rtpExecutorService));
	final ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(new OioDatagramChannelFactory(rtpExecutorService));
	
	
	
	/* Set the buffer size predictor to 1500 bytes to ensure that
	 * received packets will fit into the buffer. Packets are
	 * truncated if they are larger than that!
	 */
	bootstrap.setOption("receiveBufferSizePredictorFactory", new FixedReceiveBufferSizePredictorFactory(1500));
	
	/* Set the socket's receive buffer size. We set it to 1MB */
	bootstrap.setOption("receiveBufferSize", 1024 * 1024);
	
	/* Set pipeline factory for the RTP channel */
	bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
		@Override
		public ChannelPipeline getPipeline() throws Exception {
			final ChannelPipeline pipeline = Channels.pipeline();

			final AirPlayServer airPlayServer = AirPlayServer.getIstance();
			
			pipeline.addLast("executionHandler", airPlayServer.getChannelExecutionHandler());
			pipeline.addLast("exceptionLogger", exceptionLoggingHandler);
			pipeline.addLast("decoder", decodeHandler);
			pipeline.addLast("encoder", encodeHandler);
			
			/* We pretend that all communication takes place on the audio channel,
			 * and simply re-route packets from and to the control and timing channels
			 */
			if ( ! channelType.equals(RaopRtpChannelType.Audio)) {
				pipeline.addLast("inputToAudioRouter", inputToAudioRouterDownstreamHandler);
				
				/* Must come *after* the router, otherwise incoming packets are logged twice */
				pipeline.addLast("packetLogger", packetLoggingHandler);
			}
			else {
				/* Must come *before* the router, otherwise outgoing packets are logged twice */
				pipeline.addLast("packetLogger", packetLoggingHandler);
				pipeline.addLast("audioToOutputRouter", audioToOutputRouterUpstreamHandler);
				pipeline.addLast("timing", timingHandler);
				pipeline.addLast("resendRequester", resendRequestHandler);
				
				if (decryptionHandler != null){
					pipeline.addLast("decrypt", decryptionHandler);
				}
				
				if (audioDecodeHandler != null){
					pipeline.addLast("audioDecode", audioDecodeHandler);
				}
				
				pipeline.addLast("enqueue", audioEnqueueHandler);
			}

			return pipeline;
		}
	});

	Channel channel = null;
	boolean didThrow = true;
	try {
		/* Bind to local address */
		channel = bootstrap.bind(local);
		
		/* Add to group of RTP channels beloging to this RTSP connection */
		rtpChannels.add(channel);

		/* Connect to remote address if one was provided */
		if (remote != null){
			channel.connect(remote);
		}
		
		didThrow = false;
		return channel;
	}
	finally {
		if (didThrow && (channel != null)){
			channel.close();
		}
	}
}
 
Example 17
Source File: BgpControllerImplTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Peer1 has Node NLRI and Peer2 has Node NLRI with different MpReach and MpUnReach with VPN.
 */
@Test
public void testBgpUpdateMessage4() throws InterruptedException {
    // Initiate the connections
    peer1.peerChannelHandler.asNumber = 200;
    peer1.peerChannelHandler.version = 4;
    peer1.peerChannelHandler.holdTime = 120;

    short afi = 16388;
    byte res = 0;
    byte safi = (byte) 0x80;

    bgpControllerImpl.getConfig().setLsCapability(true);
    BgpValueType tempTlv1 = new MultiProtocolExtnCapabilityTlv(afi, res, safi);
    peer1.peerChannelHandler.capabilityTlv.add(tempTlv1);
    Channel channel =  peer1.connectFrom(connectToSocket, new InetSocketAddress("127.0.0.35", 0));
    TimeUnit.MILLISECONDS.sleep(1000);

    //Get peer1
    IpAddress ipAddress = IpAddress.valueOf("127.0.0.35");
    BgpId bgpId = new BgpId(ipAddress);
    BgpPeerImpl peer = (BgpPeerImpl) bgpControllerImpl.getPeer(bgpId);
    LinkedList<BgpValueType> subTlvs1 = new LinkedList<>();

    LinkedList<BgpValueType> subTlvs = new LinkedList<>();
    BgpValueType tlv = AutonomousSystemTlv.of(2478);
    subTlvs.add(tlv);
    tlv = BgpLSIdentifierTlv.of(33686018);
    subTlvs.add(tlv);

    NodeDescriptors nodeDes = new NodeDescriptors(subTlvs, (short) 0x10, (short) 256);
    BgpNodeLSIdentifier key = new BgpNodeLSIdentifier(nodeDes);
    RouteDistinguisher rd = new RouteDistinguisher((long) 0x0A);
    VpnAdjRibIn vpnAdj = peer.vpnAdjRib();

    //In Adj-RIB, vpnNodeTree should contain rd
    assertThat(vpnAdj.vpnNodeTree().containsKey(rd), is(true));

    Map<BgpNodeLSIdentifier, PathAttrNlriDetails> treeValue = vpnAdj.vpnNodeTree().get(rd);
    //In Adj-RIB, vpnNodeTree should contain rd key which contains specified value
    assertThat(treeValue.containsKey(key), is(true));

    BgpLocalRibImpl obj = (BgpLocalRibImpl) bgpControllerImpl.bgpLocalRibVpn();
    //In Local-RIB, vpnNodeTree should contain rd
    assertThat(obj.vpnNodeTree().containsKey(rd), is(true));

    Map<BgpNodeLSIdentifier, PathAttrNlriDetailsLocalRib> value = obj.vpnNodeTree().get(rd);
    //In Local-RIB, vpnNodeTree should contain rd key which contains specified value
    assertThat(value.containsKey(key), is(true));

    peer2.peerChannelHandler.asNumber = 200;
    peer2.peerChannelHandler.version = 4;
    peer2.peerChannelHandler.holdTime = 120;

    bgpControllerImpl.getConfig().setLsCapability(true);
    tempTlv1 = new MultiProtocolExtnCapabilityTlv(afi, res, safi);
    peer1.peerChannelHandler.capabilityTlv.add(tempTlv1);
    peer2.connectFrom(connectToSocket, new InetSocketAddress("127.0.0.40", 0));
    TimeUnit.MILLISECONDS.sleep(1000);

    //Get peer2
    bgpId = new BgpId(IpAddress.valueOf("127.0.0.40"));
    peer = (BgpPeerImpl) bgpControllerImpl.getPeer(bgpId);

    tlv = AutonomousSystemTlv.of(686);
    subTlvs1.add(tlv);
    tlv = BgpLSIdentifierTlv.of(33686018);
    subTlvs1.add(tlv);
    nodeDes = new NodeDescriptors(subTlvs1, (short) 0x10, (short) 256);
    key = new BgpNodeLSIdentifier(nodeDes);
    vpnAdj = peer.vpnAdjRib();

    //In Adj-RIB, vpnNodeTree should contain rd
    assertThat(vpnAdj.vpnNodeTree().containsKey(rd), is(true));

    treeValue = vpnAdj.vpnNodeTree().get(rd);
    //In Adj-RIB, vpnNodeTree should contain rd key which contains specified value
    assertThat(treeValue.containsKey(key), is(true));

    //Disconnect peer1
    channel.disconnect();
    channel.close();

    obj = (BgpLocalRibImpl) bgpControllerImpl.bgpLocalRibVpn();

    //In Local-RIB, vpnNodeTree should contain rd
    assertThat(obj.vpnNodeTree().containsKey(rd), is(true));

    value = obj.vpnNodeTree().get(rd);
    //In Local-RIB, vpnNodeTree should contain rd key which contains specified value
    assertThat(value.containsKey(key), is(true));
}
 
Example 18
Source File: ProgrammableTSOServer.java    From phoenix-omid with Apache License 2.0 4 votes vote down vote up
/**
 * Handle received messages
 */
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    Object msg = e.getMessage();
    if (msg instanceof TSOProto.Request) {
        TSOProto.Request request = (TSOProto.Request) msg;
        Channel channel = ctx.getChannel();
        if (request.hasHandshakeRequest()) {
            checkHandshake(ctx, request.getHandshakeRequest());
            return;
        }
        if (!handshakeCompleted(ctx)) {
            LOG.info("handshake not completed");
            channel.close();
        }

        Response resp = responseQueue.poll();
        if (request.hasTimestampRequest()) {
            if (resp == null || resp.type != ResponseType.TIMESTAMP) {
                throw new IllegalStateException("Expecting TS response to send but got " + resp);
            }
            TimestampResponse tsResp = (TimestampResponse) resp;
            sendTimestampResponse(tsResp.startTS, channel);
        } else if (request.hasCommitRequest()) {
            if (resp == null) {
                throw new IllegalStateException("Expecting COMMIT response to send but got null");
            }
            switch (resp.type) {
                case COMMIT:
                    CommitResponse commitResp = (CommitResponse) resp;
                    sendCommitResponse(commitResp.startTS, commitResp.commitTS, channel);
                    break;
                case ABORT:
                    AbortResponse abortResp = (AbortResponse) resp;
                    sendAbortResponse(abortResp.startTS, channel);
                    break;
                default:
                    throw new IllegalStateException("Expecting COMMIT response to send but got " + resp.type);
            }
        } else {
            LOG.error("Invalid request {}", request);
            ctx.getChannel().close();
        }
    } else {
        LOG.error("Unknown message type", msg);
    }
}
 
Example 19
Source File: BgpControllerImplTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Peer1 has Node NLRI (MpReach) and Peer2 has Node NLRI with same MpReach and MpUnReach.
 */
@Test
public void testBgpUpdateMessage2() throws InterruptedException, TestUtilsException {
    // Initiate the connections
    peer1.peerChannelHandler.asNumber = 200;
    peer1.peerChannelHandler.version = 4;
    peer1.peerChannelHandler.holdTime = 120;
    short afi = 16388;
    byte res = 0;
    byte safi = 71;

    bgpControllerImpl.getConfig().setLsCapability(true);
    BgpValueType tempTlv1 = new MultiProtocolExtnCapabilityTlv(afi, res, safi);
    peer2.peerChannelHandler.capabilityTlv.add(tempTlv1);
    Channel channel = peer1.connectFrom(connectToSocket, new InetSocketAddress("127.0.0.95", 0));
    TimeUnit.MILLISECONDS.sleep(1000);

    //Get peer1
    BgpId bgpId = new BgpId(IpAddress.valueOf("127.0.0.95"));
    BgpPeerImpl peer = (BgpPeerImpl) bgpControllerImpl.getPeer(bgpId);

    LinkedList<BgpValueType> subTlvs = new LinkedList<>();
    BgpValueType tlv = AutonomousSystemTlv.of(2478);
    subTlvs.add(tlv);
    tlv = BgpLSIdentifierTlv.of(33686018);
    subTlvs.add(tlv);
    NodeDescriptors nodeDes = new NodeDescriptors(subTlvs, (short) 0x10, (short) 256);
    BgpNodeLSIdentifier key = new BgpNodeLSIdentifier(nodeDes);
    TimeUnit.MILLISECONDS.sleep(500);
    AdjRibIn adj = peer.adjRib();

    //In Adj-RIB, nodeTree should contains specified key
    assertThat(adj.nodeTree().containsKey(key), is(true));

    BgpLocalRibImpl obj = (BgpLocalRibImpl) bgpControllerImpl.bgpLocalRib();
    //In Local-RIB, nodeTree should contains specified key
    assertThat(obj.nodeTree().containsKey(key), is(true));

    peer2.peerChannelHandler.asNumber = 200;
    peer2.peerChannelHandler.version = 4;
    peer2.peerChannelHandler.holdTime = 120;

    bgpControllerImpl.getConfig().setLsCapability(true);
    tempTlv1 = new MultiProtocolExtnCapabilityTlv(afi, res, safi);
    peer2.peerChannelHandler.capabilityTlv.add(tempTlv1);
    peer2.connectFrom(connectToSocket, new InetSocketAddress("127.0.0.70", 0));
    TimeUnit.MILLISECONDS.sleep(1000);

    //Get peer2
    bgpId = new BgpId(IpAddress.valueOf("127.0.0.70"));
    peer = (BgpPeerImpl) bgpControllerImpl.getPeer(bgpId);
    TimeUnit.MILLISECONDS.sleep(200);
    adj = peer.adjRib();

    //In Adj-RIB, nodetree should be empty
    assertThat(adj.nodeTree().isEmpty(), is(true));

    //Disconnect peer1
    channel.disconnect();
    channel.close();

    obj = (BgpLocalRibImpl) bgpControllerImpl.bgpLocalRib();
    TimeUnit.MILLISECONDS.sleep(200);
    //In Local-RIB, nodetree should be empty
    assertThat(obj.nodeTree().isEmpty(), is(true));
}
 
Example 20
Source File: NettyClient.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try{
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
        
        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // 关闭旧的连接
                Channel oldChannel = NettyClient.this.channel; // copy reference
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + " client-side timeout "
                    + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
                    + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    }finally{
        if (! isConnected()) {
            future.cancel();
        }
    }
}