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