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.base.Throwables;
13 import com.google.common.io.ByteSource;
14 import java.io.IOException;
15 import java.io.OutputStream;
16 import java.io.Serializable;
17 import java.util.HashMap;
19 import java.util.Optional;
20 import org.apache.commons.lang3.SerializationUtils;
21 import org.opendaylight.controller.cluster.example.messages.KeyValue;
22 import org.opendaylight.controller.cluster.example.messages.KeyValueSaved;
23 import org.opendaylight.controller.cluster.example.messages.PrintRole;
24 import org.opendaylight.controller.cluster.example.messages.PrintState;
25 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
26 import org.opendaylight.controller.cluster.raft.ConfigParams;
27 import org.opendaylight.controller.cluster.raft.RaftActor;
28 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
29 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
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.persisted.Snapshot;
34 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
35 import org.opendaylight.yangtools.concepts.Identifier;
36 import org.opendaylight.yangtools.util.AbstractStringIdentifier;
39 * A sample actor showing how the RaftActor is to be extended.
41 public class ExampleActor extends RaftActor implements RaftActorRecoveryCohort, RaftActorSnapshotCohort {
42 private static final class PayloadIdentifier extends AbstractStringIdentifier<PayloadIdentifier> {
43 private static final long serialVersionUID = 1L;
45 PayloadIdentifier(final long identifier) {
46 super(String.valueOf(identifier));
50 private final Map<String, String> state = new HashMap<>();
51 private final Optional<ActorRef> roleChangeNotifier;
53 private long persistIdentifier = 1;
55 public ExampleActor(final String id, final Map<String, String> peerAddresses,
56 final Optional<ConfigParams> configParams) {
57 super(id, peerAddresses, configParams, (short)0);
59 roleChangeNotifier = createRoleChangeNotifier(id);
62 public static Props props(final String id, final Map<String, String> peerAddresses,
63 final Optional<ConfigParams> configParams) {
64 return Props.create(ExampleActor.class, id, peerAddresses, configParams);
68 protected void handleNonRaftCommand(final Object message) {
69 if (message instanceof KeyValue) {
71 persistData(getSender(), new PayloadIdentifier(persistIdentifier++), (Payload) message, false);
73 if (getLeader() != null) {
74 getLeader().forward(message, getContext());
78 } else if (message instanceof PrintState) {
79 if (LOG.isDebugEnabled()) {
80 LOG.debug("State of the node:{} has entries={}, {}",
81 getId(), state.size(), getReplicatedLogState());
84 } else if (message instanceof PrintRole) {
85 if (LOG.isDebugEnabled()) {
86 if (getRaftState() == RaftState.Leader || getRaftState() == RaftState.IsolatedLeader) {
87 final String followers = ((Leader)this.getCurrentBehavior()).printFollowerStates();
88 LOG.debug("{} = {}, Peers={}, followers={}", getId(), getRaftState(),
89 getRaftActorContext().getPeerIds(), followers);
91 LOG.debug("{} = {}, Peers={}", getId(), getRaftState(),
92 getRaftActorContext().getPeerIds());
99 super.handleNonRaftCommand(message);
103 protected String getReplicatedLogState() {
104 return "snapshotIndex=" + getRaftActorContext().getReplicatedLog().getSnapshotIndex()
105 + ", snapshotTerm=" + getRaftActorContext().getReplicatedLog().getSnapshotTerm()
106 + ", im-mem journal size=" + getRaftActorContext().getReplicatedLog().size();
109 public Optional<ActorRef> createRoleChangeNotifier(final String actorId) {
110 ActorRef exampleRoleChangeNotifier = this.getContext().actorOf(
111 RoleChangeNotifier.getProps(actorId), actorId + "-notifier");
112 return Optional.<ActorRef>of(exampleRoleChangeNotifier);
116 protected Optional<ActorRef> getRoleChangeNotifier() {
117 return roleChangeNotifier;
121 protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
122 if (data instanceof KeyValue) {
123 KeyValue kv = (KeyValue) data;
124 state.put(kv.getKey(), kv.getValue());
125 if (clientActor != null) {
126 clientActor.tell(new KeyValueSaved(), getSelf());
132 @SuppressWarnings("checkstyle:IllegalCatch")
133 public void createSnapshot(final ActorRef actorRef, final Optional<OutputStream> installSnapshotStream) {
135 if (installSnapshotStream.isPresent()) {
136 SerializationUtils.serialize((Serializable) state, installSnapshotStream.get());
138 } catch (RuntimeException e) {
139 LOG.error("Exception in creating snapshot", e);
142 getSelf().tell(new CaptureSnapshotReply(new MapState(state), installSnapshotStream), null);
146 public void applySnapshot(final Snapshot.State snapshotState) {
148 state.putAll(((MapState)snapshotState).state);
150 if (LOG.isDebugEnabled()) {
151 LOG.debug("Snapshot applied to state : {}", state.size());
156 protected void onStateChanged() {
161 public String persistenceId() {
166 protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
171 public void startLogRecoveryBatch(final int maxBatchSize) {
175 public void appendRecoveredLogEntry(final Payload data) {
179 public void applyCurrentLogRecoveryBatch() {
183 public void onRecoveryComplete() {
187 public void applyRecoverySnapshot(final Snapshot.State snapshotState) {
191 protected RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
196 public Snapshot getRestoreFromSnapshot() {
200 @SuppressWarnings("unchecked")
202 public Snapshot.State deserializeSnapshot(final ByteSource snapshotBytes) {
204 return new MapState((Map<String, String>) SerializationUtils.deserialize(snapshotBytes.read()));
205 } catch (IOException e) {
206 throw Throwables.propagate(e);
210 private static class MapState implements Snapshot.State {
211 private static final long serialVersionUID = 1L;
213 Map<String, String> state;
215 MapState(final Map<String, String> state) {