Browse Source

fix(migrator): retry ts_kv export pages and stop import reads on failure

PostgreSQL ts_kv export now retries transient query failures from the same
cursor, fails fast on non-transient errors, and cleans up time-series files
on latest-read failures.

Cassandra export reads partitions in ordered pages through retried queries.
The importer stops reading immediately after a failed insert, abort deletes
files even when close fails, and startup failures force JVM exit.
pull/16897/head
dealnat 2 hours ago
parent
commit
95b2ded1a6
  1. 14
      migrator/src/main/java/org/thingsboard/migrator/MigrationService.java
  2. 10
      migrator/src/main/java/org/thingsboard/migrator/MigratorApplication.java
  3. 77
      migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporter.java
  4. 85
      migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporter.java
  5. 13
      migrator/src/main/java/org/thingsboard/migrator/service/tenant/importing/CassandraTsKvImporter.java
  6. 8
      migrator/src/main/java/org/thingsboard/migrator/utils/CassandraService.java
  7. 34
      migrator/src/main/java/org/thingsboard/migrator/utils/TsKvWriter.java
  8. 5
      migrator/src/main/resources/README.md
  9. 5
      migrator/src/main/resources/application.yml
  10. 139
      migrator/src/test/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporterTest.java
  11. 104
      migrator/src/test/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporterTest.java
  12. 15
      migrator/src/test/java/org/thingsboard/migrator/service/tenant/importing/CassandraTsKvImporterTest.java
  13. 21
      migrator/src/test/java/org/thingsboard/migrator/utils/TsKvWriterTest.java

14
migrator/src/main/java/org/thingsboard/migrator/MigrationService.java

