You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by GitBox <gi...@apache.org> on 2022/02/12 06:19:09 UTC

[GitHub] [iceberg] jackye1995 opened a new pull request #4102: AWS: make DynamoDbLockManager public

jackye1995 opened a new pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102


   As we have introduced `LockManager` as an official Iceberg interface, we can now move the protected Glue dynamo lock manager as public. In this PR, we first mark the existing one as deprecated and make a copy of public one. 
   
   Note that the new class is `DynamoDbLockManager` instead of `DynamoLockManager` to follow DynamoDb prefix convention (because the new Dynamo client in AWS SDK v2 is named `DynamoDbClient`).
   
   @arminnajafi @rajarshisarkar @singhpk234 @amogh-jahagirdar


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] amogh-jahagirdar commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
amogh-jahagirdar commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805405461



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Will let @jackye1995  confirm but I believe org.apache.iceberg.aws.glue.DynamoLockManager is basically public, users can pass it in as a locking implementation when creating a catalog.
   
   +1 to extending the DynamoDBLockManager though




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] amogh-jahagirdar commented on pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
amogh-jahagirdar commented on pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#issuecomment-1037023880


   Looks like the build is failing, some spacing issues and I think we need to explicitly mark the preivous class with @Deprecated. Other than that, looks good to me!


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] amogh-jahagirdar commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
amogh-jahagirdar commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805405461



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Will let @jackye1995  confirm but I believe org.apache.iceberg.aws.glue.DynamoLockManager is public, users can pass it in as a locking implementation when creating a catalog.
   
   +1 to extending the DynamoDBLockManager though




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jackye1995 edited a comment on pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
jackye1995 edited a comment on pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#issuecomment-1048562878


   @rdblue I have been thinking about this during the night, I think it's better to move this class to the `org.apache.iceberg.aws.dynamodb` package instead of keeping it as is.
   
   With the Glue optimistic locking change, I don't think any new user will use `org.apache.iceberg.aws.glue.DynamoLockManager`. The lock manager will only be for locking the file system of `HadoopCatalog` commits. It will be very confusing for those users to reference a DynamoDB lock in `glue` package, and it will be a lot of context for those users to understand. So thinking from those users' perspective, it is better for us to provide a clean package path for the DynamoDB lock manager.
   
   For existing users of `org.apache.iceberg.aws.glue.DynamoLockManager`, we are able to keep their experience using this and also show the warning message. I think this is the best path forward.
   
   Please let me know if you object, otherwise I will merge the PR after updating the warning message to be more concrete.


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
rdblue commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r809470771



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Yeah, it's okay if the library we rely on changes. If we don't make the corresponding change then users don't have to modify configurations. That's why I'd prefer to just leave this as-is.




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jackye1995 edited a comment on pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
jackye1995 edited a comment on pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#issuecomment-1048562878


   @rdblue I have been thinking about this during the night, I think it's better to move this class to the `org.apache.iceberg.aws.dynamodb` module instead of keeping it as is.
   
   With the Glue optimistic locking change, I don't think any new user will use `org.apache.iceberg.aws.glue.DynamoLockManager`. The lock manager will only be for locking the file system of `HadoopCatalog` commits. It will be very confusing for those users to reference a DynamoDB lock in `glue` package, and it will be a lot of context for those users to understand. So thinking from those users' perspective, it is better for us to provide a clean package path for the DynamoDB lock manager.
   
   For existing users of `org.apache.iceberg.aws.glue.DynamoLockManager`, we are able to keep their experience using this and also see the warning message. I think this is the best path forward.
   
   Please let me know if you object, otherwise I will merge the PR after updating the warning message to be more concrete.


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] amogh-jahagirdar commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
amogh-jahagirdar commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805405461



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Will let @jackye1995  confirm but I believe org.apache.iceberg.aws.glue.DynamoLockManager is public, users can pass it in as a locking implementation when creating a catalog.
   
   +1 to extending the DynamoDBLockManager




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jackye1995 commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
jackye1995 commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805444544



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       cool, I will update with the extending approach




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
rdblue commented on pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#issuecomment-1049198286


   That sounds reasonable to me. Thanks, @jackye1995!


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jackye1995 commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
jackye1995 commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r808624226



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       > We can make the underlying classpath change transparent to users
   
   what do you mean by transparent? Do you mean to just make `org.apache.iceberg.aws.glue.DynamoLockManager` public instead of having `org.apache.iceberg.aws.dynamodb.DynamoDbLockManager`?




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jackye1995 commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
jackye1995 commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805398359



