com.signalfx.codahale.reporter.SignalFxReporter Java Examples

The following examples show how to use com.signalfx.codahale.reporter.SignalFxReporter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SignalFxReporterFactoryTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void getReporter_passes_properly_configured_builder_to_reporterConfigurator_and_builds_the_result_of_reporterConfigurator() {
    // when
    SignalFxReporter result = factory.getReporter(metricRegistryMock);

    // then
    // Make sure the configurator function received a properly configured builder.
    ArgumentCaptor<Builder> origBuilderArgCaptor = ArgumentCaptor.forClass(Builder.class);
    verify(configuratorMock).apply(origBuilderArgCaptor.capture());
    Builder origBuilder = origBuilderArgCaptor.getValue();
    assertThat(getInternalState(origBuilder, "registry")).isSameAs(metricRegistryMock);
    assertThat(((AuthToken) getInternalState(origBuilder, "authToken")).getAuthToken()).isEqualTo(apiKey);

    // Make sure the thing returned by the configurator was used to build the final reporter.
    assertThat(
        ((Map<String, DimensionInclusion>)getInternalState(result, "defaultDimensions"))
            .get(customDimKey).getValue()
    ).isEqualTo(customDimValue);
}
 
Example #2
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
private Pair<Pair<SignalFxReporter, MetricMetadata>, Pair<Long, TimeUnit>> wireUpReporterFactoryMockForConstructor(
    SignalFxReporterFactory factoryMock, MetricRegistry expectedMetricRegistry
) {
    SignalFxReporter reporterMock = mock(SignalFxReporter.class);
    doReturn(reporterMock).when(factoryMock).getReporter(expectedMetricRegistry);

    MetricMetadata metricMetadataMock = wireUpReporterForConstructor(reporterMock);

    long reportingInterval = 42;
    TimeUnit reportingTimeUnit = TimeUnit.DAYS;

    doReturn(reportingInterval).when(factoryMock).getInterval();
    doReturn(reportingTimeUnit).when(factoryMock).getTimeUnit();

    return Pair.of(Pair.of(reporterMock, metricMetadataMock), Pair.of(reportingInterval, reportingTimeUnit));
}
 
Example #3
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void two_arg_constructor_sets_fields_as_expected() {
    // given
    SignalFxReporterFactory reporterFactoryMock = mock(SignalFxReporterFactory.class);
    Pair<Pair<SignalFxReporter, MetricMetadata>, Pair<Long, TimeUnit>> wiredUpMocksAndData =
        wireUpReporterFactoryMockForConstructor(reporterFactoryMock, metricRegistryMock);

    MetricMetadata expectedMetricMetadata = wiredUpMocksAndData.getLeft().getRight();
    long expectedReportingInterval = wiredUpMocksAndData.getRight().getLeft();
    TimeUnit expectedReportingTimeUnit = wiredUpMocksAndData.getRight().getRight();

    // when
    SignalFxEndpointMetricsHandler instance =
        new SignalFxEndpointMetricsHandler(reporterFactoryMock, metricRegistryMock);

    // then
    assertThat(instance.metricMetadata).isSameAs(expectedMetricMetadata);
    assertThat(instance.metricRegistry).isSameAs(metricRegistryMock);
    assertThat(instance.requestTimerBuilder).isInstanceOf(RollingWindowTimerBuilder.class);
    RollingWindowTimerBuilder rwtb = (RollingWindowTimerBuilder) instance.requestTimerBuilder;
    assertThat(rwtb.amount).isEqualTo(expectedReportingInterval);
    assertThat(rwtb.timeUnit).isEqualTo(expectedReportingTimeUnit);
    assertThat(instance.requestTimerDimensionConfigurator)
        .isSameAs(DEFAULT_REQUEST_LATENCY_TIMER_DIMENSION_CONFIGURATOR);
}
 
