Search in sources :

Example 16 with TableSpaceManager

use of herddb.core.TableSpaceManager in project herddb by diennea.

the class JSQLParserPlanner method buildAlterStatement.

private Statement buildAlterStatement(String defaultTableSpace, Alter alter) throws StatementExecutionException {
    if (alter.getTable() == null) {
        throw new StatementExecutionException("missing table name");
    }
    String tableSpace = alter.getTable().getSchemaName();
    if (tableSpace == null) {
        tableSpace = defaultTableSpace;
    }
    tableSpace = fixMySqlBackTicks(tableSpace);
    List<Column> addColumns = new ArrayList<>();
    List<Column> modifyColumns = new ArrayList<>();
    List<String> dropColumns = new ArrayList<>();
    List<String> dropForeignKeys = new ArrayList<>();
    List<ForeignKeyDef> addForeignKeys = new ArrayList<>();
    String tableName = fixMySqlBackTicks(alter.getTable().getName().toLowerCase());
    if (alter.getAlterExpressions() == null || alter.getAlterExpressions().size() != 1) {
        throw new StatementExecutionException("supported multi-alter operation '" + alter + "'");
    }
    AlterExpression alterExpression = alter.getAlterExpressions().get(0);
    AlterOperation operation = alterExpression.getOperation();
    Boolean changeAutoIncrement = null;
    TableSpaceManager tableSpaceManager = manager.getTableSpaceManager(tableSpace);
    if (tableSpaceManager == null) {
        throw new StatementExecutionException("bad tablespace '" + tableSpace + "'");
    }
    Table table = getTable(defaultTableSpace, alter.getTable());
    switch(operation) {
        case ADD:
            {
                if (alterExpression.getColDataTypeList() != null) {
                    List<AlterExpression.ColumnDataType> cols = alterExpression.getColDataTypeList();
                    for (AlterExpression.ColumnDataType cl : cols) {
                        List<String> columnSpecs = decodeColumnSpecs(cl.getColumnSpecs());
                        int type = sqlDataTypeToColumnType(cl.getColDataType().getDataType(), cl.getColDataType().getArgumentsStringList(), columnSpecs);
                        Column newColumn = Column.column(fixMySqlBackTicks(cl.getColumnName()), type, decodeDefaultValue(cl, type));
                        addColumns.add(newColumn);
                    }
                } else if (alterExpression.getIndex() != null && alterExpression.getIndex() instanceof ForeignKeyIndex) {
                    ForeignKeyDef fkIndex = parseForeignKeyIndex((ForeignKeyIndex) alterExpression.getIndex(), table, tableName, tableSpace);
                    addForeignKeys.add(fkIndex);
                } else {
                    throw new StatementExecutionException("Unrecognized ALTER TABLE ADD ... statement");
                }
            }
            break;
        case DROP:
            if (alterExpression.getColumnName() != null) {
                dropColumns.add(fixMySqlBackTicks(alterExpression.getColumnName()));
            } else if (alterExpression.getConstraintName() != null) {
                dropForeignKeys.add(fixMySqlBackTicks(alterExpression.getConstraintName()));
            } else {
                throw new StatementExecutionException("Unrecognized ALTER TABLE DROP ... statement");
            }
            break;
        case MODIFY:
            {
                List<AlterExpression.ColumnDataType> cols = alterExpression.getColDataTypeList();
                for (AlterExpression.ColumnDataType cl : cols) {
                    String columnName = fixMySqlBackTicks(cl.getColumnName().toLowerCase());
                    Column oldColumn = table.getColumn(columnName);
                    if (oldColumn == null) {
                        throw new StatementExecutionException("bad column " + columnName + " in table " + tableName + " in tablespace '" + tableSpace + "'");
                    }
                    Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(tableName);
                    if (indexes != null) {
                        for (AbstractIndexManager am : indexes.values()) {
                            for (String indexedColumn : am.getColumnNames()) {
                                indexedColumn = fixMySqlBackTicks(indexedColumn);
                                if (indexedColumn.equalsIgnoreCase(oldColumn.name)) {
                                    throw new StatementExecutionException("cannot alter indexed " + columnName + " in table " + tableName + " in tablespace '" + tableSpace + "'," + "index name is " + am.getIndexName());
                                }
                            }
                        }
                    }
                    List<String> columnSpecs = decodeColumnSpecs(cl.getColumnSpecs());
                    int newType = sqlDataTypeToColumnType(cl.getColDataType().getDataType(), cl.getColDataType().getArgumentsStringList(), columnSpecs);
                    if (oldColumn.type != newType) {
                        if (ColumnTypes.isNotNullToNullConversion(oldColumn.type, newType)) {
                        // allow change from "STRING NOT NULL" to "STRING NULL"
                        } else if (ColumnTypes.isNullToNotNullConversion(oldColumn.type, newType)) {
                        // allow change from "STRING NULL" to "STRING NOT NULL"
                        // it will require a check on table at execution time
                        } else {
                            throw new StatementExecutionException("cannot change datatype to " + ColumnTypes.typeToString(newType) + " for column " + columnName + " (" + ColumnTypes.typeToString(oldColumn.type) + ") in table " + tableName + " in tablespace '" + tableSpace + "'");
                        }
                    }
                    if (table.isPrimaryKeyColumn(columnName)) {
                        boolean new_auto_increment = decodeAutoIncrement(columnSpecs);
                        if (new_auto_increment && table.primaryKey.length > 1) {
                            throw new StatementExecutionException("cannot add auto_increment flag to " + cl.getColDataType().getDataType() + " for column " + columnName + " in table " + tableName + " in tablespace '" + tableSpace + "'");
                        }
                        if (table.auto_increment != new_auto_increment) {
                            changeAutoIncrement = new_auto_increment;
                        }
                    }
                    Bytes newDefault = oldColumn.defaultValue;
                    if (containsDefaultClause(cl)) {
                        newDefault = decodeDefaultValue(cl, newType);
                    }
                    Column newColumnDef = Column.column(columnName, newType, oldColumn.serialPosition, newDefault);
                    modifyColumns.add(newColumnDef);
                }
            }
            break;
        case CHANGE:
            {
                String columnName = alterExpression.getColOldName();
                List<AlterExpression.ColumnDataType> cols = alterExpression.getColDataTypeList();
                if (cols.size() != 1) {
                    throw new StatementExecutionException("bad CHANGE column " + columnName + " in table " + tableName + " in tablespace '" + tableSpace + "'");
                }
                AlterExpression.ColumnDataType cl = cols.get(0);
                Column oldColumn = table.getColumn(columnName);
                if (oldColumn == null) {
                    throw new StatementExecutionException("bad column " + columnName + " in table " + tableName + " in tablespace '" + tableSpace + "'");
                }
                Map<String, AbstractIndexManager> indexes = tableSpaceManager.getIndexesOnTable(tableName);
                if (indexes != null) {
                    for (AbstractIndexManager am : indexes.values()) {
                        for (String indexedColumn : am.getColumnNames()) {
                            indexedColumn = fixMySqlBackTicks(indexedColumn);
                            if (indexedColumn.equalsIgnoreCase(oldColumn.name)) {
                                throw new StatementExecutionException("cannot alter indexed " + columnName + " in table " + tableName + " in tablespace '" + tableSpace + "'," + "index name is " + am.getIndexName());
                            }
                        }
                    }
                }
                List<String> columnSpecs = decodeColumnSpecs(cl.getColumnSpecs());
                int newType = sqlDataTypeToColumnType(cl.getColDataType().getDataType(), cl.getColDataType().getArgumentsStringList(), columnSpecs);
                if (oldColumn.type != newType) {
                    throw new StatementExecutionException("cannot change datatype to " + ColumnTypes.typeToString(newType) + " for column " + columnName + " (" + ColumnTypes.typeToString(oldColumn.type) + ") in table " + tableName + " in tablespace '" + tableSpace + "'");
                }
                if (table.isPrimaryKeyColumn(columnName)) {
                    boolean new_auto_increment = decodeAutoIncrement(columnSpecs);
                    if (new_auto_increment && table.primaryKey.length > 1) {
                        throw new StatementExecutionException("cannot add auto_increment flag to " + cl.getColDataType().getDataType() + " for column " + columnName + " in table " + tableName + " in tablespace '" + tableSpace + "'");
                    }
                    if (table.auto_increment != new_auto_increment) {
                        changeAutoIncrement = new_auto_increment;
                    }
                }
                String renameTo = fixMySqlBackTicks(cl.getColumnName().toLowerCase());
                if (renameTo != null) {
                    columnName = renameTo;
                }
                Column newColumnDef = Column.column(columnName, newType, oldColumn.serialPosition, oldColumn.defaultValue);
                modifyColumns.add(newColumnDef);
            }
            break;
        default:
            throw new StatementExecutionException("supported alter operation '" + alter + "'");
    }
    return new AlterTableStatement(addColumns, modifyColumns, dropColumns, changeAutoIncrement, tableName.toLowerCase(), tableSpace, null, dropForeignKeys, addForeignKeys);
}
Also used : AlterOperation(net.sf.jsqlparser.statement.alter.AlterOperation) Table(herddb.model.Table) ShowCreateTableCalculator.calculateShowCreateTable(herddb.sql.functions.ShowCreateTableCalculator.calculateShowCreateTable) CreateTable(net.sf.jsqlparser.statement.create.table.CreateTable) AbstractIndexManager(herddb.core.AbstractIndexManager) AlterTableStatement(herddb.model.commands.AlterTableStatement) ArrayList(java.util.ArrayList) StatementExecutionException(herddb.model.StatementExecutionException) AlterExpression(net.sf.jsqlparser.statement.alter.AlterExpression) Bytes(herddb.utils.Bytes) Column(herddb.model.Column) TableSpaceManager(herddb.core.TableSpaceManager) ItemsList(net.sf.jsqlparser.expression.operators.relational.ItemsList) ArrayList(java.util.ArrayList) ExpressionList(net.sf.jsqlparser.expression.operators.relational.ExpressionList) MultiExpressionList(net.sf.jsqlparser.expression.operators.relational.MultiExpressionList) List(java.util.List) SetOperationList(net.sf.jsqlparser.statement.select.SetOperationList) ForeignKeyDef(herddb.model.ForeignKeyDef) ForeignKeyIndex(net.sf.jsqlparser.statement.create.table.ForeignKeyIndex) Map(java.util.Map)

