|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and other contributors where applicable. |
| 3 | + * Licensed under the BSD 2-Clause License; you may not use this file except in |
| 4 | + * compliance with the BSD 2-Clause License. |
| 5 | + */ |
| 6 | + |
| 7 | +'use strict' |
| 8 | + |
| 9 | +const fs = require('fs') |
| 10 | +const version = require('../../package').version |
| 11 | +const logging = require('../logging') |
| 12 | +const { INTAKE_STRING_MAX_SIZE } = require('../config/schema') |
| 13 | +const { CloudMetadata } = require('../cloud-metadata') |
| 14 | +const { isLambdaExecutionEnvironment } = require('../lambda') |
| 15 | +const { isAzureFunctionsEnvironment, getAzureFunctionsExtraMetadata } = require('../instrumentation/azure-functions') |
| 16 | + |
| 17 | +/** |
| 18 | + * Returns a HTTP client configuration based on agent configuration options |
| 19 | + * |
| 20 | + * @param {Object} conf The agent configuration object |
| 21 | + * @param {Object} agent |
| 22 | + * @returns {Object} |
| 23 | + */ |
| 24 | +function getHttpClientConfig (conf, agent) { |
| 25 | + let clientLogger = null |
| 26 | + if (!logging.isLoggerCustom(agent.logger)) { |
| 27 | + // https://www.elastic.co/guide/en/ecs/current/ecs-event.html#field-event-module |
| 28 | + clientLogger = agent.logger.child({ 'event.module': 'apmclient' }) |
| 29 | + } |
| 30 | + const isLambda = isLambdaExecutionEnvironment() |
| 31 | + |
| 32 | + const clientConfig = { |
| 33 | + agentName: 'nodejs', |
| 34 | + agentVersion: version, |
| 35 | + agentActivationMethod: agent._agentActivationMethod, |
| 36 | + serviceName: conf.serviceName, |
| 37 | + serviceVersion: conf.serviceVersion, |
| 38 | + frameworkName: conf.frameworkName, |
| 39 | + frameworkVersion: conf.frameworkVersion, |
| 40 | + globalLabels: maybePairsToObject(conf.globalLabels), |
| 41 | + hostname: conf.hostname, |
| 42 | + environment: conf.environment, |
| 43 | + |
| 44 | + // Sanitize conf |
| 45 | + truncateKeywordsAt: INTAKE_STRING_MAX_SIZE, |
| 46 | + truncateLongFieldsAt: conf.longFieldMaxLength, |
| 47 | + // truncateErrorMessagesAt: see below |
| 48 | + |
| 49 | + // HTTP conf |
| 50 | + secretToken: conf.secretToken, |
| 51 | + apiKey: conf.apiKey, |
| 52 | + userAgent: userAgentFromConf(conf), |
| 53 | + serverUrl: conf.serverUrl, |
| 54 | + serverCaCert: loadServerCaCertFile(conf.serverCaCertFile), |
| 55 | + rejectUnauthorized: conf.verifyServerCert, |
| 56 | + serverTimeout: conf.serverTimeout * 1000, |
| 57 | + |
| 58 | + // APM Agent Configuration via Kibana: |
| 59 | + centralConfig: conf.centralConfig, |
| 60 | + |
| 61 | + // Streaming conf |
| 62 | + size: conf.apiRequestSize, |
| 63 | + time: conf.apiRequestTime * 1000, |
| 64 | + maxQueueSize: conf.maxQueueSize, |
| 65 | + |
| 66 | + // Debugging/testing options |
| 67 | + logger: clientLogger, |
| 68 | + payloadLogFile: conf.payloadLogFile, |
| 69 | + apmServerVersion: conf.apmServerVersion, |
| 70 | + |
| 71 | + // Container conf |
| 72 | + containerId: conf.containerId, |
| 73 | + kubernetesNodeName: conf.kubernetesNodeName, |
| 74 | + kubernetesNamespace: conf.kubernetesNamespace, |
| 75 | + kubernetesPodName: conf.kubernetesPodName, |
| 76 | + kubernetesPodUID: conf.kubernetesPodUID |
| 77 | + } |
| 78 | + |
| 79 | + // `service_node_name` is ignored in Lambda and Azure Functions envs. |
| 80 | + if (conf.serviceNodeName) { |
| 81 | + if (isLambda) { |
| 82 | + agent.logger.warn({ serviceNodeName: conf.serviceNodeName }, 'ignoring "serviceNodeName" config setting in Lambda environment') |
| 83 | + } else if (isAzureFunctionsEnvironment) { |
| 84 | + agent.logger.warn({ serviceNodeName: conf.serviceNodeName }, 'ignoring "serviceNodeName" config setting in Azure Functions environment') |
| 85 | + } else { |
| 86 | + clientConfig.serviceNodeName = conf.serviceNodeName |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + // Extra metadata handling. |
| 91 | + if (isLambda) { |
| 92 | + // Tell the Client to wait for a subsequent `.setExtraMetadata()` call |
| 93 | + // before allowing intake requests. This will be called by `apm.lambda()` |
| 94 | + // on first Lambda function invocation. |
| 95 | + clientConfig.expectExtraMetadata = true |
| 96 | + } else if (isAzureFunctionsEnvironment) { |
| 97 | + clientConfig.extraMetadata = getAzureFunctionsExtraMetadata() |
| 98 | + } else if (conf.cloudProvider !== 'none') { |
| 99 | + clientConfig.cloudMetadataFetcher = new CloudMetadata(conf.cloudProvider, conf.logger, conf.serviceName) |
| 100 | + } |
| 101 | + |
| 102 | + if (conf.errorMessageMaxLength !== undefined) { |
| 103 | + // As of v10 of the http client, truncation of error messages will default |
| 104 | + // to `truncateLongFieldsAt` if `truncateErrorMessagesAt` is not specified. |
| 105 | + clientConfig.truncateErrorMessagesAt = conf.errorMessageMaxLength |
| 106 | + } |
| 107 | + |
| 108 | + return clientConfig |
| 109 | +} |
| 110 | + |
| 111 | +// Return the User-Agent string the agent will use for its comms to APM Server. |
| 112 | +// |
| 113 | +// Per https://github.com/elastic/apm/blob/main/specs/agents/transport.md#user-agent |
| 114 | +// the pattern is roughly this: |
| 115 | +// $repoName/$version ($serviceName $serviceVersion) |
| 116 | +// |
| 117 | +// The format of User-Agent is governed by https://datatracker.ietf.org/doc/html/rfc7231. |
| 118 | +// User-Agent = product *( RWS ( product / comment ) ) |
| 119 | +// We do not expect `$repoName` and `$version` to have surprise/invalid values. |
| 120 | +// From `validateServiceName` above, we know that `$serviceName` is null or a |
| 121 | +// string limited to `/^[a-zA-Z0-9 _-]+$/`. However, `$serviceVersion` is |
| 122 | +// provided by the user and could have invalid characters. |
| 123 | +// |
| 124 | +// `comment` is defined by |
| 125 | +// https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6 as: |
| 126 | +// comment = "(" *( ctext / quoted-pair / comment ) ")" |
| 127 | +// obs-text = %x80-FF |
| 128 | +// ctext = HTAB / SP / %x21-27 / %x2A-5B / %x5D-7E / obs-text |
| 129 | +// quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) |
| 130 | +// |
| 131 | +// `commentBadChar` below *approximates* these rules, and is used to replace |
| 132 | +// invalid characters with '_' in the generated User-Agent string. This |
| 133 | +// replacement isn't part of the APM spec. |
| 134 | +function userAgentFromConf (conf) { |
| 135 | + let userAgent = `apm-agent-nodejs/${version}` |
| 136 | + |
| 137 | + // This regex *approximately* matches the allowed syntax for a "comment". |
| 138 | + // It does not handle "quoted-pair" or a "comment" in a comment. |
| 139 | + const commentBadChar = /[^\t \x21-\x27\x2a-\x5b\x5d-\x7e\x80-\xff]/g |
| 140 | + const commentParts = [] |
| 141 | + if (conf.serviceName) { |
| 142 | + commentParts.push(conf.serviceName) |
| 143 | + } |
| 144 | + if (conf.serviceVersion) { |
| 145 | + commentParts.push(conf.serviceVersion.replace(commentBadChar, '_')) |
| 146 | + } |
| 147 | + if (commentParts.length > 0) { |
| 148 | + userAgent += ` (${commentParts.join(' ')})` |
| 149 | + } |
| 150 | + |
| 151 | + return userAgent |
| 152 | +} |
| 153 | + |
| 154 | +/** |
| 155 | + * Reads te server CA cert file and returns a buffer with its contents |
| 156 | + * @param {string | undefined} serverCaCertFile |
| 157 | + * @param {any} logger |
| 158 | + * @returns {Buffer} |
| 159 | + */ |
| 160 | +function loadServerCaCertFile (serverCaCertFile, logger) { |
| 161 | + if (serverCaCertFile) { |
| 162 | + try { |
| 163 | + return fs.readFileSync(serverCaCertFile) |
| 164 | + } catch (err) { |
| 165 | + logger.error('Elastic APM initialization error: Can\'t read server CA cert file %s (%s)', serverCaCertFile, err.message) |
| 166 | + } |
| 167 | + } |
| 168 | +} |
| 169 | + |
| 170 | +function maybePairsToObject (pairs) { |
| 171 | + return pairs ? pairsToObject(pairs) : undefined |
| 172 | +} |
| 173 | + |
| 174 | +function pairsToObject (pairs) { |
| 175 | + return pairs.reduce((object, [key, value]) => { |
| 176 | + object[key] = value |
| 177 | + return object |
| 178 | + }, {}) |
| 179 | +} |
| 180 | + |
| 181 | +module.exports = { |
| 182 | + getHttpClientConfig, |
| 183 | + userAgentFromConf |
| 184 | +} |
0 commit comments