forked from apache/zookeeper
/
DataTree.java
893 lines (827 loc) · 30.1 KB
/
DataTree.java
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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.zookeeper.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.jute.Index;
import org.apache.jute.InputArchive;
import org.apache.jute.OutputArchive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Quotas;
import org.apache.zookeeper.StatsTrack;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.common.AccessControlList;
import org.apache.zookeeper.common.PathTrie;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.data.StatPersisted;
import org.apache.zookeeper.txn.CreateTxn;
import org.apache.zookeeper.txn.DeleteTxn;
import org.apache.zookeeper.txn.TxnHeader;
/**
* This class maintains the tree data structure. It doesn't have any networking
* or client connection code in it so that it can be tested in a stand alone
* way.
* <p>
* The tree maintains two parallel data structures: a hashtable that maps from
* full paths to DataNodes and a tree of DataNodes. All accesses to a path is
* through the hashtable. The tree is traversed only when serializing to disk.
*/
public class DataTree {
private static final Logger LOG = LoggerFactory.getLogger(DataTree.class);
public volatile long lastProcessedZxid = 0;
/**
* This hashtable provides a fast lookup to the datanodes. The tree is the
* source of truth and is where all the locking occurs
*/
final ConcurrentHashMap<String, DataNode> nodes =
new ConcurrentHashMap<String, DataNode>();
final WatchManager dataWatches = new WatchManager();
final WatchManager childWatches = new WatchManager();
/** the root of zookeeper tree */
private static final String rootZookeeper = "/";
/** the zookeeper nodes that acts as the management and status node **/
private static final String procZookeeper = Quotas.procZookeeper;
/** this will be the string thats stored as a child of root */
private static final String procChildZookeeper = procZookeeper.substring(1);
/**
* the zookeeper quota node that acts as the quota management node for
* zookeeper
*/
private static final String quotaZookeeper = Quotas.quotaZookeeper;
/** this will be the string thats stored as a child of /zookeeper */
private static final String quotaChildZookeeper = quotaZookeeper
.substring(procZookeeper.length() + 1);
/**
* the path trie that keeps track fo the quota nodes in this datatree
*/
final PathTrie pTrie = new PathTrie();
/**
* This hashtable lists the paths of the ephemeral nodes of a session.
*/
final Map<Long, HashSet<String>> ephemerals =
new ConcurrentHashMap<Long, HashSet<String>>();
/**
* this is map from longs to acl's. It saves acl's being stored for each
* datanode.
*/
private final Map<Long, AccessControlList> longKeyMap =
new HashMap<Long, AccessControlList>();
/**
* this a map from acls to long.
*/
private final Map<AccessControlList, Long> aclKeyMap =
new HashMap<AccessControlList, Long>();
/**
* these are the number of acls that we have in the datatree
*/
private long aclIndex = 0;
@SuppressWarnings("unchecked")
public Set<String> getEphemerals(long sessionId) {
HashSet<String> retv = ephemerals.get(sessionId);
if (retv == null) {
return new HashSet<String>();
}
HashSet<String> cloned = null;
synchronized (retv) {
cloned = (HashSet<String>) retv.clone();
}
return cloned;
}
int getAclSize() {
return longKeyMap.size();
}
private long incrementIndex() {
return ++aclIndex;
}
/**
* converts the list of acls to a list of longs.
*
* @param acls
* @return a list of longs that map to the acls
*/
public synchronized Long convertAcls(AccessControlList acl) {
if (acl == null || acl == AccessControlList.EMPTY)
return -1L;
// get the value from the map
Long ret = aclKeyMap.get(acl);
// could not find the map
if (ret != null)
return ret;
long val = incrementIndex();
longKeyMap.put(val, acl);
aclKeyMap.put(acl, val);
return val;
}
/**
* converts a list of longs to a list of acls.
*
* @param longVal
* the list of longs
* @return a list of ACLs that map to longs
*/
public synchronized AccessControlList convertLong(Long longVal) {
if (longVal == null)
return null;
if (longVal == -1L)
return AccessControlList.OPEN_ACL_UNSAFE;
AccessControlList acl = longKeyMap.get(longVal);
if (acl == null) {
LOG.error("ERROR: ACL not available for long " + longVal);
throw new RuntimeException("Failed to fetch acls for " + longVal);
}
return acl;
}
public Collection<Long> getSessions() {
return ephemerals.keySet();
}
public DataNode getNode(String path) {
return nodes.get(path);
}
public int getNodeCount() {
return nodes.size();
}
public int getWatchCount() {
return dataWatches.size() + childWatches.size();
}
int getEphemeralsCount() {
int result = 0;
for (HashSet<String> set : ephemerals.values()) {
result += set.size();
}
return result;
}
/**
* Get the size of the nodes based on path and data length.
*
* @return size of the data
*/
public long approximateDataSize() {
long result = 0;
for (Map.Entry<String, DataNode> entry : nodes.entrySet()) {
DataNode value = entry.getValue();
synchronized (value) {
result += entry.getKey().length();
result += value.getApproximateDataSize();
}
}
return result;
}
/**
* This is a pointer to the root of the DataTree. It is the source of truth,
* but we usually use the nodes hashmap to find nodes in the tree.
*/
private DataNode root = new DataNode(new byte[0], -1L, new StatPersisted());
/**
* create a /zookeeper filesystem that is the proc filesystem of zookeeper
*/
private final DataNode procDataNode = new DataNode(new byte[0], -1L, new StatPersisted());
/**
* create a /zookeeper/quota node for maintaining quota properties for
* zookeeper
*/
private final DataNode quotaDataNode = new DataNode(new byte[0], -1L, new StatPersisted());
public DataTree() {
/* Rather than fight it, let root have an alias */
nodes.put("", root);
nodes.put(rootZookeeper, root);
/** add the proc node and quota node */
root.addChild(procChildZookeeper);
nodes.put(procZookeeper, procDataNode);
procDataNode.addChild(quotaChildZookeeper);
nodes.put(quotaZookeeper, quotaDataNode);
}
/**
* is the path one of the special paths owned by zookeeper.
*
* @param path
* the path to be checked
* @return true if a special path. false if not.
*/
boolean isSpecialPath(String path) {
if (rootZookeeper.equals(path) || procZookeeper.equals(path)
|| quotaZookeeper.equals(path)) {
return true;
}
return false;
}
static public void copyStatPersisted(StatPersisted from, StatPersisted to) {
to.setAversion(from.getAversion());
to.setCtime(from.getCtime());
to.setCversion(from.getCversion());
to.setCzxid(from.getCzxid());
to.setMtime(from.getMtime());
to.setMzxid(from.getMzxid());
to.setPzxid(from.getPzxid());
to.setVersion(from.getVersion());
to.setEphemeralOwner(from.getEphemeralOwner());
}
static public void copyStat(Stat from, Stat to) {
to.setAversion(from.getAversion());
to.setCtime(from.getCtime());
to.setCversion(from.getCversion());
to.setCzxid(from.getCzxid());
to.setMtime(from.getMtime());
to.setMzxid(from.getMzxid());
to.setPzxid(from.getPzxid());
to.setVersion(from.getVersion());
to.setEphemeralOwner(from.getEphemeralOwner());
to.setDataLength(from.getDataLength());
to.setNumChildren(from.getNumChildren());
}
/**
* update the count of this stat datanode
*
* @param lastPrefix
* the path of the node that is quotaed.
* @param diff
* the diff to be added to the count
*/
public void updateCount(String lastPrefix, int diff) {
String statNode = Quotas.statPath(lastPrefix);
DataNode node = nodes.get(statNode);
StatsTrack updatedStat = null;
if (node == null) {
// should not happen
LOG.error("Missing count node for stat " + statNode);
return;
}
synchronized (node) {
updatedStat = new StatsTrack(new String(node.data));
updatedStat.setCount(updatedStat.getCount() + diff);
node.data = updatedStat.toString().getBytes();
}
// now check if the counts match the quota
String quotaNode = Quotas.quotaPath(lastPrefix);
node = nodes.get(quotaNode);
StatsTrack thisStats = null;
if (node == null) {
// should not happen
LOG.error("Missing count node for quota " + quotaNode);
return;
}
synchronized (node) {
thisStats = new StatsTrack(new String(node.data));
}
if (thisStats.getCount() > -1 && (thisStats.getCount() < updatedStat.getCount())) {
LOG
.warn("Quota exceeded: " + lastPrefix + " count="
+ updatedStat.getCount() + " limit="
+ thisStats.getCount());
}
}
/**
* update the count of bytes of this stat datanode
*
* @param lastPrefix
* the path of the node that is quotaed
* @param diff
* the diff to added to number of bytes
* @throws IOException
* if path is not found
*/
public void updateBytes(String lastPrefix, long diff) {
String statNode = Quotas.statPath(lastPrefix);
DataNode node = nodes.get(statNode);
if (node == null) {
// should never be null but just to make
// findbugs happy
LOG.error("Missing stat node for bytes " + statNode);
return;
}
StatsTrack updatedStat = null;
synchronized (node) {
updatedStat = new StatsTrack(new String(node.data));
updatedStat.setBytes(updatedStat.getBytes() + diff);
node.data = updatedStat.toString().getBytes();
}
// now check if the bytes match the quota
String quotaNode = Quotas.quotaPath(lastPrefix);
node = nodes.get(quotaNode);
if (node == null) {
// should never be null but just to make
// findbugs happy
LOG.error("Missing quota node for bytes " + quotaNode);
return;
}
StatsTrack thisStats = null;
synchronized (node) {
thisStats = new StatsTrack(new String(node.data));
}
if (thisStats.getBytes() > -1 && (thisStats.getBytes() < updatedStat.getBytes())) {
LOG
.warn("Quota exceeded: " + lastPrefix + " bytes="
+ updatedStat.getBytes() + " limit="
+ thisStats.getBytes());
}
}
public void createNode(final String path, byte data[], List<ACL> acl,
long ephemeralOwner, int parentCVersion, long zxid, long time)
throws KeeperException.NoNodeException,
KeeperException.NodeExistsException {
TxnHeader hdr = new TxnHeader();
hdr.setClientId(ephemeralOwner);
hdr.setZxid(zxid);
hdr.setTime(time);
CreateTxn txn = new CreateTxn(path, data, acl, true, parentCVersion);
(new Transaction.Create(hdr, txn)).process(this);
}
/**
* If there is a quota set, return the appropriate prefix for that quota
* Else return null
* @param path The ZK path to check for quota
* @return Max quota prefix, or null if none
*/
public String getMaxPrefixWithQuota(String path) {
// do nothing for the root.
// we are not keeping a quota on the zookeeper
// root node for now.
String lastPrefix = pTrie.findMaxPrefix(path);
if (rootZookeeper.equals(lastPrefix) || "".equals(lastPrefix)) {
return null;
}
else {
return lastPrefix;
}
}
public byte[] getData(String path, Stat stat, Watcher watcher)
throws KeeperException.NoNodeException {
DataNode n = nodes.get(path);
if (n == null) {
throw new KeeperException.NoNodeException();
}
synchronized (n) {
n.copyStat(stat);
if (watcher != null) {
dataWatches.addWatch(path, watcher);
}
return n.data;
}
}
public Stat statNode(String path, Watcher watcher)
throws KeeperException.NoNodeException {
Stat stat = new Stat();
DataNode n = nodes.get(path);
if (watcher != null) {
dataWatches.addWatch(path, watcher);
}
if (n == null) {
throw new KeeperException.NoNodeException();
}
synchronized (n) {
n.copyStat(stat);
return stat;
}
}
public List<String> getChildren(String path, Stat stat, Watcher watcher)
throws KeeperException.NoNodeException {
DataNode n = nodes.get(path);
if (n == null) {
throw new KeeperException.NoNodeException();
}
synchronized (n) {
if (stat != null) {
n.copyStat(stat);
}
ArrayList<String> children;
Set<String> childs = n.getChildren();
if (childs == null) {
children = new ArrayList<String>(0);
} else {
children = new ArrayList<String>(childs);
}
if (watcher != null) {
childWatches.addWatch(path, watcher);
}
return children;
}
}
public AccessControlList getACL(String path, Stat stat)
throws KeeperException.NoNodeException {
DataNode n = nodes.get(path);
if (n == null) {
throw new KeeperException.NoNodeException();
}
synchronized (n) {
n.copyStat(stat);
return convertLong(n.acl);
}
}
void killSession(long session, long zxid) {
// the list is already removed from the ephemerals
// so we do not have to worry about synchronizing on
// the list. This is only called from FinalRequestProcessor
// so there is no need for synchronization. The list is not
// changed here. Only create and delete change the list which
// are again called from FinalRequestProcessor in sequence.
HashSet<String> list = ephemerals.remove(session);
TxnHeader header = new TxnHeader();
header.setZxid(zxid);
if (list != null) {
for (String path : list) {
try {
DeleteTxn delTxn = new DeleteTxn(path);
Transaction.Delete transaction = new Transaction.Delete(header, delTxn);
transaction.process(this);
if (LOG.isDebugEnabled()) {
LOG.debug("Deleting ephemeral node " + path
+ " for session 0x"
+ Long.toHexString(session));
}
} catch (NoNodeException e) {
LOG.warn("Ignoring NoNodeException for path " + path
+ " while removing ephemeral for dead session 0x"
+ Long.toHexString(session));
}
}
}
}
/**
* a encapsultaing class for return value
*/
private static class Counts {
long bytes;
int count;
}
/**
* this method gets the count of nodes and the bytes under a subtree
*
* @param path
* the path to be used
* @param counts
* the int count
*/
private void getCounts(String path, Counts counts) {
DataNode node = getNode(path);
if (node == null) {
return;
}
String[] children = null;
int len = 0;
synchronized (node) {
Set<String> childs = node.getChildren();
if (childs != null) {
children = childs.toArray(new String[childs.size()]);
}
len = (node.data == null ? 0 : node.data.length);
}
// add itself
counts.count += 1;
counts.bytes += len;
if (children == null || children.length == 0) {
return;
}
for (String child : children) {
getCounts(path + "/" + child, counts);
}
}
/**
* update the quota for the given path
*
* @param path
* the path to be used
*/
void updateQuotaForPath(String path) {
Counts c = new Counts();
getCounts(path, c);
StatsTrack strack = new StatsTrack();
strack.setBytes(c.bytes);
strack.setCount(c.count);
String statPath = Quotas.quotaZookeeper + path + "/" + Quotas.statNode;
DataNode node = getNode(statPath);
// it should exist
if (node == null) {
LOG.warn("Missing quota stat node " + statPath);
return;
}
synchronized (node) {
node.data = strack.toString().getBytes();
}
}
/**
* this method traverses the quota path and update the path trie and sets
*
* @param path
*/
private void traverseNode(String path) {
DataNode node = getNode(path);
String children[] = null;
synchronized (node) {
Set<String> childs = node.getChildren();
if (childs != null) {
children = childs.toArray(new String[childs.size()]);
}
}
if (children == null || children.length == 0) {
// this node does not have a child
// is the leaf node
// check if its the leaf node
String endString = "/" + Quotas.limitNode;
if (path.endsWith(endString)) {
// ok this is the limit node
// get the real node and update
// the count and the bytes
String realPath = path.substring(Quotas.quotaZookeeper
.length(), path.indexOf(endString));
updateQuotaForPath(realPath);
this.pTrie.addPath(realPath);
}
return;
}
for (String child : children) {
traverseNode(path + "/" + child);
}
}
/**
* this method sets up the path trie and sets up stats for quota nodes
*/
private void setupQuota() {
String quotaPath = Quotas.quotaZookeeper;
DataNode node = getNode(quotaPath);
if (node == null) {
return;
}
traverseNode(quotaPath);
}
/**
* this method uses a stringbuilder to create a new path for children. This
* is faster than string appends ( str1 + str2).
*
* @param oa
* OutputArchive to write to.
* @param path
* a string builder.
* @throws IOException
* @throws InterruptedException
*/
void serializeNode(OutputArchive oa, StringBuilder path) throws IOException {
String pathString = path.toString();
DataNode node = getNode(pathString);
if (node == null) {
return;
}
String children[] = null;
synchronized (node) {
oa.writeString(pathString, "path");
oa.writeRecord(node, "node");
Set<String> childs = node.getChildren();
if (childs != null) {
children = childs.toArray(new String[childs.size()]);
}
}
path.append('/');
int off = path.length();
if (children != null) {
for (String child : children) {
// since this is single buffer being resused
// we need
// to truncate the previous bytes of string.
path.delete(off, Integer.MAX_VALUE);
path.append(child);
serializeNode(oa, path);
}
}
}
private void deserializeList(Map<Long, AccessControlList> longKeyMap,
InputArchive ia) throws IOException {
int i = ia.readInt("map");
while (i > 0) {
Long val = ia.readLong("long");
if (aclIndex < val) {
aclIndex = val;
}
List<ACL> aclList = new ArrayList<ACL>();
Index j = ia.startVector("acls");
while (!j.done()) {
ACL acl = new ACL();
acl.deserialize(ia, "acl");
aclList.add(acl);
j.incr();
}
AccessControlList accessControlList = AccessControlList.fromJuteACL(aclList);
longKeyMap.put(val, accessControlList);
aclKeyMap.put(accessControlList, val);
i--;
}
}
private synchronized void serializeList(Map<Long, AccessControlList> longKeyMap,
OutputArchive oa) throws IOException {
oa.writeInt(longKeyMap.size(), "map");
Set<Map.Entry<Long, AccessControlList>> set = longKeyMap.entrySet();
for (Map.Entry<Long, AccessControlList> val : set) {
oa.writeLong(val.getKey(), "long");
List<ACL> aclList = val.getValue().toJuteACL();
oa.startVector(aclList, "acls");
for (ACL acl : aclList) {
acl.serialize(oa, "acl");
}
oa.endVector(aclList, "acls");
}
}
public void serialize(OutputArchive oa, String tag) throws IOException {
serializeList(longKeyMap, oa);
serializeNode(oa, new StringBuilder(""));
// / marks end of stream
// we need to check if clear had been called in between the snapshot.
if (root != null) {
oa.writeString("/", "path");
}
}
public void deserialize(InputArchive ia, String tag) throws IOException {
deserializeList(longKeyMap, ia);
nodes.clear();
String path = ia.readString("path");
while (!"/".equals(path)) {
DataNode node = new DataNode();
ia.readRecord(node, "node");
nodes.put(path, node);
int lastSlash = path.lastIndexOf('/');
if (lastSlash == -1) {
root = node;
} else {
String parentPath = path.substring(0, lastSlash);
DataNode parent = nodes.get(parentPath);
if (parent == null) {
throw new IOException("Invalid Datatree, unable to find " +
"parent " + parentPath + " of path " + path);
}
parent.addChild(path.substring(lastSlash + 1));
long eowner = node.stat.getEphemeralOwner();
if (eowner != 0) {
HashSet<String> list = ephemerals.get(eowner);
if (list == null) {
list = new HashSet<String>();
ephemerals.put(eowner, list);
}
list.add(path);
}
}
path = ia.readString("path");
}
nodes.put("/", root);
// we are done with deserializing the
// the datatree
// update the quotas - create path trie
// and also update the stat nodes
setupQuota();
}
/**
* Summary of the watches on the datatree.
* @param pwriter the output to write to
*/
public synchronized void dumpWatchesSummary(PrintWriter pwriter) {
pwriter.print(dataWatches.toString());
}
/**
* Write a text dump of all the watches on the datatree.
* Warning, this is expensive, use sparingly!
* @param pwriter the output to write to
*/
public synchronized void dumpWatches(PrintWriter pwriter, boolean byPath) {
dataWatches.dumpWatches(pwriter, byPath);
}
/**
* Write a text dump of all the ephemerals in the datatree.
* @param pwriter the output to write to
*/
public void dumpEphemerals(PrintWriter pwriter) {
Set<Long> keys = ephemerals.keySet();
pwriter.println("Sessions with Ephemerals ("
+ keys.size() + "):");
for (long k : keys) {
pwriter.print("0x" + Long.toHexString(k));
pwriter.println(":");
HashSet<String> tmp = ephemerals.get(k);
synchronized (tmp) {
for (String path : tmp) {
pwriter.println("\t" + path);
}
}
}
}
public void removeCnxn(Watcher watcher) {
dataWatches.removeWatcher(watcher);
childWatches.removeWatcher(watcher);
}
public void setWatches(long relativeZxid, List<String> dataWatches,
List<String> existWatches, List<String> childWatches,
Watcher watcher) {
for (String path : dataWatches) {
DataNode node = getNode(path);
WatchedEvent e = null;
if (node == null) {
e = new WatchedEvent(EventType.NodeDeleted,
KeeperState.SyncConnected, path);
} else if (node.stat.getCzxid() > relativeZxid) {
e = new WatchedEvent(EventType.NodeCreated,
KeeperState.SyncConnected, path);
} else if (node.stat.getMzxid() > relativeZxid) {
e = new WatchedEvent(EventType.NodeDataChanged,
KeeperState.SyncConnected, path);
}
if (e == null) {
this.dataWatches.addWatch(path, watcher);
} else {
watcher.process(e);
}
}
for (String path : existWatches) {
DataNode node = getNode(path);
WatchedEvent e = null;
if (node == null) {
// This is the case when the watch was registered
} else if (node.stat.getMzxid() > relativeZxid) {
e = new WatchedEvent(EventType.NodeDataChanged,
KeeperState.SyncConnected, path);
} else {
e = new WatchedEvent(EventType.NodeCreated,
KeeperState.SyncConnected, path);
}
if (e == null) {
this.dataWatches.addWatch(path, watcher);
} else {
watcher.process(e);
}
}
for (String path : childWatches) {
DataNode node = getNode(path);
WatchedEvent e = null;
if (node == null) {
e = new WatchedEvent(EventType.NodeDeleted,
KeeperState.SyncConnected, path);
} else if (node.stat.getPzxid() > relativeZxid) {
e = new WatchedEvent(EventType.NodeChildrenChanged,
KeeperState.SyncConnected, path);
}
if (e == null) {
this.childWatches.addWatch(path, watcher);
} else {
watcher.process(e);
}
}
}
/**
* This method sets the Cversion and Pzxid for the specified node to the
* values passed as arguments. The values are modified only if newCversion
* is greater than the current Cversion. A NoNodeException is thrown if
* a znode for the specified path is not found.
*
* @param path
* Full path to the znode whose Cversion needs to be modified.
* A "/" at the end of the path is ignored.
* @param newCversion
* Value to be assigned to Cversion
* @param zxid
* Value to be assigned to Pzxid
* @throws KeeperException.NoNodeException
* If znode not found.
**/
public void setCversionPzxid(String path, int newCversion, long zxid)
throws KeeperException.NoNodeException {
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
DataNode node = nodes.get(path);
if (node == null) {
throw new KeeperException.NoNodeException(path);
}
synchronized (node) {
if(newCversion == -1) {
newCversion = node.stat.getCversion() + 1;
}
if (newCversion > node.stat.getCversion()) {
node.stat.setCversion(newCversion);
node.stat.setPzxid(zxid);
}
}
}
}