Example #4
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void three_arg_constructor_sets_fields_as_expected() {
    // given
    SignalFxReporter reporterMock = mock(SignalFxReporter.class);
    MetricMetadata expectedMetricMetadata = wireUpReporterForConstructor(reporterMock);

    Pair<Long, TimeUnit> reportingFrequency = Pair.of(42L, TimeUnit.DAYS);

    // when
    SignalFxEndpointMetricsHandler instance =
        new SignalFxEndpointMetricsHandler(reporterMock, reportingFrequency, metricRegistryMock);

    // then
    assertThat(instance.metricMetadata).isSameAs(expectedMetricMetadata);
    assertThat(instance.metricRegistry).isSameAs(metricRegistryMock);
    assertThat(instance.requestTimerBuilder).isInstanceOf(RollingWindowTimerBuilder.class);
    RollingWindowTimerBuilder rwtb = (RollingWindowTimerBuilder) instance.requestTimerBuilder;
    assertThat(rwtb.amount).isEqualTo(reportingFrequency.getLeft());
    assertThat(rwtb.timeUnit).isEqualTo(reportingFrequency.getRight());
    assertThat(instance.requestTimerDimensionConfigurator)
        .isSameAs(DEFAULT_REQUEST_LATENCY_TIMER_DIMENSION_CONFIGURATOR);
}
 
Example #5
Source File: SignalFxReporterTest.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    metricRegistry = new MetricRegistry();
    dbank = new StoredDataPointReceiver();
    reporter = new SignalFxReporter
            .Builder(metricRegistry, new StaticAuthToken(""), SOURCE_NAME)
            .setDataPointReceiverFactory(new StaticDataPointReceiverFactory(dbank))
            .setDetailsToAdd(ImmutableSet.of(SignalFxReporter.MetricDetails.COUNT,
                    SignalFxReporter.MetricDetails.MIN,
                    SignalFxReporter.MetricDetails.MAX))
            .build();
    sfxMetrics = new SfxMetrics(metricRegistry, reporter.getMetricMetadata());
}
 
Example #6
Source File: SignalFxMetricsReporterService.java    From kafka-monitor with Apache License 2.0 5 votes vote down vote up
public SignalFxMetricsReporterService(Map<String, Object> props, String name) throws Exception {
  SignalFxMetricsReporterServiceConfig config = new SignalFxMetricsReporterServiceConfig(props);

  _name = name;
  _metricNames = config.getList(SignalFxMetricsReporterServiceConfig.REPORT_METRICS_CONFIG);
  _reportIntervalSec = config.getInt(SignalFxMetricsReporterServiceConfig.REPORT_INTERVAL_SEC_CONFIG);
  String signalfxUrl = config.getString(SignalFxMetricsReporterServiceConfig.REPORT_SIGNALFX_URL);
  String signalfxToken = config.getString(SignalFxMetricsReporterServiceConfig.SIGNALFX_TOKEN);

  if (StringUtils.isEmpty(signalfxToken)) {
    throw new IllegalArgumentException("SignalFx token is not configured");
  }

  _executor = Executors.newSingleThreadScheduledExecutor();
  _metricRegistry = new MetricRegistry();
  _metricMap = new HashMap<String, SettableDoubleGauge>();
  _dimensionsMap = new HashMap<String, String>();
  if (props.containsKey(SignalFxMetricsReporterServiceConfig.SIGNALFX_METRIC_DIMENSION)) {
    _dimensionsMap = (Map<String, String>) props.get(SignalFxMetricsReporterServiceConfig.SIGNALFX_METRIC_DIMENSION);
  }

  SignalFxReporter.Builder sfxReportBuilder = new SignalFxReporter.Builder(
      _metricRegistry, signalfxToken
  );
  if (!StringUtils.isEmpty(signalfxUrl)) {
    sfxReportBuilder.setEndpoint(getSignalFxEndpoint(signalfxUrl));
  }
  _signalfxReporter = sfxReportBuilder.build();

  _metricMetadata = _signalfxReporter.getMetricMetadata();
}
 
