Search in sources :

Example 66 with ClosedChannelException

use of java.nio.channels.ClosedChannelException in project voltdb by VoltDB.

the class PooledDirectByteBuf method setBytes.

@Override
public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException {
    checkIndex(index, length);
    ByteBuffer tmpBuf = internalNioBuffer();
    index = idx(index);
    tmpBuf.clear().position(index).limit(index + length);
    try {
        return in.read(tmpBuf);
    } catch (ClosedChannelException ignored) {
        return -1;
    }
}
Also used : ClosedChannelException(java.nio.channels.ClosedChannelException) ByteBuffer(java.nio.ByteBuffer)

Example 67 with ClosedChannelException

use of java.nio.channels.ClosedChannelException in project CloudStack-archive by CloudStack-extras.

the class Agent method processRequest.

protected void processRequest(final Request request, final Link link) {
    boolean requestLogged = false;
    Response response = null;
    try {
        final Command[] cmds = request.getCommands();
        final Answer[] answers = new Answer[cmds.length];
        for (int i = 0; i < cmds.length; i++) {
            final Command cmd = cmds[i];
            Answer answer;
            try {
                if (s_logger.isDebugEnabled()) {
                    // this is a hack to make sure we do NOT log the ssh keys
                    if ((cmd instanceof ModifySshKeysCommand)) {
                        s_logger.debug("Received the request for command: ModifySshKeysCommand");
                    } else {
                        if (// ensures request is logged only once per method call
                        !requestLogged) {
                            s_logger.debug("Request:" + request.toString());
                            requestLogged = true;
                        }
                    }
                    s_logger.debug("Processing command: " + cmd.toString());
                }
                if (cmd instanceof CronCommand) {
                    final CronCommand watch = (CronCommand) cmd;
                    scheduleWatch(link, request, watch.getInterval() * 1000, watch.getInterval() * 1000);
                    answer = new Answer(cmd, true, null);
                } else if (cmd instanceof UpgradeCommand) {
                    final UpgradeCommand upgrade = (UpgradeCommand) cmd;
                    answer = upgradeAgent(upgrade.getUpgradeUrl(), upgrade);
                } else if (cmd instanceof ShutdownCommand) {
                    ShutdownCommand shutdown = (ShutdownCommand) cmd;
                    s_logger.debug("Received shutdownCommand, due to: " + shutdown.getReason());
                    cancelTasks();
                    _reconnectAllowed = false;
                    answer = new Answer(cmd, true, null);
                } else if (cmd instanceof MaintainCommand) {
                    s_logger.debug("Received maintainCommand");
                    cancelTasks();
                    _reconnectAllowed = false;
                    answer = new MaintainAnswer((MaintainCommand) cmd);
                } else if (cmd instanceof AgentControlCommand) {
                    answer = null;
                    synchronized (_controlListeners) {
                        for (IAgentControlListener listener : _controlListeners) {
                            answer = listener.processControlRequest(request, (AgentControlCommand) cmd);
                            if (answer != null) {
                                break;
                            }
                        }
                    }
                    if (answer == null) {
                        s_logger.warn("No handler found to process cmd: " + cmd.toString());
                        answer = new AgentControlAnswer(cmd);
                    }
                } else {
                    _inProgress.incrementAndGet();
                    try {
                        answer = _resource.executeRequest(cmd);
                    } finally {
                        _inProgress.decrementAndGet();
                    }
                    if (answer == null) {
                        s_logger.debug("Response: unsupported command" + cmd.toString());
                        answer = Answer.createUnsupportedCommandAnswer(cmd);
                    }
                }
            } catch (final Throwable th) {
                s_logger.warn("Caught: ", th);
                final StringWriter writer = new StringWriter();
                th.printStackTrace(new PrintWriter(writer));
                answer = new Answer(cmd, false, writer.toString());
            }
            answers[i] = answer;
            if (!answer.getResult() && request.stopOnError()) {
                for (i++; i < cmds.length; i++) {
                    answers[i] = new Answer(cmds[i], false, "Stopped by previous failure");
                }
                break;
            }
        }
        response = new Response(request, answers);
    } finally {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug(response != null ? response.toString() : "response is null");
        }
        if (response != null) {
            try {
                link.send(response.toBytes());
            } catch (final ClosedChannelException e) {
                s_logger.warn("Unable to send response: " + response.toString());
            }
        }
    }
}
Also used : MaintainCommand(com.cloud.agent.api.MaintainCommand) ClosedChannelException(java.nio.channels.ClosedChannelException) UpgradeCommand(com.cloud.agent.api.UpgradeCommand) MaintainAnswer(com.cloud.agent.api.MaintainAnswer) CronCommand(com.cloud.agent.api.CronCommand) AgentControlAnswer(com.cloud.agent.api.AgentControlAnswer) ShutdownCommand(com.cloud.agent.api.ShutdownCommand) Response(com.cloud.agent.transport.Response) UpgradeAnswer(com.cloud.agent.api.UpgradeAnswer) StartupAnswer(com.cloud.agent.api.StartupAnswer) AgentControlAnswer(com.cloud.agent.api.AgentControlAnswer) Answer(com.cloud.agent.api.Answer) MaintainAnswer(com.cloud.agent.api.MaintainAnswer) AgentControlCommand(com.cloud.agent.api.AgentControlCommand) StringWriter(java.io.StringWriter) MaintainCommand(com.cloud.agent.api.MaintainCommand) StartupCommand(com.cloud.agent.api.StartupCommand) AgentControlCommand(com.cloud.agent.api.AgentControlCommand) ShutdownCommand(com.cloud.agent.api.ShutdownCommand) Command(com.cloud.agent.api.Command) PingCommand(com.cloud.agent.api.PingCommand) ModifySshKeysCommand(com.cloud.agent.api.ModifySshKeysCommand) UpgradeCommand(com.cloud.agent.api.UpgradeCommand) CronCommand(com.cloud.agent.api.CronCommand) ModifySshKeysCommand(com.cloud.agent.api.ModifySshKeysCommand) PrintWriter(java.io.PrintWriter)

