Search in sources :

Example 6 with MycatException

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

the class MycatCalciteMySqlNodeVisitor method buildIdentifier.

void buildIdentifier(SQLPropertyExpr x, List<String> names) {
    String name = SQLUtils.normalize(x.getName());
    SQLExpr owner = x.getOwner();
    if (owner instanceof SQLIdentifierExpr) {
        names.add(((SQLIdentifierExpr) owner).normalizedName());
    } else if (owner instanceof SQLPropertyExpr) {
        buildIdentifier((SQLPropertyExpr) owner, names);
    } else {
        throw new MycatException("not support : " + owner);
    }
    names.add(name);
}
Also used : MycatException(io.mycat.MycatException) TimeString(org.apache.calcite.util.TimeString) DateString(org.apache.calcite.util.DateString) TimestampString(org.apache.calcite.util.TimestampString)

Example 7 with MycatException

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

the class CachingSha2PasswordPlugin method decodeRSAPublicKey.

public static RSAPublicKey decodeRSAPublicKey(String key) throws Exception {
    if (key == null) {
        throw new MycatException("Key parameter is null\"");
    }
    int offset = key.indexOf("\n") + 1;
    int len = key.indexOf("-----END PUBLIC KEY-----") - offset;
    // TODO: use standard decoders with Java 6+
    byte[] certificateData = Base64Decoder.decode(key.getBytes(), offset, len);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(certificateData);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return (RSAPublicKey) kf.generatePublic(spec);
}
Also used : MycatException(io.mycat.MycatException) RSAPublicKey(java.security.interfaces.RSAPublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeyFactory(java.security.KeyFactory)

Example 8 with MycatException

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

the class ResponseBufferCommand method resolvePayloadType.

void resolvePayloadType(int head, boolean isPacketFinished, int payloadLength) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("state:{}", state);
    }
    switch(state) {
        case QUERY_PACKET:
            {
                if (!isPacketFinished) {
                    throw new RuntimeException("unknown state!");
                }
                switch(head) {
                    case 3:
                        {
                            state = (MySQLPacketResolver.ComQueryState.FIRST_PACKET);
                            payloadType = (REQUEST_COM_QUERY);
                            return;
                        }
                    case 24:
                        {
                            state = (MySQLPacketResolver.ComQueryState.QUERY_PACKET);
                            payloadType = (REQUEST_SEND_LONG_DATA);
                            return;
                        }
                    case 25:
                        {
                            state = (MySQLPacketResolver.ComQueryState.QUERY_PACKET);
                            payloadType = (REQUEST_COM_STMT_CLOSE);
                            return;
                        }
                    case 22:
                        {
                            state = (MySQLPacketResolver.ComQueryState.FIRST_PACKET);
                            payloadType = (REQUEST_PREPARE);
                            return;
                        }
                    default:
                        {
                            throw new IllegalArgumentException("unknown packet head:" + head);
                        }
                }
            }
        case AUTH_SWITCH_PLUGIN_RESPONSE:
        case AUTH_SWITCH_OTHER_REQUEST:
        case FIRST_PACKET:
            {
                if (!isPacketFinished) {
                    throw new MycatException("unknown state!");
                }
                if (head == 0xff) {
                    state = (MySQLPacketResolver.ComQueryState.COMMAND_END);
                    payloadType = (FIRST_ERROR);
                } else if (head == 0x00) {
                    throw new UnsupportedOperationException();
                } else if (head == 0xfb) {
                    throw new UnsupportedOperationException();
                } else if (head == 0xfe) {
                    // setServerStatus(eofPacketReadStatus(mySQLPacket));
                    state = (MySQLPacketResolver.ComQueryState.COMMAND_END);
                    payloadType = (FIRST_EOF);
                    return;
                } else {
                    state = (MySQLPacketResolver.ComQueryState.COLUMN_DEFINITION);
                    payloadType = (COLUMN_COUNT);
                }
                return;
            }
        case COLUMN_DEFINITION:
            {
                if (setColumnCount(getColumnCount() - 1) == 0) {
                    state = config.isClientDeprecateEof() ? RESULTSET_ROW : MySQLPacketResolver.ComQueryState.COLUMN_END_EOF;
                }
                payloadType = (COLUMN_DEF);
                return;
            }
        case COLUMN_END_EOF:
            {
                if (!isPacketFinished) {
                    throw new RuntimeException("unknown state!");
                }
                state = (RESULTSET_ROW);
                payloadType = (COLUMN_EOF);
                return;
            }
        case RESULTSET_ROW:
            {
                if (head == 0x00) {
                    throw new UnsupportedOperationException();
                } else if (head == 0xfe && payloadLength < 0xffffff) {
                    resolveResultsetRowEnd(isPacketFinished);
                    // COMMAND_END结束完毕就切换到读状态
                    state = (MySQLPacketResolver.ComQueryState.COMMAND_END);
                } else if (head == 0xff) {
                    state = (MySQLPacketResolver.ComQueryState.RESULTSET_ROW_ERROR);
                    payloadType = (ROW_ERROR);
                    // 还需要切换状态到COMMAND_END
                    payloadType = null;
                } else {
                    // text resultset row
                    payloadType = (TEXT_ROW);
                }
                break;
            }
        case RESULTSET_ROW_ERROR:
            {
                // COMMAND_END结束完毕就切换到读状态
                state = (MySQLPacketResolver.ComQueryState.COMMAND_END);
                payloadType = (ROW_ERROR);
                break;
            }
        case PREPARE_FIELD:
            break;
        case PREPARE_FIELD_EOF:
            break;
        case PREPARE_PARAM:
            break;
        case PREPARE_PARAM_EOF:
            break;
        case COMMAND_END:
            {
            }
            return;
        case LOCAL_INFILE_OK_PACKET:
            break;
        default:
            {
                if (!isPacketFinished) {
                    throw new RuntimeException("unknown state!");
                } else {
                    throw new RuntimeException("unknown state!");
                }
            }
    }
}
Also used : MycatException(io.mycat.MycatException)

