Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@
*/
package org.sleuthkit.autopsy.coordinationservice.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.ZooKeeper;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

/**
* A utility class for coordination service and ZooKeeper. This class is in a
Expand All @@ -29,8 +33,7 @@
public final class CoordinationServiceUtils {

private static final int ZOOKEEPER_SESSION_TIMEOUT_MILLIS = 3000;
private static final int ZOOKEEPER_CONNECTION_TIMEOUT_MILLIS = 15000;


/**
* Determines if ZooKeeper is accessible with the current settings. Closes
* the connection prior to returning.
Expand All @@ -42,22 +45,28 @@ public final class CoordinationServiceUtils {
*/
public static boolean isZooKeeperAccessible(String hostName, String port) throws InterruptedException, IOException {
boolean result = false;
Object workerThreadWaitNotifyLock = new Object();
String connectString = hostName + ":" + port;
ZooKeeper zooKeeper = new ZooKeeper(connectString, ZOOKEEPER_SESSION_TIMEOUT_MILLIS,
(WatchedEvent event) -> {
synchronized (workerThreadWaitNotifyLock) {
workerThreadWaitNotifyLock.notify();
}
});
synchronized (workerThreadWaitNotifyLock) {
workerThreadWaitNotifyLock.wait(ZOOKEEPER_CONNECTION_TIMEOUT_MILLIS);
}
ZooKeeper.States state = zooKeeper.getState();
if (state == ZooKeeper.States.CONNECTED || state == ZooKeeper.States.CONNECTEDREADONLY) {
result = true;

try {

Socket socket = new Socket();
socket.connect(new InetSocketAddress(hostName, Integer.valueOf(port)), ZOOKEEPER_SESSION_TIMEOUT_MILLIS);
socket.setSoTimeout(ZOOKEEPER_SESSION_TIMEOUT_MILLIS);

OutputStream out = socket.getOutputStream();
out.write("ruok".getBytes());
out.flush();

BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = reader.readLine();

socket.close();

if (response.toLowerCase().contains("imok")) {
result = true;
}
} catch (SocketTimeoutException e) {
result = false;
}
zooKeeper.close();
return result;
}
}