Search in sources :

Example 1 with NIOProcessor

use of io.mycat.net.NIOProcessor in project Mycat-Server by MyCATApache.

the class ConMap method clearConnections.

public void clearConnections(String reason, PhysicalDatasource dataSouce) {
    for (NIOProcessor processor : MycatServer.getInstance().getProcessors()) {
        ConcurrentMap<Long, BackendConnection> map = processor.getBackends();
        Iterator<Entry<Long, BackendConnection>> itor = map.entrySet().iterator();
        while (itor.hasNext()) {
            Entry<Long, BackendConnection> entry = itor.next();
            BackendConnection con = entry.getValue();
            if (con instanceof MySQLConnection) {
                if (((MySQLConnection) con).getPool() == dataSouce) {
                    con.close(reason);
                    itor.remove();
                }
            } else if ((con instanceof JDBCConnection) && (((JDBCConnection) con).getPool() == dataSouce)) {
                con.close(reason);
                itor.remove();
            }
        }
    }
    items.clear();
}
Also used : Entry(java.util.Map.Entry) NIOProcessor(io.mycat.net.NIOProcessor) JDBCConnection(io.mycat.backend.jdbc.JDBCConnection) MySQLConnection(io.mycat.backend.mysql.nio.MySQLConnection)

Example 2 with NIOProcessor

use of io.mycat.net.NIOProcessor in project Mycat-Server by MyCATApache.

the class MycatServer method startup.

