Search in sources :

Example 11 with PhysicalDBPool

use of io.mycat.backend.datasource.PhysicalDBPool in project Mycat_plus by coderczp.

the class ConfigTest method testTempReadHostAvailable.

/**
 * 测试 临时读可用 配置
 */
@Test
public void testTempReadHostAvailable() {
    PhysicalDBPool pool = this.dataHosts.get("localhost2");
    DataHostConfig hostConfig = pool.getSource().getHostConfig();
    Assert.assertTrue(hostConfig.isTempReadHostAvailable() == true);
}
Also used : PhysicalDBPool(io.mycat.backend.datasource.PhysicalDBPool) DataHostConfig(io.mycat.config.model.DataHostConfig) Test(org.junit.Test)

Example 12 with PhysicalDBPool

use of io.mycat.backend.datasource.PhysicalDBPool in project Mycat_plus by coderczp.

the class MycatServer method reloadDnIndex.

public void reloadDnIndex() {
    if (MycatServer.getInstance().getProcessors() == null)
        return;
    // load datanode active index from properties
    dnIndexProperties = loadDnIndexProps();
    // init datahost
    Map<String, PhysicalDBPool> dataHosts = config.getDataHosts();
    LOGGER.info("reInitialize dataHost ...");
    for (PhysicalDBPool node : dataHosts.values()) {
        String index = dnIndexProperties.getProperty(node.getHostName(), "0");
        if (!"0".equals(index)) {
            LOGGER.info("reinit datahost: " + node.getHostName() + "  to use datasource index:" + index);
        }
        node.switchSource(Integer.parseInt(index), true, "reload dnindex");
    }
}
Also used : PhysicalDBPool(io.mycat.backend.datasource.PhysicalDBPool)

Example 13 with PhysicalDBPool

use of io.mycat.backend.datasource.PhysicalDBPool in project Mycat_plus by coderczp.

the class MycatServer method startup.

public void startup() throws IOException {
    SystemConfig system = config.getSystem();
    int processorCount = system.getProcessors();
    // init RouteStrategyFactory first
    RouteStrategyFactory.init();
    // 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;
        case 2:
            bufferPool = new NettyBufferPool(bufferPoolChunkSize);
            LOGGER.info("Use Netty Buffer Pool");
            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);
    sequenceExecutor = ExecutorUtil.create("SequenceExecutor", 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);
    // 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) NettyBufferPool(io.mycat.buffer.NettyBufferPool) MyCatMemory(io.mycat.memory.MyCatMemory)

Example 14 with PhysicalDBPool

use of io.mycat.backend.datasource.PhysicalDBPool in project Mycat_plus by coderczp.

the class MySQLHeartbeat method switchSourceIfNeed.

/**
 * switch data source
 */
