TMF: Fix behavior of XML time graph views with experiments
[deliverable/tracecompass.git] / statesystem / org.eclipse.tracecompass.statesystem.core / src / org / eclipse / tracecompass / internal / statesystem / core / backend / historytree / HistoryTree.java
CommitLineData
a52fde77 1/*******************************************************************************
e13bd4cd 2 * Copyright (c) 2010, 2015 Ericsson, École Polytechnique de Montréal, and others
3b7f5abe 3 *
a52fde77
AM
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
3b7f5abe 8 *
bb7f92ce
FW
9 * Contributors:
10 * Alexandre Montplaisir - Initial API and implementation
11 * Florian Wininger - Add Extension and Leaf Node
e13bd4cd 12 * Patrick Tasse - Add message to exceptions
a52fde77
AM
13 *******************************************************************************/
14
e894a508 15package org.eclipse.tracecompass.internal.statesystem.core.backend.historytree;
a52fde77
AM
16
17import java.io.File;
18import java.io.FileInputStream;
19import java.io.IOException;
20import java.io.PrintWriter;
21import java.nio.ByteBuffer;
22import java.nio.ByteOrder;
3b7f5abe 23import java.nio.channels.ClosedChannelException;
a52fde77 24import java.nio.channels.FileChannel;
cb42195c
AM
25import java.util.ArrayList;
26import java.util.Collections;
27import java.util.List;
a52fde77 28
e894a508
AM
29import org.eclipse.tracecompass.internal.statesystem.core.Activator;
30import org.eclipse.tracecompass.statesystem.core.ITmfStateSystemBuilder;
31import org.eclipse.tracecompass.statesystem.core.exceptions.TimeRangeException;
a52fde77 32
f3476b68
GB
33import com.google.common.collect.ImmutableList;
34
a52fde77
AM
35/**
36 * Meta-container for the History Tree. This structure contains all the
37 * high-level data relevant to the tree.
3b7f5abe 38 *
ffd0aa67 39 * @author Alexandre Montplaisir
a52fde77 40 */
8d47cc34 41public class HistoryTree {
a52fde77 42
cb42195c
AM
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
a52fde77
AM
50 private static final int HISTORY_FILE_MAGIC_NUMBER = 0x05FFA900;
51
a96cc6be 52 /** File format version. Increment when breaking compatibility. */
da66cc75 53 private static final int FILE_VERSION = 5;
a52fde77 54
dbdc452f
AM
55 // ------------------------------------------------------------------------
56 // Tree-specific configuration
57 // ------------------------------------------------------------------------
58
59 /** Container for all the configuration constants */
0e9b2f07 60 private final HTConfig fConfig;
a52fde77 61
dbdc452f 62 /** Reader/writer object */
0e9b2f07 63 private final HT_IO fTreeIO;
a52fde77 64
dbdc452f 65 // ------------------------------------------------------------------------
ecb12461 66 // Variable Fields (will change throughout the existence of the SHT)
dbdc452f
AM
67 // ------------------------------------------------------------------------
68
69 /** Latest timestamp found in the tree (at any given moment) */
0e9b2f07 70 private long fTreeEnd;
a52fde77 71
360f899e 72 /** The total number of nodes that exists in this tree */
0e9b2f07 73 private int fNodeCount;
a52fde77 74
dbdc452f 75 /** "Cache" to keep the active nodes in memory */
0e9b2f07 76 private final List<HTNode> fLatestBranch;
a52fde77 77
dbdc452f
AM
78 // ------------------------------------------------------------------------
79 // Constructors/"Destructors"
80 // ------------------------------------------------------------------------
81
a52fde77 82 /**
8d47cc34
AM
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
a52fde77 91 */
8d47cc34 92 public HistoryTree(HTConfig conf) throws IOException {
a52fde77 93 /*
bb7f92ce
FW
94 * Simple check to make sure we have enough place in the 0th block for
95 * the tree configuration
a52fde77 96 */
cb42195c 97 if (conf.getBlockSize() < TREE_HEADER_SIZE) {
dbdc452f
AM
98 throw new IllegalArgumentException();
99 }
a52fde77 100
0e9b2f07
GB
101 fConfig = conf;
102 fTreeEnd = conf.getTreeStart();
103 fNodeCount = 0;
104 fLatestBranch = Collections.synchronizedList(new ArrayList<HTNode>());
a52fde77
AM
105
106 /* Prepare the IO object */
0e9b2f07 107 fTreeIO = new HT_IO(fConfig, true);
a52fde77
AM
108
109 /* Add the first node to the tree */
bb7f92ce 110 LeafNode firstNode = initNewLeafNode(-1, conf.getTreeStart());
0e9b2f07 111 fLatestBranch.add(firstNode);
a52fde77
AM
112 }
113
a52fde77
AM
114 /**
115 * "Reader" constructor : instantiate a SHTree from an existing tree file on
116 * disk
3b7f5abe 117 *
8d47cc34 118 * @param existingStateFile
a52fde77 119 * Path/filename of the history-file we are to open
a96cc6be
AM
120 * @param expProviderVersion
121 * The expected version of the state provider
a52fde77 122 * @throws IOException
8d47cc34 123 * If an error happens reading the file
a52fde77 124 */
8d47cc34 125 public HistoryTree(File existingStateFile, int expProviderVersion) throws IOException {
a52fde77
AM
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;
fb12b0c2 132 long startTime;
a52fde77
AM
133
134 /* Java I/O mumbo jumbo... */
fee997a5
AM
135 if (!existingStateFile.exists()) {
136 throw new IOException("Selected state file does not exist"); //$NON-NLS-1$
137 }
fb12b0c2 138 if (existingStateFile.length() <= 0) {
a96cc6be 139 throw new IOException("Empty target file"); //$NON-NLS-1$
a52fde77
AM
140 }
141
a4524c1b
AM
142 try (FileInputStream fis = new FileInputStream(existingStateFile);
143 FileChannel fc = fis.getChannel();) {
a52fde77 144
a4524c1b 145 ByteBuffer buffer = ByteBuffer.allocate(TREE_HEADER_SIZE);
a52fde77 146
a4524c1b
AM
147 buffer.order(ByteOrder.LITTLE_ENDIAN);
148 buffer.clear();
149 fc.read(buffer);
150 buffer.flip();
a52fde77 151
a96cc6be 152 /*
a4524c1b
AM
153 * Check the magic number to make sure we're opening the right type
154 * of file
a96cc6be 155 */
a4524c1b
AM
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 &&
bcec0116 168 expProviderVersion != ITmfStateSystemBuilder.IGNORE_PROVIDER_VERSION) {
a4524c1b
AM
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 */
a52fde77 181
0e9b2f07 182 fNodeCount = buffer.getInt();
a4524c1b
AM
183 rootNodeSeqNb = buffer.getInt();
184 startTime = buffer.getLong();
a52fde77 185
0e9b2f07 186 fConfig = new HTConfig(existingStateFile, bs, maxc, expProviderVersion, startTime);
a4524c1b 187 }
a52fde77 188
a52fde77
AM
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 */
0e9b2f07 194 fTreeIO = new HT_IO(fConfig, false);
a52fde77 195
0e9b2f07
GB
196 fLatestBranch = buildLatestBranch(rootNodeSeqNb);
197 fTreeEnd = getRootNode().getNodeEnd();
fb12b0c2
AM
198
199 /*
200 * Make sure the history start time we read previously is consistent
201 * with was is actually in the root node.
202 */
412a0225 203 if (startTime != getRootNode().getNodeStart()) {
fb12b0c2
AM
204 throw new IOException("Inconsistent start times in the" + //$NON-NLS-1$
205 "history file, it might be corrupted."); //$NON-NLS-1$
206 }
a52fde77
AM
207 }
208
412a0225
AM
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 */
bb7f92ce
FW
219 private List<HTNode> buildLatestBranch(int rootNodeSeqNb) throws ClosedChannelException {
220 List<HTNode> list = new ArrayList<>();
412a0225 221
0e9b2f07 222 HTNode nextChildNode = fTreeIO.readNode(rootNodeSeqNb);
bb7f92ce 223 list.add(nextChildNode);
412a0225 224
bb7f92ce
FW
225 /* Follow the last branch up to the leaf */
226 while (nextChildNode.getNodeType() == HTNode.NodeType.CORE) {
0e9b2f07 227 nextChildNode = fTreeIO.readNode(((CoreNode) nextChildNode).getLatestChild());
bb7f92ce 228 list.add(nextChildNode);
412a0225
AM
229 }
230 return Collections.synchronizedList(list);
231 }
232
a52fde77
AM
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.
3b7f5abe 238 *
a52fde77 239 * @param requestedEndTime
d862bcb3 240 * The greatest timestamp present in the history tree
a52fde77 241 */
8d47cc34 242 public void closeTree(long requestedEndTime) {
412a0225 243 /* This is an important operation, queries can wait */
0e9b2f07 244 synchronized (fLatestBranch) {
412a0225
AM
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 */
0e9b2f07 253 fTreeEnd = requestedEndTime;
6a1074ce 254
412a0225 255 /* Close off the latest branch of the tree */
0e9b2f07
GB
256 for (int i = 0; i < fLatestBranch.size(); i++) {
257 fLatestBranch.get(i).closeThisNode(fTreeEnd);
258 fTreeIO.writeNode(fLatestBranch.get(i));
412a0225 259 }
a52fde77 260
0e9b2f07 261 try (FileChannel fc = fTreeIO.getFcOut();) {
412a0225
AM
262 ByteBuffer buffer = ByteBuffer.allocate(TREE_HEADER_SIZE);
263 buffer.order(ByteOrder.LITTLE_ENDIAN);
264 buffer.clear();
a52fde77 265
412a0225
AM
266 /* Save the config of the tree to the header of the file */
267 fc.position(0);
a52fde77 268
412a0225 269 buffer.putInt(HISTORY_FILE_MAGIC_NUMBER);
a52fde77 270
412a0225 271 buffer.putInt(FILE_VERSION);
0e9b2f07 272 buffer.putInt(fConfig.getProviderVersion());
a52fde77 273
0e9b2f07
GB
274 buffer.putInt(fConfig.getBlockSize());
275 buffer.putInt(fConfig.getMaxChildren());
a52fde77 276
0e9b2f07 277 buffer.putInt(fNodeCount);
a52fde77 278
412a0225 279 /* root node seq. nb */
0e9b2f07 280 buffer.putInt(fLatestBranch.get(0).getSequenceNumber());
a52fde77 281
412a0225 282 /* start time of this history */
0e9b2f07 283 buffer.putLong(fLatestBranch.get(0).getNodeStart());
fb12b0c2 284
412a0225
AM
285 buffer.flip();
286 int res = fc.write(buffer);
287 assert (res <= TREE_HEADER_SIZE);
288 /* done writing the file header */
a52fde77 289
412a0225
AM
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 }
a52fde77 297 }
a52fde77
AM
298 }
299
dbdc452f
AM
300 // ------------------------------------------------------------------------
301 // Accessors
302 // ------------------------------------------------------------------------
ab604305 303
8d47cc34
AM
304 /**
305 * Get the start time of this tree.
306 *
307 * @return The start time
308 */
309 public long getTreeStart() {
0e9b2f07 310 return fConfig.getTreeStart();
a52fde77
AM
311 }
312
8d47cc34
AM
313 /**
314 * Get the current end time of this tree.
315 *
316 * @return The end time
317 */
318 public long getTreeEnd() {
0e9b2f07 319 return fTreeEnd;
a52fde77
AM
320 }
321
8d47cc34
AM
322 /**
323 * Get the number of nodes in this tree.
324 *
325 * @return The number of nodes
326 */
327 public int getNodeCount() {
0e9b2f07 328 return fNodeCount;
a52fde77
AM
329 }
330
8d47cc34 331 /**
412a0225 332 * Get the current root node of this tree
8d47cc34 333 *
412a0225 334 * @return The root node
8d47cc34 335 */
bb7f92ce 336 public HTNode getRootNode() {
0e9b2f07 337 return fLatestBranch.get(0);
cb42195c
AM
338 }
339
f3476b68
GB
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
360f899e
EB
350 // ------------------------------------------------------------------------
351 // HT_IO interface
352 // ------------------------------------------------------------------------
353
8d47cc34
AM
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() {
0e9b2f07 362 return fTreeIO.supplyATReader(getNodeCount());
360f899e
EB
363 }
364
8d47cc34
AM
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() {
0e9b2f07 371 return fConfig.getStateFile();
360f899e
EB
372 }
373
8d47cc34
AM
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() {
360f899e 381 return HistoryTree.TREE_HEADER_SIZE
0e9b2f07 382 + ((long) getNodeCount() * fConfig.getBlockSize());
360f899e
EB
383 }
384
8d47cc34
AM
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 {
360f899e 395 /* Try to read the node from memory */
0e9b2f07
GB
396 synchronized (fLatestBranch) {
397 for (HTNode node : fLatestBranch) {
412a0225
AM
398 if (node.getSequenceNumber() == seqNumber) {
399 return node;
400 }
360f899e
EB
401 }
402 }
403
404 /* Read the node from disk */
0e9b2f07 405 return fTreeIO.readNode(seqNumber);
360f899e
EB
406 }
407
8d47cc34
AM
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) {
0e9b2f07 415 fTreeIO.writeNode(node);
360f899e
EB
416 }
417
8d47cc34
AM
418 /**
419 * Close the history file.
420 */
421 public void closeFile() {
0e9b2f07 422 fTreeIO.closeFile();
360f899e
EB
423 }
424
8d47cc34
AM
425 /**
426 * Delete the history file.
427 */
428 public void deleteFile() {
0e9b2f07 429 fTreeIO.deleteFile();
360f899e
EB
430 }
431
dbdc452f
AM
432 // ------------------------------------------------------------------------
433 // Operations
434 // ------------------------------------------------------------------------
435
a52fde77 436 /**
8d47cc34 437 * Insert an interval in the tree.
3b7f5abe 438 *
a52fde77 439 * @param interval
d862bcb3 440 * The interval to be inserted
8d47cc34
AM
441 * @throws TimeRangeException
442 * If the start of end time of the interval are invalid
a52fde77 443 */
8d47cc34 444 public void insertInterval(HTInterval interval) throws TimeRangeException {
0e9b2f07
GB
445 if (interval.getStartTime() < fConfig.getTreeStart()) {
446 throw new TimeRangeException("Interval Start:" + interval.getStartTime() + ", Config Start:" + fConfig.getTreeStart()); //$NON-NLS-1$ //$NON-NLS-2$
a52fde77 447 }
0e9b2f07 448 tryInsertAtNode(interval, fLatestBranch.size() - 1);
a52fde77
AM
449 }
450
451 /**
452 * Inner method to find in which node we should add the interval.
3b7f5abe 453 *
a52fde77
AM
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) {
0e9b2f07 461 HTNode targetNode = fLatestBranch.get(indexOfNode);
a52fde77
AM
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);
0e9b2f07 467 tryInsertAtNode(interval, fLatestBranch.size() - 1);
a52fde77
AM
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 */
0e9b2f07
GB
489 if (interval.getEndTime() > fTreeEnd) {
490 fTreeEnd = interval.getEndTime();
a52fde77 491 }
a52fde77
AM
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.
3b7f5abe 497 *
a52fde77
AM
498 * @param indexOfNode
499 * The index in latestBranch where we start adding
500 */
501 private void addSiblingNode(int indexOfNode) {
0e9b2f07
GB
502 synchronized (fLatestBranch) {
503 final long splitTime = fTreeEnd;
a52fde77 504
0e9b2f07 505 if (indexOfNode >= fLatestBranch.size()) {
bb7f92ce
FW
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 }
a52fde77 512
412a0225
AM
513 /* Check if we need to add a new root node */
514 if (indexOfNode == 0) {
515 addNewRootNode();
516 return;
517 }
a52fde77 518
412a0225 519 /* Check if we can indeed add a child to the target parent */
0e9b2f07 520 if (((CoreNode) fLatestBranch.get(indexOfNode - 1)).getNbChildren() == fConfig.getMaxChildren()) {
412a0225
AM
521 /* If not, add a branch starting one level higher instead */
522 addSiblingNode(indexOfNode - 1);
523 return;
524 }
a52fde77 525
412a0225 526 /* Split off the new branch from the old one */
0e9b2f07
GB
527 for (int i = indexOfNode; i < fLatestBranch.size(); i++) {
528 fLatestBranch.get(i).closeThisNode(splitTime);
529 fTreeIO.writeNode(fLatestBranch.get(i));
a52fde77 530
0e9b2f07 531 CoreNode prevNode = (CoreNode) fLatestBranch.get(i - 1);
bb7f92ce
FW
532 HTNode newNode;
533
0e9b2f07 534 switch (fLatestBranch.get(i).getNodeType()) {
bb7f92ce
FW
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 }
a52fde77 544
bb7f92ce 545 prevNode.linkNewChild(newNode);
0e9b2f07 546 fLatestBranch.set(i, newNode);
412a0225 547 }
a52fde77 548 }
a52fde77
AM
549 }
550
551 /**
552 * Similar to the previous method, except here we rebuild a completely new
553 * latestBranch
554 */
555 private void addNewRootNode() {
0e9b2f07 556 final long splitTime = fTreeEnd;
a52fde77 557
0e9b2f07
GB
558 HTNode oldRootNode = fLatestBranch.get(0);
559 CoreNode newRootNode = initNewCoreNode(-1, fConfig.getTreeStart());
a52fde77
AM
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 */
412a0225 565
0e9b2f07
GB
566 for (int i = 0; i < fLatestBranch.size(); i++) {
567 fLatestBranch.get(i).closeThisNode(splitTime);
568 fTreeIO.writeNode(fLatestBranch.get(i));
a52fde77
AM
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 */
0e9b2f07
GB
575 int depth = fLatestBranch.size();
576 fLatestBranch.clear();
577 fLatestBranch.add(newRootNode);
bb7f92ce
FW
578
579 // Create new coreNode
412a0225 580 for (int i = 1; i < depth + 1; i++) {
0e9b2f07 581 CoreNode prevNode = (CoreNode) fLatestBranch.get(i - 1);
412a0225 582 CoreNode newNode = initNewCoreNode(prevNode.getParentSequenceNumber(),
a52fde77
AM
583 splitTime + 1);
584 prevNode.linkNewChild(newNode);
0e9b2f07 585 fLatestBranch.add(newNode);
a52fde77 586 }
bb7f92ce
FW
587
588 // Create the new leafNode
0e9b2f07 589 CoreNode prevNode = (CoreNode) fLatestBranch.get(depth);
bb7f92ce
FW
590 LeafNode newNode = initNewLeafNode(prevNode.getParentSequenceNumber(), splitTime + 1);
591 prevNode.linkNewChild(newNode);
0e9b2f07 592 fLatestBranch.add(newNode);
a52fde77
AM
593 }
594
595 /**
bb7f92ce 596 * Add a new empty core node to the tree.
3b7f5abe 597 *
a52fde77
AM
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) {
0e9b2f07 605 CoreNode newNode = new CoreNode(fConfig, fNodeCount, parentSeqNumber,
a52fde77 606 startTime);
0e9b2f07 607 fNodeCount++;
a52fde77
AM
608
609 /* Update the treeEnd if needed */
0e9b2f07
GB
610 if (startTime >= fTreeEnd) {
611 fTreeEnd = startTime + 1;
a52fde77
AM
612 }
613 return newNode;
614 }
615
bb7f92ce
FW
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) {
0e9b2f07 626 LeafNode newNode = new LeafNode(fConfig, fNodeCount, parentSeqNumber,
bb7f92ce 627 startTime);
0e9b2f07 628 fNodeCount++;
bb7f92ce
FW
629
630 /* Update the treeEnd if needed */
0e9b2f07
GB
631 if (startTime >= fTreeEnd) {
632 fTreeEnd = startTime + 1;
bb7f92ce
FW
633 }
634 return newNode;
635 }
636
a52fde77
AM
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.
3b7f5abe 641 *
a52fde77 642 * @param currentNode
d862bcb3 643 * The node on which the request is made
a52fde77 644 * @param t
d862bcb3 645 * The timestamp to choose which child is the next one
a52fde77 646 * @return The child node intersecting t
3b7f5abe
AM
647 * @throws ClosedChannelException
648 * If the file channel was closed while we were reading the tree
a52fde77 649 */
8d47cc34 650 public HTNode selectNextChild(CoreNode currentNode, long t) throws ClosedChannelException {
a52fde77
AM
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 }
d862bcb3 661
a52fde77
AM
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 */
045badfe 673 if (currentNode.isOnDisk()) {
0e9b2f07 674 return fTreeIO.readNode(potentialNextSeqNb);
a52fde77 675 }
83c31d28 676 return readNode(potentialNextSeqNb);
a52fde77
AM
677 }
678
8d47cc34
AM
679 /**
680 * Get the current size of the history file.
681 *
682 * @return The history file size
683 */
684 public long getFileSize() {
0e9b2f07 685 return fConfig.getStateFile().length();
a52fde77
AM
686 }
687
3b7f5abe
AM
688 // ------------------------------------------------------------------------
689 // Test/debugging methods
690 // ------------------------------------------------------------------------
a52fde77 691
8d47cc34
AM
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 */
a52fde77 702 @SuppressWarnings("nls")
8d47cc34
AM
703 public boolean checkNodeIntegrity(HTNode zenode) {
704 /* Only used for debugging, shouldn't be externalized */
a52fde77
AM
705 HTNode otherNode;
706 CoreNode node;
ab604305 707 StringBuffer buf = new StringBuffer();
a52fde77
AM
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
3b7f5abe
AM
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) {
0e9b2f07 723 otherNode = fTreeIO.readNode(node.getChild(0));
3b7f5abe
AM
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 #"
ab604305 728 + otherNode.getSequenceNumber() + ")\n");
a52fde77
AM
729 ret = false;
730 }
045badfe 731 if (node.isOnDisk()) {
0e9b2f07 732 otherNode = fTreeIO.readNode(node.getLatestChild());
3b7f5abe
AM
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 }
a52fde77 741 }
a52fde77 742
3b7f5abe 743 /*
bb7f92ce
FW
744 * Test that the childStartTimes[] array matches the real nodes'
745 * start times
3b7f5abe
AM
746 */
747 for (int i = 0; i < node.getNbChildren(); i++) {
0e9b2f07 748 otherNode = fTreeIO.readNode(node.getChild(i));
3b7f5abe
AM
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 }
a52fde77 757 }
3b7f5abe
AM
758
759 } catch (ClosedChannelException e) {
0e9b2f07 760 Activator.getDefault().logError(e.getMessage(), e);
a52fde77
AM
761 }
762
763 if (!ret) {
0e9b2f07
GB
764 Activator.getDefault().logError("SHT: Integrity check failed for node #"
765 + node.getSequenceNumber() + ":" + buf.toString());
a52fde77
AM
766 }
767 return ret;
768 }
769
8d47cc34
AM
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() {
3b7f5abe 775 try {
0e9b2f07
GB
776 for (int i = 0; i < fNodeCount; i++) {
777 checkNodeIntegrity(fTreeIO.readNode(i));
3b7f5abe
AM
778 }
779 } catch (ClosedChannelException e) {
a52fde77
AM
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: "
0e9b2f07
GB
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"
a52fde77 792 + "Root node has sequence number: "
0e9b2f07 793 + fLatestBranch.get(0).getSequenceNumber() + "\n"
a52fde77 794 + "'Latest leaf' has sequence number: "
0e9b2f07 795 + fLatestBranch.get(fLatestBranch.size() - 1).getSequenceNumber();
a52fde77
AM
796 }
797
a52fde77
AM
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 */
d862bcb3 803 /* Only used for debugging, shouldn't be externalized */
a52fde77
AM
804 @SuppressWarnings("nls")
805 private void preOrderPrint(PrintWriter writer, boolean printIntervals,
bb7f92ce 806 HTNode currentNode, int curDepth) {
a52fde77
AM
807
808 writer.println(currentNode.toString());
809 if (printIntervals) {
810 currentNode.debugPrintIntervals(writer);
811 }
a52fde77 812
bb7f92ce
FW
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) {
0e9b2f07 824 HTNode nextNode = fTreeIO.readNode(extension);
bb7f92ce
FW
825 preOrderPrint(writer, printIntervals, nextNode, curDepth);
826 }
827
828 /* Print the child nodes */
829 for (int i = 0; i < node.getNbChildren(); i++) {
0e9b2f07 830 HTNode nextNode = fTreeIO.readNode(node.getChild(i));
bb7f92ce
FW
831 for (int j = 0; j < curDepth; j++) {
832 writer.print(" ");
833 }
834 writer.print("+-");
835 preOrderPrint(writer, printIntervals, nextNode, curDepth + 1);
3b7f5abe 836 }
bb7f92ce 837 } catch (ClosedChannelException e) {
bcec0116 838 Activator.getDefault().logError(e.getMessage());
a52fde77 839 }
bb7f92ce
FW
840 break;
841
842 default:
843 break;
a52fde77 844 }
a52fde77
AM
845 }
846
847 /**
848 * Print out the full tree for debugging purposes
3b7f5abe 849 *
a52fde77
AM
850 * @param writer
851 * PrintWriter in which to write the output
852 * @param printIntervals
d862bcb3 853 * Flag to enable full output of the interval information
a52fde77 854 */
8d47cc34 855 public void debugPrintFullTree(PrintWriter writer, boolean printIntervals) {
a52fde77 856 /* Only used for debugging, shouldn't be externalized */
d862bcb3 857
0e9b2f07 858 preOrderPrint(writer, false, fLatestBranch.get(0), 0);
a52fde77
AM
859
860 if (printIntervals) {
861 writer.println("\nDetails of intervals:"); //$NON-NLS-1$
0e9b2f07 862 preOrderPrint(writer, true, fLatestBranch.get(0), 0);
a52fde77
AM
863 }
864 writer.println('\n');
865 }
866
867}
This page took 0.129966 seconds and 5 git commands to generate.