Search in sources :

Example 1 with FindLocalShard

use of org.opendaylight.controller.cluster.datastore.messages.FindLocalShard in project controller by opendaylight.

the class ShardManager method findLocalShard.

private void findLocalShard(final String shardName, final ActorRef sender, final Consumer<LocalShardFound> onLocalShardFound) {
    Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext().getShardInitializationTimeout().duration().$times(2));
    Future<Object> futureObj = ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
    futureObj.onComplete(new OnComplete<Object>() {

        @Override
        public void onComplete(final Throwable failure, final Object response) {
            if (failure != null) {
                LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName, failure);
                sender.tell(new Status.Failure(new RuntimeException(String.format("Failed to find local shard %s", shardName), failure)), self());
            } else {
                if (response instanceof LocalShardFound) {
                    getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept((LocalShardFound) response), sender);
                } else if (response instanceof LocalShardNotFound) {
                    String msg = String.format("Local shard %s does not exist", shardName);
                    LOG.debug("{}: {}", persistenceId, msg);
                    sender.tell(new Status.Failure(new IllegalArgumentException(msg)), self());
                } else {
                    String msg = String.format("Failed to find local shard %s: received response: %s", shardName, response);
                    LOG.debug("{}: {}", persistenceId, msg);
                    sender.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response : new RuntimeException(msg)), self());
                }
            }
        }
    }, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
}
Also used : FollowerInitialSyncUpStatus(org.opendaylight.controller.cluster.raft.base.messages.FollowerInitialSyncUpStatus) ChangeShardMembersVotingStatus(org.opendaylight.controller.cluster.datastore.messages.ChangeShardMembersVotingStatus) FlipShardMembersVotingStatus(org.opendaylight.controller.cluster.datastore.messages.FlipShardMembersVotingStatus) Status(akka.actor.Status) ServerChangeStatus(org.opendaylight.controller.cluster.raft.messages.ServerChangeStatus) ChangeServersVotingStatus(org.opendaylight.controller.cluster.raft.messages.ChangeServersVotingStatus) LocalShardFound(org.opendaylight.controller.cluster.datastore.messages.LocalShardFound) LocalShardNotFound(org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound) Timeout(akka.util.Timeout) FindLocalShard(org.opendaylight.controller.cluster.datastore.messages.FindLocalShard) SaveSnapshotFailure(akka.persistence.SaveSnapshotFailure) DeleteSnapshotsFailure(akka.persistence.DeleteSnapshotsFailure) Dispatchers(org.opendaylight.controller.cluster.common.actor.Dispatchers)

Example 2 with FindLocalShard

use of org.opendaylight.controller.cluster.datastore.messages.FindLocalShard in project controller by opendaylight.

the class ActorContext method findLocalShard.

/**
 * Finds a local shard given its shard name and return it's ActorRef.
 *
 * @param shardName the name of the local shard that needs to be found
 * @return a reference to a local shard actor which represents the shard
 *         specified by the shardName
 */
public Optional<ActorRef> findLocalShard(String shardName) {
    Object result = executeOperation(shardManager, new FindLocalShard(shardName, false));
    if (result instanceof LocalShardFound) {
        LocalShardFound found = (LocalShardFound) result;
        LOG.debug("Local shard found {}", found.getPath());
        return Optional.of(found.getPath());
    }
    return Optional.absent();
}
Also used : LocalShardFound(org.opendaylight.controller.cluster.datastore.messages.LocalShardFound) FindLocalShard(org.opendaylight.controller.cluster.datastore.messages.FindLocalShard)

Example 3 with FindLocalShard

use of org.opendaylight.controller.cluster.datastore.messages.FindLocalShard in project controller by opendaylight.

the class DistributedDataStoreIntegrationTest method testTransactionCommitFailureWithNoShardLeader.

