c4ff108611d9fbdb177f2ef4ace98bb030d69991
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / example / ExampleActor.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.controller.cluster.example;
10
11 import akka.actor.ActorRef;
12 import akka.actor.Props;
13 import akka.japi.Creator;
14 import com.google.common.base.Optional;
15 import com.google.protobuf.ByteString;
16 import org.opendaylight.controller.cluster.example.messages.KeyValue;
17 import org.opendaylight.controller.cluster.example.messages.KeyValueSaved;
18 import org.opendaylight.controller.cluster.example.messages.PrintRole;
19 import org.opendaylight.controller.cluster.example.messages.PrintState;
20 import org.opendaylight.controller.cluster.raft.ConfigParams;
21 import org.opendaylight.controller.cluster.raft.RaftActor;
22 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
23 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
24
25 import java.io.ByteArrayInputStream;
26 import java.io.ByteArrayOutputStream;
27 import java.io.IOException;
28 import java.io.ObjectInputStream;
29 import java.io.ObjectOutputStream;
30 import java.util.HashMap;
31 import java.util.Map;
32
33 /**
34  * A sample actor showing how the RaftActor is to be extended
35  */
36 public class ExampleActor extends RaftActor {
37
38     private final Map<String, String> state = new HashMap();
39
40     private long persistIdentifier = 1;
41
42
43     public ExampleActor(String id, Map<String, String> peerAddresses,
44         Optional<ConfigParams> configParams) {
45         super(id, peerAddresses, configParams);
46     }
47
48     public static Props props(final String id, final Map<String, String> peerAddresses,
49         final Optional<ConfigParams> configParams){
50         return Props.create(new Creator<ExampleActor>(){
51
52             @Override public ExampleActor create() throws Exception {
53                 return new ExampleActor(id, peerAddresses, configParams);
54             }
55         });
56     }
57
58     @Override public void onReceiveCommand(Object message){
59         if(message instanceof KeyValue){
60             if(isLeader()) {
61                 String persistId = Long.toString(persistIdentifier++);
62                 persistData(getSender(), persistId, (Payload) message);
63             } else {
64                 if(getLeader() != null) {
65                     getLeader().forward(message, getContext());
66                 }
67             }
68
69         } else if (message instanceof PrintState) {
70             LOG.debug("State of the node:{} has entries={}, {}",
71                 getId(), state.size(), getReplicatedLogState());
72
73         } else if (message instanceof PrintRole) {
74             LOG.debug("{} = {}, Peers={}", getId(), getRaftState(),getPeers());
75
76         } else {
77             super.onReceiveCommand(message);
78         }
79     }
80
81     @Override protected void applyState(ActorRef clientActor, String identifier,
82         Object data) {
83         if(data instanceof KeyValue){
84             KeyValue kv = (KeyValue) data;
85             state.put(kv.getKey(), kv.getValue());
86             if(clientActor != null) {
87                 clientActor.tell(new KeyValueSaved(), getSelf());
88             }
89         }
90     }
91
92     @Override protected void createSnapshot() {
93         ByteString bs = null;
94         try {
95             bs = fromObject(state);
96         } catch (Exception e) {
97             LOG.error("Exception in creating snapshot", e);
98         }
99         getSelf().tell(new CaptureSnapshotReply(bs), null);
100     }
101
102     @Override protected void applySnapshot(ByteString snapshot) {
103         state.clear();
104         try {
105             state.putAll((HashMap) toObject(snapshot));
106         } catch (Exception e) {
107            LOG.error("Exception in applying snapshot", e);
108         }
109         LOG.debug("Snapshot applied to state :" + ((HashMap) state).size());
110     }
111
112     private ByteString fromObject(Object snapshot) throws Exception {
113         ByteArrayOutputStream b = null;
114         ObjectOutputStream o = null;
115         try {
116             b = new ByteArrayOutputStream();
117             o = new ObjectOutputStream(b);
118             o.writeObject(snapshot);
119             byte[] snapshotBytes = b.toByteArray();
120             return ByteString.copyFrom(snapshotBytes);
121         } finally {
122             if (o != null) {
123                 o.flush();
124                 o.close();
125             }
126             if (b != null) {
127                 b.close();
128             }
129         }
130     }
131
132     private Object toObject(ByteString bs) throws ClassNotFoundException, IOException {
133         Object obj = null;
134         ByteArrayInputStream bis = null;
135         ObjectInputStream ois = null;
136         try {
137             bis = new ByteArrayInputStream(bs.toByteArray());
138             ois = new ObjectInputStream(bis);
139             obj = ois.readObject();
140         } finally {
141             if (bis != null) {
142                 bis.close();
143             }
144             if (ois != null) {
145                 ois.close();
146             }
147         }
148         return obj;
149     }
150
151     @Override protected void onStateChanged() {
152
153     }
154
155     @Override public void onReceiveRecover(Object message) {
156         super.onReceiveRecover(message);
157     }
158
159     @Override public String persistenceId() {
160         return getId();
161     }
162 }