Search in sources :

Example 1 with NoopMetricsContext

use of co.cask.cdap.api.metrics.NoopMetricsContext in project cdap by caskdata.

the class MessagingMetricsProcessorServiceTest method persistMetricsTests.

@Test
public void persistMetricsTests() throws Exception {
    injector.getInstance(TransactionManager.class).startAndWait();
    injector.getInstance(DatasetOpExecutor.class).startAndWait();
    injector.getInstance(DatasetService.class).startAndWait();
    Set<Integer> partitions = new HashSet<>();
    for (int i = 0; i < PARTITION_SIZE; i++) {
        partitions.add(i);
    }
    long startTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
    for (int iteration = 0; iteration < 50; iteration++) {
        // will fetch metrics concurrently.
        for (int i = 0; i < 50; i++) {
            // TOPIC_PREFIX + (i % PARTITION_SIZE) decides which topic the metric is published to
            publishMessagingMetrics(i, startTime, METRICS_CONTEXT, expected, "", MetricType.COUNTER);
        }
        for (int i = 50; i < 100; i++) {
            // TOPIC_PREFIX + (i % PARTITION_SIZE) decides which topic the metric is published to
            publishMessagingMetrics(i, startTime, METRICS_CONTEXT, expected, "", MetricType.GAUGE);
        }
        final MockMetricStore metricStore = new MockMetricStore();
        // Create new MessagingMetricsProcessorService instance every time because the same instance cannot be started
        // again after it's stopped
        MessagingMetricsProcessorService messagingMetricsProcessorService = new MessagingMetricsProcessorService(injector.getInstance(MetricDatasetFactory.class), TOPIC_PREFIX, messagingService, injector.getInstance(SchemaGenerator.class), injector.getInstance(DatumReaderFactory.class), metricStore, 1000L, 5, partitions, new NoopMetricsContext(), 50, 0, injector.getInstance(DatasetFramework.class), cConf, true);
        messagingMetricsProcessorService.startAndWait();
        // Wait for the 1 aggregated counter metric (with value 50) and 50 gauge metrics to be stored in the metricStore
        Tasks.waitFor(51, new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                return metricStore.getAllMetrics().size();
            }
        }, 15, TimeUnit.SECONDS, 1, TimeUnit.SECONDS);
        assertMetricsResult(expected, metricStore.getAllMetrics());
        // validate metrics processor metrics
        // 50 counter and 50 gauge metrics are emitted in each iteration above
        Assert.assertEquals(100, metricStore.getMetricsProcessedByMetricsProcessor());
        Assert.assertTrue(metricStore.isMetricsProcessorDelayEmitted());
        // Clear metricStore and expected results for the next iteration
        metricStore.deleteAll();
        expected.clear();
        // Stop messagingMetricsProcessorService
        messagingMetricsProcessorService.stopAndWait();
    }
}
Also used : DatumReaderFactory(co.cask.cdap.internal.io.DatumReaderFactory) SchemaGenerator(co.cask.cdap.internal.io.SchemaGenerator) DatasetService(co.cask.cdap.data2.datafabric.dataset.service.DatasetService) DatasetOpExecutor(co.cask.cdap.data2.datafabric.dataset.service.executor.DatasetOpExecutor) NoopMetricsContext(co.cask.cdap.api.metrics.NoopMetricsContext) MetricDatasetFactory(co.cask.cdap.metrics.store.MetricDatasetFactory) DatasetFramework(co.cask.cdap.data2.dataset2.DatasetFramework) TransactionManager(org.apache.tephra.TransactionManager) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 2 with NoopMetricsContext

use of co.cask.cdap.api.metrics.NoopMetricsContext in project cdap by caskdata.

the class HttpHandlerGeneratorTest method testHttpHeaders.

