Search in sources :

Example 11 with TelemetryClient

use of com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient in project ApplicationInsights-Java by microsoft.

the class CustomDimensionsTest method testCustomDimensionsConfigShouldNotImpactStatsbeatCustomDimensions.

@Test
public void testCustomDimensionsConfigShouldNotImpactStatsbeatCustomDimensions() {
    Configuration configuration = new Configuration();
    configuration.customDimensions.put("firstTag", "abc");
    configuration.customDimensions.put("secondTag", "def");
    TelemetryClient telemetryClient = TelemetryClient.builder().setCustomDimensions(configuration.customDimensions).build();
    NetworkStatsbeat networkStatsbeat = new NetworkStatsbeat();
    TelemetryItem networkItem = networkStatsbeat.createStatsbeatTelemetry(telemetryClient, "test-network", 0.0);
    assertThat(networkItem.getTags()).doesNotContainKey("firstTag");
    assertThat(networkItem.getTags()).doesNotContainKey("secondTag");
    assertThat(((MetricsData) networkItem.getData().getBaseData()).getProperties()).doesNotContainKey("firstTag");
    assertThat(((MetricsData) networkItem.getData().getBaseData()).getProperties()).doesNotContainKey("secondTag");
    AttachStatsbeat attachStatsbeat = new AttachStatsbeat(new CustomDimensions());
    TelemetryItem attachItem = attachStatsbeat.createStatsbeatTelemetry(telemetryClient, "test-attach", 0.0);
    assertThat(attachItem.getTags()).doesNotContainKey("firstTag");
    assertThat(attachItem.getTags()).doesNotContainKey("secondTag");
    assertThat(((MetricsData) attachItem.getData().getBaseData()).getProperties()).doesNotContainKey("firstTag");
    assertThat(((MetricsData) attachItem.getData().getBaseData()).getProperties()).doesNotContainKey("secondTag");
    FeatureStatsbeat featureStatsbeat = new FeatureStatsbeat(new CustomDimensions(), FeatureType.FEATURE);
    TelemetryItem featureItem = featureStatsbeat.createStatsbeatTelemetry(telemetryClient, "test-feature", 0.0);
    assertThat(featureItem.getTags()).doesNotContainKey("firstTag");
    assertThat(featureItem.getTags()).doesNotContainKey("secondTag");
    assertThat(((MetricsData) featureItem.getData().getBaseData()).getProperties()).doesNotContainKey("firstTag");
    assertThat(((MetricsData) featureItem.getData().getBaseData()).getProperties()).doesNotContainKey("secondTag");
}
Also used : MetricsData(com.microsoft.applicationinsights.agent.internal.exporter.models.MetricsData) Configuration(com.microsoft.applicationinsights.agent.internal.configuration.Configuration) TelemetryItem(com.microsoft.applicationinsights.agent.internal.exporter.models.TelemetryItem) TelemetryClient(com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient) Test(org.junit.jupiter.api.Test)

Example 12 with TelemetryClient

use of com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient in project ApplicationInsights-Java by microsoft.

the class OpenTelemetryConfigurer method createExporter.

