Search in sources :

Example 26 with PhysicalDBPool

use of io.mycat.backend.datasource.PhysicalDBPool in project Mycat-Server by MyCATApache.

the class ConfigTest method getPhysicalDBPool.

private PhysicalDBPool getPhysicalDBPool(DataHostConfig conf, ConfigLoader configLoader) {
    String name = conf.getName();
    String dbType = conf.getDbType();
    String dbDriver = conf.getDbDriver();
    PhysicalDatasource[] writeSources = createDataSource(conf, name, dbType, dbDriver, conf.getWriteHosts(), false);
    Map<Integer, DBHostConfig[]> readHostsMap = conf.getReadHosts();
    Map<Integer, PhysicalDatasource[]> readSourcesMap = new HashMap<Integer, PhysicalDatasource[]>(readHostsMap.size());
    for (Map.Entry<Integer, DBHostConfig[]> entry : readHostsMap.entrySet()) {
        PhysicalDatasource[] readSources = createDataSource(conf, name, dbType, dbDriver, entry.getValue(), true);
        readSourcesMap.put(entry.getKey(), readSources);
    }
    PhysicalDBPool pool = new PhysicalDBPool(conf.getName(), conf, writeSources, readSourcesMap, conf.getBalance(), conf.getWriteType());
    return pool;
}
Also used : PhysicalDatasource(io.mycat.backend.datasource.PhysicalDatasource) HashMap(java.util.HashMap) PhysicalDBPool(io.mycat.backend.datasource.PhysicalDBPool) HashMap(java.util.HashMap) Map(java.util.Map)

Example 27 with PhysicalDBPool

use of io.mycat.backend.datasource.PhysicalDBPool in project Mycat-Server by MyCATApache.

the class StopHeartbeat method execute.

public static void execute(String stmt, ManagerConnection c) {
    int count = 0;
    Pair<String[], Integer> keys = ManagerParseStop.getPair(stmt);
    if (keys.getKey() != null && keys.getValue() != null) {
        long time = keys.getValue().intValue() * 1000L;
        Map<String, PhysicalDBPool> dns = MycatServer.getInstance().getConfig().getDataHosts();
        for (String key : keys.getKey()) {
            PhysicalDBPool dn = dns.get(key);
            if (dn != null) {
                dn.getSource().setHeartbeatRecoveryTime(TimeUtil.currentTimeMillis() + time);
                ++count;
                StringBuilder s = new StringBuilder();
                s.append(dn.getHostName()).append(" stop heartbeat '");
                logger.warn(s.append(FormatUtil.formatTime(time, 3)).append("' by manager.").toString());
            }
        }
    }
    OkPacket packet = new OkPacket();
    packet.packetId = 1;
    packet.affectedRows = count;
    packet.serverStatus = 2;
    packet.write(c);
}
Also used : OkPacket(io.mycat.net.mysql.OkPacket) PhysicalDBPool(io.mycat.backend.datasource.PhysicalDBPool)

Example 28 with PhysicalDBPool

use of io.mycat.backend.datasource.PhysicalDBPool in project Mycat-Server by MyCATApache.

the class GlobalTableUtil method reGetColumnsForTable.

/**
 * 重新获得table 的列list
 * @param tableName
 */
private static void reGetColumnsForTable(String tableName) {
    MycatConfig config = MycatServer.getInstance().getConfig();
    if (globalTableMap != null && globalTableMap.get(tableName.toUpperCase()) != null) {
        TableConfig tableConfig = globalTableMap.get(tableName.toUpperCase());
        if (// consistencyCheck 在运行中
        tableConfig == null || isInnerColumnCheckFinished != 1)
            return;
        String nodeName = tableConfig.getDataNodes().get(0);
        Map<String, PhysicalDBNode> map = config.getDataNodes();
        for (String k2 : map.keySet()) {
            PhysicalDBNode dBnode = map.get(k2);
            if (nodeName.equals(dBnode.getName())) {
                PhysicalDBPool pool = dBnode.getDbPool();
                List<PhysicalDatasource> dsList = (List<PhysicalDatasource>) pool.genAllDataSources();
                for (PhysicalDatasource ds : dsList) {
                    if (ds instanceof MySQLDataSource) {
                        MySQLDataSource mds = (MySQLDataSource) dsList.get(0);
                        MySQLConsistencyChecker checker = new MySQLConsistencyChecker(mds, tableConfig.getName());
                        checker.checkInnerColumnExist();
                        // 运行一次就行了,不需要像consistencyCheck那样每个db都运行一次
                        return;
                    }
                }
            }
        }
    }
}
Also used : PhysicalDBNode(io.mycat.backend.datasource.PhysicalDBNode) MySQLConsistencyChecker(io.mycat.backend.heartbeat.MySQLConsistencyChecker) PhysicalDatasource(io.mycat.backend.datasource.PhysicalDatasource) MySQLDataSource(io.mycat.backend.mysql.nio.MySQLDataSource) TableConfig(io.mycat.config.model.TableConfig) PhysicalDBPool(io.mycat.backend.datasource.PhysicalDBPool) ArrayList(java.util.ArrayList) List(java.util.List) MycatConfig(io.mycat.config.MycatConfig)

Example 29 with PhysicalDBPool

use of io.mycat.backend.datasource.PhysicalDBPool in project Mycat-Server by MyCATApache.

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 30 with PhysicalDBPool

use of io.mycat.backend.datasource.PhysicalDBPool in project Mycat-Server by MyCATApache.

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)

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