@Test
public void testHttpHeaders() throws Exception {
    HttpHandlerFactory factory = new HttpHandlerFactory("/prefix", TransactionControl.IMPLICIT);
    HttpHandler httpHandler = factory.createHttpHandler(TypeToken.of(MyHttpHandler.class), new AbstractDelegatorContext<MyHttpHandler>() {

        @Override
        protected MyHttpHandler createHandler() {
            return new MyHttpHandler();
        }
    }, new NoopMetricsContext());
    NettyHttpService service = NettyHttpService.builder("test-headers").setHttpHandlers(httpHandler).build();
    service.start();
    try {
        InetSocketAddress bindAddress = service.getBindAddress();
        // Make a request with headers that the response should carry first value for each header name
        HttpURLConnection urlConn = (HttpURLConnection) new URL(String.format("http://%s:%d/prefix/p2/echo/firstHeaders", bindAddress.getHostName(), bindAddress.getPort())).openConnection();
        urlConn.addRequestProperty("k1", "v1");
        urlConn.addRequestProperty("k1", "v2");
        urlConn.addRequestProperty("k2", "v2");
        Assert.assertEquals(200, urlConn.getResponseCode());
        Map<String, List<String>> headers = urlConn.getHeaderFields();
        Assert.assertEquals(ImmutableList.of("v1"), headers.get("k1"));
        Assert.assertEquals(ImmutableList.of("v2"), headers.get("k2"));
        // Make a request with headers that the response should carry all values for each header name
        urlConn = (HttpURLConnection) new URL(String.format("http://%s:%d/prefix/p2/echo/allHeaders", bindAddress.getHostName(), bindAddress.getPort())).openConnection();
        urlConn.addRequestProperty("k1", "v1");
        urlConn.addRequestProperty("k1", "v2");
        urlConn.addRequestProperty("k1", "v3");
        urlConn.addRequestProperty("k2", "v2");
        Assert.assertEquals(200, urlConn.getResponseCode());
        headers = urlConn.getHeaderFields();
        // URLConnection always reverse the ordering of the header values.
        Assert.assertEquals(ImmutableList.of("v3", "v2", "v1"), headers.get("k1"));
        Assert.assertEquals(ImmutableList.of("v2"), headers.get("k2"));
    } finally {
        service.stop();
    }
}
Also used : HttpHandler(co.cask.http.HttpHandler) InetSocketAddress(java.net.InetSocketAddress) NoopMetricsContext(co.cask.cdap.api.metrics.NoopMetricsContext) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) NettyHttpService(co.cask.http.NettyHttpService) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) Test(org.junit.Test)

Example 3 with NoopMetricsContext

use of co.cask.cdap.api.metrics.NoopMetricsContext in project cdap by caskdata.

the class MetricsProcessorServiceTest method testMetricsProcessor.

