somandal commented on code in PR #16857:
URL: https://github.com/apache/pinot/pull/16857#discussion_r2414466805


##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/DistributedTaskLockManager.java:
##########
@@ -0,0 +1,288 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pinot.controller.helix.core.minion;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.concurrent.TimeUnit;
+import javax.annotation.Nullable;
+import org.apache.helix.AccessOption;
+import org.apache.helix.store.zk.ZkHelixPropertyStore;
+import org.apache.helix.zookeeper.datamodel.ZNRecord;
+import org.apache.pinot.common.metadata.ZKMetadataProvider;
+import org.apache.pinot.common.metrics.ControllerMetrics;
+import org.apache.pinot.common.metrics.ControllerTimer;
+import org.apache.zookeeper.data.Stat;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Manages distributed locks for minion task generation using ZooKeeper 
ephemeral nodes that automatically disappear
+ * when the controller session ends or when the lock is explicitly released. 
This approach provides automatic cleanup
+ * and is suitable for long-running task generation.
+ * Locks are at the table level, to ensure that only one type of task can be 
generated per table at any given time.
+ * This is to prevent task types which shouldn't run in parallel from being 
generated at the same time.
+ * <p>
+ * ZK EPHEMERAL Lock Node:
+ *   <ul>
+ *     <li>Every lock is created at the table level with the name: 
{tableName}-Lock, under the base path
+ *     MINION_TASK_METADATA within the PROPERTYSTORE.
+ *     <li>If the propertyStore::create() call returns true, that means the 
lock node was successfully created and the
+ *     lock belongs to the current controller, otherwise it was not. If the 
lock node already exists, this will return
+ *     false. No clean-up of the lock node is needed if the 
propertyStore::create() call returns false.
+ *     <li>The locks are EPHEMERAL in nature, meaning that once the session 
with ZK is lost, the lock is automatically
+ *     cleaned up. Scenarios when the ZK session can be lost: a) controller 
shutdown, b) controller crash, c) ZK session
+ *     expiry (e.g. long GC pauses can cause this). This property helps ensure 
that the lock is released under
+ *     controller failure.
+ *   </ul>
+ * <p>
+ */
+public class DistributedTaskLockManager {
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(DistributedTaskLockManager.class);
+
+  // Lock paths are constructed using ZKMetadataProvider
+  private static final String LOCK_OWNER_KEY = "lockOwner";
+  private static final String LOCK_CREATION_TIME_MS = "lockCreationTimeMs";
+
+  private final ZkHelixPropertyStore<ZNRecord> _propertyStore;
+  private final String _controllerInstanceId;
+  private final ControllerMetrics _controllerMetrics;
+
+  public DistributedTaskLockManager(ZkHelixPropertyStore<ZNRecord> 
propertyStore, String controllerInstanceId) {
+    _propertyStore = propertyStore;
+    _controllerInstanceId = controllerInstanceId;
+    _controllerMetrics = ControllerMetrics.get();
+  }
+
+  /**
+   * Attempts to acquire a distributed lock at the table level for task 
generation using session-based locking.
+   * The lock is at the table level instead of the task level to ensure that 
only a single task can be generated for
+   * a given table at any time. Certain tasks depend on other tasks not being 
generated at the same time
+   * The lock is held until explicitly released or the controller session ends.
+   *
+   * @param tableNameWithType the table name with type
+   * @return TaskLock object if successful, null if lock could not be acquired
+   */
+  @Nullable
+  public TaskLock acquireLock(String tableNameWithType) {
+    LOGGER.info("Attempting to acquire task generation lock for table: {} by 
controller: {}", tableNameWithType,
+        _controllerInstanceId);
+
+    try {
+      // Check if task generation is already in progress
+      if (isTaskGenerationInProgress(tableNameWithType)) {
+        LOGGER.info("Task generation already in progress for: {} by this or 
another controller", tableNameWithType);
+        return null;
+      }
+
+      // Try to acquire the lock using ephemeral node
+      TaskLock lock = tryAcquireSessionBasedLock(tableNameWithType);
+      if (lock != null) {
+        LOGGER.info("Successfully acquired task generation lock for table: {} 
by controller: {}", tableNameWithType,
+            _controllerInstanceId);
+        return lock;
+      } else {
+        LOGGER.warn("Could not acquire lock for table: {} - another controller 
must hold it", tableNameWithType);
+      }
+    } catch (Exception e) {
+      LOGGER.error("Error while trying to acquire task lock for table: {}", 
tableNameWithType, e);
+    }
+    return null;
+  }
+
+  private String getLockPath(String tableNameForPath) {
+    return 
ZKMetadataProvider.constructPropertyStorePathForMinionTaskGenerationLock(tableNameForPath);
+  }
+
+  /**
+   * Releases a previously acquired session-based lock and marks task 
generation as completed.
+   *
+   * @param lock the lock to release
+   * @return true if successfully released, false otherwise
+   */
+  public boolean releaseLock(TaskLock lock) {
+    if (lock == null) {
+      return true;
+    }
+
+    String tableNameWithType = lock.getTableNameWithType();
+    String lockNode = lock.getLockZNodePath();
+
+    // Remove the ephemeral lock node
+    boolean status = true;
+    if (lockNode != null) {
+      try {
+        if (_propertyStore.exists(lockNode, AccessOption.EPHEMERAL)) {
+          status = _propertyStore.remove(lockNode, AccessOption.EPHEMERAL);

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to