somandal commented on code in PR #16857: URL: https://github.com/apache/pinot/pull/16857#discussion_r2369970466
########## pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/minion/DistributedTaskLockManager.java: ########## @@ -0,0 +1,563 @@ +/** + * 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.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +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.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Manages distributed locks for minion task generation using ZooKeeper ephemeral sequential nodes. + * Uses ephemeral nodes that automatically disappear when the controller session ends. + * This approach provides automatic cleanup and is suitable for long-running task generation. + * Locks are held until explicitly released or the controller session terminates. + * Locks are at the table level, to ensure that only one type of task can be generated per table at any given time. + */ +public class DistributedTaskLockManager { + private static final Logger LOGGER = LoggerFactory.getLogger(DistributedTaskLockManager.class); + + // Lock and state paths are constructed using ZKMetadataProvider + private static final String LOCK_SUFFIX = "-Lock"; + private static final String STATE_SUFFIX = "-State"; + private static final String LOCK_OWNER_KEY = "lockOwner"; + private static final String LOCK_PATH_KEY = "lockPath"; + private static final String LOCK_UUID_KEY = "lockUuid"; + private static final String LOCK_TIMESTAMP_MILLIS_KEY = "lockTimestampMillis"; + private static final String TASK_GENERATION_STATUS_KEY = "status"; + private static final String TASK_GENERATION_START_TIME_MILLIS_KEY = "startTimeMillis"; + private static final String TASK_GENERATION_COMPLETION_TIME_MILLIS_KEY = "completionTimeMillis"; + private static final long STALE_THRESHOLD_MILLIS = 24 * 60 * 60 * 1000L; // 24 hours; + + // Task generation states + private enum Status { + // IN_PROGRESS if the task generation is currently in progress; + // COMPLETED if the task generation completed successfully; + // FAILED if the task generation failed. + IN_PROGRESS, COMPLETED, FAILED + } + + // Define a custom comparator to compare strings of format '<controllerName>-lock-<sequenceNumber>' and sort them by + // the sequence number at the end + private static final Comparator<String> TASK_LOCK_SEQUENCE_ID_COMPARATOR = (s1, s2) -> { + // Regex to find the trailing sequence of digits + Pattern p = Pattern.compile("\\d+$"); + + // Extract the number from the first string + Matcher m1 = p.matcher(s1); + long num1 = m1.find() ? Long.parseLong(m1.group()) : 0; + + // Extract the number from the second string + Matcher m2 = p.matcher(s2); + long num2 = m2.find() ? Long.parseLong(m2.group()) : 0; + + return Long.compare(num1, num2); + }; + + private final ZkHelixPropertyStore<ZNRecord> _propertyStore; + private final String _controllerInstanceId; + + public DistributedTaskLockManager(ZkHelixPropertyStore<ZNRecord> propertyStore, String controllerInstanceId) { + _propertyStore = propertyStore; + _controllerInstanceId = controllerInstanceId; + + // Ensure base paths exist + ensureBasePaths(); + } + + /** + * Attempts to acquire a distributed lock for task generation using session-based locking. + * The lock is held until explicitly released or the controller session ends. + * The lock is created at the table level + * + * @param tableName the table name (can be null for all-table operations) + * @return TaskLock object if successful, null if lock could not be acquired + */ + @Nullable + public TaskLock acquireLock(@Nullable String tableName) { + String tableNameForPath = (tableName != null) ? tableName : "ALL_TABLES"; + String lockBasePath = getLockBasePath(tableNameForPath); + String statePath = lockBasePath.replace(LOCK_SUFFIX, STATE_SUFFIX); + + LOGGER.info("Attempting to acquire task generation lock: {} by controller: {}", tableNameForPath, + _controllerInstanceId); + + try { + // Check if task generation is already in progress + if (isTaskGenerationInProgress(tableNameForPath, lockBasePath, statePath)) { + LOGGER.info("Task generation already in progress for: {} by this or another controller", tableNameForPath); + return null; + } + + // Try to acquire the lock using ephemeral sequential node + TaskLock lock = tryAcquireSessionBasedLock(lockBasePath, statePath, tableNameForPath); + if (lock != null) { + LOGGER.info("Successfully acquired task generation lock: {} by controller: {}", tableNameForPath, + _controllerInstanceId); + return lock; + } else { + LOGGER.warn("Could not acquire lock: {} - another controller holds it", tableNameForPath); + return null; + } + } catch (Exception e) { + LOGGER.error("Error while trying to acquire lock: {}", tableNameForPath, e); + return null; + } + } + + private String getLockBasePath(String tableNameForPath) { + return ZKMetadataProvider.constructPropertyStorePathForMinionTaskGenerationLock(tableNameForPath); + } + + private String getBasePath() { + return ZKMetadataProvider.getPropertyStorePathForMinionTaskMetadataPrefix(); + } + + /** + * Releases a lock assuming successful completion. + */ + public boolean releaseLock(TaskLock lock) { + return releaseLock(lock, true); + } + + /** + * Releases a previously acquired session-based lock and marks task generation as completed. + * + * @param lock the lock to release + * @param success whether task generation completed successfully + * @return true if successfully released, false otherwise + */ + public boolean releaseLock(TaskLock lock, boolean success) { + if (lock == null) { + return true; + } + + String lockKey = lock.getLockKey(); + + try { + // Mark task generation as completed/failed + markTaskGenerationCompleted(lock.getStatePath(), lockKey, success); + + // Remove the ephemeral lock node + if (lock.getLockNodePath() != null) { + try { + boolean status = _propertyStore.remove(lock.getLockNodePath(), AccessOption.EPHEMERAL); + LOGGER.info("Removed ephemeral lock node: {}, removal success: {}", lock.getLockNodePath(), status); + } catch (Exception e) { + // Lock node might have already been removed due to session timeout - this is OK + LOGGER.warn("Ephemeral lock node already removed or session expired: {}", lock.getLockNodePath(), e); + } + } + + LOGGER.info("Successfully released task generation lock: {} by controller: {} (success: {})", lockKey, + _controllerInstanceId, success); + return true; + } catch (Exception e) { + LOGGER.error("Error while releasing lock: {}", lockKey, e); + return false; + } + } + + /** + * Force release the lock without checking if any tasks are in progress + */ + public boolean forceReleaseLock(String tableNameWithType) { + LOGGER.info("Trying to force release the lock for table: {}", tableNameWithType); + String lockBasePath = getLockBasePath(tableNameWithType); + + boolean released = true; + if (_propertyStore.exists(lockBasePath, AccessOption.PERSISTENT)) { + List<String> lockNodes = _propertyStore.getChildNames(lockBasePath, AccessOption.PERSISTENT); + if (lockNodes != null && !lockNodes.isEmpty()) { + // There are active ephemeral lock nodes, check if any are still valid and delete them + for (String nodeName : lockNodes) { + String nodePath = lockBasePath + "/" + nodeName; + if (_propertyStore.exists(nodePath, AccessOption.EPHEMERAL)) { + LOGGER.info("Lock for table: {} found at path: {}, trying to remove", tableNameWithType, nodePath); + boolean result = _propertyStore.remove(nodePath, AccessOption.EPHEMERAL); + if (!result) { + LOGGER.warn("Could not force release lock: {}", nodePath); + released = false; + } + } + } + } else { + LOGGER.info("No locks to force release, no child lock ZNodes found for table: {} under base: {}", + tableNameWithType, lockBasePath); + } + } else { + LOGGER.info("No locks to force release, no base lock ZNode: {} found for table: {}", lockBasePath, + tableNameWithType); + } + return released; + } + + /** + * Checks if task generation is currently in progress for the given task type and table. + * + * @param tableName the table name + * @return true if task generation is in progress, false otherwise + */ + @VisibleForTesting + boolean isTaskGenerationInProgress(@Nullable String tableName) { + String tableNameForPath = (tableName != null) ? tableName : "ALL_TABLES"; + String lockBasePath = getLockBasePath(tableNameForPath); + String statePath = lockBasePath.replace(LOCK_SUFFIX, STATE_SUFFIX); + return isTaskGenerationInProgress(tableNameForPath, lockBasePath, statePath); + } + + /** + * Internal method to check if task generation is in progress for a lock key. + */ + private boolean isTaskGenerationInProgress(String lockKey, String lockBasePath, String statePath) { + try { + // Check if there are any active ephemeral lock nodes + if (_propertyStore.exists(lockBasePath, AccessOption.PERSISTENT)) { + List<String> lockNodes = _propertyStore.getChildNames(lockBasePath, AccessOption.PERSISTENT); + if (lockNodes != null && !lockNodes.isEmpty()) { + // There are active ephemeral lock nodes, check if any are still valid + boolean anyEphemeralLockExists = false; + for (String nodeName : lockNodes) { + String nodePath = lockBasePath + "/" + nodeName; + if (_propertyStore.exists(nodePath, AccessOption.EPHEMERAL)) { + anyEphemeralLockExists = true; + // Ephemeral node exists, meaning session is still alive and task could be in progress (we update the + // state to COMPLETED / FAILED before removing the lock, so better to double-check the task generation + // state if the lock exists) + ZNRecord stateRecord = _propertyStore.get(statePath, null, AccessOption.PERSISTENT); + if (stateRecord != null) { + String status = stateRecord.getSimpleField(TASK_GENERATION_STATUS_KEY); + String lockPath = stateRecord.getSimpleField(LOCK_PATH_KEY); + if (lockPath != null && lockPath.equals(nodePath)) { + return Status.IN_PROGRESS.name().equals(status); Review Comment: removed this "-State" ZNode, hopefully this helps simplify the logic -- 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]