@Test
public void testMetricsProcessor() throws Exception {
    injector.getInstance(TransactionManager.class).startAndWait();
    injector.getInstance(DatasetOpExecutor.class).startAndWait();
    injector.getInstance(DatasetService.class).startAndWait();
    final MetricStore metricStore = injector.getInstance(MetricStore.class);
    Set<Integer> partitions = new HashSet<>();
    for (int i = 0; i < PARTITION_SIZE; i++) {
        partitions.add(i);
    }
    // Start KafkaMetricsProcessorService after metrics are published to Kafka
    // Intentionally set queue size to a small value, so that MessagingMetricsProcessorService
    // internally can persist metrics when more messages are to be fetched
    MessagingMetricsProcessorService messagingMetricsProcessorService = new MessagingMetricsProcessorService(injector.getInstance(MetricDatasetFactory.class), TOPIC_PREFIX, messagingService, injector.getInstance(SchemaGenerator.class), injector.getInstance(DatumReaderFactory.class), metricStore, 1000L, 5, partitions, new NoopMetricsContext(), 50, 0, injector.getInstance(DatasetFramework.class), cConf, true);
    messagingMetricsProcessorService.startAndWait();
    long startTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
    // Publish metrics with messaging service and record expected metrics
    for (int i = 10; i < 20; i++) {
        publishMessagingMetrics(i, startTime, METRICS_CONTEXT, expected, SYSTEM_METRIC_PREFIX, MetricType.COUNTER);
    }
    Thread.sleep(500);
    // Stop and restart messagingMetricsProcessorService
    messagingMetricsProcessorService.stopAndWait();
    // Intentionally set queue size to a large value, so that MessagingMetricsProcessorService
    // internally only persists metrics during terminating.
    messagingMetricsProcessorService = new MessagingMetricsProcessorService(injector.getInstance(MetricDatasetFactory.class), TOPIC_PREFIX, messagingService, injector.getInstance(SchemaGenerator.class), injector.getInstance(DatumReaderFactory.class), metricStore, 500L, 100, partitions, new NoopMetricsContext(), 50, 0, injector.getInstance(DatasetFramework.class), cConf, true);
    messagingMetricsProcessorService.startAndWait();
    // Publish metrics after MessagingMetricsProcessorService restarts and record expected metrics
    for (int i = 20; i < 30; i++) {
        publishMessagingMetrics(i, startTime, METRICS_CONTEXT, expected, SYSTEM_METRIC_PREFIX, MetricType.GAUGE);
    }
    final List<String> missingMetricNames = new ArrayList<>();
    // are retrieved when timeout occurs, print out the missing metrics
    try {
        Tasks.waitFor(true, new Callable<Boolean>() {

            @Override
            public Boolean call() throws Exception {
                return canQueryAllMetrics(metricStore, METRICS_CONTEXT, expected, missingMetricNames);
            }
        }, 10000, TimeUnit.MILLISECONDS, "Failed to get all metrics");
    } catch (TimeoutException e) {
        Assert.fail(String.format("Metrics: [%s] cannot be found in the metrics store.", Joiner.on(", ").join(missingMetricNames)));
    }
    // Query metrics from the metricStore and compare them with the expected ones
    assertMetricsResult(metricStore, METRICS_CONTEXT, expected);
    // Query for the 5 counter metrics published with messaging between time 5 - 14
    Collection<MetricTimeSeries> queryResult = metricStore.query(new MetricDataQuery(5, 14, 1, Integer.MAX_VALUE, ImmutableMap.of(SYSTEM_METRIC_PREFIX + COUNTER_METRIC_NAME, AggregationFunction.SUM), METRICS_CONTEXT, ImmutableList.<String>of(), null));
    MetricTimeSeries timeSeries = Iterables.getOnlyElement(queryResult);
    Assert.assertEquals(5, timeSeries.getTimeValues().size());
    for (TimeValue timeValue : timeSeries.getTimeValues()) {
        Assert.assertEquals(1L, timeValue.getValue());
    }
    // Stop services and servers
    messagingMetricsProcessorService.stopAndWait();
    // Delete all metrics
    metricStore.deleteAll();
}
Also used : MetricStore(co.cask.cdap.api.metrics.MetricStore) DatumReaderFactory(co.cask.cdap.internal.io.DatumReaderFactory) ArrayList(java.util.ArrayList) MetricTimeSeries(co.cask.cdap.api.metrics.MetricTimeSeries) DatasetService(co.cask.cdap.data2.datafabric.dataset.service.DatasetService) NoopMetricsContext(co.cask.cdap.api.metrics.NoopMetricsContext) MetricDatasetFactory(co.cask.cdap.metrics.store.MetricDatasetFactory) DatasetFramework(co.cask.cdap.data2.dataset2.DatasetFramework) TimeValue(co.cask.cdap.api.dataset.lib.cube.TimeValue) HashSet(java.util.HashSet) TimeoutException(java.util.concurrent.TimeoutException) SchemaGenerator(co.cask.cdap.internal.io.SchemaGenerator) DatasetOpExecutor(co.cask.cdap.data2.datafabric.dataset.service.executor.DatasetOpExecutor) TimeoutException(java.util.concurrent.TimeoutException) TransactionManager(org.apache.tephra.TransactionManager) MetricDataQuery(co.cask.cdap.api.metrics.MetricDataQuery) Test(org.junit.Test)

Example 4 with NoopMetricsContext

use of co.cask.cdap.api.metrics.NoopMetricsContext in project cdap by caskdata.

the class AbstractContext method createProgramMetrics.

