Search in sources :

Example 41 with HDBConnection

use of herddb.client.HDBConnection in project herddb by diennea.

the class TableSpaceManager method downloadTableSpaceData.

private void downloadTableSpaceData() throws MetadataStorageManagerException, DataStorageManagerException, LogNotAvailableException {
    TableSpace tableSpaceData = metadataStorageManager.describeTableSpace(tableSpaceName);
    String leaderId = tableSpaceData.leaderId;
    if (this.nodeId.equals(leaderId)) {
        throw new DataStorageManagerException("cannot download data of tableSpace " + tableSpaceName + " from myself");
    }
    Optional<NodeMetadata> leaderAddress = metadataStorageManager.listNodes().stream().filter(n -> n.nodeId.equals(leaderId)).findAny();
    if (!leaderAddress.isPresent()) {
        throw new DataStorageManagerException("cannot download data of tableSpace " + tableSpaceName + " from leader " + leaderId + ", no metadata found");
    }
    // ensure we do not have any data on disk and in memory
    actualLogSequenceNumber = LogSequenceNumber.START_OF_TIME;
    newTransactionId.set(0);
    LOGGER.log(Level.INFO, "tablespace " + tableSpaceName + " at downloadTableSpaceData " + tables + ", " + indexes + ", " + transactions);
    for (AbstractTableManager manager : tables.values()) {
        // and all indexes
        if (!manager.isSystemTable()) {
            manager.dropTableData();
        }
        manager.close();
    }
    tables.clear();
    // this map should be empty
    for (AbstractIndexManager manager : indexes.values()) {
        manager.dropIndexData();
        manager.close();
    }
    indexes.clear();
    transactions.clear();
    dataStorageManager.eraseTablespaceData(tableSpaceUUID);
    NodeMetadata nodeData = leaderAddress.get();
    ClientConfiguration clientConfiguration = new ClientConfiguration(dbmanager.getTmpDirectory());
    clientConfiguration.set(ClientConfiguration.PROPERTY_CLIENT_USERNAME, dbmanager.getServerToServerUsername());
    clientConfiguration.set(ClientConfiguration.PROPERTY_CLIENT_PASSWORD, dbmanager.getServerToServerPassword());
    // always use network, we want to run tests with this case
    clientConfiguration.set(ClientConfiguration.PROPERTY_CLIENT_CONNECT_LOCALVM_SERVER, false);
    try (HDBClient client = new HDBClient(clientConfiguration)) {
        client.setClientSideMetadataProvider(new ClientSideMetadataProvider() {

            @Override
            public String getTableSpaceLeader(String tableSpace) throws ClientSideMetadataProviderException {
                return leaderId;
            }

            @Override
            public ServerHostData getServerHostData(String nodeId) throws ClientSideMetadataProviderException {
                return new ServerHostData(nodeData.host, nodeData.port, "?", nodeData.ssl, Collections.emptyMap());
            }
        });
        try (HDBConnection con = client.openConnection()) {
            ReplicaFullTableDataDumpReceiver receiver = new ReplicaFullTableDataDumpReceiver(this);
            int fetchSize = 10000;
            con.dumpTableSpace(tableSpaceName, receiver, fetchSize, false);
            receiver.getLatch().get(1, TimeUnit.HOURS);
            this.actualLogSequenceNumber = receiver.logSequenceNumber;
            LOGGER.log(Level.INFO, tableSpaceName + " After download local actualLogSequenceNumber is " + actualLogSequenceNumber);
        } catch (ClientSideMetadataProviderException | HDBException | InterruptedException | ExecutionException | TimeoutException internalError) {
            LOGGER.log(Level.SEVERE, tableSpaceName + " error downloading snapshot", internalError);
            throw new DataStorageManagerException(internalError);
        }
    }
}
Also used : HDBException(herddb.client.HDBException) SystablesTableManager(herddb.core.system.SystablesTableManager) CommitTransactionStatement(herddb.model.commands.CommitTransactionStatement) TableCheckpoint(herddb.core.AbstractTableManager.TableCheckpoint) Table(herddb.model.Table) ClientConfiguration(herddb.client.ClientConfiguration) SyslogstatusManager(herddb.core.system.SyslogstatusManager) OpStatsLogger(org.apache.bookkeeper.stats.OpStatsLogger) IndexAlreadyExistsException(herddb.model.IndexAlreadyExistsException) Map(java.util.Map) DDLStatementExecutionResult(herddb.model.DDLStatementExecutionResult) LogNotAvailableException(herddb.log.LogNotAvailableException) PduCodec(herddb.proto.PduCodec) CommitLogResult(herddb.log.CommitLogResult) ClientSideMetadataProviderException(herddb.client.ClientSideMetadataProviderException) LogSequenceNumber(herddb.log.LogSequenceNumber) Set(java.util.Set) ScanStatement(herddb.model.commands.ScanStatement) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) HDBClient(herddb.client.HDBClient) TranslatedQuery(herddb.sql.TranslatedQuery) StatsLogger(org.apache.bookkeeper.stats.StatsLogger) TableDataChecksum(herddb.data.consistency.TableDataChecksum) DropTableStatement(herddb.model.commands.DropTableStatement) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Bytes(herddb.utils.Bytes) SysdualTableManager(herddb.core.system.SysdualTableManager) LogEntry(herddb.log.LogEntry) SysnodesTableManager(herddb.core.system.SysnodesTableManager) ArrayList(java.util.ArrayList) CreateIndexStatement(herddb.model.commands.CreateIndexStatement) TableSpaceDoesNotExistException(herddb.model.TableSpaceDoesNotExistException) TransactionContext(herddb.model.TransactionContext) Transaction(herddb.model.Transaction) BRINIndexManager(herddb.index.brin.BRINIndexManager) SystablestatsTableManager(herddb.core.system.SystablestatsTableManager) BiConsumer(java.util.function.BiConsumer) CommitLogListener(herddb.log.CommitLogListener) ForeignKeyDef(herddb.model.ForeignKeyDef) IndexDoesNotExistException(herddb.model.IndexDoesNotExistException) TableSpaceManagerStats(herddb.core.stats.TableSpaceManagerStats) LogEntryType(herddb.log.LogEntryType) LogEntryFactory(herddb.log.LogEntryFactory) IOException(java.io.IOException) DataStorageManager(herddb.storage.DataStorageManager) DropIndexStatement(herddb.model.commands.DropIndexStatement) ColumnTypes(herddb.model.ColumnTypes) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) Column(herddb.model.Column) KeyValue(herddb.utils.KeyValue) FullRecoveryNeededException(herddb.log.FullRecoveryNeededException) StampedLock(java.util.concurrent.locks.StampedLock) ServerHostData(herddb.network.ServerHostData) TableAlreadyExistsException(herddb.model.TableAlreadyExistsException) RollbackTransactionStatement(herddb.model.commands.RollbackTransactionStatement) CreateTableStatement(herddb.model.commands.CreateTableStatement) TimeoutException(java.util.concurrent.TimeoutException) JMXUtils(herddb.jmx.JMXUtils) TransactionResult(herddb.model.TransactionResult) MetadataStorageManager(herddb.metadata.MetadataStorageManager) Channel(herddb.network.Channel) ServerConfiguration(herddb.server.ServerConfiguration) Futures(herddb.utils.Futures) DataStorageManagerException(herddb.storage.DataStorageManagerException) Index(herddb.model.Index) TableDoesNotExistException(herddb.model.TableDoesNotExistException) AlterTableStatement(herddb.model.commands.AlterTableStatement) SysindexcolumnsTableManager(herddb.core.system.SysindexcolumnsTableManager) DataScanner(herddb.model.DataScanner) DDLException(herddb.model.DDLException) StatementExecutionException(herddb.model.StatementExecutionException) Collection(java.util.Collection) SysstatementsTableManager(herddb.core.system.SysstatementsTableManager) BeginTransactionStatement(herddb.model.commands.BeginTransactionStatement) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CompletionException(java.util.concurrent.CompletionException) TableAwareStatement(herddb.model.TableAwareStatement) Logger(java.util.logging.Logger) EOFException(java.io.EOFException) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) HDBConnection(herddb.client.HDBConnection) List(java.util.List) FullTableScanConsumer(herddb.storage.FullTableScanConsumer) SystransactionsTableManager(herddb.core.system.SystransactionsTableManager) NodeMetadata(herddb.model.NodeMetadata) Entry(java.util.Map.Entry) Optional(java.util.Optional) TableSpace(herddb.model.TableSpace) SysconfigTableManager(herddb.core.system.SysconfigTableManager) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) SysindexesTableManager(herddb.core.system.SysindexesTableManager) Statement(herddb.model.Statement) MetadataStorageManagerException(herddb.metadata.MetadataStorageManagerException) DataScannerException(herddb.model.DataScannerException) SystablespacesTableManager(herddb.core.system.SystablespacesTableManager) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Pdu(herddb.proto.Pdu) Level(java.util.logging.Level) HashSet(java.util.HashSet) SysclientsTableManager(herddb.core.system.SysclientsTableManager) TableChecksum(herddb.data.consistency.TableChecksum) ExecutorService(java.util.concurrent.ExecutorService) DumpedLogEntry(herddb.backup.DumpedLogEntry) SysforeignkeysTableManager(herddb.core.system.SysforeignkeysTableManager) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) StatementExecutionResult(herddb.model.StatementExecutionResult) TimeUnit(java.util.concurrent.TimeUnit) CommitLog(herddb.log.CommitLog) ClientSideMetadataProvider(herddb.client.ClientSideMetadataProvider) ConcurrentSkipListSet(java.util.concurrent.ConcurrentSkipListSet) SystablespacereplicastateTableManager(herddb.core.system.SystablespacereplicastateTableManager) SQLPlannedOperationStatement(herddb.model.commands.SQLPlannedOperationStatement) StatementEvaluationContext(herddb.model.StatementEvaluationContext) SyscolumnsTableManager(herddb.core.system.SyscolumnsTableManager) Comparator(java.util.Comparator) Collections(java.util.Collections) TableManagerStats(herddb.core.stats.TableManagerStats) MemoryHashIndexManager(herddb.index.MemoryHashIndexManager) SystemProperties(herddb.utils.SystemProperties) TableSpace(herddb.model.TableSpace) DataStorageManagerException(herddb.storage.DataStorageManagerException) ClientSideMetadataProviderException(herddb.client.ClientSideMetadataProviderException) ClientSideMetadataProvider(herddb.client.ClientSideMetadataProvider) ServerHostData(herddb.network.ServerHostData) TableCheckpoint(herddb.core.AbstractTableManager.TableCheckpoint) HDBException(herddb.client.HDBException) NodeMetadata(herddb.model.NodeMetadata) HDBConnection(herddb.client.HDBConnection) HDBClient(herddb.client.HDBClient) ExecutionException(java.util.concurrent.ExecutionException) StatementExecutionException(herddb.model.StatementExecutionException) ClientConfiguration(herddb.client.ClientConfiguration) TimeoutException(java.util.concurrent.TimeoutException)

