1 /*******************************************************************************
2 * Copyright (c) 2012, 2013 Ericsson
3 * Copyright (c) 2010, 2011 École Polytechnique de Montréal
4 * Copyright (c) 2010, 2011 Alexandre Montplaisir <alexandre.montplaisir@gmail.com>
6 * All rights reserved. This program and the accompanying materials are
7 * made available under the terms of the Eclipse Public License v1.0 which
8 * accompanies this distribution, and is available at
9 * http://www.eclipse.org/legal/epl-v10.html
11 *******************************************************************************/
13 package org
.eclipse
.linuxtools
.internal
.tmf
.core
.statesystem
.backends
.historytree
;
16 import java
.io
.FileInputStream
;
17 import java
.io
.IOException
;
18 import java
.io
.PrintWriter
;
19 import java
.nio
.ByteBuffer
;
20 import java
.nio
.ByteOrder
;
21 import java
.nio
.channels
.ClosedChannelException
;
22 import java
.nio
.channels
.FileChannel
;
23 import java
.util
.ArrayList
;
24 import java
.util
.Collections
;
25 import java
.util
.List
;
27 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.TimeRangeException
;
28 import org
.eclipse
.linuxtools
.tmf
.core
.statesystem
.ITmfStateProvider
;
31 * Meta-container for the History Tree. This structure contains all the
32 * high-level data relevant to the tree.
40 * Size of the "tree header" in the tree-file The nodes will use this offset
41 * to know where they should be in the file. This should always be a
44 public static final int TREE_HEADER_SIZE
= 4096;
46 private static final int HISTORY_FILE_MAGIC_NUMBER
= 0x05FFA900;
48 /** File format version. Increment when breaking compatibility. */
49 private static final int FILE_VERSION
= 3;
51 // ------------------------------------------------------------------------
52 // Tree-specific configuration
53 // ------------------------------------------------------------------------
55 /** Container for all the configuration constants */
56 private final HTConfig config
;
58 /** Reader/writer object */
59 private final HT_IO treeIO
;
61 // ------------------------------------------------------------------------
62 // Variable Fields (will change throughout the existence of the SHT)
63 // ------------------------------------------------------------------------
65 /** Latest timestamp found in the tree (at any given moment) */
68 /** How many nodes exist in this tree, total */
69 private int nodeCount
;
71 /** "Cache" to keep the active nodes in memory */
72 private List
<CoreNode
> latestBranch
;
74 // ------------------------------------------------------------------------
75 // Constructors/"Destructors"
76 // ------------------------------------------------------------------------
79 * Create a new State History from scratch, using a SHTConfig object for
82 HistoryTree(HTConfig conf
) throws IOException
{
84 * Simple check to make sure we have enough place in the 0th block
85 * for the tree configuration
87 if (conf
.getBlockSize() < TREE_HEADER_SIZE
) {
88 throw new IllegalArgumentException();
92 treeEnd
= conf
.getTreeStart();
94 latestBranch
= new ArrayList
<CoreNode
>();
96 /* Prepare the IO object */
97 treeIO
= new HT_IO(this, true);
99 /* Add the first node to the tree */
100 CoreNode firstNode
= initNewCoreNode(-1, conf
.getTreeStart());
101 latestBranch
.add(firstNode
);
105 * "Reader" constructor : instantiate a SHTree from an existing tree file on
108 * @param existingFileName
109 * Path/filename of the history-file we are to open
110 * @param expProviderVersion
111 * The expected version of the state provider
112 * @throws IOException
114 HistoryTree(File existingStateFile
, int expProviderVersion
) throws IOException
{
116 * Open the file ourselves, get the tree header information we need,
117 * then pass on the descriptor to the TreeIO object.
119 int rootNodeSeqNb
, res
;
123 /* Java I/O mumbo jumbo... */
124 if (!existingStateFile
.exists()) {
125 throw new IOException("Selected state file does not exist"); //$NON-NLS-1$
127 if (existingStateFile
.length() <= 0) {
128 throw new IOException("Empty target file"); //$NON-NLS-1$
131 FileInputStream fis
= new FileInputStream(existingStateFile
);
132 ByteBuffer buffer
= ByteBuffer
.allocate(TREE_HEADER_SIZE
);
133 FileChannel fc
= fis
.getChannel();
134 buffer
.order(ByteOrder
.LITTLE_ENDIAN
);
140 * Check the magic number,to make sure we're opening the right type of
143 res
= buffer
.getInt();
144 if (res
!= HISTORY_FILE_MAGIC_NUMBER
) {
147 throw new IOException("Wrong magic number"); //$NON-NLS-1$
150 res
= buffer
.getInt(); /* File format version number */
151 if (res
!= FILE_VERSION
) {
154 throw new IOException("Mismatching History Tree file format versions"); //$NON-NLS-1$
157 res
= buffer
.getInt(); /* Event handler's version number */
158 if (res
!= expProviderVersion
&&
159 expProviderVersion
!= ITmfStateProvider
.IGNORE_PROVIDER_VERSION
) {
161 * The existing history was built using a event handler that doesn't
162 * match the current one in the framework. Information could be all
163 * wrong, so we'll force a rebuild of the history file instead.
167 throw new IOException("Mismatching event handler versions"); //$NON-NLS-1$
170 bs
= buffer
.getInt(); /* Block Size */
171 maxc
= buffer
.getInt(); /* Max nb of children per node */
173 this.nodeCount
= buffer
.getInt();
174 rootNodeSeqNb
= buffer
.getInt();
175 startTime
= buffer
.getLong();
177 this.config
= new HTConfig(existingStateFile
, bs
, maxc
, expProviderVersion
, startTime
);
181 * FIXME We close fis here and the TreeIO will then reopen the same
182 * file, not extremely elegant. But how to pass the information here to
185 this.treeIO
= new HT_IO(this, false);
187 rebuildLatestBranch(rootNodeSeqNb
);
188 this.treeEnd
= latestBranch
.get(0).getNodeEnd();
191 * Make sure the history start time we read previously is consistent
192 * with was is actually in the root node.
194 if (startTime
!= latestBranch
.get(0).getNodeStart()) {
197 throw new IOException("Inconsistent start times in the" + //$NON-NLS-1$
198 "history file, it might be corrupted."); //$NON-NLS-1$
203 * "Save" the tree to disk. This method will cause the treeIO object to
204 * commit all nodes to disk and then return the RandomAccessFile descriptor
205 * so the Tree object can save its configuration into the header of the
208 * @param requestedEndTime
209 * The greatest timestamp present in the history tree
211 void closeTree(long requestedEndTime
) {
217 * Work-around the "empty branches" that get created when the root node
218 * becomes full. Overwrite the tree's end time with the original wanted
219 * end-time, to ensure no queries are sent into those empty nodes.
221 * This won't be needed once extended nodes are implemented.
223 this.treeEnd
= requestedEndTime
;
225 /* Close off the latest branch of the tree */
226 for (i
= 0; i
< latestBranch
.size(); i
++) {
227 latestBranch
.get(i
).closeThisNode(treeEnd
);
228 treeIO
.writeNode(latestBranch
.get(i
));
231 fc
= treeIO
.getFcOut();
232 buffer
= ByteBuffer
.allocate(TREE_HEADER_SIZE
);
233 buffer
.order(ByteOrder
.LITTLE_ENDIAN
);
236 /* Save the config of the tree to the header of the file */
240 buffer
.putInt(HISTORY_FILE_MAGIC_NUMBER
);
242 buffer
.putInt(FILE_VERSION
);
243 buffer
.putInt(config
.getProviderVersion());
245 buffer
.putInt(config
.getBlockSize());
246 buffer
.putInt(config
.getMaxChildren());
248 buffer
.putInt(nodeCount
);
250 /* root node seq. nb */
251 buffer
.putInt(latestBranch
.get(0).getSequenceNumber());
253 /* start time of this history */
254 buffer
.putLong(latestBranch
.get(0).getNodeStart());
257 res
= fc
.write(buffer
);
258 assert (res
<= TREE_HEADER_SIZE
);
259 /* done writing the file header */
261 } catch (IOException e
) {
262 /* We should not have any problems at this point... */
266 } catch (IOException e
) {
272 // ------------------------------------------------------------------------
274 // ------------------------------------------------------------------------
276 HTConfig
getConfig() {
280 long getTreeStart() {
281 return config
.getTreeStart();
296 List
<CoreNode
> getLatestBranch() {
297 return Collections
.unmodifiableList(latestBranch
);
300 // ------------------------------------------------------------------------
302 // ------------------------------------------------------------------------
305 * Rebuild the latestBranch "cache" object by reading the nodes from disk
306 * (When we are opening an existing file on disk and want to append to it,
309 * @param rootNodeSeqNb
310 * The sequence number of the root node, so we know where to
312 * @throws ClosedChannelException
314 private void rebuildLatestBranch(int rootNodeSeqNb
) throws ClosedChannelException
{
315 HTNode nextChildNode
;
317 this.latestBranch
= new ArrayList
<CoreNode
>();
319 nextChildNode
= treeIO
.readNodeFromDisk(rootNodeSeqNb
);
320 latestBranch
.add((CoreNode
) nextChildNode
);
321 while (latestBranch
.get(latestBranch
.size() - 1).getNbChildren() > 0) {
322 nextChildNode
= treeIO
.readNodeFromDisk(latestBranch
.get(latestBranch
.size() - 1).getLatestChild());
323 latestBranch
.add((CoreNode
) nextChildNode
);
328 * Insert an interval in the tree
331 * The interval to be inserted
333 void insertInterval(HTInterval interval
) throws TimeRangeException
{
334 if (interval
.getStartTime() < config
.getTreeStart()) {
335 throw new TimeRangeException();
337 tryInsertAtNode(interval
, latestBranch
.size() - 1);
341 * Inner method to find in which node we should add the interval.
344 * The interval to add to the tree
346 * The index *in the latestBranch* where we are trying the
349 private void tryInsertAtNode(HTInterval interval
, int indexOfNode
) {
350 HTNode targetNode
= latestBranch
.get(indexOfNode
);
352 /* Verify if there is enough room in this node to store this interval */
353 if (interval
.getIntervalSize() > targetNode
.getNodeFreeSpace()) {
354 /* Nope, not enough room. Insert in a new sibling instead. */
355 addSiblingNode(indexOfNode
);
356 tryInsertAtNode(interval
, latestBranch
.size() - 1);
360 /* Make sure the interval time range fits this node */
361 if (interval
.getStartTime() < targetNode
.getNodeStart()) {
363 * No, this interval starts before the startTime of this node. We
364 * need to check recursively in parents if it can fit.
366 assert (indexOfNode
>= 1);
367 tryInsertAtNode(interval
, indexOfNode
- 1);
372 * Ok, there is room, and the interval fits in this time slot. Let's add
375 targetNode
.addInterval(interval
);
377 /* Update treeEnd if needed */
378 if (interval
.getEndTime() > this.treeEnd
) {
379 this.treeEnd
= interval
.getEndTime();
384 * Method to add a sibling to any node in the latest branch. This will add
385 * children back down to the leaf level, if needed.
388 * The index in latestBranch where we start adding
390 private void addSiblingNode(int indexOfNode
) {
392 CoreNode newNode
, prevNode
;
393 long splitTime
= treeEnd
;
395 assert (indexOfNode
< latestBranch
.size());
397 /* Check if we need to add a new root node */
398 if (indexOfNode
== 0) {
403 /* Check if we can indeed add a child to the target parent */
404 if (latestBranch
.get(indexOfNode
- 1).getNbChildren() == config
.getMaxChildren()) {
405 /* If not, add a branch starting one level higher instead */
406 addSiblingNode(indexOfNode
- 1);
410 /* Split off the new branch from the old one */
411 for (i
= indexOfNode
; i
< latestBranch
.size(); i
++) {
412 latestBranch
.get(i
).closeThisNode(splitTime
);
413 treeIO
.writeNode(latestBranch
.get(i
));
415 prevNode
= latestBranch
.get(i
- 1);
416 newNode
= initNewCoreNode(prevNode
.getSequenceNumber(),
418 prevNode
.linkNewChild(newNode
);
420 latestBranch
.set(i
, newNode
);
425 * Similar to the previous method, except here we rebuild a completely new
428 private void addNewRootNode() {
430 CoreNode oldRootNode
, newRootNode
, newNode
, prevNode
;
431 long splitTime
= this.treeEnd
;
433 oldRootNode
= latestBranch
.get(0);
434 newRootNode
= initNewCoreNode(-1, config
.getTreeStart());
436 /* Tell the old root node that it isn't root anymore */
437 oldRootNode
.setParentSequenceNumber(newRootNode
.getSequenceNumber());
439 /* Close off the whole current latestBranch */
440 for (i
= 0; i
< latestBranch
.size(); i
++) {
441 latestBranch
.get(i
).closeThisNode(splitTime
);
442 treeIO
.writeNode(latestBranch
.get(i
));
445 /* Link the new root to its first child (the previous root node) */
446 newRootNode
.linkNewChild(oldRootNode
);
448 /* Rebuild a new latestBranch */
449 depth
= latestBranch
.size();
450 latestBranch
= new ArrayList
<CoreNode
>();
451 latestBranch
.add(newRootNode
);
452 for (i
= 1; i
< depth
+ 1; i
++) {
453 prevNode
= latestBranch
.get(i
- 1);
454 newNode
= initNewCoreNode(prevNode
.getParentSequenceNumber(),
456 prevNode
.linkNewChild(newNode
);
457 latestBranch
.add(newNode
);
462 * Add a new empty node to the tree.
464 * @param parentSeqNumber
465 * Sequence number of this node's parent
467 * Start time of the new node
468 * @return The newly created node
470 private CoreNode
initNewCoreNode(int parentSeqNumber
, long startTime
) {
471 CoreNode newNode
= new CoreNode(this, this.nodeCount
, parentSeqNumber
,
475 /* Update the treeEnd if needed */
476 if (startTime
>= this.treeEnd
) {
477 this.treeEnd
= startTime
+ 1;
483 * Inner method to select the next child of the current node intersecting
484 * the given timestamp. Useful for moving down the tree following one
488 * The node on which the request is made
490 * The timestamp to choose which child is the next one
491 * @return The child node intersecting t
492 * @throws ClosedChannelException
493 * If the file channel was closed while we were reading the tree
495 HTNode
selectNextChild(CoreNode currentNode
, long t
) throws ClosedChannelException
{
496 assert (currentNode
.getNbChildren() > 0);
497 int potentialNextSeqNb
= currentNode
.getSequenceNumber();
499 for (int i
= 0; i
< currentNode
.getNbChildren(); i
++) {
500 if (t
>= currentNode
.getChildStart(i
)) {
501 potentialNextSeqNb
= currentNode
.getChild(i
);
508 * Once we exit this loop, we should have found a children to follow. If
509 * we didn't, there's a problem.
511 assert (potentialNextSeqNb
!= currentNode
.getSequenceNumber());
514 * Since this code path is quite performance-critical, avoid iterating
515 * through the whole latestBranch array if we know for sure the next
516 * node has to be on disk
518 if (currentNode
.isDone()) {
519 return treeIO
.readNodeFromDisk(potentialNextSeqNb
);
521 return treeIO
.readNode(potentialNextSeqNb
);
525 return config
.getStateFile().length();
528 // ------------------------------------------------------------------------
529 // Test/debugging methods
530 // ------------------------------------------------------------------------
532 /* Only used for debugging, shouldn't be externalized */
533 @SuppressWarnings("nls")
534 boolean checkNodeIntegrity(HTNode zenode
) {
538 StringBuffer buf
= new StringBuffer();
541 // FIXME /* Only testing Core Nodes for now */
542 if (!(zenode
instanceof CoreNode
)) {
546 node
= (CoreNode
) zenode
;
550 * Test that this node's start and end times match the start of the
551 * first child and the end of the last child, respectively
553 if (node
.getNbChildren() > 0) {
554 otherNode
= treeIO
.readNode(node
.getChild(0));
555 if (node
.getNodeStart() != otherNode
.getNodeStart()) {
556 buf
.append("Start time of node (" + node
.getNodeStart() + ") "
557 + "does not match start time of first child " + "("
558 + otherNode
.getNodeStart() + "), " + "node #"
559 + otherNode
.getSequenceNumber() + ")\n");
563 otherNode
= treeIO
.readNode(node
.getLatestChild());
564 if (node
.getNodeEnd() != otherNode
.getNodeEnd()) {
565 buf
.append("End time of node (" + node
.getNodeEnd()
566 + ") does not match end time of last child ("
567 + otherNode
.getNodeEnd() + ", node #"
568 + otherNode
.getSequenceNumber() + ")\n");
575 * Test that the childStartTimes[] array matches the real nodes' start
578 for (int i
= 0; i
< node
.getNbChildren(); i
++) {
579 otherNode
= treeIO
.readNode(node
.getChild(i
));
580 if (otherNode
.getNodeStart() != node
.getChildStart(i
)) {
581 buf
.append(" Expected start time of child node #"
582 + node
.getChild(i
) + ": " + node
.getChildStart(i
)
583 + "\n" + " Actual start time of node #"
584 + otherNode
.getSequenceNumber() + ": "
585 + otherNode
.getNodeStart() + "\n");
590 } catch (ClosedChannelException e
) {
595 System
.out
.println("");
596 System
.out
.println("SHT: Integrity check failed for node #"
597 + node
.getSequenceNumber() + ":");
598 System
.out
.println(buf
.toString());
603 void checkIntegrity() {
605 for (int i
= 0; i
< nodeCount
; i
++) {
606 checkNodeIntegrity(treeIO
.readNode(i
));
608 } catch (ClosedChannelException e
) {
612 /* Only used for debugging, shouldn't be externalized */
613 @SuppressWarnings("nls")
615 public String
toString() {
616 return "Information on the current tree:\n\n" + "Blocksize: "
617 + config
.getBlockSize() + "\n" + "Max nb. of children per node: "
618 + config
.getMaxChildren() + "\n" + "Number of nodes: " + nodeCount
619 + "\n" + "Depth of the tree: " + latestBranch
.size() + "\n"
620 + "Size of the treefile: " + this.getFileSize() + "\n"
621 + "Root node has sequence number: "
622 + latestBranch
.get(0).getSequenceNumber() + "\n"
623 + "'Latest leaf' has sequence number: "
624 + latestBranch
.get(latestBranch
.size() - 1).getSequenceNumber();
628 * Start at currentNode and print the contents of all its children, in
629 * pre-order. Give the root node in parameter to visit the whole tree, and
630 * have a nice overview.
632 /* Only used for debugging, shouldn't be externalized */
633 @SuppressWarnings("nls")
634 private void preOrderPrint(PrintWriter writer
, boolean printIntervals
,
635 CoreNode currentNode
, int curDepth
) {
637 writer
.println(currentNode
.toString());
638 if (printIntervals
) {
639 currentNode
.debugPrintIntervals(writer
);
643 for (int i
= 0; i
< currentNode
.getNbChildren(); i
++) {
644 HTNode nextNode
= treeIO
.readNode(currentNode
.getChild(i
));
645 assert (nextNode
instanceof CoreNode
); // TODO temporary
646 for (int j
= 0; j
< curDepth
; j
++) {
650 preOrderPrint(writer
, printIntervals
, (CoreNode
) nextNode
,
653 } catch (ClosedChannelException e
) {
659 * Print out the full tree for debugging purposes
662 * PrintWriter in which to write the output
663 * @param printIntervals
664 * Flag to enable full output of the interval information
666 void debugPrintFullTree(PrintWriter writer
, boolean printIntervals
) {
667 /* Only used for debugging, shouldn't be externalized */
669 this.preOrderPrint(writer
, false, latestBranch
.get(0), 0);
671 if (printIntervals
) {
672 writer
.println("\nDetails of intervals:"); //$NON-NLS-1$
673 this.preOrderPrint(writer
, true, latestBranch
.get(0), 0);
675 writer
.println('\n');