You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@accumulo.apache.org by GitBox <gi...@apache.org> on 2021/01/12 18:19:09 UTC
[GitHub] [accumulo] dlmarion opened a new pull request #1866: Add a UUID to the server's ZooLock
dlmarion opened a new pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866
@DomGarguilo @EdColeman @ctubbsii - would this work?
re #637: Add a UUID into the lock name, use it to determine if the lock with the lowest sequence number is from this ZooLock.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564833033
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000006");
+ children.add("zlock#00000000-0000-0000-0000-GGGGGGGGGGGG#0000000008");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000004");
+ children.add("zlock#00000000-0000-0000-0000-CCCCCCCCCCCC#0000000003");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000002");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001");
+
+ ZooLock.sortChildrenByLockPrefix(children);
Review comment:
I can add a test for ones with an invalid format. I was thinking of the case where some nodes remained in ZK from a pre-2.1.0 Accumulo instance. I believe there are existing issues for orphaned Watchers, I don't know if there are also issues in ZK for orphaned ephemeral nodes. I figured it was safer to be forgiving here.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564827621
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +363,245 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
Review comment:
I can change it depending on the discussion regarding the UUID being static.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r556683483
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -259,7 +304,7 @@ public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
+ final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + THIS_ZLOCK, data);
Review comment:
In the case where the ephemeral node is created on the server and that is not successfully reported back, will a second ephemeral node be created (by the retry logic in putEphemeralSequential)? For example could we end up with two ephemeral nodes w/ the same UUID like:
```
zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000002
zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000003
```
If so, would the 2nd one created be returned to this code and would the 1st one continue to exists?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] EdColeman commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
EdColeman commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r565336875
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
Review comment:
The zookeeper Programmers guide specifies the length and format of the naming.
[ZooKeeper - Sequence Nodes - Unique Naming](https://zookeeper.apache.org/doc/r3.5.9/zookeeperProgrammers.html#Sequence+Nodes+--+Unique+Naming)
` The counter has a format of %010d -- that is 10 digits with 0 (zero) padding (the counter is formatted in this way to simplify sorting), i.e. "0000000001". `
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r561343995
##########
File path: test/src/main/resources/log4j2-test.properties
##########
@@ -143,6 +143,6 @@ logger.35.level = info
logger.36.name = org.apache.thrift.transport.TIOStreamTransport
logger.36.level = error
-rootLogger.level = debug
+rootLogger.level = trace
Review comment:
Yes, that's true. It's definitely helpful to see what's happening in the test. I will definitely remove before a merge.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-768350434
Do you have any further information?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-770261846
I'll look at that.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r556044263
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -139,26 +144,66 @@ public synchronized boolean tryLock(LockWatcher lw, byte[] data)
return false;
}
+ private static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() <= 43) {
Review comment:
Yes. FYI - I talked with Ed and he gave me some more insight into some of the issues involved. I'll be updating this PR based on his feedback.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564867298
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +365,262 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private static final Logger LOG = LoggerFactory.getLogger(LockWorker.class);
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+ private Exception ex = null;
+
+ public LockWorker(final String parent, final String name, final CountDownLatch lockLatch,
+ final CountDownLatch lockCompletedLatch) {
+ this.parent = parent;
+ this.name = name;
+ this.getLockLatch = lockLatch;
+ this.lockCompletedLatch = lockCompletedLatch;
+ }
+
+ public void unlock() {
+ unlockLatch.countDown();
+ }
+
+ public boolean holdsLock() {
+ return lockWatcher.isLockHeld();
+ }
+
+ @Override
+ public void run() {
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try {
+ try (ZooKeeperWrapper zk =
+ new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ ZooReaderWriter zrw = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk;
+ }
+ };
+ ZooLock zl = new ZooLock(zrw, parent);
+ zl.setVMLockPrefix(new Prefix(name));
+ getLockLatch.countDown(); // signal we are done
+ getLockLatch.await(); // wait for others to finish
+ zl.lock(lockWatcher, "test1".getBytes(UTF_8)); // race to the lock
+ lockCompletedLatch.countDown();
+ unlockLatch.await();
+ zl.unlock();
+ }
+ } catch (IOException | InterruptedException | KeeperException e) {
Review comment:
will change to `Exception`
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +365,262 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private static final Logger LOG = LoggerFactory.getLogger(LockWorker.class);
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+ private Exception ex = null;
+
+ public LockWorker(final String parent, final String name, final CountDownLatch lockLatch,
+ final CountDownLatch lockCompletedLatch) {
+ this.parent = parent;
+ this.name = name;
+ this.getLockLatch = lockLatch;
+ this.lockCompletedLatch = lockCompletedLatch;
+ }
+
+ public void unlock() {
+ unlockLatch.countDown();
+ }
+
+ public boolean holdsLock() {
+ return lockWatcher.isLockHeld();
+ }
+
+ @Override
+ public void run() {
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try {
Review comment:
added to test
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r565721356
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +145,358 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}", vmLockPrefix,
+ pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ * @return list of ephemeral nodes that have valid formats, sorted by sequence number
+ */
+ public static List<String> validateAndSortChildrenByLockPrefix(List<String> children) {
+ List<String> validChildren = new ArrayList<>();
+ children.forEach(c -> {
+ LOG.trace("Validating {}", c);
+ if (c.startsWith(ZLOCK_PREFIX)) {
+ String candidate = c.substring(ZLOCK_PREFIX.length() + 1);
+ if (candidate.contains("#")) {
+ int idx = candidate.indexOf('#');
+ String uuid = candidate.substring(0, idx - 1);
+ String sequenceNum = candidate.substring(idx + 1);
+ try {
+ LOG.trace("Testing uuid format of {}", uuid);
+ UUID.fromString(uuid);
+ if (sequenceNum.length() == 10) {
+ try {
+ LOG.trace("Testing number format of {}", sequenceNum);
+ Integer.parseInt(sequenceNum);
+ validChildren.add(c);
+ } catch (NumberFormatException e) {
+ LOG.warn("Child found with invalid sequence format: {} (no a number)", c);
Review comment:
```suggestion
LOG.warn("Child found with invalid sequence format: {} (not a number)", c);
```
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +145,358 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}", vmLockPrefix,
+ pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ * @return list of ephemeral nodes that have valid formats, sorted by sequence number
+ */
+ public static List<String> validateAndSortChildrenByLockPrefix(List<String> children) {
+ List<String> validChildren = new ArrayList<>();
+ children.forEach(c -> {
+ LOG.trace("Validating {}", c);
+ if (c.startsWith(ZLOCK_PREFIX)) {
+ String candidate = c.substring(ZLOCK_PREFIX.length() + 1);
+ if (candidate.contains("#")) {
+ int idx = candidate.indexOf('#');
+ String uuid = candidate.substring(0, idx - 1);
+ String sequenceNum = candidate.substring(idx + 1);
+ try {
+ LOG.trace("Testing uuid format of {}", uuid);
+ UUID.fromString(uuid);
+ if (sequenceNum.length() == 10) {
+ try {
+ LOG.trace("Testing number format of {}", sequenceNum);
+ Integer.parseInt(sequenceNum);
+ validChildren.add(c);
+ } catch (NumberFormatException e) {
+ LOG.warn("Child found with invalid sequence format: {} (no a number)", c);
+ }
+ } else {
+ LOG.warn("Child found with invalid sequence format: {} (not 10 characters)", c);
+ }
+ } catch (IllegalArgumentException e) {
+ LOG.warn("Child found with invalid UUID format: {}", c);
+ }
+ } else {
+ LOG.warn("Child found with invalid format: {} (does not contain second '#')", c);
+ }
+ } else {
+ LOG.warn("Child found with invalid format: {} (does not start with {})", c, ZLOCK_PREFIX);
+ }
+ });
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ validChildren.sort(new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+ int secondHashIdx = 43;
+ return Integer.valueOf(o1.substring(secondHashIdx))
+ .compareTo(Integer.valueOf(o2.substring(secondHashIdx)));
+ }
+ });
Review comment:
Could be shorter w/ a lambda. Not sure if it compiles. Could move the comment to the beginning of the method.
```suggestion
validChildren.sort((o1,o2) -> {
int secondHashIdx = 43;
return Integer.valueOf(o1.substring(secondHashIdx))
.compareTo(Integer.valueOf(o2.substring(secondHashIdx)));
});
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] EdColeman commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
EdColeman commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r556758403
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -259,7 +304,7 @@ public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
+ final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + THIS_ZLOCK, data);
Review comment:
Dave is going to rework parts of this and I think that it might address some of these concerns.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] EdColeman commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
EdColeman commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564522647
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -38,9 +40,13 @@
import org.slf4j.LoggerFactory;
public class ZooLock implements Watcher {
- private static final Logger log = LoggerFactory.getLogger(ZooLock.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ZooLock.class);
Review comment:
Why the capitalization of LOG? I don't care - but would like to be consistent in the code base.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] ctubbsii commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
ctubbsii commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-771057716
> @ctubbsii - I pushed a fix for VolumeIT. Are you seeing any other test failures?
That was the only one I saw. I haven't re-run all of them with your latest. I don't have any objections to this change being merged in, but there are a few unresolved comment threads above that you might want to mark as resolved, or address, before merging.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] EdColeman commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
EdColeman commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r565359341
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
Review comment:
I did take a quick look to see if there was a public definition of the length in the ZooKeeper code - but I didn't see anything - even with that, the length should be stable - alternatively we could just check that it only contains chars [0-9]. Thinking about the check - rather than length - Parsing the uuid with UUID.from(string) would be a stronger check.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] ctubbsii commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
ctubbsii commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-763997733
> I will see if I can back out the variable name changes.
If it's too much trouble, don't worry about it. I was just thinking it might make code review easier. I can always rename them back in my IDE if I want to minimize the diff for my own review satisfaction.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767194001
Are you able to start 2 masters?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564852403
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +151,344 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}", vmLockPrefix,
+ pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ children.sort(new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ children.forEach(c -> LOG.debug("- {}", c));
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", vmLockPrefix);
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
- }
-
- prev = child;
- }
+ } else {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}", vmLockPrefix,
+ children.get(0));
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ LOG.debug("[{}] Establishing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", vmLockPrefix);
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ vmLockPrefix, nodeToWatch);
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted", vmLockPrefix,
+ nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ LOG.debug("[{}] Renewing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
- } catch (KeeperException | InterruptedException e) {
- lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
}
- }
- });
+ };
+
+ Stat stat = zooKeeper.getStatus(nodeToWatch, priorNodeWatcher);
+ if (stat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, priorNodeWatcher, WatcherType.Any,
+ true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ }
- if (stat == null)
- lockAsync(myLock, lw);
}
private void lostLock(LockLossReason reason) {
LockWatcher localLw = lockWatcher;
- lock = null;
+ lockNodeName = null;
lockWatcher = null;
localLw.lostLock(reason);
}
- public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
+ public synchronized void lock(final AccumuloLockWatcher lw, byte[] data) {
- if (lockWatcher != null || lock != null || asyncLock != null) {
+ if (lockWatcher != null || lockNodeName != null || createdNodeName != null) {
throw new IllegalStateException();
}
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
- log.trace("Ephemeral node {} created", asyncLockPath);
- Stat stat = zooKeeper.getStatus(asyncLockPath, new Watcher() {
+ final String lockPathPrefix = path + "/" + vmLockPrefix.toString();
+ // Implement recipe at https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks
+ // except that instead of the ephemeral lock node being of the form guid-lock- use lock-guid-.
+ // Another deviation from the recipe is that we cleanup any extraneous ephemeral nodes that
+ // were created.
+ final String createPath = zooKeeper.putEphemeralSequential(lockPathPrefix, data);
+ LOG.debug("[{}] Ephemeral node {} created", vmLockPrefix, createPath);
+
+ // It's possible that the call above was retried several times and multiple ephemeral nodes
+ // were created but the client missed the response for some reason. Find the ephemeral nodes
+ // with this ZLOCK_UUID and lowest sequential number.
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
+ }
+ });
+ String lowestSequentialPath = null;
+ sortChildrenByLockPrefix(children);
+ boolean msgLoggedOnce = false;
+ for (String child : children) {
+ if (child.startsWith(vmLockPrefix.toString())) {
+ if (null == lowestSequentialPath) {
+ if (createPath.equals(path + "/" + child)) {
+ // the path returned from create is the lowest sequential one
+ lowestSequentialPath = createPath;
+ break;
+ }
+ lowestSequentialPath = path + "/" + child;
+ LOG.debug("[{}] lowest sequential node found: {}", vmLockPrefix, lowestSequentialPath);
+ } else {
+ if (!msgLoggedOnce) {
+ LOG.info(
+ "[{}] Zookeeper client missed server response, multiple ephemeral child nodes created at {}",
+ vmLockPrefix, lockPathPrefix);
+ msgLoggedOnce = true;
+ }
+ LOG.debug("[{}] higher sequential node found: {}, deleting it", vmLockPrefix, child);
+ zooKeeper.delete(path + "/" + child);
+ }
+ }
+ }
+ final String pathForWatcher = lowestSequentialPath;
+
+ // Set a watcher on the lowest sequential node that we created, this handles the case
+ // where the node we created is deleted or if this client becomes disconnected.
+ LOG.debug("[{}] Setting watcher on {}", vmLockPrefix, pathForWatcher);
+ Watcher watcherForNodeWeCreated = new Watcher() {
private void failedToAcquireLock() {
+ LOG.debug("[{}] Lock deleted before acquired, setting createdNodeName {} to null",
+ vmLockPrefix, createdNodeName);
lw.failedToAcquireLock(new Exception("Lock deleted before acquired"));
- asyncLock = null;
+ createdNodeName = null;
}
@Override
public void process(WatchedEvent event) {
synchronized (ZooLock.this) {
- if (lock != null && event.getType() == EventType.NodeDeleted
- && event.getPath().equals(path + "/" + lock)) {
+ if (lockNodeName != null && event.getType() == EventType.NodeDeleted
+ && event.getPath().equals(path + "/" + lockNodeName)) {
+ LOG.debug("[{}] {} was deleted", vmLockPrefix, lockNodeName);
lostLock(LockLossReason.LOCK_DELETED);
- } else if (asyncLock != null && event.getType() == EventType.NodeDeleted
- && event.getPath().equals(path + "/" + asyncLock)) {
+ } else if (createdNodeName != null && event.getType() == EventType.NodeDeleted
+ && event.getPath().equals(path + "/" + createdNodeName)) {
+ LOG.debug("[{}] {} was deleted", vmLockPrefix, createdNodeName);
failedToAcquireLock();
} else if (event.getState() != KeeperState.Disconnected
- && event.getState() != KeeperState.Expired && (lock != null || asyncLock != null)) {
- log.debug("Unexpected event watching lock node {} {}", event, asyncLockPath);
+ && event.getState() != KeeperState.Expired
+ && (lockNodeName != null || createdNodeName != null)) {
+ LOG.debug("Unexpected event watching lock node {} {}", event, pathForWatcher);
try {
- Stat stat2 = zooKeeper.getStatus(asyncLockPath, this);
+ Stat stat2 = zooKeeper.getStatus(pathForWatcher, this);
if (stat2 == null) {
- if (lock != null)
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(pathForWatcher, this, WatcherType.Any,
Review comment:
I think I caught all of the cases where a `Stat` is returned and it's `null`.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-762933158
@keith-turner @DomGarguilo @EdColeman - with this latest commit I attempted to implement the recipe at https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks. If we have two processes (A and B) we might end up with the following ephemeral sequential nodes:
```
zlock#44755fbe-1c9e-40b3-AAAA-03abaf950d7e#0000000001 (created by server but missed by client, A has the lock)
zlock#44755fbe-1c9e-40b3-AAAA-03abaf950d7e#0000000002 (created by server and returned to the client)
zlock#44755fbe-1c9e-40b3-BBBB-03abaf950d7e#0000000003 (created by server but missed by client)
zlock#44755fbe-1c9e-40b3-BBBB-03abaf950d7e#0000000004 (created by server and returned to the client, B is watching 2)
```
I'm going to see what I can do to test this.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-763051560
@EdColeman @keith-turner - I added a test in [525e3ed](https://github.com/apache/accumulo/pull/1866/commits/525e3eda79514ff728b9d168fcc146e6d8599980) and I am running into something unexpected. If you look at the test output you will see that 4 nodes are created in ZK, but the call to [zk.getChildren](https://github.com/apache/accumulo/pull/1866/commits/525e3eda79514ff728b9d168fcc146e6d8599980#diff-3eaaf5fe7d173dc365a6164af9d3c0bbbfb6e5a66115bb942ae01960e8396caeR393) only returns 3 nodes. This is the reason for one of the checks being commented out currently. Working on trying to understand why this might occur. Any insight would be helpful.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-764200297
> I will see if I can back out the variable name changes.
The name changes do add a bit of work to the review for some diffs, but it's ok w/ me to leave them as is. I like the changes and have become familiar with them.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner edited a comment on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner edited a comment on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767199022
> It cleaned up the extra ephemeral nodes that were created by the "missed" server responses, then it put a watcher on the lowest sequence number of the prior ephemeral node.
Yeah that seems to be working really well. I need to try to delete the ephemeral nodes I created (while the tserver is starting up). I was curious about the repeated creation of ephemeral nodes and then the tserver dying. That is probably caused by code outside zooklock in the tserver, was wondering if you had looked at that and if that was working in a way you would expect.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r565439569
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
Review comment:
I have a fix in progress, running tests now. Should be uploaded shortly.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-763987527
I will see if I can back out the variable name changes.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564845275
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +151,344 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}", vmLockPrefix,
+ pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ children.sort(new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ children.forEach(c -> LOG.debug("- {}", c));
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", vmLockPrefix);
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
- }
-
- prev = child;
- }
+ } else {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}", vmLockPrefix,
+ children.get(0));
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ LOG.debug("[{}] Establishing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", vmLockPrefix);
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ vmLockPrefix, nodeToWatch);
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted", vmLockPrefix,
+ nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ LOG.debug("[{}] Renewing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
- } catch (KeeperException | InterruptedException e) {
- lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
}
- }
- });
+ };
+
+ Stat stat = zooKeeper.getStatus(nodeToWatch, priorNodeWatcher);
+ if (stat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, priorNodeWatcher, WatcherType.Any,
+ true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ }
- if (stat == null)
- lockAsync(myLock, lw);
}
private void lostLock(LockLossReason reason) {
LockWatcher localLw = lockWatcher;
- lock = null;
+ lockNodeName = null;
lockWatcher = null;
localLw.lostLock(reason);
}
- public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
+ public synchronized void lock(final AccumuloLockWatcher lw, byte[] data) {
- if (lockWatcher != null || lock != null || asyncLock != null) {
+ if (lockWatcher != null || lockNodeName != null || createdNodeName != null) {
throw new IllegalStateException();
}
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
- log.trace("Ephemeral node {} created", asyncLockPath);
- Stat stat = zooKeeper.getStatus(asyncLockPath, new Watcher() {
+ final String lockPathPrefix = path + "/" + vmLockPrefix.toString();
+ // Implement recipe at https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks
+ // except that instead of the ephemeral lock node being of the form guid-lock- use lock-guid-.
+ // Another deviation from the recipe is that we cleanup any extraneous ephemeral nodes that
+ // were created.
+ final String createPath = zooKeeper.putEphemeralSequential(lockPathPrefix, data);
+ LOG.debug("[{}] Ephemeral node {} created", vmLockPrefix, createPath);
+
+ // It's possible that the call above was retried several times and multiple ephemeral nodes
+ // were created but the client missed the response for some reason. Find the ephemeral nodes
+ // with this ZLOCK_UUID and lowest sequential number.
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
+ }
+ });
Review comment:
moved to a function and logged invalid format.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767228304
@dlmarion I am almost finished reviewing this. I have not looked at the test yet (my least favorite thing to review, but I think one of the more important things to review) and I want to go over the changes in zoolock once more. Hope to finish up reviewing it in the morning.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564841213
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +363,245 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+
+ public LockWorker(final String parent, final String name, final CountDownLatch lockLatch,
+ final CountDownLatch lockCompletedLatch) {
+ this.parent = parent;
+ this.name = name;
+ this.getLockLatch = lockLatch;
+ this.lockCompletedLatch = lockCompletedLatch;
+ }
+
+ public void unlock() {
+ unlockLatch.countDown();
+ }
+
+ public boolean holdsLock() {
+ return lockWatcher.isLockHeld();
+ }
+
+ @Override
+ public void run() {
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try {
+ try (ZooKeeperWrapper zk =
+ new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ ZooReaderWriter zrw = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk;
+ }
+ };
+ ZooLock zl = new ZooLock(zrw, parent);
+ zl.setVMLockPrefix(new Prefix(name));
+ getLockLatch.countDown(); // signal we are done
+ getLockLatch.await(); // wait for others to finish
+ zl.lock(lockWatcher, "test1".getBytes(UTF_8)); // race to the lock
+ lockCompletedLatch.countDown();
+ unlockLatch.await();
+ zl.unlock();
+ }
+ } catch (IOException | InterruptedException | KeeperException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "LockWorker [name=" + name + ", holdsLock()=" + holdsLock() + "]";
+ }
+
+ }
+
+ private int parseLockWorkerName(String child) {
+ if (child.startsWith("zlock#00000000-0000-0000-0000-000000000000#")) {
+ return 0;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-111111111111#")) {
+ return 1;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-222222222222#")) {
+ return 2;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-333333333333#")) {
+ return 3;
+ } else {
+ return -1;
+ }
+ }
+
+ @Test(timeout = 60000)
+ public void testLockParallel() throws Exception {
+ String parent = "/zlParallel";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ // Create the parent node
+ zk.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ int numWorkers = 4;
+ final CountDownLatch getLockLatch = new CountDownLatch(numWorkers);
+ final CountDownLatch lockFinishedLatch = new CountDownLatch(numWorkers);
+ final List<LockWorker> workers = new ArrayList<>(numWorkers);
+ final List<Thread> threads = new ArrayList<>(numWorkers);
+ for (int i = 0; i < numWorkers; i++) {
+ String name =
+ "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#".replaceAll("A", Integer.toString(i));
+ LockWorker w = new LockWorker(parent, name, getLockLatch, lockFinishedLatch);
+ Thread t = new Thread(w);
+ workers.add(w);
+ threads.add(t);
+ t.start();
Review comment:
I implemented a check, but not using Futures.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564843224
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +363,245 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+
+ public LockWorker(final String parent, final String name, final CountDownLatch lockLatch,
+ final CountDownLatch lockCompletedLatch) {
+ this.parent = parent;
+ this.name = name;
+ this.getLockLatch = lockLatch;
+ this.lockCompletedLatch = lockCompletedLatch;
+ }
+
+ public void unlock() {
+ unlockLatch.countDown();
+ }
+
+ public boolean holdsLock() {
+ return lockWatcher.isLockHeld();
+ }
+
+ @Override
+ public void run() {
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try {
+ try (ZooKeeperWrapper zk =
+ new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ ZooReaderWriter zrw = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk;
+ }
+ };
+ ZooLock zl = new ZooLock(zrw, parent);
+ zl.setVMLockPrefix(new Prefix(name));
+ getLockLatch.countDown(); // signal we are done
+ getLockLatch.await(); // wait for others to finish
+ zl.lock(lockWatcher, "test1".getBytes(UTF_8)); // race to the lock
+ lockCompletedLatch.countDown();
+ unlockLatch.await();
+ zl.unlock();
+ }
+ } catch (IOException | InterruptedException | KeeperException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "LockWorker [name=" + name + ", holdsLock()=" + holdsLock() + "]";
+ }
+
+ }
+
+ private int parseLockWorkerName(String child) {
+ if (child.startsWith("zlock#00000000-0000-0000-0000-000000000000#")) {
+ return 0;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-111111111111#")) {
+ return 1;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-222222222222#")) {
+ return 2;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-333333333333#")) {
+ return 3;
+ } else {
+ return -1;
+ }
+ }
+
+ @Test(timeout = 60000)
+ public void testLockParallel() throws Exception {
+ String parent = "/zlParallel";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ // Create the parent node
+ zk.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ int numWorkers = 4;
+ final CountDownLatch getLockLatch = new CountDownLatch(numWorkers);
+ final CountDownLatch lockFinishedLatch = new CountDownLatch(numWorkers);
+ final List<LockWorker> workers = new ArrayList<>(numWorkers);
+ final List<Thread> threads = new ArrayList<>(numWorkers);
+ for (int i = 0; i < numWorkers; i++) {
+ String name =
+ "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#".replaceAll("A", Integer.toString(i));
+ LockWorker w = new LockWorker(parent, name, getLockLatch, lockFinishedLatch);
+ Thread t = new Thread(w);
+ workers.add(w);
+ threads.add(t);
+ t.start();
+ }
+
+ getLockLatch.await(); // Threads compete for lock
+ lockFinishedLatch.await(); // Threads lock logic complete
+
+ for (int i = 4; i > 0; i--) {
+ List<String> children = zk.getChildren(parent, false);
+ ZooLock.sortChildrenByLockPrefix(children);
+ assertEquals(i, children.size());
Review comment:
so, I still need a sleep after the `worker.unlock()` to allow time for the watches to fire.
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +363,245 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+
+ public LockWorker(final String parent, final String name, final CountDownLatch lockLatch,
+ final CountDownLatch lockCompletedLatch) {
+ this.parent = parent;
+ this.name = name;
+ this.getLockLatch = lockLatch;
+ this.lockCompletedLatch = lockCompletedLatch;
+ }
+
+ public void unlock() {
+ unlockLatch.countDown();
+ }
+
+ public boolean holdsLock() {
+ return lockWatcher.isLockHeld();
+ }
+
+ @Override
+ public void run() {
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try {
+ try (ZooKeeperWrapper zk =
+ new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ ZooReaderWriter zrw = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk;
+ }
+ };
+ ZooLock zl = new ZooLock(zrw, parent);
+ zl.setVMLockPrefix(new Prefix(name));
+ getLockLatch.countDown(); // signal we are done
+ getLockLatch.await(); // wait for others to finish
+ zl.lock(lockWatcher, "test1".getBytes(UTF_8)); // race to the lock
+ lockCompletedLatch.countDown();
+ unlockLatch.await();
+ zl.unlock();
+ }
+ } catch (IOException | InterruptedException | KeeperException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "LockWorker [name=" + name + ", holdsLock()=" + holdsLock() + "]";
+ }
+
+ }
+
+ private int parseLockWorkerName(String child) {
+ if (child.startsWith("zlock#00000000-0000-0000-0000-000000000000#")) {
+ return 0;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-111111111111#")) {
+ return 1;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-222222222222#")) {
+ return 2;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-333333333333#")) {
+ return 3;
+ } else {
+ return -1;
+ }
+ }
+
+ @Test(timeout = 60000)
+ public void testLockParallel() throws Exception {
+ String parent = "/zlParallel";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ // Create the parent node
+ zk.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ int numWorkers = 4;
+ final CountDownLatch getLockLatch = new CountDownLatch(numWorkers);
+ final CountDownLatch lockFinishedLatch = new CountDownLatch(numWorkers);
+ final List<LockWorker> workers = new ArrayList<>(numWorkers);
+ final List<Thread> threads = new ArrayList<>(numWorkers);
+ for (int i = 0; i < numWorkers; i++) {
+ String name =
+ "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#".replaceAll("A", Integer.toString(i));
+ LockWorker w = new LockWorker(parent, name, getLockLatch, lockFinishedLatch);
+ Thread t = new Thread(w);
+ workers.add(w);
+ threads.add(t);
+ t.start();
+ }
+
+ getLockLatch.await(); // Threads compete for lock
+ lockFinishedLatch.await(); // Threads lock logic complete
+
+ for (int i = 4; i > 0; i--) {
+ List<String> children = zk.getChildren(parent, false);
+ ZooLock.sortChildrenByLockPrefix(children);
+ assertEquals(i, children.size());
+ String first = children.get(0);
+ int workerWithLock = parseLockWorkerName(first);
+ LockWorker worker = workers.get(workerWithLock);
+ assertTrue(worker.holdsLock());
+ workers.forEach(w -> {
+ if (w != worker) {
+ assertFalse(w.holdsLock());
+ }
+ });
+ worker.unlock();
+ Thread.sleep(500); // wait for node to be deleted and lock to be reacquired.
+ }
+
+ workers.forEach(w -> assertFalse(w.holdsLock()));
+
Review comment:
added to test
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564871331
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -38,9 +40,13 @@
import org.slf4j.LoggerFactory;
public class ZooLock implements Watcher {
- private static final Logger log = LoggerFactory.getLogger(ZooLock.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ZooLock.class);
Review comment:
We have things that check for code format in our build. The way I see it, if it passes all the checks then you're good. I'd rather have some flexibility in variable naming than have to remember all the rules. I'm sure that we can be trusted to have good judgement.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564852017
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +151,344 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}", vmLockPrefix,
+ pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ children.sort(new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ children.forEach(c -> LOG.debug("- {}", c));
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", vmLockPrefix);
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
- }
-
- prev = child;
- }
+ } else {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}", vmLockPrefix,
+ children.get(0));
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ LOG.debug("[{}] Establishing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", vmLockPrefix);
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ vmLockPrefix, nodeToWatch);
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted", vmLockPrefix,
+ nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ LOG.debug("[{}] Renewing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
- } catch (KeeperException | InterruptedException e) {
- lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
}
- }
- });
+ };
+
+ Stat stat = zooKeeper.getStatus(nodeToWatch, priorNodeWatcher);
+ if (stat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, priorNodeWatcher, WatcherType.Any,
+ true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ }
- if (stat == null)
- lockAsync(myLock, lw);
}
private void lostLock(LockLossReason reason) {
LockWatcher localLw = lockWatcher;
- lock = null;
+ lockNodeName = null;
lockWatcher = null;
localLw.lostLock(reason);
}
- public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
+ public synchronized void lock(final AccumuloLockWatcher lw, byte[] data) {
- if (lockWatcher != null || lock != null || asyncLock != null) {
+ if (lockWatcher != null || lockNodeName != null || createdNodeName != null) {
throw new IllegalStateException();
}
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
- log.trace("Ephemeral node {} created", asyncLockPath);
- Stat stat = zooKeeper.getStatus(asyncLockPath, new Watcher() {
+ final String lockPathPrefix = path + "/" + vmLockPrefix.toString();
+ // Implement recipe at https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks
+ // except that instead of the ephemeral lock node being of the form guid-lock- use lock-guid-.
+ // Another deviation from the recipe is that we cleanup any extraneous ephemeral nodes that
+ // were created.
+ final String createPath = zooKeeper.putEphemeralSequential(lockPathPrefix, data);
+ LOG.debug("[{}] Ephemeral node {} created", vmLockPrefix, createPath);
+
+ // It's possible that the call above was retried several times and multiple ephemeral nodes
+ // were created but the client missed the response for some reason. Find the ephemeral nodes
+ // with this ZLOCK_UUID and lowest sequential number.
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
+ }
+ });
Review comment:
Regarding the stronger check, I could do that and remove the code for handling invalid formats. I think it depends on how rigid we want the code to be. TBH, I'm not sure whether or not ephemeral nodes might be created at the same location by a different process at the same path.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767188215
@dlmarion I ran an experiment w/ this code locally. First I made the following change on my local copy, to always force the creation of multiple ephemeral nodes.
```diff
diff --git a/core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java b/core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
index f79ca72c50..1f87ee3c3a 100644
--- a/core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
+++ b/core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
@@ -370,6 +370,11 @@ public class ZooLock implements Watcher {
// except that instead of the ephemeral lock node being of the form guid-lock- use lock-guid-.
// Another deviation from the recipe is that we cleanup any extraneous ephermal nodes that
// were created.
+
+ for(int i = 0; i < 3; i++) {
+ zooKeeper.putEphemeralSequential(lockPathPrefix, data);
+ }
+
final String createPath = zooKeeper.putEphemeralSequential(lockPathPrefix, data);
LOG.trace("[{}] Ephemeral node {} created", this.getZLockPrefix(), createPath);
```
The I started up Accumulo using these changes, enabled trace logging for ZooLock, and restarted the tserver. After that I saw the following in the tserver logs.
```
2021-01-25T18:32:35,744 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Ephemeral node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000007 created
2021-01-25T18:32:35,754 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T18:32:35,754 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T18:32:35,754 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000005
2021-01-25T18:32:35,754 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000006
2021-01-25T18:32:35,754 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000007
2021-01-25T18:32:35,755 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] lowest sequential node found: /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T18:32:35,755 [zookeeper.ZooLock] INFO : [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#
2021-01-25T18:32:35,755 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] higher sequential node found: zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000005, deleting it
2021-01-25T18:32:35,758 [zookeeper.ZooLock] INFO : [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#
2021-01-25T18:32:35,758 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] higher sequential node found: zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000006, deleting it
2021-01-25T18:32:35,760 [zookeeper.ZooLock] INFO : [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#
2021-01-25T18:32:35,760 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] higher sequential node found: zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000007, deleting it
2021-01-25T18:32:35,761 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Setting watcher on /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T18:32:35,764 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T18:32:35,764 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T18:32:35,764 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] First candidate is my lock, acquiring
2021-01-25T18:32:35,764 [tserver.TabletServer] DEBUG: Obtained tablet server lock /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T18:32:35,768 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T18:32:35,768 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
```
Then I did the following in the zkCli.
```
[zk: localhost:2181(CONNECTED) 0] addauth digest accumulo:uno
[zk: localhost:2181(CONNECTED) 1] ls /accumulo/
3cad24a9-53a9-4a6a-a846-ba24c5d747b9 instances
[zk: localhost:2181(CONNECTED) 1] ls /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997
[zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004]
[zk: localhost:2181(CONNECTED) 2] delete /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
```
After that I saw the following in the tserver logs and confirmed the tserver was not running.
```
2021-01-25T18:37:43,487 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004 was deleted
2021-01-25T18:37:43,489 [tserver.TabletServer] ERROR: Lost tablet server lock (reason = LOCK_DELETED), exiting.
```
Everything worked great. After running this experiment I am thinking the log messages related to creating the lock that are trace could be debug. Locks are not created often, locks are really important, and the information could be useful for debugging. Also I noticed the following log message was emitted multiple times.
```
INFO : [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564858110
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +151,344 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}", vmLockPrefix,
+ pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ children.sort(new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ children.forEach(c -> LOG.debug("- {}", c));
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", vmLockPrefix);
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
- }
-
- prev = child;
- }
+ } else {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}", vmLockPrefix,
+ children.get(0));
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ LOG.debug("[{}] Establishing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", vmLockPrefix);
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ vmLockPrefix, nodeToWatch);
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted", vmLockPrefix,
+ nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ LOG.debug("[{}] Renewing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
- } catch (KeeperException | InterruptedException e) {
- lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
}
- }
- });
+ };
+
+ Stat stat = zooKeeper.getStatus(nodeToWatch, priorNodeWatcher);
+ if (stat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, priorNodeWatcher, WatcherType.Any,
+ true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ }
- if (stat == null)
- lockAsync(myLock, lw);
}
private void lostLock(LockLossReason reason) {
LockWatcher localLw = lockWatcher;
- lock = null;
+ lockNodeName = null;
lockWatcher = null;
localLw.lostLock(reason);
}
- public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
+ public synchronized void lock(final AccumuloLockWatcher lw, byte[] data) {
- if (lockWatcher != null || lock != null || asyncLock != null) {
+ if (lockWatcher != null || lockNodeName != null || createdNodeName != null) {
throw new IllegalStateException();
}
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
- log.trace("Ephemeral node {} created", asyncLockPath);
- Stat stat = zooKeeper.getStatus(asyncLockPath, new Watcher() {
+ final String lockPathPrefix = path + "/" + vmLockPrefix.toString();
+ // Implement recipe at https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks
+ // except that instead of the ephemeral lock node being of the form guid-lock- use lock-guid-.
+ // Another deviation from the recipe is that we cleanup any extraneous ephemeral nodes that
+ // were created.
+ final String createPath = zooKeeper.putEphemeralSequential(lockPathPrefix, data);
+ LOG.debug("[{}] Ephemeral node {} created", vmLockPrefix, createPath);
+
+ // It's possible that the call above was retried several times and multiple ephemeral nodes
+ // were created but the client missed the response for some reason. Find the ephemeral nodes
+ // with this ZLOCK_UUID and lowest sequential number.
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
+ }
+ });
Review comment:
Seems like ignoring/filtering out the unexpected nodes and logging a warning would be good.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] EdColeman commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
EdColeman commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r555989511
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -139,26 +144,66 @@ public synchronized boolean tryLock(LockWatcher lw, byte[] data)
return false;
}
+ private static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() <= 43) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() <= 43) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = o1.lastIndexOf('#');
+ int rightIdx = o2.lastIndexOf('#');
+ return Integer.compare(Integer.parseInt(o1.substring(leftIdx)),
+ Integer.parseInt(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
Review comment:
This should be able to be a string compare - zookeeper pads the sequence number with 0's (from zookeerer docs:
`The counter has a format of %010d -- that is 10 digits with 0 (zero) padding`
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] ctubbsii commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
ctubbsii commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r561341204
##########
File path: test/src/main/resources/log4j2-test.properties
##########
@@ -143,6 +143,6 @@ logger.35.level = info
logger.36.name = org.apache.thrift.transport.TIOStreamTransport
logger.36.level = error
-rootLogger.level = debug
+rootLogger.level = trace
Review comment:
I'm thinking we probably don't want to leave this change in, as that could easily fill up disk during a build on a resource constrained system, or create a lot of unnecessary IO wear on a developer's SSD. Debug level is probably fine for the ITs.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564836014
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000006");
+ children.add("zlock#00000000-0000-0000-0000-GGGGGGGGGGGG#0000000008");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000004");
+ children.add("zlock#00000000-0000-0000-0000-CCCCCCCCCCCC#0000000003");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000002");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001");
+
+ ZooLock.sortChildrenByLockPrefix(children);
Review comment:
After I made this comment I saw the code that filters children based on the zlock prefix. I am thinking this sort code should throw an exception if it sees something unexpected after seeing that filter code. I don't think after the filter code runs that odd/random things are expected.
If there are pre 2.1.0 processes running w/ ehpemeral nodes, throwing exception or warning in the filter code that runs before sort may not be a bad thing.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r560281265
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -259,7 +304,7 @@ public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
+ final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + THIS_ZLOCK, data);
Review comment:
resolving this, we can pick it up below.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767199022
> It cleaned up the extra ephemeral nodes that were created by the "missed" server responses, then it put a watcher on the lowest sequence number of the prior ephemeral node.
Yeah that seems to be working really well. I need to try to delete the ephemeral nodes I created. I was curious about the repeated creation of ephemeral nodes and then the tserver dying. That is probably caused by code outside zooklock in the tserver, was wondering if you had looked at that and if that was working in a way you would expect.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner edited a comment on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner edited a comment on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767193472
> Is it because the tserver was already running at that address before you stopped it and changed the log level?
Yes
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767193472
> I'm curious why in the tserver log that the ephemeral sequential sequence number started at 4.
I think its because I started accumulo, changed the logging config, and then restarted the tserver.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r561481934
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +132,326 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ // NOTE: It's possible that we silently created more than one ephemeral
+ // node at `path` if the server response was missed by the ZK client and
+ // it retried. The other ephemeral nodes will be cleaned up when the process
+ // exits.
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.trace("[{}] Deleting all at path: {}", this.getZLockPrefix(), pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ private static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() <= 43) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() <= 43) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = o1.lastIndexOf('#');
+ int rightIdx = o2.lastIndexOf('#');
+ return o1.substring(leftIdx).compareTo(o2.substring(rightIdx));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Children nodes");
+ for (String child : children) {
+ LOG.trace("- {}", child);
+ }
}
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String myLock,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(myLock)) {
+ throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
}
+ sortChildrenByLockPrefix(children);
if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ LOG.trace("[{}] First candidate is my lock, acquiring", this.getZLockPrefix());
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = myLock;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
+ } else {
+ int idx = children.indexOf(myLock);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
Review comment:
I like it how this works backwards to find the lowest prior node w/ the same uuid , its seems super efficient. It took me a while to review the overall code for correctness and I didn't see an problems. Could pull this into a function that could be unit tested, maybe something like `prev = findPriorLockNode(myLock,children)`. I suggested the unit test because of the amount of time it took me to review the code.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] ctubbsii commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
ctubbsii commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r561341204
##########
File path: test/src/main/resources/log4j2-test.properties
##########
@@ -143,6 +143,6 @@ logger.35.level = info
logger.36.name = org.apache.thrift.transport.TIOStreamTransport
logger.36.level = error
-rootLogger.level = debug
+rootLogger.level = trace
Review comment:
I'm thinking we probably don't want to leave this change in, as that could easily fill up disk during a build on a resource constrained system, or create a lot of unnecessary IO wear on a developer's SSD. Debug level is probably fine for the ITs.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r565436601
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
Review comment:
Thanks @EdColeman for the background info. My overall motivation for asking these questions is that I think its good for code that reads persisted data to be skeptical that the data is at it should be. With that motivation in mind I have been wondering what sanity checks could be done for the lock nodes.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564828880
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000006");
+ children.add("zlock#00000000-0000-0000-0000-GGGGGGGGGGGG#0000000008");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000004");
+ children.add("zlock#00000000-0000-0000-0000-CCCCCCCCCCCC#0000000003");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000002");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001");
+
+ ZooLock.sortChildrenByLockPrefix(children);
+
+ assertEquals(8, children.size());
+ assertEquals("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001", children.get(0));
+ assertEquals("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000002", children.get(1));
+ assertEquals("zlock#00000000-0000-0000-0000-CCCCCCCCCCCC#0000000003", children.get(2));
+ assertEquals("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000004", children.get(3));
+ assertEquals("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000006", children.get(4));
+ assertEquals("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007", children.get(5));
+ assertEquals("zlock#00000000-0000-0000-0000-GGGGGGGGGGGG#0000000008", children.get(6));
+ assertEquals("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010", children.get(7));
+
+ assertEquals("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000004", ZooLock
+ .findLowestPrevPrefix(children, "zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007"));
+
+ assertEquals("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001", ZooLock
+ .findLowestPrevPrefix(children, "zlock#00000000-0000-0000-0000-CCCCCCCCCCCC#0000000003"));
+
+ assertEquals("zlock#00000000-0000-0000-0000-GGGGGGGGGGGG#0000000008", ZooLock
+ .findLowestPrevPrefix(children, "zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010"));
+
Review comment:
added to test.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564839629
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -38,9 +39,27 @@
import org.slf4j.LoggerFactory;
public class ZooLock implements Watcher {
- private static final Logger log = LoggerFactory.getLogger(ZooLock.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ZooLock.class);
- public static final String LOCK_PREFIX = "zlock-";
+ private static final String ZLOCK_PREFIX = "zlock#";
+ private static final String ZLOCK_UUID = UUID.randomUUID().toString();
Review comment:
I looked in the code a bit, the Master and GC code created ZooLock objs in a loop. Could possibly require passing a UUID into the ZooLock constructor. Maybe this is useful for test and for making things crystal clear in the code. Like the GC code could created the UUID outside of the loop and it would make what is going on more apparent.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r556704441
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -259,7 +304,7 @@ public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
+ final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + THIS_ZLOCK, data);
Review comment:
Another option may be to leave putEphemeralSequential as is and always get the children list after calling putEphemeralSequential and delete anything w/ the same UUID that is not equal to what putEphemeralSequential returned.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564859274
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +365,262 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private static final Logger LOG = LoggerFactory.getLogger(LockWorker.class);
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+ private Exception ex = null;
Review comment:
```suggestion
private volatile Exception ex = null;
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r565339800
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
Review comment:
Thanks @EdColeman!
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564525208
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -38,9 +40,13 @@
import org.slf4j.LoggerFactory;
public class ZooLock implements Watcher {
- private static final Logger log = LoggerFactory.getLogger(ZooLock.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ZooLock.class);
Review comment:
Just a [convention](https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html) that I have used on my previous teams.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r561481934
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +132,326 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ // NOTE: It's possible that we silently created more than one ephemeral
+ // node at `path` if the server response was missed by the ZK client and
+ // it retried. The other ephemeral nodes will be cleaned up when the process
+ // exits.
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.trace("[{}] Deleting all at path: {}", this.getZLockPrefix(), pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ private static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() <= 43) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() <= 43) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = o1.lastIndexOf('#');
+ int rightIdx = o2.lastIndexOf('#');
+ return o1.substring(leftIdx).compareTo(o2.substring(rightIdx));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Children nodes");
+ for (String child : children) {
+ LOG.trace("- {}", child);
+ }
}
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String myLock,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(myLock)) {
+ throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
}
+ sortChildrenByLockPrefix(children);
if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ LOG.trace("[{}] First candidate is my lock, acquiring", this.getZLockPrefix());
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = myLock;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
+ } else {
+ int idx = children.indexOf(myLock);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
Review comment:
I like it how this works backwards to find the lowest prior node w/ the same uuid , its seems super efficient. It took me a while to review the overall code for correctness and I didn't see an problems. Could pull this into a function that could be unit tested, maybe something like `prev = findPriorLockNode(myLock,children)`. I suggested the unit test because of the amount of time it took me to review the code.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] ctubbsii commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
ctubbsii commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-770151558
VolumeIT is failing with these changes.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r565470401
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
Review comment:
I merged the methods that gets the children and sorts them, into one [here](https://github.com/apache/accumulo/pull/1866/files#diff-d53a0e8d1a6246f0196696217ef667f8730e51b93ffdea614d380315094e2387R176). Based on this thread, we might want to relax or remove the restriction on the ephemeral sequence number size.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767195554
@dlmarion I ran another experiment where I manually did the following in zkCli to create some ephemeral nodes before starting the tserver.
```
[zk: localhost:2181(CONNECTED) 6] addauth digest accumulo:uno
[zk: localhost:2181(CONNECTED) 7] create /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997
Created /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997
[zk: localhost:2181(CONNECTED) 17] create -s -e /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#
Created /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000002
[zk: localhost:2181(CONNECTED) 18] create -s -e /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#
Created /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000003
[zk: localhost:2181(CONNECTED) 19] create -s -e /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#
Created /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
[zk: localhost:2181(CONNECTED) 20] create -s -e /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#
Created /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000005
[zk: localhost:2181(CONNECTED) 21] ls /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997
[zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000002, zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000003, zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004, zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000005]
```
Then I started the tserver and saw the following in the logs.
```
2021-01-25T19:04:20,067 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Ephemeral node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000009 created
2021-01-25T19:04:20,080 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T19:04:20,080 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000002
2021-01-25T19:04:20,080 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000003
2021-01-25T19:04:20,080 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T19:04:20,080 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000005
2021-01-25T19:04:20,080 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000006
2021-01-25T19:04:20,080 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000007
2021-01-25T19:04:20,080 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000008
2021-01-25T19:04:20,080 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000009
2021-01-25T19:04:20,081 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] lowest sequential node found: /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000006
2021-01-25T19:04:20,081 [zookeeper.ZooLock] INFO : [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#
2021-01-25T19:04:20,081 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] higher sequential node found: zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000007, deleting it
2021-01-25T19:04:20,087 [zookeeper.ZooLock] INFO : [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#
2021-01-25T19:04:20,087 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] higher sequential node found: zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000008, deleting it
2021-01-25T19:04:20,089 [zookeeper.ZooLock] INFO : [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#
2021-01-25T19:04:20,089 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] higher sequential node found: zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000009, deleting it
2021-01-25T19:04:20,093 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Setting watcher on /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000006
2021-01-25T19:04:20,102 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T19:04:20,102 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000002
2021-01-25T19:04:20,102 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000003
2021-01-25T19:04:20,102 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T19:04:20,102 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000005
2021-01-25T19:04:20,102 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000006
2021-01-25T19:04:20,102 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Establishing watch on prior node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000002
2021-01-25T19:04:20,103 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Deleting all at path: /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000006
2021-01-25T19:04:20,109 [tserver.TabletServer] INFO : Waiting for tablet server lock
2021-01-25T19:04:20,507 [server.ServerUtil] WARN : System swappiness setting is greater than ten (60) which can cause time-sensitive operations to be delayed. Accumulo is time sensitive because it needs to maintain distributed lock agreement.
2021-01-25T19:04:20,507 [conf.SiteConfiguration] INFO : Found Accumulo configuration on classpath at /home/ubuntu/git-local/fluo-uno/install/accumulo-2.1.0-SNAPSHOT/conf/accumulo.properties
2021-01-25T19:04:20,523 [fs.VolumeManager] DEBUG: Trying to read instance id from hdfs://localhost:8020/accumulo/instance_id
2021-01-25T19:04:24,863 [server.GarbageCollectionLogger] DEBUG: gc G1 Young Generation=0.09(+0.00) secs G1 Old Generation=0.04(+0.00) secs freemem=707,227,944(-21,278,184) totalmem=805,306,368
2021-01-25T19:04:25,138 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Ephemeral node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000013 created
2021-01-25T19:04:25,139 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T19:04:25,139 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000002
2021-01-25T19:04:25,139 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000003
2021-01-25T19:04:25,139 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T19:04:25,139 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000005
2021-01-25T19:04:25,139 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000010
2021-01-25T19:04:25,139 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000011
2021-01-25T19:04:25,139 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000012
2021-01-25T19:04:25,139 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000013
```
The above pattern continued until the following happened.
```
2021-01-25T19:06:15,889 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T19:06:15,889 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000002
2021-01-25T19:06:15,889 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000003
2021-01-25T19:06:15,889 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T19:06:15,889 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000005
2021-01-25T19:06:15,889 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000098
2021-01-25T19:06:15,889 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000099
2021-01-25T19:06:15,889 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000100
2021-01-25T19:06:15,889 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000101
2021-01-25T19:06:15,889 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] lowest sequential node found: /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000098
2021-01-25T19:06:15,889 [zookeeper.ZooLock] INFO : [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#
2021-01-25T19:06:15,889 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] higher sequential node found: zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000099, deleting it
2021-01-25T19:06:15,891 [zookeeper.ZooLock] INFO : [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#
2021-01-25T19:06:15,891 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] higher sequential node found: zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000100, deleting it
2021-01-25T19:06:15,892 [zookeeper.ZooLock] INFO : [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#
2021-01-25T19:06:15,892 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] higher sequential node found: zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000101, deleting it
2021-01-25T19:06:15,895 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Setting watcher on /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000098
2021-01-25T19:06:15,897 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T19:06:15,897 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000002
2021-01-25T19:06:15,897 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000003
2021-01-25T19:06:15,897 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T19:06:15,897 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000005
2021-01-25T19:06:15,897 [zookeeper.ZooLock] TRACE: - zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000098
2021-01-25T19:06:15,897 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Establishing watch on prior node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000002
2021-01-25T19:06:15,897 [zookeeper.ZooLock] TRACE: [zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#] Deleting all at path: /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#252a29a2-a14d-4c10-9b61-01387d829ba5#0000000098
2021-01-25T19:06:15,899 [tserver.TabletServer] INFO : Waiting for tablet server lock
2021-01-25T19:06:19,557 [vfs.ContextManager] DEBUG: Managed Contexts: {}
2021-01-25T19:06:19,557 [vfs.ContextManager] DEBUG: Configured Contexts: []
2021-01-25T19:06:19,557 [vfs.ContextManager] DEBUG: Closing contexts: {}
2021-01-25T19:06:19,740 [lru.LruBlockCache] DEBUG: Cache Stats: Sizes: Total=0.013473511MB (14128), Free=191.98653MB (201312464), Max=192.0MB (201326592), Counts: Blocks=0, Access=0, Hit=0, Miss=0, Evictions=0, Evicted=0,Ratios: Hit Ratio=NaN%, Miss Ratio=NaN%, Evicted/Run=NaN, Duplicate Reads=0
2021-01-25T19:06:19,741 [lru.LruBlockCache] DEBUG: Cache Stats: Sizes: Total=0.0061035156MB (6400), Free=76.7939MB (80524236), Max=76.8MB (80530636), Counts: Blocks=0, Access=0, Hit=0, Miss=0, Evictions=0, Evicted=0,Ratios: Hit Ratio=NaN%, Miss Ratio=NaN%, Evicted/Run=NaN, Duplicate Reads=0
2021-01-25T19:06:19,757 [lru.LruBlockCache] DEBUG: Cache Stats: Sizes: Total=0.0061035156MB (6400), Free=76.7939MB (80524236), Max=76.8MB (80530636), Counts: Blocks=0, Access=0, Hit=0, Miss=0, Evictions=0, Evicted=0,Ratios: Hit Ratio=NaN%, Miss Ratio=NaN%, Evicted/Run=NaN, Duplicate Reads=0
2021-01-25T19:06:20,091 [server.GarbageCollectionLogger] DEBUG: gc G1 Young Generation=0.09(+0.00) secs G1 Old Generation=0.04(+0.00) secs freemem=684,956,760(-43,549,368) totalmem=805,306,368
2021-01-25T19:06:20,911 [tserver.TabletServer] INFO : Too many retries, exiting.
2021-01-25T19:06:20,912 [tserver.TabletServer] INFO : Could not obtain tablet server lock, exiting.
java.lang.RuntimeException: Too many retries, exiting.
at org.apache.accumulo.tserver.TabletServer.announceExistence(TabletServer.java:679) ~[accumulo-tserver-2.1.0-SNAPSHOT.jar:2.1.0-SNAPSHOT]
at org.apache.accumulo.tserver.TabletServer.run(TabletServer.java:740) ~[accumulo-tserver-2.1.0-SNAPSHOT.jar:2.1.0-SNAPSHOT]
at java.lang.Thread.run(Thread.java:834) [?:?]
2021-01-25T19:06:20,915 [start.Main] ERROR: Thread 'tserver' died.
java.lang.RuntimeException: java.lang.RuntimeException: Too many retries, exiting.
at org.apache.accumulo.tserver.TabletServer.announceExistence(TabletServer.java:682) ~[accumulo-tserver-2.1.0-SNAPSHOT.jar:2.1.0-SNAPSHOT]
at org.apache.accumulo.tserver.TabletServer.run(TabletServer.java:740) ~[accumulo-tserver-2.1.0-SNAPSHOT.jar:2.1.0-SNAPSHOT]
at java.lang.Thread.run(Thread.java:834) [?:?]
Caused by: java.lang.RuntimeException: Too many retries, exiting.
at org.apache.accumulo.tserver.TabletServer.announceExistence(TabletServer.java:679) ~[accumulo-tserver-2.1.0-SNAPSHOT.jar:2.1.0-SNAPSHOT]
... 2 more
```
Does this seem like what you would expect?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner edited a comment on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner edited a comment on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767188215
@dlmarion I ran an experiment w/ this code locally. First I made the following change on my local copy, to always force the creation of multiple ephemeral nodes.
```diff
diff --git a/core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java b/core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
index f79ca72c50..1f87ee3c3a 100644
--- a/core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
+++ b/core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
@@ -370,6 +370,11 @@ public class ZooLock implements Watcher {
// except that instead of the ephemeral lock node being of the form guid-lock- use lock-guid-.
// Another deviation from the recipe is that we cleanup any extraneous ephermal nodes that
// were created.
+
+ for(int i = 0; i < 3; i++) {
+ zooKeeper.putEphemeralSequential(lockPathPrefix, data);
+ }
+
final String createPath = zooKeeper.putEphemeralSequential(lockPathPrefix, data);
LOG.trace("[{}] Ephemeral node {} created", this.getZLockPrefix(), createPath);
```
Then I started up Accumulo using these changes, enabled trace logging for ZooLock, and restarted the tserver. After that I saw the following in the tserver logs.
```
2021-01-25T18:32:35,744 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Ephemeral node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000007 created
2021-01-25T18:32:35,754 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T18:32:35,754 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T18:32:35,754 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000005
2021-01-25T18:32:35,754 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000006
2021-01-25T18:32:35,754 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000007
2021-01-25T18:32:35,755 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] lowest sequential node found: /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T18:32:35,755 [zookeeper.ZooLock] INFO : [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#
2021-01-25T18:32:35,755 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] higher sequential node found: zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000005, deleting it
2021-01-25T18:32:35,758 [zookeeper.ZooLock] INFO : [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#
2021-01-25T18:32:35,758 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] higher sequential node found: zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000006, deleting it
2021-01-25T18:32:35,760 [zookeeper.ZooLock] INFO : [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#
2021-01-25T18:32:35,760 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] higher sequential node found: zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000007, deleting it
2021-01-25T18:32:35,761 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Setting watcher on /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T18:32:35,764 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T18:32:35,764 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T18:32:35,764 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] First candidate is my lock, acquiring
2021-01-25T18:32:35,764 [tserver.TabletServer] DEBUG: Obtained tablet server lock /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
2021-01-25T18:32:35,768 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T18:32:35,768 [zookeeper.ZooLock] TRACE: - zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
```
Then I did the following in zkCli.
```
[zk: localhost:2181(CONNECTED) 0] addauth digest accumulo:uno
[zk: localhost:2181(CONNECTED) 1] ls /accumulo/
3cad24a9-53a9-4a6a-a846-ba24c5d747b9 instances
[zk: localhost:2181(CONNECTED) 1] ls /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997
[zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004]
[zk: localhost:2181(CONNECTED) 2] delete /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/tservers/accumulo:9997/zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004
```
After that I saw the following in the tserver logs and confirmed the tserver was not running.
```
2021-01-25T18:37:43,487 [zookeeper.ZooLock] TRACE: [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#0000000004 was deleted
2021-01-25T18:37:43,489 [tserver.TabletServer] ERROR: Lost tablet server lock (reason = LOCK_DELETED), exiting.
```
Everything worked great. After running this experiment I am thinking the log messages related to creating the lock that are trace could be debug. Locks are not created often, locks are really important, and the information could be useful for debugging. Also I noticed the following log message was emitted multiple times.
```
INFO : [zlock#93852053-1721-4f2a-a8fe-ee4b9398389e#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r563857119
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +132,326 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ // NOTE: It's possible that we silently created more than one ephemeral
+ // node at `path` if the server response was missed by the ZK client and
+ // it retried. The other ephemeral nodes will be cleaned up when the process
+ // exits.
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.trace("[{}] Deleting all at path: {}", this.getZLockPrefix(), pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ private static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() <= 43) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() <= 43) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = o1.lastIndexOf('#');
+ int rightIdx = o2.lastIndexOf('#');
+ return o1.substring(leftIdx).compareTo(o2.substring(rightIdx));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Children nodes");
+ for (String child : children) {
+ LOG.trace("- {}", child);
+ }
}
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String myLock,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(myLock)) {
+ throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
}
+ sortChildrenByLockPrefix(children);
if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ LOG.trace("[{}] First candidate is my lock, acquiring", this.getZLockPrefix());
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = myLock;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
+ } else {
+ int idx = children.indexOf(myLock);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
Review comment:
@keith-turner @ctubbsii - I have made the requested changes and have added my parallel test. I have no other changes in the works.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767196667
> Are you able to start 2 masters?
I can look into that. That would be a good thing to try.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767201470
> I believe the code outside of ZooLock in the TServer is what caused the TServer to die after some period of time without the lock. I did not look at that code as I assume that functionality would be the same.
If interested I found the code that is doing that.
https://github.com/apache/accumulo/blob/680886a61158fe0906424f9fe43c2916f1f9f48f/server/tserver/src/main/java/org/apache/accumulo/tserver/TabletServer.java#L665-L676
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564837998
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +363,245 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+
+ public LockWorker(final String parent, final String name, final CountDownLatch lockLatch,
+ final CountDownLatch lockCompletedLatch) {
+ this.parent = parent;
+ this.name = name;
+ this.getLockLatch = lockLatch;
+ this.lockCompletedLatch = lockCompletedLatch;
+ }
+
+ public void unlock() {
+ unlockLatch.countDown();
+ }
+
+ public boolean holdsLock() {
+ return lockWatcher.isLockHeld();
+ }
+
+ @Override
+ public void run() {
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try {
+ try (ZooKeeperWrapper zk =
+ new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ ZooReaderWriter zrw = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk;
+ }
+ };
+ ZooLock zl = new ZooLock(zrw, parent);
+ zl.setVMLockPrefix(new Prefix(name));
+ getLockLatch.countDown(); // signal we are done
+ getLockLatch.await(); // wait for others to finish
+ zl.lock(lockWatcher, "test1".getBytes(UTF_8)); // race to the lock
+ lockCompletedLatch.countDown();
+ unlockLatch.await();
+ zl.unlock();
+ }
+ } catch (IOException | InterruptedException | KeeperException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "LockWorker [name=" + name + ", holdsLock()=" + holdsLock() + "]";
+ }
+
+ }
+
+ private int parseLockWorkerName(String child) {
+ if (child.startsWith("zlock#00000000-0000-0000-0000-000000000000#")) {
+ return 0;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-111111111111#")) {
+ return 1;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-222222222222#")) {
+ return 2;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-333333333333#")) {
+ return 3;
+ } else {
+ return -1;
+ }
+ }
+
+ @Test(timeout = 60000)
+ public void testLockParallel() throws Exception {
+ String parent = "/zlParallel";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ // Create the parent node
+ zk.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ int numWorkers = 4;
+ final CountDownLatch getLockLatch = new CountDownLatch(numWorkers);
+ final CountDownLatch lockFinishedLatch = new CountDownLatch(numWorkers);
+ final List<LockWorker> workers = new ArrayList<>(numWorkers);
+ final List<Thread> threads = new ArrayList<>(numWorkers);
+ for (int i = 0; i < numWorkers; i++) {
+ String name =
+ "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#".replaceAll("A", Integer.toString(i));
+ LockWorker w = new LockWorker(parent, name, getLockLatch, lockFinishedLatch);
+ Thread t = new Thread(w);
+ workers.add(w);
+ threads.add(t);
+ t.start();
+ }
+
+ getLockLatch.await(); // Threads compete for lock
+ lockFinishedLatch.await(); // Threads lock logic complete
+
+ for (int i = 4; i > 0; i--) {
+ List<String> children = zk.getChildren(parent, false);
+ ZooLock.sortChildrenByLockPrefix(children);
+ assertEquals(i, children.size());
Review comment:
test updated.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r565469841
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000006");
+ children.add("zlock#00000000-0000-0000-0000-GGGGGGGGGGGG#0000000008");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000004");
+ children.add("zlock#00000000-0000-0000-0000-CCCCCCCCCCCC#0000000003");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000002");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001");
+
+ ZooLock.sortChildrenByLockPrefix(children);
Review comment:
I merged the methods that gets the children and sorts them, into one [here](https://github.com/apache/accumulo/pull/1866/files#diff-d53a0e8d1a6246f0196696217ef667f8730e51b93ffdea614d380315094e2387R176). The sort code now enforces an expected pattern
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner edited a comment on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner edited a comment on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767188215
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] ctubbsii commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
ctubbsii commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r568037243
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -38,9 +40,13 @@
import org.slf4j.LoggerFactory;
public class ZooLock implements Watcher {
- private static final Logger log = LoggerFactory.getLogger(ZooLock.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ZooLock.class);
Review comment:
In general, static final variables are typically all uppercase. I'm surprised we don't adopt that convention for more of these loggers. I don't think it matters much, though.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564769513
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000006");
+ children.add("zlock#00000000-0000-0000-0000-GGGGGGGGGGGG#0000000008");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000004");
+ children.add("zlock#00000000-0000-0000-0000-CCCCCCCCCCCC#0000000003");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000002");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001");
+
+ ZooLock.sortChildrenByLockPrefix(children);
+
+ assertEquals(8, children.size());
+ assertEquals("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001", children.get(0));
+ assertEquals("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000002", children.get(1));
+ assertEquals("zlock#00000000-0000-0000-0000-CCCCCCCCCCCC#0000000003", children.get(2));
+ assertEquals("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000004", children.get(3));
+ assertEquals("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000006", children.get(4));
+ assertEquals("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007", children.get(5));
+ assertEquals("zlock#00000000-0000-0000-0000-GGGGGGGGGGGG#0000000008", children.get(6));
+ assertEquals("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010", children.get(7));
+
+ assertEquals("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000004", ZooLock
+ .findLowestPrevPrefix(children, "zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007"));
+
+ assertEquals("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001", ZooLock
+ .findLowestPrevPrefix(children, "zlock#00000000-0000-0000-0000-CCCCCCCCCCCC#0000000003"));
+
+ assertEquals("zlock#00000000-0000-0000-0000-GGGGGGGGGGGG#0000000008", ZooLock
+ .findLowestPrevPrefix(children, "zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010"));
+
Review comment:
Could add the following to ensure nothing is returned for 1st and non-existent.
```java
assertThrows(IndexOutOfBoundsException.class, () -> {
ZooLock.findLowestPrevPrefix(children,
"zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001");
});
assertThrows(IndexOutOfBoundsException.class, () -> {
ZooLock.findLowestPrevPrefix(children,
"zlock#00000000-0000-0000-0000-XXXXXXXXXXXX#0000000099");
});
```
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
Review comment:
Its nice to throw this in to ensure the sort is numeric and not lexicographic. Do you know if ZK generated seq numbers will always be 10 chars?
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +151,344 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}", vmLockPrefix,
+ pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ children.sort(new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ children.forEach(c -> LOG.debug("- {}", c));
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", vmLockPrefix);
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
- }
-
- prev = child;
- }
+ } else {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}", vmLockPrefix,
+ children.get(0));
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ LOG.debug("[{}] Establishing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", vmLockPrefix);
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ vmLockPrefix, nodeToWatch);
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted", vmLockPrefix,
+ nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ LOG.debug("[{}] Renewing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
- } catch (KeeperException | InterruptedException e) {
- lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
}
- }
- });
+ };
+
+ Stat stat = zooKeeper.getStatus(nodeToWatch, priorNodeWatcher);
+ if (stat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, priorNodeWatcher, WatcherType.Any,
+ true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ }
- if (stat == null)
- lockAsync(myLock, lw);
}
private void lostLock(LockLossReason reason) {
LockWatcher localLw = lockWatcher;
- lock = null;
+ lockNodeName = null;
lockWatcher = null;
localLw.lostLock(reason);
}
- public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
+ public synchronized void lock(final AccumuloLockWatcher lw, byte[] data) {
Review comment:
I think the method was named lockAsync because the method does not block until the lock is acquired.
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +363,245 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+
+ public LockWorker(final String parent, final String name, final CountDownLatch lockLatch,
+ final CountDownLatch lockCompletedLatch) {
+ this.parent = parent;
+ this.name = name;
+ this.getLockLatch = lockLatch;
+ this.lockCompletedLatch = lockCompletedLatch;
+ }
+
+ public void unlock() {
+ unlockLatch.countDown();
+ }
+
+ public boolean holdsLock() {
+ return lockWatcher.isLockHeld();
+ }
+
+ @Override
+ public void run() {
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try {
+ try (ZooKeeperWrapper zk =
+ new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ ZooReaderWriter zrw = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk;
+ }
+ };
+ ZooLock zl = new ZooLock(zrw, parent);
+ zl.setVMLockPrefix(new Prefix(name));
+ getLockLatch.countDown(); // signal we are done
+ getLockLatch.await(); // wait for others to finish
+ zl.lock(lockWatcher, "test1".getBytes(UTF_8)); // race to the lock
+ lockCompletedLatch.countDown();
+ unlockLatch.await();
+ zl.unlock();
+ }
+ } catch (IOException | InterruptedException | KeeperException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "LockWorker [name=" + name + ", holdsLock()=" + holdsLock() + "]";
+ }
+
+ }
+
+ private int parseLockWorkerName(String child) {
+ if (child.startsWith("zlock#00000000-0000-0000-0000-000000000000#")) {
+ return 0;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-111111111111#")) {
+ return 1;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-222222222222#")) {
+ return 2;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-333333333333#")) {
+ return 3;
+ } else {
+ return -1;
+ }
+ }
+
+ @Test(timeout = 60000)
+ public void testLockParallel() throws Exception {
+ String parent = "/zlParallel";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ // Create the parent node
+ zk.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ int numWorkers = 4;
+ final CountDownLatch getLockLatch = new CountDownLatch(numWorkers);
+ final CountDownLatch lockFinishedLatch = new CountDownLatch(numWorkers);
+ final List<LockWorker> workers = new ArrayList<>(numWorkers);
+ final List<Thread> threads = new ArrayList<>(numWorkers);
+ for (int i = 0; i < numWorkers; i++) {
+ String name =
+ "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#".replaceAll("A", Integer.toString(i));
+ LockWorker w = new LockWorker(parent, name, getLockLatch, lockFinishedLatch);
+ Thread t = new Thread(w);
+ workers.add(w);
+ threads.add(t);
+ t.start();
Review comment:
Not sure what will happen w/ this test if an exception happens in the background thread. Could refactor the test to use an executor and futures. Futures are nice because they make it easy to know when a background task had an exception.
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +363,245 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+
+ public LockWorker(final String parent, final String name, final CountDownLatch lockLatch,
+ final CountDownLatch lockCompletedLatch) {
+ this.parent = parent;
+ this.name = name;
+ this.getLockLatch = lockLatch;
+ this.lockCompletedLatch = lockCompletedLatch;
+ }
+
+ public void unlock() {
+ unlockLatch.countDown();
+ }
+
+ public boolean holdsLock() {
+ return lockWatcher.isLockHeld();
+ }
+
+ @Override
+ public void run() {
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try {
+ try (ZooKeeperWrapper zk =
+ new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ ZooReaderWriter zrw = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk;
+ }
+ };
+ ZooLock zl = new ZooLock(zrw, parent);
+ zl.setVMLockPrefix(new Prefix(name));
+ getLockLatch.countDown(); // signal we are done
+ getLockLatch.await(); // wait for others to finish
+ zl.lock(lockWatcher, "test1".getBytes(UTF_8)); // race to the lock
+ lockCompletedLatch.countDown();
+ unlockLatch.await();
+ zl.unlock();
+ }
+ } catch (IOException | InterruptedException | KeeperException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "LockWorker [name=" + name + ", holdsLock()=" + holdsLock() + "]";
+ }
+
+ }
+
+ private int parseLockWorkerName(String child) {
+ if (child.startsWith("zlock#00000000-0000-0000-0000-000000000000#")) {
+ return 0;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-111111111111#")) {
+ return 1;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-222222222222#")) {
+ return 2;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-333333333333#")) {
+ return 3;
+ } else {
+ return -1;
+ }
+ }
+
+ @Test(timeout = 60000)
+ public void testLockParallel() throws Exception {
+ String parent = "/zlParallel";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ // Create the parent node
+ zk.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ int numWorkers = 4;
+ final CountDownLatch getLockLatch = new CountDownLatch(numWorkers);
+ final CountDownLatch lockFinishedLatch = new CountDownLatch(numWorkers);
+ final List<LockWorker> workers = new ArrayList<>(numWorkers);
+ final List<Thread> threads = new ArrayList<>(numWorkers);
+ for (int i = 0; i < numWorkers; i++) {
+ String name =
+ "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#".replaceAll("A", Integer.toString(i));
+ LockWorker w = new LockWorker(parent, name, getLockLatch, lockFinishedLatch);
+ Thread t = new Thread(w);
+ workers.add(w);
+ threads.add(t);
+ t.start();
+ }
+
+ getLockLatch.await(); // Threads compete for lock
+ lockFinishedLatch.await(); // Threads lock logic complete
+
+ for (int i = 4; i > 0; i--) {
+ List<String> children = zk.getChildren(parent, false);
+ ZooLock.sortChildrenByLockPrefix(children);
+ assertEquals(i, children.size());
Review comment:
Thinking the following may make the test more stable and can get rid of the sleep(500) later in the loop.
```suggestion
List<String> children = zk.getChildren(parent, false);
while(children.size() != i){
Thread.sleep(100);
children = zk.getChildren(parent, false);
}
ZooLock.sortChildrenByLockPrefix(children);
assertEquals(i, children.size()); //probably don't need this, but it does not hurt anything
```
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000006");
+ children.add("zlock#00000000-0000-0000-0000-GGGGGGGGGGGG#0000000008");
+ children.add("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000004");
+ children.add("zlock#00000000-0000-0000-0000-CCCCCCCCCCCC#0000000003");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000002");
+ children.add("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001");
+
+ ZooLock.sortChildrenByLockPrefix(children);
Review comment:
The sort code seems to accept things that do not follow the pattern `zlock#<uuid>"<seq>`, could have another test for this case. Also in general I was wondering if this expected? If its unexpected an exception may be good.
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -38,9 +39,27 @@
import org.slf4j.LoggerFactory;
public class ZooLock implements Watcher {
- private static final Logger log = LoggerFactory.getLogger(ZooLock.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ZooLock.class);
- public static final String LOCK_PREFIX = "zlock-";
+ private static final String ZLOCK_PREFIX = "zlock#";
+ private static final String ZLOCK_UUID = UUID.randomUUID().toString();
Review comment:
Since this is static seems like two ZooLocks created in the same process would have the same UUID. Probably does not matter because all code only creates a single zoolock per process, I think. But it still seems iffy.
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +151,344 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}", vmLockPrefix,
+ pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ children.sort(new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ children.forEach(c -> LOG.debug("- {}", c));
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", vmLockPrefix);
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
- }
-
- prev = child;
- }
+ } else {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}", vmLockPrefix,
+ children.get(0));
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ LOG.debug("[{}] Establishing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", vmLockPrefix);
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ vmLockPrefix, nodeToWatch);
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted", vmLockPrefix,
+ nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ LOG.debug("[{}] Renewing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
- } catch (KeeperException | InterruptedException e) {
- lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
}
- }
- });
+ };
+
+ Stat stat = zooKeeper.getStatus(nodeToWatch, priorNodeWatcher);
+ if (stat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, priorNodeWatcher, WatcherType.Any,
+ true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ }
- if (stat == null)
- lockAsync(myLock, lw);
}
private void lostLock(LockLossReason reason) {
LockWatcher localLw = lockWatcher;
- lock = null;
+ lockNodeName = null;
lockWatcher = null;
localLw.lostLock(reason);
}
- public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
+ public synchronized void lock(final AccumuloLockWatcher lw, byte[] data) {
- if (lockWatcher != null || lock != null || asyncLock != null) {
+ if (lockWatcher != null || lockNodeName != null || createdNodeName != null) {
throw new IllegalStateException();
}
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
- log.trace("Ephemeral node {} created", asyncLockPath);
- Stat stat = zooKeeper.getStatus(asyncLockPath, new Watcher() {
+ final String lockPathPrefix = path + "/" + vmLockPrefix.toString();
+ // Implement recipe at https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks
+ // except that instead of the ephemeral lock node being of the form guid-lock- use lock-guid-.
+ // Another deviation from the recipe is that we cleanup any extraneous ephemeral nodes that
+ // were created.
+ final String createPath = zooKeeper.putEphemeralSequential(lockPathPrefix, data);
+ LOG.debug("[{}] Ephemeral node {} created", vmLockPrefix, createPath);
+
+ // It's possible that the call above was retried several times and multiple ephemeral nodes
+ // were created but the client missed the response for some reason. Find the ephemeral nodes
+ // with this ZLOCK_UUID and lowest sequential number.
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
+ }
+ });
+ String lowestSequentialPath = null;
+ sortChildrenByLockPrefix(children);
+ boolean msgLoggedOnce = false;
+ for (String child : children) {
+ if (child.startsWith(vmLockPrefix.toString())) {
+ if (null == lowestSequentialPath) {
+ if (createPath.equals(path + "/" + child)) {
+ // the path returned from create is the lowest sequential one
+ lowestSequentialPath = createPath;
+ break;
+ }
+ lowestSequentialPath = path + "/" + child;
+ LOG.debug("[{}] lowest sequential node found: {}", vmLockPrefix, lowestSequentialPath);
+ } else {
+ if (!msgLoggedOnce) {
+ LOG.info(
+ "[{}] Zookeeper client missed server response, multiple ephemeral child nodes created at {}",
+ vmLockPrefix, lockPathPrefix);
+ msgLoggedOnce = true;
+ }
+ LOG.debug("[{}] higher sequential node found: {}, deleting it", vmLockPrefix, child);
+ zooKeeper.delete(path + "/" + child);
+ }
+ }
+ }
+ final String pathForWatcher = lowestSequentialPath;
+
+ // Set a watcher on the lowest sequential node that we created, this handles the case
+ // where the node we created is deleted or if this client becomes disconnected.
+ LOG.debug("[{}] Setting watcher on {}", vmLockPrefix, pathForWatcher);
+ Watcher watcherForNodeWeCreated = new Watcher() {
private void failedToAcquireLock() {
+ LOG.debug("[{}] Lock deleted before acquired, setting createdNodeName {} to null",
+ vmLockPrefix, createdNodeName);
lw.failedToAcquireLock(new Exception("Lock deleted before acquired"));
- asyncLock = null;
+ createdNodeName = null;
}
@Override
public void process(WatchedEvent event) {
synchronized (ZooLock.this) {
- if (lock != null && event.getType() == EventType.NodeDeleted
- && event.getPath().equals(path + "/" + lock)) {
+ if (lockNodeName != null && event.getType() == EventType.NodeDeleted
+ && event.getPath().equals(path + "/" + lockNodeName)) {
+ LOG.debug("[{}] {} was deleted", vmLockPrefix, lockNodeName);
lostLock(LockLossReason.LOCK_DELETED);
- } else if (asyncLock != null && event.getType() == EventType.NodeDeleted
- && event.getPath().equals(path + "/" + asyncLock)) {
+ } else if (createdNodeName != null && event.getType() == EventType.NodeDeleted
+ && event.getPath().equals(path + "/" + createdNodeName)) {
+ LOG.debug("[{}] {} was deleted", vmLockPrefix, createdNodeName);
failedToAcquireLock();
} else if (event.getState() != KeeperState.Disconnected
- && event.getState() != KeeperState.Expired && (lock != null || asyncLock != null)) {
- log.debug("Unexpected event watching lock node {} {}", event, asyncLockPath);
+ && event.getState() != KeeperState.Expired
+ && (lockNodeName != null || createdNodeName != null)) {
+ LOG.debug("Unexpected event watching lock node {} {}", event, pathForWatcher);
try {
- Stat stat2 = zooKeeper.getStatus(asyncLockPath, this);
+ Stat stat2 = zooKeeper.getStatus(pathForWatcher, this);
if (stat2 == null) {
- if (lock != null)
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(pathForWatcher, this, WatcherType.Any,
Review comment:
Do you think calling removeWatches could be done in other places in ZooLock? Wondering if there is a follow on issue.
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +363,245 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
Review comment:
If each zoolock object created its own unique uuid, then could possibly have a getVMLockPrefix() instead of a set method. The set method is fine, just a thought.
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +363,245 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+
+ public LockWorker(final String parent, final String name, final CountDownLatch lockLatch,
+ final CountDownLatch lockCompletedLatch) {
+ this.parent = parent;
+ this.name = name;
+ this.getLockLatch = lockLatch;
+ this.lockCompletedLatch = lockCompletedLatch;
+ }
+
+ public void unlock() {
+ unlockLatch.countDown();
+ }
+
+ public boolean holdsLock() {
+ return lockWatcher.isLockHeld();
+ }
+
+ @Override
+ public void run() {
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try {
+ try (ZooKeeperWrapper zk =
+ new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ ZooReaderWriter zrw = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk;
+ }
+ };
+ ZooLock zl = new ZooLock(zrw, parent);
+ zl.setVMLockPrefix(new Prefix(name));
+ getLockLatch.countDown(); // signal we are done
+ getLockLatch.await(); // wait for others to finish
+ zl.lock(lockWatcher, "test1".getBytes(UTF_8)); // race to the lock
+ lockCompletedLatch.countDown();
+ unlockLatch.await();
+ zl.unlock();
+ }
+ } catch (IOException | InterruptedException | KeeperException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "LockWorker [name=" + name + ", holdsLock()=" + holdsLock() + "]";
+ }
+
+ }
+
+ private int parseLockWorkerName(String child) {
+ if (child.startsWith("zlock#00000000-0000-0000-0000-000000000000#")) {
+ return 0;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-111111111111#")) {
+ return 1;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-222222222222#")) {
+ return 2;
+ } else if (child.startsWith("zlock#00000000-0000-0000-0000-333333333333#")) {
+ return 3;
+ } else {
+ return -1;
+ }
+ }
+
+ @Test(timeout = 60000)
+ public void testLockParallel() throws Exception {
+ String parent = "/zlParallel";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ // Create the parent node
+ zk.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ int numWorkers = 4;
+ final CountDownLatch getLockLatch = new CountDownLatch(numWorkers);
+ final CountDownLatch lockFinishedLatch = new CountDownLatch(numWorkers);
+ final List<LockWorker> workers = new ArrayList<>(numWorkers);
+ final List<Thread> threads = new ArrayList<>(numWorkers);
+ for (int i = 0; i < numWorkers; i++) {
+ String name =
+ "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#".replaceAll("A", Integer.toString(i));
+ LockWorker w = new LockWorker(parent, name, getLockLatch, lockFinishedLatch);
+ Thread t = new Thread(w);
+ workers.add(w);
+ threads.add(t);
+ t.start();
+ }
+
+ getLockLatch.await(); // Threads compete for lock
+ lockFinishedLatch.await(); // Threads lock logic complete
+
+ for (int i = 4; i > 0; i--) {
+ List<String> children = zk.getChildren(parent, false);
+ ZooLock.sortChildrenByLockPrefix(children);
+ assertEquals(i, children.size());
+ String first = children.get(0);
+ int workerWithLock = parseLockWorkerName(first);
+ LockWorker worker = workers.get(workerWithLock);
+ assertTrue(worker.holdsLock());
+ workers.forEach(w -> {
+ if (w != worker) {
+ assertFalse(w.holdsLock());
+ }
+ });
+ worker.unlock();
+ Thread.sleep(500); // wait for node to be deleted and lock to be reacquired.
+ }
+
+ workers.forEach(w -> assertFalse(w.holdsLock()));
+
Review comment:
Does it make sense to also check the following here?
```java
assertEquals(0, zk.getChildren(parent, false));
```
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +151,344 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}", vmLockPrefix,
+ pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ children.sort(new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ children.forEach(c -> LOG.debug("- {}", c));
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", vmLockPrefix);
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
- }
-
- prev = child;
- }
+ } else {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}", vmLockPrefix,
+ children.get(0));
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ LOG.debug("[{}] Establishing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", vmLockPrefix);
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ vmLockPrefix, nodeToWatch);
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted", vmLockPrefix,
+ nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ LOG.debug("[{}] Renewing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
- } catch (KeeperException | InterruptedException e) {
- lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
}
- }
- });
+ };
+
+ Stat stat = zooKeeper.getStatus(nodeToWatch, priorNodeWatcher);
+ if (stat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, priorNodeWatcher, WatcherType.Any,
+ true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ }
- if (stat == null)
- lockAsync(myLock, lw);
}
private void lostLock(LockLossReason reason) {
LockWatcher localLw = lockWatcher;
- lock = null;
+ lockNodeName = null;
lockWatcher = null;
localLw.lostLock(reason);
}
- public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
+ public synchronized void lock(final AccumuloLockWatcher lw, byte[] data) {
- if (lockWatcher != null || lock != null || asyncLock != null) {
+ if (lockWatcher != null || lockNodeName != null || createdNodeName != null) {
throw new IllegalStateException();
}
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
- log.trace("Ephemeral node {} created", asyncLockPath);
- Stat stat = zooKeeper.getStatus(asyncLockPath, new Watcher() {
+ final String lockPathPrefix = path + "/" + vmLockPrefix.toString();
+ // Implement recipe at https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks
+ // except that instead of the ephemeral lock node being of the form guid-lock- use lock-guid-.
+ // Another deviation from the recipe is that we cleanup any extraneous ephemeral nodes that
+ // were created.
+ final String createPath = zooKeeper.putEphemeralSequential(lockPathPrefix, data);
+ LOG.debug("[{}] Ephemeral node {} created", vmLockPrefix, createPath);
+
+ // It's possible that the call above was retried several times and multiple ephemeral nodes
+ // were created but the client missed the response for some reason. Find the ephemeral nodes
+ // with this ZLOCK_UUID and lowest sequential number.
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
+ }
+ });
Review comment:
This pattern is repeated twice in the code. Do you think it would make sense to put it in a function and add a stronger check of the nodes than just the prefix (like the pattern `zlock#<uuid>#<seq>`? Also wondering if something should be logged for child nodes that do not match the pattern, but I am not sure if that is expected.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564867199
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +365,262 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private static final Logger LOG = LoggerFactory.getLogger(LockWorker.class);
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+ private Exception ex = null;
Review comment:
good catch.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767193103
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r565368711
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -38,9 +39,27 @@
import org.slf4j.LoggerFactory;
public class ZooLock implements Watcher {
- private static final Logger log = LoggerFactory.getLogger(ZooLock.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ZooLock.class);
- public static final String LOCK_PREFIX = "zlock-";
+ private static final String ZLOCK_PREFIX = "zlock#";
+ private static final String ZLOCK_UUID = UUID.randomUUID().toString();
Review comment:
Great suggestion, this also removes the need for the conversation about whether or not the UUID should be static. I updated the code and implemented this in the latest commit.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] DomGarguilo commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
DomGarguilo commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r556698226
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -259,7 +304,7 @@ public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
+ final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + THIS_ZLOCK, data);
Review comment:
I think the idea would be to avoid creating a second node. From what I understand, an attempt would be made to recover the (created but not returned) node via its UUID. A search among the parent paths children could take place when this error occurs and if a node is found with the UUID then its path would be returned for use. I outlined this [here](https://github.com/apache/accumulo/issues/637#issuecomment-756902064). I think this recovery process would probably make sense to be within the retry logic in putEphemeralSequential where the exception could be caught to begin the recovery attempt.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] ctubbsii commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
ctubbsii commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-768349093
I ran all the ITs with this change and saw ZooLockIT fail with an AssertionError.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] ctubbsii edited a comment on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
ctubbsii edited a comment on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-771057716
> @ctubbsii - I pushed a fix for VolumeIT. Are you seeing any other test failures?
That was the only one I saw. I haven't re-run all of them with your latest. I don't have any objections to this change being merged in if you've fixed that, but there are a few unresolved comment threads above that you might want to mark as resolved, or address, before merging.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-770888503
@ctubbsii - I pushed a fix for VolumeIT. Are you seeing any other test failures?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] ctubbsii commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
ctubbsii commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-768390431
> Do you have any further information?
I have a stack trace, but I'm replying on mobile at the moment and don't have a convenient way to paste it. So, I thought it'd be easier to just mention the failing test so you can try it yourself. I can post the stack trace later if you can't reproduce it.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767199913
> That is probably caused by code outside zooklock in the tserver, was wondering if you had looked at that and if that was working in a way you would expect.
I believe the code outside of ZooLock in the TServer is what caused the TServer to die after some period of time without the lock. I did not look at that code as I assume that functionality would be the same.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564871496
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +132,383 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}",
+ this.getZLockPrefix(), pathToDelete);
+ }
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ for (String child : children) {
+ LOG.debug("- {}", child);
+ }
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", this.getZLockPrefix());
+ }
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}",
+ this.getZLockPrefix(), children.get(0));
}
- prev = child;
- }
-
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Establishing watch on prior node {}", this.getZLockPrefix(), nodeToWatch);
+ }
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", getZLockPrefix());
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ getZLockPrefix(), nodeToWatch);
+ }
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted",
+ getZLockPrefix(), nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Renewing watch on prior node {}", getZLockPrefix(), nodeToWatch);
+ }
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
- } catch (KeeperException | InterruptedException e) {
- lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
}
- }
- });
+ };
+
+ Stat stat = zooKeeper.getStatus(nodeToWatch, priorNodeWatcher);
+ if (stat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, priorNodeWatcher, WatcherType.Any,
+ true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ }
- if (stat == null)
- lockAsync(myLock, lw);
}
private void lostLock(LockLossReason reason) {
LockWatcher localLw = lockWatcher;
- lock = null;
+ lockNodeName = null;
lockWatcher = null;
localLw.lostLock(reason);
}
- public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
+ /*
+ * Exists to be overriden in tests
+ */
+ protected String getZLockPrefix() {
+ return THIS_ZLOCK_PREFIX;
+ }
+
+ public synchronized void lock(final AccumuloLockWatcher lw, byte[] data) {
- if (lockWatcher != null || lock != null || asyncLock != null) {
+ if (lockWatcher != null || lockNodeName != null || createdNodeName != null) {
throw new IllegalStateException();
}
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
- log.trace("Ephemeral node {} created", asyncLockPath);
- Stat stat = zooKeeper.getStatus(asyncLockPath, new Watcher() {
+ final String lockPathPrefix = path + "/" + getZLockPrefix();
+ // Implement recipe at https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks
+ // except that instead of the ephemeral lock node being of the form guid-lock- use lock-guid-.
+ // Another deviation from the recipe is that we cleanup any extraneous ephemeral nodes that
+ // were created.
+ final String createPath = zooKeeper.putEphemeralSequential(lockPathPrefix, data);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Ephemeral node {} created", this.getZLockPrefix(), createPath);
+ }
+
+ // It's possible that the call above was retried several times and multiple ephemeral nodes
+ // were created but the client missed the response for some reason. Find the ephemeral nodes
+ // with this ZLOCK_UUID and lowest sequential number.
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
+ }
+ });
+ String lowestSequentialPath = null;
+ sortChildrenByLockPrefix(children);
+ boolean msgLoggedOnce = false;
+ for (String child : children) {
+ if (child.startsWith(getZLockPrefix())) {
+ if (null == lowestSequentialPath) {
+ if (createPath.equals(path + "/" + child)) {
+ // the path returned from create is the lowest sequential one
+ lowestSequentialPath = createPath;
+ break;
+ }
+ lowestSequentialPath = path + "/" + child;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] lowest sequential node found: {}", this.getZLockPrefix(),
+ lowestSequentialPath);
+ }
+ } else {
+ if (!msgLoggedOnce) {
+ LOG.info(
+ "[{}] Zookeeper client missed server response, multiple ephemeral child nodes created at {}",
+ this.getZLockPrefix(), lockPathPrefix);
+ msgLoggedOnce = true;
+ }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] higher sequential node found: {}, deleting it", this.getZLockPrefix(),
+ child);
+ }
+ zooKeeper.delete(path + "/" + child);
+ }
+ }
+ }
+ final String pathForWatcher = lowestSequentialPath;
+
+ // Set a watcher on the lowest sequential node that we created, this handles the case
+ // where the node we created is deleted or if this client becomes disconnected.
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Setting watcher on {}", this.getZLockPrefix(), pathForWatcher);
+ }
+ Watcher watcherForNodeWeCreated = new Watcher() {
private void failedToAcquireLock() {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Lock deleted before acquired, setting createdNodeName {} to null",
+ getZLockPrefix(), createdNodeName);
+ }
lw.failedToAcquireLock(new Exception("Lock deleted before acquired"));
- asyncLock = null;
+ createdNodeName = null;
}
@Override
public void process(WatchedEvent event) {
synchronized (ZooLock.this) {
- if (lock != null && event.getType() == EventType.NodeDeleted
- && event.getPath().equals(path + "/" + lock)) {
+ if (lockNodeName != null && event.getType() == EventType.NodeDeleted
+ && event.getPath().equals(path + "/" + lockNodeName)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] {} was deleted", getZLockPrefix(), lockNodeName);
+ }
lostLock(LockLossReason.LOCK_DELETED);
- } else if (asyncLock != null && event.getType() == EventType.NodeDeleted
- && event.getPath().equals(path + "/" + asyncLock)) {
+ } else if (createdNodeName != null && event.getType() == EventType.NodeDeleted
+ && event.getPath().equals(path + "/" + createdNodeName)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] {} was deleted", getZLockPrefix(), createdNodeName);
+ }
failedToAcquireLock();
} else if (event.getState() != KeeperState.Disconnected
- && event.getState() != KeeperState.Expired && (lock != null || asyncLock != null)) {
- log.debug("Unexpected event watching lock node {} {}", event, asyncLockPath);
+ && event.getState() != KeeperState.Expired
+ && (lockNodeName != null || createdNodeName != null)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Unexpected event watching lock node {} {}", event, pathForWatcher);
+ }
try {
- Stat stat2 = zooKeeper.getStatus(asyncLockPath, this);
+ Stat stat2 = zooKeeper.getStatus(pathForWatcher, this);
if (stat2 == null) {
- if (lock != null)
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(pathForWatcher, this, WatcherType.Any,
+ true);
+
+ if (lockNodeName != null)
lostLock(LockLossReason.LOCK_DELETED);
- else if (asyncLock != null)
+ else if (createdNodeName != null)
failedToAcquireLock();
}
} catch (Exception e) {
lockWatcher.unableToMonitorLockNode(e);
- log.error("Failed to stat lock node " + asyncLockPath, e);
+ LOG.error("Failed to stat lock node " + pathForWatcher, e);
Review comment:
Fixed. Good catch.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] DomGarguilo commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
DomGarguilo commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r556043258
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -139,26 +144,66 @@ public synchronized boolean tryLock(LockWatcher lw, byte[] data)
return false;
}
+ private static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() <= 43) {
Review comment:
Does a length of 43 or less imply there is no sequence number? If so when would this be the case?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] DomGarguilo commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
DomGarguilo commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r556081735
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -139,26 +144,66 @@ public synchronized boolean tryLock(LockWatcher lw, byte[] data)
return false;
}
+ private static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() <= 43) {
Review comment:
Okay sounds good, I'll keep an eye out for the updates. One thing that I'll add is the possibility of adding this functionality within ZooReaderWriter.java instead which would give us the flexibility to use the UUID with other kinds of nodes as well. I'm not sure if we would ever need this for other nodes besides the Ephemeral Sequential nodes used for ZooLock, but just thought I would point that out in case.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r556683483
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -259,7 +304,7 @@ public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
+ final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + THIS_ZLOCK, data);
Review comment:
In the case where the ephemeral node is created on the server and that is not successfully reported back, will a second ephemeral node be created? For example could we end up with two ephemeral nodes w/ the same UUID like:
```
zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000002
zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000003
```
If so, would the 2nd one created be returned to this code and would the 1st one continue to exists?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564831691
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
Review comment:
IIRC, @EdColeman told me this. I don't have anything to back it up.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r565469435
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +151,344 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}", vmLockPrefix,
+ pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ children.sort(new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ children.forEach(c -> LOG.debug("- {}", c));
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", vmLockPrefix);
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
- }
-
- prev = child;
- }
+ } else {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}", vmLockPrefix,
+ children.get(0));
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ LOG.debug("[{}] Establishing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", vmLockPrefix);
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ vmLockPrefix, nodeToWatch);
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted", vmLockPrefix,
+ nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ LOG.debug("[{}] Renewing watch on prior node {}", vmLockPrefix, nodeToWatch);
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
- } catch (KeeperException | InterruptedException e) {
- lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
}
- }
- });
+ };
+
+ Stat stat = zooKeeper.getStatus(nodeToWatch, priorNodeWatcher);
+ if (stat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, priorNodeWatcher, WatcherType.Any,
+ true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ }
- if (stat == null)
- lockAsync(myLock, lw);
}
private void lostLock(LockLossReason reason) {
LockWatcher localLw = lockWatcher;
- lock = null;
+ lockNodeName = null;
lockWatcher = null;
localLw.lostLock(reason);
}
- public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
+ public synchronized void lock(final AccumuloLockWatcher lw, byte[] data) {
- if (lockWatcher != null || lock != null || asyncLock != null) {
+ if (lockWatcher != null || lockNodeName != null || createdNodeName != null) {
throw new IllegalStateException();
}
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
- log.trace("Ephemeral node {} created", asyncLockPath);
- Stat stat = zooKeeper.getStatus(asyncLockPath, new Watcher() {
+ final String lockPathPrefix = path + "/" + vmLockPrefix.toString();
+ // Implement recipe at https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks
+ // except that instead of the ephemeral lock node being of the form guid-lock- use lock-guid-.
+ // Another deviation from the recipe is that we cleanup any extraneous ephemeral nodes that
+ // were created.
+ final String createPath = zooKeeper.putEphemeralSequential(lockPathPrefix, data);
+ LOG.debug("[{}] Ephemeral node {} created", vmLockPrefix, createPath);
+
+ // It's possible that the call above was retried several times and multiple ephemeral nodes
+ // were created but the client missed the response for some reason. Find the ephemeral nodes
+ // with this ZLOCK_UUID and lowest sequential number.
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
+ }
+ });
Review comment:
I merged the methods that gets the children and sorts them, into one [here](https://github.com/apache/accumulo/pull/1866/files#diff-d53a0e8d1a6246f0196696217ef667f8730e51b93ffdea614d380315094e2387R176). Unexpected nodes are not added to the child set and there is a log message as to why.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r568046371
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +132,383 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}",
+ this.getZLockPrefix(), pathToDelete);
+ }
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ for (String child : children) {
+ LOG.debug("- {}", child);
+ }
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", this.getZLockPrefix());
+ }
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}",
+ this.getZLockPrefix(), children.get(0));
}
- prev = child;
- }
-
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Establishing watch on prior node {}", this.getZLockPrefix(), nodeToWatch);
+ }
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", getZLockPrefix());
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ getZLockPrefix(), nodeToWatch);
+ }
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted",
+ getZLockPrefix(), nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Renewing watch on prior node {}", getZLockPrefix(), nodeToWatch);
+ }
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
Review comment:
@EdColeman opened https://github.com/apache/accumulo/issues/1893 for this.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] EdColeman commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
EdColeman commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564534373
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -38,9 +40,13 @@
import org.slf4j.LoggerFactory;
public class ZooLock implements Watcher {
- private static final Logger log = LoggerFactory.getLogger(ZooLock.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ZooLock.class);
Review comment:
The reason that I even noticed is that I think most of the code base uses log. When I saw LOG elsewhere in this code, my mind jumped to thinking this was something different than standard logging and I then back-tracked to find the declaration. I have no issue if we want to adopt this, I'd just like to know which I should use ;-)
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +132,383 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}",
+ this.getZLockPrefix(), pathToDelete);
+ }
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ for (String child : children) {
+ LOG.debug("- {}", child);
+ }
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", this.getZLockPrefix());
+ }
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}",
+ this.getZLockPrefix(), children.get(0));
}
- prev = child;
- }
-
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Establishing watch on prior node {}", this.getZLockPrefix(), nodeToWatch);
+ }
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", getZLockPrefix());
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ getZLockPrefix(), nodeToWatch);
+ }
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted",
+ getZLockPrefix(), nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Renewing watch on prior node {}", getZLockPrefix(), nodeToWatch);
+ }
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
Review comment:
On receiving interrupt, might want to reset the interrupt flag.
`Thread.currentThread().interrupt();`
That way whatever is up the call stack that handles the exception can also know that it was interrupted.
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +132,383 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Failed to acquire lock in tryLock(), deleting all at path: {}",
+ this.getZLockPrefix(), pathToDelete);
+ }
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ /**
+ * Sort list of ephemeral nodes by their sequence number. Any ephemeral nodes that are not of the
+ * correct form will sort last.
+ *
+ * @param children
+ * list of ephemeral nodes
+ */
+ public static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() != 53 && o1.lastIndexOf('#') != 42) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() != 53 && o2.lastIndexOf('#') != 42) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = 43, rightIdx = 43;
+ return Integer.valueOf(o1.substring(leftIdx))
+ .compareTo(Integer.valueOf(o2.substring(rightIdx)));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Children nodes: {}", children.size());
+ for (String child : children) {
+ LOG.debug("- {}", child);
+ }
+ }
+ }
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ /**
+ * Given a pre-sorted set of children ephemeral nodes where the node name is of the form
+ * "zlock#UUID#sequenceNumber", find the ephemeral node that sorts before the ephemeralNode
+ * parameter with the lowest sequence number
+ *
+ * @param children
+ * list of sequential ephemera nodes, already sorted
+ * @param ephemeralNode
+ * starting node for the search
+ * @return next lowest prefix with the lowest sequence number
+ */
+ public static String findLowestPrevPrefix(final List<String> children,
+ final String ephemeralNode) {
+ int idx = children.indexOf(ephemeralNode);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
+ return lowestPrevNode;
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String createdEphemeralNode,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(createdEphemeralNode)) {
+ throw new RuntimeException(
+ "Lock attempt ephemeral node no longer exist " + createdEphemeralNode);
}
+ sortChildrenByLockPrefix(children);
- if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ if (children.get(0).equals(createdEphemeralNode)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] First candidate is my lock, acquiring", this.getZLockPrefix());
+ }
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = createdEphemeralNode;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
+ } else {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Lock held by another process with ephemeral node: {}",
+ this.getZLockPrefix(), children.get(0));
}
- prev = child;
- }
-
- final String lockToWatch = path + "/" + prev;
- log.trace("Establishing watch on {}", lockToWatch);
- Stat stat = zooKeeper.getStatus(lockToWatch, new Watcher() {
+ String lowestPrevNode = findLowestPrevPrefix(children, createdEphemeralNode);
- @Override
- public void process(WatchedEvent event) {
- if (log.isTraceEnabled()) {
- log.trace("Processing event:");
- log.trace("- type {}", event.getType());
- log.trace("- path {}", event.getPath());
- log.trace("- state {}", event.getState());
- }
- boolean renew = true;
- if (event.getType() == EventType.NodeDeleted && event.getPath().equals(lockToWatch)) {
- log.trace("Detected deletion of {}, attempting to acquire lock", lockToWatch);
- synchronized (ZooLock.this) {
- try {
- if (asyncLock != null) {
- lockAsync(myLock, lw);
- } else if (log.isTraceEnabled()) {
- log.trace("While waiting for another lock {} {} was deleted", lockToWatch, myLock);
- }
- } catch (Exception e) {
- if (lock == null) {
- // have not acquired lock yet
- lw.failedToAcquireLock(e);
+ watchingNodeName = path + "/" + lowestPrevNode;
+ final String nodeToWatch = watchingNodeName;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Establishing watch on prior node {}", this.getZLockPrefix(), nodeToWatch);
+ }
+ Watcher priorNodeWatcher = new Watcher() {
+ @Override
+ public void process(WatchedEvent event) {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("[{}] Processing event:", getZLockPrefix());
+ LOG.trace("- type {}", event.getType());
+ LOG.trace("- path {}", event.getPath());
+ LOG.trace("- state {}", event.getState());
+ }
+ boolean renew = true;
+ if (event.getType() == EventType.NodeDeleted && event.getPath().equals(nodeToWatch)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Detected deletion of prior node {}, attempting to acquire lock",
+ getZLockPrefix(), nodeToWatch);
+ }
+ synchronized (ZooLock.this) {
+ try {
+ if (createdNodeName != null) {
+ determineLockOwnership(createdEphemeralNode, lw);
+ } else if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] While waiting for another lock {}, {} was deleted",
+ getZLockPrefix(), nodeToWatch, createdEphemeralNode);
+ }
+ } catch (Exception e) {
+ if (lockNodeName == null) {
+ // have not acquired lock yet
+ lw.failedToAcquireLock(e);
+ }
}
}
+ renew = false;
}
- renew = false;
- }
- if (event.getState() == KeeperState.Expired
- || event.getState() == KeeperState.Disconnected) {
- synchronized (ZooLock.this) {
- if (lock == null) {
- lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ if (event.getState() == KeeperState.Expired
+ || event.getState() == KeeperState.Disconnected) {
+ synchronized (ZooLock.this) {
+ if (lockNodeName == null) {
+ LOG.info("Zookeeper Session expired / disconnected");
+ lw.failedToAcquireLock(new Exception("Zookeeper Session expired / disconnected"));
+ }
}
+ renew = false;
}
- renew = false;
- }
- if (renew) {
- log.trace("Renewing watch on {}", lockToWatch);
- try {
- Stat restat = zooKeeper.getStatus(lockToWatch, this);
- if (restat == null) {
- lockAsync(myLock, lw);
+ if (renew) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Renewing watch on prior node {}", getZLockPrefix(), nodeToWatch);
+ }
+ try {
+ Stat restat = zooKeeper.getStatus(nodeToWatch, this);
+ if (restat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, this, WatcherType.Any, true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ } catch (KeeperException | InterruptedException e) {
+ lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
- } catch (KeeperException | InterruptedException e) {
- lw.failedToAcquireLock(new Exception("Failed to renew watch on other master node"));
}
}
- }
- });
+ };
+
+ Stat stat = zooKeeper.getStatus(nodeToWatch, priorNodeWatcher);
+ if (stat == null) {
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just created.
+ zooKeeper.getZooKeeper().removeWatches(nodeToWatch, priorNodeWatcher, WatcherType.Any,
+ true);
+ determineLockOwnership(createdEphemeralNode, lw);
+ }
+ }
- if (stat == null)
- lockAsync(myLock, lw);
}
private void lostLock(LockLossReason reason) {
LockWatcher localLw = lockWatcher;
- lock = null;
+ lockNodeName = null;
lockWatcher = null;
localLw.lostLock(reason);
}
- public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
+ /*
+ * Exists to be overriden in tests
+ */
+ protected String getZLockPrefix() {
+ return THIS_ZLOCK_PREFIX;
+ }
+
+ public synchronized void lock(final AccumuloLockWatcher lw, byte[] data) {
- if (lockWatcher != null || lock != null || asyncLock != null) {
+ if (lockWatcher != null || lockNodeName != null || createdNodeName != null) {
throw new IllegalStateException();
}
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
- log.trace("Ephemeral node {} created", asyncLockPath);
- Stat stat = zooKeeper.getStatus(asyncLockPath, new Watcher() {
+ final String lockPathPrefix = path + "/" + getZLockPrefix();
+ // Implement recipe at https://zookeeper.apache.org/doc/current/recipes.html#sc_recipes_Locks
+ // except that instead of the ephemeral lock node being of the form guid-lock- use lock-guid-.
+ // Another deviation from the recipe is that we cleanup any extraneous ephemeral nodes that
+ // were created.
+ final String createPath = zooKeeper.putEphemeralSequential(lockPathPrefix, data);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Ephemeral node {} created", this.getZLockPrefix(), createPath);
+ }
+
+ // It's possible that the call above was retried several times and multiple ephemeral nodes
+ // were created but the client missed the response for some reason. Find the ephemeral nodes
+ // with this ZLOCK_UUID and lowest sequential number.
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
+ }
+ });
+ String lowestSequentialPath = null;
+ sortChildrenByLockPrefix(children);
+ boolean msgLoggedOnce = false;
+ for (String child : children) {
+ if (child.startsWith(getZLockPrefix())) {
+ if (null == lowestSequentialPath) {
+ if (createPath.equals(path + "/" + child)) {
+ // the path returned from create is the lowest sequential one
+ lowestSequentialPath = createPath;
+ break;
+ }
+ lowestSequentialPath = path + "/" + child;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] lowest sequential node found: {}", this.getZLockPrefix(),
+ lowestSequentialPath);
+ }
+ } else {
+ if (!msgLoggedOnce) {
+ LOG.info(
+ "[{}] Zookeeper client missed server response, multiple ephemeral child nodes created at {}",
+ this.getZLockPrefix(), lockPathPrefix);
+ msgLoggedOnce = true;
+ }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] higher sequential node found: {}, deleting it", this.getZLockPrefix(),
+ child);
+ }
+ zooKeeper.delete(path + "/" + child);
+ }
+ }
+ }
+ final String pathForWatcher = lowestSequentialPath;
+
+ // Set a watcher on the lowest sequential node that we created, this handles the case
+ // where the node we created is deleted or if this client becomes disconnected.
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Setting watcher on {}", this.getZLockPrefix(), pathForWatcher);
+ }
+ Watcher watcherForNodeWeCreated = new Watcher() {
private void failedToAcquireLock() {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] Lock deleted before acquired, setting createdNodeName {} to null",
+ getZLockPrefix(), createdNodeName);
+ }
lw.failedToAcquireLock(new Exception("Lock deleted before acquired"));
- asyncLock = null;
+ createdNodeName = null;
}
@Override
public void process(WatchedEvent event) {
synchronized (ZooLock.this) {
- if (lock != null && event.getType() == EventType.NodeDeleted
- && event.getPath().equals(path + "/" + lock)) {
+ if (lockNodeName != null && event.getType() == EventType.NodeDeleted
+ && event.getPath().equals(path + "/" + lockNodeName)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] {} was deleted", getZLockPrefix(), lockNodeName);
+ }
lostLock(LockLossReason.LOCK_DELETED);
- } else if (asyncLock != null && event.getType() == EventType.NodeDeleted
- && event.getPath().equals(path + "/" + asyncLock)) {
+ } else if (createdNodeName != null && event.getType() == EventType.NodeDeleted
+ && event.getPath().equals(path + "/" + createdNodeName)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("[{}] {} was deleted", getZLockPrefix(), createdNodeName);
+ }
failedToAcquireLock();
} else if (event.getState() != KeeperState.Disconnected
- && event.getState() != KeeperState.Expired && (lock != null || asyncLock != null)) {
- log.debug("Unexpected event watching lock node {} {}", event, asyncLockPath);
+ && event.getState() != KeeperState.Expired
+ && (lockNodeName != null || createdNodeName != null)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Unexpected event watching lock node {} {}", event, pathForWatcher);
+ }
try {
- Stat stat2 = zooKeeper.getStatus(asyncLockPath, this);
+ Stat stat2 = zooKeeper.getStatus(pathForWatcher, this);
if (stat2 == null) {
- if (lock != null)
+ // if stat is null from the zookeeper.exists(path, Watcher) call, then we just
+ // created a Watcher on a node that does not exist. Delete the watcher we just
+ // created.
+ zooKeeper.getZooKeeper().removeWatches(pathForWatcher, this, WatcherType.Any,
+ true);
+
+ if (lockNodeName != null)
lostLock(LockLossReason.LOCK_DELETED);
- else if (asyncLock != null)
+ else if (createdNodeName != null)
failedToAcquireLock();
}
} catch (Exception e) {
lockWatcher.unableToMonitorLockNode(e);
- log.error("Failed to stat lock node " + asyncLockPath, e);
+ LOG.error("Failed to stat lock node " + pathForWatcher, e);
Review comment:
LOG.error("Failed to stat lock node {}", e);
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767188215
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-763177665
I ended up renaming a bunch of variables so that I could understand what was going on. Lots of "async"-named things, but nothing asynchronous going on. The copious amount of comments were helpful too :-)
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion merged pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion merged pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r561343995
##########
File path: test/src/main/resources/log4j2-test.properties
##########
@@ -143,6 +143,6 @@ logger.35.level = info
logger.36.name = org.apache.thrift.transport.TIOStreamTransport
logger.36.level = error
-rootLogger.level = debug
+rootLogger.level = trace
Review comment:
Yes, that's true. It's definitely helpful to see what's happening in the test. I will definitely remove before a merge.
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +132,326 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ // NOTE: It's possible that we silently created more than one ephemeral
+ // node at `path` if the server response was missed by the ZK client and
+ // it retried. The other ephemeral nodes will be cleaned up when the process
+ // exits.
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.trace("[{}] Deleting all at path: {}", this.getZLockPrefix(), pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ private static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() <= 43) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() <= 43) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = o1.lastIndexOf('#');
+ int rightIdx = o2.lastIndexOf('#');
+ return o1.substring(leftIdx).compareTo(o2.substring(rightIdx));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Children nodes");
+ for (String child : children) {
+ LOG.trace("- {}", child);
+ }
}
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String myLock,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(myLock)) {
+ throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
}
+ sortChildrenByLockPrefix(children);
if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ LOG.trace("[{}] First candidate is my lock, acquiring", this.getZLockPrefix());
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = myLock;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
+ } else {
+ int idx = children.indexOf(myLock);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
Review comment:
I can move that out into it's own function. FWIW, I'm splitting my time between two projects. I wont be working on this again until the beginning of next week so you and @ctubbsii have several days to review and leave comments for me to address when I return to this. Also, I'm working on another [test](https://github.com/dlmarion/accumulo/blob/de2e5f2377f9f5679cec0581c689bb5e14d16fea/test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java#L550) that tries to lock in parallel threads.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r563857119
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +132,326 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ // NOTE: It's possible that we silently created more than one ephemeral
+ // node at `path` if the server response was missed by the ZK client and
+ // it retried. The other ephemeral nodes will be cleaned up when the process
+ // exits.
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.trace("[{}] Deleting all at path: {}", this.getZLockPrefix(), pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ private static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() <= 43) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() <= 43) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = o1.lastIndexOf('#');
+ int rightIdx = o2.lastIndexOf('#');
+ return o1.substring(leftIdx).compareTo(o2.substring(rightIdx));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Children nodes");
+ for (String child : children) {
+ LOG.trace("- {}", child);
+ }
}
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String myLock,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(myLock)) {
+ throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
}
+ sortChildrenByLockPrefix(children);
if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ LOG.trace("[{}] First candidate is my lock, acquiring", this.getZLockPrefix());
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = myLock;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
+ } else {
+ int idx = children.indexOf(myLock);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
Review comment:
@keith-turner @ctubbsii - I have made the requested changes and have added my parallel test. I have no other changes in the works.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564827329
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -38,9 +39,27 @@
import org.slf4j.LoggerFactory;
public class ZooLock implements Watcher {
- private static final Logger log = LoggerFactory.getLogger(ZooLock.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ZooLock.class);
- public static final String LOCK_PREFIX = "zlock-";
+ private static final String ZLOCK_PREFIX = "zlock#";
+ private static final String ZLOCK_UUID = UUID.randomUUID().toString();
Review comment:
That was a question that I had, should these be static? I believe we currently only have one ZooLock per VM. I left it static to generate a discussion about it. I think it's fine as is and easy enough to change in the future.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-764200297
> I will see if I can back out the variable name changes.
The name changes do add a bit of work to the review for some diffs, but it's ok w/ me to leave them as is. I like the changes and have become familiar with them.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767193103
@keith-turner That's great. I can certainly change the log level. I'll also see what I can do to suppress the multiple server response missed log messages. I'm curious why in the tserver log that the ephemeral sequential sequence number started at 4. Is it because the tserver was already running at that address before you stopped it and changed the log level?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-763103936
I think I figured it out. ZooLock.tryLock() deletes the ephemeral node that it creates if it can't grab the lock.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767234811
That last test that you did with the three fake locks that you removed one at a time was a good test. I think you will find that it mirrors my parallel test to some degree. Thanks for testing this out, that gives me some confidence that I didn't break things even though my tests are working. I have a couple of items that you mentioned above, let me know what else you find. Thanks.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564835228
##########
File path: core/src/test/java/org/apache/accumulo/fate/zookeeper/ZooLockTest.java
##########
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.accumulo.fate.zookeeper;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ZooLockTest {
+
+ @Test
+ public void testSortAndFindLowestPrevPrefix() throws Exception {
+ List<String> children = new ArrayList<>();
+ children.add("zlock#00000000-0000-0000-0000-FFFFFFFFFFFF#0000000007");
+ children.add("zlock#00000000-0000-0000-0000-EEEEEEEEEEEE#00000000010");
Review comment:
I could remove the length checks in the `sortChildrenByLockPrefix` but leave in the check for the `#` at index 42. This would allow for longer sequence numbers.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767225146
@dlmarion I ran a test w/ the manager and my modifications to zoolock, it went great.
I did the following in zkCli.sh while Accumulo was stopped to create a few fake lock nodes. This was similar to running 2 managers as you suggested, but I wanted to see what would happen w/ multiple ephemeral nodes that slowly go away. Zoolock would delete them too quickly if I started two managers.
```
[zk: localhost:2181(CONNECTED) 2] addauth digest accumulo:uno
[zk: localhost:2181(CONNECTED) 3] create -s -e /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585# accumulo:9999
Created /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000004
[zk: localhost:2181(CONNECTED) 4] create -s -e /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585# accumulo:9999
Created /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000005
[zk: localhost:2181(CONNECTED) 5] create -s -e /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585# accumulo:9999
Created /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000006
```
Then I started Accumulo and saw the following in the manager logs.
```
2021-01-25T20:23:00,947 [master.Master] INFO : trying to get master lock
2021-01-25T20:23:00,967 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Ephemeral node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000010 created
2021-01-25T20:23:00,974 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T20:23:00,974 [zookeeper.ZooLock] TRACE: - zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000004
2021-01-25T20:23:00,974 [zookeeper.ZooLock] TRACE: - zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000005
2021-01-25T20:23:00,974 [zookeeper.ZooLock] TRACE: - zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000006
2021-01-25T20:23:00,974 [zookeeper.ZooLock] TRACE: - zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000007
2021-01-25T20:23:00,975 [zookeeper.ZooLock] TRACE: - zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000008
2021-01-25T20:23:00,975 [zookeeper.ZooLock] TRACE: - zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000009
2021-01-25T20:23:00,975 [zookeeper.ZooLock] TRACE: - zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000010
2021-01-25T20:23:00,975 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] lowest sequential node found: /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000007
2021-01-25T20:23:00,975 [zookeeper.ZooLock] INFO : [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#b6820baf-762d-4078-baef-
dfbae8130606#
2021-01-25T20:23:00,975 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] higher sequential node found: zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000008, deleting it
2021-01-25T20:23:00,979 [zookeeper.ZooLock] INFO : [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#b6820baf-762d-4078-baef-
dfbae8130606#
2021-01-25T20:23:00,979 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] higher sequential node found: zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000009, deleting it
2021-01-25T20:23:00,985 [zookeeper.ZooLock] INFO : [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Zookeeper client missed server response, multiple ephemeral child nodes created at /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#b6820baf-762d-4078-baef-
dfbae8130606#
2021-01-25T20:23:00,985 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] higher sequential node found: zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000010, deleting it
2021-01-25T20:23:00,988 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Setting watcher on /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000007
2021-01-25T20:23:00,993 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T20:23:00,993 [zookeeper.ZooLock] TRACE: - zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000004
2021-01-25T20:23:00,993 [zookeeper.ZooLock] TRACE: - zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000005
2021-01-25T20:23:00,993 [zookeeper.ZooLock] TRACE: - zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000006
2021-01-25T20:23:00,993 [zookeeper.ZooLock] TRACE: - zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000007
2021-01-25T20:23:00,994 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Establishing watch on prior node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000004
```
In zkCli.sh I did the following
```
[zk: localhost:2181(CONNECTED) 6] delete /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000004
```
After that I saw the following in manager logs.
```
2021-01-25T20:24:39,724 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Processing event:
2021-01-25T20:24:39,724 [zookeeper.ZooLock] TRACE: - type NodeDeleted
2021-01-25T20:24:39,724 [zookeeper.ZooLock] TRACE: - path /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000004
2021-01-25T20:24:39,724 [zookeeper.ZooLock] TRACE: - state SyncConnected
2021-01-25T20:24:39,724 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Detected deletion of prior node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000004, attempting to acquire lock
2021-01-25T20:24:39,725 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T20:24:39,725 [zookeeper.ZooLock] TRACE: - zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000005
2021-01-25T20:24:39,725 [zookeeper.ZooLock] TRACE: - zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000006
2021-01-25T20:24:39,725 [zookeeper.ZooLock] TRACE: - zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000007
2021-01-25T20:24:39,725 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Establishing watch on prior node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000005
```
Then I did the following in zkCli.sh
```
[zk: localhost:2181(CONNECTED) 7] delete /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000005
```
Then I saw the following in the master logs.
```
2021-01-25T20:25:05,763 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Processing event:
2021-01-25T20:25:05,763 [zookeeper.ZooLock] TRACE: - type NodeDeleted
2021-01-25T20:25:05,763 [zookeeper.ZooLock] TRACE: - path /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000005
2021-01-25T20:25:05,764 [zookeeper.ZooLock] TRACE: - state SyncConnected
2021-01-25T20:25:05,764 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Detected deletion of prior node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000005, attempting to acquire lock
2021-01-25T20:25:05,764 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T20:25:05,764 [zookeeper.ZooLock] TRACE: - zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000006
2021-01-25T20:25:05,764 [zookeeper.ZooLock] TRACE: - zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000007
2021-01-25T20:25:05,764 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Establishing watch on prior node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000006
```
Then I deleted the final fake lock node I had created in zkCli.sh
```
[zk: localhost:2181(CONNECTED) 8] delete /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000006
```
After that the manager got the lock and started managing.
```
2021-01-25T20:25:30,053 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Processing event:
2021-01-25T20:25:30,053 [zookeeper.ZooLock] TRACE: - type NodeDeleted
2021-01-25T20:25:30,053 [zookeeper.ZooLock] TRACE: - path /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000006
2021-01-25T20:25:30,053 [zookeeper.ZooLock] TRACE: - state SyncConnected
2021-01-25T20:25:30,053 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] Detected deletion of prior node /accumulo/3cad24a9-53a9-4a6a-a846-ba24c5d747b9/masters/lock/zlock#d617d244-3ecc-43e6-8cc5-f140ca234585#0000000006, attempting to acquire lock
2021-01-25T20:25:30,054 [zookeeper.ZooLock] TRACE: Children nodes
2021-01-25T20:25:30,054 [zookeeper.ZooLock] TRACE: - zlock#b6820baf-762d-4078-baef-dfbae8130606#0000000007
2021-01-25T20:25:30,054 [zookeeper.ZooLock] TRACE: [zlock#b6820baf-762d-4078-baef-dfbae8130606#] First candidate is my lock, acquiring
2021-01-25T20:25:30,054 [master.Master] DEBUG: Acquired master lock
2021-01-25T20:25:30,055 [master.EventCoordinator] INFO : State changed from INITIAL to HAVE_LOCK
2021-01-25T20:25:30,092 [master.EventCoordinator] INFO : State changed from HAVE_LOCK to NORMAL
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] ctubbsii commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
ctubbsii commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-763997733
> I will see if I can back out the variable name changes.
If it's too much trouble, don't worry about it. I was just thinking it might make code review easier. I can always rename them back in my IDE if I want to minimize the diff for my own review satisfaction.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-768404276
I'm working on that right now.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] DomGarguilo commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
DomGarguilo commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r556711120
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -259,7 +304,7 @@ public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
+ final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + THIS_ZLOCK, data);
Review comment:
I think if this error occurs where the node was created but not reported, putEphemeralSequential would not return anything.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-763987527
I will see if I can back out the variable name changes.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-767196806
Yes, that's what I would expect. The ephemeral nodes that you created had the "lock" because they had a lower sequence number. It cleaned up the extra ephemeral nodes that were created by the "missed" server responses, then it put a watcher on the lowest sequence number of the prior ephemeral node.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r565443133
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -38,9 +39,27 @@
import org.slf4j.LoggerFactory;
public class ZooLock implements Watcher {
- private static final Logger log = LoggerFactory.getLogger(ZooLock.class);
+ private static final Logger LOG = LoggerFactory.getLogger(ZooLock.class);
- public static final String LOCK_PREFIX = "zlock-";
+ private static final String ZLOCK_PREFIX = "zlock#";
+ private static final String ZLOCK_UUID = UUID.randomUUID().toString();
Review comment:
I had forgot that UUID.fromString() existed until I saw it used in the update, that made it easy to use the UUID type in the test.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] ctubbsii edited a comment on pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
ctubbsii edited a comment on pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#issuecomment-768390431
> Do you have any further information?
I have a stack trace, but I'm replying on mobile at the moment and don't have a convenient way to paste it. So, I thought it'd be easier to just mention the failing test so you can try it yourself. I can post the stack trace later if you can't reproduce it.
<details>
<summary>EDIT: @dlmarion stack trace is below (was for commit f36a90d1158e5c93a2308f6fbf4246883a9b022e, so may be OBE by more recent commits):</summary>
```java
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:87)
at org.junit.Assert.assertTrue(Assert.java:42)
at org.junit.Assert.assertFalse(Assert.java:65)
at org.junit.Assert.assertFalse(Assert.java:75)
at org.apache.accumulo.test.fate.zookeeper.ZooLockIT.testDeleteWaiting(ZooLockIT.java:285)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:288)
at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:282)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.lang.Thread.run(Thread.java:834)
```
STDOUT was:
```
2021-01-27T06:27:55,424 [miniclusterImpl.MiniAccumuloClusterImpl] INFO : Starting MAC against instance miniInstance and zookeeper(s) localhost:44585.
2021-01-27T06:27:59,070 [zookeeper.ZooSession] DEBUG: Connecting to localhost:44585 with timeout 30000 with auth
2021-01-27T06:27:59,089 [common.X509Util] INFO : Setting -D jdk.tls.rejectClientInitiatedRenegotiation=true to disable client-initiated TLS renegotiation
2021-01-27T06:28:00,389 [zookeeper.ZooLock] DEBUG: [zlock#29bc7352-8de9-4704-a1e9-456afa308ace#] Ephemeral node /zltest-1523279423-l1/zlock#29bc7352-8de9-4704-a1e9-456afa308ace#0000000000 created
2021-01-27T06:28:00,397 [zookeeper.ZooLock] DEBUG: Children nodes: 1
2021-01-27T06:28:00,398 [zookeeper.ZooLock] DEBUG: - zlock#29bc7352-8de9-4704-a1e9-456afa308ace#0000000000
2021-01-27T06:28:00,398 [zookeeper.ZooLock] DEBUG: [zlock#29bc7352-8de9-4704-a1e9-456afa308ace#] Setting watcher on /zltest-1523279423-l1/zlock#29bc7352-8de9-4704-a1e9-456afa308ace#0000000000
2021-01-27T06:28:00,402 [zookeeper.ZooLock] DEBUG: Children nodes: 1
2021-01-27T06:28:00,402 [zookeeper.ZooLock] DEBUG: - zlock#29bc7352-8de9-4704-a1e9-456afa308ace#0000000000
2021-01-27T06:28:00,402 [zookeeper.ZooLock] DEBUG: [zlock#29bc7352-8de9-4704-a1e9-456afa308ace#] First candidate is my lock, acquiring...
2021-01-27T06:28:00,406 [zookeeper.ZooLock] DEBUG: [zlock#29bc7352-8de9-4704-a1e9-456afa308ace#] Ephemeral node /zltest-1523279423-l1/zlock#29bc7352-8de9-4704-a1e9-456afa308ace#0000000001 created
2021-01-27T06:28:00,408 [zookeeper.ZooLock] DEBUG: Children nodes: 2
2021-01-27T06:28:00,408 [zookeeper.ZooLock] DEBUG: - zlock#29bc7352-8de9-4704-a1e9-456afa308ace#0000000000
2021-01-27T06:28:00,408 [zookeeper.ZooLock] DEBUG: - zlock#29bc7352-8de9-4704-a1e9-456afa308ace#0000000001
2021-01-27T06:28:00,409 [zookeeper.ZooLock] DEBUG: [zlock#29bc7352-8de9-4704-a1e9-456afa308ace#] lowest sequential node found: /zltest-1523279423-l1/zlock#29bc7352-8de9-4704-a1e9-456afa308ace#0000000000
2021-01-27T06:28:00,409 [zookeeper.ZooLock] INFO : [zlock#29bc7352-8de9-4704-a1e9-456afa308ace#] Zookeeper client missed server response, multiple ephemeral child nodes created at /zltest-1523279423-l1/zlock#29bc7352-8de9-4704-a1e9-456afa308ace#
2021-01-27T06:28:00,409 [zookeeper.ZooLock] DEBUG: [zlock#29bc7352-8de9-4704-a1e9-456afa308ace#] higher sequential node found: zlock#29bc7352-8de9-4704-a1e9-456afa308ace#0000000001, deleting it
2021-01-27T06:28:00,419 [zookeeper.ZooLock] DEBUG: [zlock#29bc7352-8de9-4704-a1e9-456afa308ace#] Setting watcher on /zltest-1523279423-l1/zlock#29bc7352-8de9-4704-a1e9-456afa308ace#0000000000
2021-01-27T06:28:00,424 [zookeeper.ZooLock] DEBUG: Children nodes: 1
2021-01-27T06:28:00,424 [zookeeper.ZooLock] DEBUG: - zlock#29bc7352-8de9-4704-a1e9-456afa308ace#0000000000
2021-01-27T06:28:00,424 [zookeeper.ZooLock] DEBUG: [zlock#29bc7352-8de9-4704-a1e9-456afa308ace#] First candidate is my lock, acquiring...
```
</details>
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564859824
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +365,262 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private static final Logger LOG = LoggerFactory.getLogger(LockWorker.class);
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+ private Exception ex = null;
+
+ public LockWorker(final String parent, final String name, final CountDownLatch lockLatch,
+ final CountDownLatch lockCompletedLatch) {
+ this.parent = parent;
+ this.name = name;
+ this.getLockLatch = lockLatch;
+ this.lockCompletedLatch = lockCompletedLatch;
+ }
+
+ public void unlock() {
+ unlockLatch.countDown();
+ }
+
+ public boolean holdsLock() {
+ return lockWatcher.isLockHeld();
+ }
+
+ @Override
+ public void run() {
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try {
+ try (ZooKeeperWrapper zk =
+ new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+ zk.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ while (!watcher.isConnected()) {
+ Thread.sleep(50);
+ }
+ ZooReaderWriter zrw = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk;
+ }
+ };
+ ZooLock zl = new ZooLock(zrw, parent);
+ zl.setVMLockPrefix(new Prefix(name));
+ getLockLatch.countDown(); // signal we are done
+ getLockLatch.await(); // wait for others to finish
+ zl.lock(lockWatcher, "test1".getBytes(UTF_8)); // race to the lock
+ lockCompletedLatch.countDown();
+ unlockLatch.await();
+ zl.unlock();
+ }
+ } catch (IOException | InterruptedException | KeeperException e) {
Review comment:
Will not catch runtime exceptions, would be good to catch those.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r564860991
##########
File path: test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java
##########
@@ -306,6 +365,262 @@ public void testUnexpectedEvent() throws Exception {
}
+ @Test(timeout = 60000)
+ public void testLockSerial() throws Exception {
+ String parent = "/zlretry";
+
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try (ZooKeeperWrapper zk1 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher);
+ ZooKeeperWrapper zk2 = new ZooKeeperWrapper(getCluster().getZooKeepers(), 30000, watcher)) {
+
+ zk1.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+ zk2.addAuthInfo("digest", "accumulo:secret".getBytes(UTF_8));
+
+ while (!watcher.isConnected()) {
+ Thread.sleep(200);
+ }
+
+ // Create the parent node
+ zk1.createOnce(parent, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+
+ ZooReaderWriter zrw1 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk1;
+ }
+ };
+
+ final RetryLockWatcher zlw1 = new RetryLockWatcher();
+ final String zlPrefix1 = "zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#";
+ ZooLock zl1 = new ZooLock(zrw1, parent);
+ zl1.setVMLockPrefix(new Prefix(zlPrefix1));
+ zl1.lock(zlw1, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000
+ // zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Lastly, because zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is the first child,
+ // zl1 assumes
+ // that it has the lock.
+
+ ZooReaderWriter zrw2 = new ZooReaderWriter(getCluster().getZooKeepers(), 30000, "secret") {
+ @Override
+ public ZooKeeper getZooKeeper() {
+ return zk2;
+ }
+ };
+
+ final RetryLockWatcher zlw2 = new RetryLockWatcher();
+ final String zlPrefix2 = "zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#";
+ ZooLock zl2 = new ZooLock(zrw2, parent);
+ zl2.setVMLockPrefix(new Prefix(zlPrefix2));
+ zl2.lock(zlw2, "test1".getBytes(UTF_8));
+ // The call above creates two nodes in ZK because of the overridden create method in
+ // ZooKeeperWrapper.
+ // The nodes created are:
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002
+ // zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003
+ //
+ // ZooLock should realize this and remove the latter one and place a watcher on the first one
+ // in case
+ // the ZooKeeper ephemeral node is deleted by some external process.
+ // Because zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002 is not the first child in the
+ // list, it
+ // places a watcher on zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 so that it may
+ // try to acquire
+ // the lock when zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000 is removed.
+
+ assertTrue(zlw1.isLockHeld());
+ assertFalse(zlw2.isLockHeld());
+
+ List<String> children = zk1.getChildren(parent, false);
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000001"));
+ assertTrue(children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000002"));
+ assertFalse("this node should have been deleted",
+ children.contains("zlock#00000000-0000-0000-0000-BBBBBBBBBBBB#0000000003"));
+
+ assertNull(zl1.getWatching());
+ assertEquals("/zlretry/zlock#00000000-0000-0000-0000-AAAAAAAAAAAA#0000000000",
+ zl2.getWatching());
+
+ zl1.unlock();
+ assertFalse(zlw1.isLockHeld());
+ zk1.close();
+
+ while (!zlw2.isLockHeld()) {
+ LockSupport.parkNanos(50);
+ }
+
+ assertTrue(zlw2.isLockHeld());
+ zl2.unlock();
+ zk2.close();
+
+ }
+
+ }
+
+ static class LockWorker implements Runnable {
+
+ private static final Logger LOG = LoggerFactory.getLogger(LockWorker.class);
+
+ private final String parent;
+ private final String name;
+ private final CountDownLatch getLockLatch;
+ private final CountDownLatch lockCompletedLatch;
+ private final CountDownLatch unlockLatch = new CountDownLatch(1);
+ private final RetryLockWatcher lockWatcher = new RetryLockWatcher();
+ private Exception ex = null;
+
+ public LockWorker(final String parent, final String name, final CountDownLatch lockLatch,
+ final CountDownLatch lockCompletedLatch) {
+ this.parent = parent;
+ this.name = name;
+ this.getLockLatch = lockLatch;
+ this.lockCompletedLatch = lockCompletedLatch;
+ }
+
+ public void unlock() {
+ unlockLatch.countDown();
+ }
+
+ public boolean holdsLock() {
+ return lockWatcher.isLockHeld();
+ }
+
+ @Override
+ public void run() {
+ ConnectedWatcher watcher = new ConnectedWatcher();
+ try {
Review comment:
Can this move inside try? in case it throws exception?
```suggestion
try {
ConnectedWatcher watcher = new ConnectedWatcher();
```
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] dlmarion commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
dlmarion commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r561829969
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -123,189 +132,326 @@ public void unableToMonitorLockNode(Exception e) {
public synchronized boolean tryLock(LockWatcher lw, byte[] data)
throws KeeperException, InterruptedException {
- TryLockAsyncLockWatcher tlalw = new TryLockAsyncLockWatcher(lw);
+ LockWatcherWrapper lww = new LockWatcherWrapper(lw);
- lockAsync(tlalw, data);
+ lock(lww, data);
- if (tlalw.acquiredLock) {
+ if (lww.acquiredLock) {
return true;
}
- if (asyncLock != null) {
- zooKeeper.recursiveDelete(path + "/" + asyncLock, NodeMissingPolicy.SKIP);
- asyncLock = null;
+ // If we didn't acquire the lock, then delete the path we just created
+ // NOTE: It's possible that we silently created more than one ephemeral
+ // node at `path` if the server response was missed by the ZK client and
+ // it retried. The other ephemeral nodes will be cleaned up when the process
+ // exits.
+ if (createdNodeName != null) {
+ String pathToDelete = path + "/" + createdNodeName;
+ LOG.trace("[{}] Deleting all at path: {}", this.getZLockPrefix(), pathToDelete);
+ zooKeeper.recursiveDelete(pathToDelete, NodeMissingPolicy.SKIP);
+ createdNodeName = null;
}
return false;
}
- private synchronized void lockAsync(final String myLock, final AsyncLockWatcher lw)
- throws KeeperException, InterruptedException {
+ private static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
- if (asyncLock == null) {
- throw new IllegalStateException("Called lockAsync() when asyncLock == null");
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() <= 43) {
+ lValid = false;
+ }
+ boolean rValid = true;
+ if (o2.length() <= 43) {
+ rValid = false;
+ }
+ // Make any invalid's sort last (higher)
+ if (lValid && rValid) {
+ int leftIdx = o1.lastIndexOf('#');
+ int rightIdx = o2.lastIndexOf('#');
+ return o1.substring(leftIdx).compareTo(o2.substring(rightIdx));
+ } else if (!lValid && rValid) {
+ return 1;
+ } else if (lValid && !rValid) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ });
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("Children nodes");
+ for (String child : children) {
+ LOG.trace("- {}", child);
+ }
}
+ }
- List<String> children = zooKeeper.getChildren(path);
+ private synchronized void determineLockOwnership(final String myLock,
+ final AccumuloLockWatcher lw) throws KeeperException, InterruptedException {
- if (!children.contains(myLock)) {
- throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
+ if (createdNodeName == null) {
+ throw new IllegalStateException(
+ "Called determineLockOwnership() when ephemeralNodeName == null");
}
- Collections.sort(children);
- if (log.isTraceEnabled()) {
- log.trace("Candidate lock nodes");
- for (String child : children) {
- log.trace("- {}", child);
+ List<String> children = new ArrayList<>();
+ zooKeeper.getChildren(path).forEach(s -> {
+ if (s.startsWith(ZLOCK_PREFIX)) {
+ children.add(s);
}
+ });
+
+ if (!children.contains(myLock)) {
+ throw new RuntimeException("Lock attempt ephemeral node no longer exist " + myLock);
}
+ sortChildrenByLockPrefix(children);
if (children.get(0).equals(myLock)) {
- log.trace("First candidate is my lock, acquiring");
+ LOG.trace("[{}] First candidate is my lock, acquiring", this.getZLockPrefix());
if (!watchingParent) {
throw new IllegalStateException(
"Can not acquire lock, no longer watching parent : " + path);
}
this.lockWatcher = lw;
- this.lock = myLock;
- asyncLock = null;
+ this.lockNodeName = myLock;
+ createdNodeName = null;
lockWasAcquired = true;
lw.acquiredLock();
- return;
- }
- String prev = null;
- for (String child : children) {
- if (child.equals(myLock)) {
- break;
+ } else {
+ int idx = children.indexOf(myLock);
+ // Get the prefix from the prior ephemeral node
+ String prev = children.get(idx - 1);
+ int prefixIdx = prev.lastIndexOf('#');
+ String prevPrefix = prev.substring(0, prefixIdx);
+
+ // Find the lowest sequential ephemeral node with prevPrefix
+ int i = 2;
+ String lowestPrevNode = prev;
+ while ((idx - i) >= 0) {
+ prev = children.get(idx - i);
+ i++;
+ if (prev.startsWith(prevPrefix)) {
+ lowestPrevNode = prev;
+ } else {
+ break;
+ }
}
Review comment:
I can move that out into it's own function. FWIW, I'm splitting my time between two projects. I wont be working on this again until the beginning of next week so you and @ctubbsii have several days to review and leave comments for me to address when I return to this. Also, I'm working on another [test](https://github.com/dlmarion/accumulo/blob/de2e5f2377f9f5679cec0581c689bb5e14d16fea/test/src/main/java/org/apache/accumulo/test/fate/zookeeper/ZooLockIT.java#L550) that tries to lock in parallel threads.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] DomGarguilo commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
DomGarguilo commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r556043258
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -139,26 +144,66 @@ public synchronized boolean tryLock(LockWatcher lw, byte[] data)
return false;
}
+ private static void sortChildrenByLockPrefix(List<String> children) {
+ Collections.sort(children, new Comparator<String>() {
+ @Override
+ public int compare(String o1, String o2) {
+
+ // Lock should be of the form:
+ // zlock#UUID#sequenceNumber
+ // Example:
+ // zlock#44755fbe-1c9e-40b3-8458-03abaf950d7e#0000000000
+
+ boolean lValid = true;
+ if (o1.length() <= 43) {
Review comment:
Does a length of 43 or less imply there is no sequence number?
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [accumulo] keith-turner commented on a change in pull request #1866: Add a UUID to the server's ZooLock
Posted by GitBox <gi...@apache.org>.
keith-turner commented on a change in pull request #1866:
URL: https://github.com/apache/accumulo/pull/1866#discussion_r556701714
##########
File path: core/src/main/java/org/apache/accumulo/fate/zookeeper/ZooLock.java
##########
@@ -259,7 +304,7 @@ public synchronized void lockAsync(final AsyncLockWatcher lw, byte[] data) {
lockWasAcquired = false;
try {
- final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + LOCK_PREFIX, data);
+ final String asyncLockPath = zooKeeper.putEphemeralSequential(path + "/" + THIS_ZLOCK, data);
Review comment:
If it can occur, one option would be to change how putEphemeralSequential works. Another option is to handle multiple nodes w/ the same UUID in the child list when deciding if the lock is held. If every child less than the node id returned by putEphemeralSequential has the same UUID, then we know we have the lock.
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org