Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#782] feat(core): Remove data of old versions that exceed TTL (#785)

Qi Yu7ed7f7f76112
diff --git a/core/src/main/java/com/datastrato/gravitino/Configs.java b/core/src/main/java/com/datastrato/gravitino/Configs.java
index d75bbb018c..114c303ddb 100644
--- a/core/src/main/java/com/datastrato/gravitino/Configs.java
+++ b/core/src/main/java/com/datastrato/gravitino/Configs.java
@@ -18,6 +18,9 @@ public interface Configs {
String ENTITY_KV_ROCKSDB_BACKEND_PATH_KEY = "gravitino.entity.store.kv.rocksdbPath";
+ Long DEFAULT_KV_DELETE_AFTER_TIME = 604800000L; // 7 days
+ String KV_DELETE_AFTER_TIME_KEY = "gravitino.entity.store.kv.deleteAfterTimeMs";
+
// Default path for RocksDB backend is "${GRAVITINO_HOME}/data/rocksdb"
String DEFAULT_KV_ROCKSDB_BACKEND_PATH =
String.join(File.separator, System.getenv("GRAVITINO_HOME"), "data", "rocksdb");
@@ -77,4 +80,12 @@ public interface Configs {
.version("0.3.0")
.longConf()
.createWithDefault(2000L);
+
+ ConfigEntry<Long> KV_DELETE_AFTER_TIME =
+ new ConfigBuilder(KV_DELETE_AFTER_TIME_KEY)
+ .doc(
+ "The max time that the deleted data and old version data will keep, unit: millisecond. At least 10 minutes and should not larger than 30 days ")
+ .version("0.3.0")
+ .longConf()
+ .createWithDefault(DEFAULT_KV_DELETE_AFTER_TIME);
}
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/BiPredicate.java b/core/src/main/java/com/datastrato/gravitino/storage/BiPredicate.java
index 63a746ace3..c8ba082bf7 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/BiPredicate.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/BiPredicate.java
@@ -13,5 +13,5 @@ import java.io.IOException;
*/
@FunctionalInterface
public interface BiPredicate<T1, T2> {
- boolean test(T1 v1, T2 value) throws IOException;
+ boolean test(T1 v1, T2 v2) throws IOException;
}
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.java
index 7b6c37cf67..c3da949975 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvEntityStore.java
@@ -78,6 +78,7 @@ public class KvEntityStore implements EntityStore {
@VisibleForTesting StorageLayoutVersion storageLayoutVersion;
private TransactionIdGenerator txIdGenerator;
+ private KvGarbageCollector kvGarbageCollector;
private TransactionalKvBackend transactionalKvBackend;
@Override
@@ -87,9 +88,13 @@ public class KvEntityStore implements EntityStore {
// instance, We should make it configurable in the future.
this.txIdGenerator = new TransactionIdGeneratorImpl(backend, config);
txIdGenerator.start();
+
this.transactionalKvBackend = new TransactionalKvBackendImpl(backend, txIdGenerator);
+ this.kvGarbageCollector = new KvGarbageCollector(backend, config);
+ kvGarbageCollector.start();
this.reentrantReadWriteLock = new ReentrantReadWriteLock();
+
this.nameMappingService =
new KvNameMappingService(transactionalKvBackend, reentrantReadWriteLock);
this.entityKeyEncoder = new BinaryEntityKeyEncoder(nameMappingService);
@@ -401,6 +406,7 @@ public class KvEntityStore implements EntityStore {
@Override
public void close() throws IOException {
txIdGenerator.close();
+ kvGarbageCollector.close();
backend.close();
}
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvGarbageCollector.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvGarbageCollector.java
new file mode 100644
index 0000000000..be748a0e35
--- /dev/null
+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvGarbageCollector.java
@@ -0,0 +1,199 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.gravitino.storage.kv;
+
+import static com.datastrato.gravitino.Configs.KV_DELETE_AFTER_TIME;
+import static com.datastrato.gravitino.storage.kv.TransactionalKvBackendImpl.endOfTransactionId;
+import static com.datastrato.gravitino.storage.kv.TransactionalKvBackendImpl.generateCommitKey;
+import static com.datastrato.gravitino.storage.kv.TransactionalKvBackendImpl.generateKey;
+import static com.datastrato.gravitino.storage.kv.TransactionalKvBackendImpl.getBinaryTransactionId;
+
+import com.datastrato.gravitino.Config;
+import com.datastrato.gravitino.utils.Bytes;
+import com.google.common.annotations.VisibleForTesting;
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.lang3.SerializationUtils;
+import org.apache.commons.lang3.tuple.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * {@link KvGarbageCollector} is a garbage collector for the kv backend. It will collect the version
+ * of data which is not committed or exceed the ttl.
+ */
+public final class KvGarbageCollector implements Closeable {
+ private static final Logger LOG = LoggerFactory.getLogger(KvGarbageCollector.class);
+ private final KvBackend kvBackend;
+ private final Config config;
+
+ private static final long MAX_DELETE_TIME_ALLOW = 1000 * 60 * 60 * 24 * 30L; // 30 days
+ private static final long MIN_DELETE_TIME_ALLOW = 1000 * 60 * 10L; // 10 minutes
+
+ @VisibleForTesting
+ final ScheduledExecutorService garbageCollectorPool =
+ new ScheduledThreadPoolExecutor(
+ 2,
+ r -> new Thread(r, "KvEntityStore-Garbage-Collector-%d"),
+ new ThreadPoolExecutor.AbortPolicy());
+
+ public KvGarbageCollector(KvBackend kvBackend, Config config) {
+ this.kvBackend = kvBackend;
+ this.config = config;
+
+ long deleteTimeLine = config.get(KV_DELETE_AFTER_TIME);
+ if (deleteTimeLine > MAX_DELETE_TIME_ALLOW || deleteTimeLine < MIN_DELETE_TIME_ALLOW) {
+ throw new IllegalArgumentException(
+ String.format(
+ "The delete time line is too long or too short, "
+ + "please check it. The delete time line is %s ms,"
+ + "max delete time allow is %s ms(30 days),"
+ + "min delete time allow is %s ms(10 minutes)",
+ deleteTimeLine, MAX_DELETE_TIME_ALLOW, MIN_DELETE_TIME_ALLOW));
+ }
+ }
+
+ public void start() {
+ long dateTimeLineMinute = config.get(KV_DELETE_AFTER_TIME) / 1000 / 60;
+
+ // We will collect garbage every 10 minutes at least. If the dateTimeLineMinute is larger than
+ // 100
+ // minutes, we would collect garbage every dateTimeLineMinute/10 minutes.
+ long frequency = Math.max(dateTimeLineMinute / 10, 10);
+ garbageCollectorPool.scheduleAtFixedRate(this::collectAndClean, 5, frequency, TimeUnit.MINUTES);
+ }
+
+ @VisibleForTesting
+ void collectAndClean() {
+ LOG.info("Start to collect garbage...");
+ try {
+ LOG.info("Start to collect and delete uncommitted data...");
+ collectAndRemoveUncommittedData();
+
+ LOG.info("Start to collect and delete old version data...");
+ collectAndRemoveOldVersionData();
+ } catch (Exception e) {
+ LOG.error("Failed to collect garbage", e);
+ }
+ }
+
+ private void collectAndRemoveUncommittedData() throws IOException {
+ List<Pair<byte[], byte[]>> kvs =
+ kvBackend.scan(
+ new KvRangeScan.KvRangeScanBuilder()
+ .start(new byte[] {0x20}) // below 0x20 is control character
+ .end(new byte[] {0x7F}) // above 0x7F is control character
+ .startInclusive(true)
+ .endInclusive(false)
+ .predicate(
+ (k, v) -> {
+ byte[] transactionId = getBinaryTransactionId(k);
+ return kvBackend.get(generateCommitKey(transactionId)) == null;
+ })
+ .limit(10000) /* Each time we only collect 10000 entities at most*/
+ .build());
+
+ LOG.info("Start to remove {} uncommitted data", kvs.size());
+ for (Pair<byte[], byte[]> pair : kvs) {
+ kvBackend.delete(pair.getKey());
+ }
+ }
+
+ private void collectAndRemoveOldVersionData() throws IOException {
+ long deleteTimeLine = System.currentTimeMillis() - config.get(KV_DELETE_AFTER_TIME);
+ // Why should we leave shift 18 bits? please refer to TransactionIdGeneratorImpl#nextId
+ // We can delete the data which is older than deleteTimeLine.(old data with transaction id that
+ // is smaller than transactionIdToDelete)
+ long transactionIdToDelete = deleteTimeLine << 18;
+ LOG.info("Start to remove data which is older than {}", transactionIdToDelete);
+ byte[] startKey = TransactionalKvBackendImpl.generateCommitKey(transactionIdToDelete);
+ byte[] endKey = endOfTransactionId();
+
+ // Get all commit marks
+ // TODO(yuqi), Use multi-thread to scan the data in case of the data is too large.
+ List<Pair<byte[], byte[]>> kvs =
+ kvBackend.scan(
+ new KvRangeScan.KvRangeScanBuilder()
+ .start(startKey)
+ .end(endKey)
+ .startInclusive(true)
+ .endInclusive(false)
+ .build());
+
+ // Why should we reverse the order? Because we need to delete the data from the oldest data to
+ // the latest ones. kvs is sorted by transaction id in ascending order (Keys with bigger
+ // transaction id
+ // is smaller than keys with smaller transaction id). So we need to reverse the order.
+ Collections.sort(kvs, (o1, o2) -> Bytes.wrap(o2.getKey()).compareTo(o1.getKey()));
+ for (Pair<byte[], byte[]> kv : kvs) {
+ List<byte[]> keysInTheTransaction = SerializationUtils.deserialize(kv.getValue());
+ byte[] transactionId = getBinaryTransactionId(kv.getKey());
+
+ int keysDeletedCount = 0;
+ for (byte[] key : keysInTheTransaction) {
+ // Raw key format: {key} + {separator} + {transaction_id}
+ byte[] rawKey = generateKey(key, transactionId);
+ byte[] rawValue = kvBackend.get(rawKey);
+ if (null == rawValue) {
+ // It has been deleted
+ keysDeletedCount++;
+ continue;
+ }
+
+ // Value has deleted mark, we can remove it.
+ if (null == TransactionalKvBackendImpl.getRealValue(rawValue)) {
+ LOG.info("Physically delete key that has marked deleted: {}", Bytes.wrap(key));
+ kvBackend.delete(rawKey);
+ keysDeletedCount++;
+ continue;
+ }
+
+ // If the key is not marked as deleted, then we need to check whether there is a newer
+ // version of the key. If there is a newer version of the key, then we can delete it
+ // directly.
+ List<Pair<byte[], byte[]>> newVersionOfKey =
+ kvBackend.scan(
+ new KvRangeScan.KvRangeScanBuilder()
+ .start(key)
+ .end(generateKey(key, transactionId))
+ .startInclusive(false)
+ .endInclusive(false)
+ .limit(1)
+ .build());
+ if (!newVersionOfKey.isEmpty()) {
+ // Has a newer version, we can remove it.
+ LOG.info(
+ "Physically delete key that has newer version: {}, a newer version {}",
+ Bytes.wrap(key),
+ Bytes.wrap(newVersionOfKey.get(0).getKey()));
+ kvBackend.delete(rawKey);
+ keysDeletedCount++;
+ }
+ }
+
+ // All keys in this transaction have been deleted, we can remove the commit mark.
+ if (keysDeletedCount == keysInTheTransaction.size()) {
+ kvBackend.delete(kv.getKey());
+ }
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ garbageCollectorPool.shutdownNow();
+ try {
+ garbageCollectorPool.awaitTermination(5, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ LOG.error("Failed to close garbage collector", e);
+ }
+ }
+}
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvRangeScan.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvRangeScan.java
index 5cad673e50..0b7fcad887 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvRangeScan.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvRangeScan.java
@@ -21,7 +21,7 @@ public class KvRangeScan {
private boolean endInclusive;
private int limit;
- private BiPredicate predicate;
+ private BiPredicate<byte[], byte[]> predicate;
/**
* Constructs a KvRangeScan instance with the specified parameters.
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionIdGeneratorImpl.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionIdGeneratorImpl.java
index 689a091b4e..383cfc71ff 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionIdGeneratorImpl.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionIdGeneratorImpl.java
@@ -10,7 +10,6 @@ import com.datastrato.gravitino.Configs;
import com.datastrato.gravitino.storage.TransactionIdGenerator;
import com.datastrato.gravitino.utils.ByteUtils;
import com.datastrato.gravitino.utils.Bytes;
-import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -24,11 +23,9 @@ public class TransactionIdGeneratorImpl implements TransactionIdGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(TransactionIdGeneratorImpl.class);
private final KvBackend kvBackend;
-
// We use three control characters 0x1D, 0x00, 0x01 to separate it from other keys.
private static final byte[] ID_GENERATOR_PREFIX = new byte[] {0x1D, 0x00, 0x01};
- @VisibleForTesting
static final byte[] LAST_TIMESTAMP =
Bytes.concat(ID_GENERATOR_PREFIX, "last_timestamp".getBytes(StandardCharsets.UTF_8));
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionalKvBackendImpl.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionalKvBackendImpl.java
index 98c6da9b9d..c263c23933 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionalKvBackendImpl.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/TransactionalKvBackendImpl.java
@@ -13,10 +13,11 @@ import com.datastrato.gravitino.utils.Bytes;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import java.io.IOException;
-import java.nio.charset.StandardCharsets;
+import java.io.Serializable;
import java.util.List;
import javax.annotation.concurrent.ThreadSafe;
import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.tuple.Pair;
/**
@@ -57,7 +58,7 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
private final ThreadLocal<List<byte[]>> originalKeys =
ThreadLocal.withInitial(() -> Lists.newArrayList());
- private final ThreadLocal<Long> txId = new ThreadLocal<>();
+ @VisibleForTesting final ThreadLocal<Long> txId = new ThreadLocal<>();
// 0x1E is control character RS
private static final byte[] TRANSACTION_PREFIX = {0x1E};
@@ -103,8 +104,8 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
// Commit
kvBackend.put(
- Bytes.concat(TRANSACTION_PREFIX, SEPARATOR, revert(ByteUtils.longToByte(txId.get()))),
- originalKeys.get().toString().getBytes(StandardCharsets.UTF_8),
+ generateCommitKey(txId.get()),
+ SerializationUtils.serialize((Serializable) originalKeys.get()),
true);
} finally {
putPairs.get().clear();
@@ -131,7 +132,9 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
throw new EntityAlreadyExistsException(
"Key already exists: " + ByteUtils.formatByteArray(key));
}
- putPairs.get().add(Pair.of(constructKey(key), constructValue(value, ValueStatusEnum.NORMAL)));
+ putPairs
+ .get()
+ .add(Pair.of(generateKey(key, txId.get()), constructValue(value, ValueStatusEnum.NORMAL)));
originalKeys.get().add(key);
}
@@ -142,7 +145,7 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
return null;
}
- return getValue(rawValue);
+ return getRealValue(rawValue);
}
@Override
@@ -153,7 +156,7 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
}
byte[] deletedValue = constructValue(oldValue, ValueStatusEnum.DELETED);
- putPairs.get().add(Pair.of(constructKey(key), deletedValue));
+ putPairs.get().add(Pair.of(generateKey(key, txId.get()), deletedValue));
originalKeys.get().add(key);
return true;
}
@@ -167,7 +170,7 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
.get()
.add(
Pair.of(
- constructKey(p.getKey()),
+ generateKey(p.getKey(), txId.get()),
constructValue(p.getValue(), ValueStatusEnum.DELETED))));
return true;
}
@@ -193,9 +196,8 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
.endInclusive(endInclude)
.predicate(
(k, v) -> {
- byte[] transactionId = getBinaryTransactionId((byte[]) k);
- return kvBackend.get(Bytes.concat(TRANSACTION_PREFIX, SEPARATOR, transactionId))
- != null;
+ byte[] transactionId = getBinaryTransactionId(k);
+ return kvBackend.get(generateCommitKey(transactionId)) != null;
})
.limit(Integer.MAX_VALUE)
.build();
@@ -223,7 +225,7 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
break;
}
- byte[] value = getValue(pair.getValue());
+ byte[] value = getRealValue(pair.getValue());
if (value != null) {
result.add(Pair.of(realKey, value));
i++;
@@ -248,7 +250,7 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
originalKeys.get().clear();
}
- private byte[] getValue(byte[] rawValue) {
+ public static byte[] getRealValue(byte[] rawValue) {
byte[] firstType = ArrayUtils.subarray(rawValue, 0, LENGTH_OF_VALUE_STATUS);
ValueStatusEnum statusEnum = ValueStatusEnum.fromCode(firstType[0]);
if (statusEnum == ValueStatusEnum.DELETED) {
@@ -268,7 +270,7 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
@VisibleForTesting
byte[] constructKey(byte[] key) {
- return Bytes.concat(key, SEPARATOR, revert(ByteUtils.longToByte(txId.get())));
+ return Bytes.concat(key, SEPARATOR, revertByteArray(ByteUtils.longToByte(txId.get())));
}
/**
@@ -285,10 +287,8 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
.endInclusive(false)
.predicate(
(k, v) -> {
- byte[] transactionId = getBinaryTransactionId((byte[]) k);
- return kvBackend.get(
- Bytes.concat(TRANSACTION_PREFIX, SEPARATOR, transactionId))
- != null;
+ byte[] transactionId = getBinaryTransactionId(k);
+ return kvBackend.get(generateCommitKey(transactionId)) != null;
})
.limit(1)
.build());
@@ -323,7 +323,7 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
* <p>When we try to get the value of key1, we will first the value of key1 10 and can skip old
* versions quickly.
*/
- private static byte[] revert(byte[] bytes) {
+ private static byte[] revertByteArray(byte[] bytes) {
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) (bytes[i] ^ (byte) 0xff);
}
@@ -331,6 +331,31 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {
return bytes;
}
+ /** Generate a key of data for a specific transaction id. */
+ @VisibleForTesting
+ static byte[] generateKey(byte[] key, long transactionId) {
+ return generateKey(key, revertByteArray(ByteUtils.longToByte(transactionId)));
+ }
+
+ static byte[] generateKey(byte[] key, byte[] binaryTransactionId) {
+ return Bytes.concat(key, SEPARATOR, binaryTransactionId);
+ }
+
+ /** Generate a commit key for a specific transaction id. */
+ static byte[] generateCommitKey(long transactionId) {
+ byte[] binaryTransactionId = ByteUtils.longToByte(transactionId);
+ return generateCommitKey(revertByteArray(binaryTransactionId));
+ }
+
+ static byte[] generateCommitKey(byte[] transactionId) {
+ return Bytes.concat(TRANSACTION_PREFIX, SEPARATOR, transactionId);
+ }
+
+ /** Get the end of transaction id, we use this key to scan all commit marks. */
+ static byte[] endOfTransactionId() {
+ return Bytes.increment(Bytes.wrap(Bytes.concat(TRANSACTION_PREFIX, SEPARATOR))).get();
+ }
+
static byte[] getRealKey(byte[] rawKey) {
return ArrayUtils.subarray(
rawKey, 0, rawKey.length - LENGTH_OF_TRANSACTION_ID - LENGTH_OF_SEPARATOR);
diff --git a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestEntityKeyEncoding.java b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestEntityKeyEncoding.java
index 51b4849448..7285009071 100644
--- a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestEntityKeyEncoding.java
+++ b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestEntityKeyEncoding.java
@@ -9,6 +9,7 @@ import static com.datastrato.gravitino.Configs.DEFAULT_ENTITY_KV_STORE;
import static com.datastrato.gravitino.Configs.ENTITY_KV_STORE;
import static com.datastrato.gravitino.Configs.ENTITY_STORE;
import static com.datastrato.gravitino.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;
+import static com.datastrato.gravitino.Configs.KV_DELETE_AFTER_TIME;
import static com.datastrato.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import static com.datastrato.gravitino.storage.kv.BinaryEntityKeyEncoder.BYTABLE_NAMESPACE_SEPARATOR;
import static com.datastrato.gravitino.storage.kv.BinaryEntityKeyEncoder.WILD_CARD;
@@ -49,6 +50,7 @@ public class TestEntityKeyEncoding {
Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(3000L);
Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");
Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
return config;
}
diff --git a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvEntityStorage.java b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvEntityStorage.java
index 48b4f33b2e..0f8e1deefd 100644
--- a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvEntityStorage.java
+++ b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvEntityStorage.java
@@ -9,6 +9,7 @@ import static com.datastrato.gravitino.Configs.DEFAULT_ENTITY_KV_STORE;
import static com.datastrato.gravitino.Configs.ENTITY_KV_STORE;
import static com.datastrato.gravitino.Configs.ENTITY_STORE;
import static com.datastrato.gravitino.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;
+import static com.datastrato.gravitino.Configs.KV_DELETE_AFTER_TIME;
import static com.datastrato.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import com.datastrato.gravitino.Catalog.Type;
@@ -114,6 +115,7 @@ public class TestKvEntityStorage {
Assertions.assertEquals(ROCKS_DB_STORE_PATH, config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH));
Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
AuditInfo auditInfo =
new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();
@@ -198,6 +200,7 @@ public class TestKvEntityStorage {
Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");
Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(ROCKS_DB_STORE_PATH);
Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
Assertions.assertEquals(ROCKS_DB_STORE_PATH, config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH));
AuditInfo auditInfo =
@@ -480,6 +483,7 @@ public class TestKvEntityStorage {
Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");
Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn("/tmp/gravitino");
Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
FileUtils.deleteDirectory(FileUtils.getFile("/tmp/gravitino"));
@@ -644,6 +648,8 @@ public class TestKvEntityStorage {
Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");
Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn("/tmp/gravitino");
Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
+
FileUtils.deleteDirectory(FileUtils.getFile("/tmp/gravitino"));
try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {
@@ -744,6 +750,8 @@ public class TestKvEntityStorage {
Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");
Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(file.getAbsolutePath());
Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
+
ThreadPoolExecutor threadPoolExecutor =
new ThreadPoolExecutor(
10,
@@ -857,6 +865,7 @@ public class TestKvEntityStorage {
Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");
Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(file.getAbsolutePath());
Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(1000L);
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
// First time create entity store, the storage layout version should be DEFAULT_LAYOUT_VERSION
try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {
diff --git a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvGarbageCollector.java b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvGarbageCollector.java
new file mode 100644
index 0000000000..1f182c3b72
--- /dev/null
+++ b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvGarbageCollector.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.gravitino.storage.kv;
+
+import static com.datastrato.gravitino.Configs.DEFAULT_ENTITY_KV_STORE;
+import static com.datastrato.gravitino.Configs.ENTITY_KV_STORE;
+import static com.datastrato.gravitino.Configs.ENTITY_STORE;
+import static com.datastrato.gravitino.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;
+import static com.datastrato.gravitino.Configs.KV_DELETE_AFTER_TIME;
+import static com.datastrato.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
+
+import com.datastrato.gravitino.Config;
+import com.datastrato.gravitino.Configs;
+import com.datastrato.gravitino.storage.TransactionIdGenerator;
+import com.google.common.io.Files;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import org.apache.commons.lang3.tuple.Pair;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+class TestKvGarbageCollector {
+ public Config getConfig() {
+ Config config = Mockito.mock(Config.class);
+ File file = Files.createTempDir();
+ file.deleteOnExit();
+ Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");
+ Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);
+ Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");
+ Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(file.getAbsolutePath());
+ Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(3L);
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
+ return config;
+ }
+
+ private KvBackend getKvBackEnd(Config config) throws IOException {
+ KvBackend kvBackend = new RocksDBKvBackend();
+ kvBackend.initialize(config);
+ return kvBackend;
+ }
+
+ @Test
+ void testScheduler() {
+ Config config = getConfig();
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L); // 20 minutes
+ long dateTimeLineMinute = config.get(KV_DELETE_AFTER_TIME) / 1000 / 60;
+ Assertions.assertEquals(10, Math.max(dateTimeLineMinute / 10, 10));
+
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(2 * 60 * 60 * 1000L); // 2 hours
+ dateTimeLineMinute = config.get(KV_DELETE_AFTER_TIME) / 1000 / 60;
+ Assertions.assertEquals(12, Math.max(dateTimeLineMinute / 10, 10));
+
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(2 * 60 * 60 * 24 * 1000L); // 2 days
+ dateTimeLineMinute = config.get(KV_DELETE_AFTER_TIME) / 1000 / 60;
+ Assertions.assertEquals(288, Math.max(dateTimeLineMinute / 10, 10));
+ }
+
+ @Test
+ void testCollectGarbage() throws IOException, InterruptedException {
+ Config config = getConfig();
+ try (KvBackend kvBackend = getKvBackEnd(config)) {
+ TransactionIdGenerator transactionIdGenerator =
+ new TransactionIdGeneratorImpl(kvBackend, config);
+ TransactionalKvBackendImpl transactionalKvBackend =
+ new TransactionalKvBackendImpl(kvBackend, transactionIdGenerator);
+ transactionalKvBackend.begin();
+ transactionalKvBackend.put("testA".getBytes(), "v1".getBytes(), true);
+ transactionalKvBackend.put("testB".getBytes(), "v1".getBytes(), true);
+ transactionalKvBackend.put("testC".getBytes(), "v1".getBytes(), true);
+ transactionalKvBackend.commit();
+ transactionalKvBackend.closeTransaction();
+
+ transactionalKvBackend.begin();
+ transactionalKvBackend.put("testA".getBytes(), "v2".getBytes(), true);
+ transactionalKvBackend.put("testB".getBytes(), "v2".getBytes(), true);
+ transactionalKvBackend.commit();
+ transactionalKvBackend.closeTransaction();
+
+ transactionalKvBackend.begin();
+ transactionalKvBackend.put("testA".getBytes(), "v3".getBytes(), true);
+ transactionalKvBackend.delete("testC".getBytes());
+ transactionalKvBackend.commit();
+ transactionalKvBackend.closeTransaction();
+
+ // Test data is OK
+ transactionalKvBackend.begin();
+ Assertions.assertEquals("v3", new String(transactionalKvBackend.get("testA".getBytes())));
+ Assertions.assertEquals("v2", new String(transactionalKvBackend.get("testB".getBytes())));
+ Assertions.assertNull(transactionalKvBackend.get("testC".getBytes()));
+ List<Pair<byte[], byte[]>> allData =
+ kvBackend.scan(
+ new KvRangeScan.KvRangeScanBuilder()
+ .start("_".getBytes())
+ .end("z".getBytes())
+ .startInclusive(false)
+ .endInclusive(false)
+ .build());
+
+ // 7 for real-data(3 testA, 2 testB, 2 testC), 3 commit marks can't be seen as they start with
+ // 0x1E, last_timestamp can be seen as they have not been stored to the backend.
+ Assertions.assertEquals(7, allData.size());
+
+ KvGarbageCollector kvGarbageCollector = new KvGarbageCollector(kvBackend, config);
+ Mockito.doReturn(2000L).when(config).get(KV_DELETE_AFTER_TIME);
+
+ // Wait TTL time to make sure the data is expired, please see ENTITY_KV_TTL
+ Thread.sleep(3000);
+ kvGarbageCollector.collectAndClean();
+
+ allData =
+ kvBackend.scan(
+ new KvRangeScan.KvRangeScanBuilder()
+ .start("_".getBytes())
+ .end("z".getBytes())
+ .startInclusive(false)
+ .endInclusive(false)
+ .build());
+ // Except version 3 of testA and version 2 of testB will be left, all will be removed, so the
+ // left key-value paris will be 2(real-data)
+ Assertions.assertEquals(2, allData.size());
+ Assertions.assertEquals("v3", new String(transactionalKvBackend.get("testA".getBytes())));
+ Assertions.assertEquals("v2", new String(transactionalKvBackend.get("testB".getBytes())));
+ Assertions.assertNull(transactionalKvBackend.get("testC".getBytes()));
+ }
+ }
+}
diff --git a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvNameMappingService.java b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvNameMappingService.java
index 1a05892f09..5bdb5db258 100644
--- a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvNameMappingService.java
+++ b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvNameMappingService.java
@@ -9,6 +9,7 @@ import static com.datastrato.gravitino.Configs.DEFAULT_ENTITY_KV_STORE;
import static com.datastrato.gravitino.Configs.ENTITY_KV_STORE;
import static com.datastrato.gravitino.Configs.ENTITY_STORE;
import static com.datastrato.gravitino.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;
+import static com.datastrato.gravitino.Configs.KV_DELETE_AFTER_TIME;
import static com.datastrato.gravitino.Configs.STORE_TRANSACTION_MAX_SKEW_TIME;
import com.datastrato.gravitino.Config;
@@ -38,6 +39,7 @@ public class TestKvNameMappingService {
Mockito.when(config.get(STORE_TRANSACTION_MAX_SKEW_TIME)).thenReturn(3000L);
Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");
Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFAULT_ENTITY_KV_STORE);
+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);
return config;
}
diff --git a/docs/gravitino-server-config.md b/docs/gravitino-server-config.md
index 468eed85be..cb09e77463 100644
--- a/docs/gravitino-server-config.md
+++ b/docs/gravitino-server-config.md
@@ -35,12 +35,13 @@ The following table lists the configuration items in the `gravitino.conf` file.
### Storage configuration
-| Configuration item | Description | Default value | Since version |
-|---------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------|---------------|
-| `gravitino.entity.store` | Which storage implementation to use, currently we only support key-value pair storage, default value is `kv`. | `kv` | 0.1.0 |
-| `gravitino.entity.store.kv` | Detailed implementation of kv storage, currently we only support `RocksDB` storage implementation `RocksDBKvBackend`. | `RocksDBKvBackend` | 0.1.0 |
-| `gravitino.entity.store.kv.rocksdbPath` | Directory path of `RocksDBKvBackend`, **we highly recommend you to change this default value** as it's under the deploy directory and version update operations may remove it. | `${GRAVITINO_HOME}/data/rocksdb` | 0.1.0 |
-| `gravitino.entity.store.maxTransactionSkewTimeMs` | The max skew time of transaction, unit: millisecond. | `2000` | 0.3.0 |
+| Configuration item | Description | Default value | Since version |
+|---------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------|---------------|
+| `gravitino.entity.store` | Which storage implementation to use, currently we only support key-value pair storage, default value is `kv`. | `kv` | 0.1.0 |
+| `gravitino.entity.store.kv` | Detailed implementation of kv storage, currently we only support `RocksDB` storage implementation `RocksDBKvBackend`. | `RocksDBKvBackend` | 0.1.0 |
+| `gravitino.entity.store.kv.rocksdbPath` | Directory path of `RocksDBKvBackend`, **we highly recommend you to change this default value** as it's under the deploy directory and version update operations may remove it. | `${GRAVITINO_HOME}/data/rocksdb` | 0.1.0 |
+| `gravitino.entity.store.maxTransactionSkewTimeMs` | The max skew time of transaction, unit: millisecond. | `2000` | 0.3.0 |
+| `gravitino.entity.store.kv.deleteAfterTimeMs` | The max time that the deleted data and old version data will keep, unit: millisecond. At least 10 minutes and should not larger than 30 days | `604800000`(7 days) | 0.3.0 |
### Catalog configuration