com.bazaarvoice.ostrich.discovery.zookeeper.ZooKeeperServiceDiscovery Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ostrich-zookeeper-discovery Show documentation
Show all versions of ostrich-zookeeper-discovery Show documentation
Ostrich service discovery backed by ZooKeeper
package com.bazaarvoice.ostrich.discovery.zookeeper;
import com.bazaarvoice.curator.recipes.NodeDiscovery;
import com.bazaarvoice.ostrich.ServiceDiscovery;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Iterables;
import org.apache.curator.framework.CuratorFramework;
import java.io.IOException;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* The ServiceDiscovery
class encapsulates a ZooKeeper backed NodeDiscovery which watches the root service
* path in ZooKeeper and will monitor which services are known to exist. As services come and go the results of calling
* the #getServices
method will change.
*
* NOTE: It's possible that a returned service doesn't have any {@code ServiceEndPoint} instances currently registered.
* This class only watches the root service path's child nodes -- it doesn't make sure that a service has child nodes
* of its own.
*/
public class ZooKeeperServiceDiscovery implements ServiceDiscovery {
/**
* The root path in ZooKeeper for where service registrations are stored.
*
* WARNING: Do not modify this without also modifying the ALL of the corresponding paths in the service registry,
* host discovery, and service discovery classes!!!
*/
@VisibleForTesting
static final String ROOT_SERVICES_PATH = "/ostrich";
/** Node data parser that returns the service name of the path. */
@VisibleForTesting
static final NodeDiscovery.NodeDataParser SERVICE_NAME_PARSER = new NodeDiscovery.NodeDataParser() {
@Override
public String parse(String path, byte[] nodeData) {
path = path.substring(ROOT_SERVICES_PATH.length());
if (path.startsWith("/")) {
path = path.substring(1);
}
return path;
}
};
private final NodeDiscovery _nodeDiscovery;
public ZooKeeperServiceDiscovery(CuratorFramework curator) {
this(new NodeDiscovery(curator, ROOT_SERVICES_PATH, SERVICE_NAME_PARSER));
}
@VisibleForTesting
ZooKeeperServiceDiscovery(NodeDiscovery nodeDiscovery) {
_nodeDiscovery = checkNotNull(nodeDiscovery);
_nodeDiscovery.start();
}
@Override
public Iterable getServices() {
Map nodes = _nodeDiscovery.getNodes();
return Iterables.unmodifiableIterable(nodes.values());
}
@Override
public void close() throws IOException {
_nodeDiscovery.close();
}
}