vinothchandar commented on code in PR #13126: URL: https://github.com/apache/hudi/pull/13126#discussion_r2038563396
########## hudi-aws/src/main/java/org/apache/hudi/aws/transaction/lock/S3StorageLockClient.java: ########## @@ -0,0 +1,248 @@ +/* + * 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.aws.transaction.lock; + +import org.apache.hudi.aws.credentials.HoodieAWSCredentialsProviderFactory; +import org.apache.hudi.client.transaction.lock.models.LockGetResult; +import org.apache.hudi.client.transaction.lock.models.LockUpdateResult; +import org.apache.hudi.client.transaction.lock.StorageLock; +import org.apache.hudi.client.transaction.lock.models.StorageLockData; +import org.apache.hudi.client.transaction.lock.models.StorageLockFile; +import org.apache.hudi.common.util.VisibleForTesting; +import org.apache.hudi.common.util.collection.Pair; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.core.ResponseInputStream; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import javax.annotation.concurrent.ThreadSafe; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Properties; +import java.util.function.Supplier; + +/** + * S3-based distributed lock service using ETag checks (AWS SDK v2). + * See RFC: <a href="https://github.com/apache/hudi/blob/master/rfc/rfc-91/rfc-91.md">RFC-91</a> + */ +@ThreadSafe +public class S3StorageLockClient implements StorageLock { + + private static final Logger LOG = LoggerFactory.getLogger(S3StorageLockClient.class); + private static final long WAIT_TIME_FOR_RETRY_MS = 1000L; + private static final int PRECONDITION_FAILURE_ERROR_CODE = 412; + private static final int NOT_FOUND_ERROR_CODE = 404; + private static final int CONDITIONAL_REQUEST_CONFLICT_ERROR_CODE = 409; + private static final int RATE_LIMIT_ERROR_CODE = 429; + private static final int INTERNAL_SERVER_ERROR_CODE_MIN = 500; + + private final Logger logger; + private final S3Client s3Client; + private final String bucketName; + private final String lockFilePath; + private final String ownerId; + + /** Constructor that is used by reflection to instantiate an S3-based storage locking client. + * @param ownerId The owner id. + * @param bucketName The name of the bucket. + * @param lockFilePath The path within the bucket where to write lock files. + * @param props The properties for the lock config, can be used to customize client. + */ + public S3StorageLockClient(String ownerId, String bucketName, String lockFilePath, Properties props) { + this( Review Comment: style ########## hudi-aws/src/main/java/org/apache/hudi/aws/transaction/lock/S3StorageLockClient.java: ########## @@ -0,0 +1,248 @@ +/* + * 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.aws.transaction.lock; + +import org.apache.hudi.aws.credentials.HoodieAWSCredentialsProviderFactory; +import org.apache.hudi.client.transaction.lock.models.LockGetResult; +import org.apache.hudi.client.transaction.lock.models.LockUpdateResult; +import org.apache.hudi.client.transaction.lock.StorageLock; +import org.apache.hudi.client.transaction.lock.models.StorageLockData; +import org.apache.hudi.client.transaction.lock.models.StorageLockFile; +import org.apache.hudi.common.util.VisibleForTesting; +import org.apache.hudi.common.util.collection.Pair; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.core.ResponseInputStream; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import javax.annotation.concurrent.ThreadSafe; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Properties; +import java.util.function.Supplier; + +/** + * S3-based distributed lock service using ETag checks (AWS SDK v2). + * See RFC: <a href="https://github.com/apache/hudi/blob/master/rfc/rfc-91/rfc-91.md">RFC-91</a> + */ +@ThreadSafe +public class S3StorageLockClient implements StorageLock { + + private static final Logger LOG = LoggerFactory.getLogger(S3StorageLockClient.class); + private static final long WAIT_TIME_FOR_RETRY_MS = 1000L; Review Comment: we have a bunch of these timeouts in `LockConfiguration` , I wonder if its better to wire/match one of those instead of hard coding ########## hudi-aws/src/main/java/org/apache/hudi/aws/transaction/lock/S3StorageLockClient.java: ########## @@ -0,0 +1,248 @@ +/* + * 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.aws.transaction.lock; + +import org.apache.hudi.aws.credentials.HoodieAWSCredentialsProviderFactory; +import org.apache.hudi.client.transaction.lock.models.LockGetResult; +import org.apache.hudi.client.transaction.lock.models.LockUpdateResult; +import org.apache.hudi.client.transaction.lock.StorageLock; +import org.apache.hudi.client.transaction.lock.models.StorageLockData; +import org.apache.hudi.client.transaction.lock.models.StorageLockFile; +import org.apache.hudi.common.util.VisibleForTesting; +import org.apache.hudi.common.util.collection.Pair; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.core.ResponseInputStream; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import javax.annotation.concurrent.ThreadSafe; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Properties; +import java.util.function.Supplier; + +/** + * S3-based distributed lock service using ETag checks (AWS SDK v2). + * See RFC: <a href="https://github.com/apache/hudi/blob/master/rfc/rfc-91/rfc-91.md">RFC-91</a> + */ +@ThreadSafe +public class S3StorageLockClient implements StorageLock { + + private static final Logger LOG = LoggerFactory.getLogger(S3StorageLockClient.class); + private static final long WAIT_TIME_FOR_RETRY_MS = 1000L; + private static final int PRECONDITION_FAILURE_ERROR_CODE = 412; + private static final int NOT_FOUND_ERROR_CODE = 404; + private static final int CONDITIONAL_REQUEST_CONFLICT_ERROR_CODE = 409; + private static final int RATE_LIMIT_ERROR_CODE = 429; + private static final int INTERNAL_SERVER_ERROR_CODE_MIN = 500; + + private final Logger logger; + private final S3Client s3Client; + private final String bucketName; + private final String lockFilePath; + private final String ownerId; + + /** Constructor that is used by reflection to instantiate an S3-based storage locking client. + * @param ownerId The owner id. + * @param bucketName The name of the bucket. + * @param lockFilePath The path within the bucket where to write lock files. + * @param props The properties for the lock config, can be used to customize client. + */ + public S3StorageLockClient(String ownerId, String bucketName, String lockFilePath, Properties props) { + this( + ownerId, + bucketName, + lockFilePath, + createDefaultS3Client(props), + LOG); + } + + @VisibleForTesting + S3StorageLockClient(String ownerId, + String bucketName, + String lockFilePath, + S3Client s3Client, + Logger logger) { + this.s3Client = s3Client; + this.lockFilePath = lockFilePath; + this.bucketName = bucketName; + this.ownerId = ownerId; + this.logger = logger; + } + + private static S3Client createDefaultS3Client(Properties props) { + Region region; + try { + region = DefaultAwsRegionProviderChain.builder().build().getRegion(); + } catch (SdkClientException e) { + // Fallback to us-east-1 if no region is found + region = Region.US_EAST_1; + } + return S3Client.builder().credentialsProvider(HoodieAWSCredentialsProviderFactory.getAwsCredentialsProvider(props)).region(region).build(); + } + + /** + * Internal helper to create or update the lock file with optional ETag precondition. + */ + private StorageLockFile createOrUpdateLockFileInternal(StorageLockData lockData, String expectedEtag) { + byte[] bytes = StorageLockFile.toByteArray(lockData); + PutObjectRequest.Builder putRequestBuilder = PutObjectRequest.builder() + .bucket(bucketName) + .key(lockFilePath); + + // ETag-based constraints: + // - If expectedEtag is not null: + // We assume that the file already exists on S3 with the ETag "expectedEtag". + // The update operation will include an ifMatch(expectedEtag) condition, meaning the update will only + // succeed if the current file's ETag exactly matches expectedEtag. + // If the actual ETag of the file on S3 differs from expectedEtag, the update attempt will fail. + // - If expectedEtag is null: + // We assume that the file does not currently exist on S3. + // The operation will use ifNoneMatch("*"), which instructs S3 to create the file only if it doesn't already exist. + // If a file with the same name is present (i.e., there is an existing ETag), the creation attempt will fail. + if (expectedEtag == null) { + putRequestBuilder.ifNoneMatch("*"); + } else { + putRequestBuilder.ifMatch(expectedEtag); + } + + PutObjectResponse response = s3Client.putObject(putRequestBuilder.build(), RequestBody.fromBytes(bytes)); + String newEtag = response.eTag(); + + return new StorageLockFile(lockData, newEtag); + } + + @Override + public Pair<LockUpdateResult, StorageLockFile> tryCreateOrUpdateLockFile( + StorageLockData newLockData, + StorageLockFile previousLockFile + ) { + String currentEtag = (previousLockFile != null) ? previousLockFile.getVersionId() : null; + try { + StorageLockFile updatedFile = createOrUpdateLockFileInternal(newLockData, currentEtag); + return Pair.of(LockUpdateResult.SUCCESS, updatedFile); + } catch (S3Exception e) { + int status = e.statusCode(); + if (status == PRECONDITION_FAILURE_ERROR_CODE || status == CONDITIONAL_REQUEST_CONFLICT_ERROR_CODE) { + logger.info("OwnerId: {}, Lockfile modified by another process: {}", ownerId, lockFilePath); + return Pair.of(LockUpdateResult.ACQUIRED_BY_OTHERS, null); + } else if (status == RATE_LIMIT_ERROR_CODE) { + logger.warn("OwnerId: {}, Rate limit exceeded for: {}", ownerId, lockFilePath); + } else if (status >= INTERNAL_SERVER_ERROR_CODE_MIN) { + logger.warn("OwnerId: {}, S3 internal server error for: {}", ownerId, lockFilePath, e); + } else { + throw e; + } + return Pair.of(LockUpdateResult.UNKNOWN_ERROR, null); Review Comment: not a fan of returning `null` as sentinels. Could we use an `Option` ########## hudi-aws/src/main/java/org/apache/hudi/aws/transaction/lock/S3StorageLockClient.java: ########## @@ -0,0 +1,248 @@ +/* + * 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.aws.transaction.lock; + +import org.apache.hudi.aws.credentials.HoodieAWSCredentialsProviderFactory; +import org.apache.hudi.client.transaction.lock.models.LockGetResult; +import org.apache.hudi.client.transaction.lock.models.LockUpdateResult; +import org.apache.hudi.client.transaction.lock.StorageLock; +import org.apache.hudi.client.transaction.lock.models.StorageLockData; +import org.apache.hudi.client.transaction.lock.models.StorageLockFile; +import org.apache.hudi.common.util.VisibleForTesting; +import org.apache.hudi.common.util.collection.Pair; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.core.ResponseInputStream; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import javax.annotation.concurrent.ThreadSafe; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Properties; +import java.util.function.Supplier; + +/** + * S3-based distributed lock service using ETag checks (AWS SDK v2). + * See RFC: <a href="https://github.com/apache/hudi/blob/master/rfc/rfc-91/rfc-91.md">RFC-91</a> + */ +@ThreadSafe +public class S3StorageLockClient implements StorageLock { + + private static final Logger LOG = LoggerFactory.getLogger(S3StorageLockClient.class); + private static final long WAIT_TIME_FOR_RETRY_MS = 1000L; + private static final int PRECONDITION_FAILURE_ERROR_CODE = 412; + private static final int NOT_FOUND_ERROR_CODE = 404; + private static final int CONDITIONAL_REQUEST_CONFLICT_ERROR_CODE = 409; + private static final int RATE_LIMIT_ERROR_CODE = 429; + private static final int INTERNAL_SERVER_ERROR_CODE_MIN = 500; + + private final Logger logger; + private final S3Client s3Client; + private final String bucketName; + private final String lockFilePath; + private final String ownerId; + + /** Constructor that is used by reflection to instantiate an S3-based storage locking client. + * @param ownerId The owner id. + * @param bucketName The name of the bucket. + * @param lockFilePath The path within the bucket where to write lock files. + * @param props The properties for the lock config, can be used to customize client. + */ + public S3StorageLockClient(String ownerId, String bucketName, String lockFilePath, Properties props) { + this( + ownerId, + bucketName, + lockFilePath, + createDefaultS3Client(props), + LOG); + } + + @VisibleForTesting + S3StorageLockClient(String ownerId, Review Comment: formatting ########## hudi-aws/src/main/java/org/apache/hudi/aws/transaction/lock/S3StorageLockClient.java: ########## @@ -0,0 +1,248 @@ +/* + * 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.aws.transaction.lock; + +import org.apache.hudi.aws.credentials.HoodieAWSCredentialsProviderFactory; +import org.apache.hudi.client.transaction.lock.models.LockGetResult; +import org.apache.hudi.client.transaction.lock.models.LockUpdateResult; +import org.apache.hudi.client.transaction.lock.StorageLock; +import org.apache.hudi.client.transaction.lock.models.StorageLockData; +import org.apache.hudi.client.transaction.lock.models.StorageLockFile; +import org.apache.hudi.common.util.VisibleForTesting; +import org.apache.hudi.common.util.collection.Pair; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.core.ResponseInputStream; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import javax.annotation.concurrent.ThreadSafe; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Properties; +import java.util.function.Supplier; + +/** + * S3-based distributed lock service using ETag checks (AWS SDK v2). + * See RFC: <a href="https://github.com/apache/hudi/blob/master/rfc/rfc-91/rfc-91.md">RFC-91</a> + */ +@ThreadSafe +public class S3StorageLockClient implements StorageLock { + + private static final Logger LOG = LoggerFactory.getLogger(S3StorageLockClient.class); + private static final long WAIT_TIME_FOR_RETRY_MS = 1000L; + private static final int PRECONDITION_FAILURE_ERROR_CODE = 412; + private static final int NOT_FOUND_ERROR_CODE = 404; + private static final int CONDITIONAL_REQUEST_CONFLICT_ERROR_CODE = 409; + private static final int RATE_LIMIT_ERROR_CODE = 429; + private static final int INTERNAL_SERVER_ERROR_CODE_MIN = 500; + + private final Logger logger; + private final S3Client s3Client; + private final String bucketName; + private final String lockFilePath; + private final String ownerId; + + /** Constructor that is used by reflection to instantiate an S3-based storage locking client. + * @param ownerId The owner id. + * @param bucketName The name of the bucket. + * @param lockFilePath The path within the bucket where to write lock files. + * @param props The properties for the lock config, can be used to customize client. + */ + public S3StorageLockClient(String ownerId, String bucketName, String lockFilePath, Properties props) { + this( + ownerId, + bucketName, + lockFilePath, + createDefaultS3Client(props), + LOG); + } + + @VisibleForTesting + S3StorageLockClient(String ownerId, + String bucketName, + String lockFilePath, + S3Client s3Client, + Logger logger) { + this.s3Client = s3Client; + this.lockFilePath = lockFilePath; + this.bucketName = bucketName; + this.ownerId = ownerId; + this.logger = logger; + } + + private static S3Client createDefaultS3Client(Properties props) { + Region region; + try { + region = DefaultAwsRegionProviderChain.builder().build().getRegion(); + } catch (SdkClientException e) { + // Fallback to us-east-1 if no region is found + region = Region.US_EAST_1; Review Comment: lets pull into a constant.. or should we error out instead if no region is found. i.e is there a valid case, where no region is found, but US_EAST_1 works? Like to more this fallback, if we think it should 99% not fail ########## hudi-aws/src/main/java/org/apache/hudi/aws/transaction/lock/S3StorageLockClient.java: ########## @@ -0,0 +1,248 @@ +/* + * 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.aws.transaction.lock; + +import org.apache.hudi.aws.credentials.HoodieAWSCredentialsProviderFactory; +import org.apache.hudi.client.transaction.lock.models.LockGetResult; +import org.apache.hudi.client.transaction.lock.models.LockUpdateResult; +import org.apache.hudi.client.transaction.lock.StorageLock; +import org.apache.hudi.client.transaction.lock.models.StorageLockData; +import org.apache.hudi.client.transaction.lock.models.StorageLockFile; +import org.apache.hudi.common.util.VisibleForTesting; +import org.apache.hudi.common.util.collection.Pair; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.core.ResponseInputStream; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import javax.annotation.concurrent.ThreadSafe; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Properties; +import java.util.function.Supplier; + +/** + * S3-based distributed lock service using ETag checks (AWS SDK v2). + * See RFC: <a href="https://github.com/apache/hudi/blob/master/rfc/rfc-91/rfc-91.md">RFC-91</a> + */ +@ThreadSafe +public class S3StorageLockClient implements StorageLock { + + private static final Logger LOG = LoggerFactory.getLogger(S3StorageLockClient.class); + private static final long WAIT_TIME_FOR_RETRY_MS = 1000L; + private static final int PRECONDITION_FAILURE_ERROR_CODE = 412; + private static final int NOT_FOUND_ERROR_CODE = 404; + private static final int CONDITIONAL_REQUEST_CONFLICT_ERROR_CODE = 409; + private static final int RATE_LIMIT_ERROR_CODE = 429; + private static final int INTERNAL_SERVER_ERROR_CODE_MIN = 500; + + private final Logger logger; + private final S3Client s3Client; + private final String bucketName; + private final String lockFilePath; + private final String ownerId; + + /** Constructor that is used by reflection to instantiate an S3-based storage locking client. + * @param ownerId The owner id. + * @param bucketName The name of the bucket. + * @param lockFilePath The path within the bucket where to write lock files. + * @param props The properties for the lock config, can be used to customize client. + */ + public S3StorageLockClient(String ownerId, String bucketName, String lockFilePath, Properties props) { + this( + ownerId, + bucketName, + lockFilePath, + createDefaultS3Client(props), + LOG); + } + + @VisibleForTesting + S3StorageLockClient(String ownerId, + String bucketName, + String lockFilePath, + S3Client s3Client, + Logger logger) { + this.s3Client = s3Client; + this.lockFilePath = lockFilePath; + this.bucketName = bucketName; + this.ownerId = ownerId; + this.logger = logger; + } + + private static S3Client createDefaultS3Client(Properties props) { + Region region; + try { + region = DefaultAwsRegionProviderChain.builder().build().getRegion(); + } catch (SdkClientException e) { Review Comment: does this only get thrown if region is not found ########## hudi-aws/src/test/java/org/apache/hudi/aws/transaction/lock/TestS3StorageBasedLockProvider.java: ########## @@ -0,0 +1,159 @@ +/* + * 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.aws.transaction.lock; + +import org.apache.hudi.client.transaction.lock.StorageBasedLockProviderTestBase; +import org.apache.hudi.client.transaction.lock.StorageBasedLockProvider; +import org.apache.hudi.common.config.LockConfiguration; +import org.apache.hudi.config.HoodieAWSConfig; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.testcontainers.containers.localstack.LocalStackContainer; +import org.testcontainers.utility.DockerImageName; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.S3ClientBuilder; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.ServerSideEncryption; + +import static org.apache.hudi.common.config.HoodieCommonConfig.BASE_PATH; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mockStatic; +import static org.testcontainers.containers.localstack.LocalStackContainer.Service.S3; + +/** + * Tests S3-based StorageBasedLockProvider using a LocalStack container + * to emulate S3. + */ +@Disabled("HUDI-9159 The tests do not work. Disabling them to unblock Azure CI") Review Comment: Should we mock s3 behavior. Looks like you are trying to functional test using localstack ########## hudi-aws/src/main/java/org/apache/hudi/aws/transaction/lock/S3StorageLockClient.java: ########## @@ -0,0 +1,248 @@ +/* + * 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.aws.transaction.lock; + +import org.apache.hudi.aws.credentials.HoodieAWSCredentialsProviderFactory; +import org.apache.hudi.client.transaction.lock.models.LockGetResult; +import org.apache.hudi.client.transaction.lock.models.LockUpdateResult; +import org.apache.hudi.client.transaction.lock.StorageLock; +import org.apache.hudi.client.transaction.lock.models.StorageLockData; +import org.apache.hudi.client.transaction.lock.models.StorageLockFile; +import org.apache.hudi.common.util.VisibleForTesting; +import org.apache.hudi.common.util.collection.Pair; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.core.ResponseInputStream; +import software.amazon.awssdk.core.exception.SdkClientException; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import javax.annotation.concurrent.ThreadSafe; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Properties; +import java.util.function.Supplier; + +/** + * S3-based distributed lock service using ETag checks (AWS SDK v2). + * See RFC: <a href="https://github.com/apache/hudi/blob/master/rfc/rfc-91/rfc-91.md">RFC-91</a> + */ +@ThreadSafe +public class S3StorageLockClient implements StorageLock { + + private static final Logger LOG = LoggerFactory.getLogger(S3StorageLockClient.class); + private static final long WAIT_TIME_FOR_RETRY_MS = 1000L; + private static final int PRECONDITION_FAILURE_ERROR_CODE = 412; + private static final int NOT_FOUND_ERROR_CODE = 404; + private static final int CONDITIONAL_REQUEST_CONFLICT_ERROR_CODE = 409; + private static final int RATE_LIMIT_ERROR_CODE = 429; + private static final int INTERNAL_SERVER_ERROR_CODE_MIN = 500; + + private final Logger logger; + private final S3Client s3Client; + private final String bucketName; + private final String lockFilePath; + private final String ownerId; + + /** Constructor that is used by reflection to instantiate an S3-based storage locking client. + * @param ownerId The owner id. + * @param bucketName The name of the bucket. + * @param lockFilePath The path within the bucket where to write lock files. + * @param props The properties for the lock config, can be used to customize client. + */ + public S3StorageLockClient(String ownerId, String bucketName, String lockFilePath, Properties props) { + this( + ownerId, + bucketName, + lockFilePath, + createDefaultS3Client(props), + LOG); + } + + @VisibleForTesting + S3StorageLockClient(String ownerId, + String bucketName, + String lockFilePath, + S3Client s3Client, + Logger logger) { + this.s3Client = s3Client; + this.lockFilePath = lockFilePath; + this.bucketName = bucketName; + this.ownerId = ownerId; + this.logger = logger; + } + + private static S3Client createDefaultS3Client(Properties props) { + Region region; + try { + region = DefaultAwsRegionProviderChain.builder().build().getRegion(); + } catch (SdkClientException e) { + // Fallback to us-east-1 if no region is found + region = Region.US_EAST_1; + } + return S3Client.builder().credentialsProvider(HoodieAWSCredentialsProviderFactory.getAwsCredentialsProvider(props)).region(region).build(); + } + + /** + * Internal helper to create or update the lock file with optional ETag precondition. + */ + private StorageLockFile createOrUpdateLockFileInternal(StorageLockData lockData, String expectedEtag) { + byte[] bytes = StorageLockFile.toByteArray(lockData); + PutObjectRequest.Builder putRequestBuilder = PutObjectRequest.builder() + .bucket(bucketName) + .key(lockFilePath); + + // ETag-based constraints: + // - If expectedEtag is not null: + // We assume that the file already exists on S3 with the ETag "expectedEtag". + // The update operation will include an ifMatch(expectedEtag) condition, meaning the update will only + // succeed if the current file's ETag exactly matches expectedEtag. + // If the actual ETag of the file on S3 differs from expectedEtag, the update attempt will fail. + // - If expectedEtag is null: + // We assume that the file does not currently exist on S3. + // The operation will use ifNoneMatch("*"), which instructs S3 to create the file only if it doesn't already exist. + // If a file with the same name is present (i.e., there is an existing ETag), the creation attempt will fail. + if (expectedEtag == null) { + putRequestBuilder.ifNoneMatch("*"); + } else { + putRequestBuilder.ifMatch(expectedEtag); + } + + PutObjectResponse response = s3Client.putObject(putRequestBuilder.build(), RequestBody.fromBytes(bytes)); + String newEtag = response.eTag(); + + return new StorageLockFile(lockData, newEtag); + } + + @Override + public Pair<LockUpdateResult, StorageLockFile> tryCreateOrUpdateLockFile( + StorageLockData newLockData, + StorageLockFile previousLockFile + ) { + String currentEtag = (previousLockFile != null) ? previousLockFile.getVersionId() : null; + try { + StorageLockFile updatedFile = createOrUpdateLockFileInternal(newLockData, currentEtag); + return Pair.of(LockUpdateResult.SUCCESS, updatedFile); + } catch (S3Exception e) { + int status = e.statusCode(); + if (status == PRECONDITION_FAILURE_ERROR_CODE || status == CONDITIONAL_REQUEST_CONFLICT_ERROR_CODE) { + logger.info("OwnerId: {}, Lockfile modified by another process: {}", ownerId, lockFilePath); + return Pair.of(LockUpdateResult.ACQUIRED_BY_OTHERS, null); + } else if (status == RATE_LIMIT_ERROR_CODE) { + logger.warn("OwnerId: {}, Rate limit exceeded for: {}", ownerId, lockFilePath); + } else if (status >= INTERNAL_SERVER_ERROR_CODE_MIN) { + logger.warn("OwnerId: {}, S3 internal server error for: {}", ownerId, lockFilePath, e); + } else { + throw e; + } + return Pair.of(LockUpdateResult.UNKNOWN_ERROR, null); + } + } + + @Override + public Pair<LockUpdateResult, StorageLockFile> tryCreateOrUpdateLockFileWithRetry( + Supplier<StorageLockData> newLockDataSupplier, + StorageLockFile previousLockFile, + long maxAttempts Review Comment: same. Check if this needs to be tied to `LockConfiguration#LOCK_ACQUIRE_NUM_RETRIES_PROP_KEY` in some way? ########## hudi-aws/src/test/java/org/apache/hudi/aws/transaction/lock/TestS3StorageBasedLockProvider.java: ########## @@ -0,0 +1,159 @@ +/* + * 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.aws.transaction.lock; + +import org.apache.hudi.client.transaction.lock.StorageBasedLockProviderTestBase; +import org.apache.hudi.client.transaction.lock.StorageBasedLockProvider; +import org.apache.hudi.common.config.LockConfiguration; +import org.apache.hudi.config.HoodieAWSConfig; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.testcontainers.containers.localstack.LocalStackContainer; +import org.testcontainers.utility.DockerImageName; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.S3ClientBuilder; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.ServerSideEncryption; + +import static org.apache.hudi.common.config.HoodieCommonConfig.BASE_PATH; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.mockStatic; +import static org.testcontainers.containers.localstack.LocalStackContainer.Service.S3; + +/** + * Tests S3-based StorageBasedLockProvider using a LocalStack container + * to emulate S3. + */ +@Disabled("HUDI-9159 The tests do not work. Disabling them to unblock Azure CI") Review Comment: is there plan to make this work ########## hudi-aws/src/test/java/org/apache/hudi/aws/transaction/lock/TestS3StorageLockClient.java: ########## @@ -0,0 +1,380 @@ +/* + * 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.aws.transaction.lock; + +import org.apache.hudi.client.transaction.lock.models.LockGetResult; +import org.apache.hudi.client.transaction.lock.models.LockUpdateResult; +import org.apache.hudi.client.transaction.lock.models.StorageLockData; +import org.apache.hudi.client.transaction.lock.models.StorageLockFile; +import org.apache.hudi.common.util.collection.Pair; +import org.apache.hudi.exception.HoodieIOException; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.core.ResponseInputStream; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectResponse; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.PutObjectResponse; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.apache.hudi.client.transaction.lock.models.LockUpdateResult.UNKNOWN_ERROR; +import static org.junit.jupiter.api.Assertions.assertEquals; +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.anyInt; +import static org.mockito.ArgumentMatchers.contains; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class TestS3StorageLockClient { + + private static final String OWNER_ID = "ownerId"; + private static final String BUCKET_NAME = "bucketName"; + private static final String LOCK_FILE_PATH = "lockFilePath"; + + @Mock + private S3Client mockS3Client; + + @Mock + private Logger mockLogger; + + private S3StorageLockClient lockService; + + @BeforeEach + void setUp() { + lockService = new S3StorageLockClient( + OWNER_ID, + BUCKET_NAME, + LOCK_FILE_PATH, + mockS3Client, + mockLogger + ); + } + + private void mockS3ObjectWithLockData(StorageLockData lockData, String eTag) { + byte[] bytes = StorageLockFile.toByteArray(lockData); + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + + ResponseInputStream<GetObjectResponse> mockResponseStream = new ResponseInputStream<>( + GetObjectResponse.builder().eTag(eTag).build(), + new MockAbortableInputStream(bais) + ); + + when(mockS3Client.getObject(any(GetObjectRequest.class))).thenReturn(mockResponseStream); + } + + private static class MockAbortableInputStream extends java.io.FilterInputStream { + protected MockAbortableInputStream(ByteArrayInputStream in) { + super(in); + } + } + + @Test + void testTryCreateOrUpdateLockFile_noPreviousLock_success() { + StorageLockData lockData = new StorageLockData(false, System.currentTimeMillis(), "myTxOwner"); + PutObjectResponse putResp = PutObjectResponse.builder().eTag("new-etag-123").build(); + when(mockS3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenReturn(putResp); + + Pair<LockUpdateResult, StorageLockFile> result = lockService.tryCreateOrUpdateLockFile(lockData, null); + + assertEquals(LockUpdateResult.SUCCESS, result.getLeft()); + assertNotNull(result.getRight()); + assertEquals("new-etag-123", result.getRight().getVersionId()); + verify(mockS3Client, times(1)).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + verifyNoMoreInteractions(mockLogger); + } + + @Test + void testTryCreateOrUpdateLockFile_withPreviousLock_success() { + StorageLockData lockData = new StorageLockData(false, 1000L, "myTxOwner"); + StorageLockFile prevLockFile = new StorageLockFile(lockData, "old-etag-999"); + PutObjectResponse putResp = PutObjectResponse.builder().eTag("new-etag-456").build(); + when(mockS3Client.putObject( + eq(PutObjectRequest.builder().bucket(BUCKET_NAME) + .key(LOCK_FILE_PATH) + .ifMatch("old-etag-999") + .build()), + any(RequestBody.class) + )).thenReturn(putResp); + + Pair<LockUpdateResult, StorageLockFile> result = + lockService.tryCreateOrUpdateLockFile(lockData, prevLockFile); + + assertEquals(LockUpdateResult.SUCCESS, result.getLeft()); + assertNotNull(result.getRight()); + assertEquals("new-etag-456", result.getRight().getVersionId()); + verify(mockS3Client, times(1)).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + } + + @Test + void testTryCreateOrUpdateLockFile_preconditionFailed() { + StorageLockData lockData = new StorageLockData(false, 2000L, "txOwner"); + StorageLockFile prevLockFile = new StorageLockFile(lockData, "some-etag"); + + AwsServiceException ex412 = S3Exception.builder().statusCode(412).build(); + when(mockS3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenThrow(ex412); Review Comment: so its mismatching due to the mocked etag. ? -- 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]
