Merge "Bug 2697: Improvement wrong response handling, missing message"
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / MockRaftActorContext.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;
10
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.actor.ActorSystem;
14 import akka.actor.Props;
15 import com.google.common.base.Preconditions;
16 import com.google.protobuf.GeneratedMessage;
17 import java.io.Serializable;
18 import java.util.HashMap;
19 import java.util.Map;
20 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
21 import org.opendaylight.controller.protobuff.messages.cluster.raft.AppendEntriesMessages;
22 import org.opendaylight.controller.protobuff.messages.cluster.raft.test.MockPayloadMessages;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 public class MockRaftActorContext implements RaftActorContext {
27
28     private String id;
29     private ActorSystem system;
30     private ActorRef actor;
31     private long index = 0;
32     private long lastApplied = 0;
33     private final ElectionTerm electionTerm;
34     private ReplicatedLog replicatedLog;
35     private Map<String, String> peerAddresses = new HashMap<>();
36     private ConfigParams configParams;
37     private boolean snapshotCaptureInitiated;
38
39     public MockRaftActorContext(){
40         electionTerm = null;
41
42         initReplicatedLog();
43     }
44
45     public MockRaftActorContext(String id, ActorSystem system, ActorRef actor){
46         this.id = id;
47         this.system = system;
48         this.actor = actor;
49
50         final String id1 = id;
51         electionTerm = new ElectionTerm() {
52             /**
53              * Identifier of the actor whose election term information this is
54              */
55             private final String id = id1;
56             private long currentTerm = 1;
57             private String votedFor = "";
58
59             @Override
60             public long getCurrentTerm() {
61                 return currentTerm;
62             }
63
64             @Override
65             public String getVotedFor() {
66                 return votedFor;
67             }
68
69             @Override
70             public void update(long currentTerm, String votedFor){
71                 this.currentTerm = currentTerm;
72                 this.votedFor = votedFor;
73
74                 // TODO : Write to some persistent state
75             }
76
77             @Override public void updateAndPersist(long currentTerm,
78                 String votedFor) {
79                 update(currentTerm, votedFor);
80             }
81         };
82
83         configParams = new DefaultConfigParamsImpl();
84
85         initReplicatedLog();
86     }
87
88
89     public void initReplicatedLog(){
90         this.replicatedLog = new SimpleReplicatedLog();
91         long term = getTermInformation().getCurrentTerm();
92         this.replicatedLog.append(new MockReplicatedLogEntry(term, 0, new MockPayload("1")));
93         this.replicatedLog.append(new MockReplicatedLogEntry(term, 1, new MockPayload("2")));
94     }
95
96     @Override public ActorRef actorOf(Props props) {
97         return system.actorOf(props);
98     }
99
100     @Override public ActorSelection actorSelection(String path) {
101         return system.actorSelection(path);
102     }
103
104     @Override public String getId() {
105         return id;
106     }
107
108     @Override public ActorRef getActor() {
109         return actor;
110     }
111
112     @Override public ElectionTerm getTermInformation() {
113         return electionTerm;
114     }
115
116     public void setIndex(long index){
117         this.index = index;
118     }
119
120     @Override public long getCommitIndex() {
121         return index;
122     }
123
124     @Override public void setCommitIndex(long commitIndex) {
125         this.index = commitIndex;
126     }
127
128     @Override public void setLastApplied(long lastApplied){
129         this.lastApplied = lastApplied;
130     }
131
132     @Override public long getLastApplied() {
133         return lastApplied;
134     }
135
136     @Override
137     // FIXME : A lot of tests try to manipulate the replicated log by setting it using this method
138     // This is OK to do if the underlyingActor is not RafActor or a derived class. If not then you should not
139     // used this way to manipulate the log because the RaftActor actually has a field replicatedLog
140     // which it creates internally and sets on the RaftActorContext
141     // The only right way to manipulate the replicated log therefore is to get it from either the RaftActor
142     // or the RaftActorContext and modify the entries in there instead of trying to replace it by using this setter
143     // Simple assertion that will fail if you do so
144     // ReplicatedLog log = new ReplicatedLogImpl();
145     // raftActor.underlyingActor().getRaftActorContext().setReplicatedLog(log);
146     // assertEquals(log, raftActor.underlyingActor().getReplicatedLog())
147     public void setReplicatedLog(ReplicatedLog replicatedLog) {
148         this.replicatedLog = replicatedLog;
149     }
150
151     @Override public ReplicatedLog getReplicatedLog() {
152         return replicatedLog;
153     }
154
155     @Override public ActorSystem getActorSystem() {
156         return this.system;
157     }
158
159     @Override public Logger getLogger() {
160         return LoggerFactory.getLogger(getClass());
161     }
162
163     @Override public Map<String, String> getPeerAddresses() {
164         return peerAddresses;
165     }
166
167     @Override public String getPeerAddress(String peerId) {
168         return peerAddresses.get(peerId);
169     }
170
171     @Override public void addToPeers(String name, String address) {
172         peerAddresses.put(name, address);
173     }
174
175     @Override public void removePeer(String name) {
176         peerAddresses.remove(name);
177     }
178
179     @Override public ActorSelection getPeerActorSelection(String peerId) {
180         String peerAddress = getPeerAddress(peerId);
181         if(peerAddress != null){
182             return actorSelection(peerAddress);
183         }
184         return null;
185     }
186
187     @Override public void setPeerAddress(String peerId, String peerAddress) {
188         Preconditions.checkState(peerAddresses.containsKey(peerId));
189         peerAddresses.put(peerId, peerAddress);
190     }
191
192     public void setPeerAddresses(Map<String, String> peerAddresses) {
193         this.peerAddresses = peerAddresses;
194     }
195
196     @Override
197     public ConfigParams getConfigParams() {
198         return configParams;
199     }
200
201     @Override
202     public void setSnapshotCaptureInitiated(boolean snapshotCaptureInitiated) {
203         this.snapshotCaptureInitiated = snapshotCaptureInitiated;
204     }
205
206     @Override
207     public boolean isSnapshotCaptureInitiated() {
208         return snapshotCaptureInitiated;
209     }
210
211     public void setConfigParams(ConfigParams configParams) {
212         this.configParams = configParams;
213     }
214
215     public static class SimpleReplicatedLog extends AbstractReplicatedLogImpl {
216         @Override public void appendAndPersist(
217             ReplicatedLogEntry replicatedLogEntry) {
218             append(replicatedLogEntry);
219         }
220
221         @Override
222         public int dataSize() {
223             return -1;
224         }
225
226         @Override public void removeFromAndPersist(long index) {
227             removeFrom(index);
228         }
229     }
230
231     public static class MockPayload extends Payload implements Serializable {
232         private static final long serialVersionUID = 3121380393130864247L;
233         private String value = "";
234
235         public MockPayload(){
236
237         }
238
239         public MockPayload(String s) {
240             this.value = s;
241         }
242
243         @Override public  Map<GeneratedMessage.GeneratedExtension, String> encode() {
244             Map<GeneratedMessage.GeneratedExtension, String> map = new HashMap<GeneratedMessage.GeneratedExtension, String>();
245             map.put(MockPayloadMessages.value, value);
246             return map;
247         }
248
249         @Override public Payload decode(
250             AppendEntriesMessages.AppendEntries.ReplicatedLogEntry.Payload payloadProtoBuff) {
251             String value = payloadProtoBuff.getExtension(MockPayloadMessages.value);
252             this.value = value;
253             return this;
254         }
255
256         @Override
257         public int size() {
258             return value.length();
259         }
260
261         @Override public String getClientPayloadClassName() {
262             return MockPayload.class.getName();
263         }
264
265         @Override
266         public String toString() {
267             return value;
268         }
269
270         @Override
271         public int hashCode() {
272             final int prime = 31;
273             int result = 1;
274             result = prime * result + ((value == null) ? 0 : value.hashCode());
275             return result;
276         }
277
278         @Override
279         public boolean equals(Object obj) {
280             if (this == obj) {
281                 return true;
282             }
283             if (obj == null) {
284                 return false;
285             }
286             if (getClass() != obj.getClass()) {
287                 return false;
288             }
289             MockPayload other = (MockPayload) obj;
290             if (value == null) {
291                 if (other.value != null) {
292                     return false;
293                 }
294             } else if (!value.equals(other.value)) {
295                 return false;
296             }
297             return true;
298         }
299     }
300
301     public static class MockReplicatedLogEntry implements ReplicatedLogEntry, Serializable {
302         private static final long serialVersionUID = 1L;
303
304         private final long term;
305         private final long index;
306         private final Payload data;
307
308         public MockReplicatedLogEntry(long term, long index, Payload data){
309
310             this.term = term;
311             this.index = index;
312             this.data = data;
313         }
314
315         @Override public Payload getData() {
316             return data;
317         }
318
319         @Override public long getTerm() {
320             return term;
321         }
322
323         @Override public long getIndex() {
324             return index;
325         }
326
327         @Override
328         public int size() {
329             return getData().size();
330         }
331
332         @Override
333         public int hashCode() {
334             final int prime = 31;
335             int result = 1;
336             result = prime * result + ((data == null) ? 0 : data.hashCode());
337             result = prime * result + (int) (index ^ (index >>> 32));
338             result = prime * result + (int) (term ^ (term >>> 32));
339             return result;
340         }
341
342         @Override
343         public boolean equals(Object obj) {
344             if (this == obj) {
345                 return true;
346             }
347             if (obj == null) {
348                 return false;
349             }
350             if (getClass() != obj.getClass()) {
351                 return false;
352             }
353             MockReplicatedLogEntry other = (MockReplicatedLogEntry) obj;
354             if (data == null) {
355                 if (other.data != null) {
356                     return false;
357                 }
358             } else if (!data.equals(other.data)) {
359                 return false;
360             }
361             if (index != other.index) {
362                 return false;
363             }
364             if (term != other.term) {
365                 return false;
366             }
367             return true;
368         }
369
370         @Override
371         public String toString() {
372             StringBuilder builder = new StringBuilder();
373             builder.append("MockReplicatedLogEntry [term=").append(term).append(", index=").append(index)
374                     .append(", data=").append(data).append("]");
375             return builder.toString();
376         }
377     }
378
379     public static class MockReplicatedLogBuilder {
380         private final ReplicatedLog mockLog = new SimpleReplicatedLog();
381
382         public  MockReplicatedLogBuilder createEntries(int start, int end, int term) {
383             for (int i=start; i<end; i++) {
384                 this.mockLog.append(new ReplicatedLogImplEntry(i, term, new MockRaftActorContext.MockPayload("foo" + i)));
385             }
386             return this;
387         }
388
389         public  MockReplicatedLogBuilder addEntry(int index, int term, MockPayload payload) {
390             this.mockLog.append(new ReplicatedLogImplEntry(index, term, payload));
391             return this;
392         }
393
394         public ReplicatedLog build() {
395             return this.mockLog;
396         }
397     }
398 }