use of com.ibm.etcd.api.PutResponse in project etcd-java by IBM.
the class WatchTest method testResiliency.
@Test
public void testResiliency() throws Exception {
try (EtcdClient directClient = EtcdClient.forEndpoint("localhost", 2379).withPlainText().build();
EtcdClient client = EtcdClient.forEndpoint("localhost", 2396).withPlainText().build()) {
directClient.getKvClient().delete(bs("watch-tr-test/")).asPrefix().sync();
try (final LocalNettyProxy prox = new LocalNettyProxy(2396)) {
Thread proxyThread = new Thread() {
{
setDaemon(true);
}
@Override
public void run() {
try {
int N = 4;
for (int i = 1; i <= N; i++) {
prox.start();
Thread.sleep(1000L + (long) (Math.random() * 5000));
System.out.println("killing proxy " + i);
// finish in running state
if (i < N)
prox.kill();
Thread.sleep((long) (Math.random() * 4000));
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
proxyThread.start();
KvClient directKv = directClient.getKvClient();
Phaser p = new Phaser(1);
Map<ByteString, Object> watchedKeys = new ConcurrentHashMap<>();
int i = 0;
// the proxy is stopped/started
while (proxyThread.isAlive()) {
// put a key
ByteString key = bs("watch-tr-test/" + Math.random());
ByteString value = bs("value " + (i++));
PutResponse pr = directKv.put(key, value).sync();
watchedKeys.put(key, "pending");
p.register();
final int ii = i;
AtomicReference<Watch> w = new AtomicReference<>();
w.set(client.getKvClient().watch(key).startRevision(pr.getHeader().getRevision()).start((ListenerObserver<WatchUpdate>) (complete, wu, err) -> {
if (complete) {
if (err != null) {
watchedKeys.replace(key, err);
err.printStackTrace();
} else
watchedKeys.remove(key);
if (w.get() == null)
p.arrive();
} else if (!wu.getEvents().isEmpty()) {
if (value.equals(wu.getEvents().get(0).getKv().getValue())) {
if (ii % 2 == 0) {
// cancel every other watch
w.get().close();
w.set(null);
} else {
watchedKeys.remove(key);
p.arrive();
}
} else {
watchedKeys.replace(key, "unexpected watch event value");
p.arrive();
}
}
}));
Thread.sleep((long) (Math.random() * 500));
}
p.arrive();
p.awaitAdvanceInterruptibly(0, 8, TimeUnit.SECONDS);
System.out.println("created " + i + " watches; left incomplete: " + watchedKeys.size());
watchedKeys.entrySet().forEach(e -> System.out.println("** " + e.getKey().toStringUtf8() + "=" + e.getValue()));
assertTrue(watchedKeys.isEmpty());
}
}
}
Aggregations