Example 42 with HDBConnection

use of herddb.client.HDBConnection in project herddb by diennea.

the class BaseBench method backupRestore.

public void backupRestore(int batchSize, ProgressListener pl) throws Exception {
    if (pl == null) {
        pl = new ProgressListener() {
        };
    }
    System.out.println("BACKUP PHASE");
    File backupFile = folder.newFile("test.backup");
    try {
        try (HDBConnection connection = client.openConnection();
            FileOutputStream oo = new FileOutputStream(backupFile);
            GZIPOutputStream zout = new GZIPOutputStream(oo)) {
            BackupUtils.dumpTableSpace(TableSpace.DEFAULT, batchSize, connection, zout, pl);
        }
        System.out.println("RESTORE PHASE on a " + backupFile.length() + " bytes file");
        try (HDBConnection connection = client.openConnection();
            FileInputStream oo = new FileInputStream(backupFile);
            GZIPInputStream zin = new GZIPInputStream(oo)) {
            BackupUtils.restoreTableSpace("newschema", server.getNodeId(), connection, zin, pl);
        }
    } finally {
        backupFile.delete();
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) HDBConnection(herddb.client.HDBConnection) ProgressListener(herddb.backup.ProgressListener) GZIPOutputStream(java.util.zip.GZIPOutputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 43 with HDBConnection

use of herddb.client.HDBConnection in project herddb by diennea.

the class SimpleClientScanTest method test.

@Test
public void test() throws Exception {
    try (Server server = new Server(newServerConfigurationWithAutoPort(folder.newFolder().toPath()))) {
        server.start();
        server.waitForStandaloneBoot();
        try (HDBClient client = new HDBClient(new ClientConfiguration(folder.newFolder().toPath()));
            HDBConnection connection = client.openConnection()) {
            client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));
            long resultCreateTable = connection.executeUpdate(TableSpace.DEFAULT, "CREATE TABLE mytable (id string primary key, n1 long, n2 integer)", 0, false, true, Collections.emptyList()).updateCount;
            Assert.assertEquals(1, resultCreateTable);
            for (int i = 0; i < 99; i++) {
                Assert.assertEquals(1, connection.executeUpdate(TableSpace.DEFAULT, "INSERT INTO mytable (id,n1,n2) values(?,?,?)", 0, false, true, Arrays.asList("test_" + i, 1, 2)).updateCount);
            }
            assertEquals(99, connection.executeScan(TableSpace.DEFAULT, "SELECT * FROM mytable", true, Collections.emptyList(), 0, 0, 10, true).consume().size());
            // maxRows
            assertEquals(17, connection.executeScan(TableSpace.DEFAULT, "SELECT * FROM mytable", true, Collections.emptyList(), 0, 17, 10, true).consume().size());
            // empty result set
            assertEquals(0, connection.executeScan(TableSpace.DEFAULT, "SELECT * FROM mytable WHERE id='none'", true, Collections.emptyList(), 0, 0, 10, true).consume().size());
            // single fetch result test
            assertEquals(1, connection.executeScan(TableSpace.DEFAULT, "SELECT * FROM mytable WHERE id='test_1'", true, Collections.emptyList(), 0, 0, 10, true).consume().size());
            // agregation in transaction, this is trickier than what you can think
            long tx = connection.beginTransaction(TableSpace.DEFAULT);
            assertEquals(1, connection.executeScan(TableSpace.DEFAULT, "SELECT count(*) FROM mytable WHERE id='test_1'", true, Collections.emptyList(), tx, 0, 10, true).consume().size());
            connection.rollbackTransaction(TableSpace.DEFAULT, tx);
            assertEquals(0, connection.executeScan(TableSpace.DEFAULT, "SELECT * FROM mytable WHERE id=?", true, Arrays.<Object>asList((Object) null), 0, 0, 10, true).consume().size());
        }
    }
}
Also used : HDBConnection(herddb.client.HDBConnection) HDBClient(herddb.client.HDBClient) ClientConfiguration(herddb.client.ClientConfiguration) Test(org.junit.Test)

