CDS: add backend support for local transactions
[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 com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
23 import com.google.common.util.concurrent.ListenableFuture;
24 import java.io.IOException;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.concurrent.TimeUnit;
28 import javax.annotation.Nonnull;
29 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
30 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
31 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
32 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
33 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
34 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
35 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
36 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
37 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
38 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
39 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
40 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
41 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
42 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
43 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
44 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
45 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
46 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
47 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
48 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
49 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
50 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
51 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
52 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
53 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
54 import org.opendaylight.controller.cluster.datastore.modification.Modification;
55 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
56 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
57 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
58 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
59 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
60 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
61 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
62 import org.opendaylight.controller.cluster.raft.RaftActor;
63 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
64 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
65 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
66 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
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.model.api.SchemaContext;
74 import scala.concurrent.duration.Duration;
75 import scala.concurrent.duration.FiniteDuration;
76
77 /**
78  * A Shard represents a portion of the logical data tree <br/>
79  * <p>
80  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
81  * </p>
82  */
83 public class Shard extends RaftActor {
84
85     private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
86
87     @VisibleForTesting
88     static final String DEFAULT_NAME = "default";
89
90     // The state of this Shard
91     private final ShardDataTree store;
92
93     /// The name of this shard
94     private final String name;
95
96     private final ShardStats shardMBean;
97
98     private DatastoreContext datastoreContext;
99
100     private final ShardCommitCoordinator commitCoordinator;
101
102     private long transactionCommitTimeout;
103
104     private Cancellable txCommitTimeoutCheckSchedule;
105
106     private final Optional<ActorRef> roleChangeNotifier;
107
108     private final MessageTracker appendEntriesReplyTracker;
109
110     private final ShardTransactionActorFactory transactionActorFactory;
111
112     private final ShardSnapshotCohort snapshotCohort;
113
114     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
115     private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
116
117     protected Shard(final ShardIdentifier name, final Map<String, String> peerAddresses,
118             final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
119         super(name.toString(), new HashMap<>(peerAddresses), Optional.of(datastoreContext.getShardRaftConfig()));
120
121         this.name = name.toString();
122         this.datastoreContext = datastoreContext;
123
124         setPersistence(datastoreContext.isPersistent());
125
126         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
127
128         store = new ShardDataTree(schemaContext);
129
130         shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
131                 datastoreContext.getDataStoreMXBeanType());
132         shardMBean.setShardActor(getSelf());
133
134         if (isMetricsCaptureEnabled()) {
135             getContext().become(new MeteringBehavior(this));
136         }
137
138         commitCoordinator = new ShardCommitCoordinator(store,
139                 TimeUnit.SECONDS.convert(5, TimeUnit.MINUTES),
140                 datastoreContext.getShardTransactionCommitQueueCapacity(), self(), LOG, this.name);
141
142         setTransactionCommitTimeout();
143
144         // create a notifier actor for each cluster member
145         roleChangeNotifier = createRoleChangeNotifier(name.toString());
146
147         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
148                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
149
150         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
151                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
152                         Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
153
154         snapshotCohort = new ShardSnapshotCohort(transactionActorFactory, store, LOG, this.name);
155     }
156
157     private void setTransactionCommitTimeout() {
158         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
159                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
160     }
161
162     public static Props props(final ShardIdentifier name,
163         final Map<String, String> peerAddresses,
164         final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
165         Preconditions.checkNotNull(name, "name should not be null");
166         Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
167         Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
168         Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
169
170         return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
171     }
172
173     private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
174         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
175             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
176         return Optional.of(shardRoleChangeNotifier);
177     }
178
179     @Override
180     public void postStop() {
181         LOG.info("Stopping Shard {}", persistenceId());
182
183         super.postStop();
184
185         if(txCommitTimeoutCheckSchedule != null) {
186             txCommitTimeoutCheckSchedule.cancel();
187         }
188
189         shardMBean.unregisterMBean();
190     }
191
192     @Override
193     public void onReceiveRecover(final Object message) throws Exception {
194         if(LOG.isDebugEnabled()) {
195             LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
196                 message.getClass().toString(), getSender());
197         }
198
199         if (message instanceof RecoveryFailure){
200             LOG.error("{}: Recovery failed because of this cause",
201                     persistenceId(), ((RecoveryFailure) message).cause());
202
203             // Even though recovery failed, we still need to finish our recovery, eg send the
204             // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
205             onRecoveryComplete();
206         } else {
207             super.onReceiveRecover(message);
208             if(LOG.isTraceEnabled()) {
209                 appendEntriesReplyTracker.begin();
210             }
211         }
212     }
213
214     @Override
215     public void onReceiveCommand(final Object message) throws Exception {
216
217         MessageTracker.Context context = appendEntriesReplyTracker.received(message);
218
219         if(context.error().isPresent()){
220             LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
221                     context.error());
222         }
223
224         try {
225             if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
226                 handleCreateTransaction(message);
227             } else if (BatchedModifications.class.isInstance(message)) {
228                 handleBatchedModifications((BatchedModifications)message);
229             } else if (message instanceof ForwardedReadyTransaction) {
230                 commitCoordinator.handleForwardedReadyTransaction((ForwardedReadyTransaction) message,
231                         getSender(), this);
232             } else if (message instanceof ReadyLocalTransaction) {
233                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
234             } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
235                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
236             } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
237                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
238             } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
239                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
240             } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
241                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
242             } else if (message instanceof RegisterChangeListener) {
243                 changeSupport.onMessage((RegisterChangeListener) message, isLeader());
244             } else if (message instanceof RegisterDataTreeChangeListener) {
245                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader());
246             } else if (message instanceof UpdateSchemaContext) {
247                 updateSchemaContext((UpdateSchemaContext) message);
248             } else if (message instanceof PeerAddressResolved) {
249                 PeerAddressResolved resolved = (PeerAddressResolved) message;
250                 setPeerAddress(resolved.getPeerId().toString(),
251                         resolved.getPeerAddress());
252             } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
253                 handleTransactionCommitTimeoutCheck();
254             } else if(message instanceof DatastoreContext) {
255                 onDatastoreContext((DatastoreContext)message);
256             } else if(message instanceof RegisterRoleChangeListener){
257                 roleChangeNotifier.get().forward(message, context());
258             } else if (message instanceof FollowerInitialSyncUpStatus){
259                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
260                 context().parent().tell(message, self());
261             } else {
262                 super.onReceiveCommand(message);
263             }
264         } finally {
265             context.done();
266         }
267     }
268
269     @Override
270     protected Optional<ActorRef> getRoleChangeNotifier() {
271         return roleChangeNotifier;
272     }
273
274     @Override
275     protected LeaderStateChanged newLeaderStateChanged(String memberId, String leaderId) {
276         return new ShardLeaderStateChanged(memberId, leaderId,
277                 isLeader() ? Optional.<DataTree>of(store.getDataTree()) : Optional.<DataTree>absent());
278     }
279
280     private void onDatastoreContext(DatastoreContext context) {
281         datastoreContext = context;
282
283         commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
284
285         setTransactionCommitTimeout();
286
287         if(datastoreContext.isPersistent() && !persistence().isRecoveryApplicable()) {
288             setPersistence(true);
289         } else if(!datastoreContext.isPersistent() && persistence().isRecoveryApplicable()) {
290             setPersistence(false);
291         }
292
293         updateConfigParams(datastoreContext.getShardRaftConfig());
294     }
295
296     private void handleTransactionCommitTimeoutCheck() {
297         CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
298         if(cohortEntry != null) {
299             long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
300             if(elapsed > transactionCommitTimeout) {
301                 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
302                         persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
303
304                 doAbortTransaction(cohortEntry.getTransactionID(), null);
305             }
306         }
307     }
308
309     private static boolean isEmptyCommit(final DataTreeCandidate candidate) {
310         return ModificationType.UNMODIFIED.equals(candidate.getRootNode().getModificationType());
311     }
312
313     void continueCommit(final CohortEntry cohortEntry) throws Exception {
314         final DataTreeCandidate candidate = cohortEntry.getCohort().getCandidate();
315
316         // If we do not have any followers and we are not using persistence
317         // or if cohortEntry has no modifications
318         // we can apply modification to the state immediately
319         if ((!hasFollowers() && !persistence().isRecoveryApplicable()) || isEmptyCommit(candidate)) {
320             applyModificationToState(getSender(), cohortEntry.getTransactionID(), candidate);
321         } else {
322             Shard.this.persistData(getSender(), cohortEntry.getTransactionID(),
323                 DataTreeCandidatePayload.create(candidate));
324         }
325     }
326
327     private void handleCommitTransaction(final CommitTransaction commit) {
328         if(!commitCoordinator.handleCommit(commit.getTransactionID(), getSender(), this)) {
329             shardMBean.incrementFailedTransactionsCount();
330         }
331     }
332
333     private void finishCommit(@Nonnull final ActorRef sender, @Nonnull final String transactionID, @Nonnull final CohortEntry cohortEntry) {
334         LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
335
336         try {
337             // We block on the future here so we don't have to worry about possibly accessing our
338             // state on a different thread outside of our dispatcher. Also, the data store
339             // currently uses a same thread executor anyway.
340             cohortEntry.getCohort().commit().get();
341
342             sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
343
344             shardMBean.incrementCommittedTransactionCount();
345             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
346
347         } catch (Exception e) {
348             sender.tell(new akka.actor.Status.Failure(e), getSelf());
349
350             LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
351                     transactionID, e);
352             shardMBean.incrementFailedTransactionsCount();
353         } finally {
354             commitCoordinator.currentTransactionComplete(transactionID, true);
355         }
356     }
357
358     private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
359         // With persistence enabled, this method is called via applyState by the leader strategy
360         // after the commit has been replicated to a majority of the followers.
361
362         CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
363         if (cohortEntry == null) {
364             // The transaction is no longer the current commit. This can happen if the transaction
365             // was aborted prior, most likely due to timeout in the front-end. We need to finish
366             // committing the transaction though since it was successfully persisted and replicated
367             // however we can't use the original cohort b/c it was already preCommitted and may
368             // conflict with the current commit or may have been aborted so we commit with a new
369             // transaction.
370             cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
371             if(cohortEntry != null) {
372                 try {
373                     store.applyForeignCandidate(transactionID, cohortEntry.getCohort().getCandidate());
374                 } catch (DataValidationFailedException e) {
375                     shardMBean.incrementFailedTransactionsCount();
376                     LOG.error("{}: Failed to re-apply transaction {}", persistenceId(), transactionID, e);
377                 }
378
379                 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
380             } else {
381                 // This really shouldn't happen - it likely means that persistence or replication
382                 // took so long to complete such that the cohort entry was expired from the cache.
383                 IllegalStateException ex = new IllegalStateException(
384                         String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
385                                 persistenceId(), transactionID));
386                 LOG.error(ex.getMessage());
387                 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
388             }
389         } else {
390             finishCommit(sender, transactionID, cohortEntry);
391         }
392     }
393
394     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
395         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
396         commitCoordinator.handleCanCommit(canCommit.getTransactionID(), getSender(), this);
397     }
398
399     private void noLeaderError(Object message) {
400         // TODO: rather than throwing an immediate exception, we could schedule a timer to try again to make
401         // it more resilient in case we're in the process of electing a new leader.
402         getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
403             "Could not find the leader for shard %s. This typically happens" +
404             " when the system is coming up or recovering and a leader is being elected. Try again" +
405             " later.", persistenceId()))), getSelf());
406     }
407
408     private void handleBatchedModifications(BatchedModifications batched) {
409         // This message is sent to prepare the modificationsa transaction directly on the Shard as an
410         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
411         // BatchedModifications message, the caller sets the ready flag in the message indicating
412         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
413         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
414         // ReadyTransaction message.
415
416         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
417         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
418         // the primary/leader shard. However with timing and caching on the front-end, there's a small
419         // window where it could have a stale leader during leadership transitions.
420         //
421         if(isLeader()) {
422             try {
423                 commitCoordinator.handleBatchedModifications(batched, getSender(), this);
424             } catch (Exception e) {
425                 LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
426                         batched.getTransactionID(), e);
427                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
428             }
429         } else {
430             ActorSelection leader = getLeader();
431             if(leader != null) {
432                 // TODO: what if this is not the first batch and leadership changed in between batched messages?
433                 // We could check if the commitCoordinator already has a cached entry and forward all the previous
434                 // batched modifications.
435                 LOG.debug("{}: Forwarding BatchedModifications to leader {}", persistenceId(), leader);
436                 leader.forward(batched, getContext());
437             } else {
438                 noLeaderError(batched);
439             }
440         }
441     }
442
443     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
444         if (isLeader()) {
445             try {
446                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
447             } catch (Exception e) {
448                 LOG.error("{}: Error handling LocalModifications for Tx {}", persistenceId(),
449                         message.getTransactionID(), e);
450                 getSender().tell(new akka.actor.Status.Failure(e), getSelf());
451             }
452         } else {
453             ActorSelection leader = getLeader();
454             if (leader != null) {
455                 LOG.debug("{}: Forwarding LocalModifications to leader {}", persistenceId(), leader);
456                 leader.forward(message, getContext());
457             } else {
458                 noLeaderError(message);
459             }
460         }
461     }
462
463     private void handleAbortTransaction(final AbortTransaction abort) {
464         doAbortTransaction(abort.getTransactionID(), getSender());
465     }
466
467     void doAbortTransaction(final String transactionID, final ActorRef sender) {
468         final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
469         if(cohortEntry != null) {
470             LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
471
472             // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
473             // aborted during replication in which case we may still commit locally if replication
474             // succeeds.
475             commitCoordinator.currentTransactionComplete(transactionID, false);
476
477             final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
478             final ActorRef self = getSelf();
479
480             Futures.addCallback(future, new FutureCallback<Void>() {
481                 @Override
482                 public void onSuccess(final Void v) {
483                     shardMBean.incrementAbortTransactionsCount();
484
485                     if(sender != null) {
486                         sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
487                     }
488                 }
489
490                 @Override
491                 public void onFailure(final Throwable t) {
492                     LOG.error("{}: An exception happened during abort", persistenceId(), t);
493
494                     if(sender != null) {
495                         sender.tell(new akka.actor.Status.Failure(t), self);
496                     }
497                 }
498             });
499         }
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(String.format(
509                 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
510                 " when the system is coming up or recovering and a leader is being elected. Try again" +
511                 " later.", persistenceId()))), getSelf());
512         }
513     }
514
515     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
516         store.closeTransactionChain(closeTransactionChain.getTransactionChainId());
517     }
518
519     private ActorRef createTypedTransactionActor(int transactionType,
520             ShardTransactionIdentifier transactionId, String transactionChainId,
521             short clientVersion ) {
522
523         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
524                 transactionId, transactionChainId, clientVersion);
525     }
526
527     private void createTransaction(CreateTransaction createTransaction) {
528         try {
529             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
530                 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
531                 createTransaction.getVersion());
532
533             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
534                     createTransaction.getTransactionId()).toSerializable(), getSelf());
535         } catch (Exception e) {
536             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
537         }
538     }
539
540     private ActorRef createTransaction(int transactionType, String remoteTransactionId,
541             String transactionChainId, short clientVersion) {
542
543
544         ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
545
546         if(LOG.isDebugEnabled()) {
547             LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
548         }
549
550         ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
551                 transactionChainId, clientVersion);
552
553         return transactionActor;
554     }
555
556     private void commitWithNewTransaction(final Modification modification) {
557         ReadWriteShardDataTreeTransaction tx = store.newReadWriteTransaction(modification.toString(), null);
558         modification.apply(tx.getSnapshot());
559         try {
560             snapshotCohort.syncCommitTransaction(tx);
561             shardMBean.incrementCommittedTransactionCount();
562             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
563         } catch (Exception e) {
564             shardMBean.incrementFailedTransactionsCount();
565             LOG.error("{}: Failed to commit", persistenceId(), e);
566         }
567     }
568
569     private void updateSchemaContext(final UpdateSchemaContext message) {
570         updateSchemaContext(message.getSchemaContext());
571     }
572
573     @VisibleForTesting
574     void updateSchemaContext(final SchemaContext schemaContext) {
575         store.updateSchemaContext(schemaContext);
576     }
577
578     private boolean isMetricsCaptureEnabled() {
579         CommonConfig config = new CommonConfig(getContext().system().settings().config());
580         return config.isMetricCaptureEnabled();
581     }
582
583     @Override
584     protected RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
585         return snapshotCohort;
586     }
587
588     @Override
589     @Nonnull
590     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
591         return new ShardRecoveryCoordinator(store, persistenceId(), LOG);
592     }
593
594     @Override
595     protected void onRecoveryComplete() {
596         //notify shard manager
597         getContext().parent().tell(new ActorInitialized(), getSelf());
598
599         // Being paranoid here - this method should only be called once but just in case...
600         if(txCommitTimeoutCheckSchedule == null) {
601             // Schedule a message to be periodically sent to check if the current in-progress
602             // transaction should be expired and aborted.
603             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
604             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
605                     period, period, getSelf(),
606                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
607         }
608     }
609
610     @Override
611     protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
612         if (data instanceof DataTreeCandidatePayload) {
613             if (clientActor == null) {
614                 // No clientActor indicates a replica coming from the leader
615                 try {
616                     store.applyForeignCandidate(identifier, ((DataTreeCandidatePayload)data).getCandidate());
617                 } catch (DataValidationFailedException | IOException e) {
618                     LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
619                 }
620             } else {
621                 // Replication consensus reached, proceed to commit
622                 finishCommit(clientActor, identifier);
623             }
624         } else if (data instanceof ModificationPayload) {
625             try {
626                 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
627             } catch (ClassNotFoundException | IOException e) {
628                 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
629             }
630         } else if (data instanceof CompositeModificationPayload) {
631             Object modification = ((CompositeModificationPayload) data).getModification();
632
633             applyModificationToState(clientActor, identifier, modification);
634         } else if(data instanceof CompositeModificationByteStringPayload ){
635             Object modification = ((CompositeModificationByteStringPayload) data).getModification();
636
637             applyModificationToState(clientActor, identifier, modification);
638         } else {
639             LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
640                     persistenceId(), data, data.getClass().getClassLoader(),
641                     CompositeModificationPayload.class.getClassLoader());
642         }
643     }
644
645     private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
646         if(modification == null) {
647             LOG.error(
648                     "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
649                     persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
650         } else if(clientActor == null) {
651             // There's no clientActor to which to send a commit reply so we must be applying
652             // replicated state from the leader.
653             commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
654         } else {
655             // This must be the OK to commit after replication consensus.
656             finishCommit(clientActor, identifier);
657         }
658     }
659
660     @Override
661     protected void onStateChanged() {
662         boolean isLeader = isLeader();
663         changeSupport.onLeadershipChange(isLeader);
664         treeChangeSupport.onLeadershipChange(isLeader);
665
666         // If this actor is no longer the leader close all the transaction chains
667         if (!isLeader) {
668             if(LOG.isDebugEnabled()) {
669                 LOG.debug(
670                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
671                     persistenceId(), getId());
672             }
673
674             store.closeAllTransactionChains();
675         }
676     }
677
678     @Override
679     protected void onLeaderChanged(String oldLeader, String newLeader) {
680         shardMBean.incrementLeadershipChangeCount();
681     }
682
683     @Override
684     public String persistenceId() {
685         return this.name;
686     }
687
688     @VisibleForTesting
689     ShardCommitCoordinator getCommitCoordinator() {
690         return commitCoordinator;
691     }
692
693
694     private static class ShardCreator implements Creator<Shard> {
695
696         private static final long serialVersionUID = 1L;
697
698         final ShardIdentifier name;
699         final Map<String, String> peerAddresses;
700         final DatastoreContext datastoreContext;
701         final SchemaContext schemaContext;
702
703         ShardCreator(final ShardIdentifier name, final Map<String, String> peerAddresses,
704                 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
705             this.name = name;
706             this.peerAddresses = peerAddresses;
707             this.datastoreContext = datastoreContext;
708             this.schemaContext = schemaContext;
709         }
710
711         @Override
712         public Shard create() throws Exception {
713             return new Shard(name, peerAddresses, datastoreContext, schemaContext);
714         }
715     }
716
717     @VisibleForTesting
718     public ShardDataTree getDataStore() {
719         return store;
720     }
721
722     @VisibleForTesting
723     ShardStats getShardMBean() {
724         return shardMBean;
725     }
726 }