f5ca3a86ec53e7ecacbfb3a617fa977c909c5cc5
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / Shard.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.datastore;
10
11 import akka.actor.ActorRef;
12 import akka.actor.ActorSelection;
13 import akka.actor.Cancellable;
14 import akka.actor.Props;
15 import akka.persistence.RecoveryFailure;
16 import akka.serialization.Serialization;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.Optional;
19 import com.google.common.base.Preconditions;
20 import java.io.IOException;
21 import java.util.Collections;
22 import java.util.Map;
23 import java.util.concurrent.TimeUnit;
24 import javax.annotation.Nonnull;
25 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
26 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
27 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
28 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
29 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
30 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
31 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
32 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
33 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
34 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
35 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
36 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
37 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
38 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
39 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
40 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
41 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
42 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot;
43 import org.opendaylight.controller.cluster.datastore.messages.DatastoreSnapshot.ShardSnapshot;
44 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
45 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
46 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
47 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
48 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
49 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
50 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
51 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
52 import org.opendaylight.controller.cluster.datastore.modification.Modification;
53 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
54 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
55 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
56 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
57 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
58 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
59 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
60 import org.opendaylight.controller.cluster.raft.RaftActor;
61 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
62 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
63 import org.opendaylight.controller.cluster.raft.RaftState;
64 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
65 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
66 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
67 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
68 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
72 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
73 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
74 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
75 import scala.concurrent.duration.Duration;
76 import scala.concurrent.duration.FiniteDuration;
77
78 /**
79  * A Shard represents a portion of the logical data tree <br/>
80  * <p>
81  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
82  * </p>
83  */
84 public class Shard extends RaftActor {
85
86     protected static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
87
88     @VisibleForTesting
89     static final Object GET_SHARD_MBEAN_MESSAGE = "getShardMBeanMessage";
90
91     @VisibleForTesting
92     static final String DEFAULT_NAME = "default";
93
94     // The state of this Shard
95     private final ShardDataTree store;
96
97     /// The name of this shard
98     private final String name;
99
100     private final ShardStats shardMBean;
101
102     private DatastoreContext datastoreContext;
103
104     private final ShardCommitCoordinator commitCoordinator;
105
106     private long transactionCommitTimeout;
107
108     private Cancellable txCommitTimeoutCheckSchedule;
109
110     private final Optional<ActorRef> roleChangeNotifier;
111
112     private final MessageTracker appendEntriesReplyTracker;
113
114     private final ShardTransactionActorFactory transactionActorFactory;
115
116     private final ShardSnapshotCohort snapshotCohort;
117
118     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
119     private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
120
121
122     private ShardSnapshot restoreFromSnapshot;
123
124     private final ShardTransactionMessageRetrySupport messageRetrySupport;
125
126     protected Shard(AbstractBuilder<?, ?> builder) {
127         super(builder.getId().toString(), builder.getPeerAddresses(),
128                 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
129
130         this.name = builder.getId().toString();
131         this.datastoreContext = builder.getDatastoreContext();
132         this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
133
134         setPersistence(datastoreContext.isPersistent());
135
136         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
137
138         store = new ShardDataTree(builder.getSchemaContext(), builder.getTreeType());
139
140         shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
141                 datastoreContext.getDataStoreMXBeanType());
142         shardMBean.setShard(this);
143
144         if (isMetricsCaptureEnabled()) {
145             getContext().become(new MeteringBehavior(this));
146         }
147
148         commitCoordinator = new ShardCommitCoordinator(store,
149                 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
150                 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, this.name);
151
152         setTransactionCommitTimeout();
153
154         // create a notifier actor for each cluster member
155         roleChangeNotifier = createRoleChangeNotifier(name.toString());
156
157         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
158                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
159
160         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
161                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
162                         Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
163
164         snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
165
166         messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
167     }
168
169     private void setTransactionCommitTimeout() {
170         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
171                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
172     }
173
174     private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
175         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
176             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
177         return Optional.of(shardRoleChangeNotifier);
178     }
179
180     @Override
181     public void postStop() {
182         LOG.info("Stopping Shard {}", persistenceId());
183
184         super.postStop();
185
186         messageRetrySupport.close();
187
188         if(txCommitTimeoutCheckSchedule != null) {
189             txCommitTimeoutCheckSchedule.cancel();
190         }
191
192         commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
193
194         shardMBean.unregisterMBean();
195     }
196
197     @Override
198     public void onReceiveRecover(final Object message) throws Exception {
199         if(LOG.isDebugEnabled()) {
200             LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
201                 message.getClass().toString(), getSender());
202         }
203
204         if (message instanceof RecoveryFailure){
205             LOG.error("{}: Recovery failed because of this cause",
206                     persistenceId(), ((RecoveryFailure) message).cause());
207
208             // Even though recovery failed, we still need to finish our recovery, eg send the
209             // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
210             onRecoveryComplete();
211         } else {
212             super.onReceiveRecover(message);
213             if(LOG.isTraceEnabled()) {
214                 appendEntriesReplyTracker.begin();
215             }
216         }
217     }
218
219     @Override
220     public void onReceiveCommand(final Object message) throws Exception {
221
222         MessageTracker.Context context = appendEntriesReplyTracker.received(message);
223
224         if(context.error().isPresent()){
225             LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
226                 context.error());
227         }
228
229         try {
230             if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
231                 handleCreateTransaction(message);
232             } else if (BatchedModifications.class.isInstance(message)) {
233                 handleBatchedModifications((BatchedModifications)message);
234             } else if (message instanceof ForwardedReadyTransaction) {
235                 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
236             } else if (message instanceof ReadyLocalTransaction) {
237                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
238             } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
239                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
240             } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
241                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
242             } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
243                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
244             } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
245                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
246             } else if (message instanceof RegisterChangeListener) {
247                 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
248             } else if (message instanceof RegisterDataTreeChangeListener) {
249                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
250             } else if (message instanceof UpdateSchemaContext) {
251                 updateSchemaContext((UpdateSchemaContext) message);
252             } else if (message instanceof PeerAddressResolved) {
253                 PeerAddressResolved resolved = (PeerAddressResolved) message;
254                 setPeerAddress(resolved.getPeerId().toString(),
255                         resolved.getPeerAddress());
256             } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
257                 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
258             } else if(message instanceof DatastoreContext) {
259                 onDatastoreContext((DatastoreContext)message);
260             } else if(message instanceof RegisterRoleChangeListener){
261                 roleChangeNotifier.get().forward(message, context());
262             } else if (message instanceof FollowerInitialSyncUpStatus) {
263                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
264                 context().parent().tell(message, self());
265             } else if(GET_SHARD_MBEAN_MESSAGE.equals(message)){
266                 sender().tell(getShardMBean(), self());
267             } else if(message instanceof GetShardDataTree) {
268                 sender().tell(store.getDataTree(), self());
269             } else if(message instanceof ServerRemoved){
270                 context().parent().forward(message, context());
271             } else if(ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
272                 messageRetrySupport.onTimerMessage(message);
273             } else {
274                 super.onReceiveCommand(message);
275             }
276         } finally {
277             context.done();
278         }
279     }
280
281     private boolean hasLeader() {
282         return getLeaderId() != null;
283     }
284
285     public int getPendingTxCommitQueueSize() {
286         return commitCoordinator.getQueueSize();
287     }
288
289     public int getCohortCacheSize() {
290         return commitCoordinator.getCohortCacheSize();
291     }
292
293     @Override
294     protected Optional<ActorRef> getRoleChangeNotifier() {
295         return roleChangeNotifier;
296     }
297
298     @Override
299     protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
300         return new ShardLeaderStateChanged(memberId, leaderId,
301                 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent(),
302                 leaderPayloadVersion);
303     }
304
305     protected void onDatastoreContext(DatastoreContext context) {
306         datastoreContext = context;
307
308         commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
309
310         setTransactionCommitTimeout();
311
312         if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
313             setPersistence(true);
314         } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
315             setPersistence(false);
316         }
317
318         updateConfigParams(datastoreContext.getShardRaftConfig());
319     }
320
321     private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
322         return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
323     }
324
325     void continueCommit(final CohortEntry cohortEntry) {
326         final DataTreeCandidate candidate = cohortEntry.getCandidate();
327
328         // If we do not have any followers and we are not using persistence
329         // or if cohortEntry has no modifications
330         // we can apply modification to the state immediately
331         if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
332             applyModificationToState(cohortEntry.getReplySender(), cohortEntry.getTransactionID(), candidate);
333         } else {
334             Shard.this.persistData(cohortEntry.getReplySender(), cohortEntry.getTransactionID(),
335                     DataTreeCandidatePayload.create(candidate));
336         }
337     }
338
339     private void handleCommitTransaction(final CommitTransaction commit) {
340         if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
341             shardMBean.incrementFailedTransactionsCount();
342         }
343     }
344
345     private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
346         LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
347
348         try {
349             cohortEntry.commit();
350
351             sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
352
353             shardMBean.incrementCommittedTransactionCount();
354             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
355
356         } catch (Exception e) {
357             sender.tell(new akka.actor.Status.Failure(e), getSelf());
358
359             LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
360                     transactionID, e);
361             shardMBean.incrementFailedTransactionsCount();
362         } finally {
363             commitCoordinator.currentTransactionComplete(transactionID, true);
364         }
365     }
366
367     private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
368         // With persistence enabled, this method is called via applyState by the leader strategy
369         // after the commit has been replicated to a majority of the followers.
370
371         CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
372         if (cohortEntry == null) {
373             // The transaction is no longer the current commit. This can happen if the transaction
374             // was aborted prior, most likely due to timeout in the front-end. We need to finish
375             // committing the transaction though since it was successfully persisted and replicated
376             // however we can't use the original cohort b/c it was already preCommitted and may
377             // conflict with the current commit or may have been aborted so we commit with a new
378             // transaction.
379             cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
380             if(cohortEntry != null) {
381                 try {
382                     store.applyForeignCandidate(transactionID, cohortEntry.getCandidate());
383                 } catch (DataValidationFailedException e) {
384                     shardMBean.incrementFailedTransactionsCount();
385                     LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
386                 }
387
388                 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
389             } else {
390                 // This really shouldn't happen - it likely means that persistence or replication
391                 // took so long to complete such that the cohort entry was expired from the cache.
392                 IllegalStateException ex = new IllegalStateException(
393                         String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
394                                 persistenceId(), transactionID));
395                 LOG.error(ex.getMessage());
396                 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
397             }
398         } else {
399             finishCommit(sender, transactionID, cohortEntry);
400         }
401     }
402
403     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
404         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
405         commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
406     }
407
408     protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
409         try {
410             commitCoordinator.handleBatchedModifications(batched, sender, this);
411         } catch (Exception e) {
412             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
413                     batched.getTransactionID(), e);
414             sender.tell(new akka.actor.Status.Failure(e), getSelf());
415         }
416     }
417
418     private void handleBatchedModifications(BatchedModifications batched) {
419         // This message is sent to prepare the modifications transaction directly on the Shard as an
420         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
421         // BatchedModifications message, the caller sets the ready flag in the message indicating
422         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
423         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
424         // ReadyTransaction message.
425
426         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
427         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
428         // the primary/leader shard. However with timing and caching on the front-end, there's a small
429         // window where it could have a stale leader during leadership transitions.
430         //
431         boolean isLeaderActive = isLeaderActive();
432         if (isLeader() && isLeaderActive) {
433             handleBatchedModificationsLocal(batched, getSender());
434         } else {
435             ActorSelection leader = getLeader();
436             if (!isLeaderActive || leader == null) {
437                 messageRetrySupport.addMessageToRetry(batched, getSender(),
438                         "Could not commit transaction " + batched.getTransactionID());
439             } else {
440                 // TODO: what if this is not the first batch and leadership changed in between batched messages?
441                 // We could check if the commitCoordinator already has a cached entry and forward all the previous
442                 // batched modifications.
443                 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
444                 leader.forward(batched, getContext());
445             }
446         }
447     }
448
449     private boolean failIfIsolatedLeader(ActorRef sender) {
450         if(isIsolatedLeader()) {
451             sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
452                     "Shard %s was the leader but has lost contact with all of its followers. Either all" +
453                     " other follower nodes are down or this node is isolated by a network partition.",
454                     persistenceId()))), getSelf());
455             return true;
456         }
457
458         return false;
459     }
460
461     protected boolean isIsolatedLeader() {
462         return getRaftState() == RaftState.IsolatedLeader;
463     }
464
465     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
466         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionID());
467
468         boolean isLeaderActive = isLeaderActive();
469         if (isLeader() && isLeaderActive) {
470             try {
471                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
472             } catch (Exception e) {
473                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
474                         message.getTransactionID(), e);
475                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
476             }
477         } else {
478             ActorSelection leader = getLeader();
479             if (!isLeaderActive || leader == null) {
480                 messageRetrySupport.addMessageToRetry(message, getSender(),
481                         "Could not commit transaction " + message.getTransactionID());
482             } else {
483                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
484                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
485                 leader.forward(message, getContext());
486             }
487         }
488     }
489
490     private void handleForwardedReadyTransaction(ForwardedReadyTransaction forwardedReady) {
491         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionID());
492
493         boolean isLeaderActive = isLeaderActive();
494         if (isLeader() && isLeaderActive) {
495             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
496         } else {
497             ActorSelection leader = getLeader();
498             if (!isLeaderActive || leader == null) {
499                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
500                         "Could not commit transaction " + forwardedReady.getTransactionID());
501             } else {
502                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
503
504                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionID(),
505                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
506                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
507                 leader.forward(readyLocal, getContext());
508             }
509         }
510     }
511
512     private void handleAbortTransaction(final AbortTransaction abort) {
513         doAbortTransaction(abort.getTransactionID(), getSender());
514     }
515
516     void doAbortTransaction(final String transactionID, final ActorRef sender) {
517         commitCoordinator.handleAbort(transactionID, sender, this);
518     }
519
520     private void handleCreateTransaction(final Object message) {
521         if (isLeader()) {
522             createTransaction(CreateTransaction.fromSerializable(message));
523         } else if (getLeader() != null) {
524             getLeader().forward(message, getContext());
525         } else {
526             getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
527                     "Could not create a shard transaction", persistenceId())), getSelf());
528         }
529     }
530
531     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
532         store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
533     }
534
535     private ActorRef createTypedTransactionActor(int transactionType,
536             ShardTransactionIdentifier transactionId, String transactionChainId,
537             short clientVersion ) {
538
539         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
540                 transactionId, transactionChainId, clientVersion);
541     }
542
543     private void createTransaction(CreateTransaction createTransaction) {
544         try {
545             if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
546                     failIfIsolatedLeader(getSender())) {
547                 return;
548             }
549
550             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
551                 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
552                 createTransaction.getVersion());
553
554             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
555                     createTransaction.getTransactionId()).toSerializable(), getSelf());
556         } catch (Exception e) {
557             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
558         }
559     }
560
561     private ActorRef createTransaction(int transactionType, String remoteTransactionId,
562             String transactionChainId, short clientVersion) {
563
564
565         ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
566
567         if(LOG.isDebugEnabled()) {
568             LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
569         }
570
571         ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
572                 transactionChainId, clientVersion);
573
574         return transactionActor;
575     }
576
577     private void commitWithNewTransaction(final Modification modification) {
578         ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
579         modification.apply(tx.getSnapshot());
580         try {
581             snapshotCohort.syncCommitTransaction(tx);
582             shardMBean.incrementCommittedTransactionCount();
583             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
584         } catch (Exception e) {
585             shardMBean.incrementFailedTransactionsCount();
586             LOG.error("{}: Failed to commit", persistenceId(), e);
587         }
588     }
589
590     private void updateSchemaContext(final UpdateSchemaContext message) {
591         updateSchemaContext(message.getSchemaContext());
592     }
593
594     @VisibleForTesting
595     void updateSchemaContext(final SchemaContext schemaContext) {
596         store.updateSchemaContext(schemaContext);
597     }
598
599     private boolean isMetricsCaptureEnabled() {
600         CommonConfig config = new CommonConfig(getContext().system().settings().config());
601         return config.isMetricCaptureEnabled();
602     }
603
604     @Override
605     @VisibleForTesting
606     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
607         return snapshotCohort;
608     }
609
610     @Override
611     @Nonnull
612     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
613         return new ShardRecoveryCoordinator(store, store.getSchemaContext(),
614                 restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
615     }
616
617     @Override
618     protected void onRecoveryComplete() {
619         restoreFromSnapshot = null;
620
621         //notify shard manager
622         getContext().parent().tell(new ActorInitialized(), getSelf());
623
624         // Being paranoid here - this method should only be called once but just in case...
625         if(txCommitTimeoutCheckSchedule == null) {
626             // Schedule a message to be periodically sent to check if the current in-progress
627             // transaction should be expired and aborted.
628             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
629             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
630                     period, period, getSelf(),
631                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
632         }
633     }
634
635     @Override
636     protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
637         if (data instanceof DataTreeCandidatePayload) {
638             if (clientActor == null) {
639                 // No clientActor indicates a replica coming from the leader
640                 try {
641                     store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
642                 } catch (DataValidationFailedException | IOException e) {
643                     LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
644                 }
645             } else {
646                 // Replication consensus reached, proceed to commit
647                 finishCommit(clientActor, identifier);
648             }
649         } else if (data instanceof ModificationPayload) {
650             try {
651                 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
652             } catch (ClassNotFoundException | IOException e) {
653                 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
654             }
655         } else if (data instanceof CompositeModificationPayload) {
656             Object modification = ((CompositeModificationPayload) data).getModification();
657
658             applyModificationToState(clientActor, identifier, modification);
659         } else if(data instanceof CompositeModificationByteStringPayload ){
660             Object modification = ((CompositeModificationByteStringPayload) data).getModification();
661
662             applyModificationToState(clientActor, identifier, modification);
663         } else {
664             LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
665                     persistenceId(), data, data.getClass().getClassLoader(),
666                     CompositeModificationPayload.class.getClassLoader());
667         }
668     }
669
670     private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
671         if(modification == null) {
672             LOG.error(
673                     "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
674                     persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
675         } else if(clientActor == null) {
676             // There's no clientActor to which to send a commit reply so we must be applying
677             // replicated state from the leader.
678             commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
679         } else {
680             // This must be the OK to commit after replication consensus.
681             finishCommit(clientActor, identifier);
682         }
683     }
684
685     @Override
686     protected void onStateChanged() {
687         boolean isLeader = isLeader();
688         boolean hasLeader = hasLeader();
689         changeSupport.onLeadershipChange(isLeader, hasLeader);
690         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
691
692         // If this actor is no longer the leader close all the transaction chains
693         if (!isLeader) {
694             if(LOG.isDebugEnabled()) {
695                 LOG.debug(
696                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
697                     persistenceId(), getId());
698             }
699
700             store.closeAllTransactionChains();
701
702             commitCoordinator.abortPendingTransactions(
703                     "The transacton was aborted due to inflight leadership change.", this);
704         }
705
706         if(hasLeader && !isIsolatedLeader()) {
707             messageRetrySupport.retryMessages();
708         }
709     }
710
711     @Override
712     protected void onLeaderChanged(String oldLeader, String newLeader) {
713         shardMBean.incrementLeadershipChangeCount();
714
715         if(hasLeader() && !isIsolatedLeader()) {
716             messageRetrySupport.retryMessages();
717         }
718     }
719
720     @Override
721     protected void pauseLeader(Runnable operation) {
722         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
723         commitCoordinator.setRunOnPendingTransactionsComplete(operation);
724     }
725
726     @Override
727     public String persistenceId() {
728         return this.name;
729     }
730
731     @VisibleForTesting
732     ShardCommitCoordinator getCommitCoordinator() {
733         return commitCoordinator;
734     }
735
736     public DatastoreContext getDatastoreContext() {
737         return datastoreContext;
738     }
739
740     @VisibleForTesting
741     public ShardDataTree getDataStore() {
742         return store;
743     }
744
745     @VisibleForTesting
746     ShardStats getShardMBean() {
747         return shardMBean;
748     }
749
750     public static Builder builder() {
751         return new Builder();
752     }
753
754     public static abstract class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
755         private final Class<S> shardClass;
756         private ShardIdentifier id;
757         private Map<String, String> peerAddresses = Collections.emptyMap();
758         private DatastoreContext datastoreContext;
759         private SchemaContext schemaContext;
760         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
761         private volatile boolean sealed;
762
763         protected AbstractBuilder(Class<S> shardClass) {
764             this.shardClass = shardClass;
765         }
766
767         protected void checkSealed() {
768             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
769         }
770
771         @SuppressWarnings("unchecked")
772         private T self() {
773             return (T) this;
774         }
775
776         public T id(ShardIdentifier id) {
777             checkSealed();
778             this.id = id;
779             return self();
780         }
781
782         public T peerAddresses(Map<String, String> peerAddresses) {
783             checkSealed();
784             this.peerAddresses = peerAddresses;
785             return self();
786         }
787
788         public T datastoreContext(DatastoreContext datastoreContext) {
789             checkSealed();
790             this.datastoreContext = datastoreContext;
791             return self();
792         }
793
794         public T schemaContext(SchemaContext schemaContext) {
795             checkSealed();
796             this.schemaContext = schemaContext;
797             return self();
798         }
799
800         public T restoreFromSnapshot(DatastoreSnapshot.ShardSnapshot restoreFromSnapshot) {
801             checkSealed();
802             this.restoreFromSnapshot = restoreFromSnapshot;
803             return self();
804         }
805
806         public ShardIdentifier getId() {
807             return id;
808         }
809
810         public Map<String, String> getPeerAddresses() {
811             return peerAddresses;
812         }
813
814         public DatastoreContext getDatastoreContext() {
815             return datastoreContext;
816         }
817
818         public SchemaContext getSchemaContext() {
819             return schemaContext;
820         }
821
822         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
823             return restoreFromSnapshot;
824         }
825
826         public TreeType getTreeType() {
827             switch (datastoreContext.getLogicalStoreType()) {
828             case CONFIGURATION:
829                 return TreeType.CONFIGURATION;
830             case OPERATIONAL:
831                 return TreeType.OPERATIONAL;
832             }
833
834             throw new IllegalStateException("Unhandled logical store type " + datastoreContext.getLogicalStoreType());
835         }
836
837         protected void verify() {
838             Preconditions.checkNotNull(id, "id should not be null");
839             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
840             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
841             Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
842         }
843
844         public Props props() {
845             sealed = true;
846             verify();
847             return Props.create(shardClass, this);
848         }
849     }
850
851     public static class Builder extends AbstractBuilder<Builder, Shard> {
852         private Builder() {
853             super(Shard.class);
854         }
855     }
856 }