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
.NullProgressMonitor
;
23 import org
.eclipse
.jdt
.annotation
.NonNull
;
24 import org
.eclipse
.jdt
.annotation
.NonNullByDefault
;
25 import org
.eclipse
.jdt
.annotation
.Nullable
;
26 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.statesystem
.backends
.partial
.PartialHistoryBackend
;
27 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.statesystem
.backends
.partial
.PartialStateSystem
;
28 import org
.eclipse
.tracecompass
.statesystem
.core
.ITmfStateSystem
;
29 import org
.eclipse
.tracecompass
.statesystem
.core
.ITmfStateSystemBuilder
;
30 import org
.eclipse
.tracecompass
.statesystem
.core
.StateSystemFactory
;
31 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.IStateHistoryBackend
;
32 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.InMemoryBackend
;
33 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.NullBackend
;
34 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.historytree
.HistoryTreeBackend
;
35 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.historytree
.ThreadedHistoryTreeBackend
;
36 import org
.eclipse
.tracecompass
.tmf
.core
.analysis
.TmfAbstractAnalysisModule
;
37 import org
.eclipse
.tracecompass
.tmf
.core
.event
.ITmfEvent
;
38 import org
.eclipse
.tracecompass
.tmf
.core
.exceptions
.TmfTraceException
;
39 import org
.eclipse
.tracecompass
.tmf
.core
.request
.ITmfEventRequest
;
40 import org
.eclipse
.tracecompass
.tmf
.core
.request
.TmfEventRequest
;
41 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimeRange
;
42 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
43 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfExperiment
;
44 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceManager
;
47 * Abstract analysis module to generate a state system. It is a base class that
48 * can be used as a shortcut by analysis who just need to build a single state
49 * system with a state provider.
51 * Analysis implementing this class should only need to provide a state system
52 * and optionally a backend (default to NULL) and, if required, a filename
53 * (defaults to the analysis'ID)
55 * @author Geneviève Bastien
59 public abstract class TmfStateSystemAnalysisModule
extends TmfAbstractAnalysisModule
60 implements ITmfAnalysisModuleWithStateSystems
{
62 private static final String EXTENSION
= ".ht"; //$NON-NLS-1$
64 private final CountDownLatch fInitialized
= new CountDownLatch(1);
66 @Nullable private ITmfStateSystemBuilder fStateSystem
;
67 @Nullable private ITmfStateProvider fStateProvider
;
68 @Nullable private IStateHistoryBackend fHtBackend
;
69 @Nullable private ITmfEventRequest fRequest
;
72 * State system backend types
74 * @author Geneviève Bastien
76 protected enum StateSystemBackendType
{
77 /** Full history in file */
79 /** In memory state system */
83 /** State system backed with partial history */
89 * Retrieve a state system belonging to trace, by passing the ID of the
90 * relevant analysis module.
92 * This will start the execution of the analysis module, and start the
93 * construction of the state system, if needed.
96 * The trace for which you want the state system
98 * The ID of the state system analysis module
99 * @return The state system, or null if there was no match
102 public static @Nullable ITmfStateSystem
getStateSystem(ITmfTrace trace
, String moduleId
) {
103 TmfStateSystemAnalysisModule module
=
104 trace
.getAnalysisModuleOfClass(TmfStateSystemAnalysisModule
.class, moduleId
);
105 if (module
!= null) {
107 module
.waitForInitialization();
109 * FIXME If we keep a reference to "module", the compiler expects us to
110 * close it. The Analysis Module's API should be reworked to not expose
111 * these objects directly (utility classes instead?)
113 return module
.getStateSystem();
119 * Get the state provider for this analysis module
121 * @return the state provider
123 protected abstract ITmfStateProvider
createStateProvider();
126 * Get the state system backend type used by this module
128 * @return The {@link StateSystemBackendType}
130 protected StateSystemBackendType
getBackendType() {
131 /* Using full history by default, sub-classes can override */
132 return StateSystemBackendType
.FULL
;
136 * Get the supplementary file name where to save this state system. The
137 * default is the ID of the analysis followed by the extension.
139 * @return The supplementary file name
141 protected String
getSsFileName() {
142 return getId() + EXTENSION
;
146 * Get the state system generated by this analysis, or null if it is not yet
149 * @return The state system
152 public ITmfStateSystem
getStateSystem() {
157 * Block the calling thread until the analysis module has been initialized.
158 * After this method returns, {@link #getStateSystem()} should not return
161 public void waitForInitialization() {
163 fInitialized
.await();
164 } catch (InterruptedException e
) {}
167 // ------------------------------------------------------------------------
168 // TmfAbstractAnalysisModule
169 // ------------------------------------------------------------------------
172 protected boolean executeAnalysis(@Nullable final IProgressMonitor monitor
) {
173 IProgressMonitor mon
= (monitor
== null ?
new NullProgressMonitor() : monitor
);
174 final ITmfStateProvider provider
= createStateProvider();
178 /* FIXME: State systems should make use of the monitor, to be cancelled */
180 /* Get the state system according to backend */
181 StateSystemBackendType backend
= getBackendType();
186 directory
= TmfTraceManager
.getSupplementaryFileDir(getTrace());
187 htFile
= new File(directory
+ getSsFileName());
188 createFullHistory(id
, provider
, htFile
);
191 directory
= TmfTraceManager
.getSupplementaryFileDir(getTrace());
192 htFile
= new File(directory
+ getSsFileName());
193 createPartialHistory(id
, provider
, htFile
);
196 createInMemoryHistory(id
, provider
);
199 createNullHistory(id
, provider
);
204 } catch (TmfTraceException e
) {
207 return !mon
.isCanceled();
211 protected void canceling() {
212 ITmfEventRequest req
= fRequest
;
213 if ((req
!= null) && (!req
.isCompleted())) {
219 public void dispose() {
221 if (fStateSystem
!= null) {
222 fStateSystem
.dispose();
226 // ------------------------------------------------------------------------
227 // History creation methods
228 // ------------------------------------------------------------------------
231 * Load the history file matching the target trace. If the file already
232 * exists, it will be opened directly. If not, it will be created from
235 private void createFullHistory(String id
, ITmfStateProvider provider
, File htFile
) throws TmfTraceException
{
237 /* If the target file already exists, do not rebuild it uselessly */
238 // TODO for now we assume it's complete. Might be a good idea to check
239 // at least if its range matches the trace's range.
241 if (htFile
.exists()) {
242 /* Load an existing history */
243 final int version
= provider
.getVersion();
245 IStateHistoryBackend backend
= new HistoryTreeBackend(htFile
, version
);
246 fHtBackend
= backend
;
247 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
, false);
248 fInitialized
.countDown();
250 } catch (IOException e
) {
252 * There was an error opening the existing file. Perhaps it was
253 * corrupted, perhaps it's an old version? We'll just
254 * fall-through and try to build a new one from scratch instead.
259 /* Size of the blocking queue to use when building a state history */
260 final int QUEUE_SIZE
= 10000;
263 IStateHistoryBackend backend
= new ThreadedHistoryTreeBackend(htFile
,
264 provider
.getStartTime(), provider
.getVersion(), QUEUE_SIZE
);
265 fHtBackend
= backend
;
266 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
);
267 provider
.assignTargetStateSystem(fStateSystem
);
269 } catch (IOException e
) {
271 * If it fails here however, it means there was a problem writing to
272 * the disk, so throw a real exception this time.
274 throw new TmfTraceException(e
.toString(), e
);
279 * Create a new state system backed with a partial history. A partial
280 * history is similar to a "full" one (which you get with
281 * {@link #newFullHistory}), except that the file on disk is much smaller,
282 * but queries are a bit slower.
284 * Also note that single-queries are implemented using a full-query
285 * underneath, (which are much slower), so this might not be a good fit for
286 * a use case where you have to do lots of single queries.
288 private void createPartialHistory(String id
, ITmfStateProvider provider
, File htPartialFile
)
289 throws TmfTraceException
{
291 * The order of initializations is very tricky (but very important!)
292 * here. We need to follow this pattern:
293 * (1 is done before the call to this method)
295 * 1- Instantiate realStateProvider
296 * 2- Instantiate realBackend
297 * 3- Instantiate partialBackend, with prereqs:
298 * 3a- Instantiate partialProvider, via realProvider.getNew()
299 * 3b- Instantiate nullBackend (partialSS's backend)
300 * 3c- Instantiate partialSS
301 * 3d- partialProvider.assignSS(partialSS)
302 * 4- Instantiate realSS
303 * 5- partialSS.assignUpstream(realSS)
304 * 6- realProvider.assignSS(realSS)
305 * 7- Call HistoryBuilder(realProvider, realSS, partialBackend) to build the thing.
308 /* Size of the blocking queue to use when building a state history */
309 final int QUEUE_SIZE
= 10000;
311 final long granularity
= 50000;
314 IStateHistoryBackend realBackend
= null;
316 realBackend
= new ThreadedHistoryTreeBackend(htPartialFile
,
317 provider
.getStartTime(), provider
.getVersion(), QUEUE_SIZE
);
318 } catch (IOException e
) {
319 throw new TmfTraceException(e
.toString(), e
);
323 ITmfStateProvider partialProvider
= provider
.getNewInstance();
325 /* 3b-3c, constructor automatically uses a NullBackend */
326 PartialStateSystem pss
= new PartialStateSystem();
329 partialProvider
.assignTargetStateSystem(pss
);
332 IStateHistoryBackend partialBackend
=
333 new PartialHistoryBackend(partialProvider
, pss
, realBackend
, granularity
);
336 @SuppressWarnings("restriction")
337 org
.eclipse
.tracecompass
.internal
.statesystem
.core
.StateSystem realSS
=
338 (org
.eclipse
.tracecompass
.internal
.statesystem
.core
.StateSystem
) StateSystemFactory
.newStateSystem(id
, partialBackend
);
341 pss
.assignUpstream(realSS
);
344 provider
.assignTargetStateSystem(realSS
);
347 fHtBackend
= partialBackend
;
348 fStateSystem
= realSS
;
354 * Create a new state system using a null history back-end. This means that
355 * no history intervals will be saved anywhere, and as such only
356 * {@link ITmfStateSystem#queryOngoingState} will be available.
358 private void createNullHistory(String id
, ITmfStateProvider provider
) {
359 IStateHistoryBackend backend
= new NullBackend();
360 fHtBackend
= backend
;
361 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
);
362 provider
.assignTargetStateSystem(fStateSystem
);
367 * Create a new state system using in-memory interval storage. This should
368 * only be done for very small state system, and will be naturally limited
371 private void createInMemoryHistory(String id
, ITmfStateProvider provider
) {
372 IStateHistoryBackend backend
= new InMemoryBackend(provider
.getStartTime());
373 fHtBackend
= backend
;
374 fStateSystem
= StateSystemFactory
.newStateSystem(id
, backend
);
375 provider
.assignTargetStateSystem(fStateSystem
);
379 private void disposeProvider(boolean deleteFiles
) {
380 ITmfStateProvider provider
= fStateProvider
;
381 if (provider
!= null) {
384 if (deleteFiles
&& (fHtBackend
!= null)) {
385 fHtBackend
.removeFiles();
389 private void build(ITmfStateProvider provider
) {
390 if ((fStateSystem
== null) || (fHtBackend
== null)) {
391 throw new IllegalArgumentException();
394 ITmfEventRequest request
= fRequest
;
395 if ((request
!= null) && (!request
.isCompleted())) {
399 request
= new StateSystemEventRequest(provider
);
400 provider
.getTrace().sendRequest(request
);
403 * Only now that we've actually started the build, we'll update the
404 * class fields, so that they become visible for other callers.
406 fStateProvider
= provider
;
410 * The state system object is now created, we can consider this module
411 * "initialized" (components can retrieve it and start doing queries).
413 fInitialized
.countDown();
416 * Block the executeAnalysis() construction is complete (so that the
417 * progress monitor displays that it is running).
420 request
.waitForCompletion();
421 } catch (InterruptedException e
) {
426 private class StateSystemEventRequest
extends TmfEventRequest
{
427 private final ITmfStateProvider sci
;
428 private final ITmfTrace trace
;
430 public StateSystemEventRequest(ITmfStateProvider sp
) {
431 super(sp
.getExpectedEventType(),
432 TmfTimeRange
.ETERNITY
,
434 ITmfEventRequest
.ALL_DATA
,
435 ITmfEventRequest
.ExecutionType
.BACKGROUND
);
438 // sci.getTrace() will eventually return a @NonNull
439 @SuppressWarnings("null")
440 @NonNull ITmfTrace tr
= sci
.getTrace();
446 public void handleData(final ITmfEvent event
) {
447 super.handleData(event
);
448 if (event
.getTrace() == trace
) {
449 sci
.processEvent(event
);
450 } else if (trace
instanceof TmfExperiment
) {
452 * If the request is for an experiment, check if the event is
453 * from one of the child trace
455 for (ITmfTrace childTrace
: ((TmfExperiment
) trace
).getTraces()) {
456 if (childTrace
== event
.getTrace()) {
457 sci
.processEvent(event
);
464 public void handleSuccess() {
465 super.handleSuccess();
466 disposeProvider(false);
470 public void handleCancel() {
471 super.handleCancel();
472 disposeProvider(true);
476 public void handleFailure() {
477 super.handleFailure();
478 disposeProvider(true);
482 // ------------------------------------------------------------------------
483 // ITmfAnalysisModuleWithStateSystems
484 // ------------------------------------------------------------------------
488 public ITmfStateSystem
getStateSystem(String id
) {
489 if (id
.equals(getId())) {
496 public Iterable
<ITmfStateSystem
> getStateSystems() {
497 @SuppressWarnings("null")
498 @NonNull Iterable
<ITmfStateSystem
> ret
= Collections
.singleton((ITmfStateSystem
) fStateSystem
);