Bug 7391: Fix out-of-order LeaderStateChange events
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / main / java / org / opendaylight / controller / cluster / raft / RaftActorSnapshotMessageSupport.java
1 /*
2  * Copyright (c) 2015 Brocade Communications 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 package org.opendaylight.controller.cluster.raft;
9
10 import akka.actor.ActorRef;
11 import akka.persistence.SaveSnapshotFailure;
12 import akka.persistence.SaveSnapshotSuccess;
13 import com.google.common.annotations.VisibleForTesting;
14 import java.util.Collections;
15 import java.util.concurrent.TimeUnit;
16 import org.apache.commons.lang3.SerializationUtils;
17 import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
18 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshot;
19 import org.opendaylight.controller.cluster.raft.base.messages.CaptureSnapshotReply;
20 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
21 import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshotReply;
22 import org.slf4j.Logger;
23 import scala.concurrent.duration.Duration;
24
25 /**
26  * Handles snapshot related messages for a RaftActor.
27  *
28  * @author Thomas Pantelis
29  */
30 class RaftActorSnapshotMessageSupport {
31     static final Object COMMIT_SNAPSHOT = new Object() {
32         @Override
33         public String toString() {
34             return "commit_snapshot";
35         }
36     };
37
38     private final RaftActorContext context;
39     private final RaftActorSnapshotCohort cohort;
40     private final Logger log;
41
42     private Duration snapshotReplyActorTimeout = Duration.create(30, TimeUnit.SECONDS);
43
44     RaftActorSnapshotMessageSupport(final RaftActorContext context, final RaftActorSnapshotCohort cohort) {
45         this.context = context;
46         this.cohort = cohort;
47         this.log = context.getLogger();
48
49         context.getSnapshotManager().setCreateSnapshotRunnable(() -> cohort.createSnapshot(context.getActor()));
50         context.getSnapshotManager().setApplySnapshotConsumer(cohort::applySnapshot);
51     }
52
53     boolean handleSnapshotMessage(Object message, ActorRef sender) {
54         if (message instanceof ApplySnapshot ) {
55             onApplySnapshot((ApplySnapshot) message);
56         } else if (message instanceof SaveSnapshotSuccess) {
57             onSaveSnapshotSuccess((SaveSnapshotSuccess) message);
58         } else if (message instanceof SaveSnapshotFailure) {
59             onSaveSnapshotFailure((SaveSnapshotFailure) message);
60         } else if (message instanceof CaptureSnapshotReply) {
61             onCaptureSnapshotReply(((CaptureSnapshotReply) message).getSnapshot());
62         } else if (COMMIT_SNAPSHOT.equals(message)) {
63             context.getSnapshotManager().commit(-1, -1);
64         } else if (message instanceof GetSnapshot) {
65             onGetSnapshot(sender);
66         } else {
67             return false;
68         }
69
70         return true;
71     }
72
73     private void onCaptureSnapshotReply(byte[] snapshotBytes) {
74         log.debug("{}: CaptureSnapshotReply received by actor: snapshot size {}", context.getId(),
75                 snapshotBytes.length);
76
77         context.getSnapshotManager().persist(snapshotBytes, context.getTotalMemory());
78     }
79
80     private void onSaveSnapshotFailure(SaveSnapshotFailure saveSnapshotFailure) {
81         log.error("{}: SaveSnapshotFailure received for snapshot Cause:",
82                 context.getId(), saveSnapshotFailure.cause());
83
84         context.getSnapshotManager().rollback();
85     }
86
87     private void onSaveSnapshotSuccess(SaveSnapshotSuccess success) {
88         long sequenceNumber = success.metadata().sequenceNr();
89
90         log.info("{}: SaveSnapshotSuccess received for snapshot, sequenceNr: {}", context.getId(), sequenceNumber);
91
92         context.getSnapshotManager().commit(sequenceNumber, success.metadata().timestamp());
93     }
94
95     private void onApplySnapshot(ApplySnapshot message) {
96         log.info("{}: Applying snapshot on follower:  {}", context.getId(), message.getSnapshot());
97
98         context.getSnapshotManager().apply(message);
99     }
100
101     private void onGetSnapshot(ActorRef sender) {
102         log.debug("{}: onGetSnapshot", context.getId());
103
104         if (context.getPersistenceProvider().isRecoveryApplicable()) {
105             CaptureSnapshot captureSnapshot = context.getSnapshotManager().newCaptureSnapshot(
106                     context.getReplicatedLog().last(), -1, false);
107
108             ActorRef snapshotReplyActor = context.actorOf(GetSnapshotReplyActor.props(captureSnapshot,
109                     ImmutableElectionTerm.copyOf(context.getTermInformation()), sender,
110                     snapshotReplyActorTimeout, context.getId(), context.getPeerServerInfo(true)));
111
112             cohort.createSnapshot(snapshotReplyActor);
113         } else {
114             Snapshot snapshot = Snapshot.create(new byte[0], Collections.<ReplicatedLogEntry>emptyList(),
115                     -1, -1, -1, -1,
116                     context.getTermInformation().getCurrentTerm(), context.getTermInformation().getVotedFor(),
117                     context.getPeerServerInfo(true));
118
119             sender.tell(new GetSnapshotReply(context.getId(), SerializationUtils.serialize(snapshot)),
120                     context.getActor());
121         }
122     }
123
124     @VisibleForTesting
125     void setSnapshotReplyActorTimeout(Duration snapshotReplyActorTimeout) {
126         this.snapshotReplyActorTimeout = snapshotReplyActorTimeout;
127     }
128 }