Example #7
Source File: SignalFxReporterFactoryTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void getReporter_caches_result_and_reuses_it_for_subsequent_calls() {
    // given
    SignalFxReporter initialResult = factory.getReporter(metricRegistryMock);
    verify(configuratorMock).apply(any(Builder.class));

    // when
    SignalFxReporter subsequentResult = factory.getReporter(metricRegistryMock);

    // then
    verifyNoMoreInteractions(configuratorMock);
    assertThat(subsequentResult).isSameAs(initialResult);
}
 
Example #8
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void three_arg_constructor_fails_with_IllegalArgumentException_if_metricRegistry_is_null() {
    // given
    SignalFxReporter reporterMock = mock(SignalFxReporter.class);
    wireUpReporterForConstructor(reporterMock);

    // when
    Throwable ex = catchThrowable(
        () -> new SignalFxEndpointMetricsHandler(reporterMock, Pair.of(42L, TimeUnit.DAYS), null)
    );

    // then
    assertThat(ex).isInstanceOf(IllegalArgumentException.class)
                  .hasMessage("metricRegistry cannot be null");
}
 
Example #9
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true   |   false",
    "false  |   true"
}, splitBy = "\\|")
@Test
public void three_arg_constructor_fails_with_IllegalArgumentException_if_reporting_frequency_args_are_null(
    boolean amountIsNull, boolean timeUnitIsNull
) {
    // given
    SignalFxReporter reporterMock = mock(SignalFxReporter.class);
    wireUpReporterForConstructor(reporterMock);

    Long amount = (amountIsNull) ? null : 42L;
    TimeUnit timeUnit = (timeUnitIsNull) ? null : TimeUnit.DAYS;

    // when
    Throwable ex = catchThrowable(
        () -> new SignalFxEndpointMetricsHandler(reporterMock, Pair.of(amount, timeUnit), metricRegistryMock)
    );

    // then
    if (amountIsNull) {
        assertThat(ex).isInstanceOf(IllegalArgumentException.class)
                      .hasMessage("reportingFrequency amount cannot be null");
    }

    if (timeUnitIsNull) {
        assertThat(ex).isInstanceOf(IllegalArgumentException.class)
                      .hasMessage("reportingFrequency TimeUnit cannot be null");
    }
}
 
Example #10
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void three_arg_constructor_fails_with_IllegalArgumentException_if_reportingFrequency_is_null() {
    // given
    SignalFxReporter reporterMock = mock(SignalFxReporter.class);
    wireUpReporterForConstructor(reporterMock);

    // when
    Throwable ex = catchThrowable(
        () -> new SignalFxEndpointMetricsHandler(reporterMock, null, metricRegistryMock)
    );

    // then
    assertThat(ex).isInstanceOf(IllegalArgumentException.class)
                  .hasMessage("reportingFrequency cannot be null");
}
 
Example #11
Source File: SignalFxReporterFactory.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized SignalFxReporter getReporter(MetricRegistry registry) {
    if (signalFxReporter == null) {
        signalFxReporter = reporterConfigurator.apply(
            new SignalFxReporter.Builder(registry,signalFxApiKey)
        ).build();
    }

    return signalFxReporter;
}
 
Example #12
Source File: SignalFxEndpointMetricsHandler.java    From riposte with Apache License 2.0 5 votes vote down vote up
protected static SignalFxReporter extractSignalFxReporterFromFactory(SignalFxReporterFactory factory,
                                                                     MetricRegistry metricRegistry) {
    if (factory == null)
        throw new IllegalArgumentException("SignalFxReporterFactory cannot be null");

    if (metricRegistry == null)
        throw new IllegalArgumentException("MetricRegistry cannot be null");

    return factory.getReporter(metricRegistry);
}
 