Example 17 with TableSpaceManager

use of herddb.core.TableSpaceManager in project herddb by diennea.

the class CalcitePlanner method getRootSchema.

private SchemaPlus getRootSchema() {
    if (rootSchema != null) {
        return rootSchema;
    }
    final SchemaPlus _rootSchema = Frameworks.createRootSchema(true);
    for (String tableSpace : manager.getLocalTableSpaces()) {
        TableSpaceManager tableSpaceManager = manager.getTableSpaceManager(tableSpace);
        SchemaPlus schema = _rootSchema.add(tableSpace, new AbstractSchema());
        List<Table> tables = tableSpaceManager.getAllTablesForPlanner();
        for (Table table : tables) {
            AbstractTableManager tableManager = tableSpaceManager.getTableManager(table.name);
            TableImpl tableDef = new TableImpl(tableManager);
            schema.add(table.name, tableDef);
        }
    }
    rootSchema = _rootSchema;
    return _rootSchema;
}
Also used : Table(herddb.model.Table) ShowCreateTableCalculator.calculateShowCreateTable(herddb.sql.functions.ShowCreateTableCalculator.calculateShowCreateTable) SqlStdOperatorTable(org.apache.calcite.sql.fun.SqlStdOperatorTable) RelOptTable(org.apache.calcite.plan.RelOptTable) ProjectableFilterableTable(org.apache.calcite.schema.ProjectableFilterableTable) ScannableTable(org.apache.calcite.schema.ScannableTable) AbstractTable(org.apache.calcite.schema.impl.AbstractTable) ModifiableTable(org.apache.calcite.schema.ModifiableTable) AbstractSchema(org.apache.calcite.schema.impl.AbstractSchema) AbstractTableManager(herddb.core.AbstractTableManager) SchemaPlus(org.apache.calcite.schema.SchemaPlus) TableSpaceManager(herddb.core.TableSpaceManager)

