-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
581 lines (547 loc) · 19.1 KB
/
index.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
/*
* See the NOTICE.txt file distributed with this work for additional information
* regarding copyright ownership.
* Sematext licenses logsene-js to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use strict'
const nodeFetch = require('node-fetch')
const fs = require('fs')
const util = require('util')
const os = require('os')
const events = require('events')
const ipAddress = require('ip').address()
const path = require('path')
const stringifySafe = require('fast-safe-stringify')
const streamBuffers = require('stream-buffers')
// settings for node stream buffer
const initialBufferSize = 1024 * 1024
const incrementBuffer = 1024 * 1024
// re-usable regular expressions
const limitRegex = /limit/i
const appNotFoundRegEx = /Application not found for token/i
const disableJsonEnrichment = (process.env.ENABLE_JSON_ENRICHMENT === 'false')
let replaceDotsInFieldNames = true
if (process.env.REPLACE_DOTS_IN_FIELD_NAMES === 'false' || process.env.REPLACE_DOTS_IN_FIELD_NAMES === '0') {
replaceDotsInFieldNames = false
}
// load ENV like Logsene receivers from file containing
// env vars e.g. SPM_RECEIVER_URL, EVENTS_RECEIVER_URL, LOGSENE_RECEIVER_URL
// the file overwrites the actual environment
// and is used by Sematext Enterprise or multi-region setups to
// setup receiver URLs
function loadEnvFromFile (fileName) {
try {
const receivers = fs.readFileSync(fileName).toString()
if (receivers) {
const lines = receivers.split('\n')
lines.forEach(function (line) {
const kv = line.split('=')
if (kv.length === 2 && kv[1].length > 0) {
process.env[kv[0].trim()] = kv[1].trim()
if (/logsene-js/.test(process.env.DEBUG)) {
console.log(kv[0].trim() + ' = ' + kv[1].trim())
}
}
})
}
if (/logsene-js/.test(process.env.DEBUG)) {
console.log(new Date(), 'loading Sematext receiver URLs from ' + fileName)
}
} catch (error) {
// ignore missing file or wrong format
if (/logsene-js/.test(process.env.DEBUG)) {
console.error(error.message)
}
}
}
const envFileName = '/etc/sematext/receivers.config'
/**
if (/win/.test(os.platform()) {
envFileName = process.env.ProgramData + '\\Sematext\\receivers.config'
}
**/
loadEnvFromFile(envFileName)
// removing LOGSENE from ENV variable names
// and be backward compatible in case users still use old ENV variable names
const envVarMapping = [
['LOGSENE_MAX_MESSAGE_FIELD_SIZE', 'LOGS_MAX_MESSAGE_FIELD_SIZE'],
['LOGSENE_MAX_STORED_REQUESTS', 'LOGS_MAX_STORED_REQUESTS'],
['LOGSENE_BULK_SIZE_BYTES', 'LOGS_BULK_SIZE_BYTES'],
['LOGSENE_BULK_SIZE', 'LOGS_BULK_SIZE'],
['LOGSENE_LOG_INTERVAL', 'LOG_INTERVAL'],
['LOGSENE_DISK_BUFFER_INTERVAL', 'LOGS_DISK_BUFFER_INTERVAL'],
['LOGSENE_RECEIVER_URL', 'LOGS_RECEIVER_URL'],
['SPM_RECEIVER_URL', 'MONITORING_RECEIVER_URL'],
['SPM_TOKEN', 'MONITORING_TOKEN'],
['LOGSENE_REMOVE_FIELDS', 'REMOVE_FIELDS'],
['LOGSENE_TMP_DIR', 'LOGS_TMP_DIR'],
['LOGSENE_BUFFER_ON_APP_LIMIT ', 'LOGS_BUFFER_ON_APP_LIMIT'],
['LOGSENE_REMOVE_FIELDS', 'LOGS_REMOVE_FIELDS'],
['LOGSENE_REMOVE_FIELDS', 'REMOVE_FIELDS'],
['SPM_REPORTED_HOSTNAME', 'REPORTED_HOSTNAME']
]
function mapEnv (item) {
if ((!process.env[item[0]]) && (process.env[item[1]] !== undefined)) {
process.env[item[0]] = process.env[item[1]]
if (/logsene-js/.test(process.env.DEBUG)) {
console.log('Set ', item[0], ' to ', process.env[item[0]], ' from ', item[1])
}
}
}
envVarMapping.forEach(mapEnv)
// SPM_REPORTED_HOSTNAME might be set by Sematext Docker Agent
// the container hostname might not be helpful ...
// this might be removed after next release of SDA setting xLogseneOrigin from SDA
var xLogseneOrigin = process.env.SPM_REPORTED_HOSTNAME || os.hostname()
// limit message size
var MAX_MESSAGE_FIELD_SIZE = Number(process.env.LOGSENE_MAX_MESSAGE_FIELD_SIZE) || 1024 * 240 // 240 K, leave
// settings for bulk requests
var MIN_LOGSENE_BULK_SIZE = 200
var MAX_LOGSENE_BULK_SIZE = 10000
var MAX_STORED_REQUESTS = Number(process.env.LOGSENE_MAX_STORED_REQUESTS) || 10000
var MAX_CLIENT_SOCKETS = Number(process.env.MAX_CLIENT_SOCKETS) || 5
// upper limit a user could set - 10 MB as configured in Sematext Cloud receivers
var MAX_LOGSENE_BULK_SIZE_BYTES = 10 * 1000 * 1000
// lower limit a user could set
var MIN_LOGSENE_BULK_SIZE_BYTES = 1024 * 1024
var MAX_LOGSENE_BUFFER_SIZE = Number(process.env.LOGSENE_BULK_SIZE_BYTES) || 1024 * 1024 * 3 // max 3 MB per http request
// check limits set by users, and adjust if those would lead to problematic settings
if (MAX_LOGSENE_BUFFER_SIZE > MAX_LOGSENE_BULK_SIZE_BYTES) {
MAX_LOGSENE_BUFFER_SIZE = MAX_LOGSENE_BULK_SIZE_BYTES
}
if (MAX_LOGSENE_BUFFER_SIZE < MIN_LOGSENE_BULK_SIZE_BYTES) {
MAX_LOGSENE_BUFFER_SIZE = MIN_LOGSENE_BULK_SIZE_BYTES
}
var LOGSENE_BULK_SIZE = Number(process.env.LOGSENE_BULK_SIZE) || 500 // max 500 messages per bulk req.
if (LOGSENE_BULK_SIZE > MAX_LOGSENE_BULK_SIZE) {
LOGSENE_BULK_SIZE = MAX_LOGSENE_BULK_SIZE
}
if (LOGSENE_BULK_SIZE < MIN_LOGSENE_BULK_SIZE) {
LOGSENE_BULK_SIZE = MIN_LOGSENE_BULK_SIZE
}
const deleteKey = require('del-key')
function removeFields (fieldList, doc) {
if (fieldList && fieldList.length > 0 && fieldList[0] !== '') {
for (let i = fieldList.length; i >= 0; --i) {
deleteKey(doc, fieldList[i])
}
}
return doc
}
// Create a deep clone of an object while allowing caller to rename
// keys, replace values, or reject key-pairs entirely.
//
// Does not modify the source object. Callback receives (key, value)
// and is expected to return a two-item array [newKey, newValue], or
// null if the pair should be absent from the resulting object.
function deepConvert (src, cb) {
let dest
if (Array.isArray(src)) {
dest = []
} else {
dest = {}
}
if (dest) {
for (let key in src) {
if (src.hasOwnProperty(key)) {
const val = src[key]
const newKV = cb(key, val)
if (newKV === null) {
// skip this field entirely
continue
}
const newKey = newKV[0]
const newVal = newKV[1]
if (newVal !== undefined &&
newVal !== null &&
(Array.isArray(newVal) || newVal.constructor === Object)) {
dest[newKey] = deepConvert(newVal, cb)
} else {
dest[newKey] = newVal
}
}
}
} else {
dest = src
}
return dest
}
/**
* token - the LOGSENE Token
* type - type of log (string)
* url - optional alternative URL for Logsene receiver (e.g. for on premises version)
* storageDirectory - directory where to buffer logs
* options - @object { useIndexInBulkUrl, httpOptions, silent }
*/
function Logsene (token, type, url, storageDirectory, options) {
if (!token) {
throw new Error('Logsene token not specified')
}
if (options) {
this.options = options
} else {
this.options = {
useIndexInBulkUrl: false,
silent: false
}
}
if (url && /logsene/.test(url)) {
// logs to logsene should use /TOKEN/_bulk
this.options.useIndexInBulkUrl = true
}
this.request = null
this.maxMessageFieldSize = MAX_MESSAGE_FIELD_SIZE
this.xLogseneOrigin = xLogseneOrigin
this.token = token
this.setUrl(url || process.env.LOGSENE_URL || process.env.LOGSENE_RECEIVER_URL || process.env.LOGS_URL || 'https://logsene-receiver.sematext.com/_bulk')
this.type = type || 'logs'
this.hostname = process.env.SPM_REPORTED_HOSTNAME || os.hostname()
this.bulkReq = new streamBuffers.WritableStreamBuffer({
initialSize: initialBufferSize,
incrementAmount: incrementBuffer
})
this.logCount = 0
this.sourceName = null
if (process.mainModule && process.mainModule.filename) {
this.sourceName = path.basename(process.mainModule.filename)
}
events.EventEmitter.call(this)
let self = this
self.lastSend = Date.now()
const logInterval = Number(process.env.LOGSENE_LOG_INTERVAL) || 20000
const tid = setInterval(function () {
if (self.logCount > 0 && (Date.now() - self.lastSend) > (logInterval - 1000)) {
self.send()
}
}, logInterval)
if (tid.unref) {
tid.unref()
}
process.on('beforeExit', function () {
self.send()
})
if (process.env.LOGSENE_TMP_DIR || storageDirectory) {
this.diskBuffer(true, process.env.LOGSENE_TMP_DIR || storageDirectory)
}
const fieldListStr = process.env.LOGSENE_REMOVE_FIELDS || process.env.REMOVE_FIELDS || ''
this.removeFieldsList = fieldListStr.replace(/ /g, '').split(',')
// error handling
self.on('x-logsene-error', function (errObj) {
if (!self.options.silent) {
console.error(
new Date().toISOString() +
` logsene-js: cannot reach the receiver URL: ${errObj.err.url}, please check the error message ...`,
errObj
)
}
})
}
util.inherits(Logsene, events.EventEmitter)
Logsene.prototype.setUrl = function (url) {
let tmpUrl = url
if (url.indexOf('_bulk') === -1) {
tmpUrl = url + '/_bulk'
} else {
tmpUrl = url
}
if (this.options && this.options.useIndexInBulkUrl) {
this.url = tmpUrl.replace('_bulk', this.token + '/_bulk')
} else {
this.url = tmpUrl
}
let Agent = null
let httpOptions = { maxSockets: MAX_CLIENT_SOCKETS, keepAlive: false, maxFreeSockets: MAX_CLIENT_SOCKETS }
if (this.options.httpOptions) {
const keys = Object.keys(this.options.httpOptions)
for (let i = 0; i < keys.length; i++) {
httpOptions[keys[i]] = this.options.httpOptions[keys[i]]
}
}
if (/^https/.test(url)) {
Agent = require('https').Agent
} else {
Agent = require('http').Agent
}
this.httpAgent = new Agent(httpOptions)
this.httpDefaults = {
agent: this.httpAgent,
timeout: 60000,
}
}
const DiskBuffer = require('./DiskBuffer.js')
Logsene.prototype.diskBuffer = function (enabled, dir) {
if (enabled) {
const tmpDir = path.join((dir || require('os').tmpdir()), this.token)
this.db = DiskBuffer.createDiskBuffer({
tmpDir: tmpDir,
maxStoredRequests: Number(MAX_STORED_REQUESTS),
interval: process.env.LOGSENE_DISK_BUFFER_INTERVAL || 5000
})
this.db.syncFileListFromDir()
let self = this
if (!this.db.isCached) {
// only the first instance registers for retransmit-req
// to avoid double event handling from multiple instances
this.db.on('retransmit-req', function (event) {
self.shipFile(event.fileName, event.buffer, function (err, res) {
if (err && err.httpBody && appNotFoundRegEx.test(err.httpBody)) {
// remove file from DiskBuffer when token is invalid
self.db.rmFile.call(self.db, event.fileName)
self.db.retransmitNext.call(self.db)
return
}
if (!err && res) {
self.db.rmFile.call(self.db, event.fileName)
self.db.retransmitNext.call(self.db)
} else {
self.db.unlock.call(self.db, event.fileName)
}
})
})
}
}
this.persistence = enabled
}
/**
* Add log message to send buffer
* @param level - log level e.g. 'info', 'warning', 'error'
* @param message - text message
* @param fields - Object with custom fields or overwrite of any other field e.g. e.g. "{@timestamp: new Date.toISOString()}"
* @param callback (err, msg object)
*/
Logsene.prototype.log = function (level, message, fields, callback) {
this.logCount = this.logCount + 1
let type = 'logs'
let logType = 'logs'
if (fields) {
logType = fields._type
}
if (this.options.useIndexInBulkUrl) {
// not a Sematext service -> use only one type per index
// Elasticsearch > 6.x allows only one type per index
type = this.type
}
let msg = {
'@timestamp': new Date(),
severity: level,
message,
logType,
os: {
host: this.hostname,
hostip: ipAddress
}
}
let elasticsearchDocId = null
if (fields && fields._type) {
delete fields._type
}
if (fields && fields._id) {
elasticsearchDocId = fields._id
}
if (disableJsonEnrichment) {
msg = {}
}
let esSanitizedFields = deepConvert(fields, function (key, val) {
if (typeof val === 'function') {
return null
} else {
if (replaceDotsInFieldNames) {
return [key.replace(/\./g, '_').replace(/^_+/, ''), val]
} else {
// remove leading _
return [key.replace(/^_+/, ''), val]
}
}
})
msg = Object.assign(msg, esSanitizedFields)
if (msg['@timestamp'] && typeof msg['@timestamp'] === 'number') {
msg['@timestamp'] = new Date(msg['@timestamp'])
}
msg = removeFields(this.removeFieldsList, msg)
let _index = this.token
if (fields && typeof (fields._index) === 'function') {
_index = fields._index(msg)
} else {
if (fields && fields._index != undefined) {
_index = fields._index
delete msg.index
}
}
if (msg.message && typeof msg.message === 'string' && Buffer.byteLength(msg.message, 'utf8') > this.maxMessageFieldSize) {
// new nodejs api, let's use Buffer.alloc instead of Buffer(size)
let cutMsg = Buffer.alloc ? Buffer.alloc(this.maxMessageFieldSize) : new Buffer(this.maxMessageFieldSize)
cutMsg.write(msg.message)
msg.message = cutMsg.toString()
if (msg.originalLine) {
// when message is too large and logagent added originalLine,
// this should be removed to stay under the limits in receiver
delete msg.originalLine
}
msg.logsene_client_warning = 'Warning: message field too large > ' + this.maxMessageFieldSize + ' bytes'
}
if (elasticsearchDocId !== null) {
this.bulkReq.write(stringifySafe({ 'index': { '_index': _index, '_id': String(elasticsearchDocId), '_type': type || this.type } }) + '\n')
} else {
this.bulkReq.write(stringifySafe({ 'index': { '_index': _index, '_type': type || this.type } }) + '\n')
}
this.bulkReq.write(stringifySafe(msg) + '\n')
if (this.logCount === LOGSENE_BULK_SIZE || this.bulkReq.size() > MAX_LOGSENE_BUFFER_SIZE) {
this.send()
}
this.emit('logged', { msg: msg, _index: _index })
if (callback) {
callback(null, msg)
}
}
/**
* Sending log entry to LOGSENE - this function is triggered every 100 log message or 30 seconds.
* @callback {function} optional callback function
*/
Logsene.prototype.send = function (callback) {
let self = this
const buffer = this.bulkReq
this.bulkReq = new streamBuffers.WritableStreamBuffer({
initialSize: initialBufferSize,
incrementAmount: incrementBuffer
})
buffer.end()
self.lastSend = Date.now()
let count = this.logCount
let options = {
url: this.url,
logCount: count,
headers: {
'User-Agent': 'logsene-js',
'Content-Type': 'application/json',
'Connection': 'Close',
'x-logsene-origin': this.xLogseneOrigin || xLogseneOrigin
},
body: buffer.getContents(),
method: 'POST'
}
if (options.body === false) {
return
}
function httpResult (err, res) {
// if (res && res.body) console.log(res.statusCode, res.body)
let logseneError = null
let responseJson = null
if (res && res.headers && res.headers['x-logsene-error']) {
logseneError = res.headers['x-logsene-error']
}
let errorMessage = null
let errObj = null
if (err || (res && res.status > 399) || logseneError) {
if (err && (err.code || err.message)) {
err.url = options.url
}
if (res && res.status) {
errorMessage = 'HTTP status code:' + res.status
}
if (logseneError) {
errorMessage += ', ' + logseneError
}
errObj = { source: 'logsene-js', err: (err || { message: errorMessage, httpStatus: res.status, httpBody: res.body, url: options.url }) }
self.emit('x-logsene-error', errObj)
if (self.persistence) {
let storeFileFlag = true
// don't use disk buffer for invalid Logsene tokens
if (res && res.body && appNotFoundRegEx.test(res.body)) {
storeFileFlag = false
}
if (res && res.status && res.status === 400) {
storeFileFlag = false
}
if (logseneError && limitRegex.test(logseneError)) {
// && process.env.LOGSENE_BUFFER_ON_APP_LIMIT === 'false'
storeFileFlag = false
}
if (storeFileFlag) {
options.body = options.body.toString()
self.db.store(options, function () {
delete options.body
})
} else {
self.emit('fileNotStored', options)
}
}
} else {
return res.json()
.then(responseJson => {
responseJson.items.forEach(function (item) {
let result = item.index || item.create || item.update || item.delete
if (result && result.status > 399) {
errorMessage = 'HTTP status code:' + result.status + ' Error: ' + JSON.stringify(result.error)
let errObj = {
source: 'logsene-js',
err: { message: errorMessage, httpStatus: result.status, httpBody: result, url: options.url }
}
self.emit('x-logsene-error', errObj)
}
})
self.emit('log', { source: 'logsene-js', count: count, url: options.url })
delete options.body
if (callback) {
callback(errObj, res)
}
})
.catch(err => {
errObj = { source: 'logsene-js', err: err }
self.emit('x-logsene-error', errObj)
})
}
}
self.logCount = Math.max(self.logCount - count, 0)
options = {...options, ...this.httpDefaults}
nodeFetch(this.url, options)
.then(response => httpResult(null, response))
.catch(err => httpResult(err, null))
}
Logsene.prototype.shipFile = function (name, data, cb) {
let self = this
let options = null
try {
options = JSON.parse(data)
} catch (err) {
// wrong file format
}
if (options == null || options.options) {
// wrong file format?
// cleanup from earlier versions
// self.db.rmFile(name)
return cb(new Error('wrong bulk file format'))
}
options.body = options.body.toString()
options.url = self.url
const callbackFunc = function (err, res) {
if (err || (res && res.status > 399)) {
let errObj = { source: 'logsene re-transmit', err: (err || { message: 'Logsene re-transmit status code:' + res.status, httpStatus: res.status, httpBody: res.body, url: options.url, fileName: name }) }
self.emit('x-logsene-error', errObj)
if (cb) {
cb(errObj)
}
} else {
if (cb) {
cb(null, { file: name, count: options.logCount })
}
self.emit('file shipped', { file: name, count: options.logCount })
self.emit('rt', { count: options.logCount, source: 'logsene', file: name, url: String(options.url), request: null, response: null })
}
}
nodeFetch(options.url, options)
.then(response => callbackFunc(null, response))
.catch(error => callbackFunc(error, null))
}
module.exports = Logsene