private static BatchSpanProcessor createExporter(Configuration configuration) {
    List<ProcessorConfig> processors = configuration.preview.processors.stream().filter(processor -> processor.type != Configuration.ProcessorType.METRIC_FILTER).collect(Collectors.toCollection(ArrayList::new));
    // Reversing the order of processors before passing it to SpanProcessor
    Collections.reverse(processors);
    SpanExporter currExporter = new Exporter(TelemetryClient.getActive(), configuration.preview.captureHttpServer4xxAsError);
    // flushing TelemetryClient
    if (!processors.isEmpty()) {
        for (ProcessorConfig processorConfig : processors) {
            switch(processorConfig.type) {
                case ATTRIBUTE:
                    currExporter = new ExporterWithAttributeProcessor(processorConfig, currExporter);
                    break;
                case SPAN:
                    currExporter = new ExporterWithSpanProcessor(processorConfig, currExporter);
                    break;
                case LOG:
                    currExporter = new ExporterWithLogProcessor(processorConfig, currExporter);
                    break;
                default:
                    throw new IllegalStateException("Not an expected ProcessorType: " + processorConfig.type);
            }
        }
        // this is temporary until semantic attributes stabilize and we make breaking change
        // then can use java.util.functions.Predicate<Attributes>
        currExporter = new BackCompatHttpUrlProcessor(currExporter);
    }
    // using BatchSpanProcessor in order to get off of the application thread as soon as possible
    BatchSpanProcessorBuilder builder = BatchSpanProcessor.builder(currExporter);
    String delayMillisStr = System.getenv("APPLICATIONINSIGHTS_PREVIEW_BSP_SCHEDULE_DELAY");
    if (delayMillisStr != null) {
        // experimenting with flushing at small interval instead of using batch size 1
        // (suspect this may be better performance on small containers)
        builder.setScheduleDelay(Duration.ofMillis(Integer.parseInt(delayMillisStr)));
    } else {
        // using batch size 1 because need to convert to SpanData as soon as possible to grab data for
        // live metrics. the real batching is done at a lower level
        builder.setMaxExportBatchSize(1);
    }
    return builder.build();
}
Also used : ConfigProperties(io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties) AiLegacyHeaderSpanProcessor(com.microsoft.applicationinsights.agent.internal.legacyheaders.AiLegacyHeaderSpanProcessor) Samplers(com.microsoft.applicationinsights.agent.internal.sampling.Samplers) SemanticAttributes(io.opentelemetry.semconv.trace.attributes.SemanticAttributes) Attributes(io.opentelemetry.api.common.Attributes) DelegatingPropagator(com.microsoft.applicationinsights.agent.internal.legacyheaders.DelegatingPropagator) ArrayList(java.util.ArrayList) SdkTracerProviderConfigurer(io.opentelemetry.sdk.autoconfigure.spi.traces.SdkTracerProviderConfigurer) ProcessorConfig(com.microsoft.applicationinsights.agent.internal.configuration.Configuration.ProcessorConfig) Duration(java.time.Duration) DelegatingSampler(com.microsoft.applicationinsights.agent.internal.sampling.DelegatingSampler) BatchSpanProcessor(io.opentelemetry.sdk.trace.export.BatchSpanProcessor) Configuration(com.microsoft.applicationinsights.agent.internal.configuration.Configuration) Collection(java.util.Collection) ExporterWithLogProcessor(com.microsoft.applicationinsights.agent.internal.processors.ExporterWithLogProcessor) SpanExporter(io.opentelemetry.sdk.trace.export.SpanExporter) SdkTracerProviderBuilder(io.opentelemetry.sdk.trace.SdkTracerProviderBuilder) Collectors(java.util.stream.Collectors) MySpanData(com.microsoft.applicationinsights.agent.internal.processors.MySpanData) AttributesBuilder(io.opentelemetry.api.common.AttributesBuilder) Exporter(com.microsoft.applicationinsights.agent.internal.exporter.Exporter) List(java.util.List) TelemetryClient(com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient) AutoService(com.google.auto.service.AutoService) SpanData(io.opentelemetry.sdk.trace.data.SpanData) ExporterWithAttributeProcessor(com.microsoft.applicationinsights.agent.internal.processors.ExporterWithAttributeProcessor) ExporterWithSpanProcessor(com.microsoft.applicationinsights.agent.internal.processors.ExporterWithSpanProcessor) BatchSpanProcessorBuilder(io.opentelemetry.sdk.trace.export.BatchSpanProcessorBuilder) Collections(java.util.Collections) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) CompletableResultCode(io.opentelemetry.sdk.common.CompletableResultCode) ExporterWithSpanProcessor(com.microsoft.applicationinsights.agent.internal.processors.ExporterWithSpanProcessor) ExporterWithLogProcessor(com.microsoft.applicationinsights.agent.internal.processors.ExporterWithLogProcessor) ExporterWithAttributeProcessor(com.microsoft.applicationinsights.agent.internal.processors.ExporterWithAttributeProcessor) SpanExporter(io.opentelemetry.sdk.trace.export.SpanExporter) BatchSpanProcessorBuilder(io.opentelemetry.sdk.trace.export.BatchSpanProcessorBuilder) SpanExporter(io.opentelemetry.sdk.trace.export.SpanExporter) Exporter(com.microsoft.applicationinsights.agent.internal.exporter.Exporter) ProcessorConfig(com.microsoft.applicationinsights.agent.internal.configuration.Configuration.ProcessorConfig)

Example 13 with TelemetryClient

use of com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient in project ApplicationInsights-Java by microsoft.

the class AiComponentInstaller method start.

