1 /*******************************************************************************
2 * Copyright (c) 2010, 2016 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 * Patrick Tasse - Keep interval list sorted on insert
13 *******************************************************************************/
15 package org
.eclipse
.tracecompass
.internal
.statesystem
.core
.backend
.historytree
;
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
.FileChannel
;
22 import java
.util
.ArrayList
;
23 import java
.util
.Collections
;
24 import java
.util
.List
;
25 import java
.util
.concurrent
.locks
.ReentrantReadWriteLock
;
27 import org
.eclipse
.jdt
.annotation
.NonNull
;
28 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.TimeRangeException
;
29 import org
.eclipse
.tracecompass
.statesystem
.core
.interval
.ITmfStateInterval
;
30 import org
.eclipse
.tracecompass
.statesystem
.core
.statevalue
.TmfStateValue
;
32 import com
.google
.common
.collect
.Iterables
;
35 * The base class for all the types of nodes that go in the History Tree.
37 * @author Alexandre Montplaisir
39 public abstract class HTNode
{
41 // ------------------------------------------------------------------------
43 // ------------------------------------------------------------------------
48 public static enum NodeType
{
50 * Core node, which is a "front" node, at any level of the tree except
51 * the bottom-most one. It has children, and may have extensions.
55 * Leaf node, which is a node at the last bottom level of the tree. It
56 * cannot have any children or extensions.
61 * Determine a node type by reading a serialized byte.
64 * The byte representation of the node type
65 * @return The corresponding NodeType
67 * If the NodeType is unrecognized
69 public static NodeType
fromByte(byte rep
) throws IOException
{
76 throw new IOException();
81 * Get the byte representation of this node type. It can then be read
82 * with {@link #fromByte}.
84 * @return The byte matching this node type
86 public byte toByte() {
93 throw new IllegalStateException();
101 * 16 - 2x long (start time, end time)
102 * 16 - 4x int (seq number, parent seq number, intervalcount,
103 * strings section pos.)
104 * 1 - byte (done or not)
107 private static final int COMMON_HEADER_SIZE
= Byte
.BYTES
112 // ------------------------------------------------------------------------
114 // ------------------------------------------------------------------------
116 /* Configuration of the History Tree to which belongs this node */
117 private final HTConfig fConfig
;
119 /* Time range of this node */
120 private final long fNodeStart
;
121 private long fNodeEnd
;
123 /* Sequence number = position in the node section of the file */
124 private final int fSequenceNumber
;
125 private int fParentSequenceNumber
; /* = -1 if this node is the root node */
127 /* Sum of bytes of all intervals in the node */
128 private int fSizeOfIntervalSection
;
130 /* True if this node was read from disk (meaning its end time is now fixed) */
131 private volatile boolean fIsOnDisk
;
133 /* Vector containing all the intervals contained in this node */
134 private final List
<HTInterval
> fIntervals
;
136 /* Lock used to protect the accesses to intervals, nodeEnd and such */
137 private final ReentrantReadWriteLock fRwl
= new ReentrantReadWriteLock(false);
143 * Configuration of the History Tree
145 * The (unique) sequence number assigned to this particular node
146 * @param parentSeqNumber
147 * The sequence number of this node's parent node
149 * The earliest timestamp stored in this node
151 protected HTNode(HTConfig config
, int seqNumber
, int parentSeqNumber
, long start
) {
154 fSequenceNumber
= seqNumber
;
155 fParentSequenceNumber
= parentSeqNumber
;
157 fSizeOfIntervalSection
= 0;
159 fIntervals
= new ArrayList
<>();
163 * Reader factory method. Build a Node object (of the right type) by reading
164 * a block in the file.
167 * Configuration of the History Tree
169 * FileChannel to the history file, ALREADY SEEKED at the start
172 * The factory to create the nodes for this tree
173 * @return The node object
174 * @throws IOException
175 * If there was an error reading from the file channel
177 public static final @NonNull HTNode
readNode(HTConfig config
, FileChannel fc
, IHistoryTree
.IHTNodeFactory nodeFactory
)
179 HTNode newNode
= null;
182 ByteBuffer buffer
= ByteBuffer
.allocate(config
.getBlockSize());
183 buffer
.order(ByteOrder
.LITTLE_ENDIAN
);
185 res
= fc
.read(buffer
);
186 assert (res
== config
.getBlockSize());
189 /* Read the common header part */
190 byte typeByte
= buffer
.get();
191 NodeType type
= NodeType
.fromByte(typeByte
);
192 long start
= buffer
.getLong();
193 long end
= buffer
.getLong();
194 int seqNb
= buffer
.getInt();
195 int parentSeqNb
= buffer
.getInt();
196 int intervalCount
= buffer
.getInt();
197 buffer
.get(); // TODO Used to be "isDone", to be removed from the header
199 /* Now the rest of the header depends on the node type */
203 newNode
= nodeFactory
.createCoreNode(config
, seqNb
, parentSeqNb
, start
);
204 newNode
.readSpecificHeader(buffer
);
209 newNode
= nodeFactory
.createLeafNode(config
, seqNb
, parentSeqNb
, start
);
210 newNode
.readSpecificHeader(buffer
);
214 /* Unrecognized node type */
215 throw new IOException();
219 * At this point, we should be done reading the header and 'buffer'
220 * should only have the intervals left
222 for (i
= 0; i
< intervalCount
; i
++) {
223 HTInterval interval
= HTInterval
.readFrom(buffer
);
224 newNode
.fIntervals
.add(interval
);
225 newNode
.fSizeOfIntervalSection
+= interval
.getSizeOnDisk();
228 /* Assign the node's other information we have read previously */
229 newNode
.fNodeEnd
= end
;
230 newNode
.fIsOnDisk
= true;
236 * Write this node to the given file channel.
239 * The file channel to write to (should be sought to be correct
241 * @throws IOException
242 * If there was an error writing
244 public final void writeSelf(FileChannel fc
) throws IOException
{
246 * Yes, we are taking the *read* lock here, because we are reading the
247 * information in the node to write it to disk.
249 fRwl
.readLock().lock();
251 final int blockSize
= fConfig
.getBlockSize();
253 ByteBuffer buffer
= ByteBuffer
.allocate(blockSize
);
254 buffer
.order(ByteOrder
.LITTLE_ENDIAN
);
257 /* Write the common header part */
258 buffer
.put(getNodeType().toByte());
259 buffer
.putLong(fNodeStart
);
260 buffer
.putLong(fNodeEnd
);
261 buffer
.putInt(fSequenceNumber
);
262 buffer
.putInt(fParentSequenceNumber
);
263 buffer
.putInt(fIntervals
.size());
264 buffer
.put((byte) 1); // TODO Used to be "isDone", to be removed from header
266 /* Now call the inner method to write the specific header part */
267 writeSpecificHeader(buffer
);
269 /* Back to us, we write the intervals */
270 fIntervals
.forEach(i
-> i
.writeInterval(buffer
));
273 * Fill the rest with zeros
275 while (buffer
.position() < blockSize
) {
276 buffer
.put((byte) 0);
279 /* Finally, write everything in the Buffer to disk */
281 int res
= fc
.write(buffer
);
282 if (res
!= blockSize
) {
283 throw new IllegalStateException("Wrong size of block written: Actual: " + res
+ ", Expected: " + blockSize
); //$NON-NLS-1$ //$NON-NLS-2$
287 fRwl
.readLock().unlock();
292 // ------------------------------------------------------------------------
294 // ------------------------------------------------------------------------
297 * Retrieve the history tree configuration used for this node.
299 * @return The history tree config
301 protected HTConfig
getConfig() {
306 * Get the start time of this node.
308 * @return The start time of this node
310 public long getNodeStart() {
315 * Get the end time of this node.
317 * @return The end time of this node
319 public long getNodeEnd() {
327 * Get the sequence number of this node.
329 * @return The sequence number of this node
331 public int getSequenceNumber() {
332 return fSequenceNumber
;
336 * Get the sequence number of this node's parent.
338 * @return The parent sequence number
340 public int getParentSequenceNumber() {
341 return fParentSequenceNumber
;
345 * Change this node's parent. Used when we create a new root node for
349 * The sequence number of the node that is the new parent
351 public void setParentSequenceNumber(int newParent
) {
352 fParentSequenceNumber
= newParent
;
356 * Return if this node is "done" (full and written to disk).
358 * @return If this node is done or not
360 public boolean isOnDisk() {
365 * Add an interval to this node
368 * Interval to add to this node
370 public void addInterval(HTInterval newInterval
) {
371 fRwl
.writeLock().lock();
373 /* Just in case, should be checked before even calling this function */
374 assert (newInterval
.getSizeOnDisk() <= getNodeFreeSpace());
376 /* Find the insert position to keep the list sorted */
377 int index
= fIntervals
.size();
378 while (index
> 0 && newInterval
.compareTo(fIntervals
.get(index
- 1)) < 0) {
382 fIntervals
.add(index
, newInterval
);
383 fSizeOfIntervalSection
+= newInterval
.getSizeOnDisk();
386 fRwl
.writeLock().unlock();
391 * We've received word from the containerTree that newest nodes now exist to
392 * our right. (Puts isDone = true and sets the endtime)
395 * The nodeEnd time that the node will have
397 public void closeThisNode(long endtime
) {
398 fRwl
.writeLock().lock();
401 * FIXME: was assert (endtime >= fNodeStart); but that exception
402 * is reached with an empty node that has start time endtime + 1
404 // if (endtime < fNodeStart) {
405 // throw new IllegalArgumentException("Endtime " + endtime + " cannot be lower than start time " + fNodeStart);
408 if (!fIntervals
.isEmpty()) {
410 * Make sure there are no intervals in this node with their
411 * EndTime > the one requested. Only need to check the last one
412 * since they are sorted
414 if (endtime
< Iterables
.getLast(fIntervals
).getEndTime()) {
415 throw new IllegalArgumentException("Closing end time should be greater than or equal to the end time of the intervals of this node"); //$NON-NLS-1$
421 fRwl
.writeLock().unlock();
426 * The method to fill up the stateInfo (passed on from the Current State
427 * Tree when it does a query on the SHT). We'll replace the data in that
428 * vector with whatever relevant we can find from this node
431 * The same stateInfo that comes from SHT's doQuery()
433 * The timestamp for which the query is for. Only return
434 * intervals that intersect t.
435 * @throws TimeRangeException
438 public void writeInfoFromNode(List
<ITmfStateInterval
> stateInfo
, long t
)
439 throws TimeRangeException
{
440 /* This is from a state system query, we are "reading" this node */
441 fRwl
.readLock().lock();
443 for (int i
= getStartIndexFor(t
); i
< fIntervals
.size(); i
++) {
445 * Now we only have to compare the Start times, since we now the
446 * End times necessarily fit.
448 * Second condition is to ignore new attributes that might have
449 * been created after stateInfo was instantiated (they would be
452 ITmfStateInterval interval
= fIntervals
.get(i
);
453 if (t
>= interval
.getStartTime() &&
454 interval
.getAttribute() < stateInfo
.size()) {
455 stateInfo
.set(interval
.getAttribute(), interval
);
459 fRwl
.readLock().unlock();
464 * Get a single Interval from the information in this node If the
465 * key/timestamp pair cannot be found, we return null.
468 * The attribute quark to look for
471 * @return The Interval containing the information we want, or null if it
473 * @throws TimeRangeException
476 public HTInterval
getRelevantInterval(int key
, long t
) throws TimeRangeException
{
477 fRwl
.readLock().lock();
479 for (int i
= getStartIndexFor(t
); i
< fIntervals
.size(); i
++) {
480 HTInterval curInterval
= fIntervals
.get(i
);
481 if (curInterval
.getAttribute() == key
482 && curInterval
.getStartTime() <= t
483 && curInterval
.getEndTime() >= t
) {
488 /* We didn't find the relevant information in this node */
492 fRwl
.readLock().unlock();
496 private int getStartIndexFor(long t
) throws TimeRangeException
{
497 /* Should only be called by methods with the readLock taken */
499 if (fIntervals
.isEmpty()) {
503 * Since the intervals are sorted by end time, we can skip all the ones
504 * at the beginning whose end times are smaller than 't'. Java does
505 * provides a .binarySearch method, but its API is quite weird...
507 HTInterval dummy
= new HTInterval(0, t
, 0, TmfStateValue
.nullValue());
508 int index
= Collections
.binarySearch(fIntervals
, dummy
);
512 * .binarySearch returns a negative number if the exact value was
513 * not found. Here we just want to know where to start searching, we
514 * don't care if the value is exact or not.
520 * Another API quirkiness, the returned index is the one of the *last*
521 * element of a series of equal endtimes, which happens sometimes. We
522 * want the *first* element of such a series, to read through them
526 && fIntervals
.get(index
- 1).compareTo(fIntervals
.get(index
)) == 0) {
535 * Return the total header size of this node (will depend on the node type).
537 * @return The total header size
539 public final int getTotalHeaderSize() {
540 return COMMON_HEADER_SIZE
+ getSpecificHeaderSize();
544 * @return The offset, within the node, where the Data section ends
546 private int getDataSectionEndOffset() {
547 return getTotalHeaderSize() + fSizeOfIntervalSection
;
551 * Returns the free space in the node, which is simply put, the
552 * stringSectionOffset - dataSectionOffset
554 * @return The amount of free space in the node (in bytes)
556 public int getNodeFreeSpace() {
557 fRwl
.readLock().lock();
558 int ret
= fConfig
.getBlockSize() - getDataSectionEndOffset();
559 fRwl
.readLock().unlock();
565 * Returns the current space utilization of this node, as a percentage.
566 * (used space / total usable space, which excludes the header)
568 * @return The percentage (value between 0 and 100) of space utilization in
571 public long getNodeUsagePercent() {
572 fRwl
.readLock().lock();
574 final int blockSize
= fConfig
.getBlockSize();
575 float freePercent
= (float) getNodeFreeSpace()
576 / (float) (blockSize
- getTotalHeaderSize())
578 return (long) (100L - freePercent
);
581 fRwl
.readLock().unlock();
586 * @name Debugging functions
589 @SuppressWarnings("nls")
591 public String
toString() {
592 /* Only used for debugging, shouldn't be externalized */
593 return String
.format("Node #%d, %s, %s, %d intervals (%d%% used), [%d - %s]",
595 (fParentSequenceNumber
== -1) ?
"Root" : "Parent #" + fParentSequenceNumber
,
598 getNodeUsagePercent(),
600 (fIsOnDisk
|| fNodeEnd
!= 0) ? fNodeEnd
: "...");
604 * Debugging function that prints out the contents of this node
607 * PrintWriter in which we will print the debug output
609 @SuppressWarnings("nls")
610 public void debugPrintIntervals(PrintWriter writer
) {
611 /* Only used for debugging, shouldn't be externalized */
612 writer
.println("Intervals for node #" + fSequenceNumber
+ ":");
614 /* Array of children */
615 if (getNodeType() != NodeType
.LEAF
) { /* Only Core Nodes can have children */
616 ParentNode thisNode
= (ParentNode
) this;
617 writer
.print(" " + thisNode
.getNbChildren() + " children");
618 if (thisNode
.getNbChildren() >= 1) {
619 writer
.print(": [ " + thisNode
.getChild(0));
620 for (int i
= 1; i
< thisNode
.getNbChildren(); i
++) {
621 writer
.print(", " + thisNode
.getChild(i
));
628 /* List of intervals in the node */
629 writer
.println(" Intervals contained:");
630 for (int i
= 0; i
< fIntervals
.size(); i
++) {
631 writer
.println(fIntervals
.get(i
).toString());
633 writer
.println('\n');
636 // ------------------------------------------------------------------------
638 // ------------------------------------------------------------------------
641 * Get the byte value representing the node type.
643 * @return The node type
645 public abstract NodeType
getNodeType();
648 * Return the specific header size of this node. This means the size
649 * occupied by the type-specific section of the header (not counting the
652 * @return The specific header size
654 protected abstract int getSpecificHeaderSize();
657 * Read the type-specific part of the node header from a byte buffer.
660 * The byte buffer to read from. It should be already positioned
663 protected abstract void readSpecificHeader(ByteBuffer buffer
);
666 * Write the type-specific part of the header in a byte buffer.
669 * The buffer to write to. It should already be at the correct
672 protected abstract void writeSpecificHeader(ByteBuffer buffer
);
675 * Node-type-specific toString method. Used for debugging.
677 * @return A string representing the node
679 protected abstract String
toStringSpecific();