Browse Source

fix(migrator): address review of the ts_kv export

- Failed or aborted exports can't be imported: abort() deletes all
  time-series files (also the legacy ts_kv.gz), worker Throwables are
  counted as failed keys, and the Cassandra exporter now fails like the
  PostgreSQL one instead of writing a manifest for a partial export.
- The import rejects a working directory with both ts_kv_manifest.gz and
  ts_kv.gz, which are files of two different exports.
- Each worker thread compresses into its own files, rolled over on the
  compressed bytes written, so gzip no longer serializes the export.
- Key ids are resolved by name in key_dictionary, so a reused
  ts_kv_latest.gz from an earlier export can't map to the wrong key.
- Timestamps near the long bounds are clamped instead of failing the key;
  the first page is inclusive instead of using startTs - 1.
- MigrationService stops its workers when start() throws, so the JVM exits
  instead of hanging.
- Validated at startup: DATABASE_MAX_POOL_SIZE > PARALLELISM_LEVEL,
  Cassandra export start/end filters, TS_KV_EXPORT_MAX_FILE_SIZE_MB >= 0
  (new TsKvWriterFactory).
- The query delay applies after every ts_kv query; NaN and Infinity
  doubles are imported; part names use Locale.ROOT.
- Tests: PostgreSQL container test for PostgresTsKvExporter, importer
  skip_lines across files and non-finite doubles, writer abort/crash/mixed
  export cases. README: compatibility with older importers, keys without
  latest values, measured cost per key by partition count.
pull/16897/head
dealnat 2 weeks ago
parent
commit
9bd089c3c8
  1. 15
      migrator/pom.xml
  2. 10
      migrator/src/main/java/org/thingsboard/migrator/MigrationService.java
  3. 37
      migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporter.java
  4. 50
      migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporter.java
  5. 5
      migrator/src/main/java/org/thingsboard/migrator/service/tenant/importing/CassandraTsKvImporter.java
  6. 48
      migrator/src/main/java/org/thingsboard/migrator/utils/Storage.java
  7. 8
      migrator/src/main/java/org/thingsboard/migrator/utils/TsKvFiles.java
  8. 123
      migrator/src/main/java/org/thingsboard/migrator/utils/TsKvWriter.java
  9. 32
      migrator/src/main/java/org/thingsboard/migrator/utils/TsKvWriterFactory.java
  10. 13
      migrator/src/main/java/org/thingsboard/migrator/utils/TsPartitioning.java
  11. 15
      migrator/src/main/resources/README.md
  12. 5
      migrator/src/main/resources/application.yml
  13. 214
      migrator/src/test/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporterTest.java
  14. 103
      migrator/src/test/java/org/thingsboard/migrator/service/tenant/importing/CassandraTsKvImporterTest.java
  15. 21
      migrator/src/test/java/org/thingsboard/migrator/utils/TestStorage.java
  16. 77
      migrator/src/test/java/org/thingsboard/migrator/utils/TsKvWriterTest.java
  17. 9
      migrator/src/test/java/org/thingsboard/migrator/utils/TsPartitioningTest.java
  18. 2
      msa/migrator/README.md

15
migrator/pom.xml

@ -81,6 +81,21 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>software.xdev</groupId>
<artifactId>testcontainers-junit4-mock</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>

10
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<String, Long> total = new ConcurrentHashMap<>();
protected final ConcurrentMap<String, AtomicLong> 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);

37
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();
}