public void startup() throws IOException {
    SystemConfig system = config.getSystem();
    int processorCount = system.getProcessors();
    // server startup
    LOGGER.info(NAME + " is ready to startup ...");
    String inf = "Startup processors ...,total processors:" + system.getProcessors() + ",aio thread pool size:" + system.getProcessorExecutor() + "    \r\n each process allocated socket buffer pool " + " bytes ,a page size:" + system.getBufferPoolPageSize() + "  a page's chunk number(PageSize/ChunkSize) is:" + (system.getBufferPoolPageSize() / system.getBufferPoolChunkSize()) + "  buffer page's number is:" + system.getBufferPoolPageNumber();
    LOGGER.info(inf);
    LOGGER.info("sysconfig params:" + system.toString());
    // startup manager
    ManagerConnectionFactory mf = new ManagerConnectionFactory();
    ServerConnectionFactory sf = new ServerConnectionFactory();
    SocketAcceptor manager = null;
    SocketAcceptor server = null;
    aio = (system.getUsingAIO() == 1);
    // startup processors
    int threadPoolSize = system.getProcessorExecutor();
    processors = new NIOProcessor[processorCount];
    // a page size
    int bufferPoolPageSize = system.getBufferPoolPageSize();
    // total page number 
    short bufferPoolPageNumber = system.getBufferPoolPageNumber();
    //minimum allocation unit
    short bufferPoolChunkSize = system.getBufferPoolChunkSize();
    int socketBufferLocalPercent = system.getProcessorBufferLocalPercent();
    int bufferPoolType = system.getProcessorBufferPoolType();
    switch(bufferPoolType) {
        case 0:
            bufferPool = new DirectByteBufferPool(bufferPoolPageSize, bufferPoolChunkSize, bufferPoolPageNumber, system.getFrontSocketSoRcvbuf());
            totalNetWorkBufferSize = bufferPoolPageSize * bufferPoolPageNumber;
            break;
        case 1:
            /**
				 * todo 对应权威指南修改:
				 *
				 * bytebufferarena由6个bytebufferlist组成,这六个list有减少内存碎片的机制
				 * 每个bytebufferlist由多个bytebufferchunk组成,每个list也有减少内存碎片的机制
				 * 每个bytebufferchunk由多个page组成,平衡二叉树管理内存使用状态,计算灵活
				 * 设置的pagesize对应bytebufferarena里面的每个bytebufferlist的每个bytebufferchunk的buffer长度
				 * bufferPoolChunkSize对应每个bytebufferchunk的每个page的长度
				 * bufferPoolPageNumber对应每个bytebufferlist有多少个bytebufferchunk
				 */
            totalNetWorkBufferSize = 6 * bufferPoolPageSize * bufferPoolPageNumber;
            break;
        default:
            bufferPool = new DirectByteBufferPool(bufferPoolPageSize, bufferPoolChunkSize, bufferPoolPageNumber, system.getFrontSocketSoRcvbuf());
            ;
            totalNetWorkBufferSize = bufferPoolPageSize * bufferPoolPageNumber;
    }
    /**
		 * Off Heap For Merge/Order/Group/Limit 初始化
		 */
    if (system.getUseOffHeapForMerge() == 1) {
        try {
            myCatMemory = new MyCatMemory(system, totalNetWorkBufferSize);
        } catch (NoSuchFieldException e) {
            LOGGER.error("NoSuchFieldException", e);
        } catch (IllegalAccessException e) {
            LOGGER.error("Error", e);
        }
    }
    businessExecutor = ExecutorUtil.create("BusinessExecutor", threadPoolSize);
    timerExecutor = ExecutorUtil.create("Timer", system.getTimerExecutor());
    listeningExecutorService = MoreExecutors.listeningDecorator(businessExecutor);
    for (int i = 0; i < processors.length; i++) {
        processors[i] = new NIOProcessor("Processor" + i, bufferPool, businessExecutor);
    }
    if (aio) {
        LOGGER.info("using aio network handler ");
        asyncChannelGroups = new AsynchronousChannelGroup[processorCount];
        // startup connector
        connector = new AIOConnector();
        for (int i = 0; i < processors.length; i++) {
            asyncChannelGroups[i] = AsynchronousChannelGroup.withFixedThreadPool(processorCount, new ThreadFactory() {

                private int inx = 1;

                @Override
                public Thread newThread(Runnable r) {
                    Thread th = new Thread(r);
                    //TODO
                    th.setName(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + "AIO" + (inx++));
                    LOGGER.info("created new AIO thread " + th.getName());
                    return th;
                }
            });
        }
        manager = new AIOAcceptor(NAME + "Manager", system.getBindIp(), system.getManagerPort(), mf, this.asyncChannelGroups[0]);
        // startup server
        server = new AIOAcceptor(NAME + "Server", system.getBindIp(), system.getServerPort(), sf, this.asyncChannelGroups[0]);
    } else {
        LOGGER.info("using nio network handler ");
        NIOReactorPool reactorPool = new NIOReactorPool(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + "NIOREACTOR", processors.length);
        connector = new NIOConnector(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + "NIOConnector", reactorPool);
        ((NIOConnector) connector).start();
        manager = new NIOAcceptor(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + NAME + "Manager", system.getBindIp(), system.getManagerPort(), mf, reactorPool);
        server = new NIOAcceptor(DirectByteBufferPool.LOCAL_BUF_THREAD_PREX + NAME + "Server", system.getBindIp(), system.getServerPort(), sf, reactorPool);
    }
    // manager start
    manager.start();
    LOGGER.info(manager.getName() + " is started and listening on " + manager.getPort());
    server.start();
    // server started
    LOGGER.info(server.getName() + " is started and listening on " + server.getPort());
    LOGGER.info("===============================================");
    // init datahost
    Map<String, PhysicalDBPool> dataHosts = config.getDataHosts();
    LOGGER.info("Initialize dataHost ...");
    for (PhysicalDBPool node : dataHosts.values()) {
        String index = dnIndexProperties.getProperty(node.getHostName(), "0");
        if (!"0".equals(index)) {
            LOGGER.info("init datahost: " + node.getHostName() + "  to use datasource index:" + index);
        }
        node.init(Integer.parseInt(index));
        node.startHeartbeat();
    }
    long dataNodeIldeCheckPeriod = system.getDataNodeIdleCheckPeriod();
    heartbeatScheduler.scheduleAtFixedRate(updateTime(), 0L, TIME_UPDATE_PERIOD, TimeUnit.MILLISECONDS);
    heartbeatScheduler.scheduleAtFixedRate(processorCheck(), 0L, system.getProcessorCheckPeriod(), TimeUnit.MILLISECONDS);
    heartbeatScheduler.scheduleAtFixedRate(dataNodeConHeartBeatCheck(dataNodeIldeCheckPeriod), 0L, dataNodeIldeCheckPeriod, TimeUnit.MILLISECONDS);
    heartbeatScheduler.scheduleAtFixedRate(dataNodeHeartbeat(), 0L, system.getDataNodeHeartbeatPeriod(), TimeUnit.MILLISECONDS);
    heartbeatScheduler.scheduleAtFixedRate(dataSourceOldConsClear(), 0L, DEFAULT_OLD_CONNECTION_CLEAR_PERIOD, TimeUnit.MILLISECONDS);
    scheduler.schedule(catletClassClear(), 30000, TimeUnit.MILLISECONDS);
    if (system.getCheckTableConsistency() == 1) {
        scheduler.scheduleAtFixedRate(tableStructureCheck(), 0L, system.getCheckTableConsistencyPeriod(), TimeUnit.MILLISECONDS);
    }
    if (system.getUseSqlStat() == 1) {
        scheduler.scheduleAtFixedRate(recycleSqlStat(), 0L, DEFAULT_SQL_STAT_RECYCLE_PERIOD, TimeUnit.MILLISECONDS);
    }
    if (system.getUseGlobleTableCheck() == 1) {
        // 全局表一致性检测是否开启
        scheduler.scheduleAtFixedRate(glableTableConsistencyCheck(), 0L, system.getGlableTableCheckPeriod(), TimeUnit.MILLISECONDS);
    }
    //定期清理结果集排行榜,控制拒绝策略
    scheduler.scheduleAtFixedRate(resultSetMapClear(), 0L, system.getClearBigSqLResultSetMapMs(), TimeUnit.MILLISECONDS);
    RouteStrategyFactory.init();
    //        new Thread(tableStructureCheck()).start();
    //XA Init recovery Log
    LOGGER.info("===============================================");
    LOGGER.info("Perform XA recovery log ...");
    performXARecoveryLog();
    if (isUseZkSwitch()) {
        //首次启动如果发现zk上dnindex为空,则将本地初始化上zk
        initZkDnindex();
    }
    initRuleData();
    startup.set(true);
}
Also used : AIOConnector(io.mycat.net.AIOConnector) ThreadFactory(java.util.concurrent.ThreadFactory) SystemConfig(io.mycat.config.model.SystemConfig) NIOReactorPool(io.mycat.net.NIOReactorPool) ManagerConnectionFactory(io.mycat.manager.ManagerConnectionFactory) PhysicalDBPool(io.mycat.backend.datasource.PhysicalDBPool) NIOProcessor(io.mycat.net.NIOProcessor) ServerConnectionFactory(io.mycat.server.ServerConnectionFactory) NIOConnector(io.mycat.net.NIOConnector) SocketAcceptor(io.mycat.net.SocketAcceptor) DirectByteBufferPool(io.mycat.buffer.DirectByteBufferPool) NIOAcceptor(io.mycat.net.NIOAcceptor) AIOAcceptor(io.mycat.net.AIOAcceptor) MyCatMemory(io.mycat.memory.MyCatMemory)

