1 /*******************************************************************************
2 * Copyright (c) 2012, 2014 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
.statesystem
.core
;
16 import java
.io
.IOException
;
17 import java
.io
.PrintWriter
;
18 import java
.util
.ArrayList
;
19 import java
.util
.LinkedList
;
20 import java
.util
.List
;
21 import java
.util
.concurrent
.CountDownLatch
;
22 import java
.util
.concurrent
.TimeUnit
;
24 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
25 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
26 import org
.eclipse
.jdt
.annotation
.NonNull
;
27 import org
.eclipse
.linuxtools
.statesystem
.core
.ITmfStateSystemBuilder
;
28 import org
.eclipse
.linuxtools
.statesystem
.core
.backend
.IStateHistoryBackend
;
29 import org
.eclipse
.linuxtools
.statesystem
.core
.exceptions
.AttributeNotFoundException
;
30 import org
.eclipse
.linuxtools
.statesystem
.core
.exceptions
.StateSystemDisposedException
;
31 import org
.eclipse
.linuxtools
.statesystem
.core
.exceptions
.StateValueTypeException
;
32 import org
.eclipse
.linuxtools
.statesystem
.core
.exceptions
.TimeRangeException
;
33 import org
.eclipse
.linuxtools
.statesystem
.core
.interval
.ITmfStateInterval
;
34 import org
.eclipse
.linuxtools
.statesystem
.core
.interval
.TmfStateInterval
;
35 import org
.eclipse
.linuxtools
.statesystem
.core
.statevalue
.ITmfStateValue
;
36 import org
.eclipse
.linuxtools
.statesystem
.core
.statevalue
.TmfStateValue
;
37 import org
.eclipse
.linuxtools
.statesystem
.core
.statevalue
.ITmfStateValue
.Type
;
40 * This is the core class of the Generic State System. It contains all the
41 * methods to build and query a state history. It's exposed externally through
42 * the IStateSystemQuerier and IStateSystemBuilder interfaces, depending if the
43 * user needs read-only access or read-write access.
45 * When building, DON'T FORGET to call .closeHistory() when you are done
46 * inserting intervals, or the storage backend will have no way of knowing it
47 * can close and write itself to disk, and its thread will keep running.
52 public class StateSystem
implements ITmfStateSystemBuilder
{
54 private final String ssid
;
56 /* References to the inner structures */
57 private final AttributeTree attributeTree
;
58 private final TransientState transState
;
59 private final IStateHistoryBackend backend
;
61 /* Latch tracking if the state history is done building or not */
62 private final CountDownLatch finishedLatch
= new CountDownLatch(1);
64 private boolean buildCancelled
= false;
65 private boolean isDisposed
= false;
68 * New-file constructor. For when you build a state system with a new file,
69 * or if the back-end does not require a file on disk.
72 * The ID of this statesystem. It should be unique.
74 * Back-end plugin to use
76 public StateSystem(@NonNull String ssid
, @NonNull IStateHistoryBackend backend
) {
78 this.backend
= backend
;
79 this.transState
= new TransientState(backend
);
80 this.attributeTree
= new AttributeTree(this);
87 * The ID of this statesystem. It should be unique.
89 * The "state history storage" back-end to use.
91 * Put true if this is a new history started from scratch. It is
92 * used to tell the state system where to get its attribute tree.
94 * If there was a problem creating the new history file
96 public StateSystem(@NonNull String ssid
, @NonNull IStateHistoryBackend backend
, boolean newFile
)
99 this.backend
= backend
;
100 this.transState
= new TransientState(backend
);
103 attributeTree
= new AttributeTree(this);
105 /* We're opening an existing file */
106 this.attributeTree
= new AttributeTree(this, backend
.supplyAttributeTreeReader());
107 transState
.setInactive();
108 finishedLatch
.countDown(); /* The history is already built */
113 public String
getSSID() {
118 public boolean isCancelled() {
119 return buildCancelled
;
123 public void waitUntilBuilt() {
125 finishedLatch
.await();
126 } catch (InterruptedException e
) {
132 public boolean waitUntilBuilt(long timeout
) {
135 ret
= finishedLatch
.await(timeout
, TimeUnit
.MILLISECONDS
);
136 } catch (InterruptedException e
) {
143 public synchronized void dispose() {
145 if (transState
.isActive()) {
146 transState
.setInactive();
147 buildCancelled
= true;
152 //--------------------------------------------------------------------------
153 // General methods related to the attribute tree
154 //--------------------------------------------------------------------------
157 * Get the attribute tree associated with this state system. This should be
158 * the only way of accessing it (and if subclasses want to point to a
159 * different attribute tree than their own, they should only need to
162 * @return The attribute tree
164 public AttributeTree
getAttributeTree() {
165 return attributeTree
;
169 * Method used by the attribute tree when creating new attributes, to keep
170 * the attribute count in the transient state in sync.
172 public void addEmptyAttribute() {
173 transState
.addEmptyEntry();
177 public int getNbAttributes() {
178 return getAttributeTree().getNbAttributes();
182 public String
getAttributeName(int attributeQuark
) {
183 return getAttributeTree().getAttributeName(attributeQuark
);
187 public String
getFullAttributePath(int attributeQuark
) {
188 return getAttributeTree().getFullAttributeName(attributeQuark
);
191 //--------------------------------------------------------------------------
192 // Methods related to the storage backend
193 //--------------------------------------------------------------------------
196 public long getStartTime() {
197 return backend
.getStartTime();
201 public long getCurrentEndTime() {
202 return backend
.getEndTime();
206 public void closeHistory(long endTime
) throws TimeRangeException
{
207 File attributeTreeFile
;
208 long attributeTreeFilePos
;
209 long realEndTime
= endTime
;
211 if (realEndTime
< backend
.getEndTime()) {
213 * This can happen (empty nodes pushing the border further, etc.)
214 * but shouldn't be too big of a deal.
216 realEndTime
= backend
.getEndTime();
218 transState
.closeTransientState(realEndTime
);
219 backend
.finishedBuilding(realEndTime
);
221 attributeTreeFile
= backend
.supplyAttributeTreeWriterFile();
222 attributeTreeFilePos
= backend
.supplyAttributeTreeWriterFilePosition();
223 if (attributeTreeFile
!= null) {
225 * If null was returned, we simply won't save the attribute tree,
228 getAttributeTree().writeSelf(attributeTreeFile
, attributeTreeFilePos
);
230 finishedLatch
.countDown(); /* Mark the history as finished building */
233 //--------------------------------------------------------------------------
234 // Quark-retrieving methods
235 //--------------------------------------------------------------------------
238 public int getQuarkAbsolute(String
... attribute
)
239 throws AttributeNotFoundException
{
240 return getAttributeTree().getQuarkDontAdd(-1, attribute
);
244 public int getQuarkAbsoluteAndAdd(String
... attribute
) {
245 return getAttributeTree().getQuarkAndAdd(-1, attribute
);
249 public int getQuarkRelative(int startingNodeQuark
, String
... subPath
)
250 throws AttributeNotFoundException
{
251 return getAttributeTree().getQuarkDontAdd(startingNodeQuark
, subPath
);
255 public int getQuarkRelativeAndAdd(int startingNodeQuark
, String
... subPath
) {
256 return getAttributeTree().getQuarkAndAdd(startingNodeQuark
, subPath
);
260 public List
<Integer
> getSubAttributes(int quark
, boolean recursive
)
261 throws AttributeNotFoundException
{
262 return getAttributeTree().getSubAttributes(quark
, recursive
);
266 public List
<Integer
> getSubAttributes(int quark
, boolean recursive
, String pattern
)
267 throws AttributeNotFoundException
{
268 List
<Integer
> all
= getSubAttributes(quark
, recursive
);
269 List
<Integer
> ret
= new LinkedList
<>();
270 for (Integer attQuark
: all
) {
271 String name
= getAttributeName(attQuark
.intValue());
272 if (name
.matches(pattern
)) {
280 public int getParentAttributeQuark(int quark
) {
281 return getAttributeTree().getParentAttributeQuark(quark
);
285 public List
<Integer
> getQuarks(String
... pattern
) {
286 List
<Integer
> quarks
= new LinkedList
<>();
287 List
<String
> prefix
= new LinkedList
<>();
288 List
<String
> suffix
= new LinkedList
<>();
289 boolean split
= false;
292 List
<Integer
> directChildren
;
293 int startingAttribute
;
295 /* Fill the "prefix" and "suffix" parts of the pattern around the '*' */
296 for (String entry
: pattern
) {
297 if (entry
.equals("*")) { //$NON-NLS-1$
300 * Split was already true? This means there was more than
301 * one wildcard. This is not supported, return an empty
316 prefixStr
= prefix
.toArray(new String
[prefix
.size()]);
317 suffixStr
= suffix
.toArray(new String
[suffix
.size()]);
320 * If there was no wildcard, we'll only return the one matching
321 * attribute, if there is one.
326 quark
= getQuarkAbsolute(prefixStr
);
327 } catch (AttributeNotFoundException e
) {
328 /* It's fine, we'll just return the empty List */
336 if (prefix
.size() == 0) {
338 * If 'prefix' is empty, this means the wildcard was the first
339 * element. Look for the root node's sub-attributes.
341 startingAttribute
= -1;
343 startingAttribute
= getQuarkAbsolute(prefixStr
);
345 directChildren
= getSubAttributes(startingAttribute
, false);
346 } catch (AttributeNotFoundException e
) {
347 /* That attribute path did not exist, return the empty array */
352 * Iterate of all the sub-attributes, and only keep those who match the
353 * 'suffix' part of the initial pattern.
355 for (int childQuark
: directChildren
) {
358 matchingQuark
= getQuarkRelative(childQuark
, suffixStr
);
359 } catch (AttributeNotFoundException e
) {
362 quarks
.add(matchingQuark
);
368 //--------------------------------------------------------------------------
369 // Methods related to insertions in the history
370 //--------------------------------------------------------------------------
373 public void modifyAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
374 throws TimeRangeException
, AttributeNotFoundException
,
375 StateValueTypeException
{
376 transState
.processStateChange(t
, value
, attributeQuark
);
380 public void incrementAttribute(long t
, int attributeQuark
)
381 throws StateValueTypeException
, TimeRangeException
,
382 AttributeNotFoundException
{
383 ITmfStateValue stateValue
= queryOngoingState(attributeQuark
);
385 /* if the attribute was previously null, start counting at 0 */
386 if (!stateValue
.isNull()) {
387 prevValue
= stateValue
.unboxInt();
389 modifyAttribute(t
, TmfStateValue
.newValueInt(prevValue
+ 1),
394 public void pushAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
395 throws TimeRangeException
, AttributeNotFoundException
,
396 StateValueTypeException
{
398 int subAttributeQuark
;
399 ITmfStateValue previousSV
= transState
.getOngoingStateValue(attributeQuark
);
401 if (previousSV
.isNull()) {
403 * If the StateValue was null, this means this is the first time we
404 * use this attribute. Leave stackDepth at 0.
407 } else if (previousSV
.getType() == Type
.INTEGER
) {
408 /* Previous value was an integer, all is good, use it */
409 stackDepth
= previousSV
.unboxInt();
411 /* Previous state of this attribute was another type? Not good! */
412 throw new StateValueTypeException();
415 if (stackDepth
>= 100000) {
417 * Limit stackDepth to 100000, to avoid having Attribute Trees grow
418 * out of control due to buggy insertions
420 String message
= "Stack limit reached, not pushing"; //$NON-NLS-1$
421 throw new AttributeNotFoundException(message
);
425 subAttributeQuark
= getQuarkRelativeAndAdd(attributeQuark
, String
.valueOf(stackDepth
));
427 modifyAttribute(t
, TmfStateValue
.newValueInt(stackDepth
), attributeQuark
);
428 modifyAttribute(t
, value
, subAttributeQuark
);
432 public ITmfStateValue
popAttribute(long t
, int attributeQuark
)
433 throws AttributeNotFoundException
, TimeRangeException
,
434 StateValueTypeException
{
435 /* These are the state values of the stack-attribute itself */
436 ITmfStateValue previousSV
= queryOngoingState(attributeQuark
);
438 if (previousSV
.isNull()) {
440 * Trying to pop an empty stack. This often happens at the start of
441 * traces, for example when we see a syscall_exit, without having
442 * the corresponding syscall_entry in the trace. Just ignore
447 if (previousSV
.getType() != Type
.INTEGER
) {
449 * The existing value was not an integer (which is expected for
450 * stack tops), this doesn't look like a valid stack attribute.
452 throw new StateValueTypeException();
455 int stackDepth
= previousSV
.unboxInt();
457 if (stackDepth
<= 0) {
458 /* This on the other hand should not happen... */
459 String message
= "A top-level stack attribute cannot " + //$NON-NLS-1$
460 "have a value of 0 or less."; //$NON-NLS-1$
461 throw new StateValueTypeException(message
);
464 /* The attribute should already exist at this point */
465 int subAttributeQuark
= getQuarkRelative(attributeQuark
, String
.valueOf(stackDepth
));
466 ITmfStateValue poppedValue
= queryOngoingState(subAttributeQuark
);
468 /* Update the state value of the stack-attribute */
469 ITmfStateValue nextSV
;
470 if (--stackDepth
== 0) {
471 /* Store a null state value */
472 nextSV
= TmfStateValue
.nullValue();
474 nextSV
= TmfStateValue
.newValueInt(stackDepth
);
476 modifyAttribute(t
, nextSV
, attributeQuark
);
478 /* Delete the sub-attribute that contained the user's state value */
479 removeAttribute(t
, subAttributeQuark
);
485 public void removeAttribute(long t
, int attributeQuark
)
486 throws TimeRangeException
, AttributeNotFoundException
{
487 assert (attributeQuark
>= 0);
488 List
<Integer
> childAttributes
;
491 * "Nullify our children first, recursively. We pass 'false' because we
492 * handle the recursion ourselves.
494 childAttributes
= getSubAttributes(attributeQuark
, false);
495 for (int childNodeQuark
: childAttributes
) {
496 assert (attributeQuark
!= childNodeQuark
);
497 removeAttribute(t
, childNodeQuark
);
499 /* Nullify ourselves */
501 transState
.processStateChange(t
, TmfStateValue
.nullValue(),
503 } catch (StateValueTypeException e
) {
505 * Will not happen since we're inserting null values only, but poor
506 * compiler has no way of knowing this...
508 throw new IllegalStateException(e
);
512 //--------------------------------------------------------------------------
513 // "Current" query/update methods
514 //--------------------------------------------------------------------------
517 public ITmfStateValue
queryOngoingState(int attributeQuark
)
518 throws AttributeNotFoundException
{
519 return transState
.getOngoingStateValue(attributeQuark
);
523 public long getOngoingStartTime(int attribute
)
524 throws AttributeNotFoundException
{
525 return transState
.getOngoingStartTime(attribute
);
529 public void updateOngoingState(ITmfStateValue newValue
, int attributeQuark
)
530 throws AttributeNotFoundException
{
531 transState
.changeOngoingStateValue(attributeQuark
, newValue
);
535 * Modify the whole "ongoing state" (state values + start times). This can
536 * be used when "seeking" a state system to a different point in the trace
537 * (and restoring the known stateInfo at this location). Use with care!
539 * @param newStateIntervals
540 * The new List of state values to use as ongoing state info
542 protected void replaceOngoingState(List
<ITmfStateInterval
> newStateIntervals
) {
543 transState
.replaceOngoingState(newStateIntervals
);
546 //--------------------------------------------------------------------------
547 // Regular query methods (sent to the back-end)
548 //--------------------------------------------------------------------------
551 public synchronized List
<ITmfStateInterval
> queryFullState(long t
)
552 throws TimeRangeException
, StateSystemDisposedException
{
554 throw new StateSystemDisposedException();
557 List
<ITmfStateInterval
> stateInfo
= new ArrayList
<>(getNbAttributes());
559 /* Bring the size of the array to the current number of attributes */
560 for (int i
= 0; i
< getNbAttributes(); i
++) {
564 /* Query the storage backend */
565 backend
.doQuery(stateInfo
, t
);
568 * If we are currently building the history, also query the "ongoing"
569 * states for stuff that might not yet be written to the history.
571 if (transState
.isActive()) {
572 transState
.doQuery(stateInfo
, t
);
576 * We should have previously inserted an interval for every attribute.
577 * If we do happen do see a 'null' object here, just replace it with a a
578 * dummy internal with a null value, to avoid NPE's further up.
580 for (int i
= 0; i
< stateInfo
.size(); i
++) {
581 if (stateInfo
.get(i
) == null) {
582 stateInfo
.set(i
, new TmfStateInterval(t
, t
, i
, TmfStateValue
.nullValue()));
589 public ITmfStateInterval
querySingleState(long t
, int attributeQuark
)
590 throws AttributeNotFoundException
, TimeRangeException
,
591 StateSystemDisposedException
{
593 throw new StateSystemDisposedException();
596 ITmfStateInterval ret
= transState
.getIntervalAt(t
, attributeQuark
);
599 * The transient state did not have the information, let's look into
602 ret
= backend
.doSingularQuery(t
, attributeQuark
);
606 * Return a fake interval if we could not find anything in the history.
607 * We do NOT want to return 'null' here.
610 return new TmfStateInterval(t
, this.getCurrentEndTime(),
611 attributeQuark
, TmfStateValue
.nullValue());
617 public ITmfStateInterval
querySingleStackTop(long t
, int stackAttributeQuark
)
618 throws StateValueTypeException
, AttributeNotFoundException
,
619 TimeRangeException
, StateSystemDisposedException
{
620 ITmfStateValue curStackStateValue
= querySingleState(t
, stackAttributeQuark
).getStateValue();
622 if (curStackStateValue
.isNull()) {
623 /* There is nothing stored in this stack at this moment */
626 int curStackDepth
= curStackStateValue
.unboxInt();
627 if (curStackDepth
<= 0) {
629 * This attribute is an integer attribute, but it doesn't seem like
630 * it's used as a stack-attribute...
632 throw new StateValueTypeException();
635 int subAttribQuark
= getQuarkRelative(stackAttributeQuark
, String
.valueOf(curStackDepth
));
636 return querySingleState(t
, subAttribQuark
);
640 public List
<ITmfStateInterval
> queryHistoryRange(int attributeQuark
,
641 long t1
, long t2
) throws TimeRangeException
,
642 AttributeNotFoundException
, StateSystemDisposedException
{
644 throw new StateSystemDisposedException();
647 List
<ITmfStateInterval
> intervals
;
648 ITmfStateInterval currentInterval
;
651 /* Make sure the time range makes sense */
653 throw new TimeRangeException();
656 /* Set the actual, valid end time of the range query */
657 if (t2
> this.getCurrentEndTime()) {
658 tEnd
= this.getCurrentEndTime();
663 /* Get the initial state at time T1 */
664 intervals
= new ArrayList
<>();
665 currentInterval
= querySingleState(t1
, attributeQuark
);
666 intervals
.add(currentInterval
);
668 /* Get the following state changes */
669 ts
= currentInterval
.getEndTime();
670 while (ts
!= -1 && ts
< tEnd
) {
671 ts
++; /* To "jump over" to the next state in the history */
672 currentInterval
= querySingleState(ts
, attributeQuark
);
673 intervals
.add(currentInterval
);
674 ts
= currentInterval
.getEndTime();
680 public List
<ITmfStateInterval
> queryHistoryRange(int attributeQuark
,
681 long t1
, long t2
, long resolution
, IProgressMonitor monitor
)
682 throws TimeRangeException
, AttributeNotFoundException
,
683 StateSystemDisposedException
{
685 throw new StateSystemDisposedException();
688 List
<ITmfStateInterval
> intervals
= new LinkedList
<>();
689 ITmfStateInterval currentInterval
= null;
692 IProgressMonitor mon
= monitor
;
694 mon
= new NullProgressMonitor();
697 /* Make sure the time range makes sense */
698 if (t2
< t1
|| resolution
<= 0) {
699 throw new TimeRangeException();
702 /* Set the actual, valid end time of the range query */
703 if (t2
> this.getCurrentEndTime()) {
704 tEnd
= this.getCurrentEndTime();
710 * Iterate over the "resolution points". We skip unneeded queries in the
711 * case the current interval is longer than the resolution.
713 for (ts
= t1
; ts
<= tEnd
;
714 ts
+= ((currentInterval
.getEndTime() - ts
) / resolution
+ 1) * resolution
) {
715 if (mon
.isCanceled()) {
718 currentInterval
= querySingleState(ts
, attributeQuark
);
719 intervals
.add(currentInterval
);
722 /* Add the interval at t2, if it wasn't included already. */
723 if (currentInterval
!= null && currentInterval
.getEndTime() < tEnd
) {
724 currentInterval
= querySingleState(tEnd
, attributeQuark
);
725 intervals
.add(currentInterval
);
730 //--------------------------------------------------------------------------
732 //--------------------------------------------------------------------------
734 static void logMissingInterval(int attribute
, long timestamp
) {
735 Activator
.getDefault().logInfo("No data found in history for attribute " + //$NON-NLS-1$
736 attribute
+ " at time " + timestamp
+ //$NON-NLS-1$
737 ", returning dummy interval"); //$NON-NLS-1$
741 * Print out the contents of the inner structures.
744 * The PrintWriter in which to print the output
746 public void debugPrint(PrintWriter writer
) {
747 getAttributeTree().debugPrint(writer
);
748 transState
.debugPrint(writer
);
749 backend
.debugPrint(writer
);