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
.linuxtools
.internal
.statesystem
.core
.backend
.historytree
;
16 import java
.io
.IOException
;
17 import java
.io
.PrintWriter
;
18 import java
.nio
.ByteBuffer
;
19 import java
.nio
.ByteOrder
;
20 import java
.nio
.channels
.FileChannel
;
21 import java
.util
.ArrayList
;
22 import java
.util
.Collections
;
23 import java
.util
.List
;
24 import java
.util
.concurrent
.locks
.ReentrantReadWriteLock
;
26 import org
.eclipse
.linuxtools
.statesystem
.core
.exceptions
.TimeRangeException
;
27 import org
.eclipse
.linuxtools
.statesystem
.core
.interval
.ITmfStateInterval
;
28 import org
.eclipse
.linuxtools
.statesystem
.core
.statevalue
.TmfStateValue
;
31 * The base class for all the types of nodes that go in the History Tree.
33 * @author Alexandre Montplaisir
35 public abstract class HTNode
{
37 // ------------------------------------------------------------------------
39 // ------------------------------------------------------------------------
44 public static enum NodeType
{
46 * Core node, which is a "front" node, at any level of the tree except
47 * the bottom-most one. It has children, and may have extensions.
51 * Leaf node, which is a node at the last bottom level of the tree. It
52 * cannot have any children or extensions.
57 * Determine a node type by reading a serialized byte.
60 * The byte representation of the node type
61 * @return The corresponding NodeType
63 * If the NodeType is unrecognized
65 public static NodeType
fromByte(byte rep
) throws IOException
{
72 throw new IOException();
77 * Get the byte representation of this node type. It can then be read
78 * with {@link #fromByte}.
80 * @return The byte matching this node type
82 public byte toByte() {
89 throw new IllegalStateException();
94 // ------------------------------------------------------------------------
96 // ------------------------------------------------------------------------
98 /* Configuration of the History Tree to which belongs this node */
99 private final HTConfig config
;
101 /* Time range of this node */
102 private final long nodeStart
;
103 private long nodeEnd
;
105 /* Sequence number = position in the node section of the file */
106 private final int sequenceNumber
;
107 private int parentSequenceNumber
; /* = -1 if this node is the root node */
109 /* Where the Strings section begins (from the start of the node */
110 private int stringSectionOffset
;
112 /* Sum of bytes of all intervals in the node */
113 private int sizeOfIntervalSection
;
115 /* True if this node was read from disk (meaning its end time is now fixed) */
116 private volatile boolean isOnDisk
;
118 /* Vector containing all the intervals contained in this node */
119 private final List
<HTInterval
> intervals
;
121 /* Lock used to protect the accesses to intervals, nodeEnd and such */
122 private final ReentrantReadWriteLock rwl
= new ReentrantReadWriteLock(false);
128 * Configuration of the History Tree
130 * The (unique) sequence number assigned to this particular node
131 * @param parentSeqNumber
132 * The sequence number of this node's parent node
134 * The earliest timestamp stored in this node
136 protected HTNode(HTConfig config
, int seqNumber
, int parentSeqNumber
, long start
) {
137 this.config
= config
;
138 this.nodeStart
= start
;
139 this.sequenceNumber
= seqNumber
;
140 this.parentSequenceNumber
= parentSeqNumber
;
142 this.stringSectionOffset
= config
.getBlockSize();
143 this.sizeOfIntervalSection
= 0;
144 this.isOnDisk
= false;
145 this.intervals
= new ArrayList
<>();
149 * Reader factory method. Build a Node object (of the right type) by reading
150 * a block in the file.
153 * Configuration of the History Tree
155 * FileChannel to the history file, ALREADY SEEKED at the start
157 * @return The node object
158 * @throws IOException
159 * If there was an error reading from the file channel
161 public static final HTNode
readNode(HTConfig config
, FileChannel fc
)
163 HTNode newNode
= null;
166 ByteBuffer buffer
= ByteBuffer
.allocate(config
.getBlockSize());
167 buffer
.order(ByteOrder
.LITTLE_ENDIAN
);
169 res
= fc
.read(buffer
);
170 assert (res
== config
.getBlockSize());
173 /* Read the common header part */
174 byte typeByte
= buffer
.get();
175 NodeType type
= NodeType
.fromByte(typeByte
);
176 long start
= buffer
.getLong();
177 long end
= buffer
.getLong();
178 int seqNb
= buffer
.getInt();
179 int parentSeqNb
= buffer
.getInt();
180 int intervalCount
= buffer
.getInt();
181 int stringSectionOffset
= buffer
.getInt();
182 buffer
.get(); // TODO Used to be "isDone", to be removed from the header
184 /* Now the rest of the header depends on the node type */
188 newNode
= new CoreNode(config
, seqNb
, parentSeqNb
, start
);
189 newNode
.readSpecificHeader(buffer
);
194 newNode
= new LeafNode(config
, seqNb
, parentSeqNb
, start
);
195 newNode
.readSpecificHeader(buffer
);
199 /* Unrecognized node type */
200 throw new IOException();
204 * At this point, we should be done reading the header and 'buffer'
205 * should only have the intervals left
207 for (i
= 0; i
< intervalCount
; i
++) {
208 newNode
.intervals
.add(HTInterval
.readFrom(buffer
));
211 /* Assign the node's other information we have read previously */
212 newNode
.nodeEnd
= end
;
213 newNode
.stringSectionOffset
= stringSectionOffset
;
214 newNode
.isOnDisk
= true;
220 * Write this node to the given file channel.
223 * The file channel to write to (should be sought to be correct
225 * @throws IOException
226 * If there was an error writing
228 public final void writeSelf(FileChannel fc
) throws IOException
{
230 * Yes, we are taking the *read* lock here, because we are reading the
231 * information in the node to write it to disk.
233 rwl
.readLock().lock();
235 final int blockSize
= config
.getBlockSize();
236 int curStringsEntryEndPos
= blockSize
;
238 ByteBuffer buffer
= ByteBuffer
.allocate(blockSize
);
239 buffer
.order(ByteOrder
.LITTLE_ENDIAN
);
242 /* Write the common header part */
243 buffer
.put(this.getNodeType().toByte());
244 buffer
.putLong(nodeStart
);
245 buffer
.putLong(nodeEnd
);
246 buffer
.putInt(sequenceNumber
);
247 buffer
.putInt(parentSequenceNumber
);
248 buffer
.putInt(intervals
.size());
249 buffer
.putInt(stringSectionOffset
);
250 buffer
.put((byte) 1); // TODO Used to be "isDone", to be removed from header
252 /* Now call the inner method to write the specific header part */
253 this.writeSpecificHeader(buffer
);
255 /* Back to us, we write the intervals */
256 for (HTInterval interval
: intervals
) {
257 int size
= interval
.writeInterval(buffer
, curStringsEntryEndPos
);
258 curStringsEntryEndPos
-= size
;
262 * Write padding between the end of the Data section and the start
263 * of the Strings section (needed to fill the node in case there is
264 * no Strings section)
266 while (buffer
.position() < stringSectionOffset
) {
267 buffer
.put((byte) 0);
271 * If the offsets were right, the size of the Strings section should
272 * be == to the expected size
274 assert (curStringsEntryEndPos
== stringSectionOffset
);
276 /* Finally, write everything in the Buffer to disk */
278 // if we don't do this, flip() will lose what's after.
279 buffer
.position(blockSize
);
282 int res
= fc
.write(buffer
);
283 assert (res
== blockSize
);
286 rwl
.readLock().unlock();
291 // ------------------------------------------------------------------------
293 // ------------------------------------------------------------------------
296 * Retrieve the history tree configuration used for this node.
298 * @return The history tree config
300 protected HTConfig
getConfig() {
305 * Get the start time of this node.
307 * @return The start time of this node
309 public long getNodeStart() {
314 * Get the end time of this node.
316 * @return The end time of this node
318 public long getNodeEnd() {
326 * Get the sequence number of this node.
328 * @return The sequence number of this node
330 public int getSequenceNumber() {
331 return sequenceNumber
;
335 * Get the sequence number of this node's parent.
337 * @return The parent sequence number
339 public int getParentSequenceNumber() {
340 return parentSequenceNumber
;
344 * Change this node's parent. Used when we create a new root node for
348 * The sequence number of the node that is the new parent
350 public void setParentSequenceNumber(int newParent
) {
351 parentSequenceNumber
= newParent
;
355 * Return if this node is "done" (full and written to disk).
357 * @return If this node is done or not
359 public boolean isOnDisk() {
364 * Add an interval to this node
367 * Interval to add to this node
369 public void addInterval(HTInterval newInterval
) {
370 rwl
.writeLock().lock();
372 /* Just in case, should be checked before even calling this function */
373 assert (newInterval
.getIntervalSize() <= this.getNodeFreeSpace());
375 intervals
.add(newInterval
);
376 sizeOfIntervalSection
+= newInterval
.getIntervalSize();
378 /* Update the in-node offset "pointer" */
379 stringSectionOffset
-= (newInterval
.getStringsEntrySize());
381 rwl
.writeLock().unlock();
386 * We've received word from the containerTree that newest nodes now exist to
387 * our right. (Puts isDone = true and sets the endtime)
390 * The nodeEnd time that the node will have
392 public void closeThisNode(long endtime
) {
393 rwl
.writeLock().lock();
395 assert (endtime
>= this.nodeStart
);
397 if (!intervals
.isEmpty()) {
399 * Sort the intervals by ascending order of their end time. This
400 * speeds up lookups a bit
402 Collections
.sort(intervals
);
405 * Make sure there are no intervals in this node with their
406 * EndTime > the one requested. Only need to check the last one
407 * since they are now sorted
409 assert (endtime
>= intervals
.get(intervals
.size() - 1).getEndTime());
412 this.nodeEnd
= endtime
;
414 rwl
.writeLock().unlock();
419 * The method to fill up the stateInfo (passed on from the Current State
420 * Tree when it does a query on the SHT). We'll replace the data in that
421 * vector with whatever relevant we can find from this node
424 * The same stateInfo that comes from SHT's doQuery()
426 * The timestamp for which the query is for. Only return
427 * intervals that intersect t.
428 * @throws TimeRangeException
431 public void writeInfoFromNode(List
<ITmfStateInterval
> stateInfo
, long t
)
432 throws TimeRangeException
{
433 /* This is from a state system query, we are "reading" this node */
434 rwl
.readLock().lock();
436 for (int i
= getStartIndexFor(t
); i
< intervals
.size(); i
++) {
438 * Now we only have to compare the Start times, since we now the
439 * End times necessarily fit.
441 * Second condition is to ignore new attributes that might have
442 * been created after stateInfo was instantiated (they would be
445 ITmfStateInterval interval
= intervals
.get(i
);
446 if (interval
.getStartTime() <= t
&&
447 interval
.getAttribute() < stateInfo
.size()) {
448 stateInfo
.set(interval
.getAttribute(), interval
);
452 rwl
.readLock().unlock();
457 * Get a single Interval from the information in this node If the
458 * key/timestamp pair cannot be found, we return null.
461 * The attribute quark to look for
464 * @return The Interval containing the information we want, or null if it
466 * @throws TimeRangeException
469 public HTInterval
getRelevantInterval(int key
, long t
) throws TimeRangeException
{
470 rwl
.readLock().lock();
472 for (int i
= getStartIndexFor(t
); i
< intervals
.size(); i
++) {
473 HTInterval curInterval
= intervals
.get(i
);
474 if (curInterval
.getAttribute() == key
475 && curInterval
.getStartTime() <= t
476 && curInterval
.getEndTime() >= t
) {
481 /* We didn't find the relevant information in this node */
485 rwl
.readLock().unlock();
489 private int getStartIndexFor(long t
) throws TimeRangeException
{
490 /* Should only be called by methods with the readLock taken */
492 if (intervals
.isEmpty()) {
496 * Since the intervals are sorted by end time, we can skip all the ones
497 * at the beginning whose end times are smaller than 't'. Java does
498 * provides a .binarySearch method, but its API is quite weird...
500 HTInterval dummy
= new HTInterval(0, t
, 0, TmfStateValue
.nullValue());
501 int index
= Collections
.binarySearch(intervals
, dummy
);
505 * .binarySearch returns a negative number if the exact value was
506 * not found. Here we just want to know where to start searching, we
507 * don't care if the value is exact or not.
513 /* Sometimes binarySearch yields weird stuff... */
517 if (index
>= intervals
.size()) {
518 index
= intervals
.size() - 1;
522 * Another API quirkiness, the returned index is the one of the *last*
523 * element of a series of equal endtimes, which happens sometimes. We
524 * want the *first* element of such a series, to read through them
528 && intervals
.get(index
- 1).compareTo(intervals
.get(index
)) == 0) {
538 * 16 - 2x long (start time, end time)
539 * 16 - 4x int (seq number, parent seq number, intervalcount,
540 * strings section pos.)
541 * 1 - byte (done or not)
544 private static final int COMMON_HEADER_SIZE
= 34;
547 * Return the total header size of this node (will depend on the node type).
549 * @return The total header size
551 public final int getTotalHeaderSize() {
552 return COMMON_HEADER_SIZE
+ getSpecificHeaderSize();
556 * @return The offset, within the node, where the Data section ends
558 private int getDataSectionEndOffset() {
559 return this.getTotalHeaderSize() + sizeOfIntervalSection
;
563 * Returns the free space in the node, which is simply put, the
564 * stringSectionOffset - dataSectionOffset
566 * @return The amount of free space in the node (in bytes)
568 public int getNodeFreeSpace() {
569 rwl
.readLock().lock();
570 int ret
= stringSectionOffset
- this.getDataSectionEndOffset();
571 rwl
.readLock().unlock();
577 * Returns the current space utilization of this node, as a percentage.
578 * (used space / total usable space, which excludes the header)
580 * @return The percentage (value between 0 and 100) of space utilization in
583 public long getNodeUsagePercent() {
584 rwl
.readLock().lock();
586 final int blockSize
= config
.getBlockSize();
587 float freePercent
= (float) this.getNodeFreeSpace()
588 / (float) (blockSize
- this.getTotalHeaderSize())
590 return (long) (100L - freePercent
);
593 rwl
.readLock().unlock();
598 * @name Debugging functions
601 @SuppressWarnings("nls")
603 public String
toString() {
604 /* Only used for debugging, shouldn't be externalized */
605 StringBuffer buf
= new StringBuffer("Node #" + sequenceNumber
+ ", ");
606 buf
.append(this.toStringSpecific());
607 buf
.append(intervals
.size() + " intervals (" + this.getNodeUsagePercent()
610 buf
.append("[" + this.nodeStart
+ " - ");
612 buf
= buf
.append("" + this.nodeEnd
+ "]");
614 buf
= buf
.append("...]");
616 return buf
.toString();
620 * Debugging function that prints out the contents of this node
623 * PrintWriter in which we will print the debug output
625 @SuppressWarnings("nls")
626 public void debugPrintIntervals(PrintWriter writer
) {
627 /* Only used for debugging, shouldn't be externalized */
628 writer
.println("Node #" + sequenceNumber
+ ":");
630 /* Array of children */
631 if (this.getNodeType() == NodeType
.CORE
) { /* Only Core Nodes can have children */
632 CoreNode thisNode
= (CoreNode
) this;
633 writer
.print(" " + thisNode
.getNbChildren() + " children");
634 if (thisNode
.getNbChildren() >= 1) {
635 writer
.print(": [ " + thisNode
.getChild(0));
636 for (int i
= 1; i
< thisNode
.getNbChildren(); i
++) {
637 writer
.print(", " + thisNode
.getChild(i
));
644 /* List of intervals in the node */
645 writer
.println(" Intervals contained:");
646 for (int i
= 0; i
< intervals
.size(); i
++) {
647 writer
.println(intervals
.get(i
).toString());
649 writer
.println('\n');
652 // ------------------------------------------------------------------------
654 // ------------------------------------------------------------------------
657 * Get the byte value representing the node type.
659 * @return The node type
661 public abstract NodeType
getNodeType();
664 * Return the specific header size of this node. This means the size
665 * occupied by the type-specific section of the header (not counting the
668 * @return The specific header size
670 protected abstract int getSpecificHeaderSize();
673 * Read the type-specific part of the node header from a byte buffer.
676 * The byte buffer to read from. It should be already positioned
679 protected abstract void readSpecificHeader(ByteBuffer buffer
);
682 * Write the type-specific part of the header in a byte buffer.
685 * The buffer to write to. It should already be at the correct
688 protected abstract void writeSpecificHeader(ByteBuffer buffer
);
691 * Node-type-specific toString method. Used for debugging.
693 * @return A string representing the node
695 protected abstract String
toStringSpecific();