@SuppressWarnings("checkstyle:IllegalCatch")
private void testTransactionCommitFailureWithNoShardLeader(final boolean writeOnly, final String testName) throws Exception {
    new IntegrationTestKit(getSystem(), datastoreContextBuilder) {

        {
            final String shardName = "default";
            // We don't want the shard to become the leader so prevent shard
            // elections.
            datastoreContextBuilder.customRaftPolicyImplementation("org.opendaylight.controller.cluster.raft.policy.DisableElectionsRaftPolicy");
            // The ShardManager uses the election timeout for FindPrimary so
            // reset it low so it will timeout quickly.
            datastoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1).shardInitializationTimeout(200, TimeUnit.MILLISECONDS).frontendRequestTimeoutInSeconds(2);
            try (AbstractDataStore dataStore = setupAbstractDataStore(testParameter, testName, false, shardName)) {
                final Object result = dataStore.getActorContext().executeOperation(dataStore.getActorContext().getShardManager(), new FindLocalShard(shardName, true));
                assertTrue("Expected LocalShardFound. Actual: " + result, result instanceof LocalShardFound);
                // Create the write Tx.
                DOMStoreWriteTransaction writeTxToClose = null;
                try {
                    writeTxToClose = writeOnly ? dataStore.newWriteOnlyTransaction() : dataStore.newReadWriteTransaction();
                    final DOMStoreWriteTransaction writeTx = writeTxToClose;
                    assertNotNull("newReadWriteTransaction returned null", writeTx);
                    // Do some modifications and ready the Tx on a separate
                    // thread.
                    final AtomicReference<DOMStoreThreePhaseCommitCohort> txCohort = new AtomicReference<>();
                    final AtomicReference<Exception> caughtEx = new AtomicReference<>();
                    final CountDownLatch txReady = new CountDownLatch(1);
                    final Thread txThread = new Thread(() -> {
                        try {
                            writeTx.write(TestModel.JUNK_PATH, ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
                            txCohort.set(writeTx.ready());
                        } catch (Exception e) {
                            caughtEx.set(e);
                        } finally {
                            txReady.countDown();
                        }
                    });
                    txThread.start();
                    // Wait for the Tx operations to complete.
                    boolean done = Uninterruptibles.awaitUninterruptibly(txReady, 5, TimeUnit.SECONDS);
                    if (caughtEx.get() != null) {
                        throw caughtEx.get();
                    }
                    assertEquals("Tx ready", true, done);
                    // exception cause.
                    try {
                        txCohort.get().canCommit().get(10, TimeUnit.SECONDS);
                        fail("Expected NoShardLeaderException");
                    } catch (final ExecutionException e) {
                        final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(e.getCause());
                        if (DistributedDataStore.class.equals(testParameter)) {
                            assertTrue(Throwables.getRootCause(e) instanceof NoShardLeaderException);
                        } else {
                            assertTrue(msg, Throwables.getRootCause(e) instanceof RequestTimeoutException);
                        }
                    }
                } finally {
                    try {
                        if (writeTxToClose != null) {
                            writeTxToClose.close();
                        }
                    } catch (Exception e) {
                    // FIXME TransactionProxy.close throws IllegalStateException:
                    // Transaction is ready, it cannot be closed
                    }
                }
            }
        }
    };
}
Also used : LocalShardFound(org.opendaylight.controller.cluster.datastore.messages.LocalShardFound) DOMStoreWriteTransaction(org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction) FindLocalShard(org.opendaylight.controller.cluster.datastore.messages.FindLocalShard) AtomicReference(java.util.concurrent.atomic.AtomicReference) AddressFromURIString(akka.actor.AddressFromURIString) CountDownLatch(java.util.concurrent.CountDownLatch) DOMStoreThreePhaseCommitCohort(org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort) ReadFailedException(org.opendaylight.mdsal.common.api.ReadFailedException) NotInitializedException(org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException) TransactionChainClosedException(org.opendaylight.mdsal.common.api.TransactionChainClosedException) RequestTimeoutException(org.opendaylight.controller.cluster.access.client.RequestTimeoutException) NoShardLeaderException(org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException) IOException(java.io.IOException) TransactionCommitFailedException(org.opendaylight.mdsal.common.api.TransactionCommitFailedException) ExecutionException(java.util.concurrent.ExecutionException) NoShardLeaderException(org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException) RequestTimeoutException(org.opendaylight.controller.cluster.access.client.RequestTimeoutException) ExecutionException(java.util.concurrent.ExecutionException)

Example 4 with FindLocalShard

use of org.opendaylight.controller.cluster.datastore.messages.FindLocalShard in project controller by opendaylight.

the class DataChangeListenerRegistrationProxyTest method testSuccessfulRegistrationForClusteredListener.

