func newInstrumentation()

in internal/beater/beater.go [521:587]


func newInstrumentation(rawConfig *agentconfig.C, logger *logp.Logger) (instrumentation.Instrumentation, error) {
	// This config struct contains missing fields from elastic agent APMConfig
	// https://github.com/elastic/elastic-agent/blob/main/internal/pkg/core/monitoring/config/config.go#L127
	// that are not directly handled by libbeat instrumentation below.
	//
	// Note that original config keys were additionally marshalled by
	// https://github.com/elastic/elastic-agent/blob/main/pkg/component/runtime/apm_config_mapper.go#L18
	// that's why some keys are different from the original APMConfig struct including "api_key" and "secret_token".
	var apmCfg struct {
		APIKey       string `config:"apikey"`
		SecretToken  string `config:"secrettoken"`
		GlobalLabels string `config:"globallabels"`
		TLS          struct {
			SkipVerify        bool   `config:"skipverify"`
			ServerCertificate string `config:"servercert"`
			ServerCA          string `config:"serverca"`
		} `config:"tls"`
		SamplingRate *float32 `config:"samplingrate"`
	}
	cfg, err := rawConfig.Child("instrumentation", -1)
	if err != nil || !cfg.Enabled() {
		// Fallback to instrumentation.New if the configs are not present or disabled.
		return instrumentation.New(rawConfig, "apm-server", version.VersionWithQualifier(), logger)
	}
	if err := cfg.Unpack(&apmCfg); err != nil {
		return nil, err
	}
	const (
		envAPIKey           = "ELASTIC_APM_API_KEY"
		envSecretToken      = "ELASTIC_APM_SECRET_TOKEN"
		envVerifyServerCert = "ELASTIC_APM_VERIFY_SERVER_CERT"
		envServerCert       = "ELASTIC_APM_SERVER_CERT"
		envCACert           = "ELASTIC_APM_SERVER_CA_CERT_FILE"
		envGlobalLabels     = "ELASTIC_APM_GLOBAL_LABELS"
		envSamplingRate     = "ELASTIC_APM_TRANSACTION_SAMPLE_RATE"
	)
	if apmCfg.APIKey != "" {
		os.Setenv(envAPIKey, apmCfg.APIKey)
		defer os.Unsetenv(envAPIKey)
	}
	if apmCfg.SecretToken != "" {
		os.Setenv(envSecretToken, apmCfg.SecretToken)
		defer os.Unsetenv(envSecretToken)
	}
	if apmCfg.TLS.SkipVerify {
		os.Setenv(envVerifyServerCert, "false")
		defer os.Unsetenv(envVerifyServerCert)
	}
	if apmCfg.TLS.ServerCertificate != "" {
		os.Setenv(envServerCert, apmCfg.TLS.ServerCertificate)
		defer os.Unsetenv(envServerCert)
	}
	if apmCfg.TLS.ServerCA != "" {
		os.Setenv(envCACert, apmCfg.TLS.ServerCA)
		defer os.Unsetenv(envCACert)
	}
	if len(apmCfg.GlobalLabels) > 0 {
		os.Setenv(envGlobalLabels, apmCfg.GlobalLabels)
		defer os.Unsetenv(envGlobalLabels)
	}
	if apmCfg.SamplingRate != nil {
		r := max(min(*apmCfg.SamplingRate, 1.0), 0.0)
		os.Setenv(envSamplingRate, strconv.FormatFloat(float64(r), 'f', -1, 32))
		defer os.Unsetenv(envSamplingRate)
	}
	return instrumentation.New(rawConfig, "apm-server", version.VersionWithQualifier(), logger)
}