Search in sources :

Example 1 with MessagingContext

use of io.cdap.cdap.api.messaging.MessagingContext in project cdap by caskdata.

the class RuntimeClientServiceTest method testBasicRelay.

@Test
public void testBasicRelay() throws Exception {
    // Send some messages to multiple topics in the client side TMS, they should get replicated to the server side TMS.
    MessagingContext messagingContext = new MultiThreadMessagingContext(clientMessagingService);
    MessagePublisher messagePublisher = messagingContext.getDirectMessagePublisher();
    ProgramStateWriter programStateWriter = new MessagingProgramStateWriter(clientCConf, clientMessagingService);
    for (Map.Entry<String, String> entry : topicConfigs.entrySet()) {
        // the RuntimeClientService will decode it to watch for program termination
        if (entry.getKey().equals(Constants.AppFabric.PROGRAM_STATUS_EVENT_TOPIC)) {
            // Write a non-terminal state to test basic relaying
            programStateWriter.running(PROGRAM_RUN_ID, null);
        } else {
            messagePublisher.publish(NamespaceId.SYSTEM.getNamespace(), entry.getValue(), entry.getKey(), entry.getKey());
        }
    }
    MessagingContext serverMessagingContext = new MultiThreadMessagingContext(messagingService);
    for (Map.Entry<String, String> entry : topicConfigs.entrySet()) {
        if (entry.getKey().equals(Constants.AppFabric.PROGRAM_STATUS_EVENT_TOPIC)) {
            // Extract the program run status from the Notification
            Tasks.waitFor(Collections.singletonList(ProgramRunStatus.RUNNING), () -> fetchMessages(serverMessagingContext, entry.getValue(), 10, null).stream().map(Message::getPayloadAsString).map(s -> GSON.fromJson(s, Notification.class)).map(n -> n.getProperties().get(ProgramOptionConstants.PROGRAM_STATUS)).map(ProgramRunStatus::valueOf).collect(Collectors.toList()), 5, TimeUnit.SECONDS);
        } else {
            Tasks.waitFor(Arrays.asList(entry.getKey(), entry.getKey()), () -> fetchMessages(serverMessagingContext, entry.getValue(), 10, null).stream().map(Message::getPayloadAsString).collect(Collectors.toList()), 5, TimeUnit.SECONDS);
        }
    }
    // Writes a program terminate message to unblock stopping of the client service
    programStateWriter.completed(PROGRAM_RUN_ID);
}
Also used : MessagingServerRuntimeModule(io.cdap.cdap.messaging.guice.MessagingServerRuntimeModule) Arrays(java.util.Arrays) ConfigModule(io.cdap.cdap.common.guice.ConfigModule) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) Notification(io.cdap.cdap.proto.Notification) Spliterators(java.util.Spliterators) TimeoutException(java.util.concurrent.TimeoutException) MessageFetcher(io.cdap.cdap.api.messaging.MessageFetcher) ProgramStateWriter(io.cdap.cdap.app.runtime.ProgramStateWriter) Gson(com.google.gson.Gson) RuntimeServerModule(io.cdap.cdap.app.guice.RuntimeServerModule) After(org.junit.After) Map(java.util.Map) ClassRule(org.junit.ClassRule) NoOpMetricsCollectionService(io.cdap.cdap.common.metrics.NoOpMetricsCollectionService) Tasks(io.cdap.cdap.common.utils.Tasks) MessagingService(io.cdap.cdap.messaging.MessagingService) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) MultiThreadMessagingContext(io.cdap.cdap.messaging.context.MultiThreadMessagingContext) Constants(io.cdap.cdap.common.conf.Constants) MessagingContext(io.cdap.cdap.api.messaging.MessagingContext) ProgramOptionConstants(io.cdap.cdap.internal.app.runtime.ProgramOptionConstants) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) InMemoryDiscoveryService(org.apache.twill.discovery.InMemoryDiscoveryService) LocalLocationModule(io.cdap.cdap.common.guice.LocalLocationModule) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) RemoteAuthenticatorModules(io.cdap.cdap.common.guice.RemoteAuthenticatorModules) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) DiscoveryServiceClient(org.apache.twill.discovery.DiscoveryServiceClient) StreamSupport(java.util.stream.StreamSupport) Nullable(javax.annotation.Nullable) Before(org.junit.Before) DiscoveryService(org.apache.twill.discovery.DiscoveryService) Message(io.cdap.cdap.api.messaging.Message) RunIds(io.cdap.cdap.common.app.RunIds) Test(org.junit.Test) IOException(java.io.IOException) CloseableIterator(io.cdap.cdap.api.dataset.lib.CloseableIterator) TopicNotFoundException(io.cdap.cdap.api.messaging.TopicNotFoundException) Service(com.google.common.util.concurrent.Service) MetricsCollectionService(io.cdap.cdap.api.metrics.MetricsCollectionService) Injector(com.google.inject.Injector) TimeUnit(java.util.concurrent.TimeUnit) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) MessagePublisher(io.cdap.cdap.api.messaging.MessagePublisher) Guice(com.google.inject.Guice) Assert(org.junit.Assert) Collections(java.util.Collections) AuthenticationContextModules(io.cdap.cdap.security.auth.context.AuthenticationContextModules) TemporaryFolder(org.junit.rules.TemporaryFolder) AbstractModule(com.google.inject.AbstractModule) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) Message(io.cdap.cdap.api.messaging.Message) ProgramStateWriter(io.cdap.cdap.app.runtime.ProgramStateWriter) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) MessagePublisher(io.cdap.cdap.api.messaging.MessagePublisher) MultiThreadMessagingContext(io.cdap.cdap.messaging.context.MultiThreadMessagingContext) MessagingContext(io.cdap.cdap.api.messaging.MessagingContext) MultiThreadMessagingContext(io.cdap.cdap.messaging.context.MultiThreadMessagingContext) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) Map(java.util.Map) Notification(io.cdap.cdap.proto.Notification) Test(org.junit.Test)

