com.signalfx.metrics.errorhandler.OnSendErrorHandler Java Examples

The following examples show how to use com.signalfx.metrics.errorhandler.OnSendErrorHandler. 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: SignalFxMetricExporterTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  endpoint = new URI("http://example.com");

  Mockito.when(
          factory.create(
              Mockito.any(URI.class), Mockito.anyString(), Mockito.any(OnSendErrorHandler.class)))
      .thenAnswer(
          new Answer<AggregateMetricSender>() {
            @Override
            public AggregateMetricSender answer(InvocationOnMock invocation) {
              Object[] args = invocation.getArguments();
              AggregateMetricSender sender =
                  SignalFxMetricsSenderFactory.DEFAULT.create(
                      (URI) args[0], (String) args[1], (OnSendErrorHandler) args[2]);
              AggregateMetricSender spy = Mockito.spy(sender);
              doReturn(session).when(spy).createSession();
              return spy;
            }
          });
}
 
Example #2
Source File: SignalFxMetricsSenderFactory.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("nullness")
public AggregateMetricSender create(
    URI endpoint, String token, OnSendErrorHandler errorHandler) {
  SignalFxEndpoint sfx =
      new SignalFxEndpoint(endpoint.getScheme(), endpoint.getHost(), endpoint.getPort());
  return new AggregateMetricSender(
      null,
      new HttpDataPointProtobufReceiverFactory(sfx).setVersion(2),
      new HttpEventProtobufReceiverFactory(sfx),
      new StaticAuthToken(token),
      Collections.singleton(errorHandler));
}
 
Example #3
Source File: AggregateMetricSender.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
public AggregateMetricSender(String defaultSourceName,
                             DataPointReceiverFactory dataPointReceiverFactory,
                             AuthToken authToken,
                             Collection<OnSendErrorHandler> onSendErrorHandlerCollection) {
    this(defaultSourceName, dataPointReceiverFactory, null, authToken,
            onSendErrorHandlerCollection);
}
 
Example #4
Source File: AggregateMetricSender.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
public AggregateMetricSender(String defaultSourceName,
                             DataPointReceiverFactory dataPointReceiverFactory,
                             EventReceiverFactory eventReceiverFactory, AuthToken authToken,
                             Collection<OnSendErrorHandler> onSendErrorHandlerCollection) {
    this.defaultSourceName = defaultSourceName;
    this.dataPointReceiverFactory = dataPointReceiverFactory;
    this.eventReceiverFactory = eventReceiverFactory;
    this.authToken = authToken;
    this.onSendErrorHandlerCollection = onSendErrorHandlerCollection;

    this.registeredMetricPairs = new HashSet<String>();
}
 
Example #5
Source File: AggregateMetricSender.java    From signalfx-java with Apache License 2.0 5 votes vote down vote up
private void communicateError(String message, MetricErrorType code,
                              SignalFxMetricsException signalfxMetricsException) {
    for (OnSendErrorHandler onSendErrorHandler : onSendErrorHandlerCollection) {
        onSendErrorHandler
                .handleError(new MetricErrorImpl(message, code, signalfxMetricsException));
    }
}
 
Example #6
Source File: SignalFxOutputPlugin.java    From ffwd with Apache License 2.0 4 votes vote down vote up
@Override
public Module module(final Key<PluginSink> key, final String id) {
    return new OutputPluginModule(id) {
        @Provides
        Supplier<AggregateMetricSender> sender() {
            final Collection<OnSendErrorHandler> handlers = ImmutableList.of(metricError -> {
                log.error(metricError.toString());
            });

            return () -> {
                final SignalFxEndpoint endpoint = new SignalFxEndpoint();
                final HttpDataPointProtobufReceiverFactory dataPoints =
                    new HttpDataPointProtobufReceiverFactory(endpoint).setVersion(2);

                BasicHttpClientConnectionManager connectionManager =
                    new BasicHttpClientConnectionManager();
                SocketConfig socketConfigWithSoTimeout = SocketConfig
                    .copy(connectionManager.getSocketConfig())
                    .setSoTimeout(soTimeout)
                    .build();
                connectionManager.setSocketConfig(socketConfigWithSoTimeout);
                dataPoints.setHttpClientConnectionManager(connectionManager);

                final EventReceiverFactory events =
                    new HttpEventProtobufReceiverFactory(endpoint);
                final AuthToken auth = new StaticAuthToken(authToken);

                return new AggregateMetricSender(sourceName, dataPoints, events, auth,
                    handlers);
            };
        }

        @Override
        protected void configure() {
            final Key<SignalFxPluginSink> sinkKey =
                Key.get(SignalFxPluginSink.class, Names.named("signalfxSink"));
            bind(sinkKey).to(SignalFxPluginSink.class).in(Scopes.SINGLETON);
            install(wrapPluginSink(sinkKey, key));
            expose(key);
        }
    };
}
 