private static AppIdSupplier start(Instrumentation instrumentation) {
    String codelessSdkNamePrefix = getCodelessSdkNamePrefix();
    if (codelessSdkNamePrefix != null) {
        PropertyHelper.setSdkNamePrefix(codelessSdkNamePrefix);
    }
    File javaTmpDir = new File(System.getProperty("java.io.tmpdir"));
    boolean readOnlyFileSystem = false;
    if (javaTmpDir.canRead() && !javaTmpDir.canWrite()) {
        readOnlyFileSystem = true;
    }
    if (!readOnlyFileSystem) {
        File tmpDir = new File(javaTmpDir, "applicationinsights-java");
        if (!tmpDir.exists() && !tmpDir.mkdirs()) {
            throw new IllegalStateException("Could not create directory: " + tmpDir.getAbsolutePath());
        }
    } else {
        startupLogger.info("Detected running on a read-only file system, telemetry will not be stored to disk or retried later on sporadic network failures. If this is unexpected, please check that the process has write access to the temp directory: " + javaTmpDir.getAbsolutePath());
    }
    Configuration config = MainEntryPoint.getConfiguration();
    if (!hasConnectionStringOrInstrumentationKey(config)) {
        if (!"java".equals(System.getenv("FUNCTIONS_WORKER_RUNTIME"))) {
            throw new FriendlyException("No connection string or instrumentation key provided", "Please provide connection string or instrumentation key.");
        }
    }
    // TODO (trask) should configuration validation be performed earlier?
    for (Configuration.SamplingOverride samplingOverride : config.preview.sampling.overrides) {
        samplingOverride.validate();
    }
    for (Configuration.InstrumentationKeyOverride instrumentationKeyOverride : config.preview.instrumentationKeyOverrides) {
        instrumentationKeyOverride.validate();
    }
    for (ProcessorConfig processorConfig : config.preview.processors) {
        processorConfig.validate();
    }
    // validate authentication configuration
    config.preview.authentication.validate();
    String jbossHome = System.getenv("JBOSS_HOME");
    if (!Strings.isNullOrEmpty(jbossHome)) {
        // this is used to delay SSL initialization because SSL initialization triggers loading of
        // java.util.logging (starting with Java 8u231)
        // and JBoss/Wildfly need to install their own JUL manager before JUL is initialized
        LazyHttpClient.safeToInitLatch = new CountDownLatch(1);
        instrumentation.addTransformer(new JulListeningClassFileTransformer(LazyHttpClient.safeToInitLatch));
    }
    if (config.proxy.host != null) {
        LazyHttpClient.proxyHost = config.proxy.host;
        LazyHttpClient.proxyPortNumber = config.proxy.port;
        LazyHttpClient.proxyUsername = config.proxy.username;
        LazyHttpClient.proxyPassword = config.proxy.password;
    }
    List<MetricFilter> metricFilters = config.preview.processors.stream().filter(processor -> processor.type == Configuration.ProcessorType.METRIC_FILTER).map(MetricFilter::new).collect(Collectors.toList());
    Cache<String, String> ikeyEndpointMap = Cache.bounded(100);
    StatsbeatModule statsbeatModule = new StatsbeatModule(ikeyEndpointMap);
    TelemetryClient telemetryClient = TelemetryClient.builder().setCustomDimensions(config.customDimensions).setMetricFilters(metricFilters).setIkeyEndpointMap(ikeyEndpointMap).setStatsbeatModule(statsbeatModule).setReadOnlyFileSystem(readOnlyFileSystem).setGeneralExportQueueSize(config.preview.generalExportQueueCapacity).setMetricsExportQueueSize(config.preview.metricsExportQueueCapacity).setAadAuthentication(config.preview.authentication).build();
    TelemetryClientInitializer.initialize(telemetryClient, config);
    TelemetryClient.setActive(telemetryClient);
    try {
        ConnectionString.updateStatsbeatConnectionString(config.internal.statsbeat.instrumentationKey, config.internal.statsbeat.endpoint, telemetryClient);
    } catch (InvalidConnectionStringException ex) {
        startupLogger.warn("Statsbeat endpoint is invalid. {}", ex.getMessage());
    }
    BytecodeUtilImpl.samplingPercentage = config.sampling.percentage;
    AppIdSupplier appIdSupplier = new AppIdSupplier(telemetryClient);
    AiAppId.setSupplier(appIdSupplier);
    if (config.preview.profiler.enabled) {
        if (readOnlyFileSystem) {
            throw new FriendlyException("Profile is not supported in a read-only file system.", "disable profiler or use a writable file system");
        }
        ProfilerServiceInitializer.initialize(appIdSupplier::get, SystemInformation.getProcessId(), formServiceProfilerConfig(config.preview.profiler), config.role.instance, config.role.name, telemetryClient, formApplicationInsightsUserAgent(), formGcEventMonitorConfiguration(config.preview.gcEvents));
    }
    // this is for Azure Function Linux consumption plan support.
    if ("java".equals(System.getenv("FUNCTIONS_WORKER_RUNTIME"))) {
        AiLazyConfiguration.setAccessor(new LazyConfigurationAccessor(telemetryClient, appIdSupplier));
    }
    // this is currently used by Micrometer instrumentation in addition to 2.x SDK
    BytecodeUtil.setDelegate(new BytecodeUtilImpl());
    Runtime.getRuntime().addShutdownHook(new ShutdownHook(telemetryClient));
    RpConfiguration rpConfiguration = MainEntryPoint.getRpConfiguration();
    if (rpConfiguration != null) {
        RpConfigurationPolling.startPolling(rpConfiguration, config, telemetryClient, appIdSupplier);
    }
    // initialize StatsbeatModule
    statsbeatModule.start(telemetryClient, config);
    // start local File purger scheduler task
    if (!readOnlyFileSystem) {
        LocalFilePurger.startPurging();
    }
    return appIdSupplier;
}
Also used : InvalidConnectionStringException(com.microsoft.applicationinsights.agent.internal.telemetry.InvalidConnectionStringException) AiLazyConfiguration(io.opentelemetry.instrumentation.api.aisdk.AiLazyConfiguration) Configuration(com.microsoft.applicationinsights.agent.internal.configuration.Configuration) RpConfiguration(com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration) ProfilerConfiguration(com.microsoft.applicationinsights.agent.internal.configuration.Configuration.ProfilerConfiguration) ConnectionString(com.microsoft.applicationinsights.agent.internal.telemetry.ConnectionString) CountDownLatch(java.util.concurrent.CountDownLatch) TelemetryClient(com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient) FriendlyException(com.microsoft.applicationinsights.agent.internal.common.FriendlyException) ProcessorConfig(com.microsoft.applicationinsights.agent.internal.configuration.Configuration.ProcessorConfig) BytecodeUtilImpl(com.microsoft.applicationinsights.agent.internal.legacysdk.BytecodeUtilImpl) MetricFilter(com.microsoft.applicationinsights.agent.internal.telemetry.MetricFilter) StatsbeatModule(com.microsoft.applicationinsights.agent.internal.statsbeat.StatsbeatModule) RpConfiguration(com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration) File(java.io.File)

