Search in sources :

Example 1 with RpConfiguration

use of com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration in project ApplicationInsights-Java by microsoft.

the class RpConfigurationPollingTest method shouldUpdate.

@Test
void shouldUpdate() throws URISyntaxException {
    // given
    RpConfiguration rpConfiguration = new RpConfiguration();
    rpConfiguration.connectionString = "InstrumentationKey=11111111-1111-1111-1111-111111111111";
    rpConfiguration.sampling.percentage = 90;
    rpConfiguration.configPath = Paths.get(RpConfigurationPollingTest.class.getResource("/applicationinsights-rp.json").toURI());
    rpConfiguration.lastModifiedTime = 0;
    TelemetryClient telemetryClient = TelemetryClient.createForTest();
    telemetryClient.setConnectionString("InstrumentationKey=00000000-0000-0000-0000-000000000000");
    AppIdSupplier appIdSupplier = new AppIdSupplier(telemetryClient);
    BytecodeUtilImpl.samplingPercentage = 100;
    // pre-check
    assertThat(telemetryClient.getInstrumentationKey()).isEqualTo("00000000-0000-0000-0000-000000000000");
    assertThat(BytecodeUtilImpl.samplingPercentage).isEqualTo(100);
    assertThat(getCurrentSamplingPercentage()).isEqualTo(100);
    // when
    new RpConfigurationPolling(rpConfiguration, new Configuration(), telemetryClient, appIdSupplier).run();
    // then
    assertThat(telemetryClient.getInstrumentationKey()).isEqualTo("00000000-0000-0000-0000-000000000000");
    assertThat(BytecodeUtilImpl.samplingPercentage).isEqualTo(10);
    assertThat(getCurrentSamplingPercentage()).isEqualTo(10);
}
Also used : Configuration(com.microsoft.applicationinsights.agent.internal.configuration.Configuration) RpConfiguration(com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration) RpConfiguration(com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration) TelemetryClient(com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient) Test(org.junit.jupiter.api.Test)

Example 2 with RpConfiguration

use of com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration in project ApplicationInsights-Java by microsoft.

the class RpConfigurationPollingTest method shouldBePopulatedByEnvVars.

@Test
void shouldBePopulatedByEnvVars() throws URISyntaxException {
    // given
    RpConfiguration rpConfiguration = new RpConfiguration();
    rpConfiguration.connectionString = "InstrumentationKey=11111111-1111-1111-1111-111111111111";
    rpConfiguration.sampling.percentage = 90;
    rpConfiguration.configPath = Paths.get(RpConfigurationPollingTest.class.getResource("/applicationinsights-rp.json").toURI());
    rpConfiguration.lastModifiedTime = 0;
    TelemetryClient telemetryClient = TelemetryClient.createForTest();
    telemetryClient.setConnectionString("InstrumentationKey=00000000-0000-0000-0000-000000000000");
    AppIdSupplier appIdSupplier = new AppIdSupplier(telemetryClient);
    BytecodeUtilImpl.samplingPercentage = 100;
    envVars.set("APPLICATIONINSIGHTS_CONNECTION_STRING", "InstrumentationKey=00000000-0000-0000-0000-000000000000");
    envVars.set("APPLICATIONINSIGHTS_SAMPLING_PERCENTAGE", "90");
    // pre-check
    assertThat(telemetryClient.getInstrumentationKey()).isEqualTo("00000000-0000-0000-0000-000000000000");
    assertThat(BytecodeUtilImpl.samplingPercentage).isEqualTo(100);
    assertThat(getCurrentSamplingPercentage()).isEqualTo(100);
    // when
    new RpConfigurationPolling(rpConfiguration, new Configuration(), telemetryClient, appIdSupplier).run();
    // then
    assertThat(telemetryClient.getInstrumentationKey()).isEqualTo("00000000-0000-0000-0000-000000000000");
    assertThat(BytecodeUtilImpl.samplingPercentage).isEqualTo(100);
    assertThat(getCurrentSamplingPercentage()).isEqualTo(100);
}
Also used : Configuration(com.microsoft.applicationinsights.agent.internal.configuration.Configuration) RpConfiguration(com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration) RpConfiguration(com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration) TelemetryClient(com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient) Test(org.junit.jupiter.api.Test)

