Skip to content

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

[#232] refactor(core): Implement NameMappingService with key-value store (#246)

Qi Yu46a35a9844ee
diff --git a/core/src/main/java/com/datastrato/graviton/storage/InMemoryNameMappingService.java b/core/src/main/java/com/datastrato/graviton/storage/InMemoryNameMappingService.java
deleted file mode 100644
index fab2a90243..0000000000
--- a/core/src/main/java/com/datastrato/graviton/storage/InMemoryNameMappingService.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright 2023 Datastrato.
- * This software is licensed under the Apache License version 2.
- */
-
-package com.datastrato.graviton.storage;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Maps;
-import java.util.Map;
-
-/**
- * In memory implemention for {@link NameMappingService}
- *
- * <p>Note, This class is only for test usage, please do not use it in production.
- */
-public class InMemoryNameMappingService implements NameMappingService {
- private final Map<String, Long> nameToId = Maps.newHashMap();
-
- private final IdGenerator idGenerator;
-
- public static final InMemoryNameMappingService INSTANCE = new InMemoryNameMappingService();
-
- public InMemoryNameMappingService() {
- // Make configurable.
- this.idGenerator = new RandomIdGenerator();
- }
-
- @Override
- public synchronized Long get(String name) {
- return nameToId.get(name);
- }
-
- @Override
- public synchronized Long create(String name) {
- // Should handle race condition.
- long nextId = idGenerator.nextId();
- nameToId.put(name, nextId);
- return nextId;
- }
-
- @Override
- public synchronized boolean update(String oldName, String newName) {
- Preconditions.checkState(nameToId.containsKey(oldName), "Name %s does not exist", oldName);
- Long id = nameToId.remove(oldName);
- nameToId.put(newName, id);
- return true;
- }
-
- @Override
- public boolean delete(String name) {
- return nameToId.remove(name) != null;
- }
-}
diff --git a/core/src/main/java/com/datastrato/graviton/storage/NameMappingService.java b/core/src/main/java/com/datastrato/graviton/storage/NameMappingService.java
index eda966e8fb..141d9269ec 100644
--- a/core/src/main/java/com/datastrato/graviton/storage/NameMappingService.java
+++ b/core/src/main/java/com/datastrato/graviton/storage/NameMappingService.java
@@ -14,7 +14,7 @@ import java.io.IOException;
*
* <p>Note. Implementations of this interface should be thread-safe.
*/
-public interface NameMappingService {
+public interface NameMappingService extends AutoCloseable {
/**
* Get id from name.
@@ -23,20 +23,24 @@ public interface NameMappingService {
* @return the id of the name, or null if the name does not exist
* @throws IOException if the underlying storage failed
*/
- Long get(String name) throws IOException;
+ Long getIdByName(String name) throws IOException;
/**
- * If we do not find the id of the name, we create a new id for the name.
+ * If we do not find the id of the name in the name mapping service. We will add a new id for the
+ * name mapping
+ *
+ * <p>Note, this method should be called in transaction.
*
* @param name the name of the entity
- * @return the id of the name, or null if the name does not exist
+ * @param id the id of the name to be binded
* @throws IOException if the underlying storage failed
*/
- Long create(String name) throws IOException;
+ void bindNameAndId(String name, long id) throws IOException;
/**
* Update the mapping of the name to id. This method is used to update the mapping when we rename
- * an entity. Please see the example
+ * an entity. E.g., If we change the name of entity from oldName to nameName, the following is the
+ * mapping before and after the update.
*
* <pre>
* Before:
@@ -50,16 +54,17 @@ public interface NameMappingService {
*
* @param oldName name to be updated
* @param newName new name
+ * @return true if the name exists and is updated successfully, false if the name does not exist
* @throws IOException if the underlying storage failed
*/
- boolean update(String oldName, String newName) throws IOException;
+ boolean updateName(String oldName, String newName) throws IOException;
/**
- * Delete id mapping for name. Ignore if the name does not exist.
+ * Unbind id-name mapping. Ignore if the name does not exist.
*
- * @param name name to be deleted
+ * @param name name to be unbined
* @return true if the name exists and is deleted successfully, false if the name does not exist
* @throws IOException if the underlying storage failed
*/
- boolean delete(String name) throws IOException;
+ boolean unbindNameAndId(String name) throws IOException;
}
diff --git a/core/src/main/java/com/datastrato/graviton/storage/RandomIdGenerator.java b/core/src/main/java/com/datastrato/graviton/storage/RandomIdGenerator.java
index 9fd15a0a92..072285fb04 100644
--- a/core/src/main/java/com/datastrato/graviton/storage/RandomIdGenerator.java
+++ b/core/src/main/java/com/datastrato/graviton/storage/RandomIdGenerator.java
@@ -15,8 +15,11 @@ public class RandomIdGenerator implements IdGenerator {
public static final RandomIdGenerator INSTACNE = new RandomIdGenerator();
+ public static final long MAX_ID = 0x7fffffffffffffffL;
+
@Override
public long nextId() {
- return UUID.randomUUID().getLeastSignificantBits();
+ // Make sure this is a postive number.
+ return UUID.randomUUID().getLeastSignificantBits() & MAX_ID;
}
}
diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.java b/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.java
index 75bb5e2646..4433046595 100644
--- a/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.java
+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/BinaryEntityKeyEncoder.java
@@ -14,6 +14,7 @@ import com.datastrato.graviton.Entity.EntityType;
import com.datastrato.graviton.NameIdentifier;
import com.datastrato.graviton.exceptions.NoSuchEntityException;
import com.datastrato.graviton.storage.EntityKeyEncoder;
+import com.datastrato.graviton.storage.IdGenerator;
import com.datastrato.graviton.util.ByteUtils;
import com.datastrato.graviton.util.Bytes;
import com.google.common.annotations.VisibleForTesting;
@@ -77,8 +78,11 @@ public class BinaryEntityKeyEncoder implements EntityKeyEncoder<byte[]> {
SCHEMA, new String[] {SCHEMA.getShortName() + "_", "_", "_"},
TABLE, new String[] {TABLE.getShortName() + "_", "_", "_", "_"});
- public BinaryEntityKeyEncoder(KvBackend backend) {
+ private IdGenerator idGenerator;
+
+ public BinaryEntityKeyEncoder(KvBackend backend, IdGenerator idGenerator) {
this.backend = backend;
+ this.idGenerator = idGenerator;
}
/**
diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java b/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java
index b3eae966c1..76858b72a0 100644
--- a/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java
+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/KvEntityStore.java
@@ -19,6 +19,8 @@ import com.datastrato.graviton.NameIdentifier;
import com.datastrato.graviton.Namespace;
import com.datastrato.graviton.exceptions.NoSuchEntityException;
import com.datastrato.graviton.storage.EntityKeyEncoder;
+import com.datastrato.graviton.storage.IdGenerator;
+import com.datastrato.graviton.storage.RandomIdGenerator;
import com.datastrato.graviton.util.Bytes;
import com.datastrato.graviton.util.Executable;
import com.google.common.annotations.VisibleForTesting;
@@ -50,7 +52,9 @@ public class KvEntityStore implements EntityStore {
@Override
public void initialize(Config config) throws RuntimeException {
this.backend = createKvEntityBackend(config);
- this.entityKeyEncoder = new BinaryEntityKeyEncoder(backend);
+ // TODO (yuqi) Make idGenerator configurable
+ IdGenerator idGenerator = new RandomIdGenerator();
+ this.entityKeyEncoder = new BinaryEntityKeyEncoder(backend, idGenerator);
}
@Override
diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/KvNameMappingService.java b/core/src/main/java/com/datastrato/graviton/storage/kv/KvNameMappingService.java
new file mode 100644
index 0000000000..fb82d55c02
--- /dev/null
+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/KvNameMappingService.java
@@ -0,0 +1,112 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.graviton.storage.kv;
+
+import com.datastrato.graviton.storage.NameMappingService;
+import com.datastrato.graviton.util.ByteUtils;
+import com.datastrato.graviton.util.Bytes;
+import com.google.common.annotations.VisibleForTesting;
+import java.io.IOException;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import javax.annotation.concurrent.ThreadSafe;
+
+/**
+ * {@link KvNameMappingService} is an implementation that use {@link KvBackend} to store name to id
+ * mapping.
+ */
+@ThreadSafe
+public class KvNameMappingService implements NameMappingService {
+
+ // TODO(yuqi) Make this configurable
+ @VisibleForTesting final KvBackend backend;
+ private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
+
+ // name prefix of name in name to id mapping,
+ // e.g., name_metalake1 -> 1
+ // name_metalake2 -> 2
+ private static final byte[] NAME_PREFIX = "name_".getBytes();
+
+ // id prefix of id in name to id mapping,
+ // e.g., id_1 -> metalake1
+ // id_2 -> metalake2
+ private static final byte[] ID_PREFIX = "id_".getBytes();
+
+ public KvNameMappingService(KvBackend backend) {
+ this.backend = backend;
+ }
+
+ @Override
+ public Long getIdByName(String name) throws IOException {
+ lock.readLock().lock();
+ try {
+ byte[] nameByte = Bytes.concat(NAME_PREFIX, name.getBytes());
+ byte[] idByte = backend.get(nameByte);
+ return idByte == null ? null : ByteUtils.byteToLong(idByte);
+ } finally {
+ lock.readLock().unlock();
+ }
+ }
+
+ @Override
+ public void bindNameAndId(String name, long id) throws IOException {
+ byte[] nameByte = Bytes.concat(NAME_PREFIX, name.getBytes());
+
+ lock.writeLock().lock();
+ try {
+ backend.executeInTransaction(
+ () -> {
+ backend.put(nameByte, ByteUtils.longToByte(id), false);
+ byte[] idByte = Bytes.concat(ID_PREFIX, ByteUtils.longToByte(id));
+ backend.put(idByte, name.getBytes(), false);
+ return null;
+ });
+ } finally {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public boolean updateName(String oldName, String newName) throws IOException {
+ lock.writeLock().lock();
+ try {
+ return backend.executeInTransaction(
+ () -> {
+ byte[] nameByte = Bytes.concat(NAME_PREFIX, oldName.getBytes());
+ byte[] oldIdValue = backend.get(nameByte);
+
+ // Old mapping has been deleted, no need to do it;
+ if (oldIdValue == null) {
+ return false;
+ }
+ // Delete old name --> id mapping
+ backend.delete(nameByte);
+
+ backend.put(Bytes.concat(NAME_PREFIX, newName.getBytes()), oldIdValue, false);
+ backend.put(Bytes.concat(ID_PREFIX, oldIdValue), newName.getBytes(), true);
+ return true;
+ });
+ } finally {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public boolean unbindNameAndId(String name) throws IOException {
+ byte[] nameByte = Bytes.concat(NAME_PREFIX, name.getBytes());
+
+ lock.writeLock().lock();
+ try {
+ return backend.delete(nameByte);
+ } finally {
+ lock.writeLock().unlock();
+ }
+ }
+
+ @Override
+ public void close() throws Exception {
+ backend.close();
+ }
+}
diff --git a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java
index 34fa2ca0a8..a9631c3d24 100644
--- a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java
+++ b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityKeyEncoding.java
@@ -21,6 +21,7 @@ import com.datastrato.graviton.EntityStore;
import com.datastrato.graviton.EntityStoreFactory;
import com.datastrato.graviton.NameIdentifier;
import com.datastrato.graviton.Namespace;
+import com.datastrato.graviton.storage.RandomIdGenerator;
import com.datastrato.graviton.util.ByteUtils;
import com.datastrato.graviton.util.Bytes;
import java.io.IOException;
@@ -54,7 +55,9 @@ public class TestEntityKeyEncoding {
ENTITY_STORE_INSTANCE.initialize(config);
ENTITY_STORE_INSTANCE.setSerDe(
EntitySerDeFactory.createEntitySerDe(config.get(Configs.ENTITY_SERDE)));
- ENCODER = new BinaryEntityKeyEncoder(((KvEntityStore) ENTITY_STORE_INSTANCE).getBackend());
+ ENCODER =
+ new BinaryEntityKeyEncoder(
+ ((KvEntityStore) ENTITY_STORE_INSTANCE).getBackend(), new RandomIdGenerator());
}
@AfterEach
diff --git a/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvNameMappingService.java b/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvNameMappingService.java
new file mode 100644
index 0000000000..e46acb86d3
--- /dev/null
+++ b/core/src/test/java/com/datastrato/graviton/storage/kv/TestKvNameMappingService.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.graviton.storage.kv;
+
+import static com.datastrato.graviton.Configs.DEFUALT_ENTITY_KV_STORE;
+import static com.datastrato.graviton.Configs.ENTITY_KV_STORE;
+import static com.datastrato.graviton.Configs.ENTITY_STORE;
+import static com.datastrato.graviton.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;
+
+import com.datastrato.graviton.Config;
+import com.datastrato.graviton.Configs;
+import com.datastrato.graviton.storage.IdGenerator;
+import com.datastrato.graviton.storage.NameMappingService;
+import com.datastrato.graviton.storage.RandomIdGenerator;
+import java.io.IOException;
+import org.apache.commons.io.FileUtils;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.ClassOrderer.OrderAnnotation;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestClassOrder;
+import org.mockito.Mockito;
+
+@TestClassOrder(OrderAnnotation.class)
+public class TestKvNameMappingService {
+
+ public static final String ROCKS_DB_STORE_PATH = "/tmp/graviton_name_mapping";
+ private IdGenerator idGenerator = new RandomIdGenerator();
+
+ @BeforeEach
+ public void cleanEnv() {
+ try {
+ FileUtils.deleteDirectory(FileUtils.getFile(ROCKS_DB_STORE_PATH));
+ } catch (Exception e) {
+ // Ignore
+ }
+ }
+
+ private KvNameMappingService createNameMappingService(String kvPath) throws IOException {
+ Config config = Mockito.mock(Config.class);
+ Mockito.when(config.get(ENTITY_STORE)).thenReturn("kv");
+ Mockito.when(config.get(ENTITY_KV_STORE)).thenReturn(DEFUALT_ENTITY_KV_STORE);
+ Mockito.when(config.get(Configs.ENTITY_SERDE)).thenReturn("proto");
+ Mockito.when(config.get(ENTRY_KV_ROCKSDB_BACKEND_PATH)).thenReturn(kvPath);
+
+ KvBackend backend = new RocksDBKvBackend();
+ backend.initialize(config);
+ return new KvNameMappingService(backend);
+ }
+
+ @Test
+ @Order(1)
+ public void testGetIdByName() throws Exception {
+ IdGenerator idGenerator = new RandomIdGenerator();
+ try (NameMappingService nameMappingService =
+ createNameMappingService(ROCKS_DB_STORE_PATH + "/1")) {
+ Assertions.assertNull(nameMappingService.getIdByName("name1"));
+ long name1Id = idGenerator.nextId();
+ nameMappingService.bindNameAndId("name1", name1Id);
+ Long name1IdRead = nameMappingService.getIdByName("name1");
+ Assertions.assertEquals(name1Id, name1IdRead);
+
+ Assertions.assertNull(nameMappingService.getIdByName("name2"));
+ long name2Id = idGenerator.nextId();
+ nameMappingService.bindNameAndId("name2", name2Id);
+ Long name2IdRead = nameMappingService.getIdByName("name2");
+ Assertions.assertEquals(name2Id, name2IdRead);
+ }
+ }
+
+ @Test
+ @Order(2)
+ public void testUpdateName() throws Exception {
+ long name1Id = idGenerator.nextId();
+ try (NameMappingService nameMappingService =
+ createNameMappingService(ROCKS_DB_STORE_PATH + "/2")) {
+ nameMappingService.bindNameAndId("name1", name1Id);
+ Assertions.assertNotNull(nameMappingService.getIdByName("name1"));
+
+ long name2Id = idGenerator.nextId();
+ nameMappingService.bindNameAndId("name2", name2Id);
+ Assertions.assertNotNull(nameMappingService.getIdByName("name1"));
+ Assertions.assertNotEquals(name1Id, name2Id);
+
+ boolean result = nameMappingService.updateName("name1", "name3");
+ Assertions.assertTrue(result);
+
+ Long name3Id = nameMappingService.getIdByName("name3");
+ Assertions.assertEquals(name1Id, name3Id);
+ Assertions.assertNull(nameMappingService.getIdByName("name1"));
+
+ Assertions.assertFalse(nameMappingService.updateName("name1", "name4"));
+ }
+ }
+
+ @Test
+ @Order(3)
+ public void testBindAndUnBind() throws IOException {
+ long name1Id = idGenerator.nextId();
+ NameMappingService nameMappingService = createNameMappingService(ROCKS_DB_STORE_PATH + "/3");
+ nameMappingService.bindNameAndId("name1", name1Id);
+ Assertions.assertNotNull(nameMappingService.getIdByName("name1"));
+
+ boolean result = nameMappingService.unbindNameAndId("name1");
+ Assertions.assertTrue(result);
+ Assertions.assertNull(nameMappingService.getIdByName("name1"));
+
+ long name2Id = idGenerator.nextId();
+ nameMappingService.bindNameAndId("name2", name2Id);
+
+ KvBackend spyKvBackend = Mockito.spy(((KvNameMappingService) nameMappingService).backend);
+ Mockito.doThrow(new ArithmeticException()).when(spyKvBackend).delete(Mockito.any());
+ final NameMappingService mock = new KvNameMappingService(spyKvBackend);
+
+ // Now we try to use update. It should fail.
+ Assertions.assertThrowsExactly(
+ ArithmeticException.class, () -> mock.updateName("name2", "name3"));
+ Assertions.assertNull(mock.getIdByName("name3"));
+ Assertions.assertNotNull(mock.getIdByName("name2"));
+ }
+}