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.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;
33 public class RaftActorContextImpl implements RaftActorContext {
34 private static final LongSupplier JVM_MEMORY_RETRIEVER = () -> Runtime.getRuntime().maxMemory();
36 private final ActorRef actor;
38 private final ActorContext context;
40 private final String id;
42 private final ElectionTerm termInformation;
44 private long commitIndex;
46 private long lastApplied;
48 private ReplicatedLog replicatedLog;
50 private final Map<String, PeerInfo> peerInfoMap = new HashMap<>();
52 private final Logger LOG;
54 private ConfigParams configParams;
56 private boolean dynamicServerConfiguration = false;
59 private LongSupplier totalMemoryRetriever = JVM_MEMORY_RETRIEVER;
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;
65 private final DataPersistenceProvider persistenceProvider;
67 private short payloadVersion;
69 private boolean votingMember = true;
71 private RaftActorBehavior currentBehavior;
73 private int numVotingPeers = -1;
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) {
79 this.context = context;
81 this.termInformation = termInformation;
82 this.commitIndex = commitIndex;
83 this.lastApplied = lastApplied;
84 this.configParams = configParams;
85 this.persistenceProvider = persistenceProvider;
88 for(Map.Entry<String, String> e: peerAddresses.entrySet()) {
89 peerInfoMap.put(e.getKey(), new PeerInfo(e.getKey(), e.getValue(), VotingState.VOTING));
94 public void setPayloadVersion(short payloadVersion) {
95 this.payloadVersion = payloadVersion;
99 public short getPayloadVersion() {
100 return payloadVersion;
103 public void setConfigParams(ConfigParams configParams) {
104 this.configParams = configParams;
108 public ActorRef actorOf(Props props){
109 return context.actorOf(props);
113 public ActorSelection actorSelection(String path){
114 return context.actorSelection(path);
118 public String getId() {
123 public ActorRef getActor() {
128 public ElectionTerm getTermInformation() {
129 return termInformation;
133 public long getCommitIndex() {
137 @Override public void setCommitIndex(long commitIndex) {
138 this.commitIndex = commitIndex;
142 public long getLastApplied() {
147 public void setLastApplied(long lastApplied) {
148 this.lastApplied = lastApplied;
152 public void setReplicatedLog(ReplicatedLog replicatedLog) {
153 this.replicatedLog = replicatedLog;
157 public ReplicatedLog getReplicatedLog() {
158 return replicatedLog;
161 @Override public ActorSystem getActorSystem() {
162 return context.system();
165 @Override public Logger getLogger() {
170 public Collection<String> getPeerIds() {
171 return peerInfoMap.keySet();
175 public Collection<PeerInfo> getPeers() {
176 return peerInfoMap.values();
180 public PeerInfo getPeerInfo(String peerId) {
181 return peerInfoMap.get(peerId);
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);
195 peerAddress = configParams.getPeerAddressResolver().resolve(peerId);
202 public void updatePeerIds(ServerConfigurationPayload serverConfig){
204 boolean foundSelf = false;
205 Set<String> currentPeers = new HashSet<>(this.getPeerIds());
206 for(ServerInfo server: serverConfig.getServerConfig()) {
207 if(getId().equals(server.getId())) {
209 if(!server.isVoting()) {
210 votingMember = false;
213 VotingState votingState = server.isVoting() ? VotingState.VOTING: VotingState.NON_VOTING;
214 if(!currentPeers.contains(server.getId())) {
215 this.addToPeers(server.getId(), null, votingState);
217 this.getPeerInfo(server.getId()).setVotingState(votingState);
218 currentPeers.remove(server.getId());
223 for(String peerIdToRemove: currentPeers) {
224 this.removePeer(peerIdToRemove);
228 votingMember = false;
231 LOG.debug("{}: Updated server config: isVoting: {}, peers: {}", id, votingMember, peerInfoMap.values());
233 setDynamicServerConfigurationInUse();
236 @Override public ConfigParams getConfigParams() {
241 public void addToPeers(String id, String address, VotingState votingState) {
242 peerInfoMap.put(id, new PeerInfo(id, address, votingState));
247 public void removePeer(String name) {
248 if(getId().equals(name)) {
249 votingMember = false;
251 peerInfoMap.remove(name);
256 @Override public ActorSelection getPeerActorSelection(String peerId) {
257 String peerAddress = getPeerAddress(peerId);
258 if(peerAddress != null){
259 return actorSelection(peerAddress);
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);
274 public SnapshotManager getSnapshotManager() {
275 if(snapshotManager == null){
276 snapshotManager = new SnapshotManager(this, LOG);
278 return snapshotManager;
282 public long getTotalMemory() {
283 return totalMemoryRetriever.getAsLong();
287 public void setTotalMemoryRetriever(LongSupplier retriever) {
288 totalMemoryRetriever = retriever == null ? JVM_MEMORY_RETRIEVER : retriever;
292 public boolean hasFollowers() {
293 return getPeerIds().size() > 0;
297 public DataPersistenceProvider getPersistenceProvider() {
298 return persistenceProvider;
303 public RaftPolicy getRaftPolicy() {
304 return configParams.getRaftPolicy();
308 public boolean isDynamicServerConfigurationInUse() {
309 return dynamicServerConfiguration;
313 public void setDynamicServerConfigurationInUse() {
314 this.dynamicServerConfiguration = true;
318 public ServerConfigurationPayload getPeerServerInfo(boolean includeSelf) {
319 if (!isDynamicServerConfigurationInUse()) {
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()));
329 newConfig.add(new ServerInfo(getId(), votingMember));
332 return (new ServerConfigurationPayload(newConfig));
336 public boolean isVotingMember() {
341 public boolean anyVotingPeers() {
342 if(numVotingPeers < 0) {
344 for(PeerInfo info: getPeers()) {
345 if(info.isVoting()) {
351 return numVotingPeers > 0;
355 public RaftActorBehavior getCurrentBehavior() {
356 return currentBehavior;
359 void setCurrentBehavior(final RaftActorBehavior behavior) {
360 this.currentBehavior = Preconditions.checkNotNull(behavior);
364 if (currentBehavior != null) {
366 currentBehavior.close();
367 } catch (Exception e) {
368 LOG.debug("{}: Error closing behavior {}", getId(), currentBehavior.state());