Browse Source

Merge pull request #16263 from zzzeebra/fix/zk-discovery-registration-check

Fixed partitions being lost after a ZooKeeper session expiry
pull/16333/head
Viacheslav Klimov 1 month ago
committed by GitHub
parent
commit
ab58fbce73
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 5
      common/queue/pom.xml
  2. 97
      common/queue/src/main/java/org/thingsboard/server/queue/discovery/ZkDiscoveryService.java
  3. 176
      common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceTest.java
  4. 109
      common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceZkTest.java

5
common/queue/pom.xml

@ -123,6 +123,11 @@
<artifactId>awaitility</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

97
common/queue/src/main/java/org/thingsboard/server/queue/discovery/ZkDiscoveryService.java

@ -20,7 +20,7 @@ import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.RetryForever;
import org.apache.curator.utils.CloseableUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationReadyEvent;
@ -32,12 +32,14 @@ import org.thingsboard.server.gen.transport.TransportProtos;
import org.thingsboard.server.queue.discovery.event.OtherServiceShutdownEvent;
import org.thingsboard.server.queue.util.AfterStartUp;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import static org.apache.curator.framework.recipes.cache.CuratorCacheAccessor.parentPathFilter;
@ -103,20 +105,29 @@ public class ZkDiscoveryService implements DiscoveryService {
@Override
public List<TransportProtos.ServiceInfo> getOtherServers() {
String currentServiceId = serviceInfoProvider.getServiceInfo().getServiceId();
return cache.stream()
.filter(parentPathFilter(zkNodesDir))
.filter(cd -> !cd.getPath().equals(nodePath))
.map(cd -> {
try {
return TransportProtos.ServiceInfo.parseFrom(cd.getData());
return new Registration(cd, TransportProtos.ServiceInfo.parseFrom(cd.getData()));
} catch (NoSuchElementException | InvalidProtocolBufferException e) {
log.error("Failed to decode ZK node", e);
throw new RuntimeException(e);
}
})
.filter(r -> !r.info().getServiceId().equals(currentServiceId))
.collect(Collectors.toMap(r -> r.info().getServiceId(), Function.identity(),
(a, b) -> b.data().getStat().getMtime() > a.data().getStat().getMtime() ? b : a,
LinkedHashMap::new))
.values().stream()
.map(Registration::info)
.collect(Collectors.toList());
}
private record Registration(ChildData data, TransportProtos.ServiceInfo info) {}
@Override
public boolean isMonolith() {
return false;
@ -146,21 +157,26 @@ public class ZkDiscoveryService implements DiscoveryService {
@SneakyThrows
public synchronized void publishCurrentServer() {
TransportProtos.ServiceInfo self = serviceInfoProvider.getServiceInfo();
if (currentServerExists()) {
log.trace("[{}] Updating ZK node for current instance: {}", self.getServiceId(), nodePath);
client.setData().forPath(nodePath, serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo().toByteArray());
} else {
try {
log.info("[{}] Creating ZK node for current instance", self.getServiceId());
nodePath = client.create()
.creatingParentsIfNeeded()
.withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(zkNodesDir + "/", self.toByteArray());
log.info("[{}] Created ZK node for current instance: {}", self.getServiceId(), nodePath);
client.getConnectionStateListenable().addListener(checkReconnect(self));
} catch (Exception e) {
log.error("Failed to create ZK node", e);
throw new RuntimeException(e);
switch (getCurrentServerNodeState()) {
case PRESENT -> {
log.trace("[{}] Updating ZK node for current instance: {}", self.getServiceId(), nodePath);
client.setData().forPath(nodePath, serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo().toByteArray());
}
case ABSENT -> {
try {
log.info("[{}] Creating ZK node for current instance", self.getServiceId());
nodePath = client.create()
.creatingParentsIfNeeded()
.withProtection()
.withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(zkNodesDir + "/node-", self.toByteArray());
log.info("[{}] Created ZK node for current instance: {}", self.getServiceId(), nodePath);
client.getConnectionStateListenable().addListener(checkReconnect(self));
} catch (Exception e) {
log.error("Failed to create ZK node", e);
throw new RuntimeException(e);
}
}
case UNKNOWN -> log.debug("[{}] Skipping ZK node publish, node state is unknown", self.getServiceId());
}
}
@ -177,23 +193,35 @@ public class ZkDiscoveryService implements DiscoveryService {
}
}
private boolean currentServerExists() {
private NodeState getCurrentServerNodeState() {
if (nodePath == null) {
return false;
return NodeState.ABSENT;
}
try {
TransportProtos.ServiceInfo self = serviceInfoProvider.getServiceInfo();
TransportProtos.ServiceInfo registeredServerInfo = null;
registeredServerInfo = TransportProtos.ServiceInfo.parseFrom(client.getData().forPath(nodePath));
if (self.equals(registeredServerInfo)) {
return true;
Stat stat = client.checkExists().forPath(nodePath);
if (stat == null) {
log.info("ZK node does not exist: {}", nodePath);
return NodeState.ABSENT;
}
} catch (KeeperException.NoNodeException e) {
log.info("ZK node does not exist: {}", nodePath);
long sessionId = client.getZookeeperClient().getZooKeeper().getSessionId();
if (stat.getEphemeralOwner() != sessionId) {
log.warn("ZK node {} is owned by another session 0x{}, current session 0x{}",
nodePath, Long.toHexString(stat.getEphemeralOwner()), Long.toHexString(sessionId));
return NodeState.ABSENT;
}
return NodeState.PRESENT;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.error("Interrupted while checking if ZK node exists", e);
return NodeState.UNKNOWN;
} catch (Exception e) {
log.error("Couldn't check if ZK node exists", e);
return NodeState.UNKNOWN;
}
return false;
}
private enum NodeState {
PRESENT, ABSENT, UNKNOWN
}
private ConnectionStateListener checkReconnect(TransportProtos.ServiceInfo self) {
@ -313,6 +341,14 @@ public class ZkDiscoveryService implements DiscoveryService {
String serviceId = instance.getServiceId();
ProtocolStringList serviceTypesList = instance.getServiceTypesList();
if (serviceId.equals(serviceInfoProvider.getServiceInfo().getServiceId())) {
if (type == CuratorCacheListener.Type.NODE_CREATED) {
log.error("[{}] Ignoring ZK node {} registered with the current service id. " +
"It is either a stale registration of this service or another service uses the same service id", serviceId, data.getPath());
}
return;
}
log.trace("Processing [{}] event for [{}]", type, serviceId);
switch (type) {
case NODE_CREATED:
@ -333,16 +369,19 @@ public class ZkDiscoveryService implements DiscoveryService {
}
break;
case NODE_DELETED:
if (getOtherServers().stream().anyMatch(s -> s.getServiceId().equals(serviceId))) {
log.debug("[{}] Ignoring removal of duplicate ZK node {}, service is still registered", serviceId, data.getPath());
break;
}
zkExecutorService.submit(() -> applicationEventPublisher.publishEvent(new OtherServiceShutdownEvent(this, serviceId, serviceTypesList)));
ScheduledFuture<?> future = zkExecutorService.schedule(() -> {
delayedTasks.compute(serviceId, (id, previous) -> zkExecutorService.schedule(() -> {
log.debug("[{}] Going to recalculate partitions due to removed node [{}]",
serviceId, serviceTypesList);
ScheduledFuture<?> removedTask = delayedTasks.remove(serviceId);
if (removedTask != null) {
recalculatePartitions();
}
}, recalculateDelay, TimeUnit.MILLISECONDS);
delayedTasks.put(serviceId, future);
}, recalculateDelay, TimeUnit.MILLISECONDS));
break;
default:
break;

176
common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceTest.java

@ -2,11 +2,19 @@
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.queue.discovery;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CreateBuilder;
import org.apache.curator.framework.api.ExistsBuilder;
import org.apache.curator.framework.api.SetDataBuilder;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.framework.listen.Listenable;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -17,6 +25,7 @@ import org.springframework.context.ApplicationEventPublisher;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.common.util.ThingsBoardExecutors;
import org.thingsboard.server.gen.transport.TransportProtos;
import org.thingsboard.server.queue.discovery.event.OtherServiceShutdownEvent;
import java.util.ArrayList;
import java.util.Collections;
@ -29,6 +38,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
@ -56,6 +68,8 @@ public class ZkDiscoveryServiceTest {
private List<ChildData> dataList;
private static final long RECALCULATE_DELAY = 100L;
private static final long SESSION_ID = 0x100L;
private static final long OTHER_SESSION_ID = 0x200L;
final TransportProtos.ServiceInfo currentInfo = TransportProtos.ServiceInfo.newBuilder().setServiceId("tb-rule-engine-0").build();
final ChildData currentData = new ChildData("/thingsboard/nodes/0000000010", null, currentInfo.toByteArray());
@ -66,7 +80,7 @@ public class ZkDiscoveryServiceTest {
public void setup() {
zkDiscoveryService = Mockito.spy(new ZkDiscoveryService(applicationEventPublisher, serviceInfoProvider, partitionService));
ScheduledExecutorService zkExecutorService = ThingsBoardExecutors.newSingleThreadScheduledExecutor("zk-discovery");
when(client.getState()).thenReturn(CuratorFrameworkState.STARTED);
lenient().when(client.getState()).thenReturn(CuratorFrameworkState.STARTED);
ReflectionTestUtils.setField(zkDiscoveryService, "stopped", false);
ReflectionTestUtils.setField(zkDiscoveryService, "client", client);
ReflectionTestUtils.setField(zkDiscoveryService, "cache", cache);
@ -76,11 +90,11 @@ public class ZkDiscoveryServiceTest {
ReflectionTestUtils.setField(zkDiscoveryService, "zkDir", "/thingsboard");
ReflectionTestUtils.setField(zkDiscoveryService, "zkNodesDir", "/thingsboard/nodes");
when(serviceInfoProvider.getServiceInfo()).thenReturn(currentInfo);
lenient().when(serviceInfoProvider.getServiceInfo()).thenReturn(currentInfo);
dataList = new ArrayList<>();
dataList.add(currentData);
when(cache.stream()).thenAnswer(inv -> dataList.stream());
lenient().when(cache.stream()).thenAnswer(inv -> dataList.stream());
}
@Test
@ -164,6 +178,162 @@ public class ZkDiscoveryServiceTest {
verify(partitionService, times(1)).recalculatePartitions(eq(currentInfo), eq(List.of(anotherInfo, childInfo)));
}
@Test
public void publishCurrentServerUpdatesExistingNodeTest() throws Exception {
ExistsBuilder existsBuilder = mockExistsBuilder();
when(existsBuilder.forPath(currentData.getPath())).thenReturn(statOwnedBy(SESSION_ID));
mockSessionId();
SetDataBuilder setDataBuilder = mock(SetDataBuilder.class);
when(client.setData()).thenReturn(setDataBuilder);
when(serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo()).thenReturn(currentInfo);
zkDiscoveryService.publishCurrentServer();
verify(setDataBuilder).forPath(currentData.getPath(), currentInfo.toByteArray());
verify(client, never()).create();
}
@Test
public void publishCurrentServerUpdatesNodeWithOutdatedDataTest() throws Exception {
TransportProtos.ServiceInfo updatedInfo = currentInfo.toBuilder().setReady(true).build();
when(serviceInfoProvider.getServiceInfo()).thenReturn(updatedInfo);
ExistsBuilder existsBuilder = mockExistsBuilder();
when(existsBuilder.forPath(currentData.getPath())).thenReturn(statOwnedBy(SESSION_ID));
mockSessionId();
SetDataBuilder setDataBuilder = mock(SetDataBuilder.class);
when(client.setData()).thenReturn(setDataBuilder);
when(serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo()).thenReturn(updatedInfo);
zkDiscoveryService.publishCurrentServer();
verify(setDataBuilder).forPath(currentData.getPath(), updatedInfo.toByteArray());
verify(client, never()).create();
}
@Test
public void publishCurrentServerCreatesNodeWhenAbsentTest() throws Exception {
String newPath = "/thingsboard/nodes/0000000011";
ExistsBuilder existsBuilder = mockExistsBuilder();
when(existsBuilder.forPath(currentData.getPath())).thenReturn(null);
CreateBuilder createBuilder = mock(CreateBuilder.class, RETURNS_DEEP_STUBS);
when(client.create()).thenReturn(createBuilder);
when(createBuilder.creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/thingsboard/nodes/node-", currentInfo.toByteArray()))
.thenReturn(newPath);
when(client.getConnectionStateListenable()).thenReturn(mock(Listenable.class));
zkDiscoveryService.publishCurrentServer();
assertEquals(newPath, ReflectionTestUtils.getField(zkDiscoveryService, "nodePath"));
verify(client, never()).setData();
}
@Test
public void publishCurrentServerCreatesNodeWhenExistingNodeOwnedByAnotherSessionTest() throws Exception {
String newPath = "/thingsboard/nodes/0000000011";
ExistsBuilder existsBuilder = mockExistsBuilder();
when(existsBuilder.forPath(currentData.getPath())).thenReturn(statOwnedBy(OTHER_SESSION_ID));
mockSessionId();
CreateBuilder createBuilder = mock(CreateBuilder.class, RETURNS_DEEP_STUBS);
when(client.create()).thenReturn(createBuilder);
when(createBuilder.creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/thingsboard/nodes/node-", currentInfo.toByteArray()))
.thenReturn(newPath);
when(client.getConnectionStateListenable()).thenReturn(mock(Listenable.class));
zkDiscoveryService.publishCurrentServer();
assertEquals(newPath, ReflectionTestUtils.getField(zkDiscoveryService, "nodePath"));
verify(client, never()).setData();
}
@Test
public void publishCurrentServerSkipsWhenNodeStateUnknownTest() throws Exception {
ExistsBuilder existsBuilder = mockExistsBuilder();
when(existsBuilder.forPath(currentData.getPath())).thenThrow(new InterruptedException());
zkDiscoveryService.publishCurrentServer();
assertTrue(Thread.interrupted());
assertEquals(currentData.getPath(), ReflectionTestUtils.getField(zkDiscoveryService, "nodePath"));
verify(client, never()).create();
verify(client, never()).setData();
}
@Test
public void getOtherServersIgnoresNodesWithCurrentServiceIdTest() {
dataList.add(new ChildData("/thingsboard/nodes/0000000011", statWithMtime(1), currentInfo.toByteArray()));
dataList.add(childData);
assertEquals(List.of(childInfo), zkDiscoveryService.getOtherServers());
}
@Test
public void getOtherServersKeepsLatestNodeForDuplicatedServiceIdTest() {
TransportProtos.ServiceInfo latestInfo = childInfo.toBuilder().setReady(true).build();
dataList.add(new ChildData("/thingsboard/nodes/0000000020", statWithMtime(1), childInfo.toByteArray()));
dataList.add(new ChildData("/thingsboard/nodes/0000000021", statWithMtime(2), latestInfo.toByteArray()));
assertEquals(List.of(latestInfo), zkDiscoveryService.getOtherServers());
Collections.swap(dataList, 1, 2);
assertEquals(List.of(latestInfo), zkDiscoveryService.getOtherServers());
}
@Test
public void nodeWithCurrentServiceIdDoesNotTriggerRecalculationTest() {
ChildData orphanData = new ChildData("/thingsboard/nodes/0000000011", statWithMtime(1), currentInfo.toByteArray());
startNode(orphanData);
stopNode(orphanData);
assertTrue(zkDiscoveryService.delayedTasks.isEmpty());
verify(partitionService, never()).recalculatePartitions(any(), any());
verify(applicationEventPublisher, never()).publishEvent(any(OtherServiceShutdownEvent.class));
}
@Test
public void removalOfDuplicatedNodeDoesNotPublishShutdownEventTest() {
ChildData staleData = new ChildData("/thingsboard/nodes/0000000019", statWithMtime(1), childInfo.toByteArray());
ChildData liveData = new ChildData("/thingsboard/nodes/0000000020", statWithMtime(2), childInfo.toByteArray());
startNode(staleData);
startNode(liveData);
stopNode(staleData);
assertTrue(zkDiscoveryService.delayedTasks.isEmpty());
verify(applicationEventPublisher, never()).publishEvent(any(OtherServiceShutdownEvent.class));
stopNode(liveData);
assertEquals(1, zkDiscoveryService.delayedTasks.size());
}
private ExistsBuilder mockExistsBuilder() {
ExistsBuilder existsBuilder = mock(ExistsBuilder.class);
when(client.checkExists()).thenReturn(existsBuilder);
return existsBuilder;
}
private void mockSessionId() throws Exception {
CuratorZookeeperClient zookeeperClient = mock(CuratorZookeeperClient.class);
ZooKeeper zooKeeper = mock(ZooKeeper.class);
when(client.getZookeeperClient()).thenReturn(zookeeperClient);
when(zookeeperClient.getZooKeeper()).thenReturn(zooKeeper);
when(zooKeeper.getSessionId()).thenReturn(SESSION_ID);
}
private static Stat statOwnedBy(long sessionId) {
Stat stat = new Stat();
stat.setEphemeralOwner(sessionId);
return stat;
}
private static Stat statWithMtime(long mtime) {
Stat stat = new Stat();
stat.setMtime(mtime);
return stat;
}
private void startNode(ChildData data) {
dataList.add(data);
zkDiscoveryService.onCacheEvent(NODE_CREATED, null, data);

109
common/queue/src/test/java/org/thingsboard/server/queue/discovery/ZkDiscoveryServiceZkTest.java

@ -0,0 +1,109 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.queue.discovery;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.curator.test.TestingServer;
import org.apache.curator.utils.CloseableUtils;
import org.apache.zookeeper.data.Stat;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.server.gen.transport.TransportProtos;
import java.time.Duration;
import java.util.List;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient;
@ExtendWith(MockitoExtension.class)
public class ZkDiscoveryServiceZkTest {
private static final String ZK_NODES_DIR = "/thingsboard/nodes";
private static final String PROTECTED_NODE_NAME_REGEX = "_c_[0-9a-f-]{36}-node-\\d{10}";
@Mock
private ApplicationEventPublisher applicationEventPublisher;
@Mock
private TbServiceInfoProvider serviceInfoProvider;
@Mock
private PartitionService partitionService;
private final TransportProtos.ServiceInfo currentInfo = TransportProtos.ServiceInfo.newBuilder().setServiceId("tb-core-0").build();
private TestingServer zkServer;
private CuratorFramework observer;
private ZkDiscoveryService zkDiscoveryService;
@BeforeEach
public void setup() throws Exception {
zkServer = new TestingServer(true);
observer = CuratorFrameworkFactory.newClient(zkServer.getConnectString(), new RetryOneTime(100));
observer.start();
lenient().when(serviceInfoProvider.getServiceInfo()).thenReturn(currentInfo);
lenient().when(serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo()).thenReturn(currentInfo);
zkDiscoveryService = new ZkDiscoveryService(applicationEventPublisher, serviceInfoProvider, partitionService);
ReflectionTestUtils.setField(zkDiscoveryService, "zkUrl", zkServer.getConnectString());
ReflectionTestUtils.setField(zkDiscoveryService, "zkRetryInterval", 100);
ReflectionTestUtils.setField(zkDiscoveryService, "zkConnectionTimeout", 3000);
ReflectionTestUtils.setField(zkDiscoveryService, "zkSessionTimeout", 3000);
ReflectionTestUtils.setField(zkDiscoveryService, "zkDir", "/thingsboard");
ReflectionTestUtils.setField(zkDiscoveryService, "recalculateDelay", 0L);
zkDiscoveryService.init();
zkDiscoveryService.onApplicationEvent(null);
}
@AfterEach
public void tearDown() throws Exception {
ReflectionTestUtils.invokeMethod(zkDiscoveryService, "destroy");
CloseableUtils.closeQuietly(observer);
zkServer.close();
}
@Test
public void publishCreatesSingleProtectedNodeAndExcludesItFromOtherServersTest() throws Exception {
List<String> nodes = observer.getChildren().forPath(ZK_NODES_DIR);
assertEquals(1, nodes.size());
assertTrue(nodes.get(0).matches(PROTECTED_NODE_NAME_REGEX), nodes.get(0));
assertEquals(ZK_NODES_DIR + "/" + nodes.get(0), ReflectionTestUtils.getField(zkDiscoveryService, "nodePath"));
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertTrue(zkDiscoveryService.getOtherServers().isEmpty()));
}
@Test
public void sessionExpiryLeavesSingleNodeOwnedByCurrentSessionTest() throws Exception {
String nodeBeforeExpiry = observer.getChildren().forPath(ZK_NODES_DIR).get(0);
zkDiscoveryService.getClient().getZookeeperClient().getZooKeeper().getTestable().injectSessionExpiration();
await().atMost(Duration.ofSeconds(30))
.during(Duration.ofSeconds(2))
.ignoreExceptions()
.untilAsserted(() -> {
List<String> nodes = observer.getChildren().forPath(ZK_NODES_DIR);
assertEquals(1, nodes.size());
String nodePath = ZK_NODES_DIR + "/" + nodes.get(0);
assertNotEquals(nodeBeforeExpiry, nodes.get(0));
assertEquals(nodePath, ReflectionTestUtils.getField(zkDiscoveryService, "nodePath"));
Stat stat = observer.checkExists().forPath(nodePath);
long sessionId = zkDiscoveryService.getClient().getZookeeperClient().getZooKeeper().getSessionId();
assertEquals(sessionId, stat.getEphemeralOwner());
assertTrue(zkDiscoveryService.getOtherServers().isEmpty());
});
}
}
Loading…
Cancel
Save