void init()

in aws-xray-agent/src/main/java/com/amazonaws/xray/agent/runtime/config/XRaySDKConfiguration.java [173:348]


    void init(AWSXRayRecorderBuilder builder) {
        log.info("Initializing the X-Ray Agent Recorder");

        // Reset to defaults
        if (agentConfiguration == null) {
            agentConfiguration = new AgentConfiguration();
        }

        this.awsServiceHandlerManifest = null;
        this.awsSdkVersion = 0;

        // X-Ray Enabled
        if ("false".equalsIgnoreCase(System.getenv(ENABLED_ENVIRONMENT_VARIABLE_KEY)) ||
                "false".equalsIgnoreCase(System.getProperty(ENABLED_SYSTEM_PROPERTY_KEY)) ||
                !agentConfiguration.isTracingEnabled())
        {
            log.info("Instrumentation via the X-Ray Agent has been disabled by user configuration.");
            return;
        }

        /*
        Service name is unique since it can still be set via JVM arg. So we check for that first, then proceed with
        the normal priority of properties. Once the JVM arg option is removed, we can remove the first condition
         */
        if (XRayTransactionState.getServiceName() == null) {
            String environmentNameOverrideValue = System.getenv(SegmentNamingStrategy.NAME_OVERRIDE_ENVIRONMENT_VARIABLE_KEY);
            String systemNameOverrideValue = System.getProperty(SegmentNamingStrategy.NAME_OVERRIDE_SYSTEM_PROPERTY_KEY);

            if (StringValidator.isNotNullOrBlank(environmentNameOverrideValue)) {
                XRayTransactionState.setServiceName(environmentNameOverrideValue);
            } else if (StringValidator.isNotNullOrBlank(systemNameOverrideValue)) {
                XRayTransactionState.setServiceName(systemNameOverrideValue);
            } else {
                XRayTransactionState.setServiceName(agentConfiguration.getServiceName());
            }
        }

        // Plugins
        // Do not add plugins in Lambda environment to improve performance & avoid irrelevant metadata
        if (StringValidator.isNullOrBlank(System.getenv(LAMBDA_TASK_ROOT_KEY)) &&
                agentConfiguration.arePluginsEnabled())
        {
            builder.withDefaultPlugins();
        }

        // Context missing
        final ContextMissingStrategy contextMissing;
        try {
            contextMissing = ContextMissingStrategy.valueOf(agentConfiguration.getContextMissingStrategy().toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new InvalidAgentConfigException("Invalid context missing strategy given in X-Ray Agent " +
                    "configuration file: " + agentConfiguration.getContextMissingStrategy());
        }
        switch (contextMissing) {
            case LOG_ERROR:
                builder.withContextMissingStrategy(new LogErrorContextMissingStrategy());
                break;
            case IGNORE_ERROR:
                builder.withContextMissingStrategy(new IgnoreErrorContextMissingStrategy());
                break;
            default:
        }

        // Daemon address
        DaemonConfiguration daemonConfiguration = new DaemonConfiguration();
        try {
            // SDK handles all validation & environment overrides
            daemonConfiguration.setDaemonAddress(agentConfiguration.getDaemonAddress());
            builder.withEmitter(new UDPEmitter(daemonConfiguration));
        } catch (Exception e) {
            throw new InvalidAgentConfigException("Invalid daemon address provided in X-Ray Agent configuration " +
                    "file: " + agentConfiguration.getDaemonAddress(), e);
        }

        // Sampling Rules manifest
        URL samplingManifest = null;
        if (agentConfiguration.getSamplingRulesManifest() != null) {
            try {
                samplingManifest = new File(agentConfiguration.getSamplingRulesManifest()).toURI().toURL();
            } catch (MalformedURLException e) {
                throw new InvalidAgentConfigException("Invalid sampling rules manifest location provided in X-Ray Agent " +
                        "configuration file: " + agentConfiguration.getSamplingRulesManifest(), e);
            }
        }

        // Sampling strategy
        final SamplingStrategy samplingStrategy;
        try {
            samplingStrategy = SamplingStrategy.valueOf(agentConfiguration.getSamplingStrategy().toUpperCase());
        } catch (IllegalArgumentException e) {
            throw new InvalidAgentConfigException("Invalid sampling strategy given in X-Ray Agent " +
                    "configuration file: " + agentConfiguration.getSamplingStrategy());
        }
        switch (samplingStrategy) {
            case ALL:
                builder.withSamplingStrategy(new AllSamplingStrategy());
                break;
            case NONE:
                builder.withSamplingStrategy(new NoSamplingStrategy());
                break;
            case LOCAL:
                builder.withSamplingStrategy(samplingManifest != null ?
                        new LocalizedSamplingStrategy(samplingManifest) :
                        new LocalizedSamplingStrategy());
                break;
            case CENTRAL:
                builder.withSamplingStrategy(samplingManifest != null ?
                        new CentralizedSamplingStrategy(samplingManifest) :
                        new CentralizedSamplingStrategy());
                break;
            default:
        }

        // Trace ID Injection
        if (agentConfiguration.isTraceIdInjection()) {
            // TODO: Include the trace ID injection libraries in the agent JAR and use this reflective approach to
            // only enable them if their corresponding logging libs are in the context classloader
            List<SegmentListener> listeners = getTraceIdInjectorsReflectively(ClassLoader.getSystemClassLoader());

            if (!listeners.isEmpty()) {
                traceIdInjectionConfigured = true;
                for (SegmentListener listener : listeners) {
                    builder.withSegmentListener(listener);
                }
            }
        }

        // Max stack trace length
        if (agentConfiguration.getMaxStackTraceLength() >= 0) {
            builder.withThrowableSerializationStrategy(
                    new DefaultThrowableSerializationStrategy(agentConfiguration.getMaxStackTraceLength()));
        } else {
            throw new InvalidAgentConfigException("Invalid max stack trace length given in X-Ray Agent " +
                    "configuration file: " + agentConfiguration.getMaxStackTraceLength());
        }

        // Streaming threshold
        if (agentConfiguration.getStreamingThreshold() >= 0) {
            builder.withStreamingStrategy(new DefaultStreamingStrategy(agentConfiguration.getStreamingThreshold()));
        } else {
            throw new InvalidAgentConfigException("Invalid streaming threshold given in X-Ray Agent " +
                    "configuration file: " + agentConfiguration.getStreamingThreshold());
        }

        // AWS Service handler manifest
        if (agentConfiguration.getAwsServiceHandlerManifest() != null) {
            int version = agentConfiguration.getAwsSdkVersion();
            if (version != 1 && version != 2) {
                throw new InvalidAgentConfigException("Invalid AWS SDK version given in X-Ray Agent configuration file: " + version);
            } else {
                this.awsSdkVersion = version;
                try {
                    this.awsServiceHandlerManifest = new File(agentConfiguration.getAwsServiceHandlerManifest()).toURI().toURL();
                } catch (MalformedURLException e) {
                    throw new InvalidAgentConfigException("Invalid AWS Service Handler Manifest location given in X-Ray Agent " +
                            "configuration file: " + agentConfiguration.getAwsServiceHandlerManifest(), e);
                }
            }
        }

        SegmentContextResolverChain segmentContextResolverChain = new SegmentContextResolverChain();
        segmentContextResolverChain.addResolver(new LambdaSegmentContextResolver());

        // Context resolution - use TransactionContext by default, or ThreadLocal if contextPropagation is disabled
        if (agentConfiguration.isContextPropagation()) {
            segmentContextResolverChain.addResolver(new XRayTransactionContextResolver());
        } else {
            segmentContextResolverChain.addResolver(new ThreadLocalSegmentContextResolver());
        }

        builder.withSegmentContextResolverChain(segmentContextResolverChain);

        log.debug("Successfully configured the X-Ray Agent's recorder.");

        AWSXRay.setGlobalRecorder(builder.build());
    }