Will-Lo commented on code in PR #3715:
URL: https://github.com/apache/gobblin/pull/3715#discussion_r1267133044


##########
gobblin-runtime/src/test/java/org/apache/gobblin/runtime/api/MysqlMultiActiveLeaseArbiterTest.java:
##########
@@ -0,0 +1,145 @@
+/*
+ * 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.gobblin.runtime.api;
+
+import com.typesafe.config.Config;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.gobblin.config.ConfigBuilder;
+import org.apache.gobblin.configuration.ConfigurationKeys;
+import org.apache.gobblin.metastore.testing.ITestMetastoreDatabase;
+import org.apache.gobblin.metastore.testing.TestMetastoreDatabaseFactory;
+import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+
+@Slf4j
+public class MysqlMultiActiveLeaseArbiterTest {
+  private static final int EPSILON = 30000;
+  private static final int LINGER = 80000;
+  private static final String USER = "testUser";
+  private static final String PASSWORD = "testPassword";
+  private static final String TABLE = "mysql_multi_active_lease_arbiter_store";
+  private static final String flowGroup = "testFlowGroup";
+  private static final String flowName = "testFlowName";
+  private static final String flowExecutionId = "12345677";
+  private static DagActionStore.DagAction launchDagAction =
+      new DagActionStore.DagAction(flowGroup, flowName, flowExecutionId, 
DagActionStore.FlowActionType.LAUNCH);
+
+  private static final long eventTimeMillis = System.currentTimeMillis();
+  private MysqlMultiActiveLeaseArbiter mysqlMultiActiveLeaseArbiter;
+
+  // The setup functionality verifies that the initialization of the tables is 
done correctly and verifies any SQL
+  // syntax errors.
+  @BeforeClass
+  public void setUp() throws Exception {
+    ITestMetastoreDatabase testDb = TestMetastoreDatabaseFactory.get();
+
+    Config config = ConfigBuilder.create()
+        .addPrimitive(ConfigurationKeys.MYSQL_LEASE_ARBITER_PREFIX + "." + 
ConfigurationKeys.SCHEDULER_EVENT_EPSILON_MILLIS_KEY, EPSILON)
+        .addPrimitive(ConfigurationKeys.MYSQL_LEASE_ARBITER_PREFIX + "." + 
ConfigurationKeys.SCHEDULER_EVENT_LINGER_MILLIS_KEY, LINGER)
+        .addPrimitive(ConfigurationKeys.MYSQL_LEASE_ARBITER_PREFIX + "." + 
ConfigurationKeys.STATE_STORE_DB_URL_KEY, testDb.getJdbcUrl())
+        .addPrimitive(ConfigurationKeys.MYSQL_LEASE_ARBITER_PREFIX + "." + 
ConfigurationKeys.STATE_STORE_DB_USER_KEY, USER)
+        .addPrimitive(ConfigurationKeys.MYSQL_LEASE_ARBITER_PREFIX + "." + 
ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY, PASSWORD)
+        .addPrimitive(ConfigurationKeys.MYSQL_LEASE_ARBITER_PREFIX + "." + 
ConfigurationKeys.STATE_STORE_DB_TABLE_KEY, TABLE)
+        .build();
+
+    this.mysqlMultiActiveLeaseArbiter = new 
MysqlMultiActiveLeaseArbiter(config);
+  }
+
+  /*
+     Tests all cases of trying to acquire a lease (CASES 1-6 detailed below) 
for a flow action event with one
+     participant involved.
+  */
+  @Test
+  public void testAcquireLeaseSingleParticipant() throws Exception {
+    // Tests CASE 1 of acquire lease for a flow action event not present in DB
+    MultiActiveLeaseArbiter.LeaseAttemptStatus firstLaunchStatus =
+        mysqlMultiActiveLeaseArbiter.tryAcquireLease(launchDagAction, 
eventTimeMillis);
+    Assert.assertTrue(firstLaunchStatus instanceof 
MultiActiveLeaseArbiter.LeaseObtainedStatus);
+    MultiActiveLeaseArbiter.LeaseObtainedStatus firstObtainedStatus =
+        (MultiActiveLeaseArbiter.LeaseObtainedStatus) firstLaunchStatus;
+    Assert.assertTrue(firstObtainedStatus.getEventTimestamp() <=
+        firstObtainedStatus.getLeaseAcquisitionTimestamp());
+    Assert.assertTrue(firstObtainedStatus.getFlowAction().equals(
+        new DagActionStore.DagAction(flowGroup, flowName, flowExecutionId, 
DagActionStore.FlowActionType.LAUNCH)));
+
+    // Verify that different DagAction types for the same flow can have leases 
at the same time
+    DagActionStore.DagAction killDagAction = new
+        DagActionStore.DagAction(flowGroup, flowName, flowExecutionId, 
DagActionStore.FlowActionType.KILL);
+    MultiActiveLeaseArbiter.LeaseAttemptStatus killStatus =
+        mysqlMultiActiveLeaseArbiter.tryAcquireLease(killDagAction, 
eventTimeMillis);
+    Assert.assertTrue(killStatus instanceof 
MultiActiveLeaseArbiter.LeaseObtainedStatus);
+    MultiActiveLeaseArbiter.LeaseObtainedStatus killObtainedStatus =
+        (MultiActiveLeaseArbiter.LeaseObtainedStatus) killStatus;
+    Assert.assertTrue(
+        killObtainedStatus.getLeaseAcquisitionTimestamp() >= 
killObtainedStatus.getEventTimestamp());
+
+    // Tests CASE 2 of acquire lease for a flow action event that already has 
a valid lease for the same event in db

Review Comment:
   Does it make sense for us to have separate cases instead of combining these 
all into one super test? In case implementation details change in the future it 
will be easier to triage/isolate for certain cases.



##########
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/api/MysqlMultiActiveLeaseArbiter.java:
##########
@@ -219,84 +258,142 @@ else if (leaseValidityStatus == 2) {
         // Use our event to acquire lease, check for previous db 
eventTimestamp and leaseAcquisitionTimestamp
         String formattedAcquireLeaseIfMatchingAllStatement =
             
String.format(CONDITIONALLY_ACQUIRE_LEASE_IF_MATCHING_ALL_COLS_STATEMENT, 
this.leaseArbiterTableName);
-        ResultSet rs = withPreparedStatement(
-            formattedAcquireLeaseIfMatchingAllStatement + "; " + 
formattedSelectAfterInsertStatement,
-            updateStatement -> {
-              completeUpdatePreparedStatement(updateStatement, flowAction, 
eventTimeMillis, true,
+        int numRowsUpdated = 
withPreparedStatement(formattedAcquireLeaseIfMatchingAllStatement,
+            insertStatement -> {
+              completeUpdatePreparedStatement(insertStatement, flowAction, 
true,
                   true, dbEventTimestamp, dbLeaseAcquisitionTimestamp);
-              return updateStatement.executeQuery();
+              return insertStatement.executeUpdate();
             }, true);
-        return handleResultFromAttemptedLeaseObtainment(rs, flowAction, 
eventTimeMillis);
+        return evaluateStatusAfterLeaseAttempt(numRowsUpdated, flowAction, 
Optional.of(dbCurrentTimestamp));
       } // No longer leasing this event
-        // CASE 6: Same event, no longer leasing event in db: terminate
         if (isWithinEpsilon) {
+          log.debug("tryAcquireLease for [{}, eventTimestamp: {}] - CASE 5: 
Same event, no longer leasing event in db: "
+              + "terminate", flowAction, dbCurrentTimestamp.getTime());
           return new NoLongerLeasingStatus();
         }
-        // CASE 7: Distinct event, no longer leasing event in db
+        log.debug("tryAcquireLease for [{}, eventTimestamp: {}] - CASE 6: 
Distinct event, no longer leasing event in "
+            + "db", flowAction, dbCurrentTimestamp.getTime());
         // Use our event to acquire lease, check for previous db 
eventTimestamp and NULL leaseAcquisitionTimestamp
         String formattedAcquireLeaseIfFinishedStatement =
             
String.format(CONDITIONALLY_ACQUIRE_LEASE_IF_FINISHED_LEASING_STATEMENT, 
this.leaseArbiterTableName);
-        ResultSet rs = withPreparedStatement(
-            formattedAcquireLeaseIfFinishedStatement + "; " + 
formattedSelectAfterInsertStatement,
-            updateStatement -> {
-              completeUpdatePreparedStatement(updateStatement, flowAction, 
eventTimeMillis, true,
+        int numRowsUpdated = 
withPreparedStatement(formattedAcquireLeaseIfFinishedStatement,
+            insertStatement -> {
+              completeUpdatePreparedStatement(insertStatement, flowAction, 
true,
                   false, dbEventTimestamp, null);
-              return updateStatement.executeQuery();
+              return insertStatement.executeUpdate();
             }, true);
-        return handleResultFromAttemptedLeaseObtainment(rs, flowAction, 
eventTimeMillis);
+        return evaluateStatusAfterLeaseAttempt(numRowsUpdated, flowAction, 
Optional.of(dbCurrentTimestamp));
     } catch (SQLException e) {
       throw new RuntimeException(e);
     }
   }
 
+  protected GetEventInfoResult createGetInfoResult(ResultSet resultSet) throws 
IOException {
+    try {
+      // Extract values from result set
+      Timestamp dbEventTimestamp = resultSet.getTimestamp("event_timestamp");
+      Timestamp dbLeaseAcquisitionTimestamp = 
resultSet.getTimestamp("lease_acquisition_timestamp");
+      boolean withinEpsilon = resultSet.getBoolean("is_within_epsilon");
+      int leaseValidityStatus = resultSet.getInt("lease_validity_status");
+      int dbLinger = resultSet.getInt("linger");
+      Timestamp dbCurrentTimestamp = 
resultSet.getTimestamp("CURRENT_TIMESTAMP");
+      return new GetEventInfoResult(dbEventTimestamp, 
dbLeaseAcquisitionTimestamp, withinEpsilon, leaseValidityStatus,
+          dbLinger, dbCurrentTimestamp);
+    } catch (SQLException e) {
+      throw new IOException(e);
+    } finally {
+      if (resultSet != null) {
+        try {
+          resultSet.close();
+        } catch (SQLException e) {
+          throw new IOException(e);
+        }
+      }
+    }
+  }
+
+  protected SelectInfoResult createSelectInfoResult(ResultSet resultSet) 
throws IOException {
+      try {
+        if (!resultSet.next()) {
+          log.error("Expected num rows and lease_acquisition_timestamp 
returned from query but received nothing");

Review Comment:
   I'm confused here, so if there's no item after in the result set we log and 
error but still try to parse the current result set results?



##########
gobblin-runtime/src/main/java/org/apache/gobblin/runtime/api/MysqlMultiActiveLeaseArbiter.java:
##########
@@ -136,81 +150,106 @@ public MysqlMultiActiveLeaseArbiter(Config config) 
throws IOException {
         ConfigurationKeys.DEFAULT_SCHEDULER_EVENT_EPSILON_MILLIS);
     this.linger = ConfigUtils.getInt(config, 
ConfigurationKeys.SCHEDULER_EVENT_LINGER_MILLIS_KEY,
         ConfigurationKeys.DEFAULT_SCHEDULER_EVENT_LINGER_MILLIS);
+    this.thisTableGetInfoStatement = String.format(GET_EVENT_INFO_STATEMENT, 
this.leaseArbiterTableName,
+        this.constantsTableName);
+    this.thisTableSelectAfterInsertStatement = 
String.format(SELECT_AFTER_INSERT_STATEMENT, this.leaseArbiterTableName,
+        this.constantsTableName);
     this.dataSource = MysqlDataSourceFactory.get(config, 
SharedResourcesBrokerFactory.getImplicitBroker());
+    String createArbiterStatement = String.format(
+        CREATE_LEASE_ARBITER_TABLE_STATEMENT, leaseArbiterTableName);
     try (Connection connection = dataSource.getConnection();
-        PreparedStatement createStatement = 
connection.prepareStatement(String.format(
-            CREATE_LEASE_ARBITER_TABLE_STATEMENT, leaseArbiterTableName))) {
+        PreparedStatement createStatement = 
connection.prepareStatement(createArbiterStatement)) {
       createStatement.executeUpdate();
       connection.commit();
     } catch (SQLException e) {
       throw new IOException("Table creation failure for " + 
leaseArbiterTableName, e);
     }
-    withPreparedStatement(String.format(CREATE_CONSTANTS_TABLE_STATEMENT, 
this.constantsTableName, this.constantsTableName),
-        createStatement -> {
+    initializeConstantsTable();
+
+    log.info("MysqlMultiActiveLeaseArbiter initialized");
+  }
+
+  // Initialize Constants table if needed and insert row into it if one does 
not exist
+  private void initializeConstantsTable() throws IOException {
+    String createConstantsStatement = 
String.format(CREATE_CONSTANTS_TABLE_STATEMENT, this.constantsTableName);
+    withPreparedStatement(createConstantsStatement, createStatement -> 
createStatement.executeUpdate(), true);
+
+    String insertConstantsStatement = 
String.format(UPSERT_CONSTANTS_TABLE_STATEMENT, this.constantsTableName);
+    withPreparedStatement(insertConstantsStatement, insertStatement -> {
       int i = 0;
-      createStatement.setInt(++i, epsilon);
-      createStatement.setInt(++i, linger);
-      return createStatement.executeUpdate();}, true);
+      insertStatement.setInt(++i, epsilon);
+      insertStatement.setInt(++i, linger);
+      return insertStatement.executeUpdate();
+    }, true);
   }
 
   @Override
   public LeaseAttemptStatus tryAcquireLease(DagActionStore.DagAction 
flowAction, long eventTimeMillis)
       throws IOException {
     // Check table for an existing entry for this flow action and event time
-    ResultSet resultSet = withPreparedStatement(
-        String.format(GET_EVENT_INFO_STATEMENT, this.leaseArbiterTableName, 
this.constantsTableName),
+    Optional<GetEventInfoResult> getResult = 
withPreparedStatement(thisTableGetInfoStatement,
         getInfoStatement -> {
           int i = 0;
-          getInfoStatement.setTimestamp(++i, new Timestamp(eventTimeMillis));
           getInfoStatement.setString(++i, flowAction.getFlowGroup());
           getInfoStatement.setString(++i, flowAction.getFlowName());
           getInfoStatement.setString(++i, flowAction.getFlowExecutionId());
           getInfoStatement.setString(++i, 
flowAction.getFlowActionType().toString());
-          return getInfoStatement.executeQuery();
+          ResultSet resultSet = getInfoStatement.executeQuery();
+          try {
+            if (!resultSet.next()) {
+              return Optional.absent();
+            }
+            return Optional.of(createGetInfoResult(resultSet));
+          } finally {
+            if (resultSet !=  null) {
+              resultSet.close();
+            }
+          }
         }, true);
 
-    String formattedSelectAfterInsertStatement =
-        String.format(SELECT_AFTER_INSERT_STATEMENT, 
this.leaseArbiterTableName, this.constantsTableName);
     try {
-      // CASE 1: If no existing row for this flow action, then go ahead and 
insert
-      if (!resultSet.next()) {
+      if (!getResult.isPresent()) {
+        log.debug("tryAcquireLease for [{}, eventTimestamp: {}] - CASE 1: no 
existing row for this flow action, then go"
+                + " ahead and insert", flowAction, eventTimeMillis);
         String formattedAcquireLeaseNewRowStatement =
             String.format(CONDITIONALLY_ACQUIRE_LEASE_IF_NEW_ROW_STATEMENT, 
this.leaseArbiterTableName);
-        ResultSet rs = withPreparedStatement(
-            formattedAcquireLeaseNewRowStatement + "; " + 
formattedSelectAfterInsertStatement,
+        int numRowsUpdated = 
withPreparedStatement(formattedAcquireLeaseNewRowStatement,
             insertStatement -> {
-              completeInsertPreparedStatement(insertStatement, flowAction, 
eventTimeMillis);
-              return insertStatement.executeQuery();
+              completeInsertPreparedStatement(insertStatement, flowAction);
+              return insertStatement.executeUpdate();
             }, true);
-       return handleResultFromAttemptedLeaseObtainment(rs, flowAction, 
eventTimeMillis);
+       return evaluateStatusAfterLeaseAttempt(numRowsUpdated, flowAction, 
Optional.absent());
       }
 
       // Extract values from result set
-      Timestamp dbEventTimestamp = resultSet.getTimestamp("event_timestamp");
-      Timestamp dbLeaseAcquisitionTimestamp = 
resultSet.getTimestamp("lease_acquisition_timestamp");
-      boolean isWithinEpsilon = resultSet.getBoolean("isWithinEpsilon");
-      int leaseValidityStatus = resultSet.getInt("leaseValidityStatus");
-      int dbLinger = resultSet.getInt("linger");
+      Timestamp dbEventTimestamp = getResult.get().getDbEventTimestamp();
+      Timestamp dbLeaseAcquisitionTimestamp = 
getResult.get().getDbLeaseAcquisitionTimestamp();
+      boolean isWithinEpsilon = getResult.get().isWithinEpsilon();
+      int leaseValidityStatus = getResult.get().getLeaseValidityStatus();
+      int dbLinger = getResult.get().getDbLinger();

Review Comment:
   Can we add a comment what dbLinger is used for



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to