cb072b5c6a031a9ee5e5c3ba1753939cb66509ab
[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.actor.Status.Failure;
16 import akka.serialization.Serialization;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.Optional;
19 import com.google.common.base.Preconditions;
20 import com.google.common.base.Ticker;
21 import com.google.common.collect.ImmutableList;
22 import com.google.common.collect.Range;
23 import java.io.IOException;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.Map;
29 import java.util.concurrent.TimeUnit;
30 import javax.annotation.Nonnull;
31 import javax.annotation.Nullable;
32 import org.opendaylight.controller.cluster.access.ABIVersion;
33 import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
34 import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
35 import org.opendaylight.controller.cluster.access.commands.LocalHistoryRequest;
36 import org.opendaylight.controller.cluster.access.commands.NotLeaderException;
37 import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
38 import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
39 import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
40 import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
41 import org.opendaylight.controller.cluster.access.concepts.Request;
42 import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
43 import org.opendaylight.controller.cluster.access.concepts.RequestException;
44 import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
45 import org.opendaylight.controller.cluster.access.concepts.RetiredGenerationException;
46 import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
47 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
48 import org.opendaylight.controller.cluster.access.concepts.UnsupportedRequestException;
49 import org.opendaylight.controller.cluster.common.actor.CommonConfig;
50 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
51 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
52 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
53 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
54 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
55 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
56 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
57 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
58 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
59 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
60 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
61 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
62 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
63 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
64 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
65 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
67 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
68 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
69 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
70 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
71 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
72 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
73 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
74 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
75 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
76 import org.opendaylight.controller.cluster.datastore.utils.Dispatchers;
77 import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
78 import org.opendaylight.controller.cluster.notifications.RegisterRoleChangeListener;
79 import org.opendaylight.controller.cluster.notifications.RoleChangeNotifier;
80 import org.opendaylight.controller.cluster.raft.RaftActor;
81 import org.opendaylight.controller.cluster.raft.RaftActorRecoveryCohort;
82 import org.opendaylight.controller.cluster.raft.RaftActorSnapshotCohort;
83 import org.opendaylight.controller.cluster.raft.RaftState;
84 import org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus;
85 import org.opendaylight.controller.cluster.raft.client.messages.OnDemandRaftState;
86 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
87 import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
88 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
89 import org.opendaylight.yangtools.concepts.Identifier;
90 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
91 import org.opendaylight.yangtools.yang.data.api.schema.tree.TipProducingDataTree;
92 import org.opendaylight.yangtools.yang.data.api.schema.tree.TreeType;
93 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
94 import scala.concurrent.duration.Duration;
95 import scala.concurrent.duration.FiniteDuration;
96
97 /**
98  * A Shard represents a portion of the logical data tree.
99  *
100  * <p>
101  * Our Shard uses InMemoryDataTree as it's internal representation and delegates all requests it
102  */
103 public class Shard extends RaftActor {
104
105     @VisibleForTesting
106     static final Object TX_COMMIT_TIMEOUT_CHECK_MESSAGE = new Object() {
107         @Override
108         public String toString() {
109             return "txCommitTimeoutCheck";
110         }
111     };
112
113     @VisibleForTesting
114     static final Object GET_SHARD_MBEAN_MESSAGE = new Object() {
115         @Override
116         public String toString() {
117             return "getShardMBeanMessage";
118         }
119     };
120
121     // FIXME: shard names should be encapsulated in their own class and this should be exposed as a constant.
122     public static final String DEFAULT_NAME = "default";
123
124     private static final Collection<ABIVersion> SUPPORTED_ABIVERSIONS;
125
126     static {
127         final ABIVersion[] values = ABIVersion.values();
128         final ABIVersion[] real = Arrays.copyOfRange(values, 1, values.length - 1);
129         SUPPORTED_ABIVERSIONS = ImmutableList.copyOf(real).reverse();
130     }
131
132     // FIXME: make this a dynamic property based on mailbox size and maximum number of clients
133     private static final int CLIENT_MAX_MESSAGES = 1000;
134
135     // The state of this Shard
136     private final ShardDataTree store;
137
138     /// The name of this shard
139     private final String name;
140
141     private final ShardStats shardMBean;
142
143     private DatastoreContext datastoreContext;
144
145     private final ShardCommitCoordinator commitCoordinator;
146
147     private long transactionCommitTimeout;
148
149     private Cancellable txCommitTimeoutCheckSchedule;
150
151     private final Optional<ActorRef> roleChangeNotifier;
152
153     private final MessageTracker appendEntriesReplyTracker;
154
155     private final ShardTransactionActorFactory transactionActorFactory;
156
157     private final ShardSnapshotCohort snapshotCohort;
158
159     private final DataTreeChangeListenerSupport treeChangeSupport = new DataTreeChangeListenerSupport(this);
160     private final DataChangeListenerSupport changeSupport = new DataChangeListenerSupport(this);
161
162
163     private ShardSnapshot restoreFromSnapshot;
164
165     private final ShardTransactionMessageRetrySupport messageRetrySupport;
166
167     private final FrontendMetadata frontendMetadata = new FrontendMetadata();
168     private final Map<FrontendIdentifier, LeaderFrontendState> knownFrontends = new HashMap<>();
169
170     protected Shard(final AbstractBuilder<?, ?> builder) {
171         super(builder.getId().toString(), builder.getPeerAddresses(),
172                 Optional.of(builder.getDatastoreContext().getShardRaftConfig()), DataStoreVersions.CURRENT_VERSION);
173
174         this.name = builder.getId().toString();
175         this.datastoreContext = builder.getDatastoreContext();
176         this.restoreFromSnapshot = builder.getRestoreFromSnapshot();
177
178         setPersistence(datastoreContext.isPersistent());
179
180         LOG.info("Shard created : {}, persistent : {}", name, datastoreContext.isPersistent());
181
182         ShardDataTreeChangeListenerPublisherActorProxy treeChangeListenerPublisher =
183                 new ShardDataTreeChangeListenerPublisherActorProxy(getContext(), name + "-DTCL-publisher");
184         ShardDataChangeListenerPublisherActorProxy dataChangeListenerPublisher =
185                 new ShardDataChangeListenerPublisherActorProxy(getContext(), name + "-DCL-publisher");
186         if (builder.getDataTree() != null) {
187             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getDataTree(),
188                     treeChangeListenerPublisher, dataChangeListenerPublisher, name);
189         } else {
190             store = new ShardDataTree(this, builder.getSchemaContext(), builder.getTreeType(),
191                     builder.getDatastoreContext().getStoreRoot(), treeChangeListenerPublisher,
192                     dataChangeListenerPublisher, name);
193         }
194
195         shardMBean = ShardMBeanFactory.getShardStatsMBean(name, datastoreContext.getDataStoreMXBeanType(), this);
196
197         if (isMetricsCaptureEnabled()) {
198             getContext().become(new MeteringBehavior(this));
199         }
200
201         commitCoordinator = new ShardCommitCoordinator(store, LOG, this.name);
202
203         setTransactionCommitTimeout();
204
205         // create a notifier actor for each cluster member
206         roleChangeNotifier = createRoleChangeNotifier(name);
207
208         appendEntriesReplyTracker = new MessageTracker(AppendEntriesReply.class,
209                 getRaftActorContext().getConfigParams().getIsolatedCheckIntervalInMillis());
210
211         transactionActorFactory = new ShardTransactionActorFactory(store, datastoreContext,
212                 new Dispatchers(context().system().dispatchers()).getDispatcherPath(
213                         Dispatchers.DispatcherType.Transaction), self(), getContext(), shardMBean);
214
215         snapshotCohort = ShardSnapshotCohort.create(getContext(), builder.getId().getMemberName(), store, LOG,
216             this.name);
217
218         messageRetrySupport = new ShardTransactionMessageRetrySupport(this);
219     }
220
221     private void setTransactionCommitTimeout() {
222         transactionCommitTimeout = TimeUnit.MILLISECONDS.convert(
223                 datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS) / 2;
224     }
225
226     private Optional<ActorRef> createRoleChangeNotifier(final String shardId) {
227         ActorRef shardRoleChangeNotifier = this.getContext().actorOf(
228             RoleChangeNotifier.getProps(shardId), shardId + "-notifier");
229         return Optional.of(shardRoleChangeNotifier);
230     }
231
232     @Override
233     public void postStop() {
234         LOG.info("Stopping Shard {}", persistenceId());
235
236         super.postStop();
237
238         messageRetrySupport.close();
239
240         if (txCommitTimeoutCheckSchedule != null) {
241             txCommitTimeoutCheckSchedule.cancel();
242         }
243
244         commitCoordinator.abortPendingTransactions("Transaction aborted due to shutdown.", this);
245
246         shardMBean.unregisterMBean();
247     }
248
249     @Override
250     protected void handleRecover(final Object message) {
251         LOG.debug("{}: onReceiveRecover: Received message {} from {}", persistenceId(), message.getClass(),
252             getSender());
253
254         super.handleRecover(message);
255         if (LOG.isTraceEnabled()) {
256             appendEntriesReplyTracker.begin();
257         }
258     }
259
260     @SuppressWarnings("checkstyle:IllegalCatch")
261     @Override
262     protected void handleNonRaftCommand(final Object message) {
263         try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
264             final Optional<Error> maybeError = context.error();
265             if (maybeError.isPresent()) {
266                 LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
267                     maybeError.get());
268             }
269
270             if (message instanceof RequestEnvelope) {
271                 final long now = ticker().read();
272                 final RequestEnvelope envelope = (RequestEnvelope)message;
273
274                 try {
275                     final RequestSuccess<?, ?> success = handleRequest(envelope, now);
276                     if (success != null) {
277                         envelope.sendSuccess(success, ticker().read() - now);
278                     }
279                 } catch (RequestException e) {
280                     LOG.debug("{}: request {} failed", persistenceId(), envelope, e);
281                     envelope.sendFailure(e, ticker().read() - now);
282                 } catch (Exception e) {
283                     LOG.debug("{}: request {} caused failure", persistenceId(), envelope, e);
284                     envelope.sendFailure(new RuntimeRequestException("Request failed to process", e),
285                         ticker().read() - now);
286                 }
287             } else if (message instanceof ConnectClientRequest) {
288                 handleConnectClient((ConnectClientRequest)message);
289             } else if (CreateTransaction.isSerializedType(message)) {
290                 handleCreateTransaction(message);
291             } else if (message instanceof BatchedModifications) {
292                 handleBatchedModifications((BatchedModifications)message);
293             } else if (message instanceof ForwardedReadyTransaction) {
294                 handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
295             } else if (message instanceof ReadyLocalTransaction) {
296                 handleReadyLocalTransaction((ReadyLocalTransaction)message);
297             } else if (CanCommitTransaction.isSerializedType(message)) {
298                 handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
299             } else if (CommitTransaction.isSerializedType(message)) {
300                 handleCommitTransaction(CommitTransaction.fromSerializable(message));
301             } else if (AbortTransaction.isSerializedType(message)) {
302                 handleAbortTransaction(AbortTransaction.fromSerializable(message));
303             } else if (CloseTransactionChain.isSerializedType(message)) {
304                 closeTransactionChain(CloseTransactionChain.fromSerializable(message));
305             } else if (message instanceof RegisterChangeListener) {
306                 changeSupport.onMessage((RegisterChangeListener) message, isLeader(), hasLeader());
307             } else if (message instanceof RegisterDataTreeChangeListener) {
308                 treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
309             } else if (message instanceof UpdateSchemaContext) {
310                 updateSchemaContext((UpdateSchemaContext) message);
311             } else if (message instanceof PeerAddressResolved) {
312                 PeerAddressResolved resolved = (PeerAddressResolved) message;
313                 setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
314             } else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
315                 store.checkForExpiredTransactions(transactionCommitTimeout);
316                 commitCoordinator.checkForExpiredTransactions(transactionCommitTimeout, this);
317             } else if (message instanceof DatastoreContext) {
318                 onDatastoreContext((DatastoreContext)message);
319             } else if (message instanceof RegisterRoleChangeListener) {
320                 roleChangeNotifier.get().forward(message, context());
321             } else if (message instanceof FollowerInitialSyncUpStatus) {
322                 shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
323                 context().parent().tell(message, self());
324             } else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
325                 sender().tell(getShardMBean(), self());
326             } else if (message instanceof GetShardDataTree) {
327                 sender().tell(store.getDataTree(), self());
328             } else if (message instanceof ServerRemoved) {
329                 context().parent().forward(message, context());
330             } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
331                 messageRetrySupport.onTimerMessage(message);
332             } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
333                 store.processCohortRegistryCommand(getSender(),
334                         (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
335             } else {
336                 super.handleNonRaftCommand(message);
337             }
338         }
339     }
340
341     // Acquire our frontend tracking handle and verify generation matches
342     private LeaderFrontendState getFrontend(final ClientIdentifier clientId) throws RequestException {
343         final LeaderFrontendState existing = knownFrontends.get(clientId.getFrontendId());
344         if (existing != null) {
345             final int cmp = Long.compareUnsigned(existing.getIdentifier().getGeneration(), clientId.getGeneration());
346             if (cmp == 0) {
347                 return existing;
348             }
349             if (cmp > 0) {
350                 LOG.debug("{}: rejecting request from outdated client {}", persistenceId(), clientId);
351                 throw new RetiredGenerationException(existing.getIdentifier().getGeneration());
352             }
353
354             LOG.info("{}: retiring state {}, outdated by request from client {}", persistenceId(), existing, clientId);
355             existing.retire();
356             knownFrontends.remove(clientId.getFrontendId());
357         } else {
358             LOG.debug("{}: client {} is not yet known", persistenceId(), clientId);
359         }
360
361         final LeaderFrontendState ret = new LeaderFrontendState(persistenceId(), clientId, store);
362         knownFrontends.put(clientId.getFrontendId(), ret);
363         LOG.debug("{}: created state {} for client {}", persistenceId(), ret, clientId);
364         return ret;
365     }
366
367     private static @Nonnull ABIVersion selectVersion(final ConnectClientRequest message) {
368         final Range<ABIVersion> clientRange = Range.closed(message.getMinVersion(), message.getMaxVersion());
369         for (ABIVersion v : SUPPORTED_ABIVERSIONS) {
370             if (clientRange.contains(v)) {
371                 return v;
372             }
373         }
374
375         throw new IllegalArgumentException(String.format(
376             "No common version between backend versions %s and client versions %s", SUPPORTED_ABIVERSIONS,
377             clientRange));
378     }
379
380     @SuppressWarnings("checkstyle:IllegalCatch")
381     private void handleConnectClient(final ConnectClientRequest message) {
382         try {
383             if (!isLeader() || !isLeaderActive()) {
384                 LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), message);
385                 throw new NotLeaderException(getSelf());
386             }
387
388             final ABIVersion selectedVersion = selectVersion(message);
389             final LeaderFrontendState frontend = getFrontend(message.getTarget());
390             frontend.reconnect();
391             message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
392                 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
393                 ActorRef.noSender());
394         } catch (RequestException | RuntimeException e) {
395             message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
396         }
397     }
398
399     private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
400             throws RequestException {
401         // We are not the leader, hence we want to fail-fast.
402         if (!isLeader() || !isLeaderActive()) {
403             LOG.debug("{}: not currently leader, rejecting request {}", persistenceId(), envelope);
404             throw new NotLeaderException(getSelf());
405         }
406
407         final Request<?, ?> request = envelope.getMessage();
408         if (request instanceof TransactionRequest) {
409             final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
410             final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
411             return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
412         } else if (request instanceof LocalHistoryRequest) {
413             final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
414             final ClientIdentifier clientId = lhReq.getTarget().getClientId();
415             return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
416         } else {
417             LOG.debug("{}: rejecting unsupported request {}", persistenceId(), request);
418             throw new UnsupportedRequestException(request);
419         }
420     }
421
422     private boolean hasLeader() {
423         return getLeaderId() != null;
424     }
425
426     public int getPendingTxCommitQueueSize() {
427         return store.getQueueSize();
428     }
429
430     public int getCohortCacheSize() {
431         return commitCoordinator.getCohortCacheSize();
432     }
433
434     @Override
435     protected Optional<ActorRef> getRoleChangeNotifier() {
436         return roleChangeNotifier;
437     }
438
439     @Override
440     protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
441             final short leaderPayloadVersion) {
442         return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
443                 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
444     }
445
446     protected void onDatastoreContext(final DatastoreContext context) {
447         datastoreContext = context;
448
449         setTransactionCommitTimeout();
450
451         setPersistence(datastoreContext.isPersistent());
452
453         updateConfigParams(datastoreContext.getShardRaftConfig());
454     }
455
456     // applyState() will be invoked once consensus is reached on the payload
457     void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
458         boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
459         if (canSkipPayload) {
460             applyState(self(), id, payload);
461         } else {
462             // We are faking the sender
463             persistData(self(), id, payload, batchHint);
464         }
465     }
466
467     private void handleCommitTransaction(final CommitTransaction commit) {
468         if (isLeader()) {
469             commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
470         } else {
471             ActorSelection leader = getLeader();
472             if (leader == null) {
473                 messageRetrySupport.addMessageToRetry(commit, getSender(),
474                         "Could not commit transaction " + commit.getTransactionId());
475             } else {
476                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
477                 leader.forward(commit, getContext());
478             }
479         }
480     }
481
482     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
483         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
484
485         if (isLeader()) {
486             commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
487         } else {
488             ActorSelection leader = getLeader();
489             if (leader == null) {
490                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
491                         "Could not canCommit transaction " + canCommit.getTransactionId());
492             } else {
493                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
494                 leader.forward(canCommit, getContext());
495             }
496         }
497     }
498
499     @SuppressWarnings("checkstyle:IllegalCatch")
500     protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
501         try {
502             commitCoordinator.handleBatchedModifications(batched, sender, this);
503         } catch (Exception e) {
504             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
505                     batched.getTransactionId(), e);
506             sender.tell(new Failure(e), getSelf());
507         }
508     }
509
510     private void handleBatchedModifications(final BatchedModifications batched) {
511         // This message is sent to prepare the modifications transaction directly on the Shard as an
512         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
513         // BatchedModifications message, the caller sets the ready flag in the message indicating
514         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
515         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
516         // ReadyTransaction message.
517
518         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
519         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
520         // the primary/leader shard. However with timing and caching on the front-end, there's a small
521         // window where it could have a stale leader during leadership transitions.
522         //
523         boolean isLeaderActive = isLeaderActive();
524         if (isLeader() && isLeaderActive) {
525             handleBatchedModificationsLocal(batched, getSender());
526         } else {
527             ActorSelection leader = getLeader();
528             if (!isLeaderActive || leader == null) {
529                 messageRetrySupport.addMessageToRetry(batched, getSender(),
530                         "Could not commit transaction " + batched.getTransactionId());
531             } else {
532                 // If this is not the first batch and leadership changed in between batched messages,
533                 // we need to reconstruct previous BatchedModifications from the transaction
534                 // DataTreeModification, honoring the max batched modification count, and forward all the
535                 // previous BatchedModifications to the new leader.
536                 Collection<BatchedModifications> newModifications = commitCoordinator
537                         .createForwardedBatchedModifications(batched,
538                                 datastoreContext.getShardBatchedModificationCount());
539
540                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
541                         newModifications.size(), leader);
542
543                 for (BatchedModifications bm : newModifications) {
544                     leader.forward(bm, getContext());
545                 }
546             }
547         }
548     }
549
550     private boolean failIfIsolatedLeader(final ActorRef sender) {
551         if (isIsolatedLeader()) {
552             sender.tell(new Failure(new NoShardLeaderException(String.format(
553                     "Shard %s was the leader but has lost contact with all of its followers. Either all"
554                     + " other follower nodes are down or this node is isolated by a network partition.",
555                     persistenceId()))), getSelf());
556             return true;
557         }
558
559         return false;
560     }
561
562     protected boolean isIsolatedLeader() {
563         return getRaftState() == RaftState.IsolatedLeader;
564     }
565
566     @SuppressWarnings("checkstyle:IllegalCatch")
567     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
568         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
569
570         boolean isLeaderActive = isLeaderActive();
571         if (isLeader() && isLeaderActive) {
572             try {
573                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
574             } catch (Exception e) {
575                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
576                         message.getTransactionId(), e);
577                 getSender().tell(new Failure(e), getSelf());
578             }
579         } else {
580             ActorSelection leader = getLeader();
581             if (!isLeaderActive || leader == null) {
582                 messageRetrySupport.addMessageToRetry(message, getSender(),
583                         "Could not commit transaction " + message.getTransactionId());
584             } else {
585                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
586                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
587                 leader.forward(message, getContext());
588             }
589         }
590     }
591
592     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
593         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
594
595         boolean isLeaderActive = isLeaderActive();
596         if (isLeader() && isLeaderActive) {
597             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
598         } else {
599             ActorSelection leader = getLeader();
600             if (!isLeaderActive || leader == null) {
601                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
602                         "Could not commit transaction " + forwardedReady.getTransactionId());
603             } else {
604                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
605
606                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
607                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
608                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
609                 leader.forward(readyLocal, getContext());
610             }
611         }
612     }
613
614     private void handleAbortTransaction(final AbortTransaction abort) {
615         doAbortTransaction(abort.getTransactionId(), getSender());
616     }
617
618     void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
619         commitCoordinator.handleAbort(transactionID, sender, this);
620     }
621
622     private void handleCreateTransaction(final Object message) {
623         if (isLeader()) {
624             createTransaction(CreateTransaction.fromSerializable(message));
625         } else if (getLeader() != null) {
626             getLeader().forward(message, getContext());
627         } else {
628             getSender().tell(new Failure(new NoShardLeaderException(
629                     "Could not create a shard transaction", persistenceId())), getSelf());
630         }
631     }
632
633     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
634         final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
635         store.closeTransactionChain(id, () -> store.purgeTransactionChain(id, null));
636     }
637
638     @SuppressWarnings("checkstyle:IllegalCatch")
639     private void createTransaction(final CreateTransaction createTransaction) {
640         try {
641             if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
642                     && failIfIsolatedLeader(getSender())) {
643                 return;
644             }
645
646             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
647                 createTransaction.getTransactionId());
648
649             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
650                     createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
651         } catch (Exception e) {
652             getSender().tell(new Failure(e), getSelf());
653         }
654     }
655
656     private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
657         LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
658         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
659             transactionId);
660     }
661
662     private void updateSchemaContext(final UpdateSchemaContext message) {
663         updateSchemaContext(message.getSchemaContext());
664     }
665
666     @VisibleForTesting
667     void updateSchemaContext(final SchemaContext schemaContext) {
668         store.updateSchemaContext(schemaContext);
669     }
670
671     private boolean isMetricsCaptureEnabled() {
672         CommonConfig config = new CommonConfig(getContext().system().settings().config());
673         return config.isMetricCaptureEnabled();
674     }
675
676     @Override
677     @VisibleForTesting
678     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
679         return snapshotCohort;
680     }
681
682     @Override
683     @Nonnull
684     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
685         return new ShardRecoveryCoordinator(store,
686             restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
687     }
688
689     @Override
690     protected void onRecoveryComplete() {
691         restoreFromSnapshot = null;
692
693         //notify shard manager
694         getContext().parent().tell(new ActorInitialized(), getSelf());
695
696         // Being paranoid here - this method should only be called once but just in case...
697         if (txCommitTimeoutCheckSchedule == null) {
698             // Schedule a message to be periodically sent to check if the current in-progress
699             // transaction should be expired and aborted.
700             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
701             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
702                     period, period, getSelf(),
703                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
704         }
705     }
706
707     @Override
708     protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
709         if (data instanceof Payload) {
710             try {
711                 store.applyReplicatedPayload(identifier, (Payload)data);
712             } catch (DataValidationFailedException | IOException e) {
713                 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
714             }
715         } else {
716             LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
717         }
718     }
719
720     @Override
721     protected void onStateChanged() {
722         boolean isLeader = isLeader();
723         boolean hasLeader = hasLeader();
724         changeSupport.onLeadershipChange(isLeader, hasLeader);
725         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
726
727         // If this actor is no longer the leader close all the transaction chains
728         if (!isLeader) {
729             if (LOG.isDebugEnabled()) {
730                 LOG.debug(
731                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
732                     persistenceId(), getId());
733             }
734
735             store.closeAllTransactionChains();
736         }
737
738         if (hasLeader && !isIsolatedLeader()) {
739             messageRetrySupport.retryMessages();
740         }
741     }
742
743     @Override
744     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
745         shardMBean.incrementLeadershipChangeCount();
746
747         boolean hasLeader = hasLeader();
748         if (hasLeader && !isLeader()) {
749             // Another leader was elected. If we were the previous leader and had pending transactions, convert
750             // them to transaction messages and send to the new leader.
751             ActorSelection leader = getLeader();
752             if (leader != null) {
753                 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
754
755                 if (!messagesToForward.isEmpty()) {
756                     LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
757                             messagesToForward.size(), leader);
758
759                     for (Object message : messagesToForward) {
760                         leader.tell(message, self());
761                     }
762                 }
763             } else {
764                 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
765                         + "change and the leader address isn't available.", this);
766             }
767         }
768
769         if (hasLeader && !isIsolatedLeader()) {
770             messageRetrySupport.retryMessages();
771         }
772     }
773
774     /**
775      * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
776      *
777      * @return the converted messages
778      */
779     public Collection<?> convertPendingTransactionsToMessages() {
780         return commitCoordinator.convertPendingTransactionsToMessages(
781                 datastoreContext.getShardBatchedModificationCount());
782     }
783
784     @Override
785     protected void pauseLeader(final Runnable operation) {
786         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
787         store.setRunOnPendingTransactionsComplete(operation);
788     }
789
790     @Override
791     protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
792         return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
793                 .dataChangeListenerActors(changeSupport.getListenerActors())
794                 .commitCohortActors(store.getCohortActors());
795     }
796
797     @Override
798     public String persistenceId() {
799         return this.name;
800     }
801
802     @VisibleForTesting
803     ShardCommitCoordinator getCommitCoordinator() {
804         return commitCoordinator;
805     }
806
807     public DatastoreContext getDatastoreContext() {
808         return datastoreContext;
809     }
810
811     @VisibleForTesting
812     public ShardDataTree getDataStore() {
813         return store;
814     }
815
816     @VisibleForTesting
817     ShardStats getShardMBean() {
818         return shardMBean;
819     }
820
821     public static Builder builder() {
822         return new Builder();
823     }
824
825     public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
826         private final Class<S> shardClass;
827         private ShardIdentifier id;
828         private Map<String, String> peerAddresses = Collections.emptyMap();
829         private DatastoreContext datastoreContext;
830         private SchemaContext schemaContext;
831         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
832         private TipProducingDataTree dataTree;
833         private volatile boolean sealed;
834
835         protected AbstractBuilder(final Class<S> shardClass) {
836             this.shardClass = shardClass;
837         }
838
839         protected void checkSealed() {
840             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
841         }
842
843         @SuppressWarnings("unchecked")
844         private T self() {
845             return (T) this;
846         }
847
848         public T id(final ShardIdentifier newId) {
849             checkSealed();
850             this.id = newId;
851             return self();
852         }
853
854         public T peerAddresses(final Map<String, String> newPeerAddresses) {
855             checkSealed();
856             this.peerAddresses = newPeerAddresses;
857             return self();
858         }
859
860         public T datastoreContext(final DatastoreContext newDatastoreContext) {
861             checkSealed();
862             this.datastoreContext = newDatastoreContext;
863             return self();
864         }
865
866         public T schemaContext(final SchemaContext newSchemaContext) {
867             checkSealed();
868             this.schemaContext = newSchemaContext;
869             return self();
870         }
871
872         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
873             checkSealed();
874             this.restoreFromSnapshot = newRestoreFromSnapshot;
875             return self();
876         }
877
878         public T dataTree(final TipProducingDataTree newDataTree) {
879             checkSealed();
880             this.dataTree = newDataTree;
881             return self();
882         }
883
884         public ShardIdentifier getId() {
885             return id;
886         }
887
888         public Map<String, String> getPeerAddresses() {
889             return peerAddresses;
890         }
891
892         public DatastoreContext getDatastoreContext() {
893             return datastoreContext;
894         }
895
896         public SchemaContext getSchemaContext() {
897             return schemaContext;
898         }
899
900         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
901             return restoreFromSnapshot;
902         }
903
904         public TipProducingDataTree getDataTree() {
905             return dataTree;
906         }
907
908         public TreeType getTreeType() {
909             switch (datastoreContext.getLogicalStoreType()) {
910                 case CONFIGURATION:
911                     return TreeType.CONFIGURATION;
912                 case OPERATIONAL:
913                     return TreeType.OPERATIONAL;
914                 default:
915                     throw new IllegalStateException("Unhandled logical store type "
916                             + datastoreContext.getLogicalStoreType());
917             }
918         }
919
920         protected void verify() {
921             Preconditions.checkNotNull(id, "id should not be null");
922             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
923             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
924             Preconditions.checkNotNull(schemaContext, "schemaContext should not be null");
925         }
926
927         public Props props() {
928             sealed = true;
929             verify();
930             return Props.create(shardClass, this);
931         }
932     }
933
934     public static class Builder extends AbstractBuilder<Builder, Shard> {
935         private Builder() {
936             super(Shard.class);
937         }
938     }
939
940     Ticker ticker() {
941         return Ticker.systemTicker();
942     }
943 }

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