1 /*******************************************************************************
2 * Copyright (c) 2013, 2015 É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
;
16 import static org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
.checkNotNull
;
19 import java
.io
.IOException
;
20 import java
.util
.Collections
;
21 import java
.util
.concurrent
.CountDownLatch
;
23 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
24 import org
.eclipse
.core
.runtime
.IStatus
;
25 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
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
.TmfTraceManager
;
48 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceUtils
;
49 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.experiment
.TmfExperiment
;
52 * Abstract analysis module to generate a state system. It is a base class that
53 * can be used as a shortcut by analysis who just need to build a single state
54 * system with a state provider.
56 * Analysis implementing this class should only need to provide a state system
57 * and optionally a backend (default to NULL) and, if required, a filename
58 * (defaults to the analysis'ID)
60 * @author Geneviève Bastien
62 public abstract class TmfStateSystemAnalysisModule
extends TmfAbstractAnalysisModule
63 implements ITmfAnalysisModuleWithStateSystems
{
65 private static final String EXTENSION
= ".ht"; //$NON-NLS-1$
67 private final CountDownLatch fInitialized
= new CountDownLatch(1);
68 private final Object fRequestSyncObj
= new Object();
70 @Nullable private ITmfStateSystemBuilder fStateSystem
;
71 @Nullable private ITmfStateProvider fStateProvider
;
72 @Nullable private IStateHistoryBackend fHtBackend
;
73 @Nullable private ITmfEventRequest fRequest
;
74 @Nullable private TmfTimeRange fTimeRange
= null;
76 private int fNbRead
= 0;
79 * State system backend types
81 * @author Geneviève Bastien
83 protected enum StateSystemBackendType
{
84 /** Full history in file */
86 /** In memory state system */
90 /** State system backed with partial history */
95 * Retrieve a state system belonging to trace, by passing the ID of the
96 * relevant analysis module.
98 * This will start the execution of the analysis module, and start the
99 * construction of the state system, if needed.
102 * The trace for which you want the state system
104 * The ID of the state system analysis module
105 * @return The state system, or null if there was no match
107 public static @Nullable ITmfStateSystem
getStateSystem(ITmfTrace trace
, String moduleId
) {
108 TmfStateSystemAnalysisModule module
=
109 TmfTraceUtils
.getAnalysisModuleOfClass(trace
, TmfStateSystemAnalysisModule
.class, moduleId
);
110 if (module
!= null) {
111 ITmfStateSystem ss
= module
.getStateSystem();
115 IStatus status
= module
.schedule();
117 module
.waitForInitialization();
118 return module
.getStateSystem();
125 * Get the state provider for this analysis module
127 * @return the state provider
129 protected abstract ITmfStateProvider
createStateProvider();
132 * Get the state system backend type used by this module
134 * @return The {@link StateSystemBackendType}
136 protected StateSystemBackendType
getBackendType() {
137 /* Using full history by default, sub-classes can override */
138 return StateSystemBackendType
.FULL
;
142 * Get the supplementary file name where to save this state system. The
143 * default is the ID of the analysis followed by the extension.
145 * @return The supplementary file name
147 protected String
getSsFileName() {
148 return getId() + EXTENSION
;
152 * Get the state system generated by this analysis, or null if it is not yet
155 * @return The state system
158 public ITmfStateSystem
getStateSystem() {
163 * Block the calling thread until the analysis module has been initialized.
164 * After this method returns, {@link #getStateSystem()} should not return
167 public void waitForInitialization() {
169 fInitialized
.await();
170 } catch (InterruptedException e
) {}
173 // ------------------------------------------------------------------------
174 // TmfAbstractAnalysisModule
175 // ------------------------------------------------------------------------
178 protected boolean executeAnalysis(@Nullable final IProgressMonitor monitor
) {
179 IProgressMonitor mon
= (monitor
== null ?
new NullProgressMonitor() : monitor
);
180 final ITmfStateProvider provider
= createStateProvider();
184 /* FIXME: State systems should make use of the monitor, to be cancelled */
186 /* Get the state system according to backend */
187 StateSystemBackendType backend
= getBackendType();
191 ITmfTrace trace
= getTrace();
193 // Analysis was cancelled in the meantime
194 fInitialized
.countDown();
199 directory
= TmfTraceManager
.getSupplementaryFileDir(trace
);
200 htFile
= new File(directory
+ getSsFileName());
201 createFullHistory(id
, provider
, htFile
);
204 directory
= TmfTraceManager
.getSupplementaryFileDir(trace
);
205 htFile
= new File(directory
+ getSsFileName());
206 createPartialHistory(id
, provider
, htFile
);
209 createInMemoryHistory(id
, provider
);
212 createNullHistory(id
, provider
);
217 } catch (TmfTraceException e
) {
218 fInitialized
.countDown();
221 return !mon
.isCanceled();
225 protected void canceling() {
226 ITmfEventRequest req
= fRequest
;
227 if ((req
!= null) && (!req
.isCompleted())) {
233 public void dispose() {
235 if (fStateSystem
!= null) {
236 fStateSystem
.dispose();
240 // ------------------------------------------------------------------------
241 // History creation methods
242 // ------------------------------------------------------------------------
245 * Load the history file matching the target trace. If the file already
246 * exists, it will be opened directly. If not, it will be created from
249 private void createFullHistory(String id
, ITmfStateProvider provider
, File htFile
) throws TmfTraceException
{
251 /* If the target file already exists, do not rebuild it uselessly */
252 // TODO for now we assume it's complete. Might be a good idea to check
253 // at least if its range matches the trace's range.
255 if (htFile
.exists()) {
256 /* Load an existing history */
257 final int version
= provider
.getVersion();
259 IStateHistoryBackend backend
= new HistoryTreeBackend(id
, htFile
, version
);
260 fHtBackend
= backend
;
261 fStateSystem
= StateSystemFactory
.newStateSystem(backend
, false);
262 fInitialized
.countDown();
264 } catch (IOException e
) {
266 * There was an error opening the existing file. Perhaps it was
267 * corrupted, perhaps it's an old version? We'll just
268 * fall-through and try to build a new one from scratch instead.
273 /* Size of the blocking queue to use when building a state history */
274 final int QUEUE_SIZE
= 10000;
277 IStateHistoryBackend backend
= new ThreadedHistoryTreeBackend(id
, htFile
,
278 provider
.getStartTime(), provider
.getVersion(), QUEUE_SIZE
);
279 fHtBackend
= backend
;
280 fStateSystem
= StateSystemFactory
.newStateSystem(backend
);
281 provider
.assignTargetStateSystem(fStateSystem
);
283 } catch (IOException e
) {
285 * If it fails here however, it means there was a problem writing to
286 * the disk, so throw a real exception this time.
288 throw new TmfTraceException(e
.toString(), e
);
293 * Create a new state system backed with a partial history. A partial
294 * history is similar to a "full" one (which you get with
295 * {@link #newFullHistory}), except that the file on disk is much smaller,
296 * but queries are a bit slower.
298 * Also note that single-queries are implemented using a full-query
299 * underneath, (which are much slower), so this might not be a good fit for
300 * a use case where you have to do lots of single queries.
302 private void createPartialHistory(String id
, ITmfStateProvider provider
, File htPartialFile
)
303 throws TmfTraceException
{
305 * The order of initializations is very tricky (but very important!)
306 * here. We need to follow this pattern:
307 * (1 is done before the call to this method)
309 * 1- Instantiate realStateProvider
310 * 2- Instantiate realBackend
311 * 3- Instantiate partialBackend, with prereqs:
312 * 3a- Instantiate partialProvider, via realProvider.getNew()
313 * 3b- Instantiate nullBackend (partialSS's backend)
314 * 3c- Instantiate partialSS
315 * 3d- partialProvider.assignSS(partialSS)
316 * 4- Instantiate realSS
317 * 5- partialSS.assignUpstream(realSS)
318 * 6- realProvider.assignSS(realSS)
319 * 7- Call HistoryBuilder(realProvider, realSS, partialBackend) to build the thing.
322 /* Size of the blocking queue to use when building a state history */
323 final int QUEUE_SIZE
= 10000;
325 final long granularity
= 50000;
328 IStateHistoryBackend realBackend
= null;
330 realBackend
= new ThreadedHistoryTreeBackend(id
, htPartialFile
,
331 provider
.getStartTime(), provider
.getVersion(), QUEUE_SIZE
);
332 } catch (IOException e
) {
333 throw new TmfTraceException(e
.toString(), e
);
337 ITmfStateProvider partialProvider
= provider
.getNewInstance();
339 /* 3b-3c, constructor automatically uses a NullBackend */
340 PartialStateSystem pss
= new PartialStateSystem();
343 partialProvider
.assignTargetStateSystem(pss
);
346 String partialId
= new String(id
+ ".partial"); //$NON-NLS-1$
347 IStateHistoryBackend partialBackend
=
348 new PartialHistoryBackend(partialId
, partialProvider
, pss
, realBackend
, granularity
);
351 @SuppressWarnings("restriction")
352 org
.eclipse
.tracecompass
.internal
.statesystem
.core
.StateSystem realSS
=
353 (org
.eclipse
.tracecompass
.internal
.statesystem
.core
.StateSystem
) StateSystemFactory
.newStateSystem(partialBackend
);
356 pss
.assignUpstream(realSS
);
359 provider
.assignTargetStateSystem(realSS
);
362 fHtBackend
= partialBackend
;
363 fStateSystem
= realSS
;
369 * Create a new state system using a null history back-end. This means that
370 * no history intervals will be saved anywhere, and as such only
371 * {@link ITmfStateSystem#queryOngoingState} will be available.
373 private void createNullHistory(String id
, ITmfStateProvider provider
) {
374 IStateHistoryBackend backend
= new NullBackend(id
);
375 fHtBackend
= backend
;
376 fStateSystem
= StateSystemFactory
.newStateSystem(backend
);
377 provider
.assignTargetStateSystem(fStateSystem
);
382 * Create a new state system using in-memory interval storage. This should
383 * only be done for very small state system, and will be naturally limited
386 private void createInMemoryHistory(String id
, ITmfStateProvider provider
) {
387 IStateHistoryBackend backend
= new InMemoryBackend(id
, provider
.getStartTime());
388 fHtBackend
= backend
;
389 fStateSystem
= StateSystemFactory
.newStateSystem(backend
);
390 provider
.assignTargetStateSystem(fStateSystem
);
394 private void disposeProvider(boolean deleteFiles
) {
395 ITmfStateProvider provider
= fStateProvider
;
396 if (provider
!= null) {
399 if (deleteFiles
&& (fHtBackend
!= null)) {
400 fHtBackend
.removeFiles();
404 private void build(ITmfStateProvider provider
) {
405 if ((fStateSystem
== null) || (fHtBackend
== null)) {
406 throw new IllegalArgumentException();
409 ITmfEventRequest request
= fRequest
;
410 if ((request
!= null) && (!request
.isCompleted())) {
414 fTimeRange
= TmfTimeRange
.ETERNITY
;
415 final ITmfTrace trace
= provider
.getTrace();
416 if (!isCompleteTrace(trace
)) {
417 fTimeRange
= trace
.getTimeRange();
420 fStateProvider
= provider
;
421 synchronized (fRequestSyncObj
) {
426 * The state system object is now created, we can consider this module
427 * "initialized" (components can retrieve it and start doing queries).
429 fInitialized
.countDown();
432 * Block the executeAnalysis() construction is complete (so that the
433 * progress monitor displays that it is running).
436 if (fRequest
!= null) {
437 fRequest
.waitForCompletion();
439 } catch (InterruptedException e
) {
444 private class StateSystemEventRequest
extends TmfEventRequest
{
445 private final ITmfStateProvider sci
;
446 private final ITmfTrace trace
;
448 public StateSystemEventRequest(ITmfStateProvider sp
, TmfTimeRange timeRange
, int index
) {
449 super(ITmfEvent
.class,
452 ITmfEventRequest
.ALL_DATA
,
453 ITmfEventRequest
.ExecutionType
.BACKGROUND
);
456 // sci.getTrace() will eventually return a @NonNull
457 trace
= checkNotNull(sci
.getTrace());
462 public void handleData(final ITmfEvent event
) {
463 super.handleData(event
);
464 if (event
.getTrace() == trace
) {
465 sci
.processEvent(event
);
466 } else if (trace
instanceof TmfExperiment
) {
468 * If the request is for an experiment, check if the event is
469 * from one of the child trace
471 for (ITmfTrace childTrace
: ((TmfExperiment
) trace
).getTraces()) {
472 if (childTrace
== event
.getTrace()) {
473 sci
.processEvent(event
);
480 public void handleSuccess() {
481 super.handleSuccess();
482 if (isCompleteTrace(trace
)) {
483 disposeProvider(false);
485 fNbRead
+= getNbRead();
486 synchronized (fRequestSyncObj
) {
487 final TmfTimeRange timeRange
= fTimeRange
;
488 if (timeRange
!= null) {
489 if (getRange().getEndTime().getValue() < timeRange
.getEndTime().getValue()) {
498 public void handleCancel() {
499 super.handleCancel();
500 if (isCompleteTrace(trace
)) {
501 disposeProvider(true);
506 public void handleFailure() {
507 super.handleFailure();
508 disposeProvider(true);
512 // ------------------------------------------------------------------------
513 // ITmfAnalysisModuleWithStateSystems
514 // ------------------------------------------------------------------------
518 public ITmfStateSystem
getStateSystem(String id
) {
519 if (id
.equals(getId())) {
526 public Iterable
<ITmfStateSystem
> getStateSystems() {
527 return checkNotNull(Collections
.<ITmfStateSystem
> singleton(fStateSystem
));
531 * Signal handler for the TmfTraceRangeUpdatedSignal signal
533 * @param signal The incoming signal
536 public void traceRangeUpdated(final TmfTraceRangeUpdatedSignal signal
) {
537 fTimeRange
= signal
.getRange();
538 ITmfStateProvider stateProvider
= fStateProvider
;
539 synchronized (fRequestSyncObj
) {
540 if (signal
.getTrace() == getTrace() && stateProvider
!= null && stateProvider
.getAssignedStateSystem() != null) {
541 ITmfEventRequest request
= fRequest
;
542 if ((request
== null) || request
.isCompleted()) {
549 private void startRequest() {
550 ITmfStateProvider stateProvider
= fStateProvider
;
551 TmfTimeRange timeRange
= fTimeRange
;
552 if (stateProvider
== null || timeRange
== null) {
555 ITmfEventRequest request
= new StateSystemEventRequest(stateProvider
, timeRange
, fNbRead
);
556 stateProvider
.getTrace().sendRequest(request
);
560 private static boolean isCompleteTrace(ITmfTrace trace
) {
561 return !(trace
instanceof ITmfTraceCompleteness
) || ((ITmfTraceCompleteness
) trace
).isComplete();