-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (71 loc) · 2.86 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
const net = require('net');
const syslogParser = require('glossy').Parse;
const { EventEmitter } = require ('events');
const MongoClient = require('mongodb').MongoClient;
class SyslogServer extends EventEmitter {
constructor(options) {
super();
this.server = net.createServer();
this.port = options.port || 514;
this.server.maxConnections = options.maxConnections || 10;
this.persistenceActive = options.persistence || false;
this.mongoUri = options.mongoDb.uri || "mongodb://localhost:27017";
this.mongoDbName = options.mongoDb.name || "logs-db";
this.logCollectionName = options.mongoDb.logCollectionName || "logs";
this.expirationDelayInDays = options.mongoDb.expirationDelayInDays || 1;
this.nbMilisecondInOneDay = 24 * 60 * 60 * 1000;
if(this.persistenceActive){
MongoClient.connect(this.mongoUri, { useUnifiedTopology: true }, (err, client) => {
if(err){
this.emit("error", error);
return;
}
console.log("Connected successfully to MongoDB");
this.db = client.db(this.mongoDbName);
this.db.collection(this.logCollectionName).createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } );
});
}
this.server.on('connection', (socket) => {
socket.setEncoding('utf8');
socket.on('data', (data) => {
let logRecord = syslogParser.parse(data);
this.emit("msg", logRecord);
if(this.persistenceActive){
logRecord.expireAt = new Date(new Date().getTime() + this.expirationDelayInDays * this.nbMilisecondInOneDay);
this.db.collection(this.logCollectionName).insertOne(logRecord);
}
});
socket.on('drain', () => {
socket.resume();
});
socket.on('error', (error) => {
this.emit("error", error);
});
socket.on('timeout', () => {
socket.end('Timed out!');
});
socket.on('end', (data) => {
console.log('Socket ended from other end!');
console.log('End data : ' + data);
});
socket.on('close', (error) => {
console.log('Socket closed!');
if (error) {
console.log('Socket was closed coz of transmission error');
}
});
});
this.server.on('close', () => {
console.log('Server closed !');
});
this.server.on('error', (error) => {
this.emit("error", error);
});
}
listen(cb) {
this.server.listen(this.port, () => {
cb();
});
}
}
module.exports = SyslogServer;