World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#1690] improvement(core): Decode byte array value of entity in log to make it more readable (#1695)
Qi Yufe045c0814f9
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.javaindex e42dbd257f..fb5e85c830 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@@ -65,7 +65,7 @@ public class KvEntityStore implements EntityStore {Bytes.concat(new byte[] {0x1D, 0x00, 0x02}, "layout_version".getBytes(StandardCharsets.UTF_8));- @Getter @VisibleForTesting private KvBackend backend;+ @Getter @VisibleForTesting KvBackend backend;// Lock to control the concurrency of the entity store, to be more exact, the concurrency of// accessing the underlying kv store.@@ -93,14 +93,15 @@ public class KvEntityStore implements EntityStore {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);+ this.kvGarbageCollector = new KvGarbageCollector(backend, config, entityKeyEncoder);+ kvGarbageCollector.start();+this.storageLayoutVersion = initStorageVersionInfo();}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.javaindex 30bbf504e2..bfd39bbb67 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@@ -6,23 +6,30 @@package com.datastrato.gravitino.storage.kv;import static com.datastrato.gravitino.Configs.KV_DELETE_AFTER_TIME;+import static com.datastrato.gravitino.storage.kv.KvNameMappingService.GENERAL_NAME_MAPPING_PREFIX;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.Entity.EntityType;+import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.storage.EntityKeyEncoder;import com.datastrato.gravitino.utils.Bytes;import com.google.common.annotations.VisibleForTesting;import java.io.Closeable;import java.io.IOException;+import java.util.Arrays;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.ArrayUtils;import org.apache.commons.lang3.SerializationUtils;+import org.apache.commons.lang3.time.DateFormatUtils;import org.apache.commons.lang3.tuple.Pair;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -35,10 +42,13 @@ public final class KvGarbageCollector implements Closeable {private static final Logger LOG = LoggerFactory.getLogger(KvGarbageCollector.class);private final KvBackend kvBackend;private final Config config;+ private final EntityKeyEncoder<byte[]> entityKeyEncoder;private static final long MAX_DELETE_TIME_ALLOW = 1000 * 60 * 60 * 24 * 30L; // 30 daysprivate static final long MIN_DELETE_TIME_ALLOW = 1000 * 60 * 10L; // 10 minutes+ private static final String TIME_STAMP_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";+@VisibleForTestingfinal ScheduledExecutorService garbageCollectorPool =new ScheduledThreadPoolExecutor(@@ -50,9 +60,11 @@ public final class KvGarbageCollector implements Closeable {},new ThreadPoolExecutor.AbortPolicy());- public KvGarbageCollector(KvBackend kvBackend, Config config) {+ public KvGarbageCollector(+ KvBackend kvBackend, Config config, EntityKeyEncoder<byte[]> entityKeyEncoder) {this.kvBackend = kvBackend;this.config = config;+ this.entityKeyEncoder = entityKeyEncoder;long deleteTimeLine = config.get(KV_DELETE_AFTER_TIME);if (deleteTimeLine > MAX_DELETE_TIME_ALLOW || deleteTimeLine < MIN_DELETE_TIME_ALLOW) {@@ -108,7 +120,14 @@ public final class KvGarbageCollector implements Closeable {LOG.info("Start to remove {} uncommitted data", kvs.size());for (Pair<byte[], byte[]> pair : kvs) {// Remove is a high-risk operation, So we log every delete operation- LOG.info("Remove uncommitted data: Key {}", Bytes.wrap(pair.getKey()));+ LogHelper logHelper = decodeKey(pair.getKey());+ LOG.info(+ "Physically delete key that has marked uncommitted: name identity: '{}', entity type: '{}', createTime: '{}({})', key: '{}'",+ logHelper.identifier,+ logHelper.type,+ logHelper.createTimeAsString,+ logHelper.createTimeInMs,+ pair.getKey());kvBackend.delete(pair.getKey());}}@@ -156,7 +175,14 @@ public final class KvGarbageCollector implements Closeable {// 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));+ LogHelper logHelper = decodeKey(key, transactionId);+ LOG.info(+ "Physically delete key that has marked deleted: name identifier: '{}', entity type: '{}', createTime: '{}({})', key: '{}'",+ logHelper.identifier,+ logHelper.type,+ logHelper.createTimeAsString,+ logHelper.createTimeInMs,+ Bytes.wrap(key));kvBackend.delete(rawKey);keysDeletedCount++;continue;@@ -176,10 +202,20 @@ public final class KvGarbageCollector implements Closeable {.build());if (!newVersionOfKey.isEmpty()) {// Has a newer version, we can remove it.+ LogHelper logHelper = decodeKey(key, transactionId);+ byte[] newVersionKey = newVersionOfKey.get(0).getKey();+ LogHelper newVersionLogHelper = decodeKey(newVersionKey);LOG.info(- "Physically delete key that has newer version: {}, a newer version {}",+ "Physically delete key that has newer version: name identifier: '{}', entity type: '{}', createTime: '{}({})', newVersion createTime: '{}({})',"+ + " key: '{}', newVersion key: '{}'",+ logHelper.identifier,+ logHelper.type,+ logHelper.createTimeAsString,+ logHelper.createTimeInMs,+ newVersionLogHelper.createTimeAsString,+ newVersionLogHelper.createTimeInMs,Bytes.wrap(rawKey),- Bytes.wrap(newVersionOfKey.get(0).getKey()));+ Bytes.wrap(newVersionKey));kvBackend.delete(rawKey);keysDeletedCount++;}@@ -187,12 +223,71 @@ 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()));+ long timestamp = TransactionalKvBackendImpl.getTransactionId(transactionId) >> 18;+ LOG.info(+ "Physically delete commit mark: {}, createTime: '{}({})', key: '{}'",+ Bytes.wrap(kv.getKey()),+ DateFormatUtils.format(timestamp, TIME_STAMP_FORMAT),+ timestamp,+ Bytes.wrap(kv.getKey()));kvBackend.delete(kv.getKey());}}}+ static class LogHelper {++ @VisibleForTesting final NameIdentifier identifier;+ @VisibleForTesting final EntityType type;+ @VisibleForTesting final long createTimeInMs;+ // Formatted createTime+ @VisibleForTesting final String createTimeAsString;++ public static final LogHelper NONE = new LogHelper(null, null, 0L, null);++ public LogHelper(+ NameIdentifier identifier,+ EntityType type,+ long createTimeInMs,+ String createTimeAsString) {+ this.identifier = identifier;+ this.type = type;+ this.createTimeInMs = createTimeInMs;+ this.createTimeAsString = createTimeAsString;+ }+ }++ @VisibleForTesting+ LogHelper decodeKey(byte[] key, byte[] timestampArray) {+ if (entityKeyEncoder == null) {+ return LogHelper.NONE;+ }++ // Name mapping data, we do not support it now.+ if (Arrays.equals(GENERAL_NAME_MAPPING_PREFIX, ArrayUtils.subarray(key, 0, 3))) {+ return LogHelper.NONE;+ }++ Pair<NameIdentifier, EntityType> entityTypePair;+ try {+ entityTypePair = entityKeyEncoder.decode(key);+ } catch (Exception e) {+ LOG.warn("Unable to decode key: {}", Bytes.wrap(key), e);+ return LogHelper.NONE;+ }+ long timestamp = TransactionalKvBackendImpl.getTransactionId(timestampArray) >> 18;+ String ts = DateFormatUtils.format(timestamp, TIME_STAMP_FORMAT);++ return new LogHelper(entityTypePair.getKey(), entityTypePair.getValue(), timestamp, ts);+ }++ @VisibleForTesting+ LogHelper decodeKey(byte[] rawKey) {+ byte[] key = TransactionalKvBackendImpl.getRealKey(rawKey);+ byte[] timestampArray = TransactionalKvBackendImpl.getBinaryTransactionId(rawKey);+ return decodeKey(key, timestampArray);+ }+@Overridepublic void close() throws IOException {garbageCollectorPool.shutdownNow();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.javaindex 21a4e1d46e..486768d172 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@@ -28,7 +28,7 @@ public class KvNameMappingService implements NameMappingService {@VisibleForTesting final IdGenerator idGenerator = new RandomIdGenerator();// To separate it from user keys, we will add three control flag 0x1D, 0x00, 0x00 as the prefix.- private static final byte[] GENERAL_NAME_MAPPING_PREFIX = new byte[] {0x1D, 0x00, 0x00};+ static final byte[] GENERAL_NAME_MAPPING_PREFIX = new byte[] {0x1D, 0x00, 0x00};// Name prefix of name in name to id mapping,// e.g., name_metalake1 -> 1@@ -73,7 +73,7 @@ public class KvNameMappingService implements NameMappingService {FunctionUtils.executeInTransaction(() -> {byte[] name = transactionalKvBackend.get(idByte);- return idByte == null ? null : new String(name);+ return name == null ? null : new String(name);},transactionalKvBackend),lock);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.javaindex 1687af82f8..77d677bc93 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@@ -329,12 +329,14 @@ 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[] revertByteArray(byte[] bytes) {+ @VisibleForTesting+ static byte[] revertByteArray(byte[] bytes) {+ byte[] result = new byte[bytes.length];for (int i = 0; i < bytes.length; i++) {- bytes[i] = (byte) (bytes[i] ^ (byte) 0xff);+ result[i] = (byte) (bytes[i] ^ (byte) 0xff);}- return bytes;+ return result;}/** Generate a key of data for a specific transaction id. */@@ -377,4 +379,9 @@ public class TransactionalKvBackendImpl implements TransactionalKvBackend {static byte[] getBinaryTransactionId(byte[] rawKey) {return ArrayUtils.subarray(rawKey, rawKey.length - LENGTH_OF_TRANSACTION_ID, rawKey.length);}++ static long getTransactionId(byte[] binaryTransactionId) {+ byte[] reverted = revertByteArray(binaryTransactionId);+ return ByteUtils.byteToLong(reverted);+ }}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.javaindex ecf1fa08bc..cd2b6f0845 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@@ -67,7 +67,7 @@ public class TestKvEntityStorage {}}- public BaseMetalake createBaseMakeLake(String name, AuditInfo auditInfo) {+ public static BaseMetalake createBaseMakeLake(String name, AuditInfo auditInfo) {return new BaseMetalake.Builder().withId(1L).withName(name)@@ -76,7 +76,7 @@ public class TestKvEntityStorage {.build();}- public CatalogEntity createCatalog(Namespace namespace, String name, AuditInfo auditInfo) {+ public static CatalogEntity createCatalog(Namespace namespace, String name, AuditInfo auditInfo) {return new CatalogEntity.Builder().withId(1L).withName(name)@@ -87,7 +87,8 @@ public class TestKvEntityStorage {.build();}- public SchemaEntity createSchemaEntity(Namespace namespace, String name, AuditInfo auditInfo) {+ public static SchemaEntity createSchemaEntity(+ Namespace namespace, String name, AuditInfo auditInfo) {return new SchemaEntity.Builder().withId(1L).withName(name)@@ -96,7 +97,8 @@ public class TestKvEntityStorage {.build();}- public TableEntity createTableEntity(Namespace namespace, String name, AuditInfo auditInfo) {+ public static TableEntity createTableEntity(+ Namespace namespace, String name, AuditInfo auditInfo) {return new TableEntity.Builder().withId(1L).withName(name)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.javaindex b9a116be0f..7699e4b2d0 100644--- a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvGarbageCollector.java+++ b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestKvGarbageCollector.java@@ -11,13 +11,29 @@ 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.TestKvEntityStorage.createBaseMakeLake;+import static com.datastrato.gravitino.storage.kv.TestKvEntityStorage.createCatalog;+import static com.datastrato.gravitino.storage.kv.TestKvEntityStorage.createSchemaEntity;+import static com.datastrato.gravitino.storage.kv.TestKvEntityStorage.createTableEntity;import com.datastrato.gravitino.Config;import com.datastrato.gravitino.Configs;+import com.datastrato.gravitino.EntitySerDeFactory;+import com.datastrato.gravitino.EntityStore;+import com.datastrato.gravitino.EntityStoreFactory;+import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.Namespace;+import com.datastrato.gravitino.meta.AuditInfo;+import com.datastrato.gravitino.meta.BaseMetalake;+import com.datastrato.gravitino.meta.CatalogEntity;+import com.datastrato.gravitino.meta.SchemaEntity;+import com.datastrato.gravitino.meta.TableEntity;import com.datastrato.gravitino.storage.TransactionIdGenerator;+import com.datastrato.gravitino.storage.kv.KvGarbageCollector.LogHelper;import java.io.File;import java.io.IOException;import java.nio.file.Files;+import java.time.Instant;import java.util.List;import org.apache.commons.lang3.tuple.Pair;import org.junit.jupiter.api.Assertions;@@ -106,7 +122,7 @@ class TestKvGarbageCollector {// 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);+ KvGarbageCollector kvGarbageCollector = new KvGarbageCollector(kvBackend, config, null);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@@ -129,4 +145,80 @@ class TestKvGarbageCollector {Assertions.assertNull(transactionalKvBackend.get("testC".getBytes()));}}++ @Test+ void testRemoveWithGCCollector() throws IOException, InterruptedException {+ Config config = Mockito.mock(Config.class);+ File baseDir = new File(System.getProperty("java.io.tmpdir"));+ File file = Files.createTempDirectory(baseDir.toPath(), "test").toFile();+ 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(1000L);+ Mockito.when(config.get(KV_DELETE_AFTER_TIME)).thenReturn(20 * 60 * 1000L);++ try (EntityStore store = EntityStoreFactory.createEntityStore(config)) {+ store.initialize(config);+ if (!(store instanceof KvEntityStore)) {+ return;+ }+ KvEntityStore kvEntityStore = (KvEntityStore) store;+ store.setSerDe(EntitySerDeFactory.createEntitySerDe(config.get(Configs.ENTITY_SERDE)));+ AuditInfo auditInfo =+ new AuditInfo.Builder().withCreator("creator").withCreateTime(Instant.now()).build();++ BaseMetalake metalake1 = createBaseMakeLake("metalake1", auditInfo);+ CatalogEntity catalog = createCatalog(Namespace.of("metalake1"), "catalog1", auditInfo);+ SchemaEntity schemaEntity =+ createSchemaEntity(Namespace.of("metalake1", "catalog1"), "schema1", auditInfo);+ TableEntity tableEntity =+ createTableEntity(Namespace.of("metalake1", "catalog1", "schema1"), "table1", auditInfo);++ kvEntityStore.put(metalake1);+ kvEntityStore.put(catalog);+ kvEntityStore.put(schemaEntity);+ kvEntityStore.put(tableEntity);++ // now try to scan raw data from kv store+ KvBackend kvBackend = kvEntityStore.backend;+ List<Pair<byte[], byte[]>> data =+ kvBackend.scan(+ new KvRangeScan.KvRangeScanBuilder()+ .start("_".getBytes())+ .end("z".getBytes())+ .startInclusive(false)+ .endInclusive(false)+ .build());++ Assertions.assertEquals(4, data.size());++ KvGarbageCollector kvGarbageCollector = kvEntityStore.kvGarbageCollector;+ for (Pair<byte[], byte[]> pair : data) {+ byte[] key = pair.getKey();+ LogHelper helper = kvGarbageCollector.decodeKey(key);+ Assertions.assertNotSame(LogHelper.NONE, helper);++ switch (helper.type) {+ case METALAKE:+ Assertions.assertEquals(NameIdentifier.of("metalake1"), helper.identifier);+ break;+ case CATALOG:+ Assertions.assertEquals(NameIdentifier.of("metalake1", "catalog1"), helper.identifier);+ break;+ case SCHEMA:+ Assertions.assertEquals(+ NameIdentifier.of("metalake1", "catalog1", "schema1"), helper.identifier);+ break;+ case TABLE:+ Assertions.assertEquals(+ NameIdentifier.of("metalake1", "catalog1", "schema1", "table1"), helper.identifier);+ break;+ default:+ Assertions.fail();+ }+ }+ }+ }}diff --git a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestTransactionalKvBackend.java b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestTransactionalKvBackend.javaindex 728bee1d45..132b323b90 100644--- a/core/src/test/java/com/datastrato/gravitino/storage/kv/TestTransactionalKvBackend.java+++ b/core/src/test/java/com/datastrato/gravitino/storage/kv/TestTransactionalKvBackend.java@@ -819,4 +819,14 @@ class TestTransactionalKvBackend {Assertions.assertEquals("bc", new String(data.get(0).getKey()));Assertions.assertEquals("bcef", new String(data.get(4).getKey()));}++ @Test+ void testRevertByte() {+ byte[] bytes = {0x01, 0x02, 0x03, 0x04};+ byte[] copy = ArrayUtils.clone(bytes);+ byte[] revertBytes = TransactionalKvBackendImpl.revertByteArray(bytes);+ Assertions.assertArrayEquals(copy, bytes);+ revertBytes = TransactionalKvBackendImpl.revertByteArray(revertBytes);+ Assertions.assertArrayEquals(bytes, revertBytes);+ }}