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
;
22 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
23 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
24 import org
.eclipse
.linuxtools
.internal
.tmf
.core
.Tracer
;
25 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.AttributeNotFoundException
;
26 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.StateValueTypeException
;
27 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.TimeRangeException
;
28 import org
.eclipse
.linuxtools
.tmf
.core
.interval
.ITmfStateInterval
;
29 import org
.eclipse
.linuxtools
.tmf
.core
.interval
.TmfStateInterval
;
30 import org
.eclipse
.linuxtools
.tmf
.core
.statesystem
.IStateSystemBuilder
;
31 import org
.eclipse
.linuxtools
.tmf
.core
.statevalue
.ITmfStateValue
;
32 import org
.eclipse
.linuxtools
.tmf
.core
.statevalue
.TmfStateValue
;
35 * This is the core class of the Generic State System. It contains all the
36 * methods to build and query a state history. It's exposed externally through
37 * the IStateSystemQuerier and IStateSystemBuilder interfaces, depending if the
38 * user needs read-only access or read-write access.
40 * When building, DON'T FORGET to call .closeHistory() when you are done
41 * inserting intervals, or the storage backend will have no way of knowing it
42 * can close and write itself to disk, and its thread will keep running.
47 public class StateSystem
implements IStateSystemBuilder
{
49 /* References to the inner structures */
50 private final AttributeTree attributeTree
;
51 private final TransientState transState
;
52 private final IStateHistoryBackend backend
;
58 * The "state history storage" backend to use.
60 * Put true if this is a new history started from scratch. It is
61 * used to tell the state system where to get its attribute tree.
63 * If there was a problem creating the new history file
65 public StateSystem(IStateHistoryBackend backend
, boolean newFile
)
67 this.backend
= backend
;
68 this.transState
= new TransientState(backend
);
71 attributeTree
= new AttributeTree(this);
73 /* We're opening an existing file */
74 this.attributeTree
= new AttributeTree(this, backend
.supplyAttributeTreeReader());
75 transState
.setInactive();
79 //--------------------------------------------------------------------------
80 // General methods related to the attribute tree
81 //--------------------------------------------------------------------------
84 * Method used by the attribute tree when creating new attributes, to keep
85 * the attribute count in the transient state in sync.
87 void addEmptyAttribute() {
88 transState
.addEmptyEntry();
92 public int getNbAttributes() {
93 return attributeTree
.getNbAttributes();
97 public boolean isLastAttribute(int quark
) {
98 return (quark
== getNbAttributes() - 1) ?
true : false;
102 public String
getAttributeName(int attributeQuark
) {
103 return attributeTree
.getAttributeName(attributeQuark
);
107 public String
getFullAttributePath(int attributeQuark
) {
108 return attributeTree
.getFullAttributeName(attributeQuark
);
111 //--------------------------------------------------------------------------
112 // Methods related to the storage backend
113 //--------------------------------------------------------------------------
116 public long getStartTime() {
117 return backend
.getStartTime();
121 public long getCurrentEndTime() {
122 return backend
.getEndTime();
126 public void closeHistory(long endTime
) throws TimeRangeException
{
127 File attributeTreeFile
;
128 long attributeTreeFilePos
;
129 long realEndTime
= endTime
;
131 if (realEndTime
< backend
.getEndTime()) {
133 * This can happen (empty nodes pushing the border further, etc.)
134 * but shouldn't be too big of a deal.
136 realEndTime
= backend
.getEndTime();
138 transState
.closeTransientState(realEndTime
);
139 backend
.finishedBuilding(realEndTime
);
141 attributeTreeFile
= backend
.supplyAttributeTreeWriterFile();
142 attributeTreeFilePos
= backend
.supplyAttributeTreeWriterFilePosition();
143 if (attributeTreeFile
!= null) {
145 * If null was returned, we simply won't save the attribute tree,
148 attributeTree
.writeSelf(attributeTreeFile
, attributeTreeFilePos
);
152 //--------------------------------------------------------------------------
153 // Quark-retrieving methods
154 //--------------------------------------------------------------------------
157 public int getQuarkAbsolute(String
... attribute
)
158 throws AttributeNotFoundException
{
159 return attributeTree
.getQuarkDontAdd(-1, attribute
);
163 public int getQuarkAbsoluteAndAdd(String
... attribute
) {
164 return attributeTree
.getQuarkAndAdd(-1, attribute
);
168 public int getQuarkRelative(int startingNodeQuark
, String
... subPath
)
169 throws AttributeNotFoundException
{
170 return attributeTree
.getQuarkDontAdd(startingNodeQuark
, subPath
);
174 public int getQuarkRelativeAndAdd(int startingNodeQuark
, String
... subPath
) {
175 return attributeTree
.getQuarkAndAdd(startingNodeQuark
, subPath
);
179 public List
<Integer
> getSubAttributes(int quark
, boolean recursive
)
180 throws AttributeNotFoundException
{
181 return attributeTree
.getSubAttributes(quark
, recursive
);
185 public List
<Integer
> getQuarks(String
... pattern
) {
186 List
<Integer
> quarks
= new LinkedList
<Integer
>();
187 List
<String
> prefix
= new LinkedList
<String
>();
188 List
<String
> suffix
= new LinkedList
<String
>();
189 boolean split
= false;
192 List
<Integer
> directChildren
;
193 int startingAttribute
;
195 /* Fill the "prefix" and "suffix" parts of the pattern around the '*' */
196 for (String entry
: pattern
) {
197 if (entry
.equals("*")) { //$NON-NLS-1$
200 * Split was already true? This means there was more than
201 * one wildcard. This is not supported, return an empty
216 prefixStr
= prefix
.toArray(new String
[prefix
.size()]);
217 suffixStr
= suffix
.toArray(new String
[suffix
.size()]);
220 * If there was no wildcard, we'll only return the one matching
221 * attribute, if there is one.
223 if (split
== false) {
226 quark
= getQuarkAbsolute(prefixStr
);
227 } catch (AttributeNotFoundException e
) {
228 /* It's fine, we'll just return the empty List */
236 if (prefix
.size() == 0) {
238 * If 'prefix' is empty, this means the wildcard was the first
239 * element. Look for the root node's sub-attributes.
241 startingAttribute
= -1;
243 startingAttribute
= getQuarkAbsolute(prefixStr
);
245 directChildren
= attributeTree
.getSubAttributes(startingAttribute
,
247 } catch (AttributeNotFoundException e
) {
248 /* That attribute path did not exist, return the empty array */
253 * Iterate of all the sub-attributes, and only keep those who match the
254 * 'suffix' part of the initial pattern.
256 for (int childQuark
: directChildren
) {
259 matchingQuark
= getQuarkRelative(childQuark
, suffixStr
);
260 } catch (AttributeNotFoundException e
) {
263 quarks
.add(matchingQuark
);
269 //--------------------------------------------------------------------------
270 // Methods related to insertions in the history
271 //--------------------------------------------------------------------------
274 public void modifyAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
275 throws TimeRangeException
, AttributeNotFoundException
,
276 StateValueTypeException
{
277 transState
.processStateChange(t
, value
, attributeQuark
);
281 public void incrementAttribute(long t
, int attributeQuark
)
282 throws StateValueTypeException
, TimeRangeException
,
283 AttributeNotFoundException
{
284 int prevValue
= queryOngoingState(attributeQuark
).unboxInt();
285 if (prevValue
== -1) {
286 /* if the attribute was previously null, start counting at 0 */
289 modifyAttribute(t
, TmfStateValue
.newValueInt(prevValue
+ 1),
294 public void pushAttribute(long t
, ITmfStateValue value
, int attributeQuark
)
295 throws TimeRangeException
, AttributeNotFoundException
,
296 StateValueTypeException
{
297 Integer stackDepth
= 0;
298 int subAttributeQuark
;
299 ITmfStateValue previousSV
= transState
.getOngoingStateValue(attributeQuark
);
301 if (previousSV
.isNull()) {
303 * If the StateValue was null, this means this is the first time we
304 * use this attribute. Leave stackDepth at 0.
306 } else if (previousSV
.getType() == 0) {
307 /* Previous value was an integer, all is good, use it */
308 stackDepth
= previousSV
.unboxInt();
310 /* Previous state of this attribute was another type? Not good! */
311 throw new StateValueTypeException();
314 if (stackDepth
>= 10) {
316 * Limit stackDepth to 10, to avoid having Attribute Trees grow out
317 * of control due to buggy insertions
319 String message
= "Stack limit reached, not pushing"; //$NON-NLS-1$
320 throw new AttributeNotFoundException(message
);
324 subAttributeQuark
= getQuarkRelativeAndAdd(attributeQuark
,
325 stackDepth
.toString());
327 modifyAttribute(t
, TmfStateValue
.newValueInt(stackDepth
),
329 modifyAttribute(t
, value
, subAttributeQuark
);
333 public void popAttribute(long t
, int attributeQuark
)
334 throws AttributeNotFoundException
, TimeRangeException
,
335 StateValueTypeException
{
337 int subAttributeQuark
;
338 ITmfStateValue previousSV
= transState
.getOngoingStateValue(attributeQuark
);
340 if (previousSV
.isNull()) {
341 /* Same as if stackDepth == 0, see below */
344 if (previousSV
.getType() != 0) {
346 * The existing value was a string, this doesn't look like a valid
349 throw new StateValueTypeException();
352 stackDepth
= previousSV
.unboxInt();
354 if (stackDepth
== 0) {
356 * Trying to pop an empty stack. This often happens at the start of
357 * traces, for example when we see a syscall_exit, without having
358 * the corresponding syscall_entry in the trace. Just ignore
364 if (stackDepth
< 0) {
365 /* This on the other hand should not happen... */
366 String message
= "A top-level stack attribute " + //$NON-NLS-1$
367 "cannot have a negative integer value."; //$NON-NLS-1$
368 throw new StateValueTypeException(message
);
371 /* The attribute should already exist... */
372 subAttributeQuark
= getQuarkRelative(attributeQuark
,
373 stackDepth
.toString());
376 modifyAttribute(t
, TmfStateValue
.newValueInt(stackDepth
),
378 removeAttribute(t
, subAttributeQuark
);
382 public void removeAttribute(long t
, int attributeQuark
)
383 throws TimeRangeException
, AttributeNotFoundException
{
384 assert (attributeQuark
>= 0);
385 List
<Integer
> childAttributes
;
388 * "Nullify our children first, recursively. We pass 'false' because we
389 * handle the recursion ourselves.
391 childAttributes
= attributeTree
.getSubAttributes(attributeQuark
, false);
392 for (Integer childNodeQuark
: childAttributes
) {
393 assert (attributeQuark
!= childNodeQuark
);
394 removeAttribute(t
, childNodeQuark
);
396 /* Nullify ourselves */
398 transState
.processStateChange(t
, TmfStateValue
.nullValue(),
400 } catch (StateValueTypeException e
) {
402 * Will not happen since we're inserting null values only, but poor
403 * compiler has no way of knowing this...
409 //--------------------------------------------------------------------------
410 // "Current" query/update methods
411 //--------------------------------------------------------------------------
414 public ITmfStateValue
queryOngoingState(int attributeQuark
)
415 throws AttributeNotFoundException
{
416 return transState
.getOngoingStateValue(attributeQuark
);
420 public void updateOngoingState(ITmfStateValue newValue
, int attributeQuark
)
421 throws AttributeNotFoundException
{
422 transState
.changeOngoingStateValue(attributeQuark
, newValue
);
427 //--------------------------------------------------------------------------
428 // Regular query methods (sent to the back-end)
429 //--------------------------------------------------------------------------
432 public synchronized List
<ITmfStateInterval
> queryFullState(long t
)
433 throws TimeRangeException
{
434 List
<ITmfStateInterval
> stateInfo
= new ArrayList
<ITmfStateInterval
>(
435 attributeTree
.getNbAttributes());
437 /* Bring the size of the array to the current number of attributes */
438 for (int i
= 0; i
< attributeTree
.getNbAttributes(); i
++) {
442 /* Query the storage backend */
443 backend
.doQuery(stateInfo
, t
);
446 * If we are currently building the history, also query the "ongoing"
447 * states for stuff that might not yet be written to the history.
449 if (transState
.isActive()) {
450 transState
.doQuery(stateInfo
, t
);
454 * We should have previously inserted an interval for every attribute.
455 * If we do happen do see a 'null' object here, just replace it with a a
456 * dummy internal with a null value, to avoid NPE's further up.
458 for (int i
= 0; i
< stateInfo
.size(); i
++) {
459 if (stateInfo
.get(i
) == null) {
460 //logMissingInterval(i, t);
461 stateInfo
.set(i
, new TmfStateInterval(t
, t
, i
, TmfStateValue
.nullValue()));
468 public ITmfStateInterval
querySingleState(long t
, int attributeQuark
)
469 throws AttributeNotFoundException
, TimeRangeException
{
470 ITmfStateInterval ret
;
472 if (transState
.hasInfoAboutStateOf(t
, attributeQuark
)) {
473 ret
= transState
.getOngoingInterval(attributeQuark
);
475 ret
= backend
.doSingularQuery(t
, attributeQuark
);
479 * Return a fake interval if we could not find anything in the history.
480 * We do NOT want to return 'null' here.
483 //logMissingInterval(attributeQuark, t);
484 return new TmfStateInterval(t
, this.getCurrentEndTime(),
485 attributeQuark
, TmfStateValue
.nullValue());
491 public List
<ITmfStateInterval
> queryHistoryRange(int attributeQuark
,
492 long t1
, long t2
) throws TimeRangeException
,
493 AttributeNotFoundException
{
494 List
<ITmfStateInterval
> intervals
;
495 ITmfStateInterval currentInterval
;
498 /* Make sure the time range makes sense */
500 throw new TimeRangeException();
503 /* Set the actual, valid end time of the range query */
504 if (t2
> this.getCurrentEndTime()) {
505 tEnd
= this.getCurrentEndTime();
510 /* Get the initial state at time T1 */
511 intervals
= new ArrayList
<ITmfStateInterval
>();
512 currentInterval
= querySingleState(t1
, attributeQuark
);
513 intervals
.add(currentInterval
);
515 /* Get the following state changes */
516 ts
= currentInterval
.getEndTime();
517 while (ts
!= -1 && ts
< tEnd
) {
518 ts
++; /* To "jump over" to the next state in the history */
519 currentInterval
= querySingleState(ts
, attributeQuark
);
520 intervals
.add(currentInterval
);
521 ts
= currentInterval
.getEndTime();
527 public List
<ITmfStateInterval
> queryHistoryRange(int attributeQuark
,
528 long t1
, long t2
, long resolution
, IProgressMonitor monitor
)
529 throws TimeRangeException
, AttributeNotFoundException
{
530 List
<ITmfStateInterval
> intervals
;
531 ITmfStateInterval currentInterval
;
534 if (monitor
== null) {
535 monitor
= new NullProgressMonitor();
538 /* Make sure the time range makes sense */
539 if (t2
< t1
|| resolution
<= 0) {
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
);
556 * Iterate over the "resolution points". We skip unneeded queries in the
557 * case the current interval is longer than the resolution.
559 for (ts
= t1
; (currentInterval
.getEndTime() != -1) && (ts
< tEnd
);
561 if (monitor
.isCanceled()) {
564 if (ts
<= currentInterval
.getEndTime()) {
567 currentInterval
= querySingleState(ts
, attributeQuark
);
568 intervals
.add(currentInterval
);
571 /* Add the interval at t2, if it wasn't included already. */
572 if (currentInterval
.getEndTime() < tEnd
) {
573 currentInterval
= querySingleState(tEnd
, attributeQuark
);
574 intervals
.add(currentInterval
);
579 //--------------------------------------------------------------------------
581 //--------------------------------------------------------------------------
583 static void logMissingInterval(int attribute
, long timestamp
) {
584 Tracer
.traceInfo("No data found in history for attribute " + //$NON-NLS-1$
585 attribute
+ " at time " + timestamp
+ //$NON-NLS-1$
586 ", returning dummy interval"); //$NON-NLS-1$
590 * Print out the contents of the inner structures.
593 * The PrintWriter in which to print the output
595 public void debugPrint(PrintWriter writer
) {
596 attributeTree
.debugPrint(writer
);
597 transState
.debugPrint(writer
);
598 backend
.debugPrint(writer
);