Example 9 with MycatException

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

the class RowSetQuery method runTextQuery.

public static PromiseInternal<SqlResult<Void>> runTextQuery(String curSql, MySQLClientSession mySQLClientSession, StreamMysqlCollector collectorArg) {
    if (mySQLClientSession.getCurNIOHandler() != null) {
        throw new IllegalArgumentException();
    }
    PromiseInternal<SqlResult<Void>> promise = VertxUtil.newPromise();
    if (mySQLClientSession.getIOThread() == Thread.currentThread()) {
        VertxMycatTextCollector<Object, Object> resultSetHandler = new VertxMycatTextCollector<Object, Object>((Collector) collectorArg);
        if (LOGGER.isDebugEnabled()) {
            if (curSql.startsWith("XA ROLLBACK")) {
                LOGGER.debug("session id:{} sql:{}", mySQLClientSession.sessionId(), curSql, new Throwable());
            }
            LOGGER.debug("session id:{} sql:{}", mySQLClientSession.sessionId(), curSql);
        }
        resultSetHandler.request(mySQLClientSession, MySQLCommandType.COM_QUERY, curSql.getBytes(), new ResultSetCallBack<MySQLClientSession>() {

            @Override
            public void onFinishedSendException(Exception exception, Object sender, Object attr) {
                MycatException mycatException = new MycatException(MySQLErrorCode.ER_UNKNOWN_ERROR, exception.getMessage());
                LOGGER.error("session id:{} sql:{}", mySQLClientSession.sessionId(), curSql, mycatException);
                promise.tryFail(mycatException);
            }

            @Override
            public void onFinishedException(Exception exception, Object sender, Object attr) {
                MycatException mycatException = new MycatException(MySQLErrorCode.ER_UNKNOWN_ERROR, exception.getMessage());
                LOGGER.error("session id:{} sql:{}", mySQLClientSession.sessionId(), curSql, mycatException);
                promise.tryFail(mycatException);
            }

            @Override
            public void onFinished(boolean monopolize, MySQLClientSession mysql, Object sender, Object attr) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("onFinished session id:{} sql:{}", mySQLClientSession.sessionId(), curSql);
                }
                MySqlResult<Void> mySqlResult = new MySqlResult<>(resultSetHandler.getRowCount(), resultSetHandler.getAffectedRows(), resultSetHandler.getLastInsertId(), null, Optional.ofNullable(resultSetHandler.getRowResultDecoder()).map(i -> i.rowDesc).map(i -> i.columnDescriptor()).orElse(Collections.emptyList()));
                promise.complete(mySqlResult);
            }

            @Override
            public void onErrorPacket(ErrorPacketImpl errorPacket, boolean monopolize, MySQLClientSession mysql, Object sender, Object attr) {
                MycatException mycatException = new MycatException(errorPacket.getErrorCode(), errorPacket.getErrorMessageString());
                LOGGER.error("onErrorPacket session id:{} sql:{}", mySQLClientSession.sessionId(), curSql, mycatException);
                promise.tryFail(mycatException);
            }
        });
    } else {
        mySQLClientSession.getIOThread().addNIOJob(new NIOJob() {

            @Override
            public void run(ReactorEnvThread reactor) throws Exception {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.error("nio job session id:{} sql:{}", mySQLClientSession.sessionId(), curSql, new Throwable());
                }
                runTextQuery(curSql, mySQLClientSession, collectorArg).onComplete(promise);
            }

            @Override
            public void stop(ReactorEnvThread reactor, Exception reason) {
                promise.tryFail(reason);
            }

            @Override
            public String message() {
                return "proxy query text result set";
            }
        });
    }
    return promise;
}
Also used : MySQLClient(io.vertx.mysqlclient.MySQLClient) LoggerFactory(org.slf4j.LoggerFactory) MySQLRowDesc(io.vertx.mysqlclient.impl.MySQLRowDesc) Function(java.util.function.Function) NIOJob(io.mycat.proxy.reactor.NIOJob) MySQLClientSession(io.mycat.proxy.session.MySQLClientSession) MySQLCommandType(io.mycat.beans.mysql.MySQLCommandType) ReactorEnvThread(io.mycat.proxy.reactor.ReactorEnvThread) StreamMysqlCollector(io.vertx.mysqlclient.impl.codec.StreamMysqlCollector) SqlResult(io.vertx.sqlclient.SqlResult) ErrorPacketImpl(io.mycat.beans.mysql.packet.ErrorPacketImpl) MySQLErrorCode(io.mycat.beans.mysql.MySQLErrorCode) RowSet(io.vertx.sqlclient.RowSet) AsyncResult(io.vertx.core.AsyncResult) Collector(java.util.stream.Collector) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) Logger(org.slf4j.Logger) MycatException(io.mycat.MycatException) Query(io.vertx.sqlclient.Query) VertxUtil(io.mycat.util.VertxUtil) Future(io.vertx.core.Future) Row(io.vertx.sqlclient.Row) VertxRowSetImpl(io.vertx.mysqlclient.impl.codec.VertxRowSetImpl) Optional(java.util.Optional) Handler(io.vertx.core.Handler) Collections(java.util.Collections) ResultSetCallBack(io.mycat.proxy.callback.ResultSetCallBack) ReactorEnvThread(io.mycat.proxy.reactor.ReactorEnvThread) MycatException(io.mycat.MycatException) SqlResult(io.vertx.sqlclient.SqlResult) NIOJob(io.mycat.proxy.reactor.NIOJob) MycatException(io.mycat.MycatException) ErrorPacketImpl(io.mycat.beans.mysql.packet.ErrorPacketImpl) MySQLClientSession(io.mycat.proxy.session.MySQLClientSession)

