From eaf0fe6d60f45be059ac66c957cc982017a4f5a7 Mon Sep 17 00:00:00 2001 From: dealnat Date: Mon, 16 Nov 2026 18:02:07 +0100 Subject: [PATCH] feat(migrator): export PostgreSQL ts_kv history and split ts_kv files by size Add PostgresTsKvExporter, so a tenant can be migrated from a PostgreSQL-only (or TimescaleDB) setup to a hybrid PostgreSQL + Cassandra one. It reads the history of every key in the exported ts_kv_latest from ts_kv with keyset pagination and writes it in the CassandraTsKvExporter format, computing the Cassandra partition from POSTGRES_TS_EXPORT_PARTITIONING (must match the target's TS_KV_PARTITIONING). Invalid configs fail at startup, and a failed key makes the export exit with an error without creating data.tar. Both time-series exporters now write ts_kv_00001.gz, ts_kv_00002.gz, ... of about TS_KV_EXPORT_MAX_FILE_SIZE_MB (default 256) and a ts_kv_manifest.gz listing them, written last. The importer reads the manifest (or the legacy single ts_kv.gz), rejects exports without it, reports progress against the total row count and applies skip_lines across files. 0 keeps the legacy format. Also cap the Hikari pool above parallelism_level and document Cassandra 4/5 compatibility (protocol pinning, the 2038 TTL limit). --- migrator/pom.xml | 6 + .../exporting/CassandraTsKvExporter.java | 17 +- .../exporting/PostgresTsKvExporter.java | 180 ++++++++++++++++++ .../importing/CassandraTsKvImporter.java | 33 +++- .../thingsboard/migrator/utils/Storage.java | 33 +++- .../thingsboard/migrator/utils/TsKvFiles.java | 68 +++++++ .../migrator/utils/TsKvWriter.java | 86 +++++++++ .../migrator/utils/TsPartitioning.java | 55 ++++++ migrator/src/main/resources/README.md | 45 ++++- migrator/src/main/resources/application.yml | 19 ++ .../migrator/utils/TsKvWriterTest.java | 166 ++++++++++++++++ .../migrator/utils/TsPartitioningTest.java | 61 ++++++ msa/migrator/README.md | 2 + 13 files changed, 752 insertions(+), 19 deletions(-) create mode 100644 migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporter.java create mode 100644 migrator/src/main/java/org/thingsboard/migrator/utils/TsKvFiles.java create mode 100644 migrator/src/main/java/org/thingsboard/migrator/utils/TsKvWriter.java create mode 100644 migrator/src/main/java/org/thingsboard/migrator/utils/TsPartitioning.java create mode 100644 migrator/src/test/java/org/thingsboard/migrator/utils/TsKvWriterTest.java create mode 100644 migrator/src/test/java/org/thingsboard/migrator/utils/TsPartitioningTest.java diff --git a/migrator/pom.xml b/migrator/pom.xml index 41717c4671..3a4edb3393 100644 --- a/migrator/pom.xml +++ b/migrator/pom.xml @@ -75,6 +75,12 @@ ch.qos.logback logback-classic + + + org.springframework.boot + spring-boot-starter-test + test + diff --git a/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporter.java b/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporter.java index b859aef839..2098a03acd 100644 --- a/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporter.java +++ b/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/CassandraTsKvExporter.java @@ -14,8 +14,9 @@ import org.thingsboard.migrator.MigrationService; import org.thingsboard.migrator.Table; import org.thingsboard.migrator.utils.CassandraService; import org.thingsboard.migrator.utils.Storage; +import org.thingsboard.migrator.utils.TsKvWriter; -import java.io.Writer; +import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; @@ -41,13 +42,14 @@ 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 TS_KV_FILE = "ts_kv"; public static final String LATEST_KV = Table.LATEST_KV.getName(); - private Writer writer; + private TsKvWriter writer; private boolean isFilterByPartition() { return partitionFilter != null && partitionFilter > 0; @@ -68,8 +70,7 @@ public class CassandraTsKvExporter extends MigrationService { } } - storage.newFile(TS_KV_FILE); - writer = storage.newWriter(TS_KV_FILE); + writer = new TsKvWriter(storage, maxFileSizeMb * 1024 * 1024); log.info("Starting Cassandra TS export. Latest KV file info: {}", storage.getFileInfo(LATEST_KV)); storage.readAndProcess(LATEST_KV, latestKvRow -> { @@ -84,7 +85,7 @@ public class CassandraTsKvExporter extends MigrationService { }); } - private void getTsHistoryAndSave(Map latestKvRow) { + private void getTsHistoryAndSave(Map latestKvRow) throws IOException { String entityType = (String) latestKvRow.get("table_name"); UUID entityId = (UUID) latestKvRow.get("entity_id"); String key = (String) latestKvRow.get("key_name"); @@ -153,7 +154,7 @@ public class CassandraTsKvExporter extends MigrationService { } data.put(column, value); } - storage.addToFile(writer, data); + writer.write(data); reportProcessed(TS_KV_TABLE, data); } } @@ -163,7 +164,7 @@ public class CassandraTsKvExporter extends MigrationService { protected void afterFinished() throws Exception { finishedProcessing(TS_KV_TABLE); finishedProcessing(LATEST_KV); - writer.close(); + writer.finish(); } } diff --git a/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporter.java b/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporter.java new file mode 100644 index 0000000000..ac57bbd0f6 --- /dev/null +++ b/migrator/src/main/java/org/thingsboard/migrator/service/tenant/exporting/PostgresTsKvExporter.java @@ -0,0 +1,180 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.migrator.service.tenant.exporting; + +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.core.annotation.Order; +import org.springframework.jdbc.core.JdbcTemplate; +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.TsPartitioning; + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; + +import static org.thingsboard.migrator.service.tenant.exporting.CassandraTsKvExporter.LATEST_KV; +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. + */ +@Service +@RequiredArgsConstructor +@ConditionalOnExpression("'${mode}' == 'TENANT_DATA_EXPORT' and ${export.postgres_ts.enabled} == true") +@Order(2) +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; + + @Value("${export.postgres_ts.partitioning}") + private String partitioningName; + @Value("${export.postgres_ts.batch_size}") + private int batchSize; + @Value("${export.postgres_ts.filter.start_ts:}") + private Long startTs; + @Value("${export.postgres_ts.filter.end_ts:}") + private Long endTs; + @Value("${export.postgres.enabled}") + private boolean postgresExportEnabled; + @Value("${export.postgres.delay_between_queries}") + private int delayBetweenQueries; + @Value("${export.cassandra.enabled}") + private boolean cassandraExportEnabled; + @Value("${skipped_tables}") + private Set skippedTables; + @Value("${export.ts_kv.max_file_size_mb}") + private long maxFileSizeMb; + + private final AtomicLong failedKeys = new AtomicLong(); + + private TsPartitioning partitioning; + private String query; + private TsKvWriter writer; + + @PostConstruct + private void validate() { + if (cassandraExportEnabled) { + throw new IllegalStateException("POSTGRES_TS_EXPORT_ENABLED requires CASSANDRA_EXPORT_ENABLED=false: both write the same " + NAME + " files"); + } + partitioning = TsPartitioning.parse(partitioningName); + if (batchSize <= 0) { + throw new IllegalArgumentException("POSTGRES_TS_EXPORT_BATCH_SIZE must be positive, got " + batchSize); + } + 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 + ")"); + } + if (postgresExportEnabled) { + if (skippedTables.contains(Table.LATEST_KV)) { + throw new IllegalStateException("Time-series keys are taken from the exported " + LATEST_KV + ", remove LATEST_KV from SKIPPED_TABLES"); + } + } 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 > ?" + + (endTs != null ? " AND ts <= ?" : "") + " ORDER BY ts LIMIT ?"; + } + + @Override + protected void start() throws Exception { + log.info("Starting PostgreSQL ts_kv export. Partitioning: {}, startTs: {}, endTs: {}. Latest KV {}", + partitioning, startTs, endTs, storage.getFileInfo(LATEST_KV)); + reportTotal(LATEST_KV, storage.count(LATEST_KV)); + + writer = new TsKvWriter(storage, maxFileSizeMb * 1024 * 1024); + + storage.readAndProcess(LATEST_KV, latestKvRow -> executor.submit(() -> { + try { + exportHistory(TsKey.of(latestKvRow)); + } catch (Exception 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); + } + reportProcessed(LATEST_KV, latestKvRow); + })); + } + + 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; + 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 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); + + for (TsRow row : rows) { + if (row.ts() < partitionTs || row.ts() >= nextPartitionTs) { + partitionTs = partitioning.toPartitionTs(row.ts()); + nextPartitionTs = partitioning.nextPartitionTs(partitionTs); + } + Map data = new LinkedHashMap<>(); + data.put("entity_type", tsKey.entityType()); + data.put("entity_id", tsKey.entityId()); + data.put("partition", partitionTs); + data.put("key", tsKey.keyName()); + data.put("ts", row.ts()); + for (int i = 0; i < VALUE_COLUMNS.length; i++) { + if (row.values()[i] != null) { + data.put(VALUE_COLUMNS[i], row.values()[i]); + } + } + writer.write(data); + reportProcessed(NAME, data); + } + + if (rows.size() < batchSize) { + return; + } + cursor = rows.get(rows.size() - 1).ts(); + if (delayBetweenQueries > 0) { + TimeUnit.MILLISECONDS.sleep(delayBetweenQueries); + } + } + } + + @Override + protected void afterFinished() throws Exception { + finishedProcessing(NAME); + 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(); + } + + private record TsKey(String entityType, UUID entityId, int keyId, String keyName) { + + static TsKey of(Map latestKvRow) { + return new TsKey((String) latestKvRow.get("table_name"), (UUID) latestKvRow.get("entity_id"), + ((Number) latestKvRow.get("key")).intValue(), (String) latestKvRow.get("key_name")); + } + + } + + private record TsRow(long ts, Object[] values) {} + +} diff --git a/migrator/src/main/java/org/thingsboard/migrator/service/tenant/importing/CassandraTsKvImporter.java b/migrator/src/main/java/org/thingsboard/migrator/service/tenant/importing/CassandraTsKvImporter.java index a8b25af9e6..0fd990374d 100644 --- a/migrator/src/main/java/org/thingsboard/migrator/service/tenant/importing/CassandraTsKvImporter.java +++ b/migrator/src/main/java/org/thingsboard/migrator/service/tenant/importing/CassandraTsKvImporter.java @@ -10,11 +10,12 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Service; import org.thingsboard.migrator.MigrationService; -import org.thingsboard.migrator.service.tenant.exporting.CassandraTsKvExporter; import org.thingsboard.migrator.utils.CassandraService; import org.thingsboard.migrator.utils.Storage; +import org.thingsboard.migrator.utils.TsKvFiles; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; @@ -45,18 +46,34 @@ public class CassandraTsKvImporter extends MigrationService { @Override protected void start() throws Exception { log.info("Starting CassandraTsKvImporter..."); - log.info("Reporting info for file: {}", storage.getFileInfo(CassandraTsKvExporter.TS_KV_FILE)); + List parts = TsKvFiles.listForImport(storage); + if (parts.stream().allMatch(part -> part.rows() != null)) { + long totalRows = parts.stream().mapToLong(TsKvFiles.Part::rows).sum(); + log.info("Importing {} time-series files with {} rows in total", parts.size(), totalRows); + reportTotal(TS_KV_TABLE, totalRows); + } if (tsKvSkipLines > 0) { log.info("Skipping first {} lines. Initial processed counter will start from {}...", tsKvSkipLines, tsKvSkipLines); reportProcessed(TS_KV_TABLE, tsKvSkipLines, null); } - storage.readAndProcess(CassandraTsKvExporter.TS_KV_FILE, tsKvSkipLines, row -> { - try { - saveTsKv(row); - } catch (Exception e) { - throw new RuntimeException("Failed to save row: " + row, e); + // skip_lines counts across all files in order, like the processed counter + long toSkip = tsKvSkipLines; + for (TsKvFiles.Part part : parts) { + if (part.rows() != null && toSkip >= part.rows()) { + log.info("Skipping file {} ({} rows)", part.name(), part.rows()); + toSkip -= part.rows(); + continue; } - }); + log.info("Importing {}", storage.getFileInfo(part.name())); + storage.readAndProcess(part.name(), toSkip, row -> { + try { + saveTsKv(row); + } catch (Exception e) { + throw new RuntimeException("Failed to save row: " + row, e); + } + }); + toSkip = 0; + } } private void saveTsKv(Map row) { diff --git a/migrator/src/main/java/org/thingsboard/migrator/utils/Storage.java b/migrator/src/main/java/org/thingsboard/migrator/utils/Storage.java index 3d7a4c55eb..88cdd5a7b2 100644 --- a/migrator/src/main/java/org/thingsboard/migrator/utils/Storage.java +++ b/migrator/src/main/java/org/thingsboard/migrator/utils/Storage.java @@ -36,6 +36,8 @@ import java.util.List; import java.util.Map; import java.util.UUID; import java.util.function.Consumer; +import java.util.regex.Pattern; +import java.util.stream.Stream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; @@ -85,6 +87,10 @@ public class Storage { @SneakyThrows public void addToFile(Writer writer, Map row) { + writer.write(toLine(row)); + } + + public String toLine(Map row) { row.replaceAll((column, data) -> { if (data instanceof PGobject object) { data = object.getValue(); @@ -101,8 +107,31 @@ public class Storage { } return data; }); - String serialized = toJson(row); - writer.write(serialized + System.lineSeparator()); + return toJson(row) + System.lineSeparator(); + } + + public boolean exists(String file) { + return Files.exists(getPath(file)); + } + + public long size(String file) throws IOException { + return Files.size(getPath(file)); + } + + public void delete(String file) throws IOException { + Files.deleteIfExists(getPath(file)); + } + + // Names without the .gz extension, sorted + public List listFiles(Pattern namePattern) throws IOException { + try (Stream files = Files.list(workingDir)) { + return files.map(path -> path.getFileName().toString()) + .filter(name -> name.endsWith(".gz")) + .map(name -> name.substring(0, name.length() - ".gz".length())) + .filter(name -> namePattern.matcher(name).matches()) + .sorted() + .toList(); + } } public long count(String file) throws IOException { diff --git a/migrator/src/main/java/org/thingsboard/migrator/utils/TsKvFiles.java b/migrator/src/main/java/org/thingsboard/migrator/utils/TsKvFiles.java new file mode 100644 index 0000000000..d5026bbf07 --- /dev/null +++ b/migrator/src/main/java/org/thingsboard/migrator/utils/TsKvFiles.java @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.migrator.utils; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +/** + * Layout of exported time-series history in the working directory. Either: + * - ts_kv_00001.gz, ts_kv_00002.gz, ... plus ts_kv_manifest.gz listing them with row counts, written last on success; + * - or a single legacy ts_kv.gz without a manifest. + */ +public final class TsKvFiles { + + public static final String NAME = "ts_kv"; + public static final String MANIFEST = NAME + "_manifest"; + + static final Pattern PARTS = Pattern.compile(NAME + "_\\d+"); + static final Pattern ALL = Pattern.compile(NAME + "(_\\d+|_manifest)?"); + + private TsKvFiles() {} + + /** + * @param rows null for the legacy single file + */ + public record Part(String name, Long rows) {} + + static String partName(int index) { + return String.format("%s_%05d", NAME, index); + } + + static void writeManifest(Storage storage, List parts) throws IOException { + storage.newFile(MANIFEST); + try (Writer writer = storage.newWriter(MANIFEST)) { + for (Part part : parts) { + Map row = new LinkedHashMap<>(); + row.put("file", part.name()); + row.put("rows", part.rows()); + storage.addToFile(writer, row); + } + } + } + + public static List listForImport(Storage storage) throws IOException { + if (storage.exists(MANIFEST)) { + List parts = new ArrayList<>(); + storage.readAndProcess(MANIFEST, row -> parts.add(new Part((String) row.get("file"), ((Number) row.get("rows")).longValue()))); + List missing = parts.stream().map(Part::name).filter(name -> !storage.exists(name)).toList(); + if (!missing.isEmpty()) { + throw new IllegalStateException("Files listed in " + MANIFEST + ".gz are missing in the working directory: " + missing); + } + return parts; + } + if (storage.exists(NAME)) { + return List.of(new Part(NAME, null)); + } + if (!storage.listFiles(PARTS).isEmpty()) { + throw new IllegalStateException(NAME + "_*.gz files found without " + MANIFEST + ".gz: the time-series export didn't complete"); + } + throw new IllegalStateException("No time-series files in the working directory: expected " + MANIFEST + ".gz or " + NAME + ".gz"); + } + +} diff --git a/migrator/src/main/java/org/thingsboard/migrator/utils/TsKvWriter.java b/migrator/src/main/java/org/thingsboard/migrator/utils/TsKvWriter.java new file mode 100644 index 0000000000..fc63871cda --- /dev/null +++ b/migrator/src/main/java/org/thingsboard/migrator/utils/TsKvWriter.java @@ -0,0 +1,86 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.migrator.utils; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * 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. + */ +public class TsKvWriter { + + private static final int SIZE_CHECK_INTERVAL_ROWS = 1000; + + private final Storage storage; + private final long maxFileSize; + private final List parts = new ArrayList<>(); + + private String fileName; + private Writer writer; + private long rows; + + /** + * @param maxFileSize in bytes; 0 or less writes a single legacy ts_kv.gz without a manifest + */ + public TsKvWriter(Storage storage, long maxFileSize) throws IOException { + 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(); + } + + public void write(Map 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(); + } + writer.write(line); + rows++; + } + } + + /** + * Closes the output and writes the manifest, which marks the export as complete. + */ + public synchronized void finish() throws IOException { + closeFile(); + if (isRolling()) { + TsKvFiles.writeManifest(storage, parts); + } + } + + /** + * Closes the output without the manifest, so the importer rejects the incomplete export. + */ + public synchronized void abort() throws IOException { + writer.close(); + } + + private boolean isRolling() { + return maxFileSize > 0; + } + + 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 closeFile() throws IOException { + writer.close(); + parts.add(new TsKvFiles.Part(fileName, rows)); + } + +} diff --git a/migrator/src/main/java/org/thingsboard/migrator/utils/TsPartitioning.java b/migrator/src/main/java/org/thingsboard/migrator/utils/TsPartitioning.java new file mode 100644 index 0000000000..8a52df3fb9 --- /dev/null +++ b/migrator/src/main/java/org/thingsboard/migrator/utils/TsPartitioning.java @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.migrator.utils; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; + +/** + * Mirrors NoSqlTsPartitionDate and CassandraBaseTimeseriesDao.toPartitionTs from the dao module, + * which the migrator doesn't depend on. + */ +public enum TsPartitioning { + + MINUTES, HOURS, DAYS, MONTHS, YEARS, INDEFINITE; + + public long toPartitionTs(long ts) { + LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(ts), ZoneOffset.UTC); + LocalDateTime partition = switch (this) { + case MINUTES -> time.truncatedTo(ChronoUnit.MINUTES); + case HOURS -> time.truncatedTo(ChronoUnit.HOURS); + case DAYS -> time.truncatedTo(ChronoUnit.DAYS); + case MONTHS -> time.truncatedTo(ChronoUnit.DAYS).withDayOfMonth(1); + case YEARS -> time.truncatedTo(ChronoUnit.DAYS).withDayOfYear(1); + case INDEFINITE -> LocalDateTime.ofEpochSecond(0, 0, ZoneOffset.UTC); + }; + return partition.toInstant(ZoneOffset.UTC).toEpochMilli(); + } + + public long nextPartitionTs(long partitionTs) { + if (this == INDEFINITE) { + return Long.MAX_VALUE; + } + LocalDateTime time = LocalDateTime.ofInstant(Instant.ofEpochMilli(partitionTs), ZoneOffset.UTC); + LocalDateTime next = switch (this) { + case MINUTES -> time.plusMinutes(1); + case HOURS -> time.plusHours(1); + case DAYS -> time.plusDays(1); + case MONTHS -> time.plusMonths(1); + case YEARS -> time.plusYears(1); + case INDEFINITE -> throw new IllegalStateException(); + }; + return next.toInstant(ZoneOffset.UTC).toEpochMilli(); + } + + public static TsPartitioning parse(String name) { + return Arrays.stream(values()) + .filter(p -> p.name().equalsIgnoreCase(name == null ? null : name.trim())) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException("Unsupported ts partitioning '" + name + "', expected one of " + Arrays.toString(values()))); + } + +} diff --git a/migrator/src/main/resources/README.md b/migrator/src/main/resources/README.md index 15c02e761a..4b33d35283 100644 --- a/migrator/src/main/resources/README.md +++ b/migrator/src/main/resources/README.md @@ -24,6 +24,33 @@ CASSANDRA_KEYSPACE_NAME=thingsboard ``` +Env file example for tenant export from a PostgreSQL-only (or TimescaleDB) setup, to be imported into a hybrid (PostgreSQL + Cassandra) one. +Time-series history is read from `ts_kv` and written in the same format as the Cassandra export, so the import is the same as below. +``` +MIGRATOR_MODE=TENANT_DATA_EXPORT +EXPORTED_TENANT_ID= +SKIPPED_TABLES=RULE_NODE_DEBUG_EVENT,STATS_EVENT,LC_EVENT + +DATABASE_URL=jdbc:postgresql://:5432/thingsboard +DATABASE_USERNAME=postgres +DATABASE_PASSWORD=postgres + +CASSANDRA_EXPORT_ENABLED=false +POSTGRES_TS_EXPORT_ENABLED=true +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. + +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. +- Import the delta with `POSTGRES_IMPORT_ENABLED=false`. Latest values (`ts_kv_latest`) of the target are not updated by it. + + Before importing, make sure to create (and then delete) a tenant so that system roles are created. Env file example for tenant import: @@ -43,4 +70,20 @@ CASSANDRA_IMPORT_TS_KV_TTL=730 CASSANDRA_URL=cassandra:9042 CASSANDRA_LOCAL_DATACENTER=us-east CASSANDRA_KEYSPACE_NAME=thingsboard -``` \ No newline at end of file +``` + + +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. + 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. +- `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. + + +Cassandra versions: +- The exported files don't depend on the Cassandra version. The import writes them with CQL through the Java driver, which negotiates the protocol version with the cluster, so Cassandra 4.x and 5.x work without configuration. +- To pin the protocol version, e.g. for a cluster in the middle of a rolling upgrade, set `JAVA_OPTS=-Ddatastax-java-driver.advanced.protocol.version=V4` (or `V5`). +- Cassandra 4.x, and 5.x with the default `storage_compatibility_mode: CASSANDRA_4`, reject writes that expire after 2038-01-19, + so `CASSANDRA_IMPORT_TS_KV_TTL_DAYS` must keep the import time plus TTL before that date. Cassandra 5.x with `storage_compatibility_mode: NONE` doesn't have this limit. \ No newline at end of file diff --git a/migrator/src/main/resources/application.yml b/migrator/src/main/resources/application.yml index dd532f3675..c07f31460c 100644 --- a/migrator/src/main/resources/application.yml +++ b/migrator/src/main/resources/application.yml @@ -14,6 +14,10 @@ exit_after_finish: ${EXIT_AFTER_FINISH:true} 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. + max_file_size_mb: ${TS_KV_EXPORT_MAX_FILE_SIZE_MB:256} postgres: enabled: ${POSTGRES_EXPORT_ENABLED:true} batch_size: ${POSTGRES_EXPORT_BATCH_SIZE:500} @@ -38,6 +42,18 @@ export: 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: + enabled: ${POSTGRES_TS_EXPORT_ENABLED:false} + # Must equal TS_KV_PARTITIONING of the target cluster, otherwise imported history won't be readable. + # MINUTES, HOURS, DAYS, MONTHS, YEARS, INDEFINITE + partitioning: ${POSTGRES_TS_EXPORT_PARTITIONING:MONTHS} + batch_size: ${POSTGRES_TS_EXPORT_BATCH_SIZE:10000} + filter: + # Inclusive bounds in epoch millis. Leave empty to export all available data. + start_ts: ${POSTGRES_TS_EXPORT_FILTER_START_TS:} + end_ts: ${POSTGRES_TS_EXPORT_FILTER_END_TS:} import: postgres: @@ -81,6 +97,9 @@ spring: url: ${DATABASE_URL:jdbc:postgresql://localhost:5432/thingsboard} username: ${DATABASE_USERNAME:postgres} password: ${DATABASE_PASSWORD:postgres} + hikari: + # Keep above parallelism_level: worker threads and the caller thread query in parallel. + maximum-pool-size: ${DATABASE_MAX_POOL_SIZE:16} cassandra: keyspace-name: ${CASSANDRA_KEYSPACE_NAME:thingsboard} diff --git a/migrator/src/test/java/org/thingsboard/migrator/utils/TsKvWriterTest.java b/migrator/src/test/java/org/thingsboard/migrator/utils/TsKvWriterTest.java new file mode 100644 index 0000000000..f5f3fdc61a --- /dev/null +++ b/migrator/src/test/java/org/thingsboard/migrator/utils/TsKvWriterTest.java @@ -0,0 +1,166 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +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.nio.file.Path; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class TsKvWriterTest { + + private static final long MAX_FILE_SIZE = 100 * 1024; + + @TempDir + Path workingDir; + + private Storage storage; + + @BeforeEach + void setUp() { + storage = new Storage(); + ReflectionTestUtils.setField(storage, "workingDir", workingDir); + ReflectionTestUtils.setField(storage, "mode", "TENANT_DATA_EXPORT"); + ReflectionTestUtils.setField(storage, "archiveResult", false); + } + + @Test + void rollsOverBySizeAndListsFilesInManifest() throws IOException { + TsKvWriter writer = new TsKvWriter(storage, MAX_FILE_SIZE); + for (int i = 0; i < 20_000; i++) { + writer.write(row(i)); + } + writer.finish(); + + List parts = TsKvFiles.listForImport(storage); + assertThat(parts).hasSizeGreaterThan(2); + 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); + } + + List read = new ArrayList<>(); + for (TsKvFiles.Part part : parts) { + List partRows = readTs(part.name()); + assertThat(partRows).hasSize(part.rows().intValue()); + read.addAll(partRows); + } + assertThat(read).isSorted().hasSize(20_000).doesNotHaveDuplicates(); + } + + @Test + void concurrentWritesKeepLinesIntact() throws Exception { + TsKvWriter writer = new TsKvWriter(storage, MAX_FILE_SIZE); + ExecutorService executor = Executors.newFixedThreadPool(8); + List> futures = new ArrayList<>(); + for (int t = 0; t < 8; t++) { + int thread = t; + futures.add(executor.submit(() -> { + for (int i = 0; i < 5_000; i++) { + writer.write(row(thread * 5_000L + i)); + } + return null; + })); + } + for (Future future : futures) { + future.get(); + } + executor.shutdown(); + writer.finish(); + + List read = new ArrayList<>(); + for (TsKvFiles.Part part : TsKvFiles.listForImport(storage)) { + read.addAll(readTs(part.name())); + } + assertThat(read).hasSize(40_000).doesNotHaveDuplicates(); + } + + @Test + void emptyExportHasManifestWithEmptyFile() throws IOException { + TsKvWriter writer = new TsKvWriter(storage, MAX_FILE_SIZE); + writer.finish(); + + assertThat(TsKvFiles.listForImport(storage)).containsExactly(new TsKvFiles.Part("ts_kv_00001", 0L)); + } + + @Test + void legacyModeWritesSingleFileAndRemovesPreviousExport() throws IOException { + TsKvWriter previous = new TsKvWriter(storage, MAX_FILE_SIZE); + previous.write(row(1)); + previous.finish(); + + TsKvWriter writer = new TsKvWriter(storage, 0); + writer.write(row(2)); + writer.write(row(3)); + writer.finish(); + + assertThat(storage.exists(TsKvFiles.MANIFEST)).isFalse(); + assertThat(storage.exists("ts_kv_00001")).isFalse(); + assertThat(TsKvFiles.listForImport(storage)).containsExactly(new TsKvFiles.Part("ts_kv", null)); + assertThat(readTs("ts_kv")).containsExactly(2L, 3L); + } + + @Test + void abortedExportIsRejectedByImport() throws IOException { + TsKvWriter writer = new TsKvWriter(storage, MAX_FILE_SIZE); + writer.write(row(1)); + writer.abort(); + + assertThatThrownBy(() -> TsKvFiles.listForImport(storage)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("didn't complete"); + } + + @Test + void missingFileListedInManifestIsRejected() throws IOException { + TsKvWriter writer = new TsKvWriter(storage, MAX_FILE_SIZE); + writer.write(row(1)); + writer.finish(); + storage.delete("ts_kv_00001"); + + assertThatThrownBy(() -> TsKvFiles.listForImport(storage)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ts_kv_00001"); + } + + @Test + void noExportIsRejected() { + assertThatThrownBy(() -> TsKvFiles.listForImport(storage)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No time-series files"); + } + + private List readTs(String file) throws IOException { + List ts = new ArrayList<>(); + storage.readAndProcess(file, row -> ts.add(((Number) row.get("ts")).longValue())); + return ts; + } + + // Random values keep the data poorly compressible, so files reach the size limit quickly + private static Map row(long ts) { + Map row = new LinkedHashMap<>(); + row.put("entity_type", "DEVICE"); + row.put("entity_id", UUID.randomUUID()); + row.put("partition", 0L); + row.put("key", "temperature"); + row.put("ts", ts); + row.put("str_v", UUID.randomUUID() + "-" + UUID.randomUUID()); + return row; + } + +} diff --git a/migrator/src/test/java/org/thingsboard/migrator/utils/TsPartitioningTest.java b/migrator/src/test/java/org/thingsboard/migrator/utils/TsPartitioningTest.java new file mode 100644 index 0000000000..643acdb466 --- /dev/null +++ b/migrator/src/test/java/org/thingsboard/migrator/utils/TsPartitioningTest.java @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.migrator.utils; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.time.Instant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class TsPartitioningTest { + + @ParameterizedTest + @CsvSource({ + "MINUTES, 2025-11-15T10:20:30.123Z, 2025-11-15T10:20:00Z, 2025-11-15T10:21:00Z", + "HOURS, 2025-11-15T10:20:30.123Z, 2025-11-15T10:00:00Z, 2025-11-15T11:00:00Z", + "DAYS, 2025-11-15T10:20:30.123Z, 2025-11-15T00:00:00Z, 2025-11-16T00:00:00Z", + "MONTHS, 2025-11-15T10:20:30.123Z, 2025-11-01T00:00:00Z, 2025-12-01T00:00:00Z", + "MONTHS, 2025-12-31T23:59:59.999Z, 2025-12-01T00:00:00Z, 2026-01-01T00:00:00Z", + "MONTHS, 2024-02-29T12:00:00Z, 2024-02-01T00:00:00Z, 2024-03-01T00:00:00Z", + "MONTHS, 2025-11-01T00:00:00Z, 2025-11-01T00:00:00Z, 2025-12-01T00:00:00Z", + "MONTHS, 2025-10-31T23:59:59.999Z, 2025-10-01T00:00:00Z, 2025-11-01T00:00:00Z", + "YEARS, 2025-11-15T10:20:30.123Z, 2025-01-01T00:00:00Z, 2026-01-01T00:00:00Z", + "YEARS, 2024-12-31T23:59:59.999Z, 2024-01-01T00:00:00Z, 2025-01-01T00:00:00Z", + "MONTHS, 1969-12-15T00:00:00Z, 1969-12-01T00:00:00Z, 1970-01-01T00:00:00Z", + }) + void partitionBoundaries(TsPartitioning partitioning, String ts, String expectedPartition, String expectedNext) { + long partitionTs = partitioning.toPartitionTs(millis(ts)); + + assertThat(partitionTs).isEqualTo(millis(expectedPartition)); + assertThat(partitioning.nextPartitionTs(partitionTs)).isEqualTo(millis(expectedNext)); + } + + @Test + void monthsMatchesKnownCassandraPartition() { + assertThat(TsPartitioning.MONTHS.toPartitionTs(millis("2025-11-20T08:00:00Z"))).isEqualTo(1761955200000L); + } + + @Test + void indefiniteIsSinglePartition() { + assertThat(TsPartitioning.INDEFINITE.toPartitionTs(millis("2025-11-15T10:20:30Z"))).isZero(); + assertThat(TsPartitioning.INDEFINITE.toPartitionTs(0)).isZero(); + assertThat(TsPartitioning.INDEFINITE.nextPartitionTs(0)).isEqualTo(Long.MAX_VALUE); + } + + @Test + void parse() { + assertThat(TsPartitioning.parse("months")).isEqualTo(TsPartitioning.MONTHS); + assertThat(TsPartitioning.parse(" INDEFINITE ")).isEqualTo(TsPartitioning.INDEFINITE); + assertThatThrownBy(() -> TsPartitioning.parse("WEEKS")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TsPartitioning.parse(null)).isInstanceOf(IllegalArgumentException.class); + } + + private static long millis(String iso) { + return Instant.parse(iso).toEpochMilli(); + } + +} diff --git a/msa/migrator/README.md b/msa/migrator/README.md index eca8dcd4a6..3494d4e035 100644 --- a/msa/migrator/README.md +++ b/msa/migrator/README.md @@ -21,6 +21,8 @@ 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. Example of `migrator.env` for tenant import: ```