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

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