Search in sources :

Example 1 with Process

use of io.mycat.Process 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)

Example 2 with Process

use of io.mycat.Process in project Mycat2 by MyCATApache.

the class ShowProcessListSQLHandler method onExecute.

@Override
protected Future<Void> onExecute(SQLRequest<MySqlShowProcessListStatement> request, MycatDataContext dataContext, Response response) {
    Map<Thread, Process> processMap = new LinkedHashMap<>(Process.getProcessMap());
    MySqlShowProcessListStatement ast = request.getAst();
    boolean full = ast.isFull();
    int maxCount = full ? Integer.MAX_VALUE : 100;
    MycatUser currentUser = full ? null : dataContext.getUser();
    ResultSetBuilder resultSetBuilder = ResultSetBuilder.create();
    resultSetBuilder.addColumnInfo("Id", JDBCType.INTEGER);
    resultSetBuilder.addColumnInfo("User", JDBCType.VARCHAR);
    resultSetBuilder.addColumnInfo("Host", JDBCType.VARCHAR);
    resultSetBuilder.addColumnInfo("db", JDBCType.VARCHAR);
    resultSetBuilder.addColumnInfo("Command", JDBCType.VARCHAR);
    resultSetBuilder.addColumnInfo("Time", JDBCType.BIGINT);
    resultSetBuilder.addColumnInfo("State", JDBCType.VARCHAR);
    resultSetBuilder.addColumnInfo("Info", JDBCType.VARCHAR);
    long timestamp = System.currentTimeMillis();
    int currentCount = 0;
    for (Map.Entry<Thread, Process> entry : processMap.entrySet()) {
        Thread holdThread = entry.getKey();
        Process process = entry.getValue();
        if (currentUser != null && !Objects.equals(process.getUser(), currentUser.getUserName())) {
            continue;
        }
        resultSetBuilder.addObjectRowPayload(Arrays.asList(process.getId(), process.getUser(), process.getHost(), process.getDb(), process.getCommand(), timestamp - process.getCreateTimestamp().getTime(), process.getState(), process.getInfo()));
        currentCount++;
        if (currentCount >= maxCount) {
            break;
        }
    }
    return response.sendResultSet(resultSetBuilder.build());
// return response.proxySelectToPrototype(request.getAst().toString());
}
Also used : ResultSetBuilder(io.mycat.beans.mycat.ResultSetBuilder) MycatUser(io.mycat.MycatUser) Process(io.mycat.Process) MySqlShowProcessListStatement(com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlShowProcessListStatement) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap)

Aggregations

Process (io.mycat.Process)2 ResultSetBuilder (io.mycat.beans.mycat.ResultSetBuilder)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 MySqlShowProcessListStatement (com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlShowProcessListStatement)1 MySqlASTVisitorAdapter (com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitorAdapter)1 io.mycat (io.mycat)1 MycatUser (io.mycat.MycatUser)1 MycatErrorCode (io.mycat.beans.mycat.MycatErrorCode)1 MycatRowMetaData (io.mycat.beans.mycat.MycatRowMetaData)1 MySQLCommandType (io.mycat.beans.mysql.MySQLCommandType)1 AuthPacket.calcLenencLength (io.mycat.beans.mysql.packet.AuthPacket.calcLenencLength)1 DefaultPreparedOKPacket (io.mycat.beans.mysql.packet.DefaultPreparedOKPacket)1