Example 10 with MycatException

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

the class MySQLDatasourcePool method createSession.

public Future<MySQLClientSession> createSession() {
    if (!(Thread.currentThread() instanceof ReactorEnvThread)) {
        return waitForIdleSession(false);
    }
    int limitCount = this.getSessionLimitCount();
    synchronized (this) {
        if (allSessions.size() >= limitCount && idleSessions.isEmpty()) {
            return waitForIdleSession(true);
        }
    }
    if (idleSessions.isEmpty()) {
        Future<MySQLClientSession> future = innerCreateCon();
        return future.recover(new Function<Throwable, Future<MySQLClientSession>>() {

            final AtomicInteger retryCount = new AtomicInteger(0);

            final long startTime = System.currentTimeMillis();

            @Override
            public Future<MySQLClientSession> apply(Throwable t) {
                PromiseInternal<MySQLClientSession> promise = VertxUtil.newPromise();
                long now = System.currentTimeMillis();
                long maxConnectTimeout = MySQLDatasourcePool.this.getMaxConnectTimeout();
                if (retryCount.get() >= limitCount) {
                    promise.tryFail(new MycatException("retry get connection fail:" + getName()));
                } else if (startTime + maxConnectTimeout > now) {
                    promise.tryFail(new MycatException("retry get connection timeout:" + getName()));
                } else {
                    retryCount.incrementAndGet();
                    waitForIdleSession(true).recover(this).onComplete(promise);
                }
                return promise.future();
            }
        });
    } else {
        MySQLClientSession session = idleSessions.removeFirst();
        if (session.checkOpen()) {
            session.setIdle(false);
            session.switchNioHandler(null);
            return Future.succeededFuture(session);
        } else {
            return session.close(false, "has closed").flatMap(unused -> createSession());
        }
    }
}
Also used : ReactorEnvThread(io.mycat.proxy.reactor.ReactorEnvThread) MycatException(io.mycat.MycatException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) ScheduledFuture(java.util.concurrent.ScheduledFuture) CompositeFuture(io.vertx.core.CompositeFuture) Future(io.vertx.core.Future) MySQLClientSession(io.mycat.proxy.session.MySQLClientSession)

