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

©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.