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 2023/01/05 00:43:42 UTC

[GitHub] [iceberg] szehon-ho commented on a diff in pull request #6451: Hive: Lock hardening

szehon-ho commented on code in PR #6451:
URL: https://github.com/apache/iceberg/pull/6451#discussion_r1061980018


##########
hive-metastore/src/main/java/org/apache/iceberg/hive/HiveTableOperations.java:
##########
@@ -759,6 +812,98 @@ private static boolean hiveEngineEnabled(TableMetadata metadata, Configuration c
         ConfigProperties.ENGINE_HIVE_ENABLED, TableProperties.ENGINE_HIVE_ENABLED_DEFAULT);
   }
 
+  @SuppressWarnings("ReverseDnsLookup")
+  private void tryLock(
+      String agentInfo, AtomicReference<Long> lockId, AtomicReference<LockState> state)
+      throws UnknownHostException, TException {
+    final LockComponent lockComponent =
+        new LockComponent(LockType.EXCLUSIVE, LockLevel.TABLE, database);
+    lockComponent.setTablename(tableName);
+    final LockRequest lockRequest =
+        new LockRequest(
+            Lists.newArrayList(lockComponent),
+            System.getProperty("user.name"),
+            InetAddress.getLocalHost().getHostName());
+
+    // Only works in Hive 2 or later.
+    if (MetastoreClientVersion.min(MetastoreClientVersion.HIVE_2)) {
+      lockRequest.setAgentInfo(agentInfo);
+    }
+
+    Tasks.foreach(lockRequest)
+        .retry(Integer.MAX_VALUE - 100)
+        .exponentialBackoff(
+            lockCreationMinWaitTime, lockCreationMaxWaitTime, lockCreationTimeout, 2.0)
+        .shouldRetryTest(
+            e ->
+                e instanceof TException
+                    && MetastoreClientVersion.min(MetastoreClientVersion.HIVE_2))
+        .throwFailureWhenFinished()
+        .run(
+            request -> {
+              try {
+                LockResponse lockResponse = metaClients.run(client -> client.lock(request));
+                lockId.set(lockResponse.getLockid());
+                state.set(lockResponse.getState());
+              } catch (TException te) {
+                LOG.warn("Failed to acquire lock {}", request, te);
+                try {
+                  // If we can not check for lock, or we do not find it, then rethrow the exception
+                  // Otherwise we are happy as the findLock sets the lockId and the state correctly
+                  if (!MetastoreClientVersion.min(MetastoreClientVersion.HIVE_2)
+                      || !findLock(agentInfo, lockId, state)) {
+                    throw te;
+                  } else {
+                    LOG.info(
+                        "Found lock by agentInfo {} with id {} and state {}",
+                        agentInfo,
+                        lockId,
+                        state);
+                  }
+                } catch (InterruptedException e) {
+                  Thread.currentThread().interrupt();
+                  LOG.warn(
+                      "Interrupted while checking for lock on table {}.{}", database, tableName, e);
+                  throw new RuntimeException("Interrupted while checking for lock", e);
+                }
+              } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+                LOG.warn("Interrupted while acquiring lock on table {}.{}", database, tableName, e);
+                throw new RuntimeException("Interrupted while acquiring lock", e);
+              }
+            },
+            TException.class);
+  }
+
+  /**
+   * Search for the locks using HMSClient.showLocks identified by the agentInfo. If the lock is
+   * there, then the lockId and the state is set based on the result.
+   *
+   * @param agentInfo The key for searching the locks
+   * @param lockId The lockId if the lock has found
+   * @param state The state if the lock has found
+   * @return <code>true</code> if the the lock is there <code>false</code> if the lock is missing
+   */
+  private boolean findLock(
+      String agentInfo, AtomicReference<Long> lockId, AtomicReference<LockState> state)
+      throws TException, InterruptedException {
+    ShowLocksRequest showLocksRequest = new ShowLocksRequest();
+    showLocksRequest.setDbname(database);
+    showLocksRequest.setTablename(tableName);
+    ShowLocksResponse response = metaClients.run(client -> client.showLocks(showLocksRequest));
+    for (ShowLocksResponseElement lock : response.getLocks()) {
+      if (lock.getAgentInfo().equals(agentInfo)) {

Review Comment:
   Should there be a Hive2+ check here?



##########
hive-metastore/src/main/java/org/apache/iceberg/hive/HiveTableOperations.java:
##########
@@ -699,18 +717,53 @@ private void cleanupMetadataAndUnlock(
     } catch (RuntimeException e) {
       LOG.error("Failed to cleanup metadata file at {}", metadataLocation, e);
     } finally {
-      unlock(lockId);
+      unlock(lockId, agentInfo);
       tableLevelMutex.unlock();
     }
   }
 
-  private void unlock(Optional<Long> lockId) {
-    if (lockId.isPresent()) {
-      try {
-        doUnlock(lockId.get());
-      } catch (Exception e) {
-        LOG.warn("Failed to unlock {}.{}", database, tableName, e);
+  private void unlock(Optional<Long> lockId, String agentInfo) {
+    Long id = null;
+    try {
+      if (!lockId.isPresent()) {
+        // Try to find the lock based on agentInfo. Only works with Hive 2 or later.
+        if (MetastoreClientVersion.min(MetastoreClientVersion.HIVE_2)) {
+          AtomicReference<Long> foundLockId = new AtomicReference<>();
+          AtomicReference<LockState> state = new AtomicReference<>();
+          if (!findLock(agentInfo, foundLockId, state)) {

Review Comment:
   Style: same, would prefer findLock to return a LockInfo if it finds a lock, or null if it cannot find it.



##########
hive-metastore/src/main/java/org/apache/iceberg/hive/MetastoreClientVersion.java:
##########
@@ -0,0 +1,65 @@
+/*
+ * 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.hive;
+
+import org.apache.hive.common.util.HiveVersionInfo;
+
+public enum MetastoreClientVersion {
+  HIVE_4(4),
+  HIVE_3(3),
+  HIVE_2(2),
+  HIVE_1_2(1),
+  NOT_SUPPORTED(0);
+
+  private final int order;
+  private static final MetastoreClientVersion current = calculate();
+
+  MetastoreClientVersion(int order) {
+    this.order = order;
+  }
+
+  public static MetastoreClientVersion current() {
+    return current;
+  }
+
+  public static boolean min(MetastoreClientVersion other) {
+    return current.order >= other.order;
+  }
+
+  private static MetastoreClientVersion calculate() {
+    String version = HiveVersionInfo.getShortVersion();
+    String[] versions = version.split("\\.");
+    switch (versions[0]) {
+      case "4":
+        return HIVE_4;
+      case "3":
+        return HIVE_3;
+      case "2":
+        return HIVE_2;
+      case "1":
+        if (versions[1].equals("2")) {
+          return HIVE_1_2;
+        } else {
+          return NOT_SUPPORTED;

Review Comment:
   Why are we explicitly not-supporting versions lesser than Hive 1.2 now?  I don't think there was any checks   previously to throw an exception for this case.  Anyway, we are protecting the agentInfo code around Hive 2 check



##########
hive-metastore/src/main/java/org/apache/iceberg/hive/HiveTableOperations.java:
##########
@@ -606,20 +630,13 @@ private StorageDescriptor storageDescriptor(TableMetadata metadata, boolean hive
     return storageDescriptor;
   }
 
-  @SuppressWarnings("ReverseDnsLookup")
   @VisibleForTesting
-  long acquireLock() throws UnknownHostException, TException, InterruptedException {
-    final LockComponent lockComponent =
-        new LockComponent(LockType.EXCLUSIVE, LockLevel.TABLE, database);
-    lockComponent.setTablename(tableName);
-    final LockRequest lockRequest =
-        new LockRequest(
-            Lists.newArrayList(lockComponent),
-            System.getProperty("user.name"),
-            InetAddress.getLocalHost().getHostName());
-    LockResponse lockResponse = metaClients.run(client -> client.lock(lockRequest));
-    AtomicReference<LockState> state = new AtomicReference<>(lockResponse.getState());
-    long lockId = lockResponse.getLockid();
+  long acquireLock(String agentInfo) throws UnknownHostException, TException, InterruptedException {
+    AtomicReference<Long> lockId = new AtomicReference<>();
+    AtomicReference<LockState> state = new AtomicReference<>();
+
+    // This will set the lockId and state if successful
+    tryLock(agentInfo, lockId, state);

Review Comment:
   Style Preference: would be great to do it more functional style, and have the method return a LockInfo class of (lockId, state), rather than having the arguments mutated which is harder to keep track.



##########
hive-metastore/src/main/java/org/apache/iceberg/hive/HiveTableOperations.java:
##########
@@ -699,18 +717,53 @@ private void cleanupMetadataAndUnlock(
     } catch (RuntimeException e) {
       LOG.error("Failed to cleanup metadata file at {}", metadataLocation, e);
     } finally {
-      unlock(lockId);
+      unlock(lockId, agentInfo);
       tableLevelMutex.unlock();
     }
   }
 
-  private void unlock(Optional<Long> lockId) {
-    if (lockId.isPresent()) {
-      try {
-        doUnlock(lockId.get());
-      } catch (Exception e) {
-        LOG.warn("Failed to unlock {}.{}", database, tableName, e);
+  private void unlock(Optional<Long> lockId, String agentInfo) {
+    Long id = null;
+    try {
+      if (!lockId.isPresent()) {
+        // Try to find the lock based on agentInfo. Only works with Hive 2 or later.
+        if (MetastoreClientVersion.min(MetastoreClientVersion.HIVE_2)) {
+          AtomicReference<Long> foundLockId = new AtomicReference<>();
+          AtomicReference<LockState> state = new AtomicReference<>();
+          if (!findLock(agentInfo, foundLockId, state)) {
+            // No lock found
+            LOG.info("No lock found with {} agentInfo", agentInfo);
+            return;
+          }
+
+          id = foundLockId.get();
+        } else {
+          LOG.warn("Could not find lock with HMSClient {}", MetastoreClientVersion.current());
+          return;
+        }
+      } else {
+        id = lockId.get();
+      }
+
+      doUnlock(id);
+    } catch (InterruptedException ie) {
+      if (id != null) {

Review Comment:
   Is this just to handle interrupt for unlock?  I'm not sure I see how its related to the rest of the change, I would think if anything here, we should be checking TException for unlock and try unlock again, synonomous with tryLock?



-- 
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