Aggregations

MycatException (io.mycat.MycatException)31 SQLExpr (com.alibaba.druid.sql.ast.SQLExpr)3 SQLName (com.alibaba.druid.sql.ast.SQLName)3 SQLIdentifierExpr (com.alibaba.druid.sql.ast.expr.SQLIdentifierExpr)3 MySQLClientSession (io.mycat.proxy.session.MySQLClientSession)3 SQLException (java.sql.SQLException)3 CalciteSqlBasicCall (com.alibaba.druid.support.calcite.CalciteSqlBasicCall)2 ColumnDefPacket (io.mycat.beans.mysql.packet.ColumnDefPacket)2 DatasourceConfig (io.mycat.config.DatasourceConfig)2 ProxyBufferImpl (io.mycat.proxy.buffer.ProxyBufferImpl)2 ReactorEnvThread (io.mycat.proxy.reactor.ReactorEnvThread)2 Future (io.vertx.core.Future)2 PromiseInternal (io.vertx.core.impl.future.PromiseInternal)2 Statement (java.sql.Statement)2 DateString (org.apache.calcite.util.DateString)2 TimeString (org.apache.calcite.util.TimeString)2 TimestampString (org.apache.calcite.util.TimestampString)2 SQLBooleanExpr (com.alibaba.druid.sql.ast.expr.SQLBooleanExpr)1 SQLExprTableSource (com.alibaba.druid.sql.ast.statement.SQLExprTableSource)1 SQLShowTablesStatement (com.alibaba.druid.sql.ast.statement.SQLShowTablesStatement)1