2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.cluster.raft;
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;
25 import java.util.function.LongSupplier;
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;
32 public class RaftActorContextImpl implements RaftActorContext {
33 private static final LongSupplier JVM_MEMORY_RETRIEVER = () -> Runtime.getRuntime().maxMemory();
35 private final ActorRef actor;
37 private final ActorContext context;
39 private final String id;
41 private final ElectionTerm termInformation;
43 private long commitIndex;
45 private long lastApplied;
47 private ReplicatedLog replicatedLog;
49 private final Map<String, PeerInfo> peerInfoMap = new HashMap<>();
51 private final Logger LOG;
53 private ConfigParams configParams;
55 private boolean dynamicServerConfiguration = false;
58 private LongSupplier totalMemoryRetriever = JVM_MEMORY_RETRIEVER;
60 // Snapshot manager will need to be created on demand as it needs raft actor context which cannot
61 // be passed to it in the constructor
62 private SnapshotManager snapshotManager;
64 private final DataPersistenceProvider persistenceProvider;
66 private short payloadVersion;
68 private boolean votingMember = true;
70 private RaftActorBehavior currentBehavior;
72 private int numVotingPeers = -1;
74 public RaftActorContextImpl(ActorRef actor, ActorContext context, String id,
75 ElectionTerm termInformation, long commitIndex, long lastApplied, Map<String, String> peerAddresses,
76 ConfigParams configParams, DataPersistenceProvider persistenceProvider, Logger logger) {
78 this.context = context;
80 this.termInformation = termInformation;
81 this.commitIndex = commitIndex;
82 this.lastApplied = lastApplied;
83 this.configParams = configParams;
84 this.persistenceProvider = persistenceProvider;
87 for(Map.Entry<String, String> e: peerAddresses.entrySet()) {
88 peerInfoMap.put(e.getKey(), new PeerInfo(e.getKey(), e.getValue(), VotingState.VOTING));
93 public void setPayloadVersion(short payloadVersion) {
94 this.payloadVersion = payloadVersion;
98 public short getPayloadVersion() {
99 return payloadVersion;
102 public void setConfigParams(ConfigParams configParams) {
103 this.configParams = configParams;
107 public ActorRef actorOf(Props props){
108 return context.actorOf(props);
112 public ActorSelection actorSelection(String path){
113 return context.actorSelection(path);
117 public String getId() {
122 public ActorRef getActor() {
127 public ElectionTerm getTermInformation() {
128 return termInformation;
132 public long getCommitIndex() {
136 @Override public void setCommitIndex(long commitIndex) {
137 this.commitIndex = commitIndex;
141 public long getLastApplied() {
146 public void setLastApplied(long lastApplied) {
147 this.lastApplied = lastApplied;
151 public void setReplicatedLog(ReplicatedLog replicatedLog) {
152 this.replicatedLog = replicatedLog;
156 public ReplicatedLog getReplicatedLog() {
157 return replicatedLog;
160 @Override public ActorSystem getActorSystem() {
161 return context.system();
164 @Override public Logger getLogger() {
169 public Collection<String> getPeerIds() {
170 return peerInfoMap.keySet();
174 public Collection<PeerInfo> getPeers() {
175 return peerInfoMap.values();
179 public PeerInfo getPeerInfo(String peerId) {
180 return peerInfoMap.get(peerId);
184 public String getPeerAddress(String peerId) {
185 String peerAddress = null;
186 PeerInfo peerInfo = peerInfoMap.get(peerId);
187 if(peerInfo != null) {
188 peerAddress = peerInfo.getAddress();
189 if(peerAddress == null) {
190 peerAddress = configParams.getPeerAddressResolver().resolve(peerId);
191 peerInfo.setAddress(peerAddress);
194 peerAddress = configParams.getPeerAddressResolver().resolve(peerId);
201 public void updatePeerIds(ServerConfigurationPayload serverConfig){
203 boolean foundSelf = false;
204 Set<String> currentPeers = new HashSet<>(this.getPeerIds());
205 for(ServerInfo server: serverConfig.getServerConfig()) {
206 if(getId().equals(server.getId())) {
208 if(!server.isVoting()) {
209 votingMember = false;
212 VotingState votingState = server.isVoting() ? VotingState.VOTING: VotingState.NON_VOTING;
213 if(!currentPeers.contains(server.getId())) {
214 this.addToPeers(server.getId(), null, votingState);
216 this.getPeerInfo(server.getId()).setVotingState(votingState);
217 currentPeers.remove(server.getId());
222 for(String peerIdToRemove: currentPeers) {
223 this.removePeer(peerIdToRemove);
227 votingMember = false;
230 LOG.debug("{}: Updated server config: isVoting: {}, peers: {}", id, votingMember, peerInfoMap.values());
232 setDynamicServerConfigurationInUse();
235 @Override public ConfigParams getConfigParams() {
240 public void addToPeers(String id, String address, VotingState votingState) {
241 peerInfoMap.put(id, new PeerInfo(id, address, votingState));
246 public void removePeer(String name) {
247 if(getId().equals(name)) {
248 votingMember = false;
250 peerInfoMap.remove(name);
255 @Override public ActorSelection getPeerActorSelection(String peerId) {
256 String peerAddress = getPeerAddress(peerId);
257 if(peerAddress != null){
258 return actorSelection(peerAddress);
264 public void setPeerAddress(String peerId, String peerAddress) {
265 PeerInfo peerInfo = peerInfoMap.get(peerId);
266 if(peerInfo != null) {
267 LOG.info("Peer address for peer {} set to {}", peerId, peerAddress);
268 peerInfo.setAddress(peerAddress);
273 public SnapshotManager getSnapshotManager() {
274 if(snapshotManager == null){
275 snapshotManager = new SnapshotManager(this, LOG);
277 return snapshotManager;
281 public long getTotalMemory() {
282 return totalMemoryRetriever.getAsLong();
286 public void setTotalMemoryRetriever(LongSupplier retriever) {
287 totalMemoryRetriever = retriever == null ? JVM_MEMORY_RETRIEVER : retriever;
291 public boolean hasFollowers() {
292 return getPeerIds().size() > 0;
296 public DataPersistenceProvider getPersistenceProvider() {
297 return persistenceProvider;
302 public RaftPolicy getRaftPolicy() {
303 return configParams.getRaftPolicy();
307 public boolean isDynamicServerConfigurationInUse() {
308 return dynamicServerConfiguration;
312 public void setDynamicServerConfigurationInUse() {
313 this.dynamicServerConfiguration = true;
317 public ServerConfigurationPayload getPeerServerInfo(boolean includeSelf) {
318 if (!isDynamicServerConfigurationInUse()) {
321 Collection<PeerInfo> peers = getPeers();
322 List<ServerInfo> newConfig = new ArrayList<>(peers.size() + 1);
323 for(PeerInfo peer: peers) {
324 newConfig.add(new ServerInfo(peer.getId(), peer.isVoting()));
328 newConfig.add(new ServerInfo(getId(), votingMember));
331 return (new ServerConfigurationPayload(newConfig));
335 public boolean isVotingMember() {
340 public boolean anyVotingPeers() {
341 if(numVotingPeers < 0) {
343 for(PeerInfo info: getPeers()) {
344 if(info.isVoting()) {
350 return numVotingPeers > 0;
354 public RaftActorBehavior getCurrentBehavior() {
355 return currentBehavior;
358 void setCurrentBehavior(final RaftActorBehavior behavior) {
359 this.currentBehavior = Preconditions.checkNotNull(behavior);
363 if (currentBehavior != null) {
365 currentBehavior.close();
366 } catch (Exception e) {
367 LOG.debug("{}: Error closing behavior {}", getId(), currentBehavior.state());