9ec4f9cfdf027680bfa9a4041bc0b335356fb20c
[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.collect.Lists;
22 import com.google.common.util.concurrent.FutureCallback;
23 import com.google.common.util.concurrent.Futures;
24 import com.google.common.util.concurrent.ListenableFuture;
25 import java.io.IOException;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.TimeUnit;
32 import javax.annotation.Nonnull;
33 import org.opendaylight.controller.cluster.DataPersistenceProvider;
34 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
35 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
36 import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry;
37 import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort;
38 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
39 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
40 import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier;
41 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
42 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
43 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
44 import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
45 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
46 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
47 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
48 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
49 import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
50 import org.opendaylight.controller.cluster.datastore.messages.CreateSnapshot;
51 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
52 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
53 import org.opendaylight.controller.cluster.datastore.messages.EnableNotification;
54 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
55 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
56 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
57 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
58 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
59 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
60 import org.opendaylight.controller.cluster.datastore.modification.Modification;
61 import org.opendaylight.controller.cluster.datastore.modification.ModificationPayload;
62 import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
63 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
64 import org.opendaylight.controller.cluster.datastore.utils.MessageTracker;
65 import org.opendaylight.controller.cluster.datastore.utils.SerializationUtils;
66 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
67 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
68 import org.opendaylight.controller.cluster.raft.RaftActor;
69 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
70 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
71 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationByteStringPayload;
72 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.CompositeModificationPayload;
73 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
74 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
75 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
76 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
77 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
78 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransaction;
79 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
80 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionFactory;
81 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
82 import org.opendaylight.yangtools.concepts.ListenerRegistration;
83 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
84 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
85 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
86 import scala.concurrent.duration.Duration;
87 import scala.concurrent.duration.FiniteDuration;
88
89 /**
90  * A Shard represents a portion of the logical data tree <br/>
91  * <p>
92  * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
93  * </p>
94  */
95 public class Shard extends RaftActor {
96
97     private static final YangInstanceIdentifier DATASTORE_ROOT = YangInstanceIdentifier.builder().build();
98
99     private static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = "txCommitTimeoutCheck";
100
101     @VisibleForTesting
102     static final String DEFAULT_NAME = "default";
103
104     // The state of this Shard
105     private final InMemoryDOMDataStore store;
106
107     /// The name of this shard
108     private final ShardIdentifier name;
109
110     private final ShardStats shardMBean;
111
112     private final List<ActorSelection> dataChangeListeners =  Lists.newArrayList();
113
114     private final List<DelayedListenerRegistration> delayedListenerRegistrations =
115                                                                        Lists.newArrayList();
116
117     private DatastoreContext datastoreContext;
118
119     private DataPersistenceProvider dataPersistenceProvider;
120
121     private SchemaContext schemaContext;
122
123     private int createSnapshotTransactionCounter;
124
125     private final ShardCommitCoordinator commitCoordinator;
126
127     private long transactionCommitTimeout;
128
129     private Cancellable txCommitTimeoutCheckSchedule;
130
131     private final Optional<ActorRef> roleChangeNotifier;
132
133     private final MessageTracker appendEntriesReplyTracker;
134
135     private final ReadyTransactionReply READY_TRANSACTION_REPLY = new ReadyTransactionReply(
136             Serialization.serializedActorPath(getSelf()));
137
138
139     /**
140      * Coordinates persistence recovery on startup.
141      */
142     private ShardRecoveryCoordinator recoveryCoordinator;
143     private List<Object> currentLogRecoveryBatch;
144
145     private final Map<String, DOMStoreTransactionChain> transactionChains = new HashMap<>();
146
147     private final String txnDispatcherPath;
148
149     protected Shard(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
150             final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
151         super(name.toString(), mapPeerAddresses(peerAddresses),
152                 Optional.of(datastoreContext.getShardRaftConfig()));
153
154         this.name = name;
155         this.datastoreContext = datastoreContext;
156         this.schemaContext = schemaContext;
157         this.dataPersistenceProvider = (datastoreContext.isPersistent())
158                 ? new PersistentDataProvider() : new NonPersistentRaftDataProvider();
159         this.txnDispatcherPath = new Dispatchers(context().system().dispatchers())
160                 .getDispatcherPath(Dispatchers.DispatcherType.Transaction);
161
162
163         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
164
165         store = InMemoryDOMDataStoreFactory.create(name.toString(), null,
166                 datastoreContext.getDataStoreProperties());
167
168         if(schemaContext != null) {
169             store.onGlobalContextUpdated(schemaContext);
170         }
171
172         shardMBean = ShardMBeanFactory.getShardStatsMBean(name.toString(),
173                 datastoreContext.getDataStoreMXBeanType());
174         shardMBean.setNotificationManager(store.getDataChangeListenerNotificationManager());
175         shardMBean.setShardActor(getSelf());
176
177         if (isMetricsCaptureEnabled()) {
178             getContext().become(new MeteringBehavior(this));
179         }
180
181         commitCoordinator = new ShardCommitCoordinator(TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES),
182                 datastoreContext.getShardTransactionCommitQueueCapacity(), LOG, name.toString());
183
184         setTransactionCommitTimeout();
185
186         // create a notifier actor for each cluster member
187         roleChangeNotifier = createRoleChangeNotifier(name.toString());
188
189         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
190                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
191     }
192
193     private void setTransactionCommitTimeout() {
194         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
195                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS);
196     }
197
198     private static Map<String, String> mapPeerAddresses(
199         final Map<ShardIdentifier, String> peerAddresses) {
200         Map<String, String> map = new HashMap<>();
201
202         for (Map.Entry<ShardIdentifier, String> entry : peerAddresses
203             .entrySet()) {
204             map.put(entry.getKey().toString(), entry.getValue());
205         }
206
207         return map;
208     }
209
210     public static Props props(final ShardIdentifier name,
211         final Map<ShardIdentifier, String> peerAddresses,
212         final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
213         Preconditions.checkNotNull(name, "name should not be null");
214         Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
215         Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
216         Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
217
218         return Props.create(new ShardCreator(name, peerAddresses, datastoreContext, schemaContext));
219     }
220
221     private Optional<ActorRef> createRoleChangeNotifier(String shardId) {
222         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
223             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
224         return Optional.of(shardRoleChangeNotifier);
225     }
226
227     @Override
228     public void postStop() {
229         LOG.info("Stopping Shard {}", persistenceId());
230
231         super.postStop();
232
233         if(txCommitTimeoutCheckSchedule != null) {
234             txCommitTimeoutCheckSchedule.cancel();
235         }
236
237         shardMBean.unregisterMBean();
238     }
239
240     @Override
241     public void onReceiveRecover(final Object message) throws Exception {
242         if(LOG.isDebugEnabled()) {
243             LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(),
244                 message.getClass().toString(), getSender());
245         }
246
247         if (message instanceof RecoveryFailure){
248             LOG.error("{}: Recovery failed because of this cause",
249                     persistenceId(), ((RecoveryFailure) message).cause());
250
251             // Even though recovery failed, we still need to finish our recovery, eg send the
252             // ActorInitialized message and start the txCommitTimeoutCheckSchedule.
253             onRecoveryComplete();
254         } else {
255             super.onReceiveRecover(message);
256             if(LOG.isTraceEnabled()) {
257                 appendEntriesReplyTracker.begin();
258             }
259         }
260     }
261
262     @Override
263     public void onReceiveCommand(final Object message) throws Exception {
264
265         MessageTracker.Context context = appendEntriesReplyTracker.received(message);
266
267         if(context.error().isPresent()){
268             LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
269                     context.error());
270         }
271
272         try {
273             if (CreateTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
274                 handleCreateTransaction(message);
275             } else if (message instanceof ForwardedReadyTransaction) {
276                 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
277             } else if (CanCommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
278                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
279             } else if (CommitTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
280                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
281             } else if (AbortTransaction.SERIALIZABLE_CLASS.isInstance(message)) {
282                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
283             } else if (CloseTransactionChain.SERIALIZABLE_CLASS.isInstance(message)) {
284                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
285             } else if (message instanceof RegisterChangeListener) {
286                 registerChangeListener((RegisterChangeListener) message);
287             } else if (message instanceof UpdateSchemaContext) {
288                 updateSchemaContext((UpdateSchemaContext) message);
289             } else if (message instanceof PeerAddressResolved) {
290                 PeerAddressResolved resolved = (PeerAddressResolved) message;
291                 setPeerAddress(resolved.getPeerId().toString(),
292                         resolved.getPeerAddress());
293             } else if (message.equals(TX_COMMIT_TIMEOUT_CHECK_MESSAGE)) {
294                 handleTransactionCommitTimeoutCheck();
295             } else if(message instanceof DatastoreContext) {
296                 onDatastoreContext((DatastoreContext)message);
297             } else if(message instanceof RegisterRoleChangeListener){
298                 roleChangeNotifier.get().forward(message, context());
299             } else if (message instanceof FollowerInitialSyncUpStatus){
300                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
301                 context().parent().tell(message, self());
302             } else {
303                 super.onReceiveCommand(message);
304             }
305         } finally {
306             context.done();
307         }
308     }
309
310     @Override
311     protected Optional<ActorRef> getRoleChangeNotifier() {
312         return roleChangeNotifier;
313     }
314
315     private void onDatastoreContext(DatastoreContext context) {
316         datastoreContext = context;
317
318         commitCoordinator.setQueueCapacity(datastoreContext.getShardTransactionCommitQueueCapacity());
319
320         setTransactionCommitTimeout();
321
322         if(datastoreContext.isPersistent() &&
323                 dataPersistenceProvider instanceof NonPersistentRaftDataProvider) {
324             dataPersistenceProvider = new PersistentDataProvider();
325         } else if(!datastoreContext.isPersistent() &&
326                 dataPersistenceProvider instanceof PersistentDataProvider) {
327             dataPersistenceProvider = new NonPersistentRaftDataProvider();
328         }
329
330         updateConfigParams(datastoreContext.getShardRaftConfig());
331     }
332
333     private void handleTransactionCommitTimeoutCheck() {
334         CohortEntry cohortEntry = commitCoordinator.getCurrentCohortEntry();
335         if(cohortEntry != null) {
336             long elapsed = System.currentTimeMillis() - cohortEntry.getLastAccessTime();
337             if(elapsed > transactionCommitTimeout) {
338                 LOG.warn("{}: Current transaction {} has timed out after {} ms - aborting",
339                         persistenceId(), cohortEntry.getTransactionID(), transactionCommitTimeout);
340
341                 doAbortTransaction(cohortEntry.getTransactionID(), null);
342             }
343         }
344     }
345
346     private void handleCommitTransaction(final CommitTransaction commit) {
347         final String transactionID = commit.getTransactionID();
348
349         LOG.debug("{}: Committing transaction {}", persistenceId(), transactionID);
350
351         // Get the current in-progress cohort entry in the commitCoordinator if it corresponds to
352         // this transaction.
353         final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
354         if(cohortEntry == null) {
355             // We're not the current Tx - the Tx was likely expired b/c it took too long in
356             // between the canCommit and commit messages.
357             IllegalStateException ex = new IllegalStateException(
358                     String.format("%s: Cannot commit transaction %s - it is not the current transaction",
359                             persistenceId(), transactionID));
360             LOG.error(ex.getMessage());
361             shardMBean.incrementFailedTransactionsCount();
362             getSender().tell(new akka.actor.Status.Failure(ex), getSelf());
363             return;
364         }
365
366         // We perform the preCommit phase here atomically with the commit phase. This is an
367         // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
368         // coordination of preCommit across shards in case of failure but preCommit should not
369         // normally fail since we ensure only one concurrent 3-phase commit.
370
371         try {
372             // We block on the future here so we don't have to worry about possibly accessing our
373             // state on a different thread outside of our dispatcher. Also, the data store
374             // currently uses a same thread executor anyway.
375             cohortEntry.getCohort().preCommit().get();
376
377             // If we do not have any followers and we are not using persistence
378             // or if cohortEntry has no modifications
379             // we can apply modification to the state immediately
380             if((!hasFollowers() && !persistence().isRecoveryApplicable()) || (!cohortEntry.hasModifications())){
381                 applyModificationToState(getSender(), transactionID, cohortEntry.getModification());
382             } else {
383                 Shard.this.persistData(getSender(), transactionID,
384                         new ModificationPayload(cohortEntry.getModification()));
385             }
386         } catch (Exception e) {
387             LOG.error("{} An exception occurred while preCommitting transaction {}",
388                     persistenceId(), cohortEntry.getTransactionID(), e);
389             shardMBean.incrementFailedTransactionsCount();
390             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
391         }
392
393         cohortEntry.updateLastAccessTime();
394     }
395
396     private void finishCommit(@Nonnull final ActorRef sender, final @Nonnull String transactionID) {
397         // With persistence enabled, this method is called via applyState by the leader strategy
398         // after the commit has been replicated to a majority of the followers.
399
400         CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
401         if(cohortEntry == null) {
402             // The transaction is no longer the current commit. This can happen if the transaction
403             // was aborted prior, most likely due to timeout in the front-end. We need to finish
404             // committing the transaction though since it was successfully persisted and replicated
405             // however we can't use the original cohort b/c it was already preCommitted and may
406             // conflict with the current commit or may have been aborted so we commit with a new
407             // transaction.
408             cohortEntry = commitCoordinator.getAndRemoveCohortEntry(transactionID);
409             if(cohortEntry != null) {
410                 commitWithNewTransaction(cohortEntry.getModification());
411                 sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
412             } else {
413                 // This really shouldn't happen - it likely means that persistence or replication
414                 // took so long to complete such that the cohort entry was expired from the cache.
415                 IllegalStateException ex = new IllegalStateException(
416                         String.format("%s: Could not finish committing transaction %s - no CohortEntry found",
417                                 persistenceId(), transactionID));
418                 LOG.error(ex.getMessage());
419                 sender.tell(new akka.actor.Status.Failure(ex), getSelf());
420             }
421
422             return;
423         }
424
425         LOG.debug("{}: Finishing commit for transaction {}", persistenceId(), cohortEntry.getTransactionID());
426
427         try {
428             // We block on the future here so we don't have to worry about possibly accessing our
429             // state on a different thread outside of our dispatcher. Also, the data store
430             // currently uses a same thread executor anyway.
431             cohortEntry.getCohort().commit().get();
432
433             sender.tell(CommitTransactionReply.INSTANCE.toSerializable(), getSelf());
434
435             shardMBean.incrementCommittedTransactionCount();
436             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
437
438         } catch (Exception e) {
439             sender.tell(new akka.actor.Status.Failure(e), getSelf());
440
441             LOG.error("{}, An exception occurred while committing transaction {}", persistenceId(),
442                     transactionID, e);
443             shardMBean.incrementFailedTransactionsCount();
444         } finally {
445             commitCoordinator.currentTransactionComplete(transactionID, true);
446         }
447     }
448
449     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
450         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionID());
451         commitCoordinator.handleCanCommit(canCommit, getSender(), self());
452     }
453
454     private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) {
455         LOG.debug("{}: Readying transaction {}, client version {}", persistenceId(),
456                 ready.getTransactionID(), ready.getTxnClientVersion());
457
458         // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the
459         // commitCoordinator in preparation for the subsequent three phase commit initiated by
460         // the front-end.
461         commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(),
462                 ready.getModification());
463
464         // Return our actor path as we'll handle the three phase commit, except if the Tx client
465         // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version
466         // node. In that case, the subsequent 3-phase commit messages won't contain the
467         // transactionId so to maintain backwards compatibility, we create a separate cohort actor
468         // to provide the compatible behavior.
469         if(ready.getTxnClientVersion() < DataStoreVersions.HELIUM_1_VERSION) {
470             LOG.debug("{}: Creating BackwardsCompatibleThreePhaseCommitCohort", persistenceId());
471             ActorRef replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props(
472                     ready.getTransactionID()));
473
474             ReadyTransactionReply readyTransactionReply =
475                     new ReadyTransactionReply(Serialization.serializedActorPath(replyActorPath));
476             getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() :
477                     readyTransactionReply, getSelf());
478
479         } else {
480
481             getSender().tell(ready.isReturnSerialized() ? READY_TRANSACTION_REPLY.toSerializable() :
482                     READY_TRANSACTION_REPLY, getSelf());
483         }
484     }
485
486     private void handleAbortTransaction(final AbortTransaction abort) {
487         doAbortTransaction(abort.getTransactionID(), getSender());
488     }
489
490     void doAbortTransaction(final String transactionID, final ActorRef sender) {
491         final CohortEntry cohortEntry = commitCoordinator.getCohortEntryIfCurrent(transactionID);
492         if(cohortEntry != null) {
493             LOG.debug("{}: Aborting transaction {}", persistenceId(), transactionID);
494
495             // We don't remove the cached cohort entry here (ie pass false) in case the Tx was
496             // aborted during replication in which case we may still commit locally if replication
497             // succeeds.
498             commitCoordinator.currentTransactionComplete(transactionID, false);
499
500             final ListenableFuture<Void> future = cohortEntry.getCohort().abort();
501             final ActorRef self = getSelf();
502
503             Futures.addCallback(future, new FutureCallback<Void>() {
504                 @Override
505                 public void onSuccess(final Void v) {
506                     shardMBean.incrementAbortTransactionsCount();
507
508                     if(sender != null) {
509                         sender.tell(AbortTransactionReply.INSTANCE.toSerializable(), self);
510                     }
511                 }
512
513                 @Override
514                 public void onFailure(final Throwable t) {
515                     LOG.error("{}: An exception happened during abort", persistenceId(), t);
516
517                     if(sender != null) {
518                         sender.tell(new akka.actor.Status.Failure(t), self);
519                     }
520                 }
521             });
522         }
523     }
524
525     private void handleCreateTransaction(final Object message) {
526         if (isLeader()) {
527             createTransaction(CreateTransaction.fromSerializable(message));
528         } else if (getLeader() != null) {
529             getLeader().forward(message, getContext());
530         } else {
531             getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException(String.format(
532                 "Could not find leader for shard %s so transaction cannot be created. This typically happens" +
533                 " when the system is coming up or recovering and a leader is being elected. Try again" +
534                 " later.", persistenceId()))), getSelf());
535         }
536     }
537
538     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
539         DOMStoreTransactionChain chain =
540             transactionChains.remove(closeTransactionChain.getTransactionChainId());
541
542         if(chain != null) {
543             chain.close();
544         }
545     }
546
547     private ActorRef createTypedTransactionActor(int transactionType,
548             ShardTransactionIdentifier transactionId, String transactionChainId,
549             short clientVersion ) {
550
551         DOMStoreTransactionFactory factory = store;
552
553         if(!transactionChainId.isEmpty()) {
554             factory = transactionChains.get(transactionChainId);
555             if(factory == null){
556                 DOMStoreTransactionChain transactionChain = store.createTransactionChain();
557                 transactionChains.put(transactionChainId, transactionChain);
558                 factory = transactionChain;
559             }
560         }
561
562         if(this.schemaContext == null) {
563             throw new IllegalStateException("SchemaContext is not set");
564         }
565
566         if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) {
567
568             shardMBean.incrementWriteOnlyTransactionCount();
569
570             return createShardTransaction(factory.newWriteOnlyTransaction(), transactionId, clientVersion);
571
572         } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) {
573
574             shardMBean.incrementReadWriteTransactionCount();
575
576             return createShardTransaction(factory.newReadWriteTransaction(), transactionId, clientVersion);
577
578         } else if (transactionType == TransactionProxy.TransactionType.READ_ONLY.ordinal()) {
579
580             shardMBean.incrementReadOnlyTransactionCount();
581
582             return createShardTransaction(factory.newReadOnlyTransaction(), transactionId, clientVersion);
583
584         } else {
585             throw new IllegalArgumentException(
586                 "Shard="+name + ":CreateTransaction message has unidentified transaction type="
587                     + transactionType);
588         }
589     }
590
591     private ActorRef createShardTransaction(DOMStoreTransaction transaction, ShardTransactionIdentifier transactionId,
592                                             short clientVersion){
593         return getContext().actorOf(
594                 ShardTransaction.props(transaction, getSelf(),
595                         schemaContext, datastoreContext, shardMBean,
596                         transactionId.getRemoteTransactionId(), clientVersion)
597                         .withDispatcher(txnDispatcherPath),
598                 transactionId.toString());
599
600     }
601
602     private void createTransaction(CreateTransaction createTransaction) {
603         try {
604             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
605                 createTransaction.getTransactionId(), createTransaction.getTransactionChainId(),
606                 createTransaction.getVersion());
607
608             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
609                     createTransaction.getTransactionId()).toSerializable(), getSelf());
610         } catch (Exception e) {
611             getSender().tell(new akka.actor.Status.Failure(e), getSelf());
612         }
613     }
614
615     private ActorRef createTransaction(int transactionType, String remoteTransactionId,
616             String transactionChainId, short clientVersion) {
617
618
619         ShardTransactionIdentifier transactionId = new ShardTransactionIdentifier(remoteTransactionId);
620
621         if(LOG.isDebugEnabled()) {
622             LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
623         }
624
625         ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId,
626                 transactionChainId, clientVersion);
627
628         return transactionActor;
629     }
630
631     private void syncCommitTransaction(final DOMStoreWriteTransaction transaction)
632         throws ExecutionException, InterruptedException {
633         DOMStoreThreePhaseCommitCohort commitCohort = transaction.ready();
634         commitCohort.preCommit().get();
635         commitCohort.commit().get();
636     }
637
638     private void commitWithNewTransaction(final Modification modification) {
639         DOMStoreWriteTransaction tx = store.newWriteOnlyTransaction();
640         modification.apply(tx);
641         try {
642             syncCommitTransaction(tx);
643             shardMBean.incrementCommittedTransactionCount();
644             shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
645         } catch (InterruptedException | ExecutionException e) {
646             shardMBean.incrementFailedTransactionsCount();
647             LOG.error("{}: Failed to commit", persistenceId(), e);
648         }
649     }
650
651     private void updateSchemaContext(final UpdateSchemaContext message) {
652         this.schemaContext = message.getSchemaContext();
653         updateSchemaContext(message.getSchemaContext());
654         store.onGlobalContextUpdated(message.getSchemaContext());
655     }
656
657     @VisibleForTesting
658     void updateSchemaContext(final SchemaContext schemaContext) {
659         store.onGlobalContextUpdated(schemaContext);
660     }
661
662     private void registerChangeListener(final RegisterChangeListener registerChangeListener) {
663
664         LOG.debug("{}: registerDataChangeListener for {}", persistenceId(), registerChangeListener.getPath());
665
666         ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
667                                                      NormalizedNode<?, ?>>> registration;
668         if(isLeader()) {
669             registration = doChangeListenerRegistration(registerChangeListener);
670         } else {
671             LOG.debug("{}: Shard is not the leader - delaying registration", persistenceId());
672
673             DelayedListenerRegistration delayedReg =
674                     new DelayedListenerRegistration(registerChangeListener);
675             delayedListenerRegistrations.add(delayedReg);
676             registration = delayedReg;
677         }
678
679         ActorRef listenerRegistration = getContext().actorOf(
680                 DataChangeListenerRegistration.props(registration));
681
682         LOG.debug("{}: registerDataChangeListener sending reply, listenerRegistrationPath = {} ",
683                 persistenceId(), listenerRegistration.path());
684
685         getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
686     }
687
688     private ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
689                                                NormalizedNode<?, ?>>> doChangeListenerRegistration(
690             final RegisterChangeListener registerChangeListener) {
691
692         ActorSelection dataChangeListenerPath = getContext().system().actorSelection(
693                 registerChangeListener.getDataChangeListenerPath());
694
695         // Notify the listener if notifications should be enabled or not
696         // If this shard is the leader then it will enable notifications else
697         // it will not
698         dataChangeListenerPath.tell(new EnableNotification(true), getSelf());
699
700         // Now store a reference to the data change listener so it can be notified
701         // at a later point if notifications should be enabled or disabled
702         dataChangeListeners.add(dataChangeListenerPath);
703
704         AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> listener =
705                 new DataChangeListenerProxy(dataChangeListenerPath);
706
707         LOG.debug("{}: Registering for path {}", persistenceId(), registerChangeListener.getPath());
708
709         return store.registerChangeListener(registerChangeListener.getPath(), listener,
710                 registerChangeListener.getScope());
711     }
712
713     private boolean isMetricsCaptureEnabled(){
714         CommonConfig config = new CommonConfig(getContext().system().settings().config());
715         return config.isMetricCaptureEnabled();
716     }
717
718     @Override
719     protected
720     void startLogRecoveryBatch(final int maxBatchSize) {
721         currentLogRecoveryBatch = Lists.newArrayListWithCapacity(maxBatchSize);
722
723         if(LOG.isDebugEnabled()) {
724             LOG.debug("{}: starting log recovery batch with max size {}", persistenceId(), maxBatchSize);
725         }
726     }
727
728     @Override
729     protected void appendRecoveredLogEntry(final Payload data) {
730         if(data instanceof ModificationPayload) {
731             try {
732                 currentLogRecoveryBatch.add(((ModificationPayload) data).getModification());
733             } catch (ClassNotFoundException | IOException e) {
734                 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
735             }
736         } else if (data instanceof CompositeModificationPayload) {
737             currentLogRecoveryBatch.add(((CompositeModificationPayload) data).getModification());
738         } else if (data instanceof CompositeModificationByteStringPayload) {
739             currentLogRecoveryBatch.add(((CompositeModificationByteStringPayload) data).getModification());
740         } else {
741             LOG.error("{}: Unknown state received {} during recovery", persistenceId(), data);
742         }
743     }
744
745     @Override
746     protected void applyRecoverySnapshot(final byte[] snapshotBytes) {
747         if(recoveryCoordinator == null) {
748             recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
749                     LOG, name.toString());
750         }
751
752         recoveryCoordinator.submit(snapshotBytes, store.newWriteOnlyTransaction());
753
754         if(LOG.isDebugEnabled()) {
755             LOG.debug("{}: submitted recovery sbapshot", persistenceId());
756         }
757     }
758
759     @Override
760     protected void applyCurrentLogRecoveryBatch() {
761         if(recoveryCoordinator == null) {
762             recoveryCoordinator = new ShardRecoveryCoordinator(persistenceId(), schemaContext,
763                     LOG, name.toString());
764         }
765
766         recoveryCoordinator.submit(currentLogRecoveryBatch, store.newWriteOnlyTransaction());
767
768         if(LOG.isDebugEnabled()) {
769             LOG.debug("{}: submitted log recovery batch with size {}", persistenceId(),
770                     currentLogRecoveryBatch.size());
771         }
772     }
773
774     @Override
775     protected void onRecoveryComplete() {
776         if(recoveryCoordinator != null) {
777             Collection<DOMStoreWriteTransaction> txList = recoveryCoordinator.getTransactions();
778
779             if(LOG.isDebugEnabled()) {
780                 LOG.debug("{}: recovery complete - committing {} Tx's", persistenceId(), txList.size());
781             }
782
783             for(DOMStoreWriteTransaction tx: txList) {
784                 try {
785                     syncCommitTransaction(tx);
786                     shardMBean.incrementCommittedTransactionCount();
787                 } catch (InterruptedException | ExecutionException e) {
788                     shardMBean.incrementFailedTransactionsCount();
789                     LOG.error("{}: Failed to commit", persistenceId(), e);
790                 }
791             }
792         }
793
794         recoveryCoordinator = null;
795         currentLogRecoveryBatch = null;
796
797         //notify shard manager
798         getContext().parent().tell(new ActorInitialized(), getSelf());
799
800         // Being paranoid here - this method should only be called once but just in case...
801         if(txCommitTimeoutCheckSchedule == null) {
802             // Schedule a message to be periodically sent to check if the current in-progress
803             // transaction should be expired and aborted.
804             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
805             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
806                     period, period, getSelf(),
807                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
808         }
809     }
810
811     @Override
812     protected void applyState(final ActorRef clientActor, final String identifier, final Object data) {
813
814         if(data instanceof ModificationPayload) {
815             try {
816                 applyModificationToState(clientActor, identifier, ((ModificationPayload) data).getModification());
817             } catch (ClassNotFoundException | IOException e) {
818                 LOG.error("{}: Error extracting ModificationPayload", persistenceId(), e);
819             }
820         }
821         else if (data instanceof CompositeModificationPayload) {
822             Object modification = ((CompositeModificationPayload) data).getModification();
823
824             applyModificationToState(clientActor, identifier, modification);
825         } else if(data instanceof CompositeModificationByteStringPayload ){
826             Object modification = ((CompositeModificationByteStringPayload) data).getModification();
827
828             applyModificationToState(clientActor, identifier, modification);
829         } else {
830             LOG.error("{}: Unknown state received {} Class loader = {} CompositeNodeMod.ClassLoader = {}",
831                     persistenceId(), data, data.getClass().getClassLoader(),
832                     CompositeModificationPayload.class.getClassLoader());
833         }
834     }
835
836     private void applyModificationToState(ActorRef clientActor, String identifier, Object modification) {
837         if(modification == null) {
838             LOG.error(
839                     "{}: modification is null - this is very unexpected, clientActor = {}, identifier = {}",
840                     persistenceId(), identifier, clientActor != null ? clientActor.path().toString() : null);
841         } else if(clientActor == null) {
842             // There's no clientActor to which to send a commit reply so we must be applying
843             // replicated state from the leader.
844             commitWithNewTransaction(MutableCompositeModification.fromSerializable(modification));
845         } else {
846             // This must be the OK to commit after replication consensus.
847             finishCommit(clientActor, identifier);
848         }
849     }
850
851     @Override
852     protected void createSnapshot() {
853         // Create a transaction actor. We are really going to treat the transaction as a worker
854         // so that this actor does not get block building the snapshot. THe transaction actor will
855         // after processing the CreateSnapshot message.
856
857         ActorRef createSnapshotTransaction = createTransaction(
858                 TransactionProxy.TransactionType.READ_ONLY.ordinal(),
859                 "createSnapshot" + ++createSnapshotTransactionCounter, "",
860                 DataStoreVersions.CURRENT_VERSION);
861
862         createSnapshotTransaction.tell(CreateSnapshot.INSTANCE, self());
863     }
864
865     @VisibleForTesting
866     @Override
867     protected void applySnapshot(final byte[] snapshotBytes) {
868         // Since this will be done only on Recovery or when this actor is a Follower
869         // we can safely commit everything in here. We not need to worry about event notifications
870         // as they would have already been disabled on the follower
871
872         LOG.info("{}: Applying snapshot", persistenceId());
873         try {
874             DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
875
876             NormalizedNode<?, ?> node = SerializationUtils.deserializeNormalizedNode(snapshotBytes);
877
878             // delete everything first
879             transaction.delete(DATASTORE_ROOT);
880
881             // Add everything from the remote node back
882             transaction.write(DATASTORE_ROOT, node);
883             syncCommitTransaction(transaction);
884         } catch (InterruptedException | ExecutionException e) {
885             LOG.error("{}: An exception occurred when applying snapshot", persistenceId(), e);
886         } finally {
887             LOG.info("{}: Done applying snapshot", persistenceId());
888         }
889     }
890
891     @Override
892     protected void onStateChanged() {
893         boolean isLeader = isLeader();
894         for (ActorSelection dataChangeListener : dataChangeListeners) {
895             dataChangeListener.tell(new EnableNotification(isLeader), getSelf());
896         }
897
898         if(isLeader) {
899             for(DelayedListenerRegistration reg: delayedListenerRegistrations) {
900                 if(!reg.isClosed()) {
901                     reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener()));
902                 }
903             }
904
905             delayedListenerRegistrations.clear();
906         }
907
908         // If this actor is no longer the leader close all the transaction chains
909         if(!isLeader){
910             for(Map.Entry<String, DOMStoreTransactionChain> entry : transactionChains.entrySet()){
911                 if(LOG.isDebugEnabled()) {
912                     LOG.debug(
913                         "{}: onStateChanged: Closing transaction chain {} because shard {} is no longer the leader",
914                         persistenceId(), entry.getKey(), getId());
915                 }
916                 entry.getValue().close();
917             }
918
919             transactionChains.clear();
920         }
921     }
922
923     @Override
924     protected DataPersistenceProvider persistence() {
925         return dataPersistenceProvider;
926     }
927
928     @Override public String persistenceId() {
929         return this.name.toString();
930     }
931
932     @VisibleForTesting
933     DataPersistenceProvider getDataPersistenceProvider() {
934         return dataPersistenceProvider;
935     }
936
937     private static class ShardCreator implements Creator<Shard> {
938
939         private static final long serialVersionUID = 1L;
940
941         final ShardIdentifier name;
942         final Map<ShardIdentifier, String> peerAddresses;
943         final DatastoreContext datastoreContext;
944         final SchemaContext schemaContext;
945
946         ShardCreator(final ShardIdentifier name, final Map<ShardIdentifier, String> peerAddresses,
947                 final DatastoreContext datastoreContext, final SchemaContext schemaContext) {
948             this.name = name;
949             this.peerAddresses = peerAddresses;
950             this.datastoreContext = datastoreContext;
951             this.schemaContext = schemaContext;
952         }
953
954         @Override
955         public Shard create() throws Exception {
956             return new Shard(name, peerAddresses, datastoreContext, schemaContext);
957         }
958     }
959
960     @VisibleForTesting
961     public InMemoryDOMDataStore getDataStore() {
962         return store;
963     }
964
965     @VisibleForTesting
966     ShardStats getShardMBean() {
967         return shardMBean;
968     }
969
970     private static class DelayedListenerRegistration implements
971         ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>> {
972
973         private volatile boolean closed;
974
975         private final RegisterChangeListener registerChangeListener;
976
977         private volatile ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
978                                                              NormalizedNode<?, ?>>> delegate;
979
980         DelayedListenerRegistration(final RegisterChangeListener registerChangeListener) {
981             this.registerChangeListener = registerChangeListener;
982         }
983
984         void setDelegate( final ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier,
985                                             NormalizedNode<?, ?>>> registration) {
986             this.delegate = registration;
987         }
988
989         boolean isClosed() {
990             return closed;
991         }
992
993         RegisterChangeListener getRegisterChangeListener() {
994             return registerChangeListener;
995         }
996
997         @Override
998         public AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> getInstance() {
999             return delegate != null ? delegate.getInstance() : null;
1000         }
1001
1002         @Override
1003         public void close() {
1004             closed = true;
1005             if(delegate != null) {
1006                 delegate.close();
1007             }
1008         }
1009     }
1010 }