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 org.opendaylight.controller.cluster.DataPersistenceProvider;
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.RaftState;
31 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
32 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
33 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
36 * A sample actor showing how the RaftActor is to be extended
38 public class ExampleActor extends RaftActor {
40 private final Map<String, String> state = new HashMap();
41 private final DataPersistenceProvider dataPersistenceProvider;
43 private long persistIdentifier = 1;
44 private final Optional<ActorRef> roleChangeNotifier;
47 public ExampleActor(String id, Map<String, String> peerAddresses,
48 Optional<ConfigParams> configParams) {
49 super(id, peerAddresses, configParams);
50 this.dataPersistenceProvider = new PersistentDataProvider();
51 roleChangeNotifier = createRoleChangeNotifier(id);
54 public static Props props(final String id, final Map<String, String> peerAddresses,
55 final Optional<ConfigParams> configParams) {
56 return Props.create(ExampleActor.class, id, peerAddresses, configParams);
59 @Override public void onReceiveCommand(Object message) throws Exception{
60 if(message instanceof KeyValue){
62 String persistId = Long.toString(persistIdentifier++);
63 persistData(getSender(), persistId, (Payload) message);
65 if(getLeader() != null) {
66 getLeader().forward(message, getContext());
70 } else if (message instanceof PrintState) {
71 if(LOG.isDebugEnabled()) {
72 LOG.debug("State of the node:{} has entries={}, {}",
73 getId(), state.size(), getReplicatedLogState());
76 } else if (message instanceof PrintRole) {
77 if(LOG.isDebugEnabled()) {
78 if (getRaftState() == RaftState.Leader || getRaftState() == RaftState.IsolatedLeader) {
79 final String followers = ((Leader)this.getCurrentBehavior()).printFollowerStates();
80 LOG.debug("{} = {}, Peers={}, followers={}", getId(), getRaftState(),
81 getRaftActorContext().getPeerAddresses().keySet(), followers);
83 LOG.debug("{} = {}, Peers={}", getId(), getRaftState(),
84 getRaftActorContext().getPeerAddresses().keySet());
91 super.onReceiveCommand(message);
95 protected String getReplicatedLogState() {
96 return "snapshotIndex=" + getRaftActorContext().getReplicatedLog().getSnapshotIndex()
97 + ", snapshotTerm=" + getRaftActorContext().getReplicatedLog().getSnapshotTerm()
98 + ", im-mem journal size=" + getRaftActorContext().getReplicatedLog().size();
101 public Optional<ActorRef> createRoleChangeNotifier(String actorId) {
102 ActorRef exampleRoleChangeNotifier = this.getContext().actorOf(
103 RoleChangeNotifier.getProps(actorId), actorId + "-notifier");
104 return Optional.<ActorRef>of(exampleRoleChangeNotifier);
108 protected Optional<ActorRef> getRoleChangeNotifier() {
109 return roleChangeNotifier;
112 @Override protected void applyState(final ActorRef clientActor, final String identifier,
114 if(data instanceof KeyValue){
115 KeyValue kv = (KeyValue) data;
116 state.put(kv.getKey(), kv.getValue());
117 if(clientActor != null) {
118 clientActor.tell(new KeyValueSaved(), getSelf());
123 @Override protected void createSnapshot() {
124 ByteString bs = null;
126 bs = fromObject(state);
127 } catch (Exception e) {
128 LOG.error(e, "Exception in creating snapshot");
130 getSelf().tell(new CaptureSnapshotReply(bs.toByteArray()), null);
133 @Override protected void applySnapshot(byte [] snapshot) {
136 state.putAll((HashMap) toObject(snapshot));
137 } catch (Exception e) {
138 LOG.error(e, "Exception in applying snapshot");
140 if(LOG.isDebugEnabled()) {
141 LOG.debug("Snapshot applied to state : {}", ((HashMap) state).size());
145 private ByteString fromObject(Object snapshot) throws Exception {
146 ByteArrayOutputStream b = null;
147 ObjectOutputStream o = null;
149 b = new ByteArrayOutputStream();
150 o = new ObjectOutputStream(b);
151 o.writeObject(snapshot);
152 byte[] snapshotBytes = b.toByteArray();
153 return ByteString.copyFrom(snapshotBytes);
165 private Object toObject(byte [] bs) throws ClassNotFoundException, IOException {
167 ByteArrayInputStream bis = null;
168 ObjectInputStream ois = null;
170 bis = new ByteArrayInputStream(bs);
171 ois = new ObjectInputStream(bis);
172 obj = ois.readObject();
184 @Override protected void onStateChanged() {
189 protected DataPersistenceProvider persistence() {
190 return dataPersistenceProvider;
193 @Override public void onReceiveRecover(Object message)throws Exception {
194 super.onReceiveRecover(message);
197 @Override public String persistenceId() {
202 protected void startLogRecoveryBatch(int maxBatchSize) {
206 protected void appendRecoveredLogEntry(Payload data) {
210 protected void applyCurrentLogRecoveryBatch() {
214 protected void onRecoveryComplete() {
218 protected void applyRecoverySnapshot(byte[] snapshot) {