while (!zk.isRunning()) {
log.info("Checking zookeeper cluster creation state");
try {
ClusterState clusterState = cluster.readClusterState();
if (clusterState != null && clusterState.isCreated()) {
log.info("Zookeeper cluster is created");
break;
} else {
log.info("Zookeeper cluster state: {}", clusterState);
}
} catch (IOException e) {
log.warn("Error reading cluster state", e);
TimeSpan.seconds(10).sleep();
continue;
}
try {
if (cluster.getLock().tryLock(1, TimeUnit.MINUTES)) {
// We've got the lock...
ClusterSnapshot snapshot = cluster.getSnapshot();
ClusterState state = snapshot.getClusterState();
if (state == null || !state.isCreated()) {
// If we haven't created the data yet, everybody should
// be an observer
for (ZookeeperClusterRegistration server : snapshot.servers.values()) {
if (!server.isObserver()) {
// TODO: It may be that the leader crashed
// mid-create...
throw new IllegalStateException("Found non-observer server in uninitialized cluster");
}
}
registration.type = ZookeeperClusterRegistration.PARTICIPANT;
cluster.writeRegistration(myid, registration);
snapshot.servers.put(myid, registration);
config.writeHosts(snapshot);
config.writeConfig(snapshot, myid);
zk.start();
if (state == null) {
state = new ClusterState();
}
state.createdBy = String.valueOf(myid);
cluster.writeClusterState(state);
}