1 /*******************************************************************************
2 * Copyright (c) 2012, 2015 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
12 * Alexandre Montplaisir - Initial API and implementation
13 * Patrick Tasse - Add message to exceptions
14 *******************************************************************************/
16 package org
.eclipse
.tracecompass
.internal
.statesystem
.core
;
19 import java
.io
.IOException
;
20 import java
.io
.PrintWriter
;
21 import java
.util
.ArrayList
;
22 import java
.util
.LinkedList
;
23 import java
.util
.List
;
24 import java
.util
.concurrent
.CountDownLatch
;
25 import java
.util
.concurrent
.TimeUnit
;
27 import org
.eclipse
.jdt
.annotation
.NonNull
;
28 import org
.eclipse
.tracecompass
.statesystem
.core
.ITmfStateSystemBuilder
;
29 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.IStateHistoryBackend
;
30 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.AttributeNotFoundException
;
31 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.StateSystemDisposedException
;
32 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.StateValueTypeException
;
33 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.TimeRangeException
;
34 import org
.eclipse
.tracecompass
.statesystem
.core
.interval
.ITmfStateInterval
;
35 import org
.eclipse
.tracecompass
.statesystem
.core
.statevalue
.ITmfStateValue
;
36 import org
.eclipse
.tracecompass
.statesystem
.core
.statevalue
.ITmfStateValue
.Type
;
37 import org
.eclipse
.tracecompass
.statesystem
.core
.statevalue
.TmfStateValue
;
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 /* References to the inner structures */
55 private final AttributeTree attributeTree
;
56 private final TransientState transState
;
57 private final IStateHistoryBackend backend
;
59 /* Latch tracking if the state history is done building or not */
60 private final CountDownLatch finishedLatch
= new CountDownLatch(1);
62 private boolean buildCancelled
= false;
63 private boolean isDisposed
= false;
66 * New-file constructor. For when you build a state system with a new file,
67 * or if the back-end does not require a file on disk.
70 * Back-end plugin to use
72 public StateSystem(@NonNull IStateHistoryBackend backend
) {
73 this.backend
= backend
;
74 this.transState
= new TransientState(backend
);
75 this.attributeTree
= new AttributeTree(this);
82 * The "state history storage" back-end to use.
84 * Put true if this is a new history started from scratch. It is
85 * used to tell the state system where to get its attribute tree.
87 * If there was a problem creating the new history file
89 public StateSystem(@NonNull IStateHistoryBackend backend
, boolean newFile
)
91 this.backend
= backend
;
92 this.transState
= new TransientState(backend
);
95 attributeTree
= new AttributeTree(this);
97 /* We're opening an existing file */
98 this.attributeTree
= new AttributeTree(this, backend
.supplyAttributeTreeReader());
99 transState
.setInactive();
100 finishedLatch
.countDown(); /* The history is already built */
105 public String
getSSID() {
106 return backend
.getSSID();
110 public boolean isCancelled() {
111 return buildCancelled
;
115 public void waitUntilBuilt() {
117 finishedLatch
.await();
118 } catch (InterruptedException e
) {
124 public boolean waitUntilBuilt(long timeout
) {
127 ret
= finishedLatch
.await(timeout
, TimeUnit
.MILLISECONDS
);
128 } catch (InterruptedException e
) {
135 public synchronized void dispose() {
137 if (transState
.isActive()) {
138 transState
.setInactive();
139 buildCancelled
= true;
144 //--------------------------------------------------------------------------
145 // General methods related to the attribute tree
146 //--------------------------------------------------------------------------
149 * Get the attribute tree associated with this state system. This should be
150 * the only way of accessing it (and if subclasses want to point to a
151 * different attribute tree than their own, they should only need to
154 * @return The attribute tree
156 public AttributeTree
getAttributeTree() {
157 return attributeTree
;
161 * Method used by the attribute tree when creating new attributes, to keep
162 * the attribute count in the transient state in sync.
164 public void addEmptyAttribute() {
165 transState
.addEmptyEntry();
169 public int getNbAttributes() {
170 return getAttributeTree().getNbAttributes();
174 public String
getAttributeName(int attributeQuark
) {
175 return getAttributeTree().getAttributeName(attributeQuark
);
179 public String
getFullAttributePath(int attributeQuark
) {
180 return getAttributeTree().getFullAttributeName(attributeQuark
);
183 //--------------------------------------------------------------------------
184 // Methods related to the storage backend
185 //--------------------------------------------------------------------------
188 public long getStartTime() {
189 return backend
.getStartTime();
193 public long getCurrentEndTime() {
194 return backend
.getEndTime();
198 public void closeHistory(long endTime
) throws TimeRangeException
{
199 File attributeTreeFile
;
200 long attributeTreeFilePos
;
201 long realEndTime
= endTime
;
203 if (realEndTime
< backend
.getEndTime()) {
205 * This can happen (empty nodes pushing the border further, etc.)
206 * but shouldn't be too big of a deal.
208 realEndTime
= backend
.getEndTime();
210 transState
.closeTransientState(realEndTime
);
211 backend
.finishedBuilding(realEndTime
);
213 attributeTreeFile
= backend
.supplyAttributeTreeWriterFile();
214 attributeTreeFilePos
= backend
.supplyAttributeTreeWriterFilePosition();
215 if (attributeTreeFile
!= null) {
217 * If null was returned, we simply won't save the attribute tree,
220 getAttributeTree().writeSelf(attributeTreeFile
, attributeTreeFilePos
);
222 finishedLatch
.countDown(); /* Mark the history as finished building */
225 //--------------------------------------------------------------------------
226 // Quark-retrieving methods
227 //--------------------------------------------------------------------------
230 public int getQuarkAbsolute(String
... attribute
)
231 throws AttributeNotFoundException
{
232 return getAttributeTree().getQuarkDontAdd(-1, attribute
);
236 public int getQuarkAbsoluteAndAdd(String
... attribute
) {
237 return getAttributeTree().getQuarkAndAdd(-1, attribute
);
241 public int getQuarkRelative(int startingNodeQuark
, String
... subPath
)
242 throws AttributeNotFoundException
{
243 return getAttributeTree().getQuarkDontAdd(startingNodeQuark
, subPath
);
247 public int getQuarkRelativeAndAdd(int startingNodeQuark
, String
... subPath
) {
248 return getAttributeTree().getQuarkAndAdd(startingNodeQuark
, subPath
);
252 public List
<Integer
> getSubAttributes(int quark
, boolean recursive
)
253 throws AttributeNotFoundException
{
254 return getAttributeTree().getSubAttributes(quark
, recursive
);
258 public List
<Integer
> getSubAttributes(int quark
, boolean recursive
, String pattern
)
259 throws AttributeNotFoundException
{
260 List
<Integer
> all
= getSubAttributes(quark
, recursive
);
261 List
<Integer
> ret
= new LinkedList
<>();
262 for (Integer attQuark
: all
) {
263 String name
= getAttributeName(attQuark
.intValue());
264 if (name
.matches(pattern
)) {
272 public int getParentAttributeQuark(int quark
) {
273 return getAttributeTree().getParentAttributeQuark(quark
);
277 public List
<Integer
> getQuarks(String
... pattern
) {
278 List
<Integer
> quarks
= new LinkedList
<>();
279 List
<String
> prefix
= new LinkedList
<>();
280 List
<String
> suffix
= new LinkedList
<>();
281 boolean split
= false;
284 List
<Integer
> directChildren
;
285 int startingAttribute
;
287 /* Fill the "prefix" and "suffix" parts of the pattern around the '*' */
288 for (String entry
: pattern
) {
289 if (entry
.equals("*")) { //$NON-NLS-1$
292 * Split was already true? This means there was more than
293 * one wildcard. This is not supported, return an empty
308 prefixStr
= prefix
.toArray(new String
[prefix
.size()]);
309 suffixStr
= suffix
.toArray(new String
[suffix
.size()]);
312 * If there was no wildcard, we'll only return the one matching
313 * attribute, if there is one.
318 quark
= getQuarkAbsolute(prefixStr
);
319 } catch (AttributeNotFoundException e
) {
320 /* It's fine, we'll just return the empty List */
328 if (prefix
.size() == 0) {
330 * If 'prefix' is empty, this means the wildcard was the first
331 * element. Look for the root node's sub-attributes.
333 startingAttribute
= -1;
335 startingAttribute
= getQuarkAbsolute(prefixStr
);
337 directChildren
= getSubAttributes(startingAttribute
, false);
338 } catch (AttributeNotFoundException e
) {
339 /* That attribute path did not exist, return the empty array */
344 * Iterate of all the sub-attributes, and only keep those who match the
345 * 'suffix' part of the initial pattern.
347 for (int childQuark
: directChildren
) {
350 matchingQuark
= getQuarkRelative(childQuark
, suffixStr
);
351 } catch (AttributeNotFoundException e
) {
354 quarks
.add(matchingQuark
);
360 //--------------------------------------------------------------------------
361 // Methods related to insertions in the history
362 //--------------------------------------------------------------------------
365 public void modifyAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
366 throws TimeRangeException
, AttributeNotFoundException
,
367 StateValueTypeException
{
370 * TODO Replace with @NonNull parameter (will require fixing all the
373 throw new IllegalArgumentException();
375 transState
.processStateChange(t
, value
, attributeQuark
);
379 public void incrementAttribute(long t
, int attributeQuark
)
380 throws StateValueTypeException
, TimeRangeException
,
381 AttributeNotFoundException
{
382 ITmfStateValue stateValue
= queryOngoingState(attributeQuark
);
384 /* if the attribute was previously null, start counting at 0 */
385 if (!stateValue
.isNull()) {
386 prevValue
= stateValue
.unboxInt();
388 modifyAttribute(t
, TmfStateValue
.newValueInt(prevValue
+ 1),
393 public void pushAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
394 throws TimeRangeException
, AttributeNotFoundException
,
395 StateValueTypeException
{
397 int subAttributeQuark
;
398 ITmfStateValue previousSV
= transState
.getOngoingStateValue(attributeQuark
);
400 if (previousSV
.isNull()) {
402 * If the StateValue was null, this means this is the first time we
403 * use this attribute. Leave stackDepth at 0.
406 } else if (previousSV
.getType() == Type
.INTEGER
) {
407 /* Previous value was an integer, all is good, use it */
408 stackDepth
= previousSV
.unboxInt();
410 /* Previous state of this attribute was another type? Not good! */
411 throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark
+ ", Type:" + previousSV
.getType() + ", Expected:" + Type
.INTEGER
); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
414 if (stackDepth
>= 100000) {
416 * Limit stackDepth to 100000, to avoid having Attribute Trees grow
417 * out of control due to buggy insertions
419 String message
= " Stack limit reached, not pushing"; //$NON-NLS-1$
420 throw new AttributeNotFoundException(getSSID() + " Quark:" + attributeQuark
+ message
); //$NON-NLS-1$
424 subAttributeQuark
= getQuarkRelativeAndAdd(attributeQuark
, String
.valueOf(stackDepth
));
426 modifyAttribute(t
, TmfStateValue
.newValueInt(stackDepth
), attributeQuark
);
427 modifyAttribute(t
, value
, subAttributeQuark
);
431 public ITmfStateValue
popAttribute(long t
, int attributeQuark
)
432 throws AttributeNotFoundException
, TimeRangeException
,
433 StateValueTypeException
{
434 /* These are the state values of the stack-attribute itself */
435 ITmfStateValue previousSV
= transState
.getOngoingStateValue(attributeQuark
);
437 if (previousSV
.isNull()) {
439 * Trying to pop an empty stack. This often happens at the start of
440 * traces, for example when we see a syscall_exit, without having
441 * the corresponding syscall_entry in the trace. Just ignore
446 if (previousSV
.getType() != Type
.INTEGER
) {
448 * The existing value was not an integer (which is expected for
449 * stack tops), this doesn't look like a valid stack attribute.
451 throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark
+ ", Type:" + previousSV
.getType() + ", Expected:" + Type
.INTEGER
); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
454 int stackDepth
= previousSV
.unboxInt();
456 if (stackDepth
<= 0) {
457 /* This on the other hand should not happen... */
458 throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark
+ ", Stack depth:" + stackDepth
); //$NON-NLS-1$//$NON-NLS-2$
461 /* The attribute should already exist at this point */
462 int subAttributeQuark
= getQuarkRelative(attributeQuark
, String
.valueOf(stackDepth
));
463 ITmfStateValue poppedValue
= queryOngoingState(subAttributeQuark
);
465 /* Update the state value of the stack-attribute */
466 ITmfStateValue nextSV
;
467 if (--stackDepth
== 0) {
468 /* Store a null state value */
469 nextSV
= TmfStateValue
.nullValue();
471 nextSV
= TmfStateValue
.newValueInt(stackDepth
);
473 modifyAttribute(t
, nextSV
, attributeQuark
);
475 /* Delete the sub-attribute that contained the user's state value */
476 removeAttribute(t
, subAttributeQuark
);
482 public void removeAttribute(long t
, int attributeQuark
)
483 throws TimeRangeException
, AttributeNotFoundException
{
484 if (attributeQuark
< 0) {
485 throw new IllegalArgumentException();
489 * Nullify our children first, recursively. We pass 'false' because we
490 * handle the recursion ourselves.
492 List
<Integer
> childAttributes
= getSubAttributes(attributeQuark
, false);
493 for (int childNodeQuark
: childAttributes
) {
494 if (attributeQuark
== childNodeQuark
) {
495 /* Something went very wrong when building out attribute tree */
496 throw new IllegalStateException();
498 removeAttribute(t
, childNodeQuark
);
500 /* Nullify ourselves */
502 transState
.processStateChange(t
, TmfStateValue
.nullValue(), attributeQuark
);
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(@NonNull 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 final int nbAttr
= getNbAttributes();
558 List
<ITmfStateInterval
> stateInfo
= new ArrayList
<>(nbAttr
);
560 /* Bring the size of the array to the current number of attributes */
561 for (int i
= 0; i
< nbAttr
; i
++) {
566 * If we are currently building the history, also query the "ongoing"
567 * states for stuff that might not yet be written to the history.
569 if (transState
.isActive()) {
570 transState
.doQuery(stateInfo
, t
);
573 /* Query the storage backend */
574 backend
.doQuery(stateInfo
, t
);
577 * We should have previously inserted an interval for every attribute.
579 for (ITmfStateInterval interval
: stateInfo
) {
580 if (interval
== null) {
581 throw new IllegalStateException("Incoherent interval storage"); //$NON-NLS-1$
588 public ITmfStateInterval
querySingleState(long t
, int attributeQuark
)
589 throws AttributeNotFoundException
, TimeRangeException
,
590 StateSystemDisposedException
{
592 throw new StateSystemDisposedException();
595 ITmfStateInterval ret
= transState
.getIntervalAt(t
, attributeQuark
);
598 * The transient state did not have the information, let's look into
601 ret
= backend
.doSingularQuery(t
, attributeQuark
);
606 * If we did our job correctly, there should be intervals for every
607 * possible attribute, over all the valid time range.
609 throw new IllegalStateException("Incoherent interval storage"); //$NON-NLS-1$
614 //--------------------------------------------------------------------------
616 //--------------------------------------------------------------------------
618 static void logMissingInterval(int attribute
, long timestamp
) {
619 Activator
.getDefault().logInfo("No data found in history for attribute " + //$NON-NLS-1$
620 attribute
+ " at time " + timestamp
+ //$NON-NLS-1$
621 ", returning dummy interval"); //$NON-NLS-1$
625 * Print out the contents of the inner structures.
628 * The PrintWriter in which to print the output
630 public void debugPrint(@NonNull PrintWriter writer
) {
631 getAttributeTree().debugPrint(writer
);
632 transState
.debugPrint(writer
);
633 backend
.debugPrint(writer
);