##########
File path: aws/src/main/java/org/apache/iceberg/aws/dynamodb/DynamoDbLockManager.java
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.iceberg.aws.dynamodb;
+
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import org.apache.iceberg.CatalogProperties;
+import org.apache.iceberg.aws.AwsClientFactories;
+import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.util.LockManagers;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
+import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+import software.amazon.awssdk.services.dynamodb.model.BillingMode;
+import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
+import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
+import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
+import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
+import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
+import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
+import software.amazon.awssdk.services.dynamodb.model.InternalServerErrorException;
+import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
+import software.amazon.awssdk.services.dynamodb.model.KeyType;
+import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException;
+import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.RequestLimitExceededException;
+import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
+import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
+import software.amazon.awssdk.services.dynamodb.model.TableStatus;
+import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
+
+/**
+ * DynamoDB implementation for the lock manager.
+ */
+public class DynamoDbLockManager extends LockManagers.BaseLockManager {
+
+  private static final Logger LOG = LoggerFactory.getLogger(DynamoDbLockManager.class);
+
+  private static final String COL_LOCK_ENTITY_ID = "entityId";
+  private static final String COL_LEASE_DURATION_MS = "leaseDurationMs";
+  private static final String COL_VERSION = "version";
+  private static final String COL_LOCK_OWNER_ID = "ownerId";
+
+  private static final String CONDITION_LOCK_ID_MATCH = String.format(
+      "%s = :eid AND %s = :oid",
+      COL_LOCK_ENTITY_ID, COL_LOCK_OWNER_ID);
+  private static final String CONDITION_LOCK_ENTITY_NOT_EXIST = String.format(
+      "attribute_not_exists(%s)",
+      COL_LOCK_ENTITY_ID);
+  private static final String CONDITION_LOCK_ENTITY_NOT_EXIST_OR_VERSION_MATCH = String.format(
+      "attribute_not_exists(%s) OR (%s = :eid AND %s = :vid)",
+      COL_LOCK_ENTITY_ID, COL_LOCK_ENTITY_ID, COL_VERSION);
+
+  private static final int LOCK_TABLE_CREATION_WAIT_ATTEMPTS_MAX = 5;
+  private static final int RELEASE_RETRY_ATTEMPTS_MAX = 5;
+
+  private static final List<KeySchemaElement> LOCK_TABLE_SCHEMA = Lists.newArrayList(
+      KeySchemaElement.builder()
+          .attributeName(COL_LOCK_ENTITY_ID)
+          .keyType(KeyType.HASH)
+          .build());
+
+  private static final List<AttributeDefinition> LOCK_TABLE_COL_DEFINITIONS = Lists.newArrayList(
+      AttributeDefinition.builder()
+          .attributeName(COL_LOCK_ENTITY_ID)
+          .attributeType(ScalarAttributeType.S)
+          .build());
+
+  private final Map<String, DynamoHeartbeat> heartbeats = Maps.newHashMap();
+
+  private DynamoDbClient dynamo;
+  private String lockTableName;
+
+  /**
+   * constructor for dynamic initialization, {@link #initialize(Map)} must be called later.
+   */
+  DynamoDbLockManager() {
+  }
+
+  /**
+   * constructor used for testing purpose
+   * @param dynamo dynamo client
+   * @param lockTableName lock table name
+   */
+  DynamoDbLockManager(DynamoDbClient dynamo, String lockTableName) {
+    super.initialize(Maps.newHashMap());
+    this.dynamo = dynamo;
+    this.lockTableName = lockTableName;
+    ensureLockTableExistsOrCreate();
+  }
+
+  private void ensureLockTableExistsOrCreate() {
+
+    if (tableExists(lockTableName)) {
+      return;
+    }
+
+    LOG.info("Dynamo lock table {} not found, trying to create", lockTableName);
+    dynamo.createTable(CreateTableRequest.builder()
+        .tableName(lockTableName)
+        .keySchema(lockTableSchema())
+        .attributeDefinitions(lockTableColDefinitions())
+        .billingMode(BillingMode.PAY_PER_REQUEST)
+        .build());
+
+    Tasks.foreach(lockTableName)
+        .retry(LOCK_TABLE_CREATION_WAIT_ATTEMPTS_MAX)
+        .throwFailureWhenFinished()
+        .onlyRetryOn(IllegalStateException.class)
+        .run(this::checkTableActive);
+  }
+
+  @VisibleForTesting
+  boolean tableExists(String tableName) {
+    try {
+      dynamo.describeTable(DescribeTableRequest.builder()
+          .tableName(tableName)
+          .build());
+      return true;
+    } catch (ResourceNotFoundException e) {
+      return false;
+    }
+  }
+
+  private void checkTableActive(String tableName) {
+    try {
+      DescribeTableResponse response = dynamo.describeTable(DescribeTableRequest.builder()
+          .tableName(tableName)
+          .build());
+      TableStatus currentStatus = response.table().tableStatus();
+      if (!currentStatus.equals(TableStatus.ACTIVE)) {
+        throw new IllegalStateException(String.format("Dynamo table %s is not active, current status: %s",
+            tableName, currentStatus));
+      }
+    } catch (ResourceNotFoundException e) {
+      throw new IllegalStateException(String.format("Cannot find Dynamo table %s", tableName));
+    }
+  }
+
+  @Override
+  public void initialize(Map<String, String> properties) {
+    super.initialize(properties);
+    this.dynamo = AwsClientFactories.from(properties).dynamo();
+    this.lockTableName = properties.get(CatalogProperties.LOCK_TABLE);
+    Preconditions.checkNotNull(lockTableName, "DynamoDB lock table name must not be null");
+    ensureLockTableExistsOrCreate();
+  }
+
+  @Override
+  public boolean acquire(String entityId, String ownerId) {
+    try {
+      Tasks.foreach(entityId)
+          .throwFailureWhenFinished()
+          .retry(Integer.MAX_VALUE - 1)
+          .exponentialBackoff(acquireIntervalMs(), acquireIntervalMs(), acquireTimeoutMs(), 1)
+          .onlyRetryOn(
+              ConditionalCheckFailedException.class,
+              ProvisionedThroughputExceededException.class,
+              TransactionConflictException.class,
+              RequestLimitExceededException.class,
+              InternalServerErrorException.class)
+          .run(id -> acquireOnce(id, ownerId));
+      return true;
+    } catch (DynamoDbException e) {
+      return false;
+    }
+  }
+
+  @VisibleForTesting
+  void acquireOnce(String entityId, String ownerId) {
+    GetItemResponse response = dynamo.getItem(GetItemRequest.builder()
+        .tableName(lockTableName)
+        .key(toKey(entityId))
+        .build());
+
+    if (!response.hasItem()) {
+      dynamo.putItem(PutItemRequest.builder()
+          .tableName(lockTableName)
+          .item(toNewItem(entityId, ownerId, heartbeatTimeoutMs()))
+          .conditionExpression(CONDITION_LOCK_ENTITY_NOT_EXIST)
+          .build());
+    } else {
+      Map<String, AttributeValue> currentItem = response.item();
+
+      try {
+        Thread.sleep(Long.parseLong(currentItem.get(COL_LEASE_DURATION_MS).n()));
+      } catch (InterruptedException e) {
+        throw new IllegalStateException(
+            String.format("Fail to acquire lock %s by %s, interrupted during sleep", entityId, ownerId), e);
+      }
+
+      dynamo.putItem(PutItemRequest.builder()
+          .tableName(lockTableName)
+          .item(toNewItem(entityId, ownerId, heartbeatTimeoutMs()))
+          .conditionExpression(CONDITION_LOCK_ENTITY_NOT_EXIST_OR_VERSION_MATCH)
+          .expressionAttributeValues(ImmutableMap.of(
+              ":eid", AttributeValue.builder().s(entityId).build(),
+              ":vid", AttributeValue.builder().s(currentItem.get(COL_VERSION).s()).build()))
+          .build());
+    }
+
+    startNewHeartbeat(entityId, ownerId);
+  }
+
+  private void startNewHeartbeat(String entityId, String ownerId) {
+    if (heartbeats.containsKey(entityId)) {
+      heartbeats.remove(entityId).cancel();
+    }
+
+    DynamoHeartbeat heartbeat = new DynamoHeartbeat(dynamo, lockTableName,
+        heartbeatIntervalMs(), heartbeatTimeoutMs(), entityId, ownerId);
+    heartbeat.schedule(scheduler());
+    heartbeats.put(entityId, heartbeat);
+  }
+
+  @Override
+  public boolean release(String entityId, String ownerId) {
+    boolean succeeded = false;
+    DynamoHeartbeat heartbeat = heartbeats.get(entityId);
+    try {
+      Tasks.foreach(entityId)
+          .retry(RELEASE_RETRY_ATTEMPTS_MAX)
+          .throwFailureWhenFinished()
+          .onlyRetryOn(
+              ProvisionedThroughputExceededException.class,
+              TransactionConflictException.class,
+              RequestLimitExceededException.class,
+              InternalServerErrorException.class)
+          .run(id -> dynamo.deleteItem(DeleteItemRequest.builder()
+              .tableName(lockTableName)
+              .key(toKey(id))
+              .conditionExpression(CONDITION_LOCK_ID_MATCH)
+              .expressionAttributeValues(toLockIdValues(id, ownerId))
+              .build()));
+      succeeded = true;
+    } catch (ConditionalCheckFailedException e) {
+      LOG.error("Failed to release lock for entity: {}, owner: {}, lock entity does not exist or owner not match",
+          entityId, ownerId, e);
+    } catch (DynamoDbException e) {
+      LOG.error("Failed to release lock {} by for entity: {}, owner: {}, encountered unexpected DynamoDB exception",
+          entityId, ownerId, e);
+    } finally {
+      if (heartbeat != null && heartbeat.ownerId().equals(ownerId)) {
+        heartbeat.cancel();
+      }
+    }
+
+    return succeeded;
+  }
+
+  private static Map<String, AttributeValue> toKey(String entityId) {
+    return ImmutableMap.of(COL_LOCK_ENTITY_ID, AttributeValue.builder().s(entityId).build());
+  }
+
+  private static Map<String, AttributeValue> toNewItem(String entityId, String ownerId, long heartbeatTimeoutMs) {
+    return ImmutableMap.of(
+        COL_LOCK_ENTITY_ID, AttributeValue.builder().s(entityId).build(),
+        COL_LOCK_OWNER_ID, AttributeValue.builder().s(ownerId).build(),
+        COL_VERSION, AttributeValue.builder().s(UUID.randomUUID().toString()).build(),
+        COL_LEASE_DURATION_MS, AttributeValue.builder().n(Long.toString(heartbeatTimeoutMs)).build());
+  }
+
+  private static Map<String, AttributeValue> toLockIdValues(String entityId, String ownerId) {
+    return ImmutableMap.of(
+        ":eid", AttributeValue.builder().s(entityId).build(),
+        ":oid", AttributeValue.builder().s(ownerId).build());
+  }
+
+  @Override
+  public void close() {
+    dynamo.close();
+    heartbeats.values().forEach(DynamoHeartbeat::cancel);
+    heartbeats.clear();
+  }
+
+  /**
+   * The lock table schema, for users who would like to create the table separately
+   * @return lock table schema
+   */
+  public static List<KeySchemaElement> lockTableSchema() {
+    return LOCK_TABLE_SCHEMA;
+  }
+
+  /**
+   * The lock table column definition, for users who whould like to create the table separately
+   * @return lock table column definition
+   */
+  public static List<AttributeDefinition> lockTableColDefinitions() {
+    return LOCK_TABLE_COL_DEFINITIONS;
+  }
+
+  private static class DynamoHeartbeat implements Runnable {

Review comment:
       updated




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
rdblue commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805404589



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Why deprecate this if it wasn't public in the first place?
   
   Also, can this extend `DynamoDbLockManager` so that we don't have two implementations? Then we can also get rid of the tests here.

##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       If this is already effectively public because people use it dynamically as their lock-impl, then I'd probably keep this instead of renaming. Or maybe have both names, but definitely not remove this unless it's absolutely necessary.




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] singhpk234 commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
singhpk234 commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805244951



##########
File path: aws/src/main/java/org/apache/iceberg/aws/dynamodb/DynamoDbLockManager.java
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.iceberg.aws.dynamodb;
+
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import org.apache.iceberg.CatalogProperties;
+import org.apache.iceberg.aws.AwsClientFactories;
+import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.util.LockManagers;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
+import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+import software.amazon.awssdk.services.dynamodb.model.BillingMode;
+import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
+import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
+import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
+import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
+import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
+import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
+import software.amazon.awssdk.services.dynamodb.model.InternalServerErrorException;
+import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
+import software.amazon.awssdk.services.dynamodb.model.KeyType;
+import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException;
+import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.RequestLimitExceededException;
+import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
+import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
+import software.amazon.awssdk.services.dynamodb.model.TableStatus;
+import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
+
+/**
+ * DynamoDB implementation for the lock manager.
+ */
+public class DynamoDbLockManager extends LockManagers.BaseLockManager {
+
+  private static final Logger LOG = LoggerFactory.getLogger(DynamoDbLockManager.class);
+
+  private static final String COL_LOCK_ENTITY_ID = "entityId";
+  private static final String COL_LEASE_DURATION_MS = "leaseDurationMs";
+  private static final String COL_VERSION = "version";
+  private static final String COL_LOCK_OWNER_ID = "ownerId";
+
+  private static final String CONDITION_LOCK_ID_MATCH = String.format(
+      "%s = :eid AND %s = :oid",
+      COL_LOCK_ENTITY_ID, COL_LOCK_OWNER_ID);
+  private static final String CONDITION_LOCK_ENTITY_NOT_EXIST = String.format(
+      "attribute_not_exists(%s)",
+      COL_LOCK_ENTITY_ID);
+  private static final String CONDITION_LOCK_ENTITY_NOT_EXIST_OR_VERSION_MATCH = String.format(
+      "attribute_not_exists(%s) OR (%s = :eid AND %s = :vid)",
+      COL_LOCK_ENTITY_ID, COL_LOCK_ENTITY_ID, COL_VERSION);
+
+  private static final int LOCK_TABLE_CREATION_WAIT_ATTEMPTS_MAX = 5;
+  private static final int RELEASE_RETRY_ATTEMPTS_MAX = 5;
+
+  private static final List<KeySchemaElement> LOCK_TABLE_SCHEMA = Lists.newArrayList(
+      KeySchemaElement.builder()
+          .attributeName(COL_LOCK_ENTITY_ID)
+          .keyType(KeyType.HASH)
+          .build());
+
+  private static final List<AttributeDefinition> LOCK_TABLE_COL_DEFINITIONS = Lists.newArrayList(
+      AttributeDefinition.builder()
+          .attributeName(COL_LOCK_ENTITY_ID)
+          .attributeType(ScalarAttributeType.S)
+          .build());
+
+  private final Map<String, DynamoHeartbeat> heartbeats = Maps.newHashMap();
+
+  private DynamoDbClient dynamo;
+  private String lockTableName;
+
+  /**
+   * constructor for dynamic initialization, {@link #initialize(Map)} must be called later.
+   */
+  DynamoDbLockManager() {
+  }
+
+  /**
+   * constructor used for testing purpose
+   * @param dynamo dynamo client
+   * @param lockTableName lock table name
+   */
+  DynamoDbLockManager(DynamoDbClient dynamo, String lockTableName) {
+    super.initialize(Maps.newHashMap());
+    this.dynamo = dynamo;
+    this.lockTableName = lockTableName;
+    ensureLockTableExistsOrCreate();
+  }
+
+  private void ensureLockTableExistsOrCreate() {
+
+    if (tableExists(lockTableName)) {
+      return;
+    }
+
+    LOG.info("Dynamo lock table {} not found, trying to create", lockTableName);
+    dynamo.createTable(CreateTableRequest.builder()
+        .tableName(lockTableName)
+        .keySchema(lockTableSchema())
+        .attributeDefinitions(lockTableColDefinitions())
+        .billingMode(BillingMode.PAY_PER_REQUEST)
+        .build());
+
+    Tasks.foreach(lockTableName)
+        .retry(LOCK_TABLE_CREATION_WAIT_ATTEMPTS_MAX)
+        .throwFailureWhenFinished()
+        .onlyRetryOn(IllegalStateException.class)
+        .run(this::checkTableActive);
+  }
+
+  @VisibleForTesting
+  boolean tableExists(String tableName) {
+    try {
+      dynamo.describeTable(DescribeTableRequest.builder()
+          .tableName(tableName)
+          .build());
+      return true;
+    } catch (ResourceNotFoundException e) {
+      return false;
+    }
+  }
+
+  private void checkTableActive(String tableName) {
+    try {
+      DescribeTableResponse response = dynamo.describeTable(DescribeTableRequest.builder()
+          .tableName(tableName)
+          .build());
+      TableStatus currentStatus = response.table().tableStatus();
+      if (!currentStatus.equals(TableStatus.ACTIVE)) {
+        throw new IllegalStateException(String.format("Dynamo table %s is not active, current status: %s",
+            tableName, currentStatus));
+      }
+    } catch (ResourceNotFoundException e) {
+      throw new IllegalStateException(String.format("Cannot find Dynamo table %s", tableName));
+    }
+  }
+
+  @Override
+  public void initialize(Map<String, String> properties) {
+    super.initialize(properties);
+    this.dynamo = AwsClientFactories.from(properties).dynamo();
+    this.lockTableName = properties.get(CatalogProperties.LOCK_TABLE);
+    Preconditions.checkNotNull(lockTableName, "DynamoDB lock table name must not be null");
+    ensureLockTableExistsOrCreate();
+  }
+
+  @Override
+  public boolean acquire(String entityId, String ownerId) {
+    try {
+      Tasks.foreach(entityId)
+          .throwFailureWhenFinished()
+          .retry(Integer.MAX_VALUE - 1)
+          .exponentialBackoff(acquireIntervalMs(), acquireIntervalMs(), acquireTimeoutMs(), 1)
+          .onlyRetryOn(
+              ConditionalCheckFailedException.class,
+              ProvisionedThroughputExceededException.class,
+              TransactionConflictException.class,
+              RequestLimitExceededException.class,
+              InternalServerErrorException.class)
+          .run(id -> acquireOnce(id, ownerId));
+      return true;
+    } catch (DynamoDbException e) {
+      return false;
+    }
+  }
+
+  @VisibleForTesting
+  void acquireOnce(String entityId, String ownerId) {
+    GetItemResponse response = dynamo.getItem(GetItemRequest.builder()
+        .tableName(lockTableName)
+        .key(toKey(entityId))
+        .build());
+
+    if (!response.hasItem()) {
+      dynamo.putItem(PutItemRequest.builder()
+          .tableName(lockTableName)
+          .item(toNewItem(entityId, ownerId, heartbeatTimeoutMs()))
+          .conditionExpression(CONDITION_LOCK_ENTITY_NOT_EXIST)
+          .build());
+    } else {
+      Map<String, AttributeValue> currentItem = response.item();
+
+      try {
+        Thread.sleep(Long.parseLong(currentItem.get(COL_LEASE_DURATION_MS).n()));
+      } catch (InterruptedException e) {
+        throw new IllegalStateException(
+            String.format("Fail to acquire lock %s by %s, interrupted during sleep", entityId, ownerId), e);
+      }
+
+      dynamo.putItem(PutItemRequest.builder()
+          .tableName(lockTableName)
+          .item(toNewItem(entityId, ownerId, heartbeatTimeoutMs()))
+          .conditionExpression(CONDITION_LOCK_ENTITY_NOT_EXIST_OR_VERSION_MATCH)
+          .expressionAttributeValues(ImmutableMap.of(
+              ":eid", AttributeValue.builder().s(entityId).build(),
+              ":vid", AttributeValue.builder().s(currentItem.get(COL_VERSION).s()).build()))
+          .build());
+    }
+
+    startNewHeartbeat(entityId, ownerId);
+  }
+
+  private void startNewHeartbeat(String entityId, String ownerId) {
+    if (heartbeats.containsKey(entityId)) {
+      heartbeats.remove(entityId).cancel();
+    }
+
+    DynamoHeartbeat heartbeat = new DynamoHeartbeat(dynamo, lockTableName,
+        heartbeatIntervalMs(), heartbeatTimeoutMs(), entityId, ownerId);
+    heartbeat.schedule(scheduler());
+    heartbeats.put(entityId, heartbeat);
+  }
+
+  @Override
+  public boolean release(String entityId, String ownerId) {
+    boolean succeeded = false;
+    DynamoHeartbeat heartbeat = heartbeats.get(entityId);
+    try {
+      Tasks.foreach(entityId)
+          .retry(RELEASE_RETRY_ATTEMPTS_MAX)
+          .throwFailureWhenFinished()
+          .onlyRetryOn(
+              ProvisionedThroughputExceededException.class,
+              TransactionConflictException.class,
+              RequestLimitExceededException.class,
+              InternalServerErrorException.class)
+          .run(id -> dynamo.deleteItem(DeleteItemRequest.builder()
+              .tableName(lockTableName)
+              .key(toKey(id))
+              .conditionExpression(CONDITION_LOCK_ID_MATCH)
+              .expressionAttributeValues(toLockIdValues(id, ownerId))
+              .build()));
+      succeeded = true;
+    } catch (ConditionalCheckFailedException e) {
+      LOG.error("Failed to release lock for entity: {}, owner: {}, lock entity does not exist or owner not match",
+          entityId, ownerId, e);
+    } catch (DynamoDbException e) {
+      LOG.error("Failed to release lock {} by for entity: {}, owner: {}, encountered unexpected DynamoDB exception",
+          entityId, ownerId, e);
+    } finally {
+      if (heartbeat != null && heartbeat.ownerId().equals(ownerId)) {
+        heartbeat.cancel();
+      }
+    }
+
+    return succeeded;
+  }
+
+  private static Map<String, AttributeValue> toKey(String entityId) {
+    return ImmutableMap.of(COL_LOCK_ENTITY_ID, AttributeValue.builder().s(entityId).build());
+  }
+
+  private static Map<String, AttributeValue> toNewItem(String entityId, String ownerId, long heartbeatTimeoutMs) {
+    return ImmutableMap.of(
+        COL_LOCK_ENTITY_ID, AttributeValue.builder().s(entityId).build(),
+        COL_LOCK_OWNER_ID, AttributeValue.builder().s(ownerId).build(),
+        COL_VERSION, AttributeValue.builder().s(UUID.randomUUID().toString()).build(),
+        COL_LEASE_DURATION_MS, AttributeValue.builder().n(Long.toString(heartbeatTimeoutMs)).build());
+  }
+
+  private static Map<String, AttributeValue> toLockIdValues(String entityId, String ownerId) {
+    return ImmutableMap.of(
+        ":eid", AttributeValue.builder().s(entityId).build(),
+        ":oid", AttributeValue.builder().s(ownerId).build());
+  }
+
+  @Override
+  public void close() {
+    dynamo.close();
+    heartbeats.values().forEach(DynamoHeartbeat::cancel);
+    heartbeats.clear();
+  }
+
+  /**
+   * The lock table schema, for users who would like to create the table separately
+   * @return lock table schema
+   */
+  public static List<KeySchemaElement> lockTableSchema() {
+    return LOCK_TABLE_SCHEMA;
+  }
+
+  /**
+   * The lock table column definition, for users who whould like to create the table separately
+   * @return lock table column definition
+   */
+  public static List<AttributeDefinition> lockTableColDefinitions() {
+    return LOCK_TABLE_COL_DEFINITIONS;
+  }
+
+  private static class DynamoHeartbeat implements Runnable {

Review comment:
       [minor] should we also make this `DynamoDbHeartbeat` following `Dynamo` -> `DynamoDb` convention




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] amogh-jahagirdar edited a comment on pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
amogh-jahagirdar edited a comment on pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#issuecomment-1037023880


   Looks like the build is failing, some spacing issues and I think we need to explicitly mark the preivous class with 
   "@Deprecated". Other than that, looks good to me!


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jackye1995 commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
jackye1995 commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805441635



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       my intention for doing that copy was to fully remove this class after 2 releases, and people who see this class can know it should not be used anymore. But extending also works, I don't have a strong opinion of which way is better.




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] singhpk234 commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
singhpk234 commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805244951



##########
File path: aws/src/main/java/org/apache/iceberg/aws/dynamodb/DynamoDbLockManager.java
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.iceberg.aws.dynamodb;
+
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import org.apache.iceberg.CatalogProperties;
+import org.apache.iceberg.aws.AwsClientFactories;
+import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.util.LockManagers;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
+import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+import software.amazon.awssdk.services.dynamodb.model.BillingMode;
+import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
+import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
+import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
+import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
+import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
+import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
+import software.amazon.awssdk.services.dynamodb.model.InternalServerErrorException;
+import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
+import software.amazon.awssdk.services.dynamodb.model.KeyType;
+import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException;
+import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.RequestLimitExceededException;
+import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
+import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
+import software.amazon.awssdk.services.dynamodb.model.TableStatus;
+import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
+
+/**
+ * DynamoDB implementation for the lock manager.
+ */
+public class DynamoDbLockManager extends LockManagers.BaseLockManager {
+
+  private static final Logger LOG = LoggerFactory.getLogger(DynamoDbLockManager.class);
+
+  private static final String COL_LOCK_ENTITY_ID = "entityId";
+  private static final String COL_LEASE_DURATION_MS = "leaseDurationMs";
+  private static final String COL_VERSION = "version";
+  private static final String COL_LOCK_OWNER_ID = "ownerId";
+
+  private static final String CONDITION_LOCK_ID_MATCH = String.format(
+      "%s = :eid AND %s = :oid",
+      COL_LOCK_ENTITY_ID, COL_LOCK_OWNER_ID);
+  private static final String CONDITION_LOCK_ENTITY_NOT_EXIST = String.format(
+      "attribute_not_exists(%s)",
+      COL_LOCK_ENTITY_ID);
+  private static final String CONDITION_LOCK_ENTITY_NOT_EXIST_OR_VERSION_MATCH = String.format(
+      "attribute_not_exists(%s) OR (%s = :eid AND %s = :vid)",
+      COL_LOCK_ENTITY_ID, COL_LOCK_ENTITY_ID, COL_VERSION);
+
+  private static final int LOCK_TABLE_CREATION_WAIT_ATTEMPTS_MAX = 5;
+  private static final int RELEASE_RETRY_ATTEMPTS_MAX = 5;
+
+  private static final List<KeySchemaElement> LOCK_TABLE_SCHEMA = Lists.newArrayList(
+      KeySchemaElement.builder()
+          .attributeName(COL_LOCK_ENTITY_ID)
+          .keyType(KeyType.HASH)
+          .build());
+
+  private static final List<AttributeDefinition> LOCK_TABLE_COL_DEFINITIONS = Lists.newArrayList(
+      AttributeDefinition.builder()
+          .attributeName(COL_LOCK_ENTITY_ID)
+          .attributeType(ScalarAttributeType.S)
+          .build());
+
+  private final Map<String, DynamoHeartbeat> heartbeats = Maps.newHashMap();
+
+  private DynamoDbClient dynamo;
+  private String lockTableName;
+
+  /**
+   * constructor for dynamic initialization, {@link #initialize(Map)} must be called later.
+   */
+  DynamoDbLockManager() {
+  }
+
+  /**
+   * constructor used for testing purpose
+   * @param dynamo dynamo client
+   * @param lockTableName lock table name
+   */
+  DynamoDbLockManager(DynamoDbClient dynamo, String lockTableName) {
+    super.initialize(Maps.newHashMap());
+    this.dynamo = dynamo;
+    this.lockTableName = lockTableName;
+    ensureLockTableExistsOrCreate();
+  }
+
+  private void ensureLockTableExistsOrCreate() {
+
+    if (tableExists(lockTableName)) {
+      return;
+    }
+
+    LOG.info("Dynamo lock table {} not found, trying to create", lockTableName);
+    dynamo.createTable(CreateTableRequest.builder()
+        .tableName(lockTableName)
+        .keySchema(lockTableSchema())
+        .attributeDefinitions(lockTableColDefinitions())
+        .billingMode(BillingMode.PAY_PER_REQUEST)
+        .build());
+
+    Tasks.foreach(lockTableName)
+        .retry(LOCK_TABLE_CREATION_WAIT_ATTEMPTS_MAX)
+        .throwFailureWhenFinished()
+        .onlyRetryOn(IllegalStateException.class)
+        .run(this::checkTableActive);
+  }
+
+  @VisibleForTesting
+  boolean tableExists(String tableName) {
+    try {
+      dynamo.describeTable(DescribeTableRequest.builder()
+          .tableName(tableName)
+          .build());
+      return true;
+    } catch (ResourceNotFoundException e) {
+      return false;
+    }
+  }
+
+  private void checkTableActive(String tableName) {
+    try {
+      DescribeTableResponse response = dynamo.describeTable(DescribeTableRequest.builder()
+          .tableName(tableName)
+          .build());
+      TableStatus currentStatus = response.table().tableStatus();
+      if (!currentStatus.equals(TableStatus.ACTIVE)) {
+        throw new IllegalStateException(String.format("Dynamo table %s is not active, current status: %s",
+            tableName, currentStatus));
+      }
+    } catch (ResourceNotFoundException e) {
+      throw new IllegalStateException(String.format("Cannot find Dynamo table %s", tableName));
+    }
+  }
+
+  @Override
+  public void initialize(Map<String, String> properties) {
+    super.initialize(properties);
+    this.dynamo = AwsClientFactories.from(properties).dynamo();
+    this.lockTableName = properties.get(CatalogProperties.LOCK_TABLE);
+    Preconditions.checkNotNull(lockTableName, "DynamoDB lock table name must not be null");
+    ensureLockTableExistsOrCreate();
+  }
+
+  @Override
+  public boolean acquire(String entityId, String ownerId) {
+    try {
+      Tasks.foreach(entityId)
+          .throwFailureWhenFinished()
+          .retry(Integer.MAX_VALUE - 1)
+          .exponentialBackoff(acquireIntervalMs(), acquireIntervalMs(), acquireTimeoutMs(), 1)
+          .onlyRetryOn(
+              ConditionalCheckFailedException.class,
+              ProvisionedThroughputExceededException.class,
+              TransactionConflictException.class,
+              RequestLimitExceededException.class,
+              InternalServerErrorException.class)
+          .run(id -> acquireOnce(id, ownerId));
+      return true;
+    } catch (DynamoDbException e) {
+      return false;
+    }
+  }
+
+  @VisibleForTesting
+  void acquireOnce(String entityId, String ownerId) {
+    GetItemResponse response = dynamo.getItem(GetItemRequest.builder()
+        .tableName(lockTableName)
+        .key(toKey(entityId))
+        .build());
+
+    if (!response.hasItem()) {
+      dynamo.putItem(PutItemRequest.builder()
+          .tableName(lockTableName)
+          .item(toNewItem(entityId, ownerId, heartbeatTimeoutMs()))
+          .conditionExpression(CONDITION_LOCK_ENTITY_NOT_EXIST)
+          .build());
+    } else {
+      Map<String, AttributeValue> currentItem = response.item();
+
+      try {
+        Thread.sleep(Long.parseLong(currentItem.get(COL_LEASE_DURATION_MS).n()));
+      } catch (InterruptedException e) {
+        throw new IllegalStateException(
+            String.format("Fail to acquire lock %s by %s, interrupted during sleep", entityId, ownerId), e);
+      }
+
+      dynamo.putItem(PutItemRequest.builder()
+          .tableName(lockTableName)
+          .item(toNewItem(entityId, ownerId, heartbeatTimeoutMs()))
+          .conditionExpression(CONDITION_LOCK_ENTITY_NOT_EXIST_OR_VERSION_MATCH)
+          .expressionAttributeValues(ImmutableMap.of(
+              ":eid", AttributeValue.builder().s(entityId).build(),
+              ":vid", AttributeValue.builder().s(currentItem.get(COL_VERSION).s()).build()))
+          .build());
+    }
+
+    startNewHeartbeat(entityId, ownerId);
+  }
+
+  private void startNewHeartbeat(String entityId, String ownerId) {
+    if (heartbeats.containsKey(entityId)) {
+      heartbeats.remove(entityId).cancel();
+    }
+
+    DynamoHeartbeat heartbeat = new DynamoHeartbeat(dynamo, lockTableName,
+        heartbeatIntervalMs(), heartbeatTimeoutMs(), entityId, ownerId);
+    heartbeat.schedule(scheduler());
+    heartbeats.put(entityId, heartbeat);
+  }
+
+  @Override
+  public boolean release(String entityId, String ownerId) {
+    boolean succeeded = false;
+    DynamoHeartbeat heartbeat = heartbeats.get(entityId);
+    try {
+      Tasks.foreach(entityId)
+          .retry(RELEASE_RETRY_ATTEMPTS_MAX)
+          .throwFailureWhenFinished()
+          .onlyRetryOn(
+              ProvisionedThroughputExceededException.class,
+              TransactionConflictException.class,
+              RequestLimitExceededException.class,
+              InternalServerErrorException.class)
+          .run(id -> dynamo.deleteItem(DeleteItemRequest.builder()
+              .tableName(lockTableName)
+              .key(toKey(id))
+              .conditionExpression(CONDITION_LOCK_ID_MATCH)
+              .expressionAttributeValues(toLockIdValues(id, ownerId))
+              .build()));
+      succeeded = true;
+    } catch (ConditionalCheckFailedException e) {
+      LOG.error("Failed to release lock for entity: {}, owner: {}, lock entity does not exist or owner not match",
+          entityId, ownerId, e);
+    } catch (DynamoDbException e) {
+      LOG.error("Failed to release lock {} by for entity: {}, owner: {}, encountered unexpected DynamoDB exception",
+          entityId, ownerId, e);
+    } finally {
+      if (heartbeat != null && heartbeat.ownerId().equals(ownerId)) {
+        heartbeat.cancel();
+      }
+    }
+
+    return succeeded;
+  }
+
+  private static Map<String, AttributeValue> toKey(String entityId) {
+    return ImmutableMap.of(COL_LOCK_ENTITY_ID, AttributeValue.builder().s(entityId).build());
+  }
+
+  private static Map<String, AttributeValue> toNewItem(String entityId, String ownerId, long heartbeatTimeoutMs) {
+    return ImmutableMap.of(
+        COL_LOCK_ENTITY_ID, AttributeValue.builder().s(entityId).build(),
+        COL_LOCK_OWNER_ID, AttributeValue.builder().s(ownerId).build(),
+        COL_VERSION, AttributeValue.builder().s(UUID.randomUUID().toString()).build(),
+        COL_LEASE_DURATION_MS, AttributeValue.builder().n(Long.toString(heartbeatTimeoutMs)).build());
+  }
+
+  private static Map<String, AttributeValue> toLockIdValues(String entityId, String ownerId) {
+    return ImmutableMap.of(
+        ":eid", AttributeValue.builder().s(entityId).build(),
+        ":oid", AttributeValue.builder().s(ownerId).build());
+  }
+
+  @Override
+  public void close() {
+    dynamo.close();
+    heartbeats.values().forEach(DynamoHeartbeat::cancel);
+    heartbeats.clear();
+  }
+
+  /**
+   * The lock table schema, for users who would like to create the table separately
+   * @return lock table schema
+   */
+  public static List<KeySchemaElement> lockTableSchema() {
+    return LOCK_TABLE_SCHEMA;
+  }
+
+  /**
+   * The lock table column definition, for users who whould like to create the table separately
+   * @return lock table column definition
+   */
+  public static List<AttributeDefinition> lockTableColDefinitions() {
+    return LOCK_TABLE_COL_DEFINITIONS;
+  }
+
+  private static class DynamoHeartbeat implements Runnable {

Review comment:
       [minor] should we also make this `DynamoDbHeartbeat` following `Dynamo` -> `DynamoDb` convention




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jackye1995 commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
jackye1995 commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805398359



##########
File path: aws/src/main/java/org/apache/iceberg/aws/dynamodb/DynamoDbLockManager.java
##########
@@ -0,0 +1,374 @@
+/*
+ * 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.iceberg.aws.dynamodb;
+
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import org.apache.iceberg.CatalogProperties;
+import org.apache.iceberg.aws.AwsClientFactories;
+import org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTesting;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.util.LockManagers;
+import org.apache.iceberg.util.Tasks;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
+import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
+import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
+import software.amazon.awssdk.services.dynamodb.model.BillingMode;
+import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
+import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
+import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
+import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
+import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
+import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
+import software.amazon.awssdk.services.dynamodb.model.InternalServerErrorException;
+import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
+import software.amazon.awssdk.services.dynamodb.model.KeyType;
+import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputExceededException;
+import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
+import software.amazon.awssdk.services.dynamodb.model.RequestLimitExceededException;
+import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
+import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
+import software.amazon.awssdk.services.dynamodb.model.TableStatus;
+import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
+
+/**
+ * DynamoDB implementation for the lock manager.
+ */
+public class DynamoDbLockManager extends LockManagers.BaseLockManager {
+
+  private static final Logger LOG = LoggerFactory.getLogger(DynamoDbLockManager.class);
+
+  private static final String COL_LOCK_ENTITY_ID = "entityId";
+  private static final String COL_LEASE_DURATION_MS = "leaseDurationMs";
+  private static final String COL_VERSION = "version";
+  private static final String COL_LOCK_OWNER_ID = "ownerId";
+
+  private static final String CONDITION_LOCK_ID_MATCH = String.format(
+      "%s = :eid AND %s = :oid",
+      COL_LOCK_ENTITY_ID, COL_LOCK_OWNER_ID);
+  private static final String CONDITION_LOCK_ENTITY_NOT_EXIST = String.format(
+      "attribute_not_exists(%s)",
+      COL_LOCK_ENTITY_ID);
+  private static final String CONDITION_LOCK_ENTITY_NOT_EXIST_OR_VERSION_MATCH = String.format(
+      "attribute_not_exists(%s) OR (%s = :eid AND %s = :vid)",
+      COL_LOCK_ENTITY_ID, COL_LOCK_ENTITY_ID, COL_VERSION);
+
+  private static final int LOCK_TABLE_CREATION_WAIT_ATTEMPTS_MAX = 5;
+  private static final int RELEASE_RETRY_ATTEMPTS_MAX = 5;
+
+  private static final List<KeySchemaElement> LOCK_TABLE_SCHEMA = Lists.newArrayList(
+      KeySchemaElement.builder()
+          .attributeName(COL_LOCK_ENTITY_ID)
+          .keyType(KeyType.HASH)
+          .build());
+
+  private static final List<AttributeDefinition> LOCK_TABLE_COL_DEFINITIONS = Lists.newArrayList(
+      AttributeDefinition.builder()
+          .attributeName(COL_LOCK_ENTITY_ID)
+          .attributeType(ScalarAttributeType.S)
+          .build());
+
+  private final Map<String, DynamoHeartbeat> heartbeats = Maps.newHashMap();
+
+  private DynamoDbClient dynamo;
+  private String lockTableName;
+
+  /**
+   * constructor for dynamic initialization, {@link #initialize(Map)} must be called later.
+   */
+  DynamoDbLockManager() {
+  }
+
+  /**
+   * constructor used for testing purpose
+   * @param dynamo dynamo client
+   * @param lockTableName lock table name
+   */
+  DynamoDbLockManager(DynamoDbClient dynamo, String lockTableName) {
+    super.initialize(Maps.newHashMap());
+    this.dynamo = dynamo;
+    this.lockTableName = lockTableName;
+    ensureLockTableExistsOrCreate();
+  }
+
+  private void ensureLockTableExistsOrCreate() {
+
+    if (tableExists(lockTableName)) {
+      return;
+    }
+
+    LOG.info("Dynamo lock table {} not found, trying to create", lockTableName);
+    dynamo.createTable(CreateTableRequest.builder()
+        .tableName(lockTableName)
+        .keySchema(lockTableSchema())
+        .attributeDefinitions(lockTableColDefinitions())
+        .billingMode(BillingMode.PAY_PER_REQUEST)
+        .build());
+
+    Tasks.foreach(lockTableName)
+        .retry(LOCK_TABLE_CREATION_WAIT_ATTEMPTS_MAX)
+        .throwFailureWhenFinished()
+        .onlyRetryOn(IllegalStateException.class)
+        .run(this::checkTableActive);
+  }
+
+  @VisibleForTesting
+  boolean tableExists(String tableName) {
+    try {
+      dynamo.describeTable(DescribeTableRequest.builder()
+          .tableName(tableName)
+          .build());
+      return true;
+    } catch (ResourceNotFoundException e) {
+      return false;
+    }
+  }
+
+  private void checkTableActive(String tableName) {
+    try {
+      DescribeTableResponse response = dynamo.describeTable(DescribeTableRequest.builder()
+          .tableName(tableName)
+          .build());
+      TableStatus currentStatus = response.table().tableStatus();
+      if (!currentStatus.equals(TableStatus.ACTIVE)) {
+        throw new IllegalStateException(String.format("Dynamo table %s is not active, current status: %s",
+            tableName, currentStatus));
+      }
+    } catch (ResourceNotFoundException e) {
+      throw new IllegalStateException(String.format("Cannot find Dynamo table %s", tableName));
+    }
+  }
+
+  @Override
+  public void initialize(Map<String, String> properties) {
+    super.initialize(properties);
+    this.dynamo = AwsClientFactories.from(properties).dynamo();
+    this.lockTableName = properties.get(CatalogProperties.LOCK_TABLE);
+    Preconditions.checkNotNull(lockTableName, "DynamoDB lock table name must not be null");
+    ensureLockTableExistsOrCreate();
+  }
+
+  @Override
+  public boolean acquire(String entityId, String ownerId) {
+    try {
+      Tasks.foreach(entityId)
+          .throwFailureWhenFinished()
+          .retry(Integer.MAX_VALUE - 1)
+          .exponentialBackoff(acquireIntervalMs(), acquireIntervalMs(), acquireTimeoutMs(), 1)
+          .onlyRetryOn(
+              ConditionalCheckFailedException.class,
+              ProvisionedThroughputExceededException.class,
+              TransactionConflictException.class,
+              RequestLimitExceededException.class,
+              InternalServerErrorException.class)
+          .run(id -> acquireOnce(id, ownerId));
+      return true;
+    } catch (DynamoDbException e) {
+      return false;
+    }
+  }
+
+  @VisibleForTesting
+  void acquireOnce(String entityId, String ownerId) {
+    GetItemResponse response = dynamo.getItem(GetItemRequest.builder()
+        .tableName(lockTableName)
+        .key(toKey(entityId))
+        .build());
+
+    if (!response.hasItem()) {
+      dynamo.putItem(PutItemRequest.builder()
+          .tableName(lockTableName)
+          .item(toNewItem(entityId, ownerId, heartbeatTimeoutMs()))
+          .conditionExpression(CONDITION_LOCK_ENTITY_NOT_EXIST)
+          .build());
+    } else {
+      Map<String, AttributeValue> currentItem = response.item();
+
+      try {
+        Thread.sleep(Long.parseLong(currentItem.get(COL_LEASE_DURATION_MS).n()));
+      } catch (InterruptedException e) {
+        throw new IllegalStateException(
+            String.format("Fail to acquire lock %s by %s, interrupted during sleep", entityId, ownerId), e);
+      }
+
+      dynamo.putItem(PutItemRequest.builder()
+          .tableName(lockTableName)
+          .item(toNewItem(entityId, ownerId, heartbeatTimeoutMs()))
+          .conditionExpression(CONDITION_LOCK_ENTITY_NOT_EXIST_OR_VERSION_MATCH)
+          .expressionAttributeValues(ImmutableMap.of(
+              ":eid", AttributeValue.builder().s(entityId).build(),
+              ":vid", AttributeValue.builder().s(currentItem.get(COL_VERSION).s()).build()))
+          .build());
+    }
+
+    startNewHeartbeat(entityId, ownerId);
+  }
+
+  private void startNewHeartbeat(String entityId, String ownerId) {
+    if (heartbeats.containsKey(entityId)) {
+      heartbeats.remove(entityId).cancel();
+    }
+
+    DynamoHeartbeat heartbeat = new DynamoHeartbeat(dynamo, lockTableName,
+        heartbeatIntervalMs(), heartbeatTimeoutMs(), entityId, ownerId);
+    heartbeat.schedule(scheduler());
+    heartbeats.put(entityId, heartbeat);
+  }
+
+  @Override
+  public boolean release(String entityId, String ownerId) {
+    boolean succeeded = false;
+    DynamoHeartbeat heartbeat = heartbeats.get(entityId);
+    try {
+      Tasks.foreach(entityId)
+          .retry(RELEASE_RETRY_ATTEMPTS_MAX)
+          .throwFailureWhenFinished()
+          .onlyRetryOn(
+              ProvisionedThroughputExceededException.class,
+              TransactionConflictException.class,
+              RequestLimitExceededException.class,
+              InternalServerErrorException.class)
+          .run(id -> dynamo.deleteItem(DeleteItemRequest.builder()
+              .tableName(lockTableName)
+              .key(toKey(id))
+              .conditionExpression(CONDITION_LOCK_ID_MATCH)
+              .expressionAttributeValues(toLockIdValues(id, ownerId))
+              .build()));
+      succeeded = true;
+    } catch (ConditionalCheckFailedException e) {
+      LOG.error("Failed to release lock for entity: {}, owner: {}, lock entity does not exist or owner not match",
+          entityId, ownerId, e);
+    } catch (DynamoDbException e) {
+      LOG.error("Failed to release lock {} by for entity: {}, owner: {}, encountered unexpected DynamoDB exception",
+          entityId, ownerId, e);
+    } finally {
+      if (heartbeat != null && heartbeat.ownerId().equals(ownerId)) {
+        heartbeat.cancel();
+      }
+    }
+
+    return succeeded;
+  }
+
+  private static Map<String, AttributeValue> toKey(String entityId) {
+    return ImmutableMap.of(COL_LOCK_ENTITY_ID, AttributeValue.builder().s(entityId).build());
+  }
+
+  private static Map<String, AttributeValue> toNewItem(String entityId, String ownerId, long heartbeatTimeoutMs) {
+    return ImmutableMap.of(
+        COL_LOCK_ENTITY_ID, AttributeValue.builder().s(entityId).build(),
+        COL_LOCK_OWNER_ID, AttributeValue.builder().s(ownerId).build(),
+        COL_VERSION, AttributeValue.builder().s(UUID.randomUUID().toString()).build(),
+        COL_LEASE_DURATION_MS, AttributeValue.builder().n(Long.toString(heartbeatTimeoutMs)).build());
+  }
+
+  private static Map<String, AttributeValue> toLockIdValues(String entityId, String ownerId) {
+    return ImmutableMap.of(
+        ":eid", AttributeValue.builder().s(entityId).build(),
+        ":oid", AttributeValue.builder().s(ownerId).build());
+  }
+
+  @Override
+  public void close() {
+    dynamo.close();
+    heartbeats.values().forEach(DynamoHeartbeat::cancel);
+    heartbeats.clear();
+  }
+
+  /**
+   * The lock table schema, for users who would like to create the table separately
+   * @return lock table schema
+   */
+  public static List<KeySchemaElement> lockTableSchema() {
+    return LOCK_TABLE_SCHEMA;
+  }
+
+  /**
+   * The lock table column definition, for users who whould like to create the table separately
+   * @return lock table column definition
+   */
+  public static List<AttributeDefinition> lockTableColDefinitions() {
+    return LOCK_TABLE_COL_DEFINITIONS;
+  }
+
+  private static class DynamoHeartbeat implements Runnable {

Review comment:
       updated

##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       my intention for doing that copy was to fully remove this class after 2 releases, and people who see this class can know it should not be used anymore. But extending also works, I don't have a strong opinion of which way is better.

##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       cool, I will update with the extending approach




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
rdblue commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805404589



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Why deprecate this if it wasn't public in the first place?
   
   Also, can this extend `DynamoDbLockManager` so that we don't have two implementations? Then we can also get rid of the tests here.




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jackye1995 commented on pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
jackye1995 commented on pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#issuecomment-1049047815


   Thanks @amogh-jahagirdar and @singhpk234 for the review, @rdblue let me know if you have any further concern and we can address accordingly.


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue edited a comment on pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
rdblue edited a comment on pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#issuecomment-1049198286


   +1 That sounds reasonable to me. Thanks, @jackye1995!


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jackye1995 commented on pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
jackye1995 commented on pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#issuecomment-1048562878


   @rdblue I have been thinking about this during the night, I think it's better to move this class to the `org.apache.iceberg.aws.dynamodb` module instead of keeping it as is.
   
   With the Glue optimistic locking change, I don't think any new user will use `org.apache.iceberg.aws.glue.DynamoLockManager`. The lock manager will only be for locking the file system of `HadoopCatalog` commits. It will be very confusing for those users to reference a DynamoDB lock in `glue` package, and it will be a lot of context for those users to understand. So thinking from those users' perspective, it is better for us to provide a clean package path for the DynamoDB lock manager.
   
   For existing users of `org.apache.iceberg.aws.glue.DynamoLockManager`, we are able to keep their experience using this and also see the warning message. I think this is the best path forward.


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
rdblue commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r806146547



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Are you sure there's much value in renaming Dynamo -> DynamoDb?




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
rdblue commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805434723



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       If this is already effectively public because people use it dynamically as their lock-impl, then I'd probably keep this instead of renaming. Or maybe have both names, but definitely not remove this unless it's absolutely necessary.




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] amogh-jahagirdar commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
amogh-jahagirdar commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r805405461



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Will let @jackye1995  confirm but I believe org.apache.iceberg.aws.glue.DynamoLockManager is public, users can pass it in as a locking implementation when creating a catalog.
   
   +1 to extending the DynamoDBLockManager

##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Will let @jackye1995  confirm but I believe org.apache.iceberg.aws.glue.DynamoLockManager is public, users can pass it in as a locking implementation when creating a catalog.
   
   +1 to extending the DynamoDBLockManager though

##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Will let @jackye1995  confirm but I believe org.apache.iceberg.aws.glue.DynamoLockManager is basically public, users can pass it in as a locking implementation when creating a catalog.
   
   +1 to extending the DynamoDBLockManager though




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
rdblue commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r806146547



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Are you sure there's much value in renaming Dynamo -> DynamoDb?




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jackye1995 commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
jackye1995 commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r807555105



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       The class path is already changing, so I thought it's better to make things consistent, as I said in the description
   
   > Note that the new class is DynamoDbLockManager instead of DynamoLockManager to follow DynamoDb prefix convention (because the new Dynamo client in AWS SDK v2 is named DynamoDbClient).
   
   but no strong opinion here. Any thoughts?




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] rdblue commented on a change in pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
rdblue commented on a change in pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#discussion_r808520201



##########
File path: aws/src/main/java/org/apache/iceberg/aws/glue/DynamoLockManager.java
##########
@@ -60,8 +60,9 @@
 import software.amazon.awssdk.services.dynamodb.model.TransactionConflictException;
 
 /**
- * DynamoDB implementation for the lock manager.
+ * @deprecated will be removed in 0.15.0, please use {@link org.apache.iceberg.aws.dynamodb.DynamoDbLockManager}
  */
+@Deprecated
 class DynamoLockManager extends LockManagers.BaseLockManager {

Review comment:
       Since this is something that people refer to directly already, I don't see much value in changing it. We can make the underlying classpath change transparent to users, so I'd probably opt to do that.




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jackye1995 merged pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
jackye1995 merged pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102


   


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] amogh-jahagirdar edited a comment on pull request #4102: AWS: make DynamoDbLockManager public

Posted by GitBox <gi...@apache.org>.
amogh-jahagirdar edited a comment on pull request #4102:
URL: https://github.com/apache/iceberg/pull/4102#issuecomment-1037023880


   Looks like the build is failing, some spacing issues and I think we need to explicitly mark the preivous class with 
   "@Deprecated". Other than that, looks good to me!


-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org