Example 3 with NIOProcessor

use of io.mycat.net.NIOProcessor in project Mycat-Server by MyCATApache.

the class KillConnection method getList.

private static List<FrontendConnection> getList(String stmt, int offset, ManagerConnection mc) {
    String ids = stmt.substring(offset).trim();
    if (ids.length() > 0) {
        String[] idList = SplitUtil.split(ids, ',', true);
        List<FrontendConnection> fcList = new ArrayList<FrontendConnection>(idList.length);
        NIOProcessor[] processors = MycatServer.getInstance().getProcessors();
        for (String id : idList) {
            long value = 0;
            try {
                value = Long.parseLong(id);
            } catch (NumberFormatException e) {
                continue;
            }
            FrontendConnection fc = null;
            for (NIOProcessor p : processors) {
                if ((fc = p.getFrontends().get(value)) != null) {
                    fcList.add(fc);
                    break;
                }
            }
        }
        return fcList;
    }
    return null;
}
Also used : FrontendConnection(io.mycat.net.FrontendConnection) ArrayList(java.util.ArrayList) NIOProcessor(io.mycat.net.NIOProcessor)

Example 4 with NIOProcessor

use of io.mycat.net.NIOProcessor in project Mycat-Server by MyCATApache.

the class ShowSession method execute.

