Search in sources :

Example 1 with HandlerKey

use of com.wavefront.agent.handlers.HandlerKey in project java by wavefrontHQ.

the class HttpEndToEndTest method testEndToEndEvents.

@Test
public void testEndToEndEvents() throws Exception {
    AtomicInteger successfulSteps = new AtomicInteger(0);
    AtomicInteger testCounter = new AtomicInteger(0);
    long time = Clock.now() / 1000;
    proxyPort = findAvailablePort(2898);
    String buffer = File.createTempFile("proxyTestBuffer", null).getPath();
    proxy = new PushAgent();
    proxy.proxyConfig.server = "http://localhost:" + backendPort + "/api/";
    proxy.proxyConfig.flushThreads = 1;
    proxy.proxyConfig.flushThreadsEvents = 1;
    proxy.proxyConfig.pushListenerPorts = String.valueOf(proxyPort);
    proxy.proxyConfig.pushFlushInterval = 10000;
    proxy.proxyConfig.pushRateLimitEvents = 100;
    proxy.proxyConfig.bufferFile = buffer;
    proxy.start(new String[] {});
    waitUntilListenerIsOnline(proxyPort);
    if (!(proxy.senderTaskFactory instanceof SenderTaskFactoryImpl))
        fail();
    if (!(proxy.queueingFactory instanceof QueueingFactoryImpl))
        fail();
    String payloadEvents = "@Event " + time + " \"Event name for testing\" host=host1 host=host2 tag=tag1 " + "severity=INFO multi=bar multi=baz\n" + "@Event " + time + " \"Another test event\" host=host3";
    String expectedEvent1 = "{\"name\":\"Event name for testing\",\"startTime\":" + (time * 1000) + ",\"endTime\":" + (time * 1000 + 1) + ",\"annotations\":{\"severity\":\"INFO\"}," + "\"dimensions\":{\"multi\":[\"bar\",\"baz\"]},\"hosts\":[\"host1\",\"host2\"]," + "\"tags\":[\"tag1\"]}";
    String expectedEvent2 = "{\"name\":\"Another test event\",\"startTime\":" + (time * 1000) + ",\"endTime\":" + (time * 1000 + 1) + ",\"annotations\":{},\"dimensions\":null," + "\"hosts\":[\"host3\"],\"tags\":null}";
    server.update(req -> {
        String content = req.content().toString(CharsetUtil.UTF_8);
        URI uri;
        try {
            uri = new URI(req.uri());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String path = uri.getPath();
        logger.fine("Content received: " + content);
        assertEquals(HttpMethod.POST, req.method());
        assertEquals("/api/v2/wfproxy/event", path);
        switch(testCounter.incrementAndGet()) {
            case 1:
                assertEquals("[" + expectedEvent1 + "," + expectedEvent2 + "]", content);
                successfulSteps.incrementAndGet();
                return makeResponse(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, "");
            case 2:
                assertEquals("[" + expectedEvent1 + "]", content);
                successfulSteps.incrementAndGet();
                return makeResponse(HttpResponseStatus.OK, "");
            case 3:
                assertEquals("[" + expectedEvent2 + "]", content);
                successfulSteps.incrementAndGet();
                return makeResponse(HttpResponseStatus.OK, "");
            case 4:
                assertEquals("[" + expectedEvent1 + "," + expectedEvent2 + "]", content);
                successfulSteps.incrementAndGet();
                return makeResponse(HttpResponseStatus.valueOf(407), "");
            case 5:
                assertEquals("[" + expectedEvent1 + "," + expectedEvent2 + "]", content);
                successfulSteps.incrementAndGet();
                return makeResponse(HttpResponseStatus.INTERNAL_SERVER_ERROR, "");
            case 6:
                assertEquals("[" + expectedEvent1 + "," + expectedEvent2 + "]", content);
                successfulSteps.incrementAndGet();
                return makeResponse(HttpResponseStatus.OK, "");
        }
        logger.warning("Too many requests");
        // this will force the assert to fail
        successfulSteps.incrementAndGet();
        return makeResponse(HttpResponseStatus.OK, "");
    });
    gzippedHttpPost("http://localhost:" + proxyPort + "/", payloadEvents);
    HandlerKey key = HandlerKey.of(ReportableEntityType.EVENT, String.valueOf(proxyPort));
    ((SenderTaskFactoryImpl) proxy.senderTaskFactory).flushNow(key);
    ((QueueingFactoryImpl) proxy.queueingFactory).flushNow(key);
    gzippedHttpPost("http://localhost:" + proxyPort + "/", payloadEvents);
    ((SenderTaskFactoryImpl) proxy.senderTaskFactory).flushNow(key);
    for (int i = 0; i < 2; i++) ((QueueingFactoryImpl) proxy.queueingFactory).flushNow(key);
    assertEquals(6, successfulSteps.getAndSet(0));
}
Also used : HandlerKey(com.wavefront.agent.handlers.HandlerKey) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SenderTaskFactoryImpl(com.wavefront.agent.handlers.SenderTaskFactoryImpl) URI(java.net.URI) QueueingFactoryImpl(com.wavefront.agent.queueing.QueueingFactoryImpl) Test(org.junit.Test)

Example 2 with HandlerKey

use of com.wavefront.agent.handlers.HandlerKey in project java by wavefrontHQ.

the class QueueingFactoryImpl method getQueueController.

@SuppressWarnings("unchecked")
@Override
public <T extends DataSubmissionTask<T>> QueueController<T> getQueueController(@Nonnull HandlerKey handlerKey, int numThreads) {
    ScheduledExecutorService executor = executors.computeIfAbsent(handlerKey, x -> Executors.newScheduledThreadPool(numThreads, new NamedThreadFactory("queueProcessor-" + handlerKey.getEntityType() + "-" + handlerKey.getHandle())));
    List<QueueProcessor<T>> queueProcessors = IntStream.range(0, numThreads).mapToObj(i -> (QueueProcessor<T>) getQueueProcessor(handlerKey, executor, i)).collect(Collectors.toList());
    return (QueueController<T>) queueControllers.computeIfAbsent(handlerKey, x -> new QueueController<>(handlerKey, queueProcessors, backlogSize -> entityPropsFactory.get(handlerKey.getEntityType()).reportBacklogSize(handlerKey.getHandle(), backlogSize)));
}
Also used : IntStream(java.util.stream.IntStream) EventDataSubmissionTask(com.wavefront.agent.data.EventDataSubmissionTask) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) EntityPropertiesFactory(com.wavefront.agent.data.EntityPropertiesFactory) DataSubmissionTask(com.wavefront.agent.data.DataSubmissionTask) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) ReportableEntityType(com.wavefront.data.ReportableEntityType) NamedThreadFactory(com.wavefront.common.NamedThreadFactory) List(java.util.List) TaskInjector(com.wavefront.agent.data.TaskInjector) TreeMap(java.util.TreeMap) SourceTagSubmissionTask(com.wavefront.agent.data.SourceTagSubmissionTask) Map(java.util.Map) APIContainer(com.wavefront.agent.api.APIContainer) HandlerKey(com.wavefront.agent.handlers.HandlerKey) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) LineDelimitedDataSubmissionTask(com.wavefront.agent.data.LineDelimitedDataSubmissionTask) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Nonnull(javax.annotation.Nonnull) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) NamedThreadFactory(com.wavefront.common.NamedThreadFactory)

