1 /*******************************************************************************
2 * Copyright (c) 2012, 2016 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
.Arrays
;
23 import java
.util
.LinkedList
;
24 import java
.util
.List
;
25 import java
.util
.concurrent
.CountDownLatch
;
26 import java
.util
.concurrent
.TimeUnit
;
28 import org
.eclipse
.jdt
.annotation
.NonNull
;
29 import org
.eclipse
.jdt
.annotation
.Nullable
;
30 import org
.eclipse
.tracecompass
.statesystem
.core
.ITmfStateSystemBuilder
;
31 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.IStateHistoryBackend
;
32 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.AttributeNotFoundException
;
33 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.StateSystemDisposedException
;
34 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.StateValueTypeException
;
35 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.TimeRangeException
;
36 import org
.eclipse
.tracecompass
.statesystem
.core
.interval
.ITmfStateInterval
;
37 import org
.eclipse
.tracecompass
.statesystem
.core
.statevalue
.ITmfStateValue
;
38 import org
.eclipse
.tracecompass
.statesystem
.core
.statevalue
.ITmfStateValue
.Type
;
39 import org
.eclipse
.tracecompass
.statesystem
.core
.statevalue
.TmfStateValue
;
41 import com
.google
.common
.collect
.ImmutableCollection
.Builder
;
42 import com
.google
.common
.collect
.ImmutableSet
;
45 * This is the core class of the Generic State System. It contains all the
46 * methods to build and query a state history. It's exposed externally through
47 * the IStateSystemQuerier and IStateSystemBuilder interfaces, depending if the
48 * user needs read-only access or read-write access.
50 * When building, DON'T FORGET to call .closeHistory() when you are done
51 * inserting intervals, or the storage backend will have no way of knowing it
52 * can close and write itself to disk, and its thread will keep running.
57 public class StateSystem
implements ITmfStateSystemBuilder
{
59 private static final String PARENT
= ".."; //$NON-NLS-1$
60 private static final String WILDCARD
= "*"; //$NON-NLS-1$
62 /* References to the inner structures */
63 private final AttributeTree attributeTree
;
64 private final TransientState transState
;
65 private final IStateHistoryBackend backend
;
67 /* Latch tracking if the state history is done building or not */
68 private final CountDownLatch finishedLatch
= new CountDownLatch(1);
70 private boolean buildCancelled
= false;
71 private boolean isDisposed
= false;
74 * New-file constructor. For when you build a state system with a new file,
75 * or if the back-end does not require a file on disk.
78 * Back-end plugin to use
80 public StateSystem(@NonNull IStateHistoryBackend backend
) {
81 this.backend
= backend
;
82 this.transState
= new TransientState(backend
);
83 this.attributeTree
= new AttributeTree(this);
90 * The "state history storage" back-end to use.
92 * Put true if this is a new history started from scratch. It is
93 * used to tell the state system where to get its attribute tree.
95 * If there was a problem creating the new history file
97 public StateSystem(@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() {
114 return backend
.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
);
192 public String
[] getFullAttributePathArray(int attributeQuark
) {
193 return getAttributeTree().getFullAttributePathArray(attributeQuark
);
196 //--------------------------------------------------------------------------
197 // Methods related to the storage backend
198 //--------------------------------------------------------------------------
201 public long getStartTime() {
202 return backend
.getStartTime();
206 public long getCurrentEndTime() {
207 return backend
.getEndTime();
211 public void closeHistory(long endTime
) throws TimeRangeException
{
212 File attributeTreeFile
;
213 long attributeTreeFilePos
;
214 long realEndTime
= endTime
;
216 if (realEndTime
< backend
.getEndTime()) {
218 * This can happen (empty nodes pushing the border further, etc.)
219 * but shouldn't be too big of a deal.
221 realEndTime
= backend
.getEndTime();
223 transState
.closeTransientState(realEndTime
);
224 backend
.finishedBuilding(realEndTime
);
226 attributeTreeFile
= backend
.supplyAttributeTreeWriterFile();
227 attributeTreeFilePos
= backend
.supplyAttributeTreeWriterFilePosition();
228 if (attributeTreeFile
!= null) {
230 * If null was returned, we simply won't save the attribute tree,
233 getAttributeTree().writeSelf(attributeTreeFile
, attributeTreeFilePos
);
235 finishedLatch
.countDown(); /* Mark the history as finished building */
238 //--------------------------------------------------------------------------
239 // Quark-retrieving methods
240 //--------------------------------------------------------------------------
243 public int getQuarkAbsolute(String
... attribute
)
244 throws AttributeNotFoundException
{
245 int quark
= getAttributeTree().getQuarkDontAdd(ROOT_ATTRIBUTE
, attribute
);
246 if (quark
== INVALID_ATTRIBUTE
) {
247 throw new AttributeNotFoundException(getSSID() + " Path:" + Arrays
.toString(attribute
)); //$NON-NLS-1$
253 public int optQuarkAbsolute(String
... attribute
) {
254 return getAttributeTree().getQuarkDontAdd(ROOT_ATTRIBUTE
, attribute
);
258 public int getQuarkAbsoluteAndAdd(String
... attribute
) {
259 return getAttributeTree().getQuarkAndAdd(ROOT_ATTRIBUTE
, attribute
);
263 public int getQuarkRelative(int startingNodeQuark
, String
... subPath
)
264 throws AttributeNotFoundException
{
265 int quark
= getAttributeTree().getQuarkDontAdd(startingNodeQuark
, subPath
);
266 if (quark
== INVALID_ATTRIBUTE
) {
267 throw new AttributeNotFoundException(getSSID() + " Quark:" + startingNodeQuark
+ ", SubPath:" + Arrays
.toString(subPath
)); //$NON-NLS-1$ //$NON-NLS-2$
273 public int optQuarkRelative(int startingNodeQuark
, String
... subPath
) {
274 return getAttributeTree().getQuarkDontAdd(startingNodeQuark
, subPath
);
278 public int getQuarkRelativeAndAdd(int startingNodeQuark
, String
... subPath
) {
279 return getAttributeTree().getQuarkAndAdd(startingNodeQuark
, subPath
);
283 public List
<@NonNull Integer
> getSubAttributes(int quark
, boolean recursive
) {
284 return getAttributeTree().getSubAttributes(quark
, recursive
);
288 public List
<@NonNull Integer
> getSubAttributes(int quark
, boolean recursive
, String pattern
) {
289 List
<Integer
> all
= getSubAttributes(quark
, recursive
);
290 List
<@NonNull Integer
> ret
= new LinkedList
<>();
291 for (Integer attQuark
: all
) {
292 String name
= getAttributeName(attQuark
.intValue());
293 if (name
.matches(pattern
)) {
301 public int getParentAttributeQuark(int quark
) {
302 return getAttributeTree().getParentAttributeQuark(quark
);
306 public List
<@NonNull Integer
> getQuarks(String
... pattern
) {
307 return getQuarks(ROOT_ATTRIBUTE
, pattern
);
311 public List
<@NonNull Integer
> getQuarks(int startingNodeQuark
, String
... pattern
) {
312 Builder
<@NonNull Integer
> builder
= ImmutableSet
.builder();
313 if (pattern
.length
> 0) {
314 getQuarks(builder
, startingNodeQuark
, Arrays
.asList(pattern
));
316 builder
.add(startingNodeQuark
);
318 return builder
.build().asList();
321 private void getQuarks(Builder
<@NonNull Integer
> builder
, int quark
, List
<String
> pattern
) {
322 String element
= pattern
.get(0);
323 if (element
== null) {
326 List
<String
> remainder
= pattern
.subList(1, pattern
.size());
327 if (remainder
.isEmpty()) {
328 if (element
.equals(WILDCARD
)) {
329 builder
.addAll(getSubAttributes(quark
, false));
330 } else if (element
.equals(PARENT
)){
331 builder
.add(getParentAttributeQuark(quark
));
333 int subQuark
= optQuarkRelative(quark
, element
);
334 if (subQuark
!= INVALID_ATTRIBUTE
) {
335 builder
.add(subQuark
);
339 if (element
.equals(WILDCARD
)) {
340 for (@NonNull Integer subquark
: getSubAttributes(quark
, false)) {
341 getQuarks(builder
, subquark
, remainder
);
343 } else if (element
.equals(PARENT
)){
344 getQuarks(builder
, getParentAttributeQuark(quark
), remainder
);
346 int subQuark
= optQuarkRelative(quark
, element
);
347 if (subQuark
!= INVALID_ATTRIBUTE
) {
348 getQuarks(builder
, subQuark
, remainder
);
354 //--------------------------------------------------------------------------
355 // Methods related to insertions in the history
356 //--------------------------------------------------------------------------
359 public void modifyAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
360 throws TimeRangeException
, StateValueTypeException
{
363 * TODO Replace with @NonNull parameter (will require fixing all the
366 throw new IllegalArgumentException();
368 transState
.processStateChange(t
, value
, attributeQuark
);
373 public void incrementAttribute(long t
, int attributeQuark
)
374 throws StateValueTypeException
, TimeRangeException
{
375 ITmfStateValue stateValue
= queryOngoingState(attributeQuark
);
377 /* if the attribute was previously null, start counting at 0 */
378 if (!stateValue
.isNull()) {
379 prevValue
= stateValue
.unboxInt();
381 modifyAttribute(t
, TmfStateValue
.newValueInt(prevValue
+ 1),
386 public void pushAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
387 throws TimeRangeException
, StateValueTypeException
{
389 int subAttributeQuark
;
390 ITmfStateValue previousSV
= transState
.getOngoingStateValue(attributeQuark
);
392 if (previousSV
.isNull()) {
394 * If the StateValue was null, this means this is the first time we
395 * use this attribute. Leave stackDepth at 0.
398 } else if (previousSV
.getType() == Type
.INTEGER
) {
399 /* Previous value was an integer, all is good, use it */
400 stackDepth
= previousSV
.unboxInt();
402 /* Previous state of this attribute was another type? Not good! */
403 throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark
+ ", Type:" + previousSV
.getType() + ", Expected:" + Type
.INTEGER
); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
406 if (stackDepth
>= 100000) {
408 * Limit stackDepth to 100000, to avoid having Attribute Trees grow
409 * out of control due to buggy insertions
411 String message
= " Stack limit reached, not pushing"; //$NON-NLS-1$
412 throw new IllegalStateException(getSSID() + " Quark:" + attributeQuark
+ message
); //$NON-NLS-1$
416 subAttributeQuark
= getQuarkRelativeAndAdd(attributeQuark
, String
.valueOf(stackDepth
));
418 modifyAttribute(t
, TmfStateValue
.newValueInt(stackDepth
), attributeQuark
);
419 modifyAttribute(t
, value
, subAttributeQuark
);
423 public ITmfStateValue
popAttribute(long t
, int attributeQuark
)
424 throws TimeRangeException
, StateValueTypeException
{
425 /* These are the state values of the stack-attribute itself */
426 ITmfStateValue previousSV
= transState
.getOngoingStateValue(attributeQuark
);
428 if (previousSV
.isNull()) {
430 * Trying to pop an empty stack. This often happens at the start of
431 * traces, for example when we see a syscall_exit, without having
432 * the corresponding syscall_entry in the trace. Just ignore
437 if (previousSV
.getType() != Type
.INTEGER
) {
439 * The existing value was not an integer (which is expected for
440 * stack tops), this doesn't look like a valid stack attribute.
442 throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark
+ ", Type:" + previousSV
.getType() + ", Expected:" + Type
.INTEGER
); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
445 int stackDepth
= previousSV
.unboxInt();
447 if (stackDepth
<= 0) {
448 /* This on the other hand should not happen... */
449 throw new StateValueTypeException(getSSID() + " Quark:" + attributeQuark
+ ", Stack depth:" + stackDepth
); //$NON-NLS-1$//$NON-NLS-2$
452 /* The attribute should already exist at this point */
453 int subAttributeQuark
;
455 subAttributeQuark
= getQuarkRelative(attributeQuark
, String
.valueOf(stackDepth
));
456 } catch (AttributeNotFoundException e
) {
457 String message
= " Stack attribute missing sub-attribute for depth:" + stackDepth
; //$NON-NLS-1$
458 throw new IllegalStateException(getSSID() + " Quark:" + attributeQuark
+ message
); //$NON-NLS-1$
460 ITmfStateValue poppedValue
= queryOngoingState(subAttributeQuark
);
462 /* Update the state value of the stack-attribute */
463 ITmfStateValue nextSV
;
464 if (--stackDepth
== 0) {
465 /* Store a null state value */
466 nextSV
= TmfStateValue
.nullValue();
468 nextSV
= TmfStateValue
.newValueInt(stackDepth
);
470 modifyAttribute(t
, nextSV
, attributeQuark
);
472 /* Delete the sub-attribute that contained the user's state value */
473 removeAttribute(t
, subAttributeQuark
);
479 public void removeAttribute(long t
, int attributeQuark
)
480 throws TimeRangeException
{
482 * Nullify our children first, recursively. We pass 'false' because we
483 * handle the recursion ourselves.
485 List
<Integer
> childAttributes
= getSubAttributes(attributeQuark
, false);
486 for (int childNodeQuark
: childAttributes
) {
487 if (attributeQuark
== childNodeQuark
) {
488 /* Something went very wrong when building out attribute tree */
489 throw new IllegalStateException();
491 removeAttribute(t
, childNodeQuark
);
493 /* Nullify ourselves */
495 transState
.processStateChange(t
, TmfStateValue
.nullValue(), attributeQuark
);
496 } catch (StateValueTypeException e
) {
498 * Will not happen since we're inserting null values only, but poor
499 * compiler has no way of knowing this...
501 throw new IllegalStateException(e
);
505 //--------------------------------------------------------------------------
506 // "Current" query/update methods
507 //--------------------------------------------------------------------------
510 public ITmfStateValue
queryOngoingState(int attributeQuark
) {
511 return transState
.getOngoingStateValue(attributeQuark
);
515 public long getOngoingStartTime(int attribute
) {
516 return transState
.getOngoingStartTime(attribute
);
520 public void updateOngoingState(ITmfStateValue newValue
, int attributeQuark
) {
521 transState
.changeOngoingStateValue(attributeQuark
, newValue
);
525 * Modify the whole "ongoing state" (state values + start times). This can
526 * be used when "seeking" a state system to a different point in the trace
527 * (and restoring the known stateInfo at this location). Use with care!
529 * @param newStateIntervals
530 * The new List of state values to use as ongoing state info
532 protected void replaceOngoingState(@NonNull List
<@NonNull ITmfStateInterval
> newStateIntervals
) {
533 transState
.replaceOngoingState(newStateIntervals
);
536 //--------------------------------------------------------------------------
537 // Regular query methods (sent to the back-end)
538 //--------------------------------------------------------------------------
541 public synchronized List
<ITmfStateInterval
> queryFullState(long t
)
542 throws TimeRangeException
, StateSystemDisposedException
{
544 throw new StateSystemDisposedException();
547 final int nbAttr
= getNbAttributes();
548 List
<@Nullable ITmfStateInterval
> stateInfo
= new ArrayList
<>(nbAttr
);
550 /* Bring the size of the array to the current number of attributes */
551 for (int i
= 0; i
< nbAttr
; i
++) {
556 * If we are currently building the history, also query the "ongoing"
557 * states for stuff that might not yet be written to the history.
559 if (transState
.isActive()) {
560 transState
.doQuery(stateInfo
, t
);
563 /* Query the storage backend */
564 backend
.doQuery(stateInfo
, t
);
567 * We should have previously inserted an interval for every attribute.
569 for (ITmfStateInterval interval
: stateInfo
) {
570 if (interval
== null) {
571 throw new IllegalStateException("Incoherent interval storage"); //$NON-NLS-1$
578 public ITmfStateInterval
querySingleState(long t
, int attributeQuark
)
579 throws TimeRangeException
, StateSystemDisposedException
{
581 throw new StateSystemDisposedException();
584 ITmfStateInterval ret
= transState
.getIntervalAt(t
, attributeQuark
);
587 * The transient state did not have the information, let's look into
590 ret
= backend
.doSingularQuery(t
, attributeQuark
);
595 * If we did our job correctly, there should be intervals for every
596 * possible attribute, over all the valid time range.
598 throw new IllegalStateException("Incoherent interval storage"); //$NON-NLS-1$
603 //--------------------------------------------------------------------------
605 //--------------------------------------------------------------------------
607 static void logMissingInterval(int attribute
, long timestamp
) {
608 Activator
.getDefault().logInfo("No data found in history for attribute " + //$NON-NLS-1$
609 attribute
+ " at time " + timestamp
+ //$NON-NLS-1$
610 ", returning dummy interval"); //$NON-NLS-1$
614 * Print out the contents of the inner structures.
617 * The PrintWriter in which to print the output
619 public void debugPrint(@NonNull PrintWriter writer
) {
620 getAttributeTree().debugPrint(writer
);
621 transState
.debugPrint(writer
);
622 backend
.debugPrint(writer
);