-
Notifications
You must be signed in to change notification settings - Fork 1
/
agent.js
109 lines (88 loc) · 2.23 KB
/
agent.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
var agents = require('./lib');
var WebSocketServer = require('ws').Server;
var self = {};
self.loadedAgents = {};
self.server = null;
self.frontends = [];
self.onFrontendConnection = function(socket) {
self.frontends.push(socket);
socket.on('message', self.onFrontendMessage.bind(socket));
socket.on('close', (function(){
for(var i =0; i<self.frontends.length;i++){
if (self.frontends[i] === socket){
self.frontends.splice(i,1);
}
}
}).bind(socket));
socket.on('error', function(error) {
console.error(error);
});
};
self.onFrontendMessage = function(message) {
var socket = this;
var data;
try {
data = JSON.parse(message);
} catch(e) {
console.error(e.stack);
return;
}
var id = data.id;
var command = data.method.split('.');
var domain = self.loadedAgents[command[0]];
var method = command[1];
var params = data.params;
if (!domain || !domain[method]) {
//console.warn('%s is not implemented', data.method);
return;
}
domain[method](params, function(result) {
var response = {
id: id,
result: result
};
try {
socket.send(JSON.stringify(response));
} catch (err) {}
});
};
self.notify = function(notification) {
self.frontends.forEach(function(socket){
try {
socket.send(JSON.stringify(notification))
} catch (err) {}
});
};
self.loadAgents = function() {
var runtimeAgent = new agents.Runtime(self.notify);
for (var agent in agents) {
if (typeof agents[agent] == 'function' && agent != 'Runtime') {
self.loadedAgents[agent] = new agents[agent](self.notify, runtimeAgent);
}
}
self.loadedAgents.Runtime = runtimeAgent;
};
module.exports = {
'start': function(port,host) {
self.port = port || 9958;
self.host = host || '0.0.0.0';
if (self.server) return;
self.server = new WebSocketServer({
port: self.port,
host: self.host
});
self.server.on('listening', function() {
self.loadAgents();
});
self.server.on('connection', self.onFrontendConnection);
},
'stop': function() {
self.frontends.forEach(function(socket){
socket.close();
});
if (self.server) {
self.server.close();
self.server = null;
}
}
}