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.example;
11 import akka.actor.ActorRef;
12 import akka.actor.Props;
13 import com.google.common.base.Optional;
14 import com.google.protobuf.ByteString;
15 import java.io.ByteArrayInputStream;
16 import java.io.ByteArrayOutputStream;
17 import java.io.IOException;
18 import java.io.ObjectInputStream;
19 import java.io.ObjectOutputStream;
20 import java.util.HashMap;
22 import javax.annotation.Nonnull;
23 import org.opendaylight.controller.cluster.example.messages.KeyValue;
24 import org.opendaylight.controller.cluster.example.messages.KeyValueSaved;
25 import org.opendaylight.controller.cluster.example.messages.PrintRole;
26 import org.opendaylight.controller.cluster.example.messages.PrintState;
27 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
28 import org.opendaylight.controller.cluster.raft.ConfigParams;
29 import org.opendaylight.controller.cluster.raft.RaftActor;
30 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
31 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
32 import org.opendaylight.controller.cluster.raft.RaftState;
33 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
34 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
35 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
38 * A sample actor showing how the RaftActor is to be extended
40 public class ExampleActor extends RaftActor implements RaftActorRecoveryCohort, RaftActorSnapshotCohort {
42 private final Map<String, String> state = new HashMap<>();
44 private long persistIdentifier = 1;
45 private final Optional<ActorRef> roleChangeNotifier;
48 public ExampleActor(String id, Map<String, String> peerAddresses,
49 Optional<ConfigParams> configParams) {
50 super(id, peerAddresses, configParams, (short)0);
52 roleChangeNotifier = createRoleChangeNotifier(id);
55 public static Props props(final String id, final Map<String, String> peerAddresses,
56 final Optional<ConfigParams> configParams) {
57 return Props.create(ExampleActor.class, id, peerAddresses, configParams);
61 protected void handleCommand(Object message) {
62 if(message instanceof KeyValue){
64 String persistId = Long.toString(persistIdentifier++);
65 persistData(getSender(), persistId, (Payload) message);
67 if(getLeader() != null) {
68 getLeader().forward(message, getContext());
72 } else if (message instanceof PrintState) {
73 if(LOG.isDebugEnabled()) {
74 LOG.debug("State of the node:{} has entries={}, {}",
75 getId(), state.size(), getReplicatedLogState());
78 } else if (message instanceof PrintRole) {
79 if(LOG.isDebugEnabled()) {
80 if (getRaftState() == RaftState.Leader || getRaftState() == RaftState.IsolatedLeader) {
81 final String followers = ((Leader)this.getCurrentBehavior()).printFollowerStates();
82 LOG.debug("{} = {}, Peers={}, followers={}", getId(), getRaftState(),
83 getRaftActorContext().getPeerIds(), followers);
85 LOG.debug("{} = {}, Peers={}", getId(), getRaftState(),
86 getRaftActorContext().getPeerIds());
93 super.handleCommand(message);
97 protected String getReplicatedLogState() {
98 return "snapshotIndex=" + getRaftActorContext().getReplicatedLog().getSnapshotIndex()
99 + ", snapshotTerm=" + getRaftActorContext().getReplicatedLog().getSnapshotTerm()
100 + ", im-mem journal size=" + getRaftActorContext().getReplicatedLog().size();
103 public Optional<ActorRef> createRoleChangeNotifier(String actorId) {
104 ActorRef exampleRoleChangeNotifier = this.getContext().actorOf(
105 RoleChangeNotifier.getProps(actorId), actorId + "-notifier");
106 return Optional.<ActorRef>of(exampleRoleChangeNotifier);
110 protected Optional<ActorRef> getRoleChangeNotifier() {
111 return roleChangeNotifier;
114 @Override protected void applyState(final ActorRef clientActor, final String identifier,
116 if(data instanceof KeyValue){
117 KeyValue kv = (KeyValue) data;
118 state.put(kv.getKey(), kv.getValue());
119 if(clientActor != null) {
120 clientActor.tell(new KeyValueSaved(), getSelf());
126 public void createSnapshot(ActorRef actorRef) {
127 ByteString bs = null;
129 bs = fromObject(state);
130 } catch (Exception e) {
131 LOG.error("Exception in creating snapshot", e);
133 getSelf().tell(new CaptureSnapshotReply(bs.toByteArray()), null);
137 public void applySnapshot(byte [] snapshot) {
140 state.putAll((HashMap<String, String>) toObject(snapshot));
141 } catch (Exception e) {
142 LOG.error("Exception in applying snapshot", e);
144 if(LOG.isDebugEnabled()) {
145 LOG.debug("Snapshot applied to state : {}", ((HashMap<?, ?>) state).size());
149 private static ByteString fromObject(Object snapshot) throws Exception {
150 ByteArrayOutputStream b = null;
151 ObjectOutputStream o = null;
153 b = new ByteArrayOutputStream();
154 o = new ObjectOutputStream(b);
155 o.writeObject(snapshot);
156 byte[] snapshotBytes = b.toByteArray();
157 return ByteString.copyFrom(snapshotBytes);
169 private static Object toObject(byte [] bs) throws ClassNotFoundException, IOException {
171 ByteArrayInputStream bis = null;
172 ObjectInputStream ois = null;
174 bis = new ByteArrayInputStream(bs);
175 ois = new ObjectInputStream(bis);
176 obj = ois.readObject();
188 @Override protected void onStateChanged() {
192 @Override public String persistenceId() {
198 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
203 public void startLogRecoveryBatch(int maxBatchSize) {
207 public void appendRecoveredLogEntry(Payload data) {
211 public void applyCurrentLogRecoveryBatch() {
215 public void onRecoveryComplete() {
219 public void applyRecoverySnapshot(byte[] snapshot) {
223 protected RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
228 public byte[] getRestoreFromSnapshot() {