use of co.cask.cdap.internal.app.runtime.messaging.MultiThreadMessagingContext 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;
}
use of co.cask.cdap.internal.app.runtime.messaging.MultiThreadMessagingContext in project cdap by caskdata.
the class TestBase method initialize.
@BeforeClass
public static void initialize() throws Exception {
if (nestedStartCount++ > 0) {
return;
}
File localDataDir = TMP_FOLDER.newFolder();
cConf = createCConf(localDataDir);
org.apache.hadoop.conf.Configuration hConf = new org.apache.hadoop.conf.Configuration();
hConf.addResource("mapred-site-local.xml");
hConf.reloadConfiguration();
hConf.set(Constants.CFG_LOCAL_DATA_DIR, localDataDir.getAbsolutePath());
hConf.set(Constants.AppFabric.OUTPUT_DIR, cConf.get(Constants.AppFabric.OUTPUT_DIR));
hConf.set("hadoop.tmp.dir", new File(localDataDir, cConf.get(Constants.AppFabric.TEMP_DIR)).getAbsolutePath());
// Windows specific requirements
if (OSDetector.isWindows()) {
File tmpDir = TMP_FOLDER.newFolder();
File binDir = new File(tmpDir, "bin");
Assert.assertTrue(binDir.mkdirs());
copyTempFile("hadoop.dll", tmpDir);
copyTempFile("winutils.exe", binDir);
System.setProperty("hadoop.home.dir", tmpDir.getAbsolutePath());
System.load(new File(tmpDir, "hadoop.dll").getAbsolutePath());
}
Injector injector = Guice.createInjector(createDataFabricModule(), new TransactionExecutorModule(), new DataSetsModules().getStandaloneModules(), new DataSetServiceModules().getInMemoryModules(), new ConfigModule(cConf, hConf), new IOModule(), new LocationRuntimeModule().getInMemoryModules(), new DiscoveryRuntimeModule().getInMemoryModules(), new AppFabricServiceRuntimeModule().getInMemoryModules(), new ServiceStoreModules().getInMemoryModules(), new InMemoryProgramRunnerModule(LocalStreamWriter.class), new SecureStoreModules().getInMemoryModules(), new AbstractModule() {
@Override
protected void configure() {
bind(StreamHandler.class).in(Scopes.SINGLETON);
bind(StreamFetchHandler.class).in(Scopes.SINGLETON);
bind(StreamViewHttpHandler.class).in(Scopes.SINGLETON);
bind(StreamFileJanitorService.class).to(LocalStreamFileJanitorService.class).in(Scopes.SINGLETON);
bind(StreamWriterSizeCollector.class).to(BasicStreamWriterSizeCollector.class).in(Scopes.SINGLETON);
bind(StreamCoordinatorClient.class).to(InMemoryStreamCoordinatorClient.class).in(Scopes.SINGLETON);
bind(MetricsManager.class).toProvider(MetricsManagerProvider.class);
}
}, // todo: do we need handler?
new MetricsHandlerModule(), new MetricsClientRuntimeModule().getInMemoryModules(), new LoggingModules().getInMemoryModules(), new LogReaderRuntimeModules().getInMemoryModules(), new ExploreRuntimeModule().getInMemoryModules(), new ExploreClientModule(), new NotificationFeedServiceRuntimeModule().getInMemoryModules(), new NotificationServiceRuntimeModule().getInMemoryModules(), new NamespaceStoreModule().getStandaloneModules(), new AuthorizationModule(), new AuthorizationEnforcementModule().getInMemoryModules(), new MessagingServerRuntimeModule().getInMemoryModules(), new PreviewHttpModule(), new AbstractModule() {
@Override
@SuppressWarnings("deprecation")
protected void configure() {
install(new FactoryModuleBuilder().implement(ApplicationManager.class, DefaultApplicationManager.class).build(ApplicationManagerFactory.class));
install(new FactoryModuleBuilder().implement(ArtifactManager.class, DefaultArtifactManager.class).build(ArtifactManagerFactory.class));
install(new FactoryModuleBuilder().implement(StreamManager.class, DefaultStreamManager.class).build(StreamManagerFactory.class));
bind(TemporaryFolder.class).toInstance(TMP_FOLDER);
bind(AuthorizationHandler.class).in(Scopes.SINGLETON);
}
});
messagingService = injector.getInstance(MessagingService.class);
if (messagingService instanceof Service) {
((Service) messagingService).startAndWait();
}
txService = injector.getInstance(TransactionManager.class);
txService.startAndWait();
dsOpService = injector.getInstance(DatasetOpExecutor.class);
dsOpService.startAndWait();
datasetService = injector.getInstance(DatasetService.class);
datasetService.startAndWait();
metricsQueryService = injector.getInstance(MetricsQueryService.class);
metricsQueryService.startAndWait();
metricsCollectionService = injector.getInstance(MetricsCollectionService.class);
metricsCollectionService.startAndWait();
programLifecycleService = injector.getInstance(ProgramLifecycleService.class);
programLifecycleService.startAndWait();
programNotificationSubscriberService = injector.getInstance(ProgramNotificationSubscriberService.class);
programNotificationSubscriberService.startAndWait();
scheduler = injector.getInstance(Scheduler.class);
if (scheduler instanceof Service) {
((Service) scheduler).startAndWait();
}
if (scheduler instanceof CoreSchedulerService) {
((CoreSchedulerService) scheduler).waitUntilFunctional(10, TimeUnit.SECONDS);
}
if (cConf.getBoolean(Constants.Explore.EXPLORE_ENABLED)) {
exploreExecutorService = injector.getInstance(ExploreExecutorService.class);
exploreExecutorService.startAndWait();
// wait for explore service to be discoverable
DiscoveryServiceClient discoveryService = injector.getInstance(DiscoveryServiceClient.class);
EndpointStrategy endpointStrategy = new RandomEndpointStrategy(discoveryService.discover(Constants.Service.EXPLORE_HTTP_USER_SERVICE));
Preconditions.checkNotNull(endpointStrategy.pick(5, TimeUnit.SECONDS), "%s service is not up after 5 seconds", Constants.Service.EXPLORE_HTTP_USER_SERVICE);
exploreClient = injector.getInstance(ExploreClient.class);
}
streamCoordinatorClient = injector.getInstance(StreamCoordinatorClient.class);
streamCoordinatorClient.startAndWait();
programScheduler = injector.getInstance(Scheduler.class);
if (programScheduler instanceof Service) {
((Service) programScheduler).startAndWait();
}
testManager = injector.getInstance(UnitTestManager.class);
metricsManager = injector.getInstance(MetricsManager.class);
authorizerInstantiator = injector.getInstance(AuthorizerInstantiator.class);
// This is needed so the logged-in user can successfully create the default namespace
if (cConf.getBoolean(Constants.Security.Authorization.ENABLED)) {
String user = System.getProperty("user.name");
SecurityRequestContext.setUserId(user);
InstanceId instance = new InstanceId(cConf.get(Constants.INSTANCE_NAME));
Principal principal = new Principal(user, Principal.PrincipalType.USER);
authorizerInstantiator.get().grant(Authorizable.fromEntityId(instance), principal, ImmutableSet.of(Action.ADMIN));
authorizerInstantiator.get().grant(Authorizable.fromEntityId(NamespaceId.DEFAULT), principal, ImmutableSet.of(Action.ADMIN));
}
namespaceAdmin = injector.getInstance(NamespaceAdmin.class);
if (firstInit) {
// only create the default namespace on first test. if multiple tests are run in the same JVM,
// then any time after the first time, the default namespace already exists. That is because
// the namespaceAdmin.delete(Id.Namespace.DEFAULT) in finish() only clears the default namespace
// but does not remove it entirely
namespaceAdmin.create(NamespaceMeta.DEFAULT);
}
secureStore = injector.getInstance(SecureStore.class);
secureStoreManager = injector.getInstance(SecureStoreManager.class);
messagingContext = new MultiThreadMessagingContext(messagingService);
firstInit = false;
previewManager = injector.getInstance(PreviewManager.class);
}
use of co.cask.cdap.internal.app.runtime.messaging.MultiThreadMessagingContext in project cdap by caskdata.
the class RuntimeMonitorTest method testRunTimeMonitor.
@Test
public void testRunTimeMonitor() throws Exception {
Map<String, String> topics = new HashMap<>();
topics.put(Constants.AppFabric.PROGRAM_STATUS_RECORD_EVENT_TOPIC, "status");
httpServer.createContext("/v3/runtime/monitor/topics", new HttpHandler() {
public void handle(HttpExchange exchange) throws IOException {
byte[] response = GSON.toJson(topics).getBytes();
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
});
ConnectionConfig connectionConfig = ConnectionConfig.builder().setHostname(address.getHostName()).setPort(1234).setSSLEnabled(false).build();
ClientConfig.Builder clientConfigBuilder = ClientConfig.builder().setDefaultReadTimeout(20000).setConnectionConfig(connectionConfig);
int limit = 2;
MessagingContext messagingContext = new MultiThreadMessagingContext(messagingService);
RuntimeMonitor runtimeMonitor = new RuntimeMonitor(new ProgramRunId("test", "app1", ProgramType.WORKFLOW, "p1", "run1"), cConf, messagingContext.getMessagePublisher(), clientConfigBuilder.build());
Map<String, List<MonitorMessage>> messages = new LinkedHashMap<>();
ArrayList<MonitorMessage> list = new ArrayList<>();
list.add(new MonitorMessage("1", "message1"));
list.add(new MonitorMessage("2", "message2"));
list.add(new MonitorMessage("3", "message3"));
list.add(new MonitorMessage("4", "message4"));
list.add(new MonitorMessage("5", "message5"));
list.add(new MonitorMessage("6", "message6"));
list.add(new MonitorMessage("7", "message7"));
list.add(new MonitorMessage("8", "message8"));
list.add(new MonitorMessage("9", "message9"));
list.add(new MonitorMessage("10", "message10"));
messages.put("status", list);
httpServer.createContext("/v3/runtime/metadata", new HttpHandler() {
int count = 0;
public void handle(HttpExchange exchange) throws IOException {
Map<String, List<MonitorMessage>> toSend = new LinkedHashMap<>();
ArrayList<MonitorMessage> list = new ArrayList<>();
int start = count;
int i = 0;
for (MonitorMessage message : messages.get("status")) {
if (start <= i && i < start + limit) {
list.add(message);
count++;
}
i++;
}
toSend.put("status", list);
byte[] response = GSON.toJson(toSend).getBytes();
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
});
HashSet<String> expected = new LinkedHashSet<>();
expected.add("message1");
expected.add("message2");
expected.add("message3");
expected.add("message4");
expected.add("message5");
expected.add("message6");
expected.add("message7");
expected.add("message8");
expected.add("message9");
expected.add("message10");
HashSet<String> actual = new LinkedHashSet<>();
final String[] messageId = { null };
runtimeMonitor.startAndWait();
Tasks.waitFor(true, new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
MessageFetcher messageFetcher = messagingContext.getMessageFetcher();
try (CloseableIterator<Message> iter = messageFetcher.fetch(NamespaceId.SYSTEM.getNamespace(), cConf.get(Constants.AppFabric.PROGRAM_STATUS_EVENT_TOPIC), 2, messageId[0])) {
while (iter.hasNext()) {
Message message = iter.next();
messageId[0] = message.getId();
actual.add(message.getPayloadAsString());
}
}
return expected.size() == actual.size() && expected.equals(actual);
}
}, 5, TimeUnit.MINUTES);
runtimeMonitor.stopAndWait();
}
Aggregations