@Test(timeout = 10000)
public void testSuccessfulRegistrationForClusteredListener() {
    new TestKit(getSystem()) {

        {
            ActorContext actorContext = new ActorContext(getSystem(), getRef(), mock(ClusterWrapper.class), mock(Configuration.class));
            AsyncDataChangeListener<YangInstanceIdentifier, NormalizedNode<?, ?>> mockClusteredListener = Mockito.mock(ClusteredDOMDataChangeListener.class);
            final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy("shard-1", actorContext, mockClusteredListener);
            final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
            final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
            new Thread(() -> proxy.init(path, scope)).start();
            FiniteDuration timeout = duration("5 seconds");
            FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
            Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
            reply(new LocalShardFound(getRef()));
            RegisterChangeListener registerMsg = expectMsgClass(timeout, RegisterChangeListener.class);
            Assert.assertEquals("getPath", path, registerMsg.getPath());
            Assert.assertEquals("getScope", scope, registerMsg.getScope());
            Assert.assertEquals("isRegisterOnAllInstances", true, registerMsg.isRegisterOnAllInstances());
            reply(new RegisterDataTreeNotificationListenerReply(getRef()));
            for (int i = 0; i < 20 * 5 && proxy.getListenerRegistrationActor() == null; i++) {
                Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
            }
            Assert.assertEquals("getListenerRegistrationActor", getSystem().actorSelection(getRef().path()), proxy.getListenerRegistrationActor());
            watch(proxy.getDataChangeListenerActor());
            proxy.close();
            // The listener registration actor should get a Close message
            expectMsgClass(timeout, CloseDataTreeNotificationListenerRegistration.class);
            // The DataChangeListener actor should be terminated
            expectMsgClass(timeout, Terminated.class);
            proxy.close();
            expectNoMsg();
        }
    };
}
Also used : DataChangeScope(org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope) RegisterDataTreeNotificationListenerReply(org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNotificationListenerReply) LocalShardFound(org.opendaylight.controller.cluster.datastore.messages.LocalShardFound) Configuration(org.opendaylight.controller.cluster.datastore.config.Configuration) RegisterChangeListener(org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener) FiniteDuration(scala.concurrent.duration.FiniteDuration) FindLocalShard(org.opendaylight.controller.cluster.datastore.messages.FindLocalShard) TestKit(akka.testkit.javadsl.TestKit) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) ActorContext(org.opendaylight.controller.cluster.datastore.utils.ActorContext) NormalizedNode(org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode) Test(org.junit.Test)

Example 5 with FindLocalShard

use of org.opendaylight.controller.cluster.datastore.messages.FindLocalShard in project controller by opendaylight.

the class DataChangeListenerRegistrationProxyTest method testLocalShardNotInitialized.

@Test(timeout = 10000)
public void testLocalShardNotInitialized() {
    new TestKit(getSystem()) {

        {
            ActorContext actorContext = new ActorContext(getSystem(), getRef(), mock(ClusterWrapper.class), mock(Configuration.class));
            final DataChangeListenerRegistrationProxy proxy = new DataChangeListenerRegistrationProxy("shard-1", actorContext, mockListener);
            final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
            final DataChangeScope scope = AsyncDataBroker.DataChangeScope.ONE;
            new Thread(() -> proxy.init(path, scope)).start();
            FiniteDuration timeout = duration("5 seconds");
            FindLocalShard findLocalShard = expectMsgClass(timeout, FindLocalShard.class);
            Assert.assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
            reply(new NotInitializedException("not initialized"));
            expectNoMsg(duration("1 seconds"));
            proxy.close();
        }
    };
}
Also used : DataChangeScope(org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope) NotInitializedException(org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException) Configuration(org.opendaylight.controller.cluster.datastore.config.Configuration) FiniteDuration(scala.concurrent.duration.FiniteDuration) FindLocalShard(org.opendaylight.controller.cluster.datastore.messages.FindLocalShard) TestKit(akka.testkit.javadsl.TestKit) YangInstanceIdentifier(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier) ActorContext(org.opendaylight.controller.cluster.datastore.utils.ActorContext) Test(org.junit.Test)

Aggregations

FindLocalShard (org.opendaylight.controller.cluster.datastore.messages.FindLocalShard)24 TestKit (akka.testkit.javadsl.TestKit)20 Test (org.junit.Test)20 AbstractShardManagerTest (org.opendaylight.controller.cluster.datastore.AbstractShardManagerTest)12 ActorRef (akka.actor.ActorRef)10 TestActorRef (akka.testkit.TestActorRef)10 LocalShardFound (org.opendaylight.controller.cluster.datastore.messages.LocalShardFound)9 UpdateSchemaContext (org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext)9 Configuration (org.opendaylight.controller.cluster.datastore.config.Configuration)8 ActorContext (org.opendaylight.controller.cluster.datastore.utils.ActorContext)8 YangInstanceIdentifier (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)8 FiniteDuration (scala.concurrent.duration.FiniteDuration)8 AddressFromURIString (akka.actor.AddressFromURIString)6 LocalShardNotFound (org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound)5 ActorInitialized (org.opendaylight.controller.cluster.datastore.messages.ActorInitialized)4 DataChangeScope (org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope)4 ClusteredDOMDataTreeChangeListener (org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener)4 Failure (akka.actor.Status.Failure)3 Shard (org.opendaylight.controller.cluster.datastore.Shard)3 ConfigurationImpl (org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl)3