Example 2 with MessagingContext

use of io.cdap.cdap.api.messaging.MessagingContext in project cdap by caskdata.

the class RuntimeClientServiceTest method testProgramTerminate.

/**
 * Test for {@link RuntimeClientService} that will terminate itself when seeing program completed message.
 */
@Test
public void testProgramTerminate() throws Exception {
    MessagingContext messagingContext = new MultiThreadMessagingContext(clientMessagingService);
    MessagePublisher messagePublisher = messagingContext.getDirectMessagePublisher();
    ProgramStateWriter programStateWriter = new MessagingProgramStateWriter(clientCConf, clientMessagingService);
    // Send a terminate program state first, wait for the service sees the state change,
    // then publish messages to other topics.
    programStateWriter.completed(PROGRAM_RUN_ID);
    Tasks.waitFor(true, () -> runtimeClientService.getProgramFinishTime() >= 0, 2, TimeUnit.SECONDS);
    for (Map.Entry<String, String> entry : topicConfigs.entrySet()) {
        // the RuntimeClientService will decode it to watch for program termination
        if (!entry.getKey().equals(Constants.AppFabric.PROGRAM_STATUS_EVENT_TOPIC)) {
            List<String> payloads = Arrays.asList(entry.getKey(), entry.getKey(), entry.getKey());
            messagePublisher.publish(NamespaceId.SYSTEM.getNamespace(), entry.getValue(), StandardCharsets.UTF_8, payloads.iterator());
        }
    }
    // The client service should get stopped by itself.
    Tasks.waitFor(Service.State.TERMINATED, () -> runtimeClientService.state(), clientCConf.getLong(Constants.RuntimeMonitor.GRACEFUL_SHUTDOWN_MS) + 2000, TimeUnit.MILLISECONDS);
    // All messages should be sent after the runtime client service stopped
    MessagingContext serverMessagingContext = new MultiThreadMessagingContext(messagingService);
    for (Map.Entry<String, String> entry : topicConfigs.entrySet()) {
        if (entry.getKey().equals(Constants.AppFabric.PROGRAM_STATUS_EVENT_TOPIC)) {
            // Extract the program run status from the Notification
            Tasks.waitFor(Collections.singletonList(ProgramRunStatus.COMPLETED), () -> fetchMessages(serverMessagingContext, entry.getValue(), 10, null).stream().map(Message::getPayloadAsString).map(s -> GSON.fromJson(s, Notification.class)).map(n -> n.getProperties().get(ProgramOptionConstants.PROGRAM_STATUS)).map(ProgramRunStatus::valueOf).collect(Collectors.toList()), 5, TimeUnit.SECONDS);
        } else {
            Tasks.waitFor(Arrays.asList(entry.getKey(), entry.getKey(), entry.getKey()), () -> fetchMessages(serverMessagingContext, entry.getValue(), 10, null).stream().map(Message::getPayloadAsString).collect(Collectors.toList()), 5, TimeUnit.SECONDS);
        }
    }
}
Also used : MessagingServerRuntimeModule(io.cdap.cdap.messaging.guice.MessagingServerRuntimeModule) Arrays(java.util.Arrays) ConfigModule(io.cdap.cdap.common.guice.ConfigModule) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) Notification(io.cdap.cdap.proto.Notification) Spliterators(java.util.Spliterators) TimeoutException(java.util.concurrent.TimeoutException) MessageFetcher(io.cdap.cdap.api.messaging.MessageFetcher) ProgramStateWriter(io.cdap.cdap.app.runtime.ProgramStateWriter) Gson(com.google.gson.Gson) RuntimeServerModule(io.cdap.cdap.app.guice.RuntimeServerModule) After(org.junit.After) Map(java.util.Map) ClassRule(org.junit.ClassRule) NoOpMetricsCollectionService(io.cdap.cdap.common.metrics.NoOpMetricsCollectionService) Tasks(io.cdap.cdap.common.utils.Tasks) MessagingService(io.cdap.cdap.messaging.MessagingService) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) MultiThreadMessagingContext(io.cdap.cdap.messaging.context.MultiThreadMessagingContext) Constants(io.cdap.cdap.common.conf.Constants) MessagingContext(io.cdap.cdap.api.messaging.MessagingContext) ProgramOptionConstants(io.cdap.cdap.internal.app.runtime.ProgramOptionConstants) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) InMemoryDiscoveryService(org.apache.twill.discovery.InMemoryDiscoveryService) LocalLocationModule(io.cdap.cdap.common.guice.LocalLocationModule) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) RemoteAuthenticatorModules(io.cdap.cdap.common.guice.RemoteAuthenticatorModules) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) DiscoveryServiceClient(org.apache.twill.discovery.DiscoveryServiceClient) StreamSupport(java.util.stream.StreamSupport) Nullable(javax.annotation.Nullable) Before(org.junit.Before) DiscoveryService(org.apache.twill.discovery.DiscoveryService) Message(io.cdap.cdap.api.messaging.Message) RunIds(io.cdap.cdap.common.app.RunIds) Test(org.junit.Test) IOException(java.io.IOException) CloseableIterator(io.cdap.cdap.api.dataset.lib.CloseableIterator) TopicNotFoundException(io.cdap.cdap.api.messaging.TopicNotFoundException) Service(com.google.common.util.concurrent.Service) MetricsCollectionService(io.cdap.cdap.api.metrics.MetricsCollectionService) Injector(com.google.inject.Injector) TimeUnit(java.util.concurrent.TimeUnit) CConfiguration(io.cdap.cdap.common.conf.CConfiguration) MessagePublisher(io.cdap.cdap.api.messaging.MessagePublisher) Guice(com.google.inject.Guice) Assert(org.junit.Assert) Collections(java.util.Collections) AuthenticationContextModules(io.cdap.cdap.security.auth.context.AuthenticationContextModules) TemporaryFolder(org.junit.rules.TemporaryFolder) AbstractModule(com.google.inject.AbstractModule) Message(io.cdap.cdap.api.messaging.Message) MessagePublisher(io.cdap.cdap.api.messaging.MessagePublisher) MultiThreadMessagingContext(io.cdap.cdap.messaging.context.MultiThreadMessagingContext) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) Notification(io.cdap.cdap.proto.Notification) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) ProgramStateWriter(io.cdap.cdap.app.runtime.ProgramStateWriter) MessagingProgramStateWriter(io.cdap.cdap.internal.app.program.MessagingProgramStateWriter) MultiThreadMessagingContext(io.cdap.cdap.messaging.context.MultiThreadMessagingContext) MessagingContext(io.cdap.cdap.api.messaging.MessagingContext) Map(java.util.Map) Test(org.junit.Test)