Example 3 with HandlerKey

use of com.wavefront.agent.handlers.HandlerKey in project java by wavefrontHQ.

the class QueueExporterTest method testQueueExporter.

@Test
public void testQueueExporter() throws Exception {
    File file = new File(File.createTempFile("proxyTestConverter", null).getPath() + ".queue");
    file.deleteOnExit();
    String bufferFile = file.getAbsolutePath();
    TaskQueueFactory taskQueueFactory = new TaskQueueFactoryImpl(bufferFile, false, false, 128);
    EntityPropertiesFactory entityPropFactory = new DefaultEntityPropertiesFactoryForTesting();
    QueueExporter qe = new QueueExporter(bufferFile, "2878", bufferFile + "-output", false, taskQueueFactory, entityPropFactory);
    BufferedWriter mockedWriter = EasyMock.createMock(BufferedWriter.class);
    reset(mockedWriter);
    HandlerKey key = HandlerKey.of(ReportableEntityType.POINT, "2878");
    TaskQueue<LineDelimitedDataSubmissionTask> queue = taskQueueFactory.getTaskQueue(key, 0);
    queue.clear();
    UUID proxyId = UUID.randomUUID();
    LineDelimitedDataSubmissionTask task = new LineDelimitedDataSubmissionTask(null, proxyId, new DefaultEntityPropertiesForTesting(), queue, "wavefront", ReportableEntityType.POINT, "2878", ImmutableList.of("item1", "item2", "item3"), () -> 12345L);
    task.enqueue(QueueingReason.RETRY);
    LineDelimitedDataSubmissionTask task2 = new LineDelimitedDataSubmissionTask(null, proxyId, new DefaultEntityPropertiesForTesting(), queue, "wavefront", ReportableEntityType.POINT, "2878", ImmutableList.of("item4", "item5"), () -> 12345L);
    task2.enqueue(QueueingReason.RETRY);
    mockedWriter.write("item1");
    mockedWriter.newLine();
    mockedWriter.write("item2");
    mockedWriter.newLine();
    mockedWriter.write("item3");
    mockedWriter.newLine();
    mockedWriter.write("item4");
    mockedWriter.newLine();
    mockedWriter.write("item5");
    mockedWriter.newLine();
    TaskQueue<EventDataSubmissionTask> queue2 = taskQueueFactory.getTaskQueue(HandlerKey.of(ReportableEntityType.EVENT, "2888"), 0);
    queue2.clear();
    EventDataSubmissionTask eventTask = new EventDataSubmissionTask(null, proxyId, new DefaultEntityPropertiesForTesting(), queue2, "2888", ImmutableList.of(new Event(ReportEvent.newBuilder().setStartTime(123456789L * 1000).setEndTime(123456789L * 1000 + 1).setName("Event name for testing").setHosts(ImmutableList.of("host1", "host2")).setDimensions(ImmutableMap.of("multi", ImmutableList.of("bar", "baz"))).setAnnotations(ImmutableMap.of("severity", "INFO")).setTags(ImmutableList.of("tag1")).build()), new Event(ReportEvent.newBuilder().setStartTime(123456789L * 1000).setEndTime(123456789L * 1000 + 1).setName("Event name for testing").setHosts(ImmutableList.of("host1", "host2")).setAnnotations(ImmutableMap.of("severity", "INFO")).build())), () -> 12345L);
    eventTask.enqueue(QueueingReason.RETRY);
    mockedWriter.write("@Event 123456789000 123456789001 \"Event name for testing\" " + "\"host\"=\"host1\" \"host\"=\"host2\" \"severity\"=\"INFO\" \"multi\"=\"bar\" " + "\"multi\"=\"baz\" \"tag\"=\"tag1\"");
    mockedWriter.newLine();
    mockedWriter.write("@Event 123456789000 123456789001 \"Event name for testing\" " + "\"host\"=\"host1\" \"host\"=\"host2\" \"severity\"=\"INFO\"");
    mockedWriter.newLine();
    TaskQueue<SourceTagSubmissionTask> queue3 = taskQueueFactory.getTaskQueue(HandlerKey.of(ReportableEntityType.SOURCE_TAG, "2898"), 0);
    queue3.clear();
    SourceTagSubmissionTask sourceTagTask = new SourceTagSubmissionTask(null, new DefaultEntityPropertiesForTesting(), queue3, "2898", new SourceTag(ReportSourceTag.newBuilder().setOperation(SourceOperationType.SOURCE_TAG).setAction(SourceTagAction.SAVE).setSource("testSource").setAnnotations(ImmutableList.of("newtag1", "newtag2")).build()), () -> 12345L);
    sourceTagTask.enqueue(QueueingReason.RETRY);
    mockedWriter.write("@SourceTag action=save source=\"testSource\" \"newtag1\" \"newtag2\"");
    mockedWriter.newLine();
    expectLastCall().once();
    replay(mockedWriter);
    assertEquals(2, queue.size());
    qe.processQueue(queue, mockedWriter);
    assertEquals(0, queue.size());
    assertEquals(1, queue2.size());
    qe.processQueue(queue2, mockedWriter);
    assertEquals(0, queue2.size());
    assertEquals(1, queue3.size());
    qe.processQueue(queue3, mockedWriter);
    assertEquals(0, queue3.size());
    verify(mockedWriter);
    List<String> files = ConcurrentShardedQueueFile.listFiles(bufferFile, ".spool").stream().map(x -> x.replace(bufferFile + ".", "")).collect(Collectors.toList());
    assertEquals(3, files.size());
    assertTrue(files.contains("points.2878.0.spool_0000"));
    assertTrue(files.contains("events.2888.0.spool_0000"));
    assertTrue(files.contains("sourceTags.2898.0.spool_0000"));
    HandlerKey k1 = HandlerKey.of(ReportableEntityType.POINT, "2878");
    HandlerKey k2 = HandlerKey.of(ReportableEntityType.EVENT, "2888");
    HandlerKey k3 = HandlerKey.of(ReportableEntityType.SOURCE_TAG, "2898");
    files = ConcurrentShardedQueueFile.listFiles(bufferFile, ".spool");
    Set<HandlerKey> hk = QueueExporter.getValidHandlerKeys(files, "all");
    assertEquals(3, hk.size());
    assertTrue(hk.contains(k1));
    assertTrue(hk.contains(k2));
    assertTrue(hk.contains(k3));
    hk = QueueExporter.getValidHandlerKeys(files, "2878, 2898");
    assertEquals(2, hk.size());
    assertTrue(hk.contains(k1));
    assertTrue(hk.contains(k3));
    hk = QueueExporter.getValidHandlerKeys(files, "2888");
    assertEquals(1, hk.size());
    assertTrue(hk.contains(k2));
}
Also used : HandlerKey(com.wavefront.agent.handlers.HandlerKey) QueueingReason(com.wavefront.agent.data.QueueingReason) ReportSourceTag(wavefront.report.ReportSourceTag) ReportEvent(wavefront.report.ReportEvent) SourceOperationType(wavefront.report.SourceOperationType) ImmutableList(com.google.common.collect.ImmutableList) Event(com.wavefront.dto.Event) EasyMock.reset(org.easymock.EasyMock.reset) Files(com.google.common.io.Files) DefaultEntityPropertiesFactoryForTesting(com.wavefront.agent.data.DefaultEntityPropertiesFactoryForTesting) SourceTagSubmissionTask(com.wavefront.agent.data.SourceTagSubmissionTask) HandlerKey(com.wavefront.agent.handlers.HandlerKey) EasyMock.replay(org.easymock.EasyMock.replay) Charsets(com.google.common.base.Charsets) DefaultEntityPropertiesForTesting(com.wavefront.agent.data.DefaultEntityPropertiesForTesting) ImmutableMap(com.google.common.collect.ImmutableMap) EventDataSubmissionTask(com.wavefront.agent.data.EventDataSubmissionTask) BufferedWriter(java.io.BufferedWriter) EntityPropertiesFactory(com.wavefront.agent.data.EntityPropertiesFactory) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) EasyMock(org.easymock.EasyMock) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) File(java.io.File) SourceTag(com.wavefront.dto.SourceTag) EasyMock.expectLastCall(org.easymock.EasyMock.expectLastCall) ReportableEntityType(com.wavefront.data.ReportableEntityType) List(java.util.List) LineDelimitedDataSubmissionTask(com.wavefront.agent.data.LineDelimitedDataSubmissionTask) EasyMock.verify(org.easymock.EasyMock.verify) Assert.assertEquals(org.junit.Assert.assertEquals) SourceTagAction(wavefront.report.SourceTagAction) EventDataSubmissionTask(com.wavefront.agent.data.EventDataSubmissionTask) ReportSourceTag(wavefront.report.ReportSourceTag) SourceTag(com.wavefront.dto.SourceTag) LineDelimitedDataSubmissionTask(com.wavefront.agent.data.LineDelimitedDataSubmissionTask) DefaultEntityPropertiesFactoryForTesting(com.wavefront.agent.data.DefaultEntityPropertiesFactoryForTesting) EntityPropertiesFactory(com.wavefront.agent.data.EntityPropertiesFactory) BufferedWriter(java.io.BufferedWriter) SourceTagSubmissionTask(com.wavefront.agent.data.SourceTagSubmissionTask) ReportEvent(wavefront.report.ReportEvent) Event(com.wavefront.dto.Event) DefaultEntityPropertiesForTesting(com.wavefront.agent.data.DefaultEntityPropertiesForTesting) UUID(java.util.UUID) File(java.io.File) Test(org.junit.Test)

