Search in sources :

Example 1 with FriendlyException

use of com.microsoft.applicationinsights.agent.internal.common.FriendlyException 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 2 with FriendlyException

use of com.microsoft.applicationinsights.agent.internal.common.FriendlyException in project ApplicationInsights-Java by microsoft.

the class ConfigurationBuilder method getConfigurationFromEnvVar.

static Configuration getConfigurationFromEnvVar(String content, boolean strict) {
    Configuration configuration;
    ObjectMapper mapper = new ObjectMapper();
    if (!strict) {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    try {
        configuration = mapper.readValue(content, Configuration.class);
    } catch (UnrecognizedPropertyException ex) {
        if (strict) {
            // Try extracting the configuration without failOnUnknown
            configuration = getConfigurationFromEnvVar(content, false);
            // cannot use logger before loading configuration, so need to store warning messages locally
            // until logger is initialized
            configurationLogger.warn(getJsonEncodingExceptionMessageForEnvVar(ex.getMessage()));
        } else {
            throw new FriendlyException(getJsonEncodingExceptionMessageForEnvVar(ex.getMessage()), "Learn more about configuration options here: https://go.microsoft.com/fwlink/?linkid=2153358");
        }
    } catch (JsonMappingException | JsonParseException ex) {
        throw new FriendlyException(getJsonEncodingExceptionMessageForEnvVar(ex.getMessage()), "Learn more about configuration options here: https://go.microsoft.com/fwlink/?linkid=2153358");
    } catch (Exception e) {
        throw new ConfigurationException("Error parsing configuration from env var: " + APPLICATIONINSIGHTS_CONFIGURATION_CONTENT, e);
    }
    if (configuration.connectionString != null) {
        throw new ConfigurationException("\"connectionString\" attribute is not supported inside of " + APPLICATIONINSIGHTS_CONFIGURATION_CONTENT + ", please use " + APPLICATIONINSIGHTS_CONNECTION_STRING_ENV + " to specify the connection string");
    }
    return configuration;
}
Also used : JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) FriendlyException(com.microsoft.applicationinsights.agent.internal.common.FriendlyException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) IOException(java.io.IOException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) FriendlyException(com.microsoft.applicationinsights.agent.internal.common.FriendlyException)

Example 3 with FriendlyException

use of com.microsoft.applicationinsights.agent.internal.common.FriendlyException in project ApplicationInsights-Java by microsoft.

the class MainEntryPoint method start.

