Merge "Avoid IllegalArgument on missing source"
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / behaviors / Candidate.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.cluster.raft.behaviors;
10
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import java.util.Set;
14 import org.opendaylight.controller.cluster.raft.RaftActorContext;
15 import org.opendaylight.controller.cluster.raft.RaftState;
16 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
17 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
18 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
19 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
20 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
21 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
22
23 /**
24  * The behavior of a RaftActor when it is in the CandidateState
25  * <p/>
26  * Candidates (§5.2):
27  * <ul>
28  * <li> On conversion to candidate, start election:
29  * <ul>
30  * <li> Increment currentTerm
31  * <li> Vote for self
32  * <li> Reset election timer
33  * <li> Send RequestVote RPCs to all other servers
34  * </ul>
35  * <li> If votes received from majority of servers: become leader
36  * <li> If AppendEntries RPC received from new leader: convert to
37  * follower
38  * <li> If election timeout elapses: start new election
39  * </ul>
40  */
41 public class Candidate extends AbstractRaftActorBehavior {
42
43     private int voteCount;
44
45     private final int votesRequired;
46
47     private final Set<String> peers;
48
49     public Candidate(RaftActorContext context) {
50         super(context, RaftState.Candidate);
51
52         peers = context.getPeerAddresses().keySet();
53
54         if(LOG.isDebugEnabled()) {
55             LOG.debug("{}: Election: Candidate has following peers: {}", logName(), peers);
56         }
57
58         votesRequired = getMajorityVoteCount(peers.size());
59
60         startNewTerm();
61
62         if(context.getPeerAddresses().isEmpty()){
63             actor().tell(ELECTION_TIMEOUT, actor());
64         } else {
65             scheduleElection(electionDuration());
66         }
67
68
69     }
70
71     @Override protected RaftActorBehavior handleAppendEntries(ActorRef sender,
72         AppendEntries appendEntries) {
73
74         if(LOG.isDebugEnabled()) {
75             LOG.debug("{}: handleAppendEntries: {}", logName(), appendEntries);
76         }
77
78         return this;
79     }
80
81     @Override protected RaftActorBehavior handleAppendEntriesReply(ActorRef sender,
82         AppendEntriesReply appendEntriesReply) {
83
84         return this;
85     }
86
87     @Override protected RaftActorBehavior handleRequestVoteReply(ActorRef sender,
88             RequestVoteReply requestVoteReply) {
89
90         LOG.debug("{}: handleRequestVoteReply: {}, current voteCount: {}", logName(), requestVoteReply,
91                 voteCount);
92
93         if (requestVoteReply.isVoteGranted()) {
94             voteCount++;
95         }
96
97         if (voteCount >= votesRequired) {
98             return switchBehavior(new Leader(context));
99         }
100
101         return this;
102     }
103
104     @Override
105     public RaftActorBehavior handleMessage(ActorRef sender, Object originalMessage) {
106
107         Object message = fromSerializableMessage(originalMessage);
108
109         if (message instanceof RaftRPC) {
110
111             RaftRPC rpc = (RaftRPC) message;
112
113             if(LOG.isDebugEnabled()) {
114                 LOG.debug("{}: RaftRPC message received {}, my term is {}", logName(), rpc,
115                         context.getTermInformation().getCurrentTerm());
116             }
117
118             // If RPC request or response contains term T > currentTerm:
119             // set currentTerm = T, convert to follower (§5.1)
120             // This applies to all RPC messages and responses
121             if (rpc.getTerm() > context.getTermInformation().getCurrentTerm()) {
122                 context.getTermInformation().updateAndPersist(rpc.getTerm(), null);
123
124                 return switchBehavior(new Follower(context));
125             }
126         }
127
128         if (message instanceof ElectionTimeout) {
129             LOG.debug("{}: Received ElectionTimeout", logName());
130
131             if (votesRequired == 0) {
132                 // If there are no peers then we should be a Leader
133                 // We wait for the election timeout to occur before declare
134                 // ourselves the leader. This gives enough time for a leader
135                 // who we do not know about (as a peer)
136                 // to send a message to the candidate
137
138                 return switchBehavior(new Leader(context));
139             }
140             startNewTerm();
141             scheduleElection(electionDuration());
142             return this;
143         }
144
145         return super.handleMessage(sender, message);
146     }
147
148
149     private void startNewTerm() {
150
151
152         // set voteCount back to 1 (that is voting for self)
153         voteCount = 1;
154
155         // Increment the election term and vote for self
156         long currentTerm = context.getTermInformation().getCurrentTerm();
157         long newTerm = currentTerm + 1;
158         context.getTermInformation().updateAndPersist(newTerm, context.getId());
159
160         LOG.debug("{}: Starting new term {}", logName(), newTerm);
161
162         // Request for a vote
163         // TODO: Retry request for vote if replies do not arrive in a reasonable
164         // amount of time TBD
165         for (String peerId : peers) {
166             ActorSelection peerActor = context.getPeerActorSelection(peerId);
167             if(peerActor != null) {
168                 RequestVote requestVote = new RequestVote(
169                         context.getTermInformation().getCurrentTerm(),
170                         context.getId(),
171                         context.getReplicatedLog().lastIndex(),
172                         context.getReplicatedLog().lastTerm());
173
174                 LOG.debug("{}: Sending {} to peer {}", logName(), requestVote, peerId);
175
176                 peerActor.tell(requestVote, context.getActor());
177             }
178         }
179     }
180
181     @Override public void close() throws Exception {
182         stopElection();
183     }
184 }