Example 18 with TableSpaceManager

use of herddb.core.TableSpaceManager in project herddb by diennea.

the class ChangeRoleTest method testChangeRoleAndReleaseMemory.

@Test
public void testChangeRoleAndReleaseMemory() throws Exception {
    ServerConfiguration serverconfig_1 = newServerConfigurationWithAutoPort(folder.newFolder().toPath());
    serverconfig_1.set(ServerConfiguration.PROPERTY_NODEID, "server1");
    serverconfig_1.set(ServerConfiguration.PROPERTY_MODE, ServerConfiguration.PROPERTY_MODE_CLUSTER);
    serverconfig_1.set(ServerConfiguration.PROPERTY_ZOOKEEPER_ADDRESS, testEnv.getAddress());
    serverconfig_1.set(ServerConfiguration.PROPERTY_ZOOKEEPER_PATH, testEnv.getPath());
    serverconfig_1.set(ServerConfiguration.PROPERTY_ZOOKEEPER_SESSIONTIMEOUT, testEnv.getTimeout());
    serverconfig_1.set(ServerConfiguration.PROPERTY_ENFORCE_LEADERSHIP, false);
    // disabled
    serverconfig_1.set(ServerConfiguration.PROPERTY_BOOKKEEPER_MAX_IDLE_TIME, 0);
    ServerConfiguration serverconfig_2 = serverconfig_1.copy().set(ServerConfiguration.PROPERTY_NODEID, "server2").set(ServerConfiguration.PROPERTY_BASEDIR, folder.newFolder().toPath().toAbsolutePath());
    try (Server server_1 = new Server(serverconfig_1);
        Server server_2 = new Server(serverconfig_2)) {
        server_1.start();
        server_1.waitForStandaloneBoot();
        server_2.start();
        MemoryManager server2MemoryManager = server_2.getManager().getMemoryManager();
        Table table = Table.builder().name("t1").column("c", ColumnTypes.INTEGER).column("s", ColumnTypes.INTEGER).primaryKey("c").build();
        Index index = Index.builder().onTable(table).type(Index.TYPE_BRIN).column("s", ColumnTypes.STRING).build();
        server_1.getManager().executeStatement(new CreateTableStatement(table), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        server_1.getManager().executeStatement(new CreateIndexStatement(index), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        server_1.getManager().executeUpdate(new InsertStatement(TableSpace.DEFAULT, "t1", RecordSerializer.makeRecord(table, "c", 1, "s", "1")), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        server_1.getManager().executeUpdate(new InsertStatement(TableSpace.DEFAULT, "t1", RecordSerializer.makeRecord(table, "c", 2, "s", "2")), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        server_1.getManager().executeUpdate(new InsertStatement(TableSpace.DEFAULT, "t1", RecordSerializer.makeRecord(table, "c", 3, "s", "3")), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        server_1.getManager().executeUpdate(new InsertStatement(TableSpace.DEFAULT, "t1", RecordSerializer.makeRecord(table, "c", 4, "s", "4")), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        // set forcibly server2 as new follower
        server_1.getManager().executeStatement(new AlterTableSpaceStatement(TableSpace.DEFAULT, new HashSet<>(Arrays.asList("server1", "server2")), "server1", 1, 0), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        assertEquals(0, server2MemoryManager.getDataPageReplacementPolicy().size());
        assertEquals(0, server2MemoryManager.getIndexPageReplacementPolicy().size());
        assertEquals(0, server2MemoryManager.getPKPageReplacementPolicy().size());
        server_2.waitForTableSpaceBoot(TableSpace.DEFAULT, false);
        assertEquals(1, server2MemoryManager.getDataPageReplacementPolicy().size());
        assertEquals(1, server2MemoryManager.getIndexPageReplacementPolicy().size());
        assertEquals(1, server2MemoryManager.getPKPageReplacementPolicy().size());
        // stop tablespace on server2
        server_1.getManager().executeStatement(new AlterTableSpaceStatement(TableSpace.DEFAULT, new HashSet<>(Arrays.asList("server1")), "server1", 1, 0), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        server_2.getManager().triggerActivator(ActivatorRunRequest.FULL);
        // wait for tablespace manager to be deallocated
        herddb.utils.TestUtils.waitForCondition(() -> {
            TableSpaceManager tableSpaceManager = server_2.getManager().getTableSpaceManager(TableSpace.DEFAULT);
            return tableSpaceManager == null;
        }, herddb.utils.TestUtils.NOOP, 100);
        // memory must have been totally released
        assertEquals(0, server2MemoryManager.getDataPageReplacementPolicy().size());
        assertEquals(0, server2MemoryManager.getIndexPageReplacementPolicy().size());
        assertEquals(0, server2MemoryManager.getPKPageReplacementPolicy().size());
        // start tablespace on server2, as let it become leader
        server_1.getManager().executeStatement(new AlterTableSpaceStatement(TableSpace.DEFAULT, new HashSet<>(Arrays.asList("server1", "server2")), "server2", 1, 0), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        server_2.waitForTableSpaceBoot(TableSpace.DEFAULT, true);
        assertTrue("unexpected value " + server2MemoryManager.getDataPageReplacementPolicy().size(), server2MemoryManager.getDataPageReplacementPolicy().size() >= 1);
        assertEquals(1, server2MemoryManager.getIndexPageReplacementPolicy().size());
        assertEquals(1, server2MemoryManager.getPKPageReplacementPolicy().size());
        server_1.getManager().executeStatement(new AlterTableSpaceStatement(TableSpace.DEFAULT, new HashSet<>(Arrays.asList("server1")), "server1", 1, 0), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        // wait for tablespace manager to be deallocated
        herddb.utils.TestUtils.waitForCondition(() -> {
            TableSpaceManager tableSpaceManager = server_2.getManager().getTableSpaceManager(TableSpace.DEFAULT);
            return tableSpaceManager == null;
        }, herddb.utils.TestUtils.NOOP, 100);
        // memory must have been totally released again
        assertEquals(0, server2MemoryManager.getDataPageReplacementPolicy().size());
        assertEquals(0, server2MemoryManager.getIndexPageReplacementPolicy().size());
        assertEquals(0, server2MemoryManager.getPKPageReplacementPolicy().size());
    }
}
Also used : AlterTableSpaceStatement(herddb.model.commands.AlterTableSpaceStatement) Table(herddb.model.Table) Server(herddb.server.Server) ServerConfiguration(herddb.server.ServerConfiguration) CreateTableStatement(herddb.model.commands.CreateTableStatement) TableSpaceManager(herddb.core.TableSpaceManager) CreateIndexStatement(herddb.model.commands.CreateIndexStatement) Index(herddb.model.Index) MemoryManager(herddb.core.MemoryManager) InsertStatement(herddb.model.commands.InsertStatement) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 19 with TableSpaceManager

use of herddb.core.TableSpaceManager in project herddb by diennea.

the class RetryOnLeaderChangedTest method testSwitchLeaderAndAuthTimeout.

@Test
public void testSwitchLeaderAndAuthTimeout() throws Exception {
    TestStatsProvider statsProvider = new TestStatsProvider();
    ServerConfiguration serverconfig_1 = newServerConfigurationWithAutoPort(folder.newFolder().toPath());
    serverconfig_1.set(ServerConfiguration.PROPERTY_NODEID, "server1");
    serverconfig_1.set(ServerConfiguration.PROPERTY_MODE, ServerConfiguration.PROPERTY_MODE_CLUSTER);
    serverconfig_1.set(ServerConfiguration.PROPERTY_ZOOKEEPER_ADDRESS, testEnv.getAddress());
    serverconfig_1.set(ServerConfiguration.PROPERTY_ZOOKEEPER_PATH, testEnv.getPath());
    serverconfig_1.set(ServerConfiguration.PROPERTY_ZOOKEEPER_SESSIONTIMEOUT, testEnv.getTimeout());
    ServerConfiguration serverconfig_2 = serverconfig_1.copy().set(ServerConfiguration.PROPERTY_NODEID, "server2").set(ServerConfiguration.PROPERTY_BASEDIR, folder.newFolder().toPath().toAbsolutePath());
    final AtomicBoolean suspendProcessing = new AtomicBoolean(false);
    try (Server server_1 = new Server(serverconfig_1)) {
        server_1.start();
        server_1.waitForStandaloneBoot();
        try (Server server_2 = new Server(serverconfig_2) {

            @Override
            protected ServerSideConnectionPeer buildPeer(Channel channel) {
                return new ServerSideConnectionPeer(channel, this) {

                    @Override
                    public void requestReceived(Pdu message, Channel channel) {
                        if (suspendProcessing.get()) {
                            LOG.log(Level.INFO, "dropping message type " + message.type + " id " + message.messageId);
                            message.close();
                            return;
                        }
                        super.requestReceived(message, channel);
                    }
                };
            }
        }) {
            server_2.start();
            TestUtils.execute(server_1.getManager(), "CREATE TABLESPACE 'ttt','leader:" + server_2.getNodeId() + "','expectedreplicacount:2'", Collections.emptyList());
            // wait for server_2 to wake up
            for (int i = 0; i < 40; i++) {
                TableSpaceManager tableSpaceManager2 = server_2.getManager().getTableSpaceManager("ttt");
                if (tableSpaceManager2 != null && tableSpaceManager2.isLeader()) {
                    break;
                }
                Thread.sleep(500);
            }
            assertTrue(server_2.getManager().getTableSpaceManager("ttt") != null && server_2.getManager().getTableSpaceManager("ttt").isLeader());
            // wait for server_1 to announce as follower
            waitClusterStatus(server_1.getManager(), server_1.getNodeId(), "follower");
            ClientConfiguration clientConfiguration = new ClientConfiguration();
            clientConfiguration.set(ClientConfiguration.PROPERTY_MODE, ClientConfiguration.PROPERTY_MODE_CLUSTER);
            clientConfiguration.set(ClientConfiguration.PROPERTY_ZOOKEEPER_ADDRESS, testEnv.getAddress());
            clientConfiguration.set(ClientConfiguration.PROPERTY_ZOOKEEPER_PATH, testEnv.getPath());
            clientConfiguration.set(ClientConfiguration.PROPERTY_ZOOKEEPER_SESSIONTIMEOUT, testEnv.getTimeout());
            clientConfiguration.set(ClientConfiguration.PROPERTY_MAX_CONNECTIONS_PER_SERVER, 2);
            clientConfiguration.set(ClientConfiguration.PROPERTY_TIMEOUT, 2000);
            StatsLogger logger = statsProvider.getStatsLogger("ds");
            try (HDBClient client1 = new HDBClient(clientConfiguration, logger) {

                @Override
                public HDBConnection openConnection() {
                    HDBConnection con = new VisibleRouteHDBConnection(this);
                    registerConnection(con);
                    return con;
                }
            }) {
                try (VisibleRouteHDBConnection connection = (VisibleRouteHDBConnection) client1.openConnection()) {
                    // create table and insert data
                    connection.executeUpdate(TableSpace.DEFAULT, "CREATE TABLE ttt.t1(k1 int primary key, n1 int)", TransactionContext.NOTRANSACTION_ID, false, false, Collections.emptyList());
                    connection.executeUpdate(TableSpace.DEFAULT, "INSERT INTO ttt.t1(k1,n1) values(1,1)", TransactionContext.NOTRANSACTION_ID, false, false, Collections.emptyList());
                    assertEquals("server2", connection.getRouteToTableSpace("ttt").getNodeId());
                    // change leader
                    switchLeader(server_1.getNodeId(), server_2.getNodeId(), server_1.getManager());
                    try (VisibleRouteHDBConnection connection2 = (VisibleRouteHDBConnection) client1.openConnection()) {
                        // connection routing still point to old leader (now follower)
                        assertEquals("server2", connection2.getRouteToTableSpace("ttt").getNodeId());
                        // suspend server_2 authentication
                        suspendProcessing.set(true);
                        // attempt an insert with old routing. Suspended autentication generates a timeout
                        // and routing will be reevaluated
                        assertEquals(1, connection2.executeUpdate(TableSpace.DEFAULT, "INSERT INTO ttt.t1(k1,n1) values(2,2)", TransactionContext.NOTRANSACTION_ID, false, false, Collections.emptyList()).updateCount);
                        // right routing to current master
                        assertEquals("server1", connection2.getRouteToTableSpace("ttt").getNodeId());
                        suspendProcessing.set(false);
                    }
                }
            }
        }
    }
}
Also used : TestStatsProvider(org.apache.bookkeeper.test.TestStatsProvider) Pdu(herddb.proto.Pdu) ServerSideConnectionPeer(herddb.server.ServerSideConnectionPeer) StatsLogger(org.apache.bookkeeper.stats.StatsLogger) Server(herddb.server.Server) ServerConfiguration(herddb.server.ServerConfiguration) Channel(herddb.network.Channel) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HDBConnection(herddb.client.HDBConnection) HDBClient(herddb.client.HDBClient) TableSpaceManager(herddb.core.TableSpaceManager) ClientConfiguration(herddb.client.ClientConfiguration) Test(org.junit.Test)

Example 20 with TableSpaceManager

use of herddb.core.TableSpaceManager in project herddb by diennea.

the class LedgerClosedTest method testLedgerClosedError.

@Test
public void testLedgerClosedError() throws Exception {
    ServerConfiguration serverconfig_1 = newServerConfigurationWithAutoPort(folder.newFolder().toPath());
    serverconfig_1.set(ServerConfiguration.PROPERTY_NODEID, "server1");
    serverconfig_1.set(ServerConfiguration.PROPERTY_MODE, ServerConfiguration.PROPERTY_MODE_CLUSTER);
    serverconfig_1.set(ServerConfiguration.PROPERTY_ZOOKEEPER_ADDRESS, testEnv.getAddress());
    serverconfig_1.set(ServerConfiguration.PROPERTY_ZOOKEEPER_PATH, testEnv.getPath());
    serverconfig_1.set(ServerConfiguration.PROPERTY_ZOOKEEPER_SESSIONTIMEOUT, testEnv.getTimeout());
    serverconfig_1.set(ServerConfiguration.PROPERTY_ENFORCE_LEADERSHIP, false);
    try (Server server = new Server(serverconfig_1)) {
        server.start();
        server.waitForStandaloneBoot();
        Table table = Table.builder().name("t1").column("c", ColumnTypes.INTEGER).primaryKey("c").build();
        server.getManager().executeStatement(new CreateTableStatement(table), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        server.getManager().executeUpdate(new InsertStatement(TableSpace.DEFAULT, "t1", RecordSerializer.makeRecord(table, "c", 1)), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        server.getManager().executeUpdate(new InsertStatement(TableSpace.DEFAULT, "t1", RecordSerializer.makeRecord(table, "c", 2)), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        server.getManager().executeUpdate(new InsertStatement(TableSpace.DEFAULT, "t1", RecordSerializer.makeRecord(table, "c", 3)), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        TableSpaceManager tableSpaceManager = server.getManager().getTableSpaceManager(TableSpace.DEFAULT);
        BookkeeperCommitLog log = (BookkeeperCommitLog) tableSpaceManager.getLog();
        long ledgerId = log.getLastSequenceNumber().ledgerId;
        assertTrue(ledgerId >= 0);
        // we do not want auto-recovery in ase of log failures
        server.getManager().setActivatorPauseStatus(true);
        assertEquals(ledgerId, log.getWriter().getOut().getId());
        // force close of the LedgerHandle
        // this may happen internally in BK in case of internal errors
        log.getWriter().getOut().close();
        // we should recover
        server.getManager().executeUpdate(new InsertStatement(TableSpace.DEFAULT, "t1", RecordSerializer.makeRecord(table, "c", 4)), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        assertNotEquals(ledgerId, log.getWriter().getOut().getId());
        ServerConfiguration serverconfig_2 = newServerConfigurationWithAutoPort(folder.newFolder().toPath());
        serverconfig_2.set(ServerConfiguration.PROPERTY_NODEID, "server2");
        serverconfig_2.set(ServerConfiguration.PROPERTY_MODE, ServerConfiguration.PROPERTY_MODE_CLUSTER);
        serverconfig_2.set(ServerConfiguration.PROPERTY_ZOOKEEPER_ADDRESS, testEnv.getAddress());
        serverconfig_2.set(ServerConfiguration.PROPERTY_ZOOKEEPER_PATH, testEnv.getPath());
        serverconfig_2.set(ServerConfiguration.PROPERTY_ZOOKEEPER_SESSIONTIMEOUT, testEnv.getTimeout());
        serverconfig_2.set(ServerConfiguration.PROPERTY_ENFORCE_LEADERSHIP, false);
        // set server2 as new leader
        server.getManager().executeStatement(new AlterTableSpaceStatement(TableSpace.DEFAULT, new HashSet<>(Arrays.asList("server1", "server2")), "server2", 1, 0), StatementEvaluationContext.DEFAULT_EVALUATION_CONTEXT(), TransactionContext.NO_TRANSACTION);
        // stop server1
        server.close();
        // boot a new leader, it will recover from bookkeeper
        try (Server server2 = new Server(serverconfig_2)) {
            server2.start();
            // wait for the boot of the new leader
            server2.waitForTableSpaceBoot(TableSpace.DEFAULT, true);
            // the server must have all of the data
            try (DataScanner scan = scan(server2.getManager(), "SELECT * FROM t1", Collections.emptyList())) {
                List<DataAccessor> consume = scan.consume();
                assertEquals(4, consume.size());
            }
        }
    }
}
Also used : AlterTableSpaceStatement(herddb.model.commands.AlterTableSpaceStatement) Table(herddb.model.Table) Server(herddb.server.Server) DataAccessor(herddb.utils.DataAccessor) ServerConfiguration(herddb.server.ServerConfiguration) CreateTableStatement(herddb.model.commands.CreateTableStatement) InsertStatement(herddb.model.commands.InsertStatement) DataScanner(herddb.model.DataScanner) TableSpaceManager(herddb.core.TableSpaceManager) BookkeeperCommitLog(herddb.cluster.BookkeeperCommitLog) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

TableSpaceManager (herddb.core.TableSpaceManager)46 Table (herddb.model.Table)33 Test (org.junit.Test)23 InsertStatement (herddb.model.commands.InsertStatement)22 StatementExecutionException (herddb.model.StatementExecutionException)20 CreateTableStatement (herddb.model.commands.CreateTableStatement)20 AbstractTableManager (herddb.core.AbstractTableManager)16 Server (herddb.server.Server)15 ServerConfiguration (herddb.server.ServerConfiguration)15 DataScanner (herddb.model.DataScanner)13 BookkeeperCommitLog (herddb.cluster.BookkeeperCommitLog)11 AlterTableSpaceStatement (herddb.model.commands.AlterTableSpaceStatement)11 HashSet (java.util.HashSet)11 CreateTable (net.sf.jsqlparser.statement.create.table.CreateTable)11 CompiledSQLExpression (herddb.sql.expressions.CompiledSQLExpression)9 ArrayList (java.util.ArrayList)9 AlterExpression (net.sf.jsqlparser.statement.alter.AlterExpression)9 ClientConfiguration (herddb.client.ClientConfiguration)8 HDBClient (herddb.client.HDBClient)8 HDBConnection (herddb.client.HDBConnection)8