Example 44 with HDBConnection

use of herddb.client.HDBConnection in project herddb by diennea.

the class SimpleClientScanTest method scanMultiChunk.

@Test
public void scanMultiChunk() throws Exception {
    try (Server server = new Server(newServerConfigurationWithAutoPort(folder.newFolder().toPath()))) {
        server.start();
        server.waitForStandaloneBoot();
        ClientConfiguration clientConfiguration = new ClientConfiguration(folder.newFolder().toPath());
        // more than one socket
        clientConfiguration.set(ClientConfiguration.PROPERTY_MAX_CONNECTIONS_PER_SERVER, 10);
        try (HDBClient client = new HDBClient(clientConfiguration);
            HDBConnection connection = client.openConnection()) {
            client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));
            long resultCreateTable = connection.executeUpdate(TableSpace.DEFAULT, "CREATE TABLE mytable (id string primary key, n1 long, n2 integer)", 0, false, true, Collections.emptyList()).updateCount;
            Assert.assertEquals(1, resultCreateTable);
            for (int i = 0; i < 99; i++) {
                Assert.assertEquals(1, connection.executeUpdate(TableSpace.DEFAULT, "INSERT INTO mytable (id,n1,n2) values(?,?,?)", 0, false, true, Arrays.asList("test_" + i, 1, 2)).updateCount);
            }
            checkUseOnlyOneSocket(connection, server);
            checkNoScannersOnTheServer(server);
            checkCloseScannerOnConnectionClose(client, connection, server, true);
            checkNoScannersOnTheServer(server);
            checkCloseScannerOnConnectionClose(client, connection, server, false);
            checkNoScannersOnTheServer(server);
            checkCloseResultSetNotFullyScanned(connection, server, true);
            checkNoScannersOnTheServer(server);
            checkCloseResultSetNotFullyScanned(connection, server, false);
            checkNoScannersOnTheServer(server);
            checkCloseResultSetNotFullyScannedWithTransactionAndAggregation(connection, server, true);
            checkNoScannersOnTheServer(server);
            checkCloseResultSetNotFullyScannedWithTransactionAndAggregation(connection, server, false);
            checkNoScannersOnTheServer(server);
        }
        checkNoScannersOnTheServer(server);
    }
}
Also used : HDBConnection(herddb.client.HDBConnection) HDBClient(herddb.client.HDBClient) ClientConfiguration(herddb.client.ClientConfiguration) Test(org.junit.Test)