Example 4 with HandlerKey

use of com.wavefront.agent.handlers.HandlerKey in project java by wavefrontHQ.

the class PushAgent method startDeltaCounterListener.

@VisibleForTesting
protected void startDeltaCounterListener(String strPort, SharedGraphiteHostAnnotator hostAnnotator, SenderTaskFactory senderTaskFactory, SpanSampler sampler) {
    final int port = Integer.parseInt(strPort);
    registerPrefixFilter(strPort);
    registerTimestampFilter(strPort);
    if (proxyConfig.isHttpHealthCheckAllPorts())
        healthCheckManager.enableHealthcheck(port);
    if (this.deltaCounterHandlerFactory == null) {
        this.deltaCounterHandlerFactory = new ReportableEntityHandlerFactory() {

            private final Map<String, ReportableEntityHandler<?, ?>> handlers = new ConcurrentHashMap<>();

            @Override
            public <T, U> ReportableEntityHandler<T, U> getHandler(HandlerKey handlerKey) {
                // noinspection unchecked
                return (ReportableEntityHandler<T, U>) handlers.computeIfAbsent(handlerKey.getHandle(), k -> new DeltaCounterAccumulationHandlerImpl(handlerKey, proxyConfig.getPushBlockedSamples(), senderTaskFactory.createSenderTasks(handlerKey), validationConfiguration, proxyConfig.getDeltaCountersAggregationIntervalSeconds(), rate -> entityProps.get(ReportableEntityType.POINT).reportReceivedRate(handlerKey.getHandle(), rate), blockedPointsLogger, VALID_POINTS_LOGGER));
            }

            @Override
            public void shutdown(@Nonnull String handle) {
                if (handlers.containsKey(handle)) {
                    handlers.values().forEach(ReportableEntityHandler::shutdown);
                }
            }
        };
    }
    shutdownTasks.add(() -> deltaCounterHandlerFactory.shutdown(strPort));
    WavefrontPortUnificationHandler wavefrontPortUnificationHandler = new WavefrontPortUnificationHandler(strPort, tokenAuthenticator, healthCheckManager, decoderSupplier.get(), deltaCounterHandlerFactory, hostAnnotator, preprocessors.get(strPort), () -> false, () -> false, () -> false, sampler);
    startAsManagedThread(port, new TcpIngester(createInitializer(wavefrontPortUnificationHandler, port, proxyConfig.getPushListenerMaxReceivedLength(), proxyConfig.getPushListenerHttpBufferSize(), proxyConfig.getListenerIdleConnectionTimeout(), getSslContext(strPort), getCorsConfig(strPort)), port).withChildChannelOptions(childChannelOptions), "listener-deltaCounter-" + port);
}
Also used : HandlerKey(com.wavefront.agent.handlers.HandlerKey) QueueingReason(com.wavefront.agent.data.QueueingReason) CustomTracingPortUnificationHandler(com.wavefront.agent.listeners.tracing.CustomTracingPortUnificationHandler) CompositeSampler(com.wavefront.sdk.entities.tracing.sampling.CompositeSampler) EntityProperties(com.wavefront.agent.data.EntityProperties) NettyServerBuilder(io.grpc.netty.NettyServerBuilder) RequestConfig(org.apache.http.client.config.RequestConfig) StringUtils(org.apache.commons.lang3.StringUtils) SpanSanitizeTransformer(com.wavefront.agent.preprocessor.SpanSanitizeTransformer) BooleanUtils(org.apache.commons.lang.BooleanUtils) InetAddress(java.net.InetAddress) SQSQueueFactoryImpl(com.wavefront.agent.queueing.SQSQueueFactoryImpl) PointHandlerDispatcher(com.wavefront.agent.histogram.PointHandlerDispatcher) Map(java.util.Map) HandlerKey(com.wavefront.agent.handlers.HandlerKey) ByteArrayDecoder(io.netty.handler.codec.bytes.ByteArrayDecoder) RecyclableRateLimiter(com.google.common.util.concurrent.RecyclableRateLimiter) HealthCheckManagerImpl(com.wavefront.agent.channel.HealthCheckManagerImpl) HistogramKey(com.wavefront.agent.histogram.HistogramKey) AdminPortUnificationHandler(com.wavefront.agent.listeners.AdminPortUnificationHandler) ChronicleMap(net.openhft.chronicle.map.ChronicleMap) ProxyUtil.createInitializer(com.wavefront.agent.ProxyUtil.createInitializer) Executors(java.util.concurrent.Executors) AgentDigestFactory(com.wavefront.agent.histogram.accumulator.AgentDigestFactory) ByteOrder(java.nio.ByteOrder) AgentConfiguration(com.wavefront.api.agent.AgentConfiguration) OpenTSDBDecoder(com.wavefront.ingester.OpenTSDBDecoder) ReportPointTimestampInRangeFilter(com.wavefront.agent.preprocessor.ReportPointTimestampInRangeFilter) AccumulationCache(com.wavefront.agent.histogram.accumulator.AccumulationCache) HealthCheckManager(com.wavefront.agent.channel.HealthCheckManager) ChannelOption(io.netty.channel.ChannelOption) SpanSampler(com.wavefront.agent.sampler.SpanSampler) TChannel(com.uber.tchannel.api.TChannel) Supplier(java.util.function.Supplier) RelayPortUnificationHandler(com.wavefront.agent.listeners.RelayPortUnificationHandler) TcpIngester(com.wavefront.ingester.TcpIngester) ArrayList(java.util.ArrayList) HttpClient(org.apache.http.client.HttpClient) SharedGraphiteHostAnnotator(com.wavefront.agent.channel.SharedGraphiteHostAnnotator) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ConfigurationException(com.wavefront.agent.config.ConfigurationException) Utils.lazySupplier(com.wavefront.common.Utils.lazySupplier) Utils.csvToList(com.wavefront.common.Utils.csvToList) Server(org.logstash.beats.Server) TokenAuthenticatorBuilder(com.wavefront.agent.auth.TokenAuthenticatorBuilder) MapLoader(com.wavefront.agent.histogram.MapLoader) Nullable(javax.annotation.Nullable) HistogramUtils(com.wavefront.agent.histogram.HistogramUtils) DataDogPortUnificationHandler(com.wavefront.agent.listeners.DataDogPortUnificationHandler) SslContext(io.netty.handler.ssl.SslContext) WavefrontSender(com.wavefront.sdk.common.WavefrontSender) NO_RATE_LIMIT(com.wavefront.agent.data.EntityProperties.NO_RATE_LIMIT) WavefrontPortUnificationHandler(com.wavefront.agent.listeners.WavefrontPortUnificationHandler) File(java.io.File) CachingHostnameLookupResolver(com.wavefront.agent.channel.CachingHostnameLookupResolver) NamedThreadFactory(com.wavefront.common.NamedThreadFactory) GraphiteFormatter(com.wavefront.agent.formatter.GraphiteFormatter) ReportSourceTagDecoder(com.wavefront.ingester.ReportSourceTagDecoder) ReportableEntityDecoder(com.wavefront.ingester.ReportableEntityDecoder) VALID_POINTS_LOGGER(com.wavefront.agent.handlers.ReportableEntityHandlerFactoryImpl.VALID_POINTS_LOGGER) Preconditions(com.google.common.base.Preconditions) WriteHttpJsonPortUnificationHandler(com.wavefront.agent.listeners.WriteHttpJsonPortUnificationHandler) Metrics(com.yammer.metrics.Metrics) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) QueueingFactory(com.wavefront.agent.queueing.QueueingFactory) SpanSamplerUtils(com.wavefront.agent.sampler.SpanSamplerUtils) ReportPointDecoder(com.wavefront.ingester.ReportPointDecoder) LogsIngester(com.wavefront.agent.logsharvesting.LogsIngester) SpanLogsDecoder(com.wavefront.ingester.SpanLogsDecoder) Sampler(com.wavefront.sdk.entities.tracing.sampling.Sampler) ZipkinPortUnificationHandler(com.wavefront.agent.listeners.tracing.ZipkinPortUnificationHandler) TaskQueueFactory(com.wavefront.agent.queueing.TaskQueueFactory) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) TokenAuthenticator(com.wavefront.agent.auth.TokenAuthenticator) ReportableEntityHandler(com.wavefront.agent.handlers.ReportableEntityHandler) HistogramAccumulationHandlerImpl(com.wavefront.agent.handlers.HistogramAccumulationHandlerImpl) Granularity(com.wavefront.agent.histogram.Granularity) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) ReportPoint(wavefront.report.ReportPoint) WavefrontInternalReporter(com.wavefront.internal.reporter.WavefrontInternalReporter) HistogramRecompressor(com.wavefront.agent.histogram.HistogramRecompressor) CorsConfigBuilder(io.netty.handler.codec.http.cors.CorsConfigBuilder) FilebeatIngester(com.wavefront.agent.logsharvesting.FilebeatIngester) PickleProtocolDecoder(com.wavefront.ingester.PickleProtocolDecoder) JaegerPortUnificationHandler(com.wavefront.agent.listeners.tracing.JaegerPortUnificationHandler) IdentityHashMap(java.util.IdentityHashMap) TaggedMetricName(com.wavefront.common.TaggedMetricName) ImmutableMap(com.google.common.collect.ImmutableMap) HttpHealthCheckEndpointHandler(com.wavefront.agent.listeners.HttpHealthCheckEndpointHandler) Accumulator(com.wavefront.agent.histogram.accumulator.Accumulator) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Logger(java.util.logging.Logger) ReportableEntityHandlerFactoryImpl(com.wavefront.agent.handlers.ReportableEntityHandlerFactoryImpl) Collectors(java.util.stream.Collectors) ReportableEntityType(com.wavefront.data.ReportableEntityType) List(java.util.List) ExpectedAgentMetric(com.wavefront.metrics.ExpectedAgentMetric) ChannelByteArrayHandler(com.wavefront.agent.listeners.ChannelByteArrayHandler) QueueingFactoryImpl(com.wavefront.agent.queueing.QueueingFactoryImpl) JaegerTChannelCollectorHandler(com.wavefront.agent.listeners.tracing.JaegerTChannelCollectorHandler) PreprocessorRuleMetrics(com.wavefront.agent.preprocessor.PreprocessorRuleMetrics) HistogramDecoder(com.wavefront.ingester.HistogramDecoder) HashMap(java.util.HashMap) BindException(java.net.BindException) Function(java.util.function.Function) OpenTSDBPortUnificationHandler(com.wavefront.agent.listeners.OpenTSDBPortUnificationHandler) Level(java.util.logging.Level) JsonMetricsPortUnificationHandler(com.wavefront.agent.listeners.JsonMetricsPortUnificationHandler) TaskQueueFactoryImpl(com.wavefront.agent.queueing.TaskQueueFactoryImpl) ReportPointAddPrefixTransformer(com.wavefront.agent.preprocessor.ReportPointAddPrefixTransformer) ImmutableList(com.google.common.collect.ImmutableList) TrafficShapingRateLimitAdjuster(com.wavefront.agent.handlers.TrafficShapingRateLimitAdjuster) ObjectUtils(org.apache.commons.lang3.ObjectUtils) RawLogsIngesterPortUnificationHandler(com.wavefront.agent.listeners.RawLogsIngesterPortUnificationHandler) HistogramKeyMarshaller(com.wavefront.agent.histogram.HistogramUtils.HistogramKeyMarshaller) EventDecoder(com.wavefront.ingester.EventDecoder) ReportPointDecoderWrapper(com.wavefront.ingester.ReportPointDecoderWrapper) Nonnull(javax.annotation.Nonnull) InternalProxyWavefrontClient(com.wavefront.agent.handlers.InternalProxyWavefrontClient) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) Counter(com.yammer.metrics.core.Counter) SenderTaskFactory(com.wavefront.agent.handlers.SenderTaskFactory) AgentDigestMarshaller(com.tdunning.math.stats.AgentDigest.AgentDigestMarshaller) DelegatingReportableEntityHandlerFactoryImpl(com.wavefront.agent.handlers.DelegatingReportableEntityHandlerFactoryImpl) SpanDecoder(com.wavefront.ingester.SpanDecoder) CorsConfig(io.netty.handler.codec.http.cors.CorsConfig) VALID_HISTOGRAMS_LOGGER(com.wavefront.agent.handlers.ReportableEntityHandlerFactoryImpl.VALID_HISTOGRAMS_LOGGER) HttpMethod(io.netty.handler.codec.http.HttpMethod) AgentDigest(com.tdunning.math.stats.AgentDigest) DeltaCounterAccumulationHandlerImpl(com.wavefront.agent.handlers.DeltaCounterAccumulationHandlerImpl) TracePortUnificationHandler(com.wavefront.agent.listeners.tracing.TracePortUnificationHandler) TimeUnit(java.util.concurrent.TimeUnit) Connection(com.uber.tchannel.channels.Connection) RateSampler(com.wavefront.sdk.entities.tracing.sampling.RateSampler) ReportableEntityHandlerFactory(com.wavefront.agent.handlers.ReportableEntityHandlerFactory) SenderTaskFactoryImpl(com.wavefront.agent.handlers.SenderTaskFactoryImpl) JaegerGrpcCollectorHandler(com.wavefront.agent.listeners.tracing.JaegerGrpcCollectorHandler) ChannelHandler(io.netty.channel.ChannelHandler) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Histogram(wavefront.report.Histogram) WavefrontPortUnificationHandler(com.wavefront.agent.listeners.WavefrontPortUnificationHandler) ReportPoint(wavefront.report.ReportPoint) ReportableEntityHandler(com.wavefront.agent.handlers.ReportableEntityHandler) NO_RATE_LIMIT(com.wavefront.agent.data.EntityProperties.NO_RATE_LIMIT) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) DeltaCounterAccumulationHandlerImpl(com.wavefront.agent.handlers.DeltaCounterAccumulationHandlerImpl) ReportableEntityHandlerFactory(com.wavefront.agent.handlers.ReportableEntityHandlerFactory) TcpIngester(com.wavefront.ingester.TcpIngester) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 5 with HandlerKey