Example #13
Source File: SignalFxEndpointMetricsHandlerTest.java    From riposte with Apache License 2.0 4 votes vote down vote up
private MetricMetadata wireUpReporterForConstructor(SignalFxReporter reporterMock) {
    MetricMetadata metricMetadataMock = mock(MetricMetadata.class);
    doReturn(metricMetadataMock).when(reporterMock).getMetricMetadata();

    return metricMetadataMock;
}
 
Example #14
Source File: SignalFxAwareCodahaleMetricsCollectorTest.java    From riposte with Apache License 2.0 4 votes vote down vote up
@Before
public void beforeMethod() {
    metricRegistryMock = mock(MetricRegistry.class);
    sfxReporterFactoryMock = mock(SignalFxReporterFactory.class);
    sfxReporterMock = mock(SignalFxReporter.class);
    metricMetadataMock = mock(MetricMetadata.class);

    doReturn(sfxReporterMock).when(sfxReporterFactoryMock).getReporter(any(MetricRegistry.class));
    doReturn(metricMetadataMock).when(sfxReporterMock).getMetricMetadata();

    doReturn(reportingInterval).when(sfxReporterFactoryMock).getInterval();
    doReturn(reportingTimeUnit).when(sfxReporterFactoryMock).getTimeUnit();

    timerBuilderMock = mock(MetricBuilder.class);
    histogramBuilderMock = mock(MetricBuilder.class);
    genericMetricBuilderMock = mock(MetricBuilder.class);

    timerMock = mock(Timer.class);
    meterMock = mock(Meter.class);
    histogramMock = mock(Histogram.class);
    counterMock = mock(Counter.class);
    gaugeMock = mock(Gauge.class);
    genericMetricMock = mock(Metric.class);

    timerTaggerMock = mock(BuilderTagger.class);
    meterTaggerMock = mock(BuilderTagger.class);
    histogramTaggerMock = mock(BuilderTagger.class);
    counterTaggerMock = mock(BuilderTagger.class);
    gaugeTaggerMock = mock(Tagger.class);
    genericMetricTaggerMock = mock(BuilderTagger.class);

    setupBuilderTaggerMock(timerTaggerMock, timerBuilderMock, timerMock);
    setupBuilderTaggerMock(meterTaggerMock, MetricBuilder.METERS, meterMock);
    setupBuilderTaggerMock(histogramTaggerMock, histogramBuilderMock, histogramMock);
    setupBuilderTaggerMock(counterTaggerMock, MetricBuilder.COUNTERS, counterMock);
    setupTaggerMock(gaugeTaggerMock);
    setupBuilderTaggerMock(genericMetricTaggerMock, genericMetricBuilderMock, genericMetricMock);

    sfxImpl = new SignalFxAwareCodahaleMetricsCollector(
        metricRegistryMock, metricMetadataMock, timerBuilderMock, histogramBuilderMock
    );
}
 
Example #15
Source File: SignalFxEndpointMetricsHandler.java    From riposte with Apache License 2.0 4 votes vote down vote up
protected static MetricMetadata extractMetricMetadataFromSignalFxReporter(SignalFxReporter reporter) {
    if (reporter  == null)
        throw new IllegalArgumentException("SignalFxReporter cannot be null");

    return reporter.getMetricMetadata();
}
 
