X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?p=controller.git;a=blobdiff_plain;f=opendaylight%2Fmd-sal%2Fsal-distributed-datastore%2Fsrc%2Fmain%2Fjava%2Forg%2Fopendaylight%2Fcontroller%2Fcluster%2Fdatastore%2FShard.java;h=5ea9b30c63e7d3f9b44e9800eddb2b5e42f08657;hp=fef7e228737b9cb0ab63db21596c4bba10230065;hb=f5a373c5378af41f62a2c36ced4046fbdb77e00b;hpb=b3c034675957f963c5878ce1e5e183ec2de8b5e2 diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/Shard.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/Shard.java index fef7e22873..5ea9b30c63 100644 --- a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/Shard.java +++ b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/Shard.java @@ -27,16 +27,19 @@ import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; +import org.opendaylight.controller.cluster.DataPersistenceProvider; import org.opendaylight.controller.cluster.common.actor.CommonConfig; import org.opendaylight.controller.cluster.common.actor.MeteringBehavior; import org.opendaylight.controller.cluster.datastore.ShardCommitCoordinator.CohortEntry; +import org.opendaylight.controller.cluster.datastore.compat.BackwardsCompatibleThreePhaseCommitCohort; +import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException; import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier; import org.opendaylight.controller.cluster.datastore.identifiers.ShardTransactionIdentifier; import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardMBeanFactory; import org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.ShardStats; -import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized; import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction; import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply; +import org.opendaylight.controller.cluster.datastore.messages.ActorInitialized; import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction; import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain; import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction; @@ -74,14 +77,14 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode; import org.opendaylight.yangtools.yang.model.api.SchemaContext; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; -import java.util.ArrayList; + +import javax.annotation.Nonnull; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; -import javax.annotation.Nonnull; /** * A Shard represents a portion of the logical data tree
@@ -103,19 +106,20 @@ public class Shard extends RaftActor { private final LoggingAdapter LOG = Logging.getLogger(getContext().system(), this); - // By default persistent will be true and can be turned off using the system - // property shard.persistent - private final boolean persistent; - /// The name of this shard private final ShardIdentifier name; private final ShardStats shardMBean; - private final List dataChangeListeners = new ArrayList<>(); + private final List dataChangeListeners = Lists.newArrayList(); + + private final List delayedListenerRegistrations = + Lists.newArrayList(); private final DatastoreContext datastoreContext; + private final DataPersistenceProvider dataPersistenceProvider; + private SchemaContext schemaContext; private ActorRef createSnapshotTransaction; @@ -144,12 +148,9 @@ public class Shard extends RaftActor { this.name = name; this.datastoreContext = datastoreContext; this.schemaContext = schemaContext; + this.dataPersistenceProvider = (datastoreContext.isPersistent()) ? new PersistentDataProvider() : new NonPersistentRaftDataProvider(); - String setting = System.getProperty("shard.persistent"); - - this.persistent = !"false".equals(setting); - - LOG.info("Shard created : {} persistent : {}", name, persistent); + LOG.info("Shard created : {} persistent : {}", name, datastoreContext.isPersistent()); store = InMemoryDOMDataStoreFactory.create(name.toString(), null, datastoreContext.getDataStoreProperties()); @@ -207,7 +208,7 @@ public class Shard extends RaftActor { } @Override - public void onReceiveRecover(Object message) { + public void onReceiveRecover(Object message) throws Exception { if(LOG.isDebugEnabled()) { LOG.debug("onReceiveRecover: Received message {} from {}", message.getClass().toString(), @@ -216,13 +217,17 @@ public class Shard extends RaftActor { if (message instanceof RecoveryFailure){ LOG.error(((RecoveryFailure) message).cause(), "Recovery failed because of this cause"); + + // Even though recovery failed, we still need to finish our recovery, eg send the + // ActorInitialized message and start the txCommitTimeoutCheckSchedule. + onRecoveryComplete(); } else { super.onReceiveRecover(message); } } @Override - public void onReceiveCommand(Object message) { + public void onReceiveCommand(Object message) throws Exception { if(LOG.isDebugEnabled()) { LOG.debug("onReceiveCommand: Received message {} from {}", message, getSender()); } @@ -300,12 +305,8 @@ public class Shard extends RaftActor { // currently uses a same thread executor anyway. cohortEntry.getCohort().preCommit().get(); - if(persistent) { - Shard.this.persistData(getSender(), transactionID, - new CompositeModificationPayload(cohortEntry.getModification().toSerializable())); - } else { - Shard.this.finishCommit(getSender(), transactionID); - } + Shard.this.persistData(getSender(), transactionID, + new CompositeModificationPayload(cohortEntry.getModification().toSerializable())); } catch (InterruptedException | ExecutionException e) { LOG.error(e, "An exception occurred while preCommitting transaction {}", cohortEntry.getTransactionID()); @@ -374,7 +375,8 @@ public class Shard extends RaftActor { } private void handleForwardedReadyTransaction(ForwardedReadyTransaction ready) { - LOG.debug("Readying transaction {}", ready.getTransactionID()); + LOG.debug("Readying transaction {}, client version {}", ready.getTransactionID(), + ready.getTxnClientVersion()); // This message is forwarded by the ShardTransaction on ready. We cache the cohort in the // commitCoordinator in preparation for the subsequent three phase commit initiated by @@ -382,9 +384,22 @@ public class Shard extends RaftActor { commitCoordinator.transactionReady(ready.getTransactionID(), ready.getCohort(), ready.getModification()); - // Return our actor path as we'll handle the three phase commit. - getSender().tell(new ReadyTransactionReply(Serialization.serializedActorPath(self())). - toSerializable(), getSelf()); + // Return our actor path as we'll handle the three phase commit, except if the Tx client + // version < 1 (Helium-1 version). This means the Tx was initiated by a base Helium version + // node. In that case, the subsequent 3-phase commit messages won't contain the + // transactionId so to maintain backwards compatibility, we create a separate cohort actor + // to provide the compatible behavior. + ActorRef replyActorPath = self(); + if(ready.getTxnClientVersion() < CreateTransaction.HELIUM_1_VERSION) { + LOG.debug("Creating BackwardsCompatibleThreePhaseCommitCohort"); + replyActorPath = getContext().actorOf(BackwardsCompatibleThreePhaseCommitCohort.props( + ready.getTransactionID())); + } + + ReadyTransactionReply readyTransactionReply = new ReadyTransactionReply( + Serialization.serializedActorPath(replyActorPath)); + getSender().tell(ready.isReturnSerialized() ? readyTransactionReply.toSerializable() : + readyTransactionReply, getSelf()); } private void handleAbortTransaction(AbortTransaction abort) { @@ -432,9 +447,9 @@ public class Shard extends RaftActor { } else if (getLeader() != null) { getLeader().forward(message, getContext()); } else { - getSender().tell(new akka.actor.Status.Failure(new IllegalStateException( + getSender().tell(new akka.actor.Status.Failure(new NoShardLeaderException( "Could not find shard leader so transaction cannot be created. This typically happens" + - " when system is coming up or recovering and a leader is being elected. Try again" + + " when the system is coming up or recovering and a leader is being elected. Try again" + " later.")), getSelf()); } } @@ -462,10 +477,8 @@ public class Shard extends RaftActor { } } - private ActorRef createTypedTransactionActor( - int transactionType, - ShardTransactionIdentifier transactionId, - String transactionChainId ) { + private ActorRef createTypedTransactionActor(int transactionType, + ShardTransactionIdentifier transactionId, String transactionChainId, int clientVersion ) { DOMStoreTransactionFactory factory = store; @@ -489,7 +502,8 @@ public class Shard extends RaftActor { return getContext().actorOf( ShardTransaction.props(factory.newReadOnlyTransaction(), getSelf(), schemaContext,datastoreContext, shardMBean, - transactionId.getRemoteTransactionId()), transactionId.toString()); + transactionId.getRemoteTransactionId(), clientVersion), + transactionId.toString()); } else if (transactionType == TransactionProxy.TransactionType.READ_WRITE.ordinal()) { @@ -498,7 +512,8 @@ public class Shard extends RaftActor { return getContext().actorOf( ShardTransaction.props(factory.newReadWriteTransaction(), getSelf(), schemaContext, datastoreContext, shardMBean, - transactionId.getRemoteTransactionId()), transactionId.toString()); + transactionId.getRemoteTransactionId(), clientVersion), + transactionId.toString()); } else if (transactionType == TransactionProxy.TransactionType.WRITE_ONLY.ordinal()) { @@ -508,7 +523,8 @@ public class Shard extends RaftActor { return getContext().actorOf( ShardTransaction.props(factory.newWriteOnlyTransaction(), getSelf(), schemaContext, datastoreContext, shardMBean, - transactionId.getRemoteTransactionId()), transactionId.toString()); + transactionId.getRemoteTransactionId(), clientVersion), + transactionId.toString()); } else { throw new IllegalArgumentException( "Shard="+name + ":CreateTransaction message has unidentified transaction type=" @@ -518,10 +534,12 @@ public class Shard extends RaftActor { private void createTransaction(CreateTransaction createTransaction) { createTransaction(createTransaction.getTransactionType(), - createTransaction.getTransactionId(), createTransaction.getTransactionChainId()); + createTransaction.getTransactionId(), createTransaction.getTransactionChainId(), + createTransaction.getVersion()); } - private ActorRef createTransaction(int transactionType, String remoteTransactionId, String transactionChainId) { + private ActorRef createTransaction(int transactionType, String remoteTransactionId, + String transactionChainId, int clientVersion) { ShardTransactionIdentifier transactionId = ShardTransactionIdentifier.builder() @@ -530,8 +548,8 @@ public class Shard extends RaftActor { if(LOG.isDebugEnabled()) { LOG.debug("Creating transaction : {} ", transactionId); } - ActorRef transactionActor = - createTypedTransactionActor(transactionType, transactionId, transactionChainId); + ActorRef transactionActor = createTypedTransactionActor(transactionType, transactionId, + transactionChainId, clientVersion); getSender() .tell(new CreateTransactionReply( @@ -568,53 +586,60 @@ public class Shard extends RaftActor { store.onGlobalContextUpdated(message.getSchemaContext()); } - @VisibleForTesting void updateSchemaContext(SchemaContext schemaContext) { + @VisibleForTesting + void updateSchemaContext(SchemaContext schemaContext) { store.onGlobalContextUpdated(schemaContext); } - private void registerChangeListener( - RegisterChangeListener registerChangeListener) { + private void registerChangeListener(RegisterChangeListener registerChangeListener) { - if(LOG.isDebugEnabled()) { - LOG.debug("registerDataChangeListener for {}", registerChangeListener - .getPath()); + LOG.debug("registerDataChangeListener for {}", registerChangeListener.getPath()); + + ListenerRegistration>> registration; + if(isLeader()) { + registration = doChangeListenerRegistration(registerChangeListener); + } else { + LOG.debug("Shard is not the leader - delaying registration"); + + DelayedListenerRegistration delayedReg = + new DelayedListenerRegistration(registerChangeListener); + delayedListenerRegistrations.add(delayedReg); + registration = delayedReg; } + ActorRef listenerRegistration = getContext().actorOf( + DataChangeListenerRegistration.props(registration)); + + LOG.debug("registerDataChangeListener sending reply, listenerRegistrationPath = {} ", + listenerRegistration.path()); - ActorSelection dataChangeListenerPath = getContext() - .system().actorSelection( - registerChangeListener.getDataChangeListenerPath()); + getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf()); + } + + private ListenerRegistration>> doChangeListenerRegistration( + RegisterChangeListener registerChangeListener) { + 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()); + dataChangeListenerPath.tell(new EnableNotification(true), 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> - listener = new DataChangeListenerProxy(schemaContext, dataChangeListenerPath); - - ListenerRegistration>> - registration = store.registerChangeListener(registerChangeListener.getPath(), - listener, registerChangeListener.getScope()); - ActorRef listenerRegistration = - getContext().actorOf( - DataChangeListenerRegistration.props(registration)); + AsyncDataChangeListener> listener = + new DataChangeListenerProxy(schemaContext, dataChangeListenerPath); - if(LOG.isDebugEnabled()) { - LOG.debug( - "registerDataChangeListener sending reply, listenerRegistrationPath = {} " - , listenerRegistration.path().toString()); - } + LOG.debug("Registering for path {}", registerChangeListener.getPath()); - getSender() - .tell(new RegisterChangeListenerReply(listenerRegistration.path()), - getSelf()); + return store.registerChangeListener(registerChangeListener.getPath(), listener, + registerChangeListener.getScope()); } private boolean isMetricsCaptureEnabled(){ @@ -695,12 +720,15 @@ public class Shard extends RaftActor { //notify shard manager getContext().parent().tell(new ActorInitialized(), getSelf()); - // Schedule a message to be periodically sent to check if the current in-progress - // transaction should be expired and aborted. - FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS); - txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule( - period, period, getSelf(), - TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender()); + // Being paranoid here - this method should only be called once but just in case... + if(txCommitTimeoutCheckSchedule == null) { + // Schedule a message to be periodically sent to check if the current in-progress + // transaction should be expired and aborted. + FiniteDuration period = Duration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS); + txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule( + period, period, getSelf(), + TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender()); + } } @Override @@ -752,7 +780,8 @@ public class Shard extends RaftActor { // so that this actor does not get block building the snapshot createSnapshotTransaction = createTransaction( TransactionProxy.TransactionType.READ_ONLY.ordinal(), - "createSnapshot" + ++createSnapshotTransactionCounter, ""); + "createSnapshot" + ++createSnapshotTransactionCounter, "", + CreateTransaction.CURRENT_VERSION); createSnapshotTransaction.tell( new ReadData(YangInstanceIdentifier.builder().build()).toSerializable(), self()); @@ -787,17 +816,28 @@ public class Shard extends RaftActor { } } - @Override protected void onStateChanged() { + @Override + protected void onStateChanged() { + boolean isLeader = isLeader(); for (ActorSelection dataChangeListener : dataChangeListeners) { - dataChangeListener - .tell(new EnableNotification(isLeader()), getSelf()); + dataChangeListener.tell(new EnableNotification(isLeader), getSelf()); + } + + if(isLeader) { + for(DelayedListenerRegistration reg: delayedListenerRegistrations) { + if(!reg.isClosed()) { + reg.setDelegate(doChangeListenerRegistration(reg.getRegisterChangeListener())); + } + } + + delayedListenerRegistrations.clear(); } shardMBean.setRaftState(getRaftState().name()); shardMBean.setCurrentTerm(getCurrentTerm()); // If this actor is no longer the leader close all the transaction chains - if(!isLeader()){ + if(!isLeader){ for(Map.Entry entry : transactionChains.entrySet()){ if(LOG.isDebugEnabled()) { LOG.debug( @@ -811,6 +851,11 @@ public class Shard extends RaftActor { } } + @Override + protected DataPersistenceProvider persistence() { + return dataPersistenceProvider; + } + @Override protected void onLeaderChanged(String oldLeader, String newLeader) { shardMBean.setLeader(newLeader); } @@ -819,6 +864,11 @@ public class Shard extends RaftActor { return this.name.toString(); } + @VisibleForTesting + DataPersistenceProvider getDataPersistenceProvider() { + return dataPersistenceProvider; + } + private static class ShardCreator implements Creator { private static final long serialVersionUID = 1L; @@ -851,4 +901,45 @@ public class Shard extends RaftActor { ShardStats getShardMBean() { return shardMBean; } + + private static class DelayedListenerRegistration implements + ListenerRegistration>> { + + private volatile boolean closed; + + private final RegisterChangeListener registerChangeListener; + + private volatile ListenerRegistration>> delegate; + + DelayedListenerRegistration(RegisterChangeListener registerChangeListener) { + this.registerChangeListener = registerChangeListener; + } + + void setDelegate( ListenerRegistration>> registration) { + this.delegate = registration; + } + + boolean isClosed() { + return closed; + } + + RegisterChangeListener getRegisterChangeListener() { + return registerChangeListener; + } + + @Override + public AsyncDataChangeListener> getInstance() { + return delegate != null ? delegate.getInstance() : null; + } + + @Override + public void close() { + closed = true; + if(delegate != null) { + delegate.close(); + } + } + } }