/**
 * Creates a {@link MetricsContext} for metrics emission of the program represented by this context.
 *
 * @param programRunId the {@link ProgramRunId} of the current execution
 * @param metricsService the underlying service for metrics publishing; or {@code null} to suppress metrics publishing
 * @param metricsTags a set of extra tags to be used for creating the {@link MetricsContext}
 * @return a {@link MetricsContext} for emitting metrics for the current program context.
 */
private MetricsContext createProgramMetrics(ProgramRunId programRunId, @Nullable MetricsCollectionService metricsService, Map<String, String> metricsTags) {
    Map<String, String> tags = Maps.newHashMap(metricsTags);
    tags.put(Constants.Metrics.Tag.NAMESPACE, programRunId.getNamespace());
    tags.put(Constants.Metrics.Tag.APP, programRunId.getApplication());
    tags.put(ProgramTypeMetricTag.getTagName(programRunId.getType()), programRunId.getProgram());
    tags.put(Constants.Metrics.Tag.RUN_ID, programRunId.getRun());
    return metricsService == null ? new NoopMetricsContext(tags) : metricsService.getContext(tags);
}
Also used : NoopMetricsContext(co.cask.cdap.api.metrics.NoopMetricsContext)

Example 5 with NoopMetricsContext

use of co.cask.cdap.api.metrics.NoopMetricsContext in project cdap by caskdata.

the class HttpHandlerFactory method validateHttpHandler.

/**
 * Validates the given set of user service handlers.
 *
 * @param handlers set of service handlers to validate.
 * @param <T> type of the handler
 * @throws IllegalArgumentException if any of the service handler is not valid
 */
public <T> void validateHttpHandler(Iterable<T> handlers) {
    List<HttpHandler> httpHandlers = new ArrayList<>();
    NoopMetricsContext metricsContext = new NoopMetricsContext();
    for (T handler : handlers) {
        try {
            @SuppressWarnings("unchecked") TypeToken<T> type = (TypeToken<T>) TypeToken.of(handler.getClass());
            httpHandlers.add(createHttpHandler(type, new VerificationDelegateContext<>(handler), metricsContext));
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid http handler class " + handler.getClass().getName());
        }
    }
    try {
        // Constructs a NettyHttpService, to verify that the handlers passed in by the user are valid.
        NettyHttpService.builder("service-configurer").setHttpHandlers(httpHandlers).build();
    } catch (Exception e) {
        throw new IllegalArgumentException("Invalid http handler", e);
    }
}
Also used : HttpHandler(co.cask.http.HttpHandler) TypeToken(com.google.common.reflect.TypeToken) ArrayList(java.util.ArrayList) NoopMetricsContext(co.cask.cdap.api.metrics.NoopMetricsContext)

Aggregations

NoopMetricsContext (co.cask.cdap.api.metrics.NoopMetricsContext)8 Test (org.junit.Test)6 HttpHandler (co.cask.http.HttpHandler)5 NettyHttpService (co.cask.http.NettyHttpService)4 InetSocketAddress (java.net.InetSocketAddress)4 HttpURLConnection (java.net.HttpURLConnection)3 URL (java.net.URL)3 ArrayList (java.util.ArrayList)3 DatasetService (co.cask.cdap.data2.datafabric.dataset.service.DatasetService)2 DatasetOpExecutor (co.cask.cdap.data2.datafabric.dataset.service.executor.DatasetOpExecutor)2 DatasetFramework (co.cask.cdap.data2.dataset2.DatasetFramework)2 DatumReaderFactory (co.cask.cdap.internal.io.DatumReaderFactory)2 SchemaGenerator (co.cask.cdap.internal.io.SchemaGenerator)2 MetricDatasetFactory (co.cask.cdap.metrics.store.MetricDatasetFactory)2 File (java.io.File)2 HashSet (java.util.HashSet)2 TransactionManager (org.apache.tephra.TransactionManager)2 TimeValue (co.cask.cdap.api.dataset.lib.cube.TimeValue)1 MetricDataQuery (co.cask.cdap.api.metrics.MetricDataQuery)1 MetricStore (co.cask.cdap.api.metrics.MetricStore)1