World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#2766] feat(core): Gravitino event listener code skeleton (#2787)
FANNGd349cf7745e1
diff --git a/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java b/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.javaindex 59c25878ae..c357c9bcc0 100644--- a/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java+++ b/core/src/main/java/com/datastrato/gravitino/GravitinoEnv.java@@ -9,8 +9,12 @@ import com.datastrato.gravitino.auxiliary.AuxiliaryServiceManager;import com.datastrato.gravitino.catalog.CatalogManager;import com.datastrato.gravitino.catalog.FilesetOperationDispatcher;import com.datastrato.gravitino.catalog.SchemaOperationDispatcher;+import com.datastrato.gravitino.catalog.TableDispatcher;+import com.datastrato.gravitino.catalog.TableEventDispatcher;import com.datastrato.gravitino.catalog.TableOperationDispatcher;import com.datastrato.gravitino.catalog.TopicOperationDispatcher;+import com.datastrato.gravitino.listener.EventBus;+import com.datastrato.gravitino.listener.EventListenerManager;import com.datastrato.gravitino.lock.LockManager;import com.datastrato.gravitino.metalake.MetalakeManager;import com.datastrato.gravitino.metrics.MetricsSystem;@@ -37,7 +41,7 @@ public class GravitinoEnv {private SchemaOperationDispatcher schemaOperationDispatcher;- private TableOperationDispatcher tableOperationDispatcher;+ private TableDispatcher tableDispatcher;private FilesetOperationDispatcher filesetOperationDispatcher;@@ -54,6 +58,7 @@ public class GravitinoEnv {private MetricsSystem metricsSystem;private LockManager lockManager;+ private EventListenerManager eventListenerManager;private GravitinoEnv() {}@@ -112,6 +117,11 @@ public class GravitinoEnv {// create and initialize a random id generatorthis.idGenerator = new RandomIdGenerator();+ this.eventListenerManager = new EventListenerManager();+ eventListenerManager.init(+ config.getConfigsWithPrefix(EventListenerManager.GRAVITINO_EVENT_LISTENER_PREFIX));+ EventBus eventBus = eventListenerManager.createEventBus();+// Create and initialize metalake related modulesthis.metalakeManager = new MetalakeManager(entityStore, idGenerator);@@ -119,8 +129,9 @@ public class GravitinoEnv {this.catalogManager = new CatalogManager(config, entityStore, idGenerator);this.schemaOperationDispatcher =new SchemaOperationDispatcher(catalogManager, entityStore, idGenerator);- this.tableOperationDispatcher =+ TableOperationDispatcher tableOperationDispatcher =new TableOperationDispatcher(catalogManager, entityStore, idGenerator);+ this.tableDispatcher = new TableEventDispatcher(eventBus, tableOperationDispatcher);this.filesetOperationDispatcher =new FilesetOperationDispatcher(catalogManager, entityStore, idGenerator);this.topicOperationDispatcher =@@ -181,12 +192,12 @@ public class GravitinoEnv {}/**- * Get the TableOperationDispatcher associated with the Gravitino environment.+ * Get the TableDispatcher associated with the Gravitino environment.*- * @return The TableOperationDispatcher instance.+ * @return The TableDispatcher instance.*/- public TableOperationDispatcher tableOperationDispatcher() {- return tableOperationDispatcher;+ public TableDispatcher tableDispatcher() {+ return tableDispatcher;}/**@@ -250,6 +261,7 @@ public class GravitinoEnv {public void start() {auxServiceManager.serviceStart();metricsSystem.start();+ eventListenerManager.start();}/** Shutdown the Gravitino environment. */@@ -280,6 +292,10 @@ public class GravitinoEnv {metricsSystem.close();}+ if (eventListenerManager != null) {+ eventListenerManager.stop();+ }+LOG.info("Gravitino Environment is shut down.");}}diff --git a/core/src/main/java/com/datastrato/gravitino/catalog/TableDispatcher.java b/core/src/main/java/com/datastrato/gravitino/catalog/TableDispatcher.javanew file mode 100644index 0000000000..7b54ccd579--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/catalog/TableDispatcher.java@@ -0,0 +1,16 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.catalog;++import com.datastrato.gravitino.rel.TableCatalog;++/**+ * {@code TableDispatcher} interface acts as a specialization of the {@link TableCatalog} interface.+ * This interface is designed to potentially add custom behaviors or operations related to+ * dispatching or handling table-related events or actions that are not covered by the standard+ * {@code TableCatalog} operations.+ */+public interface TableDispatcher extends TableCatalog {}diff --git a/core/src/main/java/com/datastrato/gravitino/catalog/TableEventDispatcher.java b/core/src/main/java/com/datastrato/gravitino/catalog/TableEventDispatcher.javanew file mode 100644index 0000000000..987b2687b9--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/catalog/TableEventDispatcher.java@@ -0,0 +1,127 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.catalog;++import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.Namespace;+import com.datastrato.gravitino.exceptions.NoSuchSchemaException;+import com.datastrato.gravitino.exceptions.NoSuchTableException;+import com.datastrato.gravitino.exceptions.TableAlreadyExistsException;+import com.datastrato.gravitino.listener.EventBus;+import com.datastrato.gravitino.listener.api.event.CreateTableEvent;+import com.datastrato.gravitino.listener.api.event.CreateTableFailureEvent;+import com.datastrato.gravitino.listener.api.event.DropTableEvent;+import com.datastrato.gravitino.listener.api.event.DropTableFailureEvent;+import com.datastrato.gravitino.listener.api.info.TableInfo;+import com.datastrato.gravitino.rel.Column;+import com.datastrato.gravitino.rel.Table;+import com.datastrato.gravitino.rel.TableChange;+import com.datastrato.gravitino.rel.expressions.distributions.Distribution;+import com.datastrato.gravitino.rel.expressions.sorts.SortOrder;+import com.datastrato.gravitino.rel.expressions.transforms.Transform;+import com.datastrato.gravitino.rel.indexes.Index;+import com.datastrato.gravitino.utils.PrincipalUtils;+import java.util.Map;++/**+ * {@code TableEventDispatcher} is a decorator for {@link TableDispatcher} that not only delegates+ * table operations to the underlying catalog dispatcher but also dispatches corresponding events to+ * an {@link EventBus} after each operation is completed. This allows for event-driven workflows or+ * monitoring of table operations.+ */+public class TableEventDispatcher implements TableDispatcher {+ private final EventBus eventBus;+ private final TableDispatcher dispatcher;++ /**+ * Constructs a TableEventDispatcher with a specified EventBus and TableCatalog.+ *+ * @param eventBus The EventBus to which events will be dispatched.+ * @param dispatcher The underlying {@link TableOperationDispatcher} that will perform the actual+ * table operations.+ */+ public TableEventDispatcher(EventBus eventBus, TableDispatcher dispatcher) {+ this.eventBus = eventBus;+ this.dispatcher = dispatcher;+ }++ @Override+ public NameIdentifier[] listTables(Namespace namespace) throws NoSuchSchemaException {+ return dispatcher.listTables(namespace);+ }++ @Override+ public Table loadTable(NameIdentifier ident) throws NoSuchTableException {+ return dispatcher.loadTable(ident);+ }++ @Override+ public Table createTable(+ NameIdentifier ident,+ Column[] columns,+ String comment,+ Map<String, String> properties,+ Transform[] partitions,+ Distribution distribution,+ SortOrder[] sortOrders,+ Index[] indexes)+ throws NoSuchSchemaException, TableAlreadyExistsException {+ try {+ Table table =+ dispatcher.createTable(+ ident, columns, comment, properties, partitions, distribution, sortOrders, indexes);+ eventBus.dispatchEvent(+ new CreateTableEvent(PrincipalUtils.getCurrentUserName(), ident, new TableInfo(table)));+ return table;+ } catch (Exception e) {+ TableInfo createTableRequest =+ new TableInfo(+ ident.name(),+ columns,+ comment,+ properties,+ partitions,+ distribution,+ sortOrders,+ indexes,+ null);+ eventBus.dispatchEvent(+ new CreateTableFailureEvent(+ PrincipalUtils.getCurrentUserName(), ident, e, createTableRequest));+ throw e;+ }+ }++ @Override+ public Table alterTable(NameIdentifier ident, TableChange... changes)+ throws NoSuchTableException, IllegalArgumentException {+ return dispatcher.alterTable(ident, changes);+ }++ @Override+ public boolean dropTable(NameIdentifier ident) {+ try {+ boolean isExists = dispatcher.dropTable(ident);+ eventBus.dispatchEvent(+ new DropTableEvent(PrincipalUtils.getCurrentUserName(), ident, isExists));+ return isExists;+ } catch (Exception e) {+ eventBus.dispatchEvent(+ new DropTableFailureEvent(PrincipalUtils.getCurrentUserName(), ident, e));+ throw e;+ }+ }++ @Override+ public boolean purgeTable(NameIdentifier ident) {+ return dispatcher.purgeTable(ident);+ }++ @Override+ public boolean tableExists(NameIdentifier ident) {+ return dispatcher.tableExists(ident);+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/catalog/TableOperationDispatcher.java b/core/src/main/java/com/datastrato/gravitino/catalog/TableOperationDispatcher.javaindex 2947ca3180..1d58fb0d9a 100644--- a/core/src/main/java/com/datastrato/gravitino/catalog/TableOperationDispatcher.java+++ b/core/src/main/java/com/datastrato/gravitino/catalog/TableOperationDispatcher.java@@ -20,7 +20,6 @@ import com.datastrato.gravitino.meta.AuditInfo;import com.datastrato.gravitino.meta.TableEntity;import com.datastrato.gravitino.rel.Column;import com.datastrato.gravitino.rel.Table;-import com.datastrato.gravitino.rel.TableCatalog;import com.datastrato.gravitino.rel.TableChange;import com.datastrato.gravitino.rel.expressions.distributions.Distribution;import com.datastrato.gravitino.rel.expressions.distributions.Distributions;@@ -36,7 +35,7 @@ import java.util.Map;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-public class TableOperationDispatcher extends OperationDispatcher implements TableCatalog {+public class TableOperationDispatcher extends OperationDispatcher implements TableDispatcher {private static final Logger LOG = LoggerFactory.getLogger(TableOperationDispatcher.class);diff --git a/core/src/main/java/com/datastrato/gravitino/listener/AsyncQueueListener.java b/core/src/main/java/com/datastrato/gravitino/listener/AsyncQueueListener.javanew file mode 100644index 0000000000..d9beb62435--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/AsyncQueueListener.java@@ -0,0 +1,143 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener;++import com.datastrato.gravitino.listener.api.EventListenerPlugin;+import com.datastrato.gravitino.listener.api.event.Event;+import com.google.common.annotations.VisibleForTesting;+import com.google.common.base.Preconditions;+import java.time.Instant;+import java.util.List;+import java.util.Map;+import java.util.concurrent.BlockingQueue;+import java.util.concurrent.LinkedBlockingQueue;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.concurrent.atomic.AtomicLong;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * AsyncQueueListener acts as event listener, and internally buffer event to a queue, start a+ * dispatcher thread to dispatch event to the real listeners. For default AsyncQueueListener it may+ * contain multi listeners share with one queue and dispatcher thread. For other+ * AsyncQueueDispatchers, contain only one listener.+ */+public class AsyncQueueListener implements EventListenerPlugin {+ private static final Logger LOG = LoggerFactory.getLogger(AsyncQueueListener.class);+ private static final String NAME_PREFIX = "async-queue-listener-";++ private final List<EventListenerPlugin> eventListeners;+ private final BlockingQueue<Event> queue;+ private final Thread asyncProcessor;+ private final int dispatcherJoinSeconds;+ private final AtomicBoolean stopped = new AtomicBoolean(false);+ private final AtomicLong dropEventCounters = new AtomicLong(0);+ private final AtomicLong lastDropEventCounters = new AtomicLong(0);+ private Instant lastRecordDropEventTime;+ private final String asyncQueueListenerName;++ public AsyncQueueListener(+ List<EventListenerPlugin> listeners,+ String name,+ int queueCapacity,+ int dispatcherJoinSeconds) {+ this.asyncQueueListenerName = NAME_PREFIX + name;+ this.eventListeners = listeners;+ this.queue = new LinkedBlockingQueue<>(queueCapacity);+ this.asyncProcessor = new Thread(() -> processEvents());+ this.dispatcherJoinSeconds = dispatcherJoinSeconds;+ asyncProcessor.setDaemon(true);+ asyncProcessor.setName(asyncQueueListenerName);+ }++ @Override+ public void onPostEvent(Event event) {+ if (stopped.get()) {+ LOG.warn(+ "{} drop event: {}, since AsyncQueueListener is stopped",+ asyncQueueListenerName,+ event.getClass().getSimpleName());+ return;+ }++ if (queue.offer(event)) {+ return;+ }++ logDropEventsIfNecessary();+ }++ @Override+ public void init(Map<String, String> properties) {+ throw new RuntimeException(+ "Should not reach here, the event listener has already been initialized.");+ }++ @Override+ public void start() {+ eventListeners.forEach(listenerPlugin -> listenerPlugin.start());+ asyncProcessor.start();+ }++ @Override+ public void stop() {+ Preconditions.checkState(!stopped.get(), asyncQueueListenerName + " had already stopped");+ stopped.compareAndSet(false, true);+ asyncProcessor.interrupt();+ try {+ asyncProcessor.join(dispatcherJoinSeconds * 1000L);+ } catch (InterruptedException e) {+ LOG.warn("{} interrupt async processor failed.", asyncQueueListenerName, e);+ }+ eventListeners.forEach(listenerPlugin -> listenerPlugin.stop());+ }++ @VisibleForTesting+ List<EventListenerPlugin> getEventListeners() {+ return this.eventListeners;+ }++ private void processEvents() {+ while (!Thread.currentThread().isInterrupted()) {+ try {+ Event event = queue.take();+ this.eventListeners.forEach(listener -> listener.onPostEvent(event));+ } catch (InterruptedException e) {+ LOG.warn("{} event dispatcher thread is interrupted.", asyncQueueListenerName);+ break;+ } catch (Exception e) {+ LOG.warn("{} throw a exception while processing event", asyncQueueListenerName, e);+ }+ }++ if (!queue.isEmpty()) {+ LOG.warn(+ "{} drop {} events since dispatch thread is interrupted",+ asyncQueueListenerName,+ queue.size());+ }+ }++ private void logDropEventsIfNecessary() {+ long currentDropEvents = dropEventCounters.incrementAndGet();+ long lastDropEvents = lastDropEventCounters.get();+ // dropEvents may less than zero in such conditions:+ // 1. Thread A increment dropEventCounters+ // 2. Thread B increment dropEventCounters and update lastDropEventCounters+ // 3. Thread A get lastDropEventCounters+ long dropEvents = currentDropEvents - lastDropEvents;+ if (dropEvents > 0 && Instant.now().isAfter(lastRecordDropEventTime.plusSeconds(60))) {+ if (lastDropEventCounters.compareAndSet(lastDropEvents, currentDropEvents)) {+ LOG.warn(+ "{} drop {} events since {}",+ asyncQueueListenerName,+ dropEvents,+ lastRecordDropEventTime);+ lastRecordDropEventTime = Instant.now();+ }+ }+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/EventBus.java b/core/src/main/java/com/datastrato/gravitino/listener/EventBus.javanew file mode 100644index 0000000000..0c186f4d00--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/EventBus.java@@ -0,0 +1,56 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener;++import com.datastrato.gravitino.listener.api.EventListenerPlugin;+import com.datastrato.gravitino.listener.api.event.Event;+import com.google.common.annotations.VisibleForTesting;+import java.util.List;++/**+ * The {@code EventBus} class serves as a mechanism to dispatch events to registered listeners. It+ * supports both synchronous and asynchronous listeners by categorizing them into two distinct types+ * within its internal management.+ */+public class EventBus {+ // Holds instances of EventListenerPlugin. These instances can either be+ // EventListenerPluginWrapper,+ // which are meant for synchronous event listening, or AsyncQueueListener, designed for+ // asynchronous event processing.+ private final List<EventListenerPlugin> postEventListeners;++ /**+ * Constructs an EventBus with a predefined list of event listeners.+ *+ * @param postEventListeners A list of {@link EventListenerPlugin} instances that are to be+ * registered with this EventBus for event dispatch.+ */+ public EventBus(List<EventListenerPlugin> postEventListeners) {+ this.postEventListeners = postEventListeners;+ }++ /**+ * Dispatches an event to all registered listeners. Each listener processes the event based on its+ * implementation, which could be either synchronous or asynchronous.+ *+ * @param event The event to be dispatched to all registered listeners.+ */+ public void dispatchEvent(Event event) {+ postEventListeners.forEach(postEventListener -> postEventListener.onPostEvent(event));+ }++ /**+ * Retrieves the list of registered post-event listeners. This method is primarily intended for+ * testing purposes to verify the correct registration and functioning of event listeners.+ *+ * @return A list of {@link EventListenerPlugin} instances currently registered with this+ * EventBus.+ */+ @VisibleForTesting+ List<EventListenerPlugin> getPostEventListeners() {+ return postEventListeners;+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/EventListenerConfig.java b/core/src/main/java/com/datastrato/gravitino/listener/EventListenerConfig.javanew file mode 100644index 0000000000..f803203175--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/EventListenerConfig.java@@ -0,0 +1,42 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener;++import com.datastrato.gravitino.Config;+import com.datastrato.gravitino.config.ConfigBuilder;+import com.datastrato.gravitino.config.ConfigConstants;+import com.datastrato.gravitino.config.ConfigEntry;+import java.util.Map;++class EventListenerConfig extends Config {+ static final ConfigEntry<String> LISTENER_NAMES =+ new ConfigBuilder(EventListenerManager.GRAVITINO_EVENT_LISTENER_NAMES)+ .doc("Gravitino event listener names, comma is utilized to separate multiple names")+ .version(ConfigConstants.VERSION_0_5_0)+ .stringConf()+ .createWithDefault("");++ static final ConfigEntry<Integer> QUEUE_CAPACITY =+ new ConfigBuilder(EventListenerManager.GRAVITINO_EVENT_LISTENER_QUEUE_CAPACITY)+ .doc("Gravitino event listener async queue capacity")+ .version(ConfigConstants.VERSION_0_5_0)+ .intConf()+ .checkValue(value -> value > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)+ .createWithDefault(3000);++ static final ConfigEntry<Integer> DISPATCHER_JOIN_SECONDS =+ new ConfigBuilder(EventListenerManager.GRAVITINO_EVENT_LISTENER_DISPATCHER_JOIN_SECONDS)+ .doc("Gravitino async event dispatcher join seconds")+ .version(ConfigConstants.VERSION_0_5_0)+ .intConf()+ .checkValue(value -> value > 0, ConfigConstants.POSITIVE_NUMBER_ERROR_MSG)+ .createWithDefault(3);++ EventListenerConfig(Map<String, String> properties) {+ super(false);+ loadFromMap(properties, k -> true);+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/EventListenerManager.java b/core/src/main/java/com/datastrato/gravitino/listener/EventListenerManager.javanew file mode 100644index 0000000000..c26e9abcdb--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/EventListenerManager.java@@ -0,0 +1,153 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener;++import com.datastrato.gravitino.listener.api.EventListenerPlugin;+import com.datastrato.gravitino.utils.MapUtils;+import com.google.common.annotations.VisibleForTesting;+import com.google.common.base.Joiner;+import com.google.common.base.Preconditions;+import com.google.common.base.Splitter;+import com.google.common.collect.ImmutableList;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;+import java.util.Objects;+import java.util.stream.Collectors;+import org.apache.commons.lang3.StringUtils;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * EventListenerManager loads listeners according to the configurations, and assemble the listeners+ * with following rules:+ *+ * <p>Wrap all listener with EventListenerWrapper to do some common process, like exception handing,+ * record metrics.+ *+ * <p>For async listeners with the shared dispatcher, will create a default AsyncQueueListener to+ * assemble the corresponding EventListenerWrappers.+ *+ * <p>For async listeners with the isolated dispatcher, will create a separate AsyncQueueListener+ * for each EventListenerWrapper.+ */+public class EventListenerManager {+ private static final Logger LOG = LoggerFactory.getLogger(EventListenerManager.class);+ public static final String GRAVITINO_EVENT_LISTENER_PREFIX = "gravitino.eventListener.";+ static final String GRAVITINO_EVENT_LISTENER_NAMES = "names";+ @VisibleForTesting static final String GRAVITINO_EVENT_LISTENER_CLASS = "class";+ static final String GRAVITINO_EVENT_LISTENER_QUEUE_CAPACITY = "queueCapacity";+ static final String GRAVITINO_EVENT_LISTENER_DISPATCHER_JOIN_SECONDS = "dispatcherJoinSeconds";+ private static final Splitter splitter = Splitter.on(",");+ private static final Joiner DOT = Joiner.on(".");++ private int queueCapacity;+ private int dispatcherJoinSeconds;+ private List<EventListenerPlugin> eventListeners;++ public void init(Map<String, String> properties) {+ EventListenerConfig config = new EventListenerConfig(properties);+ this.queueCapacity = config.get(EventListenerConfig.QUEUE_CAPACITY);+ this.dispatcherJoinSeconds = config.get(EventListenerConfig.DISPATCHER_JOIN_SECONDS);++ String eventListenerNames = config.get(EventListenerConfig.LISTENER_NAMES);+ Map<String, EventListenerPlugin> userEventListenerPlugins =+ splitter+ .omitEmptyStrings()+ .trimResults()+ .splitToStream(eventListenerNames)+ .collect(+ Collectors.toMap(+ listenerName -> listenerName,+ listenerName ->+ loadUserEventListenerPlugin(+ listenerName,+ MapUtils.getPrefixMap(properties, DOT.join(listenerName, ""))),+ (existingValue, newValue) -> {+ throw new IllegalStateException(+ "Duplicate event listener name detected: " + existingValue);+ }));+ this.eventListeners = assembleEventListeners(userEventListenerPlugins);+ }++ public void start() {+ eventListeners.stream().forEach(listener -> listener.start());+ }++ public void stop() {+ eventListeners.stream().forEach(listener -> listener.stop());+ }++ public EventBus createEventBus() {+ return new EventBus(eventListeners);+ }++ private List<EventListenerPlugin> assembleEventListeners(+ Map<String, EventListenerPlugin> userEventListeners) {+ List<EventListenerPlugin> sharedQueueListeners = new ArrayList<>();++ List<EventListenerPlugin> listeners =+ userEventListeners.entrySet().stream()+ .map(+ entrySet -> {+ String listenerName = entrySet.getKey();+ EventListenerPlugin listener = entrySet.getValue();+ switch (listener.mode()) {+ case SYNC:+ return new EventListenerPluginWrapper(listenerName, listener);+ case ASYNC_ISOLATED:+ return new AsyncQueueListener(+ ImmutableList.of(new EventListenerPluginWrapper(listenerName, listener)),+ listenerName,+ queueCapacity,+ dispatcherJoinSeconds);+ case ASYNC_SHARED:+ sharedQueueListeners.add(+ new EventListenerPluginWrapper(listenerName, listener));+ return null;+ default:+ throw new RuntimeException("Unexpected listener mode:" + listener.mode());+ }+ })+ .filter(Objects::nonNull)+ .collect(Collectors.toList());++ if (!sharedQueueListeners.isEmpty()) {+ listeners.add(+ new AsyncQueueListener(+ sharedQueueListeners, "default", queueCapacity, dispatcherJoinSeconds));+ }+ return listeners;+ }++ private EventListenerPlugin loadUserEventListenerPlugin(+ String listenerName, Map<String, String> config) {+ LOG.info("EventListener:{}, config:{}.", listenerName, config);+ String className = config.get(GRAVITINO_EVENT_LISTENER_CLASS);+ Preconditions.checkArgument(+ StringUtils.isNotBlank(className),+ String.format(+ "EventListener:%s, %s%s.%s is not set in configuration.",+ listenerName,+ GRAVITINO_EVENT_LISTENER_PREFIX,+ listenerName,+ GRAVITINO_EVENT_LISTENER_CLASS));++ try {+ EventListenerPlugin listenerPlugin =+ (EventListenerPlugin) Class.forName(className).getDeclaredConstructor().newInstance();+ listenerPlugin.init(config);+ return listenerPlugin;+ } catch (Exception e) {+ LOG.error(+ "Failed to create and initialize event listener {}, className: {}.",+ listenerName,+ className,+ e);+ throw new RuntimeException(e);+ }+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/EventListenerPluginWrapper.java b/core/src/main/java/com/datastrato/gravitino/listener/EventListenerPluginWrapper.javanew file mode 100644index 0000000000..2dda84a84b--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/EventListenerPluginWrapper.java@@ -0,0 +1,68 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener;++import com.datastrato.gravitino.listener.api.EventListenerPlugin;+import com.datastrato.gravitino.listener.api.event.Event;+import com.google.common.annotations.VisibleForTesting;+import java.util.Map;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * A wrapper for user provided event listener, could contain common logic like exception handling,+ * recording metrics, recording slow event process.+ */+public class EventListenerPluginWrapper implements EventListenerPlugin {+ private static final Logger LOG = LoggerFactory.getLogger(EventListenerPluginWrapper.class);+ private String listenerName;+ private EventListenerPlugin userEventListener;++ public EventListenerPluginWrapper(String listenerName, EventListenerPlugin userEventListener) {+ this.listenerName = listenerName;+ this.userEventListener = userEventListener;+ }++ @Override+ public void init(Map<String, String> properties) {+ throw new RuntimeException(+ "Should not reach here, the event listener has already been initialized.");+ }++ @Override+ public void start() {+ userEventListener.start();+ LOG.info("Start event listener {}.", listenerName);+ }++ @Override+ public void stop() {+ try {+ userEventListener.stop();+ LOG.info("Stop event listener {}.", listenerName);+ } catch (Exception e) {+ LOG.warn("Failed to stop event listener {}.", listenerName, e);+ }+ }++ @Override+ public void onPostEvent(Event event) {+ try {+ userEventListener.onPostEvent(event);+ } catch (Exception e) {+ LOG.warn(+ "Event listener {} process event {} failed,",+ listenerName,+ event.getClass().getSimpleName(),+ e);+ }+ }++ @VisibleForTesting+ EventListenerPlugin getUserEventListener() {+ return userEventListener;+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/api/EventListenerPlugin.java b/core/src/main/java/com/datastrato/gravitino/listener/api/EventListenerPlugin.javanew file mode 100644index 0000000000..24bebbac30--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/api/EventListenerPlugin.java@@ -0,0 +1,106 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener.api;++import com.datastrato.gravitino.annotation.DeveloperApi;+import com.datastrato.gravitino.listener.api.event.Event;+import java.util.Map;++/**+ * Defines an interface for event listeners that manage the lifecycle and state of a plugin,+ * including its initialization, starting, and stopping processes, as well as the handling of events+ * occurring after various operations have been executed.+ *+ * <p>This interface is intended for developers who implement plugins within a system, providing a+ * structured approach to managing plugin operations and event processing.+ */+@DeveloperApi+public interface EventListenerPlugin {+ /**+ * Defines the operational modes for event processing within an event listener, catering to both+ * synchronous and asynchronous processing strategies. Each mode determines how events are+ * handled, balancing between immediacy and resource efficiency.+ *+ * <ul>+ * <li>{@code SYNC} - Events are processed synchronously, immediately after the associated+ * operation completes. While this approach ensures prompt handling of events, it may block+ * the main process if the event listener requires significant time to process an event.+ * <li>{@code ASYNC_ISOLATED} - Events are handled asynchronously with each listener possessing+ * its own distinct event-processing queue. This mode allows for customized and isolated+ * event processing but may increase resource consumption due to the necessity of a+ * dedicated event dispatcher for each listener.+ * <li>{@code ASYNC_SHARED} - In this mode, event listeners share a common event-processing+ * queue, processing events asynchronously. This approach enhances resource efficiency by+ * utilizing a shared dispatcher for handling events across multiple listeners.+ * </ul>+ */+ enum Mode {+ SYNC,+ ASYNC_ISOLATED,+ ASYNC_SHARED+ }++ /**+ * Initializes the plugin with the given set of properties. This phase may involve setting up+ * necessary resources for the plugin's functionality.+ *+ * <p>Failure during this phase will prevent the server from starting, highlighting a critical+ * setup issue with the plugin.+ *+ * @param properties A map of properties used for initializing the plugin.+ * @throws RuntimeException Indicates a critical failure in plugin setup, preventing server+ * startup.+ */+ void init(Map<String, String> properties) throws RuntimeException;++ /**+ * Starts the plugin, transitioning it to a ready state. This method is invoked after successful+ * initialization.+ *+ * <p>A failure to start indicates an inability for the plugin to enter its operational state,+ * which will prevent the server from starting.+ *+ * @throws RuntimeException Indicates a failure to start the plugin, blocking the server's launch.+ */+ void start() throws RuntimeException;++ /**+ * Stops the plugin, releasing any resources that were allocated during its operation. This method+ * aims to ensure a clean termination, mitigating potential resource leaks or incomplete+ * shutdowns.+ *+ * <p>While the server's operation is unaffected by exceptions thrown during this process, failing+ * to properly stop may lead to resource management issues.+ *+ * @throws RuntimeException Indicates issues during the stopping process, potentially leading to+ * resource leaks.+ */+ void stop() throws RuntimeException;++ /**+ * Handles events generated after the completion of an operation. Implementers are responsible for+ * processing these events, which may involve additional logic to respond to the operation+ * outcomes.+ *+ * <p>This method provides a hook for post-operation event processing, allowing plugins to react+ * or adapt based on the event details.+ *+ * @param event The event to be processed.+ * @throws RuntimeException Indicates issues encountered during event processing.+ */+ void onPostEvent(Event event) throws RuntimeException;++ /**+ * Specifies the default operational mode for event processing by the plugin. The default+ * implementation is synchronous, but implementers can override this to utilize asynchronous+ * processing modes.+ *+ * @return The operational {@link Mode} of the plugin for event processing.+ */+ default Mode mode() {+ return Mode.SYNC;+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/api/event/CreateTableEvent.java b/core/src/main/java/com/datastrato/gravitino/listener/api/event/CreateTableEvent.javanew file mode 100644index 0000000000..b68dee9db0--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/api/event/CreateTableEvent.java@@ -0,0 +1,57 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener.api.event;++import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.annotation.DeveloperApi;+import com.datastrato.gravitino.listener.api.info.TableInfo;++/**+ * Represents an event triggered upon the successful creation of a table. This class extends {@link+ * TableEvent} to provide detailed information specifically related to the table's creation. This+ * includes the final table information as it is returned to the user once the creation process has+ * successfully completed.+ *+ * <p>Such an event is instrumental for a variety of purposes including, but not limited to,+ * auditing activities associated with table creation, monitoring the creation of tables within a+ * system, and acquiring insights into the final configuration and state of a newly created table.+ */+@DeveloperApi+public final class CreateTableEvent extends TableEvent {+ private final TableInfo createdTableInfo;++ /**+ * Constructs an instance of {@code CreateTableEvent}, capturing essential details about the+ * successful creation of a table.+ *+ * <p>This constructor documents the successful culmination of the table creation process by+ * encapsulating the final state of the table. This includes any adjustments or resolutions made+ * to the table's properties or configuration during the creation process.+ *+ * @param user The username of the individual who initiated the table creation. This information+ * is vital for tracking the source of changes and for audit trails.+ * @param identifier The unique identifier of the table that was created, providing a precise+ * reference to the affected table.+ * @param createdTableInfo The final state of the table post-creation. This information is+ * reflective of the table's configuration, including any default settings or properties+ * applied during the creation process.+ */+ public CreateTableEvent(String user, NameIdentifier identifier, TableInfo createdTableInfo) {+ super(user, identifier);+ this.createdTableInfo = createdTableInfo;+ }++ /**+ * Retrieves the final state and configuration information of the table as it was returned to the+ * user after successful creation.+ *+ * @return A {@link TableInfo} instance encapsulating the comprehensive details of the newly+ * created table, highlighting its configuration and any default settings applied.+ */+ public TableInfo createdTableInfo() {+ return createdTableInfo;+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/api/event/CreateTableFailureEvent.java b/core/src/main/java/com/datastrato/gravitino/listener/api/event/CreateTableFailureEvent.javanew file mode 100644index 0000000000..6370378b3f--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/api/event/CreateTableFailureEvent.java@@ -0,0 +1,55 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener.api.event;++import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.annotation.DeveloperApi;+import com.datastrato.gravitino.listener.api.info.TableInfo;+import com.datastrato.gravitino.rel.Table;++/**+ * Represents an event that is generated when an attempt to create a table fails due to an+ * exception. This class extends {@link TableFailureEvent} to specifically address failure scenarios+ * encountered during the table creation process. It encapsulates both the exception that caused the+ * failure and the original request details for the table creation, providing comprehensive context+ * for the failure.+ */+@DeveloperApi+public final class CreateTableFailureEvent extends TableFailureEvent {+ private final TableInfo createTableRequest;++ /**+ * Constructs a {@code CreateTableFailureEvent} instance, capturing detailed information about the+ * failed table creation attempt.+ *+ * @param user The user who initiated the table creation operation. This information is essential+ * for auditing and diagnosing the cause of the failure.+ * @param identifier The identifier of the table that was attempted to be created. This helps in+ * pinpointing the specific table related to the failure.+ * @param exception The exception that was thrown during the table creation operation, providing+ * insight into what went wrong.+ * @param createTableRequest The original request information used to attempt to create the table.+ * This includes details such as the intended table schema, properties, and other+ * configuration options that were specified.+ */+ public CreateTableFailureEvent(+ String user, NameIdentifier identifier, Exception exception, TableInfo createTableRequest) {+ super(user, identifier, exception);+ this.createTableRequest = createTableRequest;+ }++ /**+ * Retrieves the original request information for the attempted table creation. This information+ * can be valuable for understanding the configuration and expectations that led to the failure,+ * facilitating analysis and potential corrective actions.+ *+ * @return The {@link Table} instance representing the request information for the failed table+ * creation attempt.+ */+ public TableInfo createTableRequest() {+ return createTableRequest;+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/api/event/DropTableEvent.java b/core/src/main/java/com/datastrato/gravitino/listener/api/event/DropTableEvent.javanew file mode 100644index 0000000000..a75939eaf6--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/api/event/DropTableEvent.java@@ -0,0 +1,47 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener.api.event;++import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.annotation.DeveloperApi;++/**+ * Represents an event that is generated after a table is successfully dropped from the database.+ * This class extends {@link TableEvent} to capture specific details related to the dropping of a+ * table, including the status of the table's existence at the time of the operation and identifying+ * information about the table and the user who initiated the drop operation.+ */+@DeveloperApi+public final class DropTableEvent extends TableEvent {+ private final boolean isExists;++ /**+ * Constructs a new {@code DropTableEvent} instance, encapsulating information about the outcome+ * of a table drop operation.+ *+ * @param user The user who initiated the drop table operation. This information is important for+ * auditing purposes and understanding who is responsible for the change.+ * @param identifier The identifier of the table that was attempted to be dropped. This provides a+ * clear reference to the specific table affected by the operation.+ * @param isExists A boolean flag indicating whether the table existed at the time of the drop+ * operation. This can be useful to understand the state of the database prior to the+ * operation.+ */+ public DropTableEvent(String user, NameIdentifier identifier, boolean isExists) {+ super(user, identifier);+ this.isExists = isExists;+ }++ /**+ * Retrieves the existence status of the table at the time of the drop operation.+ *+ * @return A boolean value indicating whether the table existed. {@code true} if the table+ * existed, otherwise {@code false}.+ */+ public boolean isExists() {+ return isExists;+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/api/event/DropTableFailureEvent.java b/core/src/main/java/com/datastrato/gravitino/listener/api/event/DropTableFailureEvent.javanew file mode 100644index 0000000000..78076fe961--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/api/event/DropTableFailureEvent.java@@ -0,0 +1,36 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener.api.event;++import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.annotation.DeveloperApi;++/**+ * Represents an event that is generated when an attempt to drop a table from the database fails due+ * to an exception. This class extends {@link TableFailureEvent} to provide specific context related+ * to table drop failures, encapsulating details about the user who initiated the operation, the+ * identifier of the table that was attempted to be dropped, and the exception that led to the+ * failure. This event can be used for auditing purposes and to facilitate error handling and+ * diagnostic processes.+ */+@DeveloperApi+public final class DropTableFailureEvent extends TableFailureEvent {+ /**+ * Constructs a new {@code DropTableFailureEvent} instance, capturing detailed information about+ * the failed attempt to drop a table.+ *+ * @param user The user who initiated the drop table operation. This information is crucial for+ * understanding the context of the operation and for auditing who is responsible for the+ * attempted change.+ * @param identifier The identifier of the table that the operation attempted to drop. This+ * provides a clear reference to the specific table involved in the failure.+ * @param exception The exception that was thrown during the drop table operation, offering+ * insights into what went wrong and why the operation failed.+ */+ public DropTableFailureEvent(String user, NameIdentifier identifier, Exception exception) {+ super(user, identifier, exception);+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/api/event/Event.java b/core/src/main/java/com/datastrato/gravitino/listener/api/event/Event.javanew file mode 100644index 0000000000..484120a8bc--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/api/event/Event.java@@ -0,0 +1,52 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener.api.event;++import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.annotation.DeveloperApi;++/**+ * The abstract base class for all events. It encapsulates common information such as the user who+ * generated the event and the identifier for the resource associated with the event. Subclasses+ * should provide specific details related to their individual event types.+ */+@DeveloperApi+public abstract class Event {+ private final String user;+ private final NameIdentifier identifier;++ /**+ * Constructs an Event instance with the specified user and resource identifier details.+ *+ * @param user The user associated with this event. It provides context about who triggered the+ * event.+ * @param identifier The resource identifier associated with this event. This may refer to various+ * types of resources such as a metalake, catalog, schema, or table, etc.+ */+ protected Event(String user, NameIdentifier identifier) {+ this.user = user;+ this.identifier = identifier;+ }++ /**+ * Retrieves the user associated with this event.+ *+ * @return A string representing the user associated with this event.+ */+ public String user() {+ return user;+ }++ /**+ * Retrieves the resource identifier associated with this event.+ *+ * @return A NameIdentifier object that represents the resource, like a metalake, catalog, schema,+ * table, etc., associated with the event.+ */+ public NameIdentifier identifier() {+ return identifier;+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/api/event/FailureEvent.java b/core/src/main/java/com/datastrato/gravitino/listener/api/event/FailureEvent.javanew file mode 100644index 0000000000..ca0c263c20--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/api/event/FailureEvent.java@@ -0,0 +1,47 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener.api.event;++import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.annotation.DeveloperApi;++/**+ * Represents an abstract base class for events that indicate a failure in an operation. This class+ * extends {@link Event} to encapsulate common information related to failures, such as the user who+ * performed the operation, the resource identifier, and the exception that was thrown during the+ * operation. This class serves as a foundation for more specific failure event types that might+ * include additional context or details about the failure.+ */+@DeveloperApi+public abstract class FailureEvent extends Event {+ private final Exception exception;++ /**+ * Constructs a new {@code FailureEvent} instance with the specified user, resource identifier,+ * and the exception that was thrown.+ *+ * @param user The user associated with the operation that resulted in a failure. This information+ * is important for auditing and understanding the context of the failure.+ * @param identifier The identifier of the resource involved in the operation that failed. This+ * provides a clear reference to what was being acted upon when the exception occurred.+ * @param exception The exception that was thrown during the operation. This is the primary piece+ * of information indicating what went wrong.+ */+ protected FailureEvent(String user, NameIdentifier identifier, Exception exception) {+ super(user, identifier);+ this.exception = exception;+ }++ /**+ * Retrieves the exception that was thrown during the operation, indicating the reason for the+ * failure.+ *+ * @return The exception thrown by the operation.+ */+ public Exception exception() {+ return exception;+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/api/event/TableEvent.java b/core/src/main/java/com/datastrato/gravitino/listener/api/event/TableEvent.javanew file mode 100644index 0000000000..238ad0eea4--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/api/event/TableEvent.java@@ -0,0 +1,33 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener.api.event;++import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.annotation.DeveloperApi;++/**+ * Represents an abstract base class for events related to table operations. This class extends+ * {@link Event} to provide a more specific context involving operations on tables, such as+ * creation, deletion, or modification. It captures essential information including the user+ * performing the operation and the identifier of the table being operated on.+ *+ * <p>Concrete implementations of this class should provide additional details pertinent to the+ * specific type of table operation being represented.+ */+@DeveloperApi+public abstract class TableEvent extends Event {+ /**+ * Constructs a new {@code TableEvent} with the specified user and table identifier.+ *+ * @param user The user responsible for triggering the table operation. This information is+ * crucial for auditing and tracking purposes.+ * @param identifier The identifier of the table involved in the operation. This encapsulates+ * details such as the metalake, catalog, schema, and table name.+ */+ protected TableEvent(String user, NameIdentifier identifier) {+ super(user, identifier);+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/api/event/TableFailureEvent.java b/core/src/main/java/com/datastrato/gravitino/listener/api/event/TableFailureEvent.javanew file mode 100644index 0000000000..8b78df964c--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/api/event/TableFailureEvent.java@@ -0,0 +1,38 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener.api.event;++import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.annotation.DeveloperApi;++/**+ * An abstract class representing events that are triggered when a table operation fails due to an+ * exception. This class extends {@link FailureEvent} to provide a more specific context related to+ * table operations, encapsulating details about the user who initiated the operation, the+ * identifier of the table involved, and the exception that led to the failure.+ *+ * <p>Implementations of this class can be used to convey detailed information about failures in+ * operations such as creating, updating, deleting, or querying tables, making it easier to diagnose+ * and respond to issues.+ */+@DeveloperApi+public abstract class TableFailureEvent extends FailureEvent {+ /**+ * Constructs a new {@code TableFailureEvent} instance, capturing information about the failed+ * table operation.+ *+ * @param user The user associated with the failed table operation. This information helps in+ * auditing and understanding the context of the operation that resulted in a failure.+ * @param identifier The identifier of the table that was involved in the failed operation. This+ * provides a clear reference to the specific table that the operation was attempting to+ * modify or interact with.+ * @param exception The exception that was thrown during the table operation, indicating the cause+ * of the failure.+ */+ protected TableFailureEvent(String user, NameIdentifier identifier, Exception exception) {+ super(user, identifier, exception);+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/listener/api/info/TableInfo.java b/core/src/main/java/com/datastrato/gravitino/listener/api/info/TableInfo.javanew file mode 100644index 0000000000..2f7329e050--- /dev/null+++ b/core/src/main/java/com/datastrato/gravitino/listener/api/info/TableInfo.java@@ -0,0 +1,130 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener.api.info;++import com.datastrato.gravitino.Audit;+import com.datastrato.gravitino.annotation.DeveloperApi;+import com.datastrato.gravitino.rel.Column;+import com.datastrato.gravitino.rel.Table;+import com.datastrato.gravitino.rel.expressions.distributions.Distribution;+import com.datastrato.gravitino.rel.expressions.distributions.Distributions;+import com.datastrato.gravitino.rel.expressions.sorts.SortOrder;+import com.datastrato.gravitino.rel.expressions.transforms.Transform;+import com.datastrato.gravitino.rel.indexes.Index;+import com.datastrato.gravitino.rel.indexes.Indexes;+import com.google.common.collect.ImmutableMap;+import java.util.Map;+import javax.annotation.Nullable;++/**+ * TableInfo exposes table information for event listener, it's supposed to be read only. Most of+ * the fields are shallow copied internally not deep copies for performance.+ */+@DeveloperApi+public final class TableInfo {+ private final String name;+ private final Column[] columns;+ @Nullable private final String comment;+ private final Map<String, String> properties;+ private final Transform[] partitions;+ private final Distribution distribution;+ private final SortOrder[] sortOrders;+ private final Index[] indexes;+ @Nullable private final Audit auditInfo;++ public TableInfo(Table table) {+ this(+ table.name(),+ table.columns(),+ table.comment(),+ table.properties(),+ table.partitioning(),+ table.distribution(),+ table.sortOrder(),+ table.index(),+ table.auditInfo());+ }++ public TableInfo(+ String name,+ Column[] columns,+ String comment,+ Map<String, String> properties,+ Transform[] partitions,+ Distribution distribution,+ SortOrder[] sortOrders,+ Index[] indexes,+ Audit auditInfo) {+ this.name = name;+ this.columns = columns.clone();+ this.comment = comment;+ if (properties == null) {+ this.properties = ImmutableMap.of();+ } else {+ this.properties = ImmutableMap.<String, String>builder().putAll(properties).build();+ }+ if (partitions == null) {+ this.partitions = new Transform[0];+ } else {+ this.partitions = partitions.clone();+ }+ if (distribution == null) {+ this.distribution = Distributions.NONE;+ } else {+ this.distribution = distribution;+ }+ if (sortOrders == null) {+ this.sortOrders = new SortOrder[0];+ } else {+ this.sortOrders = sortOrders.clone();+ }+ if (indexes == null) {+ this.indexes = Indexes.EMPTY_INDEXES;+ } else {+ this.indexes = indexes.clone();+ }+ this.auditInfo = auditInfo;+ }++ /** Audit information is null when tableInfo is generated from create table request. */+ @Nullable+ public Audit auditInfo() {+ return this.auditInfo;+ }++ public String name() {+ return name;+ }++ public Column[] columns() {+ return columns;+ }++ public Transform[] partitioning() {+ return partitions;+ }++ public SortOrder[] sortOrder() {+ return sortOrders;+ }++ public Distribution distribution() {+ return distribution;+ }++ public Index[] index() {+ return indexes;+ }++ @Nullable+ public String comment() {+ return comment;+ }++ public Map<String, String> properties() {+ return properties;+ }+}diff --git a/core/src/main/java/com/datastrato/gravitino/utils/PrincipalUtils.java b/core/src/main/java/com/datastrato/gravitino/utils/PrincipalUtils.javaindex cbaba064ec..d8a3255f1e 100644--- a/core/src/main/java/com/datastrato/gravitino/utils/PrincipalUtils.java+++ b/core/src/main/java/com/datastrato/gravitino/utils/PrincipalUtils.java@@ -38,4 +38,8 @@ public class PrincipalUtils {}return subject.getPrincipals(UserPrincipal.class).iterator().next();}++ public static String getCurrentUserName() {+ return getCurrentPrincipal().getName();+ }}diff --git a/core/src/test/java/com/datastrato/gravitino/listener/TestEventListenerManager.java b/core/src/test/java/com/datastrato/gravitino/listener/TestEventListenerManager.javanew file mode 100644index 0000000000..f670a39404--- /dev/null+++ b/core/src/test/java/com/datastrato/gravitino/listener/TestEventListenerManager.java@@ -0,0 +1,252 @@+/*+ * Copyright 2024 Datastrato Pvt Ltd.+ * This software is licensed under the Apache License version 2.+ */++package com.datastrato.gravitino.listener;++import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.listener.api.EventListenerPlugin;+import com.datastrato.gravitino.listener.api.event.Event;+import com.google.common.collect.ImmutableSet;+import java.time.Instant;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.stream.Collectors;+import lombok.Getter;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++public class TestEventListenerManager {+ static class DummyEvent extends Event {+ protected DummyEvent(String user, NameIdentifier identifier) {+ super(user, identifier);+ }+ }++ static class DummyEventListener implements EventListenerPlugin {+ Map<String, String> properties;+ @Getter List<Event> events = new ArrayList<>();++ @Override+ public void init(Map<String, String> properties) {+ this.properties = properties;+ }++ @Override+ public void start() {}++ @Override+ public void stop() {}++ @Override+ public void onPostEvent(Event event) {+ this.events.add(event);+ }++ @Override+ public Mode mode() {+ return Mode.SYNC;+ }+ }++ static class DummyAsyncEventListener extends DummyEventListener {+ List<Event> tryGetEvents() {+ Instant waitTime = Instant.now().plusSeconds(20);+ while (getEvents().size() == 0 && Instant.now().isBefore(waitTime)) {+ try {+ Thread.sleep(100);+ } catch (InterruptedException e) {+ break;+ }+ }+ return getEvents();+ }++ @Override+ public Mode mode() {+ return Mode.ASYNC_SHARED;+ }+ }++ static class DummyAsyncIsolatedEventListener extends DummyAsyncEventListener {+ @Override+ public Mode mode() {+ return Mode.ASYNC_ISOLATED;+ }+ }++ private static final DummyEvent DUMMY_EVENT_INSTANCE =+ new DummyEvent("user", NameIdentifier.of("a", "b"));++ @Test+ void testSyncListener() {+ String sync1 = "sync1";+ String sync2 = "sync2";+ Map<String, String> properties = createSyncEventListenerConfig(sync1, sync2);++ EventListenerManager eventListenerManager = new EventListenerManager();+ eventListenerManager.init(properties);+ eventListenerManager.start();++ EventBus eventBus = eventListenerManager.createEventBus();+ eventBus.dispatchEvent(DUMMY_EVENT_INSTANCE);++ List<EventListenerPlugin> listeners = eventBus.getPostEventListeners();+ Assertions.assertEquals(2, listeners.size());+ Set<String> names =+ listeners.stream()+ .map(+ listener -> {+ Assertions.assertTrue(listener instanceof EventListenerPluginWrapper);+ EventListenerPluginWrapper wrapper = (EventListenerPluginWrapper) listener;+ EventListenerPlugin userListener = wrapper.getUserEventListener();+ Assertions.assertTrue(userListener instanceof DummyEventListener);+ checkEvents(((DummyEventListener) userListener).getEvents());+ return ((DummyEventListener) userListener).properties.get("name");+ })+ .collect(Collectors.toSet());+ Assertions.assertEquals(ImmutableSet.of(sync1, sync2), names);++ eventListenerManager.stop();+ }++ @Test+ void testSharedAsyncListeners() {+ String async1 = "async1";+ String async2 = "async2";+ Map<String, String> properties = createAsyncEventListenerConfig(async1, async2);++ EventListenerManager eventListenerManager = new EventListenerManager();+ eventListenerManager.init(properties);+ eventListenerManager.start();++ EventBus eventBus = eventListenerManager.createEventBus();+ eventBus.dispatchEvent(DUMMY_EVENT_INSTANCE);+ List<EventListenerPlugin> listeners = eventBus.getPostEventListeners();++ Assertions.assertEquals(1, listeners.size());+ Assertions.assertTrue(listeners.get(0) instanceof AsyncQueueListener);+ AsyncQueueListener asyncQueueListener = (AsyncQueueListener) listeners.get(0);+ List<EventListenerPlugin> shareQueueListeners = asyncQueueListener.getEventListeners();+ Assertions.assertEquals(2, shareQueueListeners.size());+ Set<String> sharedQueueListenerNames =+ shareQueueListeners.stream()+ .map(+ shareQueueListener -> {+ Assertions.assertTrue(shareQueueListener instanceof EventListenerPluginWrapper);+ EventListenerPlugin userListener =+ ((EventListenerPluginWrapper) shareQueueListener).getUserEventListener();+ Assertions.assertTrue(userListener instanceof DummyAsyncEventListener);+ checkEvents(((DummyAsyncEventListener) userListener).tryGetEvents());+ return ((DummyAsyncEventListener) userListener).properties.get("name");+ })+ .collect(Collectors.toSet());+ Assertions.assertEquals(ImmutableSet.of(async1, async2), sharedQueueListenerNames);++ eventListenerManager.stop();+ }++ @Test+ void testIsolatedAsyncListeners() {+ String async1 = "async1";+ String async2 = "async2";+ Map<String, String> properties = createIsolatedAsyncEventListenerConfig(async1, async2);++ EventListenerManager eventListenerManager = new EventListenerManager();+ eventListenerManager.init(properties);+ eventListenerManager.start();++ EventBus eventBus = eventListenerManager.createEventBus();+ eventBus.dispatchEvent(DUMMY_EVENT_INSTANCE);+ List<EventListenerPlugin> listeners = eventBus.getPostEventListeners();++ Assertions.assertEquals(2, listeners.size());+ Set<String> isolatedListenerNames =+ listeners.stream()+ .map(+ listener -> {+ Assertions.assertTrue(listener instanceof AsyncQueueListener);+ AsyncQueueListener asyncQueueListener = (AsyncQueueListener) listener;+ List<EventListenerPlugin> internalListeners =+ asyncQueueListener.getEventListeners();+ Assertions.assertEquals(1, internalListeners.size());+ Assertions.assertTrue(+ internalListeners.get(0) instanceof EventListenerPluginWrapper);+ EventListenerPlugin userListener =+ ((EventListenerPluginWrapper) internalListeners.get(0))+ .getUserEventListener();+ Assertions.assertTrue(userListener instanceof DummyAsyncEventListener);+ checkEvents(((DummyAsyncEventListener) userListener).tryGetEvents());+ return ((DummyAsyncEventListener) userListener).properties.get("name");+ })+ .collect(Collectors.toSet());+ Assertions.assertEquals(ImmutableSet.of(async1, async2), isolatedListenerNames);++ eventListenerManager.stop();+ }++ private Map<String, String> createIsolatedAsyncEventListenerConfig(String async1, String async2) {+ Map<String, String> config = new HashMap<>();++ config.put(+ EventListenerManager.GRAVITINO_EVENT_LISTENER_NAMES, String.join(",", async1, async2));++ config.put(+ async1 + "." + EventListenerManager.GRAVITINO_EVENT_LISTENER_CLASS,+ DummyAsyncIsolatedEventListener.class.getName());+ config.put(async1 + ".name", async1);++ config.put(+ async2 + "." + EventListenerManager.GRAVITINO_EVENT_LISTENER_CLASS,+ DummyAsyncIsolatedEventListener.class.getName());+ config.put(async2 + ".name", async2);++ return config;+ }++ private Map<String, String> createAsyncEventListenerConfig(String async1, String async2) {+ Map<String, String> config = new HashMap<>();++ config.put(+ EventListenerManager.GRAVITINO_EVENT_LISTENER_NAMES, String.join(",", async1, async2));++ config.put(+ async1 + "." + EventListenerManager.GRAVITINO_EVENT_LISTENER_CLASS,+ DummyAsyncEventListener.class.getName());+ config.put(async1 + ".name", async1);++ config.put(+ async2 + "." + EventListenerManager.GRAVITINO_EVENT_LISTENER_CLASS,+ DummyAsyncEventListener.class.getName());+ config.put(async2 + ".name", async2);++ return config;+ }++ private Map<String, String> createSyncEventListenerConfig(String sync1, String sync2) {+ Map<String, String> config = new HashMap<>();++ config.put(EventListenerManager.GRAVITINO_EVENT_LISTENER_NAMES, String.join(",", sync1, sync2));++ config.put(+ sync1 + "." + EventListenerManager.GRAVITINO_EVENT_LISTENER_CLASS,+ DummyEventListener.class.getName());+ config.put(sync1 + ".name", sync1);++ config.put(+ sync2 + "." + EventListenerManager.GRAVITINO_EVENT_LISTENER_CLASS,+ DummyEventListener.class.getName());+ config.put(sync2 + ".name", sync2);++ return config;+ }++ private void checkEvents(List<Event> events) {+ Assertions.assertEquals(1, events.size());+ Assertions.assertEquals(DUMMY_EVENT_INSTANCE, events.get(0));+ }+}diff --git a/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.java b/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.javaindex d17e21159b..67756319a6 100644--- a/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.java+++ b/server/src/main/java/com/datastrato/gravitino/server/GravitinoServer.java@@ -9,7 +9,7 @@ import com.datastrato.gravitino.GravitinoEnv;import com.datastrato.gravitino.catalog.CatalogManager;import com.datastrato.gravitino.catalog.FilesetOperationDispatcher;import com.datastrato.gravitino.catalog.SchemaOperationDispatcher;-import com.datastrato.gravitino.catalog.TableOperationDispatcher;+import com.datastrato.gravitino.catalog.TableDispatcher;import com.datastrato.gravitino.metalake.MetalakeManager;import com.datastrato.gravitino.metrics.MetricsSystem;import com.datastrato.gravitino.metrics.source.MetricsSource;@@ -82,9 +82,7 @@ public class GravitinoServer extends ResourceConfig {bind(gravitinoEnv.schemaOperationDispatcher()).to(SchemaOperationDispatcher.class).ranked(1);- bind(gravitinoEnv.tableOperationDispatcher())- .to(TableOperationDispatcher.class)- .ranked(1);+ bind(gravitinoEnv.tableDispatcher()).to(TableDispatcher.class).ranked(1);bind(gravitinoEnv.filesetOperationDispatcher()).to(FilesetOperationDispatcher.class).ranked(1);diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/PartitionOperations.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/PartitionOperations.javaindex dd43901c7d..0b8e17ad6f 100644--- a/server/src/main/java/com/datastrato/gravitino/server/web/rest/PartitionOperations.java+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/PartitionOperations.java@@ -10,7 +10,7 @@ import static com.datastrato.gravitino.dto.util.DTOConverters.toDTOs;import com.codahale.metrics.annotation.ResponseMetered;import com.codahale.metrics.annotation.Timed;import com.datastrato.gravitino.NameIdentifier;-import com.datastrato.gravitino.catalog.TableOperationDispatcher;+import com.datastrato.gravitino.catalog.TableDispatcher;import com.datastrato.gravitino.dto.rel.partitions.PartitionDTO;import com.datastrato.gravitino.dto.requests.AddPartitionsRequest;import com.datastrato.gravitino.dto.responses.DropResponse;@@ -44,11 +44,11 @@ import org.slf4j.LoggerFactory;public class PartitionOperations {private static final Logger LOG = LoggerFactory.getLogger(PartitionOperations.class);- private final TableOperationDispatcher dispatcher;+ private final TableDispatcher dispatcher;@Context private HttpServletRequest httpRequest;@Inject- public PartitionOperations(TableOperationDispatcher dispatcher) {+ public PartitionOperations(TableDispatcher dispatcher) {this.dispatcher = dispatcher;}diff --git a/server/src/main/java/com/datastrato/gravitino/server/web/rest/TableOperations.java b/server/src/main/java/com/datastrato/gravitino/server/web/rest/TableOperations.javaindex 2c94c7caa8..d45017b767 100644--- a/server/src/main/java/com/datastrato/gravitino/server/web/rest/TableOperations.java+++ b/server/src/main/java/com/datastrato/gravitino/server/web/rest/TableOperations.java@@ -11,7 +11,7 @@ import com.codahale.metrics.annotation.ResponseMetered;import com.codahale.metrics.annotation.Timed;import com.datastrato.gravitino.NameIdentifier;import com.datastrato.gravitino.Namespace;-import com.datastrato.gravitino.catalog.TableOperationDispatcher;+import com.datastrato.gravitino.catalog.TableDispatcher;import com.datastrato.gravitino.dto.requests.TableCreateRequest;import com.datastrato.gravitino.dto.requests.TableUpdateRequest;import com.datastrato.gravitino.dto.requests.TableUpdatesRequest;@@ -46,12 +46,12 @@ public class TableOperations {private static final Logger LOG = LoggerFactory.getLogger(TableOperations.class);- private final TableOperationDispatcher dispatcher;+ private final TableDispatcher dispatcher;@Context private HttpServletRequest httpRequest;@Inject- public TableOperations(TableOperationDispatcher dispatcher) {+ public TableOperations(TableDispatcher dispatcher) {this.dispatcher = dispatcher;}diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestPartitionOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestPartitionOperations.javaindex cf8ffceb84..a6f7b178b7 100644--- a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestPartitionOperations.java+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestPartitionOperations.java@@ -16,6 +16,7 @@ import static org.mockito.Mockito.when;import com.datastrato.gravitino.Config;import com.datastrato.gravitino.GravitinoEnv;+import com.datastrato.gravitino.catalog.TableDispatcher;import com.datastrato.gravitino.catalog.TableOperationDispatcher;import com.datastrato.gravitino.dto.rel.partitions.PartitionDTO;import com.datastrato.gravitino.dto.requests.AddPartitionsRequest;@@ -117,7 +118,7 @@ public class TestPartitionOperations extends JerseyTest {new AbstractBinder() {@Overrideprotected void configure() {- bind(dispatcher).to(TableOperationDispatcher.class).ranked(2);+ bind(dispatcher).to(TableDispatcher.class).ranked(2);bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);}});diff --git a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestTableOperations.java b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestTableOperations.javaindex 8dcd6630a1..6d46bdf6fc 100644--- a/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestTableOperations.java+++ b/server/src/test/java/com/datastrato/gravitino/server/web/rest/TestTableOperations.java@@ -17,6 +17,7 @@ import com.datastrato.gravitino.Audit;import com.datastrato.gravitino.Config;import com.datastrato.gravitino.GravitinoEnv;import com.datastrato.gravitino.NameIdentifier;+import com.datastrato.gravitino.catalog.TableDispatcher;import com.datastrato.gravitino.catalog.TableOperationDispatcher;import com.datastrato.gravitino.dto.rel.ColumnDTO;import com.datastrato.gravitino.dto.rel.DistributionDTO;@@ -120,7 +121,7 @@ public class TestTableOperations extends JerseyTest {new AbstractBinder() {@Overrideprotected void configure() {- bind(dispatcher).to(TableOperationDispatcher.class).ranked(2);+ bind(dispatcher).to(TableDispatcher.class).ranked(2);bindFactory(MockServletRequestFactory.class).to(HttpServletRequest.class);}});