Search in sources :

Example 1 with ServerConfig

use of io.mycat.config.ServerConfig in project Mycat2 by MyCATApache.

the class JdbcConnectionManager method createDatasourceProvider.

private static DatasourceProvider createDatasourceProvider(String customerDatasourceProvider) {
    String defaultDatasourceProvider = Optional.ofNullable(customerDatasourceProvider).orElse(DruidDatasourceProvider.class.getName());
    try {
        DatasourceProvider o = (DatasourceProvider) Class.forName(defaultDatasourceProvider).getDeclaredConstructor().newInstance();
        ServerConfig serverConfig = MetaClusterCurrent.exist(ServerConfig.class) ? MetaClusterCurrent.wrapper(ServerConfig.class) : new ServerConfig();
        o.init(serverConfig);
        return o;
    } catch (Exception e) {
        throw new MycatException("can not load datasourceProvider:{}", customerDatasourceProvider);
    }
}
Also used : DruidDatasourceProvider(io.mycat.datasource.jdbc.DruidDatasourceProvider) DruidDatasourceProvider(io.mycat.datasource.jdbc.DruidDatasourceProvider) DatasourceProvider(io.mycat.datasource.jdbc.DatasourceProvider) ServerConfig(io.mycat.config.ServerConfig) MycatException(io.mycat.MycatException) MycatException(io.mycat.MycatException) SQLException(java.sql.SQLException)

Example 2 with ServerConfig

use of io.mycat.config.ServerConfig in project Mycat2 by MyCATApache.

the class StatisticCenterTest method init.

@BeforeClass
public static void init() throws Exception {
    HashMap<Class, Object> context = new HashMap<>();
    context.put(Vertx.class, Vertx.vertx());
    context.put(ServerConfig.class, new ServerConfig());
    context.put(DrdsSqlCompiler.class, new DrdsSqlCompiler(new DrdsConst() {

        @Override
        public NameMap<SchemaHandler> schemas() {
            return new NameMap<>();
        }
    }));
    MetaClusterCurrent.register(context);
    String customerDatasourceProvider = DruidDatasourceProvider.class.getName();
    DatasourceConfig datasourceConfig = new DatasourceConfig();
    datasourceConfig.setDbType("mysql");
    datasourceConfig.setUser("root");
    datasourceConfig.setPassword("123456");
    datasourceConfig.setName("prototypeDs");
    datasourceConfig.setUrl("jdbc:mysql://localhost:3306/mysql");
    Map<String, DatasourceConfig> datasources = Maps.of("prototypeDs", datasourceConfig);
    ClusterConfig clusterConfig = new ClusterConfig();
    clusterConfig.setName("prototype");
    clusterConfig.setMasters(Arrays.asList("prototypeDs"));
    Map<String, ClusterConfig> clusterConfigs = Maps.of("prototype", clusterConfig);
    LinkedList<Runnable> runnables = new LinkedList<>();
    ReplicaSelectorManager manager = ReplicaSelectorRuntime.create(new ArrayList<>(clusterConfigs.values()), datasources, new LoadBalanceManager(), name -> 0, (command, initialDelay, period, unit) -> {
        runnables.add(command);
        return () -> {
        };
    });
    context.put(ReplicaSelectorManager.class, manager);
    context.put(JdbcConnectionManager.class, jdbcManager = new JdbcConnectionManager(DruidDatasourceProvider.class.getName(), datasources));
    MetaClusterCurrent.register(context);
    statisticCenter.init();
}
Also used : SchemaHandler(io.mycat.calcite.table.SchemaHandler) ReplicaSelectorManager(io.mycat.replica.ReplicaSelectorManager) NameMap(io.mycat.util.NameMap) LoadBalanceManager(io.mycat.plug.loadBalance.LoadBalanceManager) DruidDatasourceProvider(io.mycat.datasource.jdbc.DruidDatasourceProvider) ServerConfig(io.mycat.config.ServerConfig) DatasourceConfig(io.mycat.config.DatasourceConfig) JdbcConnectionManager(io.mycat.datasource.jdbc.datasource.JdbcConnectionManager) ClusterConfig(io.mycat.config.ClusterConfig)

Example 3 with ServerConfig

use of io.mycat.config.ServerConfig in project Mycat2 by MyCATApache.