Example #7
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 #8
Source File: ProtobufExample.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        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 signalFxEndpoint = new SignalFxEndpoint(hostUrl.getProtocol(),
                hostUrl.getHost(), hostUrl.getPort());

        AggregateMetricSender mf = new AggregateMetricSender("test.SendMetrics",
                new HttpDataPointProtobufReceiverFactory(signalFxEndpoint).setVersion(2),
                new HttpEventProtobufReceiverFactory(signalFxEndpoint),
                new StaticAuthToken(auth_token),
                Collections.<OnSendErrorHandler> singleton(new OnSendErrorHandler() {
                    @Override
                    public void handleError(MetricError metricError) {
                        System.out.println("Unable to POST metrics: " + metricError.getMessage());
                    }
                }));

        int j = 0;
        while(true) {
            // session should be recreated after every sessionObj.close().
            AggregateMetricSender.Session i = mf.createSession();

            System.out.println("Setting datapoint " + (j));
            i.setDatapoint(
                SignalFxProtocolBuffers.DataPoint.newBuilder()
                        .setMetric("test.cpu")
                        .setMetricType(SignalFxProtocolBuffers.MetricType.GAUGE)
                        .setValue(
                                SignalFxProtocolBuffers.Datum.newBuilder()
                                        .setIntValue(j%3))
                        .addDimensions(getDimensionAsProtobuf("host", "myhost"))
                        .addDimensions(getDimensionAsProtobuf("service", "myservice"))
                        .build());
            
            if(j%3 == 0){
                System.out.println("Setting Event  " + j/3);
                i.setEvent(
                    SignalFxProtocolBuffers.Event.newBuilder()
                        .setEventType("Deployments")
                        .setCategory(SignalFxProtocolBuffers.EventCategory.USER_DEFINED)
                        .setTimestamp(System.currentTimeMillis())
                        .addDimensions(getDimensionAsProtobuf("host", "myhost"))
                        .addDimensions(getDimensionAsProtobuf("service", "myservice"))
                        .addProperties(getPropertyAsProtobuf("version", j/3))
                        .build());
            } 

            System.out.println("Flushing set datapoints and events");
            i.close(); // close session resource to flush the set datapoints and events
            j++;
            Thread.sleep(500);
        }
    }
 
Example #9
Source File: SendMetrics.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Properties prop = new Properties();
    prop.load(new FileInputStream("auth.properties"));

    String token = Preconditions.checkNotNull(prop.getProperty("auth"), "No auth token set");
    String host = Preconditions.checkNotNull(prop.getProperty("host"), "No endpoint set");
    URL hostUrl = new URL(host);

    System.out.printf("Sending metrics to %s (X-SF-Token: %s) ...%n", hostUrl, token);

    SignalFxReceiverEndpoint endpoint = new SignalFxEndpoint(
            hostUrl.getProtocol(),
            hostUrl.getHost(),
            hostUrl.getPort());

    OnSendErrorHandler errorHandler = new OnSendErrorHandler() {
        @Override
        public void handleError(MetricError metricError) {
            System.err.printf("Error %s sending data: %s%n",
                    metricError.getMetricErrorType(),
                    metricError.getMessage());
            metricError.getException().printStackTrace(System.err);
        }
    };

    AggregateMetricSender mf = new AggregateMetricSender(
            "test.SendMetrics",
            new HttpDataPointProtobufReceiverFactory(endpoint).setVersion(2),
            new StaticAuthToken(token),
            Collections.singletonList(errorHandler));

    while (true) {
        Thread.sleep(250);
        AggregateMetricSender.Session i = mf.createSession();
        try {
            i.setDatapoint(SignalFxProtocolBuffers.DataPoint.newBuilder()
                    .setMetric("curtime")
                    .setValue(SignalFxProtocolBuffers.Datum.newBuilder()
                            .setIntValue(System.currentTimeMillis()))
                    .addDimensions(
                            SignalFxProtocolBuffers.Dimension.newBuilder()
                                    .setKey("source")
                                    .setValue("java")).build());
        } finally {
            System.out.printf("Sending data at %s%n", new Date());
            i.close();
        }
    }
}
 
Example #10
Source File: AggregateMetricSender.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
public AggregateMetricSender(String defaultSourceName,
                             EventReceiverFactory eventReceiverFactory, AuthToken authToken,
                             Collection<OnSendErrorHandler> onSendErrorHandlerCollection) {
    this(defaultSourceName, null, eventReceiverFactory, authToken,
            onSendErrorHandlerCollection);
}
 
Example #11
Source File: SignalFxReporter.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
public Builder setOnSendErrorHandlerCollection(
        Collection<OnSendErrorHandler> onSendErrorHandlerCollection) {
    this.onSendErrorHandlerCollection = onSendErrorHandlerCollection;
    return this;
}
 
Example #12
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 #13
Source File: SignalFxReporter.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
public Builder setOnSendErrorHandlerCollection(
        Collection<OnSendErrorHandler> onSendErrorHandlerCollection) {
    this.onSendErrorHandlerCollection = onSendErrorHandlerCollection;
    return this;
}
 
Example #14
Source File: SignalFxMetricsSenderFactory.java    From opencensus-java with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new SignalFx metrics sender instance.
 *
 * @param endpoint The SignalFx ingest endpoint URL.
 * @param token The SignalFx ingest token.
 * @param errorHandler An {@link OnSendErrorHandler} through which errors when sending data to
 *     SignalFx will be communicated.
 * @return The created {@link AggregateMetricSender} instance.
 */
AggregateMetricSender create(URI endpoint, String token, OnSendErrorHandler errorHandler);