-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathipc.js
598 lines (516 loc) · 16.7 KB
/
ipc.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
/**
* ipc.js
*
* Handles simple Interprocess (server) communication between multiple instances of
* an application, allowing voting to determine the master process.
*
* Released under the MIT License (MIT)
* Copyright (c) 2012 Paris Stamatopoulos
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
* following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var redis = require('redis');
var winston = require('winston');
var events = require('events');
var util = require('util');
var async = require('async');
var PackerEnum = {
JSON : 1
};
var Defaults = {
pid : process.pid,
packer : PackerEnum.JSON,
electionInterval : 60000,
redis : {
host : 'localhost',
port : 6379
}
};
var Ipc = function( serverId, options ) {
var self = this;
events.EventEmitter.call(this);
/**
* The current options
*
* @var array
*/
this._options = (options) ? (Defaults.extend(options)) : Defaults;
/**
* The redis client
*
* @var redis
*/
this._redis = redis.createClient( this._options.redis.port, this._options.redis.host );
/**
* The redis client for the IPC
*
* @var redis
*/
this._subscriber = redis.createClient( this._options.redis.port, this._options.redis.host );
/**
* The server id of this server process
*
* @var string
*/
this._serverId = serverId;
/**
* The sent votes for the Bully algorithm
*
* @var array
*/
this._sentVotes = [];
/**
* The bully timeout reference for the setTimeout
* section, that terminates an election
*
* @var array
*/
this._bullyTimeout = [];
/**
* The last result of the election
*
* @var array
*/
this._lastResult = [];
/**
* The election interval reference
*
* @var array
*/
this._electionInterval = [];
// Channel used for inter process communication
this._subscriber.subscribe( 'ipc::comm:' + this._serverId );
// Channel used for process elections
this._subscriber.subscribe( 'ipc::bully:' + this._serverId );
// Channel used for public messages
this._subscriber.subscribe( 'ipc::public' );
this._subscriber.on('message', function( channel, message ) {
try {
var message = self._unpack(message);
} catch( error ) {
winston.error("ipc: Unable to process recieved message. Ignoring");
return;
}
// Election message
if( channel == 'ipc::bully:' + self._serverId ) {
self._handleElectionMessage(message);
}
else {
/*
if( message.event !== undefined ) {
var ev = message.event;
delete message['event'];
self.emit(ev, message);
}
else
*/
self.emit('message', message);
}
});
};
util.inherits(Ipc, events.EventEmitter);
/**
* Send a message to a server
*
* @param string serverId The server id of the server to send the message
* @param object message The message to send to the server
* @param function fn The callback function (Optional)
*/
Ipc.prototype.sendMessage = function( serverId, message, fn ) {
this._redis.publish( 'ipc::comm:' + serverId, this._pack(message), function( error, result ) {
fn && fn(error, result);
});
};
/**
* Send a message to all servers
*
* @param object message The message to send to the server
* @param function fn The callback function
*/
Ipc.prototype.sendMessageToAll = function( message, fn ) {
this._redis.publish( 'ipc::public', this._pack(message), function(error, result) {
fn && fn(error, result);
});
};
/**
* Implements the Bully algorithm so that the processes can vote on issues
* and decide on who is going to run certain functions of the server. The election
* eventually will emit 'win', or 'lose' depending on the previous election status
* (will not emit if the status of the previous election is the same as this one)
*
* @param string election The name of the election to run
*/
Ipc.prototype._startElections = function( election ) {
var self = this;
if( !election ) {
election = 'default';
}
if( !this._sentVotes[election] ) {
this._sentVotes[election] = [];
}
async.series([
function( callback ) {
self._redis.smembers( 'ipc::election:' + election + ':candidates', function( error, result ) {
if( error || !result ) {
winston.error("Unable to get information for the servers participating in the election");
callback("Unable to get information about the servers running");
return;
}
result.forEach( function( serverId, serverNum ) {
self._redis.hget( 'ipc::server:details', serverId, function( error, details ) {
try {
var data = self._unpack( details );
} catch( error ) {
winston.debug("bully: Found junk data in the servers pool. Ignoring");
return;
}
if( data === undefined || data == null ) {
winston.debug("bully: Found a candidate with no server details. Ignore him");
return;
}
if( self._options.pid == data.process ) {
// This is me, don't mind me
if( serverNum == result.length - 1 ) {
callback && callback(null);
}
return;
}
self._sentVotes[election].push(serverId);
self._redis.publish(
'ipc::bully:' + serverId,
JSON.stringify({
type : 'vote',
election : election,
me : self._options.pid,
id : self._serverId
}), function( error, pResult ) {
if( !pResult ) {
winston.error("bully: Server with process " + data.process + " appears to be offline. Cleaning up");
// Should the emit be sent to the winner only?
self.emit('dead', {
process: data.process,
id: serverId
});
self.markProcessOffline( serverId );
var pos = self._sentVotes[election].indexOf(serverId);
if( pos != -1 ) {
self._sentVotes[election].splice(pos,1);
}
}
else {
winston.debug("bully: Sent vote message to server " + serverId);
}
if( serverNum == result.length - 1) {
callback && callback(null);
}
});
});
});
});
},
function( callback ) {
winston.debug("bully: Finished sending votes to all alive members of the cluster");
self._bullyTimeout[election] = setTimeout(function() {
if( self._sentVotes[election].length == 0 ) {
winston.debug("bully: Vote timeout has ended for election " + election + ". It looks like I am the winner. Hooray!");
if( self._lastResult[election] != 1 ) {
self.emit('won');
}
self._lastResult[election] = 1;
}
else {
//console.log(self._sentVotes[election]);
winston.debug("bully: Election " + election + " appears to be non conclusive. Try again later");
self._sentVotes[election] = [];
self._lastResult[election] = -1;
return;
}
}, 10000);
}
]);
};
/**
* Mark the process as being a candidate for the elections. This will start a new
* round of elections until the process quitElection().
*
* @param string election The election to run for
*/
Ipc.prototype.runForPresident = function( election ) {
var self = this;
if( !election ) {
election = 'default';
}
this._redis.multi()
.sadd( 'ipc::election:' + this._serverId + ':participated', election )
.sadd( 'ipc::election:' + election + ':candidates', this._serverId )
.exec( function( error, result ) {
if( !error ) {
winston.debug("ipc:: Starting elections for election " + election);
self._startElections(election);
self._electionInterval[election] = setInterval(function() {
self._startElections(election);
}, self._options.electionInterval);
}
else {
winston.error("ipc: Unable to add process as a candidate for elections for " + election);
}
});
};
/**
* Removes the process from the candidates for the elections. This will stop
* all elections initiated from this process
*
* @param string election The election to quit
*/
Ipc.prototype.quitElection = function( election ) {
var self = this;
if( !election ) {
election = 'default';
}
if( this._electionInterval[election] !== undefined ) {
this._redis.multi()
.srem( 'ipc::election:' + this._serverId + ':participated', election )
.srem( 'ipc::election:' + election + ':candidates', this._serverId )
.exec( function( error, result ) {
if( !error ) {
clearInterval(self._electionInterval[election]);
delete self._electionInterval[election];
}
else {
winston.error("ipc: Unable to remove process from election candidates for election " + election);
}
});
}
else {
winston.info("ipc: Process is not a candidate for election " + election);
}
};
/**
* Handles the responses from the Bully election replying back to the initiator of the election
*
* @param object message The message received
*/
Ipc.prototype._handleElectionMessage = function( message ) {
var self = this;
switch( message.type ) {
case 'vote':
if( message.me > this._options.pid ) {
winston.debug("bully: Received vote message from server " + message.id + " (PID: " + message.me
+ ") while I have pid " + this._options.pid + " for election " + message.election + ". I must obey");
this._redis.publish(
'ipc::bully:' + message.id,
this._pack({
type : 'voteack',
me : this._options.pid,
id : this._serverId,
election : message.election
}),
function( error, result ) {
if( self._lastResult[message.election] != 0 ) {
self.emit('lost');
}
self._lastResult[message.election] = 0;
if( self._bullyTimeout[message.election] ) {
clearTimeout(self._bullyTimeout[message.election]);
}
});
}
else if( message.me < this._options.pid ) {
winston.debug("bully: Received vote message from server " + message.id + " (PID: " + message.me
+ ") while I have pid " + this._options.pid + " for election " + message.election + ". Tough luck");
this._redis.publish(
'ipc::bully:' + message.id,
this._pack({
type : 'votekick',
me : this._options.pid,
id : this._serverId,
election : message.election
}),
function( error, result ) {
});
}
break;
case 'voteack':
var pos = this._sentVotes[message.election].indexOf(message.id);
if( pos != -1 ) {
this._sentVotes[message.election].splice(pos,1);
}
winston.debug("bully: Received voteack from server " + message.id + " (PID: " + message.me
+ ") for election " + message.election + ". Another one bites the dust");
break;
case 'votekick':
winston.debug("bully: Received votekick from server " + message.id + " (PID: " + message.me
+ ") for election " + message.election + ". Shame on me for trying to become the king.");
this._sentVotes[message.election] = [];
if( self._lastResult[message.election] != 0 ) {
this.emit('lost');
}
self._lastResult[message.election] = 0;
clearTimeout(self._bullyTimeout[message.election]);
break;
}
};
/**
* Get the status of the last election
*
* @param string election The election to get the status of
*
* @return int
*/
Ipc.prototype.getLastStatus = function( election ) {
return self._lastResult[election];
};
/**
* Mark the process as being online on the system
*
*/
Ipc.prototype.markProcessOnline = function( fn ) {
var self = this;
var _markOnline = function() {
self._redis.multi()
.sadd( 'ipc::server:list', self._serverId )
.hset( 'ipc::server:details', self._serverId, self._pack({
process: self._options.pid,
timestamp: new Date()
}))
.exec(function( error, result ) {
fn && fn();
});
};
this._redis.sismember( 'ipc::server:list', this._serverId, function(error, result) {
if( result ) {
winston.info("ipc: Found a server with the same server id (" + self._serverId + "). Overwriting...");
self.markProcessOffline( self._serverId, function() {
_markOnline();
});
}
else {
_markOnline();
}
});
};
/**
* Mark the process as being offline on the system
*
* @param string serverId Optional
* @param function fn
*/
Ipc.prototype.markProcessOffline = function( serverId, fn ) {
var self = this;
this._redis.multi()
.srem( 'ipc::server:list', serverId || this._serverId )
.hdel( 'ipc::server:details', serverId || this._serverId )
.exec( function( error, result ) {
self._removeParticipantFromAllElections(serverId, function() {
fn && fn();
});
});
};
/**
* Remove a participart from all the elections he is a part of
*
* @param int serverId The serverId to remove
* @param function fn
*/
Ipc.prototype._removeParticipantFromAllElections = function( serverId, fn ) {
var self = this;
this._redis.smembers( 'ipc::election:' + serverId + ':participated', function( error, result ) {
if( error && !result ) {
winston.error("Unable to get list of elections this server has participated");
fn && fn(error);
return;
}
result.forEach(function(election, index) {
self._redis.srem( 'ipc::election:' + election + ':candidates', serverId, function(error) {
if( error ) {
winston.error("Unable to remove candidate " + serverId + " from election " + election);
return;
}
});
if( index == result.length - 1) {
fn && fn(null);
}
});
});
};
/**
* Store the winner of the election
*
*/
Ipc.prototype._markMeAsWinner = function() {
this._redis.set('ipc::election:winner', this._pack( { serverId: this._serverId, pid: this._options.pid }));
};
/**
* Get winner of the election
*
* @param function fn The callback function
*/
Ipc.prototype.getCurrentWinner = function( fn ) {
this._redis.get('ipc::election:winner', function(error, result) {
fn && fn(error, result);
});
};
/**
* Get server process details
*
* @param string serverId The server id to retrieve the details of
* @param function callback The callback function
*/
Ipc.prototype.getProcessDetails = function( serverId, callback ) {
var self = this;
this._redis.hget( 'ipc::server:details', serverId, function( error, result ) {
if( error ) {
callback(error);
}
else {
try {
var details = self._unpack(result);
} catch( error ) {
callback("Unable to parse process details. Not in JSON");
return;
}
callback(null, details);
}
});
};
/**
* Pack a message
*
* @todo Add msgpack?
* @param object message
*/
Ipc.prototype._pack = function( message ) {
switch( this._options.packer ) {
case PackerEnum.JSON:
return JSON.stringify(message);
default:
throw "Unable to pack message. Invalid packer specified";
}
};
/**
* Unpack a message
*
* @todo Add msgpack?
* @param object message
*/
Ipc.prototype._unpack = function( message ) {
switch( this._options.packer ) {
case PackerEnum.JSON:
return JSON.parse(message);
default:
throw "Unable to unpack message. Invalid packer specified";
}
};
module.exports = Ipc;