/
geoip.js
89 lines (83 loc) · 2.68 KB
/
geoip.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
var path = require('path')
var fs = require('fs')
var consoleLogger = require('../../util/logger.js')
var maxmindUpdate = require('../../parser/maxmind-update')
var MaxMindReader = require('maxmind').Reader
var cityLookup = null
var geoIpStatus = {
maxmindDbDir: process.env.MAXMIND_DB_DIR || '/tmp/',
fields: process.env.GEOIP_FIELDS,
debug: !!process.env.DEBUG
}
function initMaxmind () {
maxmindUpdate(true, geoIpStatus.maxmindDbDir, function (err, fileName) {
if (geoIpStatus.debug) {
consoleLogger.debug('GeoIP: init GeoIP DB ' + fileName)
}
if (err) {
consoleLogger.error('GeoIP: error ' + err)
geoIpStatus.geoIpFailed = true
return
}
try {
fs.statSync(fileName)
cityLookup = new MaxMindReader(fs.readFileSync(fileName), { watchForUpdates: true })
if (cityLookup) {
consoleLogger.debug('GeoIP: open ' + fileName)
} else {
consoleLogger.log('GeoIP: error ' + err)
}
if (geoIpStatus.fields) {
consoleLogger.log('GeoIP: lookup enabled for fields ' + geoIpStatus.fields)
} else {
consoleLogger.log('GeoIP: lookup enabled ')
}
} catch (fsStatError) {
geoIpStatus.geoIpFailed = true
consoleLogger.error('GeoIP: error ' + fsStatError)
}
})
}
function geoipLookup (parsedObject, fieldName, outputFieldName) {
if (cityLookup != null && parsedObject[fieldName]) {
var location = cityLookup.get(parsedObject[fieldName])
if (location && location.country && location.city && location.city.names && location.city.names.en) {
parsedObject[outputFieldName || 'geoip'] = {
location: [location.location.longitude, location.location.latitude],
info: {
country: location.country.iso_code,
continent: location.continent.code,
city: location.city.names.en
}
}
}
} else {
return null
}
}
function geoipOutputFilter (context, config, eventEmitter, data, callback) {
// get config values from output-filter config
if (!geoIpStatus.fields) {
geoIpStatus.fields = config.fields
geoIpStatus.debug = config.debug
}
if (geoIpStatus.geoIpFailed === true) {
return callback(null, data)
}
var fields = config.fields || []
for (var i = 0; i < fields.length; i++) {
if ((data[fields[i]] !== undefined)) {
geoipLookup(data, fields[i], 'geoip')
}
}
return callback(null, data)
}
function test () {
var cfg = { fields: ['client_ip'], maxmindDbDir: '/tmp/', debug: true }
setInterval(() => {
geoipOutputFilter(null, cfg, null, { client_ip: '94.216.99.1' }, console.log)
}, 200)
}
consoleLogger.log('GeoIP: Loading Maxmind DB ')
initMaxmind()
module.exports = geoipOutputFilter