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
.timestamp
.TmfTimeRange
;
43 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
44 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfExperiment
;
45 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceManager
;
48 * Abstract analysis module to generate a state system. It is a base class that
49 * can be used as a shortcut by analysis who just need to build a single state
50 * system with a state provider.
52 * Analysis implementing this class should only need to provide a state system
53 * and optionally a backend (default to NULL) and, if required, a filename
54 * (defaults to the analysis'ID)
56 * @author Geneviève Bastien
60 public abstract class TmfStateSystemAnalysisModule
extends TmfAbstractAnalysisModule
61 implements ITmfAnalysisModuleWithStateSystems
{
63 private static final String EXTENSION
= ".ht"; //$NON-NLS-1$
65 private final CountDownLatch fInitialized
= new CountDownLatch(1);
67 @Nullable private ITmfStateSystemBuilder fStateSystem
;
68 @Nullable private ITmfStateProvider fStateProvider
;
69 @Nullable private IStateHistoryBackend fHtBackend
;
70 @Nullable private ITmfEventRequest fRequest
;
73 * State system backend types
75 * @author Geneviève Bastien
77 protected enum StateSystemBackendType
{
78 /** Full history in file */
80 /** In memory state system */
84 /** State system backed with partial history */
90 * Retrieve a state system belonging to trace, by passing the ID of the
91 * relevant analysis module.
93 * This will start the execution of the analysis module, and start the
94 * construction of the state system, if needed.
97 * The trace for which you want the state system
99 * The ID of the state system analysis module
100 * @return The state system, or null if there was no match
103 public static @Nullable ITmfStateSystem
getStateSystem(ITmfTrace trace
, String moduleId
) {
104 TmfStateSystemAnalysisModule module
=
105 trace
.getAnalysisModuleOfClass(TmfStateSystemAnalysisModule
.class, moduleId
);
106 if (module
!= null) {
107 IStatus status
= module
.schedule();
109 module
.waitForInitialization();
111 * FIXME If we keep a reference to "module", the compiler expects us to
112 * close it. The Analysis Module's API should be reworked to not expose
113 * these objects directly (utility classes instead?)
115 return module
.getStateSystem();
122 * Get the state provider for this analysis module
124 * @return the state provider
126 protected abstract ITmfStateProvider
createStateProvider();
129 * Get the state system backend type used by this module
131 * @return The {@link StateSystemBackendType}
133 protected StateSystemBackendType
getBackendType() {
134 /* Using full history by default, sub-classes can override */
135 return StateSystemBackendType
.FULL
;
139 * Get the supplementary file name where to save this state system. The
140 * default is the ID of the analysis followed by the extension.
142 * @return The supplementary file name
144 protected String
getSsFileName() {
145 return getId() + EXTENSION
;
149 * Get the state system generated by this analysis, or null if it is not yet
152 * @return The state system
155 public ITmfStateSystem
getStateSystem() {
160 * Block the calling thread until the analysis module has been initialized.
161 * After this method returns, {@link #getStateSystem()} should not return
164 public void waitForInitialization() {
166 fInitialized
.await();
167 } catch (InterruptedException e
) {}
170 // ------------------------------------------------------------------------
171 // TmfAbstractAnalysisModule
172 // ------------------------------------------------------------------------
175 protected boolean executeAnalysis(@Nullable final IProgressMonitor monitor
) {
176 IProgressMonitor mon
= (monitor
== null ?
new NullProgressMonitor() : monitor
);
177 final ITmfStateProvider provider
= createStateProvider();
181 /* FIXME: State systems should make use of the monitor, to be cancelled */
183 /* Get the state system according to backend */
184 StateSystemBackendType backend
= getBackendType();
188 ITmfTrace trace
= getTrace();
190 // Analysis was cancelled in the meantime
191 fInitialized
.countDown();
196 directory
= TmfTraceManager
.getSupplementaryFileDir(trace
);
197 htFile
= new File(directory
+ getSsFileName());
198 createFullHistory(id
, provider
, htFile
);
201 directory
= TmfTraceManager
.getSupplementaryFileDir(trace
);
202 htFile
= new File(directory
+ getSsFileName());
203 createPartialHistory(id
, provider
, htFile
);
206 createInMemoryHistory(id
, provider
);
209 createNullHistory(id
, provider
);
214 } catch (TmfTraceException e
) {
215 fInitialized
.countDown();
218 return !mon
.isCanceled();
222 protected void canceling() {
223 ITmfEventRequest req
= fRequest
;
224 if ((req
!= null) && (!req
.isCompleted())) {
230 public void dispose() {
232 if (fStateSystem
!= null) {
233 fStateSystem
.dispose();
237 // ------------------------------------------------------------------------
238 // History creation methods
239 // ------------------------------------------------------------------------
242 * Load the history file matching the target trace. If the file already
243 * exists, it will be opened directly. If not, it will be created from
246 private void createFullHistory(String id
, ITmfStateProvider provider
, File htFile
) throws TmfTraceException
{
248 /* If the target file already exists, do not rebuild it uselessly */
249 // TODO for now we assume it's complete. Might be a good idea to check
250 // at least if its range matches the trace's range.
252 if (htFile
.exists()) {
253 /* Load an existing history */
254 final int version
= provider
.getVersion();
256 IStateHistoryBackend backend
= new HistoryTreeBackend(htFile
, version
);
257 fHtBackend
= backend
;
258 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
, false);
259 fInitialized
.countDown();
261 } catch (IOException e
) {
263 * There was an error opening the existing file. Perhaps it was
264 * corrupted, perhaps it's an old version? We'll just
265 * fall-through and try to build a new one from scratch instead.
270 /* Size of the blocking queue to use when building a state history */
271 final int QUEUE_SIZE
= 10000;
274 IStateHistoryBackend backend
= new ThreadedHistoryTreeBackend(htFile
,
275 provider
.getStartTime(), provider
.getVersion(), QUEUE_SIZE
);
276 fHtBackend
= backend
;
277 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
);
278 provider
.assignTargetStateSystem(fStateSystem
);
280 } catch (IOException e
) {
282 * If it fails here however, it means there was a problem writing to
283 * the disk, so throw a real exception this time.
285 throw new TmfTraceException(e
.toString(), e
);
290 * Create a new state system backed with a partial history. A partial
291 * history is similar to a "full" one (which you get with
292 * {@link #newFullHistory}), except that the file on disk is much smaller,
293 * but queries are a bit slower.
295 * Also note that single-queries are implemented using a full-query
296 * underneath, (which are much slower), so this might not be a good fit for
297 * a use case where you have to do lots of single queries.
299 private void createPartialHistory(String id
, ITmfStateProvider provider
, File htPartialFile
)
300 throws TmfTraceException
{
302 * The order of initializations is very tricky (but very important!)
303 * here. We need to follow this pattern:
304 * (1 is done before the call to this method)
306 * 1- Instantiate realStateProvider
307 * 2- Instantiate realBackend
308 * 3- Instantiate partialBackend, with prereqs:
309 * 3a- Instantiate partialProvider, via realProvider.getNew()
310 * 3b- Instantiate nullBackend (partialSS's backend)
311 * 3c- Instantiate partialSS
312 * 3d- partialProvider.assignSS(partialSS)
313 * 4- Instantiate realSS
314 * 5- partialSS.assignUpstream(realSS)
315 * 6- realProvider.assignSS(realSS)
316 * 7- Call HistoryBuilder(realProvider, realSS, partialBackend) to build the thing.
319 /* Size of the blocking queue to use when building a state history */
320 final int QUEUE_SIZE
= 10000;
322 final long granularity
= 50000;
325 IStateHistoryBackend realBackend
= null;
327 realBackend
= new ThreadedHistoryTreeBackend(htPartialFile
,
328 provider
.getStartTime(), provider
.getVersion(), QUEUE_SIZE
);
329 } catch (IOException e
) {
330 throw new TmfTraceException(e
.toString(), e
);
334 ITmfStateProvider partialProvider
= provider
.getNewInstance();
336 /* 3b-3c, constructor automatically uses a NullBackend */
337 PartialStateSystem pss
= new PartialStateSystem();
340 partialProvider
.assignTargetStateSystem(pss
);
343 IStateHistoryBackend partialBackend
=
344 new PartialHistoryBackend(partialProvider
, pss
, realBackend
, granularity
);
347 @SuppressWarnings("restriction")
348 org
.eclipse
.tracecompass
.internal
.statesystem
.core
.StateSystem realSS
=
349 (org
.eclipse
.tracecompass
.internal
.statesystem
.core
.StateSystem
) StateSystemFactory
.newStateSystem(id
, partialBackend
);
352 pss
.assignUpstream(realSS
);
355 provider
.assignTargetStateSystem(realSS
);
358 fHtBackend
= partialBackend
;
359 fStateSystem
= realSS
;
365 * Create a new state system using a null history back-end. This means that
366 * no history intervals will be saved anywhere, and as such only
367 * {@link ITmfStateSystem#queryOngoingState} will be available.
369 private void createNullHistory(String id
, ITmfStateProvider provider
) {
370 IStateHistoryBackend backend
= new NullBackend();
371 fHtBackend
= backend
;
372 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
);
373 provider
.assignTargetStateSystem(fStateSystem
);
378 * Create a new state system using in-memory interval storage. This should
379 * only be done for very small state system, and will be naturally limited
382 private void createInMemoryHistory(String id
, ITmfStateProvider provider
) {
383 IStateHistoryBackend backend
= new InMemoryBackend(provider
.getStartTime());
384 fHtBackend
= backend
;
385 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
);
386 provider
.assignTargetStateSystem(fStateSystem
);
390 private void disposeProvider(boolean deleteFiles
) {
391 ITmfStateProvider provider
= fStateProvider
;
392 if (provider
!= null) {
395 if (deleteFiles
&& (fHtBackend
!= null)) {
396 fHtBackend
.removeFiles();
400 private void build(ITmfStateProvider provider
) {
401 if ((fStateSystem
== null) || (fHtBackend
== null)) {
402 throw new IllegalArgumentException();
405 ITmfEventRequest request
= fRequest
;
406 if ((request
!= null) && (!request
.isCompleted())) {
410 request
= new StateSystemEventRequest(provider
);
411 provider
.getTrace().sendRequest(request
);
414 * Only now that we've actually started the build, we'll update the
415 * class fields, so that they become visible for other callers.
417 fStateProvider
= provider
;
421 * The state system object is now created, we can consider this module
422 * "initialized" (components can retrieve it and start doing queries).
424 fInitialized
.countDown();
427 * Block the executeAnalysis() construction is complete (so that the
428 * progress monitor displays that it is running).
431 request
.waitForCompletion();
432 } catch (InterruptedException e
) {
437 private class StateSystemEventRequest
extends TmfEventRequest
{
438 private final ITmfStateProvider sci
;
439 private final ITmfTrace trace
;
441 public StateSystemEventRequest(ITmfStateProvider sp
) {
442 super(sp
.getExpectedEventType(),
443 TmfTimeRange
.ETERNITY
,
445 ITmfEventRequest
.ALL_DATA
,
446 ITmfEventRequest
.ExecutionType
.BACKGROUND
);
449 // sci.getTrace() will eventually return a @NonNull
450 @SuppressWarnings("null")
451 @NonNull ITmfTrace tr
= sci
.getTrace();
457 public void handleData(final ITmfEvent event
) {
458 super.handleData(event
);
459 if (event
.getTrace() == trace
) {
460 sci
.processEvent(event
);
461 } else if (trace
instanceof TmfExperiment
) {
463 * If the request is for an experiment, check if the event is
464 * from one of the child trace
466 for (ITmfTrace childTrace
: ((TmfExperiment
) trace
).getTraces()) {
467 if (childTrace
== event
.getTrace()) {
468 sci
.processEvent(event
);
475 public void handleSuccess() {
476 super.handleSuccess();
477 disposeProvider(false);
481 public void handleCancel() {
482 super.handleCancel();
483 disposeProvider(true);
487 public void handleFailure() {
488 super.handleFailure();
489 disposeProvider(true);
493 // ------------------------------------------------------------------------
494 // ITmfAnalysisModuleWithStateSystems
495 // ------------------------------------------------------------------------
499 public ITmfStateSystem
getStateSystem(String id
) {
500 if (id
.equals(getId())) {
507 public Iterable
<ITmfStateSystem
> getStateSystems() {
508 @SuppressWarnings("null")
509 @NonNull Iterable
<ITmfStateSystem
> ret
= Collections
.singleton((ITmfStateSystem
) fStateSystem
);