Example 45 with HDBConnection

use of herddb.client.HDBConnection in project herddb by diennea.

the class JmxTest method test.

@Test
public void test() throws Exception {
    try (Server server = new Server(newServerConfigurationWithAutoPort(folder.newFolder().toPath()))) {
        server.start();
        server.waitForStandaloneBoot();
        try (HDBClient client = new HDBClient(new ClientConfiguration(folder.newFolder().toPath()));
            HDBConnection connection = client.openConnection()) {
            client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));
            long resultCreateTable = connection.executeUpdate(TableSpace.DEFAULT, "CREATE TABLE mytable (id string primary key, n1 long, n2 integer)", 0, false, true, Collections.emptyList()).updateCount;
            Assert.assertEquals(1, resultCreateTable);
            {
                final ObjectName statusBeanName = new ObjectName("herddb.server:type=Table,Name=" + TableSpace.DEFAULT + ".mytable");
                Object attribute = ManagementFactory.getPlatformMBeanServer().getAttribute(statusBeanName, "Tablesize");
                assertEquals(0L, attribute);
            }
            {
                final ObjectName statusBeanName = new ObjectName("herddb.server:type=TableSpace,Name=" + TableSpace.DEFAULT);
                Object attribute = ManagementFactory.getPlatformMBeanServer().getAttribute(statusBeanName, "Tablesize");
                assertEquals(0L, attribute);
            }
        }
    }
}
Also used : HDBConnection(herddb.client.HDBConnection) HDBClient(herddb.client.HDBClient) ClientConfiguration(herddb.client.ClientConfiguration) ObjectName(javax.management.ObjectName) Test(org.junit.Test)

Aggregations

HDBConnection (herddb.client.HDBConnection)48 HDBClient (herddb.client.HDBClient)45 ClientConfiguration (herddb.client.ClientConfiguration)44 Test (org.junit.Test)38 Table (herddb.model.Table)20 CreateTableStatement (herddb.model.commands.CreateTableStatement)20 InsertStatement (herddb.model.commands.InsertStatement)19 ProgressListener (herddb.backup.ProgressListener)15 Server (herddb.server.Server)14 ServerConfiguration (herddb.server.ServerConfiguration)14 ScanResultSet (herddb.client.ScanResultSet)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 ByteArrayOutputStream (java.io.ByteArrayOutputStream)12 Index (herddb.model.Index)9 CreateIndexStatement (herddb.model.commands.CreateIndexStatement)9 TableSpaceManager (herddb.core.TableSpaceManager)8 HashSet (java.util.HashSet)8 Map (java.util.Map)8 RawString (herddb.utils.RawString)7 Path (java.nio.file.Path)7