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