Example 3 with RpConfiguration

use of com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration 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 4 with RpConfiguration

use of com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration in project ApplicationInsights-Java by microsoft.

the class RpConfigurationPolling method run.

@Override
public void run() {
    if (rpConfiguration.configPath == null) {
        logger.warn("rp configuration path is null");
        return;
    }
    if (!Files.exists(rpConfiguration.configPath)) {
        logger.warn("rp configuration path doesn't exist: {}", rpConfiguration.configPath);
        return;
    }
    try {
        BasicFileAttributes attributes = Files.readAttributes(rpConfiguration.configPath, BasicFileAttributes.class);
        FileTime fileTime = attributes.lastModifiedTime();
        if (rpConfiguration.lastModifiedTime != fileTime.toMillis()) {
            rpConfiguration.lastModifiedTime = fileTime.toMillis();
            RpConfiguration newRpConfiguration = RpConfigurationBuilder.loadJsonConfigFile(rpConfiguration.configPath);
            ConfigurationBuilder.overlayFromEnv(newRpConfiguration);
            if (!newRpConfiguration.connectionString.equals(rpConfiguration.connectionString)) {
                logger.debug("Connection string from the JSON config file is overriding the previously configured connection string.");
                telemetryClient.setConnectionString(newRpConfiguration.connectionString);
                if (!Strings.isNullOrEmpty(newRpConfiguration.connectionString)) {
                    appIdSupplier.startAppIdRetrieval();
                }
            }
            if (newRpConfiguration.sampling.percentage != rpConfiguration.sampling.percentage) {
                logger.debug("Updating sampling percentage from {} to {}", rpConfiguration.sampling.percentage, newRpConfiguration.sampling.percentage);
                float roundedSamplingPercentage = ConfigurationBuilder.roundToNearest(newRpConfiguration.sampling.percentage);
                DelegatingSampler.getInstance().setDelegate(Samplers.getSampler(roundedSamplingPercentage, configuration));
                BytecodeUtilImpl.samplingPercentage = roundedSamplingPercentage;
                rpConfiguration.sampling.percentage = newRpConfiguration.sampling.percentage;
            }
            rpConfiguration = newRpConfiguration;
        }
    } catch (IOException e) {
        logger.error("Error occurred when polling json config file: {}", e.getMessage(), e);
    }
}
Also used : FileTime(java.nio.file.attribute.FileTime) RpConfiguration(com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Aggregations

RpConfiguration (com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration)4 Configuration (com.microsoft.applicationinsights.agent.internal.configuration.Configuration)3 TelemetryClient (com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient)3 Test (org.junit.jupiter.api.Test)2 FriendlyException (com.microsoft.applicationinsights.agent.internal.common.FriendlyException)1 ProcessorConfig (com.microsoft.applicationinsights.agent.internal.configuration.Configuration.ProcessorConfig)1 ProfilerConfiguration (com.microsoft.applicationinsights.agent.internal.configuration.Configuration.ProfilerConfiguration)1 BytecodeUtilImpl (com.microsoft.applicationinsights.agent.internal.legacysdk.BytecodeUtilImpl)1 StatsbeatModule (com.microsoft.applicationinsights.agent.internal.statsbeat.StatsbeatModule)1 ConnectionString (com.microsoft.applicationinsights.agent.internal.telemetry.ConnectionString)1 InvalidConnectionStringException (com.microsoft.applicationinsights.agent.internal.telemetry.InvalidConnectionStringException)1 MetricFilter (com.microsoft.applicationinsights.agent.internal.telemetry.MetricFilter)1 AiLazyConfiguration (io.opentelemetry.instrumentation.api.aisdk.AiLazyConfiguration)1 File (java.io.File)1 IOException (java.io.IOException)1 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)1 FileTime (java.nio.file.attribute.FileTime)1 CountDownLatch (java.util.concurrent.CountDownLatch)1