Example 14 with TelemetryClient

use of com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient in project ApplicationInsights-Java by microsoft.

the class LazyConfigurationAccessorTest method disableLazySetWithLazySetOptInOffConnectionStringNullInstrumentationKeyNull.

@Test
// is TRUE"
void disableLazySetWithLazySetOptInOffConnectionStringNullInstrumentationKeyNull() {
    assertThat(LazyConfigurationAccessor.shouldSetConnectionString(false, "true")).isTrue();
    // given
    TelemetryClient telemetryClient = mock(TelemetryClient.class);
    AppIdSupplier appIdSupplier = mock(AppIdSupplier.class);
    LazyConfigurationAccessor lazyConfigurationAccessor = new LazyConfigurationAccessor(telemetryClient, appIdSupplier);
    // when
    lazyConfigurationAccessor.setConnectionString(null, null);
    // then
    verify(telemetryClient, never()).setConnectionString(anyString());
}
Also used : TelemetryClient(com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient) Test(org.junit.jupiter.api.Test)

Example 15 with TelemetryClient

use of com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient in project ApplicationInsights-Java by microsoft.

the class LazyConfigurationAccessorTest method enableLazySetWithLazySetOptInOnConnectionStringNotNullInstrumentationKeyNull.

@Test
// is TRUE"
void enableLazySetWithLazySetOptInOnConnectionStringNotNullInstrumentationKeyNull() {
    assertThat(LazyConfigurationAccessor.shouldSetConnectionString(false, "true")).isTrue();
    // given
    TelemetryClient telemetryClient = mock(TelemetryClient.class);
    AppIdSupplier appIdSupplier = mock(AppIdSupplier.class);
    LazyConfigurationAccessor lazyConfigurationAccessor = new LazyConfigurationAccessor(telemetryClient, appIdSupplier);
    // when
    lazyConfigurationAccessor.setConnectionString(CONNECTION_STRING, null);
    // then
    verify(telemetryClient).setConnectionString(CONNECTION_STRING);
}
Also used : TelemetryClient(com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient) Test(org.junit.jupiter.api.Test)

Aggregations

TelemetryClient (com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient)28 Test (org.junit.jupiter.api.Test)21 TelemetryItem (com.microsoft.applicationinsights.agent.internal.exporter.models.TelemetryItem)7 Configuration (com.microsoft.applicationinsights.agent.internal.configuration.Configuration)6 URI (java.net.URI)5 FinalCounters (com.microsoft.applicationinsights.agent.internal.quickpulse.QuickPulseDataCollector.FinalCounters)4 RpConfiguration (com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration)3 Date (java.util.Date)3 HttpHeaders (com.azure.core.http.HttpHeaders)2 HttpPipeline (com.azure.core.http.HttpPipeline)2 HttpPipelineBuilder (com.azure.core.http.HttpPipelineBuilder)2 MockHttpResponse (com.microsoft.applicationinsights.agent.internal.MockHttpResponse)2 ProcessorConfig (com.microsoft.applicationinsights.agent.internal.configuration.Configuration.ProcessorConfig)2 AiLegacyHeaderSpanProcessor (com.microsoft.applicationinsights.agent.internal.legacyheaders.AiLegacyHeaderSpanProcessor)2 URISyntaxException (java.net.URISyntaxException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)2 Mono (reactor.core.publisher.Mono)2 HttpRequest (com.azure.core.http.HttpRequest)1