-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathConnectionManager.js
735 lines (610 loc) · 21.6 KB
/
ConnectionManager.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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
/**
* Copyright (c) 2013 Yahoo! Inc. All rights reserved.
*
* Copyrights licensed under the MIT License. See the accompanying LICENSE file
* for terms.
*/
var net = require('net');
var utils = require('util');
var events = require('events');
var jute = require('./jute');
var ConnectionStringParser = require('./ConnectionStringParser.js');
var WatcherManager = require('./WatcherManager.js');
var PacketQueue = require('./PacketQueue.js');
var Exception = require('./Exception.js');
/**
* This class manages the connection between the client and the ensemble.
*
* @module node-zookeeper-client
*/
// Constants.
var STATES = { // Connection States.
DISCONNECTED : 0,
CONNECTING : 1,
CONNECTED : 2,
CONNECTED_READ_ONLY : 3,
CLOSING : -1,
CLOSED : -2,
SESSION_EXPIRED : -3,
AUTHENTICATION_FAILED : -4
};
/**
* Construct a new ConnectionManager instance.
*
* @class ConnectionStringParser
* @constructor
* @param connectionString {String} ZooKeeper server ensemble string.
* @param options {Object} Client options.
* @param stateListener {Object} Listener for state changes.
*/
function ConnectionManager(connectionString, options, stateListener) {
events.EventEmitter.call(this);
this.watcherManager = new WatcherManager();
this.connectionStringParser = new ConnectionStringParser(connectionString);
this.servers = this.connectionStringParser.getServers();
this.chrootPath = this.connectionStringParser.getChrootPath();
this.nextServerIndex = 0;
this.serverAttempts = 0;
this.state = STATES.DISCONNECTED;
this.options = options;
this.spinDelay = options.spinDelay;
this.updateTimeout(options.sessionTimeout);
this.connectTimeoutHandler = null;
this.xid = 0;
this.sessionId = Buffer.alloc(8);
if (Buffer.isBuffer(options.sessionId)) {
options.sessionId.copy(this.sessionId);
} else {
this.sessionId.fill(0);
}
this.sessionPassword = Buffer.alloc(16);
if (Buffer.isBuffer(options.sessionPassword)) {
options.sessionPassword.copy(this.sessionPassword);
} else {
this.sessionPassword.fill(0);
}
// scheme:auth pairs
this.credentials = [];
// Last seen zxid.
this.zxid = Buffer.alloc(8);
this.zxid.fill(0);
this.pendingBuffer = null;
this.packetQueue = new PacketQueue();
this.packetQueue.on('readable', this.onPacketQueueReadable.bind(this));
this.pendingQueue = [];
this.on('state', stateListener);
}
utils.inherits(ConnectionManager, events.EventEmitter);
/**
* Update the session timeout and related timeout variables.
*
* @method updateTimeout
* @private
* @param sessionTimeout {Number} Milliseconds of the timeout value.
*/
ConnectionManager.prototype.updateTimeout = function (sessionTimeout) {
this.sessionTimeout = sessionTimeout;
// Designed to have time to try all the servers.
this.connectTimeout = Math.floor(sessionTimeout / this.servers.length);
// We at least send out one ping one third of the session timeout, so
// the read timeout is two third of the session timeout.
this.pingTimeout = Math.floor(this.sessionTimeout / 3);
// this.readTimeout = Math.floor(sessionTimeout * 2 / 3);
};
/**
* Find the next available server to connect. If all server has been tried,
* it will wait for a random time between 0 to spin delay before call back
* with the next server.
*
* callback prototype:
* callback(server);
*
* @method findNextServer
* @param callback {Function} callback function.
*
*/
ConnectionManager.prototype.findNextServer = function (callback) {
var self = this;
self.nextServerIndex %= self.servers.length;
if (self.serverAttempts === self.servers.length) {
setTimeout(function () {
callback(self.servers[self.nextServerIndex]);
self.nextServerIndex += 1;
// reset attempts since we already waited for enough time.
self.serverAttempts = 0;
}, Math.random() * self.spinDelay);
} else {
self.serverAttempts += 1;
process.nextTick(function () {
callback(self.servers[self.nextServerIndex]);
self.nextServerIndex += 1;
});
}
};
/**
* Change the current state to the given state if the given state is different
* from current state. Emit the state change event with the changed state.
*
* @method setState
* @param state {Number} The state to be set.
*/
ConnectionManager.prototype.setState = function (state) {
if (typeof state !== 'number') {
throw new Error('state must be a valid number.');
}
if (this.state !== state) {
this.state = state;
this.emit('state', this.state);
}
};
ConnectionManager.prototype.registerDataWatcher = function (path, watcher) {
this.watcherManager.registerDataWatcher(path, watcher);
};
ConnectionManager.prototype.registerChildWatcher = function (path, watcher) {
this.watcherManager.registerChildWatcher(path, watcher);
};
ConnectionManager.prototype.registerExistenceWatcher = function (path, watcher) {
this.watcherManager.registerExistenceWatcher(path, watcher);
};
ConnectionManager.prototype.cleanupPendingQueue = function (errorCode) {
var pendingPacket = this.pendingQueue.shift();
while (pendingPacket) {
if (pendingPacket.callback) {
pendingPacket.callback(Exception.create(errorCode));
}
pendingPacket = this.pendingQueue.shift();
}
};
ConnectionManager.prototype.getSessionId = function () {
var result = Buffer.alloc(8);
this.sessionId.copy(result);
return result;
};
ConnectionManager.prototype.getSessionPassword = function () {
var result = Buffer.alloc(16);
this.sessionPassword.copy(result);
return result;
};
ConnectionManager.prototype.getSessionTimeout = function () {
return this.sessionTimeout;
};
ConnectionManager.prototype.connect = function () {
var self = this;
self.setState(STATES.CONNECTING);
self.findNextServer(function (server) {
self.socket = net.connect(server);
self.connectTimeoutHandler = setTimeout(
self.onSocketConnectTimeout.bind(self),
self.connectTimeout
);
// Disable the Nagle algorithm.
self.socket.setNoDelay();
self.socket.on('connect', self.onSocketConnected.bind(self));
self.socket.on('data', self.onSocketData.bind(self));
self.socket.on('drain', self.onSocketDrain.bind(self));
self.socket.on('close', self.onSocketClosed.bind(self));
self.socket.on('error', self.onSocketError.bind(self));
});
};
ConnectionManager.prototype.close = function () {
var self = this,
header = new jute.protocol.RequestHeader(),
request;
self.setState(STATES.CLOSING);
header.type = jute.OP_CODES.CLOSE_SESSION;
request = new jute.Request(header, null);
self.queue(request);
};
ConnectionManager.prototype.onSocketClosed = function (hasError) {
var retry = false,
errorCode,
pendingPacket;
switch (this.state) {
case STATES.CLOSING:
errorCode = Exception.CONNECTION_LOSS;
retry = false;
break;
case STATES.SESSION_EXPIRED:
errorCode = Exception.SESSION_EXPIRED;
retry = false;
break;
case STATES.AUTHENTICATION_FAILED:
errorCode = Exception.AUTH_FAILED;
retry = false;
break;
default:
errorCode = Exception.CONNECTION_LOSS;
retry = true;
}
this.cleanupPendingQueue(errorCode);
this.setState(STATES.DISCONNECTED);
if (retry) {
this.connect();
} else {
this.setState(STATES.CLOSED);
}
};
ConnectionManager.prototype.onSocketError = function (error) {
if (this.connectTimeoutHandler) {
clearTimeout(this.connectTimeoutHandler);
}
// After socket error, the socket closed event will be triggered,
// we will retry connect in that listener function.
};
ConnectionManager.prototype.onSocketConnectTimeout = function () {
// Destroy the current socket so the socket closed event
// will be trigger.
this.socket.destroy();
};
ConnectionManager.prototype.onSocketConnected = function () {
var connectRequest,
authRequest,
setWatchesRequest,
header,
payload;
if (this.connectTimeoutHandler) {
clearTimeout(this.connectTimeoutHandler);
}
connectRequest = new jute.Request(null, new jute.protocol.ConnectRequest(
jute.PROTOCOL_VERSION,
this.zxid,
this.sessionTimeout,
this.sessionId,
this.sessionPassword
));
// XXX No read only support yet.
this.socket.write(connectRequest.toBuffer());
// Set auth info
if (this.credentials.length > 0) {
this.credentials.forEach(function (credential) {
header = new jute.protocol.RequestHeader();
payload = new jute.protocol.AuthPacket();
header.xid = jute.XID_AUTHENTICATION;
header.type = jute.OP_CODES.AUTH;
payload.type = 0;
payload.scheme = credential.scheme;
payload.auth = credential.auth;
authRequest = new jute.Request(header, payload);
this.queue(authRequest);
}, this);
}
// Reset the watchers if we have any.
if (!this.watcherManager.isEmpty()) {
header = new jute.protocol.RequestHeader();
payload = new jute.protocol.SetWatches();
header.type = jute.OP_CODES.SET_WATCHES;
header.xid = jute.XID_SET_WATCHES;
payload.setChrootPath(this.chrootPath);
payload.relativeZxid = this.zxid;
payload.dataWatches = this.watcherManager.getDataWatcherPaths();
payload.existWatches = this.watcherManager.getExistenceWatcherPaths();
payload.childWatches = this.watcherManager.getChildWatcherPaths();
setWatchesRequest = new jute.Request(header, payload);
this.queue(setWatchesRequest);
}
};
ConnectionManager.prototype.onSocketTimeout = function () {
var header,
request;
if (this.socket &&
(this.state === STATES.CONNECTED ||
this.state === STATES.CONNECTED_READ_ONLY)) {
header = new jute.protocol.RequestHeader(
jute.XID_PING,
jute.OP_CODES.PING
);
request = new jute.Request(header, null);
this.queue(request);
// Re-register the timeout handler since it only fired once.
this.socket.setTimeout(
this.pingTimeout,
this.onSocketTimeout.bind(this)
);
}
};
/* eslint-disable complexity,max-depth */
ConnectionManager.prototype.onSocketData = function (buffer) {
var self = this,
offset = 0,
size = 0,
connectResponse,
pendingPacket,
responseHeader,
responsePayload,
response,
event;
// Combine the pending buffer with the new buffer.
if (self.pendingBuffer) {
buffer = Buffer.concat(
[self.pendingBuffer, buffer],
self.pendingBuffer.length + buffer.length
);
}
// We need at least 4 bytes
if (buffer.length < 4) {
self.pendingBuffer = buffer;
return;
}
size = buffer.readInt32BE(offset);
offset += 4;
if (buffer.length < size + 4) {
// More data are coming.
self.pendingBuffer = buffer;
return;
}
if (buffer.length === size + 4) {
// The size is perfect.
self.pendingBuffer = null;
} else {
// We have extra bytes, splice them out as pending buffer.
self.pendingBuffer = buffer.slice(size + 4);
buffer = buffer.slice(0, size + 4);
}
if (self.state === STATES.CONNECTING) {
// Handle connect response.
connectResponse = new jute.protocol.ConnectResponse();
offset += connectResponse.deserialize(buffer, offset);
if (connectResponse.timeOut <= 0) {
self.setState(STATES.SESSION_EXPIRED);
} else {
// Reset the server connection attempts since we connected now.
self.serverAttempts = 0;
self.sessionId = connectResponse.sessionId;
self.sessionPassword = connectResponse.passwd;
self.updateTimeout(connectResponse.timeOut);
self.setState(STATES.CONNECTED);
// Check if we have anything to send out just in case.
self.onPacketQueueReadable();
self.socket.setTimeout(
self.pingTimeout,
self.onSocketTimeout.bind(self)
);
}
} else {
// Handle all other repsonses.
responseHeader = new jute.protocol.ReplyHeader();
offset += responseHeader.deserialize(buffer, offset);
// TODO BETTTER LOGGING
switch (responseHeader.xid) {
case jute.XID_PING:
break;
case jute.XID_AUTHENTICATION:
if (responseHeader.err === Exception.AUTH_FAILED) {
self.setState(STATES.AUTHENTICATION_FAILED);
}
break;
case jute.XID_NOTIFICATION:
event = new jute.protocol.WatcherEvent();
if (self.chrootPath) {
event.setChrootPath(self.chrootPath);
}
offset += event.deserialize(buffer, offset);
self.watcherManager.emit(event);
break;
default:
pendingPacket = self.pendingQueue.shift();
if (!pendingPacket) {
// TODO, better error handling and logging need to be done.
// Need to clean up and do a reconnect.
// throw new Error(
// 'Nothing in pending queue but got data from server.'
// );
self.socket.destroy(); // this will trigger reconnect
return;
}
if (pendingPacket.request.header.xid !== responseHeader.xid) {
// TODO, better error handling/logging need to bee done here.
// Need to clean up and do a reconnect.
// throw new Error(
// 'Xid out of order. Got xid: ' +
// responseHeader.xid + ' with error code: ' +
// responseHeader.err + ', expected xid: ' +
// pendingPacket.request.header.xid + '.'
// );
self.socket.destroy(); // this will trigger reconnect
return;
}
if (responseHeader.zxid) {
// TODO, In Java implementation, the condition is to
// check whether the long zxid is greater than 0, here
// use buffer so we simplify.
// Need to figure out side effect.
self.zxid = responseHeader.zxid;
}
if (responseHeader.err === 0) {
switch (pendingPacket.request.header.type) {
case jute.OP_CODES.CREATE:
responsePayload = new jute.protocol.CreateResponse();
break;
case jute.OP_CODES.DELETE:
responsePayload = null;
break;
case jute.OP_CODES.GET_CHILDREN2:
responsePayload = new jute.protocol.GetChildren2Response();
break;
case jute.OP_CODES.EXISTS:
responsePayload = new jute.protocol.ExistsResponse();
break;
case jute.OP_CODES.SET_DATA:
responsePayload = new jute.protocol.SetDataResponse();
break;
case jute.OP_CODES.GET_DATA:
responsePayload = new jute.protocol.GetDataResponse();
break;
case jute.OP_CODES.SET_ACL:
responsePayload = new jute.protocol.SetACLResponse();
break;
case jute.OP_CODES.GET_ACL:
responsePayload = new jute.protocol.GetACLResponse();
break;
case jute.OP_CODES.SET_WATCHES:
responsePayload = null;
break;
case jute.OP_CODES.CLOSE_SESSION:
responsePayload = null;
break;
case jute.OP_CODES.MULTI:
responsePayload = new jute.TransactionResponse();
break;
default:
// throw new Error('Unknown request OP_CODE: ' +
// pendingPacket.request.header.type);
self.socket.destroy(); // this will trigger reconnect
return;
}
if (responsePayload) {
if (self.chrootPath) {
responsePayload.setChrootPath(self.chrootPath);
}
offset += responsePayload.deserialize(buffer, offset);
}
if (pendingPacket.callback) {
pendingPacket.callback(
null,
new jute.Response(responseHeader, responsePayload)
);
}
} else if (pendingPacket.callback) {
pendingPacket.callback(
Exception.create(responseHeader.err),
new jute.Response(responseHeader, null)
);
}
}
}
// We have more data to process, need to recursively process it.
if (self.pendingBuffer) {
self.onSocketData(Buffer.alloc(0));
}
};
/* eslint-enable complexity,max-depth */
ConnectionManager.prototype.onSocketDrain = function () {
// Trigger write on socket.
this.onPacketQueueReadable();
};
ConnectionManager.prototype.onPacketQueueReadable = function () {
var packet,
header;
switch (this.state) {
case STATES.CONNECTED:
case STATES.CONNECTED_READ_ONLY:
case STATES.CLOSING:
// Continue
break;
case STATES.DISCONNECTED:
case STATES.CONNECTING:
case STATES.CLOSED:
case STATES.SESSION_EXPIRED:
case STATES.AUTHENTICATION_FAILED:
// Skip since we can not send traffic out
return;
default:
throw new Error('Unknown state: ' + this.state);
}
while ((packet = this.packetQueue.shift()) !== undefined) {
header = packet.request.header;
if (header !== null &&
header.type !== jute.OP_CODES.PING &&
header.type !== jute.OP_CODES.AUTH) {
header.xid = this.xid;
this.xid += 1;
// Only put requests that are not connect, ping and auth into
// the pending queue.
this.pendingQueue.push(packet);
}
if (!this.socket.write(packet.request.toBuffer())) {
// Back pressure is handled here, when the socket emit
// drain event, this method will be invoked again.
break;
}
if (header.type === jute.OP_CODES.CLOSE_SESSION) {
// The close session should be the final packet sent to the
// server.
break;
}
}
};
ConnectionManager.prototype.addAuthInfo = function (scheme, auth) {
if (!scheme || typeof scheme !== 'string') {
throw new Error('scheme must be a non-empty string.');
}
if (!Buffer.isBuffer(auth)) {
throw new Error('auth must be a valid instance of Buffer');
}
var header,
payload,
request;
this.credentials.push({
scheme : scheme,
auth : auth
});
switch (this.state) {
case STATES.CONNECTED:
case STATES.CONNECTED_READ_ONLY:
// Only queue the auth request when connected.
header = new jute.protocol.RequestHeader();
payload = new jute.protocol.AuthPacket();
header.xid = jute.XID_AUTHENTICATION;
header.type = jute.OP_CODES.AUTH;
payload.type = 0;
payload.scheme = scheme;
payload.auth = auth;
this.queue(new jute.Request(header, payload));
break;
case STATES.DISCONNECTED:
case STATES.CONNECTING:
case STATES.CLOSING:
case STATES.CLOSED:
case STATES.SESSION_EXPIRED:
case STATES.AUTHENTICATION_FAILED:
// Skip when we are not in a live state.
return;
default:
throw new Error('Unknown state: ' + this.state);
}
};
ConnectionManager.prototype.queue = function (request, callback) {
if (typeof request !== 'object') {
throw new Error('request must be a valid instance of jute.Request.');
}
if (this.chrootPath && request.payload) {
request.payload.setChrootPath(this.chrootPath);
}
callback = callback || function () {};
switch (this.state) {
case STATES.DISCONNECTED:
case STATES.CONNECTING:
case STATES.CONNECTED:
case STATES.CONNECTED_READ_ONLY:
// queue the packet
this.packetQueue.push({
request : request,
callback : callback
});
break;
case STATES.CLOSING:
if (request.header &&
request.header.type === jute.OP_CODES.CLOSE_SESSION) {
this.packetQueue.push({
request : request,
callback : callback
});
} else {
callback(Exception.create(Exception.CONNECTION_LOSS));
}
break;
case STATES.CLOSED:
callback(Exception.create(Exception.CONNECTION_LOSS));
return;
case STATES.SESSION_EXPIRED:
callback(Exception.create(Exception.SESSION_EXPIRED));
return;
case STATES.AUTHENTICATION_FAILED:
callback(Exception.create(Exception.AUTH_FAILED));
return;
default:
throw new Error('Unknown state: ' + this.state);
}
};
module.exports = ConnectionManager;
module.exports.STATES = STATES;