+ private void commit(final ActorRef sender, Object serialized) {
+ Modification modification = MutableCompositeModification
+ .fromSerializable(serialized, schemaContext);
+ DOMStoreThreePhaseCommitCohort cohort =
+ modificationToCohort.remove(serialized);
+ if (cohort == null) {
+ LOG.debug(
+ "Could not find cohort for modification : {}. Writing modification using a new transaction",
+ modification);
+ DOMStoreWriteTransaction transaction =
+ store.newWriteOnlyTransaction();
+ modification.apply(transaction);
+ try {
+ syncCommitTransaction(transaction);
+ } catch (InterruptedException | ExecutionException e) {
+ shardMBean.incrementFailedTransactionsCount();
+ LOG.error("Failed to commit", e);
+ return;
+ }
+ //we want to just apply the recovery commit and return
+ shardMBean.incrementCommittedTransactionCount();
+ return;
+ }
+
+ final ListenableFuture<Void> future = cohort.commit();
+ final ActorRef self = getSelf();
+
+ Futures.addCallback(future, new FutureCallback<Void>() {
+ @Override
+ public void onSuccess(Void v) {
+ sender.tell(new CommitTransactionReply().toSerializable(), self);
+ shardMBean.incrementCommittedTransactionCount();
+ shardMBean.setLastCommittedTransactionTime(System.currentTimeMillis());
+ }
+
+ @Override
+ public void onFailure(Throwable t) {
+ LOG.error(t, "An exception happened during commit");
+ shardMBean.incrementFailedTransactionsCount();
+ sender.tell(new akka.actor.Status.Failure(t), self);
+ }
+ });
+
+ }
+
+ private void handleForwardedCommit(ForwardedCommitTransaction message) {
+ Object serializedModification =
+ message.getModification().toSerializable();
+
+ modificationToCohort
+ .put(serializedModification, message.getCohort());
+
+ if (persistent) {
+ this.persistData(getSender(), "identifier",
+ new CompositeModificationPayload(serializedModification));
+ } else {
+ this.commit(getSender(), serializedModification);
+ }
+ }
+
+ private void updateSchemaContext(UpdateSchemaContext message) {
+ this.schemaContext = message.getSchemaContext();
+ updateSchemaContext(message.getSchemaContext());
+ store.onGlobalContextUpdated(message.getSchemaContext());
+ }
+
+ @VisibleForTesting void updateSchemaContext(SchemaContext schemaContext) {
+ store.onGlobalContextUpdated(schemaContext);
+ }
+
+ private void registerChangeListener(
+ RegisterChangeListener registerChangeListener) {
+
+ LOG.debug("registerDataChangeListener for {}", registerChangeListener
+ .getPath());
+
+
+ ActorSelection dataChangeListenerPath = getContext()
+ .system().actorSelection(
+ registerChangeListener.getDataChangeListenerPath());
+
+
+ // Notify the listener if notifications should be enabled or not
+ // If this shard is the leader then it will enable notifications else
+ // it will not
+ dataChangeListenerPath
+ .tell(new EnableNotification(isLeader()), getSelf());
+
+ // Now store a reference to the data change listener so it can be notified
+ // at a later point if notifications should be enabled or disabled
+ dataChangeListeners.add(dataChangeListenerPath);
+
+ AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>
+ listener = new DataChangeListenerProxy(schemaContext, dataChangeListenerPath);
+
+ ListenerRegistration<AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>>>
+ registration = store.registerChangeListener(registerChangeListener.getPath(),
+ listener, registerChangeListener.getScope());
+ ActorRef listenerRegistration =
+ getContext().actorOf(
+ DataChangeListenerRegistration.props(registration));
+
+ LOG.debug(
+ "registerDataChangeListener sending reply, listenerRegistrationPath = {} "
+ , listenerRegistration.path().toString());
+
+ getSender()
+ .tell(new RegisterChangeListenerReply(listenerRegistration.path()),
+ getSelf());
+ }
+
+ private void createTransactionChain() {
+ DOMStoreTransactionChain chain = store.createTransactionChain();
+ ActorRef transactionChain = getContext().actorOf(
+ ShardTransactionChain.props(chain, schemaContext, datastoreContext, shardMBean));
+ getSender().tell(new CreateTransactionChainReply(transactionChain.path()).toSerializable(),
+ getSelf());
+ }
+
+ @Override protected void applyState(ActorRef clientActor, String identifier,
+ Object data) {
+
+ if (data instanceof CompositeModificationPayload) {
+ Object modification =
+ ((CompositeModificationPayload) data).getModification();
+
+ if (modification != null) {
+ commit(clientActor, modification);
+ } else {
+ LOG.error(
+ "modification is null - this is very unexpected, clientActor = {}, identifier = {}",
+ identifier, clientActor.path().toString());
+ }
+
+ } else {
+ LOG.error("Unknown state received {}", data);
+ }
+
+ // Update stats
+ ReplicatedLogEntry lastLogEntry = getLastLogEntry();
+
+ if (lastLogEntry != null) {
+ shardMBean.setLastLogIndex(lastLogEntry.getIndex());
+ shardMBean.setLastLogTerm(lastLogEntry.getTerm());
+ }
+
+ shardMBean.setCommitIndex(getCommitIndex());
+ shardMBean.setLastApplied(getLastApplied());
+
+ }
+
+ @Override protected void createSnapshot() {
+ if (createSnapshotTransaction == null) {
+
+ // Create a transaction. We are really going to treat the transaction as a worker
+ // so that this actor does not get block building the snapshot
+ createSnapshotTransaction = createTransaction(
+ TransactionProxy.TransactionType.READ_ONLY.ordinal(),
+ "createSnapshot");
+
+ createSnapshotTransaction.tell(
+ new ReadData(YangInstanceIdentifier.builder().build()).toSerializable(), self());
+
+ }
+ }
+
+ @VisibleForTesting @Override protected void applySnapshot(ByteString snapshot) {
+ // Since this will be done only on Recovery or when this actor is a Follower
+ // we can safely commit everything in here. We not need to worry about event notifications
+ // as they would have already been disabled on the follower
+ try {
+ DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
+ NormalizedNodeMessages.Node serializedNode = NormalizedNodeMessages.Node.parseFrom(snapshot);
+ NormalizedNode<?, ?> node = new NormalizedNodeToNodeCodec(schemaContext)
+ .decode(YangInstanceIdentifier.builder().build(), serializedNode);
+
+ // delete everything first
+ transaction.delete(YangInstanceIdentifier.builder().build());
+
+ // Add everything from the remote node back
+ transaction.write(YangInstanceIdentifier.builder().build(), node);
+ syncCommitTransaction(transaction);
+ } catch (InvalidProtocolBufferException | InterruptedException | ExecutionException e) {
+ LOG.error(e, "An exception occurred when applying snapshot");
+ }
+ }
+
+ @Override protected void onStateChanged() {
+ for (ActorSelection dataChangeListener : dataChangeListeners) {
+ dataChangeListener
+ .tell(new EnableNotification(isLeader()), getSelf());
+ }
+
+ if (getLeaderId() != null) {
+ shardMBean.setLeader(getLeaderId());
+ }
+
+ shardMBean.setRaftState(getRaftState().name());
+ shardMBean.setCurrentTerm(getCurrentTerm());
+ }
+
+ @Override public String persistenceId() {
+ return this.name.toString();
+ }
+
+
+ private static class ShardConfigParams extends DefaultConfigParamsImpl {
+ public static final FiniteDuration HEART_BEAT_INTERVAL =
+ new FiniteDuration(500, TimeUnit.MILLISECONDS);
+
+ @Override public FiniteDuration getHeartBeatInterval() {
+ return HEART_BEAT_INTERVAL;
+ }
+ }
+
+ private static class ShardCreator implements Creator<Shard> {
+
+ private static final long serialVersionUID = 1L;
+
+ final ShardIdentifier name;
+ final Map<ShardIdentifier, String> peerAddresses;
+ final DatastoreContext datastoreContext;
+ final SchemaContext schemaContext;
+
+ ShardCreator(ShardIdentifier name, Map<ShardIdentifier, String> peerAddresses,
+ DatastoreContext datastoreContext, SchemaContext schemaContext) {
+ this.name = name;
+ this.peerAddresses = peerAddresses;
+ this.datastoreContext = datastoreContext;
+ this.schemaContext = schemaContext;
+ }
+
+ @Override
+ public Shard create() throws Exception {
+ return new Shard(name, peerAddresses, datastoreContext, schemaContext);
+ }
+ }
+
+ @VisibleForTesting NormalizedNode readStore() throws ExecutionException, InterruptedException {
+ DOMStoreReadTransaction transaction = store.newReadOnlyTransaction();
+
+ CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> future =
+ transaction.read(YangInstanceIdentifier.builder().build());
+
+ NormalizedNode<?, ?> node = future.get().get();
+
+ transaction.close();
+
+ return node;
+ }
+
+ @VisibleForTesting void writeToStore(YangInstanceIdentifier id, NormalizedNode node)
+ throws ExecutionException, InterruptedException {
+ DOMStoreWriteTransaction transaction = store.newWriteOnlyTransaction();
+
+ transaction.write(id, node);
+
+ syncCommitTransaction(transaction);
+ }