1 /*******************************************************************************
2 * Copyright (c) 2010, 2014 Ericsson, École Polytechnique de Montréal, and others
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
10 * Alexandre Montplaisir - Initial API and implementation
11 * Florian Wininger - Add Extension and Leaf Node
12 *******************************************************************************/
14 package org
.eclipse
.tracecompass
.internal
.statesystem
.core
.backend
.historytree
;
17 import java
.io
.FileInputStream
;
18 import java
.io
.IOException
;
19 import java
.io
.PrintWriter
;
20 import java
.nio
.ByteBuffer
;
21 import java
.nio
.ByteOrder
;
22 import java
.nio
.channels
.ClosedChannelException
;
23 import java
.nio
.channels
.FileChannel
;
24 import java
.util
.ArrayList
;
25 import java
.util
.Collections
;
26 import java
.util
.List
;
28 import org
.eclipse
.tracecompass
.internal
.statesystem
.core
.Activator
;
29 import org
.eclipse
.tracecompass
.statesystem
.core
.ITmfStateSystemBuilder
;
30 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.TimeRangeException
;
33 * Meta-container for the History Tree. This structure contains all the
34 * high-level data relevant to the tree.
36 * @author Alexandre Montplaisir
38 public class HistoryTree
{
41 * Size of the "tree header" in the tree-file The nodes will use this offset
42 * to know where they should be in the file. This should always be a
45 public static final int TREE_HEADER_SIZE
= 4096;
47 private static final int HISTORY_FILE_MAGIC_NUMBER
= 0x05FFA900;
49 /** File format version. Increment when breaking compatibility. */
50 private static final int FILE_VERSION
= 4;
52 // ------------------------------------------------------------------------
53 // Tree-specific configuration
54 // ------------------------------------------------------------------------
56 /** Container for all the configuration constants */
57 private final HTConfig config
;
59 /** Reader/writer object */
60 private final HT_IO treeIO
;
62 // ------------------------------------------------------------------------
63 // Variable Fields (will change throughout the existence of the SHT)
64 // ------------------------------------------------------------------------
66 /** Latest timestamp found in the tree (at any given moment) */
69 /** The total number of nodes that exists in this tree */
70 private int nodeCount
;
72 /** "Cache" to keep the active nodes in memory */
73 private final List
<HTNode
> latestBranch
;
75 // ------------------------------------------------------------------------
76 // Constructors/"Destructors"
77 // ------------------------------------------------------------------------
80 * Create a new State History from scratch, using a {@link HTConfig} object
84 * The config to use for this History Tree.
86 * If an error happens trying to open/write to the file
87 * specified in the config
89 public HistoryTree(HTConfig conf
) throws IOException
{
91 * Simple check to make sure we have enough place in the 0th block for
92 * the tree configuration
94 if (conf
.getBlockSize() < TREE_HEADER_SIZE
) {
95 throw new IllegalArgumentException();
99 treeEnd
= conf
.getTreeStart();
101 latestBranch
= Collections
.synchronizedList(new ArrayList
<HTNode
>());
103 /* Prepare the IO object */
104 treeIO
= new HT_IO(config
, true);
106 /* Add the first node to the tree */
107 LeafNode firstNode
= initNewLeafNode(-1, conf
.getTreeStart());
108 latestBranch
.add(firstNode
);
112 * "Reader" constructor : instantiate a SHTree from an existing tree file on
115 * @param existingStateFile
116 * Path/filename of the history-file we are to open
117 * @param expProviderVersion
118 * The expected version of the state provider
119 * @throws IOException
120 * If an error happens reading the file
122 public HistoryTree(File existingStateFile
, int expProviderVersion
) throws IOException
{
124 * Open the file ourselves, get the tree header information we need,
125 * then pass on the descriptor to the TreeIO object.
127 int rootNodeSeqNb
, res
;
131 /* Java I/O mumbo jumbo... */
132 if (!existingStateFile
.exists()) {
133 throw new IOException("Selected state file does not exist"); //$NON-NLS-1$
135 if (existingStateFile
.length() <= 0) {
136 throw new IOException("Empty target file"); //$NON-NLS-1$
139 try (FileInputStream fis
= new FileInputStream(existingStateFile
);
140 FileChannel fc
= fis
.getChannel();) {
142 ByteBuffer buffer
= ByteBuffer
.allocate(TREE_HEADER_SIZE
);
144 buffer
.order(ByteOrder
.LITTLE_ENDIAN
);
150 * Check the magic number to make sure we're opening the right type
153 res
= buffer
.getInt();
154 if (res
!= HISTORY_FILE_MAGIC_NUMBER
) {
155 throw new IOException("Wrong magic number"); //$NON-NLS-1$
158 res
= buffer
.getInt(); /* File format version number */
159 if (res
!= FILE_VERSION
) {
160 throw new IOException("Mismatching History Tree file format versions"); //$NON-NLS-1$
163 res
= buffer
.getInt(); /* Event handler's version number */
164 if (res
!= expProviderVersion
&&
165 expProviderVersion
!= ITmfStateSystemBuilder
.IGNORE_PROVIDER_VERSION
) {
167 * The existing history was built using an event handler that
168 * doesn't match the current one in the framework.
170 * Information could be all wrong. Instead of keeping an
171 * incorrect history file, a rebuild is done.
173 throw new IOException("Mismatching event handler versions"); //$NON-NLS-1$
176 bs
= buffer
.getInt(); /* Block Size */
177 maxc
= buffer
.getInt(); /* Max nb of children per node */
179 this.nodeCount
= buffer
.getInt();
180 rootNodeSeqNb
= buffer
.getInt();
181 startTime
= buffer
.getLong();
183 this.config
= new HTConfig(existingStateFile
, bs
, maxc
, expProviderVersion
, startTime
);
187 * FIXME We close fis here and the TreeIO will then reopen the same
188 * file, not extremely elegant. But how to pass the information here to
191 this.treeIO
= new HT_IO(config
, false);
193 this.latestBranch
= buildLatestBranch(rootNodeSeqNb
);
194 this.treeEnd
= getRootNode().getNodeEnd();
197 * Make sure the history start time we read previously is consistent
198 * with was is actually in the root node.
200 if (startTime
!= getRootNode().getNodeStart()) {
201 throw new IOException("Inconsistent start times in the" + //$NON-NLS-1$
202 "history file, it might be corrupted."); //$NON-NLS-1$
207 * Rebuild the latestBranch "cache" object by reading the nodes from disk
208 * (When we are opening an existing file on disk and want to append to it,
211 * @param rootNodeSeqNb
212 * The sequence number of the root node, so we know where to
214 * @throws ClosedChannelException
216 private List
<HTNode
> buildLatestBranch(int rootNodeSeqNb
) throws ClosedChannelException
{
217 List
<HTNode
> list
= new ArrayList
<>();
219 HTNode nextChildNode
= treeIO
.readNode(rootNodeSeqNb
);
220 list
.add(nextChildNode
);
222 /* Follow the last branch up to the leaf */
223 while (nextChildNode
.getNodeType() == HTNode
.NodeType
.CORE
) {
224 nextChildNode
= treeIO
.readNode(((CoreNode
) nextChildNode
).getLatestChild());
225 list
.add(nextChildNode
);
227 return Collections
.synchronizedList(list
);
231 * "Save" the tree to disk. This method will cause the treeIO object to
232 * commit all nodes to disk and then return the RandomAccessFile descriptor
233 * so the Tree object can save its configuration into the header of the
236 * @param requestedEndTime
237 * The greatest timestamp present in the history tree
239 public void closeTree(long requestedEndTime
) {
240 /* This is an important operation, queries can wait */
241 synchronized (latestBranch
) {
243 * Work-around the "empty branches" that get created when the root
244 * node becomes full. Overwrite the tree's end time with the
245 * original wanted end-time, to ensure no queries are sent into
248 * This won't be needed once extended nodes are implemented.
250 this.treeEnd
= requestedEndTime
;
252 /* Close off the latest branch of the tree */
253 for (int i
= 0; i
< latestBranch
.size(); i
++) {
254 latestBranch
.get(i
).closeThisNode(treeEnd
);
255 treeIO
.writeNode(latestBranch
.get(i
));
258 try (FileChannel fc
= treeIO
.getFcOut();) {
259 ByteBuffer buffer
= ByteBuffer
.allocate(TREE_HEADER_SIZE
);
260 buffer
.order(ByteOrder
.LITTLE_ENDIAN
);
263 /* Save the config of the tree to the header of the file */
266 buffer
.putInt(HISTORY_FILE_MAGIC_NUMBER
);
268 buffer
.putInt(FILE_VERSION
);
269 buffer
.putInt(config
.getProviderVersion());
271 buffer
.putInt(config
.getBlockSize());
272 buffer
.putInt(config
.getMaxChildren());
274 buffer
.putInt(nodeCount
);
276 /* root node seq. nb */
277 buffer
.putInt(latestBranch
.get(0).getSequenceNumber());
279 /* start time of this history */
280 buffer
.putLong(latestBranch
.get(0).getNodeStart());
283 int res
= fc
.write(buffer
);
284 assert (res
<= TREE_HEADER_SIZE
);
285 /* done writing the file header */
287 } catch (IOException e
) {
289 * If we were able to write so far, there should not be any
290 * problem at this point...
292 throw new RuntimeException("State system write error"); //$NON-NLS-1$
297 // ------------------------------------------------------------------------
299 // ------------------------------------------------------------------------
302 * Get the start time of this tree.
304 * @return The start time
306 public long getTreeStart() {
307 return config
.getTreeStart();
311 * Get the current end time of this tree.
313 * @return The end time
315 public long getTreeEnd() {
320 * Get the number of nodes in this tree.
322 * @return The number of nodes
324 public int getNodeCount() {
329 * Get the current root node of this tree
331 * @return The root node
333 public HTNode
getRootNode() {
334 return latestBranch
.get(0);
337 // ------------------------------------------------------------------------
339 // ------------------------------------------------------------------------
342 * Return the FileInputStream reader with which we will read an attribute
343 * tree (it will be sought to the correct position).
345 * @return The FileInputStream indicating the file and position from which
346 * the attribute tree can be read.
348 public FileInputStream
supplyATReader() {
349 return treeIO
.supplyATReader(getNodeCount());
353 * Return the file to which we will write the attribute tree.
355 * @return The file to which we will write the attribute tree
357 public File
supplyATWriterFile() {
358 return config
.getStateFile();
362 * Return the position in the file (given by {@link #supplyATWriterFile})
363 * where to start writing the attribute tree.
365 * @return The position in the file where to start writing
367 public long supplyATWriterFilePos() {
368 return HistoryTree
.TREE_HEADER_SIZE
369 + ((long) getNodeCount() * config
.getBlockSize());
373 * Read a node from the tree.
376 * The sequence number of the node to read
378 * @throws ClosedChannelException
379 * If the tree IO is unavailable
381 public HTNode
readNode(int seqNumber
) throws ClosedChannelException
{
382 /* Try to read the node from memory */
383 synchronized (latestBranch
) {
384 for (HTNode node
: latestBranch
) {
385 if (node
.getSequenceNumber() == seqNumber
) {
391 /* Read the node from disk */
392 return treeIO
.readNode(seqNumber
);
396 * Write a node object to the history file.
399 * The node to write to disk
401 public void writeNode(HTNode node
) {
402 treeIO
.writeNode(node
);
406 * Close the history file.
408 public void closeFile() {
413 * Delete the history file.
415 public void deleteFile() {
419 // ------------------------------------------------------------------------
421 // ------------------------------------------------------------------------
424 * Insert an interval in the tree.
427 * The interval to be inserted
428 * @throws TimeRangeException
429 * If the start of end time of the interval are invalid
431 public void insertInterval(HTInterval interval
) throws TimeRangeException
{
432 if (interval
.getStartTime() < config
.getTreeStart()) {
433 throw new TimeRangeException();
435 tryInsertAtNode(interval
, latestBranch
.size() - 1);
439 * Inner method to find in which node we should add the interval.
442 * The interval to add to the tree
444 * The index *in the latestBranch* where we are trying the
447 private void tryInsertAtNode(HTInterval interval
, int indexOfNode
) {
448 HTNode targetNode
= latestBranch
.get(indexOfNode
);
450 /* Verify if there is enough room in this node to store this interval */
451 if (interval
.getIntervalSize() > targetNode
.getNodeFreeSpace()) {
452 /* Nope, not enough room. Insert in a new sibling instead. */
453 addSiblingNode(indexOfNode
);
454 tryInsertAtNode(interval
, latestBranch
.size() - 1);
458 /* Make sure the interval time range fits this node */
459 if (interval
.getStartTime() < targetNode
.getNodeStart()) {
461 * No, this interval starts before the startTime of this node. We
462 * need to check recursively in parents if it can fit.
464 assert (indexOfNode
>= 1);
465 tryInsertAtNode(interval
, indexOfNode
- 1);
470 * Ok, there is room, and the interval fits in this time slot. Let's add
473 targetNode
.addInterval(interval
);
475 /* Update treeEnd if needed */
476 if (interval
.getEndTime() > this.treeEnd
) {
477 this.treeEnd
= interval
.getEndTime();
482 * Method to add a sibling to any node in the latest branch. This will add
483 * children back down to the leaf level, if needed.
486 * The index in latestBranch where we start adding
488 private void addSiblingNode(int indexOfNode
) {
489 synchronized (latestBranch
) {
490 final long splitTime
= treeEnd
;
492 if (indexOfNode
>= latestBranch
.size()) {
494 * We need to make sure (indexOfNode - 1) doesn't get the last
495 * node in the branch, because that one is a Leaf Node.
497 throw new IllegalStateException();
500 /* Check if we need to add a new root node */
501 if (indexOfNode
== 0) {
506 /* Check if we can indeed add a child to the target parent */
507 if (((CoreNode
) latestBranch
.get(indexOfNode
- 1)).getNbChildren() == config
.getMaxChildren()) {
508 /* If not, add a branch starting one level higher instead */
509 addSiblingNode(indexOfNode
- 1);
513 /* Split off the new branch from the old one */
514 for (int i
= indexOfNode
; i
< latestBranch
.size(); i
++) {
515 latestBranch
.get(i
).closeThisNode(splitTime
);
516 treeIO
.writeNode(latestBranch
.get(i
));
518 CoreNode prevNode
= (CoreNode
) latestBranch
.get(i
- 1);
521 switch (latestBranch
.get(i
).getNodeType()) {
523 newNode
= initNewCoreNode(prevNode
.getSequenceNumber(), splitTime
+ 1);
526 newNode
= initNewLeafNode(prevNode
.getSequenceNumber(), splitTime
+ 1);
529 throw new IllegalStateException();
532 prevNode
.linkNewChild(newNode
);
533 latestBranch
.set(i
, newNode
);
539 * Similar to the previous method, except here we rebuild a completely new
542 private void addNewRootNode() {
543 final long splitTime
= this.treeEnd
;
545 HTNode oldRootNode
= latestBranch
.get(0);
546 CoreNode newRootNode
= initNewCoreNode(-1, config
.getTreeStart());
548 /* Tell the old root node that it isn't root anymore */
549 oldRootNode
.setParentSequenceNumber(newRootNode
.getSequenceNumber());
551 /* Close off the whole current latestBranch */
553 for (int i
= 0; i
< latestBranch
.size(); i
++) {
554 latestBranch
.get(i
).closeThisNode(splitTime
);
555 treeIO
.writeNode(latestBranch
.get(i
));
558 /* Link the new root to its first child (the previous root node) */
559 newRootNode
.linkNewChild(oldRootNode
);
561 /* Rebuild a new latestBranch */
562 int depth
= latestBranch
.size();
563 latestBranch
.clear();
564 latestBranch
.add(newRootNode
);
566 // Create new coreNode
567 for (int i
= 1; i
< depth
+ 1; i
++) {
568 CoreNode prevNode
= (CoreNode
) latestBranch
.get(i
- 1);
569 CoreNode newNode
= initNewCoreNode(prevNode
.getParentSequenceNumber(),
571 prevNode
.linkNewChild(newNode
);
572 latestBranch
.add(newNode
);
575 // Create the new leafNode
576 CoreNode prevNode
= (CoreNode
) latestBranch
.get(depth
);
577 LeafNode newNode
= initNewLeafNode(prevNode
.getParentSequenceNumber(), splitTime
+ 1);
578 prevNode
.linkNewChild(newNode
);
579 latestBranch
.add(newNode
);
583 * Add a new empty core node to the tree.
585 * @param parentSeqNumber
586 * Sequence number of this node's parent
588 * Start time of the new node
589 * @return The newly created node
591 private CoreNode
initNewCoreNode(int parentSeqNumber
, long startTime
) {
592 CoreNode newNode
= new CoreNode(config
, this.nodeCount
, parentSeqNumber
,
596 /* Update the treeEnd if needed */
597 if (startTime
>= this.treeEnd
) {
598 this.treeEnd
= startTime
+ 1;
604 * Add a new empty leaf node to the tree.
606 * @param parentSeqNumber
607 * Sequence number of this node's parent
609 * Start time of the new node
610 * @return The newly created node
612 private LeafNode
initNewLeafNode(int parentSeqNumber
, long startTime
) {
613 LeafNode newNode
= new LeafNode(config
, this.nodeCount
, parentSeqNumber
,
617 /* Update the treeEnd if needed */
618 if (startTime
>= this.treeEnd
) {
619 this.treeEnd
= startTime
+ 1;
625 * Inner method to select the next child of the current node intersecting
626 * the given timestamp. Useful for moving down the tree following one
630 * The node on which the request is made
632 * The timestamp to choose which child is the next one
633 * @return The child node intersecting t
634 * @throws ClosedChannelException
635 * If the file channel was closed while we were reading the tree
637 public HTNode
selectNextChild(CoreNode currentNode
, long t
) throws ClosedChannelException
{
638 assert (currentNode
.getNbChildren() > 0);
639 int potentialNextSeqNb
= currentNode
.getSequenceNumber();
641 for (int i
= 0; i
< currentNode
.getNbChildren(); i
++) {
642 if (t
>= currentNode
.getChildStart(i
)) {
643 potentialNextSeqNb
= currentNode
.getChild(i
);
650 * Once we exit this loop, we should have found a children to follow. If
651 * we didn't, there's a problem.
653 assert (potentialNextSeqNb
!= currentNode
.getSequenceNumber());
656 * Since this code path is quite performance-critical, avoid iterating
657 * through the whole latestBranch array if we know for sure the next
658 * node has to be on disk
660 if (currentNode
.isOnDisk()) {
661 return treeIO
.readNode(potentialNextSeqNb
);
663 return readNode(potentialNextSeqNb
);
667 * Get the current size of the history file.
669 * @return The history file size
671 public long getFileSize() {
672 return config
.getStateFile().length();
675 // ------------------------------------------------------------------------
676 // Test/debugging methods
677 // ------------------------------------------------------------------------
680 * Debugging method to make sure all intervals contained in the given node
681 * have valid start and end times.
685 * @return True if everything is fine, false if there is at least one
686 * invalid timestamp (end time < start time, time outside of the
687 * range of the node, etc.)
689 @SuppressWarnings("nls")
690 public boolean checkNodeIntegrity(HTNode zenode
) {
691 /* Only used for debugging, shouldn't be externalized */
694 StringBuffer buf
= new StringBuffer();
697 // FIXME /* Only testing Core Nodes for now */
698 if (!(zenode
instanceof CoreNode
)) {
702 node
= (CoreNode
) zenode
;
706 * Test that this node's start and end times match the start of the
707 * first child and the end of the last child, respectively
709 if (node
.getNbChildren() > 0) {
710 otherNode
= treeIO
.readNode(node
.getChild(0));
711 if (node
.getNodeStart() != otherNode
.getNodeStart()) {
712 buf
.append("Start time of node (" + node
.getNodeStart() + ") "
713 + "does not match start time of first child " + "("
714 + otherNode
.getNodeStart() + "), " + "node #"
715 + otherNode
.getSequenceNumber() + ")\n");
718 if (node
.isOnDisk()) {
719 otherNode
= treeIO
.readNode(node
.getLatestChild());
720 if (node
.getNodeEnd() != otherNode
.getNodeEnd()) {
721 buf
.append("End time of node (" + node
.getNodeEnd()
722 + ") does not match end time of last child ("
723 + otherNode
.getNodeEnd() + ", node #"
724 + otherNode
.getSequenceNumber() + ")\n");
731 * Test that the childStartTimes[] array matches the real nodes'
734 for (int i
= 0; i
< node
.getNbChildren(); i
++) {
735 otherNode
= treeIO
.readNode(node
.getChild(i
));
736 if (otherNode
.getNodeStart() != node
.getChildStart(i
)) {
737 buf
.append(" Expected start time of child node #"
738 + node
.getChild(i
) + ": " + node
.getChildStart(i
)
739 + "\n" + " Actual start time of node #"
740 + otherNode
.getSequenceNumber() + ": "
741 + otherNode
.getNodeStart() + "\n");
746 } catch (ClosedChannelException e
) {
751 System
.out
.println("");
752 System
.out
.println("SHT: Integrity check failed for node #"
753 + node
.getSequenceNumber() + ":");
754 System
.out
.println(buf
.toString());
760 * Check the integrity of all the nodes in the tree. Calls
761 * {@link #checkNodeIntegrity} for every node in the tree.
763 public void checkIntegrity() {
765 for (int i
= 0; i
< nodeCount
; i
++) {
766 checkNodeIntegrity(treeIO
.readNode(i
));
768 } catch (ClosedChannelException e
) {
772 /* Only used for debugging, shouldn't be externalized */
773 @SuppressWarnings("nls")
775 public String
toString() {
776 return "Information on the current tree:\n\n" + "Blocksize: "
777 + config
.getBlockSize() + "\n" + "Max nb. of children per node: "
778 + config
.getMaxChildren() + "\n" + "Number of nodes: " + nodeCount
779 + "\n" + "Depth of the tree: " + latestBranch
.size() + "\n"
780 + "Size of the treefile: " + this.getFileSize() + "\n"
781 + "Root node has sequence number: "
782 + latestBranch
.get(0).getSequenceNumber() + "\n"
783 + "'Latest leaf' has sequence number: "
784 + latestBranch
.get(latestBranch
.size() - 1).getSequenceNumber();
788 * Start at currentNode and print the contents of all its children, in
789 * pre-order. Give the root node in parameter to visit the whole tree, and
790 * have a nice overview.
792 /* Only used for debugging, shouldn't be externalized */
793 @SuppressWarnings("nls")
794 private void preOrderPrint(PrintWriter writer
, boolean printIntervals
,
795 HTNode currentNode
, int curDepth
) {
797 writer
.println(currentNode
.toString());
798 if (printIntervals
) {
799 currentNode
.debugPrintIntervals(writer
);
802 switch (currentNode
.getNodeType()) {
804 /* Stop if it's the leaf node */
809 final CoreNode node
= (CoreNode
) currentNode
;
810 /* Print the extensions, if any */
811 int extension
= node
.getExtensionSequenceNumber();
812 while (extension
!= -1) {
813 HTNode nextNode
= treeIO
.readNode(extension
);
814 preOrderPrint(writer
, printIntervals
, nextNode
, curDepth
);
817 /* Print the child nodes */
818 for (int i
= 0; i
< node
.getNbChildren(); i
++) {
819 HTNode nextNode
= treeIO
.readNode(node
.getChild(i
));
820 for (int j
= 0; j
< curDepth
; j
++) {
824 preOrderPrint(writer
, printIntervals
, nextNode
, curDepth
+ 1);
826 } catch (ClosedChannelException e
) {
827 Activator
.getDefault().logError(e
.getMessage());
837 * Print out the full tree for debugging purposes
840 * PrintWriter in which to write the output
841 * @param printIntervals
842 * Flag to enable full output of the interval information
844 public void debugPrintFullTree(PrintWriter writer
, boolean printIntervals
) {
845 /* Only used for debugging, shouldn't be externalized */
847 this.preOrderPrint(writer
, false, latestBranch
.get(0), 0);
849 if (printIntervals
) {
850 writer
.println("\nDetails of intervals:"); //$NON-NLS-1$
851 this.preOrderPrint(writer
, true, latestBranch
.get(0), 0);
853 writer
.println('\n');