1 // node.js version of analysis.pl; hopefully scales a bit better
2 // for this specific kind of task.
5 var http = require('http');
6 var fs = require('fs');
7 var url = require('url');
8 var querystring = require('querystring');
9 var path = require('path');
10 var zlib = require('zlib');
11 var readline = require('readline');
12 var child_process = require('child_process');
13 var delta = require('../www/js/json_delta.js');
14 var hash_lookup = require('./hash-lookup.js');
17 var HISTORY_TO_KEEP = 5;
18 var MINIMUM_VERSION = null;
19 var COUNT_FROM_VARNISH_LOG = true;
22 var json_filename = '/srv/analysis.sesse.net/www/analysis.json';
23 if (process.argv.length >= 3) {
24 json_filename = process.argv[2];
27 // Expected destination filenames.
28 var serve_url = '/analysis.pl';
29 var hash_serve_url = '/hash';
30 if (process.argv.length >= 4) {
31 serve_url = process.argv[3];
33 if (process.argv.length >= 5) {
34 hash_serve_url = process.argv[4];
37 // TCP port to listen on.
39 if (process.argv.length >= 6) {
40 port = parseInt(process.argv[5]);
44 var grpc_backends = ["localhost:50051", "localhost:50052"];
45 if (process.argv.length >= 7) {
46 grpc_backends = process.argv[6].split(",");
48 hash_lookup.init(grpc_backends);
50 // If set to 1, we are already processing a JSON update and should not
51 // start a new one. If set to 2, we are _also_ having one in the queue.
54 // The current contents of the file to hand out, and its last modified time.
57 // The last five timestamps, and diffs from them to the latest version.
58 var historic_json = [];
61 // The list of clients that are waiting for new data to show up.
62 // Uniquely keyed by request_id so that we can take them out of
63 // the queue if they close the socket.
64 var sleeping_clients = {};
67 // List of when clients were last seen, keyed by their unique ID.
68 // Used to show a viewer count to the user.
69 var last_seen_clients = {};
71 // The timer used to touch the file every 30 seconds if nobody
72 // else does it for us. This makes sure we don't have clients
73 // hanging indefinitely (which might have them return errors).
74 var touch_timer = undefined;
76 // If we are behind Varnish, we can't count the number of clients
77 // ourselves, so we need to get it from parsing varnishncsa.
78 var viewer_count_override = undefined;
80 var replace_json = function(new_json_contents, mtime) {
81 // Generate the list of diffs from the last five versions.
82 if (json !== undefined) {
83 // If two versions have the same mtime, clients could have either.
84 // Note the fact, so that we never insert it.
85 if (json.last_modified == mtime) {
86 json.invalid_base = true;
88 if (!json.invalid_base) {
89 historic_json.push(json);
90 if (historic_json.length > HISTORY_TO_KEEP) {
91 historic_json.shift();
96 var parsed = JSON.parse(new_json_contents);
98 if (parsed['internal']) {
99 if (parsed['internal']['grpc_backends'] &&
100 hash_lookup.need_reinit(parsed['internal']['grpc_backends'])) {
101 hash_lookup.init(parsed['internal']['grpc_backends']);
103 delete parsed['internal'];
108 plain: new_json_contents,
111 create_json_historic_diff(new_json, historic_json.slice(0), {}, function(new_diff_json) {
112 // gzip the new version (non-delta), and put it into place.
113 zlib.gzip(new_json_contents, function(err, buffer) {
116 new_json.gzip = buffer;
118 diff_json = new_diff_json;
121 // Finally, wake up any sleeping clients.
122 possibly_wakeup_clients();
127 var create_json_historic_diff = function(new_json, history_left, new_diff_json, cb) {
128 if (history_left.length == 0) {
133 var histobj = history_left.shift();
134 var diff = delta.JSON_delta.diff(histobj.parsed, new_json.parsed);
135 var diff_text = JSON.stringify(diff);
136 zlib.gzip(diff_text, function(err, buffer) {
138 new_diff_json[histobj.last_modified] = {
142 last_modified: new_json.last_modified,
144 create_json_historic_diff(new_json, history_left, new_diff_json, cb);
148 var reread_file = function(event, filename) {
149 if (filename != path.basename(json_filename)) {
152 if (json_lock >= 2) {
155 if (json_lock == 1) {
156 // Already processing; wait a bit.
158 setTimeout(function() { if (json_lock == 2) json_lock = 1; reread_file(event, filename); }, 100);
163 console.log("Rereading " + json_filename);
164 fs.open(json_filename, 'r', function(err, fd) {
166 fs.fstat(fd, function(err, st) {
168 var buffer = new Buffer(1048576);
169 fs.read(fd, buffer, 0, 1048576, 0, function(err, bytesRead, buffer) {
171 fs.close(fd, function() {
172 var new_json_contents = buffer.toString('utf8', 0, bytesRead);
173 replace_json(new_json_contents, st.mtime.getTime());
179 if (touch_timer !== undefined) {
180 clearTimeout(touch_timer);
182 touch_timer = setTimeout(function() {
183 console.log("Touching analysis.json due to no other activity");
184 var now = Date.now() / 1000;
185 fs.utimes(json_filename, now, now);
188 var possibly_wakeup_clients = function() {
189 var num_viewers = count_viewers();
190 for (var i in sleeping_clients) {
191 mark_recently_seen(sleeping_clients[i].unique);
192 send_json(sleeping_clients[i].response,
193 sleeping_clients[i].ims,
194 sleeping_clients[i].accept_gzip,
197 sleeping_clients = {};
199 var send_404 = function(response) {
200 response.writeHead(404, {
201 'Content-Type': 'text/plain',
203 response.write('Something went wrong. Sorry.');
206 var send_json = function(response, ims, accept_gzip, num_viewers) {
207 var this_json = diff_json[ims] || json;
210 'Content-Type': 'text/json',
211 'X-RGLM': this_json.last_modified,
212 'X-RGNV': num_viewers,
213 'Access-Control-Expose-Headers': 'X-RGLM, X-RGNV, X-RGMV',
214 'Vary': 'Accept-Encoding',
217 if (MINIMUM_VERSION) {
218 headers['X-RGMV'] = MINIMUM_VERSION;
222 headers['Content-Length'] = this_json.gzip.length;
223 headers['Content-Encoding'] = 'gzip';
224 response.writeHead(200, headers);
225 response.write(this_json.gzip);
227 headers['Content-Length'] = this_json.plain.length;
228 response.writeHead(200, headers);
229 response.write(this_json.plain);
233 var mark_recently_seen = function(unique) {
235 last_seen_clients[unique] = (new Date).getTime();
238 var count_viewers = function() {
239 if (viewer_count_override !== undefined) {
240 return viewer_count_override;
243 var now = (new Date).getTime();
245 // Go through and remove old viewers, and count them at the same time.
246 var new_last_seen_clients = {};
248 for (var unique in last_seen_clients) {
249 if (now - last_seen_clients[unique] < 5000) {
251 new_last_seen_clients[unique] = last_seen_clients[unique];
255 // Also add sleeping clients that we would otherwise assume timed out.
256 for (var request_id in sleeping_clients) {
257 var unique = sleeping_clients[request_id].unique;
258 if (unique && !(unique in new_last_seen_clients)) {
263 last_seen_clients = new_last_seen_clients;
266 var log = function(str) {
267 console.log("[" + ((new Date).getTime()*1e-3).toFixed(3) + "] " + str);
270 // Set up a watcher to catch changes to the file, then do an initial read
271 // to make sure we have a copy.
272 fs.watch(path.dirname(json_filename), reread_file);
273 reread_file(null, path.basename(json_filename));
275 if (COUNT_FROM_VARNISH_LOG) {
276 // Note: We abuse serve_url as a regex.
277 var varnishncsa = child_process.spawn(
278 'varnishncsa', ['-F', '%{%s}t %U %q tffb=%{Varnish:time_firstbyte}x',
279 '-q', 'ReqURL ~ "^' + serve_url + '"']);
280 var rl = readline.createInterface({
281 input: varnishncsa.stdout,
282 output: varnishncsa.stdin,
287 rl.on('line', function(line) {
288 var v = line.match(/(\d+) .*\?ims=\d+&unique=(.*) tffb=(.*)/);
291 last_seen: (parseInt(v[1]) + parseFloat(v[3])) * 1e3,
294 log(v[1] + " " + v[2] + " " + v[3]);
296 log("VARNISHNCSA UNPARSEABLE LINE: " + line);
299 setInterval(function() {
300 var mtime = json.last_modified - 1000; // Compensate for subsecond issues.
301 var now = (new Date).getTime();
304 for (var unique in uniques) {
306 var last_seen = uniques[unique].last_seen;
307 if (now - last_seen <= 5000) {
308 // We've seen this user in the last five seconds;
312 if (last_seen >= mtime) {
313 // This user has the latest version;
314 // they are probably just hanging.
317 if (uniques[unique].grace === null) {
318 // They have five seconds after a new JSON has been
319 // provided to get get it, or they're out.
320 // We don't simply use mtime, since we don't want to
321 // reset the grace timer just because a new JSON is
323 uniques[unique].grace = mtime;
325 if (now - uniques[unique].grace > 5000) {
326 log("Timing out " + unique + " (last_seen=" + last_seen + ", now=" + now +
327 ", mtime=" + mtime, ", grace=" + uniques[unique].grace + ")");
328 delete uniques[unique];
333 log(num_viewers + " entries in hash, mtime=" + mtime);
334 viewer_count_override = num_viewers;
338 var server = http.createServer();
339 server.on('request', function(request, response) {
340 var u = url.parse(request.url, true);
341 var ims = (u.query)['ims'];
342 var unique = (u.query)['unique'];
345 if (u.pathname === hash_serve_url) {
346 var fen = (u.query)['fen'];
347 hash_lookup.handle_request(fen, response);
350 if (u.pathname !== serve_url) {
351 // This is not the request you are looking for.
356 mark_recently_seen(unique);
358 var accept_encoding = request.headers['accept-encoding'];
360 if (accept_encoding !== undefined && accept_encoding.match(/\bgzip\b/)) {
366 // If we already have something newer than what the user has,
367 // just send it out and be done with it.
368 if (json !== undefined && (!ims || json.last_modified > ims)) {
369 send_json(response, ims, accept_gzip, count_viewers());
373 // OK, so we need to hang until we have something newer.
374 // Put the user on the wait list.
376 client.response = response;
377 client.request_id = request_id;
378 client.accept_gzip = accept_gzip;
379 client.unique = unique;
381 sleeping_clients[request_id++] = client;
383 request.socket.client = client;
385 server.on('connection', function(socket) {
386 socket.on('close', function() {
387 var client = socket.client;
389 mark_recently_seen(client.unique);
390 delete sleeping_clients[client.request_id];