959b37cb7b03c2d5cc0cf2d410965b3c39bb6223
[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.Dispatchers;
53 import org.opendaylight.controller.cluster.common.actor.MessageTracker;
54 import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
55 import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
56 import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
57 import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
58 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory;
59 import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats;
60 import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
61 import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized;
62 import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
63 import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
64 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
65 import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
66 import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
67 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
68 import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
69 import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
70 import org.opendaylight.controller.cluster.datastore.messages.MakeLeaderLocal;
71 import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
72 import org.opendaylight.controller.cluster.datastore.messages.PeerAddressResolved;
73 import org.opendaylight.controller.cluster.datastore.messages.PersistAbortTransactionPayload;
74 import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
75 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
76 import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
77 import org.opendaylight.controller.cluster.datastore.messages.ShardLeaderStateChanged;
78 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
79 import org.opendaylight.controller.cluster.datastore.persisted.AbortTransactionPayload;
80 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
81 import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
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.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
436                                 + "isLeadershipTransferInProgress: {}.",
437                         persistenceId(), message, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
438                 throw new NotLeaderException(getSelf());
439             }
440
441             final ABIVersion selectedVersion = selectVersion(message);
442             final LeaderFrontendState frontend = getFrontend(message.getTarget());
443             frontend.reconnect();
444             message.getReplyTo().tell(new ConnectClientSuccess(message.getTarget(), message.getSequence(), getSelf(),
445                 ImmutableList.of(), store.getDataTree(), CLIENT_MAX_MESSAGES).toVersion(selectedVersion),
446                 ActorRef.noSender());
447         } catch (RequestException | RuntimeException e) {
448             message.getReplyTo().tell(new Failure(e), ActorRef.noSender());
449         }
450     }
451
452     private @Nullable RequestSuccess<?, ?> handleRequest(final RequestEnvelope envelope, final long now)
453             throws RequestException {
454         // We are not the leader, hence we want to fail-fast.
455         if (!isLeader() || !isLeaderActive()) {
456             LOG.info("{}: not currently leader, rejecting request {}. isLeader: {}, isLeaderActive: {},"
457                             + "isLeadershipTransferInProgress: {}.",
458                     persistenceId(), envelope, isLeader(), isLeaderActive(), isLeadershipTransferInProgress());
459             throw new NotLeaderException(getSelf());
460         }
461
462         final Request<?, ?> request = envelope.getMessage();
463         if (request instanceof TransactionRequest) {
464             final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
465             final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
466             return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
467         } else if (request instanceof LocalHistoryRequest) {
468             final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
469             final ClientIdentifier clientId = lhReq.getTarget().getClientId();
470             return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
471         } else {
472             LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
473             throw new UnsupportedRequestException(request);
474         }
475     }
476
477     private boolean hasLeader() {
478         return getLeaderId() != null;
479     }
480
481     public int getPendingTxCommitQueueSize() {
482         return store.getQueueSize();
483     }
484
485     public int getCohortCacheSize() {
486         return commitCoordinator.getCohortCacheSize();
487     }
488
489     @Override
490     protected Optional<ActorRef> getRoleChangeNotifier() {
491         return roleChangeNotifier;
492     }
493
494     @Override
495     protected LeaderStateChanged newLeaderStateChanged(final String memberId, final String leaderId,
496             final short leaderPayloadVersion) {
497         return isLeader() ? new ShardLeaderStateChanged(memberId, leaderId, store.getDataTree(), leaderPayloadVersion)
498                 : new ShardLeaderStateChanged(memberId, leaderId, leaderPayloadVersion);
499     }
500
501     protected void onDatastoreContext(final DatastoreContext context) {
502         datastoreContext = context;
503
504         setTransactionCommitTimeout();
505
506         setPersistence(datastoreContext.isPersistent());
507
508         updateConfigParams(datastoreContext.getShardRaftConfig());
509     }
510
511     // applyState() will be invoked once consensus is reached on the payload
512     void persistPayload(final Identifier id, final Payload payload, final boolean batchHint) {
513         boolean canSkipPayload = !hasFollowers() && !persistence().isRecoveryApplicable();
514         if (canSkipPayload) {
515             applyState(self(), id, payload);
516         } else {
517             // We are faking the sender
518             persistData(self(), id, payload, batchHint);
519         }
520     }
521
522     private void handleCommitTransaction(final CommitTransaction commit) {
523         if (isLeader()) {
524             commitCoordinator.handleCommit(commit.getTransactionId(), getSender(), this);
525         } else {
526             ActorSelection leader = getLeader();
527             if (leader == null) {
528                 messageRetrySupport.addMessageToRetry(commit, getSender(),
529                         "Could not commit transaction " + commit.getTransactionId());
530             } else {
531                 LOG.debug("{}: Forwarding CommitTransaction to leader {}", persistenceId(), leader);
532                 leader.forward(commit, getContext());
533             }
534         }
535     }
536
537     private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
538         LOG.debug("{}: Can committing transaction {}", persistenceId(), canCommit.getTransactionId());
539
540         if (isLeader()) {
541             commitCoordinator.handleCanCommit(canCommit.getTransactionId(), getSender(), this);
542         } else {
543             ActorSelection leader = getLeader();
544             if (leader == null) {
545                 messageRetrySupport.addMessageToRetry(canCommit, getSender(),
546                         "Could not canCommit transaction " + canCommit.getTransactionId());
547             } else {
548                 LOG.debug("{}: Forwarding CanCommitTransaction to leader {}", persistenceId(), leader);
549                 leader.forward(canCommit, getContext());
550             }
551         }
552     }
553
554     @SuppressWarnings("checkstyle:IllegalCatch")
555     protected void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
556         try {
557             commitCoordinator.handleBatchedModifications(batched, sender, this);
558         } catch (Exception e) {
559             LOG.error("{}: Error handling BatchedModifications for Tx {}", persistenceId(),
560                     batched.getTransactionId(), e);
561             sender.tell(new Failure(e), getSelf());
562         }
563     }
564
565     private void handleBatchedModifications(final BatchedModifications batched) {
566         // This message is sent to prepare the modifications transaction directly on the Shard as an
567         // optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
568         // BatchedModifications message, the caller sets the ready flag in the message indicating
569         // modifications are complete. The reply contains the cohort actor path (this actor) for the caller
570         // to initiate the 3-phase commit. This also avoids the overhead of sending an additional
571         // ReadyTransaction message.
572
573         // If we're not the leader then forward to the leader. This is a safety measure - we shouldn't
574         // normally get here if we're not the leader as the front-end (TransactionProxy) should determine
575         // the primary/leader shard. However with timing and caching on the front-end, there's a small
576         // window where it could have a stale leader during leadership transitions.
577         //
578         boolean isLeaderActive = isLeaderActive();
579         if (isLeader() && isLeaderActive) {
580             handleBatchedModificationsLocal(batched, getSender());
581         } else {
582             ActorSelection leader = getLeader();
583             if (!isLeaderActive || leader == null) {
584                 messageRetrySupport.addMessageToRetry(batched, getSender(),
585                         "Could not commit transaction " + batched.getTransactionId());
586             } else {
587                 // If this is not the first batch and leadership changed in between batched messages,
588                 // we need to reconstruct previous BatchedModifications from the transaction
589                 // DataTreeModification, honoring the max batched modification count, and forward all the
590                 // previous BatchedModifications to the new leader.
591                 Collection<BatchedModifications> newModifications = commitCoordinator
592                         .createForwardedBatchedModifications(batched,
593                                 datastoreContext.getShardBatchedModificationCount());
594
595                 LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
596                         newModifications.size(), leader);
597
598                 for (BatchedModifications bm : newModifications) {
599                     leader.forward(bm, getContext());
600                 }
601             }
602         }
603     }
604
605     private boolean failIfIsolatedLeader(final ActorRef sender) {
606         if (isIsolatedLeader()) {
607             sender.tell(new Failure(new NoShardLeaderException(String.format(
608                     "Shard %s was the leader but has lost contact with all of its followers. Either all"
609                     + " other follower nodes are down or this node is isolated by a network partition.",
610                     persistenceId()))), getSelf());
611             return true;
612         }
613
614         return false;
615     }
616
617     protected boolean isIsolatedLeader() {
618         return getRaftState() == RaftState.IsolatedLeader;
619     }
620
621     @SuppressWarnings("checkstyle:IllegalCatch")
622     private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
623         LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), message.getTransactionId());
624
625         boolean isLeaderActive = isLeaderActive();
626         if (isLeader() && isLeaderActive) {
627             try {
628                 commitCoordinator.handleReadyLocalTransaction(message, getSender(), this);
629             } catch (Exception e) {
630                 LOG.error("{}: Error handling ReadyLocalTransaction for Tx {}", persistenceId(),
631                         message.getTransactionId(), e);
632                 getSender().tell(new Failure(e), getSelf());
633             }
634         } else {
635             ActorSelection leader = getLeader();
636             if (!isLeaderActive || leader == null) {
637                 messageRetrySupport.addMessageToRetry(message, getSender(),
638                         "Could not commit transaction " + message.getTransactionId());
639             } else {
640                 LOG.debug("{}: Forwarding ReadyLocalTransaction to leader {}", persistenceId(), leader);
641                 message.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
642                 leader.forward(message, getContext());
643             }
644         }
645     }
646
647     private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
648         LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
649
650         boolean isLeaderActive = isLeaderActive();
651         if (isLeader() && isLeaderActive) {
652             commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
653         } else {
654             ActorSelection leader = getLeader();
655             if (!isLeaderActive || leader == null) {
656                 messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
657                         "Could not commit transaction " + forwardedReady.getTransactionId());
658             } else {
659                 LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
660
661                 ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
662                         forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit());
663                 readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
664                 leader.forward(readyLocal, getContext());
665             }
666         }
667     }
668
669     private void handleAbortTransaction(final AbortTransaction abort) {
670         doAbortTransaction(abort.getTransactionId(), getSender());
671     }
672
673     void doAbortTransaction(final Identifier transactionID, final ActorRef sender) {
674         commitCoordinator.handleAbort(transactionID, sender, this);
675     }
676
677     private void handleCreateTransaction(final Object message) {
678         if (isLeader()) {
679             createTransaction(CreateTransaction.fromSerializable(message));
680         } else if (getLeader() != null) {
681             getLeader().forward(message, getContext());
682         } else {
683             getSender().tell(new Failure(new NoShardLeaderException(
684                     "Could not create a shard transaction", persistenceId())), getSelf());
685         }
686     }
687
688     private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
689         final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
690         store.closeTransactionChain(id, null);
691         store.purgeTransactionChain(id, null);
692     }
693
694     @SuppressWarnings("checkstyle:IllegalCatch")
695     private void createTransaction(final CreateTransaction createTransaction) {
696         try {
697             if (TransactionType.fromInt(createTransaction.getTransactionType()) != TransactionType.READ_ONLY
698                     && failIfIsolatedLeader(getSender())) {
699                 return;
700             }
701
702             ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
703                 createTransaction.getTransactionId());
704
705             getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
706                     createTransaction.getTransactionId(), createTransaction.getVersion()).toSerializable(), getSelf());
707         } catch (Exception e) {
708             getSender().tell(new Failure(e), getSelf());
709         }
710     }
711
712     private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
713         LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
714         return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
715             transactionId);
716     }
717
718     private void updateSchemaContext(final UpdateSchemaContext message) {
719         updateSchemaContext(message.getSchemaContext());
720     }
721
722     @VisibleForTesting
723     void updateSchemaContext(final SchemaContext schemaContext) {
724         store.updateSchemaContext(schemaContext);
725     }
726
727     private boolean isMetricsCaptureEnabled() {
728         CommonConfig config = new CommonConfig(getContext().system().settings().config());
729         return config.isMetricCaptureEnabled();
730     }
731
732     @Override
733     @VisibleForTesting
734     public RaftActorSnapshotCohort getRaftActorSnapshotCohort() {
735         return snapshotCohort;
736     }
737
738     @Override
739     @Nonnull
740     protected RaftActorRecoveryCohort getRaftActorRecoveryCohort() {
741         return new ShardRecoveryCoordinator(store,
742             restoreFromSnapshot != null ? restoreFromSnapshot.getSnapshot() : null, persistenceId(), LOG);
743     }
744
745     @Override
746     protected void onRecoveryComplete() {
747         restoreFromSnapshot = null;
748
749         //notify shard manager
750         getContext().parent().tell(new ActorInitialized(), getSelf());
751
752         // Being paranoid here - this method should only be called once but just in case...
753         if (txCommitTimeoutCheckSchedule == null) {
754             // Schedule a message to be periodically sent to check if the current in-progress
755             // transaction should be expired and aborted.
756             FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
757             txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
758                     period, period, getSelf(),
759                     TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
760         }
761     }
762
763     @Override
764     protected void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
765         if (data instanceof Payload) {
766             try {
767                 store.applyReplicatedPayload(identifier, (Payload)data);
768             } catch (DataValidationFailedException | IOException e) {
769                 LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
770             }
771         } else {
772             LOG.error("{}: Unknown state for {} received {}", persistenceId(), identifier, data);
773         }
774     }
775
776     @Override
777     protected void onStateChanged() {
778         boolean isLeader = isLeader();
779         boolean hasLeader = hasLeader();
780         changeSupport.onLeadershipChange(isLeader, hasLeader);
781         treeChangeSupport.onLeadershipChange(isLeader, hasLeader);
782
783         // If this actor is no longer the leader close all the transaction chains
784         if (!isLeader) {
785             if (LOG.isDebugEnabled()) {
786                 LOG.debug(
787                     "{}: onStateChanged: Closing all transaction chains because shard {} is no longer the leader",
788                     persistenceId(), getId());
789             }
790
791             store.purgeLeaderState();
792         }
793
794         if (hasLeader && !isIsolatedLeader()) {
795             messageRetrySupport.retryMessages();
796         }
797     }
798
799     @Override
800     protected void onLeaderChanged(final String oldLeader, final String newLeader) {
801         shardMBean.incrementLeadershipChangeCount();
802
803         final boolean hasLeader = hasLeader();
804         if (!hasLeader) {
805             // No leader implies we are not the leader, lose frontend state if we have any. This also places
806             // an explicit guard so the map will not get modified accidentally.
807             if (!knownFrontends.isEmpty()) {
808                 LOG.debug("{}: removing frontend state for {}", persistenceId(), knownFrontends.keySet());
809                 knownFrontends = ImmutableMap.of();
810             }
811             return;
812         }
813
814         if (!isLeader()) {
815             // Another leader was elected. If we were the previous leader and had pending transactions, convert
816             // them to transaction messages and send to the new leader.
817             ActorSelection leader = getLeader();
818             if (leader != null) {
819                 Collection<?> messagesToForward = convertPendingTransactionsToMessages();
820
821                 if (!messagesToForward.isEmpty()) {
822                     LOG.debug("{}: Forwarding {} pending transaction messages to leader {}", persistenceId(),
823                             messagesToForward.size(), leader);
824
825                     for (Object message : messagesToForward) {
826                         leader.tell(message, self());
827                     }
828                 }
829             } else {
830                 commitCoordinator.abortPendingTransactions("The transacton was aborted due to inflight leadership "
831                         + "change and the leader address isn't available.", this);
832             }
833         } else {
834             // We have become the leader, we need to reconstruct frontend state
835             knownFrontends = Verify.verifyNotNull(frontendMetadata.toLeaderState(this));
836             LOG.debug("{}: became leader with frontend state for {}", persistenceId(), knownFrontends.keySet());
837         }
838
839         if (!isIsolatedLeader()) {
840             messageRetrySupport.retryMessages();
841         }
842     }
843
844     /**
845      * Clears all pending transactions and converts them to messages to be forwarded to a new leader.
846      *
847      * @return the converted messages
848      */
849     public Collection<?> convertPendingTransactionsToMessages() {
850         return commitCoordinator.convertPendingTransactionsToMessages(
851                 datastoreContext.getShardBatchedModificationCount());
852     }
853
854     @Override
855     protected void pauseLeader(final Runnable operation) {
856         LOG.debug("{}: In pauseLeader, operation: {}", persistenceId(), operation);
857         store.setRunOnPendingTransactionsComplete(operation);
858     }
859
860     @Override
861     protected OnDemandRaftState.AbstractBuilder<?> newOnDemandRaftStateBuilder() {
862         return OnDemandShardState.newBuilder().treeChangeListenerActors(treeChangeSupport.getListenerActors())
863                 .dataChangeListenerActors(changeSupport.getListenerActors())
864                 .commitCohortActors(store.getCohortActors());
865     }
866
867     @Override
868     public String persistenceId() {
869         return this.name;
870     }
871
872     @VisibleForTesting
873     ShardCommitCoordinator getCommitCoordinator() {
874         return commitCoordinator;
875     }
876
877     public DatastoreContext getDatastoreContext() {
878         return datastoreContext;
879     }
880
881     @VisibleForTesting
882     public ShardDataTree getDataStore() {
883         return store;
884     }
885
886     @VisibleForTesting
887     ShardStats getShardMBean() {
888         return shardMBean;
889     }
890
891     public static Builder builder() {
892         return new Builder();
893     }
894
895     public abstract static class AbstractBuilder<T extends AbstractBuilder<T, S>, S extends Shard> {
896         private final Class<S> shardClass;
897         private ShardIdentifier id;
898         private Map<String, String> peerAddresses = Collections.emptyMap();
899         private DatastoreContext datastoreContext;
900         private SchemaContextProvider schemaContextProvider;
901         private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
902         private TipProducingDataTree dataTree;
903         private volatile boolean sealed;
904
905         protected AbstractBuilder(final Class<S> shardClass) {
906             this.shardClass = shardClass;
907         }
908
909         protected void checkSealed() {
910             Preconditions.checkState(!sealed, "Builder isalready sealed - further modifications are not allowed");
911         }
912
913         @SuppressWarnings("unchecked")
914         private T self() {
915             return (T) this;
916         }
917
918         public T id(final ShardIdentifier newId) {
919             checkSealed();
920             this.id = newId;
921             return self();
922         }
923
924         public T peerAddresses(final Map<String, String> newPeerAddresses) {
925             checkSealed();
926             this.peerAddresses = newPeerAddresses;
927             return self();
928         }
929
930         public T datastoreContext(final DatastoreContext newDatastoreContext) {
931             checkSealed();
932             this.datastoreContext = newDatastoreContext;
933             return self();
934         }
935
936         public T schemaContextProvider(final SchemaContextProvider schemaContextProvider) {
937             checkSealed();
938             this.schemaContextProvider = Preconditions.checkNotNull(schemaContextProvider);
939             return self();
940         }
941
942         public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
943             checkSealed();
944             this.restoreFromSnapshot = newRestoreFromSnapshot;
945             return self();
946         }
947
948         public T dataTree(final TipProducingDataTree newDataTree) {
949             checkSealed();
950             this.dataTree = newDataTree;
951             return self();
952         }
953
954         public ShardIdentifier getId() {
955             return id;
956         }
957
958         public Map<String, String> getPeerAddresses() {
959             return peerAddresses;
960         }
961
962         public DatastoreContext getDatastoreContext() {
963             return datastoreContext;
964         }
965
966         public SchemaContext getSchemaContext() {
967             return Verify.verifyNotNull(schemaContextProvider.getSchemaContext());
968         }
969
970         public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
971             return restoreFromSnapshot;
972         }
973
974         public TipProducingDataTree getDataTree() {
975             return dataTree;
976         }
977
978         public TreeType getTreeType() {
979             switch (datastoreContext.getLogicalStoreType()) {
980                 case CONFIGURATION:
981                     return TreeType.CONFIGURATION;
982                 case OPERATIONAL:
983                     return TreeType.OPERATIONAL;
984                 default:
985                     throw new IllegalStateException("Unhandled logical store type "
986                             + datastoreContext.getLogicalStoreType());
987             }
988         }
989
990         protected void verify() {
991             Preconditions.checkNotNull(id, "id should not be null");
992             Preconditions.checkNotNull(peerAddresses, "peerAddresses should not be null");
993             Preconditions.checkNotNull(datastoreContext, "dataStoreContext should not be null");
994             Preconditions.checkNotNull(schemaContextProvider, "schemaContextProvider should not be null");
995         }
996
997         public Props props() {
998             sealed = true;
999             verify();
1000             return Props.create(shardClass, this);
1001         }
1002     }
1003
1004     public static class Builder extends AbstractBuilder<Builder, Shard> {
1005         private Builder() {
1006             super(Shard.class);
1007         }
1008     }
1009
1010     Ticker ticker() {
1011         return Ticker.systemTicker();
1012     }
1013
1014     void scheduleNextPendingTransaction() {
1015         self().tell(RESUME_NEXT_PENDING_TRANSACTION, ActorRef.noSender());
1016     }
1017 }

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