-
Notifications
You must be signed in to change notification settings - Fork 147
/
index.js
996 lines (847 loc) · 27.2 KB
/
index.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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
/**
* Copyright (c) 2013 Yahoo! Inc. All rights reserved.
*
* Copyrights licensed under the MIT License. See the accompanying LICENSE file
* for terms.
*/
/**
*
* A pure Javascript ZooKeeper client.
*
* @module node-zookeeper-client
*
*/
var assert = require('assert');
var events = require('events');
var util = require('util');
var net = require('net');
var async = require('async');
var u = require('underscore');
var jute = require('./lib/jute');
var ACL = require('./lib/ACL.js');
var Id = require('./lib/Id.js');
var Path = require('./lib/Path.js');
var Event = require('./lib/Event.js');
var State = require('./lib/State.js');
var Permission = require('./lib/Permission.js');
var CreateMode = require('./lib/CreateMode.js');
var Exception = require('./lib/Exception');
var Transaction = require('./lib/Transaction.js');
var ConnectionManager = require('./lib/ConnectionManager.js');
// Constants.
var CLIENT_DEFAULT_OPTIONS = {
sessionTimeout : 30000, // Default to 30 seconds.
spinDelay : 1000, // Defaults to 1 second.
retries : 0 // Defaults to 0, no retry.
};
var DATA_SIZE_LIMIT = 1048576; // 1 mega bytes.
/**
* Default state listener to emit user-friendly events.
*/
function defaultStateListener(state) {
switch (state) {
case State.DISCONNECTED:
this.emit('disconnected');
break;
case State.SYNC_CONNECTED:
this.emit('connected');
break;
case State.CONNECTED_READ_ONLY:
this.emit('connectedReadOnly');
break;
case State.EXPIRED:
this.emit('expired');
break;
case State.AUTH_FAILED:
this.emit('authenticationFailed');
break;
default:
return;
}
}
/**
* Try to execute the given function 'fn'. If it fails to execute, retry for
* 'self.options.retires' times. The duration between each retry starts at
* 1000ms and grows exponentially as:
*
* duration = Math.min(1000 * Math.pow(2, attempts), sessionTimeout)
*
* When the given function is executed successfully or max retry has been
* reached, an optional callback function will be invoked with the error (if
* any) and the result.
*
* fn prototype:
* function(attempts, next);
* attempts: tells you what is the current execution attempts. It starts with 0.
* next: You invoke the next function when complete or there is an error.
*
* next prototype:
* function(error, ...);
* error: The error you encounter in the operation.
* other arguments: Will be passed to the optional callback
*
* callback prototype:
* function(error, ...)
*
* @private
* @method attempt
* @param self {Client} an instance of zookeeper client.
* @param fn {Function} the function to execute.
* @param callback {Function} optional callback function.
*
*/
function attempt(self, fn, callback) {
var count = 0,
retry = true,
retries = self.options.retries,
results = {};
assert(typeof fn === 'function', 'fn must be a function.');
assert(
typeof retries === 'number' && retries >= 0,
'retries must be an integer greater or equal to 0.'
);
assert(typeof callback === 'function', 'callback must be a function.');
async.whilst(
function (next) {
return next(null, count <= retries && retry);
},
function (next) {
var attempts = count;
count += 1;
fn(attempts, function (error) {
var args,
sessionTimeout;
results[attempts] = {};
results[attempts].error = error;
if (arguments.length > 1) {
args = Array.prototype.slice.apply(arguments);
results[attempts].args = args.slice(1);
}
if (error && error.code === Exception.CONNECTION_LOSS) {
retry = true;
} else {
retry = false;
}
if (!retry || count > retries) {
// call next so we can get out the loop without delay
next();
} else {
sessionTimeout = self.connectionManager.getSessionTimeout();
// Exponentially back-off
setTimeout(
next,
Math.min(1000 * Math.pow(2, attempts), sessionTimeout)
);
}
});
},
function (error) {
var args = [],
result = results[count - 1];
if (callback) {
args.push(result.error);
Array.prototype.push.apply(args, result.args);
callback.apply(null, args);
}
}
);
}
/**
* The ZooKeeper client constructor.
*
* @class Client
* @constructor
* @param connectionString {String} ZooKeeper server ensemble string.
* @param [options] {Object} client options.
*/
function Client(connectionString, options) {
if (!(this instanceof Client)) {
return new Client(connectionString, options);
}
events.EventEmitter.call(this);
options = options || {};
assert(
connectionString && typeof connectionString === 'string',
'connectionString must be an non-empty string.'
);
assert(
typeof options === 'object',
'options must be a valid object'
);
options = u.defaults(u.clone(options), CLIENT_DEFAULT_OPTIONS);
this.connectionManager = new ConnectionManager(
connectionString,
options,
this.onConnectionManagerState.bind(this)
);
this.options = options;
this.state = State.DISCONNECTED;
this.on('state', defaultStateListener);
}
util.inherits(Client, events.EventEmitter);
/**
* Start the client and try to connect to the ensemble.
*
* @method connect
*/
Client.prototype.connect = function () {
this.connectionManager.connect();
};
/**
* Shutdown the client.
*
* @method connect
*/
Client.prototype.close = function () {
this.connectionManager.close();
};
/**
* Private method to translate connection manager state into client state.
*/
Client.prototype.onConnectionManagerState = function (connectionManagerState) {
var state;
// Convert connection state to ZooKeeper state.
switch (connectionManagerState) {
case ConnectionManager.STATES.DISCONNECTED:
state = State.DISCONNECTED;
break;
case ConnectionManager.STATES.CONNECTED:
state = State.SYNC_CONNECTED;
break;
case ConnectionManager.STATES.CONNECTED_READ_ONLY:
state = State.CONNECTED_READ_ONLY;
break;
case ConnectionManager.STATES.SESSION_EXPIRED:
state = State.EXPIRED;
break;
case ConnectionManager.STATES.AUTHENTICATION_FAILED:
state = State.AUTH_FAILED;
break;
default:
// Not a event in which client is interested, so skip it.
return;
}
if (this.state !== state) {
this.state = state;
this.emit('state', this.state);
}
};
/**
* Returns the state of the client.
*
* @method getState
* @return {State} the state of the client.
*/
Client.prototype.getState = function () {
return this.state;
};
/**
* Returns the session id for this client instance. The value returned is not
* valid until the client connects to a server and may change after a
* re-connect.
*
* @method getSessionId
* @return {Buffer} the session id, 8 bytes long buffer.
*/
Client.prototype.getSessionId = function () {
return this.connectionManager.getSessionId();
};
/**
* Returns the session password for this client instance. The value returned
* is not valid until the client connects to a server and may change after a
* re-connect.
*
* @method getSessionPassword
* @return {Buffer} the session password, 16 bytes buffer.
*/
Client.prototype.getSessionPassword = function () {
return this.connectionManager.getSessionPassword();
};
/**
* Returns the negotiated session timeout for this client instance. The value
* returned is not valid until the client connects to a server and may change
* after a re-connect.
*
* @method getSessionTimeout
* @return {Integer} the session timeout value.
*/
Client.prototype.getSessionTimeout = function () {
return this.connectionManager.getSessionTimeout();
};
/**
* Add the specified scheme:auth information to this client.
*
* @method addAuthInfo
* @param scheme {String} The authentication scheme.
* @param auth {Buffer} The authentication data buffer.
*/
Client.prototype.addAuthInfo = function (scheme, auth) {
assert(
scheme || typeof scheme === 'string',
'scheme must be a non-empty string.'
);
assert(
Buffer.isBuffer(auth),
'auth must be a valid instance of Buffer'
);
var buffer = Buffer.alloc(auth.length);
auth.copy(buffer);
this.connectionManager.addAuthInfo(scheme, buffer);
};
/**
* Create a node with given path, data, acls and mode.
*
* @method create
* @param path {String} The node path.
* @param [data=undefined] {Buffer} The data buffer.
* @param [acls=ACL.OPEN_ACL_UNSAFE] {Array} An array of ACL object.
* @param [mode=CreateMode.PERSISTENT] {CreateMode} The creation mode.
* @param callback {Function} The callback function.
*/
Client.prototype.create = function (path, data, acls, mode, callback) {
var self = this,
optionalArgs = [data, acls, mode, callback],
header,
payload,
request;
Path.validate(path);
// Reset arguments so we can reassign correct value to them.
data = acls = mode = callback = undefined;
optionalArgs.forEach(function (arg, index) {
if (Array.isArray(arg)) {
acls = arg;
} else if (typeof arg === 'number') {
mode = arg;
} else if (Buffer.isBuffer(arg)) {
data = arg;
} else if (typeof arg === 'function') {
callback = arg;
}
});
assert(
typeof callback === 'function',
'callback must be a function.'
);
acls = Array.isArray(acls) ? acls : ACL.OPEN_ACL_UNSAFE;
mode = typeof mode === 'number' ? mode : CreateMode.PERSISTENT;
assert(
data === null || data === undefined || Buffer.isBuffer(data),
'data must be a valid buffer, null or undefined.'
);
if (Buffer.isBuffer(data)) {
assert(
data.length <= DATA_SIZE_LIMIT,
'data must be equal of smaller than ' + DATA_SIZE_LIMIT + ' bytes.'
);
}
assert(acls.length > 0, 'acls must be a non-empty array.');
header = new jute.protocol.RequestHeader();
header.type = jute.OP_CODES.CREATE;
payload = new jute.protocol.CreateRequest();
payload.path = path;
payload.acl = acls.map(function (item) {
return item.toRecord();
});
payload.flags = mode;
if (Buffer.isBuffer(data)) {
payload.data = Buffer.alloc(data.length);
data.copy(payload.data);
}
request = new jute.Request(header, payload);
attempt(
self,
function (attempts, next) {
self.connectionManager.queue(request, function (error, response) {
if (error) {
next(error);
return;
}
next(null, response.payload.path);
});
},
callback
);
};
/**
* Delete a node with the given path. If version is not -1, the request will
* fail when the provided version does not match the server version.
*
* @method delete
* @param path {String} The node path.
* @param [version=-1] {Number} The version of the node.
* @param callback {Function} The callback function.
*/
Client.prototype.remove = function (path, version, callback) {
if (!callback) {
callback = version;
version = -1;
}
Path.validate(path);
assert(typeof callback === 'function', 'callback must be a function.');
assert(typeof version === 'number', 'version must be a number.');
var self = this,
header = new jute.protocol.RequestHeader(),
payload = new jute.protocol.DeleteRequest(),
request;
header.type = jute.OP_CODES.DELETE;
payload.path = path;
payload.version = version;
request = new jute.Request(header, payload);
attempt(
self,
function (attempts, next) {
self.connectionManager.queue(request, function (error, response) {
next(error);
});
},
callback
);
};
/**
* Deletes a node and all its children.
*
* @param path {String} The node path.
* @param [version=-1] {Number} The version of the node.
* @param callback {Function} The callback function.
*/
Client.prototype.removeRecursive = function(path, version, callback) {
if (!callback) {
callback = version;
version = -1;
}
Path.validate(path);
assert(typeof callback === 'function', 'callback must be a function.');
assert(typeof version === 'number', 'version must be a number.');
var self = this;
self.listSubTreeBFS(path, function (error, children) {
if (error) {
callback(error);
return;
}
async.eachSeries(children.reverse(), function (nodePath, next) {
self.remove(nodePath, version, function(err) {
// Skip NO_NODE exception
if (err && err.getCode() === Exception.NO_NODE) {
next(null);
return;
}
next(err);
});
}, callback);
});
};
/**
* Set the data for the node of the given path if such a node exists and the
* optional given version matches the version of the node (if the given
* version is -1, it matches any node's versions).
*
* @method setData
* @param path {String} The node path.
* @param data {Buffer} The data buffer.
* @param [version=-1] {Number} The version of the node.
* @param callback {Function} The callback function.
*/
Client.prototype.setData = function (path, data, version, callback) {
if (!callback) {
callback = version;
version = -1;
}
Path.validate(path);
assert(typeof callback === 'function', 'callback must be a function.');
assert(typeof version === 'number', 'version must be a number.');
assert(
data === null || data === undefined || Buffer.isBuffer(data),
'data must be a valid buffer, null or undefined.'
);
if (Buffer.isBuffer(data)) {
assert(
data.length <= DATA_SIZE_LIMIT,
'data must be equal of smaller than ' + DATA_SIZE_LIMIT + ' bytes.'
);
}
var self = this,
header = new jute.protocol.RequestHeader(),
payload = new jute.protocol.SetDataRequest(),
request;
header.type = jute.OP_CODES.SET_DATA;
payload.path = path;
payload.data = Buffer.alloc(data.length);
data.copy(payload.data);
payload.version = version;
request = new jute.Request(header, payload);
attempt(
self,
function (attempts, next) {
self.connectionManager.queue(request, function (error, response) {
if (error) {
next(error);
return;
}
next(null, response.payload.stat);
});
},
callback
);
};
/**
*
* Retrieve the data and the stat of the node of the given path.
*
* If the watcher is provided and the call is successful (no error), a watcher
* will be left on the node with the given path.
*
* The watch will be triggered by a successful operation that sets data on
* the node, or deletes the node.
*
* @method getData
* @param path {String} The node path.
* @param [watcher] {Function} The watcher function.
* @param callback {Function} The callback function.
*/
Client.prototype.getData = function (path, watcher, callback) {
if (!callback) {
callback = watcher;
watcher = undefined;
}
Path.validate(path);
assert(typeof callback === 'function', 'callback must be a function.');
var self = this,
header = new jute.protocol.RequestHeader(),
payload = new jute.protocol.GetDataRequest(),
request;
header.type = jute.OP_CODES.GET_DATA;
payload.path = path;
payload.watch = (typeof watcher === 'function');
request = new jute.Request(header, payload);
attempt(
self,
function (attempts, next) {
self.connectionManager.queue(request, function (error, response) {
if (error) {
next(error);
return;
}
if (watcher) {
self.connectionManager.registerDataWatcher(path, watcher);
}
next(null, response.payload.data, response.payload.stat);
});
},
callback
);
};
/**
* Set the ACL for the node of the given path if such a node exists and the
* given version matches the version of the node (if the given version is -1,
* it matches any node's versions).
*
*
* @method setACL
* @param path {String} The node path.
* @param acls {Array} The array of ACL objects.
* @param [version] {Number} The version of the node.
* @param callback {Function} The callback function.
*/
Client.prototype.setACL = function (path, acls, version, callback) {
if (!callback) {
callback = version;
version = -1;
}
Path.validate(path);
assert(typeof callback === 'function', 'callback must be a function.');
assert(
Array.isArray(acls) && acls.length > 0,
'acls must be a non-empty array.'
);
assert(typeof version === 'number', 'version must be a number.');
var self = this,
header = new jute.protocol.RequestHeader(),
payload = new jute.protocol.SetACLRequest(),
request;
header.type = jute.OP_CODES.SET_ACL;
payload.path = path;
payload.acl = acls.map(function (item) {
return item.toRecord();
});
payload.version = version;
request = new jute.Request(header, payload);
attempt(
self,
function (attempts, next) {
self.connectionManager.queue(request, function (error, response) {
if (error) {
next(error);
return;
}
next(null, response.payload.stat);
});
},
callback
);
};
/**
* Retrieve the ACL list and the stat of the node of the given path.
*
* @method getACL
* @param path {String} The node path.
* @param callback {Function} The callback function.
*/
Client.prototype.getACL = function (path, callback) {
Path.validate(path);
assert(typeof callback === 'function', 'callback must be a function.');
var self = this,
header = new jute.protocol.RequestHeader(),
payload = new jute.protocol.GetACLRequest(),
request;
header.type = jute.OP_CODES.GET_ACL;
payload.path = path;
request = new jute.Request(header, payload);
attempt(
self,
function (attempts, next) {
self.connectionManager.queue(request, function (error, response) {
if (error) {
next(error);
return;
}
var acls;
if (Array.isArray(response.payload.acl)) {
acls = response.payload.acl.map(function (item) {
return ACL.fromRecord(item);
});
}
next(null, acls, response.payload.stat);
});
},
callback
);
};
/**
* Check the existence of a node. The callback will be invoked with the
* stat of the given path, or null if node such node exists.
*
* If the watcher function is provided and the call is successful (no error
* from callback), a watcher will be placed on the node with the given path.
* The watcher will be triggered by a successful operation that creates/delete
* the node or sets the data on the node.
*
* @method exists
* @param path {String} The node path.
* @param [watcher] {Function} The watcher function.
* @param callback {Function} The callback function.
*/
Client.prototype.exists = function (path, watcher, callback) {
if (!callback) {
callback = watcher;
watcher = undefined;
}
Path.validate(path);
assert(typeof callback === 'function', 'callback must be a function.');
var self = this,
header = new jute.protocol.RequestHeader(),
payload = new jute.protocol.ExistsRequest(),
request;
header.type = jute.OP_CODES.EXISTS;
payload.path = path;
payload.watch = (typeof watcher === 'function');
request = new jute.Request(header, payload);
attempt(
self,
function (attempts, next) {
self.connectionManager.queue(request, function (error, response) {
if (error && error.getCode() !== Exception.NO_NODE) {
next(error);
return;
}
var existence = response.header.err === Exception.OK;
if (watcher) {
if (existence) {
self.connectionManager.registerDataWatcher(
path,
watcher
);
} else {
self.connectionManager.registerExistenceWatcher(
path,
watcher
);
}
}
next(
null,
existence ? response.payload.stat : null
);
});
},
callback
);
};
/**
* For the given node path, retrieve the children list and the stat.
*
* If the watcher callback is provided and the method completes successfully,
* a watcher will be placed the given node. The watcher will be triggered
* when an operation successfully deletes the given node or creates/deletes
* the child under it.
*
* @method getChildren
* @param path {String} The node path.
* @param [watcher] {Function} The watcher function.
* @param callback {Function} The callback function.
*/
Client.prototype.getChildren = function (path, watcher, callback) {
if (!callback) {
callback = watcher;
watcher = undefined;
}
Path.validate(path);
assert(typeof callback === 'function', 'callback must be a function.');
var self = this,
header = new jute.protocol.RequestHeader(),
payload = new jute.protocol.GetChildren2Request(),
request;
header.type = jute.OP_CODES.GET_CHILDREN2;
payload.path = path;
payload.watch = (typeof watcher === 'function');
request = new jute.Request(header, payload);
attempt(
self,
function (attempts, next) {
self.connectionManager.queue(request, function (error, response) {
if (error) {
next(error);
return;
}
if (watcher) {
self.connectionManager.registerChildWatcher(path, watcher);
}
next(null, response.payload.children, response.payload.stat);
});
},
callback
);
};
/**
* BFS list of the system under path. Note that this is not an atomic snapshot of
* the tree, but the state as it exists across multiple RPCs from clients to the
* ensemble.
*
* @method listSubTreeBFS
* @param path {String} The node path.
* @param callback {Function} The callback function.
*/
Client.prototype.listSubTreeBFS = function(path, callback) {
Path.validate(path);
assert(typeof callback === 'function', 'callback must be a function.');
var self = this;
var tree = [path];
async.reduce(tree, tree, function(memo, item, next) {
self.getChildren(item, function (error, children) {
if (error) {
next(error);
return;
}
if (!children || !Array.isArray(children) || !children.length) {
next(null, tree);
return;
}
children.forEach(function(child) {
var childPath = item + '/' + child;
if (item === '/') {
childPath = item + child;
}
tree.push(childPath);
});
next(null, tree);
});
}, callback);
};
/**
* Create node path in the similar way of `mkdir -p`
*
*
* @method mkdirp
* @param path {String} The node path.
* @param [data=undefined] {Buffer} The data buffer.
* @param [acls=ACL.OPEN_ACL_UNSAFE] {Array} The array of ACL object.
* @param [mode=CreateMode.PERSISTENT] {CreateMode} The creation mode.
* @param callback {Function} The callback function.
*/
Client.prototype.mkdirp = function (path, data, acls, mode, callback) {
var optionalArgs = [data, acls, mode, callback],
self = this,
currentPath = '',
nodes;
Path.validate(path);
// Reset arguments so we can reassign correct value to them.
data = acls = mode = callback = undefined;
optionalArgs.forEach(function (arg, index) {
if (Array.isArray(arg)) {
acls = arg;
} else if (typeof arg === 'number') {
mode = arg;
} else if (Buffer.isBuffer(arg)) {
data = arg;
} else if (typeof arg === 'function') {
callback = arg;
}
});
assert(
typeof callback === 'function',
'callback must be a function.'
);
acls = Array.isArray(acls) ? acls : ACL.OPEN_ACL_UNSAFE;
mode = typeof mode === 'number' ? mode : CreateMode.PERSISTENT;
assert(
data === null || data === undefined || Buffer.isBuffer(data),
'data must be a valid buffer, null or undefined.'
);
if (Buffer.isBuffer(data)) {
assert(
data.length <= DATA_SIZE_LIMIT,
'data must be equal of smaller than ' + DATA_SIZE_LIMIT + ' bytes.'
);
}
assert(acls.length > 0, 'acls must be a non-empty array.');
// Remove the empty string
nodes = path.split('/').slice(1);
async.eachSeries(nodes, function (node, next) {
currentPath = currentPath + '/' + node;
self.create(currentPath, data, acls, mode, function (error) {
// Skip node exist error.
if (error && error.getCode() === Exception.NODE_EXISTS) {
next(null);
return;
}
next(error);
});
}, function (error) {
callback(error, currentPath);
});
};
/**
* Create and return a new Transaction instance.
*
* @method transaction
* @return {Transaction} an instance of Transaction.
*/
Client.prototype.transaction = function () {
return new Transaction(this.connectionManager);
};
/**
* Create a new ZooKeeper client.
*
* @method createClient
* @for node-zookeeper-client
*/
function createClient(connectionString, options) {
return new Client(connectionString, options);
}
exports.createClient = createClient;
exports.ACL = ACL;
exports.Id = Id;
exports.Permission = Permission;
exports.CreateMode = CreateMode;
exports.State = State;
exports.Event = Event;
exports.Exception = Exception;