1 /*******************************************************************************
2 * Copyright (c) 2012 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
;
23 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
24 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
25 import org
.eclipse
.linuxtools
.internal
.tmf
.core
.Activator
;
26 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.AttributeNotFoundException
;
27 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.StateValueTypeException
;
28 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.TimeRangeException
;
29 import org
.eclipse
.linuxtools
.tmf
.core
.interval
.ITmfStateInterval
;
30 import org
.eclipse
.linuxtools
.tmf
.core
.interval
.TmfStateInterval
;
31 import org
.eclipse
.linuxtools
.tmf
.core
.statesystem
.ITmfStateSystemBuilder
;
32 import org
.eclipse
.linuxtools
.tmf
.core
.statevalue
.ITmfStateValue
;
33 import org
.eclipse
.linuxtools
.tmf
.core
.statevalue
.TmfStateValue
;
36 * This is the core class of the Generic State System. It contains all the
37 * methods to build and query a state history. It's exposed externally through
38 * the IStateSystemQuerier and IStateSystemBuilder interfaces, depending if the
39 * user needs read-only access or read-write access.
41 * When building, DON'T FORGET to call .closeHistory() when you are done
42 * inserting intervals, or the storage backend will have no way of knowing it
43 * can close and write itself to disk, and its thread will keep running.
48 public class StateSystem
implements ITmfStateSystemBuilder
{
50 /* References to the inner structures */
51 private final AttributeTree attributeTree
;
52 private final TransientState transState
;
53 private final IStateHistoryBackend backend
;
55 /* Latch tracking if the state history is done building or not */
56 private final CountDownLatch finishedLatch
= new CountDownLatch(1);
62 * The "state history storage" backend to use.
64 * Put true if this is a new history started from scratch. It is
65 * used to tell the state system where to get its attribute tree.
67 * If there was a problem creating the new history file
69 public StateSystem(IStateHistoryBackend backend
, boolean newFile
)
71 this.backend
= backend
;
72 this.transState
= new TransientState(backend
);
75 attributeTree
= new AttributeTree(this);
77 /* We're opening an existing file */
78 this.attributeTree
= new AttributeTree(this, backend
.supplyAttributeTreeReader());
79 transState
.setInactive();
80 finishedLatch
.countDown(); /* The history is already built */
85 public void waitUntilBuilt() {
87 finishedLatch
.await();
88 } catch (InterruptedException e
) {
93 //--------------------------------------------------------------------------
94 // General methods related to the attribute tree
95 //--------------------------------------------------------------------------
98 * Method used by the attribute tree when creating new attributes, to keep
99 * the attribute count in the transient state in sync.
101 void addEmptyAttribute() {
102 transState
.addEmptyEntry();
106 public int getNbAttributes() {
107 return attributeTree
.getNbAttributes();
111 public boolean isLastAttribute(int quark
) {
112 return (quark
== getNbAttributes() - 1) ?
true : false;
116 public String
getAttributeName(int attributeQuark
) {
117 return attributeTree
.getAttributeName(attributeQuark
);
121 public String
getFullAttributePath(int attributeQuark
) {
122 return attributeTree
.getFullAttributeName(attributeQuark
);
125 //--------------------------------------------------------------------------
126 // Methods related to the storage backend
127 //--------------------------------------------------------------------------
130 public long getStartTime() {
131 return backend
.getStartTime();
135 public long getCurrentEndTime() {
136 return backend
.getEndTime();
140 public void closeHistory(long endTime
) throws TimeRangeException
{
141 File attributeTreeFile
;
142 long attributeTreeFilePos
;
143 long realEndTime
= endTime
;
145 if (realEndTime
< backend
.getEndTime()) {
147 * This can happen (empty nodes pushing the border further, etc.)
148 * but shouldn't be too big of a deal.
150 realEndTime
= backend
.getEndTime();
152 transState
.closeTransientState(realEndTime
);
153 backend
.finishedBuilding(realEndTime
);
155 attributeTreeFile
= backend
.supplyAttributeTreeWriterFile();
156 attributeTreeFilePos
= backend
.supplyAttributeTreeWriterFilePosition();
157 if (attributeTreeFile
!= null) {
159 * If null was returned, we simply won't save the attribute tree,
162 attributeTree
.writeSelf(attributeTreeFile
, attributeTreeFilePos
);
164 finishedLatch
.countDown(); /* Mark the history as finished building */
167 //--------------------------------------------------------------------------
168 // Quark-retrieving methods
169 //--------------------------------------------------------------------------
172 public int getQuarkAbsolute(String
... attribute
)
173 throws AttributeNotFoundException
{
174 return attributeTree
.getQuarkDontAdd(-1, attribute
);
178 public int getQuarkAbsoluteAndAdd(String
... attribute
) {
179 return attributeTree
.getQuarkAndAdd(-1, attribute
);
183 public int getQuarkRelative(int startingNodeQuark
, String
... subPath
)
184 throws AttributeNotFoundException
{
185 return attributeTree
.getQuarkDontAdd(startingNodeQuark
, subPath
);
189 public int getQuarkRelativeAndAdd(int startingNodeQuark
, String
... subPath
) {
190 return attributeTree
.getQuarkAndAdd(startingNodeQuark
, subPath
);
194 public List
<Integer
> getSubAttributes(int quark
, boolean recursive
)
195 throws AttributeNotFoundException
{
196 return attributeTree
.getSubAttributes(quark
, recursive
);
200 public List
<Integer
> getQuarks(String
... pattern
) {
201 List
<Integer
> quarks
= new LinkedList
<Integer
>();
202 List
<String
> prefix
= new LinkedList
<String
>();
203 List
<String
> suffix
= new LinkedList
<String
>();
204 boolean split
= false;
207 List
<Integer
> directChildren
;
208 int startingAttribute
;
210 /* Fill the "prefix" and "suffix" parts of the pattern around the '*' */
211 for (String entry
: pattern
) {
212 if (entry
.equals("*")) { //$NON-NLS-1$
215 * Split was already true? This means there was more than
216 * one wildcard. This is not supported, return an empty
231 prefixStr
= prefix
.toArray(new String
[prefix
.size()]);
232 suffixStr
= suffix
.toArray(new String
[suffix
.size()]);
235 * If there was no wildcard, we'll only return the one matching
236 * attribute, if there is one.
238 if (split
== false) {
241 quark
= getQuarkAbsolute(prefixStr
);
242 } catch (AttributeNotFoundException e
) {
243 /* It's fine, we'll just return the empty List */
251 if (prefix
.size() == 0) {
253 * If 'prefix' is empty, this means the wildcard was the first
254 * element. Look for the root node's sub-attributes.
256 startingAttribute
= -1;
258 startingAttribute
= getQuarkAbsolute(prefixStr
);
260 directChildren
= attributeTree
.getSubAttributes(startingAttribute
,
262 } catch (AttributeNotFoundException e
) {
263 /* That attribute path did not exist, return the empty array */
268 * Iterate of all the sub-attributes, and only keep those who match the
269 * 'suffix' part of the initial pattern.
271 for (int childQuark
: directChildren
) {
274 matchingQuark
= getQuarkRelative(childQuark
, suffixStr
);
275 } catch (AttributeNotFoundException e
) {
278 quarks
.add(matchingQuark
);
284 //--------------------------------------------------------------------------
285 // Methods related to insertions in the history
286 //--------------------------------------------------------------------------
289 public void modifyAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
290 throws TimeRangeException
, AttributeNotFoundException
,
291 StateValueTypeException
{
292 transState
.processStateChange(t
, value
, attributeQuark
);
296 public void incrementAttribute(long t
, int attributeQuark
)
297 throws StateValueTypeException
, TimeRangeException
,
298 AttributeNotFoundException
{
299 int prevValue
= queryOngoingState(attributeQuark
).unboxInt();
300 if (prevValue
== -1) {
301 /* if the attribute was previously null, start counting at 0 */
304 modifyAttribute(t
, TmfStateValue
.newValueInt(prevValue
+ 1),
309 public void pushAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
310 throws TimeRangeException
, AttributeNotFoundException
,
311 StateValueTypeException
{
312 Integer stackDepth
= 0;
313 int subAttributeQuark
;
314 ITmfStateValue previousSV
= transState
.getOngoingStateValue(attributeQuark
);
316 if (previousSV
.isNull()) {
318 * If the StateValue was null, this means this is the first time we
319 * use this attribute. Leave stackDepth at 0.
321 } else if (previousSV
.getType() == 0) {
322 /* Previous value was an integer, all is good, use it */
323 stackDepth
= previousSV
.unboxInt();
325 /* Previous state of this attribute was another type? Not good! */
326 throw new StateValueTypeException();
329 if (stackDepth
>= 10) {
331 * Limit stackDepth to 10, to avoid having Attribute Trees grow out
332 * of control due to buggy insertions
334 String message
= "Stack limit reached, not pushing"; //$NON-NLS-1$
335 throw new AttributeNotFoundException(message
);
339 subAttributeQuark
= getQuarkRelativeAndAdd(attributeQuark
, stackDepth
.toString());
341 modifyAttribute(t
, TmfStateValue
.newValueInt(stackDepth
), attributeQuark
);
342 modifyAttribute(t
, value
, subAttributeQuark
);
346 public ITmfStateValue
popAttribute(long t
, int attributeQuark
)
347 throws AttributeNotFoundException
, TimeRangeException
,
348 StateValueTypeException
{
349 /* These are the state values of the stack-attribute itself */
350 ITmfStateValue previousSV
= queryOngoingState(attributeQuark
);
352 if (previousSV
.isNull()) {
354 * Trying to pop an empty stack. This often happens at the start of
355 * traces, for example when we see a syscall_exit, without having
356 * the corresponding syscall_entry in the trace. Just ignore
361 if (previousSV
.getType() != ITmfStateValue
.TYPE_INTEGER
) {
363 * The existing value was a string, this doesn't look like a valid
366 throw new StateValueTypeException();
369 Integer stackDepth
= previousSV
.unboxInt();
371 if (stackDepth
<= 0) {
372 /* This on the other hand should not happen... */
373 /* the case where == -1 was handled previously by .isNull() */
374 String message
= "A top-level stack attribute cannot " + //$NON-NLS-1$
375 "have a value of 0 or less (except -1/null)."; //$NON-NLS-1$
376 throw new StateValueTypeException(message
);
379 /* The attribute should already exist at this point */
380 int subAttributeQuark
= getQuarkRelative(attributeQuark
, stackDepth
.toString());
381 ITmfStateValue poppedValue
= queryOngoingState(subAttributeQuark
);
383 /* Update the state value of the stack-attribute */
384 ITmfStateValue nextSV
;
385 if (--stackDepth
== 0 ) {
386 /* Jump over "0" and store -1 (a null state value) */
387 nextSV
= TmfStateValue
.nullValue();
389 nextSV
= TmfStateValue
.newValueInt(stackDepth
);
391 modifyAttribute(t
, nextSV
, attributeQuark
);
393 /* Delete the sub-attribute that contained the user's state value */
394 removeAttribute(t
, subAttributeQuark
);
400 public void removeAttribute(long t
, int attributeQuark
)
401 throws TimeRangeException
, AttributeNotFoundException
{
402 assert (attributeQuark
>= 0);
403 List
<Integer
> childAttributes
;
406 * "Nullify our children first, recursively. We pass 'false' because we
407 * handle the recursion ourselves.
409 childAttributes
= attributeTree
.getSubAttributes(attributeQuark
, false);
410 for (Integer childNodeQuark
: childAttributes
) {
411 assert (attributeQuark
!= childNodeQuark
);
412 removeAttribute(t
, childNodeQuark
);
414 /* Nullify ourselves */
416 transState
.processStateChange(t
, TmfStateValue
.nullValue(),
418 } catch (StateValueTypeException e
) {
420 * Will not happen since we're inserting null values only, but poor
421 * compiler has no way of knowing this...
427 //--------------------------------------------------------------------------
428 // "Current" query/update methods
429 //--------------------------------------------------------------------------
432 public ITmfStateValue
queryOngoingState(int attributeQuark
)
433 throws AttributeNotFoundException
{
434 return transState
.getOngoingStateValue(attributeQuark
);
438 public void updateOngoingState(ITmfStateValue newValue
, int attributeQuark
)
439 throws AttributeNotFoundException
{
440 transState
.changeOngoingStateValue(attributeQuark
, newValue
);
445 //--------------------------------------------------------------------------
446 // Regular query methods (sent to the back-end)
447 //--------------------------------------------------------------------------
450 public synchronized List
<ITmfStateInterval
> queryFullState(long t
)
451 throws TimeRangeException
{
452 List
<ITmfStateInterval
> stateInfo
= new ArrayList
<ITmfStateInterval
>(
453 attributeTree
.getNbAttributes());
455 /* Bring the size of the array to the current number of attributes */
456 for (int i
= 0; i
< attributeTree
.getNbAttributes(); i
++) {
460 /* Query the storage backend */
461 backend
.doQuery(stateInfo
, t
);
464 * If we are currently building the history, also query the "ongoing"
465 * states for stuff that might not yet be written to the history.
467 if (transState
.isActive()) {
468 transState
.doQuery(stateInfo
, t
);
472 * We should have previously inserted an interval for every attribute.
473 * If we do happen do see a 'null' object here, just replace it with a a
474 * dummy internal with a null value, to avoid NPE's further up.
476 for (int i
= 0; i
< stateInfo
.size(); i
++) {
477 if (stateInfo
.get(i
) == null) {
478 //logMissingInterval(i, t);
479 stateInfo
.set(i
, new TmfStateInterval(t
, t
, i
, TmfStateValue
.nullValue()));
486 public ITmfStateInterval
querySingleState(long t
, int attributeQuark
)
487 throws AttributeNotFoundException
, TimeRangeException
{
488 ITmfStateInterval ret
;
490 if (transState
.hasInfoAboutStateOf(t
, attributeQuark
)) {
491 ret
= transState
.getOngoingInterval(attributeQuark
);
493 ret
= backend
.doSingularQuery(t
, attributeQuark
);
497 * Return a fake interval if we could not find anything in the history.
498 * We do NOT want to return 'null' here.
501 //logMissingInterval(attributeQuark, t);
502 return new TmfStateInterval(t
, this.getCurrentEndTime(),
503 attributeQuark
, TmfStateValue
.nullValue());
509 public ITmfStateInterval
querySingleStackTop(long t
, int stackAttributeQuark
)
510 throws StateValueTypeException
, AttributeNotFoundException
,
512 Integer curStackDepth
= querySingleState(t
, stackAttributeQuark
).getStateValue().unboxInt();
514 if (curStackDepth
== -1) {
515 /* There is nothing stored in this stack at this moment */
517 } else if (curStackDepth
< -1 || curStackDepth
== 0) {
519 * This attribute is an integer attribute, but it doesn't seem like
520 * it's used as a stack-attribute...
522 throw new StateValueTypeException();
525 int subAttribQuark
= getQuarkRelative(stackAttributeQuark
, curStackDepth
.toString());
526 ITmfStateInterval ret
= querySingleState(t
, subAttribQuark
);
531 public List
<ITmfStateInterval
> queryHistoryRange(int attributeQuark
,
532 long t1
, long t2
) throws TimeRangeException
,
533 AttributeNotFoundException
{
534 List
<ITmfStateInterval
> intervals
;
535 ITmfStateInterval currentInterval
;
538 /* Make sure the time range makes sense */
540 throw new TimeRangeException();
543 /* Set the actual, valid end time of the range query */
544 if (t2
> this.getCurrentEndTime()) {
545 tEnd
= this.getCurrentEndTime();
550 /* Get the initial state at time T1 */
551 intervals
= new ArrayList
<ITmfStateInterval
>();
552 currentInterval
= querySingleState(t1
, attributeQuark
);
553 intervals
.add(currentInterval
);
555 /* Get the following state changes */
556 ts
= currentInterval
.getEndTime();
557 while (ts
!= -1 && ts
< tEnd
) {
558 ts
++; /* To "jump over" to the next state in the history */
559 currentInterval
= querySingleState(ts
, attributeQuark
);
560 intervals
.add(currentInterval
);
561 ts
= currentInterval
.getEndTime();
567 public List
<ITmfStateInterval
> queryHistoryRange(int attributeQuark
,
568 long t1
, long t2
, long resolution
, IProgressMonitor monitor
)
569 throws TimeRangeException
, AttributeNotFoundException
{
570 List
<ITmfStateInterval
> intervals
;
571 ITmfStateInterval currentInterval
;
574 if (monitor
== null) {
575 monitor
= new NullProgressMonitor();
578 /* Make sure the time range makes sense */
579 if (t2
< t1
|| resolution
<= 0) {
580 throw new TimeRangeException();
583 /* Set the actual, valid end time of the range query */
584 if (t2
> this.getCurrentEndTime()) {
585 tEnd
= this.getCurrentEndTime();
590 /* Get the initial state at time T1 */
591 intervals
= new ArrayList
<ITmfStateInterval
>();
592 currentInterval
= querySingleState(t1
, attributeQuark
);
593 intervals
.add(currentInterval
);
596 * Iterate over the "resolution points". We skip unneeded queries in the
597 * case the current interval is longer than the resolution.
599 for (ts
= t1
; (currentInterval
.getEndTime() != -1) && (ts
< tEnd
);
601 if (monitor
.isCanceled()) {
604 if (ts
<= currentInterval
.getEndTime()) {
607 currentInterval
= querySingleState(ts
, attributeQuark
);
608 intervals
.add(currentInterval
);
611 /* Add the interval at t2, if it wasn't included already. */
612 if (currentInterval
.getEndTime() < tEnd
) {
613 currentInterval
= querySingleState(tEnd
, attributeQuark
);
614 intervals
.add(currentInterval
);
619 //--------------------------------------------------------------------------
621 //--------------------------------------------------------------------------
623 static void logMissingInterval(int attribute
, long timestamp
) {
624 Activator
.logInfo("No data found in history for attribute " + //$NON-NLS-1$
625 attribute
+ " at time " + timestamp
+ //$NON-NLS-1$
626 ", returning dummy interval"); //$NON-NLS-1$
630 * Print out the contents of the inner structures.
633 * The PrintWriter in which to print the output
635 public void debugPrint(PrintWriter writer
) {
636 attributeTree
.debugPrint(writer
);
637 transState
.debugPrint(writer
);
638 backend
.debugPrint(writer
);