Example 3 with MessagingContext

use of io.cdap.cdap.api.messaging.MessagingContext in project cdap by caskdata.

the class MapReduceRunnerTestBase method getDataNotifications.

/**
 * Returns a list of {@link Notification} object fetched from the data event topic in TMS that was published
 * starting from the given time.
 */
protected List<Notification> getDataNotifications(long startTime) throws Exception {
    // Get data notifications from TMS
    List<Notification> notifications = new ArrayList<>();
    MessagingContext messagingContext = new MultiThreadMessagingContext(injector.getInstance(MessagingService.class));
    try (CloseableIterator<Message> messages = messagingContext.getMessageFetcher().fetch(NamespaceId.SYSTEM.getNamespace(), injector.getInstance(CConfiguration.class).get(Constants.Dataset.DATA_EVENT_TOPIC), 10, startTime)) {
        while (messages.hasNext()) {
            notifications.add(GSON.fromJson(new String(messages.next().getPayload(), StandardCharsets.UTF_8), Notification.class));
        }
    }
    return notifications;
}
Also used : Message(io.cdap.cdap.api.messaging.Message) ArrayList(java.util.ArrayList) MultiThreadMessagingContext(io.cdap.cdap.messaging.context.MultiThreadMessagingContext) MessagingContext(io.cdap.cdap.api.messaging.MessagingContext) MultiThreadMessagingContext(io.cdap.cdap.messaging.context.MultiThreadMessagingContext) Notification(io.cdap.cdap.proto.Notification) MessagingService(io.cdap.cdap.messaging.MessagingService)

