fa851515d70d94d7a8b7411652519926d5d85a1e
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / RaftActorContextImpl.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.ActorContext;
12 import akka.actor.ActorRef;
13 import akka.actor.ActorSelection;
14 import akka.actor.ActorSystem;
15 import akka.actor.Props;
16 import com.google.common.annotations.VisibleForTesting;
17 import com.google.common.base.Preconditions;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25 import java.util.function.Supplier;
26 import org.opendaylight.controller.cluster.DataPersistenceProvider;
27 import org.opendaylight.controller.cluster.raft.ServerConfigurationPayload.ServerInfo;
28 import org.opendaylight.controller.cluster.raft.behaviors.RaftActorBehavior;
29 import org.opendaylight.controller.cluster.raft.policy.RaftPolicy;
30 import org.slf4j.Logger;
31
32 public class RaftActorContextImpl implements RaftActorContext {
33
34     private final ActorRef actor;
35
36     private final ActorContext context;
37
38     private final String id;
39
40     private final ElectionTerm termInformation;
41
42     private long commitIndex;
43
44     private long lastApplied;
45
46     private ReplicatedLog replicatedLog;
47
48     private final Map<String, PeerInfo> peerInfoMap = new HashMap<>();
49
50     private final Logger LOG;
51
52     private ConfigParams configParams;
53
54     private boolean dynamicServerConfiguration = false;
55
56     @VisibleForTesting
57     private Supplier<Long> totalMemoryRetriever;
58
59     // Snapshot manager will need to be created on demand as it needs raft actor context which cannot
60     // be passed to it in the constructor
61     private SnapshotManager snapshotManager;
62
63     private final DataPersistenceProvider persistenceProvider;
64
65     private short payloadVersion;
66
67     private boolean votingMember = true;
68
69     private RaftActorBehavior currentBehavior;
70
71     public RaftActorContextImpl(ActorRef actor, ActorContext context, String id,
72             ElectionTerm termInformation, long commitIndex, long lastApplied, Map<String, String> peerAddresses,
73             ConfigParams configParams, DataPersistenceProvider persistenceProvider, Logger logger) {
74         this.actor = actor;
75         this.context = context;
76         this.id = id;
77         this.termInformation = termInformation;
78         this.commitIndex = commitIndex;
79         this.lastApplied = lastApplied;
80         this.configParams = configParams;
81         this.persistenceProvider = persistenceProvider;
82         this.LOG = logger;
83
84         for(Map.Entry<String, String> e: peerAddresses.entrySet()) {
85             peerInfoMap.put(e.getKey(), new PeerInfo(e.getKey(), e.getValue(), VotingState.VOTING));
86         }
87     }
88
89     @VisibleForTesting
90     public void setPayloadVersion(short payloadVersion) {
91         this.payloadVersion = payloadVersion;
92     }
93
94     @Override
95     public short getPayloadVersion() {
96         return payloadVersion;
97     }
98
99     public void setConfigParams(ConfigParams configParams) {
100         this.configParams = configParams;
101     }
102
103     @Override
104     public ActorRef actorOf(Props props){
105         return context.actorOf(props);
106     }
107
108     @Override
109     public ActorSelection actorSelection(String path){
110         return context.actorSelection(path);
111     }
112
113     @Override
114     public String getId() {
115         return id;
116     }
117
118     @Override
119     public ActorRef getActor() {
120         return actor;
121     }
122
123     @Override
124     public ElectionTerm getTermInformation() {
125         return termInformation;
126     }
127
128     @Override
129     public long getCommitIndex() {
130         return commitIndex;
131     }
132
133     @Override public void setCommitIndex(long commitIndex) {
134         this.commitIndex = commitIndex;
135     }
136
137     @Override
138     public long getLastApplied() {
139         return lastApplied;
140     }
141
142     @Override
143     public void setLastApplied(long lastApplied) {
144         this.lastApplied = lastApplied;
145     }
146
147     @Override
148     public void setReplicatedLog(ReplicatedLog replicatedLog) {
149         this.replicatedLog = replicatedLog;
150     }
151
152     @Override
153     public ReplicatedLog getReplicatedLog() {
154         return replicatedLog;
155     }
156
157     @Override public ActorSystem getActorSystem() {
158         return context.system();
159     }
160
161     @Override public Logger getLogger() {
162         return this.LOG;
163     }
164
165     @Override
166     public Collection<String> getPeerIds() {
167         return peerInfoMap.keySet();
168     }
169
170     @Override
171     public Collection<PeerInfo> getPeers() {
172         return peerInfoMap.values();
173     }
174
175     @Override
176     public PeerInfo getPeerInfo(String peerId) {
177         return peerInfoMap.get(peerId);
178     }
179
180     @Override
181     public String getPeerAddress(String peerId) {
182         String peerAddress = null;
183         PeerInfo peerInfo = peerInfoMap.get(peerId);
184         if(peerInfo != null) {
185             peerAddress = peerInfo.getAddress();
186             if(peerAddress == null) {
187                 peerAddress = configParams.getPeerAddressResolver().resolve(peerId);
188                 peerInfo.setAddress(peerAddress);
189             }
190         } else {
191             peerAddress = configParams.getPeerAddressResolver().resolve(peerId);
192         }
193
194         return peerAddress;
195     }
196
197     @Override
198     public void updatePeerIds(ServerConfigurationPayload serverConfig){
199         votingMember = true;
200         boolean foundSelf = false;
201         Set<String> currentPeers = new HashSet<>(this.getPeerIds());
202         for(ServerInfo server: serverConfig.getServerConfig()) {
203             if(getId().equals(server.getId())) {
204                 foundSelf = true;
205                 if(!server.isVoting()) {
206                     votingMember = false;
207                 }
208             } else {
209                 VotingState votingState = server.isVoting() ? VotingState.VOTING: VotingState.NON_VOTING;
210                 if(!currentPeers.contains(server.getId())) {
211                     this.addToPeers(server.getId(), null, votingState);
212                 } else {
213                     this.getPeerInfo(server.getId()).setVotingState(votingState);
214                     currentPeers.remove(server.getId());
215                 }
216             }
217         }
218
219         for(String peerIdToRemove: currentPeers) {
220             this.removePeer(peerIdToRemove);
221         }
222
223         if(!foundSelf) {
224             votingMember = false;
225         }
226
227         setDynamicServerConfigurationInUse();
228     }
229
230     @Override public ConfigParams getConfigParams() {
231         return configParams;
232     }
233
234     @Override
235     public void addToPeers(String id, String address, VotingState votingState) {
236         peerInfoMap.put(id, new PeerInfo(id, address, votingState));
237     }
238
239     @Override
240     public void removePeer(String name) {
241         if(getId().equals(name)) {
242             votingMember = false;
243         } else {
244             peerInfoMap.remove(name);
245         }
246     }
247
248     @Override public ActorSelection getPeerActorSelection(String peerId) {
249         String peerAddress = getPeerAddress(peerId);
250         if(peerAddress != null){
251             return actorSelection(peerAddress);
252         }
253         return null;
254     }
255
256     @Override
257     public void setPeerAddress(String peerId, String peerAddress) {
258         PeerInfo peerInfo = peerInfoMap.get(peerId);
259         if(peerInfo != null) {
260             LOG.info("Peer address for peer {} set to {}", peerId, peerAddress);
261             peerInfo.setAddress(peerAddress);
262         }
263     }
264
265     @Override
266     public SnapshotManager getSnapshotManager() {
267         if(snapshotManager == null){
268             snapshotManager = new SnapshotManager(this, LOG);
269         }
270         return snapshotManager;
271     }
272
273     @Override
274     public long getTotalMemory() {
275         return totalMemoryRetriever != null ? totalMemoryRetriever.get() : Runtime.getRuntime().totalMemory();
276     }
277
278     @Override
279     public void setTotalMemoryRetriever(Supplier<Long> retriever) {
280         totalMemoryRetriever = retriever;
281     }
282
283     @Override
284     public boolean hasFollowers() {
285         return getPeerIds().size() > 0;
286     }
287
288     @Override
289     public DataPersistenceProvider getPersistenceProvider() {
290         return persistenceProvider;
291     }
292
293
294     @Override
295     public RaftPolicy getRaftPolicy() {
296         return configParams.getRaftPolicy();
297     }
298
299     @Override
300     public boolean isDynamicServerConfigurationInUse() {
301         return dynamicServerConfiguration;
302     }
303
304     @Override
305     public void setDynamicServerConfigurationInUse() {
306         this.dynamicServerConfiguration = true;
307     }
308
309     @Override
310     public ServerConfigurationPayload getPeerServerInfo(boolean includeSelf) {
311         if (!isDynamicServerConfigurationInUse()) {
312             return null;
313         }
314         Collection<PeerInfo> peers = getPeers();
315         List<ServerInfo> newConfig = new ArrayList<>(peers.size() + 1);
316         for(PeerInfo peer: peers) {
317             newConfig.add(new ServerInfo(peer.getId(), peer.isVoting()));
318         }
319
320         if(includeSelf) {
321             newConfig.add(new ServerInfo(getId(), votingMember));
322         }
323
324         return (new ServerConfigurationPayload(newConfig));
325     }
326
327     @Override
328     public boolean isVotingMember() {
329         return votingMember;
330     }
331
332     @Override
333     public RaftActorBehavior getCurrentBehavior() {
334         return currentBehavior;
335     }
336
337     void setCurrentBehavior(final RaftActorBehavior behavior) {
338         this.currentBehavior = Preconditions.checkNotNull(behavior);
339     }
340
341     void close() {
342         if (currentBehavior != null) {
343             try {
344                 currentBehavior.close();
345             } catch (Exception e) {
346                 LOG.debug("{}: Error closing behavior {}", getId(), currentBehavior.state());
347             }
348         }
349     }
350 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.