Browse Source
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).pull/16897/head
13 changed files with 752 additions and 19 deletions
@ -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<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 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<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); |
|||
|
|||
for (TsRow row : rows) { |
|||
if (row.ts() < partitionTs || row.ts() >= nextPartitionTs) { |
|||
partitionTs = partitioning.toPartitionTs(row.ts()); |
|||
nextPartitionTs = partitioning.nextPartitionTs(partitionTs); |
|||
} |
|||
Map<String, Object> 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<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")); |
|||
} |
|||
|
|||
} |
|||
|
|||
private record TsRow(long ts, Object[] values) {} |
|||
|
|||
} |
|||
@ -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<Part> parts) throws IOException { |
|||
storage.newFile(MANIFEST); |
|||
try (Writer writer = storage.newWriter(MANIFEST)) { |
|||
for (Part part : parts) { |
|||
Map<String, Object> row = new LinkedHashMap<>(); |
|||
row.put("file", part.name()); |
|||
row.put("rows", part.rows()); |
|||
storage.addToFile(writer, row); |
|||
} |
|||
} |
|||
} |
|||
|
|||
public static List<Part> listForImport(Storage storage) throws IOException { |
|||
if (storage.exists(MANIFEST)) { |
|||
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(); |
|||
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"); |
|||
} |
|||
|
|||
} |
|||
@ -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<TsKvFiles.Part> 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<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(); |
|||
} |
|||
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)); |
|||
} |
|||
|
|||
} |
|||
@ -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()))); |
|||
} |
|||
|
|||
} |
|||
@ -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<TsKvFiles.Part> 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<Long> read = new ArrayList<>(); |
|||
for (TsKvFiles.Part part : parts) { |
|||
List<Long> 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<Future<?>> 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<Long> 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<Long> readTs(String file) throws IOException { |
|||
List<Long> 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<String, Object> row(long ts) { |
|||
Map<String, Object> 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; |
|||
} |
|||
|
|||
} |
|||
@ -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(); |
|||
} |
|||
|
|||
} |
|||
Loading…
Reference in new issue