Example 4 with MessagingContext

use of io.cdap.cdap.api.messaging.MessagingContext in project cdap by caskdata.

the class BasicMapReduceTaskContext method getMessagingContext.

@Override
protected MessagingContext getMessagingContext() {
    // Override to have transactional publisher use "store" instead of "payload"
    // since a task is executed with long transaction.
    // The actual publish will be done in the MR driver.
    final MessagingContext context = super.getMessagingContext();
    // TODO: CDAP-7807 Make it available for any topic
    final TopicId allowedTopic = NamespaceId.SYSTEM.topic(cConf.get(Constants.Dataset.DATA_EVENT_TOPIC));
    return new MessagingContext() {

        @Override
        public MessagePublisher getMessagePublisher() {
            return new AbstractMessagePublisher() {

                @Override
                protected void publish(TopicId topicId, Iterator<byte[]> payloads) throws IOException, TopicNotFoundException, UnauthorizedException {
                    if (!allowedTopic.equals(topicId)) {
                        throw new UnsupportedOperationException("Publish to topic '" + topicId.getTopic() + "' is not supported");
                    }
                    // If there is transaction, use storePayload. Otherwise publish without transaction
                    if (transaction == null) {
                        getMessagingService().publish(StoreRequestBuilder.of(topicId).addPayloads(payloads).build());
                    } else {
                        getMessagingService().storePayload(StoreRequestBuilder.of(topicId).setTransaction(transaction.getWritePointer()).addPayloads(payloads).build());
                    }
                }
            };
        }

        @Override
        public MessagePublisher getDirectMessagePublisher() {
            return context.getDirectMessagePublisher();
        }

        @Override
        public MessageFetcher getMessageFetcher() {
            return context.getMessageFetcher();
        }
    };
}
Also used : Iterator(java.util.Iterator) MessagingContext(io.cdap.cdap.api.messaging.MessagingContext) TopicId(io.cdap.cdap.proto.id.TopicId) AbstractMessagePublisher(io.cdap.cdap.messaging.context.AbstractMessagePublisher)

Example 5 with MessagingContext

use of io.cdap.cdap.api.messaging.MessagingContext in project cdap by caskdata.

the class MessagingAppTestRun method testWithWorker.