use of com.wavefront.agent.handlers.HandlerKey in project java by wavefrontHQ.

the class InteractiveLogsTester method interactiveTest.

/**
 * Read one line of stdin and print a message to stdout.
 */
@Override
public boolean interactiveTest() throws ConfigurationException {
    final AtomicBoolean reported = new AtomicBoolean(false);
    ReportableEntityHandlerFactory factory = new ReportableEntityHandlerFactory() {

        @SuppressWarnings("unchecked")
        @Override
        public <T, U> ReportableEntityHandler<T, U> getHandler(HandlerKey handlerKey) {
            return (ReportableEntityHandler<T, U>) new ReportableEntityHandler<ReportPoint, String>() {

                @Override
                public void report(ReportPoint reportPoint) {
                    reported.set(true);
                    System.out.println(ReportPointSerializer.pointToString(reportPoint));
                }

                @Override
                public void block(ReportPoint reportPoint) {
                    System.out.println("Blocked: " + reportPoint);
                }

                @Override
                public void block(@Nullable ReportPoint reportPoint, @Nullable String message) {
                    System.out.println("Blocked: " + reportPoint);
                }

                @Override
                public void reject(@Nullable ReportPoint reportPoint, @Nullable String message) {
                    System.out.println("Rejected: " + reportPoint);
                }

                @Override
                public void reject(@Nonnull String t, @Nullable String message) {
                    System.out.println("Rejected: " + t);
                }

                @Override
                public void shutdown() {
                }
            };
        }

        @Override
        public void shutdown(@Nonnull String handle) {
        }
    };
    LogsIngester logsIngester = new LogsIngester(factory, logsIngestionConfigSupplier, prefix);
    String line = stdin.nextLine();
    logsIngester.ingestLog(new LogsMessage() {

        @Override
        public String getLogLine() {
            return line;
        }

        @Override
        public String hostOrDefault(String fallbackHost) {
            try {
                return InetAddress.getLocalHost().getHostName();
            } catch (UnknownHostException e) {
                return "localhost";
            }
        }
    });
    logsIngester.flush();
    if (!reported.get()) {
        System.out.println("Input matched no groks.");
    }
    return stdin.hasNext();
}
Also used : HandlerKey(com.wavefront.agent.handlers.HandlerKey) UnknownHostException(java.net.UnknownHostException) Nonnull(javax.annotation.Nonnull) ReportableEntityHandler(com.wavefront.agent.handlers.ReportableEntityHandler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ReportPoint(wavefront.report.ReportPoint) ReportableEntityHandlerFactory(com.wavefront.agent.handlers.ReportableEntityHandlerFactory)

Aggregations

HandlerKey (com.wavefront.agent.handlers.HandlerKey)13 SenderTaskFactoryImpl (com.wavefront.agent.handlers.SenderTaskFactoryImpl)7 QueueingFactoryImpl (com.wavefront.agent.queueing.QueueingFactoryImpl)7 ReportableEntityType (com.wavefront.data.ReportableEntityType)6 File (java.io.File)6 Nonnull (javax.annotation.Nonnull)6 Test (org.junit.Test)6 VisibleForTesting (com.google.common.annotations.VisibleForTesting)5 ImmutableMap (com.google.common.collect.ImmutableMap)5 Map (java.util.Map)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 ImmutableList (com.google.common.collect.ImmutableList)4 QueueingReason (com.wavefront.agent.data.QueueingReason)4 Preconditions (com.google.common.base.Preconditions)3 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)3 RecyclableRateLimiter (com.google.common.util.concurrent.RecyclableRateLimiter)3 AgentDigest (com.tdunning.math.stats.AgentDigest)3 AgentDigestMarshaller (com.tdunning.math.stats.AgentDigest.AgentDigestMarshaller)3 TChannel (com.uber.tchannel.api.TChannel)3 Connection (com.uber.tchannel.channels.Connection)3