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
8 package org.opendaylight.controller.cluster.example;
10 import akka.actor.ActorRef;
11 import akka.actor.Props;
12 import com.google.common.io.ByteSource;
13 import java.io.IOException;
14 import java.io.OutputStream;
15 import java.io.Serializable;
16 import java.util.HashMap;
18 import java.util.Optional;
19 import org.apache.commons.lang3.SerializationUtils;
20 import org.opendaylight.controller.cluster.example.messages.KeyValue;
21 import org.opendaylight.controller.cluster.example.messages.KeyValueSaved;
22 import org.opendaylight.controller.cluster.example.messages.PrintRole;
23 import org.opendaylight.controller.cluster.example.messages.PrintState;
24 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
25 import org.opendaylight.controller.cluster.raft.ConfigParams;
26 import org.opendaylight.controller.cluster.raft.RaftActor;
27 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
28 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
29 import org.opendaylight.controller.cluster.raft.RaftState;
30 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
31 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
32 import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
33 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
34 import org.opendaylight.yangtools.concepts.Identifier;
35 import org.opendaylight.yangtools.util.AbstractStringIdentifier;
38 * A sample actor showing how the RaftActor is to be extended.
40 public class ExampleActor extends RaftActor implements RaftActorRecoveryCohort, RaftActorSnapshotCohort {
41 private static final class PayloadIdentifier extends AbstractStringIdentifier<PayloadIdentifier> {
42 private static final long serialVersionUID = 1L;
44 PayloadIdentifier(final long identifier) {
45 super(String.valueOf(identifier));
49 private final Map<String, String> state = new HashMap<>();
50 private final Optional<ActorRef> roleChangeNotifier;
52 private long persistIdentifier = 1;
54 public ExampleActor(final String id, final Map<String, String> peerAddresses,
55 final Optional<ConfigParams> configParams) {
56 super(id, peerAddresses, configParams, (short)0);
58 roleChangeNotifier = createRoleChangeNotifier(id);
61 public static Props props(final String id, final Map<String, String> peerAddresses,
62 final Optional<ConfigParams> configParams) {
63 return Props.create(ExampleActor.class, id, peerAddresses, configParams);
67 protected void handleNonRaftCommand(final Object message) {
68 if (message instanceof KeyValue) {
70 persistData(getSender(), new PayloadIdentifier(persistIdentifier++), (Payload) message, false);
72 if (getLeader() != null) {
73 getLeader().forward(message, getContext());
77 } else if (message instanceof PrintState) {
78 if (LOG.isDebugEnabled()) {
79 LOG.debug("State of the node:{} has entries={}, {}",
80 getId(), state.size(), getReplicatedLogState());
83 } else if (message instanceof PrintRole) {
84 if (LOG.isDebugEnabled()) {
85 if (getRaftState() == RaftState.Leader || getRaftState() == RaftState.IsolatedLeader) {
86 final String followers = ((Leader)this.getCurrentBehavior()).printFollowerStates();
87 LOG.debug("{} = {}, Peers={}, followers={}", getId(), getRaftState(),
88 getRaftActorContext().getPeerIds(), followers);
90 LOG.debug("{} = {}, Peers={}", getId(), getRaftState(),
91 getRaftActorContext().getPeerIds());
98 super.handleNonRaftCommand(message);
102 protected String getReplicatedLogState() {
103 return "snapshotIndex=" + getRaftActorContext().getReplicatedLog().getSnapshotIndex()
104 + ", snapshotTerm=" + getRaftActorContext().getReplicatedLog().getSnapshotTerm()
105 + ", im-mem journal size=" + getRaftActorContext().getReplicatedLog().size();
108 public Optional<ActorRef> createRoleChangeNotifier(final String actorId) {
109 ActorRef exampleRoleChangeNotifier = this.getContext().actorOf(
110 RoleChangeNotifier.getProps(actorId), actorId + "-notifier");
111 return Optional.<ActorRef>of(exampleRoleChangeNotifier);
115 protected Optional<ActorRef> getRoleChangeNotifier() {
116 return roleChangeNotifier;
120 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
121 if (data instanceof KeyValue) {
122 KeyValue kv = (KeyValue) data;
123 state.put(kv.getKey(), kv.getValue());
124 if (clientActor != null) {
125 clientActor.tell(new KeyValueSaved(), getSelf());
131 @SuppressWarnings("checkstyle:IllegalCatch")
132 public void createSnapshot(final ActorRef actorRef, final Optional<OutputStream> installSnapshotStream) {
134 if (installSnapshotStream.isPresent()) {
135 SerializationUtils.serialize((Serializable) state, installSnapshotStream.get());
137 } catch (RuntimeException e) {
138 LOG.error("Exception in creating snapshot", e);
141 getSelf().tell(new CaptureSnapshotReply(new MapState(state), installSnapshotStream), null);
145 public void applySnapshot(final Snapshot.State snapshotState) {
147 state.putAll(((MapState)snapshotState).state);
149 if (LOG.isDebugEnabled()) {
150 LOG.debug("Snapshot applied to state : {}", state.size());
155 protected void onStateChanged() {
160 public String persistenceId() {
165 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
170 public void startLogRecoveryBatch(final int maxBatchSize) {
174 public void appendRecoveredLogEntry(final Payload data) {
178 public void applyCurrentLogRecoveryBatch() {
182 public void onRecoveryComplete() {
186 public void applyRecoverySnapshot(final Snapshot.State snapshotState) {
190 protected RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
195 public Snapshot getRestoreFromSnapshot() {
199 @SuppressWarnings("unchecked")
201 public Snapshot.State deserializeSnapshot(final ByteSource snapshotBytes) {
203 return new MapState((Map<String, String>) SerializationUtils.deserialize(snapshotBytes.read()));
204 } catch (IOException e) {
205 throw new IllegalStateException(e);
209 private static class MapState implements Snapshot.State {
210 private static final long serialVersionUID = 1L;
212 Map<String, String> state;
214 MapState(final Map<String, String> state) {