diff --git a/storm-client/src/jvm/org/apache/storm/cluster/ClusterStateListener.java b/storm-client/src/jvm/org/apache/storm/cluster/ClusterStateListener.java
index f0968a14d51..dd4ad6209bb 100644
--- a/storm-client/src/jvm/org/apache/storm/cluster/ClusterStateListener.java
+++ b/storm-client/src/jvm/org/apache/storm/cluster/ClusterStateListener.java
@@ -12,6 +12,10 @@
package org.apache.storm.cluster;
+/**
+ * Listener for connection state changes of the client backing an {@link IStateStorage}.
+ */
+@FunctionalInterface
public interface ClusterStateListener {
void stateChanged(ConnectionState newState);
}
diff --git a/storm-client/src/jvm/org/apache/storm/cluster/ConnectionState.java b/storm-client/src/jvm/org/apache/storm/cluster/ConnectionState.java
index 0fa75382d7b..43a00b51188 100644
--- a/storm-client/src/jvm/org/apache/storm/cluster/ConnectionState.java
+++ b/storm-client/src/jvm/org/apache/storm/cluster/ConnectionState.java
@@ -12,8 +12,18 @@
package org.apache.storm.cluster;
+/**
+ * Connection state of a ZooKeeper client, as delivered to a {@link ClusterStateListener}.
+ */
public enum ConnectionState {
+ /** The first successful connection. */
CONNECTED,
+ /** The connection was re-established after being suspended or lost. */
RECONNECTED,
- LOST
+ /** The session is considered lost (expired or the connection timed out). */
+ LOST,
+ /** The connection was interrupted (ZooKeeper Disconnected); the session may still be alive. */
+ SUSPENDED,
+ /** Connected in read-only mode (ZooKeeper ConnectedReadOnly). */
+ READ_ONLY
}
diff --git a/storm-client/src/jvm/org/apache/storm/cluster/IStateStorage.java b/storm-client/src/jvm/org/apache/storm/cluster/IStateStorage.java
index abc35b0cf96..48bffcd17f5 100644
--- a/storm-client/src/jvm/org/apache/storm/cluster/IStateStorage.java
+++ b/storm-client/src/jvm/org/apache/storm/cluster/IStateStorage.java
@@ -15,7 +15,6 @@
import java.io.Closeable;
import java.util.List;
import org.apache.storm.callback.ZKStateChangedCallback;
-import org.apache.storm.shade.org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
/**
@@ -206,11 +205,15 @@ public interface IStateStorage extends Closeable {
void delete_worker_hb(String path);
/**
- * Add a StateStorageListener to the connection.
+ * Add a listener for connection state changes of the underlying store.
*
- * @param listener A StateStorageListener to handle changing cluster state events.
+ *
This takes Storm's own {@link ClusterStateListener}. Earlier releases took Curator's
+ * {@code ConnectionStateListener}; implementations of {@code storm.cluster.state.store} must
+ * be updated accordingly.
+ *
+ * @param listener A ClusterStateListener to handle changing cluster state events.
*/
- void add_listener(ConnectionStateListener listener);
+ void add_listener(ClusterStateListener listener);
/**
* Force consistency on a path. Any writes committed on the path before this call will be
diff --git a/storm-client/src/jvm/org/apache/storm/cluster/PaceMakerStateStorage.java b/storm-client/src/jvm/org/apache/storm/cluster/PaceMakerStateStorage.java
index ec8b061c8c2..d7ea0328e56 100644
--- a/storm-client/src/jvm/org/apache/storm/cluster/PaceMakerStateStorage.java
+++ b/storm-client/src/jvm/org/apache/storm/cluster/PaceMakerStateStorage.java
@@ -30,7 +30,6 @@
import org.apache.storm.generated.HBServerMessageType;
import org.apache.storm.pacemaker.PacemakerClientPool;
import org.apache.storm.pacemaker.PacemakerConnectionException;
-import org.apache.storm.shade.org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
import org.apache.storm.utils.Utils;
import org.apache.storm.utils.WrappedHBExecutionException;
@@ -286,7 +285,7 @@ public void delete_worker_hb(String path) {
}
@Override
- public void add_listener(ConnectionStateListener listener) {
+ public void add_listener(ClusterStateListener listener) {
stateStorage.add_listener(listener);
}
diff --git a/storm-client/src/jvm/org/apache/storm/cluster/StormClusterStateImpl.java b/storm-client/src/jvm/org/apache/storm/cluster/StormClusterStateImpl.java
index f6610eca5b3..286779dd0be 100644
--- a/storm-client/src/jvm/org/apache/storm/cluster/StormClusterStateImpl.java
+++ b/storm-client/src/jvm/org/apache/storm/cluster/StormClusterStateImpl.java
@@ -41,7 +41,6 @@
import org.apache.storm.generated.WorkerTokenServiceType;
import org.apache.storm.nimbus.NimbusInfo;
import org.apache.storm.shade.org.apache.commons.lang3.StringUtils;
-import org.apache.storm.shade.org.apache.curator.framework.state.ConnectionState;
import org.apache.storm.shade.org.apache.zookeeper.KeeperException;
import org.apache.storm.shade.org.apache.zookeeper.Watcher;
import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
@@ -296,10 +295,10 @@ public List nimbuses() {
public void addNimbusHost(final String nimbusId, final NimbusSummary nimbusSummary) {
// explicit delete for ephmeral node to ensure this session creates the entry.
stateStorage.delete_node(ClusterUtils.nimbusPath(nimbusId));
- stateStorage.add_listener((curatorFramework, connectionState) -> {
+ stateStorage.add_listener(connectionState -> {
LOG.info("Connection state listener invoked, zookeeper connection state has changed "
+ "to {}", connectionState);
- if (connectionState.equals(ConnectionState.RECONNECTED)) {
+ if (connectionState == ConnectionState.RECONNECTED) {
LOG.info("Connection state has changed to reconnected so setting nimbuses entry "
+ "one more time");
// explicit delete for ephemeral node to ensure this session creates the entry.
diff --git a/storm-client/src/jvm/org/apache/storm/cluster/ZKStateStorage.java b/storm-client/src/jvm/org/apache/storm/cluster/ZKStateStorage.java
index 102702fd03e..53d2011efe9 100644
--- a/storm-client/src/jvm/org/apache/storm/cluster/ZKStateStorage.java
+++ b/storm-client/src/jvm/org/apache/storm/cluster/ZKStateStorage.java
@@ -27,14 +27,13 @@
import org.apache.storm.callback.DefaultWatcherCallBack;
import org.apache.storm.callback.WatcherCallBack;
import org.apache.storm.callback.ZKStateChangedCallback;
-import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
-import org.apache.storm.shade.org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.storm.shade.org.apache.zookeeper.CreateMode;
import org.apache.storm.shade.org.apache.zookeeper.KeeperException;
import org.apache.storm.shade.org.apache.zookeeper.Watcher;
import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
import org.apache.storm.utils.Utils;
import org.apache.storm.zookeeper.ClientZookeeper;
+import org.apache.storm.zookeeper.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -45,8 +44,8 @@ public class ZKStateStorage implements IStateStorage {
private ConcurrentHashMap callbacks =
new ConcurrentHashMap();
- private CuratorFramework zkWriter;
- private CuratorFramework zkReader;
+ private ZkClient zkWriter;
+ private ZkClient zkReader;
private AtomicBoolean active;
private boolean isNimbus;
@@ -62,7 +61,7 @@ public ZKStateStorage(Map conf, Map authConf,
}
// just mkdir STORM_ZOOKEEPER_ROOT dir
- CuratorFramework zkTemp = mkZk(context.getDaemonType());
+ ZkClient zkTemp = mkZk(context.getDaemonType());
String rootPath = String.valueOf(conf.get(Config.STORM_ZOOKEEPER_ROOT));
ClientZookeeper.mkdirs(zkTemp, rootPath, context.getDefaultZkAcls());
zkTemp.close();
@@ -78,14 +77,14 @@ public ZKStateStorage(Map conf, Map authConf,
}
@SuppressWarnings("unchecked")
- private CuratorFramework mkZk(DaemonType type) {
+ private ZkClient mkZk(DaemonType type) {
return ClientZookeeper.mkClient(conf, (List) conf
.get(Config.STORM_ZOOKEEPER_SERVERS),
conf.get(Config.STORM_ZOOKEEPER_PORT), "", new DefaultWatcherCallBack(), authConf, type);
}
@SuppressWarnings("unchecked")
- private CuratorFramework mkZk(WatcherCallBack watcher,
+ private ZkClient mkZk(WatcherCallBack watcher,
DaemonType type) throws NumberFormatException {
return ClientZookeeper.mkClient(conf, (List) conf
.get(Config.STORM_ZOOKEEPER_SERVERS),
@@ -225,10 +224,8 @@ public void delete_worker_hb(String path) {
}
@Override
- public void add_listener(final ConnectionStateListener listener) {
- ClientZookeeper.addListener(zkReader,
- (curatorFramework, connectionState) -> listener.stateChanged(curatorFramework,
- connectionState));
+ public void add_listener(ClusterStateListener listener) {
+ ClientZookeeper.addListener(zkReader, listener);
}
@Override
diff --git a/storm-client/src/jvm/org/apache/storm/trident/topology/state/TestTransactionalState.java b/storm-client/src/jvm/org/apache/storm/trident/topology/state/TestTransactionalState.java
index cae188d3259..f212484db81 100644
--- a/storm-client/src/jvm/org/apache/storm/trident/topology/state/TestTransactionalState.java
+++ b/storm-client/src/jvm/org/apache/storm/trident/topology/state/TestTransactionalState.java
@@ -14,9 +14,9 @@
import java.util.List;
import java.util.Map;
-import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
import org.apache.storm.shade.org.apache.zookeeper.CreateMode;
import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
+import org.apache.storm.zookeeper.ZkClient;
/**
* Facilitates testing of non-public methods in the parent class.
@@ -30,9 +30,9 @@ protected TestTransactionalState(Map conf, String id, String sub
super(conf, id, subroot);
}
- public static void createNode(CuratorFramework curator,
+ public static void createNode(ZkClient zk,
String rootDir, byte[] data, List acls, CreateMode mode)
throws Exception {
- TransactionalState.createNode(curator, rootDir, data, acls, mode);
+ TransactionalState.createNode(zk, rootDir, data, acls, mode);
}
}
diff --git a/storm-client/src/jvm/org/apache/storm/trident/topology/state/TransactionalState.java b/storm-client/src/jvm/org/apache/storm/trident/topology/state/TransactionalState.java
index c98028d8420..e66e32883cb 100644
--- a/storm-client/src/jvm/org/apache/storm/trident/topology/state/TransactionalState.java
+++ b/storm-client/src/jvm/org/apache/storm/trident/topology/state/TransactionalState.java
@@ -21,27 +21,25 @@
import org.apache.storm.cluster.DaemonType;
import org.apache.storm.shade.net.minidev.json.JSONValue;
import org.apache.storm.shade.net.minidev.json.parser.ParseException;
-import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
-import org.apache.storm.shade.org.apache.curator.framework.api.PathAndBytesable;
-import org.apache.storm.shade.org.apache.curator.framework.api.ProtectACLCreateModePathAndBytesable;
import org.apache.storm.shade.org.apache.zookeeper.CreateMode;
import org.apache.storm.shade.org.apache.zookeeper.KeeperException;
import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
-import org.apache.storm.utils.CuratorUtils;
import org.apache.storm.utils.Utils;
-import org.apache.storm.utils.ZookeeperAuthInfo;
+import org.apache.storm.zookeeper.ClientZookeeper;
+import org.apache.storm.zookeeper.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class that contains the logic to extract the transactional state info from zookeeper. All
* transactional state is kept in zookeeper. This
- * class only contains references to Curator, which is used to get all info from zookeeper.
+ * class only contains references to a {@link ZkClient}, which is used to get all info from
+ * zookeeper.
*/
public class TransactionalState {
private static final Logger LOG = LoggerFactory.getLogger(TransactionalState.class);
- CuratorFramework curator;
+ ZkClient zkClient;
List zkAcls = null;
protected TransactionalState(Map conf, String id, String subroot) {
@@ -54,9 +52,8 @@ protected TransactionalState(Map conf, String id, String subroot
Config.STORM_ZOOKEEPER_SERVERS);
Object port = getWithBackup(conf, Config.TRANSACTIONAL_ZOOKEEPER_PORT,
Config.STORM_ZOOKEEPER_PORT);
- ZookeeperAuthInfo auth = new ZookeeperAuthInfo(conf);
- CuratorFramework initter = CuratorUtils.newCuratorStarted(conf, servers, port, auth,
- DaemonType.WORKER.getDefaultZkAcls(conf));
+ ZkClient initter = ClientZookeeper.mkClient(conf, servers, port, "", null, conf,
+ DaemonType.WORKER);
zkAcls = Utils.getWorkerACL(conf);
try {
TransactionalState.createNode(initter, transactionalRoot, null, null, null);
@@ -70,8 +67,8 @@ protected TransactionalState(Map conf, String id, String subroot
}
initter.close();
- curator = CuratorUtils.newCuratorStarted(conf, servers, port, rootDir, auth,
- DaemonType.WORKER.getDefaultZkAcls(conf));
+ zkClient = ClientZookeeper.mkClient(conf, servers, port, rootDir, null, conf,
+ DaemonType.WORKER);
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -85,30 +82,31 @@ public static TransactionalState newCoordinatorState(Map conf, S
return new TransactionalState(conf, id, "coordinator");
}
- protected static String forPath(PathAndBytesable builder,
- String path, byte[] data) throws Exception {
- return (data == null)
- ? builder.forPath(path)
- : builder.forPath(path, data);
- }
-
- protected static void createNode(CuratorFramework curator, String path,
+ /**
+ * Create a node, and any missing parents.
+ *
+ * {@code mode} is only honoured when {@code acls} is {@code null}; when {@code acls} is
+ * given, or {@code mode} is {@code null}, the node is created {@link CreateMode#PERSISTENT}.
+ * When {@code data} is {@code null} the client's default payload is stored.
+ *
+ * @param zk the client to use
+ * @param path the path of the node
+ * @param data the data to store, or {@code null} for the client's default payload
+ * @param acls the ACL of the node, or {@code null} for the client's default ACL
+ * @param mode the create mode, see above
+ * @throws Exception on failure, ZooKeeper exceptions unwrapped
+ */
+ protected static void createNode(ZkClient zk, String path,
byte[] data, List acls, CreateMode mode) throws Exception {
- ProtectACLCreateModePathAndBytesable builder =
- curator.create().creatingParentsIfNeeded();
LOG.debug("Creating node [path = {}], [data = {}], [acls = {}], [mode = {}]", path,
asString(data), acls, mode);
- if (acls == null) {
- if (mode == null) {
- TransactionalState.forPath(builder, path, data);
- } else {
- TransactionalState.forPath(builder.withMode(mode), path, data);
- }
- return;
+ CreateMode effectiveMode = (acls == null && mode != null) ? mode : CreateMode.PERSISTENT;
+ if (data == null) {
+ zk.createWithDefaultData(path, effectiveMode, acls, true);
+ } else {
+ zk.create(path, data, effectiveMode, acls, true);
}
-
- TransactionalState.forPath(builder.withACL(acls), path, data);
}
private static String asString(byte[] data) {
@@ -124,10 +122,10 @@ public void setData(String path, Object obj) {
throw new RuntimeException(e);
}
try {
- if (curator.checkExists().forPath(path) != null) {
- curator.setData().forPath(path, ser);
+ if (zkClient.exists(path, false) != null) {
+ zkClient.setData(path, ser);
} else {
- TransactionalState.createNode(curator, path, ser, zkAcls,
+ TransactionalState.createNode(zkClient, path, ser, zkAcls,
CreateMode.PERSISTENT);
}
} catch (KeeperException.NodeExistsException nne) {
@@ -140,7 +138,7 @@ public void setData(String path, Object obj) {
public void delete(String path) {
path = "/" + path;
try {
- curator.delete().forPath(path);
+ zkClient.delete(path, false);
} catch (KeeperException.NoNodeException nne) {
LOG.warn("Path {} already deleted.", path);
} catch (Exception e) {
@@ -153,10 +151,10 @@ public List list(String path) {
path = "/" + path;
try {
List children;
- if (curator.checkExists().forPath(path) == null) {
+ if (zkClient.exists(path, false) == null) {
children = new ArrayList<>();
} else {
- children = curator.getChildren().forPath(path);
+ children = zkClient.getChildren(path, false);
}
LOG.debug("List [path = {}], [children = {}]", path, children);
return children;
@@ -173,12 +171,12 @@ public Object getData(String path) {
path = "/" + path;
try {
Object data;
- if (curator.checkExists().forPath(path) != null) {
+ if (zkClient.exists(path, false) != null) {
// Use parseWithException instead of parse so we can capture deserialization errors
// in the log.
// They are likely to be bugs in the spout code.
try {
- data = JSONValue.parseWithException(new String(curator.getData().forPath(path),
+ data = JSONValue.parseWithException(new String(zkClient.getData(path, false, null),
"UTF-8"));
} catch (ParseException e) {
LOG.warn("Failed to deserialize zookeeper data for path {}", path, e);
@@ -195,7 +193,7 @@ public Object getData(String path) {
}
public void close() {
- curator.close();
+ zkClient.close();
}
private Object getWithBackup(Map amap, String primary, String backup) {
diff --git a/storm-client/src/jvm/org/apache/storm/utils/StormBoundedExponentialBackoffRetry.java b/storm-client/src/jvm/org/apache/storm/utils/StormBoundedExponentialBackoffRetry.java
index 47790b8d943..ee5c739d651 100644
--- a/storm-client/src/jvm/org/apache/storm/utils/StormBoundedExponentialBackoffRetry.java
+++ b/storm-client/src/jvm/org/apache/storm/utils/StormBoundedExponentialBackoffRetry.java
@@ -13,14 +13,22 @@
package org.apache.storm.utils;
import java.util.Random;
-import org.apache.storm.shade.org.apache.curator.retry.BoundedExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class StormBoundedExponentialBackoffRetry extends BoundedExponentialBackoffRetry {
+/**
+ * Exponential-then-linear backoff calculator with jitter, used for ZooKeeper, Netty, Thrift and
+ * Pacemaker reconnects.
+ *
+ * This class does not depend on any ZooKeeper client library. In earlier releases it extended
+ * Curator's {@code BoundedExponentialBackoffRetry}; it no longer is a Curator {@code RetryPolicy}.
+ */
+public class StormBoundedExponentialBackoffRetry {
private static final Logger LOG = LoggerFactory
.getLogger(StormBoundedExponentialBackoffRetry.class);
private final Random random = new Random();
+ private final int baseSleepTimeMs;
+ private final int maxSleepTimeMs;
private final int linearBaseSleepMs;
private final int stepSize;
private int expRetriesThreshold;
@@ -36,7 +44,8 @@ public class StormBoundedExponentialBackoffRetry extends BoundedExponentialBacko
*/
public StormBoundedExponentialBackoffRetry(int baseSleepTimeMs, int maxSleepTimeMs,
int maxRetries) {
- super(baseSleepTimeMs, maxSleepTimeMs, maxRetries);
+ this.baseSleepTimeMs = baseSleepTimeMs;
+ this.maxSleepTimeMs = maxSleepTimeMs;
expRetriesThreshold = 1;
while ((1 << (expRetriesThreshold + 1)) < ((maxSleepTimeMs - baseSleepTimeMs) / 2)) {
expRetriesThreshold++;
@@ -54,20 +63,34 @@ public StormBoundedExponentialBackoffRetry(int baseSleepTimeMs, int maxSleepTime
} else {
this.stepSize = 1;
}
- this.linearBaseSleepMs = super.getBaseSleepTimeMs() + (1 << expRetriesThreshold);
+ this.linearBaseSleepMs = this.baseSleepTimeMs + (1 << expRetriesThreshold);
+ }
+
+ public int getBaseSleepTimeMs() {
+ return baseSleepTimeMs;
}
- @Override
+ public int getMaxSleepTimeMs() {
+ return maxSleepTimeMs;
+ }
+
+ /**
+ * Compute the time to sleep before the given retry.
+ *
+ * @param retryCount the number of retries already attempted (0 based)
+ * @param elapsedTimeMs elapsed time since the first attempt (unused)
+ * @return the time to sleep in milliseconds
+ */
public long getSleepTimeMs(int retryCount, long elapsedTimeMs) {
if (retryCount < expRetriesThreshold) {
int exp = 1 << retryCount;
int jitter = random.nextInt(exp);
- long sleepTimeMs = super.getBaseSleepTimeMs() + exp + jitter;
+ long sleepTimeMs = baseSleepTimeMs + exp + jitter;
LOG.debug("WILL SLEEP FOR {}ms (NOT MAX)", sleepTimeMs);
return sleepTimeMs;
} else {
int stepJitter = random.nextInt(stepSize);
- long sleepTimeMs = Math.min(super.getMaxSleepTimeMs(), (linearBaseSleepMs
+ long sleepTimeMs = Math.min(maxSleepTimeMs, (linearBaseSleepMs
+ (stepSize * (retryCount - expRetriesThreshold)) + stepJitter));
LOG.debug("WILL SLEEP FOR {}ms (MAX)", sleepTimeMs);
return sleepTimeMs;
diff --git a/storm-client/src/jvm/org/apache/storm/zookeeper/ClientZookeeper.java b/storm-client/src/jvm/org/apache/storm/zookeeper/ClientZookeeper.java
index be53a8aa230..a3ce0579247 100644
--- a/storm-client/src/jvm/org/apache/storm/zookeeper/ClientZookeeper.java
+++ b/storm-client/src/jvm/org/apache/storm/zookeeper/ClientZookeeper.java
@@ -22,19 +22,16 @@
import java.util.List;
import java.util.Map;
import org.apache.storm.callback.WatcherCallBack;
+import org.apache.storm.cluster.ClusterStateListener;
import org.apache.storm.cluster.DaemonType;
import org.apache.storm.cluster.VersionedData;
-import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
-import org.apache.storm.shade.org.apache.curator.framework.api.CuratorEventType;
-import org.apache.storm.shade.org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.storm.shade.org.apache.zookeeper.CreateMode;
import org.apache.storm.shade.org.apache.zookeeper.KeeperException;
-import org.apache.storm.shade.org.apache.zookeeper.WatchedEvent;
import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
import org.apache.storm.shade.org.apache.zookeeper.data.Stat;
-import org.apache.storm.utils.CuratorUtils;
import org.apache.storm.utils.Utils;
import org.apache.storm.utils.ZookeeperAuthInfo;
+import org.apache.storm.zookeeper.curator.CuratorUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -66,11 +63,24 @@ public static void resetInstance() {
_instance = INSTANCE;
}
- public static void mkdirs(CuratorFramework zk, String path, List acls) {
+ public static void mkdirs(ZkClient zk, String path, List acls) {
_instance.mkdirsImpl(zk, path, acls);
}
- public static CuratorFramework mkClient(Map conf, List servers,
+ /**
+ * Create and start a ZooKeeper client.
+ *
+ * @param conf the Storm configuration (timeouts, retries, TLS)
+ * @param servers the ZooKeeper servers
+ * @param port the ZooKeeper port
+ * @param root the chroot, {@code ""} for none
+ * @param watcher receives events of watches set through the client; may be {@code null}, in
+ * which case watch events are dropped
+ * @param authConf configuration holding the ZooKeeper authentication, may be {@code null}
+ * @param type the daemon type, which determines the client's default ACL
+ * @return the started client
+ */
+ public static ZkClient mkClient(Map conf, List servers,
Object port,
String root, final WatcherCallBack watcher, Map authConf, DaemonType type) {
return _instance.mkClientImpl(conf, servers, port, root, watcher, authConf, type);
@@ -78,7 +88,7 @@ public static CuratorFramework mkClient(Map conf, List s
// Deletes the state inside the zookeeper for a key, for which the
// contents of the key starts with nimbus host port information
- public static void deleteNodeBlobstore(CuratorFramework zk, String parentPath,
+ public static void deleteNodeBlobstore(ZkClient zk, String parentPath,
String hostPortInfo) {
String normalizedParentPath = normalizePath(parentPath);
List childPathList = null;
@@ -93,20 +103,19 @@ public static void deleteNodeBlobstore(CuratorFramework zk, String parentPath,
}
}
- public static String createNode(CuratorFramework zk, String path, byte[] data, CreateMode mode,
+ public static String createNode(ZkClient zk, String path, byte[] data, CreateMode mode,
List acls) {
String ret = null;
try {
String npath = normalizePath(path);
- ret = zk.create().creatingParentsIfNeeded().withMode(mode).withACL(acls).forPath(npath,
- data);
+ ret = zk.create(npath, data, mode, acls, true);
} catch (Exception e) {
throw Utils.wrapInRuntime(e);
}
return ret;
}
- public static String createNode(CuratorFramework zk, String path, byte[] data, List acls) {
+ public static String createNode(ZkClient zk, String path, byte[] data, List acls) {
return createNode(zk, path, data, CreateMode.PERSISTENT, acls);
}
@@ -139,25 +148,21 @@ public static String normalizePath(String path) {
return rtn;
}
- public static boolean existsNode(CuratorFramework zk, String path, boolean watch) {
+ public static boolean existsNode(ZkClient zk, String path, boolean watch) {
Stat stat = null;
try {
- if (watch) {
- stat = zk.checkExists().watched().forPath(normalizePath(path));
- } else {
- stat = zk.checkExists().forPath(normalizePath(path));
- }
+ stat = zk.exists(normalizePath(path), watch);
} catch (Exception e) {
throw Utils.wrapInRuntime(e);
}
return stat != null;
}
- public static void deleteNode(CuratorFramework zk, String path) {
+ public static void deleteNode(ZkClient zk, String path) {
try {
String npath = normalizePath(path);
if (existsNode(zk, npath, false)) {
- zk.delete().deletingChildrenIfNeeded().forPath(normalizePath(path));
+ zk.delete(normalizePath(path), true);
}
} catch (Exception e) {
if (Utils.exceptionCauseIsInstanceOf(KeeperException.NoNodeException.class, e)) {
@@ -178,54 +183,41 @@ public static String parentPath(String path) {
return toksToPath(toks);
}
- public static boolean exists(CuratorFramework zk, String path, boolean watch) {
+ public static boolean exists(ZkClient zk, String path, boolean watch) {
return existsNode(zk, path, watch);
}
- public static Stat setData(CuratorFramework zk, String path, byte[] data) {
+ public static Stat setData(ZkClient zk, String path, byte[] data) {
try {
String npath = normalizePath(path);
- return zk.setData().forPath(npath, data);
+ return zk.setData(npath, data);
} catch (Exception e) {
throw Utils.wrapInRuntime(e);
}
}
- public static Integer getVersion(CuratorFramework zk, String path,
+ public static Integer getVersion(ZkClient zk, String path,
boolean watch) throws Exception {
String npath = normalizePath(path);
- // checkExists returns the Stat directly (null when absent) and still arms the watch when
- // watch is true. request 1.
- Stat stat;
- if (watch) {
- stat = zk.checkExists().watched().forPath(npath);
- } else {
- stat = zk.checkExists().forPath(npath); // request 2.
- }
+ // exists returns the Stat directly (null when absent) and still arms the watch when
+ // watch is true.
+ Stat stat = zk.exists(npath, watch);
return stat == null ? null : Integer.valueOf(stat.getVersion());
}
- public static List getChildren(CuratorFramework zk, String path, boolean watch) {
+ public static List getChildren(ZkClient zk, String path, boolean watch) {
try {
String npath = normalizePath(path);
- if (watch) {
- return zk.getChildren().watched().forPath(npath);
- } else {
- return zk.getChildren().forPath(npath);
- }
+ return zk.getChildren(npath, watch);
} catch (Exception e) {
throw Utils.wrapInRuntime(e);
}
}
- public static byte[] getData(CuratorFramework zk, String path, boolean watch) {
+ public static byte[] getData(ZkClient zk, String path, boolean watch) {
String npath = normalizePath(path);
try {
- if (watch) {
- return zk.getData().watched().forPath(npath);
- } else {
- return zk.getData().forPath(npath);
- }
+ return zk.getData(npath, watch, null);
} catch (Exception e) {
if (Utils.exceptionCauseIsInstanceOf(KeeperException.NoNodeException.class, e)) {
// Node is absent. A watcher can notify when the node is announced.
@@ -246,18 +238,13 @@ public static byte[] getData(CuratorFramework zk, String path, boolean watch) {
* @param watch should a watch be enabled
* @return null if no data is found, else the data with the version.
*/
- public static VersionedData getDataWithVersion(CuratorFramework zk, String path,
+ public static VersionedData getDataWithVersion(ZkClient zk, String path,
boolean watch) {
VersionedData data = null;
String npath = normalizePath(path);
Stat stats = new Stat();
try {
- byte[] bytes;
- if (watch) {
- bytes = zk.getData().storingStatIn(stats).watched().forPath(npath);
- } else {
- bytes = zk.getData().storingStatIn(stats).forPath(npath);
- }
+ byte[] bytes = zk.getData(npath, watch, stats);
if (bytes != null) {
data = new VersionedData<>(stats.getVersion(), bytes);
}
@@ -275,19 +262,19 @@ public static VersionedData getDataWithVersion(CuratorFramework zk, Stri
return data;
}
- public static void addListener(CuratorFramework zk, ConnectionStateListener listener) {
- zk.getConnectionStateListenable().addListener(listener);
+ public static void addListener(ZkClient zk, ClusterStateListener listener) {
+ zk.addConnectionStateListener(listener);
}
- public static void syncPath(CuratorFramework zk, String path) {
+ public static void syncPath(ZkClient zk, String path) {
try {
- zk.sync().forPath(normalizePath(path));
+ zk.sync(normalizePath(path));
} catch (Exception e) {
throw Utils.wrapInRuntime(e);
}
}
- public void mkdirsImpl(CuratorFramework zk, String path, List acls) {
+ public void mkdirsImpl(ZkClient zk, String path, List acls) {
String npath = ClientZookeeper.normalizePath(path);
if (npath.equals("/")) {
return;
@@ -306,26 +293,12 @@ public void mkdirsImpl(CuratorFramework zk, String path, List acls) {
}
}
- public CuratorFramework mkClientImpl(Map conf, List servers,
+ public ZkClient mkClientImpl(Map conf, List servers,
Object port, String root,
final WatcherCallBack watcher, Map authConf, DaemonType type) {
- CuratorFramework fk;
- if (authConf != null) {
- fk = CuratorUtils.newCurator(conf, servers, port, root, new ZookeeperAuthInfo(authConf),
- type.getDefaultZkAcls(conf));
- } else {
- fk = CuratorUtils.newCurator(conf, servers, port, root, null, type
- .getDefaultZkAcls(conf));
- }
-
- fk.getCuratorListenable().addListener((unused, e) -> {
- if (e.getType().equals(CuratorEventType.WATCHED)) {
- WatchedEvent event = e.getWatchedEvent();
- watcher.execute(event.getState(), event.getType(), event.getPath());
- }
- });
+ ZookeeperAuthInfo auth = authConf != null ? new ZookeeperAuthInfo(authConf) : null;
LOG.info("Starting ZK Curator");
- fk.start();
- return fk;
+ return CuratorUtils.newClient(conf, servers, port, root, auth, type.getDefaultZkAcls(conf),
+ watcher);
}
}
diff --git a/storm-client/src/jvm/org/apache/storm/zookeeper/ZkClient.java b/storm-client/src/jvm/org/apache/storm/zookeeper/ZkClient.java
new file mode 100644
index 00000000000..268016e77f0
--- /dev/null
+++ b/storm-client/src/jvm/org/apache/storm/zookeeper/ZkClient.java
@@ -0,0 +1,186 @@
+/*
+ * 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.storm.zookeeper;
+
+import java.util.List;
+import org.apache.storm.cluster.ClusterStateListener;
+import org.apache.storm.shade.org.apache.zookeeper.CreateMode;
+import org.apache.storm.shade.org.apache.zookeeper.KeeperException;
+import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
+import org.apache.storm.shade.org.apache.zookeeper.data.Stat;
+
+/**
+ * A Storm-owned handle to a started ZooKeeper session.
+ *
+ * This is the type Storm uses in its public and protected APIs wherever a ZooKeeper client is
+ * passed around. It deliberately exposes only the operations Storm itself needs, and each method is
+ * named after the native ZooKeeper call it maps to, so the implementation can be swapped without
+ * touching callers. Instances are obtained from
+ * {@link ClientZookeeper#mkClient(java.util.Map, List, Object, String,
+ * org.apache.storm.callback.WatcherCallBack, java.util.Map, org.apache.storm.cluster.DaemonType)}.
+ *
+ *
Contract that every implementation must honour:
+ *
+ * - Paths are absolute and relative to the chroot the client was created with. The
+ * client does not normalize them; callers such as {@link ClientZookeeper} do.
+ * - Exceptions: ZooKeeper {@link KeeperException} subclasses (for example
+ * {@link KeeperException.NoNodeException} and {@link KeeperException.NodeExistsException})
+ * propagate unwrapped, so callers may catch them directly.
+ * - Watches: {@code watch == true} registers a one-shot ZooKeeper watch whose events
+ * are delivered to the {@link org.apache.storm.callback.WatcherCallBack} the client was created
+ * with. If the client was created without a callback, events are dropped.
+ * - ACLs: {@code acls == null} means the client's default ACL, which is the
+ * {@link org.apache.storm.cluster.DaemonType} default ACL given at creation, or
+ * {@code OPEN_ACL_UNSAFE} when that is {@code null}. Parent nodes created because
+ * {@code createParents == true} always get the client's default ACL, never the ACL passed to
+ * the call.
+ * - Retries: operations block until the session is connected and are retried on
+ * connection loss according to the configured
+ * {@link org.apache.storm.utils.StormBoundedExponentialBackoffRetry} parameters
+ * ({@code storm.zookeeper.retry.interval},
+ * {@code storm.zookeeper.retry.intervalceiling.millis},
+ * {@code storm.zookeeper.retry.times}).
+ * - Sync: {@link #sync(String)} is asynchronous (fire-and-forget) and does not wait
+ * for the sync to complete.
+ * - Default data: {@link #createWithDefaultData(String, CreateMode, List, boolean)}
+ * writes the client's default payload, which is the bytes of
+ * {@code InetAddress.getLocalHost().getHostAddress()}. This is distinct from
+ * {@link #create(String, byte[], CreateMode, List, boolean)} with {@code data == null}, which
+ * stores no data.
+ *
+ */
+public interface ZkClient extends AutoCloseable {
+
+ /**
+ * Create a node.
+ *
+ * @param path absolute path of the node to create
+ * @param data the data to store, may be {@code null} for no data
+ * @param mode the create mode
+ * @param acls the ACL for the node, or {@code null} for the client default ACL
+ * @param createParents whether missing parent nodes are created (with the client default ACL)
+ * @return the actual path of the created node (differs from {@code path} for sequential modes)
+ * @throws Exception on failure, ZooKeeper exceptions unwrapped
+ */
+ String create(String path, byte[] data, CreateMode mode, List acls, boolean createParents)
+ throws Exception;
+
+ /**
+ * Create a node storing the client's default payload (the local host address bytes).
+ *
+ * @param path absolute path of the node to create
+ * @param mode the create mode
+ * @param acls the ACL for the node, or {@code null} for the client default ACL
+ * @param createParents whether missing parent nodes are created (with the client default ACL)
+ * @return the actual path of the created node
+ * @throws Exception on failure, ZooKeeper exceptions unwrapped
+ */
+ String createWithDefaultData(String path, CreateMode mode, List acls,
+ boolean createParents) throws Exception;
+
+ /**
+ * Check whether a node exists.
+ *
+ * @param path absolute path
+ * @param watch whether to leave a watch on the node (set even when the node is absent)
+ * @return the node's stat, or {@code null} if the node does not exist
+ * @throws Exception on failure, ZooKeeper exceptions unwrapped
+ */
+ Stat exists(String path, boolean watch) throws Exception;
+
+ /**
+ * Read the data of a node.
+ *
+ * @param path absolute path
+ * @param watch whether to leave a watch on the node
+ * @param stat if not {@code null}, filled with the node's stat
+ * @return the node data
+ * @throws Exception on failure, for example {@link KeeperException.NoNodeException}
+ */
+ byte[] getData(String path, boolean watch, Stat stat) throws Exception;
+
+ /**
+ * Unconditionally (any version) set the data of a node.
+ *
+ * @param path absolute path
+ * @param data new data
+ * @return the node's new stat
+ * @throws Exception on failure, ZooKeeper exceptions unwrapped
+ */
+ Stat setData(String path, byte[] data) throws Exception;
+
+ /**
+ * List the children of a node.
+ *
+ * @param path absolute path
+ * @param watch whether to leave a watch on the node
+ * @return the child names (not full paths)
+ * @throws Exception on failure, ZooKeeper exceptions unwrapped
+ */
+ List getChildren(String path, boolean watch) throws Exception;
+
+ /**
+ * Unconditionally (any version) delete a node.
+ *
+ * @param path absolute path
+ * @param recursive whether to delete the node's children first
+ * @throws Exception on failure, ZooKeeper exceptions unwrapped
+ */
+ void delete(String path, boolean recursive) throws Exception;
+
+ /**
+ * Read the ACL of a node.
+ *
+ * @param path absolute path
+ * @return the node's ACL
+ * @throws Exception on failure, ZooKeeper exceptions unwrapped
+ */
+ List getAcl(String path) throws Exception;
+
+ /**
+ * Unconditionally (any version) set the ACL of a node.
+ *
+ * @param path absolute path
+ * @param acls the new ACL
+ * @throws Exception on failure, ZooKeeper exceptions unwrapped
+ */
+ void setAcl(String path, List acls) throws Exception;
+
+ /**
+ * Asynchronously ask the server to sync the given path with the leader. This call does not
+ * wait for the sync to complete.
+ *
+ * @param path absolute path
+ * @throws Exception if the request could not be issued
+ */
+ void sync(String path) throws Exception;
+
+ /**
+ * Register a listener for connection state changes of this client.
+ *
+ * @param listener the listener to notify
+ */
+ void addConnectionStateListener(ClusterStateListener listener);
+
+ /**
+ * Close the session and release all resources.
+ */
+ @Override
+ void close();
+}
diff --git a/storm-client/src/jvm/org/apache/storm/zookeeper/curator/CuratorRetryPolicy.java b/storm-client/src/jvm/org/apache/storm/zookeeper/curator/CuratorRetryPolicy.java
new file mode 100644
index 00000000000..165898316ed
--- /dev/null
+++ b/storm-client/src/jvm/org/apache/storm/zookeeper/curator/CuratorRetryPolicy.java
@@ -0,0 +1,44 @@
+/*
+ * 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.storm.zookeeper.curator;
+
+import org.apache.storm.shade.org.apache.curator.retry.BoundedExponentialBackoffRetry;
+import org.apache.storm.utils.StormBoundedExponentialBackoffRetry;
+
+/**
+ * Internal. Adapts {@link StormBoundedExponentialBackoffRetry} to Curator's retry policy.
+ *
+ * Extending {@link BoundedExponentialBackoffRetry} with the same arguments keeps Curator's own
+ * handling (the maximum-retries cap and {@code allowRetry} semantics), while the sleep time is
+ * computed by Storm's backoff algorithm.
+ */
+final class CuratorRetryPolicy extends BoundedExponentialBackoffRetry {
+ private final StormBoundedExponentialBackoffRetry delegate;
+
+ CuratorRetryPolicy(int baseSleepTimeMs, int maxSleepTimeMs, int maxRetries) {
+ super(baseSleepTimeMs, maxSleepTimeMs, maxRetries);
+ this.delegate = new StormBoundedExponentialBackoffRetry(baseSleepTimeMs, maxSleepTimeMs,
+ maxRetries);
+ }
+
+ @Override
+ public long getSleepTimeMs(int retryCount, long elapsedTimeMs) {
+ return delegate.getSleepTimeMs(retryCount, elapsedTimeMs);
+ }
+}
diff --git a/storm-client/src/jvm/org/apache/storm/utils/CuratorUtils.java b/storm-client/src/jvm/org/apache/storm/zookeeper/curator/CuratorUtils.java
similarity index 83%
rename from storm-client/src/jvm/org/apache/storm/utils/CuratorUtils.java
rename to storm-client/src/jvm/org/apache/storm/zookeeper/curator/CuratorUtils.java
index 4faf4ce095f..98348ea3d2f 100644
--- a/storm-client/src/jvm/org/apache/storm/utils/CuratorUtils.java
+++ b/storm-client/src/jvm/org/apache/storm/zookeeper/curator/CuratorUtils.java
@@ -16,38 +16,74 @@
* limitations under the License.
*/
-package org.apache.storm.utils;
+package org.apache.storm.zookeeper.curator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.naming.ConfigurationException;
import org.apache.storm.Config;
+import org.apache.storm.callback.WatcherCallBack;
import org.apache.storm.shade.org.apache.commons.lang3.StringUtils;
import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
import org.apache.storm.shade.org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.storm.shade.org.apache.curator.framework.api.ACLProvider;
+import org.apache.storm.shade.org.apache.curator.framework.api.CuratorEventType;
+import org.apache.storm.shade.org.apache.zookeeper.WatchedEvent;
import org.apache.storm.shade.org.apache.zookeeper.client.ZKClientConfig;
import org.apache.storm.shade.org.apache.zookeeper.common.ClientX509Util;
import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
+import org.apache.storm.utils.ObjectReader;
+import org.apache.storm.utils.ZookeeperAuthInfo;
+import org.apache.storm.zookeeper.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class CuratorUtils {
+/**
+ * Internal. Builds Curator clients from a Storm configuration.
+ *
+ *
Not part of Storm's public API; may change or be removed without notice. Use
+ * {@link org.apache.storm.zookeeper.ClientZookeeper#mkClient} to obtain a {@link ZkClient}.
+ */
+public final class CuratorUtils {
public static final Logger LOG = LoggerFactory.getLogger(CuratorUtils.class);
public static final String CLIENT_CNXN
= org.apache.storm.shade.org.apache.zookeeper.ClientCnxnSocketNetty.class.getName();
- public static CuratorFramework newCurator(Map conf, List servers,
- Object port, String root,
- List defaultAcl) {
- return newCurator(conf, servers, port, root, null, defaultAcl);
+ private CuratorUtils() {
+ }
+
+ /**
+ * Build, start and wrap a Curator client.
+ *
+ * @param conf the Storm configuration
+ * @param servers the ZooKeeper servers
+ * @param port the ZooKeeper port
+ * @param root the chroot, {@code ""} for none
+ * @param auth the authentication to add, may be {@code null}
+ * @param defaultAcl the default ACL for created nodes, {@code null} for OPEN_ACL_UNSAFE
+ * @param watcher receives watch events, {@code null} to drop them
+ * @return the started client
+ */
+ public static ZkClient newClient(Map conf, List servers, Object port,
+ String root, ZookeeperAuthInfo auth, List defaultAcl, WatcherCallBack watcher) {
+ CuratorFramework fk = newCurator(conf, servers, port, root, auth, defaultAcl);
+ if (watcher != null) {
+ fk.getCuratorListenable().addListener((unused, e) -> {
+ if (e.getType().equals(CuratorEventType.WATCHED)) {
+ WatchedEvent event = e.getWatchedEvent();
+ watcher.execute(event.getState(), event.getType(), event.getPath());
+ }
+ });
+ }
+ fk.start();
+ return new CuratorZkClient(fk);
}
public static CuratorFramework newCurator(Map conf, List servers,
- Object port, ZookeeperAuthInfo auth,
+ Object port, String root,
List defaultAcl) {
- return newCurator(conf, servers, port, "", auth, defaultAcl);
+ return newCurator(conf, servers, port, root, null, defaultAcl);
}
public static CuratorFramework newCurator(Map conf, List servers,
@@ -87,7 +123,7 @@ protected static void setupBuilder(CuratorFrameworkFactory.Builder builder, fina
.get(Config.STORM_ZOOKEEPER_CONNECTION_TIMEOUT)))
.sessionTimeoutMs(ObjectReader.getInt(conf
.get(Config.STORM_ZOOKEEPER_SESSION_TIMEOUT)))
- .retryPolicy(new StormBoundedExponentialBackoffRetry(
+ .retryPolicy(new CuratorRetryPolicy(
ObjectReader.getInt(conf.get(Config.STORM_ZOOKEEPER_RETRY_INTERVAL)),
ObjectReader.getInt(conf
.get(Config.STORM_ZOOKEEPER_RETRY_INTERVAL_CEILING)),
@@ -224,22 +260,4 @@ public static void testSetupBuilder(CuratorFrameworkFactory.Builder
builder, String zkStr, Map conf, ZookeeperAuthInfo auth) {
setupBuilder(builder, zkStr, conf, auth);
}
-
- public static CuratorFramework newCuratorStarted(Map conf, List servers,
- Object port,
- String root, ZookeeperAuthInfo auth, List defaultAcl) {
- CuratorFramework ret = newCurator(conf, servers, port, root, auth, defaultAcl);
- LOG.info("Starting Utils Curator...");
- ret.start();
- return ret;
- }
-
- public static CuratorFramework newCuratorStarted(Map conf, List servers,
- Object port,
- ZookeeperAuthInfo auth, List defaultAcl) {
- CuratorFramework ret = newCurator(conf, servers, port, auth, defaultAcl);
- LOG.info("Starting Utils Curator (2)...");
- ret.start();
- return ret;
- }
}
diff --git a/storm-client/src/jvm/org/apache/storm/zookeeper/curator/CuratorZkClient.java b/storm-client/src/jvm/org/apache/storm/zookeeper/curator/CuratorZkClient.java
new file mode 100644
index 00000000000..31c737bcd9e
--- /dev/null
+++ b/storm-client/src/jvm/org/apache/storm/zookeeper/curator/CuratorZkClient.java
@@ -0,0 +1,183 @@
+/*
+ * 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.storm.zookeeper.curator;
+
+import java.util.List;
+import java.util.Objects;
+import org.apache.storm.cluster.ClusterStateListener;
+import org.apache.storm.cluster.ConnectionState;
+import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
+import org.apache.storm.shade.org.apache.zookeeper.CreateMode;
+import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
+import org.apache.storm.shade.org.apache.zookeeper.data.Stat;
+import org.apache.storm.zookeeper.ZkClient;
+
+/**
+ * Internal. The Curator-backed {@link ZkClient}. Every method is a one-to-one translation to the
+ * corresponding Curator builder chain, so behaviour is identical to calling Curator directly.
+ *
+ * Not part of Storm's public API; may change or be removed without notice.
+ */
+public final class CuratorZkClient implements ZkClient {
+ private final CuratorFramework curator;
+
+ CuratorZkClient(CuratorFramework curator) {
+ this.curator = Objects.requireNonNull(curator, "curator");
+ }
+
+ /**
+ * Wrap an already started {@link CuratorFramework}. Intended for tests that build their own
+ * Curator client.
+ *
+ * @param curator the started Curator client
+ * @return a {@link ZkClient} delegating to {@code curator}
+ */
+ public static ZkClient wrap(CuratorFramework curator) {
+ return new CuratorZkClient(curator);
+ }
+
+ /**
+ * Return the {@link CuratorFramework} backing a {@link ZkClient}. Only used by code that still
+ * needs Curator recipes directly (leader election).
+ *
+ * @param client a Curator-backed client
+ * @return the underlying Curator client
+ * @throws IllegalArgumentException if {@code client} is not Curator-backed
+ */
+ public static CuratorFramework unwrap(ZkClient client) {
+ if (client instanceof CuratorZkClient) {
+ return ((CuratorZkClient) client).curator;
+ }
+ throw new IllegalArgumentException("ZkClient is not backed by Curator: "
+ + (client == null ? "null" : client.getClass().getName()));
+ }
+
+ @Override
+ public String create(String path, byte[] data, CreateMode mode, List acls,
+ boolean createParents) throws Exception {
+ if (createParents) {
+ return curator.create().creatingParentsIfNeeded().withMode(mode).withACL(acls)
+ .forPath(path, data);
+ }
+ return curator.create().withMode(mode).withACL(acls).forPath(path, data);
+ }
+
+ @Override
+ public String createWithDefaultData(String path, CreateMode mode, List acls,
+ boolean createParents) throws Exception {
+ if (createParents) {
+ return curator.create().creatingParentsIfNeeded().withMode(mode).withACL(acls)
+ .forPath(path);
+ }
+ return curator.create().withMode(mode).withACL(acls).forPath(path);
+ }
+
+ @Override
+ public Stat exists(String path, boolean watch) throws Exception {
+ if (watch) {
+ return curator.checkExists().watched().forPath(path);
+ }
+ return curator.checkExists().forPath(path);
+ }
+
+ @Override
+ public byte[] getData(String path, boolean watch, Stat stat) throws Exception {
+ if (stat != null) {
+ if (watch) {
+ return curator.getData().storingStatIn(stat).watched().forPath(path);
+ }
+ return curator.getData().storingStatIn(stat).forPath(path);
+ }
+ if (watch) {
+ return curator.getData().watched().forPath(path);
+ }
+ return curator.getData().forPath(path);
+ }
+
+ @Override
+ public Stat setData(String path, byte[] data) throws Exception {
+ return curator.setData().forPath(path, data);
+ }
+
+ @Override
+ public List getChildren(String path, boolean watch) throws Exception {
+ if (watch) {
+ return curator.getChildren().watched().forPath(path);
+ }
+ return curator.getChildren().forPath(path);
+ }
+
+ @Override
+ public void delete(String path, boolean recursive) throws Exception {
+ if (recursive) {
+ curator.delete().deletingChildrenIfNeeded().forPath(path);
+ } else {
+ curator.delete().forPath(path);
+ }
+ }
+
+ @Override
+ public List getAcl(String path) throws Exception {
+ return curator.getACL().forPath(path);
+ }
+
+ @Override
+ public void setAcl(String path, List acls) throws Exception {
+ curator.setACL().withACL(acls).forPath(path);
+ }
+
+ @Override
+ public void sync(String path) throws Exception {
+ curator.sync().forPath(path);
+ }
+
+ @Override
+ public void addConnectionStateListener(ClusterStateListener listener) {
+ Objects.requireNonNull(listener, "listener");
+ curator.getConnectionStateListenable().addListener(
+ (unused, newState) -> listener.stateChanged(toStorm(newState)));
+ }
+
+ @Override
+ public void close() {
+ curator.close();
+ }
+
+ /**
+ * Map a Curator connection state onto Storm's. An explicit switch so that a Curator upgrade
+ * adding a state fails loudly instead of being silently mis-mapped.
+ */
+ static ConnectionState toStorm(
+ org.apache.storm.shade.org.apache.curator.framework.state.ConnectionState state) {
+ switch (state) {
+ case CONNECTED:
+ return ConnectionState.CONNECTED;
+ case SUSPENDED:
+ return ConnectionState.SUSPENDED;
+ case RECONNECTED:
+ return ConnectionState.RECONNECTED;
+ case LOST:
+ return ConnectionState.LOST;
+ case READ_ONLY:
+ return ConnectionState.READ_ONLY;
+ default:
+ throw new IllegalStateException("Unknown Curator connection state " + state);
+ }
+ }
+}
diff --git a/storm-client/src/jvm/org/apache/storm/zookeeper/curator/package-info.java b/storm-client/src/jvm/org/apache/storm/zookeeper/curator/package-info.java
new file mode 100644
index 00000000000..a087dfa1db5
--- /dev/null
+++ b/storm-client/src/jvm/org/apache/storm/zookeeper/curator/package-info.java
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+/**
+ * Internal. Curator-backed implementation of {@link org.apache.storm.zookeeper.ZkClient}.
+ *
+ * This package is not part of Storm's public API and may change or be removed without notice,
+ * in particular when Storm stops depending on Apache Curator. External code must use
+ * {@link org.apache.storm.zookeeper.ZkClient},
+ * {@link org.apache.storm.zookeeper.ClientZookeeper#mkClient} and
+ * {@link org.apache.storm.cluster.ClusterStateListener} instead.
+ */
+package org.apache.storm.zookeeper.curator;
diff --git a/storm-client/test/jvm/org/apache/storm/utils/CuratorUtilsTest.java b/storm-client/test/jvm/org/apache/storm/zookeeper/curator/CuratorUtilsTest.java
similarity index 98%
rename from storm-client/test/jvm/org/apache/storm/utils/CuratorUtilsTest.java
rename to storm-client/test/jvm/org/apache/storm/zookeeper/curator/CuratorUtilsTest.java
index 08115d28ddf..953aeffa4b3 100644
--- a/storm-client/test/jvm/org/apache/storm/utils/CuratorUtilsTest.java
+++ b/storm-client/test/jvm/org/apache/storm/zookeeper/curator/CuratorUtilsTest.java
@@ -16,7 +16,7 @@
* limitations under the License.
*/
-package org.apache.storm.utils;
+package org.apache.storm.zookeeper.curator;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -38,6 +38,9 @@
import org.apache.storm.shade.org.apache.zookeeper.ZooKeeper;
import org.apache.storm.shade.org.apache.zookeeper.client.ZKClientConfig;
import org.apache.storm.shade.org.apache.zookeeper.common.ClientX509Util;
+import org.apache.storm.utils.ObjectReader;
+import org.apache.storm.utils.Utils;
+import org.apache.storm.utils.ZookeeperAuthInfo;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -70,8 +73,8 @@ public void newCuratorUsesExponentialBackoffTest() {
CuratorFramework curator = CuratorUtils.newCurator(config,
Collections.singletonList("bogus_server"), 42, "", DaemonType.WORKER
.getDefaultZkAcls(config));
- StormBoundedExponentialBackoffRetry policy =
- (StormBoundedExponentialBackoffRetry) curator.getZookeeperClient().getRetryPolicy();
+ CuratorRetryPolicy policy =
+ (CuratorRetryPolicy) curator.getZookeeperClient().getRetryPolicy();
assertEquals(policy.getBaseSleepTimeMs(), expectedInterval);
assertEquals(policy.getN(), expectedRetries);
assertEquals(policy.getSleepTimeMs(10, 0), expectedCeiling);
diff --git a/storm-client/test/jvm/org/apache/storm/zookeeper/curator/CuratorZkClientTest.java b/storm-client/test/jvm/org/apache/storm/zookeeper/curator/CuratorZkClientTest.java
new file mode 100644
index 00000000000..e1c57c75f5a
--- /dev/null
+++ b/storm-client/test/jvm/org/apache/storm/zookeeper/curator/CuratorZkClientTest.java
@@ -0,0 +1,211 @@
+/*
+ * 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.storm.zookeeper.curator;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.net.InetAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import org.apache.curator.test.TestingServer;
+import org.apache.storm.Config;
+import org.apache.storm.cluster.ConnectionState;
+import org.apache.storm.shade.org.apache.zookeeper.CreateMode;
+import org.apache.storm.shade.org.apache.zookeeper.KeeperException;
+import org.apache.storm.shade.org.apache.zookeeper.Watcher;
+import org.apache.storm.shade.org.apache.zookeeper.ZooDefs;
+import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
+import org.apache.storm.shade.org.apache.zookeeper.data.Stat;
+import org.apache.storm.utils.Utils;
+import org.apache.storm.zookeeper.ZkClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class CuratorZkClientTest {
+ /**
+ * A default ACL that differs from OPEN_ACL_UNSAFE (no ADMIN permission), so tests can tell the
+ * client default apart from Curator's fallback.
+ */
+ private static final List DEFAULT_ACL = Collections.singletonList(
+ new ACL(ZooDefs.Perms.ALL & ~ZooDefs.Perms.ADMIN, ZooDefs.Ids.ANYONE_ID_UNSAFE));
+
+ private TestingServer server;
+ private ZkClient client;
+ private final LinkedBlockingQueue events = new LinkedBlockingQueue<>();
+
+ @BeforeEach
+ public void setUp() throws Exception {
+ server = new TestingServer(true);
+ Map conf = Utils.readDefaultConfig();
+ conf.put(Config.STORM_ZOOKEEPER_RETRY_TIMES, 1);
+ client = CuratorUtils.newClient(conf, Collections.singletonList("127.0.0.1"),
+ server.getPort(), "", null, DEFAULT_ACL,
+ (state, type, path) -> {
+ // Session events (type None) are delivered too; only keep node events.
+ if (type != Watcher.Event.EventType.None) {
+ events.add(type);
+ }
+ });
+ }
+
+ @AfterEach
+ public void tearDown() throws Exception {
+ if (client != null) {
+ client.close();
+ }
+ if (server != null) {
+ server.close();
+ }
+ }
+
+ @Test
+ public void createWithDefaultDataStoresLocalAddress() throws Exception {
+ client.createWithDefaultData("/dflt", CreateMode.PERSISTENT, null, false);
+ byte[] expected = InetAddress.getLocalHost().getHostAddress().getBytes();
+ assertArrayEquals(expected, client.getData("/dflt", false, null));
+ }
+
+ @Test
+ public void createWithNullDataStoresNoData() throws Exception {
+ client.create("/nulldata", null, CreateMode.PERSISTENT, null, false);
+ byte[] data = client.getData("/nulldata", false, null);
+ assertTrue(data == null || data.length == 0, "expected no data");
+ }
+
+ @Test
+ public void createParentsUseClientDefaultAcl() throws Exception {
+ String path = client.create("/a/b/c", "x".getBytes(StandardCharsets.UTF_8),
+ CreateMode.PERSISTENT, ZooDefs.Ids.OPEN_ACL_UNSAFE, true);
+ assertEquals("/a/b/c", path);
+ assertEquals(DEFAULT_ACL, client.getAcl("/a"));
+ assertEquals(DEFAULT_ACL, client.getAcl("/a/b"));
+ assertEquals(ZooDefs.Ids.OPEN_ACL_UNSAFE, client.getAcl("/a/b/c"));
+
+ client.create("/a/dflt", null, CreateMode.PERSISTENT, null, false);
+ assertEquals(DEFAULT_ACL, client.getAcl("/a/dflt"));
+ }
+
+ @Test
+ public void aclRoundTrip() throws Exception {
+ client.create("/acl", null, CreateMode.PERSISTENT, ZooDefs.Ids.OPEN_ACL_UNSAFE, false);
+ client.setAcl("/acl", ZooDefs.Ids.READ_ACL_UNSAFE);
+ assertEquals(ZooDefs.Ids.READ_ACL_UNSAFE, client.getAcl("/acl"));
+ }
+
+ @Test
+ public void dataStatAndVersions() throws Exception {
+ assertNull(client.exists("/v", false));
+ client.create("/v", "1".getBytes(StandardCharsets.UTF_8), CreateMode.PERSISTENT, null,
+ false);
+ Stat stat = client.setData("/v", "2".getBytes(StandardCharsets.UTF_8));
+ assertEquals(1, stat.getVersion());
+ Stat read = new Stat();
+ assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), client.getData("/v", false, read));
+ assertEquals(1, read.getVersion());
+ assertEquals(1, client.exists("/v", false).getVersion());
+ }
+
+ @Test
+ public void sequentialCreateReturnsActualPath() throws Exception {
+ String path = client.create("/seq-", null, CreateMode.PERSISTENT_SEQUENTIAL, null, false);
+ assertTrue(path.startsWith("/seq-") && path.length() > "/seq-".length(), path);
+ }
+
+ @Test
+ public void watchesReachWatcherCallBack() throws Exception {
+ assertNull(client.exists("/w", true));
+ client.create("/w", "a".getBytes(StandardCharsets.UTF_8), CreateMode.PERSISTENT, null,
+ false);
+ assertEquals(Watcher.Event.EventType.NodeCreated, events.poll(30, TimeUnit.SECONDS));
+
+ client.getData("/w", true, null);
+ client.setData("/w", "b".getBytes(StandardCharsets.UTF_8));
+ assertEquals(Watcher.Event.EventType.NodeDataChanged, events.poll(30, TimeUnit.SECONDS));
+
+ client.getChildren("/w", true);
+ client.create("/w/child", null, CreateMode.PERSISTENT, null, false);
+ assertEquals(Watcher.Event.EventType.NodeChildrenChanged,
+ events.poll(30, TimeUnit.SECONDS));
+ }
+
+ @Test
+ public void deleteRecursiveAndNonRecursive() throws Exception {
+ client.create("/d/e/f", null, CreateMode.PERSISTENT, null, true);
+ assertThrows(KeeperException.NotEmptyException.class, () -> client.delete("/d", false));
+ client.delete("/d", true);
+ assertNull(client.exists("/d", false));
+ }
+
+ @Test
+ public void keeperExceptionsPropagateUnwrapped() throws Exception {
+ assertThrows(KeeperException.NoNodeException.class,
+ () -> client.getData("/missing", false, null));
+ assertThrows(KeeperException.NoNodeException.class,
+ () -> client.setData("/missing", new byte[0]));
+ assertThrows(KeeperException.NoNodeException.class,
+ () -> client.delete("/missing", false));
+ client.create("/dup", null, CreateMode.PERSISTENT, null, false);
+ assertThrows(KeeperException.NodeExistsException.class,
+ () -> client.create("/dup", null, CreateMode.PERSISTENT, null, false));
+ }
+
+ @Test
+ public void syncDoesNotFail() throws Exception {
+ client.create("/s", null, CreateMode.PERSISTENT, null, false);
+ client.sync("/s");
+ }
+
+ @Test
+ public void unwrapReturnsBackingCuratorAndRejectsOthers() {
+ assertNotNull(CuratorZkClient.unwrap(client));
+ assertSame(CuratorZkClient.unwrap(client),
+ CuratorZkClient.unwrap(CuratorZkClient.wrap(CuratorZkClient.unwrap(client))));
+ assertThrows(IllegalArgumentException.class, () -> CuratorZkClient.unwrap(null));
+ }
+
+ @Test
+ public void connectionStatesMapOneToOne() {
+ assertEquals(ConnectionState.CONNECTED, CuratorZkClient.toStorm(
+ org.apache.storm.shade.org.apache.curator.framework.state.ConnectionState.CONNECTED));
+ assertEquals(ConnectionState.SUSPENDED, CuratorZkClient.toStorm(
+ org.apache.storm.shade.org.apache.curator.framework.state.ConnectionState.SUSPENDED));
+ assertEquals(ConnectionState.RECONNECTED, CuratorZkClient.toStorm(
+ org.apache.storm.shade.org.apache.curator.framework.state.ConnectionState.RECONNECTED));
+ assertEquals(ConnectionState.LOST, CuratorZkClient.toStorm(
+ org.apache.storm.shade.org.apache.curator.framework.state.ConnectionState.LOST));
+ assertEquals(ConnectionState.READ_ONLY, CuratorZkClient.toStorm(
+ org.apache.storm.shade.org.apache.curator.framework.state.ConnectionState.READ_ONLY));
+ // Every Curator state must be mapped (fails loudly if Curator adds one).
+ for (org.apache.storm.shade.org.apache.curator.framework.state.ConnectionState s
+ : org.apache.storm.shade.org.apache.curator.framework.state.ConnectionState.values()) {
+ assertEquals(s.name(), CuratorZkClient.toStorm(s).name());
+ }
+ }
+}
diff --git a/storm-core/test/jvm/org/apache/storm/trident/StateTest.java b/storm-core/test/jvm/org/apache/storm/trident/StateTest.java
index f43a391b6c7..c85f2a586dd 100644
--- a/storm-core/test/jvm/org/apache/storm/trident/StateTest.java
+++ b/storm-core/test/jvm/org/apache/storm/trident/StateTest.java
@@ -19,9 +19,6 @@
package org.apache.storm.trident;
-import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
-import org.apache.storm.shade.org.apache.curator.framework.api.CreateBuilder;
-import org.apache.storm.shade.org.apache.curator.framework.api.ProtectACLCreateModeStatPathAndBytesable;
import org.apache.storm.shade.org.apache.zookeeper.CreateMode;
import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
import org.apache.storm.shade.org.apache.zookeeper.ZooDefs;
@@ -36,6 +33,7 @@
import org.apache.storm.trident.testing.MemoryMapState;
import org.apache.storm.trident.topology.state.TestTransactionalState;
import org.apache.storm.utils.Utils;
+import org.apache.storm.zookeeper.ZkClient;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
@@ -141,16 +139,41 @@ public void testTransactionalMap() {
@Test
public void testCreateNodeAcl() throws Exception {
// Creates ZooKeeper nodes with the correct ACLs
- CuratorFramework curator = Mockito.mock(CuratorFramework.class);
- CreateBuilder builder0 = Mockito.mock(CreateBuilder.class);
- ProtectACLCreateModeStatPathAndBytesable builder1 = Mockito.mock(ProtectACLCreateModeStatPathAndBytesable.class);
+ ZkClient zk = Mockito.mock(ZkClient.class);
List expectedAcls = ZooDefs.Ids.CREATOR_ALL_ACL;
- Mockito.when(curator.create()).thenReturn(builder0);
- Mockito.when(builder0.creatingParentsIfNeeded()).thenReturn(builder1);
- Mockito.when(builder1.withMode(ArgumentMatchers.isA(CreateMode.class))).thenReturn(builder1);
- Mockito.when(builder1.withACL(Mockito.anyList())).thenReturn(builder1);
- TestTransactionalState.createNode(curator, "", new byte[0], expectedAcls, null);
- Mockito.verify(builder1).withACL(expectedAcls);
+ TestTransactionalState.createNode(zk, "", new byte[0], expectedAcls, null);
+ Mockito.verify(zk).create(ArgumentMatchers.eq(""), ArgumentMatchers.any(byte[].class),
+ ArgumentMatchers.eq(CreateMode.PERSISTENT), ArgumentMatchers.eq(expectedAcls),
+ ArgumentMatchers.eq(true));
+ Mockito.verifyNoMoreInteractions(zk);
+ }
+
+ @Test
+ public void testCreateNodeAclIgnoresModeWhenAclsGiven() throws Exception {
+ // As with the former Curator builder chain, the mode is only honoured without explicit ACLs
+ ZkClient zk = Mockito.mock(ZkClient.class);
+ List expectedAcls = ZooDefs.Ids.CREATOR_ALL_ACL;
+ TestTransactionalState.createNode(zk, "/n", new byte[]{1}, expectedAcls, CreateMode.EPHEMERAL);
+ Mockito.verify(zk).create(ArgumentMatchers.eq("/n"), ArgumentMatchers.any(byte[].class),
+ ArgumentMatchers.eq(CreateMode.PERSISTENT), ArgumentMatchers.eq(expectedAcls),
+ ArgumentMatchers.eq(true));
+ }
+
+ @Test
+ public void testCreateNodeNullDataUsesDefaultData() throws Exception {
+ ZkClient zk = Mockito.mock(ZkClient.class);
+ TestTransactionalState.createNode(zk, "/root", null, null, null);
+ Mockito.verify(zk).createWithDefaultData("/root", CreateMode.PERSISTENT, null, true);
+ Mockito.verifyNoMoreInteractions(zk);
+ }
+
+ @Test
+ public void testCreateNodeNullAclsKeepsMode() throws Exception {
+ ZkClient zk = Mockito.mock(ZkClient.class);
+ byte[] data = new byte[]{1, 2};
+ TestTransactionalState.createNode(zk, "/eph", data, null, CreateMode.EPHEMERAL);
+ Mockito.verify(zk).create("/eph", data, CreateMode.EPHEMERAL, null, true);
+ Mockito.verifyNoMoreInteractions(zk);
}
@Test
diff --git a/storm-server/src/main/java/org/apache/storm/blobstore/BlobStoreUtils.java b/storm-server/src/main/java/org/apache/storm/blobstore/BlobStoreUtils.java
index f42b0c7e03e..8b0fb563c9d 100644
--- a/storm-server/src/main/java/org/apache/storm/blobstore/BlobStoreUtils.java
+++ b/storm-server/src/main/java/org/apache/storm/blobstore/BlobStoreUtils.java
@@ -29,13 +29,12 @@
import org.apache.storm.generated.ReadableBlobMeta;
import org.apache.storm.nimbus.NimbusInfo;
import org.apache.storm.security.auth.NimbusPrincipal;
-import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
import org.apache.storm.shade.org.apache.zookeeper.KeeperException;
import org.apache.storm.thrift.transport.TTransportException;
-import org.apache.storm.utils.CuratorUtils;
import org.apache.storm.utils.NimbusClient;
import org.apache.storm.utils.WrappedKeyNotFoundException;
-import org.apache.storm.utils.ZookeeperAuthInfo;
+import org.apache.storm.zookeeper.ClientZookeeper;
+import org.apache.storm.zookeeper.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -49,16 +48,12 @@ public static String getBlobStoreSubtree() {
}
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
- public static CuratorFramework createZKClient(Map conf, DaemonType type) {
+ public static ZkClient createZKClient(Map conf, DaemonType type) {
@SuppressWarnings("unchecked")
List zkServers = (List) conf.get(Config.STORM_ZOOKEEPER_SERVERS);
Object port = conf.get(Config.STORM_ZOOKEEPER_PORT);
- ZookeeperAuthInfo zkAuthInfo = new ZookeeperAuthInfo(conf);
- CuratorFramework zkClient = CuratorUtils.newCurator(conf, zkServers, port,
- (String) conf.get(Config.STORM_ZOOKEEPER_ROOT), zkAuthInfo,
- type.getDefaultZkAcls(conf));
- zkClient.start();
- return zkClient;
+ return ClientZookeeper.mkClient(conf, zkServers, port, (String) conf.get(Config.STORM_ZOOKEEPER_ROOT), null, conf,
+ type);
}
public static Subject getNimbusSubject() {
@@ -77,10 +72,10 @@ public static BlobKeySequenceInfo normalizeNimbusHostPortSequenceNumberInfo(Stri
}
// Check for latest sequence number of a key inside zookeeper and return nimbodes containing the latest sequence number
- public static Set getNimbodesWithLatestSequenceNumberOfBlob(CuratorFramework zkClient, String key) throws Exception {
+ public static Set getNimbodesWithLatestSequenceNumberOfBlob(ZkClient zkClient, String key) throws Exception {
List stateInfoList;
try {
- stateInfoList = zkClient.getChildren().forPath("/blobstore/" + key);
+ stateInfoList = zkClient.getChildren("/blobstore/" + key, false);
} catch (KeeperException.NoNodeException e) {
// there's a race condition with a delete: blobstore
// this should be thrown to the caller to indicate that the key is invalid now
@@ -243,7 +238,7 @@ public static void createStateInZookeeper(Map conf, String key,
cb.createStateInZookeeper(key);
}
- public static void updateKeyForBlobStore(Map conf, BlobStore blobStore, CuratorFramework zkClient, String key,
+ public static void updateKeyForBlobStore(Map conf, BlobStore blobStore, ZkClient zkClient, String key,
NimbusInfo nimbusDetails) {
try {
// Most of clojure tests currently try to access the blobs using getBlob. Since, updateKeyForBlobStore
@@ -257,10 +252,10 @@ public static void updateKeyForBlobStore(Map conf, BlobStore blo
}
boolean isListContainsCurrentNimbusInfo = false;
List stateInfo;
- if (zkClient.checkExists().forPath(BLOBSTORE_SUBTREE + "/" + key) == null) {
+ if (zkClient.exists(BLOBSTORE_SUBTREE + "/" + key, false) == null) {
return;
}
- stateInfo = zkClient.getChildren().forPath(BLOBSTORE_SUBTREE + "/" + key);
+ stateInfo = zkClient.getChildren(BLOBSTORE_SUBTREE + "/" + key, false);
if (stateInfo == null || stateInfo.isEmpty()) {
return;
}
diff --git a/storm-server/src/main/java/org/apache/storm/blobstore/KeySequenceNumber.java b/storm-server/src/main/java/org/apache/storm/blobstore/KeySequenceNumber.java
index ae0f998603b..ea0117d347f 100644
--- a/storm-server/src/main/java/org/apache/storm/blobstore/KeySequenceNumber.java
+++ b/storm-server/src/main/java/org/apache/storm/blobstore/KeySequenceNumber.java
@@ -17,11 +17,11 @@
import java.util.TreeSet;
import org.apache.storm.generated.KeyNotFoundException;
import org.apache.storm.nimbus.NimbusInfo;
-import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
import org.apache.storm.shade.org.apache.zookeeper.CreateMode;
import org.apache.storm.shade.org.apache.zookeeper.KeeperException;
import org.apache.storm.shade.org.apache.zookeeper.ZooDefs;
import org.apache.storm.utils.WrappedKeyNotFoundException;
+import org.apache.storm.zookeeper.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -123,7 +123,7 @@ public KeySequenceNumber(String key, NimbusInfo nimbusInfo) {
this.nimbusInfo = nimbusInfo;
}
- public synchronized int getKeySequenceNumber(CuratorFramework zkClient) throws KeyNotFoundException {
+ public synchronized int getKeySequenceNumber(ZkClient zkClient) throws KeyNotFoundException {
return getKeySequenceNumber(zkClient, true);
}
@@ -137,17 +137,17 @@ public synchronized int getKeySequenceNumber(CuratorFramework zkClient) throws K
* @return the sequence number
* @throws KeyNotFoundException if the key is not in zookeeper and may not be created, or it is deleted meanwhile
*/
- public synchronized int getKeySequenceNumber(CuratorFramework zkClient, boolean mayCreateKey) throws KeyNotFoundException {
+ public synchronized int getKeySequenceNumber(ZkClient zkClient, boolean mayCreateKey) throws KeyNotFoundException {
TreeSet sequenceNumbers = new TreeSet();
try {
// Key has not been created yet and it is the first time it is being created
- if (zkClient.checkExists().forPath(BlobStoreUtils.getBlobStoreSubtree() + "/" + key) == null) {
+ if (zkClient.exists(BlobStoreUtils.getBlobStoreSubtree() + "/" + key, false) == null) {
if (!mayCreateKey) {
throw new KeeperException.NoNodeException(BlobStoreUtils.getBlobStoreSubtree() + "/" + key);
}
- zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT)
- .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE).forPath(BLOBSTORE_MAX_KEY_SEQUENCE_SUBTREE + "/" + key);
- zkClient.setData().forPath(BLOBSTORE_MAX_KEY_SEQUENCE_SUBTREE + "/" + key,
+ zkClient.createWithDefaultData(BLOBSTORE_MAX_KEY_SEQUENCE_SUBTREE + "/" + key, CreateMode.PERSISTENT,
+ ZooDefs.Ids.OPEN_ACL_UNSAFE, true);
+ zkClient.setData(BLOBSTORE_MAX_KEY_SEQUENCE_SUBTREE + "/" + key,
ByteBuffer.allocate(INT_CAPACITY).putInt(INITIAL_SEQUENCE_NUMBER).array());
return INITIAL_SEQUENCE_NUMBER;
}
@@ -155,7 +155,7 @@ public synchronized int getKeySequenceNumber(CuratorFramework zkClient, boolean
// When all nimbodes go down and one or few of them come up
// Unfortunately there might not be an exact way to know which one contains the most updated blob,
// if all go down which is unlikely. Hence there might be a need to update the blob if all go down.
- List stateInfoList = zkClient.getChildren().forPath(BlobStoreUtils.getBlobStoreSubtree() + "/" + key);
+ List stateInfoList = zkClient.getChildren(BlobStoreUtils.getBlobStoreSubtree() + "/" + key, false);
LOG.debug("stateInfoList-size {} stateInfoList-data {}", stateInfoList.size(), stateInfoList);
if (stateInfoList.isEmpty()) {
return getMaxSequenceNumber(zkClient);
@@ -229,13 +229,12 @@ private boolean checkIfStateContainsCurrentNimbusHost(List stateInfoList
return containsNimbusHost;
}
- private void incrementMaxSequenceNumber(CuratorFramework zkClient, int count) throws Exception {
- zkClient.setData().forPath(BLOBSTORE_MAX_KEY_SEQUENCE_SUBTREE + "/" + key,
- ByteBuffer.allocate(INT_CAPACITY).putInt(count + 1).array());
+ private void incrementMaxSequenceNumber(ZkClient zkClient, int count) throws Exception {
+ zkClient.setData(BLOBSTORE_MAX_KEY_SEQUENCE_SUBTREE + "/" + key,
+ ByteBuffer.allocate(INT_CAPACITY).putInt(count + 1).array());
}
- private int getMaxSequenceNumber(CuratorFramework zkClient) throws Exception {
- return ByteBuffer.wrap(zkClient.getData()
- .forPath(BLOBSTORE_MAX_KEY_SEQUENCE_SUBTREE + "/" + key)).getInt();
+ private int getMaxSequenceNumber(ZkClient zkClient) throws Exception {
+ return ByteBuffer.wrap(zkClient.getData(BLOBSTORE_MAX_KEY_SEQUENCE_SUBTREE + "/" + key, false, null)).getInt();
}
}
diff --git a/storm-server/src/main/java/org/apache/storm/blobstore/LocalFsBlobStore.java b/storm-server/src/main/java/org/apache/storm/blobstore/LocalFsBlobStore.java
index a5d5c5bcf8e..717087d3996 100644
--- a/storm-server/src/main/java/org/apache/storm/blobstore/LocalFsBlobStore.java
+++ b/storm-server/src/main/java/org/apache/storm/blobstore/LocalFsBlobStore.java
@@ -48,13 +48,13 @@
import org.apache.storm.nimbus.ILeaderElector;
import org.apache.storm.nimbus.NimbusInfo;
import org.apache.storm.shade.com.google.common.annotations.VisibleForTesting;
-import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
import org.apache.storm.shade.org.apache.zookeeper.KeeperException;
import org.apache.storm.utils.ConfigUtils;
import org.apache.storm.utils.ObjectReader;
import org.apache.storm.utils.Utils;
import org.apache.storm.utils.WrappedKeyAlreadyExistsException;
import org.apache.storm.utils.WrappedKeyNotFoundException;
+import org.apache.storm.zookeeper.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -87,7 +87,7 @@ public class LocalFsBlobStore extends BlobStore {
private NimbusInfo nimbusInfo;
private FileBlobStoreImpl fbs;
private Map conf;
- private CuratorFramework zkClient;
+ private ZkClient zkClient;
private IStormClusterState stormClusterState;
private Timer timer;
private ILeaderElector leaderElector;
@@ -438,11 +438,11 @@ public int getBlobReplication(String key, Subject who) throws Exception {
validateKey(key);
SettableBlobMeta meta = getStoredBlobMeta(key);
aclHandler.hasPermissions(meta.get_acl(), READ, who, key);
- if (zkClient.checkExists().forPath(BLOBSTORE_SUBTREE + key) == null) {
+ if (zkClient.exists(BLOBSTORE_SUBTREE + key, false) == null) {
return 0;
}
try {
- replicationCount = zkClient.getChildren().forPath(BLOBSTORE_SUBTREE + key).size();
+ replicationCount = zkClient.getChildren(BLOBSTORE_SUBTREE + key, false).size();
} catch (KeeperException.NoNodeException e) {
//Race with delete
//If it is not here the replication is 0
@@ -462,7 +462,7 @@ public synchronized boolean checkForBlobOrDownload(String key) throws KeyNotFoun
try {
List keyList = BlobStoreUtils.getKeyListFromBlobStore(this);
if (!keyList.contains(key)) {
- if (zkClient.checkExists().forPath(BLOBSTORE_SUBTREE + key) != null) {
+ if (zkClient.exists(BLOBSTORE_SUBTREE + key, false) != null) {
Set nimbusSet = BlobStoreUtils.getNimbodesWithLatestSequenceNumberOfBlob(zkClient, key);
nimbusSet.remove(this.nimbusInfo);
if (BlobStoreUtils.downloadMissingBlob(conf, this, key, nimbusSet)) {
diff --git a/storm-server/src/main/java/org/apache/storm/blobstore/LocalFsBlobStoreSynchronizer.java b/storm-server/src/main/java/org/apache/storm/blobstore/LocalFsBlobStoreSynchronizer.java
index 77ef8c9be9b..3d21bb85efc 100644
--- a/storm-server/src/main/java/org/apache/storm/blobstore/LocalFsBlobStoreSynchronizer.java
+++ b/storm-server/src/main/java/org/apache/storm/blobstore/LocalFsBlobStoreSynchronizer.java
@@ -25,7 +25,7 @@
import java.util.Set;
import org.apache.storm.generated.KeyNotFoundException;
import org.apache.storm.nimbus.NimbusInfo;
-import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
+import org.apache.storm.zookeeper.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,7 +37,7 @@
*/
public class LocalFsBlobStoreSynchronizer {
private static final Logger LOG = LoggerFactory.getLogger(LocalFsBlobStoreSynchronizer.class);
- private CuratorFramework zkClient;
+ private ZkClient zkClient;
private Map conf;
private BlobStore blobStore;
private Set blobStoreKeySet = new HashSet();
@@ -53,7 +53,7 @@ public void setNimbusInfo(NimbusInfo nimbusInfo) {
this.nimbusInfo = nimbusInfo;
}
- public void setZkClient(CuratorFramework zkClient) {
+ public void setZkClient(ZkClient zkClient) {
this.zkClient = zkClient;
}
diff --git a/storm-server/src/main/java/org/apache/storm/daemon/nimbus/Nimbus.java b/storm-server/src/main/java/org/apache/storm/daemon/nimbus/Nimbus.java
index eab1fe49e47..dbc26c556a0 100644
--- a/storm-server/src/main/java/org/apache/storm/daemon/nimbus/Nimbus.java
+++ b/storm-server/src/main/java/org/apache/storm/daemon/nimbus/Nimbus.java
@@ -205,7 +205,6 @@
import org.apache.storm.shade.com.google.common.collect.ImmutableMap;
import org.apache.storm.shade.com.google.common.collect.MapDifference;
import org.apache.storm.shade.com.google.common.collect.Maps;
-import org.apache.storm.shade.org.apache.curator.framework.CuratorFramework;
import org.apache.storm.shade.org.apache.zookeeper.ZooDefs;
import org.apache.storm.shade.org.apache.zookeeper.data.ACL;
import org.apache.storm.stats.ClientStatsUtil;
@@ -234,6 +233,7 @@
import org.apache.storm.validation.ConfigValidation;
import org.apache.storm.zookeeper.AclEnforcement;
import org.apache.storm.zookeeper.ClientZookeeper;
+import org.apache.storm.zookeeper.ZkClient;
import org.apache.storm.zookeeper.Zookeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -476,8 +476,8 @@ public static List getNimbusAcls(Map conf) {
private final ClusterSummaryMetricSet clusterMetricSet;
private MetricStore metricsStore;
private IAuthorizer authorizationHandler;
- //Cached CuratorFramework, mainly used for BlobStore.
- private final CuratorFramework zkClient;
+ //Cached zookeeper client, mainly used for BlobStore.
+ private final ZkClient zkClient;
//Cached topology -> executor ids, used for deciding timeout workers of heartbeatsCache.
private AtomicReference