Example 68 with ClosedChannelException

use of java.nio.channels.ClosedChannelException in project CshBBrain by CshBBrain.

the class Client method close.

/**
	 * 
	 * <li>方法名:close
	 * <li>
	 * <li>返回类型:void
	 * <li>说明:关闭链接
	 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
	 * <li>创建日期:2011-12-11
	 * <li>修改人: 
	 * <li>修改日期:
	 * @throws IOException 
	 */
public void close() {
    if (this.requestWithFile != null && this.requestWithFile.isReadFile()) {
        FileTransfer fr = requestWithFile.getFileReceiver();
        if (fr != null && !fr.finishWrite()) {
            // 强制关闭删除损害的文件
            fr.forceClose();
        }
    }
    // 关闭连接
    SocketChannel socketChannel = (SocketChannel) this.key.channel();
    try {
        // 清除
        this.sockectServer.clearSocket(index);
        unregiste();
        this.key.attach(null);
        this.key.cancel();
    } catch (ClosedChannelException e) {
        e.printStackTrace();
    } finally {
        try {
            //socketChannel.socket().getOutputStream().flush();
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException)

Example 69 with ClosedChannelException

use of java.nio.channels.ClosedChannelException in project CshBBrain by CshBBrain.

the class MasterServer method startClustersMessage.

/**
	 * 
	 * <li>方法名:startClustersMessage
	 * <li>
	 * <li>返回类型:void
	 * <li>说明:开始处理集群通信客户端的消息
	 * <li>创建人:CshBBrain, 技术博客:http://cshbbrain.iteye.com/
	 * <li>创建日期:2012-10-22
	 * <li>修改人: 
	 * <li>修改日期:
	 */
protected void startClustersMessage() {
    // 是否连接集群服务器
    Boolean isConnect = true;
    // 连接客户端通道
    SocketChannel socketChannel = null;
    // 集群服务器地址
    String[] address = this.masterServer.split(":");
    if (address.length < 2) {
        // 集群服务器地址错误
        log.info("集群服务器地址配置错误,集群服务器地址格式为:ip:port,例如:192.168.2.32:9090,请重新配置后再启动");
        return;
    }
    if (MyStringUtil.isBlank(address[0]) || MyStringUtil.isBlank(address[1])) {
        // 集群服务器ip地址错误
        log.info("集群服务器ip地址配置错误,集群服务器ip地址格式为:ip:port,例如:192.168.2.32:9090,请重新配置后再启动");
        return;
    }
    InetSocketAddress socketAddress = new InetSocketAddress(address[0], Integer.parseInt(address[1]));
    while (noStopRequested) {
        try {
            if (isConnect && socketChannel == null) {
                // 第一次连接或连接断开都需要连接到集群服务器上 
                try {
                    if (socketChannel != null && socketChannel.isConnected() && !socketChannel.isOpen()) {
                        socketChannel.close();
                        log.info("已经连接到集群服务器,但连接断开,重新连接");
                    }
                    socketChannel = SocketChannel.open();
                    socketChannel.configureBlocking(false);
                    socketChannel.socket().setSoTimeout(0);
                    socketChannel.socket().setTcpNoDelay(true);
                    socketChannel.socket().setReuseAddress(true);
                    // 设置接收缓存
                    socketChannel.socket().setReceiveBufferSize(this.sockectReceiveBufferSize * 1024);
                    // 设置发送缓存
                    socketChannel.socket().setSendBufferSize(this.sockectSendBufferSize * 1024);
                    socketChannel.connect(socketAddress);
                    if (socketChannel.finishConnect()) {
                        //socketChannel.finishConnect();// 连接建立完成
                        // 不需要做连接服务器了的操作了,已经连接上集群服务器了  			        	 
                        isConnect = false;
                        this.readWriteMonitors.get(Math.abs(this.connectIndex.getAndIncrement()) % this.readWriteMonitors.size()).registeClient(socketChannel);
                        log.info("成功连接到集群服务器  " + address[0] + " 的端口:" + address[1]);
                        // 休眠60秒钟
                        Thread.sleep(60 * 1000);
                    }
                } catch (ClosedChannelException e) {
                    log.info("连接集群服务器失败");
                } catch (IOException e) {
                    log.info("连接集群服务器失败");
                }
            } else {
                // 处理消息监听
                if (isConnect && socketChannel.isConnectionPending()) {
                    // 正在连接服务器
                    // 正在连接,等待30秒
                    Thread.sleep(1000);
                }
                try {
                    if (isConnect && socketChannel.finishConnect()) {
                        // 已经建立连接
                        try {
                            // 连接建立完成
                            socketChannel.finishConnect();
                            // 不需要做连接服务器了的操作了,已经连接上集群服务器了  	
                            isConnect = false;
                            this.readWriteMonitors.get(Math.abs(this.connectIndex.getAndIncrement()) % this.readWriteMonitors.size()).registeClient(socketChannel);
                        } catch (IOException e) {
                            log.warn(e.getMessage());
                        }
                        log.info("成功连接到集群服务器  ");
                        // 休眠60秒钟
                        Thread.sleep(60 * 1000);
                    }
                } catch (IOException e) {
                    log.warn(e.getMessage());
                }
                if (!isConnect && !socketChannel.isConnected()) {
                    // 到集群服务器的连接端口,重新连接
                    isConnect = true;
                    try {
                        socketChannel.connect(socketAddress);
                    } catch (IOException e) {
                        log.warn(e.getMessage());
                    }
                    // 重新连接
                    continue;
                }
                if (!isConnect && socketChannel.isConnected()) {
                    // 汇报本服务的负载情况到集群管理服务器
                    if (this.localClient != null) {
                        // 已经连接好,等待通信
                        StringBuilder sb = new StringBuilder();
                        sb.append("节点服务器:").append(this.localClient.getLocalAddress()).append("\r\n").append("服务器CPU内核数量:").append(this.coreCount).append("\r\n").append("服务器读写监听线程数量:").append(this.readerWriterCount).append("\r\n").append("服务器工作线程数量:").append(this.workerCount).append("\r\n").append("活跃连接客户端数量:").append(this.clients.keySet().size()).append("\r\n").append("活跃集群连接客户端数量:").append(this.clustersClients.keySet().size()).append("\r\n").append("活跃本地连接客户端数量:").append(this.localClients.keySet().size()).append("\r\n");
                        log.info(sb.toString());
                        StringBuilder msg = new StringBuilder("action=1&");
                        msg.append("coreCount=").append(this.coreCount).append("&").append("readerWriterCount=").append(this.readerWriterCount).append("&").append("workerCount=").append(this.workerCount).append("&").append("clientCount=").append(this.clients.keySet().size()).append("&").append("clustersCount=").append(this.clustersClients.keySet().size()).append("&").append("port=").append(this.port).append("&").append("localCount=").append(this.localClients.keySet().size());
                        Response response = new Response();
                        response.setBody(msg.toString());
                        this.localClient.sendMessage(response);
                    //coreCount=4&readerWriterCount=8&workerCount=32&clientCount=10000&clustersCount=5&localCount=4&port=9191
                    }
                    //10分钟检查一次
                    Thread.sleep(30 * 1000);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ClosedChannelException(java.nio.channels.ClosedChannelException) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 70 with ClosedChannelException

use of java.nio.channels.ClosedChannelException in project CloudStack-archive by CloudStack-extras.

the class NioConnection method processTodos.

protected void processTodos() {
    List<ChangeRequest> todos;
    if (_todos.size() == 0) {
        // Nothing to do.
        return;
    }
    synchronized (this) {
        todos = _todos;
        _todos = new ArrayList<ChangeRequest>();
    }
    if (s_logger.isTraceEnabled()) {
        s_logger.trace("Todos Processing: " + todos.size());
    }
    SelectionKey key;
    for (ChangeRequest todo : todos) {
        switch(todo.type) {
            case ChangeRequest.CHANGEOPS:
                try {
                    key = (SelectionKey) todo.key;
                    if (key != null && key.isValid()) {
                        if (todo.att != null) {
                            key.attach(todo.att);
                            Link link = (Link) todo.att;
                            link.setKey(key);
                        }
                        key.interestOps(todo.ops);
                    }
                } catch (CancelledKeyException e) {
                    s_logger.debug("key has been cancelled");
                }
                break;
            case ChangeRequest.REGISTER:
                try {
                    key = ((SocketChannel) (todo.key)).register(_selector, todo.ops, todo.att);
                    if (todo.att != null) {
                        Link link = (Link) todo.att;
                        link.setKey(key);
                    }
                } catch (ClosedChannelException e) {
                    s_logger.warn("Couldn't register socket: " + todo.key);
                    try {
                        ((SocketChannel) (todo.key)).close();
                    } catch (IOException ignore) {
                    } finally {
                        Link link = (Link) todo.att;
                        link.terminated();
                    }
                }
                break;
            case ChangeRequest.CLOSE:
                if (s_logger.isTraceEnabled()) {
                    s_logger.trace("Trying to close " + todo.key);
                }
                key = (SelectionKey) todo.key;
                closeConnection(key);
                if (key != null) {
                    Link link = (Link) key.attachment();
                    if (link != null) {
                        link.terminated();
                    }
                }
                break;
            default:
                s_logger.warn("Shouldn't be here");
                throw new RuntimeException("Shouldn't be here");
        }
    }
    s_logger.trace("Todos Done processing");
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ClosedChannelException(java.nio.channels.ClosedChannelException) CancelledKeyException(java.nio.channels.CancelledKeyException) IOException(java.io.IOException)

Aggregations

ClosedChannelException (java.nio.channels.ClosedChannelException)211 ByteBuffer (java.nio.ByteBuffer)67 IOException (java.io.IOException)60 Test (org.junit.Test)23 InetSocketAddress (java.net.InetSocketAddress)19 SelectionKey (java.nio.channels.SelectionKey)18 SocketChannel (java.nio.channels.SocketChannel)15 ArrayList (java.util.ArrayList)13 NotYetConnectedException (java.nio.channels.NotYetConnectedException)11 InterruptedIOException (java.io.InterruptedIOException)10 CancelledKeyException (java.nio.channels.CancelledKeyException)10 ShutdownCommand (com.cloud.agent.api.ShutdownCommand)9 File (java.io.File)9 ServerSocketChannel (java.nio.channels.ServerSocketChannel)9 PooledByteBuffer (io.undertow.connector.PooledByteBuffer)8 FileChannel (java.nio.channels.FileChannel)8 ConnectException (java.net.ConnectException)7 FsVolumeReference (org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeReference)6 AgentControlCommand (com.cloud.agent.api.AgentControlCommand)5 Command (com.cloud.agent.api.Command)5