Example #16
Source File: YammerExample.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        System.out.println("Running example...");

        Properties prop = new Properties();
        prop.load(new FileInputStream("auth.properties"));
        final String auth_token = prop.getProperty("auth");
        final String hostUrlStr = prop.getProperty("host");
        final URL hostUrl = new URL(hostUrlStr);
        System.out.println("Auth=" + auth_token + " .. host=" + hostUrl);
        SignalFxReceiverEndpoint endpoint = new SignalFxEndpoint(hostUrl.getProtocol(),
                hostUrl.getHost(), hostUrl.getPort());

        MetricsRegistry metricsRegistry = new MetricsRegistry();
        SignalFxReporter reporter = new SignalFxReporter.Builder(metricsRegistry,
                new StaticAuthToken(auth_token),
                hostUrlStr).setEndpoint(endpoint)
                .setOnSendErrorHandlerCollection(
                        Collections.<OnSendErrorHandler>singleton(new OnSendErrorHandler() {
                            public void handleError(MetricError error) {
                                System.out.println("" + error.getMessage());
                            }
                        }))
                .setDetailsToAdd(ImmutableSet.of(SignalFxReporter.MetricDetails.COUNT,
                        SignalFxReporter.MetricDetails.MIN,
                        SignalFxReporter.MetricDetails.MAX))
                .build();

        final MetricMetadata metricMetadata = reporter.getMetricMetadata();

        Counter counter = getCounter(metricsRegistry, metricMetadata);

        Metric cumulativeCounter = getCumulativeCounter(metricsRegistry, metricMetadata);

        Gauge gauge1 = getGauge(metricsRegistry, metricMetadata);

        Timer timer = getTimer(metricsRegistry, metricMetadata);

        // main body generating data and sending it in a loop
        while (true) {
            final TimerContext context = timer.time();
            try {
                System.out.println("Sending data...");
                Thread.sleep(500);
                counter.inc();
            } finally {
                context.stop();
            }
            reporter.report(); // Report all metrics
        }

    }
 
Example #17
Source File: SignalFxReporterTest.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
private void testReporterWithDetails(){
	
	StoredDataPointReceiver dbank = new StoredDataPointReceiver();
       assertEquals(0, dbank.addDataPoints.size());

       Set<SignalFxReporter.MetricDetails> detailsToAdd = new HashSet<SignalFxReporter.MetricDetails>();
       detailsToAdd.add(SignalFxReporter.MetricDetails.STD_DEV);
       detailsToAdd.add(SignalFxReporter.MetricDetails.MEAN);
       
       MetricsRegistry metricRegistery = new MetricsRegistry();
       SignalFxReporter reporter = new SignalFxReporter.Builder(metricRegistery, new StaticAuthToken(""), "myserver")
               .setDataPointReceiverFactory(new StaticDataPointReceiverFactory(dbank))
               .setDetailsToAdd(
           		ImmutableSet.of(
       				SignalFxReporter.MetricDetails.COUNT,
       				SignalFxReporter.MetricDetails.MIN, 
       				SignalFxReporter.MetricDetails.MAX
           		)
               )
               .setName("testReporter")
               .setDefaultSourceName("defaultSource")
               .useLocalTime(false)
               .setOnSendErrorHandlerCollection(
               		Collections.<OnSendErrorHandler>singleton(new OnSendErrorHandler(){
                       	public void handleError(MetricError error){
                       		System.out.println("" + error.getMessage());
                       	}
                       })
               )
               .setFilter(MetricPredicate.ALL)
               .setRateUnit(TimeUnit.SECONDS)
               .setDetailsToAdd(detailsToAdd)
               .build();
       
       final MetricMetadata metricMetadata = reporter.getMetricMetadata();
       
       MetricName histogramName = new MetricName("group1", "type1", "histogram");
       Histogram histogram = metricRegistery.newHistogram(histogramName, true);
       histogram.update(10);
       histogram.update(14);
       histogram.update(7);
       
       metricMetadata.forMetric(histogram)
       	.withMetricName("histogram")
       	.withSourceName("histogram_source")
       	.withMetricType(SignalFxProtocolBuffers.MetricType.GAUGE)
       	.withDimension("key", "value");
       
       reporter.report();
       
       assertEquals(2, dbank.addDataPoints.size());
	
}
 