@Test
public void testWithWorker() throws Exception {
    ApplicationManager appManager = deployWithArtifact(NAMESPACE, MessagingApp.class, artifactJar);
    final WorkerManager workerManager = appManager.getWorkerManager(MessagingApp.MessagingWorker.class.getSimpleName()).start();
    MessagingContext messagingContext = getMessagingContext();
    final MessagingAdmin messagingAdmin = getMessagingAdmin(NAMESPACE);
    // Wait for the worker to create the topic
    Tasks.waitFor(true, new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            try {
                messagingAdmin.getTopicProperties(MessagingApp.TOPIC);
                return true;
            } catch (TopicNotFoundException e) {
                return false;
            }
        }
    }, 5, TimeUnit.SECONDS, 100, TimeUnit.MILLISECONDS);
    // Publish a message
    String message = "message";
    MessagePublisher messagePublisher = messagingContext.getMessagePublisher();
    messagePublisher.publish(NAMESPACE.getNamespace(), MessagingApp.TOPIC, message);
    // The worker will publish back a message with payload as concat(message, message)
    final MessageFetcher messageFetcher = messagingContext.getMessageFetcher();
    Tasks.waitFor(message + message, new Callable<String>() {

        @Override
        public String call() throws Exception {
            try (CloseableIterator<Message> iterator = messageFetcher.fetch(NAMESPACE.getNamespace(), MessagingApp.TOPIC, Integer.MAX_VALUE, 0L)) {
                Message message = Iterators.getLast(iterator, null);
                return message == null ? null : message.getPayloadAsString();
            }
        }
    }, 5, TimeUnit.SECONDS, 100, TimeUnit.MILLISECONDS);
    // Publish concat(message + message) to the app
    messagePublisher.publish(NAMESPACE.getNamespace(), MessagingApp.TOPIC, message + message);
    // timeout.
    try {
        Tasks.waitFor(message + message + message + message, new Callable<String>() {

            @Override
            public String call() throws Exception {
                try (CloseableIterator<Message> iterator = messageFetcher.fetch(NAMESPACE.getNamespace(), MessagingApp.TOPIC, Integer.MAX_VALUE, 0L)) {
                    Message message = Iterators.getLast(iterator, null);
                    return message == null ? null : message.getPayloadAsString();
                }
            }
        }, 2, TimeUnit.SECONDS, 100, TimeUnit.MILLISECONDS);
        Assert.fail("Expected timeout exception");
    } catch (TimeoutException e) {
    // expected
    }
    // Now publish a message to the control topic, to unblock the transaction block.
    messagePublisher.publish(NAMESPACE.getNamespace(), MessagingApp.CONTROL_TOPIC, message);
    // Should expect a new message as concat(message, message, message, message)
    Tasks.waitFor(message + message + message + message, new Callable<String>() {

        @Override
        public String call() throws Exception {
            try (CloseableIterator<Message> iterator = messageFetcher.fetch(NAMESPACE.getNamespace(), MessagingApp.TOPIC, Integer.MAX_VALUE, 0L)) {
                Message message = Iterators.getLast(iterator, null);
                return message == null ? null : message.getPayloadAsString();
            }
        }
    }, 5, TimeUnit.SECONDS, 100, TimeUnit.MILLISECONDS);
    // Wait for the worker to finish and verify that it completes successfully.
    workerManager.waitForRun(ProgramRunStatus.COMPLETED, 5, TimeUnit.SECONDS);
}
Also used : ApplicationManager(io.cdap.cdap.test.ApplicationManager) MessageFetcher(io.cdap.cdap.api.messaging.MessageFetcher) CloseableIterator(io.cdap.cdap.api.dataset.lib.CloseableIterator) Message(io.cdap.cdap.api.messaging.Message) TopicNotFoundException(io.cdap.cdap.api.messaging.TopicNotFoundException) MessagePublisher(io.cdap.cdap.api.messaging.MessagePublisher) TimeoutException(java.util.concurrent.TimeoutException) TopicNotFoundException(io.cdap.cdap.api.messaging.TopicNotFoundException) WorkerManager(io.cdap.cdap.test.WorkerManager) MessagingAdmin(io.cdap.cdap.api.messaging.MessagingAdmin) MessagingContext(io.cdap.cdap.api.messaging.MessagingContext) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Aggregations

MessagingContext (io.cdap.cdap.api.messaging.MessagingContext)6 Message (io.cdap.cdap.api.messaging.Message)5 MultiThreadMessagingContext (io.cdap.cdap.messaging.context.MultiThreadMessagingContext)4 CloseableIterator (io.cdap.cdap.api.dataset.lib.CloseableIterator)3 MessageFetcher (io.cdap.cdap.api.messaging.MessageFetcher)3 MessagePublisher (io.cdap.cdap.api.messaging.MessagePublisher)3 TopicNotFoundException (io.cdap.cdap.api.messaging.TopicNotFoundException)3 MessagingService (io.cdap.cdap.messaging.MessagingService)3 Notification (io.cdap.cdap.proto.Notification)3 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)2 Service (com.google.common.util.concurrent.Service)2 Gson (com.google.gson.Gson)2 AbstractModule (com.google.inject.AbstractModule)2 Guice (com.google.inject.Guice)2 Injector (com.google.inject.Injector)2 MetricsCollectionService (io.cdap.cdap.api.metrics.MetricsCollectionService)2 RuntimeServerModule (io.cdap.cdap.app.guice.RuntimeServerModule)2 ProgramStateWriter (io.cdap.cdap.app.runtime.ProgramStateWriter)2 RunIds (io.cdap.cdap.common.app.RunIds)2 CConfiguration (io.cdap.cdap.common.conf.CConfiguration)2