Created
April 10, 2013 18:37
-
-
Save mkhq/5357250 to your computer and use it in GitHub Desktop.
Primary election using zookeeper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.twitter.zookeeper.ZooKeeperClient | |
import org.apache.zookeeper.CreateMode | |
import java.util.UUID | |
object PrimaryBootstrap { | |
def main(args:Array[String]) { | |
val path = args(0) | |
val zk = new ZooKeeperClient("localhost:2181") | |
zk.create(path, null, CreateMode.PERSISTENT) | |
} | |
} | |
object Primary { | |
case class Node(order:Int, guid:String, zNode:String) | |
val guid = UUID.randomUUID | |
def becomePrimary(path:String, zk:ZooKeeperClient) { | |
val children = zk.getChildren(path) | |
val nodes = children.map { | |
c => | |
val spl = c.split(":") | |
Node(spl(1).toInt, spl(0), path + "/" + c) | |
}.sortBy(_.order) | |
println("Nodes: " + nodes) | |
val index = nodes.indexWhere(_.guid.equals(guid.toString)) | |
if(index == 0) { | |
// only one child, we are the primary | |
println("I'm the primary: " + guid) | |
} else if(index > 0) { | |
// start watching the node before us | |
zk.watchNode(nodes(index-1).zNode, { data => | |
data match { | |
case Some(value) => | |
println("Node updated! " + data) | |
case None => | |
println("Node " + nodes(index-1) + " deleted!") | |
becomePrimary(path, zk) | |
} | |
}) | |
} else { | |
println("No children found at " + path) | |
} | |
} | |
def main(args:Array[String]) { | |
val path = args(0) | |
val zk = new ZooKeeperClient("localhost:2181") | |
zk.create(path + "/" + guid + ":", null, CreateMode.EPHEMERAL_SEQUENTIAL) | |
println("--- Starting as " + guid) | |
becomePrimary(path, zk) | |
Thread.sleep(60*1000) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment