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
;
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
.internal
.tmf
.core
.Activator
;
28 import org
.eclipse
.linuxtools
.internal
.tmf
.core
.statesystem
.backends
.IStateHistoryBackend
;
29 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.AttributeNotFoundException
;
30 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.StateSystemDisposedException
;
31 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.StateValueTypeException
;
32 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.TimeRangeException
;
33 import org
.eclipse
.linuxtools
.tmf
.core
.interval
.ITmfStateInterval
;
34 import org
.eclipse
.linuxtools
.tmf
.core
.interval
.TmfStateInterval
;
35 import org
.eclipse
.linuxtools
.tmf
.core
.statesystem
.ITmfStateSystemBuilder
;
36 import org
.eclipse
.linuxtools
.tmf
.core
.statevalue
.ITmfStateValue
;
37 import org
.eclipse
.linuxtools
.tmf
.core
.statevalue
.ITmfStateValue
.Type
;
38 import org
.eclipse
.linuxtools
.tmf
.core
.statevalue
.TmfStateValue
;
41 * This is the core class of the Generic State System. It contains all the
42 * methods to build and query a state history. It's exposed externally through
43 * the IStateSystemQuerier and IStateSystemBuilder interfaces, depending if the
44 * user needs read-only access or read-write access.
46 * When building, DON'T FORGET to call .closeHistory() when you are done
47 * inserting intervals, or the storage backend will have no way of knowing it
48 * can close and write itself to disk, and its thread will keep running.
53 public class StateSystem
implements ITmfStateSystemBuilder
{
55 /* References to the inner structures */
56 private final AttributeTree attributeTree
;
57 private final TransientState transState
;
58 private final IStateHistoryBackend backend
;
60 /* Latch tracking if the state history is done building or not */
61 private final CountDownLatch finishedLatch
= new CountDownLatch(1);
63 private boolean buildCancelled
= false;
64 private boolean isDisposed
= false;
67 * New-file constructor. For when you build a state system with a new file,
68 * or if the back-end does not require a file on disk.
71 * Back-end plugin to use
73 public StateSystem(@NonNull IStateHistoryBackend backend
) {
74 this.backend
= backend
;
75 this.transState
= new TransientState(backend
);
76 this.attributeTree
= new AttributeTree(this);
83 * The "state history storage" back-end to use.
85 * Put true if this is a new history started from scratch. It is
86 * used to tell the state system where to get its attribute tree.
88 * If there was a problem creating the new history file
90 public StateSystem(@NonNull IStateHistoryBackend backend
, boolean newFile
)
92 this.backend
= backend
;
93 this.transState
= new TransientState(backend
);
96 attributeTree
= new AttributeTree(this);
98 /* We're opening an existing file */
99 this.attributeTree
= new AttributeTree(this, backend
.supplyAttributeTreeReader());
100 transState
.setInactive();
101 finishedLatch
.countDown(); /* The history is already built */
106 public boolean isCancelled() {
107 return buildCancelled
;
111 public void waitUntilBuilt() {
113 finishedLatch
.await();
114 } catch (InterruptedException e
) {
120 public boolean waitUntilBuilt(long timeout
) {
123 ret
= finishedLatch
.await(timeout
, TimeUnit
.MILLISECONDS
);
124 } catch (InterruptedException e
) {
131 public synchronized void dispose() {
133 if (transState
.isActive()) {
134 transState
.setInactive();
135 buildCancelled
= true;
140 //--------------------------------------------------------------------------
141 // General methods related to the attribute tree
142 //--------------------------------------------------------------------------
145 * Get the attribute tree associated with this state system. This should be
146 * the only way of accessing it (and if subclasses want to point to a
147 * different attribute tree than their own, they should only need to
150 * @return The attribute tree
152 public AttributeTree
getAttributeTree() {
153 return attributeTree
;
157 * Method used by the attribute tree when creating new attributes, to keep
158 * the attribute count in the transient state in sync.
160 protected void addEmptyAttribute() {
161 transState
.addEmptyEntry();
165 public int getNbAttributes() {
166 return getAttributeTree().getNbAttributes();
170 public String
getAttributeName(int attributeQuark
) {
171 return getAttributeTree().getAttributeName(attributeQuark
);
175 public String
getFullAttributePath(int attributeQuark
) {
176 return getAttributeTree().getFullAttributeName(attributeQuark
);
179 //--------------------------------------------------------------------------
180 // Methods related to the storage backend
181 //--------------------------------------------------------------------------
184 public long getStartTime() {
185 return backend
.getStartTime();
189 public long getCurrentEndTime() {
190 return backend
.getEndTime();
194 public void closeHistory(long endTime
) throws TimeRangeException
{
195 File attributeTreeFile
;
196 long attributeTreeFilePos
;
197 long realEndTime
= endTime
;
199 if (realEndTime
< backend
.getEndTime()) {
201 * This can happen (empty nodes pushing the border further, etc.)
202 * but shouldn't be too big of a deal.
204 realEndTime
= backend
.getEndTime();
206 transState
.closeTransientState(realEndTime
);
207 backend
.finishedBuilding(realEndTime
);
209 attributeTreeFile
= backend
.supplyAttributeTreeWriterFile();
210 attributeTreeFilePos
= backend
.supplyAttributeTreeWriterFilePosition();
211 if (attributeTreeFile
!= null) {
213 * If null was returned, we simply won't save the attribute tree,
216 getAttributeTree().writeSelf(attributeTreeFile
, attributeTreeFilePos
);
218 finishedLatch
.countDown(); /* Mark the history as finished building */
221 //--------------------------------------------------------------------------
222 // Quark-retrieving methods
223 //--------------------------------------------------------------------------
226 public int getQuarkAbsolute(String
... attribute
)
227 throws AttributeNotFoundException
{
228 return getAttributeTree().getQuarkDontAdd(-1, attribute
);
232 public int getQuarkAbsoluteAndAdd(String
... attribute
) {
233 return getAttributeTree().getQuarkAndAdd(-1, attribute
);
237 public int getQuarkRelative(int startingNodeQuark
, String
... subPath
)
238 throws AttributeNotFoundException
{
239 return getAttributeTree().getQuarkDontAdd(startingNodeQuark
, subPath
);
243 public int getQuarkRelativeAndAdd(int startingNodeQuark
, String
... subPath
) {
244 return getAttributeTree().getQuarkAndAdd(startingNodeQuark
, subPath
);
248 public List
<Integer
> getSubAttributes(int quark
, boolean recursive
)
249 throws AttributeNotFoundException
{
250 return getAttributeTree().getSubAttributes(quark
, recursive
);
254 public List
<Integer
> getQuarks(String
... pattern
) {
255 List
<Integer
> quarks
= new LinkedList
<>();
256 List
<String
> prefix
= new LinkedList
<>();
257 List
<String
> suffix
= new LinkedList
<>();
258 boolean split
= false;
261 List
<Integer
> directChildren
;
262 int startingAttribute
;
264 /* Fill the "prefix" and "suffix" parts of the pattern around the '*' */
265 for (String entry
: pattern
) {
266 if (entry
.equals("*")) { //$NON-NLS-1$
269 * Split was already true? This means there was more than
270 * one wildcard. This is not supported, return an empty
285 prefixStr
= prefix
.toArray(new String
[prefix
.size()]);
286 suffixStr
= suffix
.toArray(new String
[suffix
.size()]);
289 * If there was no wildcard, we'll only return the one matching
290 * attribute, if there is one.
295 quark
= getQuarkAbsolute(prefixStr
);
296 } catch (AttributeNotFoundException e
) {
297 /* It's fine, we'll just return the empty List */
305 if (prefix
.size() == 0) {
307 * If 'prefix' is empty, this means the wildcard was the first
308 * element. Look for the root node's sub-attributes.
310 startingAttribute
= -1;
312 startingAttribute
= getQuarkAbsolute(prefixStr
);
314 directChildren
= getSubAttributes(startingAttribute
, false);
315 } catch (AttributeNotFoundException e
) {
316 /* That attribute path did not exist, return the empty array */
321 * Iterate of all the sub-attributes, and only keep those who match the
322 * 'suffix' part of the initial pattern.
324 for (int childQuark
: directChildren
) {
327 matchingQuark
= getQuarkRelative(childQuark
, suffixStr
);
328 } catch (AttributeNotFoundException e
) {
331 quarks
.add(matchingQuark
);
337 //--------------------------------------------------------------------------
338 // Methods related to insertions in the history
339 //--------------------------------------------------------------------------
342 public void modifyAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
343 throws TimeRangeException
, AttributeNotFoundException
,
344 StateValueTypeException
{
345 transState
.processStateChange(t
, value
, attributeQuark
);
349 public void incrementAttribute(long t
, int attributeQuark
)
350 throws StateValueTypeException
, TimeRangeException
,
351 AttributeNotFoundException
{
352 ITmfStateValue stateValue
= queryOngoingState(attributeQuark
);
354 /* if the attribute was previously null, start counting at 0 */
355 if (!stateValue
.isNull()) {
356 prevValue
= stateValue
.unboxInt();
358 modifyAttribute(t
, TmfStateValue
.newValueInt(prevValue
+ 1),
363 public void pushAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
364 throws TimeRangeException
, AttributeNotFoundException
,
365 StateValueTypeException
{
367 int subAttributeQuark
;
368 ITmfStateValue previousSV
= transState
.getOngoingStateValue(attributeQuark
);
370 if (previousSV
.isNull()) {
372 * If the StateValue was null, this means this is the first time we
373 * use this attribute. Leave stackDepth at 0.
376 } else if (previousSV
.getType() == Type
.INTEGER
) {
377 /* Previous value was an integer, all is good, use it */
378 stackDepth
= previousSV
.unboxInt();
380 /* Previous state of this attribute was another type? Not good! */
381 throw new StateValueTypeException();
384 if (stackDepth
>= 100000) {
386 * Limit stackDepth to 100000, to avoid having Attribute Trees grow out
387 * of control due to buggy insertions
389 String message
= "Stack limit reached, not pushing"; //$NON-NLS-1$
390 throw new AttributeNotFoundException(message
);
394 subAttributeQuark
= getQuarkRelativeAndAdd(attributeQuark
, stackDepth
.toString());
396 modifyAttribute(t
, TmfStateValue
.newValueInt(stackDepth
), attributeQuark
);
397 modifyAttribute(t
, value
, subAttributeQuark
);
401 public ITmfStateValue
popAttribute(long t
, int attributeQuark
)
402 throws AttributeNotFoundException
, TimeRangeException
,
403 StateValueTypeException
{
404 /* These are the state values of the stack-attribute itself */
405 ITmfStateValue previousSV
= queryOngoingState(attributeQuark
);
407 if (previousSV
.isNull()) {
409 * Trying to pop an empty stack. This often happens at the start of
410 * traces, for example when we see a syscall_exit, without having
411 * the corresponding syscall_entry in the trace. Just ignore
416 if (previousSV
.getType() != Type
.INTEGER
) {
418 * The existing value was not an integer (which is expected for
419 * stack tops), this doesn't look like a valid stack attribute.
421 throw new StateValueTypeException();
424 Integer stackDepth
= previousSV
.unboxInt();
426 if (stackDepth
<= 0) {
427 /* This on the other hand should not happen... */
428 String message
= "A top-level stack attribute cannot " + //$NON-NLS-1$
429 "have a value of 0 or less."; //$NON-NLS-1$
430 throw new StateValueTypeException(message
);
433 /* The attribute should already exist at this point */
434 int subAttributeQuark
= getQuarkRelative(attributeQuark
, stackDepth
.toString());
435 ITmfStateValue poppedValue
= queryOngoingState(subAttributeQuark
);
437 /* Update the state value of the stack-attribute */
438 ITmfStateValue nextSV
;
439 if (--stackDepth
== 0 ) {
440 /* Store a null state value */
441 nextSV
= TmfStateValue
.nullValue();
443 nextSV
= TmfStateValue
.newValueInt(stackDepth
);
445 modifyAttribute(t
, nextSV
, attributeQuark
);
447 /* Delete the sub-attribute that contained the user's state value */
448 removeAttribute(t
, subAttributeQuark
);
454 public void removeAttribute(long t
, int attributeQuark
)
455 throws TimeRangeException
, AttributeNotFoundException
{
456 assert (attributeQuark
>= 0);
457 List
<Integer
> childAttributes
;
460 * "Nullify our children first, recursively. We pass 'false' because we
461 * handle the recursion ourselves.
463 childAttributes
= getSubAttributes(attributeQuark
, false);
464 for (Integer childNodeQuark
: childAttributes
) {
465 assert (attributeQuark
!= childNodeQuark
);
466 removeAttribute(t
, childNodeQuark
);
468 /* Nullify ourselves */
470 transState
.processStateChange(t
, TmfStateValue
.nullValue(),
472 } catch (StateValueTypeException e
) {
474 * Will not happen since we're inserting null values only, but poor
475 * compiler has no way of knowing this...
477 throw new IllegalStateException(e
);
481 //--------------------------------------------------------------------------
482 // "Current" query/update methods
483 //--------------------------------------------------------------------------
486 public ITmfStateValue
queryOngoingState(int attributeQuark
)
487 throws AttributeNotFoundException
{
488 return transState
.getOngoingStateValue(attributeQuark
);
492 public long getOngoingStartTime(int attribute
)
493 throws AttributeNotFoundException
{
494 return transState
.getOngoingStartTime(attribute
);
498 public void updateOngoingState(ITmfStateValue newValue
, int attributeQuark
)
499 throws AttributeNotFoundException
{
500 transState
.changeOngoingStateValue(attributeQuark
, newValue
);
504 * Modify the whole "ongoing state" (state values + start times). This can
505 * be used when "seeking" a state system to a different point in the trace
506 * (and restoring the known stateInfo at this location). Use with care!
508 * @param newStateIntervals
509 * The new List of state values to use as ongoing state info
511 protected void replaceOngoingState(List
<ITmfStateInterval
> newStateIntervals
) {
512 transState
.replaceOngoingState(newStateIntervals
);
515 //--------------------------------------------------------------------------
516 // Regular query methods (sent to the back-end)
517 //--------------------------------------------------------------------------
520 public synchronized List
<ITmfStateInterval
> queryFullState(long t
)
521 throws TimeRangeException
, StateSystemDisposedException
{
523 throw new StateSystemDisposedException();
526 List
<ITmfStateInterval
> stateInfo
= new ArrayList
<>(getNbAttributes());
528 /* Bring the size of the array to the current number of attributes */
529 for (int i
= 0; i
< getNbAttributes(); i
++) {
533 /* Query the storage backend */
534 backend
.doQuery(stateInfo
, t
);
537 * If we are currently building the history, also query the "ongoing"
538 * states for stuff that might not yet be written to the history.
540 if (transState
.isActive()) {
541 transState
.doQuery(stateInfo
, t
);
545 * We should have previously inserted an interval for every attribute.
546 * If we do happen do see a 'null' object here, just replace it with a a
547 * dummy internal with a null value, to avoid NPE's further up.
549 for (int i
= 0; i
< stateInfo
.size(); i
++) {
550 if (stateInfo
.get(i
) == null) {
551 stateInfo
.set(i
, new TmfStateInterval(t
, t
, i
, TmfStateValue
.nullValue()));
558 public ITmfStateInterval
querySingleState(long t
, int attributeQuark
)
559 throws AttributeNotFoundException
, TimeRangeException
,
560 StateSystemDisposedException
{
562 throw new StateSystemDisposedException();
565 ITmfStateInterval ret
= transState
.getIntervalAt(t
, attributeQuark
);
568 * The transient state did not have the information, let's look into
571 ret
= backend
.doSingularQuery(t
, attributeQuark
);
575 * Return a fake interval if we could not find anything in the history.
576 * We do NOT want to return 'null' here.
579 return new TmfStateInterval(t
, this.getCurrentEndTime(),
580 attributeQuark
, TmfStateValue
.nullValue());
586 public ITmfStateInterval
querySingleStackTop(long t
, int stackAttributeQuark
)
587 throws StateValueTypeException
, AttributeNotFoundException
,
588 TimeRangeException
, StateSystemDisposedException
{
589 ITmfStateValue curStackStateValue
= querySingleState(t
, stackAttributeQuark
).getStateValue();
591 if (curStackStateValue
.isNull()) {
592 /* There is nothing stored in this stack at this moment */
595 Integer curStackDepth
= curStackStateValue
.unboxInt();
596 if (curStackDepth
<= 0) {
598 * This attribute is an integer attribute, but it doesn't seem like
599 * it's used as a stack-attribute...
601 throw new StateValueTypeException();
604 int subAttribQuark
= getQuarkRelative(stackAttributeQuark
, curStackDepth
.toString());
605 return querySingleState(t
, subAttribQuark
);
609 public List
<ITmfStateInterval
> queryHistoryRange(int attributeQuark
,
610 long t1
, long t2
) throws TimeRangeException
,
611 AttributeNotFoundException
, StateSystemDisposedException
{
613 throw new StateSystemDisposedException();
616 List
<ITmfStateInterval
> intervals
;
617 ITmfStateInterval currentInterval
;
620 /* Make sure the time range makes sense */
622 throw new TimeRangeException();
625 /* Set the actual, valid end time of the range query */
626 if (t2
> this.getCurrentEndTime()) {
627 tEnd
= this.getCurrentEndTime();
632 /* Get the initial state at time T1 */
633 intervals
= new ArrayList
<>();
634 currentInterval
= querySingleState(t1
, attributeQuark
);
635 intervals
.add(currentInterval
);
637 /* Get the following state changes */
638 ts
= currentInterval
.getEndTime();
639 while (ts
!= -1 && ts
< tEnd
) {
640 ts
++; /* To "jump over" to the next state in the history */
641 currentInterval
= querySingleState(ts
, attributeQuark
);
642 intervals
.add(currentInterval
);
643 ts
= currentInterval
.getEndTime();
649 public List
<ITmfStateInterval
> queryHistoryRange(int attributeQuark
,
650 long t1
, long t2
, long resolution
, IProgressMonitor monitor
)
651 throws TimeRangeException
, AttributeNotFoundException
,
652 StateSystemDisposedException
{
654 throw new StateSystemDisposedException();
657 List
<ITmfStateInterval
> intervals
;
658 ITmfStateInterval currentInterval
;
661 IProgressMonitor mon
= monitor
;
663 mon
= new NullProgressMonitor();
666 /* Make sure the time range makes sense */
667 if (t2
< t1
|| resolution
<= 0) {
668 throw new TimeRangeException();
671 /* Set the actual, valid end time of the range query */
672 if (t2
> this.getCurrentEndTime()) {
673 tEnd
= this.getCurrentEndTime();
678 /* Get the initial state at time T1 */
679 intervals
= new ArrayList
<>();
680 currentInterval
= querySingleState(t1
, attributeQuark
);
681 intervals
.add(currentInterval
);
684 * Iterate over the "resolution points". We skip unneeded queries in the
685 * case the current interval is longer than the resolution.
687 for (ts
= t1
; (currentInterval
.getEndTime() != -1) && (ts
< tEnd
);
689 if (mon
.isCanceled()) {
692 if (ts
<= currentInterval
.getEndTime()) {
695 currentInterval
= querySingleState(ts
, attributeQuark
);
696 intervals
.add(currentInterval
);
699 /* Add the interval at t2, if it wasn't included already. */
700 if (currentInterval
.getEndTime() < tEnd
) {
701 currentInterval
= querySingleState(tEnd
, attributeQuark
);
702 intervals
.add(currentInterval
);
707 //--------------------------------------------------------------------------
709 //--------------------------------------------------------------------------
711 static void logMissingInterval(int attribute
, long timestamp
) {
712 Activator
.logInfo("No data found in history for attribute " + //$NON-NLS-1$
713 attribute
+ " at time " + timestamp
+ //$NON-NLS-1$
714 ", returning dummy interval"); //$NON-NLS-1$
718 * Print out the contents of the inner structures.
721 * The PrintWriter in which to print the output
723 public void debugPrint(PrintWriter writer
) {
724 getAttributeTree().debugPrint(writer
);
725 transState
.debugPrint(writer
);
726 backend
.debugPrint(writer
);