forked from pinpoint-apm/pinpoint-node-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.js
260 lines (225 loc) · 7.39 KB
/
config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
/**
* Pinpoint Node.js Agent
* Copyright 2020-present NAVER Corp.
* Apache License v2.0
*/
'use strict'
const path = require('path')
const fs = require('fs')
const defaultConfig = require('./pinpoint-config-default')
const log = require('./utils/logger')
const { setLog } = require('./supports')
const { makeLogLevelLog } = require('./utils/log/log-level-logger')
const valueOfString = (envName) => {
return () => {
if (process.env[envName] === undefined) {
return undefined
}
return process.env[envName]
}
}
const valueOfBoolean = (envName) => {
return () => {
if (process.env[envName] === undefined) {
return undefined
}
return process.env[envName] === 'true'
}
}
const valueOfNumber = (envName) => {
return () => {
if (process.env[envName] === undefined) {
return undefined
}
return Number(process.env[envName])
}
}
const ENV_MAP = {
agentId: valueOfString('PINPOINT_AGENT_ID'),
applicationName: valueOfString('PINPOINT_APPLICATION_NAME'),
serviceType: valueOfNumber('PINPOINT_SERVICE_TYPE'),
collectorIp: valueOfString('PINPOINT_COLLECTOR_IP'),
collectorTcpPort: valueOfNumber('PINPOINT_COLLECTOR_TCP_PORT'),
collectorStatPort: valueOfNumber('PINPOINT_COLLECTOR_STAT_PORT'),
collectorSpanPort: valueOfNumber('PINPOINT_COLLECTOR_SPAN_PORT'),
sampling: valueOfBoolean('PINPOINT_SAMPLING'),
sampleRate: valueOfNumber('PINPOINT_SAMPLING_RATE'),
logLevel: valueOfString('PINPOINT_LOG_LEVEL'),
enable: valueOfBoolean('PINPOINT_ENABLE'),
container: valueOfBoolean('PINPOINT_CONTAINER'),
traceExclusionUrlPatterns: valueOfString('PINPOINT_TRACE_EXCLUSION_URL_PATTERN'),
traceExclusionUrlCacheSize: valueOfNumber('PINPOINT_TRACE_EXCLUSION_URL_CACHE_SIZE'),
}
const CONFIG_FILE_MAP = {
agentId: 'agent-id',
applicationName: 'application-name',
serviceType: 'application-type',
collectorIp: 'collector.ip',
collectorTcpPort: 'collector.tcp-port',
collectorStatPort: 'collector.stat-port',
collectorSpanPort: 'collector.span-port',
sampling: 'sampling.enable',
sampleRate: 'sampling.rate',
httpStatusCodeErrors: 'http-status-code-errors',
logLevel: 'log-level',
enabledDataSending: 'enabled-data-sending',
enabledStatsMonitor: 'enabled-stats-monitor-sending',
enabledActiveThreadCount: 'enabled-active-thread-count',
express: 'express.enable',
koa: 'koa.enable',
mongo: 'mongo.enable',
redis: 'redis.enable',
enable: 'enable',
container: 'container',
traceExclusionUrlPatterns: 'trace-exclusion-url.pattern',
traceExclusionUrlCacheSize: 'trace-exclusion-url.cache-size',
streamDeadlineMinutesClientSide: 'stream-deadline-minutes.client-side'
}
let agentConfig = null
const REQUIRE_CONFIG = {
agentId: 'an Agent ID',
applicationName: 'an Application Name'
}
// ref: https://github.com/elastic/apm-agent-nodejs/blob/master/lib/config.js
const ARRAY_CONFIG = [
'traceExclusionUrlPatterns'
]
const configurationValueValidations = {
validateTraceExclusionUrlCacheSize: () => {
if (typeof agentConfig.traceExclusionUrlCacheSize !== 'undefined' && typeof agentConfig.traceExclusionUrlPatterns === 'undefined') {
delete agentConfig.traceExclusionUrlCacheSize
log.warn(`You have to set the PINPOINT_TRACE_EXCLUSION_URL_PATTERN, PINPOINT_TRACE_EXCLUSION_URL_CACHE_SIZE or trace-exclusion-url{ pattern: 'pattern', 'cache-size': 100} for using excludsion url cache.`)
}
if (Array.isArray(agentConfig.traceExclusionUrlPatterns) && Number.isInteger(agentConfig.traceExclusionUrlCacheSize)) {
if (agentConfig.traceExclusionUrlCacheSize < 100) {
agentConfig.traceExclusionUrlCacheSize = 100
}
}
},
validateIds: () => {
[{ id: agentConfig.agentId, name: 'Agent ID' }, { id: agentConfig.applicationName, name: 'Application Name' }].filter(id => id.id)
.filter(id => {
const ID_MAX_LEN = 24
const idRegex = /[a-zA-Z0-9\\._\\-]+/
if (id.id.length < 1) {
agentConfig.enable = false
log.error(`You have to set ${id.name}`)
return false
}
if (id.id.length > ID_MAX_LEN) {
agentConfig.enable = false
log.error(`You have to set ${id.name} to less ${ID_MAX_LEN} characters.`)
return false
}
if (!idRegex.test(id.id)) {
agentConfig.enable = false
log.error(`invalidate ${id.name} name with /[a-zA-Z0-9\\._\\-]+/ RegExp`)
return false
}
})
}
}
const init = (initOptions = {}) => {
agentConfig = Object.assign({},
readConfigJson(defaultConfig),
readConfigJson(readRootConfigFile()),
readFromEnv(),
readConfigJson(initOptions))
log.init(agentConfig.logLevel)
setLog(makeLogLevelLog(agentConfig.logLevel))
Object.entries(REQUIRE_CONFIG).forEach(([propertyName, description]) => {
if (agentConfig.enable && !agentConfig[propertyName]) {
agentConfig.enable = false
log.error(`You must set ${description}.The Pinpoint Node JS Agent has been shutdown.`)
}
})
if (!ENV_MAP.container() && isContainerEnvironment()) {
agentConfig.container = true
}
for (const [key, validation] of Object.entries(configurationValueValidations)) {
validation()
}
}
const readFromEnv = () => {
return Object.entries(ENV_MAP).reduce((acc, [key, valueOf]) => {
const value = valueOf()
if (typeof value === 'undefined') {
return acc
}
acc[key] = ARRAY_CONFIG.includes(key) ? splitString(value) : value
return acc
}, {})
}
const splitString = (value) => {
if (typeof value !== 'string') {
return value
}
return value.split(',').map(token => token.trim()).filter(token => token.length > 0)
}
const readConfigJson = (formattedConfig) => {
return Object.entries(CONFIG_FILE_MAP).reduce((acc, [key, propName]) => {
const value = getValue(propName, formattedConfig)
if (value !== undefined) {
acc[key] = value
}
return acc
}, {})
}
const readRootConfigFile = () => {
const fileName = 'pinpoint-config.json'
const mainModulePath = getMainModulePath(require)
if (!mainModulePath) {
log.warn('If executed with `node - r`, pinpoint-config.json cannot be read because require.main value is undefined.')
return {}
}
const fileFullPath = mainModulePath + '/' + fileName
if (!fs.existsSync(fileFullPath)) {
return {}
}
return require(fileFullPath)
}
const getMainModulePath = (requireFuction) => {
if (!requireFuction || !requireFuction.main || !requireFuction.main.filename) {
return
}
return path.dirname(requireFuction.main.filename)
}
const getValue = (key, configFile) => {
if (key) {
return key.split('.').reduce((object, prop) => object && object[prop], configFile)
}
}
const getConfig = (initOptions) => {
if (!agentConfig) {
init(initOptions)
}
return agentConfig
}
const clear = () => agentConfig && (agentConfig = null)
//https://github.com/sindresorhus/is-docker
const isContainerEnvironment = () => {
return hasDockerEnv() || hasDockerCGroup() || (process.env['KUBERNETES_SERVICE_HOST'] && process.env['KUBERNETES_SERVICE_HOST'].length > 0)
}
function hasDockerEnv() {
try {
fs.statSync('/.dockerenv')
return true
} catch (_) {
return false
}
}
function hasDockerCGroup() {
try {
return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker')
} catch (_) {
return false
}
}
module.exports = {
getConfig,
clear,
readConfigJson,
readRootConfigFile,
getMainModulePath,
isContainerEnvironment
}