diff --git a/migrator/pom.xml b/migrator/pom.xml
index 3a4edb3393..e0141d2d0d 100644
--- a/migrator/pom.xml
+++ b/migrator/pom.xml
@@ -81,6 +81,21 @@
spring-boot-starter-test
test
+
+ org.testcontainers
+ postgresql
+ test
+
+
+ org.testcontainers
+ junit-jupiter
+ test
+
+
+ software.xdev
+ testcontainers-junit4-mock
+ test
+
diff --git a/migrator/src/main/java/org/thingsboard/migrator/MigrationService.java b/migrator/src/main/java/org/thingsboard/migrator/MigrationService.java
index 96b65b3698..c8ef7002fd 100644
--- a/migrator/src/main/java/org/thingsboard/migrator/MigrationService.java
+++ b/migrator/src/main/java/org/thingsboard/migrator/MigrationService.java
@@ -31,7 +31,7 @@ public abstract class MigrationService {
@Value("${stats_print_interval}")
private int statsPrintInterval;
@Value("${parallelism_level}")
- private int parallelismLevel;
+ protected int parallelismLevel;
protected final ConcurrentMap total = new ConcurrentHashMap<>();
protected final ConcurrentMap processed = new ConcurrentHashMap<>();
@@ -57,7 +57,13 @@ public abstract class MigrationService {
public final void run() throws Exception {
// TODO: more logs on tenant
log.info("Starting...");
- start();
+ try {
+ start();
+ } catch (Throwable e) {
+ // Idle non-daemon workers would otherwise keep the JVM running
+ executor.shutdownNow();
+ throw e;
+ }
executor.shutdown();
executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
diff --git a/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporter.java b/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporter.java
index 2098a03acd..68d572ad39 100644
--- a/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporter.java
+++ b/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporter.java
@@ -5,6 +5,7 @@ package org.thingsboard.migrator.service.tenant.exporting;
import com.datastax.oss.driver.api.core.cql.ColumnDefinition;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
+import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
@@ -15,6 +16,7 @@ import org.thingsboard.migrator.Table;
import org.thingsboard.migrator.utils.CassandraService;
import org.thingsboard.migrator.utils.Storage;
import org.thingsboard.migrator.utils.TsKvWriter;
+import org.thingsboard.migrator.utils.TsKvWriterFactory;
import java.io.IOException;
import java.util.ArrayList;
@@ -22,6 +24,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
+import java.util.concurrent.atomic.AtomicLong;
@Service
@RequiredArgsConstructor
@@ -31,6 +34,7 @@ public class CassandraTsKvExporter extends MigrationService {
private final Storage storage;
private final CassandraService cassandraService;
+ private final TsKvWriterFactory writerFactory;
@Value("${export.cassandra.ts.filter.start_ts:}")
private Long startTs;
@@ -42,45 +46,46 @@ public class CassandraTsKvExporter extends MigrationService {
private long partitionSizeMs;
@Value("${export.cassandra.ts.order.ts:false}")
private boolean orderByTimestamp;
- @Value("${export.ts_kv.max_file_size_mb}")
- private long maxFileSizeMb;
public static final String TS_KV_TABLE = "ts_kv_cf";
public static final String TS_KV_PARTITIONS_TABLE = "ts_kv_partitions_cf";
public static final String LATEST_KV = Table.LATEST_KV.getName();
+ private final AtomicLong failedKeys = new AtomicLong();
+
private TsKvWriter writer;
private boolean isFilterByPartition() {
return partitionFilter != null && partitionFilter > 0;
}
+ @PostConstruct
+ private void validate() {
+ if (!isFilterByPartition() && startTs != null && endTs != null && startTs > endTs) {
+ throw new IllegalArgumentException("CASSANDRA_EXPORT_TS_FILTER_START_TS (" + startTs + ") is greater than CASSANDRA_EXPORT_TS_FILTER_END_TS (" + endTs + ")");
+ }
+ }
+
@Override
protected void start() throws Exception {
if (isFilterByPartition()) {
log.info("Cassandra TS filter by partition [{}] is ACTIVE and other filters are IGNORED (startTs, endTs, partitionSizeMs).", partitionFilter);
- } else {
- // Validate time filter once at start
- if (startTs != null && endTs != null && startTs > endTs) {
- log.error("Invalid time range configuration: startTs {} is greater than endTs {}. Aborting Cassandra TS export.", startTs, endTs);
- return;
- }
- if (startTs != null || endTs != null) {
- log.info("Cassandra TS export filter is active. startTs={}, endTs={}, partitionSizeMs={}", startTs, endTs, partitionSizeMs);
- }
+ } else if (startTs != null || endTs != null) {
+ log.info("Cassandra TS export filter is active. startTs={}, endTs={}, partitionSizeMs={}", startTs, endTs, partitionSizeMs);
}
- writer = new TsKvWriter(storage, maxFileSizeMb * 1024 * 1024);
+ writer = writerFactory.create();
log.info("Starting Cassandra TS export. Latest KV file info: {}", storage.getFileInfo(LATEST_KV));
storage.readAndProcess(LATEST_KV, latestKvRow -> {
executor.submit(() -> {
try {
getTsHistoryAndSave(latestKvRow);
- reportProcessed(LATEST_KV, latestKvRow);
- } catch (Exception e) {
+ } catch (Throwable e) {
+ failedKeys.incrementAndGet();
log.error("Failed to retrieve timeseries history for {}", latestKvRow, e);
}
+ reportProcessed(LATEST_KV, latestKvRow);
});
});
}
@@ -164,6 +169,10 @@ public class CassandraTsKvExporter extends MigrationService {
protected void afterFinished() throws Exception {
finishedProcessing(TS_KV_TABLE);
finishedProcessing(LATEST_KV);
+ if (failedKeys.get() > 0) {
+ writer.abort();
+ throw new IllegalStateException(failedKeys.get() + " time-series keys failed to export, see errors above. The export is incomplete");
+ }
writer.finish();
}
diff --git a/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporter.java b/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporter.java
index ac57bbd0f6..8a2d786569 100644
--- a/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporter.java
+++ b/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporter.java
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.migrator.service.tenant.exporting;
+import com.zaxxer.hikari.HikariDataSource;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
@@ -12,9 +13,11 @@ import org.springframework.stereotype.Service;
import org.thingsboard.migrator.MigrationService;
import org.thingsboard.migrator.Table;
import org.thingsboard.migrator.utils.TsKvWriter;
+import org.thingsboard.migrator.utils.TsKvWriterFactory;
import org.thingsboard.migrator.utils.TsPartitioning;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -29,6 +32,7 @@ import static org.thingsboard.migrator.utils.TsKvFiles.NAME;
/**
* Exports time-series history from PostgreSQL/TimescaleDB ts_kv in the CassandraTsKvExporter files format,
* so that CassandraTsKvImporter can load it into a hybrid setup.
+ * History is read for the keys in the exported ts_kv_latest.
*/
@Service
@RequiredArgsConstructor
@@ -39,6 +43,7 @@ public class PostgresTsKvExporter extends MigrationService {
private static final String[] VALUE_COLUMNS = {"bool_v", "str_v", "long_v", "dbl_v", "json_v"};
private final JdbcTemplate jdbcTemplate;
+ private final TsKvWriterFactory writerFactory;
@Value("${export.postgres_ts.partitioning}")
private String partitioningName;
@@ -56,13 +61,12 @@ public class PostgresTsKvExporter extends MigrationService {
private boolean cassandraExportEnabled;
@Value("${skipped_tables}")
private Set skippedTables;
- @Value("${export.ts_kv.max_file_size_mb}")
- private long maxFileSizeMb;
private final AtomicLong failedKeys = new AtomicLong();
private TsPartitioning partitioning;
- private String query;
+ private String firstPageQuery;
+ private String nextPageQuery;
private TsKvWriter writer;
@PostConstruct
@@ -84,8 +88,17 @@ public class PostgresTsKvExporter extends MigrationService {
} else if (!storage.exists(LATEST_KV)) {
throw new IllegalStateException(LATEST_KV + ".gz not found in the working directory. Enable POSTGRES_EXPORT_ENABLED or put a previously exported " + LATEST_KV + ".gz there");
}
- query = "SELECT ts, bool_v, str_v, long_v, dbl_v, json_v FROM ts_kv WHERE entity_id = ? AND key = ? AND ts > ?" +
+ // Workers and the main thread (CallerRunsPolicy) query in parallel; waiting for a connection would time out
+ if (jdbcTemplate.getDataSource() instanceof HikariDataSource dataSource && dataSource.getMaximumPoolSize() <= parallelismLevel) {
+ throw new IllegalStateException("DATABASE_MAX_POOL_SIZE (" + dataSource.getMaximumPoolSize() +
+ ") must be greater than PARALLELISM_LEVEL (" + parallelismLevel + ")");
+ }
+ // The key id is resolved by name: ts_kv_latest.gz may come from an earlier export
+ String query = "SELECT ts, bool_v, str_v, long_v, dbl_v, json_v FROM ts_kv " +
+ "WHERE entity_id = ? AND key = (SELECT key_id FROM key_dictionary WHERE key = ?) AND ts %s ?" +
(endTs != null ? " AND ts <= ?" : "") + " ORDER BY ts LIMIT ?";
+ firstPageQuery = query.formatted(">=");
+ nextPageQuery = query.formatted(">");
}
@Override
@@ -94,12 +107,12 @@ public class PostgresTsKvExporter extends MigrationService {
partitioning, startTs, endTs, storage.getFileInfo(LATEST_KV));
reportTotal(LATEST_KV, storage.count(LATEST_KV));
- writer = new TsKvWriter(storage, maxFileSizeMb * 1024 * 1024);
+ writer = writerFactory.create();
storage.readAndProcess(LATEST_KV, latestKvRow -> executor.submit(() -> {
try {
exportHistory(TsKey.of(latestKvRow));
- } catch (Exception e) {
+ } catch (Throwable e) {
failedKeys.incrementAndGet();
log.error("Failed to export time-series history for {} {}, key '{}'",
latestKvRow.get("table_name"), latestKvRow.get("entity_id"), latestKvRow.get("key_name"), e);
@@ -110,20 +123,23 @@ public class PostgresTsKvExporter extends MigrationService {
private void exportHistory(TsKey tsKey) throws InterruptedException, IOException {
// Keyset pagination: ts is unique per (entity_id, key)
- long cursor = startTs != null ? startTs - 1 : Long.MIN_VALUE;
+ String query = firstPageQuery;
+ long cursor = startTs != null ? startTs : Long.MIN_VALUE;
long partitionTs = Long.MIN_VALUE;
long nextPartitionTs = Long.MIN_VALUE;
while (true) {
- Object[] args = endTs != null ?
- new Object[]{tsKey.entityId(), tsKey.keyId(), cursor, endTs, batchSize} :
- new Object[]{tsKey.entityId(), tsKey.keyId(), cursor, batchSize};
+ List