Skip to content

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

[#121] feat(storage): Implement RocksDB storage backend for EntityStore (#125)

Qi Yu247ee4a00b98
diff --git a/core/build.gradle.kts b/core/build.gradle.kts
index cae7036a07..4d57bde791 100644
--- a/core/build.gradle.kts
+++ b/core/build.gradle.kts
@@ -26,6 +26,7 @@ dependencies {
implementation(libs.commons.lang3)
implementation(libs.commons.io)
implementation(libs.caffeine)
+ implementation(libs.rocksdbjni)
compileOnly(libs.lombok)
annotationProcessor(libs.lombok)
diff --git a/core/src/main/java/com/datastrato/graviton/Configs.java b/core/src/main/java/com/datastrato/graviton/Configs.java
index 4845530d29..7d1d51564f 100644
--- a/core/src/main/java/com/datastrato/graviton/Configs.java
+++ b/core/src/main/java/com/datastrato/graviton/Configs.java
@@ -8,14 +8,35 @@ import com.datastrato.graviton.config.ConfigBuilder;
import com.datastrato.graviton.config.ConfigEntry;
public interface Configs {
+ String DEFUALT_ENTITY_STORE = "kv";
+ String ENTITY_STORE_KEY = "graviton.entity.store";
+
+ String DEFUALT_ENTITY_KV_STORE = "RocksDBKvBackend";
+ String ENTITY_KV_STORE_KEY = "graviton.entity.store.kv";
+
+ String ENTITY_KV_ROCKSDB_BACKEND_PATH_KEY = "graviton.entity.store.kv.rocskdb.path";
+ String DEFAULT_KV_ROCKSDB_BACKEND_PATH = "/tmp/graviton";
ConfigEntry<String> ENTITY_STORE =
- new ConfigBuilder("graviton.entity.store")
+ new ConfigBuilder(ENTITY_STORE_KEY)
.doc("The entity store to use")
.version("0.1.0")
.stringConf()
- // TODO. Change this when we have a EntityStore implementation. @Jerry
- .createWithDefault("in-memory");
+ .createWithDefault(DEFUALT_ENTITY_STORE);
+
+ ConfigEntry<String> ENTITY_KV_STORE =
+ new ConfigBuilder(ENTITY_KV_STORE_KEY)
+ .doc("The kv entity store to use")
+ .version("0.1.0")
+ .stringConf()
+ .createWithDefault(DEFUALT_ENTITY_KV_STORE);
+
+ ConfigEntry<String> ENTRY_KV_ROCKSDB_BACKEND_PATH =
+ new ConfigBuilder(ENTITY_KV_ROCKSDB_BACKEND_PATH_KEY)
+ .doc("The RocksDB backend path for entity store")
+ .version("0.1.0")
+ .stringConf()
+ .createWithDefault(DEFAULT_KV_ROCKSDB_BACKEND_PATH);
ConfigEntry<String> ENTITY_SERDE =
new ConfigBuilder("graviton.entity.serde")
diff --git a/core/src/main/java/com/datastrato/graviton/EntityStoreFactory.java b/core/src/main/java/com/datastrato/graviton/EntityStoreFactory.java
index 12027f19e9..f791f56025 100644
--- a/core/src/main/java/com/datastrato/graviton/EntityStoreFactory.java
+++ b/core/src/main/java/com/datastrato/graviton/EntityStoreFactory.java
@@ -4,8 +4,8 @@
*/
package com.datastrato.graviton;
+import com.datastrato.graviton.storage.kv.KvEntityStore;
import com.google.common.collect.ImmutableMap;
-import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -14,8 +14,9 @@ public class EntityStoreFactory {
private static final Logger LOG = LoggerFactory.getLogger(EntityStoreFactory.class);
// Register EntityStore's short name to its full qualified class name in the map. So that user
- // don't need to specify the full qualified class name when creating an EntityStore.
- private static final Map<String, String> ENTITY_STORES = ImmutableMap.of();
+ // doesn't need to specify the full qualified class name when creating an EntityStore.
+ public static final ImmutableMap<String, String> ENTITY_STORES =
+ ImmutableMap.of("kv", KvEntityStore.class.getCanonicalName());
private EntityStoreFactory() {}
diff --git a/core/src/main/java/com/datastrato/graviton/meta/CatalogEntity.java b/core/src/main/java/com/datastrato/graviton/meta/CatalogEntity.java
index 73cae274a5..e54d209d62 100644
--- a/core/src/main/java/com/datastrato/graviton/meta/CatalogEntity.java
+++ b/core/src/main/java/com/datastrato/graviton/meta/CatalogEntity.java
@@ -11,15 +11,14 @@ import com.datastrato.graviton.Entity;
import com.datastrato.graviton.Field;
import com.datastrato.graviton.HasIdentifier;
import com.datastrato.graviton.Namespace;
+import com.google.common.base.Objects;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
-import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
-@EqualsAndHashCode
@ToString
public class CatalogEntity implements Entity, Auditable, HasIdentifier {
@@ -140,4 +139,28 @@ public class CatalogEntity implements Entity, Auditable, HasIdentifier {
return catalog;
}
}
+
+ /** Attention, this method ignores the namespace field in the comparison */
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ CatalogEntity that = (CatalogEntity) o;
+ return Objects.equal(id, that.id)
+ && Objects.equal(metalakeId, that.metalakeId)
+ && Objects.equal(name, that.name)
+ && type == that.type
+ && Objects.equal(comment, that.comment)
+ && Objects.equal(properties, that.properties)
+ && Objects.equal(auditInfo, that.auditInfo);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hashCode(id, metalakeId, name, type, comment, properties, auditInfo);
+ }
}
diff --git a/core/src/main/java/com/datastrato/graviton/proto/CatalogEntitySerDe.java b/core/src/main/java/com/datastrato/graviton/proto/CatalogEntitySerDe.java
new file mode 100644
index 0000000000..68d7de8370
--- /dev/null
+++ b/core/src/main/java/com/datastrato/graviton/proto/CatalogEntitySerDe.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.graviton.proto;
+
+import com.datastrato.graviton.meta.AuditInfo;
+import com.datastrato.graviton.meta.CatalogEntity;
+
+public class CatalogEntitySerDe implements ProtoSerDe<CatalogEntity, Catalog> {
+ @Override
+ public Catalog serialize(CatalogEntity catalogEntity) {
+ Catalog.Builder builder =
+ Catalog.newBuilder()
+ .setId(catalogEntity.getId())
+ .setName(catalogEntity.name())
+ .setAuditInfo(new AuditInfoSerDe().serialize((AuditInfo) catalogEntity.auditInfo()));
+
+ if (catalogEntity.getComment() != null) {
+ builder.setComment(catalogEntity.getComment());
+ }
+
+ if (catalogEntity.getProperties() != null && !catalogEntity.getProperties().isEmpty()) {
+ builder.putAllProperties(catalogEntity.getProperties());
+ }
+
+ com.datastrato.graviton.proto.Catalog.Type type =
+ com.datastrato.graviton.proto.Catalog.Type.valueOf(catalogEntity.getType().name());
+ builder.setType(type);
+ builder.setMetalakeId(catalogEntity.getMetalakeId());
+
+ // Attention we have ignored namespace field here
+ return builder.build();
+ }
+
+ @Override
+ public CatalogEntity deserialize(Catalog p) {
+ CatalogEntity.Builder builder = new CatalogEntity.Builder();
+ builder
+ .withId(p.getId())
+ .withName(p.getName())
+ .withAuditInfo(new AuditInfoSerDe().deserialize(p.getAuditInfo()));
+
+ if (p.hasComment()) {
+ builder.withComment(p.getComment());
+ }
+
+ if (p.getPropertiesCount() > 0) {
+ builder.withProperties(p.getPropertiesMap());
+ }
+
+ builder.withType(com.datastrato.graviton.Catalog.Type.valueOf(p.getType().name()));
+ builder.withMetalakeId(p.getMetalakeId());
+ return builder.build();
+ }
+}
diff --git a/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java b/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java
index e4ede1c5e9..4a472f0e14 100644
--- a/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java
+++ b/core/src/main/java/com/datastrato/graviton/proto/ProtoEntitySerDe.java
@@ -23,12 +23,15 @@ public class ProtoEntitySerDe implements EntitySerDe {
"com.datastrato.graviton.meta.AuditInfo",
"com.datastrato.graviton.proto.AuditInfoSerDe",
"com.datastrato.graviton.meta.BaseMetalake",
- "com.datastrato.graviton.proto.BaseMetalakeSerDe");
+ "com.datastrato.graviton.proto.BaseMetalakeSerDe",
+ "com.datastrato.graviton.meta.CatalogEntity",
+ "com.datastrato.graviton.proto.CatalogEntitySerDe");
private static final Map<String, String> ENTITY_TO_PROTO =
ImmutableMap.of(
"com.datastrato.graviton.meta.AuditInfo", "com.datastrato.graviton.proto.AuditInfo",
- "com.datastrato.graviton.meta.BaseMetalake", "com.datastrato.graviton.proto.Metalake");
+ "com.datastrato.graviton.meta.BaseMetalake", "com.datastrato.graviton.proto.Metalake",
+ "com.datastrato.graviton.meta.CatalogEntity", "com.datastrato.graviton.proto.Catalog");
private final Map<Class<? extends Entity>, ProtoSerDe<? extends Entity, ? extends Message>>
entityToSerDe;
diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/EntityKeyEncoder.java b/core/src/main/java/com/datastrato/graviton/storage/kv/EntityKeyEncoder.java
index 2c372bb9ca..6f81fd267e 100644
--- a/core/src/main/java/com/datastrato/graviton/storage/kv/EntityKeyEncoder.java
+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/EntityKeyEncoder.java
@@ -9,7 +9,7 @@ import com.datastrato.graviton.NameIdentifier;
import com.datastrato.graviton.Namespace;
/**
- * Interface for encoding entity key for KV backend, e.g. RocksDB. The key is used to store the
+ * Interface for encoding entity key for KV backend, e.g., RocksDB. The key is used to store the
* entity in the backend.
*/
public interface EntityKeyEncoder {
diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.java b/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.java
index e7bb785fb8..5f3f799150 100644
--- a/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.java
+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/KvBackend.java
@@ -6,6 +6,8 @@
package com.datastrato.graviton.storage.kv;
import com.datastrato.graviton.Config;
+import com.datastrato.graviton.EntityAlreadyExistsException;
+import com.datastrato.graviton.util.Executable;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
@@ -20,14 +22,17 @@ public interface KvBackend extends Closeable {
void initialize(Config config) throws IOException;
/**
- * Store key value pair ignoring any existing value
+ * Store a key value pair ignoring any existing value if overwrite is true. Once the value is
+ * false, it will throw {@link EntityAlreadyExistsException} if the key already exists
*
* @param key key of the pair
* @param value value of the pair
+ * @param overwrite if true, overwrite existing value
*/
- void put(byte[] key, byte[] value) throws IOException;
+ void put(byte[] key, byte[] value, boolean overwrite)
+ throws IOException, EntityAlreadyExistsException;
- /** Get value pair for key, Null if the key does not exist */
+ /** Get a value pair for a key, Null if the key does not exist */
byte[] get(byte[] key) throws IOException;
/** Delete key value pair */
@@ -43,4 +48,12 @@ public interface KvBackend extends Closeable {
* @throws IOException if exectiopn occurs
*/
List<Pair<byte[], byte[]>> scan(KvRangeScan scanRange) throws IOException;
+
+ /**
+ * Do a transactional operation on the backend
+ *
+ * @param executable
+ * @throws IOException
+ */
+ <R> R executeInTransaction(Executable<R> executable) throws IOException;
}
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 494fd25ae5..af307b422f 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
@@ -5,6 +5,8 @@
package com.datastrato.graviton.storage.kv;
+import static com.datastrato.graviton.Configs.ENTITY_KV_STORE;
+
import com.datastrato.graviton.Config;
import com.datastrato.graviton.Entity;
import com.datastrato.graviton.EntityAlreadyExistsException;
@@ -14,27 +16,35 @@ import com.datastrato.graviton.HasIdentifier;
import com.datastrato.graviton.NameIdentifier;
import com.datastrato.graviton.Namespace;
import com.datastrato.graviton.NoSuchEntityException;
+import com.datastrato.graviton.util.Bytes;
import com.datastrato.graviton.util.Executable;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
-import java.util.concurrent.locks.Lock;
+import java.util.Objects;
+import org.apache.commons.lang3.tuple.Pair;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * KV store to store entities. This means we can store entities in a key value store. i.e. RocksDB,
- * Cassandra, etc. If you want to use a different backend, you can implement the {@link
- * com.datastrato.graviton.storage.kv.KvBackend} interface
+ * KV store to store entities. This means we can store entities in a key value store. I.e. RocksDB,
+ * Cassandra, etc. If you want to use a different backend, you can implement the {@link KvBackend}
+ * interface
*/
public class KvEntityStore implements EntityStore {
+ public static final Logger LOGGER = LoggerFactory.getLogger(KvEntityStore.class);
+ public static final ImmutableMap<String, String> KV_BACKENDS =
+ ImmutableMap.of("RocksDBKvBackend", RocksDBKvBackend.class.getCanonicalName());
+
private KvBackend backend;
private EntityKeyEncoder entityKeyEncoder;
private EntitySerDe serDe;
- // TODO replaced with rocksdb transaction
- private Lock lock;
-
@Override
public void initialize(Config config) throws RuntimeException {
- // TODO
+ this.backend = createKvEntityBackend(config);
+ this.entityKeyEncoder = new CustomEntityKeyEncoder();
}
@Override
@@ -45,45 +55,81 @@ public class KvEntityStore implements EntityStore {
@Override
public <E extends Entity & HasIdentifier> List<E> list(Namespace namespace, Class<E> e)
throws IOException {
- // TODO
- return null;
+ byte[] startKey = entityKeyEncoder.encode(namespace);
+ byte[] endKey = Bytes.increment(Bytes.wrap(startKey)).get();
+ List<Pair<byte[], byte[]>> kvs =
+ backend.scan(
+ new KvRangeScan.KvRangeScanBuilder()
+ .start(startKey)
+ .end(endKey)
+ .startInclusive(true)
+ .endInclusive(false)
+ .limit(Integer.MAX_VALUE)
+ .build());
+
+ List<E> entities = Lists.newArrayList();
+ for (Pair<byte[], byte[]> pairs : kvs) {
+ entities.add(serDe.deserialize(pairs.getRight(), e));
+ }
+ // TODO (yuqi), if the list is too large, we need to do pagination or streaming
+ return entities;
}
@Override
public boolean exists(NameIdentifier ident) throws IOException {
- return false;
+ return backend.get(entityKeyEncoder.encode(ident)) != null;
}
@Override
public <E extends Entity & HasIdentifier> void put(NameIdentifier ident, E e, boolean overwritten)
throws IOException, EntityAlreadyExistsException {
- // TODO
+ // Simple implementation, just use the entity's identifier as the key
+ byte[] key = entityKeyEncoder.encode(ident);
+ byte[] value = serDe.serialize(e);
+ backend.put(key, value, overwritten);
}
@Override
public <E extends Entity & HasIdentifier> E get(NameIdentifier ident, Class<E> type)
throws NoSuchEntityException, IOException {
- // TODO
- return null;
+ byte[] key = entityKeyEncoder.encode(ident);
+ byte[] value = backend.get(key);
+ if (value == null) {
+ throw new NoSuchEntityException(ident.toString());
+ }
+ return serDe.deserialize(value, type);
}
@Override
public boolean delete(NameIdentifier ident) throws IOException {
- return false;
+ return backend.delete(entityKeyEncoder.encode(ident));
}
@Override
public <R> R executeInTransaction(Executable<R> executable) throws IOException {
- lock.lock();
- try {
- return executable.execute();
- } finally {
- lock.unlock();
- }
+ return backend.executeInTransaction(executable);
}
@Override
public void close() throws IOException {
backend.close();
}
+
+ private static KvBackend createKvEntityBackend(Config config) {
+ String backendName = config.get(ENTITY_KV_STORE);
+ String className = KV_BACKENDS.getOrDefault(backendName, backendName);
+ if (Objects.isNull(className)) {
+ throw new RuntimeException("Unsupported backend type..." + backendName);
+ }
+
+ try {
+ KvBackend kvBackend = (KvBackend) Class.forName(className).newInstance();
+ kvBackend.initialize(config);
+ return kvBackend;
+ } catch (Exception e) {
+ LOGGER.error("Failed to create and initialize KvBackend by name '{}'.", backendName, e);
+ throw new RuntimeException(
+ "Failed to create and initialize KvBackend by name: " + backendName, e);
+ }
+ }
}
diff --git a/core/src/main/java/com/datastrato/graviton/storage/kv/RocksDBKvBackend.java b/core/src/main/java/com/datastrato/graviton/storage/kv/RocksDBKvBackend.java
new file mode 100644
index 0000000000..2df3967a3d
--- /dev/null
+++ b/core/src/main/java/com/datastrato/graviton/storage/kv/RocksDBKvBackend.java
@@ -0,0 +1,229 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.graviton.storage.kv;
+
+import com.datastrato.graviton.Config;
+import com.datastrato.graviton.Configs;
+import com.datastrato.graviton.EntityAlreadyExistsException;
+import com.datastrato.graviton.util.Bytes;
+import com.datastrato.graviton.util.Executable;
+import com.google.common.collect.Lists;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import org.apache.commons.lang3.tuple.Pair;
+import org.rocksdb.Options;
+import org.rocksdb.ReadOptions;
+import org.rocksdb.RocksDB;
+import org.rocksdb.RocksDBException;
+import org.rocksdb.RocksIterator;
+import org.rocksdb.Transaction;
+import org.rocksdb.TransactionDB;
+import org.rocksdb.TransactionDBOptions;
+import org.rocksdb.WriteOptions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * {@link RocksDBKvBackend} is a RocksDB implementation of KvBackend interface. If we want to use
+ * another kv implementation, We can just implement {@link KvBackend} interface and use it in the
+ * Graviton.
+ */
+public class RocksDBKvBackend implements KvBackend {
+ public static final Logger LOGGER = LoggerFactory.getLogger(RocksDBKvBackend.class);
+ private TransactionDB db;
+
+ public static final ThreadLocal<Transaction> TX_LOCAL = new ThreadLocal<>();
+
+ /**
+ * Initialize the RocksDB backend instance. We have used the {@link TransactionDB} to support
+ * transaction instead of {@link RocksDB} instance.
+ */
+ private TransactionDB initRocksDB(Config config) throws RocksDBException {
+ RocksDB.loadLibrary();
+ final Options options = new Options();
+ options.setCreateIfMissing(true);
+
+ String dbPath = config.get(Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH);
+ File dbDir = new File(dbPath, "instance");
+ try {
+ if (!dbDir.exists() && !dbDir.mkdirs()) {
+ throw new RocksDBException(
+ String.format("Can't create RocksDB path '%s'", dbDir.getAbsolutePath()));
+ }
+ // TODO (yuqi), make options and transactionDBOptions configurable
+ TransactionDBOptions transactionDBOptions = new TransactionDBOptions();
+ return TransactionDB.open(options, transactionDBOptions, dbDir.getAbsolutePath());
+ } catch (RocksDBException ex) {
+ LOGGER.error(
+ "Error initializing RocksDB, check configurations and permissions, exception: {}, message: {}, stackTrace: {}",
+ ex.getCause(),
+ ex.getMessage(),
+ ex.getStackTrace());
+ throw ex;
+ }
+ }
+
+ @Override
+ public void initialize(Config config) throws IOException {
+ try {
+ db = initRocksDB(config);
+ } catch (RocksDBException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public void put(byte[] key, byte[] value, boolean overwrite) throws IOException {
+ Transaction tx = TX_LOCAL.get();
+ try {
+ // Do without transaction if not in transaction
+ if (tx == null) {
+ handlePutWithoutTransaction(key, value, overwrite);
+ return;
+ }
+
+ // Now try with transaction
+ handlePutWithTransaction(key, value, overwrite, tx);
+ } catch (EntityAlreadyExistsException e) {
+ throw e;
+ } catch (Throwable e) {
+ throw new IOException(e);
+ }
+ }
+
+ private void handlePutWithTransaction(byte[] key, byte[] value, boolean overwrite, Transaction tx)
+ throws RocksDBException {
+ if (overwrite) {
+ tx.put(key, value);
+ return;
+ }
+
+ byte[] existKey = tx.get(new ReadOptions(), key);
+ if (existKey != null) {
+ throw new EntityAlreadyExistsException(
+ String.format(
+ "Key %s already exists in the database, please use overwrite option to overwrite it",
+ key));
+ }
+ tx.put(key, value);
+ }
+
+ private void handlePutWithoutTransaction(byte[] key, byte[] value, boolean overwrite)
+ throws RocksDBException {
+ if (overwrite) {
+ db.put(key, value);
+ return;
+ }
+ byte[] existKey = db.get(key);
+ if (existKey != null) {
+ throw new EntityAlreadyExistsException(
+ String.format(
+ "Key %s already exists in the database, please use overwrite option to overwrite it",
+ key));
+ }
+ db.put(key, value);
+ }
+
+ @Override
+ public byte[] get(byte[] key) throws IOException {
+ try {
+ if (TX_LOCAL.get() != null) {
+ return TX_LOCAL.get().get(new ReadOptions(), key);
+ }
+
+ return db.get(key);
+ } catch (RocksDBException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public List<Pair<byte[], byte[]>> scan(KvRangeScan scanRange) throws IOException {
+ Transaction tx = TX_LOCAL.get();
+ RocksIterator rocksIterator =
+ TX_LOCAL.get() == null ? db.newIterator() : tx.getIterator(new ReadOptions());
+ rocksIterator.seek(scanRange.getStart());
+
+ List<Pair<byte[], byte[]>> result = Lists.newArrayList();
+ int count = 0;
+ while (count < scanRange.getLimit() && rocksIterator.isValid()) {
+ byte[] key = rocksIterator.key();
+ if (Bytes.wrap(key).compareTo(scanRange.getStart()) == 0) {
+ if (scanRange.isStartInclusive()) {
+ result.add(Pair.of(key, rocksIterator.value()));
+ count++;
+ }
+ } else if (Bytes.wrap(key).compareTo(scanRange.getEnd()) == 0) {
+ if (scanRange.isEndInclusive()) {
+ result.add(Pair.of(key, rocksIterator.value()));
+ }
+
+ break;
+ } else {
+ result.add(Pair.of(key, rocksIterator.value()));
+ count++;
+ }
+
+ rocksIterator.next();
+ }
+
+ rocksIterator.close();
+ return result;
+ }
+
+ @Override
+ public boolean delete(byte[] key) throws IOException {
+ try {
+ if (TX_LOCAL.get() != null) {
+ TX_LOCAL.get().delete(key);
+ return true;
+ }
+
+ db.delete(key);
+ return true;
+ } catch (RocksDBException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public void close() throws IOException {
+ db.close();
+ }
+
+ @Override
+ public <R> R executeInTransaction(Executable<R> executable) throws IOException {
+ Transaction tx = db.beginTransaction(new WriteOptions());
+ LOGGER.info("Starting transaction: {}", tx);
+ TX_LOCAL.set(tx);
+ try {
+ R r = executable.execute();
+ tx.commit();
+ return r;
+ } catch (Exception e) {
+ LOGGER.error(
+ "Error executing transaction, exception: {}, message: {}, stackTrace: {}",
+ e.getCause(),
+ e.getMessage(),
+ e.getStackTrace());
+ try {
+ tx.rollback();
+ } catch (Exception e1) {
+ LOGGER.error(
+ "Error rolling back transaction, exception: {}, message: {}, stackTrace: {}",
+ e1.getCause(),
+ e1.getMessage(),
+ e1.getStackTrace());
+ }
+ throw new IOException(e);
+ } finally {
+ tx.close();
+ LOGGER.info("Transaction close: {}", tx);
+ TX_LOCAL.remove();
+ }
+ }
+}
diff --git a/core/src/main/java/com/datastrato/graviton/util/Bytes.java b/core/src/main/java/com/datastrato/graviton/util/Bytes.java
new file mode 100644
index 0000000000..def69107e8
--- /dev/null
+++ b/core/src/main/java/com/datastrato/graviton/util/Bytes.java
@@ -0,0 +1,206 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.graviton.util;
+
+import java.io.Serializable;
+import java.util.Arrays;
+import java.util.Comparator;
+
+public class Bytes implements Comparable<byte[]> {
+
+ public static final byte[] EMPTY = new byte[0];
+
+ private static final char[] HEX_CHARS_UPPER = {
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
+ };
+
+ private final byte[] bytes;
+
+ // cache the hash code for the string, default to 0
+ private int hashCode;
+
+ public static Bytes wrap(byte[] bytes) {
+ if (bytes == null) return null;
+ return new Bytes(bytes);
+ }
+
+ /**
+ * Create a Bytes using the byte array.
+ *
+ * @param bytes This array becomes the backing storage for the object.
+ */
+ public Bytes(byte[] bytes) {
+ this.bytes = bytes;
+
+ // initialize hash code to 0
+ hashCode = 0;
+ }
+
+ /**
+ * Get the data from the Bytes.
+ *
+ * @return The underlying byte array
+ */
+ public byte[] get() {
+ return this.bytes;
+ }
+
+ /** Concat two byte arrays into one. */
+ public static byte[] concat(byte[] one, byte[] two) {
+ int totalLen = one.length + two.length;
+ byte[] res = new byte[totalLen];
+ System.arraycopy(one, 0, res, 0, one.length);
+ System.arraycopy(two, 0, res, one.length, two.length);
+ return res;
+ }
+
+ /**
+ * The hashcode is cached except for the case where it is computed as 0, in which case we compute
+ * the hashcode on every call.
+ *
+ * @return the hashcode
+ */
+ @Override
+ public int hashCode() {
+ if (hashCode == 0) {
+ hashCode = Arrays.hashCode(bytes);
+ }
+
+ return hashCode;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) return true;
+ if (other == null) return false;
+
+ // we intentionally use the function to compute hashcode here
+ if (this.hashCode() != other.hashCode()) return false;
+
+ if (other instanceof Bytes) return Arrays.equals(this.bytes, ((Bytes) other).get());
+
+ return false;
+ }
+
+ @Override
+ public int compareTo(byte[] o) {
+ return BYTES_LEXICO_COMPARATOR.compare(this.bytes, o);
+ }
+
+ @Override
+ public String toString() {
+ return Bytes.toString(bytes, 0, bytes.length);
+ }
+
+ /**
+ * Write a printable representation of a byte array. Non-printable characters are hex escaped in
+ * the format \\x%02X, eg: \x00 \x05 etc.
+ *
+ * <p>This function is brought from org.apache.hadoop.hbase.util.Bytes
+ *
+ * @param b array to write out
+ * @param off offset to start at
+ * @param len length to write
+ * @return string output
+ */
+ private static String toString(final byte[] b, int off, int len) {
+ StringBuilder result = new StringBuilder();
+
+ if (b == null) return result.toString();
+
+ // just in case we are passed a 'len' that is > buffer length...
+ if (off >= b.length) return result.toString();
+
+ if (off + len > b.length) len = b.length - off;
+
+ for (int i = off; i < off + len; ++i) {
+ int ch = b[i] & 0xFF;
+ if (ch >= ' ' && ch <= '~' && ch != '\\') {
+ result.append((char) ch);
+ } else {
+ result.append("\\x");
+ result.append(HEX_CHARS_UPPER[ch / 0x10]);
+ result.append(HEX_CHARS_UPPER[ch % 0x10]);
+ }
+ }
+ return result.toString();
+ }
+
+ /**
+ * Increment the underlying byte array by adding 1. Throws an IndexOutOfBoundsException if
+ * incrementing would cause the underlying input byte array to overflow.
+ *
+ * @param input - The byte array to increment
+ * @return A new copy of the incremented byte array.
+ */
+ public static Bytes increment(Bytes input) throws IndexOutOfBoundsException {
+ byte[] inputArr = input.get();
+ byte[] ret = new byte[inputArr.length];
+ int carry = 1;
+ for (int i = inputArr.length - 1; i >= 0; i--) {
+ if (inputArr[i] == (byte) 0xFF && carry == 1) {
+ ret[i] = (byte) 0x00;
+ } else {
+ ret[i] = (byte) (inputArr[i] + carry);
+ carry = 0;
+ }
+ }
+ if (carry == 0) {
+ return wrap(ret);
+ } else {
+ throw new IndexOutOfBoundsException();
+ }
+ }
+
+ /** A byte array comparator based on lexicograpic ordering. */
+ public static final ByteArrayComparator BYTES_LEXICO_COMPARATOR =
+ new LexicographicByteArrayComparator();
+
+ public interface ByteArrayComparator extends Comparator<byte[]>, Serializable {
+
+ int compare(
+ final byte[] buffer1,
+ int offset1,
+ int length1,
+ final byte[] buffer2,
+ int offset2,
+ int length2);
+ }
+
+ private static class LexicographicByteArrayComparator implements ByteArrayComparator {
+
+ @Override
+ public int compare(byte[] buffer1, byte[] buffer2) {
+ return compare(buffer1, 0, buffer1.length, buffer2, 0, buffer2.length);
+ }
+
+ public int compare(
+ final byte[] buffer1,
+ int offset1,
+ int length1,
+ final byte[] buffer2,
+ int offset2,
+ int length2) {
+
+ // short circuit equal case
+ if (buffer1 == buffer2 && offset1 == offset2 && length1 == length2) {
+ return 0;
+ }
+
+ // similar to Arrays.compare() but considers offset and length
+ int end1 = offset1 + length1;
+ int end2 = offset2 + length2;
+ for (int i = offset1, j = offset2; i < end1 && j < end2; i++, j++) {
+ int a = buffer1[i] & 0xff;
+ int b = buffer2[j] & 0xff;
+ if (a != b) {
+ return a - b;
+ }
+ }
+ return length1 - length2;
+ }
+ }
+}
diff --git a/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java
new file mode 100644
index 0000000000..6d56c28f2b
--- /dev/null
+++ b/core/src/test/java/com/datastrato/graviton/storage/kv/TestEntityStorageBackend.java
@@ -0,0 +1,150 @@
+/*
+ * 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.Catalog.Type;
+import com.datastrato.graviton.Config;
+import com.datastrato.graviton.Configs;
+import com.datastrato.graviton.EntityAlreadyExistsException;
+import com.datastrato.graviton.EntitySerDeFactory;
+import com.datastrato.graviton.EntityStore;
+import com.datastrato.graviton.EntityStoreFactory;
+import com.datastrato.graviton.Metalake;
+import com.datastrato.graviton.Namespace;
+import com.datastrato.graviton.NoSuchEntityException;
+import com.datastrato.graviton.meta.AuditInfo;
+import com.datastrato.graviton.meta.BaseMetalake;
+import com.datastrato.graviton.meta.CatalogEntity;
+import com.datastrato.graviton.meta.SchemaVersion;
+import java.io.IOException;
+import java.time.Instant;
+import org.apache.commons.io.FileUtils;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+public class TestEntityStorageBackend {
+ public static final String ROCKS_DB_STORE_PATH = "/tmp/graviton";
+
+ @BeforeEach
+ @AfterEach
+ public void cleanEnv() {
+ try {
+ FileUtils.deleteDirectory(FileUtils.getFile(ROCKS_DB_STORE_PATH));
+ } catch (Exception e) {
+ // Ignore
+ }
+ }
+
+ @Test
+ public void testCreateKvEntityStore() {
+ 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("/tmp/graviton");
+
+ try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {
+ Assertions.assertTrue(store instanceof KvEntityStore);
+ store.setSerDe(EntitySerDeFactory.createEntitySerDe(config.get(Configs.ENTITY_SERDE)));
+
+ AuditInfo auditInfo =
+ new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();
+
+ BaseMetalake metalake =
+ new BaseMetalake.Builder()
+ .withId(1L)
+ .withName("metalake")
+ .withAuditInfo(auditInfo)
+ .withVersion(SchemaVersion.V_0_1)
+ .build();
+
+ BaseMetalake metalakeCopy =
+ new BaseMetalake.Builder()
+ .withId(1L)
+ .withName("metalakeCopy")
+ .withAuditInfo(auditInfo)
+ .withVersion(SchemaVersion.V_0_1)
+ .build();
+
+ CatalogEntity catalog =
+ new CatalogEntity.Builder()
+ .withId(1L)
+ .withName("catalog")
+ .withNamespace(Namespace.of("metalake"))
+ .withType(Type.RELATIONAL)
+ .withMetalakeId(1L)
+ .withAuditInfo(auditInfo)
+ .build();
+
+ CatalogEntity catalogCopy =
+ new CatalogEntity.Builder()
+ .withId(1L)
+ .withName("catalogCopy")
+ .withNamespace(Namespace.of("metalake"))
+ .withType(Type.RELATIONAL)
+ .withMetalakeId(1L)
+ .withAuditInfo(auditInfo)
+ .build();
+
+ // First, we try to test transactional is OK
+
+ try {
+ store.executeInTransaction(
+ () -> {
+ store.put(metalake.nameIdentifier(), metalake);
+ // Try to mock an exception
+ double a = 1 / 0;
+ store.put(catalog.nameIdentifier(), catalog);
+ return null;
+ });
+ } catch (Exception e) {
+ Assertions.assertTrue(e instanceof IOException);
+ }
+
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> store.get(metalake.nameIdentifier(), BaseMetalake.class));
+
+ store.put(metalake.nameIdentifier(), metalake);
+ store.put(catalog.nameIdentifier(), catalog);
+ store.put(metalakeCopy.nameIdentifier(), metalakeCopy);
+ store.put(catalogCopy.nameIdentifier(), catalogCopy);
+
+ Metalake retrievedMetalake = store.get(metalake.nameIdentifier(), BaseMetalake.class);
+ Assertions.assertEquals(metalake, retrievedMetalake);
+ CatalogEntity retrievedCatalog = store.get(catalog.nameIdentifier(), CatalogEntity.class);
+ Assertions.assertEquals(catalog, retrievedCatalog);
+ Metalake retrievedMetalakeCopy = store.get(metalakeCopy.nameIdentifier(), BaseMetalake.class);
+ Assertions.assertEquals(metalakeCopy, retrievedMetalakeCopy);
+ CatalogEntity retrievedCatalogCopy =
+ store.get(catalogCopy.nameIdentifier(), CatalogEntity.class);
+ Assertions.assertEquals(catalogCopy, retrievedCatalogCopy);
+
+ store.delete(metalake.nameIdentifier());
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> store.get(metalake.nameIdentifier(), BaseMetalake.class));
+
+ Assertions.assertThrows(
+ EntityAlreadyExistsException.class,
+ () -> store.put(catalog.nameIdentifier(), catalog, false));
+ store.delete(catalog.nameIdentifier());
+ Assertions.assertThrows(
+ NoSuchEntityException.class,
+ () -> store.get(catalog.nameIdentifier(), CatalogEntity.class));
+ } catch (Exception e) {
+ Assertions.fail(e.getMessage());
+ }
+ }
+}
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 74c4da189b..9743e2ad21 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -23,6 +23,7 @@ mockserver = "5.13.2"
commons-lang3 = "3.12.0"
commons-io = "2.11.0"
caffeine = "2.9.3"
+rocksdbjni = "7.7.3"
protobuf-plugin = "0.9.2"
spotless-plugin = '6.11.0'
@@ -72,6 +73,7 @@ mockserver-client-java = { group = "org.mock-server", name = "mockserver-client-
commons-lang3 = { group = "org.apache.commons", name = "commons-lang3", version.ref = "commons-lang3" }
commons-io = { group = "commons-io", name = "commons-io", version.ref = "commons-io" }
caffeine = { group = "com.github.ben-manes.caffeine", name = "caffeine", version.ref = "caffeine" }
+rocksdbjni = { group = "org.rocksdb", name = "rocksdbjni", version.ref = "rocksdbjni" }
[bundles]
log4j = ["slf4j-api", "log4j-slf4j2-impl", "log4j-api", "log4j-core", "log4j-12-api"]
diff --git a/meta/src/main/proto/graviton_meta.proto b/meta/src/main/proto/graviton_meta.proto
index 2c1d68d7a2..2c055e4864 100644
--- a/meta/src/main/proto/graviton_meta.proto
+++ b/meta/src/main/proto/graviton_meta.proto
@@ -43,7 +43,7 @@ message Metalake {
message Catalog {
enum Type {
- REL = 0; // Catalog Type for Relational Data Structure, like db.table.
+ RELATIONAL = 0; // Catalog Type for Relational Data Structure, like db.table.
FILE = 1; // Catalog Type for File System (including HDFS, S3, etc.), like path/to/file.
STREAM = 2; // Catalog Type for Streaming Data, like kafka://topic.
}
diff --git a/settings.gradle.kts b/settings.gradle.kts
index 405100a019..b3bec86704 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -5,4 +5,3 @@
rootProject.name = "Graviton"
include("api", "client-java", "common", "core", "meta", "server", "catalog-hive")
-include("storage")