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