forked from prophile/nwatchlive
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
285 lines (251 loc) · 7.34 KB
/
main.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
var fs = require('fs');
var vm = require('vm');
var net = require('net');
var child_process = require('child_process');
var Bacon = require('baconjs');
var EventSource = require('eventsource');
var SSE = require('express-sse');
var request = require('request');
var QUERY_INTERVAL = 12; // seconds
var opt = require('node-getopt').create([
['h', 'help', 'display this help'],
['v', 'version', 'show version'],
['q', 'quiet', "don't print every update"],
['a', 'accept-self-signed', "accept self signed HTTPS certificates"],
['p', 'port=PORT', 'listen port']
])
.bindHelp()
.parseSystem();
if (opt.options.version) {
console.log('nwatchlive 0.0.1');
process.exit();
}
var port = opt.options.port || 3050;
if (opt.argv.length == 0) {
console.log('no services specified.');
process.exit(1);
}
if (opt.options['accept-self-signed']) {
// Avoids DEPTH_ZERO_SELF_SIGNED_CERT error for self-signed certs
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
}
var watchers = {};
var watchHTTP = function(url) {
return function(ack, err) {
request(url, function(e, response, body) {
if (e) {
err(e.message);
} else if (response.statusCode != 200) {
err("status " + response.statusCode);
} else {
ack();
}
});
};
};
var watchStream = function(url, eventNames) {
var EventSource_OPEN = 1;
var delay = QUERY_INTERVAL / 2;
var timeoutMessage = function() {
var names = eventNames.slice();
var namesStr = names.pop();
if (names.length > 0) {
namesStr = names.join("', '") + "' or '" + namesStr;
}
return "Connection succeeded, but no '" + namesStr + "' events detected were before timeout (" + delay + "s)";
}();
return function(ack, err) {
if (eventNames.length == 0) {
err("No event names to check!");
return;
}
var es = new EventSource(url);
var doAck = function() {
ack();
es.close();
};
eventNames.forEach(function(eventName) {
es.addEventListener(eventName, doAck);
});
es.onerror = function(ev) {
if (!ev.status) {
err("connection error");
} else {
err("status " + ev.status);
}
es.close();
};
setTimeout(function() {
if (es.readyState == EventSource_OPEN) {
err(timeoutMessage);
} else {
err('unexpected error: readyState=' + es.readyState + " after " + delay + "s");
}
}, delay * 1000);
};
};
var watchTCP = function(host, port) {
return function(ack, err) {
var cte = false;
var conn = net.createConnection({'host': host,
'port': port},
function() {
ack();
cte = true;
conn.end();
});
conn.on('end', function() {
if (!cte) {
err('premature FIN');
}
});
conn.on('timeout', function() {
err('timeout');
});
conn.on('error', function(e) {
err(e.message);
});
};
};
var watchChild = function(child, args) {
return function(ack, err) {
var chld = child_process.spawn(child, args, {
'stdio': ['ignore', 'pipe', 'pipe']
});
var io = '';
var getIO = function(chunk) {
io += chunk;
};
chld.stdout.on('data', getIO);
chld.stderr.on('data', getIO);
chld.on('error', function(e) {
err(e.message);
});
chld.on('exit', function(code, signal) {
if (signal !== null || code != 0) {
err(io);
} else {
ack();
}
});
};
};
var watchPing = function(target) {
return watchChild('ping', ['-c', '1', '-W', '3', target]);
};
var watchPing6 = function(target) {
return watchChild('ping6', ['-c', '1', target]);
};
var context = vm.createContext({
'addWatcher': function(name, watcher) {
watchers[name] = watcher;
},
'watchHTTP': watchHTTP,
'watchStream': watchStream,
'watchChild': watchChild,
'watchTCP': watchTCP,
'watchPing': watchPing,
'watchPing6': watchPing6,
'require': require,
'console': console
});
opt.argv.forEach(function(sfile) {
var services = fs.readFileSync(sfile);
vm.runInContext(services, context, sfile);
});
console.log(watchers);
var services = [];
for (var watcher in watchers) {
if (watchers.hasOwnProperty(watcher)) {
services.push(watcher);
}
}
var statuses = {};
services.forEach(function(service) {
statuses[service] = '...';
});
var statBus = new Bacon.Bus();
var Stat = statBus.toProperty(statuses);
var setStatus = function(service, stat) {
var oldStatus = statuses[service];
if (oldStatus === stat) {
return;
}
statuses[service] = stat;
statBus.push(statuses);
};
var propertiesInflight = [];
var currentQueryGeneration = 0;
var runQueries = function() {
currentQueryGeneration += 1;
var currentQuery = currentQueryGeneration;
propertiesInflight.forEach(function(inflight) {
setStatus(inflight, 'query timed out');
});
services.forEach(function(service) {
propertiesInflight.push(service);
var watcher = watchers[service];
var recv = function(stat) {
if (currentQuery !== currentQueryGeneration)
return;
var ix = propertiesInflight.indexOf(service);
if (ix > -1) {
propertiesInflight.splice(ix, 1);
setStatus(service, stat);
}
};
var ack = function() {
recv(null);
};
var err = function(e) {
recv(e || 'error');
};
setImmediate(function() {
watcher(ack, err);
});
});
};
runQueries();
setInterval(runQueries, QUERY_INTERVAL*1000);
Stat.onValue(function(val) {
if (!opt.options.quiet) {
console.log(val);
}
});
var build_content = function(statuses) {
return {
'statuses': statuses,
};
};
var express = require('express');
var app = express();
var root = fs.readFileSync(__dirname + '/index.html', {'encoding': 'utf-8'});
app.get('/', function(req, res) {
res.header('Content-Type', 'text/html; charset=utf-8');
res.end(root);
});
app.get('/status', function(req, res) {
res.header('Content-Type', 'application/json');
res.end(JSON.stringify(build_content(statuses)));
});
var sse = new SSE([]);
app.get('/stream', sse.init);
Stat.debounce(700).onValue(function(x) {
var val = build_content(x);
sse.send(val);
sse.updateInit([val]);
});
// setup pings -- needed so that the client can tell when either the
// client or server has become disconnected from the network without
// actively dying or raising an error.
var PING_INTERVAL = 5; // seconds
setInterval(function() {
sse.send({'ping': PING_INTERVAL});
}, PING_INTERVAL * 1000);
app.use('/static', express.static(__dirname + '/static'));
var server = app.listen(port, '::', function() {
var ad = server.address();
var hs = ad.address;
var pt = ad.port;
console.log("Listening on http://%s:%s", hs, pt);
});