Add getOwnershipState method to EntityOwnershipService
[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.japi.Creator;
16 import akka.persistence.RecoveryFailure;
17 import akka.serialization.Serialization;
18 import com.google.common.annotations.VisibleForTesting;
19 import com.google.common.base.Optional;
20 import com.google.common.base.Preconditions;
21 import java.io.IOException;
22 import java.util.HashMap;
23 import java.util.Map;
24 import java.util.concurrent.TimeUnit;
25 import javax.annotation.Nonnull;
26 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
27 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
28 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
29 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
30 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
31 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
32 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
33 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
34 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
35 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
36 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
37 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
38 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
39 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
40 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
41 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
43 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
44 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
45 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
46 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
47 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
48 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
49 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
50 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
51 import org.opendaylight.controller.cluster.datastore.modification.Modification;
52 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
53 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
54 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
55 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
56 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
57 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
58 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
59 import org.opendaylight.controller.cluster.raft.RaftActor;
60 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
61 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
62 import org.opendaylight.controller.cluster.raft.RaftState;
63 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
64 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
65 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
66 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
67 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
68 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
69 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
70 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import scala.concurrent.duration.Duration;
73 import scala.concurrent.duration.FiniteDuration;
74
75 /**
76  * A Shard represents a portion of the logical data tree <br/>
77  * <p>
78  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
79  * </p>
80  */
81 public class Shard extends RaftActor {
82
83     protected static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
84
85     @VisibleForTesting
86     static final Object GET_SHARD_MBEAN_MESSAGE = "getShardMBeanMessage";
87
88     @VisibleForTesting
89     static final String DEFAULT_NAME = "default";
90
91     // The state of this Shard
92     private final ShardDataTree store;
93
94     /// The name of this shard
95     private final String name;
96
97     private final ShardStats shardMBean;
98
99     private DatastoreContext datastoreContext;
100
101     private final ShardCommitCoordinator commitCoordinator;
102
103     private long transactionCommitTimeout;
104
105     private Cancellable txCommitTimeoutCheckSchedule;
106
107     private final Optional<ActorRef> roleChangeNotifier;
108
109     private final MessageTracker appendEntriesReplyTracker;
110
111     private final ShardTransactionActorFactory transactionActorFactory;
112
113     private final ShardSnapshotCohort snapshotCohort;
114
115     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
116     private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
117
118     protected Shard(final ShardIdentifier name, final Map<String, String> peerAddresses,
119             final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
120         super(name.toString(), new HashMap<>(peerAddresses), Optional.of(datastoreContext.getShardRaftConfig()),
121                 DataStoreVersions.CURRENT_VERSION);
122
123         this.name = name.toString();
124         this.datastoreContext = datastoreContext;
125
126         setPersistence(datastoreContext.isPersistent());
127
128         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
129
130         store = new ShardDataTree(schemaContext);
131
132         shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
133                 datastoreContext.getDataStoreMXBeanType());
134         shardMBean.setShard(this);
135
136         if (isMetricsCaptureEnabled()) {
137             getContext().become(new MeteringBehavior(this));
138         }
139
140         commitCoordinator = new ShardCommitCoordinator(store,
141                 datastoreContext.getShardCommitQueueExpiryTimeoutInMillis(),
142                 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
143
144         setTransactionCommitTimeout();
145
146         // create a notifier actor for each cluster member
147         roleChangeNotifier = createRoleChangeNotifier(name.toString());
148
149         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
150                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
151
152         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
153                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
154                         Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
155
156         snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
157
158
159     }
160
161     private void setTransactionCommitTimeout() {
162         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
163                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
164     }
165
166     public static Props props(final ShardIdentifier name, final Map<String, String> peerAddresses,
167             final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
168         return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
169     }
170
171     private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
172         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
173             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
174         return Optional.of(shardRoleChangeNotifier);
175     }
176
177     @Override
178     public void postStop() {
179         LOG.info("Stopping Shard {}", persistenceId());
180
181         super.postStop();
182
183         if(txCommitTimeoutCheckSchedule != null) {
184             txCommitTimeoutCheckSchedule.cancel();
185         }
186
187         shardMBean.unregisterMBean();
188     }
189
190     @Override
191     public void onReceiveRecover(final Object message) throws Exception {
192         if(LOG.isDebugEnabled()) {
193             LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
194                 message.getClass().toString(), getSender());
195         }
196
197         if (message instanceof RecoveryFailure){
198             LOG.error("{}: Recovery failed because of this cause",
199                     persistenceId(), ((RecoveryFailure) message).cause());
200
201             // Even though recovery failed, we still need to finish our recovery, eg send the
202             // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
203             onRecoveryComplete();
204         } else {
205             super.onReceiveRecover(message);
206             if(LOG.isTraceEnabled()) {
207                 appendEntriesReplyTracker.begin();
208             }
209         }
210     }
211
212     @Override
213     public void onReceiveCommand(final Object message) throws Exception {
214
215         MessageTracker.Context context = appendEntriesReplyTracker.received(message);
216
217         if(context.error().isPresent()){
218             LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
219                 context.error());
220         }
221
222         try {
223             if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
224                 handleCreateTransaction(message);
225             } else if (BatchedModifications.class.isInstance(message)) {
226                 handleBatchedModifications((BatchedModifications)message);
227             } else if (message instanceof ForwardedReadyTransaction) {
228                 commitCoordinator.handleForwardedReadyTransaction((ForwardedReadyTransaction) message,
229                         getSender(), this);
230             } else if (message instanceof ReadyLocalTransaction) {
231                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
232             } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
233                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
234             } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
235                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
236             } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
237                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
238             } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
239                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
240             } else if (message instanceof RegisterChangeListener) {
241                 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
242             } else if (message instanceof RegisterDataTreeChangeListener) {
243                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
244             } else if (message instanceof UpdateSchemaContext) {
245                 updateSchemaContext((UpdateSchemaContext) message);
246             } else if (message instanceof PeerAddressResolved) {
247                 PeerAddressResolved resolved = (PeerAddressResolved) message;
248                 setPeerAddress(resolved.getPeerId().toString(),
249                         resolved.getPeerAddress());
250             } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
251                 handleTransactionCommitTimeoutCheck();
252             } else if(message instanceof DatastoreContext) {
253                 onDatastoreContext((DatastoreContext)message);
254             } else if(message instanceof RegisterRoleChangeListener){
255                 roleChangeNotifier.get().forward(message, context());
256             } else if (message instanceof FollowerInitialSyncUpStatus) {
257                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
258                 context().parent().tell(message, self());
259             } else if(GET_SHARD_MBEAN_MESSAGE.equals(message)){
260                 sender().tell(getShardMBean(), self());
261             } else if(message instanceof GetShardDataTree){
262                 sender().tell(store.getDataTree(), self());
263             } else {
264                 super.onReceiveCommand(message);
265             }
266         } finally {
267             context.done();
268         }
269     }
270
271     private boolean hasLeader() {
272         return getLeaderId() != null;
273     }
274
275     public int getPendingTxCommitQueueSize() {
276         return commitCoordinator.getQueueSize();
277     }
278
279     @Override
280     protected Optional<ActorRef> getRoleChangeNotifier() {
281         return roleChangeNotifier;
282     }
283
284     @Override
285     protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId, short leaderPayloadVersion) {
286         return new ShardLeaderStateChanged(memberId, leaderId,
287                 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent(),
288                 leaderPayloadVersion);
289     }
290
291     protected void onDatastoreContext(DatastoreContext context) {
292         datastoreContext = context;
293
294         commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
295
296         setTransactionCommitTimeout();
297
298         if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
299             setPersistence(true);
300         } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
301             setPersistence(false);
302         }
303
304         updateConfigParams(datastoreContext.getShardRaftConfig());
305     }
306
307     private void handleTransactionCommitTimeoutCheck() {
308         CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
309         if(cohortEntry != null) {
310             if(cohortEntry.isExpired(transactionCommitTimeout)) {
311                 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
312                         persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
313
314                 doAbortTransaction(cohortEntry.getTransactionID(), null);
315             }
316         }
317
318         commitCoordinator.cleanupExpiredCohortEntries();
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) throws Exception {
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     private void noLeaderError(String errMessage, Object message) {
409         // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
410         // it more resilient in case we're in the process of electing a new leader.
411         getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(errMessage, persistenceId())), getSelf());
412     }
413
414     protected void handleBatchedModificationsLocal(BatchedModifications batched, ActorRef sender) {
415         try {
416             commitCoordinator.handleBatchedModifications(batched, sender, this);
417         } catch (Exception e) {
418             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
419                     batched.getTransactionID(), e);
420             sender.tell(new akka.actor.Status.Failure(e), getSelf());
421         }
422     }
423
424     private void handleBatchedModifications(BatchedModifications batched) {
425         // This message is sent to prepare the modifications transaction directly on the Shard as an
426         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
427         // BatchedModifications message, the caller sets the ready flag in the message indicating
428         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
429         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
430         // ReadyTransaction message.
431
432         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
433         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
434         // the primary/leader shard. However with timing and caching on the front-end, there's a small
435         // window where it could have a stale leader during leadership transitions.
436         //
437         if(isLeader()) {
438             failIfIsolatedLeader(getSender());
439
440             handleBatchedModificationsLocal(batched, getSender());
441         } else {
442             ActorSelection leader = getLeader();
443             if(leader != null) {
444                 // TODO: what if this is not the first batch and leadership changed in between batched messages?
445                 // We could check if the commitCoordinator already has a cached entry and forward all the previous
446                 // batched modifications.
447                 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
448                 leader.forward(batched, getContext());
449             } else {
450                 noLeaderError("Could not commit transaction " + batched.getTransactionID(), batched);
451             }
452         }
453     }
454
455     private boolean failIfIsolatedLeader(ActorRef sender) {
456         if(isIsolatedLeader()) {
457             sender.tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
458                     "Shard %s was the leader but has lost contact with all of its followers. Either all" +
459                     " other follower nodes are down or this node is isolated by a network partition.",
460                     persistenceId()))), getSelf());
461             return true;
462         }
463
464         return false;
465     }
466
467     protected boolean isIsolatedLeader() {
468         return getRaftState() == RaftState.IsolatedLeader;
469     }
470
471     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
472         if (isLeader()) {
473             failIfIsolatedLeader(getSender());
474
475             try {
476                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
477             } catch (Exception e) {
478                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
479                         message.getTransactionID(), e);
480                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
481             }
482         } else {
483             ActorSelection leader = getLeader();
484             if (leader != null) {
485                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
486                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
487                 leader.forward(message, getContext());
488             } else {
489                 noLeaderError("Could not commit transaction " + message.getTransactionID(), message);
490             }
491         }
492     }
493
494     private void handleAbortTransaction(final AbortTransaction abort) {
495         doAbortTransaction(abort.getTransactionID(), getSender());
496     }
497
498     void doAbortTransaction(final String transactionID, final ActorRef sender) {
499         commitCoordinator.handleAbort(transactionID, sender, this);
500     }
501
502     private void handleCreateTransaction(final Object message) {
503         if (isLeader()) {
504             createTransaction(CreateTransaction.fromSerializable(message));
505         } else if (getLeader() != null) {
506             getLeader().forward(message, getContext());
507         } else {
508             getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(
509                     "Could not create a shard transaction", persistenceId())), getSelf());
510         }
511     }
512
513     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
514         store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
515     }
516
517     private ActorRef createTypedTransactionActor(int transactionType,
518             ShardTransactionIdentifier transactionId, String transactionChainId,
519             short clientVersion ) {
520
521         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
522                 transactionId, transactionChainId, clientVersion);
523     }
524
525     private void createTransaction(CreateTransaction createTransaction) {
526         try {
527             if(TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY &&
528                     failIfIsolatedLeader(getSender())) {
529                 return;
530             }
531
532             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
533                 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
534                 createTransaction.getVersion());
535
536             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
537                     createTransaction.getTransactionId()).toSerializable(), getSelf());
538         } catch (Exception e) {
539             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
540         }
541     }
542
543     private ActorRef createTransaction(int transactionType, String remoteTransactionId,
544             String transactionChainId, short clientVersion) {
545
546
547         ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
548
549         if(LOG.isDebugEnabled()) {
550             LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
551         }
552
553         ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
554                 transactionChainId, clientVersion);
555
556         return transactionActor;
557     }
558
559     private void commitWithNewTransaction(final Modification modification) {
560         ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
561         modification.apply(tx.getSnapshot());
562         try {
563             snapshotCohort.syncCommitTransaction(tx);
564             shardMBean.incrementCommittedTransactionCount();
565             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
566         } catch (Exception e) {
567             shardMBean.incrementFailedTransactionsCount();
568             LOG.error("{}: Failed to commit", persistenceId(), e);
569         }
570     }
571
572     private void updateSchemaContext(final UpdateSchemaContext message) {
573         updateSchemaContext(message.getSchemaContext());
574     }
575
576     @VisibleForTesting
577     void updateSchemaContext(final SchemaContext schemaContext) {
578         store.updateSchemaContext(schemaContext);
579     }
580
581     private boolean isMetricsCaptureEnabled() {
582         CommonConfig config = new CommonConfig(getContext().system().settings().config());
583         return config.isMetricCaptureEnabled();
584     }
585
586     @Override
587     @VisibleForTesting
588     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
589         return snapshotCohort;
590     }
591
592     @Override
593     @Nonnull
594     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
595         return new ShardRecoveryCoordinator(store, store.getSchemaContext(), persistenceId(), LOG);
596     }
597
598     @Override
599     protected void onRecoveryComplete() {
600         //notify shard manager
601         getContext().parent().tell(new ActorInitialized(), getSelf());
602
603         // Being paranoid here - this method should only be called once but just in case...
604         if(txCommitTimeoutCheckSchedule == null) {
605             // Schedule a message to be periodically sent to check if the current in-progress
606             // transaction should be expired and aborted.
607             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
608             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
609                     period, period, getSelf(),
610                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
611         }
612     }
613
614     @Override
615     protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
616         if (data instanceof DataTreeCandidatePayload) {
617             if (clientActor == null) {
618                 // No clientActor indicates a replica coming from the leader
619                 try {
620                     store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
621                 } catch (DataValidationFailedException | IOException e) {
622                     LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
623                 }
624             } else {
625                 // Replication consensus reached, proceed to commit
626                 finishCommit(clientActor, identifier);
627             }
628         } else if (data instanceof ModificationPayload) {
629             try {
630                 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
631             } catch (ClassNotFoundException | IOException e) {
632                 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
633             }
634         } else if (data instanceof CompositeModificationPayload) {
635             Object modification = ((CompositeModificationPayload) data).getModification();
636
637             applyModificationToState(clientActor, identifier, modification);
638         } else if(data instanceof CompositeModificationByteStringPayload ){
639             Object modification = ((CompositeModificationByteStringPayload) data).getModification();
640
641             applyModificationToState(clientActor, identifier, modification);
642         } else {
643             LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
644                     persistenceId(), data, data.getClass().getClassLoader(),
645                     CompositeModificationPayload.class.getClassLoader());
646         }
647     }
648
649     private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
650         if(modification == null) {
651             LOG.error(
652                     "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
653                     persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
654         } else if(clientActor == null) {
655             // There's no clientActor to which to send a commit reply so we must be applying
656             // replicated state from the leader.
657             commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
658         } else {
659             // This must be the OK to commit after replication consensus.
660             finishCommit(clientActor, identifier);
661         }
662     }
663
664     @Override
665     protected void onStateChanged() {
666         boolean isLeader = isLeader();
667         boolean hasLeader = hasLeader();
668         changeSupport.onLeadershipChange(isLeader, hasLeader);
669         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
670
671         // If this actor is no longer the leader close all the transaction chains
672         if (!isLeader) {
673             if(LOG.isDebugEnabled()) {
674                 LOG.debug(
675                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
676                     persistenceId(), getId());
677             }
678
679             store.closeAllTransactionChains();
680         }
681     }
682
683     @Override
684     protected void onLeaderChanged(String oldLeader, String newLeader) {
685         shardMBean.incrementLeadershipChangeCount();
686     }
687
688     @Override
689     public String persistenceId() {
690         return this.name;
691     }
692
693     @VisibleForTesting
694     ShardCommitCoordinator getCommitCoordinator() {
695         return commitCoordinator;
696     }
697
698     public DatastoreContext getDatastoreContext() {
699         return datastoreContext;
700     }
701
702     protected abstract static class AbstractShardCreator implements Creator<Shard> {
703         private static final long serialVersionUID = 1L;
704
705         protected final ShardIdentifier name;
706         protected final Map<String, String> peerAddresses;
707         protected final DatastoreContext datastoreContext;
708         protected final SchemaContext schemaContext;
709
710         protected AbstractShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
711                 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
712             this.name = Preconditions.checkNotNull(name, "name should not be null");
713             this.peerAddresses = Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
714             this.datastoreContext = Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
715             this.schemaContext = Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
716         }
717     }
718
719     private static class ShardCreator extends AbstractShardCreator {
720         private static final long serialVersionUID = 1L;
721
722         ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
723                 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
724             super(name, peerAddresses, datastoreContext, schemaContext);
725         }
726
727         @Override
728         public Shard create() throws Exception {
729             return new Shard(name, peerAddresses, datastoreContext, schemaContext);
730         }
731     }
732
733     @VisibleForTesting
734     public ShardDataTree getDataStore() {
735         return store;
736     }
737
738     @VisibleForTesting
739     ShardStats getShardMBean() {
740         return shardMBean;
741     }
742 }