public static void execute(ManagerConnection c) {
    ByteBuffer buffer = c.allocate();
    // write header
    buffer = header.write(buffer, c, true);
    // write fields
    for (FieldPacket field : fields) {
        buffer = field.write(buffer, c, true);
    }
    // write eof
    buffer = eof.write(buffer, c, true);
    // write rows
    byte packetId = eof.packetId;
    for (NIOProcessor process : MycatServer.getInstance().getProcessors()) {
        for (FrontendConnection front : process.getFrontends().values()) {
            if (!(front instanceof ServerConnection)) {
                continue;
            }
            ServerConnection sc = (ServerConnection) front;
            RowDataPacket row = getRow(sc, c.getCharset());
            if (row != null) {
                row.packetId = ++packetId;
                buffer = row.write(buffer, c, true);
            }
        }
    }
    // write last eof
    EOFPacket lastEof = new EOFPacket();
    lastEof.packetId = ++packetId;
    buffer = lastEof.write(buffer, c, true);
    // write buffer
    c.write(buffer);
}
Also used : FrontendConnection(io.mycat.net.FrontendConnection) RowDataPacket(io.mycat.net.mysql.RowDataPacket) EOFPacket(io.mycat.net.mysql.EOFPacket) ServerConnection(io.mycat.server.ServerConnection) NIOProcessor(io.mycat.net.NIOProcessor) ByteBuffer(java.nio.ByteBuffer) FieldPacket(io.mycat.net.mysql.FieldPacket)

Example 5 with NIOProcessor

use of io.mycat.net.NIOProcessor in project Mycat-Server by MyCATApache.

the class ShowCommand method execute.

public static void execute(ManagerConnection c) {
    ByteBuffer buffer = c.allocate();
    // write header
    buffer = header.write(buffer, c, true);
    // write fields
    for (FieldPacket field : fields) {
        buffer = field.write(buffer, c, true);
    }
    // write eof
    buffer = eof.write(buffer, c, true);
    // write rows
    byte packetId = eof.packetId;
    for (NIOProcessor p : MycatServer.getInstance().getProcessors()) {
        RowDataPacket row = getRow(p, c.getCharset());
        row.packetId = ++packetId;
        buffer = row.write(buffer, c, true);
    }
    // write last eof
    EOFPacket lastEof = new EOFPacket();
    lastEof.packetId = ++packetId;
    buffer = lastEof.write(buffer, c, true);
    // write buffer
    c.write(buffer);
}
Also used : RowDataPacket(io.mycat.net.mysql.RowDataPacket) EOFPacket(io.mycat.net.mysql.EOFPacket) NIOProcessor(io.mycat.net.NIOProcessor) ByteBuffer(java.nio.ByteBuffer) FieldPacket(io.mycat.net.mysql.FieldPacket)

Aggregations

NIOProcessor (io.mycat.net.NIOProcessor)15 EOFPacket (io.mycat.net.mysql.EOFPacket)7 FieldPacket (io.mycat.net.mysql.FieldPacket)7 RowDataPacket (io.mycat.net.mysql.RowDataPacket)7 ByteBuffer (java.nio.ByteBuffer)7 FrontendConnection (io.mycat.net.FrontendConnection)5 BackendConnection (io.mycat.backend.BackendConnection)3 PhysicalDBPool (io.mycat.backend.datasource.PhysicalDBPool)2 JDBCConnection (io.mycat.backend.jdbc.JDBCConnection)2 MySQLConnection (io.mycat.backend.mysql.nio.MySQLConnection)2 ArrayList (java.util.ArrayList)2 PhysicalDBNode (io.mycat.backend.datasource.PhysicalDBNode)1 PhysicalDatasource (io.mycat.backend.datasource.PhysicalDatasource)1 DirectByteBufferPool (io.mycat.buffer.DirectByteBufferPool)1 ConfigInitializer (io.mycat.config.ConfigInitializer)1 MycatCluster (io.mycat.config.MycatCluster)1 MycatConfig (io.mycat.config.MycatConfig)1 DBHostConfig (io.mycat.config.model.DBHostConfig)1 FirewallConfig (io.mycat.config.model.FirewallConfig)1 SchemaConfig (io.mycat.config.model.SchemaConfig)1