You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@helix.apache.org by jx...@apache.org on 2023/08/28 23:51:58 UTC
[helix] branch master updated (792f21162 -> 2e53694f7)
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
from 792f21162 [apache/helix] -- Fixes #2590 Removed resetting of the missingTopStatePartitionsBeyondThresholdGauge to avoid incorrect accounting.
new ff4c5cadd DataRecord Serializer
new df1eb6ae9 Inline
new b93f89a06 tests for get, create, set, update, and data change listeners
new 1f80503b6 deserialize test
new b45361ba3 refactor, update with dataRecord
new 17f8ab3fd set test iteration count to 500
new 09649b34c [helix/metaclient] ZkMetaClient Stress Tests (Part 2) (#2523)
new 0e917599c MetaClient Distributed Semaphore API and Permit object (#2520)
new 53f9fa7c3 Add API for getDataAndStat (#2535)
new c7a0d28fc Lattice MetaClient Distributed Semaphore Implementation (#2515)
new f41a2c606 MetaClient LockClient and Semaphore Creation Edge Cases and Added Exception(#2550)
new 6aa7c2cce ZkClient - only register one time watcher for read data when not using persist listener. (#2555)
new 5389b1739 MultiThreading Stress Test Lattice - Puppy Logic and Skeleton (Part 1) (#2549)
new 36231faeb Metaclient leader election - basics (#2558)
new b1f59e6f8 Multithreading stress test lattice - CRUD puppies and Listener Tests (#2548)
new 52fe73818 Metaclient - Leader election - Track participants and add participant info (#2562)
new 4eacde331 Metaclient - Leader election - leader change event notification (#2560)
new 26f319608 Lattice LockClient LockInfoSerializer Implementation(#2580)
new c3afa7f27 Lattice Puppy Stress Test Race Condition Fix and Code Cleanup (#2579)
new 7a96d9ba8 Add stress test for Metaclient leader election (#2574)
new 2e53694f7 Leader election client - Proactively send leader gone event when disconnect from ZK (#2585)
The 21 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../helix/metaclient/api/MetaClientInterface.java | 19 +-
.../org/apache/helix/metaclient/api/OpResult.java | 2 +-
.../helix/metaclient/datamodel/DataRecord.java | 5 +
...ion.java => MetaClientNodeExistsException.java} | 11 +-
.../helix/metaclient/impl/zk/ZkMetaClient.java | 73 ++--
.../impl/zk/adapter/DataListenerAdapter.java | 1 +
.../metaclient/impl/zk/util/ZkMetaClientUtil.java | 12 +
.../leaderelection/LeaderElectionClient.java | 318 ++++++++++++--
.../LeaderElectionListenerInterface.java | 15 +-
.../LeaderElectionListenerInterfaceAdapter.java | 64 +++
.../recipes/leaderelection/LeaderInfo.java | 34 +-
.../leaderelection/LeaderInfoSerializer.java | 42 ++
.../recipes/lock/DataRecordSerializer.java | 19 +-
.../recipes/lock/DistributedSemaphore.java | 248 +++++++++++
.../helix/metaclient/recipes/lock/LockClient.java | 19 +-
.../helix/metaclient/recipes/lock/LockInfo.java | 30 +-
.../recipes/lock/LockInfoSerializer.java | 26 +-
.../helix/metaclient/recipes/lock/Permit.java | 87 ++++
.../helix/metaclient/MetaClientTestUtil.java | 25 ++
.../zk/TestConnectStateChangeListenerAndRetry.java | 42 +-
.../zk/TestMultiThreadStressTest/CreatePuppy.java | 77 ++++
.../zk/TestMultiThreadStressTest/DeletePuppy.java | 67 +++
.../zk/TestMultiThreadStressTest/GetPuppy.java | 67 +++
.../zk/TestMultiThreadStressTest/SetPuppy.java | 70 ++++
.../TestMultiThreadStressZKClient.java | 350 ++++++++++++++++
.../zk/TestMultiThreadStressTest/UpdatePuppy.java | 73 ++++
.../metaclient/impl/zk/TestStressZkClient.java | 455 ++++++++++++++++++++-
.../apache/helix/metaclient/impl/zk/TestUtil.java | 92 +++++
.../helix/metaclient/impl/zk/TestZkMetaClient.java | 50 +++
.../metaclient/impl/zk/ZkMetaClientTestBase.java | 2 +
.../helix/metaclient/puppy/AbstractPuppy.java | 91 +++++
.../apache/helix/metaclient/puppy/ExecDelay.java | 63 +++
.../helix/metaclient/puppy/PuppyManager.java | 64 +++
.../apache/helix/metaclient/puppy/PuppyMode.java | 10 +-
.../apache/helix/metaclient/puppy/PuppySpec.java | 42 +-
.../leaderelection/LeaderElectionPuppy.java | 92 +++++
.../recipes/leaderelection/TestLeaderElection.java | 361 ++++++++++++++++
.../TestMultiClientLeaderElection.java | 85 ++++
.../recipes/lock/DistributedSemaphoreTest.java | 105 +++++
.../metaclient/recipes/lock/LockClientTest.java | 36 +-
.../datamodel/serializer/ZNRecordSerializer.java | 2 +-
.../apache/helix/zookeeper/zkclient/ZkClient.java | 2 +-
.../zkclient/TestZkClientPersistWatcher.java | 75 ++--
43 files changed, 3184 insertions(+), 239 deletions(-)
copy meta-client/src/main/java/org/apache/helix/metaclient/exception/{MetaClientTimeoutException.java => MetaClientNodeExistsException.java} (75%)
create mode 100644 meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterfaceAdapter.java
create mode 100644 meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderInfoSerializer.java
copy helix-core/src/main/java/org/apache/helix/healthcheck/ParticipantHealthReportCollector.java => meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DataRecordSerializer.java (70%)
create mode 100644 meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java
copy helix-core/src/main/java/org/apache/helix/store/ZNRecordJsonSerializer.java => meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockInfoSerializer.java (60%)
create mode 100644 meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/Permit.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/MetaClientTestUtil.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/CreatePuppy.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/DeletePuppy.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/GetPuppy.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/SetPuppy.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/TestMultiThreadStressZKClient.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/UpdatePuppy.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/puppy/ExecDelay.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppyManager.java
copy helix-core/src/main/java/org/apache/helix/controller/stages/package-info.java => meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppyMode.java (86%)
copy helix-core/src/main/java/org/apache/helix/monitoring/StateTransitionDataPoint.java => meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppySpec.java (54%)
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionPuppy.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestMultiClientLeaderElection.java
create mode 100644 meta-client/src/test/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphoreTest.java
[helix] 17/21: Metaclient - Leader election - leader change event notification (#2560)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 4eacde3312265e5184708f59641451bccb649ca0
Author: xyuanlu <xy...@gmail.com>
AuthorDate: Sat Jul 22 22:39:37 2023 -0700
Metaclient - Leader election - leader change event notification (#2560)
Co-authored-by: Xiaoyuan Lu <xi...@xialu-mn2.linkedin.biz>
---
.../impl/zk/adapter/DataListenerAdapter.java | 1 +
.../leaderelection/LeaderElectionClient.java | 4 +-
.../LeaderElectionListenerInterface.java | 15 ++-
.../LeaderElectionListenerInterfaceAdapter.java | 43 +++++++
.../zk/TestConnectStateChangeListenerAndRetry.java | 3 +-
.../recipes/leaderelection/TestLeaderElection.java | 135 ++++++++++++++++++++-
.../helix/zookeeper/zkclient/ZkConnection.java | 1 -
7 files changed, 193 insertions(+), 9 deletions(-)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/DataListenerAdapter.java b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/DataListenerAdapter.java
index 94ae198ce..748b6ed3f 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/DataListenerAdapter.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/adapter/DataListenerAdapter.java
@@ -21,6 +21,7 @@ package org.apache.helix.metaclient.impl.zk.adapter;
import org.apache.helix.metaclient.api.DataChangeListener;
import org.apache.helix.zookeeper.zkclient.IZkDataListener;
+import org.apache.helix.zookeeper.zkclient.annotation.PreFetchChangedData;
import org.apache.zookeeper.Watcher;
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
index 39233e979..7b13778c0 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
@@ -334,7 +334,8 @@ public class LeaderElectionClient implements AutoCloseable {
* @return A boolean value indicating if registration is success.
*/
public boolean subscribeLeadershipChanges(String leaderPath, LeaderElectionListenerInterface listener) {
- //TODO: add converter class for LeaderElectionListenerInterface
+ _metaClient.subscribeDataChange(leaderPath + LEADER_ENTRY_KEY, new LeaderElectionListenerInterfaceAdapter(listener),
+ false);
return false;
}
@@ -343,6 +344,7 @@ public class LeaderElectionClient implements AutoCloseable {
* @param listener An implementation of LeaderElectionListenerInterface
*/
public void unsubscribeLeadershipChanges(String leaderPath, LeaderElectionListenerInterface listener) {
+ _metaClient.unsubscribeDataChange(leaderPath + LEADER_ENTRY_KEY, new LeaderElectionListenerInterfaceAdapter(listener));
}
@Override
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterface.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterface.java
index 0436e1eb0..230fc2af1 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterface.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterface.java
@@ -24,9 +24,16 @@ package org.apache.helix.metaclient.recipes.leaderelection;
* leader node is deleted.
*/
public interface LeaderElectionListenerInterface {
+ enum ChangeType {
+ LEADER_ACQUIRED,
+ LEADER_LOST
+ }
+
// When new leader is elected:
- // noLeader (null) -> has leader (new leader name)
- // When existing leader not leader anymore:
- // has Leader (prevleader name) -> no leader (null)
- public void onLeadershipChange(String leaderPath, String prevLeader, String curLeader);
+ // ChangeType == NEW_LEADER_ELECTED, curLeader is the new leader name
+ // When no leader anymore:
+ // ChangeType == LEADER_GONE, curLeader is an empty string
+ // In ZK implementation, since notification does not include changed data and metaclient fetches
+ // the entry when event comes, it is possible that
+ public void onLeadershipChange(String leaderPath, ChangeType type, String curLeader);
}
\ No newline at end of file
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterfaceAdapter.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterfaceAdapter.java
new file mode 100644
index 000000000..5c64d6790
--- /dev/null
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterfaceAdapter.java
@@ -0,0 +1,43 @@
+package org.apache.helix.metaclient.recipes.leaderelection;
+
+import org.apache.helix.metaclient.api.DataChangeListener;
+
+import static org.apache.helix.metaclient.recipes.leaderelection.LeaderElectionListenerInterface.ChangeType.*;
+
+
+public class LeaderElectionListenerInterfaceAdapter implements DataChangeListener {
+ private final LeaderElectionListenerInterface _leaderElectionListener;
+
+ public LeaderElectionListenerInterfaceAdapter(LeaderElectionListenerInterface leaderElectionListener) {
+ _leaderElectionListener = leaderElectionListener;
+ }
+
+ @Override
+ public void handleDataChange(String key, Object data, ChangeType changeType) throws Exception {
+ switch (changeType) {
+ case ENTRY_CREATED:
+ String newLeader = ((LeaderInfo) data).getLeaderName();
+ _leaderElectionListener.onLeadershipChange(key, LEADER_ACQUIRED, newLeader);
+ break;
+ case ENTRY_DELETED:
+ _leaderElectionListener.onLeadershipChange(key, LEADER_LOST, "");
+ }
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ LeaderElectionListenerInterfaceAdapter that = (LeaderElectionListenerInterfaceAdapter) o;
+ return _leaderElectionListener.equals(that._leaderElectionListener);
+ }
+
+ @Override
+ public int hashCode() {
+ return _leaderElectionListener.hashCode();
+ }
+}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java
index 36b9b2131..c74b7d7ef 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java
@@ -162,7 +162,8 @@ public class TestConnectStateChangeListenerAndRetry {
zkMetaClient.create("/key", "value");
Assert.fail("Create call after close should throw IllegalStateException");
} catch (Exception ex) {
- Assert.assertTrue(ex.getCause() instanceof IllegalStateException);
+ System.out.println("ex " + ex);
+ Assert.assertTrue(ex instanceof IllegalStateException);
}
}
System.out.println("END TestConnectStateChangeListenerAndRetry.testConnectStateChangeListener at " + new Date(System.currentTimeMillis()));
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
index 412ecaf8b..b0b396c1a 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
@@ -2,6 +2,8 @@ package org.apache.helix.metaclient.recipes.leaderelection;
import java.util.ConcurrentModificationException;
import org.apache.helix.metaclient.MetaClientTestUtil;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.helix.metaclient.factories.MetaClientConfig;
import org.apache.helix.metaclient.impl.zk.ZkMetaClient;
import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase;
@@ -26,12 +28,14 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
@Test
public void testAcquireLeadership() throws Exception {
+ String leaderPath = LEADER_PATH + "testAcquireLeadership";
+
// create 2 clients representing 2 participants
LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
- clt1.joinLeaderElectionParticipantPool(LEADER_PATH);
- clt2.joinLeaderElectionParticipantPool(LEADER_PATH);
+ clt1.joinLeaderElectionParticipantPool(leaderPath);
+ clt2.joinLeaderElectionParticipantPool(leaderPath);
// First client joining the leader election group should be current leader
Assert.assertTrue(MetaClientTestUtil.verify(() -> {
return (clt1.getLeader(LEADER_PATH) != null);
@@ -139,4 +143,131 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
}
+ @Test (dependsOnMethods = "testAcquireLeadership")
+ public void testLeadershipListener() throws Exception {
+ String leaderPath = LEADER_PATH + "testLeadershipListener";
+ // create 2 clients representing 2 participants
+ LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
+ LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
+ LeaderElectionClient clt3 = createLeaderElectionClient(PARTICIPANT_NAME2);
+
+ final int count = 10;
+ final int[] numNewLeaderEvent = {0};
+ final int[] numLeaderGoneEvent = {0};
+ CountDownLatch countDownLatchNewLeader = new CountDownLatch(count*2);
+ CountDownLatch countDownLatchLeaderGone = new CountDownLatch(count*2);
+
+ LeaderElectionListenerInterface listener = new LeaderElectionListenerInterface() {
+
+ @Override
+ public void onLeadershipChange(String leaderPath, ChangeType type, String curLeader) {
+ if (type == ChangeType.LEADER_LOST) {
+ countDownLatchLeaderGone.countDown();
+ Assert.assertEquals(curLeader.length(), 0);
+ numLeaderGoneEvent[0]++;
+ } else if (type == ChangeType.LEADER_ACQUIRED) {
+ countDownLatchNewLeader.countDown();
+ numNewLeaderEvent[0]++;
+ Assert.assertTrue(curLeader.length()!=0);
+ } else {
+ Assert.fail();
+ }
+ }
+ };
+
+ clt3.subscribeLeadershipChanges(leaderPath, listener);
+
+ // each iteration will be participant_1 is new leader, leader gone, participant_2 is new leader, leader gone
+ for (int i=0; i<count; ++i) {
+ joinPoolTestHelper(leaderPath, clt1, clt2);
+ Thread.sleep(1000);
+ }
+
+ Assert.assertTrue(countDownLatchNewLeader.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS));
+ Assert.assertTrue(countDownLatchLeaderGone.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS));
+ Assert.assertEquals(numLeaderGoneEvent[0], count*2);
+ Assert.assertEquals(numNewLeaderEvent[0], count*2);
+
+ clt3.unsubscribeLeadershipChanges(leaderPath, listener);
+
+ // listener shouldn't receive any event after unsubscribe
+ joinPoolTestHelper(leaderPath, clt1, clt2);
+ Assert.assertEquals(numLeaderGoneEvent[0], count*2);
+ Assert.assertEquals(numNewLeaderEvent[0], count*2);
+
+ clt1.close();
+ clt2.close();
+ clt3.close();
+ }
+
+ private void joinPoolTestHelper(String leaderPath, LeaderElectionClient clt1, LeaderElectionClient clt2) throws Exception {
+ clt1.joinLeaderElectionParticipantPool(leaderPath);
+ clt2.joinLeaderElectionParticipantPool(leaderPath);
+
+ Thread.sleep(2000);
+
+ // clt1 gone
+ clt1.exitLeaderElectionParticipantPool(leaderPath);
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (clt1.getLeader(leaderPath) != null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (clt1.getLeader(leaderPath).equals(PARTICIPANT_NAME2));
+ }, MetaClientTestUtil.WAIT_DURATION));
+
+ clt2.exitLeaderElectionParticipantPool(leaderPath);
+
+ }
+
+ @Test (dependsOnMethods = "testLeadershipListener")
+ public void testRelinquishLeadership() throws Exception {
+ String leaderPath = LEADER_PATH + "testRelinquishLeadership";
+ LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
+ LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
+ LeaderElectionClient clt3 = createLeaderElectionClient(PARTICIPANT_NAME2);
+
+
+ final int count = 1;
+ CountDownLatch countDownLatchNewLeader = new CountDownLatch(count);
+ CountDownLatch countDownLatchLeaderGone = new CountDownLatch(count);
+
+ LeaderElectionListenerInterface listener = new LeaderElectionListenerInterface() {
+
+ @Override
+ public void onLeadershipChange(String leaderPath, ChangeType type, String curLeader) {
+ if (type == ChangeType.LEADER_LOST) {
+ countDownLatchLeaderGone.countDown();
+ Assert.assertEquals(curLeader.length(), 0);
+ } else if (type == ChangeType.LEADER_ACQUIRED) {
+ countDownLatchNewLeader.countDown();
+ Assert.assertTrue(curLeader.length()!=0);
+ } else {
+ Assert.fail();
+ }
+ }
+ };
+
+ clt1.joinLeaderElectionParticipantPool(leaderPath);
+ clt2.joinLeaderElectionParticipantPool(leaderPath);
+ clt3.subscribeLeadershipChanges(leaderPath, listener);
+ // clt1 gone
+ clt1.relinquishLeader(leaderPath);
+
+ // participant 1 should have gone, and a leader gone event is sent
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (clt1.getLeader(leaderPath) != null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+ Assert.assertTrue(countDownLatchLeaderGone.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS));
+
+ clt1.exitLeaderElectionParticipantPool(leaderPath);
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (clt1.getLeader(leaderPath) != null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (clt1.getLeader(leaderPath).equals(PARTICIPANT_NAME2));
+ }, MetaClientTestUtil.WAIT_DURATION));
+
+ clt2.exitLeaderElectionParticipantPool(leaderPath);
+ }
+
}
diff --git a/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkConnection.java b/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkConnection.java
index 589425462..376409231 100644
--- a/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkConnection.java
+++ b/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkConnection.java
@@ -260,7 +260,6 @@ public class ZkConnection implements IZkConnection {
private void lookupGetChildrenMethod() {
_getChildrenMethod = doLookUpGetChildrenMethod();
- System.out.println(" ZkSystemPropertyKeys.ZK_GETCHILDREN_PAGINATION_DISABLED " + GETCHILDREN_PAGINATION_DISABLED);
LOG.info("Pagination config {}={}, method to be invoked: {}",
ZkSystemPropertyKeys.ZK_GETCHILDREN_PAGINATION_DISABLED, GETCHILDREN_PAGINATION_DISABLED,
_getChildrenMethod.getName());
[helix] 02/21: Inline
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit df1eb6ae92e086676d22adda2f39ed43c2fbf8c7
Author: mapeng <ma...@linkedin.com>
AuthorDate: Fri Jun 2 13:59:35 2023 -0400
Inline
---
.../org/apache/helix/metaclient/recipes/lock/DataRecordSerializer.java | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DataRecordSerializer.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DataRecordSerializer.java
index 6fee7bdea..bf7806327 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DataRecordSerializer.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DataRecordSerializer.java
@@ -26,7 +26,6 @@ import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer;
public class DataRecordSerializer extends ZNRecordSerializer {
@Override
public Object deserialize(byte[] bytes) {
- Object o = super.deserialize(bytes);
- return new DataRecord((ZNRecord) o);
+ return new DataRecord((ZNRecord) super.deserialize(bytes));
}
}
[helix] 04/21: deserialize test
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 1f80503b675f0b4bb916ccd29e9f4bc84c8ed5b0
Author: Grant Palau Spencer <gs...@linkedin.com>
AuthorDate: Sat Jun 3 10:06:19 2023 -0700
deserialize test
---
.../metaclient/impl/zk/TestStressZkClient.java | 140 ++++++++++++---------
1 file changed, 79 insertions(+), 61 deletions(-)
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
index 3e7140f64..4b541ba74 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
@@ -29,8 +29,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.helix.metaclient.api.DataChangeListener;
import org.apache.helix.metaclient.api.DataUpdater;
import org.apache.helix.metaclient.api.MetaClientInterface;
+import org.apache.helix.metaclient.datamodel.DataRecord;
import org.apache.helix.metaclient.exception.MetaClientException;
import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig;
+import org.apache.helix.zookeeper.datamodel.ZNRecord;
+import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer;
import org.apache.helix.zookeeper.exception.ZkClientException;
import org.testng.Assert;
import org.slf4j.Logger;
@@ -43,23 +46,6 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
private static final long TEST_ITERATION_COUNT = 1000;
private static final Logger LOG = LoggerFactory.getLogger(TestStressZkClient.class);
- private void cleanUpTestNodes(String parentZnodeKey) {
- try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
- zkMetaClient.connect();
- int retryCount = 0;
- while (zkMetaClient.countDirectChildren(parentZnodeKey) > 0) {
- try {
- retryCount++;
- zkMetaClient.recursiveDelete(parentZnodeKey);
- } catch (ZkClientException e) {
- if (retryCount >= 3) {
- throw new ZkClientException("Failed to clean up test nodes after 3 tries", e);
- }
- }
- }
- Assert.assertEquals(zkMetaClient.countDirectChildren(parentZnodeKey), 0);
- }
- }
@Test
public void testCreate() {
@@ -92,7 +78,10 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
} catch (Exception ignoredException) {
}
}
- cleanUpTestNodes(zkParentKey);
+
+ // cleanup
+ zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
}
}
@@ -111,7 +100,9 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
Assert.assertEquals(String.valueOf(zkMetaClient.get(zkParentKey + "/" + i)), String.valueOf(i));
}
- cleanUpTestNodes(zkParentKey);
+ // cleanup
+ zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
}
}
@@ -142,8 +133,11 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
} catch (Exception ignoredException) {
}
}
+
+ // cleanup
+ zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
}
- cleanUpTestNodes(zkParentKey);
}
@Test
@@ -212,9 +206,11 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
} catch (Exception ignoredException) {
}
}
- }
- cleanUpTestNodes(zkParentKey);
+ // cleanup
+ zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
+ }
}
@Test
@@ -251,8 +247,11 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
Assert.assertEquals(zkMetaClient.get(childKey), String.valueOf(i));
Assert.assertEquals(entryStat.getVersion(), 2);
}
+
+ // cleanup
+ zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
}
- cleanUpTestNodes(zkParentKey);
}
@Test
@@ -260,59 +259,72 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
final String zkParentKey = "/stressZk_testUpdateSingleNode";
ZkMetaClientConfig config =
new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR).build();
- try (ZkMetaClient<Integer> zkMetaClient = new ZkMetaClient<>(config)) {
+ try (ZkMetaClient<byte[]> zkMetaClient = new ZkMetaClient<>(config)) {
zkMetaClient.connect();
- zkMetaClient.create(zkParentKey, 0);
+ ZNRecord record = new ZNRecord("foo");
+ record.setIntField("key", 0);
+ ZNRecordSerializer serializer = new ZNRecordSerializer();
+ zkMetaClient.create(zkParentKey, serializer.serialize(record));
+
for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
MetaClientInterface.Stat entryStat = zkMetaClient.exists(zkParentKey);
Assert.assertEquals(entryStat.getVersion(), i);
- Integer newData = zkMetaClient.update(zkParentKey, new DataUpdater<Integer>() {
+ byte[] newData = zkMetaClient.update(zkParentKey, new DataUpdater<byte[]>() {
@Override
- public Integer update(Integer currentData) {
- return currentData + 1;
+ public byte[] update(byte[] currentData) {
+ ZNRecordSerializer serializer = new ZNRecordSerializer();
+ ZNRecord record = (ZNRecord) serializer.deserialize(currentData);
+ int value = record.getIntField("key", 0);
+ record.setIntField("key", value + 1);
+ return serializer.serialize(record);
}
});
- Assert.assertEquals((int) newData, i + 1);
+ ZNRecord newRecord = (ZNRecord) serializer.deserialize(newData);
+ Assert.assertEquals(newRecord.getIntField("key", 0), i+1);
}
- zkMetaClient.delete(zkParentKey);
- zkMetaClient.create(zkParentKey, "parent_node");
- // Set with path to non-existent node - should fail
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- try {
- zkMetaClient.update("/a/b/c", new DataUpdater<Integer>() {
- @Override
- public Integer update(Integer currentData) {
- return currentData + 1;
- }
- });
+// zkMetaClient.delete(zkParentKey);
+// zkMetaClient.create(zkParentKey, "parent_node");
- Assert.fail("Should have failed due to path to non-existent node");
- } catch (Exception ignoredException) {
- }
- }
+// Set with path to non-existent node - should fail
+// for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+// try {
+// zkMetaClient.update("/a/b/c", new DataUpdater<Integer>() {
+// @Override
+// public Integer update(Integer currentData) {
+// return currentData + 1;
+// }
+// });
+//
+// Assert.fail("Should have failed due to path to non-existent node");
+// } catch (Exception ignoredException) {
+// }
+// }
- zkMetaClient.delete(zkParentKey);
- zkMetaClient.create(zkParentKey, "parent_node");
+// zkMetaClient.delete(zkParentKey);
+// zkMetaClient.create(zkParentKey, "parent_node");
// Set with invalid path - should fail
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- try {
- zkMetaClient.update("/a/b/c", new DataUpdater<Integer>() {
- @Override
- public Integer update(Integer currentData) {
- return currentData + 1;
- }
- });
- Assert.fail("Should have failed due to invalid path - no leading /.");
- } catch (Exception ignoredException) {
- }
- }
+// for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+// try {
+// zkMetaClient.update("/a/b/c", new DataUpdater<Integer>() {
+// @Override
+// public Integer update(Integer currentData) {
+// return currentData + 1;
+// }
+// });
+// Assert.fail("Should have failed due to invalid path - no leading /.");
+// } catch (Exception ignoredException) {
+// }
+// }
+
+ // cleanup
+ zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
}
- cleanUpTestNodes(zkParentKey);
}
@Test
@@ -344,8 +356,11 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
entryStat = zkMetaClient.exists(childKey);
Assert.assertEquals(entryStat.getVersion(), 1);
}
+
+ // cleanup
+ zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
}
- cleanUpTestNodes(zkParentKey);
}
@Test
@@ -388,7 +403,10 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
Assert.assertTrue(countDownLatch.await(5000, TimeUnit.MILLISECONDS));
Assert.assertTrue(dataExpected.get());
+
+ // cleanup
+ zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
}
- cleanUpTestNodes(zkParentKey);
}
}
\ No newline at end of file
[helix] 06/21: set test iteration count to 500
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 17f8ab3fd167023e3b3e7e8c8bcffaf8c7e3e243
Author: Grant Palau Spencer <gs...@linkedin.com>
AuthorDate: Mon Jun 5 10:52:30 2023 -0700
set test iteration count to 500
---
.../java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
index 5706dec7d..393a17f1b 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
@@ -48,7 +48,7 @@ import static org.apache.helix.metaclient.api.MetaClientInterface.EntryMode.*;
public class TestStressZkClient extends ZkMetaClientTestBase {
private ZkMetaClient<String> _zkMetaClient;
- private static final long TEST_ITERATION_COUNT = 10;
+ private static final long TEST_ITERATION_COUNT = 500;
@BeforeTest
private void setUp() {
[helix] 16/21: Metaclient - Leader election - Track participants and add participant info (#2562)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 52fe73818d9be5b493888943da58d2e763c8a5be
Author: xyuanlu <xy...@gmail.com>
AuthorDate: Sat Jul 22 21:45:29 2023 -0700
Metaclient - Leader election - Track participants and add participant info (#2562)
Co-authored-by: Xiaoyuan Lu <xi...@xialu-mn2.linkedin.biz>
---
.../helix/metaclient/impl/zk/ZkMetaClient.java | 2 -
.../leaderelection/LeaderElectionClient.java | 132 ++++++++++++++++-----
.../{TestUtil.java => MetaClientTestUtil.java} | 7 +-
.../apache/helix/metaclient/impl/zk/TestUtil.java | 68 +++++++++++
.../recipes/leaderelection/TestLeaderElection.java | 104 ++++++++++++++--
5 files changed, 266 insertions(+), 47 deletions(-)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
index 691f31cde..8753747f3 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
@@ -57,14 +57,12 @@ import org.apache.helix.zookeeper.impl.client.ZkClient;
import org.apache.helix.zookeeper.zkclient.IZkStateListener;
import org.apache.helix.zookeeper.zkclient.ZkConnection;
import org.apache.helix.zookeeper.zkclient.exception.ZkException;
-import org.apache.helix.zookeeper.zkclient.exception.ZkInterruptedException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static org.apache.helix.metaclient.impl.zk.util.ZkMetaClientUtil.convertZkEntryModeToMetaClientEntryMode;
import static org.apache.helix.metaclient.impl.zk.util.ZkMetaClientUtil.translateZkExceptionToMetaclientException;
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
index d5bdb735a..39233e979 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
@@ -21,11 +21,14 @@ package org.apache.helix.metaclient.recipes.leaderelection;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.helix.metaclient.api.ConnectStateChangeListener;
import org.apache.helix.metaclient.api.DataChangeListener;
import org.apache.helix.metaclient.api.MetaClientInterface;
import org.apache.helix.metaclient.api.Op;
@@ -34,6 +37,7 @@ import org.apache.helix.metaclient.exception.MetaClientException;
import org.apache.helix.metaclient.exception.MetaClientNoNodeException;
import org.apache.helix.metaclient.exception.MetaClientNodeExistsException;
import org.apache.helix.metaclient.factories.MetaClientConfig;
+import org.apache.helix.metaclient.impl.zk.ZkMetaClient;
import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig;
import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientFactory;
import org.slf4j.Logger;
@@ -68,8 +72,13 @@ public class LeaderElectionClient implements AutoCloseable {
// A list of leader election group that this client joins.
private Set<String> _leaderGroups = new HashSet<>();
+ private Map<String, LeaderInfo> _participantInfos = new HashMap<>();
+
private final static String LEADER_ENTRY_KEY = "/LEADER";
+ private final static String PARTICIPANTS_ENTRY_KEY = "/PARTICIPANTS";
+ private final static String PARTICIPANTS_ENTRY_PARENT = "/PARTICIPANTS/";
ReElectListener _reElectListener = new ReElectListener();
+ ConnectStateListener _connectStateListener = new ConnectStateListener();
/**
* Construct a LeaderElectionClient using a user passed in leaderElectionConfig. It creates a MetaClient
@@ -90,6 +99,7 @@ public class LeaderElectionClient implements AutoCloseable {
metaClientConfig.getConnectionAddress()).setZkSerializer((new LeaderInfoSerializer())).build();
_metaClient = new ZkMetaClientFactory().getMetaClient(zkMetaClientConfig);
_metaClient.connect();
+ _metaClient.subscribeStateChanges(_connectStateListener);
} else {
throw new MetaClientException("Unsupported store type: " + metaClientConfig.getStoreType());
}
@@ -121,8 +131,8 @@ public class LeaderElectionClient implements AutoCloseable {
* @throws RuntimeException if the operation is not succeeded.
*/
public void joinLeaderElectionParticipantPool(String leaderPath) {
- // TODO: create participant entry
subscribeAndTryCreateLeaderEntry(leaderPath);
+ createParticipantInfo(leaderPath, new LeaderInfo(_participant));
}
/**
@@ -134,8 +144,40 @@ public class LeaderElectionClient implements AutoCloseable {
* @throws RuntimeException if the operation is not succeeded.
*/
public void joinLeaderElectionParticipantPool(String leaderPath, LeaderInfo userInfo) {
- // TODO: create participant entry with info
subscribeAndTryCreateLeaderEntry(leaderPath);
+
+ LeaderInfo participantInfo = new LeaderInfo(userInfo);
+ createParticipantInfo(leaderPath, participantInfo);
+ }
+
+ private void createParticipantInfo(String leaderPath, LeaderInfo participantInfo) {
+ _participantInfos.put(leaderPath, participantInfo);
+
+ createPathIfNotExists(leaderPath + PARTICIPANTS_ENTRY_KEY);
+
+ try {
+ // try to create participant info entry, assuming leader election group node is already there
+ _metaClient.create(leaderPath + PARTICIPANTS_ENTRY_PARENT + _participant, participantInfo,
+ MetaClientInterface.EntryMode.EPHEMERAL);
+ } catch (MetaClientNodeExistsException ex) {
+ throw new ConcurrentModificationException("Already joined leader election group. ", ex);
+ } catch (MetaClientNoNodeException ex) {
+ // Leader group root entry or participant parent entry is gone after we checked or created.
+ // Meaning other client removed the group. Throw ConcurrentModificationException.
+ throw new ConcurrentModificationException(
+ "Other client trying to modify the leader election group at the same time, please retry.", ex);
+ }
+ }
+
+ private void createPathIfNotExists(String path) {
+ if (_metaClient.exists(path) == null) {
+ LOG.info("{} Creating leader group directory {}.", _participant, path);
+ try {
+ _metaClient.create(path, null);
+ } catch (MetaClientNodeExistsException ignore) {
+ LOG.info("Leader election group root path already created: path {}.", path);
+ }
+ }
}
private void subscribeAndTryCreateLeaderEntry(String leaderPath) {
@@ -144,30 +186,19 @@ public class LeaderElectionClient implements AutoCloseable {
leaderInfo.setLeaderName(_participant);
try {
+ createPathIfNotExists(leaderPath);
+ } catch (MetaClientNoNodeException e) {
+ // Parent entry missed in root path.
+ throw new MetaClientException("Parent entry in leaderGroup path" + leaderPath + " does not exist.");
+ }
+
+ // create actual leader node
+ try {
+ LOG.info("{} joining leader group {}.", _participant, leaderPath);
// try to create leader entry, assuming leader election group node is already there
_metaClient.create(leaderPath + LEADER_ENTRY_KEY, leaderInfo, MetaClientInterface.EntryMode.EPHEMERAL);
} catch (MetaClientNodeExistsException ex) {
- LOG.info("Already a leader for group {}", leaderPath);
- } catch (MetaClientNoNodeException ex) {
- try {
- // try to create leader path root entry
- _metaClient.create(leaderPath, null);
- } catch (MetaClientNodeExistsException ignored) {
- // root entry created by other client, ignore
- } catch (MetaClientNoNodeException e) {
- // Parent entry of user provided leader election group path missing.
- // (e.g. `/a/b` not created in user specified leader election group path /a/b/c/LeaderGroup)
- throw new MetaClientException("Parent entry in leaderGroup path" + leaderPath + " does not exist.");
- }
- try {
- // try to create leader node again.
- _metaClient.create(leaderPath + LEADER_ENTRY_KEY, leaderInfo, MetaClientInterface.EntryMode.EPHEMERAL);
- } catch (MetaClientNoNodeException e) {
- // Leader group root entry is gone after we checked at outer catch block.
- // Meaning other client removed the group. Throw ConcurrentModificationException.
- throw new ConcurrentModificationException(
- "Other client trying to modify the leader election group at the same time, please retry.", ex);
- }
+ LOG.info("Already a leader in leader group {}.", leaderPath);
}
_leaderGroups.add(leaderPath + LEADER_ENTRY_KEY);
@@ -222,6 +253,7 @@ public class LeaderElectionClient implements AutoCloseable {
// deleting ZNode. So that handler in ReElectListener won't recreate the leader node.
if (exitLeaderElectionParticipantPool) {
_leaderGroups.remove(leaderPath + LEADER_ENTRY_KEY);
+ _metaClient.delete(leaderPath + PARTICIPANTS_ENTRY_PARENT + _participant);
}
// check if current participant is the leader
// read data and stats, check, and multi check + delete
@@ -250,13 +282,23 @@ public class LeaderElectionClient implements AutoCloseable {
* @throws RuntimeException when leader path does not exist. // TODO: define exp type
*/
public String getLeader(String leaderPath) {
+
LeaderInfo leaderInfo = _metaClient.get(leaderPath + LEADER_ENTRY_KEY);
return leaderInfo == null ? null : leaderInfo.getLeaderName();
}
- public LeaderInfo getParticipantInfo(String leaderPath) {
- // TODO: add getParticipantInfo impl
- return null;
+ /**
+ * Get current leader.
+ *
+ * @param leaderPath The path for leader election.
+ * @return Returns a LeaderInfo entry. Return null if participant is not in the pool.
+ * */
+ public LeaderInfo getParticipantInfo(String leaderPath, String participant) {
+ return _metaClient.get(leaderPath + PARTICIPANTS_ENTRY_PARENT + participant);
+ }
+
+ public MetaClientInterface.Stat getLeaderEntryStat(String leaderPath) {
+ return _metaClient.exists(leaderPath + LEADER_ENTRY_KEY);
}
/**
@@ -271,7 +313,11 @@ public class LeaderElectionClient implements AutoCloseable {
* @throws RuntimeException when leader path does not exist. // TODO: define exp type
*/
public List<String> getParticipants(String leaderPath) {
- return null;
+ try {
+ return _metaClient.getDirectChildrenKeys(leaderPath + PARTICIPANTS_ENTRY_KEY);
+ } catch (MetaClientNoNodeException ex) {
+ throw new MetaClientException("No leader election group create for path " + leaderPath, ex);
+ }
}
/**
@@ -302,6 +348,8 @@ public class LeaderElectionClient implements AutoCloseable {
@Override
public void close() throws Exception {
+ _metaClient.unsubscribeConnectStateChanges(_connectStateListener);
+
// exit all previous joined leader election groups
for (String leaderGroup : _leaderGroups) {
String leaderGroupPathName =
@@ -318,19 +366,43 @@ public class LeaderElectionClient implements AutoCloseable {
@Override
public void handleDataChange(String key, Object data, ChangeType changeType) throws Exception {
if (changeType == ChangeType.ENTRY_CREATED) {
- LOG.info("new leader {} for leader election group {}.", ((LeaderInfo) data).getLeaderName(), key);
+ LOG.info("new leader for leader election group {}.", key);
} else if (changeType == ChangeType.ENTRY_DELETED) {
if (_leaderGroups.contains(key)) {
LeaderInfo lf = new LeaderInfo("LEADER");
lf.setLeaderName(_participant);
try {
+ LOG.info("Leader gone for group {}, {} try to reelect.", key, _participant);
_metaClient.create(key, lf, MetaClientInterface.EntryMode.EPHEMERAL);
} catch (MetaClientNodeExistsException ex) {
- LOG.info("Already a leader {} for leader election group {}.", ((LeaderInfo) data).getLeaderName(), key);
+ LOG.info("Already a leader for leader election group {}.", key);
}
}
}
}
}
-}
+ class ConnectStateListener implements ConnectStateChangeListener {
+
+ @Override
+ public void handleConnectStateChanged(MetaClientInterface.ConnectState prevState,
+ MetaClientInterface.ConnectState currentState) throws Exception {
+ if (prevState == MetaClientInterface.ConnectState.EXPIRED
+ && currentState == MetaClientInterface.ConnectState.CONNECTED) {
+ for (String leaderPath : _participantInfos.keySet()) {
+ _metaClient.create(leaderPath + PARTICIPANTS_ENTRY_PARENT + _participant, _participantInfos.get(leaderPath),
+ MetaClientInterface.EntryMode.EPHEMERAL);
+ }
+ }
+ }
+
+ @Override
+ public void handleConnectionEstablishmentError(Throwable error) throws Exception {
+
+ }
+ }
+
+ public MetaClientInterface getMetaClient() {
+ return _metaClient;
+ }
+}
\ No newline at end of file
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/TestUtil.java b/meta-client/src/test/java/org/apache/helix/metaclient/MetaClientTestUtil.java
similarity index 75%
rename from meta-client/src/test/java/org/apache/helix/metaclient/TestUtil.java
rename to meta-client/src/test/java/org/apache/helix/metaclient/MetaClientTestUtil.java
index 9b20c8e53..2c7543e31 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/TestUtil.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/MetaClientTestUtil.java
@@ -1,7 +1,10 @@
package org.apache.helix.metaclient;
-public class TestUtil {
- public static final long WAIT_DURATION = 6 * 1000L;
+import java.util.concurrent.TimeUnit;
+
+
+public class MetaClientTestUtil {
+ public static final long WAIT_DURATION = TimeUnit.MINUTES.toMicros(1);
public interface Verifier {
boolean verify()
throws Exception;
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestUtil.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestUtil.java
index 1296a72f3..fbf1ab1f3 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestUtil.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestUtil.java
@@ -25,11 +25,17 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import org.apache.helix.zookeeper.api.client.HelixZkClient;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
+import org.apache.helix.zookeeper.zkclient.IZkStateListener;
import org.apache.helix.zookeeper.zkclient.ZkClient;
import org.apache.helix.zookeeper.zkclient.ZkConnection;
+import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
+import org.testng.Assert;
public class TestUtil {
@@ -93,4 +99,66 @@ public class TestUtil {
return lists;
}
+
+ public static void expireSession(ZkMetaClient client)
+ throws Exception {
+ final CountDownLatch waitNewSession = new CountDownLatch(1);
+ final ZkClient zkClient = client.getZkClient();
+
+ IZkStateListener listener = new IZkStateListener() {
+ @Override
+ public void handleStateChanged(Watcher.Event.KeeperState state)
+ throws Exception {
+ }
+
+ @Override
+ public void handleNewSession(final String sessionId)
+ throws Exception {
+ // make sure zkclient is connected again
+ zkClient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.SECONDS);
+
+ waitNewSession.countDown();
+ }
+
+ @Override
+ public void handleSessionEstablishmentError(Throwable var1)
+ throws Exception {
+ }
+ };
+
+ zkClient.subscribeStateChanges(listener);
+
+ ZkConnection connection = ((ZkConnection) zkClient.getConnection());
+ ZooKeeper curZookeeper = connection.getZookeeper();
+ String oldSessionId = Long.toHexString(curZookeeper.getSessionId());
+
+ Watcher watcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ }
+ };
+
+ final ZooKeeper dupZookeeper =
+ new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher,
+ curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
+ // wait until connected, then close
+ while (dupZookeeper.getState() != ZooKeeper.States.CONNECTED) {
+ Thread.sleep(10);
+ }
+ Assert.assertEquals(dupZookeeper.getState(), ZooKeeper.States.CONNECTED,
+ "Fail to connect to zk using current session info");
+ dupZookeeper.close();
+
+ // make sure session expiry really happens
+ waitNewSession.await();
+ zkClient.unsubscribeStateChanges(listener);
+
+ connection = (ZkConnection) zkClient.getConnection();
+ curZookeeper = connection.getZookeeper();
+
+ String newSessionId = Long.toHexString(curZookeeper.getSessionId());
+ Assert.assertFalse(newSessionId.equals(oldSessionId),
+ "Fail to expire current session, zk: " + curZookeeper);
+ }
+
}
\ No newline at end of file
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
index 3a45d97ce..412ecaf8b 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
@@ -1,11 +1,15 @@
package org.apache.helix.metaclient.recipes.leaderelection;
-import org.apache.helix.metaclient.TestUtil;
+import java.util.ConcurrentModificationException;
+import org.apache.helix.metaclient.MetaClientTestUtil;
import org.apache.helix.metaclient.factories.MetaClientConfig;
+import org.apache.helix.metaclient.impl.zk.ZkMetaClient;
import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase;
import org.testng.Assert;
import org.testng.annotations.Test;
+import static org.apache.helix.metaclient.impl.zk.TestUtil.*;
+
public class TestLeaderElection extends ZkMetaClientTestBase {
@@ -15,8 +19,8 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
public LeaderElectionClient createLeaderElectionClient(String participantName) {
MetaClientConfig.StoreType storeType = MetaClientConfig.StoreType.ZOOKEEPER;
- MetaClientConfig config = new MetaClientConfig.MetaClientConfigBuilder<>().setConnectionAddress(ZK_ADDR)
- .setStoreType(storeType).build();
+ MetaClientConfig config =
+ new MetaClientConfig.MetaClientConfigBuilder<>().setConnectionAddress(ZK_ADDR).setStoreType(storeType).build();
return new LeaderElectionClient(config, participantName);
}
@@ -29,31 +33,31 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
clt1.joinLeaderElectionParticipantPool(LEADER_PATH);
clt2.joinLeaderElectionParticipantPool(LEADER_PATH);
// First client joining the leader election group should be current leader
- Assert.assertTrue(TestUtil.verify(() -> {
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
return (clt1.getLeader(LEADER_PATH) != null);
- }, TestUtil.WAIT_DURATION));
+ }, MetaClientTestUtil.WAIT_DURATION));
Assert.assertNotNull(clt1.getLeader(LEADER_PATH));
Assert.assertEquals(clt1.getLeader(LEADER_PATH), clt2.getLeader(LEADER_PATH));
Assert.assertEquals(clt1.getLeader(LEADER_PATH), PARTICIPANT_NAME1);
// client 1 exit leader election group, and client 2 should be current leader.
clt1.exitLeaderElectionParticipantPool(LEADER_PATH);
- Assert.assertTrue(TestUtil.verify(() -> {
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
return (clt1.getLeader(LEADER_PATH) != null);
- }, TestUtil.WAIT_DURATION));
- Assert.assertTrue(TestUtil.verify(() -> {
+ }, MetaClientTestUtil.WAIT_DURATION));
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
return (clt1.getLeader(LEADER_PATH).equals(PARTICIPANT_NAME2));
- }, TestUtil.WAIT_DURATION));
+ }, MetaClientTestUtil.WAIT_DURATION));
// client1 join and client2 leave. client 1 should be leader.
clt1.joinLeaderElectionParticipantPool(LEADER_PATH);
clt2.exitLeaderElectionParticipantPool(LEADER_PATH);
- Assert.assertTrue(TestUtil.verify(() -> {
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
return (clt1.getLeader(LEADER_PATH) != null);
- }, TestUtil.WAIT_DURATION));
- Assert.assertTrue(TestUtil.verify(() -> {
+ }, MetaClientTestUtil.WAIT_DURATION));
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
return (clt1.getLeader(LEADER_PATH).equals(PARTICIPANT_NAME1));
- }, TestUtil.WAIT_DURATION));
+ }, MetaClientTestUtil.WAIT_DURATION));
Assert.assertTrue(clt1.isLeader(LEADER_PATH));
Assert.assertFalse(clt2.isLeader(LEADER_PATH));
@@ -61,4 +65,78 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
clt2.close();
}
+ @Test
+ public void testElectionPoolMembership() throws Exception {
+ String leaderPath = LEADER_PATH + "/testElectionPoolMembership";
+ LeaderInfo participantInfo = new LeaderInfo(PARTICIPANT_NAME1);
+ participantInfo.setSimpleField("Key1", "value1");
+ LeaderInfo participantInfo2 = new LeaderInfo(PARTICIPANT_NAME2);
+ participantInfo2.setSimpleField("Key2", "value2");
+ LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
+ LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
+
+ clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo);
+ try {
+ clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo); // no op
+ } catch (ConcurrentModificationException ex) {
+ // expected
+ Assert.assertEquals(ex.getClass().getName(), "java.util.ConcurrentModificationException");
+ }
+ clt2.joinLeaderElectionParticipantPool(leaderPath, participantInfo2);
+
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (clt1.getLeader(leaderPath) != null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+ Assert.assertNotNull(clt1.getLeaderEntryStat(leaderPath));
+ Assert.assertNotNull(clt1.getLeader(leaderPath));
+ Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1");
+ Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1");
+ Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
+ Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
+
+ // clt1 gone
+ clt1.relinquishLeader(leaderPath);
+ clt1.exitLeaderElectionParticipantPool(leaderPath);
+ clt2.exitLeaderElectionParticipantPool(leaderPath);
+
+ Assert.assertNull(clt2.getParticipantInfo(LEADER_PATH, PARTICIPANT_NAME2));
+ }
+
+ @Test
+ public void testSessionExpire() throws Exception {
+ String leaderPath = LEADER_PATH + "/testSessionExpire";
+ LeaderInfo participantInfo = new LeaderInfo(PARTICIPANT_NAME1);
+ participantInfo.setSimpleField("Key1", "value1");
+ LeaderInfo participantInfo2 = new LeaderInfo(PARTICIPANT_NAME2);
+ participantInfo2.setSimpleField("Key2", "value2");
+ LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
+ LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
+
+ clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo);
+ try {
+ clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo); // no op
+ } catch (ConcurrentModificationException ex) {
+ // expected
+ Assert.assertEquals(ex.getClass().getName(), "java.util.ConcurrentModificationException");
+ }
+ clt2.joinLeaderElectionParticipantPool(leaderPath, participantInfo2);
+ // a leader should be up
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (clt1.getLeader(leaderPath) != null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+
+ // session expire and reconnect
+ expireSession((ZkMetaClient) clt1.getMetaClient());
+
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (clt1.getLeader(leaderPath) != null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+ Assert.assertNotNull(clt1.getLeaderEntryStat(leaderPath));
+ Assert.assertNotNull(clt1.getLeader(leaderPath));
+ // when session recreated, participant info node should maintain
+ Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1");
+ Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1");
+ Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
+ Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
+ }
}
[helix] 13/21: MultiThreading Stress Test Lattice - Puppy Logic and Skeleton (Part 1) (#2549)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 5389b173945b6f82cd5691a7c0457b1ccb98988a
Author: Marcos Rico Peng <55...@users.noreply.github.com>
AuthorDate: Thu Jul 13 17:16:30 2023 -0400
MultiThreading Stress Test Lattice - Puppy Logic and Skeleton (Part 1) (#2549)
---------
Co-authored-by: mapeng <ma...@linkedin.com>
---
.../helix/metaclient/puppy/AbstractPuppy.java | 95 ++++++++++++++++++++++
.../apache/helix/metaclient/puppy/ExecDelay.java | 63 ++++++++++++++
.../helix/metaclient/puppy/PuppyManager.java | 64 +++++++++++++++
.../apache/helix/metaclient/puppy/PuppyMode.java | 28 +++++++
.../apache/helix/metaclient/puppy/PuppySpec.java | 53 ++++++++++++
5 files changed, 303 insertions(+)
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
new file mode 100644
index 000000000..85137fc17
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
@@ -0,0 +1,95 @@
+package org.apache.helix.metaclient.puppy;
+
+/*
+ * 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.
+ */
+
+import org.apache.helix.metaclient.api.MetaClientInterface;
+import java.util.HashMap;
+
+/**
+ * AbstractPuppy object contains interfaces to implement puppy and main logics to manage puppy life cycle
+ */
+public abstract class AbstractPuppy implements Runnable {
+
+ protected MetaClientInterface<String> _metaclient;
+ protected PuppySpec _puppySpec;
+ public HashMap<String, Integer> _eventChangeCounterMap;
+ protected int _unhandledErrorCounter;
+
+ public AbstractPuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) {
+ _metaclient = metaclient;
+ _puppySpec = puppySpec;
+ _eventChangeCounterMap = new HashMap<>();
+ }
+
+ /**
+ * Implements puppy's main logic. Puppy needs to implement its chaos logic, recovery logic based on
+ * errorRate, recoverDelay. For OneOff puppy, it will bark once with execDelay in spec, and for
+ * Repeat puppy, it will bark forever, with execDelay between 2 barks
+ */
+ protected abstract void bark() throws Exception;
+
+ /**
+ * Implements puppy's final cleanup logic - it will be called only once right before the puppy terminates.
+ * Before the puppy terminates, it needs to recover from all chaos it created.
+ */
+ protected abstract void cleanup();
+
+ @Override
+ public void run() {
+ try {
+ while (true) {
+ try {
+ bark();
+ } catch (Exception e) {
+ incrementUnhandledErrorCounter();
+ e.printStackTrace();
+ }
+
+ if (getPuppySpec().getMode() == PuppyMode.ONE_OFF) {
+ cleanup();
+ break;
+ } else {
+ try {
+ Thread.sleep(getPuppySpec().getExecDelay().getNextDelay());
+ } catch (InterruptedException e) {
+ // Handle interruption if necessary
+ }
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ public PuppySpec getPuppySpec() {
+ return _puppySpec;
+ }
+
+ public int getUnhandledErrorCounter() {
+ return _unhandledErrorCounter;
+ }
+
+ private void incrementUnhandledErrorCounter() {
+ _unhandledErrorCounter++;
+ }
+}
+
+
+
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/puppy/ExecDelay.java b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/ExecDelay.java
new file mode 100644
index 000000000..da0bc529a
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/ExecDelay.java
@@ -0,0 +1,63 @@
+package org.apache.helix.metaclient.puppy;
+
+/*
+ * 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.
+ */
+
+import java.util.Random;
+
+/**
+ * ExecDelay class definition
+ */
+public class ExecDelay {
+ private final long _duration;
+ private final float _jitter;
+
+ private final long _delayBase;
+ private final long _delayRange;
+ private final Random _random;
+
+ public ExecDelay(long duration, float jitter) {
+ if (jitter < 0 || jitter > 1 || duration < 0) {
+ throw new IllegalArgumentException(
+ String.format("Invalid _jitter (%s) or _duration (%s)", jitter, duration));
+ }
+ _duration = duration;
+ _jitter = jitter;
+ _delayRange = Math.round(_duration * _jitter * 2);
+ _delayBase = _duration - _delayRange / 2;
+ _random = new Random();
+ }
+
+ /**
+ * Calculate the next delay based on the configured _duration and _jitter.
+ * @return The next delay in milliseconds.
+ */
+ public long getNextDelay() {
+ long randomDelay = _delayBase + _random.nextLong() % _delayRange;
+ return Math.max(randomDelay, 0);
+ }
+
+ public long getDuration() {
+ return _duration;
+ }
+
+ public float getJitter() {
+ return _jitter;
+ }
+}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppyManager.java b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppyManager.java
new file mode 100644
index 000000000..9ef948c59
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppyManager.java
@@ -0,0 +1,64 @@
+package org.apache.helix.metaclient.puppy;
+
+/*
+ * 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.
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * This class is used to manage the lifecycle of a set of _puppies.
+ */
+public class PuppyManager {
+ private final List<AbstractPuppy> _puppies = new ArrayList<>();
+ private final ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool();
+
+ public PuppyManager() {
+ }
+
+ public void addPuppy(AbstractPuppy puppy) {
+ _puppies.add(puppy);
+ }
+
+ public List<AbstractPuppy> getPuppies() {
+ return _puppies;
+ }
+
+ public void start(long timeoutInSeconds) {
+ for (AbstractPuppy puppy : _puppies) {
+ EXECUTOR_SERVICE.submit(puppy);
+ }
+
+ try {
+ EXECUTOR_SERVICE.awaitTermination(timeoutInSeconds, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ // Ignore
+ }
+
+ stop();
+ }
+
+ public void stop() {
+ EXECUTOR_SERVICE.shutdownNow();
+ }
+}
+
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppyMode.java b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppyMode.java
new file mode 100644
index 000000000..d834f020e
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppyMode.java
@@ -0,0 +1,28 @@
+package org.apache.helix.metaclient.puppy;
+
+/*
+ * 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.
+ */
+
+/**
+ * Enum for Puppy mode (OneOff or Repeat)
+ */
+public enum PuppyMode {
+ ONE_OFF,
+ REPEAT
+}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppySpec.java b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppySpec.java
new file mode 100644
index 000000000..ac6d527df
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/PuppySpec.java
@@ -0,0 +1,53 @@
+package org.apache.helix.metaclient.puppy;
+
+/*
+ * 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.
+ */
+
+/**
+ * PuppySpec class definition
+ */
+public class PuppySpec {
+ private final PuppyMode _mode;
+ private final float _errorRate;
+ private final ExecDelay _execDelay;
+ private final int _numberDiffPaths;
+
+ public PuppySpec(PuppyMode mode, float errorRate, ExecDelay execDelay, int numberDiffPaths) {
+ _mode = mode;
+ _errorRate = errorRate;
+ _execDelay = execDelay;
+ _numberDiffPaths = numberDiffPaths;
+ }
+
+ public PuppyMode getMode() {
+ return _mode;
+ }
+
+ public float getErrorRate() {
+ return _errorRate;
+ }
+
+ public ExecDelay getExecDelay() {
+ return _execDelay;
+ }
+
+ public int getNumberDiffPaths() {
+ return _numberDiffPaths;
+ }
+}
[helix] 09/21: Add API for getDataAndStat (#2535)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 53f9fa7c32c0b11f8cf00353478f50d3c98dead5
Author: xyuanlu <xy...@gmail.com>
AuthorDate: Wed Jun 21 09:05:02 2023 -0700
Add API for getDataAndStat (#2535)
Add API for getDataAndStat
---
.../helix/metaclient/api/MetaClientInterface.java | 13 ++++++++--
.../helix/metaclient/impl/zk/ZkMetaClient.java | 16 +++++++++++--
.../metaclient/impl/zk/util/ZkMetaClientUtil.java | 8 +++++++
.../helix/metaclient/impl/zk/TestZkMetaClient.java | 28 ++++++++++++++++++++++
4 files changed, 61 insertions(+), 4 deletions(-)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/api/MetaClientInterface.java b/meta-client/src/main/java/org/apache/helix/metaclient/api/MetaClientInterface.java
index 375c0814c..b4bfaac2e 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/api/MetaClientInterface.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/api/MetaClientInterface.java
@@ -23,7 +23,9 @@ import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.NotImplementedException;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.helix.metaclient.exception.MetaClientInterruptException;
+import org.apache.helix.metaclient.exception.MetaClientNoNodeException;
import org.apache.helix.metaclient.exception.MetaClientTimeoutException;
@@ -195,12 +197,19 @@ public interface MetaClientInterface<T> {
/**
* Fetch the data for a given key.
- * TODO: define exception type when key does not exist
* @param key key to identify the entry
- * @return Return data of the entry
+ * @return Return data of the entry. Return null if data does not exists.
*/
T get(final String key);
+ /**
+ * Fetch the data and stat for a given key.
+ * @param key key to identify the entry
+ * @return Return an ImmutablePair of data and stat for the entry.
+ * @throws MetaClientNoNodeException if no such entry
+ */
+ ImmutablePair<T, Stat> getDataAndStat(final String key);
+
/**
* API for transaction. The list of operation will be executed as an atomic operation.
* @param ops a list of operations. These operations will all be executed or none of them.
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
index 4398e8e3a..fc8998e95 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
@@ -28,6 +28,7 @@ import java.util.concurrent.locks.ReentrantLock;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang3.NotImplementedException;
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.helix.metaclient.api.AsyncCallback;
import org.apache.helix.metaclient.api.ChildChangeListener;
import org.apache.helix.metaclient.api.ConnectStateChangeListener;
@@ -166,8 +167,7 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
if (zkStats == null) {
return null;
}
- return new Stat(convertZkEntryModeToMetaClientEntryMode(zkStats.getEphemeralOwner()),
- zkStats.getVersion(), zkStats.getCtime(), zkStats.getMtime(), -1);
+ return ZkMetaClientUtil.convertZkStatToStat(zkStats);
} catch (ZkException e) {
throw translateZkExceptionToMetaclientException(e);
}
@@ -178,6 +178,18 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
return _zkClient.readData(key, true);
}
+
+ @Override
+ public ImmutablePair<T, Stat> getDataAndStat(final String key) {
+ try {
+ org.apache.zookeeper.data.Stat zkStat = new org.apache.zookeeper.data.Stat();
+ T data = _zkClient.readData(key, zkStat);
+ return ImmutablePair.of(data, ZkMetaClientUtil.convertZkStatToStat(zkStat));
+ } catch (ZkException e) {
+ throw translateZkExceptionToMetaclientException(e);
+ }
+ }
+
@Override
public List<String> getDirectChildrenKeys(String key) {
try {
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java
index f21a883f3..6bf0ce74b 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java
@@ -262,6 +262,14 @@ public class ZkMetaClientUtil {
}
}
+ public static MetaClientInterface.Stat convertZkStatToStat(
+ org.apache.zookeeper.data.Stat zkStat) {
+ return new MetaClientInterface.Stat(
+ convertZkEntryModeToMetaClientEntryMode(zkStat.getEphemeralOwner()), zkStat.getVersion(),
+ zkStat.getCtime(), zkStat.getMtime(),
+ EphemeralType.TTL.getValue(zkStat.getEphemeralOwner()));
+ }
+
/**
* This function translate and group Zk exception code to metaclient code.
* It currently includes all ZK code on 3.6.3.
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestZkMetaClient.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestZkMetaClient.java
index 69724c9fe..8aca150b0 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestZkMetaClient.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestZkMetaClient.java
@@ -19,6 +19,7 @@ package org.apache.helix.metaclient.impl.zk;
* under the License.
*/
+import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.helix.metaclient.api.ChildChangeListener;
import org.apache.helix.metaclient.api.DataUpdater;
import org.apache.helix.metaclient.api.MetaClientInterface;
@@ -208,6 +209,33 @@ public class TestZkMetaClient extends ZkMetaClientTestBase{
}
}
+ @Test
+ public void testGetDataAndStat() {
+ final String key = "/TestZkMetaClient_testGetDataAndStat";
+ ZkMetaClientConfig config =
+ new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR).build();
+ try (ZkMetaClient<Integer> zkMetaClient = new ZkMetaClient<>(config)) {
+ zkMetaClient.connect();
+ int initValue = 3;
+ zkMetaClient.create(key, initValue);
+ MetaClientInterface.Stat entryStat = zkMetaClient.exists(key);
+ Assert.assertEquals(entryStat.getVersion(), 0);
+ zkMetaClient.set(key, initValue+1, -1);
+ ImmutablePair<Integer, MetaClientInterface.Stat> touple = zkMetaClient.getDataAndStat(key);
+ Assert.assertEquals(touple.right.getVersion(), 1);
+ zkMetaClient.delete(key);
+
+ // test non exist key
+ try{
+ zkMetaClient.getDataAndStat(key);
+ } catch (MetaClientException ex){
+ Assert.assertEquals(ex.getClass().getName(),
+ "org.apache.helix.metaclient.exception.MetaClientNoNodeException");
+ }
+
+ }
+ }
+
@Test
public void testGetAndCountChildrenAndRecursiveDelete() {
final String key = "/TestZkMetaClient_testGetAndCountChildren";
[helix] 12/21: ZkClient - only register one time watcher for read data when not using persist listener. (#2555)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 6aa7c2cce8c6202e80df63ef11a1ee1af085b7dc
Author: xyuanlu <xy...@gmail.com>
AuthorDate: Thu Jul 13 10:25:10 2023 -0700
ZkClient - only register one time watcher for read data when not using persist listener. (#2555)
---------
Co-authored-by: Xiaoyuan Lu <xi...@xialu-mn2.linkedin.biz>
---
.../helix/metaclient/impl/zk/TestZkMetaClient.java | 22 +++++++
.../apache/helix/zookeeper/zkclient/ZkClient.java | 2 +-
.../zkclient/TestZkClientPersistWatcher.java | 75 +++++++++++++---------
3 files changed, 67 insertions(+), 32 deletions(-)
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestZkMetaClient.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestZkMetaClient.java
index 8aca150b0..19f21977b 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestZkMetaClient.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestZkMetaClient.java
@@ -504,6 +504,28 @@ public class TestZkMetaClient extends ZkMetaClientTestBase{
}
}
+ @Test
+ public void testChangeListener() throws Exception {
+ final String basePath = "/TestZkMetaClient_ChangeListener";
+ final int count = 100;
+ try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
+ zkMetaClient.connect();
+ DataChangeListener listener = new DataChangeListener() {
+
+ @Override
+ public void handleDataChange(String key, Object data, ChangeType changeType)
+ throws Exception {
+ }
+ };
+ zkMetaClient.subscribeDataChange(basePath, listener, false);
+ zkMetaClient.create(basePath, "");
+ zkMetaClient.get(basePath);
+ zkMetaClient.exists(basePath);
+ zkMetaClient.getDataAndStat(basePath);
+ zkMetaClient.getDirectChildrenKeys(basePath);
+ }
+ }
+
/**
* Transactional op calls zk.multi() with a set of ops (operations)
* and the return values are converted into metaclient opResults.
diff --git a/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkClient.java b/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkClient.java
index 064f6b494..2a06158d0 100644
--- a/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkClient.java
+++ b/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkClient.java
@@ -2232,7 +2232,7 @@ public class ZkClient implements Watcher {
@SuppressWarnings("unchecked")
public <T extends Object> T readData(String path, Stat stat) {
- return (T) readData(path, stat, hasChildOrDataListeners(path));
+ return (T) readData(path, stat, (!_usePersistWatcher) && hasChildOrDataListeners(path));
}
@SuppressWarnings("unchecked")
diff --git a/zookeeper-api/src/test/java/org/apache/helix/zookeeper/zkclient/TestZkClientPersistWatcher.java b/zookeeper-api/src/test/java/org/apache/helix/zookeeper/zkclient/TestZkClientPersistWatcher.java
index 76f5352c9..c54bca1ef 100644
--- a/zookeeper-api/src/test/java/org/apache/helix/zookeeper/zkclient/TestZkClientPersistWatcher.java
+++ b/zookeeper-api/src/test/java/org/apache/helix/zookeeper/zkclient/TestZkClientPersistWatcher.java
@@ -41,8 +41,7 @@ public class TestZkClientPersistWatcher extends ZkTestBase {
void testZkClientDataChange() throws Exception {
org.apache.helix.zookeeper.impl.client.ZkClient.Builder builder =
new org.apache.helix.zookeeper.impl.client.ZkClient.Builder();
- builder.setZkServer(ZkTestBase.ZK_ADDR).setMonitorRootPathOnly(false)
- .setUsePersistWatcher(true);
+ builder.setZkServer(ZkTestBase.ZK_ADDR).setMonitorRootPathOnly(false).setUsePersistWatcher(true);
org.apache.helix.zookeeper.impl.client.ZkClient zkClient = builder.build();
zkClient.setZkSerializer(new BasicZkSerializer(new SerializableSerializer()));
int count = 1000;
@@ -63,8 +62,8 @@ public class TestZkClientPersistWatcher extends ZkTestBase {
zkClient.subscribeDataChanges(path, dataListener);
zkClient.create(path, "datat", CreateMode.PERSISTENT);
- for(int i=0; i<count; ++i) {
- zkClient.writeData(path, ("datat"+i), -1);
+ for (int i = 0; i < count; ++i) {
+ zkClient.writeData(path, ("datat" + i), -1);
}
Assert.assertTrue(countDownLatch1.await(15000, TimeUnit.MILLISECONDS));
@@ -75,8 +74,7 @@ public class TestZkClientPersistWatcher extends ZkTestBase {
void testZkClientChildChange() throws Exception {
org.apache.helix.zookeeper.impl.client.ZkClient.Builder builder =
new org.apache.helix.zookeeper.impl.client.ZkClient.Builder();
- builder.setZkServer(ZkTestBase.ZK_ADDR).setMonitorRootPathOnly(false)
- .setUsePersistWatcher(true);
+ builder.setZkServer(ZkTestBase.ZK_ADDR).setMonitorRootPathOnly(false).setUsePersistWatcher(true);
org.apache.helix.zookeeper.impl.client.ZkClient zkClient = builder.build();
zkClient.setZkSerializer(new BasicZkSerializer(new SerializableSerializer()));
int count = 100;
@@ -86,16 +84,14 @@ public class TestZkClientPersistWatcher extends ZkTestBase {
String path = "/testZkClientChildChange";
IZkChildListener childListener = new IZkChildListener() {
@Override
- public void handleChildChange(String parentPath, List<String> currentChilds)
- throws Exception {
+ public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
countDownLatch1.countDown();
- event_count[0]++ ;
+ event_count[0]++;
}
};
IZkChildListener childListener2 = new IZkChildListener() {
@Override
- public void handleChildChange(String parentPath, List<String> currentChilds)
- throws Exception {
+ public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
countDownLatch2.countDown();
event_count[0]++;
}
@@ -108,6 +104,7 @@ public class TestZkClientPersistWatcher extends ZkTestBase {
}
Assert.assertTrue(countDownLatch1.await(15000, TimeUnit.MILLISECONDS));
Assert.assertTrue(countDownLatch2.await(15000, TimeUnit.MILLISECONDS));
+ zkClient.deleteRecursively(path);
zkClient.close();
}
@@ -115,8 +112,7 @@ public class TestZkClientPersistWatcher extends ZkTestBase {
void testZkClientPersistRecursiveChange() throws Exception {
org.apache.helix.zookeeper.impl.client.ZkClient.Builder builder =
new org.apache.helix.zookeeper.impl.client.ZkClient.Builder();
- builder.setZkServer(ZkTestBase.ZK_ADDR).setMonitorRootPathOnly(false)
- .setUsePersistWatcher(true);
+ builder.setZkServer(ZkTestBase.ZK_ADDR).setMonitorRootPathOnly(false).setUsePersistWatcher(true);
org.apache.helix.zookeeper.impl.client.ZkClient zkClient = builder.build();
zkClient.setZkSerializer(new BasicZkSerializer(new SerializableSerializer()));
int count = 100;
@@ -124,39 +120,37 @@ public class TestZkClientPersistWatcher extends ZkTestBase {
final AtomicInteger[] event_count2 = {new AtomicInteger(0)};
// for each iteration, we will edit a node, create a child, create a grand child, and
// delete child. Expect 4 event per iteration. -> total event should be count*4
- CountDownLatch countDownLatch1 = new CountDownLatch(count*4);
+ CountDownLatch countDownLatch1 = new CountDownLatch(count * 4);
CountDownLatch countDownLatch2 = new CountDownLatch(count);
String path = "/testZkClientPersistRecursiveChange";
RecursivePersistListener rcListener = new RecursivePersistListener() {
@Override
- public void handleZNodeChange(String dataPath, Watcher.Event.EventType eventType)
- throws Exception {
+ public void handleZNodeChange(String dataPath, Watcher.Event.EventType eventType) throws Exception {
countDownLatch1.countDown();
- event_count[0].incrementAndGet() ;
+ event_count[0].incrementAndGet();
}
};
zkClient.create(path, "datat", CreateMode.PERSISTENT);
zkClient.subscribePersistRecursiveListener(path, rcListener);
- for (int i=0; i<count; ++i) {
+ for (int i = 0; i < count; ++i) {
zkClient.writeData(path, "data7" + i, -1);
- zkClient.create(path+"/c1_" +i , "datat", CreateMode.PERSISTENT);
- zkClient.create(path+"/c1_" +i + "/c2", "datat", CreateMode.PERSISTENT);
- zkClient.delete(path+"/c1_" +i + "/c2");
+ zkClient.create(path + "/c1_" + i, "datat", CreateMode.PERSISTENT);
+ zkClient.create(path + "/c1_" + i + "/c2", "datat", CreateMode.PERSISTENT);
+ zkClient.delete(path + "/c1_" + i + "/c2");
}
Assert.assertTrue(countDownLatch1.await(50000000, TimeUnit.MILLISECONDS));
// subscribe a persist child watch, it should throw exception
IZkChildListener childListener2 = new IZkChildListener() {
@Override
- public void handleChildChange(String parentPath, List<String> currentChilds)
- throws Exception {
+ public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
countDownLatch2.countDown();
event_count2[0].incrementAndGet();
}
};
try {
zkClient.subscribeChildChanges(path, childListener2, false);
- } catch ( Exception ex) {
+ } catch (Exception ex) {
Assert.assertEquals(ex.getClass().getName(), "java.lang.UnsupportedOperationException");
}
@@ -164,14 +158,15 @@ public class TestZkClientPersistWatcher extends ZkTestBase {
zkClient.unsubscribePersistRecursiveListener(path, rcListener);
zkClient.subscribeChildChanges(path, childListener2, false);
// we should only get 100 event since only 100 direct child change.
- for (int i=0; i<count; ++i) {
+ for (int i = 0; i < count; ++i) {
zkClient.writeData(path, "data7" + i, -1);
- zkClient.create(path+"/c2_" +i , "datat", CreateMode.PERSISTENT);
- zkClient.create(path+"/c2_" +i + "/c3", "datat", CreateMode.PERSISTENT);
- zkClient.delete(path+"/c2_" +i + "/c3");
+ zkClient.create(path + "/c2_" + i, "datat", CreateMode.PERSISTENT);
+ zkClient.create(path + "/c2_" + i + "/c3", "datat", CreateMode.PERSISTENT);
+ zkClient.delete(path + "/c2_" + i + "/c3");
}
Assert.assertTrue(countDownLatch2.await(50000000, TimeUnit.MILLISECONDS));
+ zkClient.deleteRecursively(path);
zkClient.close();
}
@@ -179,8 +174,7 @@ public class TestZkClientPersistWatcher extends ZkTestBase {
void testSubscribeOneTimeChangeWhenUsingPersistWatcher() {
org.apache.helix.zookeeper.impl.client.ZkClient.Builder builder =
new org.apache.helix.zookeeper.impl.client.ZkClient.Builder();
- builder.setZkServer(ZkTestBase.ZK_ADDR).setMonitorRootPathOnly(false)
- .setUsePersistWatcher(true);
+ builder.setZkServer(ZkTestBase.ZK_ADDR).setMonitorRootPathOnly(false).setUsePersistWatcher(true);
ZkClient zkClient = builder.build();
zkClient.setZkSerializer(new BasicZkSerializer(new SerializableSerializer()));
@@ -194,7 +188,7 @@ public class TestZkClientPersistWatcher extends ZkTestBase {
}
try {
- zkClient.readData(path, null, true);
+ zkClient.readData(path, null, true);
Assert.fail("Should throw exception when subscribe one time listener");
} catch (Exception e) {
Assert.assertEquals(e.getClass().getName(), "java.lang.IllegalArgumentException");
@@ -206,5 +200,24 @@ public class TestZkClientPersistWatcher extends ZkTestBase {
} catch (Exception e) {
Assert.assertEquals(e.getClass().getName(), "java.lang.IllegalArgumentException");
}
+ zkClient.delete(path);
+ zkClient.close();
+ }
+
+ @Test
+ void testCrudOperationWithResubscribe() {
+ org.apache.helix.zookeeper.impl.client.ZkClient.Builder builder =
+ new org.apache.helix.zookeeper.impl.client.ZkClient.Builder();
+ builder.setZkServer(ZkTestBase.ZK_ADDR).setMonitorRootPathOnly(false).setUsePersistWatcher(false);
+ ZkClient zkClient = builder.build();
+ zkClient.setZkSerializer(new BasicZkSerializer(new SerializableSerializer()));
+
+ String path = "/testCrudOperationWithResubscribe";
+ zkClient.create(path, "datat", CreateMode.PERSISTENT);
+ zkClient.exists(path, true);
+ zkClient.readData(path, null, true);
+ zkClient.getChildren(path, true);
+ zkClient.delete(path);
+ zkClient.close();
}
}
\ No newline at end of file
[helix] 21/21: Leader election client - Proactively send leader gone event when disconnect from ZK (#2585)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 2e53694f77df0360d8092fe2b576eb4faa433ab2
Author: xyuanlu <xy...@gmail.com>
AuthorDate: Tue Aug 15 17:15:27 2023 -0700
Leader election client - Proactively send leader gone event when disconnect from ZK (#2585)
---
.../leaderelection/LeaderElectionClient.java | 64 ++++--
.../LeaderElectionListenerInterfaceAdapter.java | 29 ++-
.../zk/TestConnectStateChangeListenerAndRetry.java | 32 +--
.../metaclient/impl/zk/TestStressZkClient.java | 3 +-
.../apache/helix/metaclient/impl/zk/TestUtil.java | 24 ++
.../leaderelection/LeaderElectionPuppy.java | 5 +
.../recipes/leaderelection/TestLeaderElection.java | 247 ++++++++++++++-------
.../TestMultiClientLeaderElection.java | 3 +
8 files changed, 273 insertions(+), 134 deletions(-)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
index 7b13778c0..3bcf09ceb 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
@@ -33,6 +33,7 @@ import org.apache.helix.metaclient.api.DataChangeListener;
import org.apache.helix.metaclient.api.MetaClientInterface;
import org.apache.helix.metaclient.api.Op;
import org.apache.helix.metaclient.api.OpResult;
+import org.apache.helix.metaclient.exception.MetaClientBadVersionException;
import org.apache.helix.metaclient.exception.MetaClientException;
import org.apache.helix.metaclient.exception.MetaClientNoNodeException;
import org.apache.helix.metaclient.exception.MetaClientNodeExistsException;
@@ -83,7 +84,7 @@ public class LeaderElectionClient implements AutoCloseable {
/**
* Construct a LeaderElectionClient using a user passed in leaderElectionConfig. It creates a MetaClient
* instance underneath.
- * When MetaClient is auto closed be cause of being disconnected and auto retry connection timed out, A new
+ * When MetaClient is auto closed because of being disconnected and auto retry connection timed out, A new
* MetaClient instance will be created and keeps retry connection.
*
* @param metaClientConfig The config used to create an metaclient.
@@ -257,20 +258,24 @@ public class LeaderElectionClient implements AutoCloseable {
}
// check if current participant is the leader
// read data and stats, check, and multi check + delete
- ImmutablePair<LeaderInfo, MetaClientInterface.Stat> tup = _metaClient.getDataAndStat(key);
- if (tup.left.getLeaderName().equalsIgnoreCase(_participant)) {
- int expectedVersion = tup.right.getVersion();
- List<Op> ops = Arrays.asList(Op.check(key, expectedVersion), Op.delete(key, expectedVersion));
- //Execute transactional support on operations
- List<OpResult> opResults = _metaClient.transactionOP(ops);
- if (opResults.get(0).getType() == ERRORRESULT) {
- if (isLeader(leaderPath)) {
- // Participant re-elected as leader.
- throw new ConcurrentModificationException("Concurrent operation, please retry");
- } else {
- LOG.info("Someone else is already leader");
+ try {
+ ImmutablePair<LeaderInfo, MetaClientInterface.Stat> tup = _metaClient.getDataAndStat(key);
+ if (tup.left.getLeaderName().equalsIgnoreCase(_participant)) {
+ int expectedVersion = tup.right.getVersion();
+ List<Op> ops = Arrays.asList(Op.check(key, expectedVersion), Op.delete(key, expectedVersion));
+ //Execute transactional support on operations
+ List<OpResult> opResults = _metaClient.transactionOP(ops);
+ if (opResults.get(0).getType() == ERRORRESULT) {
+ if (isLeader(leaderPath)) {
+ // Participant re-elected as leader.
+ throw new ConcurrentModificationException("Concurrent operation, please retry");
+ } else {
+ LOG.info("Someone else is already leader");
+ }
}
}
+ } catch (MetaClientNoNodeException ex) {
+ LOG.info("No Leader for participant pool {} when exit the pool", leaderPath);
}
}
@@ -334,8 +339,10 @@ public class LeaderElectionClient implements AutoCloseable {
* @return A boolean value indicating if registration is success.
*/
public boolean subscribeLeadershipChanges(String leaderPath, LeaderElectionListenerInterface listener) {
- _metaClient.subscribeDataChange(leaderPath + LEADER_ENTRY_KEY, new LeaderElectionListenerInterfaceAdapter(listener),
- false);
+ LeaderElectionListenerInterfaceAdapter adapter = new LeaderElectionListenerInterfaceAdapter(leaderPath, listener);
+ _metaClient.subscribeDataChange(leaderPath + LEADER_ENTRY_KEY,
+ adapter, false /*skipWatchingNonExistNode*/); // we need to subscribe event when path is not there
+ _metaClient.subscribeStateChanges(adapter);
return false;
}
@@ -344,7 +351,10 @@ public class LeaderElectionClient implements AutoCloseable {
* @param listener An implementation of LeaderElectionListenerInterface
*/
public void unsubscribeLeadershipChanges(String leaderPath, LeaderElectionListenerInterface listener) {
- _metaClient.unsubscribeDataChange(leaderPath + LEADER_ENTRY_KEY, new LeaderElectionListenerInterfaceAdapter(listener));
+ LeaderElectionListenerInterfaceAdapter adapter = new LeaderElectionListenerInterfaceAdapter(leaderPath, listener);
+ _metaClient.unsubscribeDataChange(leaderPath + LEADER_ENTRY_KEY, adapter
+ );
+ _metaClient.unsubscribeConnectStateChanges(adapter);
}
@Override
@@ -395,6 +405,9 @@ public class LeaderElectionClient implements AutoCloseable {
_metaClient.create(leaderPath + PARTICIPANTS_ENTRY_PARENT + _participant, _participantInfos.get(leaderPath),
MetaClientInterface.EntryMode.EPHEMERAL);
}
+ } else if (prevState == MetaClientInterface.ConnectState.DISCONNECTED
+ && currentState == MetaClientInterface.ConnectState.CONNECTED) {
+ touchLeaderNode();
}
}
@@ -404,6 +417,25 @@ public class LeaderElectionClient implements AutoCloseable {
}
}
+ private void touchLeaderNode() {
+ for (String leaderPath : _leaderGroups) {
+ String key = leaderPath;
+ ImmutablePair<LeaderInfo, MetaClientInterface.Stat> tup = _metaClient.getDataAndStat(key);
+ if (tup.left.getLeaderName().equalsIgnoreCase(_participant)) {
+ int expectedVersion = tup.right.getVersion();
+ try {
+ _metaClient.set(key, tup.left, expectedVersion);
+ } catch (MetaClientNoNodeException ex) {
+ LOG.info("leaderPath {} gone when retouch leader node.", key);
+ } catch (MetaClientBadVersionException e) {
+ LOG.info("New leader for leaderPath {} when retouch leader node.", key);
+ } catch (MetaClientException ex) {
+ LOG.warn("Failed to touch {} when reconnected.", key, ex);
+ }
+ }
+ }
+ }
+
public MetaClientInterface getMetaClient() {
return _metaClient;
}
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterfaceAdapter.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterfaceAdapter.java
index 5c64d6790..ee790ac82 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterfaceAdapter.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionListenerInterfaceAdapter.java
@@ -1,14 +1,18 @@
package org.apache.helix.metaclient.recipes.leaderelection;
+import org.apache.helix.metaclient.api.ConnectStateChangeListener;
import org.apache.helix.metaclient.api.DataChangeListener;
+import org.apache.helix.metaclient.api.MetaClientInterface;
import static org.apache.helix.metaclient.recipes.leaderelection.LeaderElectionListenerInterface.ChangeType.*;
-public class LeaderElectionListenerInterfaceAdapter implements DataChangeListener {
+public class LeaderElectionListenerInterfaceAdapter implements DataChangeListener, ConnectStateChangeListener {
+ private String _leaderPath;
private final LeaderElectionListenerInterface _leaderElectionListener;
- public LeaderElectionListenerInterfaceAdapter(LeaderElectionListenerInterface leaderElectionListener) {
+ public LeaderElectionListenerInterfaceAdapter(String leaderPath, LeaderElectionListenerInterface leaderElectionListener) {
+ _leaderPath = leaderPath;
_leaderElectionListener = leaderElectionListener;
}
@@ -16,11 +20,12 @@ public class LeaderElectionListenerInterfaceAdapter implements DataChangeListene
public void handleDataChange(String key, Object data, ChangeType changeType) throws Exception {
switch (changeType) {
case ENTRY_CREATED:
+ case ENTRY_UPDATE:
String newLeader = ((LeaderInfo) data).getLeaderName();
- _leaderElectionListener.onLeadershipChange(key, LEADER_ACQUIRED, newLeader);
+ _leaderElectionListener.onLeadershipChange(_leaderPath, LEADER_ACQUIRED, newLeader);
break;
case ENTRY_DELETED:
- _leaderElectionListener.onLeadershipChange(key, LEADER_LOST, "");
+ _leaderElectionListener.onLeadershipChange(_leaderPath, LEADER_LOST, "");
}
}
@@ -40,4 +45,20 @@ public class LeaderElectionListenerInterfaceAdapter implements DataChangeListene
public int hashCode() {
return _leaderElectionListener.hashCode();
}
+
+ @Override
+ public void handleConnectStateChanged(MetaClientInterface.ConnectState prevState,
+ MetaClientInterface.ConnectState currentState) throws Exception {
+ if (currentState == MetaClientInterface.ConnectState.DISCONNECTED) {
+ // when disconnected, notify leader lost even though the ephmeral node is not gone until expire
+ // Leader election client will touch the node if reconnect before expire
+ _leaderElectionListener.onLeadershipChange(_leaderPath, LEADER_LOST, "");
+ }
+
+ }
+
+ @Override
+ public void handleConnectionEstablishmentError(Throwable error) throws Exception {
+
+ }
}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java
index 086db51c7..f088140c6 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java
@@ -48,32 +48,14 @@ import org.testng.annotations.Test;
import static org.apache.helix.metaclient.constants.MetaClientConstants.DEFAULT_INIT_EXP_BACKOFF_RETRY_INTERVAL_MS;
import static org.apache.helix.metaclient.constants.MetaClientConstants.DEFAULT_MAX_EXP_BACKOFF_RETRY_INTERVAL_MS;
+import static org.apache.helix.metaclient.impl.zk.TestUtil.*;
public class TestConnectStateChangeListenerAndRetry {
- protected static final String ZK_ADDR = "localhost:2181";
+ protected static final String ZK_ADDR = "localhost:2184";
protected static ZkServer _zkServer;
- private static final long AUTO_RECONNECT_TIMEOUT_MS_FOR_TEST = 3 * 1000;
- private static final long AUTO_RECONNECT_WAIT_TIME_WITHIN = 1 * 1000;
- private static final long AUTO_RECONNECT_WAIT_TIME_EXD = 5 * 1000;
-
- /**
- * Simulate a zk state change by calling {@link ZkClient#process(WatchedEvent)} directly
- * This need to be done in a separate thread to simulate ZkClient eventThread.
- */
- private static void simulateZkStateReconnected(ZkClient zkClient) throws InterruptedException {
- WatchedEvent event =
- new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Disconnected,
- null);
- zkClient.process(event);
-
- Thread.sleep(AUTO_RECONNECT_WAIT_TIME_WITHIN);
-
- event = new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.SyncConnected,
- null);
- zkClient.process(event);
- }
+
@BeforeTest
public void prepare() {
@@ -82,11 +64,6 @@ public class TestConnectStateChangeListenerAndRetry {
_zkServer = ZkMetaClientTestBase.startZkServer(ZK_ADDR);
}
- @AfterTest
- public void cleanUp() {
- System.out.println("END TestConnectStateChangeListenerAndRetry at " + new Date(System.currentTimeMillis()));
- }
-
@Test
public void testConnectState() {
System.out.println("STARTING TestConnectStateChangeListenerAndRetry.testConnectState at " + new Date(System.currentTimeMillis()));
@@ -115,7 +92,7 @@ public class TestConnectStateChangeListenerAndRetry {
@Override
public void run() {
try {
- simulateZkStateReconnected(zkMetaClient.getZkClient());
+ simulateZkStateReconnected(zkMetaClient);
} catch (InterruptedException e) {
Assert.fail("Exception in simulateZkStateReconnected", e);
}
@@ -170,6 +147,7 @@ public class TestConnectStateChangeListenerAndRetry {
} catch (Exception ex) {
Assert.assertTrue(ex instanceof IllegalStateException);
}
+ zkMetaClient.unsubscribeConnectStateChanges(listener);
}
System.out.println("END TestConnectStateChangeListenerAndRetry.testConnectStateChangeListener at " + new Date(System.currentTimeMillis()));
}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
index 8a3f9c115..6f358f0e8 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
@@ -48,7 +48,8 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
}
@AfterTest
- private void tearDown() {
+ @Override
+ public void cleanUp() {
this._zkMetaClient.close();
}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestUtil.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestUtil.java
index fbf1ab1f3..067fe3eb5 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestUtil.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestUtil.java
@@ -40,6 +40,10 @@ import org.testng.Assert;
public class TestUtil {
+ public static final long AUTO_RECONNECT_TIMEOUT_MS_FOR_TEST = 3 * 1000;
+ public static final long AUTO_RECONNECT_WAIT_TIME_WITHIN = 1 * 1000;
+ public static final long AUTO_RECONNECT_WAIT_TIME_EXD = 5 * 1000;
+
static java.lang.reflect.Field getField(Class clazz, String fieldName)
throws NoSuchFieldException {
try {
@@ -161,4 +165,24 @@ public class TestUtil {
"Fail to expire current session, zk: " + curZookeeper);
}
+
+
+ /**
+ * Simulate a zk state change by calling {@link ZkClient#process(WatchedEvent)} directly
+ * This need to be done in a separate thread to simulate ZkClient eventThread.
+ */
+ public static void simulateZkStateReconnected(ZkMetaClient client) throws InterruptedException {
+ final ZkClient zkClient = client.getZkClient();
+ WatchedEvent event =
+ new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Disconnected,
+ null);
+ zkClient.process(event);
+
+ Thread.sleep(AUTO_RECONNECT_WAIT_TIME_WITHIN);
+
+ event = new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.SyncConnected,
+ null);
+ zkClient.process(event);
+ }
+
}
\ No newline at end of file
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionPuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionPuppy.java
index 5f1fdf631..3f123d3ac 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionPuppy.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionPuppy.java
@@ -82,6 +82,11 @@ public class LeaderElectionPuppy extends AbstractPuppy {
_leaderElectionClient.exitLeaderElectionParticipantPool(_leaderGroup);
} catch (MetaClientException ignore) {
// already leave the pool. OK to throw exception.
+ } finally {
+ try {
+ _leaderElectionClient.close();
+ } catch (Exception e) {
+ }
}
}
}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
index 71d85fdb9..75917623c 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
@@ -5,9 +5,13 @@ import org.apache.helix.metaclient.MetaClientTestUtil;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.helix.metaclient.factories.MetaClientConfig;
+import org.apache.helix.metaclient.impl.zk.TestUtil;
import org.apache.helix.metaclient.impl.zk.ZkMetaClient;
import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase;
+import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig;
+import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.testng.Assert;
+import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import static org.apache.helix.metaclient.impl.zk.TestUtil.*;
@@ -19,13 +23,24 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
private static final String PARTICIPANT_NAME2 = "participant_2";
private static final String LEADER_PATH = "/LEADER_ELECTION_GROUP_1";
- public static LeaderElectionClient createLeaderElectionClient(String participantName) {
+ public static LeaderElectionClient createLeaderElectionClient(String participantName) {
MetaClientConfig.StoreType storeType = MetaClientConfig.StoreType.ZOOKEEPER;
MetaClientConfig config =
new MetaClientConfig.MetaClientConfigBuilder<>().setConnectionAddress(ZK_ADDR).setStoreType(storeType).build();
return new LeaderElectionClient(config, participantName);
}
+ @AfterTest
+ @Override
+ public void cleanUp() {
+ ZkMetaClientConfig config = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR)
+ .build();
+ try (ZkMetaClient<ZNRecord> client = new ZkMetaClient<>(config)) {
+ client.connect();
+ client.recursiveDelete(LEADER_PATH);
+ }
+ }
+
@Test
public void testAcquireLeadership() throws Exception {
System.out.println("START TestLeaderElection.testAcquireLeadership");
@@ -47,7 +62,6 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
Assert.assertEquals(clt1.getLeader(leaderPath), clt2.getLeader(leaderPath));
Assert.assertEquals(clt1.getLeader(leaderPath), PARTICIPANT_NAME1);
-
// client 1 exit leader election group, and client 2 should be current leader.
clt1.exitLeaderElectionParticipantPool(leaderPath);
@@ -75,7 +89,7 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
System.out.println("END TestLeaderElection.testAcquireLeadership");
}
- @Test
+ @Test(dependsOnMethods = "testAcquireLeadership")
public void testElectionPoolMembership() throws Exception {
System.out.println("START TestLeaderElection.testElectionPoolMembership");
String leaderPath = LEADER_PATH + "/_testElectionPoolMembership";
@@ -111,49 +125,12 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
clt2.exitLeaderElectionParticipantPool(leaderPath);
Assert.assertNull(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME2));
+ clt1.close();
+ clt2.close();
System.out.println("END TestLeaderElection.testElectionPoolMembership");
}
- @Test
- public void testSessionExpire() throws Exception {
- System.out.println("START TestLeaderElection.testSessionExpire");
- String leaderPath = LEADER_PATH + "/_testSessionExpire";
- LeaderInfo participantInfo = new LeaderInfo(PARTICIPANT_NAME1);
- participantInfo.setSimpleField("Key1", "value1");
- LeaderInfo participantInfo2 = new LeaderInfo(PARTICIPANT_NAME2);
- participantInfo2.setSimpleField("Key2", "value2");
- LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
- LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
-
- clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo);
- try {
- clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo); // no op
- } catch (ConcurrentModificationException ex) {
- // expected
- Assert.assertEquals(ex.getClass().getName(), "java.util.ConcurrentModificationException");
- }
- clt2.joinLeaderElectionParticipantPool(leaderPath, participantInfo2);
- // a leader should be up
- Assert.assertTrue(MetaClientTestUtil.verify(() -> {
- return (clt1.getLeader(leaderPath) != null);
- }, MetaClientTestUtil.WAIT_DURATION));
-
- // session expire and reconnect
- expireSession((ZkMetaClient) clt1.getMetaClient());
-
- Assert.assertTrue(MetaClientTestUtil.verify(() -> {
- return (clt1.getLeader(leaderPath) != null);
- }, MetaClientTestUtil.WAIT_DURATION));
- Assert.assertNotNull(clt1.getLeaderEntryStat(leaderPath));
- Assert.assertNotNull(clt1.getLeader(leaderPath));
- // when session recreated, participant info node should maintain
- Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1");
- Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1");
- Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
- Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
- System.out.println("END TestLeaderElection.testSessionExpire");
- }
- @Test (dependsOnMethods = "testAcquireLeadership")
+ @Test(dependsOnMethods = "testElectionPoolMembership")
public void testLeadershipListener() throws Exception {
System.out.println("START TestLeaderElection.testLeadershipListener");
String leaderPath = LEADER_PATH + "/testLeadershipListener";
@@ -165,45 +142,45 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
final int count = 10;
final int[] numNewLeaderEvent = {0};
final int[] numLeaderGoneEvent = {0};
- CountDownLatch countDownLatchNewLeader = new CountDownLatch(count*2);
- CountDownLatch countDownLatchLeaderGone = new CountDownLatch(count*2);
-
- LeaderElectionListenerInterface listener = new LeaderElectionListenerInterface() {
-
- @Override
- public void onLeadershipChange(String leaderPath, ChangeType type, String curLeader) {
- if (type == ChangeType.LEADER_LOST) {
- countDownLatchLeaderGone.countDown();
- Assert.assertEquals(curLeader.length(), 0);
- numLeaderGoneEvent[0]++;
- } else if (type == ChangeType.LEADER_ACQUIRED) {
- countDownLatchNewLeader.countDown();
- numNewLeaderEvent[0]++;
- Assert.assertTrue(curLeader.length()!=0);
- } else {
- Assert.fail();
- }
- }
- };
+ CountDownLatch countDownLatchNewLeader = new CountDownLatch(count * 2);
+ CountDownLatch countDownLatchLeaderGone = new CountDownLatch(count * 2);
+
+ LeaderElectionListenerInterface listener = new LeaderElectionListenerInterface() {
+
+ @Override
+ public void onLeadershipChange(String leaderPath, ChangeType type, String curLeader) {
+ if (type == ChangeType.LEADER_LOST) {
+ countDownLatchLeaderGone.countDown();
+ Assert.assertEquals(curLeader.length(), 0);
+ numLeaderGoneEvent[0]++;
+ } else if (type == ChangeType.LEADER_ACQUIRED) {
+ countDownLatchNewLeader.countDown();
+ numNewLeaderEvent[0]++;
+ Assert.assertTrue(curLeader.length() != 0);
+ } else {
+ Assert.fail();
+ }
+ }
+ };
clt3.subscribeLeadershipChanges(leaderPath, listener);
// each iteration will be participant_1 is new leader, leader gone, participant_2 is new leader, leader gone
- for (int i=0; i<count; ++i) {
+ for (int i = 0; i < count; ++i) {
joinPoolTestHelper(leaderPath, clt1, clt2);
Thread.sleep(1000);
}
Assert.assertTrue(countDownLatchNewLeader.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS));
Assert.assertTrue(countDownLatchLeaderGone.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS));
- Assert.assertEquals(numLeaderGoneEvent[0], count*2);
- Assert.assertEquals(numNewLeaderEvent[0], count*2);
+ Assert.assertEquals(numLeaderGoneEvent[0], count * 2);
+ Assert.assertEquals(numNewLeaderEvent[0], count * 2);
clt3.unsubscribeLeadershipChanges(leaderPath, listener);
// listener shouldn't receive any event after unsubscribe
joinPoolTestHelper(leaderPath, clt1, clt2);
- Assert.assertEquals(numLeaderGoneEvent[0], count*2);
- Assert.assertEquals(numNewLeaderEvent[0], count*2);
+ Assert.assertEquals(numLeaderGoneEvent[0], count * 2);
+ Assert.assertEquals(numNewLeaderEvent[0], count * 2);
clt1.close();
clt2.close();
@@ -211,13 +188,46 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
System.out.println("END TestLeaderElection.testLeadershipListener");
}
- private void joinPoolTestHelper(String leaderPath, LeaderElectionClient clt1, LeaderElectionClient clt2) throws Exception {
+ @Test(dependsOnMethods = "testLeadershipListener")
+ public void testRelinquishLeadership() throws Exception {
+ System.out.println("START TestLeaderElection.testRelinquishLeadership");
+ String leaderPath = LEADER_PATH + "/testRelinquishLeadership";
+ LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
+ LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
+ LeaderElectionClient clt3 = createLeaderElectionClient(PARTICIPANT_NAME2);
+
+ final int count = 1;
+ CountDownLatch countDownLatchNewLeader = new CountDownLatch(count);
+ CountDownLatch countDownLatchLeaderGone = new CountDownLatch(count);
+
+ LeaderElectionListenerInterface listener = new LeaderElectionListenerInterface() {
+
+ @Override
+ public void onLeadershipChange(String leaderPath, ChangeType type, String curLeader) {
+ if (type == ChangeType.LEADER_LOST) {
+ countDownLatchLeaderGone.countDown();
+ Assert.assertEquals(curLeader.length(), 0);
+ } else if (type == ChangeType.LEADER_ACQUIRED) {
+ countDownLatchNewLeader.countDown();
+ Assert.assertTrue(curLeader.length() != 0);
+ } else {
+ Assert.fail();
+ }
+ }
+ };
+
clt1.joinLeaderElectionParticipantPool(leaderPath);
clt2.joinLeaderElectionParticipantPool(leaderPath);
+ clt3.subscribeLeadershipChanges(leaderPath, listener);
+ // clt1 gone
+ clt1.relinquishLeader(leaderPath);
- Thread.sleep(2000);
+ // participant 1 should have gone, and a leader gone event is sent
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (clt1.getLeader(leaderPath) != null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+ Assert.assertTrue(countDownLatchLeaderGone.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS));
- // clt1 gone
clt1.exitLeaderElectionParticipantPool(leaderPath);
Assert.assertTrue(MetaClientTestUtil.verify(() -> {
return (clt1.getLeader(leaderPath) != null);
@@ -227,20 +237,63 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
}, MetaClientTestUtil.WAIT_DURATION));
clt2.exitLeaderElectionParticipantPool(leaderPath);
-
+ clt1.close();
+ clt2.close();
+ clt3.close();
+ System.out.println("END TestLeaderElection.testRelinquishLeadership");
}
- @Test (dependsOnMethods = "testLeadershipListener")
- public void testRelinquishLeadership() throws Exception {
- System.out.println("START TestLeaderElection.testRelinquishLeadership");
- String leaderPath = LEADER_PATH + "/testRelinquishLeadership";
+ @Test(dependsOnMethods = "testAcquireLeadership")
+ public void testSessionExpire() throws Exception {
+ System.out.println("START TestLeaderElection.testSessionExpire");
+ String leaderPath = LEADER_PATH + "/_testSessionExpire";
+ LeaderInfo participantInfo = new LeaderInfo(PARTICIPANT_NAME1);
+ participantInfo.setSimpleField("Key1", "value1");
+ LeaderInfo participantInfo2 = new LeaderInfo(PARTICIPANT_NAME2);
+ participantInfo2.setSimpleField("Key2", "value2");
LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
- LeaderElectionClient clt3 = createLeaderElectionClient(PARTICIPANT_NAME2);
+ clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo);
+ try {
+ clt1.joinLeaderElectionParticipantPool(leaderPath, participantInfo); // no op
+ } catch (ConcurrentModificationException ex) {
+ // expected
+ Assert.assertEquals(ex.getClass().getName(), "java.util.ConcurrentModificationException");
+ }
+ clt2.joinLeaderElectionParticipantPool(leaderPath, participantInfo2);
+ // a leader should be up
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (clt1.getLeader(leaderPath) != null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+
+ // session expire and reconnect
+ expireSession((ZkMetaClient) clt1.getMetaClient());
+
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (clt1.getLeader(leaderPath) != null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+ Assert.assertNotNull(clt1.getLeaderEntryStat(leaderPath));
+ Assert.assertNotNull(clt1.getLeader(leaderPath));
+ // when session recreated, participant info node should maintain
+ Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1");
+ Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1");
+ Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
+ Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
+ clt1.close();
+ clt2.close();
+ System.out.println("END TestLeaderElection.testSessionExpire");
+ }
+
+ @Test(dependsOnMethods = "testSessionExpire")
+ public void testClientDisconnectAndReconnectBeforeExpire() throws Exception {
+ System.out.println("START TestLeaderElection.testClientDisconnectAndReconnectBeforeExpire");
+ String leaderPath = LEADER_PATH + "/testClientDisconnectAndReconnectBeforeExpire";
+ LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
+ LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
final int count = 1;
- CountDownLatch countDownLatchNewLeader = new CountDownLatch(count);
+ CountDownLatch countDownLatchNewLeader = new CountDownLatch(count + 1);
CountDownLatch countDownLatchLeaderGone = new CountDownLatch(count);
LeaderElectionListenerInterface listener = new LeaderElectionListenerInterface() {
@@ -250,27 +303,51 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
if (type == ChangeType.LEADER_LOST) {
countDownLatchLeaderGone.countDown();
Assert.assertEquals(curLeader.length(), 0);
+ System.out.println("gone leader");
} else if (type == ChangeType.LEADER_ACQUIRED) {
countDownLatchNewLeader.countDown();
- Assert.assertTrue(curLeader.length()!=0);
+ Assert.assertTrue(curLeader.length() != 0);
+ System.out.println("new leader");
} else {
Assert.fail();
}
}
};
+ clt1.subscribeLeadershipChanges(leaderPath, listener);
clt1.joinLeaderElectionParticipantPool(leaderPath);
clt2.joinLeaderElectionParticipantPool(leaderPath);
- clt3.subscribeLeadershipChanges(leaderPath, listener);
- // clt1 gone
- clt1.relinquishLeader(leaderPath);
-
- // participant 1 should have gone, and a leader gone event is sent
+ // check leader node version before we simulate disconnect.
Assert.assertTrue(MetaClientTestUtil.verify(() -> {
return (clt1.getLeader(leaderPath) != null);
}, MetaClientTestUtil.WAIT_DURATION));
+ int leaderNodeVersion = ((ZkMetaClient) clt1.getMetaClient()).exists(leaderPath + "/LEADER").getVersion();
+ System.out.println("version " + leaderNodeVersion);
+
+ // clt1 disconnected and reconnected before session expire
+ simulateZkStateReconnected((ZkMetaClient) clt1.getMetaClient());
+
+ Assert.assertTrue(countDownLatchNewLeader.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS));
Assert.assertTrue(countDownLatchLeaderGone.await(MetaClientTestUtil.WAIT_DURATION, TimeUnit.MILLISECONDS));
+ leaderNodeVersion = ((ZkMetaClient) clt2.getMetaClient()).exists(leaderPath + "/LEADER").getVersion();
+ System.out.println("version " + leaderNodeVersion);
+
+ clt1.exitLeaderElectionParticipantPool(leaderPath);
+ clt2.exitLeaderElectionParticipantPool(leaderPath);
+ clt1.close();
+ clt2.close();
+ System.out.println("END TestLeaderElection.testClientDisconnectAndReconnectBeforeExpire");
+ }
+
+ private void joinPoolTestHelper(String leaderPath, LeaderElectionClient clt1, LeaderElectionClient clt2)
+ throws Exception {
+ clt1.joinLeaderElectionParticipantPool(leaderPath);
+ clt2.joinLeaderElectionParticipantPool(leaderPath);
+
+ Thread.sleep(2000);
+
+ // clt1 gone
clt1.exitLeaderElectionParticipantPool(leaderPath);
Assert.assertTrue(MetaClientTestUtil.verify(() -> {
return (clt1.getLeader(leaderPath) != null);
@@ -280,7 +357,5 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
}, MetaClientTestUtil.WAIT_DURATION));
clt2.exitLeaderElectionParticipantPool(leaderPath);
- System.out.println("END TestLeaderElection.testRelinquishLeadership");
}
-
}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestMultiClientLeaderElection.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestMultiClientLeaderElection.java
index 0fe424501..4fb508790 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestMultiClientLeaderElection.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestMultiClientLeaderElection.java
@@ -51,11 +51,14 @@ public class TestMultiClientLeaderElection extends ZkMetaClientTestBase {
_zkMetaClient.create("/Parent/a", "");
}
@AfterTest
+ @Override
public void cleanUp() {
try {
_zkMetaClient.recursiveDelete(_leaderElectionGroup);
} catch (MetaClientException ex) {
_zkMetaClient.recursiveDelete(_leaderElectionGroup);
+ } finally {
+ _zkMetaClient.close();
}
}
[helix] 18/21: Lattice LockClient LockInfoSerializer Implementation(#2580)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 26f319608cae205e66bc6ab3cbf3b882b4980ae9
Author: Marcos Rico Peng <55...@users.noreply.github.com>
AuthorDate: Wed Aug 2 18:41:59 2023 +0200
Lattice LockClient LockInfoSerializer Implementation(#2580)
---------
Co-authored-by: mapeng <ma...@linkedin.com>
---
.../helix/metaclient/recipes/lock/LockClient.java | 9 ++---
.../helix/metaclient/recipes/lock/LockInfo.java | 30 ++++++++---------
.../recipes/lock/LockInfoSerializer.java | 39 ++++++++++++++++++++++
.../metaclient/recipes/lock/LockClientTest.java | 36 ++++++++++++++++----
4 files changed, 85 insertions(+), 29 deletions(-)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java
index 480e87c30..a186f3d81 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java
@@ -48,8 +48,7 @@ public class LockClient implements LockClientInterface, AutoCloseable {
if (MetaClientConfig.StoreType.ZOOKEEPER.equals(config.getStoreType())) {
ZkMetaClientConfig zkMetaClientConfig = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().
setConnectionAddress(config.getConnectionAddress())
- // Currently only support ZNRecordSerializer. TODO: make this configurable
- .setZkSerializer((new ZNRecordSerializer()))
+ .setZkSerializer((new LockInfoSerializer()))
.build();
_metaClient = new ZkMetaClientFactory().getMetaClient(zkMetaClientConfig);
_metaClient.connect();
@@ -110,11 +109,7 @@ public class LockClient implements LockClientInterface, AutoCloseable {
if (stat == null) {
return null;
}
- //Create a new DataRecord from underlying record
- DataRecord dataRecord = new DataRecord(_metaClient.get(key));
- //Create a new LockInfo from DataRecord
- LockInfo lockInfo = new LockInfo(dataRecord, stat);
- return lockInfo;
+ return new LockInfo(_metaClient.get(key), stat);
}
@Override
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockInfo.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockInfo.java
index 26736f1b0..2a08c3754 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockInfo.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockInfo.java
@@ -39,7 +39,6 @@ public class LockInfo extends DataRecord {
public static final long DEFAULT_LAST_RENEWED_AT_LONG = -1L;
public static final long DEFAULT_TIMEOUT_DURATION = -1L;
private static final String DEFAULT_LOCK_INFO = "lockInfo.";
- private DataRecord _dataRecord;
/**
* The keys to lock information
@@ -59,7 +58,6 @@ public class LockInfo extends DataRecord {
*/
public LockInfo() {
super(DEFAULT_LOCK_INFO);
- _dataRecord = new DataRecord(DEFAULT_LOCK_INFO);
setLockInfoFields(DEFAULT_LOCK_ID_TEXT, DEFAULT_OWNER_ID_TEXT, DEFAULT_CLIENT_ID_TEXT, DEFAULT_CLIENT_DATA, DEFAULT_GRANTED_AT_LONG,
DEFAULT_LAST_RENEWED_AT_LONG, DEFAULT_TIMEOUT_DURATION);
}
@@ -140,7 +138,7 @@ public class LockInfo extends DataRecord {
* It is created by the lockClient and a new one is created for each time the lock is acquired.
*/
public void setLockId(String lockId) {
- _dataRecord.setSimpleField(LockInfoAttribute.LOCK_ID.name(), lockId == null ? DEFAULT_LOCK_ID_TEXT : lockId);
+ setSimpleField(LockInfoAttribute.LOCK_ID.name(), lockId == null ? DEFAULT_LOCK_ID_TEXT : lockId);
}
/**
@@ -150,7 +148,7 @@ public class LockInfo extends DataRecord {
* by the same owner.
*/
public void setOwnerId(String ownerId) {
- _dataRecord.setSimpleField(LockInfoAttribute.OWNER_ID.name(), ownerId == null ? DEFAULT_OWNER_ID_TEXT : ownerId);
+ setSimpleField(LockInfoAttribute.OWNER_ID.name(), ownerId == null ? DEFAULT_OWNER_ID_TEXT : ownerId);
}
/**
@@ -158,7 +156,7 @@ public class LockInfo extends DataRecord {
* @param clientId Unique identifier that represents who will get the lock (the client).
*/
public void setClientId(String clientId) {
- _dataRecord.setSimpleField(LockInfoAttribute.CLIENT_ID.name(), clientId == null ? DEFAULT_CLIENT_ID_TEXT : clientId);
+ setSimpleField(LockInfoAttribute.CLIENT_ID.name(), clientId == null ? DEFAULT_CLIENT_ID_TEXT : clientId);
}
/**
@@ -166,7 +164,7 @@ public class LockInfo extends DataRecord {
* @param clientData String representing the serialized data object
*/
public void setClientData(String clientData) {
- _dataRecord.setSimpleField(LockInfoAttribute.CLIENT_DATA.name(), clientData == null ? DEFAULT_CLIENT_DATA : clientData);
+ setSimpleField(LockInfoAttribute.CLIENT_DATA.name(), clientData == null ? DEFAULT_CLIENT_DATA : clientData);
}
/**
@@ -174,7 +172,7 @@ public class LockInfo extends DataRecord {
* @param grantTime Long representing the time at which the lock was granted
*/
public void setGrantedAt(Long grantTime) {
- _dataRecord.setLongField(LockInfoAttribute.GRANTED_AT.name(), grantTime);
+ setLongField(LockInfoAttribute.GRANTED_AT.name(), grantTime);
}
/**
@@ -182,7 +180,7 @@ public class LockInfo extends DataRecord {
* @param lastRenewalTime Long representing the time at which the lock was last renewed
*/
public void setLastRenewedAt(Long lastRenewalTime) {
- _dataRecord.setLongField(LockInfoAttribute.LAST_RENEWED_AT.name(), lastRenewalTime);
+ setLongField(LockInfoAttribute.LAST_RENEWED_AT.name(), lastRenewalTime);
}
/**
@@ -191,7 +189,7 @@ public class LockInfo extends DataRecord {
*/
public void setTimeout(long timeout) {
// Always store the timeout value in milliseconds for the sake of simplicity
- _dataRecord.setLongField(LockInfoAttribute.TIMEOUT.name(), timeout);
+ setLongField(LockInfoAttribute.TIMEOUT.name(), timeout);
}
/**
@@ -199,7 +197,7 @@ public class LockInfo extends DataRecord {
* @return the owner id of the lock, {@link #DEFAULT_OWNER_ID_TEXT} if there is no owner id set
*/
public String getOwnerId() {
- return _dataRecord.getStringField(LockInfoAttribute.OWNER_ID.name(), DEFAULT_OWNER_ID_TEXT);
+ return getStringField(LockInfoAttribute.OWNER_ID.name(), DEFAULT_OWNER_ID_TEXT);
}
/**
@@ -207,7 +205,7 @@ public class LockInfo extends DataRecord {
* @return the client id of the lock, {@link #DEFAULT_CLIENT_ID_TEXT} if there is no client id set
*/
public String getClientId() {
- return _dataRecord.getStringField(LockInfoAttribute.CLIENT_ID.name(), DEFAULT_CLIENT_ID_TEXT);
+ return getStringField(LockInfoAttribute.CLIENT_ID.name(), DEFAULT_CLIENT_ID_TEXT);
}
/**
@@ -215,7 +213,7 @@ public class LockInfo extends DataRecord {
* @return the id of the lock, {@link #DEFAULT_LOCK_ID_TEXT} if there is no lock id set
*/
public String getLockId() {
- return _dataRecord.getStringField(LockInfoAttribute.LOCK_ID.name(), DEFAULT_LOCK_ID_TEXT);
+ return getStringField(LockInfoAttribute.LOCK_ID.name(), DEFAULT_LOCK_ID_TEXT);
}
/**
@@ -224,7 +222,7 @@ public class LockInfo extends DataRecord {
* if there is no client data set.
*/
public String getClientData() {
- return _dataRecord.getStringField(LockInfoAttribute.CLIENT_DATA.name(), DEFAULT_CLIENT_DATA);
+ return getStringField(LockInfoAttribute.CLIENT_DATA.name(), DEFAULT_CLIENT_DATA);
}
/**
@@ -233,7 +231,7 @@ public class LockInfo extends DataRecord {
* if there is no grant time set
*/
public Long getGrantedAt() {
- return _dataRecord.getLongField(LockInfoAttribute.GRANTED_AT.name(), DEFAULT_GRANTED_AT_LONG);
+ return getLongField(LockInfoAttribute.GRANTED_AT.name(), DEFAULT_GRANTED_AT_LONG);
}
/**
@@ -242,7 +240,7 @@ public class LockInfo extends DataRecord {
* if there is no renewal time set
*/
public Long getLastRenewedAt() {
- return _dataRecord.getLongField(LockInfoAttribute.LAST_RENEWED_AT.name(), DEFAULT_LAST_RENEWED_AT_LONG);
+ return getLongField(LockInfoAttribute.LAST_RENEWED_AT.name(), DEFAULT_LAST_RENEWED_AT_LONG);
}
/**
@@ -250,7 +248,7 @@ public class LockInfo extends DataRecord {
* @return the expiring time of the lock, {@link #DEFAULT_TIMEOUT_DURATION} if there is no timeout set
*/
public long getTimeout() {
- return _dataRecord.getLongField(LockInfoAttribute.TIMEOUT.name(), DEFAULT_TIMEOUT_DURATION);
+ return getLongField(LockInfoAttribute.TIMEOUT.name(), DEFAULT_TIMEOUT_DURATION);
}
}
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockInfoSerializer.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockInfoSerializer.java
new file mode 100644
index 000000000..20648fbaf
--- /dev/null
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockInfoSerializer.java
@@ -0,0 +1,39 @@
+package org.apache.helix.metaclient.recipes.lock;
+
+/*
+ * 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.
+ */
+
+import org.apache.helix.metaclient.datamodel.DataRecord;
+import org.apache.helix.zookeeper.datamodel.ZNRecord;
+import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class LockInfoSerializer extends ZNRecordSerializer {
+ private static final Logger LOG = LoggerFactory.getLogger(LockInfoSerializer.class);
+ @Override
+ public Object deserialize(byte[] bytes) {
+ try {
+ return new LockInfo(new DataRecord((ZNRecord) super.deserialize(bytes)));
+ } catch (Exception e) {
+ LOG.error("Exception during deserialization of bytes: {}", new String(bytes), e);
+ return null;
+ }
+ }
+}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/lock/LockClientTest.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/lock/LockClientTest.java
index a8ca387ca..672781b08 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/lock/LockClientTest.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/lock/LockClientTest.java
@@ -28,6 +28,13 @@ import org.testng.annotations.Test;
public class LockClientTest extends ZkMetaClientTestBase {
private static final String TEST_INVALID_PATH = "/_invalid/a/b/c";
+ private static final String OWNER_ID = "urn:li:principal:UNKNOWN";
+ private static final String CLIENT_ID = "test_client_id";
+ private static final String CLIENT_DATA = "client_data";
+ private static final String LOCK_ID = "794c8a4c-c14b-4c23-b83f-4e1147fc6978";
+ private static final long GRANT_TIME = System.currentTimeMillis();
+ private static final long LAST_RENEWAL_TIME = System.currentTimeMillis();
+ private static final long TIMEOUT = 100000;
public LockClient createLockClient() {
@@ -37,11 +44,23 @@ public class LockClientTest extends ZkMetaClientTestBase {
return new LockClient(config);
}
+ private LockInfo createLockInfo() {
+ LockInfo lockInfo = new LockInfo();
+ lockInfo.setOwnerId(OWNER_ID);
+ lockInfo.setClientId(CLIENT_ID);
+ lockInfo.setClientData(CLIENT_DATA);
+ lockInfo.setLockId(LOCK_ID);
+ lockInfo.setGrantedAt(GRANT_TIME);
+ lockInfo.setLastRenewedAt(LAST_RENEWAL_TIME);
+ lockInfo.setTimeout(TIMEOUT);
+ return lockInfo;
+ }
+
@Test
public void testAcquireLock() {
final String key = "/TestLockClient_testAcquireLock";
LockClient lockClient = createLockClient();
- LockInfo lockInfo = new LockInfo();
+ LockInfo lockInfo = createLockInfo();
lockClient.acquireLock(key, lockInfo, MetaClientInterface.EntryMode.PERSISTENT);
Assert.assertNotNull(lockClient.retrieveLock(key));
try {
@@ -56,7 +75,7 @@ public class LockClientTest extends ZkMetaClientTestBase {
public void testReleaseLock() {
final String key = "/TestLockClient_testReleaseLock";
LockClient lockClient = createLockClient();
- LockInfo lockInfo = new LockInfo();
+ LockInfo lockInfo = createLockInfo();
lockClient.acquireLock(key, lockInfo, MetaClientInterface.EntryMode.PERSISTENT);
Assert.assertNotNull(lockClient.retrieveLock(key));
@@ -69,7 +88,7 @@ public class LockClientTest extends ZkMetaClientTestBase {
public void testAcquireTTLLock() {
final String key = "/TestLockClient_testAcquireTTLLock";
LockClient lockClient = createLockClient();
- LockInfo lockInfo = new LockInfo();
+ LockInfo lockInfo = createLockInfo();
lockClient.acquireLockWithTTL(key, lockInfo, 1L);
Assert.assertNotNull(lockClient.retrieveLock(key));
try {
@@ -84,9 +103,14 @@ public class LockClientTest extends ZkMetaClientTestBase {
public void testRetrieveLock() {
final String key = "/TestLockClient_testRetrieveLock";
LockClient lockClient = createLockClient();
- LockInfo lockInfo = new LockInfo();
+ LockInfo lockInfo = createLockInfo();
lockClient.acquireLock(key, lockInfo, MetaClientInterface.EntryMode.PERSISTENT);
Assert.assertNotNull(lockClient.retrieveLock(key));
+ Assert.assertEquals(lockClient.retrieveLock(key).getOwnerId(), OWNER_ID);
+ Assert.assertEquals(lockClient.retrieveLock(key).getClientId(), CLIENT_ID);
+ Assert.assertEquals(lockClient.retrieveLock(key).getClientData(), CLIENT_DATA);
+ Assert.assertEquals(lockClient.retrieveLock(key).getLockId(), LOCK_ID);
+ Assert.assertEquals(lockClient.retrieveLock(key).getTimeout(), TIMEOUT);
Assert.assertNull(lockClient.retrieveLock(TEST_INVALID_PATH));
}
@@ -94,12 +118,12 @@ public class LockClientTest extends ZkMetaClientTestBase {
public void testRenewTTLLock() {
final String key = "/TestLockClient_testRenewTTLLock";
LockClient lockClient = createLockClient();
- LockInfo lockInfo = new LockInfo();
+ LockInfo lockInfo = createLockInfo();
lockClient.acquireLockWithTTL(key, lockInfo, 1L);
Assert.assertNotNull(lockClient.retrieveLock(key));
lockClient.renewTTLLock(key);
- Assert.assertNotSame(lockClient.retrieveLock(key).getGrantedAt(), lockInfo.getLastRenewedAt());
+ Assert.assertNotSame(lockClient.retrieveLock(key).getGrantedAt(), lockClient.retrieveLock(key).getLastRenewedAt());
try {
lockClient.renewTTLLock(TEST_INVALID_PATH);
Assert.fail("Should not be able to renew lock for key: " + key);
[helix] 08/21: MetaClient Distributed Semaphore API and Permit object (#2520)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 0e917599cce521b1ca5fdaf60a13b8dc5cf9d1d0
Author: Marcos Rico Peng <55...@users.noreply.github.com>
AuthorDate: Sun Jun 11 00:53:46 2023 -0400
MetaClient Distributed Semaphore API and Permit object (#2520)
MetaClient Distributed Semaphore API and Permit object
---------
Co-authored-by: mapeng <ma...@linkedin.com>
---
.../recipes/lock/DistributedSemaphore.java | 148 +++++++++++++++++++++
.../helix/metaclient/recipes/lock/Permit.java | 87 ++++++++++++
2 files changed, 235 insertions(+)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java
new file mode 100644
index 000000000..0cccb130f
--- /dev/null
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java
@@ -0,0 +1,148 @@
+package org.apache.helix.metaclient.recipes.lock;
+
+/*
+ * 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.
+ */
+
+import org.apache.commons.lang3.NotImplementedException;
+import org.apache.helix.metaclient.api.MetaClientInterface;
+import org.apache.helix.metaclient.datamodel.DataRecord;
+import org.apache.helix.metaclient.factories.MetaClientConfig;
+import java.util.Collection;
+import java.util.concurrent.TimeUnit;
+
+public class DistributedSemaphore {
+
+ /**
+ * Create a distributed semaphore client with the given configuration.
+ * @param config configuration of the client
+ */
+ public DistributedSemaphore(MetaClientConfig config) {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Connect to an existing distributed semaphore client.
+ * @param client client to connect to
+ */
+ public DistributedSemaphore(MetaClientInterface<DataRecord> client) {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Create a distributed semaphore with the given path and capacity.
+ * @param path path of the semaphore
+ * @param capacity capacity of the semaphore
+ */
+ public void createSemaphore(String path, int capacity) {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Connect to an existing distributed semaphore.
+ * @param path path of the semaphore
+ */
+ public void connectSemaphore(String path) {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Acquire a permit. If no permit is available, log error and return null.
+ * @return a permit
+ */
+ public Permit acquire() {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+
+ /**
+ * Try to acquire multiple permits. If not enough permits are available, log error and return null.
+ * @param count number of permits to acquire
+ * @return a collection of permits
+ */
+ public Collection<Permit> acquire(int count) {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Try to acquire a permit. If no enough permit is available, wait for a specific time or return when it was able to acquire.
+ * If timeout <=0, then return immediately when not able to acquire.
+ * @param count number of permits to acquire
+ * @param timeout time to wait
+ * @param unit time unit
+ * @return a collection of permits
+ */
+ public Collection<Permit> acquire(int count, long timeout, TimeUnit unit) {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Get the remaining capacity of the semaphore
+ * @return remaining capacity
+ */
+ public long getRemainingCapacity() {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Get the semaphore data record
+ * @return semaphore data record
+ */
+ private DataRecord getSemaphore() {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Return a permit. If the permit is already returned, log and return void.
+ */
+ public void returnPermit(Permit permit) {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Return a collection of permits. If a permit in that collection is already returned,
+ * log and return void.
+ */
+ public void returnAllPermits(Collection<Permit> permits) {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Retrieve a permit from the semaphore data record.
+ * @param path path of the permit
+ * @return a permit
+ */
+ private Permit retrievePermit(String path) {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Update the remaining capacity of the semaphore after acquiring a permit.
+ * @param count number of permits to acquire
+ */
+ private void updateAcquirePermit(int count) {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+
+ /**
+ * Update the remaining capacity of the semaphore after returning a permit.
+ */
+ private void updateReturnPermit() {
+ throw new NotImplementedException("Not implemented yet.");
+ }
+}
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/Permit.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/Permit.java
new file mode 100644
index 000000000..5af31b59a
--- /dev/null
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/Permit.java
@@ -0,0 +1,87 @@
+package org.apache.helix.metaclient.recipes.lock;
+
+/*
+ * 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.
+ */
+
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import org.apache.helix.metaclient.api.MetaClientInterface;
+import org.apache.helix.metaclient.datamodel.DataRecord;
+
+import java.util.concurrent.locks.Lock;
+
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+public class Permit extends DataRecord {
+
+ private static final String DEFAULT_PERMIT_INFO = "permitInfo";
+ public static final long DEFAULT_TIME_PERMIT_ACQUIRED = -1L;
+ public static final long DEFAULT_TIME_SEMAPHORE_CREATED = -1L;
+ private boolean _isReleased;
+
+ public enum PermitAttribute {
+ TIME_PERMIT_ACQUIRED,
+ TIME_SEMAPHORE_CREATED
+ }
+ public Permit() {
+ super(DEFAULT_PERMIT_INFO);
+ setPermitFields(DEFAULT_TIME_PERMIT_ACQUIRED, DEFAULT_TIME_SEMAPHORE_CREATED);
+ }
+ public Permit(DataRecord record) {
+ this();
+ if (record != null) {
+ long timePermitAcquired = record.getLongField(PermitAttribute.TIME_PERMIT_ACQUIRED.name(), DEFAULT_TIME_PERMIT_ACQUIRED);
+ long timeSemaphoreCreated = record.getLongField(PermitAttribute.TIME_SEMAPHORE_CREATED.name(), DEFAULT_TIME_SEMAPHORE_CREATED);
+ setPermitFields(timePermitAcquired, timeSemaphoreCreated);
+ }
+ }
+
+ public Permit(DataRecord record, MetaClientInterface.Stat stat) {
+ this(record);
+ setTimeSemaphoreCreated(stat.getCreationTime());
+ setTimePermitAcquired(stat.getModifiedTime());
+ }
+
+ public void setPermitFields(long timePermitAcquired, long timeSemaphoreCreated) {
+ setTimePermitAcquired(timePermitAcquired);
+ setTimeSemaphoreCreated(timeSemaphoreCreated);
+ _isReleased = false;
+ }
+
+ public void setTimePermitAcquired(long timePermitAcquired) {
+ setLongField(PermitAttribute.TIME_PERMIT_ACQUIRED.name(), timePermitAcquired);
+ }
+
+ public void setTimeSemaphoreCreated(long timeSemaphoreCreated) {
+ setLongField(PermitAttribute.TIME_SEMAPHORE_CREATED.name(), timeSemaphoreCreated);
+ }
+
+ public void getTimePermitAcquired() {
+ getLongField(PermitAttribute.TIME_PERMIT_ACQUIRED.name(), DEFAULT_TIME_PERMIT_ACQUIRED);
+ }
+
+ public void getTimeSemaphoreCreated() {
+ getLongField(PermitAttribute.TIME_SEMAPHORE_CREATED.name(), DEFAULT_TIME_SEMAPHORE_CREATED);
+ }
+
+ public boolean isReleased() {
+ return _isReleased;
+ }
+ public void releasePermit() {
+ _isReleased = true;
+ }
+}
[helix] 07/21: [helix/metaclient] ZkMetaClient Stress Tests (Part 2) (#2523)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 09649b34c4941adfab951defa52975683393bb80
Author: Marcos Rico Peng <55...@users.noreply.github.com>
AuthorDate: Wed Jun 7 17:36:51 2023 -0400
[helix/metaclient] ZkMetaClient Stress Tests (Part 2) (#2523)
ZkMetaClient Stress Tests (Part 2)
---------
Co-authored-by: mapeng <ma...@linkedin.com>
---
.../metaclient/impl/zk/TestStressZkClient.java | 96 +++++++++++++++++++---
1 file changed, 83 insertions(+), 13 deletions(-)
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
index 393a17f1b..8a3f9c115 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
@@ -19,27 +19,18 @@ package org.apache.helix.metaclient.impl.zk;
* under the License.
*/
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
+import java.util.List;
+import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
-import org.apache.helix.metaclient.api.DataChangeListener;
-import org.apache.helix.metaclient.api.DataUpdater;
-import org.apache.helix.metaclient.api.MetaClientInterface;
+
+import org.apache.helix.metaclient.api.*;
import org.apache.helix.metaclient.datamodel.DataRecord;
import org.apache.helix.metaclient.exception.MetaClientException;
import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig;
import org.apache.helix.metaclient.recipes.lock.DataRecordSerializer;
-import org.apache.helix.zookeeper.datamodel.ZNRecord;
-import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer;
-import org.apache.helix.zookeeper.exception.ZkClientException;
-import org.junit.Before;
import org.testng.Assert;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
@@ -114,6 +105,29 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
}
+ @Test
+ public void testCreateAndRenewTTL() {
+ final String zkParentKey = "/stressZk_testCreateAndRenewTTL";
+ _zkMetaClient.create(zkParentKey, ENTRY_STRING_VALUE);
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ _zkMetaClient.createWithTTL(zkParentKey + i, ENTRY_STRING_VALUE, 10000);
+ }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertNotNull(_zkMetaClient.exists(zkParentKey));
+ }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ _zkMetaClient.renewTTLNode(zkParentKey + i);
+ }
+ MetaClientInterface.Stat stat;
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ stat = _zkMetaClient.exists(zkParentKey + i);
+ Assert.assertNotSame(stat.getCreationTime(), stat.getModifiedTime());
+ }
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
+ }
+
@Test
public void testGet() {
final String zkParentKey = "/stressZk_testGet";
@@ -369,4 +383,60 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
_zkMetaClient.recursiveDelete(zkParentKey);
Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
}
+
+ @Test
+ public void testTransactionOps() {
+ String zkParentKey = "/stressZk_testTransactionOp";
+ _zkMetaClient.create(zkParentKey, "parent_node");
+
+ // Transaction Create
+ List<Op> ops = new ArrayList<>();
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ ops.add(Op.create(zkParentKey + "/" + i, new byte[0], PERSISTENT));
+ }
+ List<OpResult> opResults = _zkMetaClient.transactionOP(ops);
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertTrue(opResults.get(i) instanceof OpResult.CreateResult);
+ }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertNotNull(_zkMetaClient.exists(zkParentKey + "/" + i));
+ }
+
+ // Transaction Set
+ List<Op> ops_set = new ArrayList<>();
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ ops_set.add(Op.set(zkParentKey + "/" + i, new byte[0], -1));
+ }
+ List<OpResult> opsResultSet = _zkMetaClient.transactionOP(ops_set);
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertTrue(opsResultSet.get(i) instanceof OpResult.SetDataResult);
+ }
+
+ // Transaction Delete
+ List<Op> ops_delete = new ArrayList<>();
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ ops_delete.add(Op.delete(zkParentKey + "/" + i, -1));
+ }
+ List<OpResult> opsResultDelete = _zkMetaClient.transactionOP(ops_delete);
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertTrue(opsResultDelete.get(i) instanceof OpResult.DeleteResult);
+ }
+
+ // Transaction Create
+ List<Op> ops_error = new ArrayList<>();
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ ops_error.add(Op.create("/_invalid/a/b/c" + "/" + i, new byte[0], PERSISTENT));
+ }
+ try {
+ _zkMetaClient.transactionOP(ops_error);
+ Assert.fail("Should fail");
+ } catch (Exception e) {
+ // OK
+ }
+
+
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
+ }
}
\ No newline at end of file
[helix] 11/21: MetaClient LockClient and Semaphore Creation Edge Cases and Added Exception(#2550)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit f41a2c606c715a5da436c47f5063978e893aee68
Author: Marcos Rico Peng <55...@users.noreply.github.com>
AuthorDate: Wed Jul 12 13:07:21 2023 -0400
MetaClient LockClient and Semaphore Creation Edge Cases and Added Exception(#2550)
Co-authored-by: mapeng <ma...@linkedin.com>
---
.../helix/metaclient/api/MetaClientInterface.java | 6 ++++
.../exception/MetaClientNodeExistsException.java | 38 ++++++++++++++++++++++
.../helix/metaclient/impl/zk/ZkMetaClient.java | 5 +++
.../metaclient/impl/zk/util/ZkMetaClientUtil.java | 4 +++
.../recipes/lock/DistributedSemaphore.java | 7 ++--
.../helix/metaclient/recipes/lock/LockClient.java | 6 ++--
6 files changed, 62 insertions(+), 4 deletions(-)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/api/MetaClientInterface.java b/meta-client/src/main/java/org/apache/helix/metaclient/api/MetaClientInterface.java
index b4bfaac2e..5b26896a9 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/api/MetaClientInterface.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/api/MetaClientInterface.java
@@ -429,6 +429,12 @@ public interface MetaClientInterface<T> {
*/
void disconnect();
+ /**
+ * Check whether client is closed
+ * @return true if client is closed, false otherwise
+ */
+ boolean isClosed();
+
/**
* @return client current connection state with metadata service.
*/
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/exception/MetaClientNodeExistsException.java b/meta-client/src/main/java/org/apache/helix/metaclient/exception/MetaClientNodeExistsException.java
new file mode 100644
index 000000000..74e6d4f0f
--- /dev/null
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/exception/MetaClientNodeExistsException.java
@@ -0,0 +1,38 @@
+package org.apache.helix.metaclient.exception;
+
+/*
+ * 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.
+ */
+
+public final class MetaClientNodeExistsException extends MetaClientException {
+ public MetaClientNodeExistsException() {
+ super();
+ }
+
+ public MetaClientNodeExistsException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public MetaClientNodeExistsException(String message) {
+ super(message);
+ }
+
+ public MetaClientNodeExistsException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
index fc8998e95..a1b6eb1ad 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
@@ -420,6 +420,11 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
disconnect();
}
+ @Override
+ public boolean isClosed() {
+ return _zkClient.isClosed();
+ }
+
@Override
public List<OpResult> transactionOP(Iterable<Op> ops) {
// Convert list of MetaClient Ops to Zk Ops
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java
index 6bf0ce74b..dec8711cf 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java
@@ -34,11 +34,13 @@ import org.apache.helix.metaclient.exception.MetaClientException;
import org.apache.helix.metaclient.exception.MetaClientInterruptException;
import org.apache.helix.metaclient.exception.MetaClientNoNodeException;
import org.apache.helix.metaclient.exception.MetaClientTimeoutException;
+import org.apache.helix.metaclient.exception.MetaClientNodeExistsException;
import org.apache.helix.zookeeper.zkclient.exception.ZkBadVersionException;
import org.apache.helix.zookeeper.zkclient.exception.ZkException;
import org.apache.helix.zookeeper.zkclient.exception.ZkInterruptedException;
import org.apache.helix.zookeeper.zkclient.exception.ZkNoNodeException;
import org.apache.helix.zookeeper.zkclient.exception.ZkTimeoutException;
+import org.apache.helix.zookeeper.zkclient.exception.ZkNodeExistsException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Op;
@@ -235,6 +237,8 @@ public class ZkMetaClientUtil {
return new MetaClientTimeoutException(e);
} else if (e instanceof ZkInterruptedException) {
return new MetaClientInterruptException(e);
+ } else if (e instanceof ZkNodeExistsException) {
+ return new MetaClientNodeExistsException(e);
}
return new MetaClientException(e);
}
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java
index 7b16e78fd..b5660bed9 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java
@@ -26,6 +26,7 @@ import org.apache.helix.metaclient.exception.MetaClientException;
import org.apache.helix.metaclient.factories.MetaClientConfig;
import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig;
import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientFactory;
+import org.apache.helix.metaclient.impl.zk.util.ZkMetaClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -73,11 +74,13 @@ public class DistributedSemaphore {
}
LOG.info("Connecting to existing DistributedSemaphore Client");
_metaClient = client;
+ if (_metaClient.isClosed()) {
+ throw new IllegalStateException("Client already closed!");
+ }
try {
_metaClient.connect();
- // TODO: Differentiate exception catch between already connected and already closed.
} catch (IllegalStateException e) {
- // Ignore as it either has already been connected or already been closed.
+ // Already connected.
}
}
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java
index 8a9c489e3..480e87c30 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java
@@ -64,11 +64,13 @@ public class LockClient implements LockClientInterface, AutoCloseable {
throw new IllegalArgumentException("MetaClient cannot be null.");
}
_metaClient = client;
+ if (_metaClient.isClosed()) {
+ throw new IllegalStateException("Client already closed!");
+ }
try {
- LOG.info("Connecting to existing MetaClient for LockClient");
_metaClient.connect();
} catch (IllegalStateException e) {
- // Ignore as it either has already been connected or already been closed.
+ // Already connected.
}
}
[helix] 14/21: Metaclient leader election - basics (#2558)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 36231faebaf85559c39578b1ce1bab71903d35e4
Author: xyuanlu <xy...@gmail.com>
AuthorDate: Tue Jul 18 09:41:55 2023 -0700
Metaclient leader election - basics (#2558)
Co-authored-by: Xiaoyuan Lu <xi...@xialu-mn2.linkedin.biz>
---
.../org/apache/helix/metaclient/api/OpResult.java | 2 +-
.../helix/metaclient/datamodel/DataRecord.java | 5 +
.../helix/metaclient/impl/zk/ZkMetaClient.java | 50 +++--
.../metaclient/impl/zk/util/ZkMetaClientUtil.java | 2 +-
.../leaderelection/LeaderElectionClient.java | 204 ++++++++++++++++++---
.../recipes/leaderelection/LeaderInfo.java | 34 +++-
.../leaderelection/LeaderInfoSerializer.java | 42 +++++
.../java/org/apache/helix/metaclient/TestUtil.java | 22 +++
.../recipes/leaderelection/TestLeaderElection.java | 64 +++++++
.../datamodel/serializer/ZNRecordSerializer.java | 2 +-
.../helix/zookeeper/zkclient/ZkConnection.java | 1 +
11 files changed, 366 insertions(+), 62 deletions(-)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/api/OpResult.java b/meta-client/src/main/java/org/apache/helix/metaclient/api/OpResult.java
index effed8543..e3621190a 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/api/OpResult.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/api/OpResult.java
@@ -26,7 +26,7 @@ import java.util.List;
*/
public class OpResult {
- enum Type {
+ public enum Type {
ERRORRESULT,
GETDATARESULT,
GETCHILDRENRESULT,
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/datamodel/DataRecord.java b/meta-client/src/main/java/org/apache/helix/metaclient/datamodel/DataRecord.java
index 3ed6928f1..91e5409ca 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/datamodel/DataRecord.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/datamodel/DataRecord.java
@@ -20,6 +20,7 @@ package org.apache.helix.metaclient.datamodel;
*/
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import org.apache.helix.metaclient.recipes.leaderelection.LeaderInfo;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
/**
@@ -35,4 +36,8 @@ public class DataRecord extends ZNRecord {
public DataRecord(ZNRecord record) {
super(record);
}
+
+ public DataRecord(DataRecord record, String id) {
+ super(record, id);
+ }
}
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
index a1b6eb1ad..7f68ec9ca 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
@@ -83,17 +83,15 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
// Lock all activities related to ZkClient connection
private ReentrantLock _zkClientConnectionMutex = new ReentrantLock();
-
public ZkMetaClient(ZkMetaClientConfig config) {
_initConnectionTimeout = config.getConnectionInitTimeoutInMillis();
_reconnectTimeout = config.getMetaClientReconnectPolicy().getAutoReconnectTimeout();
// TODO: Right new ZkClient reconnect using exp backoff with fixed max backoff interval. We should
// Allow user to config reconnect policy
- _zkClient = new ZkClient(
- new ZkConnection(config.getConnectionAddress(), (int) config.getSessionTimeoutInMillis()),
+ _zkClient = new ZkClient(new ZkConnection(config.getConnectionAddress(), (int) config.getSessionTimeoutInMillis()),
(int) _initConnectionTimeout, _reconnectTimeout /*use reconnect timeout for retry timeout*/,
- config.getZkSerializer(), config.getMonitorType(), config.getMonitorKey(),
- config.getMonitorInstanceName(), config.getMonitorRootPathOnly(), false, true);
+ config.getZkSerializer(), config.getMonitorType(), config.getMonitorKey(), config.getMonitorInstanceName(),
+ config.getMonitorRootPathOnly(), false, true);
_zkClientReconnectMonitor = Executors.newSingleThreadScheduledExecutor();
_reconnectStateChangeListener = new ReconnectStateChangeListener();
}
@@ -102,6 +100,8 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
public void create(String key, Object data) {
try {
create(key, data, EntryMode.PERSISTENT);
+ } catch (ZkException e) {
+ throw ZkMetaClientUtil.translateZkExceptionToMetaclientException(e);
} catch (Exception e) {
throw new MetaClientException(e);
}
@@ -110,16 +110,18 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
@Override
public void create(String key, Object data, MetaClientInterface.EntryMode mode) {
- try{
+ try {
_zkClient.create(key, data, ZkMetaClientUtil.convertMetaClientMode(mode));
- } catch (ZkException | KeeperException e) {
+ } catch (ZkException e) {
+ throw ZkMetaClientUtil.translateZkExceptionToMetaclientException(e);
+ } catch (KeeperException e) {
throw new MetaClientException(e);
}
}
@Override
public void createWithTTL(String key, T data, long ttl) {
- try{
+ try {
_zkClient.createPersistentWithTTL(key, data, ttl);
} catch (ZkException e) {
throw translateZkExceptionToMetaclientException(e);
@@ -178,7 +180,6 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
return _zkClient.readData(key, true);
}
-
@Override
public ImmutablePair<T, Stat> getDataAndStat(final String key) {
try {
@@ -231,8 +232,7 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
// corresponding callbacks for each operation are invoked in order.
@Override
public void setAsyncExecPoolSize(int poolSize) {
- throw new UnsupportedOperationException(
- "All async calls are executed in a single thread to maintain sequence.");
+ throw new UnsupportedOperationException("All async calls are executed in a single thread to maintain sequence.");
}
@Override
@@ -243,8 +243,7 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
} catch (ZkException | KeeperException e) {
throw new MetaClientException(e);
}
- _zkClient.asyncCreate(key, data, entryMode,
- new ZkMetaClientCreateCallbackHandler(cb));
+ _zkClient.asyncCreate(key, data, entryMode, new ZkMetaClientCreateCallbackHandler(cb));
}
@Override
@@ -258,14 +257,12 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
@Override
public void asyncGet(String key, AsyncCallback.DataCallback cb) {
- _zkClient.asyncGetData(key,
- new ZkMetaClientGetCallbackHandler(cb));
+ _zkClient.asyncGetData(key, new ZkMetaClientGetCallbackHandler(cb));
}
@Override
public void asyncCountChildren(String key, AsyncCallback.DataCallback cb) {
- throw new NotImplementedException(
- "Currently asyncCountChildren is not supported in ZkMetaClient.");
+ throw new NotImplementedException("Currently asyncCountChildren is not supported in ZkMetaClient.");
/*
* TODO: Only Helix has potential using this API as of now. (ZkBaseDataAccessor.getChildren())
* Will move impl from ZkBaseDataAccessor to here when retiring ZkBaseDataAccessor.
@@ -275,8 +272,7 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
@Override
public void asyncExist(String key, AsyncCallback.StatCallback cb) {
- _zkClient.asyncExists(key,
- new ZkMetaClientExistCallbackHandler(cb));
+ _zkClient.asyncExists(key, new ZkMetaClientExistCallbackHandler(cb));
}
public void asyncDelete(String key, AsyncCallback.VoidCallback cb) {
@@ -285,16 +281,14 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
@Override
public void asyncTransaction(Iterable<Op> ops, AsyncCallback.TransactionCallback cb) {
- throw new NotImplementedException(
- "Currently asyncTransaction is not supported in ZkMetaClient.");
+ throw new NotImplementedException("Currently asyncTransaction is not supported in ZkMetaClient.");
- //TODO: There is no active use case for Async transaction.
+ //TODO: There is no active use case for Async transaction.
}
@Override
public void asyncSet(String key, T data, int version, AsyncCallback.StatCallback cb) {
- _zkClient.asyncSetData(key, data, version,
- new ZkMetaClientSetCallbackHandler(cb));
+ _zkClient.asyncSetData(key, data, version, new ZkMetaClientSetCallbackHandler(cb));
}
@Override
@@ -332,8 +326,8 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
}
@Override
- public DirectChildSubscribeResult subscribeDirectChildChange(String key,
- DirectChildChangeListener listener, boolean skipWatchingNonExistNode) {
+ public DirectChildSubscribeResult subscribeDirectChildChange(String key, DirectChildChangeListener listener,
+ boolean skipWatchingNonExistNode) {
ChildrenSubscribeResult result =
_zkClient.subscribeChildChanges(key, new DirectChildListenerAdapter(listener), skipWatchingNonExistNode);
return new DirectChildSubscribeResult(result.getChildren(), result.isInstalled());
@@ -466,7 +460,6 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
_reconnectMonitorFuture.cancel(true);
LOG.info("ZkClient reconnect monitor thread is canceled");
}
-
} finally {
_zkClientConnectionMutex.unlock();
}
@@ -539,8 +532,7 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
cleanUpAndClose(false, true);
}
}, _reconnectTimeout, TimeUnit.MILLISECONDS);
- LOG.info("ZkClient is Disconnected, schedule a reconnect monitor after {}",
- _reconnectTimeout);
+ LOG.info("ZkClient is Disconnected, schedule a reconnect monitor after {}", _reconnectTimeout);
}
} finally {
_zkClientConnectionMutex.unlock();
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java
index dec8711cf..f93e98919 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/util/ZkMetaClientUtil.java
@@ -39,8 +39,8 @@ import org.apache.helix.zookeeper.zkclient.exception.ZkBadVersionException;
import org.apache.helix.zookeeper.zkclient.exception.ZkException;
import org.apache.helix.zookeeper.zkclient.exception.ZkInterruptedException;
import org.apache.helix.zookeeper.zkclient.exception.ZkNoNodeException;
-import org.apache.helix.zookeeper.zkclient.exception.ZkTimeoutException;
import org.apache.helix.zookeeper.zkclient.exception.ZkNodeExistsException;
+import org.apache.helix.zookeeper.zkclient.exception.ZkTimeoutException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Op;
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
index 4f609153b..d5bdb735a 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
@@ -19,10 +19,27 @@ package org.apache.helix.metaclient.recipes.leaderelection;
* under the License.
*/
+import java.util.Arrays;
+import java.util.ConcurrentModificationException;
+import java.util.HashSet;
import java.util.List;
+import java.util.Set;
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.helix.metaclient.api.DataChangeListener;
import org.apache.helix.metaclient.api.MetaClientInterface;
+import org.apache.helix.metaclient.api.Op;
+import org.apache.helix.metaclient.api.OpResult;
+import org.apache.helix.metaclient.exception.MetaClientException;
+import org.apache.helix.metaclient.exception.MetaClientNoNodeException;
+import org.apache.helix.metaclient.exception.MetaClientNodeExistsException;
import org.apache.helix.metaclient.factories.MetaClientConfig;
+import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig;
+import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.helix.metaclient.api.OpResult.Type.*;
/**
@@ -42,7 +59,17 @@ import org.apache.helix.metaclient.factories.MetaClientConfig;
* When the client is used by a leader election service, one client is created for each participant.
*
*/
-public class LeaderElectionClient {
+public class LeaderElectionClient implements AutoCloseable {
+
+ private final MetaClientInterface<LeaderInfo> _metaClient;
+ private final String _participant;
+ private static final Logger LOG = LoggerFactory.getLogger(LeaderElectionClient.class);
+
+ // A list of leader election group that this client joins.
+ private Set<String> _leaderGroups = new HashSet<>();
+
+ private final static String LEADER_ENTRY_KEY = "/LEADER";
+ ReElectListener _reElectListener = new ReElectListener();
/**
* Construct a LeaderElectionClient using a user passed in leaderElectionConfig. It creates a MetaClient
@@ -53,25 +80,37 @@ public class LeaderElectionClient {
* @param metaClientConfig The config used to create an metaclient.
*/
public LeaderElectionClient(MetaClientConfig metaClientConfig, String participant) {
-
+ _participant = participant;
+ if (metaClientConfig == null) {
+ throw new IllegalArgumentException("MetaClientConfig cannot be null.");
+ }
+ LOG.info("Creating MetaClient for LeaderElectionClient");
+ if (MetaClientConfig.StoreType.ZOOKEEPER.equals(metaClientConfig.getStoreType())) {
+ ZkMetaClientConfig zkMetaClientConfig = new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(
+ metaClientConfig.getConnectionAddress()).setZkSerializer((new LeaderInfoSerializer())).build();
+ _metaClient = new ZkMetaClientFactory().getMetaClient(zkMetaClientConfig);
+ _metaClient.connect();
+ } else {
+ throw new MetaClientException("Unsupported store type: " + metaClientConfig.getStoreType());
+ }
}
/**
* Construct a LeaderElectionClient using a user passed in MetaClient object
- * When MetaClient is auto closed be cause of being disconnected and auto retry connection timed out, user
+ * When MetaClient is auto closed because of being disconnected and auto retry connection timed out, user
* will need to create a new MetaClient and a new LeaderElectionClient instance.
*
* @param metaClient metaClient object to be used.
*/
- public LeaderElectionClient(MetaClientInterface metaClient, String participant) {
-
+ public LeaderElectionClient(MetaClientInterface<LeaderInfo> metaClient, String participant) {
+ throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Returns true if current participant is the current leadership.
*/
public boolean isLeader(String leaderPath) {
- return false;
+ return getLeader(leaderPath).equalsIgnoreCase(_participant);
}
/**
@@ -79,10 +118,11 @@ public class LeaderElectionClient {
* The Leader Election client maintains and elect an active leader from the participant pool.
*
* @param leaderPath The path for leader election.
- * @return boolean indicating if the operation is succeeded.
+ * @throws RuntimeException if the operation is not succeeded.
*/
- public boolean joinLeaderElectionParticipantPool(String leaderPath) {
- return false;
+ public void joinLeaderElectionParticipantPool(String leaderPath) {
+ // TODO: create participant entry
+ subscribeAndTryCreateLeaderEntry(leaderPath);
}
/**
@@ -91,10 +131,46 @@ public class LeaderElectionClient {
*
* @param leaderPath The path for leader election.
* @param userInfo Any additional information to associate with this participant.
- * @return boolean indicating if the operation is succeeded.
+ * @throws RuntimeException if the operation is not succeeded.
*/
- public boolean joinLeaderElectionParticipantPool(String leaderPath, Object userInfo) {
- return false;
+ public void joinLeaderElectionParticipantPool(String leaderPath, LeaderInfo userInfo) {
+ // TODO: create participant entry with info
+ subscribeAndTryCreateLeaderEntry(leaderPath);
+ }
+
+ private void subscribeAndTryCreateLeaderEntry(String leaderPath) {
+ _metaClient.subscribeDataChange(leaderPath + LEADER_ENTRY_KEY, _reElectListener, false);
+ LeaderInfo leaderInfo = new LeaderInfo(LEADER_ENTRY_KEY);
+ leaderInfo.setLeaderName(_participant);
+
+ try {
+ // try to create leader entry, assuming leader election group node is already there
+ _metaClient.create(leaderPath + LEADER_ENTRY_KEY, leaderInfo, MetaClientInterface.EntryMode.EPHEMERAL);
+ } catch (MetaClientNodeExistsException ex) {
+ LOG.info("Already a leader for group {}", leaderPath);
+ } catch (MetaClientNoNodeException ex) {
+ try {
+ // try to create leader path root entry
+ _metaClient.create(leaderPath, null);
+ } catch (MetaClientNodeExistsException ignored) {
+ // root entry created by other client, ignore
+ } catch (MetaClientNoNodeException e) {
+ // Parent entry of user provided leader election group path missing.
+ // (e.g. `/a/b` not created in user specified leader election group path /a/b/c/LeaderGroup)
+ throw new MetaClientException("Parent entry in leaderGroup path" + leaderPath + " does not exist.");
+ }
+ try {
+ // try to create leader node again.
+ _metaClient.create(leaderPath + LEADER_ENTRY_KEY, leaderInfo, MetaClientInterface.EntryMode.EPHEMERAL);
+ } catch (MetaClientNoNodeException e) {
+ // Leader group root entry is gone after we checked at outer catch block.
+ // Meaning other client removed the group. Throw ConcurrentModificationException.
+ throw new ConcurrentModificationException(
+ "Other client trying to modify the leader election group at the same time, please retry.", ex);
+ }
+ }
+
+ _leaderGroups.add(leaderPath + LEADER_ENTRY_KEY);
}
/**
@@ -106,23 +182,64 @@ public class LeaderElectionClient {
* Throws exception if the participant is not in the pool.
*
* @param leaderPath The path for leader election.
- * @return boolean indicating if the operation is succeeded.
+ * @throws RuntimeException if the operation is not succeeded.
*
- * @throws RuntimeException If the participant did not join participant pool via this client. // TODO: define exp type
+ * @throws RuntimeException If the participant did not join participant pool via this client.
*/
- public boolean exitLeaderElectionParticipantPool(String leaderPath) {
- return false;
+ public void exitLeaderElectionParticipantPool(String leaderPath) {
+ _metaClient.unsubscribeDataChange(leaderPath + LEADER_ENTRY_KEY, _reElectListener);
+ // TODO: remove from pool folder
+ relinquishLeaderHelper(leaderPath, true);
}
/**
- * Releases leadership for participant.
+ * Releases leadership for participant. Still stays in the participant pool.
*
* @param leaderPath The path for leader election.
*
* @throws RuntimeException if the leadership is not owned by this participant, or if the
- * participant did not join participant pool via this client. // TODO: define exp type
+ * participant did not join participant pool via this client.
*/
public void relinquishLeader(String leaderPath) {
+ relinquishLeaderHelper(leaderPath, false);
+ }
+
+ /**
+ * relinquishLeaderHelper and LeaderElectionParticipantPool if configured
+ * @param leaderPath
+ * @param exitLeaderElectionParticipantPool
+ */
+ private void relinquishLeaderHelper(String leaderPath, Boolean exitLeaderElectionParticipantPool) {
+ String key = leaderPath + LEADER_ENTRY_KEY;
+ // if current client is in the group
+ if (!_leaderGroups.contains(key)) {
+ throw new MetaClientException("Participant is not in the leader election group");
+ }
+ // remove leader path from leaderGroups after check if exiting the pool.
+ // to prevent a race condition in In Zk implementation:
+ // If there are delays in ZkClient event queue, it is possible the leader election client received leader
+ // deleted event after unsubscribeDataChange. We will need to remove it from in memory `leaderGroups` map before
+ // deleting ZNode. So that handler in ReElectListener won't recreate the leader node.
+ if (exitLeaderElectionParticipantPool) {
+ _leaderGroups.remove(leaderPath + LEADER_ENTRY_KEY);
+ }
+ // check if current participant is the leader
+ // read data and stats, check, and multi check + delete
+ ImmutablePair<LeaderInfo, MetaClientInterface.Stat> tup = _metaClient.getDataAndStat(key);
+ if (tup.left.getLeaderName().equalsIgnoreCase(_participant)) {
+ int expectedVersion = tup.right.getVersion();
+ List<Op> ops = Arrays.asList(Op.check(key, expectedVersion), Op.delete(key, expectedVersion));
+ //Execute transactional support on operations
+ List<OpResult> opResults = _metaClient.transactionOP(ops);
+ if (opResults.get(0).getType() == ERRORRESULT) {
+ if (isLeader(leaderPath)) {
+ // Participant re-elected as leader.
+ throw new ConcurrentModificationException("Concurrent operation, please retry");
+ } else {
+ LOG.info("Someone else is already leader");
+ }
+ }
+ }
}
/**
@@ -133,6 +250,12 @@ public class LeaderElectionClient {
* @throws RuntimeException when leader path does not exist. // TODO: define exp type
*/
public String getLeader(String leaderPath) {
+ LeaderInfo leaderInfo = _metaClient.get(leaderPath + LEADER_ENTRY_KEY);
+ return leaderInfo == null ? null : leaderInfo.getLeaderName();
+ }
+
+ public LeaderInfo getParticipantInfo(String leaderPath) {
+ // TODO: add getParticipantInfo impl
return null;
}
@@ -158,14 +281,14 @@ public class LeaderElectionClient {
* get's auto-deleted after TTL or session timeout) or a new leader comes up, it notifies all
* participants who have been listening on entryChange event.
*
- * An listener will still be installed if the path does not exists yet.
+ * A listener will still be installed if the path does not exist yet.
*
* @param leaderPath The path for leader election that listener is interested for change.
* @param listener An implementation of LeaderElectionListenerInterface
- * @return an boolean value indicating if registration is success.
+ * @return A boolean value indicating if registration is success.
*/
- public boolean subscribeLeadershipChanges(String leaderPath,
- LeaderElectionListenerInterface listener) {
+ public boolean subscribeLeadershipChanges(String leaderPath, LeaderElectionListenerInterface listener) {
+ //TODO: add converter class for LeaderElectionListenerInterface
return false;
}
@@ -173,8 +296,41 @@ public class LeaderElectionClient {
* @param leaderPath The path for leader election that listener is no longer interested for change.
* @param listener An implementation of LeaderElectionListenerInterface
*/
- public void unsubscribeLeadershipChanges(String leaderPath,
- LeaderElectionListenerInterface listener) {
+ public void unsubscribeLeadershipChanges(String leaderPath, LeaderElectionListenerInterface listener) {
+ }
+
+ @Override
+ public void close() throws Exception {
+
+ // exit all previous joined leader election groups
+ for (String leaderGroup : _leaderGroups) {
+ String leaderGroupPathName =
+ leaderGroup.substring(0, leaderGroup.length() - LEADER_ENTRY_KEY.length() /*remove '/LEADER' */);
+ exitLeaderElectionParticipantPool(leaderGroupPathName);
+ }
+
+ // TODO: if last participant, remove folder
+ _metaClient.disconnect();
+ }
+
+ class ReElectListener implements DataChangeListener {
+
+ @Override
+ public void handleDataChange(String key, Object data, ChangeType changeType) throws Exception {
+ if (changeType == ChangeType.ENTRY_CREATED) {
+ LOG.info("new leader {} for leader election group {}.", ((LeaderInfo) data).getLeaderName(), key);
+ } else if (changeType == ChangeType.ENTRY_DELETED) {
+ if (_leaderGroups.contains(key)) {
+ LeaderInfo lf = new LeaderInfo("LEADER");
+ lf.setLeaderName(_participant);
+ try {
+ _metaClient.create(key, lf, MetaClientInterface.EntryMode.EPHEMERAL);
+ } catch (MetaClientNodeExistsException ex) {
+ LOG.info("Already a leader {} for leader election group {}.", ((LeaderInfo) data).getLeaderName(), key);
+ }
+ }
+ }
+ }
}
}
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderInfo.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderInfo.java
index 9e817c1c9..ab0562502 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderInfo.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderInfo.java
@@ -19,27 +19,49 @@ package org.apache.helix.metaclient.recipes.leaderelection;
* under the License.
*/
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.apache.helix.metaclient.datamodel.DataRecord;
/**
* This is the data represent leader election info of a leader election path.
*/
-public class LeaderInfo {
+@JsonIgnoreProperties(ignoreUnknown = true)
+@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
+public class LeaderInfo extends DataRecord {
- private String _leaderElectionGroupName;
- private final DataRecord _record;
+ public LeaderInfo(DataRecord dataRecord) {
+ super(dataRecord);
+ }
+ @JsonCreator
+ public LeaderInfo(@JsonProperty("id") String id) {
+ super(id);
+ }
- public LeaderInfo( String leaderElectionGroupName) {
- _leaderElectionGroupName = leaderElectionGroupName;
- _record = new DataRecord(_leaderElectionGroupName);
+ public LeaderInfo(LeaderInfo info, String id) {
+ super(info, id);
}
+
public enum LeaderAttribute {
LEADER_NAME,
PARTICIPANTS
}
+@JsonIgnore(true)
+public String getLeaderName() {
+ return getSimpleField("LEADER_NAME");
+ }
+
+ @JsonIgnore(true)
+ public void setLeaderName(String id) {
+ setSimpleField("LEADER_NAME", id);
+ }
+
}
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderInfoSerializer.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderInfoSerializer.java
new file mode 100644
index 000000000..fd6d256f6
--- /dev/null
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderInfoSerializer.java
@@ -0,0 +1,42 @@
+package org.apache.helix.metaclient.recipes.leaderelection;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.MapperFeature;
+import java.io.ByteArrayInputStream;
+import org.apache.helix.zookeeper.datamodel.ZNRecord;
+import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer;
+import org.apache.helix.zookeeper.util.GZipCompressionUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+public class LeaderInfoSerializer extends ZNRecordSerializer {
+
+ private static final Logger LOG = LoggerFactory.getLogger(LeaderInfoSerializer.class);
+
+ @Override
+ public Object deserialize(byte[] bytes) {
+ if (bytes == null || bytes.length == 0) {
+ // reading a parent/null node
+ return null;
+ }
+
+ ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
+
+ mapper.enable(MapperFeature.AUTO_DETECT_FIELDS);
+ mapper.enable(MapperFeature.AUTO_DETECT_SETTERS);
+ mapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
+ try {
+ //decompress the data if its already compressed
+ if (GZipCompressionUtil.isCompressed(bytes)) {
+ byte[] uncompressedBytes = GZipCompressionUtil.uncompress(bais);
+ bais = new ByteArrayInputStream(uncompressedBytes);
+ }
+
+ return mapper.readValue(bais, LeaderInfo.class);
+ } catch (Exception e) {
+ LOG.error("Exception during deserialization of bytes: {}", new String(bytes), e);
+ return null;
+ }
+ }
+}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/TestUtil.java b/meta-client/src/test/java/org/apache/helix/metaclient/TestUtil.java
new file mode 100644
index 000000000..9b20c8e53
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/TestUtil.java
@@ -0,0 +1,22 @@
+package org.apache.helix.metaclient;
+
+public class TestUtil {
+ public static final long WAIT_DURATION = 6 * 1000L;
+ public interface Verifier {
+ boolean verify()
+ throws Exception;
+ }
+
+ public static boolean verify(Verifier verifier, long timeout)
+ throws Exception {
+ long start = System.currentTimeMillis();
+ do {
+ boolean result = verifier.verify();
+ if (result || (System.currentTimeMillis() - start) > timeout) {
+ return result;
+ }
+ Thread.sleep(50);
+ } while (true);
+ }
+
+}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
new file mode 100644
index 000000000..3a45d97ce
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
@@ -0,0 +1,64 @@
+package org.apache.helix.metaclient.recipes.leaderelection;
+
+import org.apache.helix.metaclient.TestUtil;
+import org.apache.helix.metaclient.factories.MetaClientConfig;
+import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+
+public class TestLeaderElection extends ZkMetaClientTestBase {
+
+ private static final String PARTICIPANT_NAME1 = "participant_1";
+ private static final String PARTICIPANT_NAME2 = "participant_2";
+ private static final String LEADER_PATH = "/LEADER_ELECTION_GROUP_1";
+
+ public LeaderElectionClient createLeaderElectionClient(String participantName) {
+ MetaClientConfig.StoreType storeType = MetaClientConfig.StoreType.ZOOKEEPER;
+ MetaClientConfig config = new MetaClientConfig.MetaClientConfigBuilder<>().setConnectionAddress(ZK_ADDR)
+ .setStoreType(storeType).build();
+ return new LeaderElectionClient(config, participantName);
+ }
+
+ @Test
+ public void testAcquireLeadership() throws Exception {
+ // create 2 clients representing 2 participants
+ LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
+ LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
+
+ clt1.joinLeaderElectionParticipantPool(LEADER_PATH);
+ clt2.joinLeaderElectionParticipantPool(LEADER_PATH);
+ // First client joining the leader election group should be current leader
+ Assert.assertTrue(TestUtil.verify(() -> {
+ return (clt1.getLeader(LEADER_PATH) != null);
+ }, TestUtil.WAIT_DURATION));
+ Assert.assertNotNull(clt1.getLeader(LEADER_PATH));
+ Assert.assertEquals(clt1.getLeader(LEADER_PATH), clt2.getLeader(LEADER_PATH));
+ Assert.assertEquals(clt1.getLeader(LEADER_PATH), PARTICIPANT_NAME1);
+
+ // client 1 exit leader election group, and client 2 should be current leader.
+ clt1.exitLeaderElectionParticipantPool(LEADER_PATH);
+ Assert.assertTrue(TestUtil.verify(() -> {
+ return (clt1.getLeader(LEADER_PATH) != null);
+ }, TestUtil.WAIT_DURATION));
+ Assert.assertTrue(TestUtil.verify(() -> {
+ return (clt1.getLeader(LEADER_PATH).equals(PARTICIPANT_NAME2));
+ }, TestUtil.WAIT_DURATION));
+
+ // client1 join and client2 leave. client 1 should be leader.
+ clt1.joinLeaderElectionParticipantPool(LEADER_PATH);
+ clt2.exitLeaderElectionParticipantPool(LEADER_PATH);
+ Assert.assertTrue(TestUtil.verify(() -> {
+ return (clt1.getLeader(LEADER_PATH) != null);
+ }, TestUtil.WAIT_DURATION));
+ Assert.assertTrue(TestUtil.verify(() -> {
+ return (clt1.getLeader(LEADER_PATH).equals(PARTICIPANT_NAME1));
+ }, TestUtil.WAIT_DURATION));
+ Assert.assertTrue(clt1.isLeader(LEADER_PATH));
+ Assert.assertFalse(clt2.isLeader(LEADER_PATH));
+
+ clt1.close();
+ clt2.close();
+ }
+
+}
diff --git a/zookeeper-api/src/main/java/org/apache/helix/zookeeper/datamodel/serializer/ZNRecordSerializer.java b/zookeeper-api/src/main/java/org/apache/helix/zookeeper/datamodel/serializer/ZNRecordSerializer.java
index 5838cfad7..0cc3215bb 100644
--- a/zookeeper-api/src/main/java/org/apache/helix/zookeeper/datamodel/serializer/ZNRecordSerializer.java
+++ b/zookeeper-api/src/main/java/org/apache/helix/zookeeper/datamodel/serializer/ZNRecordSerializer.java
@@ -40,7 +40,7 @@ import org.slf4j.LoggerFactory;
public class ZNRecordSerializer implements ZkSerializer {
private static final Logger LOG = LoggerFactory.getLogger(ZNRecordSerializer.class);
- private static ObjectMapper mapper = new ObjectMapper()
+ protected static ObjectMapper mapper = new ObjectMapper()
// TODO: remove it after upgrading ZNRecord's annotations to Jackson 2
.setAnnotationIntrospector(new CodehausJacksonIntrospector());
diff --git a/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkConnection.java b/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkConnection.java
index 376409231..589425462 100644
--- a/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkConnection.java
+++ b/zookeeper-api/src/main/java/org/apache/helix/zookeeper/zkclient/ZkConnection.java
@@ -260,6 +260,7 @@ public class ZkConnection implements IZkConnection {
private void lookupGetChildrenMethod() {
_getChildrenMethod = doLookUpGetChildrenMethod();
+ System.out.println(" ZkSystemPropertyKeys.ZK_GETCHILDREN_PAGINATION_DISABLED " + GETCHILDREN_PAGINATION_DISABLED);
LOG.info("Pagination config {}={}, method to be invoked: {}",
ZkSystemPropertyKeys.ZK_GETCHILDREN_PAGINATION_DISABLED, GETCHILDREN_PAGINATION_DISABLED,
_getChildrenMethod.getName());
[helix] 05/21: refactor, update with dataRecord
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit b45361ba373bdf8c7167d02164e4442f423ed7e2
Author: Grant Palau Spencer <gs...@linkedin.com>
AuthorDate: Sat Jun 3 11:00:33 2023 -0700
refactor, update with dataRecord
---
.../metaclient/impl/zk/TestStressZkClient.java | 406 ++++++++++-----------
1 file changed, 183 insertions(+), 223 deletions(-)
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
index 4b541ba74..5706dec7d 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
@@ -32,295 +32,254 @@ import org.apache.helix.metaclient.api.MetaClientInterface;
import org.apache.helix.metaclient.datamodel.DataRecord;
import org.apache.helix.metaclient.exception.MetaClientException;
import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig;
+import org.apache.helix.metaclient.recipes.lock.DataRecordSerializer;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer;
import org.apache.helix.zookeeper.exception.ZkClientException;
+import org.junit.Before;
import org.testng.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.apache.helix.metaclient.api.MetaClientInterface.EntryMode.*;
public class TestStressZkClient extends ZkMetaClientTestBase {
- private static final long TEST_ITERATION_COUNT = 1000;
- private static final Logger LOG = LoggerFactory.getLogger(TestStressZkClient.class);
+ private ZkMetaClient<String> _zkMetaClient;
+ private static final long TEST_ITERATION_COUNT = 10;
+ @BeforeTest
+ private void setUp() {
+ this._zkMetaClient = createZkMetaClient();
+ this._zkMetaClient.connect();
+ }
+
+ @AfterTest
+ private void tearDown() {
+ this._zkMetaClient.close();
+ }
@Test
public void testCreate() {
String zkParentKey = "/stressZk_testCreate";
- try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
- zkMetaClient.connect();
- zkMetaClient.create(zkParentKey, "parent_node");
+ _zkMetaClient.create(zkParentKey, "parent_node");
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- zkMetaClient.create(zkParentKey + "/" + i, i);
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ _zkMetaClient.create(zkParentKey + "/" + i, i);
+ }
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- Assert.assertEquals(String.valueOf(zkMetaClient.get(zkParentKey + "/" + i)), String.valueOf(i));
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertEquals(String.valueOf(_zkMetaClient.get(zkParentKey + "/" + i)), String.valueOf(i));
+ }
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- try {
- zkMetaClient.create("/a/b/c", "invalid_path");
- Assert.fail("Should have failed with incorrect path.");
- } catch (MetaClientException ignoredException) {
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ _zkMetaClient.create("/a/b/c", "invalid_path");
+ Assert.fail("Should have failed with incorrect path.");
+ } catch (MetaClientException ignoredException) {
}
+ }
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- try {
- zkMetaClient.create("a/b/c", "invalid_path");
- Assert.fail("Should have failed with invalid path - no leading /.");
- } catch (Exception ignoredException) {
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ _zkMetaClient.create("a/b/c", "invalid_path");
+ Assert.fail("Should have failed with invalid path - no leading /.");
+ } catch (Exception ignoredException) {
}
// cleanup
- zkMetaClient.recursiveDelete(zkParentKey);
- Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
}
}
@Test
public void testCreateContainer() {
final String zkParentKey = "/stressZk_testCreateContainer";
- try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
- zkMetaClient.connect();
- zkMetaClient.create(zkParentKey, "parent_node");
+ _zkMetaClient.create(zkParentKey, "parent_node");
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- zkMetaClient.create(zkParentKey + "/" + i, i, CONTAINER);
- }
-
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- Assert.assertEquals(String.valueOf(zkMetaClient.get(zkParentKey + "/" + i)), String.valueOf(i));
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ _zkMetaClient.create(zkParentKey + "/" + i, i, CONTAINER);
+ }
- // cleanup
- zkMetaClient.recursiveDelete(zkParentKey);
- Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertEquals(String.valueOf(_zkMetaClient.get(zkParentKey + "/" + i)), String.valueOf(i));
}
+
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
}
@Test
public void testGet() {
final String zkParentKey = "/stressZk_testGet";
- try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
- zkMetaClient.connect();
- zkMetaClient.create(zkParentKey, "parent_node");
+ _zkMetaClient.create(zkParentKey, "parent_node");
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- zkMetaClient.create(zkParentKey + "/" + i, i);
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ _zkMetaClient.create(zkParentKey + "/" + i, i);
+ }
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- Assert.assertEquals(zkMetaClient.get(zkParentKey + "/" + i), i);
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertEquals(_zkMetaClient.get(zkParentKey + "/" + i), i);
+ }
- // Test with non-existent node path
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- Assert.assertNull(zkMetaClient.get("/a/b/c"));
- }
+ // Test with non-existent node path
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertNull(_zkMetaClient.get("/a/b/c"));
+ }
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- try {
- zkMetaClient.get("a/b/c");
- Assert.fail("Should have failed due to invalid path - no leading /.");
- } catch (Exception ignoredException) {
- }
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ _zkMetaClient.get("a/b/c");
+ Assert.fail("Should have failed due to invalid path - no leading /.");
+ } catch (Exception ignoredException) {
+ }
// cleanup
- zkMetaClient.recursiveDelete(zkParentKey);
- Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
}
}
@Test
public void testSetSingleNode() {
final String zkParentKey = "/stressZk_testSetSingleNode";
- try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
- zkMetaClient.connect();
- zkMetaClient.create(zkParentKey, "parent_node");
-
- // Set with no expected version
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- zkMetaClient.set(zkParentKey, String.valueOf(i), -1);
- MetaClientInterface.Stat entryStat = zkMetaClient.exists(zkParentKey);
+ _zkMetaClient.create(zkParentKey, "parent_node");
- Assert.assertEquals(zkMetaClient.get(zkParentKey), String.valueOf(i));
- Assert.assertEquals(entryStat.getVersion(), i + 1);
- Assert.assertEquals(entryStat.getEntryType().name(), PERSISTENT.name());
- }
+ // Set with no expected version
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ _zkMetaClient.set(zkParentKey, String.valueOf(i), -1);
+ MetaClientInterface.Stat entryStat = _zkMetaClient.exists(zkParentKey);
- zkMetaClient.delete(zkParentKey);
- zkMetaClient.create(zkParentKey, "parent_node");
+ Assert.assertEquals(_zkMetaClient.get(zkParentKey), String.valueOf(i));
+ Assert.assertEquals(entryStat.getVersion(), i + 1);
+ Assert.assertEquals(entryStat.getEntryType().name(), PERSISTENT.name());
+ }
- // Set with expected version
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- zkMetaClient.set(zkParentKey, String.valueOf(i), i);
- MetaClientInterface.Stat entryStat = zkMetaClient.exists(zkParentKey);
+ _zkMetaClient.delete(zkParentKey);
+ _zkMetaClient.create(zkParentKey, "parent_node");
- Assert.assertEquals(zkMetaClient.get(zkParentKey), String.valueOf(i));
- Assert.assertEquals(entryStat.getVersion(), i + 1);
- }
+ // Set with expected version
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ _zkMetaClient.set(zkParentKey, String.valueOf(i), i);
+ MetaClientInterface.Stat entryStat = _zkMetaClient.exists(zkParentKey);
- zkMetaClient.delete(zkParentKey);
- zkMetaClient.create(zkParentKey, "parent_node");
+ Assert.assertEquals(_zkMetaClient.get(zkParentKey), String.valueOf(i));
+ Assert.assertEquals(entryStat.getVersion(), i + 1);
+ }
- // Set with bad expected version - should fail
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- try {
- zkMetaClient.set(zkParentKey, "test-should-fail", 12345);
- Assert.fail("Should have failed due to bad expected version in set function.");
- } catch (MetaClientException ex) {
- Assert.assertEquals(ex.getClass().getName(),
- "org.apache.helix.metaclient.exception.MetaClientBadVersionException");
- }
+ _zkMetaClient.delete(zkParentKey);
+ _zkMetaClient.create(zkParentKey, "parent_node");
+
+ // Set with bad expected version - should fail
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ _zkMetaClient.set(zkParentKey, "test-should-fail", 12345);
+ Assert.fail("Should have failed due to bad expected version in set function.");
+ } catch (MetaClientException ex) {
+ Assert.assertEquals(ex.getClass().getName(),
+ "org.apache.helix.metaclient.exception.MetaClientBadVersionException");
}
-
- zkMetaClient.delete(zkParentKey);
- zkMetaClient.create(zkParentKey, "parent_node");
+ }
+ _zkMetaClient.delete(zkParentKey);
+ _zkMetaClient.create(zkParentKey, "parent_node");
// Set with path to non-existent node - should fail
for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
try {
- zkMetaClient.set("/a/b/c", "test-should-fail", -1);
+ _zkMetaClient.set("/a/b/c", "test-should-fail", -1);
Assert.fail("Should have failed due to path to non-existent node");
} catch (Exception ignoredException) {
}
}
- zkMetaClient.delete(zkParentKey);
- zkMetaClient.create(zkParentKey, "parent_node");
+ _zkMetaClient.delete(zkParentKey);
+ _zkMetaClient.create(zkParentKey, "parent_node");
// Set with invalid path - should fail
for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
try {
- zkMetaClient.set("a/b/c", "test-should-fail", -1);
+ _zkMetaClient.set("a/b/c", "test-should-fail", -1);
Assert.fail("Should have failed due to invalid path - no leading /.");
} catch (Exception ignoredException) {
}
}
// cleanup
- zkMetaClient.recursiveDelete(zkParentKey);
- Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
}
- }
@Test
public void testSetMultiNode() {
final String zkParentKey = "/stressZk_testSetMultiNode";
- try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
- zkMetaClient.connect();
- zkMetaClient.create(zkParentKey, "parent_node");
+ _zkMetaClient.create(zkParentKey, "parent_node");
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- zkMetaClient.create(zkParentKey + "/" + i, i);
- }
-
- // Set with no expected version
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- zkMetaClient.set(zkParentKey + "/" + i, "-" + i, -1);
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ _zkMetaClient.create(zkParentKey + "/" + i, i);
+ }
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- String childKey = zkParentKey + "/" + i;
- MetaClientInterface.Stat entryStat = zkMetaClient.exists(childKey);
+ // Set with no expected version
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ _zkMetaClient.set(zkParentKey + "/" + i, "-" + i, -1);
+ }
- Assert.assertEquals(zkMetaClient.get(childKey), "-" + i);
- Assert.assertEquals(entryStat.getVersion(), 1);
- Assert.assertEquals(entryStat.getEntryType().name(), PERSISTENT.name());
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ String childKey = zkParentKey + "/" + i;
+ MetaClientInterface.Stat entryStat = _zkMetaClient.exists(childKey);
- // Set with expected version
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- String childKey = zkParentKey + "/" + i;
- zkMetaClient.set(childKey, String.valueOf(i), 1);
- MetaClientInterface.Stat entryStat = zkMetaClient.exists(childKey);
+ Assert.assertEquals(_zkMetaClient.get(childKey), "-" + i);
+ Assert.assertEquals(entryStat.getVersion(), 1);
+ Assert.assertEquals(entryStat.getEntryType().name(), PERSISTENT.name());
+ }
- Assert.assertEquals(zkMetaClient.get(childKey), String.valueOf(i));
- Assert.assertEquals(entryStat.getVersion(), 2);
- }
+ // Set with expected version
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ String childKey = zkParentKey + "/" + i;
+ _zkMetaClient.set(childKey, String.valueOf(i), 1);
+ MetaClientInterface.Stat entryStat = _zkMetaClient.exists(childKey);
- // cleanup
- zkMetaClient.recursiveDelete(zkParentKey);
- Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
+ Assert.assertEquals(_zkMetaClient.get(childKey), String.valueOf(i));
+ Assert.assertEquals(entryStat.getVersion(), 2);
}
+
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
}
@Test
public void testUpdateSingleNode() {
final String zkParentKey = "/stressZk_testUpdateSingleNode";
ZkMetaClientConfig config =
- new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR).build();
- try (ZkMetaClient<byte[]> zkMetaClient = new ZkMetaClient<>(config)) {
+ new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR)
+ .setZkSerializer(new DataRecordSerializer()).build();
+ try (ZkMetaClient<DataRecord> zkMetaClient = new ZkMetaClient<>(config)) {
zkMetaClient.connect();
- ZNRecord record = new ZNRecord("foo");
- record.setIntField("key", 0);
- ZNRecordSerializer serializer = new ZNRecordSerializer();
- zkMetaClient.create(zkParentKey, serializer.serialize(record));
+ DataRecord record = new DataRecord(zkParentKey);
+ record.setIntField("key", 0);
+ zkMetaClient.create(zkParentKey, record);
for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
MetaClientInterface.Stat entryStat = zkMetaClient.exists(zkParentKey);
Assert.assertEquals(entryStat.getVersion(), i);
- byte[] newData = zkMetaClient.update(zkParentKey, new DataUpdater<byte[]>() {
+ DataRecord newData = zkMetaClient.update(zkParentKey, new DataUpdater<DataRecord>() {
@Override
- public byte[] update(byte[] currentData) {
- ZNRecordSerializer serializer = new ZNRecordSerializer();
- ZNRecord record = (ZNRecord) serializer.deserialize(currentData);
- int value = record.getIntField("key", 0);
- record.setIntField("key", value + 1);
- return serializer.serialize(record);
+ public DataRecord update(DataRecord currentData) {
+ int value = currentData.getIntField("key", 0);
+ currentData.setIntField("key", value + 1);
+ return currentData;
}
});
- ZNRecord newRecord = (ZNRecord) serializer.deserialize(newData);
- Assert.assertEquals(newRecord.getIntField("key", 0), i+1);
+ Assert.assertEquals(newData.getIntField("key", 0), i+1);
}
-
-// zkMetaClient.delete(zkParentKey);
-// zkMetaClient.create(zkParentKey, "parent_node");
-
-// Set with path to non-existent node - should fail
-// for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
-// try {
-// zkMetaClient.update("/a/b/c", new DataUpdater<Integer>() {
-// @Override
-// public Integer update(Integer currentData) {
-// return currentData + 1;
-// }
-// });
-//
-// Assert.fail("Should have failed due to path to non-existent node");
-// } catch (Exception ignoredException) {
-// }
-// }
-
-// zkMetaClient.delete(zkParentKey);
-// zkMetaClient.create(zkParentKey, "parent_node");
-
- // Set with invalid path - should fail
-// for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
-// try {
-// zkMetaClient.update("/a/b/c", new DataUpdater<Integer>() {
-// @Override
-// public Integer update(Integer currentData) {
-// return currentData + 1;
-// }
-// });
-// Assert.fail("Should have failed due to invalid path - no leading /.");
-// } catch (Exception ignoredException) {
-// }
-// }
-
// cleanup
zkMetaClient.recursiveDelete(zkParentKey);
Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
@@ -329,15 +288,20 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
@Test
public void testUpdateMultiNode() {
- final String zkParentKey = "/stressZk_testUpdateSingleNode";
+ final String zkParentKey = "/stressZk_testUpdateMultiNode";
ZkMetaClientConfig config =
- new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR).build();
- try (ZkMetaClient<Integer> zkMetaClient = new ZkMetaClient<>(config)) {
+ new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR)
+ .setZkSerializer(new DataRecordSerializer()).build();
+ try (ZkMetaClient<DataRecord> zkMetaClient = new ZkMetaClient<>(config)) {
zkMetaClient.connect();
- zkMetaClient.create(zkParentKey, "test_parent");
+ DataRecord parentRecord = new DataRecord(zkParentKey);
+ zkMetaClient.create(zkParentKey, parentRecord);
for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- zkMetaClient.create(zkParentKey + "/" + i, 0);
+ String childKey = zkParentKey + "/" + i;
+ DataRecord record = new DataRecord(childKey);
+ record.setIntField("key", 0);
+ zkMetaClient.create(childKey, record);
}
for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
@@ -345,14 +309,16 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
MetaClientInterface.Stat entryStat = zkMetaClient.exists(childKey);
Assert.assertEquals(entryStat.getVersion(), 0);
- Integer newData = zkMetaClient.update(childKey, new DataUpdater<Integer>() {
+ DataRecord newData = zkMetaClient.update(childKey, new DataUpdater<DataRecord>() {
@Override
- public Integer update(Integer currentData) {
- return currentData + 1;
+ public DataRecord update(DataRecord currentData) {
+ int value = currentData.getIntField("key", 0);
+ currentData.setIntField("key", value + 1);
+ return currentData;
}
});
- Assert.assertEquals((int) newData, 1);
+ Assert.assertEquals(newData.getIntField("key",0), 1);
entryStat = zkMetaClient.exists(childKey);
Assert.assertEquals(entryStat.getVersion(), 1);
}
@@ -370,43 +336,37 @@ public class TestStressZkClient extends ZkMetaClientTestBase {
final String testData = "test-data";
final AtomicBoolean dataExpected = new AtomicBoolean(true);
- try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
- zkMetaClient.connect();
- zkMetaClient.create(zkParentKey, "parent_node");
- Map<String, Set<DataChangeListener>> listeners = new HashMap<>();
- CountDownLatch countDownLatch = new CountDownLatch((int) TEST_ITERATION_COUNT * listenerCount);
+ _zkMetaClient.create(zkParentKey, "parent_node");
+ CountDownLatch countDownLatch = new CountDownLatch((int) TEST_ITERATION_COUNT * listenerCount);
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- zkMetaClient.create(zkParentKey + "/" + i, i);
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ _zkMetaClient.create(zkParentKey + "/" + i, i);
+ }
- // create paths
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- String childKey = zkParentKey + "/" + i;
- listeners.put(childKey, new HashSet<>());
- for (int j = 0; j < listenerCount; j++) {
- DataChangeListener listener = new DataChangeListener() {
- @Override
- public void handleDataChange(String key, Object data, ChangeType changeType) {
- countDownLatch.countDown();
- dataExpected.set(dataExpected.get() && testData.equals(data));
- }
- };
- listeners.get(childKey).add(listener);
- zkMetaClient.subscribeDataChange(childKey, listener, false);
- }
+ // create paths
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ String childKey = zkParentKey + "/" + i;
+ for (int j = 0; j < listenerCount; j++) {
+ DataChangeListener listener = new DataChangeListener() {
+ @Override
+ public void handleDataChange(String key, Object data, ChangeType changeType) {
+ countDownLatch.countDown();
+ dataExpected.set(dataExpected.get() && testData.equals(data));
+ }
+ };
+ _zkMetaClient.subscribeDataChange(childKey, listener, false);
}
+ }
- for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
- zkMetaClient.set(zkParentKey + "/" + i, testData, -1);
- }
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ _zkMetaClient.set(zkParentKey + "/" + i, testData, -1);
+ }
- Assert.assertTrue(countDownLatch.await(5000, TimeUnit.MILLISECONDS));
- Assert.assertTrue(dataExpected.get());
+ Assert.assertTrue(countDownLatch.await(5000, TimeUnit.MILLISECONDS));
+ Assert.assertTrue(dataExpected.get());
- // cleanup
- zkMetaClient.recursiveDelete(zkParentKey);
- Assert.assertEquals(zkMetaClient.countDirectChildren(zkParentKey), 0);
- }
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
}
}
\ No newline at end of file
[helix] 20/21: Add stress test for Metaclient leader election (#2574)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit 7a96d9ba8c7dd671f6847bb8f01f50dbf41d7ca9
Author: xyuanlu <xy...@gmail.com>
AuthorDate: Mon Aug 7 09:56:18 2023 -0700
Add stress test for Metaclient leader election (#2574)
---
.../zk/TestConnectStateChangeListenerAndRetry.java | 11 ++-
.../metaclient/impl/zk/ZkMetaClientTestBase.java | 2 +
.../helix/metaclient/puppy/AbstractPuppy.java | 2 +-
.../leaderelection/LeaderElectionPuppy.java | 87 ++++++++++++++++++++++
.../recipes/leaderelection/TestLeaderElection.java | 55 ++++++++------
.../TestMultiClientLeaderElection.java | 82 ++++++++++++++++++++
6 files changed, 214 insertions(+), 25 deletions(-)
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java
index c74b7d7ef..086db51c7 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestConnectStateChangeListenerAndRetry.java
@@ -19,6 +19,8 @@ package org.apache.helix.metaclient.impl.zk;
* under the License.
*/
+import java.io.File;
+import java.io.IOException;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
@@ -27,17 +29,21 @@ import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
+import org.apache.commons.io.FileUtils;
import org.apache.helix.metaclient.api.ConnectStateChangeListener;
import org.apache.helix.metaclient.api.MetaClientInterface;
import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig;
import org.apache.helix.metaclient.policy.ExponentialBackoffReconnectPolicy;
+import org.apache.helix.zookeeper.zkclient.IDefaultNameSpace;
import org.apache.helix.zookeeper.zkclient.ZkClient;
import org.apache.helix.zookeeper.zkclient.ZkServer;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
+import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
+import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static org.apache.helix.metaclient.constants.MetaClientConstants.DEFAULT_INIT_EXP_BACKOFF_RETRY_INTERVAL_MS;
@@ -69,14 +75,14 @@ public class TestConnectStateChangeListenerAndRetry {
zkClient.process(event);
}
- @BeforeSuite
+ @BeforeTest
public void prepare() {
System.out.println("START TestConnectStateChangeListenerAndRetry at " + new Date(System.currentTimeMillis()));
// start local zookeeper server
_zkServer = ZkMetaClientTestBase.startZkServer(ZK_ADDR);
}
- @AfterSuite
+ @AfterTest
public void cleanUp() {
System.out.println("END TestConnectStateChangeListenerAndRetry at " + new Date(System.currentTimeMillis()));
}
@@ -162,7 +168,6 @@ public class TestConnectStateChangeListenerAndRetry {
zkMetaClient.create("/key", "value");
Assert.fail("Create call after close should throw IllegalStateException");
} catch (Exception ex) {
- System.out.println("ex " + ex);
Assert.assertTrue(ex instanceof IllegalStateException);
}
}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/ZkMetaClientTestBase.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/ZkMetaClientTestBase.java
index 2a5f4b97b..eade017c1 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/ZkMetaClientTestBase.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/ZkMetaClientTestBase.java
@@ -49,6 +49,7 @@ public abstract class ZkMetaClientTestBase {
*/
@BeforeSuite
public void prepare() {
+ System.out.println("ZkMetaClientTestBase start ");
// Enable extended types and create a ZkClient
System.setProperty("zookeeper.extendedTypesEnabled", "true");
// start local zookeeper server
@@ -57,6 +58,7 @@ public abstract class ZkMetaClientTestBase {
@AfterSuite
public void cleanUp() {
+ System.out.println("ZkMetaClientTestBase shut down");
_zkServer.shutdown();
}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
index 9ce21fc15..b16f78615 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
@@ -22,6 +22,7 @@ package org.apache.helix.metaclient.puppy;
import org.apache.helix.metaclient.api.MetaClientInterface;
import java.util.HashMap;
+
/**
* AbstractPuppy object contains interfaces to implement puppy and main logics to manage puppy life cycle
*/
@@ -32,7 +33,6 @@ public abstract class AbstractPuppy implements Runnable {
public final HashMap<String, Integer> _eventChangeCounterMap;
public int _unhandledErrorCounter;
-
public AbstractPuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) {
_metaclient = metaclient;
_puppySpec = puppySpec;
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionPuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionPuppy.java
new file mode 100644
index 000000000..5f1fdf631
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionPuppy.java
@@ -0,0 +1,87 @@
+package org.apache.helix.metaclient.recipes.leaderelection;
+
+/*
+ * 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.
+ */
+
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
+import org.apache.helix.metaclient.MetaClientTestUtil;
+import org.apache.helix.metaclient.api.MetaClientInterface;
+import org.apache.helix.metaclient.exception.MetaClientException;
+import org.apache.helix.metaclient.puppy.AbstractPuppy;
+import org.apache.helix.metaclient.puppy.PuppySpec;
+import org.testng.Assert;
+
+
+public class LeaderElectionPuppy extends AbstractPuppy {
+ String _leaderGroup;
+ String _participant;
+ private final Random _random;
+ LeaderElectionClient _leaderElectionClient;
+
+ public LeaderElectionPuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) {
+ super(metaclient, puppySpec);
+ _random = new Random();
+ }
+
+ public LeaderElectionPuppy(LeaderElectionClient leaderElectionClient, PuppySpec puppySpec, String leaderGroup,
+ String participant) {
+ super(leaderElectionClient.getMetaClient(), puppySpec);
+ _leaderElectionClient = leaderElectionClient;
+ _leaderGroup = leaderGroup;
+ _random = new Random();
+ _participant = participant;
+ }
+
+ @Override
+ protected void bark() throws Exception {
+ int randomNumber = _random.nextInt((int) TimeUnit.SECONDS.toMillis(5));
+ System.out.println("LeaderElectionPuppy " + _participant + " Joining");
+ _leaderElectionClient.joinLeaderElectionParticipantPool(_leaderGroup);
+
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (_leaderElectionClient.getLeader(_leaderGroup) != null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+ if (_random.nextBoolean()) {
+ _leaderElectionClient.relinquishLeader(_leaderGroup);
+ }
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (_leaderElectionClient.getParticipantInfo(_leaderGroup, _participant) != null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+
+ Thread.sleep(randomNumber);
+ System.out.println("LeaderElectionPuppy " + _participant + " Leaving");
+ _leaderElectionClient.exitLeaderElectionParticipantPool(_leaderGroup);
+ Assert.assertTrue(MetaClientTestUtil.verify(() -> {
+ return (_leaderElectionClient.getParticipantInfo(_leaderGroup, _participant) == null);
+ }, MetaClientTestUtil.WAIT_DURATION));
+
+ Thread.sleep(randomNumber);
+ }
+
+ @Override
+ protected void cleanup() {
+ try {
+ System.out.println("Cleaning - LeaderElectionPuppy " + _participant + " Leaving");
+ _leaderElectionClient.exitLeaderElectionParticipantPool(_leaderGroup);
+ } catch (MetaClientException ignore) {
+ // already leave the pool. OK to throw exception.
+ }
+ }
+}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
index b0b396c1a..71d85fdb9 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
@@ -19,7 +19,7 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
private static final String PARTICIPANT_NAME2 = "participant_2";
private static final String LEADER_PATH = "/LEADER_ELECTION_GROUP_1";
- public LeaderElectionClient createLeaderElectionClient(String participantName) {
+ public static LeaderElectionClient createLeaderElectionClient(String participantName) {
MetaClientConfig.StoreType storeType = MetaClientConfig.StoreType.ZOOKEEPER;
MetaClientConfig config =
new MetaClientConfig.MetaClientConfigBuilder<>().setConnectionAddress(ZK_ADDR).setStoreType(storeType).build();
@@ -28,50 +28,57 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
@Test
public void testAcquireLeadership() throws Exception {
- String leaderPath = LEADER_PATH + "testAcquireLeadership";
+ System.out.println("START TestLeaderElection.testAcquireLeadership");
+ String leaderPath = LEADER_PATH + "/testAcquireLeadership";
// create 2 clients representing 2 participants
LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
+ clt1.getMetaClient().create(LEADER_PATH, new LeaderInfo(LEADER_PATH));
+
clt1.joinLeaderElectionParticipantPool(leaderPath);
clt2.joinLeaderElectionParticipantPool(leaderPath);
// First client joining the leader election group should be current leader
Assert.assertTrue(MetaClientTestUtil.verify(() -> {
- return (clt1.getLeader(LEADER_PATH) != null);
+ return (clt1.getLeader(leaderPath) != null);
}, MetaClientTestUtil.WAIT_DURATION));
- Assert.assertNotNull(clt1.getLeader(LEADER_PATH));
- Assert.assertEquals(clt1.getLeader(LEADER_PATH), clt2.getLeader(LEADER_PATH));
- Assert.assertEquals(clt1.getLeader(LEADER_PATH), PARTICIPANT_NAME1);
+ Assert.assertNotNull(clt1.getLeader(leaderPath));
+ Assert.assertEquals(clt1.getLeader(leaderPath), clt2.getLeader(leaderPath));
+ Assert.assertEquals(clt1.getLeader(leaderPath), PARTICIPANT_NAME1);
+
// client 1 exit leader election group, and client 2 should be current leader.
- clt1.exitLeaderElectionParticipantPool(LEADER_PATH);
+ clt1.exitLeaderElectionParticipantPool(leaderPath);
+
Assert.assertTrue(MetaClientTestUtil.verify(() -> {
- return (clt1.getLeader(LEADER_PATH) != null);
+ return (clt1.getLeader(leaderPath) != null);
}, MetaClientTestUtil.WAIT_DURATION));
Assert.assertTrue(MetaClientTestUtil.verify(() -> {
- return (clt1.getLeader(LEADER_PATH).equals(PARTICIPANT_NAME2));
+ return (clt1.getLeader(leaderPath).equals(PARTICIPANT_NAME2));
}, MetaClientTestUtil.WAIT_DURATION));
// client1 join and client2 leave. client 1 should be leader.
- clt1.joinLeaderElectionParticipantPool(LEADER_PATH);
- clt2.exitLeaderElectionParticipantPool(LEADER_PATH);
+ clt1.joinLeaderElectionParticipantPool(leaderPath);
+ clt2.exitLeaderElectionParticipantPool(leaderPath);
Assert.assertTrue(MetaClientTestUtil.verify(() -> {
- return (clt1.getLeader(LEADER_PATH) != null);
+ return (clt1.getLeader(leaderPath) != null);
}, MetaClientTestUtil.WAIT_DURATION));
Assert.assertTrue(MetaClientTestUtil.verify(() -> {
- return (clt1.getLeader(LEADER_PATH).equals(PARTICIPANT_NAME1));
+ return (clt1.getLeader(leaderPath).equals(PARTICIPANT_NAME1));
}, MetaClientTestUtil.WAIT_DURATION));
- Assert.assertTrue(clt1.isLeader(LEADER_PATH));
- Assert.assertFalse(clt2.isLeader(LEADER_PATH));
+ Assert.assertTrue(clt1.isLeader(leaderPath));
+ Assert.assertFalse(clt2.isLeader(leaderPath));
clt1.close();
clt2.close();
+ System.out.println("END TestLeaderElection.testAcquireLeadership");
}
@Test
public void testElectionPoolMembership() throws Exception {
- String leaderPath = LEADER_PATH + "/testElectionPoolMembership";
+ System.out.println("START TestLeaderElection.testElectionPoolMembership");
+ String leaderPath = LEADER_PATH + "/_testElectionPoolMembership";
LeaderInfo participantInfo = new LeaderInfo(PARTICIPANT_NAME1);
participantInfo.setSimpleField("Key1", "value1");
LeaderInfo participantInfo2 = new LeaderInfo(PARTICIPANT_NAME2);
@@ -103,12 +110,14 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
clt1.exitLeaderElectionParticipantPool(leaderPath);
clt2.exitLeaderElectionParticipantPool(leaderPath);
- Assert.assertNull(clt2.getParticipantInfo(LEADER_PATH, PARTICIPANT_NAME2));
+ Assert.assertNull(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME2));
+ System.out.println("END TestLeaderElection.testElectionPoolMembership");
}
@Test
public void testSessionExpire() throws Exception {
- String leaderPath = LEADER_PATH + "/testSessionExpire";
+ System.out.println("START TestLeaderElection.testSessionExpire");
+ String leaderPath = LEADER_PATH + "/_testSessionExpire";
LeaderInfo participantInfo = new LeaderInfo(PARTICIPANT_NAME1);
participantInfo.setSimpleField("Key1", "value1");
LeaderInfo participantInfo2 = new LeaderInfo(PARTICIPANT_NAME2);
@@ -142,10 +151,12 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME1).getSimpleField("Key1"), "value1");
Assert.assertEquals(clt1.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
Assert.assertEquals(clt2.getParticipantInfo(leaderPath, PARTICIPANT_NAME2).getSimpleField("Key2"), "value2");
+ System.out.println("END TestLeaderElection.testSessionExpire");
}
@Test (dependsOnMethods = "testAcquireLeadership")
public void testLeadershipListener() throws Exception {
- String leaderPath = LEADER_PATH + "testLeadershipListener";
+ System.out.println("START TestLeaderElection.testLeadershipListener");
+ String leaderPath = LEADER_PATH + "/testLeadershipListener";
// create 2 clients representing 2 participants
LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
@@ -189,7 +200,6 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
Assert.assertEquals(numNewLeaderEvent[0], count*2);
clt3.unsubscribeLeadershipChanges(leaderPath, listener);
-
// listener shouldn't receive any event after unsubscribe
joinPoolTestHelper(leaderPath, clt1, clt2);
Assert.assertEquals(numLeaderGoneEvent[0], count*2);
@@ -198,6 +208,7 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
clt1.close();
clt2.close();
clt3.close();
+ System.out.println("END TestLeaderElection.testLeadershipListener");
}
private void joinPoolTestHelper(String leaderPath, LeaderElectionClient clt1, LeaderElectionClient clt2) throws Exception {
@@ -221,7 +232,8 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
@Test (dependsOnMethods = "testLeadershipListener")
public void testRelinquishLeadership() throws Exception {
- String leaderPath = LEADER_PATH + "testRelinquishLeadership";
+ System.out.println("START TestLeaderElection.testRelinquishLeadership");
+ String leaderPath = LEADER_PATH + "/testRelinquishLeadership";
LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
LeaderElectionClient clt2 = createLeaderElectionClient(PARTICIPANT_NAME2);
LeaderElectionClient clt3 = createLeaderElectionClient(PARTICIPANT_NAME2);
@@ -268,6 +280,7 @@ public class TestLeaderElection extends ZkMetaClientTestBase {
}, MetaClientTestUtil.WAIT_DURATION));
clt2.exitLeaderElectionParticipantPool(leaderPath);
+ System.out.println("END TestLeaderElection.testRelinquishLeadership");
}
}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestMultiClientLeaderElection.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestMultiClientLeaderElection.java
new file mode 100644
index 000000000..0fe424501
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestMultiClientLeaderElection.java
@@ -0,0 +1,82 @@
+package org.apache.helix.metaclient.recipes.leaderelection;
+
+/*
+ * 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.
+ */
+
+import org.apache.helix.metaclient.MetaClientTestUtil;
+import org.apache.helix.metaclient.exception.MetaClientException;
+import org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest.CreatePuppy;
+import org.apache.helix.metaclient.impl.zk.ZkMetaClient;
+import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase;
+import org.apache.helix.metaclient.puppy.ExecDelay;
+import org.apache.helix.metaclient.puppy.PuppyManager;
+import org.apache.helix.metaclient.puppy.PuppyMode;
+import org.apache.helix.metaclient.puppy.PuppySpec;
+import org.apache.helix.zookeeper.exception.ZkClientException;
+import org.testng.annotations.AfterTest;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+import static org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase.*;
+
+
+public class TestMultiClientLeaderElection extends ZkMetaClientTestBase {
+ private final String _leaderElectionGroup = "/Parent/a/LEADER_ELECTION_GROUP";
+ private ZkMetaClient<String> _zkMetaClient;
+ private final String _participant1 = "participant_1";
+ private final String _participant2 = "participant_2";
+
+ @BeforeTest
+ private void setUp() {
+ System.out.println("STARTING TestMultiClientLeaderElection");
+ this._zkMetaClient = createZkMetaClient();
+ this._zkMetaClient.connect();
+ _zkMetaClient.create("/Parent", "");
+ _zkMetaClient.create("/Parent/a", "");
+ }
+ @AfterTest
+ public void cleanUp() {
+ try {
+ _zkMetaClient.recursiveDelete(_leaderElectionGroup);
+ } catch (MetaClientException ex) {
+ _zkMetaClient.recursiveDelete(_leaderElectionGroup);
+ }
+ }
+
+ @Test
+ public void testLeaderElectionPuppy() {
+ System.out.println("Starting TestMultiClientLeaderElection.testLeaderElectionPuppy");
+ PuppySpec puppySpec =
+ new org.apache.helix.metaclient.puppy.PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
+ LeaderElectionPuppy leaderElectionPuppy1 =
+ new LeaderElectionPuppy(TestLeaderElection.createLeaderElectionClient(_participant1),
+ puppySpec, _leaderElectionGroup, _participant1);
+ LeaderElectionPuppy leaderElectionPuppy2 =
+ new LeaderElectionPuppy(TestLeaderElection.createLeaderElectionClient(_participant2),
+ puppySpec, _leaderElectionGroup, _participant2);
+
+ PuppyManager puppyManager = new PuppyManager();
+ puppyManager.addPuppy(leaderElectionPuppy1);
+ puppyManager.addPuppy(leaderElectionPuppy2);
+
+ puppyManager.start(60);
+ System.out.println("Ending TestMultiClientLeaderElection.testLeaderElectionPuppy");
+
+ }
+}
[helix] 03/21: tests for get, create, set, update, and data change listeners
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit b93f89a0603e32faf7e498cda9433c9b5fe3c8e4
Author: Grant Palau Spencer <gs...@linkedin.com>
AuthorDate: Thu Jun 1 15:17:59 2023 -0700
tests for get, create, set, update, and data change listeners
---
.../metaclient/impl/zk/TestStressZkClient.java | 406 ++++++++++++++++++++-
1 file changed, 388 insertions(+), 18 deletions(-)
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
index 9306891d6..3e7140f64 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestStressZkClient.java
@@ -1,24 +1,394 @@
package org.apache.helix.metaclient.impl.zk;
/*
- * 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.
- */
+ * 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.
+ */
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.apache.helix.metaclient.api.DataChangeListener;
+import org.apache.helix.metaclient.api.DataUpdater;
+import org.apache.helix.metaclient.api.MetaClientInterface;
+import org.apache.helix.metaclient.exception.MetaClientException;
+import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig;
+import org.apache.helix.zookeeper.exception.ZkClientException;
+import org.testng.Assert;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.annotations.Test;
+import static org.apache.helix.metaclient.api.MetaClientInterface.EntryMode.*;
public class TestStressZkClient extends ZkMetaClientTestBase {
- // TODO: add tests
+
+ private static final long TEST_ITERATION_COUNT = 1000;
+ private static final Logger LOG = LoggerFactory.getLogger(TestStressZkClient.class);
+
+ private void cleanUpTestNodes(String parentZnodeKey) {
+ try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
+ zkMetaClient.connect();
+ int retryCount = 0;
+ while (zkMetaClient.countDirectChildren(parentZnodeKey) > 0) {
+ try {
+ retryCount++;
+ zkMetaClient.recursiveDelete(parentZnodeKey);
+ } catch (ZkClientException e) {
+ if (retryCount >= 3) {
+ throw new ZkClientException("Failed to clean up test nodes after 3 tries", e);
+ }
+ }
+ }
+ Assert.assertEquals(zkMetaClient.countDirectChildren(parentZnodeKey), 0);
+ }
+ }
+
+ @Test
+ public void testCreate() {
+ String zkParentKey = "/stressZk_testCreate";
+
+ try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
+ zkMetaClient.connect();
+ zkMetaClient.create(zkParentKey, "parent_node");
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ zkMetaClient.create(zkParentKey + "/" + i, i);
+ }
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertEquals(String.valueOf(zkMetaClient.get(zkParentKey + "/" + i)), String.valueOf(i));
+ }
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ zkMetaClient.create("/a/b/c", "invalid_path");
+ Assert.fail("Should have failed with incorrect path.");
+ } catch (MetaClientException ignoredException) {
+ }
+ }
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ zkMetaClient.create("a/b/c", "invalid_path");
+ Assert.fail("Should have failed with invalid path - no leading /.");
+ } catch (Exception ignoredException) {
+ }
+ }
+ cleanUpTestNodes(zkParentKey);
+ }
+ }
+
+ @Test
+ public void testCreateContainer() {
+ final String zkParentKey = "/stressZk_testCreateContainer";
+ try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
+ zkMetaClient.connect();
+ zkMetaClient.create(zkParentKey, "parent_node");
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ zkMetaClient.create(zkParentKey + "/" + i, i, CONTAINER);
+ }
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertEquals(String.valueOf(zkMetaClient.get(zkParentKey + "/" + i)), String.valueOf(i));
+ }
+
+ cleanUpTestNodes(zkParentKey);
+ }
+ }
+
+ @Test
+ public void testGet() {
+ final String zkParentKey = "/stressZk_testGet";
+ try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
+ zkMetaClient.connect();
+ zkMetaClient.create(zkParentKey, "parent_node");
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ zkMetaClient.create(zkParentKey + "/" + i, i);
+ }
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertEquals(zkMetaClient.get(zkParentKey + "/" + i), i);
+ }
+
+ // Test with non-existent node path
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ Assert.assertNull(zkMetaClient.get("/a/b/c"));
+ }
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ zkMetaClient.get("a/b/c");
+ Assert.fail("Should have failed due to invalid path - no leading /.");
+ } catch (Exception ignoredException) {
+ }
+ }
+ }
+ cleanUpTestNodes(zkParentKey);
+ }
+
+ @Test
+ public void testSetSingleNode() {
+ final String zkParentKey = "/stressZk_testSetSingleNode";
+ try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
+ zkMetaClient.connect();
+ zkMetaClient.create(zkParentKey, "parent_node");
+
+ // Set with no expected version
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ zkMetaClient.set(zkParentKey, String.valueOf(i), -1);
+ MetaClientInterface.Stat entryStat = zkMetaClient.exists(zkParentKey);
+
+ Assert.assertEquals(zkMetaClient.get(zkParentKey), String.valueOf(i));
+ Assert.assertEquals(entryStat.getVersion(), i + 1);
+ Assert.assertEquals(entryStat.getEntryType().name(), PERSISTENT.name());
+ }
+
+ zkMetaClient.delete(zkParentKey);
+ zkMetaClient.create(zkParentKey, "parent_node");
+
+ // Set with expected version
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ zkMetaClient.set(zkParentKey, String.valueOf(i), i);
+ MetaClientInterface.Stat entryStat = zkMetaClient.exists(zkParentKey);
+
+ Assert.assertEquals(zkMetaClient.get(zkParentKey), String.valueOf(i));
+ Assert.assertEquals(entryStat.getVersion(), i + 1);
+ }
+
+ zkMetaClient.delete(zkParentKey);
+ zkMetaClient.create(zkParentKey, "parent_node");
+
+ // Set with bad expected version - should fail
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ zkMetaClient.set(zkParentKey, "test-should-fail", 12345);
+ Assert.fail("Should have failed due to bad expected version in set function.");
+ } catch (MetaClientException ex) {
+ Assert.assertEquals(ex.getClass().getName(),
+ "org.apache.helix.metaclient.exception.MetaClientBadVersionException");
+ }
+ }
+
+ zkMetaClient.delete(zkParentKey);
+ zkMetaClient.create(zkParentKey, "parent_node");
+
+ // Set with path to non-existent node - should fail
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ zkMetaClient.set("/a/b/c", "test-should-fail", -1);
+ Assert.fail("Should have failed due to path to non-existent node");
+ } catch (Exception ignoredException) {
+ }
+ }
+
+ zkMetaClient.delete(zkParentKey);
+ zkMetaClient.create(zkParentKey, "parent_node");
+
+ // Set with invalid path - should fail
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ zkMetaClient.set("a/b/c", "test-should-fail", -1);
+ Assert.fail("Should have failed due to invalid path - no leading /.");
+ } catch (Exception ignoredException) {
+ }
+ }
+ }
+
+ cleanUpTestNodes(zkParentKey);
+ }
+
+ @Test
+ public void testSetMultiNode() {
+ final String zkParentKey = "/stressZk_testSetMultiNode";
+ try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
+ zkMetaClient.connect();
+ zkMetaClient.create(zkParentKey, "parent_node");
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ zkMetaClient.create(zkParentKey + "/" + i, i);
+ }
+
+ // Set with no expected version
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ zkMetaClient.set(zkParentKey + "/" + i, "-" + i, -1);
+ }
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ String childKey = zkParentKey + "/" + i;
+ MetaClientInterface.Stat entryStat = zkMetaClient.exists(childKey);
+
+ Assert.assertEquals(zkMetaClient.get(childKey), "-" + i);
+ Assert.assertEquals(entryStat.getVersion(), 1);
+ Assert.assertEquals(entryStat.getEntryType().name(), PERSISTENT.name());
+ }
+
+ // Set with expected version
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ String childKey = zkParentKey + "/" + i;
+ zkMetaClient.set(childKey, String.valueOf(i), 1);
+ MetaClientInterface.Stat entryStat = zkMetaClient.exists(childKey);
+
+ Assert.assertEquals(zkMetaClient.get(childKey), String.valueOf(i));
+ Assert.assertEquals(entryStat.getVersion(), 2);
+ }
+ }
+ cleanUpTestNodes(zkParentKey);
+ }
+
+ @Test
+ public void testUpdateSingleNode() {
+ final String zkParentKey = "/stressZk_testUpdateSingleNode";
+ ZkMetaClientConfig config =
+ new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR).build();
+ try (ZkMetaClient<Integer> zkMetaClient = new ZkMetaClient<>(config)) {
+ zkMetaClient.connect();
+ zkMetaClient.create(zkParentKey, 0);
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ MetaClientInterface.Stat entryStat = zkMetaClient.exists(zkParentKey);
+ Assert.assertEquals(entryStat.getVersion(), i);
+
+ Integer newData = zkMetaClient.update(zkParentKey, new DataUpdater<Integer>() {
+ @Override
+ public Integer update(Integer currentData) {
+ return currentData + 1;
+ }
+ });
+ Assert.assertEquals((int) newData, i + 1);
+ }
+
+ zkMetaClient.delete(zkParentKey);
+ zkMetaClient.create(zkParentKey, "parent_node");
+
+ // Set with path to non-existent node - should fail
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ zkMetaClient.update("/a/b/c", new DataUpdater<Integer>() {
+ @Override
+ public Integer update(Integer currentData) {
+ return currentData + 1;
+ }
+ });
+
+ Assert.fail("Should have failed due to path to non-existent node");
+ } catch (Exception ignoredException) {
+ }
+ }
+
+ zkMetaClient.delete(zkParentKey);
+ zkMetaClient.create(zkParentKey, "parent_node");
+
+ // Set with invalid path - should fail
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ try {
+ zkMetaClient.update("/a/b/c", new DataUpdater<Integer>() {
+ @Override
+ public Integer update(Integer currentData) {
+ return currentData + 1;
+ }
+ });
+ Assert.fail("Should have failed due to invalid path - no leading /.");
+ } catch (Exception ignoredException) {
+ }
+ }
+ }
+ cleanUpTestNodes(zkParentKey);
+ }
+
+ @Test
+ public void testUpdateMultiNode() {
+ final String zkParentKey = "/stressZk_testUpdateSingleNode";
+ ZkMetaClientConfig config =
+ new ZkMetaClientConfig.ZkMetaClientConfigBuilder().setConnectionAddress(ZK_ADDR).build();
+ try (ZkMetaClient<Integer> zkMetaClient = new ZkMetaClient<>(config)) {
+ zkMetaClient.connect();
+ zkMetaClient.create(zkParentKey, "test_parent");
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ zkMetaClient.create(zkParentKey + "/" + i, 0);
+ }
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ String childKey = zkParentKey + "/" + i;
+ MetaClientInterface.Stat entryStat = zkMetaClient.exists(childKey);
+ Assert.assertEquals(entryStat.getVersion(), 0);
+
+ Integer newData = zkMetaClient.update(childKey, new DataUpdater<Integer>() {
+ @Override
+ public Integer update(Integer currentData) {
+ return currentData + 1;
+ }
+ });
+
+ Assert.assertEquals((int) newData, 1);
+ entryStat = zkMetaClient.exists(childKey);
+ Assert.assertEquals(entryStat.getVersion(), 1);
+ }
+ }
+ cleanUpTestNodes(zkParentKey);
+ }
+
+ @Test
+ public void testMultipleDataChangeListeners() throws Exception {
+ final String zkParentKey = "/stressZk_testMultipleDataChangeListeners";
+ final int listenerCount = 10;
+ final String testData = "test-data";
+ final AtomicBoolean dataExpected = new AtomicBoolean(true);
+
+ try (ZkMetaClient<String> zkMetaClient = createZkMetaClient()) {
+ zkMetaClient.connect();
+ zkMetaClient.create(zkParentKey, "parent_node");
+ Map<String, Set<DataChangeListener>> listeners = new HashMap<>();
+ CountDownLatch countDownLatch = new CountDownLatch((int) TEST_ITERATION_COUNT * listenerCount);
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ zkMetaClient.create(zkParentKey + "/" + i, i);
+ }
+
+ // create paths
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ String childKey = zkParentKey + "/" + i;
+ listeners.put(childKey, new HashSet<>());
+ for (int j = 0; j < listenerCount; j++) {
+ DataChangeListener listener = new DataChangeListener() {
+ @Override
+ public void handleDataChange(String key, Object data, ChangeType changeType) {
+ countDownLatch.countDown();
+ dataExpected.set(dataExpected.get() && testData.equals(data));
+ }
+ };
+ listeners.get(childKey).add(listener);
+ zkMetaClient.subscribeDataChange(childKey, listener, false);
+ }
+ }
+
+ for (int i = 0; i < TEST_ITERATION_COUNT; i++) {
+ zkMetaClient.set(zkParentKey + "/" + i, testData, -1);
+ }
+
+ Assert.assertTrue(countDownLatch.await(5000, TimeUnit.MILLISECONDS));
+ Assert.assertTrue(dataExpected.get());
+ }
+ cleanUpTestNodes(zkParentKey);
+ }
}
\ No newline at end of file
[helix] 15/21: Multithreading stress test lattice - CRUD puppies and Listener Tests (#2548)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit b1f59e6f8669633df47523f7e36e989afd496fa2
Author: Marcos Rico Peng <55...@users.noreply.github.com>
AuthorDate: Thu Jul 20 13:05:37 2023 -0400
Multithreading stress test lattice - CRUD puppies and Listener Tests (#2548)
---------
Co-authored-by: mapeng <ma...@linkedin.com>
---
.../helix/metaclient/impl/zk/ZkMetaClient.java | 6 +-
.../zk/TestMultiThreadStressTest/CreatePuppy.java | 78 +++++
.../zk/TestMultiThreadStressTest/DeletePuppy.java | 67 ++++
.../zk/TestMultiThreadStressTest/GetPuppy.java | 68 ++++
.../zk/TestMultiThreadStressTest/SetPuppy.java | 71 +++++
.../TestMultiThreadStressZKClient.java | 352 +++++++++++++++++++++
.../zk/TestMultiThreadStressTest/UpdatePuppy.java | 74 +++++
.../helix/metaclient/puppy/AbstractPuppy.java | 7 +-
8 files changed, 717 insertions(+), 6 deletions(-)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
index 7f68ec9ca..691f31cde 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/impl/zk/ZkMetaClient.java
@@ -101,9 +101,7 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
try {
create(key, data, EntryMode.PERSISTENT);
} catch (ZkException e) {
- throw ZkMetaClientUtil.translateZkExceptionToMetaclientException(e);
- } catch (Exception e) {
- throw new MetaClientException(e);
+ throw translateZkExceptionToMetaclientException(e);
}
}
@@ -113,7 +111,7 @@ public class ZkMetaClient<T> implements MetaClientInterface<T>, AutoCloseable {
try {
_zkClient.create(key, data, ZkMetaClientUtil.convertMetaClientMode(mode));
} catch (ZkException e) {
- throw ZkMetaClientUtil.translateZkExceptionToMetaclientException(e);
+ throw translateZkExceptionToMetaclientException(e);
} catch (KeeperException e) {
throw new MetaClientException(e);
}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/CreatePuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/CreatePuppy.java
new file mode 100644
index 000000000..3e28df06b
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/CreatePuppy.java
@@ -0,0 +1,78 @@
+package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest;
+
+/*
+ * 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.
+ */
+
+import org.apache.helix.metaclient.api.MetaClientInterface;
+import org.apache.helix.metaclient.exception.MetaClientNodeExistsException;
+import org.apache.helix.metaclient.puppy.AbstractPuppy;
+import org.apache.helix.metaclient.puppy.PuppySpec;
+
+import java.util.Random;
+
+public class CreatePuppy extends AbstractPuppy {
+
+ private final Random _random;
+ private final String _parentPath = "/test";
+
+ public CreatePuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) {
+ super(metaclient, puppySpec);
+ _random = new Random();
+ }
+
+ @Override
+ protected void bark() {
+ // Implement the chaos logic for creating nodes
+ int randomNumber = _random.nextInt(_puppySpec.getNumberDiffPaths());
+ if (shouldIntroduceError()) {
+ try {
+ // Simulate an error by creating an invalid path
+ _metaclient.create("invalid", "test");
+ } catch (IllegalArgumentException e) { // Catch invalid exception
+ System.out.println(Thread.currentThread().getName() + " tried to create an invalid path" + " at time: " + System.currentTimeMillis());
+ // Expected exception
+ }
+ } else {
+ // Normal behavior - create a new node
+ try {
+ System.out.println(Thread.currentThread().getName() + " is attempting to create node: " + randomNumber + " at time: " + System.currentTimeMillis());
+ _metaclient.create(_parentPath + "/" + randomNumber,"test");
+ System.out.println(Thread.currentThread().getName() + " successfully created node " + randomNumber + " at time: " + System.currentTimeMillis());
+ _eventChangeCounterMap.put(String.valueOf(randomNumber), _eventChangeCounterMap.getOrDefault(String.valueOf(randomNumber), 0) + 1);
+ } catch (MetaClientNodeExistsException e) {
+ // Expected exception
+ System.out.println(Thread.currentThread().getName() + " failed to create node " + randomNumber + " at time: " + System.currentTimeMillis() + ", it already exists");
+ }
+ }
+ }
+
+ @Override
+ protected void cleanup() {
+ // Implement the recovery logic by deleting the created documents
+ _metaclient.recursiveDelete(_parentPath);
+ }
+
+ private boolean shouldIntroduceError() {
+ float randomValue = _random.nextFloat();
+ return randomValue < _puppySpec.getErrorRate();
+ }
+}
+
+
+
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/DeletePuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/DeletePuppy.java
new file mode 100644
index 000000000..e0e1b7b5c
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/DeletePuppy.java
@@ -0,0 +1,67 @@
+package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest;
+
+/*
+ * 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.
+ */
+
+import org.apache.helix.metaclient.api.MetaClientInterface;
+import org.apache.helix.metaclient.puppy.AbstractPuppy;
+import org.apache.helix.metaclient.puppy.PuppySpec;
+
+import java.util.Random;
+
+public class DeletePuppy extends AbstractPuppy {
+
+ private final Random _random;
+ private final String _parentPath = "/test";
+
+ public DeletePuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) {
+ super(metaclient, puppySpec);
+ _random = new Random();
+ }
+
+ @Override
+ protected void bark() {
+ int randomNumber = _random.nextInt(_puppySpec.getNumberDiffPaths());
+ if (shouldIntroduceError()) {
+ try {
+ _metaclient.delete("invalid");
+ _unhandledErrorCounter++;
+ } catch (IllegalArgumentException e) {
+ System.out.println(Thread.currentThread().getName() + " intentionally deleted an invalid path" + " at time: " + System.currentTimeMillis() );
+ }
+ } else {
+ System.out.println(Thread.currentThread().getName() + " is attempting to delete node: " + randomNumber + " at time: " + System.currentTimeMillis());
+ if (_metaclient.delete(_parentPath + "/" + randomNumber)) {
+ System.out.println(Thread.currentThread().getName() + " successfully deleted node " + randomNumber + " at time: " + System.currentTimeMillis());
+ _eventChangeCounterMap.put(String.valueOf(randomNumber), _eventChangeCounterMap.getOrDefault(String.valueOf(randomNumber), 0) + 1);
+ } else {
+ System.out.println(Thread.currentThread().getName() + " failed to delete node " + randomNumber + " at time: " + System.currentTimeMillis() + ", it does not exist");
+ }
+ }
+ }
+
+ @Override
+ protected void cleanup() {
+ _metaclient.recursiveDelete(_parentPath);
+ }
+
+ private boolean shouldIntroduceError() {
+ return _random.nextFloat() < _puppySpec.getErrorRate();
+ }
+}
\ No newline at end of file
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/GetPuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/GetPuppy.java
new file mode 100644
index 000000000..fe24b2bd3
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/GetPuppy.java
@@ -0,0 +1,68 @@
+package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest;
+
+/*
+ * 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.
+ */
+
+import org.apache.helix.metaclient.api.MetaClientInterface;
+import org.apache.helix.metaclient.puppy.AbstractPuppy;
+import org.apache.helix.metaclient.puppy.PuppySpec;
+
+import java.util.Objects;
+import java.util.Random;
+
+public class GetPuppy extends AbstractPuppy {
+
+ private final Random _random;
+ private final String _parentPath = "/test";
+
+ public GetPuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) {
+ super(metaclient, puppySpec);
+ _random = new Random();
+ }
+
+ @Override
+ protected void bark() {
+ int randomNumber = _random.nextInt(_puppySpec.getNumberDiffPaths());
+ if (shouldIntroduceError()) {
+ try {
+ _metaclient.get("invalid");
+ _unhandledErrorCounter++;
+ } catch (IllegalArgumentException e) {
+ System.out.println(Thread.currentThread().getName() + " intentionally tried to read an invalid path" + " at time: " + System.currentTimeMillis());
+ }
+ } else {
+ System.out.println(Thread.currentThread().getName() + " is attempting to read node: " + randomNumber + " at time: " + System.currentTimeMillis());
+ String nodeValue = _metaclient.get(_parentPath + "/" + randomNumber);
+ if (Objects.equals(nodeValue, null)) {
+ System.out.println(Thread.currentThread().getName() + " failed to read node " + randomNumber + " at time: " + System.currentTimeMillis() + ", it does not exist");
+ } else {
+ System.out.println(Thread.currentThread().getName() + " successfully read node " + randomNumber + " at time: " + System.currentTimeMillis());
+ }
+ }
+ }
+
+ @Override
+ protected void cleanup() {
+ _metaclient.recursiveDelete(_parentPath);
+ }
+
+ private boolean shouldIntroduceError() {
+ return _random.nextFloat() < _puppySpec.getErrorRate();
+ }
+}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/SetPuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/SetPuppy.java
new file mode 100644
index 000000000..c0de4ece7
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/SetPuppy.java
@@ -0,0 +1,71 @@
+package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest;
+
+/*
+ * 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.
+ */
+
+import org.apache.helix.metaclient.api.MetaClientInterface;
+import org.apache.helix.metaclient.exception.MetaClientNoNodeException;
+import org.apache.helix.metaclient.puppy.AbstractPuppy;
+import org.apache.helix.metaclient.puppy.PuppySpec;
+
+import java.util.Random;
+
+public class SetPuppy extends AbstractPuppy {
+
+ private final Random _random;
+ private final String _parentPath = "/test";
+
+ public SetPuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) {
+ super(metaclient, puppySpec);
+ _random = new Random();
+ }
+
+ @Override
+ protected void bark() {
+ int randomNumber = _random.nextInt(_puppySpec.getNumberDiffPaths());
+ if (shouldIntroduceError()) {
+ try {
+ _metaclient.set("invalid", "test", -1);
+ } catch (IllegalArgumentException e) {
+ System.out.println(Thread.currentThread().getName() + " intentionally called set on an invalid path" + " at time: " + System.currentTimeMillis());
+ }
+ } else {
+ try {
+ System.out.println(Thread.currentThread().getName() + " is attempting to set node: " + randomNumber + " at time: " + System.currentTimeMillis());
+ _metaclient.set(_parentPath + "/" + randomNumber, "test", -1);
+ _eventChangeCounterMap.put(String.valueOf(randomNumber), _eventChangeCounterMap.getOrDefault(String.valueOf(randomNumber), 0) + 1);
+ System.out.println(
+ Thread.currentThread().getName() + " successfully set node " + randomNumber + " at time: "
+ + System.currentTimeMillis());
+ } catch (MetaClientNoNodeException e) {
+ System.out.println(Thread.currentThread().getName() + " failed to set node " + randomNumber + " at time: " + System.currentTimeMillis() + ", it does not exist");
+ }
+ }
+ }
+
+ @Override
+ protected void cleanup() {
+ _metaclient.recursiveDelete(_parentPath);
+ }
+
+ private boolean shouldIntroduceError() {
+ float randomValue = _random.nextFloat();
+ return randomValue < _puppySpec.getErrorRate();
+ }
+}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/TestMultiThreadStressZKClient.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/TestMultiThreadStressZKClient.java
new file mode 100644
index 000000000..5ee026bc1
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/TestMultiThreadStressZKClient.java
@@ -0,0 +1,352 @@
+package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest;
+
+/*
+ * 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.
+ */
+
+import org.apache.helix.metaclient.api.ChildChangeListener;
+import org.apache.helix.metaclient.impl.zk.ZkMetaClient;
+import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase;
+import org.apache.helix.metaclient.puppy.ExecDelay;
+import org.apache.helix.metaclient.puppy.PuppyManager;
+import org.apache.helix.metaclient.puppy.PuppyMode;
+import org.apache.helix.metaclient.puppy.PuppySpec;
+import org.apache.helix.metaclient.puppy.AbstractPuppy;
+import org.testng.Assert;
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class TestMultiThreadStressZKClient extends ZkMetaClientTestBase {
+
+ private ZkMetaClient<String> _zkMetaClient;
+ private final String zkParentKey = "/test";
+
+ private final long TIMEOUT = 60; // The desired timeout duration of tests in seconds
+
+ @BeforeTest
+ private void setUp() {
+ this._zkMetaClient = createZkMetaClient();
+ this._zkMetaClient.connect();
+ }
+
+ @Test
+ public void testCreatePuppy() {
+ _zkMetaClient.create(zkParentKey, "test");
+
+ PuppySpec puppySpec = new org.apache.helix.metaclient.puppy.PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
+ CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec);
+ CreatePuppy createPuppy2 = new CreatePuppy(_zkMetaClient, puppySpec);
+ CreatePuppy createPuppy3 = new CreatePuppy(_zkMetaClient, puppySpec);
+
+ PuppyManager puppyManager = new PuppyManager();
+ puppyManager.addPuppy(createPuppy);
+ puppyManager.addPuppy(createPuppy2);
+ puppyManager.addPuppy(createPuppy3);
+
+ puppyManager.start(TIMEOUT);
+
+ assertNoExceptions(puppyManager, null);
+
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
+ }
+
+ @Test
+ public void testDeletePuppy() {
+ _zkMetaClient.create(zkParentKey, "test");
+
+ PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
+ CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec);
+ DeletePuppy deletePuppy = new DeletePuppy(_zkMetaClient, puppySpec);
+
+ PuppyManager puppyManager = new PuppyManager();
+ puppyManager.addPuppy(createPuppy);
+ puppyManager.addPuppy(deletePuppy);
+
+ puppyManager.start(TIMEOUT);
+
+ assertNoExceptions(puppyManager, null);
+
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
+ }
+
+ @Test
+ public void testGetPuppy() {
+ _zkMetaClient.create(zkParentKey, "test");
+
+ PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
+ CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec);
+ GetPuppy getPuppy = new GetPuppy(_zkMetaClient, puppySpec);
+
+ PuppyManager puppyManager = new PuppyManager();
+ puppyManager.addPuppy(createPuppy);
+ puppyManager.addPuppy(getPuppy);
+
+ puppyManager.start(TIMEOUT);
+
+ assertNoExceptions(puppyManager, null);
+
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
+ }
+
+ @Test
+ public void testSetPuppy() {
+ _zkMetaClient.create(zkParentKey, "test");
+
+ PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
+ CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec);
+ SetPuppy setPuppy = new SetPuppy(_zkMetaClient, puppySpec);
+
+ PuppyManager puppyManager = new PuppyManager();
+ puppyManager.addPuppy(createPuppy);
+ puppyManager.addPuppy(setPuppy);
+
+ puppyManager.start(TIMEOUT);
+
+ assertNoExceptions(puppyManager, null);
+
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
+ }
+
+ @Test
+ public void testUpdatePuppy() {
+ _zkMetaClient.create(zkParentKey, "test");
+
+ PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
+ CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec);
+ UpdatePuppy updatePuppy = new UpdatePuppy(_zkMetaClient, puppySpec);
+
+ PuppyManager puppyManager = new PuppyManager();
+ puppyManager.addPuppy(createPuppy);
+ puppyManager.addPuppy(updatePuppy);
+
+ puppyManager.start(TIMEOUT);
+
+ assertNoExceptions(puppyManager, null);
+
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
+ }
+
+ @Test
+ public void testCrudPuppies() {
+ _zkMetaClient.create(zkParentKey, "test");
+
+ PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
+ CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec);
+ GetPuppy getPuppy = new GetPuppy(_zkMetaClient, puppySpec);
+ DeletePuppy deletePuppy = new DeletePuppy(_zkMetaClient, puppySpec);
+ SetPuppy setPuppy = new SetPuppy(_zkMetaClient, puppySpec);
+ UpdatePuppy updatePuppy = new UpdatePuppy(_zkMetaClient, puppySpec);
+
+ PuppyManager puppyManager = new PuppyManager();
+ puppyManager.addPuppy(createPuppy);
+ puppyManager.addPuppy(getPuppy);
+ puppyManager.addPuppy(deletePuppy);
+ puppyManager.addPuppy(setPuppy);
+ puppyManager.addPuppy(updatePuppy);
+
+ puppyManager.start(TIMEOUT);
+
+ assertNoExceptions(puppyManager, null);
+
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
+ }
+
+
+ @Test
+ public void testBasicParentListenerPuppy() {
+ _zkMetaClient.create(zkParentKey, "test");
+ AtomicInteger globalChildChangeCounter = new AtomicInteger();
+ ChildChangeListener childChangeListener = (changedPath, changeType) -> {
+ globalChildChangeCounter.addAndGet(1);
+ System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + " number of changes: " + globalChildChangeCounter.get());
+ };
+
+ _zkMetaClient.subscribeChildChanges(zkParentKey, childChangeListener, false);
+
+ PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
+ CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec);
+
+ PuppyManager puppyManager = new PuppyManager();
+ puppyManager.addPuppy(createPuppy);
+
+ puppyManager.start(TIMEOUT);
+
+ assertNoExceptions(puppyManager, globalChildChangeCounter);
+
+ // cleanup
+ _zkMetaClient.unsubscribeChildChanges(zkParentKey, childChangeListener);
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
+ }
+
+ @Test
+ public void testComplexParentListenerPuppy() {
+ _zkMetaClient.create(zkParentKey, "test");
+ // Global counter for all child changes
+ AtomicInteger globalChildChangeCounter = new AtomicInteger();
+ ChildChangeListener childChangeListener = (changedPath, changeType) -> {
+ globalChildChangeCounter.addAndGet(1);
+ System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + " number of changes: " + globalChildChangeCounter.get());
+ };
+
+
+ _zkMetaClient.subscribeChildChanges(zkParentKey, childChangeListener, false);
+
+ PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
+ CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec);
+ GetPuppy getPuppy = new GetPuppy(_zkMetaClient, puppySpec);
+ DeletePuppy deletePuppy = new DeletePuppy(_zkMetaClient, puppySpec);
+ SetPuppy setPuppy = new SetPuppy(_zkMetaClient, puppySpec);
+ UpdatePuppy updatePuppy = new UpdatePuppy(_zkMetaClient, puppySpec);
+
+ PuppyManager puppyManager = new PuppyManager();
+ puppyManager.addPuppy(createPuppy);
+ puppyManager.addPuppy(getPuppy);
+ puppyManager.addPuppy(deletePuppy);
+ puppyManager.addPuppy(setPuppy);
+ puppyManager.addPuppy(updatePuppy);
+
+ puppyManager.start(TIMEOUT);
+
+ assertNoExceptions(puppyManager, globalChildChangeCounter);
+
+ // cleanup
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
+ _zkMetaClient.unsubscribeChildChanges(zkParentKey, childChangeListener);
+ _zkMetaClient.delete(zkParentKey);
+ }
+
+
+ @Test
+ public void testChildListenerPuppy() {
+ _zkMetaClient.create(zkParentKey, "test");
+ // Setting num diff paths to 3 until we find a better way of scaling listeners.
+ PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 3);
+ CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec);
+ GetPuppy getPuppy = new GetPuppy(_zkMetaClient, puppySpec);
+ DeletePuppy deletePuppy = new DeletePuppy(_zkMetaClient, puppySpec);
+ SetPuppy setPuppy = new SetPuppy(_zkMetaClient, puppySpec);
+ UpdatePuppy updatePuppy = new UpdatePuppy(_zkMetaClient, puppySpec);
+
+ PuppyManager puppyManager = new PuppyManager();
+ puppyManager.addPuppy(createPuppy);
+ puppyManager.addPuppy(getPuppy);
+ puppyManager.addPuppy(deletePuppy);
+ puppyManager.addPuppy(setPuppy);
+ puppyManager.addPuppy(updatePuppy);
+
+ // Create a child listener for each child defined in number diff paths in puppyspec.
+ // TODO: Make this a parameter for a loop.
+ AtomicInteger childChangeCounter0 = new AtomicInteger();
+ ChildChangeListener childChangeListener0 = (changedPath, changeType) -> {
+ childChangeCounter0.addAndGet(1);
+ System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + " number of changes: " + childChangeCounter0.get());
+ };
+ _zkMetaClient.subscribeChildChanges("/test/0", childChangeListener0, false);
+
+ AtomicInteger childChangeCounter1 = new AtomicInteger();
+ ChildChangeListener childChangeListener1 = (changedPath, changeType) -> {
+ childChangeCounter1.addAndGet(1);
+ System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + " number of changes: " + childChangeCounter1.get());
+ };
+ _zkMetaClient.subscribeChildChanges("/test/1", childChangeListener1, false);
+
+ AtomicInteger childChangeCounter2 = new AtomicInteger();
+ ChildChangeListener childChangeListener2 = (changedPath, changeType) -> {
+ childChangeCounter2.addAndGet(1);
+ System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + " number of changes: " + childChangeCounter2.get());
+ };
+ _zkMetaClient.subscribeChildChanges("/test/2", childChangeListener2, false);
+
+ puppyManager.start(TIMEOUT);
+
+ assertNoExceptions(puppyManager, null);
+
+ // Add all event changes from all puppies and compare with child change listener
+ // Inner merged by path
+ Map<String, Integer> mergedEventChangeCounterMap = new HashMap<>();
+ for (AbstractPuppy puppy : puppyManager.getPuppies()) {
+ puppy._eventChangeCounterMap.forEach((key, value) -> {
+ if (mergedEventChangeCounterMap.containsKey(key)) {
+ mergedEventChangeCounterMap.put(key, mergedEventChangeCounterMap.get(key) + value);
+ } else {
+ mergedEventChangeCounterMap.put(key, value);
+ }
+ });
+ }
+
+ System.out.println("Merged event change counter map: " + mergedEventChangeCounterMap);
+ System.out.println("Child change counter 0: " + childChangeCounter0);
+ System.out.println("Child change counter 1: " + childChangeCounter1);
+ System.out.println("Child change counter 2: " + childChangeCounter2);
+ Assert.assertEquals(childChangeCounter0.get(), mergedEventChangeCounterMap.getOrDefault("0", 0).intValue());
+ Assert.assertEquals(childChangeCounter1.get(), mergedEventChangeCounterMap.getOrDefault("1", 0).intValue());
+ Assert.assertEquals(childChangeCounter2.get(), mergedEventChangeCounterMap.getOrDefault("2", 0).intValue());
+
+ // cleanup
+ _zkMetaClient.unsubscribeChildChanges("/test/0", childChangeListener0);
+ _zkMetaClient.unsubscribeChildChanges("/test/1", childChangeListener1);
+ _zkMetaClient.unsubscribeChildChanges("/test/2", childChangeListener2);
+ _zkMetaClient.recursiveDelete(zkParentKey);
+ Assert.assertEquals(_zkMetaClient.countDirectChildren(zkParentKey), 0);
+ }
+
+ private void assertNoExceptions(PuppyManager puppyManager, AtomicInteger globalChangeCounter) {
+ int totalUnhandledErrors = 0;
+ int totalEventChanges = 0;
+
+ // Add all change counters and compare with event change listener
+ for (AbstractPuppy puppy : puppyManager.getPuppies()) {
+ AtomicInteger totalHandledErrors = new AtomicInteger();
+ puppy._eventChangeCounterMap.forEach((key, value) -> {
+ totalHandledErrors.addAndGet(value);
+ });
+
+ System.out.println("Change counter: " + totalHandledErrors + " for " + puppy.getClass());
+ System.out.println("Error counter: " + puppy._unhandledErrorCounter + " for " + puppy.getClass());
+ totalUnhandledErrors += puppy._unhandledErrorCounter;
+ totalEventChanges += totalHandledErrors.get();
+ }
+
+ // Assert no unhandled (unexpected) exceptions and that the child change listener placed on
+ // test parent node (/test) caught all successful changes that were recorded by each puppy
+ Assert.assertEquals(totalUnhandledErrors, 0);
+
+ // Assert that the global change counter matches the total number of events recorded by each puppy
+ if (globalChangeCounter != null) {
+ Assert.assertEquals(totalEventChanges, globalChangeCounter.get());
+ }
+ }
+}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/UpdatePuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/UpdatePuppy.java
new file mode 100644
index 000000000..721d507eb
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/UpdatePuppy.java
@@ -0,0 +1,74 @@
+package org.apache.helix.metaclient.impl.zk.TestMultiThreadStressTest;
+
+/*
+ * 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.
+ */
+
+import org.apache.helix.metaclient.api.MetaClientInterface;
+import org.apache.helix.metaclient.exception.MetaClientNoNodeException;
+import org.apache.helix.metaclient.puppy.AbstractPuppy;
+import org.apache.helix.metaclient.puppy.PuppySpec;
+
+import java.util.Random;
+
+public class UpdatePuppy extends AbstractPuppy {
+
+ private final Random _random;
+ private final String _parentPath = "/test";
+
+ public UpdatePuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) {
+ super(metaclient, puppySpec);
+ _random = new Random();
+ }
+
+ @Override
+ protected void bark() throws Exception {
+ int randomNumber = _random.nextInt(_puppySpec.getNumberDiffPaths());
+ if (shouldIntroduceError()) {
+ try {
+ _metaclient.update("invalid", (data) -> "foo");
+ } catch (IllegalArgumentException e) {
+ System.out.println(Thread.currentThread().getName() + " intentionally tried to update an invalid path" + " at time: " + System.currentTimeMillis());
+ }
+ } else {
+ try {
+ System.out.println(Thread.currentThread().getName() + " is attempting to update node: " + randomNumber + " at time: " + System.currentTimeMillis());
+ _metaclient.update(_parentPath + "/" + randomNumber, (data) -> "foo");
+ _eventChangeCounterMap.put(String.valueOf(randomNumber), _eventChangeCounterMap.getOrDefault(String.valueOf(randomNumber), 0) + 1);
+ System.out.println(Thread.currentThread().getName() + " successfully updated node " + randomNumber + " at time: "
+ + System.currentTimeMillis());
+ } catch (MetaClientNoNodeException e) {
+ System.out.println(Thread.currentThread().getName() + " failed to update node " + randomNumber + " at time: " + System.currentTimeMillis() + ", it does not exist");
+ } catch (IllegalArgumentException e) {
+ if (!e.getMessage().equals("Can not subscribe one time watcher when ZkClient is using PersistWatcher")) {
+ throw e;
+ }
+ }
+ }
+ }
+
+ @Override
+ protected void cleanup() {
+ _metaclient.recursiveDelete(_parentPath);
+ }
+
+ private boolean shouldIntroduceError() {
+ float randomValue = _random.nextFloat();
+ return randomValue < _puppySpec.getErrorRate();
+ }
+}
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
index 85137fc17..bfbbb915d 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
@@ -29,8 +29,9 @@ public abstract class AbstractPuppy implements Runnable {
protected MetaClientInterface<String> _metaclient;
protected PuppySpec _puppySpec;
- public HashMap<String, Integer> _eventChangeCounterMap;
- protected int _unhandledErrorCounter;
+ public final HashMap<String, Integer> _eventChangeCounterMap;
+ public int _unhandledErrorCounter;
+
public AbstractPuppy(MetaClientInterface<String> metaclient, PuppySpec puppySpec) {
_metaclient = metaclient;
@@ -69,6 +70,8 @@ public abstract class AbstractPuppy implements Runnable {
try {
Thread.sleep(getPuppySpec().getExecDelay().getNextDelay());
} catch (InterruptedException e) {
+ cleanup();
+ break;
// Handle interruption if necessary
}
}
[helix] 10/21: Lattice MetaClient Distributed Semaphore Implementation (#2515)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit c7a0d28fc605f521c8597622a6eea442b34b3195
Author: Marcos Rico Peng <55...@users.noreply.github.com>
AuthorDate: Fri Jun 23 19:12:23 2023 -0400
Lattice MetaClient Distributed Semaphore Implementation (#2515)
Co-authored-by: mapeng <ma...@linkedin.com>
---
.../recipes/lock/DistributedSemaphore.java | 123 ++++++++++++++++++---
.../helix/metaclient/recipes/lock/LockClient.java | 8 +-
.../recipes/lock/DistributedSemaphoreTest.java | 105 ++++++++++++++++++
3 files changed, 221 insertions(+), 15 deletions(-)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java
index 0cccb130f..7b16e78fd 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphore.java
@@ -22,18 +22,45 @@ package org.apache.helix.metaclient.recipes.lock;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.helix.metaclient.api.MetaClientInterface;
import org.apache.helix.metaclient.datamodel.DataRecord;
+import org.apache.helix.metaclient.exception.MetaClientException;
import org.apache.helix.metaclient.factories.MetaClientConfig;
+import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientConfig;
+import org.apache.helix.metaclient.impl.zk.factory.ZkMetaClientFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
public class DistributedSemaphore {
+ private final MetaClientInterface<DataRecord> _metaClient;
+ private String _path;
+ private static final String INITIAL_CAPACITY_NAME = "INITIAL_CAPACITY";
+ private static final String REMAINING_CAPACITY_NAME = "REMAINING_CAPACITY";
+ private static final long DEFAULT_REMAINING_CAPACITY = -1;
+ private static final Logger LOG = LoggerFactory.getLogger(DistributedSemaphore.class);
/**
* Create a distributed semaphore client with the given configuration.
* @param config configuration of the client
*/
public DistributedSemaphore(MetaClientConfig config) {
- throw new NotImplementedException("Not implemented yet.");
+ if (config == null) {
+ throw new MetaClientException("Configuration cannot be null");
+ }
+ LOG.info("Creating DistributedSemaphore Client");
+ if (MetaClientConfig.StoreType.ZOOKEEPER.equals(config.getStoreType())) {
+ ZkMetaClientConfig zkMetaClientConfig = new ZkMetaClientConfig.ZkMetaClientConfigBuilder()
+ .setConnectionAddress(config.getConnectionAddress())
+ .setZkSerializer(new DataRecordSerializer()) // Currently only support ZNRecordSerializer.
+ // Setting DataRecordSerializer as DataRecord extends ZNRecord.
+ .build();
+ _metaClient = new ZkMetaClientFactory().getMetaClient(zkMetaClientConfig);
+ _metaClient.connect();
+ } else {
+ throw new MetaClientException("Unsupported store type: " + config.getStoreType());
+ }
}
/**
@@ -41,7 +68,17 @@ public class DistributedSemaphore {
* @param client client to connect to
*/
public DistributedSemaphore(MetaClientInterface<DataRecord> client) {
- throw new NotImplementedException("Not implemented yet.");
+ if (client == null) {
+ throw new MetaClientException("Client cannot be null");
+ }
+ LOG.info("Connecting to existing DistributedSemaphore Client");
+ _metaClient = client;
+ try {
+ _metaClient.connect();
+ // TODO: Differentiate exception catch between already connected and already closed.
+ } catch (IllegalStateException e) {
+ // Ignore as it either has already been connected or already been closed.
+ }
}
/**
@@ -50,7 +87,22 @@ public class DistributedSemaphore {
* @param capacity capacity of the semaphore
*/
public void createSemaphore(String path, int capacity) {
- throw new NotImplementedException("Not implemented yet.");
+ if (capacity <= 0) {
+ throw new MetaClientException("Capacity must be positive");
+ }
+ if (path == null || path.isEmpty()) {
+ throw new MetaClientException("Invalid path to create semaphore");
+ }
+ if (_metaClient.exists(path) != null) {
+ throw new MetaClientException("Semaphore already exists");
+ }
+ if (_metaClient.exists(path) == null) {
+ DataRecord dataRecord = new DataRecord(path);
+ dataRecord.setLongField(INITIAL_CAPACITY_NAME, capacity);
+ dataRecord.setLongField(REMAINING_CAPACITY_NAME, capacity);
+ _metaClient.create(path, dataRecord);
+ _path = path;
+ }
}
/**
@@ -58,7 +110,13 @@ public class DistributedSemaphore {
* @param path path of the semaphore
*/
public void connectSemaphore(String path) {
- throw new NotImplementedException("Not implemented yet.");
+ if (path == null || path.isEmpty()) {
+ throw new MetaClientException("Invalid path to connect semaphore");
+ }
+ if (_metaClient.exists(path) == null) {
+ throw new MetaClientException("Semaphore does not exist");
+ }
+ _path = path;
}
/**
@@ -66,7 +124,13 @@ public class DistributedSemaphore {
* @return a permit
*/
public Permit acquire() {
- throw new NotImplementedException("Not implemented yet.");
+ try {
+ updateAcquirePermit(1);
+ return retrievePermit(_path);
+ } catch (MetaClientException e) {
+ LOG.error("Failed to acquire permit.", e);
+ return null;
+ }
}
@@ -76,7 +140,17 @@ public class DistributedSemaphore {
* @return a collection of permits
*/
public Collection<Permit> acquire(int count) {
- throw new NotImplementedException("Not implemented yet.");
+ try {
+ updateAcquirePermit(count);
+ Collection<Permit> permits = new ArrayList<>();
+ for (int i = 0; i < count; i++) {
+ permits.add(retrievePermit(_path));
+ }
+ return permits;
+ } catch (MetaClientException e) {
+ LOG.error("Failed to acquire permits.", e);
+ return null;
+ }
}
/**
@@ -96,7 +170,7 @@ public class DistributedSemaphore {
* @return remaining capacity
*/
public long getRemainingCapacity() {
- throw new NotImplementedException("Not implemented yet.");
+ return getSemaphore().getLongField(REMAINING_CAPACITY_NAME, DEFAULT_REMAINING_CAPACITY);
}
/**
@@ -104,14 +178,22 @@ public class DistributedSemaphore {
* @return semaphore data record
*/
private DataRecord getSemaphore() {
- throw new NotImplementedException("Not implemented yet.");
+ if (_metaClient.exists(_path) == null) {
+ throw new MetaClientException("Semaphore does not exist at path: " + _path + ". Please create it first.");
+ }
+ return new DataRecord(_metaClient.get(_path));
}
/**
* Return a permit. If the permit is already returned, log and return void.
*/
public void returnPermit(Permit permit) {
- throw new NotImplementedException("Not implemented yet.");
+ if (permit.isReleased()) {
+ LOG.info("The permit has already been released");
+ } else {
+ updateReturnPermit();
+ permit.releasePermit();
+ }
}
/**
@@ -119,7 +201,9 @@ public class DistributedSemaphore {
* log and return void.
*/
public void returnAllPermits(Collection<Permit> permits) {
- throw new NotImplementedException("Not implemented yet.");
+ for (Permit permit : permits) {
+ returnPermit(permit);
+ }
}
/**
@@ -128,7 +212,8 @@ public class DistributedSemaphore {
* @return a permit
*/
private Permit retrievePermit(String path) {
- throw new NotImplementedException("Not implemented yet.");
+ MetaClientInterface.Stat stat = _metaClient.exists(path);
+ return new Permit(getSemaphore(), stat);
}
/**
@@ -136,13 +221,25 @@ public class DistributedSemaphore {
* @param count number of permits to acquire
*/
private void updateAcquirePermit(int count) {
- throw new NotImplementedException("Not implemented yet.");
+ _metaClient.update(_path, record -> {
+ long permitsAvailable = record.getLongField(REMAINING_CAPACITY_NAME, DEFAULT_REMAINING_CAPACITY);
+ if (permitsAvailable < count) {
+ throw new MetaClientException("No sufficient permits available. Attempt to acquire " + count + " permits, but only "
+ + permitsAvailable + " permits available");
+ }
+ record.setLongField(REMAINING_CAPACITY_NAME, permitsAvailable - count);
+ return record;
+ });
}
/**
* Update the remaining capacity of the semaphore after returning a permit.
*/
private void updateReturnPermit() {
- throw new NotImplementedException("Not implemented yet.");
+ _metaClient.update(_path, record -> {
+ long permitsAvailable = record.getLongField(REMAINING_CAPACITY_NAME, DEFAULT_REMAINING_CAPACITY);
+ record.setLongField(REMAINING_CAPACITY_NAME, permitsAvailable + 1);
+ return record;
+ });
}
}
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java
index cd5c3c297..8a9c489e3 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/LockClient.java
@@ -64,8 +64,12 @@ public class LockClient implements LockClientInterface, AutoCloseable {
throw new IllegalArgumentException("MetaClient cannot be null.");
}
_metaClient = client;
- LOG.info("Connecting to existing MetaClient for LockClient");
- _metaClient.connect();
+ try {
+ LOG.info("Connecting to existing MetaClient for LockClient");
+ _metaClient.connect();
+ } catch (IllegalStateException e) {
+ // Ignore as it either has already been connected or already been closed.
+ }
}
@Override
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphoreTest.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphoreTest.java
new file mode 100644
index 000000000..db874cd33
--- /dev/null
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/lock/DistributedSemaphoreTest.java
@@ -0,0 +1,105 @@
+package org.apache.helix.metaclient.recipes.lock;
+
+/*
+ * 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.
+ */
+
+import org.apache.helix.metaclient.factories.MetaClientConfig;
+import org.apache.helix.metaclient.impl.zk.ZkMetaClientTestBase;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import java.util.Collection;
+
+public class DistributedSemaphoreTest extends ZkMetaClientTestBase {
+
+ public DistributedSemaphore createSemaphoreClientAndSemaphore(String path, int capacity) {
+
+ MetaClientConfig.StoreType storeType = MetaClientConfig.StoreType.ZOOKEEPER;
+ MetaClientConfig config = new MetaClientConfig.MetaClientConfigBuilder<>().setConnectionAddress(ZK_ADDR)
+ .setStoreType(storeType).build();
+ DistributedSemaphore client = new DistributedSemaphore(config);
+ client.createSemaphore(path, capacity);
+ return client;
+ }
+
+ @Test
+ public void testAcquirePermit() {
+ final String key = "/TestSemaphore_testAcquirePermit";
+ int capacity = 5;
+ DistributedSemaphore semaphoreClient = createSemaphoreClientAndSemaphore(key, capacity);
+ Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity);
+
+ Permit permit = semaphoreClient.acquire();
+ Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity - 1);
+ }
+
+ @Test
+ public void testAcquireMultiplePermits() {
+ final String key = "/TestSemaphore_testAcquireMultiplePermits";
+ int capacity = 5;
+ int count = 4;
+ DistributedSemaphore semaphoreClient = createSemaphoreClientAndSemaphore(key, capacity);
+ Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity);
+
+ Collection<Permit> permits = semaphoreClient.acquire(count);
+ Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity - 4);
+ Assert.assertEquals(permits.size(), count);
+ Assert.assertNull(semaphoreClient.acquire(count));
+ }
+
+ @Test
+ public void testReturnPermit() {
+ final String key = "/TestSemaphore_testReturnPermit";
+ int capacity = 5;
+ DistributedSemaphore semaphoreClient = createSemaphoreClientAndSemaphore(key, capacity);
+ Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity);
+
+ Permit permit = semaphoreClient.acquire();
+ Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity - 1);
+
+ semaphoreClient.returnPermit(permit);
+ Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity);
+
+ // return the same permit again. Should not fail but capacity remains same.
+ semaphoreClient.returnPermit(permit);
+ Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity);
+ }
+
+ @Test
+ public void testReturnMultiplePermits() {
+ final String key = "/TestSemaphore_testReturnMultiplePermits";
+ int capacity = 5;
+ int count = 4;
+ DistributedSemaphore semaphoreClient = createSemaphoreClientAndSemaphore(key, capacity);
+ Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity);
+
+ Collection<Permit> permits = semaphoreClient.acquire(count);
+ Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity - 4);
+ Assert.assertEquals(permits.size(), count);
+
+ semaphoreClient.returnAllPermits(permits);
+ Assert.assertEquals(semaphoreClient.getRemainingCapacity(), capacity);
+ }
+
+ @Test
+ public void testTryAcquirePermit() {
+ // Not implemented
+ }
+
+}
[helix] 19/21: Lattice Puppy Stress Test Race Condition Fix and Code Cleanup (#2579)
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit c3afa7f2714c44e73fe8f0210a624f88b382a270
Author: Marcos Rico Peng <55...@users.noreply.github.com>
AuthorDate: Wed Aug 2 18:46:26 2023 +0200
Lattice Puppy Stress Test Race Condition Fix and Code Cleanup (#2579)
---------
Co-authored-by: mapeng <ma...@linkedin.com>
---
.../apache/helix/metaclient/MetaClientTestUtil.java | 2 +-
.../zk/TestMultiThreadStressTest/CreatePuppy.java | 3 +--
.../zk/TestMultiThreadStressTest/DeletePuppy.java | 2 +-
.../impl/zk/TestMultiThreadStressTest/GetPuppy.java | 1 -
.../impl/zk/TestMultiThreadStressTest/SetPuppy.java | 1 -
.../TestMultiThreadStressZKClient.java | 6 ++----
.../zk/TestMultiThreadStressTest/UpdatePuppy.java | 1 -
.../helix/metaclient/puppy/AbstractPuppy.java | 21 +++++++--------------
8 files changed, 12 insertions(+), 25 deletions(-)
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/MetaClientTestUtil.java b/meta-client/src/test/java/org/apache/helix/metaclient/MetaClientTestUtil.java
index 2c7543e31..f0a14c4a4 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/MetaClientTestUtil.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/MetaClientTestUtil.java
@@ -4,7 +4,7 @@ import java.util.concurrent.TimeUnit;
public class MetaClientTestUtil {
- public static final long WAIT_DURATION = TimeUnit.MINUTES.toMicros(1);
+ public static final long WAIT_DURATION = TimeUnit.MINUTES.toMillis(1);
public interface Verifier {
boolean verify()
throws Exception;
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/CreatePuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/CreatePuppy.java
index 3e28df06b..3940f79ab 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/CreatePuppy.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/CreatePuppy.java
@@ -64,8 +64,7 @@ public class CreatePuppy extends AbstractPuppy {
@Override
protected void cleanup() {
- // Implement the recovery logic by deleting the created documents
- _metaclient.recursiveDelete(_parentPath);
+ // Cleanup logic in test case
}
private boolean shouldIntroduceError() {
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/DeletePuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/DeletePuppy.java
index e0e1b7b5c..1aa9d4d72 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/DeletePuppy.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/DeletePuppy.java
@@ -58,7 +58,7 @@ public class DeletePuppy extends AbstractPuppy {
@Override
protected void cleanup() {
- _metaclient.recursiveDelete(_parentPath);
+ // Do nothing
}
private boolean shouldIntroduceError() {
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/GetPuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/GetPuppy.java
index fe24b2bd3..4af1c4df3 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/GetPuppy.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/GetPuppy.java
@@ -59,7 +59,6 @@ public class GetPuppy extends AbstractPuppy {
@Override
protected void cleanup() {
- _metaclient.recursiveDelete(_parentPath);
}
private boolean shouldIntroduceError() {
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/SetPuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/SetPuppy.java
index c0de4ece7..3385b8673 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/SetPuppy.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/SetPuppy.java
@@ -61,7 +61,6 @@ public class SetPuppy extends AbstractPuppy {
@Override
protected void cleanup() {
- _metaclient.recursiveDelete(_parentPath);
}
private boolean shouldIntroduceError() {
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/TestMultiThreadStressZKClient.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/TestMultiThreadStressZKClient.java
index 5ee026bc1..6a01fffa7 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/TestMultiThreadStressZKClient.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/TestMultiThreadStressZKClient.java
@@ -52,7 +52,7 @@ public class TestMultiThreadStressZKClient extends ZkMetaClientTestBase {
public void testCreatePuppy() {
_zkMetaClient.create(zkParentKey, "test");
- PuppySpec puppySpec = new org.apache.helix.metaclient.puppy.PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
+ PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
CreatePuppy createPuppy = new CreatePuppy(_zkMetaClient, puppySpec);
CreatePuppy createPuppy2 = new CreatePuppy(_zkMetaClient, puppySpec);
CreatePuppy createPuppy3 = new CreatePuppy(_zkMetaClient, puppySpec);
@@ -189,7 +189,7 @@ public class TestMultiThreadStressZKClient extends ZkMetaClientTestBase {
AtomicInteger globalChildChangeCounter = new AtomicInteger();
ChildChangeListener childChangeListener = (changedPath, changeType) -> {
globalChildChangeCounter.addAndGet(1);
- System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + " number of changes: " + globalChildChangeCounter.get());
+ System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + ". Number of total changes: " + globalChildChangeCounter.get());
};
_zkMetaClient.subscribeChildChanges(zkParentKey, childChangeListener, false);
@@ -219,8 +219,6 @@ public class TestMultiThreadStressZKClient extends ZkMetaClientTestBase {
globalChildChangeCounter.addAndGet(1);
System.out.println("-------------- Child change detected: " + changeType + " at path: " + changedPath + " number of changes: " + globalChildChangeCounter.get());
};
-
-
_zkMetaClient.subscribeChildChanges(zkParentKey, childChangeListener, false);
PuppySpec puppySpec = new PuppySpec(PuppyMode.REPEAT, 0.2f, new ExecDelay(5000, 0.1f), 5);
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/UpdatePuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/UpdatePuppy.java
index 721d507eb..5af055f74 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/UpdatePuppy.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/impl/zk/TestMultiThreadStressTest/UpdatePuppy.java
@@ -64,7 +64,6 @@ public class UpdatePuppy extends AbstractPuppy {
@Override
protected void cleanup() {
- _metaclient.recursiveDelete(_parentPath);
}
private boolean shouldIntroduceError() {
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
index bfbbb915d..9ce21fc15 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/puppy/AbstractPuppy.java
@@ -55,30 +55,23 @@ public abstract class AbstractPuppy implements Runnable {
@Override
public void run() {
try {
- while (true) {
+ while (!Thread.currentThread().isInterrupted()) {
try {
+ Thread.sleep(getPuppySpec().getExecDelay().getNextDelay());
bark();
+ } catch (InterruptedException e) {
+ break;
} catch (Exception e) {
incrementUnhandledErrorCounter();
e.printStackTrace();
}
-
- if (getPuppySpec().getMode() == PuppyMode.ONE_OFF) {
- cleanup();
- break;
- } else {
- try {
- Thread.sleep(getPuppySpec().getExecDelay().getNextDelay());
- } catch (InterruptedException e) {
- cleanup();
- break;
- // Handle interruption if necessary
- }
- }
}
} catch (Exception e) {
e.printStackTrace();
}
+ finally {
+ cleanup();
+ }
}
public PuppySpec getPuppySpec() {
[helix] 01/21: DataRecord Serializer
Posted by jx...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
jxue pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/helix.git
commit ff4c5cadd476726198daaee0e832de25a10539e2
Author: mapeng <ma...@linkedin.com>
AuthorDate: Fri Jun 2 13:53:21 2023 -0400
DataRecord Serializer
---
.../recipes/lock/DataRecordSerializer.java | 32 ++++++++++++++++++++++
1 file changed, 32 insertions(+)
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DataRecordSerializer.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DataRecordSerializer.java
new file mode 100644
index 000000000..6fee7bdea
--- /dev/null
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/lock/DataRecordSerializer.java
@@ -0,0 +1,32 @@
+package org.apache.helix.metaclient.recipes.lock;
+
+/*
+ * 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.
+ */
+
+import org.apache.helix.metaclient.datamodel.DataRecord;
+import org.apache.helix.zookeeper.datamodel.ZNRecord;
+import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer;
+
+public class DataRecordSerializer extends ZNRecordSerializer {
+ @Override
+ public Object deserialize(byte[] bytes) {
+ Object o = super.deserialize(bytes);
+ return new DataRecord((ZNRecord) o);
+ }
+}