the class CommandResolver method handle.

public static void handle(MycatSession mycat, MySQLPacket curPacket, CommandDispatcher commandHandler) {
    MycatMonitor.onCommandStart(mycat);
    Future<Void> endFuture = null;
    try {
        boolean isEmptyPayload = curPacket.readFinished();
        if (isEmptyPayload) {
            MycatMonitor.onLoadDataLocalInFileEmptyPacketStart(mycat);
            endFuture = commandHandler.handleContentOfFilenameEmptyOk(mycat);
            mycat.resetCurrentProxyPayload();
            MycatMonitor.onLoadDataLocalInFileEmptyPacketEnd(mycat);
            return;
        } else if (mycat.shouldHandleContentOfFilename()) {
            MycatMonitor.onLoadDataLocalInFileContextStart(mycat);
            endFuture = commandHandler.handleContentOfFilename(curPacket.readEOFStringBytes(), mycat);
            mycat.resetCurrentProxyPayload();
            MycatMonitor.onLoadDataLocalInFileContextEnd(mycat);
            return;
        }
        byte head = curPacket.getByte(curPacket.packetReadStartIndex());
        switch(head) {
            case MySQLCommandType.COM_SLEEP:
                {
                    MycatMonitor.onSleepCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleSleep(mycat);
                    MycatMonitor.onSleepCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_QUIT:
                {
                    MycatMonitor.onQuitCommandStart(mycat);
                    curPacket.readByte();
                    endFuture = commandHandler.handleQuit(mycat);
                    MycatMonitor.onQuitCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_QUERY:
                {
                    MycatMonitor.onQueryCommandStart(mycat);
                    curPacket.readByte();
                    byte[] bytes = curPacket.readEOFStringBytes();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleQuery(bytes, mycat);
                    break;
                }
            case MySQLCommandType.COM_INIT_DB:
                {
                    MycatMonitor.onInitDbCommandStart(mycat);
                    curPacket.readByte();
                    String schema = curPacket.readEOFString();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleInitDb(schema, mycat);
                    MycatMonitor.onInitDbCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_PING:
                {
                    MycatMonitor.onPingCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePing(mycat);
                    MycatMonitor.onPingCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_FIELD_LIST:
                {
                    MycatMonitor.onFieldListCommandStart(mycat);
                    curPacket.readByte();
                    String table = curPacket.readNULString();
                    String field = curPacket.readEOFString();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleFieldList(table, field, mycat);
                    MycatMonitor.onFieldListCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_SET_OPTION:
                {
                    MycatMonitor.onSetOptionCommandStart(mycat);
                    curPacket.readByte();
                    boolean option = curPacket.readFixInt(2) == 1;
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleSetOption(option, mycat);
                    MycatMonitor.onSetOptionCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_STMT_PREPARE:
                {
                    MycatMonitor.onPrepareCommandStart(mycat);
                    curPacket.readByte();
                    byte[] bytes = curPacket.readEOFStringBytes();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePrepareStatement(bytes, mycat);
                    MycatMonitor.onPrepareCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_STMT_SEND_LONG_DATA:
                {
                    MycatMonitor.onSendLongDataCommandStart(mycat);
                    curPacket.readByte();
                    long statementId = curPacket.readFixInt(4);
                    int paramId = (int) curPacket.readFixInt(2);
                    byte[] data = curPacket.readEOFStringBytes();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePrepareStatementLongdata(statementId, paramId, data, mycat);
                    MycatMonitor.onSendLongDataCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_STMT_EXECUTE:
                {
                    MycatMonitor.onExecuteCommandStart(mycat);
                    MycatDataContext dataContext = mycat.getDataContext();
                    dataContext.getPrepareInfo();
                    try {
                        byte[] rawPayload = curPacket.getEOFStringBytes(curPacket.packetReadStartIndex());
                        curPacket.readByte();
                        long statementId = curPacket.readFixInt(4);
                        byte flags = curPacket.readByte();
                        long iteration = curPacket.readFixInt(4);
                        assert iteration == 1;
                        int numParams = commandHandler.getNumParamsByStatementId(statementId, mycat);
                        byte[] nullMap = null;
                        if (numParams > 0) {
                            nullMap = curPacket.readBytes((numParams + 7) / 8);
                        }
                        int[] params = null;
                        BindValue[] values = null;
                        boolean newParameterBoundFlag = !curPacket.readFinished() && curPacket.readByte() == 1;
                        if (newParameterBoundFlag) {
                            params = new int[numParams];
                            for (int i = 0; i < numParams; i++) {
                                params[i] = (int) curPacket.readFixInt(2);
                            }
                            values = new BindValue[numParams];
                            for (int i = 0; i < numParams; i++) {
                                BindValue bv = new BindValue();
                                bv.type = params[i];
                                if ((nullMap[i / 8] & (1 << (i & 7))) != 0) {
                                    bv.isNull = true;
                                } else {
                                    byte[] longData = commandHandler.getLongData(statementId, i, mycat);
                                    if (longData == null) {
                                        ServerConfig serverConfig = MetaClusterCurrent.wrapper(ServerConfig.class);
                                        BindValueUtil.read(curPacket, bv, StandardCharsets.UTF_8, !serverConfig.isPstmtStringVal());
                                        bv.isLongData = false;
                                    } else {
                                        bv.value = longData;
                                        bv.isLongData = true;
                                    }
                                }
                                values[i] = bv;
                            }
                            commandHandler.saveBindValue(statementId, values, mycat);
                        } else {
                            values = commandHandler.getLastBindValue(statementId, mycat);
                        }
                        mycat.resetCurrentProxyPayload();
                        endFuture = commandHandler.handlePrepareStatementExecute(statementId, flags, params, values, mycat);
                        break;
                    } finally {
                        MycatMonitor.onExecuteCommandEnd(mycat);
                    }
                }
            case MySQLCommandType.COM_STMT_CLOSE:
                {
                    MycatMonitor.onCloseCommandStart(mycat);
                    curPacket.readByte();
                    long statementId = curPacket.readFixInt(4);
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePrepareStatementClose(statementId, mycat);
                    endFuture = endFuture.onComplete(event -> mycat.onHandlerFinishedClear());
                    MycatMonitor.onCloseCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_STMT_FETCH:
                {
                    MycatMonitor.onFetchCommandStart(mycat);
                    curPacket.readByte();
                    long statementId = curPacket.readFixInt(4);
                    long row = curPacket.readFixInt(4);
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePrepareStatementFetch(statementId, row, mycat);
                    MycatMonitor.onFetchCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_STMT_RESET:
                {
                    MycatMonitor.onResetCommandStart(mycat);
                    curPacket.readByte();
                    long statementId = curPacket.readFixInt(4);
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handlePrepareStatementReset(statementId, mycat);
                    MycatMonitor.onResetCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_CREATE_DB:
                {
                    MycatMonitor.onCreateDbCommandStart(mycat);
                    curPacket.readByte();
                    String schema = curPacket.readEOFString();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleCreateDb(schema, mycat);
                    MycatMonitor.onCreateDbCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_DROP_DB:
                {
                    MycatMonitor.onDropDbCommandStart(mycat);
                    curPacket.readByte();
                    String schema = curPacket.readEOFString();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleDropDb(schema, mycat);
                    MycatMonitor.onDropDbCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_REFRESH:
                {
                    MycatMonitor.onRefreshCommandStart(mycat);
                    curPacket.readByte();
                    byte subCommand = curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleRefresh(subCommand, mycat);
                    MycatMonitor.onRefreshCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_SHUTDOWN:
                {
                    MycatMonitor.onShutdownCommandStart(mycat);
                    curPacket.readByte();
                    try {
                        if (!curPacket.readFinished()) {
                            byte shutdownType = curPacket.readByte();
                            mycat.resetCurrentProxyPayload();
                            endFuture = commandHandler.handleShutdown(shutdownType, mycat);
                        } else {
                            mycat.resetCurrentProxyPayload();
                            endFuture = commandHandler.handleShutdown(0, mycat);
                        }
                    } finally {
                        MycatMonitor.onShutdownCommandEnd(mycat);
                    }
                    break;
                }
            case MySQLCommandType.COM_STATISTICS:
                {
                    MycatMonitor.onStatisticsCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleStatistics(mycat);
                    MycatMonitor.onStatisticsCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_PROCESS_INFO:
                {
                    MycatMonitor.onProcessInfoCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleProcessInfo(mycat);
                    MycatMonitor.onProcessInfoCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_CONNECT:
                {
                    MycatMonitor.onConnectCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleConnect(mycat);
                    MycatMonitor.onConnectCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_PROCESS_KILL:
                {
                    MycatMonitor.onProcessKillCommandStart(mycat);
                    curPacket.readByte();
                    long connectionId = curPacket.readFixInt(4);
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleProcessKill(connectionId, mycat);
                    MycatMonitor.onProcessKillCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_DEBUG:
                {
                    MycatMonitor.onDebugCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleDebug(mycat);
                    MycatMonitor.onDebugCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_TIME:
                {
                    MycatMonitor.onTimeCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleTime(mycat);
                    MycatMonitor.onTimeCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_DELAYED_INSERT:
                {
                    MycatMonitor.onDelayedInsertCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleDelayedInsert(mycat);
                    MycatMonitor.onDelayedInsertCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_CHANGE_USER:
                {
                    MycatMonitor.onChangeUserCommandStart(mycat);
                    curPacket.readByte();
                    try {
                        String userName = curPacket.readNULString();
                        String authResponse = null;
                        String schemaName = null;
                        Integer characterSet = null;
                        String authPluginName = null;
                        HashMap<String, String> clientConnectAttrs = new HashMap<>();
                        int capabilities = mycat.getCapabilities();
                        if (MySQLServerCapabilityFlags.isCanDo41Anthentication(capabilities)) {
                            byte len = curPacket.readByte();
                            authResponse = curPacket.readFixString(len);
                        } else {
                            authResponse = curPacket.readNULString();
                        }
                        schemaName = curPacket.readNULString();
                        if (!curPacket.readFinished()) {
                            characterSet = (int) curPacket.readFixInt(2);
                            if (MySQLServerCapabilityFlags.isPluginAuth(capabilities)) {
                                authPluginName = curPacket.readNULString();
                            }
                            if (MySQLServerCapabilityFlags.isConnectAttrs(capabilities)) {
                                long kvAllLength = curPacket.readLenencInt();
                                if (kvAllLength != 0) {
                                    clientConnectAttrs = new HashMap<>();
                                }
                                int count = 0;
                                while (count < kvAllLength) {
                                    String k = curPacket.readLenencString();
                                    String v = curPacket.readLenencString();
                                    count += k.length();
                                    count += v.length();
                                    count += calcLenencLength(k.length());
                                    count += calcLenencLength(v.length());
                                    clientConnectAttrs.put(k, v);
                                }
                            }
                        }
                        mycat.resetCurrentProxyPayload();
                        endFuture = commandHandler.handleChangeUser(userName, authResponse, schemaName, characterSet, authPluginName, clientConnectAttrs, mycat);
                    } finally {
                        MycatMonitor.onChangeUserCommandEnd(mycat);
                    }
                    break;
                }
            case MySQLCommandType.COM_RESET_CONNECTION:
                {
                    MycatMonitor.onResetConnectionCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleResetConnection(mycat);
                    MycatMonitor.onResetConnectionCommandEnd(mycat);
                    break;
                }
            case MySQLCommandType.COM_DAEMON:
                {
                    MycatMonitor.onDaemonCommandStart(mycat);
                    curPacket.readByte();
                    mycat.resetCurrentProxyPayload();
                    endFuture = commandHandler.handleDaemon(mycat);
                    MycatMonitor.onDaemonCommandEnd(mycat);
                    break;
                }
            default:
                {
                    assert false;
                }
        }
    } finally {
        Objects.requireNonNull(endFuture).onComplete(event -> {
            Future<Void> future = Future.succeededFuture();
            if (event.failed()) {
                mycat.setLastMessage(event.cause());
                future = mycat.writeErrorEndPacketBySyncInProcessError();
            }
            future.onComplete(event1 -> {
                MycatMonitor.onCommandEnd(mycat);
            });
        });
    }
}
Also used : ServerConfig(io.mycat.config.ServerConfig) HashMap(java.util.HashMap) MycatDataContext(io.mycat.MycatDataContext) BindValue(io.mycat.BindValue)

Example 4 with ServerConfig

use of io.mycat.config.ServerConfig in project Mycat2 by MyCATApache.

the class SpmTest method init.

@BeforeClass
public static void init() throws Exception {
    HashMap<Class, Object> context = new HashMap<>();
    context.put(Vertx.class, Vertx.vertx());
    context.put(ServerConfig.class, new ServerConfig());
    context.put(IOExecutor.class, IOExecutor.DEFAULT);
    context.put(DrdsSqlCompiler.class, new DrdsSqlCompiler(new DrdsConst() {

        @Override
        public NameMap<SchemaHandler> schemas() {
            return new NameMap<>();
        }
    }));
    MetaClusterCurrent.register(context);
    String customerDatasourceProvider = DruidDatasourceProvider.class.getName();
    DatasourceConfig datasourceConfig = new DatasourceConfig();
    datasourceConfig.setDbType("mysql");
    datasourceConfig.setUser("root");
    datasourceConfig.setPassword("123456");
    datasourceConfig.setName("prototypeDs");
    datasourceConfig.setUrl("jdbc:mysql://localhost:3306/mysql");
    Map<String, DatasourceConfig> datasources = Maps.of("prototypeDs", datasourceConfig);
    ClusterConfig clusterConfig = new ClusterConfig();
    clusterConfig.setName("prototype");
    clusterConfig.setMasters(Arrays.asList("prototypeDs"));
    Map<String, ClusterConfig> clusterConfigs = Maps.of("prototype", clusterConfig);
    LinkedList<Runnable> runnables = new LinkedList<>();
    ReplicaSelectorManager manager = ReplicaSelectorRuntime.create(new ArrayList<>(clusterConfigs.values()), datasources, new LoadBalanceManager(), name -> 0, (command, initialDelay, period, unit) -> {
        runnables.add(command);
        return () -> {
        };
    });
    context.put(ReplicaSelectorManager.class, manager);
    context.put(JdbcConnectionManager.class, jdbcManager = new JdbcConnectionManager(DruidDatasourceProvider.class.getName(), datasources));
    MetaClusterCurrent.register(context);
}
Also used : SchemaHandler(io.mycat.calcite.table.SchemaHandler) ReplicaSelectorManager(io.mycat.replica.ReplicaSelectorManager) NameMap(io.mycat.util.NameMap) LoadBalanceManager(io.mycat.plug.loadBalance.LoadBalanceManager) DruidDatasourceProvider(io.mycat.datasource.jdbc.DruidDatasourceProvider) ServerConfig(io.mycat.config.ServerConfig) DatasourceConfig(io.mycat.config.DatasourceConfig) BeforeClass(org.junit.BeforeClass) AfterClass(org.junit.AfterClass) JdbcConnectionManager(io.mycat.datasource.jdbc.datasource.JdbcConnectionManager) ClusterConfig(io.mycat.config.ClusterConfig) BeforeClass(org.junit.BeforeClass)

Example 5 with ServerConfig

use of io.mycat.config.ServerConfig in project Mycat2 by MyCATApache.

the class MycatVertxMySQLHandler method handle0.

public Future<Void> handle0(int packetId, Buffer event) {
    Process process = Process.getCurrentProcess();
    session.setPacketId(packetId);
    ReadView readView = new ReadView(event);
    Future<Void> promise;
    try {
        byte command = readView.readByte();
        process.setCommand(command);
        process.setContext(mycatDataContext);
        switch(command) {
            case MySQLCommandType.COM_SLEEP:
                {
                    promise = handleSleep(this.session);
                    break;
                }
            case MySQLCommandType.COM_QUIT:
                {
                    promise = handleQuit(this.session);
                    break;
                }
            case MySQLCommandType.COM_QUERY:
                {
                    String sql = new String(readView.readEOFStringBytes(), StandardCharsets.UTF_8);
                    process.setQuery(sql);
                    process.setState(Process.State.INIT);
                    IOExecutor vertx = MetaClusterCurrent.wrapper(IOExecutor.class);
                    promise = vertx.executeBlocking((Handler<Promise<Void>>) event1 -> handleQuery(sql, session).onComplete(event1));
                    break;
                }
            case MySQLCommandType.COM_INIT_DB:
                {
                    String schema = readView.readEOFString();
                    promise = handleInitDb(schema, this.session);
                    break;
                }
            case MySQLCommandType.COM_PING:
                {
                    promise = handlePing(this.session);
                    break;
                }
            case MySQLCommandType.COM_FIELD_LIST:
                {
                    String table = readView.readNULString();
                    String field = readView.readEOFString();
                    promise = handleFieldList(table, field, this.session);
                    break;
                }
            case MySQLCommandType.COM_SET_OPTION:
                {
                    boolean option = readView.readFixInt(2) == 1;
                    promise = handleSetOption(option, this.session);
                    break;
                }
            case MySQLCommandType.COM_STMT_PREPARE:
                {
                    byte[] bytes = readView.readEOFStringBytes();
                    IOExecutor ioExecutor = MetaClusterCurrent.wrapper(IOExecutor.class);
                    promise = ioExecutor.executeBlocking(voidPromise -> {
                        try {
                            handlePrepareStatement(bytes, session).onComplete(voidPromise);
                        } catch (Throwable throwable) {
                            voidPromise.fail(throwable);
                        }
                    });
                    break;
                }
            case MySQLCommandType.COM_STMT_SEND_LONG_DATA:
                {
                    long statementId = readView.readFixInt(4);
                    int paramId = (int) readView.readFixInt(2);
                    byte[] data = readView.readEOFStringBytes();
                    promise = handlePrepareStatementLongdata(statementId, paramId, data, this.session);
                    break;
                }
            case MySQLCommandType.COM_STMT_EXECUTE:
                {
                    MycatDataContext dataContext = this.session.getDataContext();
                    Map<Long, PreparedStatement> prepareInfo = dataContext.getPrepareInfo();
                    long statementId = readView.readFixInt(4);
                    byte flags = readView.readByte();
                    long iteration = readView.readFixInt(4);
                    assert iteration == 1;
                    int numParams = getNumParamsByStatementId(statementId, this.session);
                    byte[] nullMap = null;
                    if (numParams > 0) {
                        nullMap = readView.readBytes((numParams + 7) / 8);
                    }
                    int[] params = prepareInfo.get(statementId).getParametersType();
                    BindValue[] values = new BindValue[numParams];
                    boolean newParameterBoundFlag = !readView.readFinished() && readView.readByte() == 1;
                    if (newParameterBoundFlag) {
                        for (int i = 0; i < numParams; i++) {
                            params[i] = (int) readView.readFixInt(2);
                        }
                    }
                    for (int i = 0; i < numParams; i++) {
                        BindValue bv = new BindValue();
                        bv.type = params[i];
                        if ((nullMap[i / 8] & (1 << (i & 7))) != 0) {
                            bv.isNull = true;
                        } else {
                            byte[] longData = getLongData(statementId, i, this.session);
                            if (longData == null) {
                                ServerConfig serverConfig = MetaClusterCurrent.wrapper(ServerConfig.class);
                                BindValueUtil.read(readView, bv, StandardCharsets.UTF_8, !serverConfig.isPstmtStringVal());
                                bv.isLongData = false;
                            } else {
                                bv.value = longData;
                                bv.isLongData = true;
                            }
                        }
                        values[i] = bv;
                    }
                    saveBindValue(statementId, values, this.session);
                    promise = handlePrepareStatementExecute(statementId, flags, params, values, this.session);
                    break;
                }
            case MySQLCommandType.COM_STMT_CLOSE:
                {
                    long statementId = readView.readFixInt(4);
                    promise = handlePrepareStatementClose(statementId, this.session);
                    break;
                }
            case MySQLCommandType.COM_STMT_FETCH:
                {
                    long statementId = readView.readFixInt(4);
                    long row = readView.readFixInt(4);
                    promise = handlePrepareStatementFetch(statementId, row, this.session);
                    break;
                }
            case MySQLCommandType.COM_STMT_RESET:
                {
                    long statementId = readView.readFixInt(4);
                    promise = handlePrepareStatementReset(statementId, this.session);
                    break;
                }
            case MySQLCommandType.COM_CREATE_DB:
                {
                    String schema = readView.readEOFString();
                    promise = handleCreateDb(schema, this.session);
                    break;
                }
            case MySQLCommandType.COM_DROP_DB:
                {
                    String schema = readView.readEOFString();
                    promise = handleDropDb(schema, this.session);
                    break;
                }
            case MySQLCommandType.COM_REFRESH:
                {
                    byte subCommand = readView.readByte();
                    promise = handleRefresh(subCommand, this.session);
                    break;
                }
            case MySQLCommandType.COM_SHUTDOWN:
                {
                    try {
                        if (!readView.readFinished()) {
                            byte shutdownType = readView.readByte();
                            promise = handleShutdown(shutdownType, this.session);
                        } else {
                            promise = handleShutdown(0, this.session);
                        }
                    } finally {
                    }
                    break;
                }
            case MySQLCommandType.COM_STATISTICS:
                {
                    promise = handleStatistics(this.session);
                    break;
                }
            case MySQLCommandType.COM_PROCESS_INFO:
                {
                    promise = handleProcessInfo(this.session);
                    break;
                }
            case MySQLCommandType.COM_CONNECT:
                {
                    promise = handleConnect(this.session);
                    break;
                }
            case MySQLCommandType.COM_PROCESS_KILL:
                {
                    long connectionId = readView.readFixInt(4);
                    promise = handleProcessKill(connectionId, this.session);
                    break;
                }
            case MySQLCommandType.COM_DEBUG:
                {
                    promise = handleDebug(this.session);
                    break;
                }
            case MySQLCommandType.COM_TIME:
                {
                    promise = handleTime(this.session);
                    break;
                }
            case MySQLCommandType.COM_DELAYED_INSERT:
                {
                    promise = handleDelayedInsert(this.session);
                    break;
                }
            case MySQLCommandType.COM_CHANGE_USER:
                {
                    String userName = readView.readNULString();
                    String authResponse = null;
                    String schemaName = null;
                    Integer characterSet = null;
                    String authPluginName = null;
                    HashMap<String, String> clientConnectAttrs = new HashMap<>();
                    int capabilities = this.session.getCapabilities();
                    if (MySQLServerCapabilityFlags.isCanDo41Anthentication(capabilities)) {
                        byte len = readView.readByte();
                        authResponse = readView.readFixString(len);
                    } else {
                        authResponse = readView.readNULString();
                    }
                    schemaName = readView.readNULString();
                    if (!readView.readFinished()) {
                        characterSet = (int) readView.readFixInt(2);
                        if (MySQLServerCapabilityFlags.isPluginAuth(capabilities)) {
                            authPluginName = readView.readNULString();
                        }
                        if (MySQLServerCapabilityFlags.isConnectAttrs(capabilities)) {
                            long kvAllLength = readView.readLenencInt();
                            if (kvAllLength != 0) {
                                clientConnectAttrs = new HashMap<>();
                            }
                            int count = 0;
                            while (count < kvAllLength) {
                                String k = readView.readLenencString();
                                String v = readView.readLenencString();
                                count += k.length();
                                count += v.length();
                                count += calcLenencLength(k.length());
                                count += calcLenencLength(v.length());
                                clientConnectAttrs.put(k, v);
                            }
                        }
                    }
                    promise = handleChangeUser(userName, authResponse, schemaName, characterSet, authPluginName, clientConnectAttrs, this.session);
                    break;
                }
            case MySQLCommandType.COM_RESET_CONNECTION:
                {
                    promise = handleResetConnection(this.session);
                    break;
                }
            case MySQLCommandType.COM_DAEMON:
                {
                    promise = handleDaemon(this.session);
                    break;
                }
            default:
                {
                    promise = VertxUtil.newFailPromise(new MycatException(MycatErrorCode.ERR_NOT_SUPPORT, "无法识别的MYSQL数据包"));
                    assert false;
                }
        }
        return promise.onSuccess(event12 -> mycatDataContext.setLastMessage((String) null)).recover(cause -> {
            int errorCode = 0;
            String message;
            String sqlState;
            if (cause instanceof SQLException) {
                errorCode = ((SQLException) cause).getErrorCode();
                message = ((SQLException) cause).getMessage();
                sqlState = ((SQLException) cause).getSQLState();
            } else if (cause instanceof MycatException) {
                errorCode = ((MycatException) cause).getErrorCode();
                message = ((MycatException) cause).getMessage();
                sqlState = "";
            } else {
                message = cause.toString();
            }
            mycatDataContext.setLastMessage(message);
            return this.session.writeErrorEndPacketBySyncInProcessError(errorCode);
        });
    } catch (Throwable throwable) {
        mycatDataContext.setLastMessage(throwable);
        return this.session.writeErrorEndPacketBySyncInProcessError(0);
    }
}
Also used : MycatdbCommand(io.mycat.commands.MycatdbCommand) MySQLServerCapabilityFlags(io.mycat.config.MySQLServerCapabilityFlags) java.util(java.util) ResultSetBuilder(io.mycat.beans.mycat.ResultSetBuilder) io.mycat(io.mycat) MycatRowMetaData(io.mycat.beans.mycat.MycatRowMetaData) ByteArrayOutputStream(java.io.ByteArrayOutputStream) LoggerFactory(org.slf4j.LoggerFactory) SQLUpdateStatement(com.alibaba.druid.sql.ast.statement.SQLUpdateStatement) JDBCType(java.sql.JDBCType) SQLException(java.sql.SQLException) ProxyReceiverImpl(io.mycat.commands.ProxyReceiverImpl) MySqlASTVisitorAdapter(com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter) MySQLCommandType(io.mycat.beans.mysql.MySQLCommandType) Process(io.mycat.Process) MycatErrorCode(io.mycat.beans.mycat.MycatErrorCode) SQLVariantRefExpr(com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr) ReceiverImpl(io.mycat.commands.ReceiverImpl) DefaultPreparedOKPacket(io.mycat.beans.mysql.packet.DefaultPreparedOKPacket) SQLUtils(com.alibaba.druid.sql.SQLUtils) Logger(org.slf4j.Logger) Promise(io.vertx.core.Promise) SQLInsertStatement(com.alibaba.druid.sql.ast.statement.SQLInsertStatement) SQLExpr(com.alibaba.druid.sql.ast.SQLExpr) SQLDeleteStatement(com.alibaba.druid.sql.ast.statement.SQLDeleteStatement) PrototypeService(io.mycat.prototypeserver.mysql.PrototypeService) VertxUtil(io.mycat.util.VertxUtil) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) AuthPacket.calcLenencLength(io.mycat.beans.mysql.packet.AuthPacket.calcLenencLength) MySqlKillStatement(com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlKillStatement) ServerConfig(io.mycat.config.ServerConfig) Buffer(io.vertx.core.buffer.Buffer) SQLStatement(com.alibaba.druid.sql.ast.SQLStatement) SQLSelectStatement(com.alibaba.druid.sql.ast.statement.SQLSelectStatement) ReadView(io.mycat.vertx.ReadView) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) SQLException(java.sql.SQLException) Process(io.mycat.Process) Promise(io.vertx.core.Promise) ServerConfig(io.mycat.config.ServerConfig) ReadView(io.mycat.vertx.ReadView)

Aggregations

ServerConfig (io.mycat.config.ServerConfig)6 DruidDatasourceProvider (io.mycat.datasource.jdbc.DruidDatasourceProvider)3 SchemaHandler (io.mycat.calcite.table.SchemaHandler)2 ClusterConfig (io.mycat.config.ClusterConfig)2 DatasourceConfig (io.mycat.config.DatasourceConfig)2 JdbcConnectionManager (io.mycat.datasource.jdbc.datasource.JdbcConnectionManager)2 LoadBalanceManager (io.mycat.plug.loadBalance.LoadBalanceManager)2 ReplicaSelectorManager (io.mycat.replica.ReplicaSelectorManager)2 NameMap (io.mycat.util.NameMap)2 SQLUtils (com.alibaba.druid.sql.SQLUtils)1 SQLExpr (com.alibaba.druid.sql.ast.SQLExpr)1 SQLStatement (com.alibaba.druid.sql.ast.SQLStatement)1 SQLVariantRefExpr (com.alibaba.druid.sql.ast.expr.SQLVariantRefExpr)1 SQLDeleteStatement (com.alibaba.druid.sql.ast.statement.SQLDeleteStatement)1 SQLInsertStatement (com.alibaba.druid.sql.ast.statement.SQLInsertStatement)1 SQLSelectStatement (com.alibaba.druid.sql.ast.statement.SQLSelectStatement)1 SQLUpdateStatement (com.alibaba.druid.sql.ast.statement.SQLUpdateStatement)1 MySqlKillStatement (com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlKillStatement)1 MySqlASTVisitorAdapter (com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter)1 io.mycat (io.mycat)1