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

©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.