Search in sources :

Example 1 with LocalShardFound

use of org.opendaylight.controller.cluster.datastore.messages.LocalShardFound 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 LocalShardFound

use of org.opendaylight.controller.cluster.datastore.messages.LocalShardFound 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 LocalShardFound

use of org.opendaylight.controller.cluster.datastore.messages.LocalShardFound 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 LocalShardFound

use of org.opendaylight.controller.cluster.datastore.messages.LocalShardFound 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 LocalShardFound

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

the class ShardManagerTest method testOnReceiveFindLocalShardWaitForShardInitialized.

@Test
public void testOnReceiveFindLocalShardWaitForShardInitialized() throws Exception {
    LOG.info("testOnReceiveFindLocalShardWaitForShardInitialized starting");
    new TestKit(getSystem()) {

        {
            final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
            shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
            // We're passing waitUntilInitialized = true to FindLocalShard
            // so the response should be
            // delayed until we send ActorInitialized.
            Future<Object> future = Patterns.ask(shardManager, new FindLocalShard(Shard.DEFAULT_NAME, true), new Timeout(5, TimeUnit.SECONDS));
            shardManager.tell(new ActorInitialized(), mockShardActor);
            Object resp = Await.result(future, duration("5 seconds"));
            assertTrue("Expected: LocalShardFound, Actual: " + resp, resp instanceof LocalShardFound);
        }
    };
    LOG.info("testOnReceiveFindLocalShardWaitForShardInitialized starting");
}
Also used : UpdateSchemaContext(org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext) LocalShardFound(org.opendaylight.controller.cluster.datastore.messages.LocalShardFound) ActorRef(akka.actor.ActorRef) TestActorRef(akka.testkit.TestActorRef) Timeout(akka.util.Timeout) FindLocalShard(org.opendaylight.controller.cluster.datastore.messages.FindLocalShard) ActorInitialized(org.opendaylight.controller.cluster.datastore.messages.ActorInitialized) TestKit(akka.testkit.javadsl.TestKit) Test(org.junit.Test) AbstractShardManagerTest(org.opendaylight.controller.cluster.datastore.AbstractShardManagerTest)

Aggregations

LocalShardFound (org.opendaylight.controller.cluster.datastore.messages.LocalShardFound)10 FindLocalShard (org.opendaylight.controller.cluster.datastore.messages.FindLocalShard)9 TestKit (akka.testkit.javadsl.TestKit)6 Test (org.junit.Test)6 Configuration (org.opendaylight.controller.cluster.datastore.config.Configuration)4 ActorContext (org.opendaylight.controller.cluster.datastore.utils.ActorContext)4 YangInstanceIdentifier (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier)4 RegisterDataTreeNotificationListenerReply (org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNotificationListenerReply)3 FiniteDuration (scala.concurrent.duration.FiniteDuration)3 ActorRef (akka.actor.ActorRef)2 TestActorRef (akka.testkit.TestActorRef)2 Timeout (akka.util.Timeout)2 AbstractShardManagerTest (org.opendaylight.controller.cluster.datastore.AbstractShardManagerTest)2 ActorInitialized (org.opendaylight.controller.cluster.datastore.messages.ActorInitialized)2 LocalShardNotFound (org.opendaylight.controller.cluster.datastore.messages.LocalShardNotFound)2 RegisterChangeListener (org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener)2 RegisterDataTreeChangeListener (org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener)2 UpdateSchemaContext (org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext)2 DataChangeScope (org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope)2 ClusteredDOMDataTreeChangeListener (org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener)2