Package org.apache.zookeeper.server.quorum

Examples of org.apache.zookeeper.server.quorum.Vote


        long leaderSid = peer.getCurrentVote().getId();
        long zxid = peer.getCurrentVote().getZxid();
        long electionEpoch = peer.getCurrentVote().getElectionEpoch();
        ServerState state = peer.getCurrentVote().getState();
        long peerEpoch = peer.getCurrentVote().getPeerEpoch();
        Vote newVote = new Vote(leaderSid, zxid+100, electionEpoch+100, peerEpoch, state);
        peer.setCurrentVote(newVote);
        // Start 3rd peer and check if it joins the quorum
        peer = new QuorumPeer(peers, tmpdir[2], tmpdir[2],
                 port[2], 3, 2, 2000, 2, 2);
        LOG.info("Starting peer " + peer.getId());
View Full Code Here


            this.peer = peer;
            LOG.info("Constructor: " + getName());
        }
        public void run() {
            try {
                Vote v = null;
                while(true) {
                    peer.setPeerState(ServerState.LOOKING);
                    LOG.info("Going to call leader election again.");
                    v = peer.getElectionAlg().lookForLeader();
                    if(v == null){
                        LOG.info("Thread " + i + " got a null vote");
                        break;
                    }

                    /*
                     * A real zookeeper would take care of setting the current vote. Here
                     * we do it manually.
                     */
                    peer.setCurrentVote(v);

                    LOG.info("Finished election: " + i + ", " + v.getId());
                    votes[i] = v;

                    /*
                     * Get the current value of the logical clock for this peer.
                     */
                    int lc = (int) ((FastLeaderElection) peer.getElectionAlg()).getLogicalClock();

                    if (v.getId() == i) {
                        /*
                         * A leader executes this part of the code. If it is the first leader to be
                         * elected, then it Assert.fails right after. Otherwise, it waits until it has enough
                         * followers supporting it.
                         */
                        LOG.info("I'm the leader: " + i);
                        synchronized(FLETest.this) {
                            if (leaderDies) {
                                LOG.info("Leader " + i + " dying");
                                leaderDies = false;
                                ((FastLeaderElection) peer.getElectionAlg()).shutdown();
                                leader = -1;
                                LOG.info("Leader " + i + " dead");

                                //round++;
                                FLETest.this.notifyAll();

                                break;

                            } else {
                                synchronized(voteMap){
                                    if(voteMap.get(lc) == null)
                                        voteMap.put(lc, new HashSet<TestVote>());
                                    HashSet<TestVote> hs = voteMap.get(lc);
                                    hs.add(new TestVote(i, v.getId()));

                                    if(countVotes(hs, v.getId()) > (count/2)){
                                        leader = i;
                                        LOG.info("Got majority: " + i);
                                    } else {
                                        voteMap.wait(3000);
                                        LOG.info("Notified or expired: " + i);
                                        hs = voteMap.get(lc);
                                        if(countVotes(hs, v.getId()) > (count/2)){
                                            leader = i;
                                            LOG.info("Got majority: " + i);
                                        } else {
                                            //round++;
                                        }
                                    }
                                }
                                FLETest.this.notifyAll();

                                if(leader == i){
                                    synchronized(finalObj){
                                        successCount++;
                                        joinedThreads.add((long)i);
                                        if(successCount > (count/2)) finalObj.notify();
                                    }

                                    break;
                                }
                            }
                        }
                    } else {
                        /*
                         * Followers execute this part. They first add their vote to voteMap, and then
                         * they wait for bounded amount of time. A leader notifies followers through the
                         * FLETest.this object.
                         *
                         * Note that I can get FLETest.this, and then voteMap before adding the vote of
                         * a follower, otherwise a follower would be blocked out until the leader notifies
                         * or leaves the synchronized block on FLEtest.this.
                         */


                        LOG.info("Logical clock " + ((FastLeaderElection) peer.getElectionAlg()).getLogicalClock());
                        synchronized(voteMap){
                            LOG.info("Voting on " + votes[i].getId() + ", round " + ((FastLeaderElection) peer.getElectionAlg()).getLogicalClock());
                            if(voteMap.get(lc) == null)
                                voteMap.put(lc, new HashSet<TestVote>());
                            HashSet<TestVote> hs = voteMap.get(lc);
                            hs.add(new TestVote(i, votes[i].getId()));
                            if(countVotes(hs, votes[i].getId()) > (count/2)){
                                LOG.info("Logical clock: " + lc + ", " + votes[i].getId());
                                voteMap.notify();
                            }
                        }

                        /*
                         * In this part a follower waits until the leader notifies it, and remove its
                         * vote if the leader takes too long to respond.
                         */
                        synchronized(FLETest.this){
                            if (leader != votes[i].getId()) FLETest.this.wait(3000);

                            LOG.info("The leader: " + leader + " and my vote " + votes[i].getId());
                            synchronized(voteMap){
                                if (leader == votes[i].getId()) {
                                    synchronized(finalObj){
                                        successCount++;
                                        joinedThreads.add((long)i);
                                        if(successCount > (count/2)) finalObj.notify();
                                    }
                                    break;
                                } else {
                                    HashSet<TestVote> hs = voteMap.get(lc);
                                    TestVote toRemove = null;
                                    for(TestVote tv : hs){
                                        if(v.getId() == i){
                                            toRemove = tv;
                                            break;
                                        }
                                    }
                                    hs.remove(toRemove);
                                }
                            }
                        }
                    }
                    /*
                     * Add some randomness to the execution.
                     */
                    Thread.sleep(rand.nextInt(500));
                    peer.setCurrentVote(new Vote(peer.getId(), 0));
                }
                LOG.debug("Thread " + i + " votes " + v);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
View Full Code Here

            this.i = i;
            this.peer = peer;
        }
        public void run() {
            try {
                Vote v = null;
                while(true) {
                    v = le.lookForLeader();
                    votes[i] = v;
                    if (v.getId() == i) {
                        synchronized(LETest.this) {
                            if (leaderDies) {
                                leaderDies = false;
                                peer.stopLeaderElection();
                                LOG.info("Leader " + i + " dying");
                                leader = -2;
                            } else {
                                leader = i;
                            }
                            LETest.this.notifyAll();
                        }
                        break;
                    }
                    synchronized(LETest.this) {
                        if (leader == -1) {
                            LETest.this.wait();
                        }
                        if (leader == v.getId()) {
                            break;
                        }
                    }
                    Thread.sleep(rand.nextInt(1000));
                    peer.setCurrentVote(new Vote(peer.getId(), 0));
                }
                LOG.info("Thread " + i + " votes " + v);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
View Full Code Here

                            proposedZxid = n.zxid;
   
                            sendNotifications();
                        }
   
                        recvset.put(n.addr, new Vote(n.leader, n.zxid));
   
                        // If have received from all nodes, then terminate
                        if (self.getVotingView().size() == recvset.size()) {
                            self.setPeerState((proposedLeader == self.getId()) ?
                                    ServerState.LEADING: ServerState.FOLLOWING);
                            // if (self.state == ServerState.FOLLOWING) {
                            // Thread.sleep(100);
                            // }
                            leaveInstance();
                            return new Vote(proposedLeader, proposedZxid);
   
                        } else if (termPredicate(recvset, proposedLeader,
                                proposedZxid)) {
                            // Otherwise, wait for a fixed amount of time
                            LOG.info("Passed predicate");
                            Thread.sleep(finalizeWait);
   
                            // Notification probe = recvqueue.peek();
   
                            // Verify if there is any change in the proposed leader
                            while ((!recvqueue.isEmpty())
                                    && !totalOrderPredicate(
                                            recvqueue.peek().leader, recvqueue
                                                    .peek().zxid)) {
                                recvqueue.poll();
                            }
                            if (recvqueue.isEmpty()) {
                                // LOG.warn("Proposed leader: " +
                                // proposedLeader);
                                self.setPeerState(
                                        (proposedLeader == self.getId()) ?
                                         ServerState.LEADING :
                                         ServerState.FOLLOWING);
   
                                leaveInstance();
                                return new Vote(proposedLeader, proposedZxid);
                            }
                        }
                        break;
                    case LEADING:
                        outofelection.put(n.addr, new Vote(n.leader, n.zxid));
   
                        if (termPredicate(outofelection, n.leader, n.zxid)) {
   
                            self.setPeerState((n.leader == self.getId()) ?
                                    ServerState.LEADING: ServerState.FOLLOWING);
   
                            leaveInstance();
                            return new Vote(n.leader, n.zxid);
                        }
                        break;
                    case FOLLOWING:
                        outofelection.put(n.addr, new Vote(n.leader, n.zxid));
   
                        if (termPredicate(outofelection, n.leader, n.zxid)) {
   
                            self.setPeerState((n.leader == self.getId()) ?
                                    ServerState.LEADING: ServerState.FOLLOWING);
   
                            leaveInstance();
                            return new Vote(n.leader, n.zxid);
                        }
                        break;
                    default:
                        break;
                    }
View Full Code Here

                    case 2:
                        ackstate = QuorumPeer.ServerState.FOLLOWING;
                        break;
                    }

                    Vote current = self.getCurrentVote();

                    switch (type) {
                    case 0:
                        // Receive challenge request
                        ToSend c = new ToSend(ToSend.mType.challenge, tag,
                                current.getId(), current.getZxid(),
                                logicalclock, self.getPeerState(),
                                (InetSocketAddress) responsePacket
                                        .getSocketAddress());
                        sendqueue.offer(c);
                        break;
                    case 1:
                        // Receive challenge and store somewhere else
                        long challenge = responseBuffer.getLong();
                        saveChallenge(tag, challenge);

                        break;
                    case 2:
                        Notification n = new Notification();
                        n.leader = responseBuffer.getLong();
                        n.zxid = responseBuffer.getLong();
                        n.epoch = responseBuffer.getLong();
                        n.state = ackstate;
                        n.addr = (InetSocketAddress) responsePacket
                                .getSocketAddress();

                        if ((myMsg.lastEpoch <= n.epoch)
                                && ((n.zxid > myMsg.lastProposedZxid)
                                || ((n.zxid == myMsg.lastProposedZxid)
                                && (n.leader > myMsg.lastProposedLeader)))) {
                            myMsg.lastProposedZxid = n.zxid;
                            myMsg.lastProposedLeader = n.leader;
                            myMsg.lastEpoch = n.epoch;
                        }

                        long recChallenge;
                        InetSocketAddress addr = (InetSocketAddress) responsePacket
                                .getSocketAddress();
                        if (authEnabled) {
                            ConcurrentHashMap<Long, Long> tmpMap = addrChallengeMap.get(addr);
                            if(tmpMap != null){
                                if (tmpMap.get(tag) != null) {
                                    recChallenge = responseBuffer.getLong();

                                    if (tmpMap.get(tag) == recChallenge) {
                                        recvqueue.offer(n);

                                        ToSend a = new ToSend(ToSend.mType.ack,
                                                tag, current.getId(),
                                                current.getZxid(),
                                                logicalclock, self.getPeerState(),
                                                addr);

                                        sendqueue.offer(a);
                                    } else {
                                        LOG.warn("Incorrect challenge: "
                                                + recChallenge + ", "
                                                + addrChallengeMap.toString());
                                    }
                                } else {
                                    LOG.warn("No challenge for host: " + addr
                                            + " " + tag);
                                }
                            }
                        } else {
                            recvqueue.offer(n);

                            ToSend a = new ToSend(ToSend.mType.ack, tag,
                                    current.getId(), current.getZxid(),
                                    logicalclock, self.getPeerState(),
                                    (InetSocketAddress) responsePacket
                                            .getSocketAddress());

                            sendqueue.offer(a);
View Full Code Here

            this.peer = peer;
            LOG.info("Constructor: " + getName());
        }
        public void run() {
            try {
                Vote v = null;
                while(true) {
                    peer.setPeerState(ServerState.LOOKING);
                    LOG.info("Going to call leader election again.");
                    v = peer.getElectionAlg().lookForLeader();
                    if(v == null){
                        LOG.info("Thread " + i + " got a null vote");
                        break;
                    }

                    /*
                     * A real zookeeper would take care of setting the current vote. Here
                     * we do it manually.
                     */
                    peer.setCurrentVote(v);

                    LOG.info("Finished election: " + i + ", " + v.getId());
                    //votes[i] = v;

                    switch(i){
                    case 0:
                        if(peerRound == 0){
View Full Code Here

        }

        public void run(){           
            try{
                Vote v = null;
                peer.setPeerState(ServerState.LOOKING);
                LOG.info("Going to call leader election: " + i);
                v = peer.getElectionAlg().lookForLeader();

                if (v == null){
                    Assert.fail("Thread " + i + " got a null vote");
                }                               

                /*
                 * A real zookeeper would take care of setting the current vote. Here
                 * we do it manually.
                 */
                peer.setCurrentVote(v);

                LOG.info("Finished election: " + i + ", " + v.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            LOG.info("Joining");
        }
View Full Code Here

        DatagramPacket packet = new DatagramPacket(b, b.length);
        QuorumServer server = peers.get(Long.valueOf(2));
        DatagramSocket udpSocket = new DatagramSocket(server.addr.getPort());
        LOG.info("In MockServer");
        mockLatch.countDown();
        Vote current = new Vote(2, 1);
        for (int i=0;i<2;++i) {
            udpSocket.receive(packet);
            responseBuffer.rewind();
            LOG.info("Received " + responseBuffer.getInt() + " " + responseBuffer.getLong() + " " + responseBuffer.getLong());
            LOG.info("From " + packet.getSocketAddress());
            responseBuffer.clear();
            responseBuffer.getInt(); // Skip the xid
            responseBuffer.putLong(2);
           
            responseBuffer.putLong(current.getId());
            responseBuffer.putLong(current.getZxid());
            packet.setData(b);
            udpSocket.send(packet);
        }
    }   
View Full Code Here

         * there should be much less duplicated code.
         *
         * JMX bean method calls are removed to reduce noise.
         */
        public Vote lookForLeader() throws InterruptedException {           
            self.setCurrentVote(new Vote(self.getId(),
                    self.getLastLoggedZxid()));
            // We are going to look for a leader by casting a vote for ourself
            byte requestBytes[] = new byte[4];
            ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes);
            byte responseBytes[] = new byte[28];
            ByteBuffer responseBuffer = ByteBuffer.wrap(responseBytes);
            /* The current vote for the leader. Initially me! */
            DatagramSocket s = null;
            try {
                s = new DatagramSocket();
                s.setSoTimeout(200);
            } catch (SocketException e1) {
                LOG.error("Socket exception when creating socket for leader election", e1);
                System.exit(4);
            }
            DatagramPacket requestPacket = new DatagramPacket(requestBytes,
                    requestBytes.length);
            DatagramPacket responsePacket = new DatagramPacket(responseBytes,
                    responseBytes.length);
            int xid = epochGen.nextInt();
            while (self.isRunning()) {
                HashMap<InetSocketAddress, Vote> votes =
                    new HashMap<InetSocketAddress, Vote>(self.getVotingView().size());

                requestBuffer.clear();
                requestBuffer.putInt(xid);
                requestPacket.setLength(4);
                HashSet<Long> heardFrom = new HashSet<Long>();
                for (QuorumServer server :
                    self.getVotingView().values())
                {
                    LOG.info("Server address: " + server.addr);
                    try {
                        requestPacket.setSocketAddress(server.addr);
                    } catch (IllegalArgumentException e) {
                        // Sun doesn't include the address that causes this
                        // exception to be thrown, so we wrap the exception
                        // in order to capture this critical detail.
                        throw new IllegalArgumentException(
                                "Unable to set socket address on packet, msg:"
                                + e.getMessage() + " with addr:" + server.addr,
                                e);
                    }

                    try {
                        s.send(requestPacket);
                        responsePacket.setLength(responseBytes.length);
                        s.receive(responsePacket);
                        if (responsePacket.getLength() != responseBytes.length) {
                            LOG.error("Got a short response: "
                                    + responsePacket.getLength());
                            continue;
                        }
                        responseBuffer.clear();
                        int recvedXid = responseBuffer.getInt();
                        if (recvedXid != xid) {
                            LOG.error("Got bad xid: expected " + xid
                                    + " got " + recvedXid);
                            continue;
                        }
                        long peerId = responseBuffer.getLong();
                        heardFrom.add(peerId);
                        //if(server.id != peerId){
                        Vote vote = new Vote(responseBuffer.getLong(),
                                responseBuffer.getLong());
                        InetSocketAddress addr =
                            (InetSocketAddress) responsePacket
                            .getSocketAddress();
                        votes.put(addr, vote);
                        //}
                    } catch (IOException e) {
                        LOG.warn("Ignoring exception while looking for leader",
                                e);
                        // Errors are okay, since hosts may be
                        // down
                    }
                }

                ElectionResult result = countVotes(votes, heardFrom);
               
                /**
                 * This is the only difference from LeaderElection - wait for
                 * this latch on the first time through this method. This ensures
                 * that the first round of voting happens before setCurrentVote
                 * is called below.
                 */
                LOG.info("Waiting for first round of voting to complete");
                latch.countDown();
                Assert.assertTrue("Thread timed out waiting for latch",
                        latch.await(10000, TimeUnit.MILLISECONDS));
               
                // ZOOKEEPER-569:
                // If no votes are received for live peers, reset to voting
                // for ourselves as otherwise we may hang on to a vote
                // for a dead peer                
                if (result.numValidVotes == 0) {
                    self.setCurrentVote(new Vote(self.getId(),
                            self.getLastLoggedZxid()));
                } else {
                    if (result.winner.getId() >= 0) {
                        self.setCurrentVote(result.vote);
                        // To do: this doesn't use a quorum verifier
                        if (result.winningCount > (self.getVotingView().size() / 2)) {
                            self.setCurrentVote(result.winner);
                            s.close();
                            Vote current = self.getCurrentVote();
                            LOG.info("Found leader: my type is: " + self.getLearnerType());
                            /*
                             * We want to make sure we implement the state machine
                             * correctly. If we are a PARTICIPANT, once a leader
                             * is elected we can move either to LEADING or
                             * FOLLOWING. However if we are an OBSERVER, it is an
                             * error to be elected as a Leader.
                             */
                            if (self.getLearnerType() == LearnerType.OBSERVER) {
                                if (current.getId() == self.getId()) {
                                    // This should never happen!
                                    LOG.error("OBSERVER elected as leader!");
                                    Thread.sleep(100);
                                }
                                else {
                                    self.setPeerState(ServerState.OBSERVING);
                                    Thread.sleep(100);
                                    return current;
                                }
                            } else {
                                self.setPeerState((current.getId() == self.getId())
                                        ? ServerState.LEADING: ServerState.FOLLOWING);
                                if (self.getPeerState() == ServerState.FOLLOWING) {
                                    Thread.sleep(100);
                                }                           
                                return current;
View Full Code Here

                        proposedZxid = n.zxid;

                        sendNotifications();
                    }

                    recvset.put(n.addr, new Vote(n.leader, n.zxid));

                    // If have received from all nodes, then terminate
                    if (self.quorumPeers.size() == recvset.size()) {
                        self.setPeerState((proposedLeader == self.getId()) ?
                                ServerState.LEADING: ServerState.FOLLOWING);
                        // if (self.state == ServerState.FOLLOWING) {
                        // Thread.sleep(100);
                        // }
                        leaveInstance();
                        return new Vote(proposedLeader, proposedZxid);

                    } else if (termPredicate(recvset, proposedLeader,
                            proposedZxid)) {
                        // Otherwise, wait for a fixed amount of time
                        LOG.info("Passed predicate");
                        Thread.sleep(finalizeWait);

                        // Notification probe = recvqueue.peek();

                        // Verify if there is any change in the proposed leader
                        while ((!recvqueue.isEmpty())
                                && !totalOrderPredicate(
                                        recvqueue.peek().leader, recvqueue
                                                .peek().zxid)) {
                            recvqueue.poll();
                        }
                        if (recvqueue.isEmpty()) {
                            // LOG.warn("Proposed leader: " +
                            // proposedLeader);
                            self.setPeerState((proposedLeader == self.getId()) ?
                                    ServerState.LEADING: ServerState.FOLLOWING);
                            // if (self.state == ServerState.FOLLOWING) {
                            // Thread.sleep(100);
                            // }

                            leaveInstance();
                            return new Vote(proposedLeader, proposedZxid);
                        }
                    }
                    break;
                case LEADING:
                    outofelection.put(n.addr, new Vote(n.leader, n.zxid));

                    if (termPredicate(outofelection, n.leader, n.zxid)) {

                        self.setPeerState((n.leader == self.getId()) ?
                                ServerState.LEADING: ServerState.FOLLOWING);

                        leaveInstance();
                        return new Vote(n.leader, n.zxid);
                    }
                    break;
                case FOLLOWING:
                    outofelection.put(n.addr, new Vote(n.leader, n.zxid));

                    if (termPredicate(outofelection, n.leader, n.zxid)) {

                        self.setPeerState((n.leader == self.getId()) ?
                                ServerState.LEADING: ServerState.FOLLOWING);

                        leaveInstance();
                        return new Vote(n.leader, n.zxid);
                    }
                    break;
                default:
                    break;
                }
View Full Code Here

TOP

Related Classes of org.apache.zookeeper.server.quorum.Vote

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.