private void switchSourceIfNeed(String reason) {
    int switchType = source.getHostConfig().getSwitchType();
    if (switchType == DataHostConfig.NOT_SWITCH_DS) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("not switch datasource ,for switchType is " + DataHostConfig.NOT_SWITCH_DS);
            return;
        }
        return;
    }
    PhysicalDBPool pool = this.source.getDbPool();
    int curDatasourceHB = pool.getSource().getHeartbeat().getStatus();
    // read node can't switch ,only write node can switch
    if (pool.getWriteType() == PhysicalDBPool.WRITE_ONLYONE_NODE && !source.isReadNode() && curDatasourceHB != DBHeartbeat.OK_STATUS && pool.getSources().length > 1) {
        synchronized (pool) {
            // try to see if need switch datasource
            curDatasourceHB = pool.getSource().getHeartbeat().getStatus();
            if (curDatasourceHB != DBHeartbeat.INIT_STATUS && curDatasourceHB != DBHeartbeat.OK_STATUS) {
                int curIndex = pool.getActivedIndex();
                int nextId = pool.next(curIndex);
                PhysicalDatasource[] allWriteNodes = pool.getSources();
                while (true) {
                    if (nextId == curIndex) {
                        break;
                    }
                    PhysicalDatasource theSource = allWriteNodes[nextId];
                    DBHeartbeat theSourceHB = theSource.getHeartbeat();
                    int theSourceHBStatus = theSourceHB.getStatus();
                    if (theSourceHBStatus == DBHeartbeat.OK_STATUS) {
                        if (switchType == DataHostConfig.SYN_STATUS_SWITCH_DS) {
                            if (Integer.valueOf(0).equals(theSourceHB.getSlaveBehindMaster())) {
                                LOGGER.info("try to switch datasource ,slave is synchronized to master " + theSource.getConfig());
                                pool.switchSource(nextId, true, reason);
                                break;
                            } else {
                                LOGGER.warn("ignored  datasource ,slave is not  synchronized to master , slave behind master :" + theSourceHB.getSlaveBehindMaster() + " " + theSource.getConfig());
                            }
                        } else {
                            // normal switch
                            LOGGER.info("try to switch datasource ,not checked slave synchronize status " + theSource.getConfig());
                            pool.switchSource(nextId, true, reason);
                            break;
                        }
                    }
                    nextId = pool.next(nextId);
                }
            }
        }
    }
}
Also used : PhysicalDatasource(io.mycat.backend.datasource.PhysicalDatasource) PhysicalDBPool(io.mycat.backend.datasource.PhysicalDBPool)

Example 15 with PhysicalDBPool

use of io.mycat.backend.datasource.PhysicalDBPool in project Mycat_plus by coderczp.

the class RouterUtil method getRandomDataNode.

@Deprecated
private static String getRandomDataNode(TableConfig tc) {
    // 写节点不可用,意味着读节点也不可用。
    // 直接使用下一个 dataHost
    String randomDn = tc.getRandomDataNode();
    MycatConfig mycatConfig = MycatServer.getInstance().getConfig();
    if (mycatConfig != null) {
        PhysicalDBNode physicalDBNode = mycatConfig.getDataNodes().get(randomDn);
        if (physicalDBNode != null) {
            if (physicalDBNode.getDbPool().getSource().isAlive()) {
                for (PhysicalDBPool pool : MycatServer.getInstance().getConfig().getDataHosts().values()) {
                    if (pool.getSource().getHostConfig().containDataNode(randomDn)) {
                        continue;
                    }
                    if (pool.getSource().isAlive()) {
                        return pool.getSource().getHostConfig().getRandomDataNode();
                    }
                }
            }
        }
    }
    // all fail return default
    return randomDn;
}
Also used : PhysicalDBNode(io.mycat.backend.datasource.PhysicalDBNode) PhysicalDBPool(io.mycat.backend.datasource.PhysicalDBPool) MycatConfig(io.mycat.config.MycatConfig)

Aggregations

PhysicalDBPool (io.mycat.backend.datasource.PhysicalDBPool)69 PhysicalDatasource (io.mycat.backend.datasource.PhysicalDatasource)43 PhysicalDBNode (io.mycat.backend.datasource.PhysicalDBNode)28 MycatConfig (io.mycat.config.MycatConfig)22 HashMap (java.util.HashMap)14 DBHostConfig (io.mycat.config.model.DBHostConfig)12 RowDataPacket (io.mycat.net.mysql.RowDataPacket)12 DBHeartbeat (io.mycat.backend.heartbeat.DBHeartbeat)11 LinkedList (java.util.LinkedList)10 Connection (java.sql.Connection)8 MycatCluster (io.mycat.config.MycatCluster)6 DataHostConfig (io.mycat.config.model.DataHostConfig)6 FirewallConfig (io.mycat.config.model.FirewallConfig)6 SchemaConfig (io.mycat.config.model.SchemaConfig)6 UserConfig (io.mycat.config.model.UserConfig)6 DataSourceSyncRecorder (io.mycat.statistic.DataSourceSyncRecorder)6 IOException (java.io.IOException)6 Map (java.util.Map)6 ArrayList (java.util.ArrayList)5 MySQLConsistencyChecker (io.mycat.backend.heartbeat.MySQLConsistencyChecker)4