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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.