50
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<Table> 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<Object> args = new ArrayList<>(List.of(tsKey.entityId(), tsKey.keyName(), 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);
}, args.toArray());
for (TsRow row : rows) {
if (row.ts() < partitionTs || row.ts() >= nextPartitionTs) {
@ -145,13 +161,14 @@ public class PostgresTsKvExporter extends MigrationService {
reportProcessed(NAME, data);
}
if (delayBetweenQueries > 0) {
TimeUnit.MILLISECONDS.sleep(delayBetweenQueries);
}
if (rows.size() < batchSize) {
return;
}
query = nextPageQuery;
cursor = rows.get(rows.size() - 1).ts();
if (delayBetweenQueries > 0) {
TimeUnit.MILLISECONDS.sleep(delayBetweenQueries);
}
}
}
@ -166,11 +183,10 @@ public class PostgresTsKvExporter extends MigrationService {
writer.finish();
}
private record TsKey(String entityType, UUID entityId, int keyId, String keyName) {
private record TsKey(String entityType, UUID entityId, String keyName) {
static TsKey of(Map<String, Object> latestKvRow) {
return new TsKey((String) latestKvRow.get("table_name"), (UUID) latestKvRow.get("entity_id"),
((Number) latestKvRow.get("key")).intValue(), (String) latestKvRow.get("key_name"));
return new TsKey((String) latestKvRow.get("table_name"), (UUID) latestKvRow.get("entity_id"), (String) latestKvRow.get("key_name"));
}
}

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

@ -101,7 +101,10 @@ public class CassandraTsKvImporter extends MigrationService {
row.put("long_v", ((Number) longV).longValue());
}
Object dblV = row.get("dbl_v");
if (dblV != null && !(dblV instanceof Double)) {
if (dblV instanceof String string) {
// NaN and Infinity are exported as strings
row.put("dbl_v", Double.parseDouble(string));
} else if (dblV != null && !(dblV instanceof Double)) {
row.put("dbl_v", ((Number) dblV).doubleValue());
}
Number ts = (Number) row.get("ts");

48
migrator/src/main/java/org/thingsboard/migrator/utils/Storage.java

@ -22,6 +22,7 @@ import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
@ -35,6 +36,7 @@ import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Stream;
@ -66,19 +68,30 @@ public class Storage {
Files.createDirectories(workingDir);
}
public void newFile(String name) throws IOException {
// Synchronized: time-series exporters create files from worker threads
public synchronized void newFile(String name) throws IOException {
Path file = getPath(name);
Files.deleteIfExists(file);
Files.createFile(file);
createdFiles.add(file);
}
@SneakyThrows
public Writer newWriter(String file) {
return newWriter(file, null);
}
/**
* @param compressedSize if not null, tracks the number of compressed bytes the gzip stream has emitted
*/
@SneakyThrows
public Writer newWriter(String file, AtomicLong compressedSize) {
// The raw file
FileOutputStream fos = new FileOutputStream(getPath(file).toFile());
// Reducing disk IOPS
BufferedOutputStream bos = new BufferedOutputStream(fos, 128 * 1024);
OutputStream bos = new BufferedOutputStream(fos, 128 * 1024);
if (compressedSize != null) {
bos = new CountingOutputStream(bos, compressedSize);
}
// Giving GZIP its own buffer allows the compression engine to work on large chunks of data at once.
GZIPOutputStream gzos = new GZIPOutputStream(bos, 128 * 1024);
// The UTF-8 Writer
@ -118,8 +131,10 @@ public class Storage {
return Files.size(getPath(file));
}
public void delete(String file) throws IOException {
Files.deleteIfExists(getPath(file));
public synchronized void delete(String file) throws IOException {
Path path = getPath(file);
Files.deleteIfExists(path);
createdFiles.remove(path);
}
// Names without the .gz extension, sorted
@ -208,6 +223,29 @@ public class Storage {
return new BufferedReader(new InputStreamReader(new GZIPInputStream(fileInputStream)));
}
private static class CountingOutputStream extends FilterOutputStream {
private final AtomicLong count;
CountingOutputStream(OutputStream out, AtomicLong count) {
super(out);
this.count = count;
}
@Override
public void write(int b) throws IOException {
out.write(b);
count.incrementAndGet();
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
count.addAndGet(len);
}
}
@SneakyThrows
private String toJson(Object o) {
return jsonMapper.writeValueAsString(o);

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

@ -7,6 +7,7 @@ import java.io.Writer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
@ -31,7 +32,7 @@ public final class TsKvFiles {
public record Part(String name, Long rows) {}
static String partName(int index) {
return String.format("%s_%05d", NAME, index);
return String.format(Locale.ROOT, "%s_%05d", NAME, index);
}
static void writeManifest(Storage storage, List<Part> parts) throws IOException {
@ -48,6 +49,11 @@ public final class TsKvFiles {
public static List<Part> listForImport(Storage storage) throws IOException {
if (storage.exists(MANIFEST)) {
// Extracting data.tar doesn't remove files of an earlier import in the same directory
if (storage.exists(NAME)) {
throw new IllegalStateException("Both " + MANIFEST + ".gz and " + NAME + ".gz found in the working directory, " +
"one of them is left from another export. Remove the " + NAME + "*.gz files and extract the export again");
}
List<Part> parts = new ArrayList<>();
storage.readAndProcess(MANIFEST, row -> parts.add(new Part((String) row.get("file"), ((Number) row.get("rows")).longValue())));
List<String> missing = parts.stream().map(Part::name).filter(name -> !storage.exists(name)).toList();

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

@ -5,25 +5,30 @@ package org.thingsboard.migrator.utils;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* Thread-safe writer of exported time-series rows in the {@link TsKvFiles} layout.
* With a positive max file size, starts the next file once the current one reaches it on disk.
* The size is checked after the gzip and file buffers are flushed, so a file may exceed it by a few hundred KB.
* Writer of exported time-series rows in the {@link TsKvFiles} layout, safe for concurrent use.
* With a positive max file size, each thread writes its own files, so compression runs in parallel,
* and starts the next file once the compressed size reaches the limit (exceeded by up to the gzip buffers, tens of KB).
* Otherwise all threads write a single legacy ts_kv.gz.
*/
public class TsKvWriter {
private static final int SIZE_CHECK_INTERVAL_ROWS = 1000;
private final Storage storage;
private final long maxFileSize;
private final List<TsKvFiles.Part> parts = new ArrayList<>();
private String fileName;
private Writer writer;
private long rows;
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;
/**
* @param maxFileSize in bytes; 0 or less writes a single legacy ts_kv.gz without a manifest
@ -32,55 +37,97 @@ public class TsKvWriter {
this.storage = storage;
this.maxFileSize = maxFileSize;
// Leftovers of a previous export would otherwise be picked up by the importer
for (String file : storage.listFiles(TsKvFiles.ALL)) {
storage.delete(file);
}
openFile();
deleteFiles();
legacyFile = maxFileSize > 0 ? null : new File(TsKvFiles.NAME, 0);
}
public void write(Map<String, Object> row) throws IOException {
String line = storage.toLine(row);
synchronized (this) {
if (isRolling() && rows > 0 && rows % SIZE_CHECK_INTERVAL_ROWS == 0 && storage.size(fileName) >= maxFileSize) {
closeFile();
openFile();
if (legacyFile != null) {
synchronized (legacyFile) {
legacyFile.write(line);
}
writer.write(line);
rows++;
return;
}
File 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);
openParts.add(part);
threadPart.set(part);
}
part.write(line);
}
/**
* Closes the output and writes the manifest, which marks the export as complete.
* Closes all files and writes the manifest, which marks the export as complete.
* Must be called after all writing threads are done.
*/
public synchronized void finish() throws IOException {
closeFile();
if (isRolling()) {
TsKvFiles.writeManifest(storage, parts);
public void finish() throws IOException {
if (legacyFile != null) {
legacyFile.writer.close();
return;
}
for (File part : List.copyOf(openParts)) {
close(part);
}
List<TsKvFiles.Part> parts = closedParts.stream()
.sorted(Comparator.comparingInt(part -> part.index))
.map(part -> new TsKvFiles.Part(part.name, part.rows))
.toList();
TsKvFiles.writeManifest(storage, parts);
}
/**
* Closes the output without the manifest, so the importer rejects the incomplete export.
* Closes and deletes all files of this export, so that the importer can't load it.
* Must be called after all writing threads are done.
*/
public synchronized void abort() throws IOException {
writer.close();
public void abort() throws IOException {
if (legacyFile != null) {
legacyFile.writer.close();
}
for (File part : List.copyOf(openParts)) {
close(part);
}
deleteFiles();
}
private boolean isRolling() {
return maxFileSize > 0;
private void close(File part) throws IOException {
part.writer.close();
openParts.remove(part);
closedParts.add(part);
}
private void openFile() throws IOException {
fileName = isRolling() ? TsKvFiles.partName(parts.size() + 1) : TsKvFiles.NAME;
storage.newFile(fileName);
writer = storage.newWriter(fileName);
rows = 0;
private void deleteFiles() throws IOException {
for (String file : storage.listFiles(TsKvFiles.ALL)) {
storage.delete(file);
}
}
private void closeFile() throws IOException {
writer.close();
parts.add(new TsKvFiles.Part(fileName, rows));
// Written by one thread at a time
private class File {
final String name;
final int index;
final AtomicLong compressedSize = new AtomicLong();
final Writer writer;
long rows;
File(String name, int index) throws IOException {
this.name = name;
this.index = index;
storage.newFile(name);
writer = storage.newWriter(name, compressedSize);
}
void write(String line) throws IOException {
writer.write(line);
rows++;
}
}
}

32
migrator/src/main/java/org/thingsboard/migrator/utils/TsKvWriterFactory.java

@ -0,0 +1,32 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.migrator.utils;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
@RequiredArgsConstructor
public class TsKvWriterFactory {
private final Storage storage;
@Value("${export.ts_kv.max_file_size_mb}")
private long maxFileSizeMb;
@PostConstruct
private void validate() {
if (maxFileSizeMb < 0) {
throw new IllegalArgumentException("TS_KV_EXPORT_MAX_FILE_SIZE_MB must be 0 or positive, got " + maxFileSizeMb);
}
}
public TsKvWriter create() throws IOException {
return new TsKvWriter(storage, maxFileSizeMb * 1024 * 1024);
}
}

13
migrator/src/main/java/org/thingsboard/migrator/utils/TsPartitioning.java

@ -26,7 +26,7 @@ public enum TsPartitioning {
case YEARS -> time.truncatedTo(ChronoUnit.DAYS).withDayOfYear(1);
case INDEFINITE -> LocalDateTime.ofEpochSecond(0, 0, ZoneOffset.UTC);
};
return partition.toInstant(ZoneOffset.UTC).toEpochMilli();
return toEpochMilli(partition);
}
public long nextPartitionTs(long partitionTs) {
@ -42,7 +42,16 @@ public enum TsPartitioning {
case YEARS -> time.plusYears(1);
case INDEFINITE -> throw new IllegalStateException();
};
return next.toInstant(ZoneOffset.UTC).toEpochMilli();
return toEpochMilli(next);
}
// Clamped, so that a sentinel ts close to Long.MIN_VALUE/MAX_VALUE doesn't fail the export
private static long toEpochMilli(LocalDateTime time) {
try {
return time.toInstant(ZoneOffset.UTC).toEpochMilli();
} catch (ArithmeticException e) {
return time.getYear() < 1970 ? Long.MIN_VALUE : Long.MAX_VALUE;
}
}
public static TsPartitioning parse(String name) {

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

@ -41,13 +41,19 @@ POSTGRES_TS_EXPORT_PARTITIONING=MONTHS
```
- `POSTGRES_TS_EXPORT_PARTITIONING` must equal `TS_KV_PARTITIONING` of the target cluster. Otherwise the import succeeds, but the history is not readable.
- 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 saved with the "latest" processing strategy set to SKIP are not exported).
- If any key fails to export, the migrator exits with an error and `data.tar` is not created.
- 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.
- If any key fails to export, the migrator exits with an error, deletes the time-series files and doesn't create `data.tar`.
- `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.
Measured on PostgreSQL 18 with 12 threads: about 15000 keys/s with 36 monthly partitions, about 500 keys/s with 1096 daily ones.
Two-phase migration (full export at T1, then a time-series delta after devices are switched over):
- Use a separate `WORKING_DIRECTORY` for the delta, `data.tar` is overwritten otherwise.
- Set `POSTGRES_TS_EXPORT_FILTER_START_TS` to T1 minus a safety margin: `ts` is the device timestamp, so late-arriving data may have `ts` < T1. Importing overlapping points again is safe.
- Either keep `POSTGRES_EXPORT_ENABLED=true` (fresh key list; add non-entity tables to `SKIPPED_TABLES` to speed it up), or set `POSTGRES_EXPORT_ENABLED=false` and put `ts_kv_latest.gz` from the full export into the working directory.
Key ids are resolved by name in this database's `key_dictionary`, so the ids in that file don't matter.
- Import the delta with `POSTGRES_IMPORT_ENABLED=false`. Latest values (`ts_kv_latest`) of the target are not updated by it.
@ -75,8 +81,11 @@ CASSANDRA_KEYSPACE_NAME=thingsboard
Time-series files:
- Both time-series exports write `ts_kv_00001.gz`, `ts_kv_00002.gz`, ... of about `TS_KV_EXPORT_MAX_FILE_SIZE_MB` (default 256) each, and `ts_kv_manifest.gz` listing them with row counts.
Each worker thread compresses into its own files, so the last file of each thread is smaller.
The manifest is written last, so the import rejects files without it as an incomplete export.
- `TS_KV_EXPORT_MAX_FILE_SIZE_MB=0` writes a single `ts_kv.gz` instead, the format older migrator versions import. The import reads both formats.
- Older migrator versions can't import this format: they expect a single `ts_kv.gz`. For them, export with `TS_KV_EXPORT_MAX_FILE_SIZE_MB=0`.
The import reads both formats.
- Extract each export into an empty working directory. If files of two exports are mixed (both `ts_kv_manifest.gz` and `ts_kv.gz`), the import fails.
- `CASSANDRA_IMPORT_TS_KV_SKIP_LINES` counts rows across all files in order, like the processed counter in the import log. Fully skipped files are not read.
- `data.tar` is limited to about 2GB, use `ARCHIVE_RESULT=false` for larger exports and transfer the files as they are.
- For time-based slices instead of size-based ones, run exports with the `*_FILTER_START_TS` / `*_FILTER_END_TS` filters into separate working directories.

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

@ -16,7 +16,7 @@ export:
tenant_id: ${EXPORTED_TENANT_ID:}
ts_kv:
# Time-series history is split into ts_kv_00001.gz, ts_kv_00002.gz, ... of about this compressed size,
# listed in ts_kv_manifest.gz. 0 writes a single ts_kv.gz, the format of older migrator versions.
# listed in ts_kv_manifest.gz. Older migrator versions can't import it: 0 writes a single ts_kv.gz, the format they read.
max_file_size_mb: ${TS_KV_EXPORT_MAX_FILE_SIZE_MB:256}
postgres:
enabled: ${POSTGRES_EXPORT_ENABLED:true}
@ -98,7 +98,8 @@ spring:
username: ${DATABASE_USERNAME:postgres}
password: ${DATABASE_PASSWORD:postgres}
hikari:
# Keep above parallelism_level: worker threads and the caller thread query in parallel.
# Must be greater than parallelism_level: worker threads and the caller thread query in parallel.
# The PostgreSQL time-series export checks it at startup.
maximum-pool-size: ${DATABASE_MAX_POOL_SIZE:16}
cassandra:

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

@ -0,0 +1,214 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.migrator.service.tenant.exporting;
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.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.util.ReflectionTestUtils;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
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 org.thingsboard.migrator.utils.TsPartitioning;
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.Set;
import java.util.UUID;
import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Testcontainers(disabledWithoutDocker = true)
class PostgresTsKvExporterTest {
@Container
private static final PostgreSQLContainer<?> POSTGRES = new PostgreSQLContainer<>("postgres:18");
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");
private static final long OCT_31_23_58 = 1761955080000L;
private static final long NOV_1 = 1761955200000L;
private static final long OCT_1 = 1759276800000L;
private static JdbcTemplate jdbcTemplate;
@TempDir
Path workingDir;
private Storage storage;
@BeforeAll
static void createDatabase() {
jdbcTemplate = new JdbcTemplate(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),
long_v bigint, dbl_v double precision, json_v json, CONSTRAINT ts_kv_pkey PRIMARY KEY (entity_id, key, ts)) PARTITION BY RANGE (ts);
CREATE TABLE ts_kv_2025_10 PARTITION OF ts_kv FOR VALUES FROM (1759276800000) TO (1761955200000);
CREATE TABLE ts_kv_2025_11 PARTITION OF ts_kv FOR VALUES FROM (1761955200000) TO (1764547200000);
CREATE TABLE ts_kv_default PARTITION OF ts_kv DEFAULT;
-- ids differ from the ones in ts_kv_latest.gz written by the tests
INSERT INTO key_dictionary (key) VALUES ('unused1'), ('unused2'), ('temperature'), ('status'), ('active'), ('counter'), ('payload'), ('orphan');
CREATE FUNCTION k(name text) RETURNS int AS $$ SELECT key_id FROM key_dictionary WHERE key = name $$ LANGUAGE sql;
""");
// 5 points crossing the October/November partitions, with non-finite values
jdbcTemplate.update("INSERT INTO ts_kv (entity_id, key, ts, dbl_v) SELECT ?, k('temperature'), ? + g * 60000, " +
"(ARRAY['1.5', 'NaN', 'Infinity', '-Infinity', '2.5']::float8[])[g + 1] FROM generate_series(0, 4) g", DEVICE, OCT_31_23_58);
// timestamps at the long bounds land in the DEFAULT partition
jdbcTemplate.update("INSERT INTO ts_kv (entity_id, key, ts, dbl_v) VALUES (?, k('temperature'), ?, 0), (?, k('temperature'), ?, 0)",
DEVICE, Long.MIN_VALUE, DEVICE, Long.MAX_VALUE);
jdbcTemplate.update("INSERT INTO ts_kv (entity_id, key, ts, str_v) VALUES (?, k('status'), ?, 'ünïcödé \"q\"')", DEVICE, NOV_1);
jdbcTemplate.update("INSERT INTO ts_kv (entity_id, key, ts, bool_v) VALUES (?, k('active'), ?, true)", DEVICE, NOV_1);
jdbcTemplate.update("INSERT INTO ts_kv (entity_id, key, ts, long_v) VALUES (?, k('counter'), ?, 9000000000)", DEVICE, NOV_1);
jdbcTemplate.update("INSERT INTO ts_kv (entity_id, key, ts, json_v) VALUES (?, k('payload'), ?, '{\"a\":1}')", DEVICE, NOV_1);
// not exported: no ts_kv_latest row
jdbcTemplate.update("INSERT INTO ts_kv (entity_id, key, ts, long_v) VALUES (?, k('orphan'), ?, 1)", DEVICE, NOV_1);
jdbcTemplate.update("INSERT INTO ts_kv (entity_id, key, ts, dbl_v) VALUES (?, k('temperature'), ?, 1)", OTHER_DEVICE, NOV_1);
}
@BeforeEach
void setUp() {
storage = TestStorage.create(workingDir, "TENANT_DATA_EXPORT");
}
@Test
void exportsHistoryOfLatestKeys() throws Exception {
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();
List<Map<String, Object>> rows = readExport();
assertThat(rows).hasSize(11);
assertThat(rows).allSatisfy(row -> {
assertThat(row).containsEntry("entity_type", "DEVICE").containsEntry("entity_id", DEVICE);
assertThat(List.copyOf(row.keySet()).subList(0, 5)).containsExactly("entity_type", "entity_id", "partition", "key", "ts");
});
assertThat(values(rows, "temperature", "dbl_v")).containsExactly(0.0, 1.5, "NaN", "Infinity", "-Infinity", 2.5, 0.0);
assertThat(partitions(rows, "temperature")).containsExactly(Long.MIN_VALUE, OCT_1, OCT_1, NOV_1, NOV_1, NOV_1,
TsPartitioning.MONTHS.toPartitionTs(Long.MAX_VALUE));
assertThat(values(rows, "status", "str_v")).containsExactly("ünïcödé \"q\"");
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}");
}
@Test
void filterBoundsAreInclusive() throws Exception {
writeLatest(latest(DEVICE, "temperature"));
exporter(OCT_31_23_58 + 60000, NOV_1 + 60000).run();
assertThat(readExport()).extracting(row -> ((Number) row.get("ts")).longValue())
.containsExactlyInAnyOrder(OCT_31_23_58 + 60000, NOV_1, NOV_1 + 60000);
}
@Test
void failedKeyAbortsExport() throws IOException {
Map<String, Object> broken = latest(DEVICE, "status");
broken.put("entity_id", "not-a-uuid");
writeLatest(latest(DEVICE, "temperature"), broken);
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();
}
@Test
void poolSmallerThanParallelismIsRejected() throws IOException {
writeLatest(latest(DEVICE, "temperature"));
try (HikariDataSource dataSource = new HikariDataSource()) {
dataSource.setMaximumPoolSize(4);
PostgresTsKvExporter exporter = new PostgresTsKvExporter(new JdbcTemplate(dataSource), writerFactory());
configure(exporter, null, null);
assertThatThrownBy(() -> ReflectionTestUtils.invokeMethod(exporter, "validate"))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("DATABASE_MAX_POOL_SIZE (4) must be greater than PARALLELISM_LEVEL (4)");
}
}
private PostgresTsKvExporter exporter(Long startTs, Long endTs) {
PostgresTsKvExporter exporter = new PostgresTsKvExporter(jdbcTemplate, writerFactory());
configure(exporter, startTs, endTs);
ReflectionTestUtils.invokeMethod(exporter, "init");
ReflectionTestUtils.invokeMethod(exporter, "validate");
return exporter;
}
private void configure(PostgresTsKvExporter exporter, Long startTs, Long endTs) {
ReflectionTestUtils.setField(exporter, "storage", storage);
ReflectionTestUtils.setField(exporter, "parallelismLevel", 4);
ReflectionTestUtils.setField(exporter, "statsPrintInterval", 1_000);
ReflectionTestUtils.setField(exporter, "partitioningName", "MONTHS");
// pages of 2 rows exercise the keyset pagination
ReflectionTestUtils.setField(exporter, "batchSize", 2);
ReflectionTestUtils.setField(exporter, "startTs", startTs);
ReflectionTestUtils.setField(exporter, "endTs", endTs);
ReflectionTestUtils.setField(exporter, "postgresExportEnabled", false);
ReflectionTestUtils.setField(exporter, "delayBetweenQueries", 0);
ReflectionTestUtils.setField(exporter, "cassandraExportEnabled", false);
ReflectionTestUtils.setField(exporter, "skippedTables", Set.of());
}
private TsKvWriterFactory writerFactory() {
TsKvWriterFactory factory = new TsKvWriterFactory(storage);
ReflectionTestUtils.setField(factory, "maxFileSizeMb", 1L);
return factory;
}
// As written by PostgresTenantDataExporter; the key ids are wrong on purpose
private static Map<String, Object> latest(UUID entityId, String keyName) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("table_name", "DEVICE");
row.put("entity_id", entityId);
row.put("key", 1000);
row.put("ts", NOV_1);
row.put("key_name", keyName);
return row;
}
@SafeVarargs
private void writeLatest(Map<String, Object>... rows) throws IOException {
storage.newFile(CassandraTsKvExporter.LATEST_KV);
try (Writer writer = storage.newWriter(CassandraTsKvExporter.LATEST_KV)) {
for (Map<String, Object> row : rows) {
storage.addToFile(writer, row);
}
}
}
private List<Map<String, Object>> readExport() throws IOException {
List<Map<String, Object>> rows = new ArrayList<>();
for (TsKvFiles.Part part : TsKvFiles.listForImport(storage)) {
storage.readAndProcess(part.name(), rows::add);
}
rows.sort((a, b) -> Long.compare(((Number) a.get("ts")).longValue(), ((Number) b.get("ts")).longValue()));
return rows;
}
private static List<Object> values(List<Map<String, Object>> rows, String key, String column) {
return rows.stream().filter(row -> key.equals(row.get("key"))).map(row -> row.get(column)).toList();
}
private static List<Long> partitions(List<Map<String, Object>> rows, String key) {
return rows.stream().filter(row -> key.equals(row.get("key"))).map(row -> ((Number) row.get("partition")).longValue()).toList();
}
}

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

@ -0,0 +1,103 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.migrator.service.tenant.importing;
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.TsKvWriter;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.stream.LongStream;
import static org.assertj.core.api.Assertions.assertThat;
class CassandraTsKvImporterTest {
private static final UUID ENTITY_ID = UUID.randomUUID();
@TempDir
Path workingDir;
private Storage storage;
private final Queue<Object[]> tsKvInserts = new ConcurrentLinkedQueue<>();
private CassandraService cassandraService;
@BeforeEach
void setUp() {
storage = TestStorage.create(workingDir, "TENANT_DATA_IMPORT");
cassandraService = Mockito.mock(CassandraService.class, invocation -> {
if (invocation.getArgument(0) instanceof String query && query.startsWith("INSERT INTO ts_kv_cf ")) {
tsKvInserts.add((Object[]) invocation.getRawArguments()[1]);
}
return null;
});
}
@Test
void skipLinesCountsAcrossFiles() throws Exception {
TsKvWriter writer = new TsKvWriter(storage, 20 * 1024);
for (long ts = 0; ts < 3_000; ts++) {
// poorly compressible, so that the files roll over
writer.write(row(ts, "str_v", UUID.randomUUID().toString()));
}
writer.finish();
List<TsKvFiles.Part> parts = TsKvFiles.listForImport(storage);
assertThat(parts).hasSizeGreaterThan(2);
long skip = parts.get(0).rows() + parts.get(1).rows() + 10;
importer(skip).run();
assertThat(tsKvInserts).extracting(args -> ((Number) args[4]).longValue())
.containsExactlyInAnyOrderElementsOf(LongStream.range(skip, 3_000).boxed().toList());
}
@Test
void importsNonFiniteDoubles() throws Exception {
TsKvWriter writer = new TsKvWriter(storage, 1024 * 1024);
writer.write(row(1, "dbl_v", Double.NaN));
writer.write(row(2, "dbl_v", Double.POSITIVE_INFINITY));
writer.write(row(3, "dbl_v", Double.NEGATIVE_INFINITY));
writer.write(row(4, "dbl_v", 2.5));
writer.finish();
importer(0).run();
assertThat(tsKvInserts).extracting(args -> args[5])
.containsExactlyInAnyOrder(Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 2.5);
}
private CassandraTsKvImporter importer(long skipLines) {
CassandraTsKvImporter importer = new CassandraTsKvImporter(storage, cassandraService);
ReflectionTestUtils.setField(importer, "tsKvTtlDays", 0);
ReflectionTestUtils.setField(importer, "tsKvSkipLines", skipLines);
ReflectionTestUtils.setField(importer, "parallelismLevel", 4);
ReflectionTestUtils.setField(importer, "statsPrintInterval", 1_000);
ReflectionTestUtils.invokeMethod(importer, "init");
return importer;
}
private static Map<String, Object> row(long ts, String column, Object value) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("entity_type", "DEVICE");
row.put("entity_id", ENTITY_ID);
row.put("partition", 0L);
row.put("key", "temperature");
row.put("ts", ts);
row.put(column, value);
return row;
}
}

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

@ -0,0 +1,21 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.migrator.utils;
import org.springframework.test.util.ReflectionTestUtils;
import java.nio.file.Path;
public final class TestStorage {
private TestStorage() {}
public static Storage create(Path workingDir, String mode) {
Storage storage = new Storage();
ReflectionTestUtils.setField(storage, "workingDir", workingDir);
ReflectionTestUtils.setField(storage, "mode", mode);
ReflectionTestUtils.setField(storage, "archiveResult", false);
return storage;
}
}

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

@ -5,13 +5,14 @@ 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.springframework.test.util.ReflectionTestUtils;
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.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
@ -32,10 +33,7 @@ class TsKvWriterTest {
@BeforeEach
void setUp() {
storage = new Storage();
ReflectionTestUtils.setField(storage, "workingDir", workingDir);
ReflectionTestUtils.setField(storage, "mode", "TENANT_DATA_EXPORT");
ReflectionTestUtils.setField(storage, "archiveResult", false);
storage = TestStorage.create(workingDir, "TENANT_DATA_EXPORT");
}
@Test
@ -51,7 +49,7 @@ class TsKvWriterTest {
assertThat(parts).extracting(TsKvFiles.Part::name).startsWith("ts_kv_00001", "ts_kv_00002");
assertThat(parts.stream().mapToLong(TsKvFiles.Part::rows).sum()).isEqualTo(20_000);
for (TsKvFiles.Part part : parts.subList(0, parts.size() - 1)) {
assertThat(storage.size(part.name())).isGreaterThanOrEqualTo(MAX_FILE_SIZE);
assertThat(storage.size(part.name())).isBetween(MAX_FILE_SIZE, MAX_FILE_SIZE + 64 * 1024);
}
List<Long> read = new ArrayList<>();
@ -64,7 +62,7 @@ class TsKvWriterTest {
}
@Test
void concurrentWritesKeepLinesIntact() throws Exception {
void eachThreadWritesItsOwnFiles() throws Exception {
TsKvWriter writer = new TsKvWriter(storage, MAX_FILE_SIZE);
ExecutorService executor = Executors.newFixedThreadPool(8);
List<Future<?>> futures = new ArrayList<>();
@ -83,19 +81,26 @@ class TsKvWriterTest {
executor.shutdown();
writer.finish();
List<TsKvFiles.Part> parts = TsKvFiles.listForImport(storage);
assertThat(parts).extracting(TsKvFiles.Part::name).isSorted();
List<Long> read = new ArrayList<>();
for (TsKvFiles.Part part : TsKvFiles.listForImport(storage)) {
read.addAll(readTs(part.name()));
for (TsKvFiles.Part part : parts) {
List<Long> partRows = readTs(part.name());
assertThat(partRows).hasSize(part.rows().intValue());
// rows of a file come from one thread, in its order
assertThat(partRows).isSorted();
assertThat(partRows.get(partRows.size() - 1) / 5_000).isEqualTo(partRows.get(0) / 5_000);
read.addAll(partRows);
}
assertThat(read).hasSize(40_000).doesNotHaveDuplicates();
}
@Test
void emptyExportHasManifestWithEmptyFile() throws IOException {
void emptyExportHasEmptyManifest() throws IOException {
TsKvWriter writer = new TsKvWriter(storage, MAX_FILE_SIZE);
writer.finish();
assertThat(TsKvFiles.listForImport(storage)).containsExactly(new TsKvFiles.Part("ts_kv_00001", 0L));
assertThat(TsKvFiles.listForImport(storage)).isEmpty();
}
@Test
@ -116,16 +121,53 @@ class TsKvWriterTest {
}
@Test
void abortedExportIsRejectedByImport() throws IOException {
void abortDeletesAllFiles() throws IOException {
TsKvWriter writer = new TsKvWriter(storage, MAX_FILE_SIZE);
for (int i = 0; i < 5_000; i++) {
writer.write(row(i));
}
writer.abort();
assertThat(storage.listFiles(TsKvFiles.ALL)).isEmpty();
assertThatThrownBy(() -> TsKvFiles.listForImport(storage)).hasMessageContaining("No time-series files");
}
@Test
void abortDeletesLegacyFile() throws IOException {
TsKvWriter writer = new TsKvWriter(storage, 0);
writer.write(row(1));
writer.abort();
assertThat(storage.listFiles(TsKvFiles.ALL)).isEmpty();
assertThatThrownBy(() -> TsKvFiles.listForImport(storage)).hasMessageContaining("No time-series files");
}
@Test
void filesWithoutManifestAreRejected() throws IOException {
// An export that crashed before finish()
TsKvWriter writer = new TsKvWriter(storage, MAX_FILE_SIZE);
writer.write(row(1));
assertThatThrownBy(() -> TsKvFiles.listForImport(storage))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("didn't complete");
}
@Test
void manifestAndLegacyFileTogetherAreRejected() throws IOException {
TsKvWriter writer = new TsKvWriter(storage, MAX_FILE_SIZE);
writer.write(row(1));
writer.finish();
storage.newFile(TsKvFiles.NAME);
try (Writer legacy = storage.newWriter(TsKvFiles.NAME)) {
storage.addToFile(legacy, row(2));
}
assertThatThrownBy(() -> TsKvFiles.listForImport(storage))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("left from another export");
}
@Test
void missingFileListedInManifestIsRejected() throws IOException {
TsKvWriter writer = new TsKvWriter(storage, MAX_FILE_SIZE);
@ -145,6 +187,17 @@ class TsKvWriterTest {
.hasMessageContaining("No time-series files");
}
@Test
void partNamesUseAsciiDigitsInAnyLocale() {
Locale defaultLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.forLanguageTag("th-TH-u-nu-thai"));
assertThat(TsKvFiles.partName(12)).isEqualTo("ts_kv_00012");
} finally {
Locale.setDefault(defaultLocale);
}
}
private List<Long> readTs(String file) throws IOException {
List<Long> ts = new ArrayList<>();
storage.readAndProcess(file, row -> ts.add(((Number) row.get("ts")).longValue()));

9
migrator/src/test/java/org/thingsboard/migrator/utils/TsPartitioningTest.java

@ -46,6 +46,15 @@ class TsPartitioningTest {
assertThat(TsPartitioning.INDEFINITE.nextPartitionTs(0)).isEqualTo(Long.MAX_VALUE);
}
@Test
void timestampsCloseToLongBoundsAreClamped() {
assertThat(TsPartitioning.MONTHS.toPartitionTs(Long.MIN_VALUE)).isEqualTo(Long.MIN_VALUE);
long lastPartition = TsPartitioning.MONTHS.toPartitionTs(Long.MAX_VALUE);
assertThat(lastPartition).isLessThan(Long.MAX_VALUE);
assertThat(TsPartitioning.MONTHS.nextPartitionTs(lastPartition)).isEqualTo(Long.MAX_VALUE);
assertThat(TsPartitioning.YEARS.nextPartitionTs(TsPartitioning.YEARS.toPartitionTs(Long.MAX_VALUE))).isEqualTo(Long.MAX_VALUE);
}
@Test
void parse() {
assertThat(TsPartitioning.parse("months")).isEqualTo(TsPartitioning.MONTHS);

2
msa/migrator/README.md

@ -22,7 +22,7 @@ CASSANDRA_LOCAL_DATACENTER=datacenter1
PARALLELISM_LEVEL=4
```
For a PostgreSQL-only (or TimescaleDB) source, set `CASSANDRA_EXPORT_ENABLED=false` and `POSTGRES_TS_EXPORT_ENABLED=true` to export timeseries history from PostgreSQL `ts_kv` (see `migrator/src/main/resources/README.md`).
Timeseries history is split into files of about `TS_KV_EXPORT_MAX_FILE_SIZE_MB` (default 256); `0` writes a single `ts_kv.gz` like older versions.
Timeseries history is split into files of about `TS_KV_EXPORT_MAX_FILE_SIZE_MB` (default 256). Older migrator versions can't import them; `0` writes a single `ts_kv.gz` they can read.
Example of `migrator.env` for tenant import:
```

Loading…
Cancel
Save