Example #18
Source File: SignalFxReporterFactory.java    From riposte with Apache License 2.0 3 votes vote down vote up
/**
 * Creates a new instance with the given SignalFX API key (auth token), the given reporter configurator function,
 * and the given reporting frequency. The SignalFx {@link SignalFxReporter.Builder} will be passed through the given
 * function before building the reporter, allowing you to customize anything you want about the reporter. For
 * example:
 *
 * <pre>
 *      new SignalFxReporterFactory(
 *          "mySignalFxApiKey",
 *          (reporterConfig) -> reporterConfig.addDimension("foo", "bar")
 *                                            .addUniqueDimension("host_foo", "host_bar")
 *                                            .setDetailsToAdd(SignalFxReporter.MetricDetails.ALL),
 *          Pair.of(10L, TimeUnit.SECONDS)
 *      );
 * </pre>
 *
 * <p>If you pass in null for the reporterConfigurator argument then {@link Function#identity()} will be used for
 * a fully default SignalFx reporter.
 *
 * <p>The {@code reportingFrequency} passed in will be used to set what is returned by the {@link #getInterval()}
 * and {@link #getTimeUnit()} methods, which controls the reporting frequency of the SignalFx reporter. If you pass
 * in null for reportingFrequency then {@link #DEFAULT_REPORTING_FREQUENCY} will be used (10 seconds).
 *
 * @param signalFxApiKey The SignalFx API key (auth token) to use when reporting data to SignalFx.
 * @param reporterConfigurator A function that performs any custom reporter configuration you want done on the
 * resulting {@link SignalFxReporter}. If you pass in null for the reporterConfigurator argument then {@link
 * Function#identity()} will be used for a fully default SignalFx reporter.
 * @param reportingFrequency The reporting frequency for the SignalFx reporter. If you pass in null then
 * {@link #DEFAULT_REPORTING_FREQUENCY} will be used (10 seconds).
 */
public SignalFxReporterFactory(String signalFxApiKey,
                               Function<SignalFxReporter.Builder, SignalFxReporter.Builder> reporterConfigurator,
                               Pair<Long, TimeUnit> reportingFrequency) {
    if (reporterConfigurator == null)
        reporterConfigurator = Function.identity();

    if (reportingFrequency == null)
        reportingFrequency = DEFAULT_REPORTING_FREQUENCY;
    
    this.signalFxApiKey = signalFxApiKey;
    this.reporterConfigurator = reporterConfigurator;
    this.reportingFrequencyInterval = reportingFrequency.getLeft();
    this.reportingFrequencyTimeUnit = reportingFrequency.getRight();
}
 
Example #19
Source File: SignalFxEndpointMetricsHandler.java    From riposte with Apache License 2.0 3 votes vote down vote up
/**
 * Create a new instance for the given {@link SignalFxReporter} reporting with the given frequency. The default
 * metric dimension configurator will be used to set up the endpoint timer dimensions:
 * {@link #DEFAULT_REQUEST_LATENCY_TIMER_DIMENSION_CONFIGURATOR}.
 *
 * <p>IMPORTANT NOTE: The given {@code reportingFrequency} must match whatever you used when starting the given
 * {@link SignalFxReporter} (see {@link SignalFxReporter#start(long, TimeUnit)}), or else the data reported to
 * SignalFx may not make sense.
 *
 * @param signalFxReporter The {@link SignalFxReporter} to use for metric metadata. Cannot be null.
 * @param reportingFrequency The frequency that the given {@code signalFxReporter} reports its data to SignalFx.
 * Cannot be null, and the individual values inside the pair cannot be null.
 * @param metricRegistry The {@link MetricRegistry} being used for the application that the endpoint timers should
 * be registered under. Cannot be null.
 */
public SignalFxEndpointMetricsHandler(SignalFxReporter signalFxReporter,
                                      Pair<Long, TimeUnit> reportingFrequency,
                                      MetricRegistry metricRegistry) {
    this(extractMetricMetadataFromSignalFxReporter(signalFxReporter),
         metricRegistry,
         generateDefaultTimerMetricBuilder(reportingFrequency),
         null);
}