// TODO turn this into an interceptor
@SuppressWarnings("SystemOut")
public static void start(Instrumentation instrumentation, File javaagentFile) {
    boolean success = false;
    Logger startupLogger = null;
    try {
        if (DEBUG_SIGNED_JAR_ACCESS) {
            JarVerifierClassFileTransformer transformer = new JarVerifierClassFileTransformer();
            instrumentation.addTransformer(transformer, true);
            instrumentation.retransformClasses(Class.forName("java.util.jar.JarVerifier"));
            instrumentation.removeTransformer(transformer);
        }
        Path agentPath = javaagentFile.toPath();
        // need to initialize version before initializing DiagnosticsHelper
        agentVersion = SdkVersionFinder.initVersion(agentPath);
        DiagnosticsHelper.setAgentJarFile(agentPath);
        // configuration is only read this early in order to extract logging configuration
        rpConfiguration = RpConfigurationBuilder.create(agentPath);
        configuration = ConfigurationBuilder.create(agentPath, rpConfiguration);
        startupLogger = configureLogging(configuration.selfDiagnostics, agentPath);
        StatusFile.startupLogger = startupLogger;
        ConfigurationBuilder.logConfigurationWarnMessages();
        MDC.put(DiagnosticsHelper.MDC_PROP_OPERATION, "Startup");
        // TODO convert to agent builder concept
        AppIdSupplier appIdSupplier = AiComponentInstaller.beforeAgent(instrumentation);
        StartAppIdRetrieval.setAppIdSupplier(appIdSupplier);
        AgentInstaller.installBytebuddyAgent(instrumentation, ConfigOverride.getConfig(configuration), false);
        startupLogger.info("ApplicationInsights Java Agent {} started successfully (PID {})", agentVersion, new PidFinder().getValue());
        startupLogger.info("Java version: {}, vendor: {}, home: {}", System.getProperty("java.version"), System.getProperty("java.vendor"), System.getProperty("java.home"));
        success = true;
        LoggerFactory.getLogger(DiagnosticsHelper.DIAGNOSTICS_LOGGER_NAME).info("Application Insights Codeless Agent {} Attach Successful", agentVersion);
    } catch (ThreadDeath td) {
        throw td;
    } catch (Throwable t) {
        FriendlyException friendlyException = getFriendlyException(t);
        String banner = "ApplicationInsights Java Agent " + agentVersion + " failed to start (PID " + new PidFinder().getValue() + ")";
        if (friendlyException != null) {
            logErrorMessage(startupLogger, friendlyException.getMessageWithBanner(banner), true, t, javaagentFile);
        } else {
            logErrorMessage(startupLogger, banner, false, t, javaagentFile);
        }
    } finally {
        try {
            StatusFile.putValueAndWrite("AgentInitializedSuccessfully", success, startupLogger != null);
        } catch (Throwable t) {
            if (startupLogger != null) {
                startupLogger.error("Error writing status.json", t);
            } else {
                t.printStackTrace();
            }
        }
        MDC.clear();
    }
}
Also used : Path(java.nio.file.Path) PidFinder(com.microsoft.applicationinsights.agent.bootstrap.diagnostics.PidFinder) Logger(org.slf4j.Logger) FriendlyException(com.microsoft.applicationinsights.agent.internal.common.FriendlyException)

Example 4 with FriendlyException

use of com.microsoft.applicationinsights.agent.internal.common.FriendlyException in project ApplicationInsights-Java by microsoft.

the class MainEntryPointTest method getFriendlyExceptionTest.

@Test
void getFriendlyExceptionTest() {
    FriendlyException friendlyException = MainEntryPoint.getFriendlyException(new FriendlyException("<message>", "<action>"));
    FriendlyException nonFriendlyException = MainEntryPoint.getFriendlyException(new IllegalArgumentException());
    FriendlyException nestedFriendlyException = MainEntryPoint.getFriendlyException(new RuntimeException("Run time Exception", new FriendlyException("<message>", "<action>")));
    FriendlyException nestedNonFriendlyException = MainEntryPoint.getFriendlyException(new RuntimeException("Run time Exception", new IllegalArgumentException()));
    assertThat(friendlyException).isNotNull();
    assertThat(nonFriendlyException).isNull();
    assertThat(nestedFriendlyException).isNotNull();
    assertThat(nestedNonFriendlyException).isNull();
}
Also used : FriendlyException(com.microsoft.applicationinsights.agent.internal.common.FriendlyException) Test(org.junit.jupiter.api.Test)

Aggregations

FriendlyException (com.microsoft.applicationinsights.agent.internal.common.FriendlyException)4 JsonParseException (com.fasterxml.jackson.core.JsonParseException)1 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 UnrecognizedPropertyException (com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException)1 PidFinder (com.microsoft.applicationinsights.agent.bootstrap.diagnostics.PidFinder)1 Configuration (com.microsoft.applicationinsights.agent.internal.configuration.Configuration)1 ProcessorConfig (com.microsoft.applicationinsights.agent.internal.configuration.Configuration.ProcessorConfig)1 ProfilerConfiguration (com.microsoft.applicationinsights.agent.internal.configuration.Configuration.ProfilerConfiguration)1 RpConfiguration (com.microsoft.applicationinsights.agent.internal.configuration.RpConfiguration)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 TelemetryClient (com.microsoft.applicationinsights.agent.internal.telemetry.TelemetryClient)1 AiLazyConfiguration (io.opentelemetry.instrumentation.api.aisdk.AiLazyConfiguration)1 File (java.io.File)1 IOException (java.io.IOException)1 Path (java.nio.file.Path)1