1cc3785e02731bacb5594d799aa506854c58f1a9
[deliverable/tracecompass.git] / statesystem / org.eclipse.tracecompass.statesystem.core / src / org / eclipse / tracecompass / internal / statesystem / core / backend / historytree / HistoryTree.java
1 /*******************************************************************************
2 * Copyright (c) 2010, 2015 Ericsson, École Polytechnique de Montréal, and others
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *
9 * Contributors:
10 * Alexandre Montplaisir - Initial API and implementation
11 * Florian Wininger - Add Extension and Leaf Node
12 * Patrick Tasse - Add message to exceptions
13 *******************************************************************************/
14
15 package org.eclipse.tracecompass.internal.statesystem.core.backend.historytree;
16
17 import java.io.File;
18 import java.io.FileInputStream;
19 import java.io.IOException;
20 import java.io.PrintWriter;
21 import java.nio.ByteBuffer;
22 import java.nio.ByteOrder;
23 import java.nio.channels.ClosedChannelException;
24 import java.nio.channels.FileChannel;
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.List;
28
29 import org.eclipse.tracecompass.internal.statesystem.core.Activator;
30 import org.eclipse.tracecompass.statesystem.core.ITmfStateSystemBuilder;
31 import org.eclipse.tracecompass.statesystem.core.exceptions.TimeRangeException;
32
33 import com.google.common.collect.ImmutableList;
34
35 /**
36 * Meta-container for the History Tree. This structure contains all the
37 * high-level data relevant to the tree.
38 *
39 * @author Alexandre Montplaisir
40 */
41 public class HistoryTree {
42
43 /**
44 * Size of the "tree header" in the tree-file The nodes will use this offset
45 * to know where they should be in the file. This should always be a
46 * multiple of 4K.
47 */
48 public static final int TREE_HEADER_SIZE = 4096;
49
50 private static final int HISTORY_FILE_MAGIC_NUMBER = 0x05FFA900;
51
52 /** File format version. Increment when breaking compatibility. */
53 private static final int FILE_VERSION = 5;
54
55 // ------------------------------------------------------------------------
56 // Tree-specific configuration
57 // ------------------------------------------------------------------------
58
59 /** Container for all the configuration constants */
60 private final HTConfig fConfig;
61
62 /** Reader/writer object */
63 private final HT_IO fTreeIO;
64
65 // ------------------------------------------------------------------------
66 // Variable Fields (will change throughout the existence of the SHT)
67 // ------------------------------------------------------------------------
68
69 /** Latest timestamp found in the tree (at any given moment) */
70 private long fTreeEnd;
71
72 /** The total number of nodes that exists in this tree */
73 private int fNodeCount;
74
75 /** "Cache" to keep the active nodes in memory */
76 private final List<HTNode> fLatestBranch;
77
78 // ------------------------------------------------------------------------
79 // Constructors/"Destructors"
80 // ------------------------------------------------------------------------
81
82 /**
83 * Create a new State History from scratch, using a {@link HTConfig} object
84 * for configuration.
85 *
86 * @param conf
87 * The config to use for this History Tree.
88 * @throws IOException
89 * If an error happens trying to open/write to the file
90 * specified in the config
91 */
92 public HistoryTree(HTConfig conf) throws IOException {
93 /*
94 * Simple check to make sure we have enough place in the 0th block for
95 * the tree configuration
96 */
97 if (conf.getBlockSize() < TREE_HEADER_SIZE) {
98 throw new IllegalArgumentException();
99 }
100
101 fConfig = conf;
102 fTreeEnd = conf.getTreeStart();
103 fNodeCount = 0;
104 fLatestBranch = Collections.synchronizedList(new ArrayList<HTNode>());
105
106 /* Prepare the IO object */
107 fTreeIO = new HT_IO(fConfig, true);
108
109 /* Add the first node to the tree */
110 LeafNode firstNode = initNewLeafNode(-1, conf.getTreeStart());
111 fLatestBranch.add(firstNode);
112 }
113
114 /**
115 * "Reader" constructor : instantiate a SHTree from an existing tree file on
116 * disk
117 *
118 * @param existingStateFile
119 * Path/filename of the history-file we are to open
120 * @param expProviderVersion
121 * The expected version of the state provider
122 * @throws IOException
123 * If an error happens reading the file
124 */
125 public HistoryTree(File existingStateFile, int expProviderVersion) throws IOException {
126 /*
127 * Open the file ourselves, get the tree header information we need,
128 * then pass on the descriptor to the TreeIO object.
129 */
130 int rootNodeSeqNb, res;
131 int bs, maxc;
132 long startTime;
133
134 /* Java I/O mumbo jumbo... */
135 if (!existingStateFile.exists()) {
136 throw new IOException("Selected state file does not exist"); //$NON-NLS-1$
137 }
138 if (existingStateFile.length() <= 0) {
139 throw new IOException("Empty target file"); //$NON-NLS-1$
140 }
141
142 try (FileInputStream fis = new FileInputStream(existingStateFile);
143 FileChannel fc = fis.getChannel();) {
144
145 ByteBuffer buffer = ByteBuffer.allocate(TREE_HEADER_SIZE);
146
147 buffer.order(ByteOrder.LITTLE_ENDIAN);
148 buffer.clear();
149 fc.read(buffer);
150 buffer.flip();
151
152 /*
153 * Check the magic number to make sure we're opening the right type
154 * of file
155 */
156 res = buffer.getInt();
157 if (res != HISTORY_FILE_MAGIC_NUMBER) {
158 throw new IOException("Wrong magic number"); //$NON-NLS-1$
159 }
160
161 res = buffer.getInt(); /* File format version number */
162 if (res != FILE_VERSION) {
163 throw new IOException("Mismatching History Tree file format versions"); //$NON-NLS-1$
164 }
165
166 res = buffer.getInt(); /* Event handler's version number */
167 if (res != expProviderVersion &&
168 expProviderVersion != ITmfStateSystemBuilder.IGNORE_PROVIDER_VERSION) {
169 /*
170 * The existing history was built using an event handler that
171 * doesn't match the current one in the framework.
172 *
173 * Information could be all wrong. Instead of keeping an
174 * incorrect history file, a rebuild is done.
175 */
176 throw new IOException("Mismatching event handler versions"); //$NON-NLS-1$
177 }
178
179 bs = buffer.getInt(); /* Block Size */
180 maxc = buffer.getInt(); /* Max nb of children per node */
181
182 fNodeCount = buffer.getInt();
183 rootNodeSeqNb = buffer.getInt();
184 startTime = buffer.getLong();
185
186 fConfig = new HTConfig(existingStateFile, bs, maxc, expProviderVersion, startTime);
187 }
188
189 /*
190 * FIXME We close fis here and the TreeIO will then reopen the same
191 * file, not extremely elegant. But how to pass the information here to
192 * the SHT otherwise?
193 */
194 fTreeIO = new HT_IO(fConfig, false);
195
196 fLatestBranch = buildLatestBranch(rootNodeSeqNb);
197 fTreeEnd = getRootNode().getNodeEnd();
198
199 /*
200 * Make sure the history start time we read previously is consistent
201 * with was is actually in the root node.
202 */
203 if (startTime != getRootNode().getNodeStart()) {
204 throw new IOException("Inconsistent start times in the" + //$NON-NLS-1$
205 "history file, it might be corrupted."); //$NON-NLS-1$
206 }
207 }
208
209 /**
210 * Rebuild the latestBranch "cache" object by reading the nodes from disk
211 * (When we are opening an existing file on disk and want to append to it,
212 * for example).
213 *
214 * @param rootNodeSeqNb
215 * The sequence number of the root node, so we know where to
216 * start
217 * @throws ClosedChannelException
218 */
219 private List<HTNode> buildLatestBranch(int rootNodeSeqNb) throws ClosedChannelException {
220 List<HTNode> list = new ArrayList<>();
221
222 HTNode nextChildNode = fTreeIO.readNode(rootNodeSeqNb);
223 list.add(nextChildNode);
224
225 /* Follow the last branch up to the leaf */
226 while (nextChildNode.getNodeType() == HTNode.NodeType.CORE) {
227 nextChildNode = fTreeIO.readNode(((CoreNode) nextChildNode).getLatestChild());
228 list.add(nextChildNode);
229 }
230 return Collections.synchronizedList(list);
231 }
232
233 /**
234 * "Save" the tree to disk. This method will cause the treeIO object to
235 * commit all nodes to disk and then return the RandomAccessFile descriptor
236 * so the Tree object can save its configuration into the header of the
237 * file.
238 *
239 * @param requestedEndTime
240 * The greatest timestamp present in the history tree
241 */
242 public void closeTree(long requestedEndTime) {
243 /* This is an important operation, queries can wait */
244 synchronized (fLatestBranch) {
245 /*
246 * Work-around the "empty branches" that get created when the root
247 * node becomes full. Overwrite the tree's end time with the
248 * original wanted end-time, to ensure no queries are sent into
249 * those empty nodes.
250 *
251 * This won't be needed once extended nodes are implemented.
252 */
253 fTreeEnd = requestedEndTime;
254
255 /* Close off the latest branch of the tree */
256 for (int i = 0; i < fLatestBranch.size(); i++) {
257 fLatestBranch.get(i).closeThisNode(fTreeEnd);
258 fTreeIO.writeNode(fLatestBranch.get(i));
259 }
260
261 try (FileChannel fc = fTreeIO.getFcOut();) {
262 ByteBuffer buffer = ByteBuffer.allocate(TREE_HEADER_SIZE);
263 buffer.order(ByteOrder.LITTLE_ENDIAN);
264 buffer.clear();
265
266 /* Save the config of the tree to the header of the file */
267 fc.position(0);
268
269 buffer.putInt(HISTORY_FILE_MAGIC_NUMBER);
270
271 buffer.putInt(FILE_VERSION);
272 buffer.putInt(fConfig.getProviderVersion());
273
274 buffer.putInt(fConfig.getBlockSize());
275 buffer.putInt(fConfig.getMaxChildren());
276
277 buffer.putInt(fNodeCount);
278
279 /* root node seq. nb */
280 buffer.putInt(fLatestBranch.get(0).getSequenceNumber());
281
282 /* start time of this history */
283 buffer.putLong(fLatestBranch.get(0).getNodeStart());
284
285 buffer.flip();
286 int res = fc.write(buffer);
287 assert (res <= TREE_HEADER_SIZE);
288 /* done writing the file header */
289
290 } catch (IOException e) {
291 /*
292 * If we were able to write so far, there should not be any
293 * problem at this point...
294 */
295 throw new RuntimeException("State system write error"); //$NON-NLS-1$
296 }
297 }
298 }
299
300 // ------------------------------------------------------------------------
301 // Accessors
302 // ------------------------------------------------------------------------
303
304 /**
305 * Get the start time of this tree.
306 *
307 * @return The start time
308 */
309 public long getTreeStart() {
310 return fConfig.getTreeStart();
311 }
312
313 /**
314 * Get the current end time of this tree.
315 *
316 * @return The end time
317 */
318 public long getTreeEnd() {
319 return fTreeEnd;
320 }
321
322 /**
323 * Get the number of nodes in this tree.
324 *
325 * @return The number of nodes
326 */
327 public int getNodeCount() {
328 return fNodeCount;
329 }
330
331 /**
332 * Get the current root node of this tree
333 *
334 * @return The root node
335 */
336 public HTNode getRootNode() {
337 return fLatestBranch.get(0);
338 }
339
340 /**
341 * Return the latest branch of the tree. That branch is immutable. Used for
342 * unit testing and debugging.
343 *
344 * @return The immutable latest branch
345 */
346 protected List<HTNode> getLatestBranch() {
347 return ImmutableList.copyOf(fLatestBranch);
348 }
349
350 // ------------------------------------------------------------------------
351 // HT_IO interface
352 // ------------------------------------------------------------------------
353
354 /**
355 * Return the FileInputStream reader with which we will read an attribute
356 * tree (it will be sought to the correct position).
357 *
358 * @return The FileInputStream indicating the file and position from which
359 * the attribute tree can be read.
360 */
361 public FileInputStream supplyATReader() {
362 return fTreeIO.supplyATReader(getNodeCount());
363 }
364
365 /**
366 * Return the file to which we will write the attribute tree.
367 *
368 * @return The file to which we will write the attribute tree
369 */
370 public File supplyATWriterFile() {
371 return fConfig.getStateFile();
372 }
373
374 /**
375 * Return the position in the file (given by {@link #supplyATWriterFile})
376 * where to start writing the attribute tree.
377 *
378 * @return The position in the file where to start writing
379 */
380 public long supplyATWriterFilePos() {
381 return HistoryTree.TREE_HEADER_SIZE
382 + ((long) getNodeCount() * fConfig.getBlockSize());
383 }
384
385 /**
386 * Read a node from the tree.
387 *
388 * @param seqNumber
389 * The sequence number of the node to read
390 * @return The node
391 * @throws ClosedChannelException
392 * If the tree IO is unavailable
393 */
394 public HTNode readNode(int seqNumber) throws ClosedChannelException {
395 /* Try to read the node from memory */
396 synchronized (fLatestBranch) {
397 for (HTNode node : fLatestBranch) {
398 if (node.getSequenceNumber() == seqNumber) {
399 return node;
400 }
401 }
402 }
403
404 /* Read the node from disk */
405 return fTreeIO.readNode(seqNumber);
406 }
407
408 /**
409 * Write a node object to the history file.
410 *
411 * @param node
412 * The node to write to disk
413 */
414 public void writeNode(HTNode node) {
415 fTreeIO.writeNode(node);
416 }
417
418 /**
419 * Close the history file.
420 */
421 public void closeFile() {
422 fTreeIO.closeFile();
423 }
424
425 /**
426 * Delete the history file.
427 */
428 public void deleteFile() {
429 fTreeIO.deleteFile();
430 }
431
432 // ------------------------------------------------------------------------
433 // Operations
434 // ------------------------------------------------------------------------
435
436 /**
437 * Insert an interval in the tree.
438 *
439 * @param interval
440 * The interval to be inserted
441 * @throws TimeRangeException
442 * If the start of end time of the interval are invalid
443 */
444 public void insertInterval(HTInterval interval) throws TimeRangeException {
445 if (interval.getStartTime() < fConfig.getTreeStart()) {
446 throw new TimeRangeException("Interval Start:" + interval.getStartTime() + ", Config Start:" + fConfig.getTreeStart()); //$NON-NLS-1$ //$NON-NLS-2$
447 }
448 tryInsertAtNode(interval, fLatestBranch.size() - 1);
449 }
450
451 /**
452 * Inner method to find in which node we should add the interval.
453 *
454 * @param interval
455 * The interval to add to the tree
456 * @param indexOfNode
457 * The index *in the latestBranch* where we are trying the
458 * insertion
459 */
460 private void tryInsertAtNode(HTInterval interval, int indexOfNode) {
461 HTNode targetNode = fLatestBranch.get(indexOfNode);
462
463 /* Verify if there is enough room in this node to store this interval */
464 if (interval.getIntervalSize() > targetNode.getNodeFreeSpace()) {
465 /* Nope, not enough room. Insert in a new sibling instead. */
466 addSiblingNode(indexOfNode);
467 tryInsertAtNode(interval, fLatestBranch.size() - 1);
468 return;
469 }
470
471 /* Make sure the interval time range fits this node */
472 if (interval.getStartTime() < targetNode.getNodeStart()) {
473 /*
474 * No, this interval starts before the startTime of this node. We
475 * need to check recursively in parents if it can fit.
476 */
477 assert (indexOfNode >= 1);
478 tryInsertAtNode(interval, indexOfNode - 1);
479 return;
480 }
481
482 /*
483 * Ok, there is room, and the interval fits in this time slot. Let's add
484 * it.
485 */
486 targetNode.addInterval(interval);
487
488 /* Update treeEnd if needed */
489 if (interval.getEndTime() > fTreeEnd) {
490 fTreeEnd = interval.getEndTime();
491 }
492 }
493
494 /**
495 * Method to add a sibling to any node in the latest branch. This will add
496 * children back down to the leaf level, if needed.
497 *
498 * @param indexOfNode
499 * The index in latestBranch where we start adding
500 */
501 private void addSiblingNode(int indexOfNode) {
502 synchronized (fLatestBranch) {
503 final long splitTime = fTreeEnd;
504
505 if (indexOfNode >= fLatestBranch.size()) {
506 /*
507 * We need to make sure (indexOfNode - 1) doesn't get the last
508 * node in the branch, because that one is a Leaf Node.
509 */
510 throw new IllegalStateException();
511 }
512
513 /* Check if we need to add a new root node */
514 if (indexOfNode == 0) {
515 addNewRootNode();
516 return;
517 }
518
519 /* Check if we can indeed add a child to the target parent */
520 if (((CoreNode) fLatestBranch.get(indexOfNode - 1)).getNbChildren() == fConfig.getMaxChildren()) {
521 /* If not, add a branch starting one level higher instead */
522 addSiblingNode(indexOfNode - 1);
523 return;
524 }
525
526 /* Split off the new branch from the old one */
527 for (int i = indexOfNode; i < fLatestBranch.size(); i++) {
528 fLatestBranch.get(i).closeThisNode(splitTime);
529 fTreeIO.writeNode(fLatestBranch.get(i));
530
531 CoreNode prevNode = (CoreNode) fLatestBranch.get(i - 1);
532 HTNode newNode;
533
534 switch (fLatestBranch.get(i).getNodeType()) {
535 case CORE:
536 newNode = initNewCoreNode(prevNode.getSequenceNumber(), splitTime + 1);
537 break;
538 case LEAF:
539 newNode = initNewLeafNode(prevNode.getSequenceNumber(), splitTime + 1);
540 break;
541 default:
542 throw new IllegalStateException();
543 }
544
545 prevNode.linkNewChild(newNode);
546 fLatestBranch.set(i, newNode);
547 }
548 }
549 }
550
551 /**
552 * Similar to the previous method, except here we rebuild a completely new
553 * latestBranch
554 */
555 private void addNewRootNode() {
556 final long splitTime = fTreeEnd;
557
558 HTNode oldRootNode = fLatestBranch.get(0);
559 CoreNode newRootNode = initNewCoreNode(-1, fConfig.getTreeStart());
560
561 /* Tell the old root node that it isn't root anymore */
562 oldRootNode.setParentSequenceNumber(newRootNode.getSequenceNumber());
563
564 /* Close off the whole current latestBranch */
565
566 for (int i = 0; i < fLatestBranch.size(); i++) {
567 fLatestBranch.get(i).closeThisNode(splitTime);
568 fTreeIO.writeNode(fLatestBranch.get(i));
569 }
570
571 /* Link the new root to its first child (the previous root node) */
572 newRootNode.linkNewChild(oldRootNode);
573
574 /* Rebuild a new latestBranch */
575 int depth = fLatestBranch.size();
576 fLatestBranch.clear();
577 fLatestBranch.add(newRootNode);
578
579 // Create new coreNode
580 for (int i = 1; i < depth + 1; i++) {
581 CoreNode prevNode = (CoreNode) fLatestBranch.get(i - 1);
582 CoreNode newNode = initNewCoreNode(prevNode.getParentSequenceNumber(),
583 splitTime + 1);
584 prevNode.linkNewChild(newNode);
585 fLatestBranch.add(newNode);
586 }
587
588 // Create the new leafNode
589 CoreNode prevNode = (CoreNode) fLatestBranch.get(depth);
590 LeafNode newNode = initNewLeafNode(prevNode.getParentSequenceNumber(), splitTime + 1);
591 prevNode.linkNewChild(newNode);
592 fLatestBranch.add(newNode);
593 }
594
595 /**
596 * Add a new empty core node to the tree.
597 *
598 * @param parentSeqNumber
599 * Sequence number of this node's parent
600 * @param startTime
601 * Start time of the new node
602 * @return The newly created node
603 */
604 private CoreNode initNewCoreNode(int parentSeqNumber, long startTime) {
605 CoreNode newNode = new CoreNode(fConfig, fNodeCount, parentSeqNumber,
606 startTime);
607 fNodeCount++;
608
609 /* Update the treeEnd if needed */
610 if (startTime >= fTreeEnd) {
611 fTreeEnd = startTime + 1;
612 }
613 return newNode;
614 }
615
616 /**
617 * Add a new empty leaf node to the tree.
618 *
619 * @param parentSeqNumber
620 * Sequence number of this node's parent
621 * @param startTime
622 * Start time of the new node
623 * @return The newly created node
624 */
625 private LeafNode initNewLeafNode(int parentSeqNumber, long startTime) {
626 LeafNode newNode = new LeafNode(fConfig, fNodeCount, parentSeqNumber,
627 startTime);
628 fNodeCount++;
629
630 /* Update the treeEnd if needed */
631 if (startTime >= fTreeEnd) {
632 fTreeEnd = startTime + 1;
633 }
634 return newNode;
635 }
636
637 /**
638 * Inner method to select the next child of the current node intersecting
639 * the given timestamp. Useful for moving down the tree following one
640 * branch.
641 *
642 * @param currentNode
643 * The node on which the request is made
644 * @param t
645 * The timestamp to choose which child is the next one
646 * @return The child node intersecting t
647 * @throws ClosedChannelException
648 * If the file channel was closed while we were reading the tree
649 */
650 public HTNode selectNextChild(CoreNode currentNode, long t) throws ClosedChannelException {
651 assert (currentNode.getNbChildren() > 0);
652 int potentialNextSeqNb = currentNode.getSequenceNumber();
653
654 for (int i = 0; i < currentNode.getNbChildren(); i++) {
655 if (t >= currentNode.getChildStart(i)) {
656 potentialNextSeqNb = currentNode.getChild(i);
657 } else {
658 break;
659 }
660 }
661
662 /*
663 * Once we exit this loop, we should have found a children to follow. If
664 * we didn't, there's a problem.
665 */
666 assert (potentialNextSeqNb != currentNode.getSequenceNumber());
667
668 /*
669 * Since this code path is quite performance-critical, avoid iterating
670 * through the whole latestBranch array if we know for sure the next
671 * node has to be on disk
672 */
673 if (currentNode.isOnDisk()) {
674 return fTreeIO.readNode(potentialNextSeqNb);
675 }
676 return readNode(potentialNextSeqNb);
677 }
678
679 /**
680 * Get the current size of the history file.
681 *
682 * @return The history file size
683 */
684 public long getFileSize() {
685 return fConfig.getStateFile().length();
686 }
687
688 // ------------------------------------------------------------------------
689 // Test/debugging methods
690 // ------------------------------------------------------------------------
691
692 /**
693 * Debugging method to make sure all intervals contained in the given node
694 * have valid start and end times.
695 *
696 * @param zenode
697 * The node to check
698 * @return True if everything is fine, false if there is at least one
699 * invalid timestamp (end time < start time, time outside of the
700 * range of the node, etc.)
701 */
702 @SuppressWarnings("nls")
703 public boolean checkNodeIntegrity(HTNode zenode) {
704 /* Only used for debugging, shouldn't be externalized */
705 HTNode otherNode;
706 CoreNode node;
707 StringBuffer buf = new StringBuffer();
708 boolean ret = true;
709
710 // FIXME /* Only testing Core Nodes for now */
711 if (!(zenode instanceof CoreNode)) {
712 return true;
713 }
714
715 node = (CoreNode) zenode;
716
717 try {
718 /*
719 * Test that this node's start and end times match the start of the
720 * first child and the end of the last child, respectively
721 */
722 if (node.getNbChildren() > 0) {
723 otherNode = fTreeIO.readNode(node.getChild(0));
724 if (node.getNodeStart() != otherNode.getNodeStart()) {
725 buf.append("Start time of node (" + node.getNodeStart() + ") "
726 + "does not match start time of first child " + "("
727 + otherNode.getNodeStart() + "), " + "node #"
728 + otherNode.getSequenceNumber() + ")\n");
729 ret = false;
730 }
731 if (node.isOnDisk()) {
732 otherNode = fTreeIO.readNode(node.getLatestChild());
733 if (node.getNodeEnd() != otherNode.getNodeEnd()) {
734 buf.append("End time of node (" + node.getNodeEnd()
735 + ") does not match end time of last child ("
736 + otherNode.getNodeEnd() + ", node #"
737 + otherNode.getSequenceNumber() + ")\n");
738 ret = false;
739 }
740 }
741 }
742
743 /*
744 * Test that the childStartTimes[] array matches the real nodes'
745 * start times
746 */
747 for (int i = 0; i < node.getNbChildren(); i++) {
748 otherNode = fTreeIO.readNode(node.getChild(i));
749 if (otherNode.getNodeStart() != node.getChildStart(i)) {
750 buf.append(" Expected start time of child node #"
751 + node.getChild(i) + ": " + node.getChildStart(i)
752 + "\n" + " Actual start time of node #"
753 + otherNode.getSequenceNumber() + ": "
754 + otherNode.getNodeStart() + "\n");
755 ret = false;
756 }
757 }
758
759 } catch (ClosedChannelException e) {
760 Activator.getDefault().logError(e.getMessage(), e);
761 }
762
763 if (!ret) {
764 Activator.getDefault().logError("SHT: Integrity check failed for node #"
765 + node.getSequenceNumber() + ":" + buf.toString());
766 }
767 return ret;
768 }
769
770 /**
771 * Check the integrity of all the nodes in the tree. Calls
772 * {@link #checkNodeIntegrity} for every node in the tree.
773 */
774 public void checkIntegrity() {
775 try {
776 for (int i = 0; i < fNodeCount; i++) {
777 checkNodeIntegrity(fTreeIO.readNode(i));
778 }
779 } catch (ClosedChannelException e) {
780 }
781 }
782
783 /* Only used for debugging, shouldn't be externalized */
784 @SuppressWarnings("nls")
785 @Override
786 public String toString() {
787 return "Information on the current tree:\n\n" + "Blocksize: "
788 + fConfig.getBlockSize() + "\n" + "Max nb. of children per node: "
789 + fConfig.getMaxChildren() + "\n" + "Number of nodes: " + fNodeCount
790 + "\n" + "Depth of the tree: " + fLatestBranch.size() + "\n"
791 + "Size of the treefile: " + getFileSize() + "\n"
792 + "Root node has sequence number: "
793 + fLatestBranch.get(0).getSequenceNumber() + "\n"
794 + "'Latest leaf' has sequence number: "
795 + fLatestBranch.get(fLatestBranch.size() - 1).getSequenceNumber();
796 }
797
798 /**
799 * Start at currentNode and print the contents of all its children, in
800 * pre-order. Give the root node in parameter to visit the whole tree, and
801 * have a nice overview.
802 */
803 /* Only used for debugging, shouldn't be externalized */
804 @SuppressWarnings("nls")
805 private void preOrderPrint(PrintWriter writer, boolean printIntervals,
806 HTNode currentNode, int curDepth) {
807
808 writer.println(currentNode.toString());
809 if (printIntervals) {
810 currentNode.debugPrintIntervals(writer);
811 }
812
813 switch (currentNode.getNodeType()) {
814 case LEAF:
815 /* Stop if it's the leaf node */
816 return;
817
818 case CORE:
819 try {
820 final CoreNode node = (CoreNode) currentNode;
821 /* Print the extensions, if any */
822 int extension = node.getExtensionSequenceNumber();
823 while (extension != -1) {
824 HTNode nextNode = fTreeIO.readNode(extension);
825 preOrderPrint(writer, printIntervals, nextNode, curDepth);
826 }
827
828 /* Print the child nodes */
829 for (int i = 0; i < node.getNbChildren(); i++) {
830 HTNode nextNode = fTreeIO.readNode(node.getChild(i));
831 for (int j = 0; j < curDepth; j++) {
832 writer.print(" ");
833 }
834 writer.print("+-");
835 preOrderPrint(writer, printIntervals, nextNode, curDepth + 1);
836 }
837 } catch (ClosedChannelException e) {
838 Activator.getDefault().logError(e.getMessage());
839 }
840 break;
841
842 default:
843 break;
844 }
845 }
846
847 /**
848 * Print out the full tree for debugging purposes
849 *
850 * @param writer
851 * PrintWriter in which to write the output
852 * @param printIntervals
853 * Flag to enable full output of the interval information
854 */
855 public void debugPrintFullTree(PrintWriter writer, boolean printIntervals) {
856 /* Only used for debugging, shouldn't be externalized */
857
858 preOrderPrint(writer, false, fLatestBranch.get(0), 0);
859
860 if (printIntervals) {
861 writer.println("\nDetails of intervals:"); //$NON-NLS-1$
862 preOrderPrint(writer, true, fLatestBranch.get(0), 0);
863 }
864 writer.println('\n');
865 }
866
867 }
This page took 0.062362 seconds and 4 git commands to generate.