com.signalfx.metrics.auth.StaticAuthToken Java Examples

The following examples show how to use com.signalfx.metrics.auth.StaticAuthToken. 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: SignalFxMeterRegistry.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Override
protected void publish() {
    final long timestamp = clock.wallTime();

    AggregateMetricSender metricSender = new AggregateMetricSender(this.config.source(),
            this.dataPointReceiverFactory, this.eventReceiverFactory,
            new StaticAuthToken(this.config.accessToken()), this.onSendErrorHandlerCollection);

    for (List<Meter> batch : MeterPartition.partition(this, config.batchSize())) {
        try (AggregateMetricSender.Session session = metricSender.createSession()) {
            batch.stream()
                    .map(meter -> meter.match(
                            this::addGauge,
                            this::addCounter,
                            this::addTimer,
                            this::addDistributionSummary,
                            this::addLongTaskTimer,
                            this::addTimeGauge,
                            this::addFunctionCounter,
                            this::addFunctionTimer,
                            this::addMeter))
                    .flatMap(builders -> builders.map(builder -> builder.setTimestamp(timestamp).build()))
                    .forEach(session::setDatapoint);

            logger.debug("successfully sent {} metrics to SignalFx.", batch.size());
        } catch (Throwable e) {
            logger.warn("failed to send metrics", e);
        }
    }
}
 
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: 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 #4
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 #5
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 #6
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 #7
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 #8
Source File: SignalFxReporter.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
public Builder(MetricsRegistry registry, String authToken) {
    this(registry, new StaticAuthToken(authToken));
}
 
Example #9
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 #10
Source File: SignalFxReporter.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
public Builder(MetricRegistry registry, String authToken) {
    this(registry, new StaticAuthToken(authToken));
}