Skip to content

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

[#1597] feat(core): Support entity decoder (#1604)

Qi Yua20589e89f00
diff --git a/core/src/main/java/com/datastrato/gravitino/Entity.java b/core/src/main/java/com/datastrato/gravitino/Entity.java
index 8d5ec9b259..65e3d073a9 100644
--- a/core/src/main/java/com/datastrato/gravitino/Entity.java
+++ b/core/src/main/java/com/datastrato/gravitino/Entity.java
@@ -31,6 +31,15 @@ public interface Entity extends Serializable {
this.shortName = shortName;
this.index = index;
}
+
+ public static EntityType fromShortName(String shortName) {
+ for (EntityType entityType : EntityType.values()) {
+ if (entityType.shortName.equals(shortName)) {
+ return entityType;
+ }
+ }
+ throw new IllegalArgumentException("Unknown entity type: " + shortName);
+ }
}
/**
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/EntityKeyEncoder.java b/core/src/main/java/com/datastrato/gravitino/storage/EntityKeyEncoder.java
index 1c4a07c4af..fcbea84c2c 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/EntityKeyEncoder.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/EntityKeyEncoder.java
@@ -8,6 +8,7 @@ package com.datastrato.gravitino.storage;
import com.datastrato.gravitino.Entity.EntityType;
import com.datastrato.gravitino.NameIdentifier;
import java.io.IOException;
+import org.apache.commons.lang3.tuple.Pair;
/** Interface for encoding entity to storage it in underlying storage. E.g., RocksDB. */
public interface EntityKeyEncoder<T> {
@@ -33,4 +34,15 @@ public interface EntityKeyEncoder<T> {
* @throws IOException Exception if error occurs
*/
T encode(NameIdentifier ident, EntityType type, boolean nullIfMissing) throws IOException;
+
+ /**
+ * Decode the key to NameIdentifier and EntityType.
+ *
+ * @param key the key to decode
+ * @return the pair of NameIdentifier and EntityType
+ * @throws IOException Exception if error occurs
+ */
+ default Pair<NameIdentifier, EntityType> decode(T key) throws IOException {
+ throw new UnsupportedOperationException("Not implemented yet");
+ }
}
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/NameMappingService.java b/core/src/main/java/com/datastrato/gravitino/storage/NameMappingService.java
index 7458a8beed..83136bb22c 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/NameMappingService.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/NameMappingService.java
@@ -25,6 +25,15 @@ public interface NameMappingService extends AutoCloseable {
*/
Long getIdByName(String name) throws IOException;
+ /**
+ * Get name by id in the mapping service.
+ *
+ * @param id the id of the name
+ * @return the name of the id, or null if the id does not exist
+ * @throws IOException
+ */
+ String getNameById(long id) throws IOException;
+
/**
* Get id from name. If the name does not exist, we will create a new id for the name and bind the
* mapping between them
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/BinaryEntityKeyEncoder.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/BinaryEntityKeyEncoder.java
index c9c7e7c183..3de6930ef6 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/BinaryEntityKeyEncoder.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/BinaryEntityKeyEncoder.java
@@ -26,6 +26,7 @@ import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -197,4 +198,39 @@ public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {
throws IOException {
return encodeEntity(ident, type, nullIfMissing);
}
+
+ /**
+ * Decodes a byte array into an entity object and corresponding entity type.
+ *
+ * @param key The byte array representing the encoded key.
+ * @return The decoded entity object and corresponding entity type.
+ * @throws IOException
+ */
+ @Override
+ public Pair<NameIdentifier, EntityType> decode(byte[] key) throws IOException {
+ String entityTypeString = new String(ArrayUtils.subarray(key, 0, 2), StandardCharsets.UTF_8);
+ EntityType entityType = EntityType.fromShortName(entityTypeString);
+
+ // If the entity type is a table, the key is encoded as:
+ // ta/{metalake_id}/{catalog_id}/{schema_id}/{table_id} and the length of the id is 8;
+ byte[] idArrays = ArrayUtils.subarray(key, 3, key.length);
+ long[] ids = new long[(idArrays.length + 1) / 9];
+ int index = 0;
+ for (int i = 0; i < ids.length; i++) {
+ ids[i] = ByteUtils.byteToLong(ArrayUtils.subarray(idArrays, index, index + 8));
+ index += 9;
+ }
+
+ // Please review the id-name mapping content in KvNameMappingService.java and
+ // method generateMappingKey in this class.
+ String[] names = new String[ids.length];
+ for (int i = 0; i < ids.length; i++) {
+ // The format of name is like '{metalake_id}/{catalog_id}/schema_name'
+ String name = nameMappingService.getNameById(ids[i]);
+ names[i] = name.split(NAMESPACE_SEPARATOR, i + 1)[i];
+ }
+
+ NameIdentifier nameIdentifier = NameIdentifier.of(names);
+ return Pair.of(nameIdentifier, entityType);
+ }
}
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 d985e7c2f9..f3e7f975e2 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
@@ -380,10 +380,15 @@ public class KvEntityStore implements EntityStore {
.build());
if (!cascade && !kvs.isEmpty()) {
+ List<NameIdentifier> subEntities = Lists.newArrayListWithCapacity(kvs.size());
+ for (Pair<byte[], byte[]> pair : kvs) {
+ subEntities.add(entityKeyEncoder.decode(pair.getLeft()).getLeft());
+ }
+
throw new NonEmptyEntityException(
String.format(
- "Entity %s has sub-entities, you should remove sub-entities first",
- ident));
+ "Entity %s has sub-entities %s, you should remove sub-entities first",
+ ident, subEntities));
}
for (byte[] prefix : subEntityPrefix) {
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
index b481e63541..1e178aedf0 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvGarbageCollector.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvGarbageCollector.java
@@ -188,6 +188,7 @@ public final class KvGarbageCollector implements Closeable {
// All keys in this transaction have been deleted, we can remove the commit mark.
if (keysDeletedCount == keysInTheTransaction.size()) {
+ LOG.info("Physically delete commit mark: {}", Bytes.wrap(kv.getKey()));
kvBackend.delete(kv.getKey());
}
}
diff --git a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvNameMappingService.java b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvNameMappingService.java
index 1dc3a5bd0e..21a4e1d46e 100644
--- a/core/src/main/java/com/datastrato/gravitino/storage/kv/KvNameMappingService.java
+++ b/core/src/main/java/com/datastrato/gravitino/storage/kv/KvNameMappingService.java
@@ -65,6 +65,20 @@ public class KvNameMappingService implements NameMappingService {
lock);
}
+ @Override
+ public String getNameById(long id) throws IOException {
+ byte[] idByte = getIdKey(id);
+ return FunctionUtils.executeWithReadLock(
+ () ->
+ FunctionUtils.executeInTransaction(
+ () -> {
+ byte[] name = transactionalKvBackend.get(idByte);
+ return idByte == null ? null : new String(name);
+ },
+ transactionalKvBackend),
+ lock);
+ }
+
private long bindNameAndId(String name) throws IOException {
byte[] nameByte = getNameKey(name);
long id = idGenerator.nextId();
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 89cb2d16e2..6bc1bc95c4 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
@@ -28,10 +28,16 @@ import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
+import java.util.Random;
+import java.util.stream.Stream;
+import org.apache.commons.lang3.tuple.Pair;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mockito;
@TestInstance(Lifecycle.PER_CLASS)
@@ -92,6 +98,9 @@ public class TestEntityKeyEncoding {
ByteUtils.longToByte(0L));
Assertions.assertArrayEquals(expectKey, realKey);
+ NameIdentifier decodeIdentifier = encoder.decode(realKey).getKey();
+ Assertions.assertEquals(mateLakeIdentifier1, decodeIdentifier);
+
// name ---> id
// catalog1 --> 1
// catalog2 --> 2
@@ -115,6 +124,8 @@ public class TestEntityKeyEncoding {
BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(1L + i));
Assertions.assertArrayEquals(expectKey, realKey);
+ decodeIdentifier = encoder.decode(realKey).getKey();
+ Assertions.assertEquals(identifier, decodeIdentifier);
}
// name ---> id
@@ -142,6 +153,8 @@ public class TestEntityKeyEncoding {
BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(4L + i));
Assertions.assertArrayEquals(expectKey, realKey);
+ decodeIdentifier = encoder.decode(realKey).getKey();
+ Assertions.assertEquals(identifier, decodeIdentifier);
}
// name ---> id
@@ -171,6 +184,8 @@ public class TestEntityKeyEncoding {
BYTABLE_NAMESPACE_SEPARATOR,
ByteUtils.longToByte(i + 7L));
Assertions.assertArrayEquals(expectKey, realKey);
+ decodeIdentifier = encoder.decode(realKey).getKey();
+ Assertions.assertEquals(identifier, decodeIdentifier);
}
// Unsupported operation
@@ -262,4 +277,73 @@ public class TestEntityKeyEncoding {
EntityType.COLUMN));
}
}
+
+ // Create random names for name identifiers.
+ private static Stream<Arguments> provideParameters() {
+ Random random = new Random();
+ Arguments[] arguments = new Arguments[100];
+ int identifierNameLen = 16;
+
+ for (int i = 0; i < 100; i++) {
+ String[] value = new String[4];
+ for (int j = 0; j < 4; j++) {
+ String tmp = "";
+ int current = 0;
+ while (current < identifierNameLen) {
+ int v;
+ while ((v = random.nextInt(127)) < 32) {}
+ if (v % 4 == 0) {
+ v = 47;
+ }
+
+ tmp += ((char) v);
+ current++;
+ }
+
+ value[j] = tmp;
+ }
+
+ arguments[i] = Arguments.of((Object[]) value);
+ }
+
+ return Stream.of(arguments);
+ }
+
+ @ParameterizedTest
+ @MethodSource("provideParameters")
+ void testSpecialCharacterDecoder(
+ String metalakeName, String catalogName, String schemaName, String tableName)
+ throws IOException {
+ Config config = getConfig();
+ try (KvEntityStore kvEntityStore = getKvEntityStore(config)) {
+ BinaryEntityKeyEncoder encoder = (BinaryEntityKeyEncoder) kvEntityStore.entityKeyEncoder;
+
+ NameIdentifier identifier = NameIdentifier.of(Namespace.of(), metalakeName);
+ byte[] key = encoder.encode(identifier, EntityType.METALAKE);
+
+ Pair<NameIdentifier, EntityType> nameIdentifierEntityTypePair = encoder.decode(key);
+ Assertions.assertEquals(identifier, nameIdentifierEntityTypePair.getKey());
+ Assertions.assertEquals(EntityType.METALAKE, nameIdentifierEntityTypePair.getValue());
+
+ identifier = NameIdentifier.of(Namespace.of(metalakeName), catalogName);
+ key = encoder.encode(identifier, EntityType.CATALOG);
+ nameIdentifierEntityTypePair = encoder.decode(key);
+ Assertions.assertEquals(identifier, nameIdentifierEntityTypePair.getKey());
+ Assertions.assertEquals(EntityType.CATALOG, nameIdentifierEntityTypePair.getValue());
+
+ // Test Schema
+ identifier = NameIdentifier.of(Namespace.of(catalogName, catalogName), schemaName);
+ key = encoder.encode(identifier, EntityType.SCHEMA);
+ nameIdentifierEntityTypePair = encoder.decode(key);
+ Assertions.assertEquals(identifier, nameIdentifierEntityTypePair.getKey());
+ Assertions.assertEquals(EntityType.SCHEMA, nameIdentifierEntityTypePair.getValue());
+
+ // Test Table
+ identifier = NameIdentifier.of(Namespace.of(catalogName, catalogName, schemaName), tableName);
+ key = encoder.encode(identifier, EntityType.TABLE);
+ nameIdentifierEntityTypePair = encoder.decode(key);
+ Assertions.assertEquals(identifier, nameIdentifierEntityTypePair.getKey());
+ Assertions.assertEquals(EntityType.TABLE, nameIdentifierEntityTypePair.getValue());
+ }
+ }
}
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 a0afdd6137..f45bc620a6 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
@@ -550,9 +550,11 @@ public class TestKvEntityStorage {
Assertions.assertTrue(store.exists(table1InSchema2.nameIdentifier(), EntityType.TABLE));
// Delete the schema 'metalake.catalog.schema1' but failed, because it ha sub-entities;
- Assertions.assertThrowsExactly(
- NonEmptyEntityException.class,
- () -> store.delete(schema1.nameIdentifier(), EntityType.SCHEMA));
+ NonEmptyEntityException exception =
+ Assertions.assertThrowsExactly(
+ NonEmptyEntityException.class,
+ () -> store.delete(schema1.nameIdentifier(), EntityType.SCHEMA));
+ Assertions.assertTrue(exception.getMessage().contains("metalake.catalog.schema1.table1"));
// Make sure schema 'metalake.catalog.schema1' and table 'metalake.catalog.schema1.table1'
// has not been deleted yet;
Assertions.assertTrue(store.exists(schema1.nameIdentifier(), EntityType.SCHEMA));