yihua commented on code in PR #13103: URL: https://github.com/apache/hudi/pull/13103#discussion_r2038863660
########## hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/StorageBasedLockConfig.java: ########## @@ -0,0 +1,100 @@ +/* + * 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.hudi.config; + +import org.apache.hudi.common.config.ConfigProperty; +import org.apache.hudi.common.config.HoodieConfig; +import org.apache.hudi.common.config.LockConfiguration; +import org.apache.hudi.common.config.TypedProperties; + +import java.util.concurrent.TimeUnit; + +import static org.apache.hudi.common.config.HoodieCommonConfig.BASE_PATH; + +public class StorageBasedLockConfig extends HoodieConfig { + private static final String SINCE_VERSION_1_0_2 = "1.0.2"; + private static final String STORAGE_BASED_LOCK_PROPERTY_PREFIX = LockConfiguration.LOCK_PREFIX + + "storage."; + + public static final ConfigProperty<Long> VALIDITY_TIMEOUT_SECONDS = ConfigProperty + .key(STORAGE_BASED_LOCK_PROPERTY_PREFIX + "validity.timeout.secs") + .defaultValue(TimeUnit.MINUTES.toSeconds(5)) + .markAdvanced() + .sinceVersion(SINCE_VERSION_1_0_2) + .withDocumentation( + "For storage-based lock provider, the amount of time in seconds each new lock is valid for. " + + "The lock provider will attempt to renew its lock until it successfully extends the lock lease period " + + "or the validity timeout is reached."); + + public static final ConfigProperty<Long> HEARTBEAT_POLL_SECONDS = ConfigProperty + .key(STORAGE_BASED_LOCK_PROPERTY_PREFIX + "heartbeat.poll.secs") + .defaultValue(TimeUnit.SECONDS.toSeconds(30)) + .markAdvanced() + .sinceVersion(SINCE_VERSION_1_0_2) + .withDocumentation( + "For storage-based conditional write lock provider, the amount of time in seconds to wait before renewing the lock." Review Comment: ```suggestion "For storage-based lock provider, the amount of time in seconds to wait before renewing the lock. " ``` ########## hudi-client/hudi-client-common/src/main/java/org/apache/hudi/config/StorageBasedLockConfig.java: ########## @@ -0,0 +1,100 @@ +/* + * 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.hudi.config; + +import org.apache.hudi.common.config.ConfigProperty; +import org.apache.hudi.common.config.HoodieConfig; +import org.apache.hudi.common.config.LockConfiguration; +import org.apache.hudi.common.config.TypedProperties; + +import java.util.concurrent.TimeUnit; + +import static org.apache.hudi.common.config.HoodieCommonConfig.BASE_PATH; + +public class StorageBasedLockConfig extends HoodieConfig { + private static final String SINCE_VERSION_1_0_2 = "1.0.2"; + private static final String STORAGE_BASED_LOCK_PROPERTY_PREFIX = LockConfiguration.LOCK_PREFIX + + "storage."; + + public static final ConfigProperty<Long> VALIDITY_TIMEOUT_SECONDS = ConfigProperty + .key(STORAGE_BASED_LOCK_PROPERTY_PREFIX + "validity.timeout.secs") + .defaultValue(TimeUnit.MINUTES.toSeconds(5)) + .markAdvanced() + .sinceVersion(SINCE_VERSION_1_0_2) + .withDocumentation( + "For storage-based lock provider, the amount of time in seconds each new lock is valid for. " + + "The lock provider will attempt to renew its lock until it successfully extends the lock lease period " + + "or the validity timeout is reached."); + + public static final ConfigProperty<Long> HEARTBEAT_POLL_SECONDS = ConfigProperty + .key(STORAGE_BASED_LOCK_PROPERTY_PREFIX + "heartbeat.poll.secs") + .defaultValue(TimeUnit.SECONDS.toSeconds(30)) Review Comment: ```suggestion .defaultValue(30L) ``` ########## hudi-client/hudi-client-common/src/main/java/org/apache/hudi/client/transaction/lock/ConditionalWriteLockProvider.java: ########## @@ -0,0 +1,581 @@ +/* + * 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.hudi.client.transaction.lock; + +import org.apache.hudi.client.transaction.lock.models.StorageLockData; +import org.apache.hudi.client.transaction.lock.models.StorageLockFile; +import org.apache.hudi.client.transaction.lock.models.HeartbeatManager; +import org.apache.hudi.client.transaction.lock.models.LockGetResult; +import org.apache.hudi.client.transaction.lock.models.LockProviderHeartbeatManager; +import org.apache.hudi.client.transaction.lock.models.LockUpdateResult; +import org.apache.hudi.common.config.LockConfiguration; +import org.apache.hudi.common.lock.LockProvider; +import org.apache.hudi.common.lock.LockState; +import org.apache.hudi.common.util.CollectionUtils; +import org.apache.hudi.common.util.ReflectionUtils; +import org.apache.hudi.common.util.StringUtils; +import org.apache.hudi.common.util.VisibleForTesting; +import org.apache.hudi.common.util.collection.Pair; +import org.apache.hudi.common.util.hash.HashID; +import org.apache.hudi.exception.HoodieLockException; +import org.apache.hudi.exception.HoodieNotSupportedException; +import org.apache.hudi.storage.StorageConfiguration; +import org.apache.hudi.storage.StoragePath; +import org.apache.hudi.storage.StorageSchemes; + +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.concurrent.GuardedBy; +import javax.annotation.concurrent.ThreadSafe; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.apache.hudi.common.lock.LockState.ACQUIRED; +import static org.apache.hudi.common.lock.LockState.ACQUIRING; +import static org.apache.hudi.common.lock.LockState.FAILED_TO_ACQUIRE; +import static org.apache.hudi.common.lock.LockState.FAILED_TO_RELEASE; +import static org.apache.hudi.common.lock.LockState.RELEASED; +import static org.apache.hudi.common.lock.LockState.RELEASING; +import static org.apache.hudi.common.table.HoodieTableMetaClient.LOCKS_FOLDER_NAME; + +@ThreadSafe +public class ConditionalWriteLockProvider implements LockProvider<StorageLockFile> { + + public static final String DEFAULT_TABLE_LOCK_FILE_NAME = "table_lock"; + // How long to wait before retrying lock acquisition in blocking calls. + private static final long DEFAULT_LOCK_ACQUISITION_BUFFER = 1000; + // Maximum expected clock drift between two nodes. + // This is similar idea as SkewAdjustingTimeGenerator. + // In reality, within a single cloud provider all nodes share the same ntp + // server + // therefore we do not expect drift more than a few ms. + // However, since our lock leases are pretty long, we can use a high buffer. + private static final long CLOCK_DRIFT_BUFFER_MS = 500; + + // When we retry lock upserts, do so 5 times + private static final long LOCK_UPSERT_RETRY_COUNT = 5; + + private static final String GCS_LOCK_SERVICE_CLASS_NAME = "org.apache.hudi.gcp.transaction.lock.GCSStorageLock"; + private static final String S3_LOCK_SERVICE_CLASS_NAME = "org.apache.hudi.aws.transaction.lock.S3StorageLock"; + + // The static logger to be shared across contexts + private static final Logger DEFAULT_LOGGER = LoggerFactory.getLogger(ConditionalWriteLockProvider.class); + private static final String LOCK_STATE_LOGGER_MSG = "Owner {}: Lock file path {}, Thread {}, Conditional Write lock state {}"; + private static final String LOCK_STATE_LOGGER_MSG_WITH_INFO = "Owner {}: Lock file path {}, Thread {}, Conditional Write lock state {}, {}"; + + private static final Map<String, String> SUPPORTED_LOCK_SERVICE_IMPLEMENTATIONS = CollectionUtils.createImmutableMap( + Pair.of(StorageSchemes.GCS.getScheme(), GCS_LOCK_SERVICE_CLASS_NAME), + Pair.of(StorageSchemes.S3A.getScheme(), S3_LOCK_SERVICE_CLASS_NAME), + Pair.of(StorageSchemes.S3.getScheme(), S3_LOCK_SERVICE_CLASS_NAME)); + + @VisibleForTesting + Logger logger; + + // The lock service implementation which interacts with cloud storage. + private final StorageLock lockService; + + // Local variables + private final long heartbeatIntervalMs; + private final long lockValidityMs; + private final String ownerId; + private final String lockFilePath; + private final String bucketName; + private final HeartbeatManager heartbeatManager; + + // Provide a place to store the "current lock object". + @GuardedBy("this") + private StorageLockFile currentLockObj = null; + // Ensures we do not try to lock after being closed. + @GuardedBy("this") + private boolean isClosed = false; + + private synchronized void setLock(StorageLockFile lockObj) { + if (lockObj != null && !Objects.equals(lockObj.getOwner(), this.ownerId)) { + throw new HoodieLockException("Owners do not match! Current LP owner: " + this.ownerId + " lock path: " + + this.lockFilePath + " owner: " + lockObj.getOwner()); + } + this.currentLockObj = lockObj; + } + + /** + * Default constructor for ConditionalWriteLockProvider, required by LockManager + * to instantiate it using reflection. + * + * @param lockConfiguration The lock configuration, should be transformable into + * ConditionalWriteLockConfig + * @param conf Storage config, ignored. + */ + public ConditionalWriteLockProvider(final LockConfiguration lockConfiguration, final StorageConfiguration<?> conf) { + ConditionalWriteLockConfig config = new ConditionalWriteLockConfig.Builder() + .fromProperties(lockConfiguration.getConfig()).build(); + heartbeatIntervalMs = config.getHeartbeatPollMs(); + lockValidityMs = config.getLockValidityTimeoutMs(); + + // Determine if the provided locks location is relative. + String configuredLocksLocation = config.getLocksLocation(); + + // If using base path, recalculate the locks location as .hoodie/.locks + String locksLocation = StringUtils.isNullOrEmpty(configuredLocksLocation) + ? String.format("%s%s%s", config.getHudiTableBasePath(), StoragePath.SEPARATOR, LOCKS_FOLDER_NAME) + : configuredLocksLocation; + + URI uri = parseURI(locksLocation); + bucketName = uri.getHost(); // For most schemes, the bucket/container is the host. + String folderName = uri.getPath(); // Path after the bucket/container. + + String fileName = StringUtils.isNullOrEmpty(configuredLocksLocation) + ? DEFAULT_TABLE_LOCK_FILE_NAME + : slugifyLockFolderFromBasePath(config.getHudiTableBasePath()); + + lockFilePath = buildLockObjectPath(folderName, fileName); + ownerId = UUID.randomUUID().toString(); + this.logger = DEFAULT_LOGGER; + this.heartbeatManager = new LockProviderHeartbeatManager( + ownerId, + heartbeatIntervalMs, + this::renewLock); + + try { + this.lockService = (StorageLock) ReflectionUtils.loadClass( + getLockServiceClassName(uri.getScheme()), + new Class<?>[] { String.class, String.class, String.class, Properties.class }, + new Object[] { ownerId, bucketName, lockFilePath, lockConfiguration.getConfig() }); + } catch (Throwable e) { + throw new HoodieLockException("Failed to load and initialize StorageLock", e); + } + + logger.info("Instantiated new Conditional Write LP, owner: {}, lockfilePath: {}", ownerId, lockFilePath); + } + + private URI parseURI(String location) { + try { + return new URI(location); + } catch (URISyntaxException e) { + throw new HoodieLockException("Unable to parse locks location as a URI: " + location, e); + } + } + + private static @NotNull String getLockServiceClassName(String scheme) { + if (SUPPORTED_LOCK_SERVICE_IMPLEMENTATIONS.containsKey(scheme) + && StorageSchemes.isConditionalWriteSupported(scheme)) { + return SUPPORTED_LOCK_SERVICE_IMPLEMENTATIONS.get(scheme); Review Comment: Discussed offline that we use a String to store the class name. ########## hudi-client/hudi-client-common/src/test/java/org/apache/hudi/client/transaction/lock/TestStorageBasedLockProvider.java: ########## @@ -0,0 +1,624 @@ +/* + * 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.hudi.client.transaction.lock; + +import org.apache.hudi.client.transaction.lock.models.StorageLockData; +import org.apache.hudi.client.transaction.lock.models.StorageLockFile; +import org.apache.hudi.client.transaction.lock.models.HeartbeatManager; +import org.apache.hudi.client.transaction.lock.models.LockGetResult; +import org.apache.hudi.client.transaction.lock.models.LockUpdateResult; +import org.apache.hudi.common.config.LockConfiguration; +import org.apache.hudi.common.config.TypedProperties; +import org.apache.hudi.common.testutils.HoodieTestUtils; +import org.apache.hudi.common.util.collection.Pair; +import org.apache.hudi.config.StorageBasedLockConfig; +import org.apache.hudi.exception.HoodieLockException; +import org.apache.hudi.exception.HoodieNotSupportedException; +import org.apache.hudi.storage.StorageConfiguration; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.slf4j.Logger; + +import java.lang.reflect.Method; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import static org.apache.hudi.common.config.HoodieCommonConfig.BASE_PATH; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Unit test class for StorageBasedLockProvider + */ +class TestStorageBasedLockProvider { + private StorageBasedLockProvider lockProvider; + private StorageLock mockLockService; + private HeartbeatManager mockHeartbeatManager; + private Logger mockLogger; + private final String ownerId = UUID.randomUUID().toString(); + private static final int DEFAULT_LOCK_VALIDITY_MS = 5000; + + @BeforeEach + void setupLockProvider() { + mockLockService = mock(StorageLock.class); + mockHeartbeatManager = mock(HeartbeatManager.class); + mockLogger = mock(Logger.class); + when(mockHeartbeatManager.stopHeartbeat(true)).thenReturn(true); + TypedProperties props = new TypedProperties(); + props.put(StorageBasedLockConfig.VALIDITY_TIMEOUT_SECONDS.key(), "5"); + props.put(StorageBasedLockConfig.HEARTBEAT_POLL_SECONDS.key(), "1"); + props.put(BASE_PATH.key(), "gs://bucket/lake/db/tbl-default"); + + lockProvider = spy(new StorageBasedLockProvider( + ownerId, + props, + (a,b,c) -> mockHeartbeatManager, + (a,b,c) -> mockLockService, + mockLogger)); + } + + @AfterEach + void cleanupLockProvider() { + lockProvider.close(); + } + + @Test + void testUnsupportedLockStorageLocation() { + TypedProperties props = new TypedProperties(); + props.put(BASE_PATH.key(), "hdfs://bucket/lake/db/tbl-default"); + LockConfiguration lockConf = new LockConfiguration(props); + StorageConfiguration<?> storageConf = HoodieTestUtils.getDefaultStorageConf(); + HoodieLockException ex = assertThrows(HoodieLockException.class, + () -> new StorageBasedLockProvider(lockConf, storageConf)); + assertTrue(ex.getCause().getMessage().contains("No implementation of StorageLock supports this scheme")); + } + + @Test + void testValidLockStorageLocation() { + TypedProperties props = new TypedProperties(); + props.put(BASE_PATH.key(), "s3://bucket/lake/db/tbl-default"); + + LockConfiguration lockConf = new LockConfiguration(props); + StorageConfiguration<?> storageConf = HoodieTestUtils.getDefaultStorageConf(); + + HoodieLockException ex = assertThrows(HoodieLockException.class, + () -> new StorageBasedLockProvider(lockConf, storageConf)); + assertTrue(ex.getMessage().contains("Failed to load and initialize StorageLock")); + } + + @ParameterizedTest + @ValueSource(strings = { "gs://bucket/lake/db/tbl-default", "s3://bucket/lake/db/tbl-default", + "s3a://bucket/lake/db/tbl-default" }) + void testNonExistentWriteServiceWithDefaults(String tableBasePathString) { + TypedProperties props = new TypedProperties(); + props.put(BASE_PATH.key(), tableBasePathString); + + LockConfiguration lockConf = new LockConfiguration(props); + StorageConfiguration<?> storageConf = HoodieTestUtils.getDefaultStorageConf(); + + HoodieLockException ex = assertThrows(HoodieLockException.class, + () -> new StorageBasedLockProvider(lockConf, storageConf)); + assertTrue(ex.getMessage().contains("Failed to load and initialize StorageLock")); + } + + @Test + void testInvalidLocksLocationForWriteService() { + TypedProperties props = new TypedProperties(); + props.put(BASE_PATH.key(), "gs://bucket/lake/db/tbl-default"); + props.put(StorageBasedLockConfig.VALIDITY_TIMEOUT_SECONDS.key(), "5"); + props.put(StorageBasedLockConfig.HEARTBEAT_POLL_SECONDS.key(), "1"); + + LockConfiguration lockConf = new LockConfiguration(props); + StorageConfiguration<?> storageConf = HoodieTestUtils.getDefaultStorageConf(); + + HoodieLockException ex = assertThrows(HoodieLockException.class, + () -> new StorageBasedLockProvider(lockConf, storageConf)); + Throwable cause = ex.getCause(); + assertNotNull(cause); + assertInstanceOf(HoodieNotSupportedException.class, cause); + } + + @Test + void testTryLockForTimeUnitThrowsOnInterrupt() throws Exception { + doReturn(false).when(lockProvider).tryLock(); + CountDownLatch latch = new CountDownLatch(1); + Thread t = new Thread(() -> { + try { + lockProvider.tryLock(1, TimeUnit.SECONDS); + } catch (HoodieLockException e) { + latch.countDown(); + } + }); + t.start(); + Thread.sleep(50); + t.interrupt(); + assertTrue(latch.await(2, TimeUnit.SECONDS)); + } + + @Test + void testTryLockForTimeUnitAcquiresLockEventually() throws Exception { + AtomicInteger count = new AtomicInteger(0); + doAnswer(inv -> count.incrementAndGet() > 2).when(lockProvider).tryLock(); + CountDownLatch latch = new CountDownLatch(1); + Thread t = new Thread(() -> { + assertTrue(lockProvider.tryLock(4, TimeUnit.SECONDS)); + latch.countDown(); + }); + t.start(); + assertTrue(latch.await(5, TimeUnit.SECONDS)); + } + + @Test + void testTryLockForTimeUnitFailsToAcquireLockEventually() throws Exception { + AtomicInteger count = new AtomicInteger(0); + doAnswer(inv -> count.incrementAndGet() > 2).when(lockProvider).tryLock(); + CountDownLatch latch = new CountDownLatch(1); + Thread t = new Thread(() -> { + assertFalse(lockProvider.tryLock(1, TimeUnit.SECONDS)); + latch.countDown(); + }); + t.start(); + assertTrue(latch.await(2, TimeUnit.SECONDS)); + } + + @Test + void testTryLockSuccess() { + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.NOT_EXISTS, null)); + StorageLockData data = new StorageLockData(false, System.currentTimeMillis() + DEFAULT_LOCK_VALIDITY_MS, ownerId); + StorageLockFile realLockFile = new StorageLockFile(data, "v1"); + when(mockLockService.tryCreateOrUpdateLockFile(any(), isNull())) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, realLockFile)); + when(mockHeartbeatManager.startHeartbeatForThread(any())).thenReturn(true); + + boolean acquired = lockProvider.tryLock(); + assertTrue(acquired); + assertEquals(realLockFile, lockProvider.getLock()); + verify(mockLockService, atLeastOnce()).tryCreateOrUpdateLockFile(any(), any()); + } + + @Test + void testTryLockSuccessButFailureToStartHeartbeat() { + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.NOT_EXISTS, null)); + StorageLockData data = new StorageLockData(false, System.currentTimeMillis() + DEFAULT_LOCK_VALIDITY_MS, ownerId); + StorageLockFile realLockFile = new StorageLockFile(data, "v1"); + when(mockLockService.tryCreateOrUpdateLockFile(any(), isNull())) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, realLockFile)); + when(mockHeartbeatManager.startHeartbeatForThread(any())).thenReturn(false); + when(mockLockService.tryCreateOrUpdateLockFileWithRetry(any(), eq(realLockFile), anyLong())) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, realLockFile)); + + boolean acquired = lockProvider.tryLock(); + assertFalse(acquired); + } + + @Test + void testTryLockFailsFromOwnerMismatch() { + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.NOT_EXISTS, null)); + StorageLockFile returnedLockFile = new StorageLockFile( + new StorageLockData(false, System.currentTimeMillis() + DEFAULT_LOCK_VALIDITY_MS, "different-owner"), "v1"); + when(mockLockService.tryCreateOrUpdateLockFile(any(), isNull())) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, returnedLockFile)); + + HoodieLockException ex = assertThrows(HoodieLockException.class, () -> lockProvider.tryLock()); + assertTrue(ex.getMessage().contains("Owners do not match")); + } + + @Test + void testTryLockFailsDueToExistingLock() { + StorageLockData data = new StorageLockData(false, System.currentTimeMillis() + DEFAULT_LOCK_VALIDITY_MS, + "other-owner"); + StorageLockFile existingLock = new StorageLockFile(data, "v2"); + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.SUCCESS, existingLock)); + + boolean acquired = lockProvider.tryLock(); + assertFalse(acquired); + } + + @Test + void testTryLockFailsToUpdateFile() { + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.NOT_EXISTS, null)); + when(mockLockService.tryCreateOrUpdateLockFile(any(), isNull())) + .thenReturn(Pair.of(LockUpdateResult.ACQUIRED_BY_OTHERS, null)); + assertFalse(lockProvider.tryLock()); + } + + @Test + void testTryLockFailsDueToUnknownState() { + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.UNKNOWN_ERROR, null)); + assertFalse(lockProvider.tryLock()); + } + + @Test + void testTryLockSucceedsWhenExistingLockExpiredByTime() { + StorageLockData data = new StorageLockData(false, System.currentTimeMillis() - DEFAULT_LOCK_VALIDITY_MS, + "other-owner"); + StorageLockFile existingLock = new StorageLockFile(data, "v2"); + StorageLockData newData = new StorageLockData(false, System.currentTimeMillis() + DEFAULT_LOCK_VALIDITY_MS, + ownerId); + StorageLockFile realLockFile = new StorageLockFile(newData, "v1"); + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.SUCCESS, existingLock)); + when(mockLockService.tryCreateOrUpdateLockFile(any(), eq(existingLock))) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, realLockFile)); + when(mockHeartbeatManager.startHeartbeatForThread(any())).thenReturn(true); + boolean acquired = lockProvider.tryLock(); + assertTrue(acquired); + } + + @Test + void testTryLockReentrancySucceeds() { + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.NOT_EXISTS, null)); + StorageLockData data = new StorageLockData(false, System.currentTimeMillis() + DEFAULT_LOCK_VALIDITY_MS, ownerId); + StorageLockFile realLockFile = new StorageLockFile(data, "v1"); + when(mockLockService.tryCreateOrUpdateLockFile(any(), isNull())) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, realLockFile)); + when(mockHeartbeatManager.startHeartbeatForThread(any())).thenReturn(true); + + boolean acquired = lockProvider.tryLock(); + assertTrue(acquired); + // Re-entrancy succeeds + assertTrue(lockProvider.tryLock()); + } + + @Test + void testTryLockReentrancyAfterLockExpiredByTime() { + // In an extremely unlikely scenario, we could have a local reference to a lock + // which is present but expired, + // and because we were unable to stop the heartbeat properly, we did not + // successfully set it to null. + // Due to the nature of the heartbeat manager, this is expected to introduce + // some delay, but not be permanently blocking. + // There are a few variations of this edge case, so we must test them all. + + // Here the lock is still "unexpired" but the time shows expired. + StorageLockData data = new StorageLockData(false, System.currentTimeMillis() - DEFAULT_LOCK_VALIDITY_MS, ownerId); + StorageLockFile expiredLock = new StorageLockFile(data, "v1"); + doReturn(expiredLock).when(lockProvider).getLock(); + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.NOT_EXISTS, null)); + StorageLockData validData = new StorageLockData(false, System.currentTimeMillis() - DEFAULT_LOCK_VALIDITY_MS, + ownerId); + StorageLockFile validLock = new StorageLockFile(validData, "v2"); + when(mockLockService.tryCreateOrUpdateLockFile(any(), isNull())) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, validLock)); + when(mockHeartbeatManager.startHeartbeatForThread(any())).thenReturn(true); + + assertTrue(lockProvider.tryLock()); + } + + @Test + void testTryLockReentrancyAfterLockSetExpired() { + // In an extremely unlikely scenario, we could have a local reference to a lock + // which is present but expired, + // and because we were unable to stop the heartbeat properly, we did not + // successfully set it to null. + // Due to the nature of the heartbeat manager, this is expected to introduce + // some delay, but not be permanently blocking. + // There are a few variations of this edge case, so we must test them all. + + // Here the lock is "expired" but the time shows unexpired. + StorageLockData data = new StorageLockData(true, System.currentTimeMillis() + DEFAULT_LOCK_VALIDITY_MS, ownerId); + StorageLockFile expiredLock = new StorageLockFile(data, "v1"); + doReturn(expiredLock).when(lockProvider).getLock(); + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.NOT_EXISTS, null)); + StorageLockData validData = new StorageLockData(false, System.currentTimeMillis() - DEFAULT_LOCK_VALIDITY_MS, + ownerId); + StorageLockFile validLock = new StorageLockFile(validData, "v2"); + when(mockLockService.tryCreateOrUpdateLockFile(any(), isNull())) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, validLock)); + when(mockHeartbeatManager.startHeartbeatForThread(any())).thenReturn(true); + + assertTrue(lockProvider.tryLock()); + } + + @Test + void testTryLockHeartbeatStillActive() { + // In an extremely unlikely scenario, we could have a local reference to a lock + // which is present but expired, + // and because we were unable to stop the heartbeat properly, we did not + // successfully set it to null. + // Due to the nature of the heartbeat manager, this is expected to introduce + // some delay, but not be permanently blocking. + // There are a few variations of this edge case, so we must test them all. + + // Here the heartbeat is still active, so we have to error out. + StorageLockData data = new StorageLockData(true, System.currentTimeMillis() + DEFAULT_LOCK_VALIDITY_MS, ownerId); + StorageLockFile expiredLock = new StorageLockFile(data, "v1"); + doReturn(expiredLock).when(lockProvider).getLock(); + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.NOT_EXISTS, null)); + when(mockHeartbeatManager.hasActiveHeartbeat()).thenReturn(true); + assertThrows(HoodieLockException.class, () -> lockProvider.tryLock()); + } + + @Test + void testUnlockSucceedsAndReentrancy() { + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.NOT_EXISTS, null)); + StorageLockData data = new StorageLockData(false, System.currentTimeMillis() + DEFAULT_LOCK_VALIDITY_MS, ownerId); + StorageLockFile realLockFile = new StorageLockFile(data, "v1"); + when(mockLockService.tryCreateOrUpdateLockFile(any(), isNull())) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, realLockFile)); + when(mockHeartbeatManager.startHeartbeatForThread(any())).thenReturn(true); + when(mockHeartbeatManager.stopHeartbeat(true)).thenReturn(true); + when(mockHeartbeatManager.hasActiveHeartbeat()).thenReturn(false); + when(mockLockService.tryCreateOrUpdateLockFileWithRetry(any(), eq(realLockFile), anyLong())) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, + new StorageLockFile(new StorageLockData(true, data.getValidUntil(), ownerId), "v2"))); + assertTrue(lockProvider.tryLock()); + when(mockHeartbeatManager.hasActiveHeartbeat()) + .thenReturn(true) // when we try to stop the heartbeat we will check if heartbeat is active return true. + .thenReturn(false); // when try to set lock to expire we will assert no active heartbeat as a precondition. + lockProvider.unlock(); + assertNull(lockProvider.getLock()); + lockProvider.unlock(); + } + + @Test + void testUnlockFailsToStopHeartbeat() { + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.NOT_EXISTS, null)); + StorageLockData data = new StorageLockData(false, System.currentTimeMillis() + DEFAULT_LOCK_VALIDITY_MS, ownerId); + StorageLockFile realLockFile = new StorageLockFile(data, "v1"); + when(mockLockService.tryCreateOrUpdateLockFile(any(), isNull())) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, realLockFile)); + when(mockHeartbeatManager.startHeartbeatForThread(any())).thenReturn(true); + assertTrue(lockProvider.tryLock()); + when(mockHeartbeatManager.stopHeartbeat(true)).thenReturn(false); + when(mockHeartbeatManager.hasActiveHeartbeat()).thenReturn(true); + assertThrows(HoodieLockException.class, () -> lockProvider.unlock()); + when(mockHeartbeatManager.hasActiveHeartbeat()).thenReturn(false); + } + + @Test + void testCloseFailsToStopHeartbeat() { + when(mockLockService.readCurrentLockFile()).thenReturn(Pair.of(LockGetResult.NOT_EXISTS, null)); + StorageLockData data = new StorageLockData(false, System.currentTimeMillis() + DEFAULT_LOCK_VALIDITY_MS, ownerId); + StorageLockFile realLockFile = new StorageLockFile(data, "v1"); + when(mockLockService.tryCreateOrUpdateLockFile(any(), isNull())) + .thenReturn(Pair.of(LockUpdateResult.SUCCESS, realLockFile)); + when(mockHeartbeatManager.startHeartbeatForThread(any())).thenReturn(true); + assertTrue(lockProvider.tryLock()); + when(mockHeartbeatManager.stopHeartbeat(true)).thenReturn(false); + when(mockHeartbeatManager.hasActiveHeartbeat()).thenReturn(true); + // Should wrap the exception and log error. + lockProvider.close(); + when(mockHeartbeatManager.hasActiveHeartbeat()).thenReturn(false); + } + + @Test + void testRenewLockReturnsFalseWhenNoLockHeld() { + doReturn(null).when(lockProvider).getLock(); + assertFalse(lockProvider.renewLock()); + when(mockHeartbeatManager.hasActiveHeartbeat()).thenReturn(true); + verify(mockLogger).warn("Owner {}: Cannot renew, no lock held by this process", this.ownerId); + } + + @Test + void testRenewLockWithoutHoldingLock() { + doReturn(null).when(lockProvider).getLock(); + assertFalse(lockProvider.renewLock()); + when(mockHeartbeatManager.hasActiveHeartbeat()).thenReturn(false); + verify(mockLogger).warn("Owner {}: Cannot renew, no lock held by this process", this.ownerId); + } + + @Test + void testRenewLockWithFullyExpiredLock() { + StorageLockData data = new StorageLockData(false, System.currentTimeMillis() - DEFAULT_LOCK_VALIDITY_MS, ownerId); + StorageLockFile nearExpiredLockFile = new StorageLockFile(data, "v1"); + doReturn(nearExpiredLockFile).when(lockProvider).getLock(); + when(mockLockService.tryCreateOrUpdateLockFileWithRetry(any(), eq(nearExpiredLockFile), anyLong())) + .thenReturn(Pair.of(LockUpdateResult.ACQUIRED_BY_OTHERS, null)); + assertFalse(lockProvider.renewLock()); + verify(mockLogger).error("Owner {}: Unable to renew lock as it is acquired by others.", this.ownerId); Review Comment: nit: checking logger is not the best way to validate the logic. If it's not easy to validate without this way, we should think about improving the interface in the future for testing. HUDI-9307 to track. -- 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]
