1 /*******************************************************************************
2 * Copyright (c) 2013, 2014 École Polytechnique de Montréal
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * Geneviève Bastien - Initial API and implementation
11 * Bernd Hufmann - Integrated history builder functionality
12 *******************************************************************************/
14 package org
.eclipse
.tracecompass
.tmf
.core
.statesystem
;
17 import java
.io
.IOException
;
18 import java
.util
.Collections
;
19 import java
.util
.concurrent
.CountDownLatch
;
21 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
22 import org
.eclipse
.core
.runtime
.IStatus
;
23 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
24 import org
.eclipse
.jdt
.annotation
.NonNull
;
25 import org
.eclipse
.jdt
.annotation
.NonNullByDefault
;
26 import org
.eclipse
.jdt
.annotation
.Nullable
;
27 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.statesystem
.backends
.partial
.PartialHistoryBackend
;
28 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.statesystem
.backends
.partial
.PartialStateSystem
;
29 import org
.eclipse
.tracecompass
.statesystem
.core
.ITmfStateSystem
;
30 import org
.eclipse
.tracecompass
.statesystem
.core
.ITmfStateSystemBuilder
;
31 import org
.eclipse
.tracecompass
.statesystem
.core
.StateSystemFactory
;
32 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.IStateHistoryBackend
;
33 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.InMemoryBackend
;
34 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.NullBackend
;
35 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.historytree
.HistoryTreeBackend
;
36 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.historytree
.ThreadedHistoryTreeBackend
;
37 import org
.eclipse
.tracecompass
.tmf
.core
.analysis
.TmfAbstractAnalysisModule
;
38 import org
.eclipse
.tracecompass
.tmf
.core
.event
.ITmfEvent
;
39 import org
.eclipse
.tracecompass
.tmf
.core
.exceptions
.TmfTraceException
;
40 import org
.eclipse
.tracecompass
.tmf
.core
.request
.ITmfEventRequest
;
41 import org
.eclipse
.tracecompass
.tmf
.core
.request
.TmfEventRequest
;
42 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalHandler
;
43 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceRangeUpdatedSignal
;
44 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimeRange
;
45 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
46 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTraceCompleteness
;
47 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfExperiment
;
48 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceManager
;
51 * Abstract analysis module to generate a state system. It is a base class that
52 * can be used as a shortcut by analysis who just need to build a single state
53 * system with a state provider.
55 * Analysis implementing this class should only need to provide a state system
56 * and optionally a backend (default to NULL) and, if required, a filename
57 * (defaults to the analysis'ID)
59 * @author Geneviève Bastien
63 public abstract class TmfStateSystemAnalysisModule
extends TmfAbstractAnalysisModule
64 implements ITmfAnalysisModuleWithStateSystems
{
66 private static final String EXTENSION
= ".ht"; //$NON-NLS-1$
68 private final CountDownLatch fInitialized
= new CountDownLatch(1);
69 private final Object fRequestSyncObj
= new Object();
71 @Nullable private ITmfStateSystemBuilder fStateSystem
;
72 @Nullable private ITmfStateProvider fStateProvider
;
73 @Nullable private IStateHistoryBackend fHtBackend
;
74 @Nullable private ITmfEventRequest fRequest
;
75 @Nullable private TmfTimeRange fTimeRange
= null;
77 private int fNbRead
= 0;
80 * State system backend types
82 * @author Geneviève Bastien
84 protected enum StateSystemBackendType
{
85 /** Full history in file */
87 /** In memory state system */
91 /** State system backed with partial history */
97 * Retrieve a state system belonging to trace, by passing the ID of the
98 * relevant analysis module.
100 * This will start the execution of the analysis module, and start the
101 * construction of the state system, if needed.
104 * The trace for which you want the state system
106 * The ID of the state system analysis module
107 * @return The state system, or null if there was no match
110 public static @Nullable ITmfStateSystem
getStateSystem(ITmfTrace trace
, String moduleId
) {
111 TmfStateSystemAnalysisModule module
=
112 trace
.getAnalysisModuleOfClass(TmfStateSystemAnalysisModule
.class, moduleId
);
113 if (module
!= null) {
114 IStatus status
= module
.schedule();
116 module
.waitForInitialization();
117 return module
.getStateSystem();
124 * Get the state provider for this analysis module
126 * @return the state provider
128 protected abstract ITmfStateProvider
createStateProvider();
131 * Get the state system backend type used by this module
133 * @return The {@link StateSystemBackendType}
135 protected StateSystemBackendType
getBackendType() {
136 /* Using full history by default, sub-classes can override */
137 return StateSystemBackendType
.FULL
;
141 * Get the supplementary file name where to save this state system. The
142 * default is the ID of the analysis followed by the extension.
144 * @return The supplementary file name
146 protected String
getSsFileName() {
147 return getId() + EXTENSION
;
151 * Get the state system generated by this analysis, or null if it is not yet
154 * @return The state system
157 public ITmfStateSystem
getStateSystem() {
162 * Block the calling thread until the analysis module has been initialized.
163 * After this method returns, {@link #getStateSystem()} should not return
166 public void waitForInitialization() {
168 fInitialized
.await();
169 } catch (InterruptedException e
) {}
172 // ------------------------------------------------------------------------
173 // TmfAbstractAnalysisModule
174 // ------------------------------------------------------------------------
177 protected boolean executeAnalysis(@Nullable final IProgressMonitor monitor
) {
178 IProgressMonitor mon
= (monitor
== null ?
new NullProgressMonitor() : monitor
);
179 final ITmfStateProvider provider
= createStateProvider();
183 /* FIXME: State systems should make use of the monitor, to be cancelled */
185 /* Get the state system according to backend */
186 StateSystemBackendType backend
= getBackendType();
190 ITmfTrace trace
= getTrace();
192 // Analysis was cancelled in the meantime
193 fInitialized
.countDown();
198 directory
= TmfTraceManager
.getSupplementaryFileDir(trace
);
199 htFile
= new File(directory
+ getSsFileName());
200 createFullHistory(id
, provider
, htFile
);
203 directory
= TmfTraceManager
.getSupplementaryFileDir(trace
);
204 htFile
= new File(directory
+ getSsFileName());
205 createPartialHistory(id
, provider
, htFile
);
208 createInMemoryHistory(id
, provider
);
211 createNullHistory(id
, provider
);
216 } catch (TmfTraceException e
) {
217 fInitialized
.countDown();
220 return !mon
.isCanceled();
224 protected void canceling() {
225 ITmfEventRequest req
= fRequest
;
226 if ((req
!= null) && (!req
.isCompleted())) {
232 public void dispose() {
234 if (fStateSystem
!= null) {
235 fStateSystem
.dispose();
239 // ------------------------------------------------------------------------
240 // History creation methods
241 // ------------------------------------------------------------------------
244 * Load the history file matching the target trace. If the file already
245 * exists, it will be opened directly. If not, it will be created from
248 private void createFullHistory(String id
, ITmfStateProvider provider
, File htFile
) throws TmfTraceException
{
250 /* If the target file already exists, do not rebuild it uselessly */
251 // TODO for now we assume it's complete. Might be a good idea to check
252 // at least if its range matches the trace's range.
254 if (htFile
.exists()) {
255 /* Load an existing history */
256 final int version
= provider
.getVersion();
258 IStateHistoryBackend backend
= new HistoryTreeBackend(htFile
, version
);
259 fHtBackend
= backend
;
260 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
, false);
261 fInitialized
.countDown();
263 } catch (IOException e
) {
265 * There was an error opening the existing file. Perhaps it was
266 * corrupted, perhaps it's an old version? We'll just
267 * fall-through and try to build a new one from scratch instead.
272 /* Size of the blocking queue to use when building a state history */
273 final int QUEUE_SIZE
= 10000;
276 IStateHistoryBackend backend
= new ThreadedHistoryTreeBackend(htFile
,
277 provider
.getStartTime(), provider
.getVersion(), QUEUE_SIZE
);
278 fHtBackend
= backend
;
279 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
);
280 provider
.assignTargetStateSystem(fStateSystem
);
282 } catch (IOException e
) {
284 * If it fails here however, it means there was a problem writing to
285 * the disk, so throw a real exception this time.
287 throw new TmfTraceException(e
.toString(), e
);
292 * Create a new state system backed with a partial history. A partial
293 * history is similar to a "full" one (which you get with
294 * {@link #newFullHistory}), except that the file on disk is much smaller,
295 * but queries are a bit slower.
297 * Also note that single-queries are implemented using a full-query
298 * underneath, (which are much slower), so this might not be a good fit for
299 * a use case where you have to do lots of single queries.
301 private void createPartialHistory(String id
, ITmfStateProvider provider
, File htPartialFile
)
302 throws TmfTraceException
{
304 * The order of initializations is very tricky (but very important!)
305 * here. We need to follow this pattern:
306 * (1 is done before the call to this method)
308 * 1- Instantiate realStateProvider
309 * 2- Instantiate realBackend
310 * 3- Instantiate partialBackend, with prereqs:
311 * 3a- Instantiate partialProvider, via realProvider.getNew()
312 * 3b- Instantiate nullBackend (partialSS's backend)
313 * 3c- Instantiate partialSS
314 * 3d- partialProvider.assignSS(partialSS)
315 * 4- Instantiate realSS
316 * 5- partialSS.assignUpstream(realSS)
317 * 6- realProvider.assignSS(realSS)
318 * 7- Call HistoryBuilder(realProvider, realSS, partialBackend) to build the thing.
321 /* Size of the blocking queue to use when building a state history */
322 final int QUEUE_SIZE
= 10000;
324 final long granularity
= 50000;
327 IStateHistoryBackend realBackend
= null;
329 realBackend
= new ThreadedHistoryTreeBackend(htPartialFile
,
330 provider
.getStartTime(), provider
.getVersion(), QUEUE_SIZE
);
331 } catch (IOException e
) {
332 throw new TmfTraceException(e
.toString(), e
);
336 ITmfStateProvider partialProvider
= provider
.getNewInstance();
338 /* 3b-3c, constructor automatically uses a NullBackend */
339 PartialStateSystem pss
= new PartialStateSystem();
342 partialProvider
.assignTargetStateSystem(pss
);
345 IStateHistoryBackend partialBackend
=
346 new PartialHistoryBackend(partialProvider
, pss
, realBackend
, granularity
);
349 @SuppressWarnings("restriction")
350 org
.eclipse
.tracecompass
.internal
.statesystem
.core
.StateSystem realSS
=
351 (org
.eclipse
.tracecompass
.internal
.statesystem
.core
.StateSystem
) StateSystemFactory
.newStateSystem(id
, partialBackend
);
354 pss
.assignUpstream(realSS
);
357 provider
.assignTargetStateSystem(realSS
);
360 fHtBackend
= partialBackend
;
361 fStateSystem
= realSS
;
367 * Create a new state system using a null history back-end. This means that
368 * no history intervals will be saved anywhere, and as such only
369 * {@link ITmfStateSystem#queryOngoingState} will be available.
371 private void createNullHistory(String id
, ITmfStateProvider provider
) {
372 IStateHistoryBackend backend
= new NullBackend();
373 fHtBackend
= backend
;
374 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
);
375 provider
.assignTargetStateSystem(fStateSystem
);
380 * Create a new state system using in-memory interval storage. This should
381 * only be done for very small state system, and will be naturally limited
384 private void createInMemoryHistory(String id
, ITmfStateProvider provider
) {
385 IStateHistoryBackend backend
= new InMemoryBackend(provider
.getStartTime());
386 fHtBackend
= backend
;
387 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
);
388 provider
.assignTargetStateSystem(fStateSystem
);
392 private void disposeProvider(boolean deleteFiles
) {
393 ITmfStateProvider provider
= fStateProvider
;
394 if (provider
!= null) {
397 if (deleteFiles
&& (fHtBackend
!= null)) {
398 fHtBackend
.removeFiles();
402 private void build(ITmfStateProvider provider
) {
403 if ((fStateSystem
== null) || (fHtBackend
== null)) {
404 throw new IllegalArgumentException();
407 ITmfEventRequest request
= fRequest
;
408 if ((request
!= null) && (!request
.isCompleted())) {
412 fTimeRange
= TmfTimeRange
.ETERNITY
;
413 final ITmfTrace trace
= provider
.getTrace();
414 if (trace
!= null && !isCompleteTrace(trace
)) {
415 TmfTimeRange traceTimeRange
= trace
.getTimeRange();
416 if (traceTimeRange
!= null) {
417 fTimeRange
= traceTimeRange
;
421 fStateProvider
= provider
;
422 synchronized (fRequestSyncObj
) {
427 * The state system object is now created, we can consider this module
428 * "initialized" (components can retrieve it and start doing queries).
430 fInitialized
.countDown();
433 * Block the executeAnalysis() construction is complete (so that the
434 * progress monitor displays that it is running).
437 if (fRequest
!= null) {
438 fRequest
.waitForCompletion();
440 } catch (InterruptedException e
) {
445 private class StateSystemEventRequest
extends TmfEventRequest
{
446 private final ITmfStateProvider sci
;
447 private final ITmfTrace trace
;
449 public StateSystemEventRequest(ITmfStateProvider sp
, TmfTimeRange timeRange
, int index
) {
450 super(sp
.getExpectedEventType(),
453 ITmfEventRequest
.ALL_DATA
,
454 ITmfEventRequest
.ExecutionType
.BACKGROUND
);
457 // sci.getTrace() will eventually return a @NonNull
458 @SuppressWarnings("null")
459 @NonNull ITmfTrace tr
= sci
.getTrace();
465 public void handleData(final ITmfEvent event
) {
466 super.handleData(event
);
467 if (event
.getTrace() == trace
) {
468 sci
.processEvent(event
);
469 } else if (trace
instanceof TmfExperiment
) {
471 * If the request is for an experiment, check if the event is
472 * from one of the child trace
474 for (ITmfTrace childTrace
: ((TmfExperiment
) trace
).getTraces()) {
475 if (childTrace
== event
.getTrace()) {
476 sci
.processEvent(event
);
483 public void handleSuccess() {
484 super.handleSuccess();
485 if (isCompleteTrace(trace
)) {
486 disposeProvider(false);
488 fNbRead
+= getNbRead();
489 synchronized (fRequestSyncObj
) {
490 final TmfTimeRange timeRange
= fTimeRange
;
491 if (timeRange
!= null) {
492 if (getRange().getEndTime().getValue() < timeRange
.getEndTime().getValue()) {
501 public void handleCancel() {
502 super.handleCancel();
503 if (isCompleteTrace(trace
)) {
504 disposeProvider(true);
509 public void handleFailure() {
510 super.handleFailure();
511 disposeProvider(true);
515 // ------------------------------------------------------------------------
516 // ITmfAnalysisModuleWithStateSystems
517 // ------------------------------------------------------------------------
521 public ITmfStateSystem
getStateSystem(String id
) {
522 if (id
.equals(getId())) {
529 public Iterable
<ITmfStateSystem
> getStateSystems() {
530 @SuppressWarnings("null")
531 @NonNull Iterable
<ITmfStateSystem
> ret
= Collections
.singleton((ITmfStateSystem
) fStateSystem
);
536 * Signal handler for the TmfTraceRangeUpdatedSignal signal
538 * @param signal The incoming signal
541 public void traceRangeUpdated(final TmfTraceRangeUpdatedSignal signal
) {
542 fTimeRange
= signal
.getRange();
543 ITmfStateProvider stateProvider
= fStateProvider
;
544 synchronized (fRequestSyncObj
) {
545 if (signal
.getTrace() == getTrace() && stateProvider
!= null && stateProvider
.getAssignedStateSystem() != null) {
546 ITmfEventRequest request
= fRequest
;
547 if ((request
== null) || request
.isCompleted()) {
554 private void startRequest() {
555 ITmfStateProvider stateProvider
= fStateProvider
;
556 TmfTimeRange timeRange
= fTimeRange
;
557 if (stateProvider
== null || timeRange
== null) {
560 ITmfEventRequest request
= new StateSystemEventRequest(stateProvider
, timeRange
, fNbRead
);
561 stateProvider
.getTrace().sendRequest(request
);
565 private static boolean isCompleteTrace(ITmfTrace trace
) {
566 return !(trace
instanceof ITmfTraceCompleteness
) || ((ITmfTraceCompleteness
) trace
).isComplete();