@ -62,6 +62,15 @@ public abstract class MigrationService {
} catch (Throwable e) {
// Idle non-daemon workers would otherwise keep the JVM running
executor.shutdownNow();
if (executor.awaitTermination(1, TimeUnit.MINUTES)) {
try {
afterFailed();
} catch (Throwable cleanupError) {
e.addSuppressed(cleanupError);
}
} else {
log.warn("Workers didn't stop within a minute, skipping the cleanup");
}
throw e;
}
@ -75,6 +84,11 @@ public abstract class MigrationService {
protected void afterFinished() throws Exception {}
/**
* Called instead of {@link #afterFinished()} when {@link #start()} throws, once the workers have stopped.
*/
protected void afterFailed() throws Exception {}
protected void reportTotal(String key, long total) {
this.total.put(key, total);
}

10
migrator/src/main/java/org/thingsboard/migrator/MigratorApplication.java

@ -5,6 +5,7 @@ package org.thingsboard.migrator;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.thingsboard.migrator.utils.Storage;
@ -14,7 +15,14 @@ import java.util.List;
public class MigratorApplication {
public static void main(String[] args) {
var ctx = SpringApplication.run(MigratorApplication.class, args);
ConfigurableApplicationContext ctx;
try {
ctx = SpringApplication.run(MigratorApplication.class, args);
} catch (Throwable e) {
// Logged by Spring Boot. Threads still running, e.g. of the Cassandra driver, would keep the JVM alive
System.exit(1);
return;
}
boolean exitAfterFinish = ctx.getEnvironment().getProperty("exit_after_finish", Boolean.class, true);
if (exitAfterFinish) {

77
migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporter.java

@ -3,7 +3,6 @@
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;
@ -20,6 +19,7 @@ import org.thingsboard.migrator.utils.TsKvWriterFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@ -44,8 +44,8 @@ public class CassandraTsKvExporter extends MigrationService {
private Long partitionFilter;
@Value("${export.cassandra.ts.filter.partition_size_ms:2678400000}")
private long partitionSizeMs;
@Value("${export.cassandra.ts.order.ts:false}")
private boolean orderByTimestamp;
@Value("${spring.cassandra.request.page-size:10000}")
private int pageSize;
public static final String TS_KV_TABLE = "ts_kv_cf";
public static final String TS_KV_PARTITIONS_TABLE = "ts_kv_partitions_cf";
@ -61,6 +61,9 @@ public class CassandraTsKvExporter extends MigrationService {
@PostConstruct
private void validate() {
if (pageSize <= 0) {
throw new IllegalArgumentException("CASSANDRA_REQUEST_PAGE_SIZE must be positive, got " + pageSize);
}
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 + ")");
}
@ -90,7 +93,7 @@ public class CassandraTsKvExporter extends MigrationService {
});
}
private void getTsHistoryAndSave(Map<String, Object> latestKvRow) throws IOException {
private void getTsHistoryAndSave(Map<String, Object> latestKvRow) throws IOException, InterruptedException {
String entityType = (String) latestKvRow.get("table_name");
UUID entityId = (UUID) latestKvRow.get("entity_id");
String key = (String) latestKvRow.get("key_name");
@ -129,14 +132,24 @@ public class CassandraTsKvExporter extends MigrationService {
continue;
}
StringBuilder query = new StringBuilder("SELECT entity_type, entity_id, partition, key, ts, bool_v, str_v, long_v, dbl_v, json_v FROM " + TS_KV_TABLE + " WHERE entity_type = ? AND entity_id = ? AND key = ? AND partition = ?");
List<Object> args = new ArrayList<>();
args.add(entityType);
args.add(entityId);
args.add(key);
args.add(partition);
exportPartition(entityType, entityId, key, partition, startTs, endTs);
}
}
if (startTs != null) {
// Keyset pagination over the rows of a partition, ordered by the clustering column ts.
// Each page is read within the CassandraService retries, so a failed page is read again without duplicates.
private void exportPartition(String entityType, UUID entityId, String key, long partition, Long startTs, Long endTs) throws IOException, InterruptedException {
Long cursor = null;
while (true) {
if (Thread.interrupted()) {
throw new InterruptedException();
}
StringBuilder query = new StringBuilder("SELECT entity_type, entity_id, partition, key, ts, bool_v, str_v, long_v, dbl_v, json_v FROM " + TS_KV_TABLE + " WHERE entity_type = ? AND entity_id = ? AND key = ? AND partition = ?");
List<Object> args = new ArrayList<>(Arrays.asList(entityType, entityId, key, partition));
if (cursor != null) {
query.append(" AND ts > ?");
args.add(cursor);
} else if (startTs != null) {
query.append(" AND ts >= ?");
args.add(startTs);
}
@ -144,27 +157,34 @@ public class CassandraTsKvExporter extends MigrationService {
query.append(" AND ts <= ?");
args.add(endTs);
}
if (orderByTimestamp) {
query.append(" ORDER BY ts");
}
query.append(" ORDER BY ts LIMIT ?");
args.add(pageSize);
ResultSet rows = cassandraService.query(query.toString(), args.toArray());
for (Row row : rows) {
Map<String, Object> data = new LinkedHashMap<>(); //preserve order of columns
for (ColumnDefinition columnDefinition : row.getColumnDefinitions()) {
String column = columnDefinition.getName().toString();
Object value = row.getObject(columnDefinition.getName());
if (column.endsWith("_v") && value == null) {
continue;
}
data.put(column, value);
}
List<Map<String, Object>> rows = cassandraService.query(query.toString(), CassandraTsKvExporter::toMap, args.toArray());
for (Map<String, Object> data : rows) {
writer.write(data);
reportProcessed(TS_KV_TABLE, data);
}
if (rows.size() < pageSize) {
return;
}
cursor = (Long) rows.get(rows.size() - 1).get("ts");
}
}
private static Map<String, Object> toMap(Row row, int rowNum) {
Map<String, Object> data = new LinkedHashMap<>(); //preserve order of columns
for (ColumnDefinition columnDefinition : row.getColumnDefinitions()) {
String column = columnDefinition.getName().toString();
Object value = row.getObject(columnDefinition.getName());
if (column.endsWith("_v") && value == null) {
continue;
}
data.put(column, value);
}
return data;
}
@Override
protected void afterFinished() throws Exception {
finishedProcessing(TS_KV_TABLE);
@ -176,4 +196,11 @@ public class CassandraTsKvExporter extends MigrationService {
writer.finish();
}
@Override
protected void afterFailed() throws Exception {
if (writer != null) {
writer.abort();
}
}
}

85
migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporter.java

@ -5,10 +5,16 @@ package org.thingsboard.migrator.service.tenant.exporting;
import com.zaxxer.hikari.HikariDataSource;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.dao.RecoverableDataAccessException;
import org.springframework.dao.TransientDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.stereotype.Service;
import org.thingsboard.migrator.MigrationService;
import org.thingsboard.migrator.Table;
@ -21,8 +27,10 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
@ -41,6 +49,14 @@ import static org.thingsboard.migrator.utils.TsKvFiles.NAME;
public class PostgresTsKvExporter extends MigrationService {
private static final String[] VALUE_COLUMNS = {"bool_v", "str_v", "long_v", "dbl_v", "json_v"};
private static final RowMapper<TsRow> TS_ROW_MAPPER = (rs, rowNum) -> {
Object[] values = new Object[VALUE_COLUMNS.length];
for (int i = 0; i < VALUE_COLUMNS.length; i++) {
values[i] = rs.getObject(i + 2);
}
return new TsRow(rs.getLong(1), values);
};
private static final long MAX_RETRY_DELAY_MS = 30_000;
private final JdbcTemplate jdbcTemplate;
private final TsKvWriterFactory writerFactory;
@ -49,6 +65,8 @@ public class PostgresTsKvExporter extends MigrationService {
private String partitioningName;
@Value("${export.postgres_ts.batch_size}")
private int batchSize;
@Value("${export.postgres_ts.max_retries:10}")
private int maxRetries;
@Value("${export.postgres_ts.filter.start_ts:}")
private Long startTs;
@Value("${export.postgres_ts.filter.end_ts:}")
@ -63,6 +81,8 @@ public class PostgresTsKvExporter extends MigrationService {
private Set<Table> skippedTables;
private final AtomicLong failedKeys = new AtomicLong();
private final Map<String, Optional<Integer>> keyIds = new ConcurrentHashMap<>();
private final Set<String> missingKeys = ConcurrentHashMap.newKeySet();
private TsPartitioning partitioning;
private String firstPageQuery;
@ -78,6 +98,9 @@ public class PostgresTsKvExporter extends MigrationService {
if (batchSize <= 0) {
throw new IllegalArgumentException("POSTGRES_TS_EXPORT_BATCH_SIZE must be positive, got " + batchSize);
}
if (maxRetries < 0) {
throw new IllegalArgumentException("POSTGRES_TS_EXPORT_MAX_RETRIES must not be negative, got " + maxRetries);
}
if (startTs != null && endTs != null && startTs > endTs) {
throw new IllegalArgumentException("POSTGRES_TS_EXPORT_FILTER_START_TS (" + startTs + ") is greater than POSTGRES_TS_EXPORT_FILTER_END_TS (" + endTs + ")");
}
@ -93,9 +116,7 @@ public class PostgresTsKvExporter extends MigrationService {
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 ?" +
String query = "SELECT ts, bool_v, str_v, long_v, dbl_v, json_v FROM ts_kv WHERE entity_id = ? AND key = ? AND ts %s ?" +
(endTs != null ? " AND ts <= ?" : "") + " ORDER BY ts LIMIT ?";
firstPageQuery = query.formatted(">=");
nextPageQuery = query.formatted(">");
@ -122,24 +143,28 @@ public class PostgresTsKvExporter extends MigrationService {
}
private void exportHistory(TsKey tsKey) throws InterruptedException, IOException {
Optional<Integer> keyId = keyId(tsKey.keyName());
if (keyId.isEmpty()) {
if (missingKeys.add(tsKey.keyName())) {
log.warn("Key '{}' is not in key_dictionary, its time-series history is not exported", tsKey.keyName());
}
return;
}
// Keyset pagination: ts is unique per (entity_id, key)
String query = firstPageQuery;
long cursor = startTs != null ? startTs : Long.MIN_VALUE;
long partitionTs = Long.MIN_VALUE;
long nextPartitionTs = Long.MIN_VALUE;
while (true) {
List<Object> args = new ArrayList<>(List.of(tsKey.entityId(), tsKey.keyName(), cursor));
if (Thread.interrupted()) {
throw new InterruptedException();
}
List<Object> args = new ArrayList<>(List.of(tsKey.entityId(), keyId.get(), cursor));
if (endTs != null) {
args.add(endTs);
}
args.add(batchSize);
List<TsRow> rows = jdbcTemplate.query(query, (rs, rowNum) -> {
Object[] values = new Object[VALUE_COLUMNS.length];
for (int i = 0; i < VALUE_COLUMNS.length; i++) {
values[i] = rs.getObject(i + 2);
}
return new TsRow(rs.getLong(1), values);
}, args.toArray());
List<TsRow> rows = queryWithRetries(query, TS_ROW_MAPPER, args.toArray());
for (TsRow row : rows) {
if (row.ts() < partitionTs || row.ts() >= nextPartitionTs) {
@ -172,10 +197,41 @@ public class PostgresTsKvExporter extends MigrationService {
}
}
// Resolved by name: ts_kv_latest.gz may come from an earlier export, with other ids
private Optional<Integer> keyId(String keyName) throws InterruptedException {
Optional<Integer> keyId = keyIds.get(keyName);
if (keyId == null) {
keyId = queryWithRetries("SELECT key_id FROM key_dictionary WHERE key = ?", SingleColumnRowMapper.newInstance(Integer.class), keyName)
.stream().findFirst();
keyIds.put(keyName, keyId);
}
return keyId;
}
// A failed query is repeated with the same cursor, so a retry doesn't duplicate rows
private <T> List<T> queryWithRetries(String sql, RowMapper<T> rowMapper, Object... args) throws InterruptedException {
for (int attempt = 1; ; attempt++) {
try {
return jdbcTemplate.query(sql, rowMapper, args);
} catch (TransientDataAccessException | DataAccessResourceFailureException | RecoverableDataAccessException e) {
if (attempt > maxRetries) {
throw e;
}
long delay = Math.min(MAX_RETRY_DELAY_MS, 1000L << Math.min(attempt - 1, 15));
log.warn("Query failed, retry {}/{} in {} ms: {}", attempt, maxRetries, delay, e.getMessage());
TimeUnit.MILLISECONDS.sleep(delay);
}
}
}
@Override
protected void afterFinished() throws Exception {
finishedProcessing(NAME);
finishedProcessing(LATEST_KV);
if (!missingKeys.isEmpty()) {
log.warn("Time-series history of {} keys not found in key_dictionary is not exported: {}", missingKeys.size(),
StringUtils.abbreviate(missingKeys.toString(), 1000));
}
if (failedKeys.get() > 0) {
writer.abort();
throw new IllegalStateException(failedKeys.get() + " time-series keys failed to export, see errors above. The export is incomplete");
@ -183,6 +239,13 @@ public class PostgresTsKvExporter extends MigrationService {
writer.finish();
}
@Override
protected void afterFailed() throws Exception {
if (writer != null) {
writer.abort();
}
}
private record TsKey(String entityType, UUID entityId, String keyName) {
static TsKey of(Map<String, Object> latestKvRow) {

13
migrator/src/main/java/org/thingsboard/migrator/service/tenant/importing/CassandraTsKvImporter.java

@ -78,17 +78,19 @@ public class CassandraTsKvImporter extends MigrationService {
log.info("Importing {}", storage.getFileInfo(part.name()));
try {
storage.readAndProcess(part.name(), toSkip, row -> {
long position = nextPosition++;
// after a failure the rest is imported on resume
if (failedInserts.get() > 0) {
return;
throw new ImportStoppedException();
}
long position = nextPosition++;
try {
saveTsKv(row, position);
} catch (Throwable e) {
onFailure(position, row, e);
}
});
} catch (ImportStoppedException e) {
break;
} catch (Exception e) {
// e.g. a truncated file; rows already submitted still complete
onFailure(nextPosition, "file " + part.name(), e);
@ -176,6 +178,13 @@ public class CassandraTsKvImporter extends MigrationService {
}
}
// Stops reading the file
private static class ImportStoppedException extends RuntimeException {
ImportStoppedException() {
super(null, null, false, false);
}
}
@Data(staticConstructor = "of")
private static class PartitionKey {
private final String entityType;

8
migrator/src/main/java/org/thingsboard/migrator/utils/CassandraService.java

@ -16,6 +16,7 @@ import org.springframework.data.cassandra.core.cql.ArgumentPreparedStatementBind
import org.springframework.data.cassandra.core.cql.CachedPreparedStatementCreator;
import org.springframework.data.cassandra.core.cql.CqlOperations;
import org.springframework.data.cassandra.core.cql.ResultSetExtractor;
import org.springframework.data.cassandra.core.cql.RowMapper;
import org.springframework.data.cassandra.core.cql.RowMapperResultSetExtractor;
import org.springframework.data.cassandra.core.cql.SingleColumnRowMapper;
import org.springframework.stereotype.Service;
@ -61,6 +62,13 @@ public class CassandraService {
return query(query, new RowMapperResultSetExtractor<>(SingleColumnRowMapper.newInstance(type)), args);
}
/**
* Reads all rows within the retries, unlike the lazy {@link ResultSet}, whose next pages are fetched without them.
*/
public <T> List<T> query(String query, RowMapper<T> rowMapper, Object... args) {
return query(query, new RowMapperResultSetExtractor<>(rowMapper), args);
}
@SuppressWarnings("deprecation")
private <T> T query(String query, ResultSetExtractor<T> resultSetExtractor, Object... args) {
int attempt = 0;

34
migrator/src/main/java/org/thingsboard/migrator/utils/TsKvWriter.java

@ -25,10 +25,10 @@ public class TsKvWriter {
private final Storage storage;
private final long maxFileSize;
private final AtomicInteger lastPartIndex = new AtomicInteger();
private final ThreadLocal<File> threadPart = new ThreadLocal<>();
private final Set<File> openParts = ConcurrentHashMap.newKeySet();
private final List<File> closedParts = Collections.synchronizedList(new ArrayList<>());
private final File legacyFile;
private final ThreadLocal<OutputFile> threadPart = new ThreadLocal<>();
private final Set<OutputFile> openParts = ConcurrentHashMap.newKeySet();
private final List<OutputFile> closedParts = Collections.synchronizedList(new ArrayList<>());
private final OutputFile legacyFile;
/**
* @param maxFileSize in bytes; 0 or less writes a single legacy ts_kv.gz without a manifest
@ -38,7 +38,7 @@ public class TsKvWriter {
this.maxFileSize = maxFileSize;
// Leftovers of a previous export would otherwise be picked up by the importer
deleteFiles();
legacyFile = maxFileSize > 0 ? null : new File(TsKvFiles.NAME, 0);
legacyFile = maxFileSize > 0 ? null : new OutputFile(TsKvFiles.NAME, 0);
}
public void write(Map<String, Object> row) throws IOException {
@ -49,13 +49,13 @@ public class TsKvWriter {
}
return;
}
File part = threadPart.get();
OutputFile part = threadPart.get();
if (part == null || part.compressedSize.get() >= maxFileSize) {
if (part != null) {
close(part);
}
int index = lastPartIndex.incrementAndGet();
part = new File(TsKvFiles.partName(index), index);
part = new OutputFile(TsKvFiles.partName(index), index);
openParts.add(part);
threadPart.set(part);
}
@ -71,7 +71,7 @@ public class TsKvWriter {
legacyFile.writer.close();
return;
}
for (File part : List.copyOf(openParts)) {
for (OutputFile part : List.copyOf(openParts)) {
close(part);
}
List<TsKvFiles.Part> parts = closedParts.stream()
@ -86,16 +86,18 @@ public class TsKvWriter {
* Must be called after all writing threads are done.
*/
public void abort() throws IOException {
if (legacyFile != null) {
legacyFile.writer.close();
}
for (File part : List.copyOf(openParts)) {
close(part);
List<OutputFile> files = legacyFile != null ? List.of(legacyFile) : List.copyOf(openParts);
for (OutputFile file : files) {
try {
file.writer.close();
} catch (IOException ignored) {
// e.g. disk full; the file is deleted anyway
}
}
deleteFiles();
}
private void close(File part) throws IOException {
private void close(OutputFile part) throws IOException {
part.writer.close();
openParts.remove(part);
closedParts.add(part);
@ -108,7 +110,7 @@ public class TsKvWriter {
}
// Written by one thread at a time
private class File {
private class OutputFile {
final String name;
final int index;
@ -116,7 +118,7 @@ public class TsKvWriter {
final Writer writer;
long rows;
File(String name, int index) throws IOException {
OutputFile(String name, int index) throws IOException {
this.name = name;
this.index = index;
storage.newFile(name);

5
migrator/src/main/resources/README.md

@ -43,7 +43,10 @@ POSTGRES_TS_EXPORT_PARTITIONING=MONTHS
- Optional: `POSTGRES_TS_EXPORT_FILTER_START_TS` / `POSTGRES_TS_EXPORT_FILTER_END_TS` (inclusive, epoch millis), `POSTGRES_TS_EXPORT_BATCH_SIZE` (default 10000).
- History is exported only for keys present in `ts_kv_latest`. Keys without a latest value are not exported, e.g. keys saved by
the "Save time series" node with the latest processing strategy set to skip, or keys whose latest value was deleted.
- A `ts_kv` query that fails on a lost connection, a timeout or a failover is retried with the same cursor, without duplicating rows
(`POSTGRES_TS_EXPORT_MAX_RETRIES`, default 10, backoff from 1s up to 30s). Other errors are not retried.
- If any key fails to export, the migrator exits with an error, deletes the time-series files and doesn't create `data.tar`.
Key names missing from `key_dictionary` (when `ts_kv_latest.gz` comes from another database) are logged as warnings and skipped.
- `DATABASE_MAX_POOL_SIZE` (default 16) must be greater than `PARALLELISM_LEVEL`, the export checks it at startup.
- `POSTGRES_EXPORT_DELAY_BETWEEN_QUERIES` also throttles the time-series export: it sleeps after every `ts_kv` query.
- Each key is one query (per `POSTGRES_TS_EXPORT_BATCH_SIZE` rows) that probes every `ts_kv` partition or TimescaleDB chunk.
@ -90,6 +93,8 @@ Time-series files:
- Timeouts and unavailable nodes are retried (`CASSANDRA_RETRY_MAX_RETRIES`, default 10), other errors such as an invalid query are not.
If an insert still fails, the import stops and exits with an error naming the `CASSANDRA_IMPORT_TS_KV_SKIP_LINES` value to resume from:
every row before it is imported. Rows imported again are overwritten, so resuming earlier is safe.
- The Cassandra export reads each partition in pages of `CASSANDRA_REQUEST_PAGE_SIZE` rows ordered by `ts`, and retries a failed page like the import does.
If a key still fails, the export exits with an error and deletes the time-series files.
- If Cassandra nodes crashed during the import (rather than becoming unreachable), writes they acknowledged since their last commit log sync
(`commitlog_sync_period`, 10s by default) can be lost when a single replica holds them. Resume from an earlier position or import again.
- `data.tar` is limited to about 2GB, use `ARCHIVE_RESULT=false` for larger exports and transfer the files as they are.

5
migrator/src/main/resources/application.yml

@ -39,9 +39,6 @@ export:
# Partition size (ms) used to compute the lower bound of partitions for startTs filtering.
# We will start scanning partitions from (startTs - partition_size_ms). Defaults to 31 days in ms.
partition_size_ms: ${CASSANDRA_EXPORT_TS_FILTER_PARTITION_SIZE_MS:${CASSANDRA_EXPORT_TS_FILTER_MONTH_MS:2678400000}}
order:
# Enforce result order by ts in the query. Disabled by default because explicit ordering is not required for export and results may be returned in any order.
ts: ${CASSANDRA_EXPORT_TS_ORDER_TS:false}
# Exports time-series history from PostgreSQL/TimescaleDB ts_kv into the same ts_kv file the Cassandra importer reads.
# Mutually exclusive with export.cassandra (CASSANDRA_EXPORT_ENABLED must be false).
postgres_ts:
@ -50,6 +47,8 @@ export:
# MINUTES, HOURS, DAYS, MONTHS, YEARS, INDEFINITE
partitioning: ${POSTGRES_TS_EXPORT_PARTITIONING:MONTHS}
batch_size: ${POSTGRES_TS_EXPORT_BATCH_SIZE:10000}
# Retries of a failed ts_kv query on transient errors (lost connection, timeout, failover), with backoff from 1s up to 30s
max_retries: ${POSTGRES_TS_EXPORT_MAX_RETRIES:10}
filter:
# Inclusive bounds in epoch millis. Leave empty to export all available data.
start_ts: ${POSTGRES_TS_EXPORT_FILTER_START_TS:}

139
migrator/src/test/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporterTest.java

@ -0,0 +1,139 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.migrator.service.tenant.exporting;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.migrator.utils.CassandraService;
import org.thingsboard.migrator.utils.Storage;
import org.thingsboard.migrator.utils.TestStorage;
import org.thingsboard.migrator.utils.TsKvFiles;
import org.thingsboard.migrator.utils.TsKvWriterFactory;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.stream.LongStream;
import static org.assertj.core.api.Assertions.assertThat;
class CassandraTsKvExporterTest {
private static final UUID DEVICE = UUID.randomUUID();
@TempDir
Path workingDir;
private Storage storage;
// ts of the rows by partition, as in ts_kv_cf
private final Map<Long, List<Long>> partitions = new TreeMap<>();
private final Queue<String> rowQueries = new ConcurrentLinkedQueue<>();
private CassandraService cassandraService;
@BeforeEach
void setUp() throws IOException {
storage = TestStorage.create(workingDir, "TENANT_DATA_EXPORT");
cassandraService = Mockito.mock(CassandraService.class, invocation -> {
String query = invocation.getArgument(0);
Object[] args = (Object[]) invocation.getRawArguments()[2];
if (query.contains(" FROM ts_kv_partitions_cf ")) {
return List.copyOf(partitions.keySet());
}
if (query.contains(" FROM ts_kv_cf ")) {
rowQueries.add(query);
return page(query, args);
}
return null;
});
storage.newFile(CassandraTsKvExporter.LATEST_KV);
try (Writer writer = storage.newWriter(CassandraTsKvExporter.LATEST_KV)) {
storage.addToFile(writer, new LinkedHashMap<>(Map.of("table_name", "DEVICE", "entity_id", DEVICE, "key_name", "temperature")));
}
}
@Test
void readsPartitionsInPages() throws Exception {
partitions.put(0L, List.of(1L, 2L, 3L, 4L, 5L));
partitions.put(1000L, List.of(1001L, 1002L, 1003L, 1004L));
partitions.put(2000L, List.of());
exporter(null, null).run();
assertThat(exportedTs()).containsExactly(1L, 2L, 3L, 4L, 5L, 1001L, 1002L, 1003L, 1004L);
// 3 + 3 (the last page is empty) + 1
assertThat(rowQueries).hasSize(7).allMatch(query -> query.endsWith(" ORDER BY ts LIMIT ?"));
}
@Test
void appliesFilterBoundsToAllPages() throws Exception {
partitions.put(0L, LongStream.rangeClosed(1, 10).boxed().toList());
exporter(3L, 8L).run();
assertThat(exportedTs()).containsExactly(3L, 4L, 5L, 6L, 7L, 8L);
}
private CassandraTsKvExporter exporter(Long startTs, Long endTs) {
TsKvWriterFactory writerFactory = new TsKvWriterFactory(storage);
ReflectionTestUtils.setField(writerFactory, "maxFileSizeMb", 1L);
CassandraTsKvExporter exporter = new CassandraTsKvExporter(storage, cassandraService, writerFactory);
ReflectionTestUtils.setField(exporter, "parallelismLevel", 4);
ReflectionTestUtils.setField(exporter, "statsPrintInterval", 1_000);
ReflectionTestUtils.setField(exporter, "startTs", startTs);
ReflectionTestUtils.setField(exporter, "endTs", endTs);
ReflectionTestUtils.setField(exporter, "partitionSizeMs", 1000L);
ReflectionTestUtils.setField(exporter, "pageSize", 2);
ReflectionTestUtils.invokeMethod(exporter, "init");
ReflectionTestUtils.invokeMethod(exporter, "validate");
return exporter;
}
// Executes the row query against the partitions map
private List<Map<String, Object>> page(String query, Object[] args) {
long partition = (Long) args[3];
int i = 4;
long lowerBound = Long.MIN_VALUE;
if (query.contains(" ts > ?")) {
lowerBound = (Long) args[i++] + 1;
} else if (query.contains(" ts >= ?")) {
lowerBound = (Long) args[i++];
}
long upperBound = query.contains(" ts <= ?") ? (Long) args[i++] : Long.MAX_VALUE;
int limit = (Integer) args[i];
long from = lowerBound;
return partitions.get(partition).stream()
.filter(ts -> ts >= from && ts <= upperBound)
.limit(limit)
.map(ts -> {
Map<String, Object> row = new LinkedHashMap<>();
row.put("entity_type", "DEVICE");
row.put("entity_id", DEVICE);
row.put("partition", partition);
row.put("key", "temperature");
row.put("ts", ts);
row.put("long_v", ts);
return row;
})
.toList();
}
private List<Long> exportedTs() throws IOException {
List<Long> ts = new ArrayList<>();
for (TsKvFiles.Part part : TsKvFiles.listForImport(storage)) {
storage.readAndProcess(part.name(), row -> ts.add(((Number) row.get("ts")).longValue()));
}
return ts;
}
}

104
migrator/src/test/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporterTest.java

@ -2,12 +2,16 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.migrator.service.tenant.exporting;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.dao.TransientDataAccessResourceException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.util.ReflectionTestUtils;
import org.testcontainers.containers.PostgreSQLContainer;
@ -19,25 +23,30 @@ import org.thingsboard.migrator.utils.TsKvFiles;
import org.thingsboard.migrator.utils.TsKvWriterFactory;
import org.thingsboard.migrator.utils.TsPartitioning;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Path;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntFunction;
import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Testcontainers(disabledWithoutDocker = true)
@Testcontainers
class PostgresTsKvExporterTest {
@Container
private static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:18");
private static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:18.6");
private static final Pattern TS_KV_FILES = Pattern.compile("ts_kv(_\\d+|_manifest)?");
private static final UUID DEVICE = UUID.fromString("d1000000-0000-1000-8000-000000000001");
private static final UUID OTHER_DEVICE = UUID.fromString("d2000000-0000-1000-8000-000000000002");
@ -45,7 +54,7 @@ class PostgresTsKvExporterTest {
private static final long NOV_1 = 1761955200000L;
private static final long OCT_1 = 1759276800000L;
private static JdbcTemplate jdbcTemplate;
private static FailingJdbcTemplate jdbcTemplate;
@TempDir
Path workingDir;
@ -54,7 +63,7 @@ class PostgresTsKvExporterTest {
@BeforeAll
static void createDatabase() {
jdbcTemplate = new JdbcTemplate(new DriverManagerDataSource(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()));
jdbcTemplate = new FailingJdbcTemplate(new DriverManagerDataSource(POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()));
jdbcTemplate.execute("""
CREATE TABLE key_dictionary (key varchar(255) NOT NULL, key_id serial UNIQUE, CONSTRAINT key_dictionary_id_pkey PRIMARY KEY (key));
CREATE TABLE ts_kv (entity_id uuid NOT NULL, key int NOT NULL, ts bigint NOT NULL, bool_v boolean, str_v varchar(10000000),
@ -84,6 +93,8 @@ class PostgresTsKvExporterTest {
@BeforeEach
void setUp() {
storage = TestStorage.create(workingDir, "TENANT_DATA_EXPORT");
jdbcTemplate.tsKvQueries.set(0);
jdbcTemplate.failure = call -> null;
}
@Test
@ -91,7 +102,8 @@ class PostgresTsKvExporterTest {
writeLatest(latest(DEVICE, "temperature"), latest(DEVICE, "status"), latest(DEVICE, "active"), latest(DEVICE, "counter"),
latest(DEVICE, "payload"), latest(DEVICE, "missing_in_dictionary"));
exporter(null, null).run();
PostgresTsKvExporter exporter = exporter(null, null);
exporter.run();
List<Map<String, Object>> rows = readExport();
assertThat(rows).hasSize(11);
@ -106,16 +118,56 @@ class PostgresTsKvExporterTest {
assertThat(values(rows, "active", "bool_v")).containsExactly(true);
assertThat(values(rows, "counter", "long_v")).containsExactly(9000000000L);
assertThat(values(rows, "payload", "json_v")).containsExactly("{\"a\":1}");
assertThat((Set<Object>) ReflectionTestUtils.getField(exporter, "missingKeys")).containsExactly("missing_in_dictionary");
}
@Test
void transientErrorIsRetriedWithoutDuplicates() throws Exception {
writeLatest(latest(DEVICE, "temperature"));
// the 3rd of 4 pages
jdbcTemplate.failure = call -> call == 3 ? new TransientDataAccessResourceException("Connection lost") : null;
exporter(null, null).run();
assertThat(jdbcTemplate.tsKvQueries).hasValue(5);
assertThat(readExport()).extracting(row -> row.get("ts")).doesNotHaveDuplicates().hasSize(7);
}
@Test
void filterBoundsAreInclusive() throws Exception {
void retriesAreLimited() throws IOException {
writeLatest(latest(DEVICE, "temperature"));
jdbcTemplate.failure = call -> new TransientDataAccessResourceException("Connection lost");
PostgresTsKvExporter exporter = exporter(null, null);
ReflectionTestUtils.setField(exporter, "maxRetries", 1);
assertThatThrownBy(exporter::run).hasMessageContaining("1 time-series keys failed to export");
assertThat(jdbcTemplate.tsKvQueries).hasValue(2);
}
@Test
void otherErrorsAreNotRetried() throws IOException {
writeLatest(latest(DEVICE, "temperature"));
jdbcTemplate.failure = call -> new BadSqlGrammarException("ts_kv", "SELECT", new SQLException("column does not exist"));
assertThatThrownBy(() -> exporter(null, null).run()).hasMessageContaining("1 time-series keys failed to export");
assertThat(jdbcTemplate.tsKvQueries).hasValue(1);
}
exporter(OCT_31_23_58 + 60000, NOV_1 + 60000).run();
@Test
void failureWhileReadingLatestDeletesTimeSeriesFiles() throws IOException {
storage.newFile(CassandraTsKvExporter.LATEST_KV);
try (Writer writer = storage.newWriter(CassandraTsKvExporter.LATEST_KV)) {
storage.addToFile(writer, latest(DEVICE, "temperature"));
writer.write("{corrupt\n");
}
// legacy single ts_kv.gz, which the import wouldn't reject as incomplete
PostgresTsKvExporter exporter = new PostgresTsKvExporter(jdbcTemplate, writerFactory(0));
configure(exporter, null, null);
ReflectionTestUtils.invokeMethod(exporter, "init");
ReflectionTestUtils.invokeMethod(exporter, "validate");
assertThat(readExport()).extracting(row -> ((Number) row.get("ts")).longValue())
.containsExactlyInAnyOrder(OCT_31_23_58 + 60000, NOV_1, NOV_1 + 60000);
assertThatThrownBy(exporter::run).hasRootCauseInstanceOf(JsonProcessingException.class);
assertThat(storage.listFiles(TS_KV_FILES)).isEmpty();
}
@Test
@ -127,7 +179,7 @@ class PostgresTsKvExporterTest {
assertThatThrownBy(() -> exporter(null, null).run())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("1 time-series keys failed to export");
assertThat(storage.listFiles(Pattern.compile("ts_kv(_\\d+|_manifest)?"))).isEmpty();
assertThat(storage.listFiles(TS_KV_FILES)).isEmpty();
}
@Test
@ -135,7 +187,7 @@ class PostgresTsKvExporterTest {
writeLatest(latest(DEVICE, "temperature"));
try (HikariDataSource dataSource = new HikariDataSource()) {
dataSource.setMaximumPoolSize(4);
PostgresTsKvExporter exporter = new PostgresTsKvExporter(new JdbcTemplate(dataSource), writerFactory());
PostgresTsKvExporter exporter = new PostgresTsKvExporter(new JdbcTemplate(dataSource), writerFactory(1));
configure(exporter, null, null);
assertThatThrownBy(() -> ReflectionTestUtils.invokeMethod(exporter, "validate"))
@ -145,7 +197,7 @@ class PostgresTsKvExporterTest {
}
private PostgresTsKvExporter exporter(Long startTs, Long endTs) {
PostgresTsKvExporter exporter = new PostgresTsKvExporter(jdbcTemplate, writerFactory());
PostgresTsKvExporter exporter = new PostgresTsKvExporter(jdbcTemplate, writerFactory(1));
configure(exporter, startTs, endTs);
ReflectionTestUtils.invokeMethod(exporter, "init");
ReflectionTestUtils.invokeMethod(exporter, "validate");
@ -159,6 +211,7 @@ class PostgresTsKvExporterTest {
ReflectionTestUtils.setField(exporter, "partitioningName", "MONTHS");
// pages of 2 rows exercise the keyset pagination
ReflectionTestUtils.setField(exporter, "batchSize", 2);
ReflectionTestUtils.setField(exporter, "maxRetries", 3);
ReflectionTestUtils.setField(exporter, "startTs", startTs);
ReflectionTestUtils.setField(exporter, "endTs", endTs);
ReflectionTestUtils.setField(exporter, "postgresExportEnabled", false);
@ -167,9 +220,9 @@ class PostgresTsKvExporterTest {
ReflectionTestUtils.setField(exporter, "skippedTables", Set.of());
}
private TsKvWriterFactory writerFactory() {
private TsKvWriterFactory writerFactory(long maxFileSizeMb) {
TsKvWriterFactory factory = new TsKvWriterFactory(storage);
ReflectionTestUtils.setField(factory, "maxFileSizeMb", 1L);
ReflectionTestUtils.setField(factory, "maxFileSizeMb", maxFileSizeMb);
return factory;
}
@ -211,4 +264,27 @@ class PostgresTsKvExporterTest {
return rows.stream().filter(row -> key.equals(row.get("key"))).map(row -> ((Number) row.get("partition")).longValue()).toList();
}
// Fails ts_kv queries chosen by their number, counted from 1
private static class FailingJdbcTemplate extends JdbcTemplate {
final AtomicInteger tsKvQueries = new AtomicInteger();
volatile IntFunction<RuntimeException> failure = call -> null;
FailingJdbcTemplate(DataSource dataSource) {
super(dataSource);
}
@Override
public <T> List<T> query(String sql, RowMapper<T> rowMapper, Object... args) {
if (sql.contains(" FROM ts_kv ")) {
RuntimeException e = failure.apply(tsKvQueries.incrementAndGet());
if (e != null) {
throw e;
}
}
return super.query(sql, rowMapper, args);
}
}
}

15
migrator/src/test/java/org/thingsboard/migrator/service/tenant/importing/CassandraTsKvImporterTest.java

@ -87,6 +87,21 @@ class CassandraTsKvImporterTest {
assertThat(importedTs()).isEqualTo(LongStream.range(0, 3_000).boxed().collect(Collectors.toSet()));
}
@Test
void failedInsertStopsReadingTheFile() throws Exception {
TsKvWriter writer = new TsKvWriter(storage, 0);
for (long ts = 0; ts < 20_000; ts++) {
writer.write(row(ts, "long_v", ts));
}
writer.finish();
failingTs = 100;
CassandraTsKvImporter importer = importer(0);
assertThatThrownBy(importer::run).hasMessageContaining("CASSANDRA_IMPORT_TS_KV_SKIP_LINES=100");
// rows read ahead are bounded by the executor queue
assertThat((long) ReflectionTestUtils.getField(importer, "nextPosition")).isLessThan(20_000);
}
@Test
void truncatedFileStopsImportWithResumePosition() throws Exception {
List<TsKvFiles.Part> parts = writeExport(3_000);

21
migrator/src/test/java/org/thingsboard/migrator/utils/TsKvWriterTest.java

@ -5,7 +5,9 @@ package org.thingsboard.migrator.utils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.mockito.Mockito;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Path;
@ -18,6 +20,7 @@ import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@ -142,6 +145,24 @@ class TsKvWriterTest {
assertThatThrownBy(() -> TsKvFiles.listForImport(storage)).hasMessageContaining("No time-series files");
}
@Test
void abortDeletesFilesThatFailToClose() throws IOException {
Storage failingStorage = Mockito.spy(storage);
Mockito.doAnswer(invocation -> new FilterWriter((Writer) invocation.callRealMethod()) {
@Override
public void close() throws IOException {
super.close();
throw new IOException("No space left on device");
}
}).when(failingStorage).newWriter(Mockito.anyString(), Mockito.any(AtomicLong.class));
TsKvWriter writer = new TsKvWriter(failingStorage, MAX_FILE_SIZE);
writer.write(row(1));
writer.abort();
assertThat(storage.listFiles(TsKvFiles.ALL)).isEmpty();
}
@Test
void filesWithoutManifestAreRejected() throws IOException {
// An export that crashed before finish()

Loading…
Cancel
Save