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

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