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
.HashMap
;
23 import java
.util
.concurrent
.CountDownLatch
;
25 import org
.apache
.commons
.io
.FileUtils
;
26 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
27 import org
.eclipse
.core
.runtime
.IStatus
;
28 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
29 import org
.eclipse
.jdt
.annotation
.NonNull
;
30 import org
.eclipse
.jdt
.annotation
.Nullable
;
31 import org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
;
32 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.statesystem
.backends
.partial
.PartialHistoryBackend
;
33 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.statesystem
.backends
.partial
.PartialStateSystem
;
34 import org
.eclipse
.tracecompass
.statesystem
.core
.ITmfStateSystem
;
35 import org
.eclipse
.tracecompass
.statesystem
.core
.ITmfStateSystemBuilder
;
36 import org
.eclipse
.tracecompass
.statesystem
.core
.StateSystemFactory
;
37 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.IStateHistoryBackend
;
38 import org
.eclipse
.tracecompass
.statesystem
.core
.backend
.StateHistoryBackendFactory
;
39 import org
.eclipse
.tracecompass
.tmf
.core
.analysis
.TmfAbstractAnalysisModule
;
40 import org
.eclipse
.tracecompass
.tmf
.core
.event
.ITmfEvent
;
41 import org
.eclipse
.tracecompass
.tmf
.core
.exceptions
.TmfTraceException
;
42 import org
.eclipse
.tracecompass
.tmf
.core
.project
.model
.ITmfPropertiesProvider
;
43 import org
.eclipse
.tracecompass
.tmf
.core
.request
.ITmfEventRequest
;
44 import org
.eclipse
.tracecompass
.tmf
.core
.request
.TmfEventRequest
;
45 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalHandler
;
46 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceRangeUpdatedSignal
;
47 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimeRange
;
48 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
49 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTraceCompleteness
;
50 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceManager
;
51 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceUtils
;
52 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.experiment
.TmfExperiment
;
55 * Abstract analysis module to generate a state system. It is a base class that
56 * can be used as a shortcut by analysis who just need to build a single state
57 * system with a state provider.
59 * Analysis implementing this class should only need to provide a state system
60 * and optionally a backend (default to NULL) and, if required, a filename
61 * (defaults to the analysis'ID)
63 * @author Geneviève Bastien
65 public abstract class TmfStateSystemAnalysisModule
extends TmfAbstractAnalysisModule
66 implements ITmfAnalysisModuleWithStateSystems
, ITmfPropertiesProvider
{
68 private static final String EXTENSION
= ".ht"; //$NON-NLS-1$
70 private final CountDownLatch fInitialized
= new CountDownLatch(1);
71 private final Object fRequestSyncObj
= new Object();
73 @Nullable private ITmfStateSystemBuilder fStateSystem
;
74 @Nullable private ITmfStateProvider fStateProvider
;
75 @Nullable private IStateHistoryBackend fHtBackend
;
76 @Nullable private ITmfEventRequest fRequest
;
77 @Nullable private TmfTimeRange fTimeRange
= null;
79 private int fNbRead
= 0;
80 private boolean fInitializationSucceeded
;
83 * State system backend types
85 * @author Geneviève Bastien
87 protected enum StateSystemBackendType
{
88 /** Full history in file */
90 /** In memory state system */
94 /** State system backed with partial history */
99 * Retrieve a state system belonging to trace, by passing the ID of the
100 * relevant analysis module.
102 * This will start the execution of the analysis module, and start the
103 * construction of the state system, if needed.
106 * The trace for which you want the state system
108 * The ID of the state system analysis module
109 * @return The state system, or null if there was no match or the module was
110 * not initialized correctly
112 public static @Nullable ITmfStateSystem
getStateSystem(ITmfTrace trace
, String moduleId
) {
113 TmfStateSystemAnalysisModule module
=
114 TmfTraceUtils
.getAnalysisModuleOfClass(trace
, TmfStateSystemAnalysisModule
.class, moduleId
);
115 if (module
!= null) {
116 ITmfStateSystem ss
= module
.getStateSystem();
120 IStatus status
= module
.schedule();
122 return module
.waitForInitialization() ? module
.getStateSystem() : null;
129 * Get the state provider for this analysis module
131 * @return the state provider
133 protected abstract ITmfStateProvider
createStateProvider();
136 * Get the state system backend type used by this module
138 * @return The {@link StateSystemBackendType}
140 protected StateSystemBackendType
getBackendType() {
141 /* Using full history by default, sub-classes can override */
142 return StateSystemBackendType
.FULL
;
146 * Get the supplementary file name where to save this state system. The
147 * default is the ID of the analysis followed by the extension.
149 * @return The supplementary file name
151 protected String
getSsFileName() {
152 return getId() + EXTENSION
;
156 * Get the state system generated by this analysis, or null if it is not yet
159 * @return The state system
162 public ITmfStateSystem
getStateSystem() {
170 public boolean waitForInitialization() {
172 fInitialized
.await();
173 } catch (InterruptedException e
) {
176 return fInitializationSucceeded
;
179 // ------------------------------------------------------------------------
180 // TmfAbstractAnalysisModule
181 // ------------------------------------------------------------------------
183 private @Nullable File
getSsFile() {
184 ITmfTrace trace
= getTrace();
188 String directory
= TmfTraceManager
.getSupplementaryFileDir(trace
);
189 File htFile
= new File(directory
+ getSsFileName());
194 protected boolean executeAnalysis(@Nullable final IProgressMonitor monitor
) {
195 IProgressMonitor mon
= (monitor
== null ?
new NullProgressMonitor() : monitor
);
196 final ITmfStateProvider provider
= createStateProvider();
200 /* FIXME: State systems should make use of the monitor, to be cancelled */
202 /* Get the state system according to backend */
203 StateSystemBackendType backend
= getBackendType();
206 ITmfTrace trace
= getTrace();
208 // Analysis was cancelled in the meantime
209 fInitializationSucceeded
= false;
210 fInitialized
.countDown();
215 File htFile
= getSsFile();
216 if (htFile
== null) {
219 createFullHistory(id
, provider
, htFile
);
223 File htFile
= getSsFile();
224 if (htFile
== null) {
227 createPartialHistory(id
, provider
, htFile
);
231 createInMemoryHistory(id
, provider
);
234 createNullHistory(id
, provider
);
239 } catch (TmfTraceException e
) {
240 fInitializationSucceeded
= false;
241 fInitialized
.countDown();
244 return !mon
.isCanceled();
248 protected void canceling() {
249 ITmfEventRequest req
= fRequest
;
250 if ((req
!= null) && (!req
.isCompleted())) {
256 public void dispose() {
258 if (fStateSystem
!= null) {
259 fStateSystem
.dispose();
263 // ------------------------------------------------------------------------
264 // History creation methods
265 // ------------------------------------------------------------------------
268 * Load the history file matching the target trace. If the file already
269 * exists, it will be opened directly. If not, it will be created from
272 private void createFullHistory(String id
, ITmfStateProvider provider
, File htFile
) throws TmfTraceException
{
274 /* If the target file already exists, do not rebuild it uselessly */
275 // TODO for now we assume it's complete. Might be a good idea to check
276 // at least if its range matches the trace's range.
278 if (htFile
.exists()) {
279 /* Load an existing history */
280 final int version
= provider
.getVersion();
282 IStateHistoryBackend backend
= StateHistoryBackendFactory
.createHistoryTreeBackendExistingFile(
283 id
, htFile
, version
);
284 fHtBackend
= backend
;
285 fStateSystem
= StateSystemFactory
.newStateSystem(backend
, false);
286 fInitializationSucceeded
= true;
287 fInitialized
.countDown();
289 } catch (IOException e
) {
291 * There was an error opening the existing file. Perhaps it was
292 * corrupted, perhaps it's an old version? We'll just
293 * fall-through and try to build a new one from scratch instead.
298 /* Size of the blocking queue to use when building a state history */
299 final int QUEUE_SIZE
= 10000;
302 IStateHistoryBackend backend
= StateHistoryBackendFactory
.createHistoryTreeBackendNewFile(
303 id
, htFile
, provider
.getVersion(), provider
.getStartTime(), QUEUE_SIZE
);
304 fHtBackend
= backend
;
305 fStateSystem
= StateSystemFactory
.newStateSystem(backend
);
306 provider
.assignTargetStateSystem(fStateSystem
);
308 } catch (IOException e
) {
310 * If it fails here however, it means there was a problem writing to
311 * the disk, so throw a real exception this time.
313 throw new TmfTraceException(e
.toString(), e
);
318 * Create a new state system backed with a partial history. A partial
319 * history is similar to a "full" one (which you get with
320 * {@link #newFullHistory}), except that the file on disk is much smaller,
321 * but queries are a bit slower.
323 * Also note that single-queries are implemented using a full-query
324 * underneath, (which are much slower), so this might not be a good fit for
325 * a use case where you have to do lots of single queries.
327 private void createPartialHistory(String id
, ITmfStateProvider provider
, File htPartialFile
)
328 throws TmfTraceException
{
330 * The order of initializations is very tricky (but very important!)
331 * here. We need to follow this pattern:
332 * (1 is done before the call to this method)
334 * 1- Instantiate realStateProvider
335 * 2- Instantiate realBackend
336 * 3- Instantiate partialBackend, with prereqs:
337 * 3a- Instantiate partialProvider, via realProvider.getNew()
338 * 3b- Instantiate nullBackend (partialSS's backend)
339 * 3c- Instantiate partialSS
340 * 3d- partialProvider.assignSS(partialSS)
341 * 4- Instantiate realSS
342 * 5- partialSS.assignUpstream(realSS)
343 * 6- realProvider.assignSS(realSS)
344 * 7- Call HistoryBuilder(realProvider, realSS, partialBackend) to build the thing.
347 /* Size of the blocking queue to use when building a state history */
348 final int QUEUE_SIZE
= 10000;
350 final long granularity
= 50000;
353 IStateHistoryBackend realBackend
= null;
355 realBackend
= StateHistoryBackendFactory
.createHistoryTreeBackendNewFile(
356 id
, htPartialFile
, provider
.getVersion(), provider
.getStartTime(), QUEUE_SIZE
);
357 } catch (IOException e
) {
358 throw new TmfTraceException(e
.toString(), e
);
362 ITmfStateProvider partialProvider
= provider
.getNewInstance();
364 /* 3b-3c, constructor automatically uses a NullBackend */
365 PartialStateSystem pss
= new PartialStateSystem();
368 partialProvider
.assignTargetStateSystem(pss
);
371 IStateHistoryBackend partialBackend
= new PartialHistoryBackend(id
+ ".partial", partialProvider
, pss
, realBackend
, granularity
); //$NON-NLS-1$
374 @SuppressWarnings("restriction")
375 org
.eclipse
.tracecompass
.internal
.statesystem
.core
.StateSystem realSS
=
376 (org
.eclipse
.tracecompass
.internal
.statesystem
.core
.StateSystem
) StateSystemFactory
.newStateSystem(partialBackend
);
379 pss
.assignUpstream(realSS
);
382 provider
.assignTargetStateSystem(realSS
);
385 fHtBackend
= partialBackend
;
386 fStateSystem
= realSS
;
392 * Create a new state system using a null history back-end. This means that
393 * no history intervals will be saved anywhere, and as such only
394 * {@link ITmfStateSystem#queryOngoingState} will be available.
396 private void createNullHistory(String id
, ITmfStateProvider provider
) {
397 IStateHistoryBackend backend
= StateHistoryBackendFactory
.createNullBackend(id
);
398 fHtBackend
= backend
;
399 fStateSystem
= StateSystemFactory
.newStateSystem(backend
);
400 provider
.assignTargetStateSystem(fStateSystem
);
405 * Create a new state system using in-memory interval storage. This should
406 * only be done for very small state system, and will be naturally limited
409 private void createInMemoryHistory(String id
, ITmfStateProvider provider
) {
410 IStateHistoryBackend backend
= StateHistoryBackendFactory
.createInMemoryBackend(id
, provider
.getStartTime());
411 fHtBackend
= backend
;
412 fStateSystem
= StateSystemFactory
.newStateSystem(backend
);
413 provider
.assignTargetStateSystem(fStateSystem
);
417 private void disposeProvider(boolean deleteFiles
) {
418 ITmfStateProvider provider
= fStateProvider
;
419 if (provider
!= null) {
422 if (deleteFiles
&& (fHtBackend
!= null)) {
423 fHtBackend
.removeFiles();
427 private void build(ITmfStateProvider provider
) {
428 if ((fStateSystem
== null) || (fHtBackend
== null)) {
429 throw new IllegalArgumentException();
432 ITmfEventRequest request
= fRequest
;
433 if ((request
!= null) && (!request
.isCompleted())) {
437 fTimeRange
= TmfTimeRange
.ETERNITY
;
438 final ITmfTrace trace
= provider
.getTrace();
439 if (!isCompleteTrace(trace
)) {
440 fTimeRange
= trace
.getTimeRange();
443 fStateProvider
= provider
;
444 synchronized (fRequestSyncObj
) {
449 * The state system object is now created, we can consider this module
450 * "initialized" (components can retrieve it and start doing queries).
452 fInitializationSucceeded
= true;
453 fInitialized
.countDown();
456 * Block the executeAnalysis() construction is complete (so that the
457 * progress monitor displays that it is running).
460 if (fRequest
!= null) {
461 fRequest
.waitForCompletion();
463 } catch (InterruptedException e
) {
468 private class StateSystemEventRequest
extends TmfEventRequest
{
469 private final ITmfStateProvider sci
;
470 private final ITmfTrace trace
;
472 public StateSystemEventRequest(ITmfStateProvider sp
, TmfTimeRange timeRange
, int index
) {
473 super(ITmfEvent
.class,
476 ITmfEventRequest
.ALL_DATA
,
477 ITmfEventRequest
.ExecutionType
.BACKGROUND
);
480 // sci.getTrace() will eventually return a @NonNull
481 trace
= checkNotNull(sci
.getTrace());
486 public void handleData(final ITmfEvent event
) {
487 super.handleData(event
);
488 if (event
.getTrace() == trace
) {
489 sci
.processEvent(event
);
490 } else if (trace
instanceof TmfExperiment
) {
492 * If the request is for an experiment, check if the event is
493 * from one of the child trace
495 for (ITmfTrace childTrace
: ((TmfExperiment
) trace
).getTraces()) {
496 if (childTrace
== event
.getTrace()) {
497 sci
.processEvent(event
);
504 public void handleSuccess() {
505 super.handleSuccess();
506 if (isCompleteTrace(trace
)) {
507 disposeProvider(false);
509 fNbRead
+= getNbRead();
510 synchronized (fRequestSyncObj
) {
511 final TmfTimeRange timeRange
= fTimeRange
;
512 if (timeRange
!= null) {
513 if (getRange().getEndTime().getValue() < timeRange
.getEndTime().getValue()) {
522 public void handleCancel() {
523 super.handleCancel();
524 if (isCompleteTrace(trace
)) {
525 disposeProvider(true);
530 public void handleFailure() {
531 super.handleFailure();
532 disposeProvider(true);
536 // ------------------------------------------------------------------------
537 // ITmfAnalysisModuleWithStateSystems
538 // ------------------------------------------------------------------------
542 public ITmfStateSystem
getStateSystem(String id
) {
543 if (id
.equals(getId())) {
550 public @NonNull Iterable
<@NonNull ITmfStateSystem
> getStateSystems() {
551 ITmfStateSystemBuilder stateSystem
= fStateSystem
;
552 if (stateSystem
== null) {
553 return Collections
.EMPTY_SET
;
555 return Collections
.singleton(stateSystem
);
559 * Signal handler for the TmfTraceRangeUpdatedSignal signal
561 * @param signal The incoming signal
564 public void traceRangeUpdated(final TmfTraceRangeUpdatedSignal signal
) {
565 fTimeRange
= signal
.getRange();
566 ITmfStateProvider stateProvider
= fStateProvider
;
567 synchronized (fRequestSyncObj
) {
568 if (signal
.getTrace() == getTrace() && stateProvider
!= null && stateProvider
.getAssignedStateSystem() != null) {
569 ITmfEventRequest request
= fRequest
;
570 if ((request
== null) || request
.isCompleted()) {
577 private void startRequest() {
578 ITmfStateProvider stateProvider
= fStateProvider
;
579 TmfTimeRange timeRange
= fTimeRange
;
580 if (stateProvider
== null || timeRange
== null) {
583 ITmfEventRequest request
= new StateSystemEventRequest(stateProvider
, timeRange
, fNbRead
);
584 stateProvider
.getTrace().sendRequest(request
);
588 private static boolean isCompleteTrace(ITmfTrace trace
) {
589 return !(trace
instanceof ITmfTraceCompleteness
) || ((ITmfTraceCompleteness
) trace
).isComplete();
592 // ------------------------------------------------------------------------
593 // ITmfPropertiesProvider
594 // ------------------------------------------------------------------------
600 public @NonNull Map
<@NonNull String
, @NonNull String
> getProperties() {
601 Map
<@NonNull String
, @NonNull String
> properties
= new HashMap
<>();
603 StateSystemBackendType backend
= getBackendType();
604 properties
.put(NonNullUtils
.checkNotNull(Messages
.TmfStateSystemAnalysisModule_PropertiesBackend
), NonNullUtils
.checkNotNull(backend
.name()));
608 File htFile
= getSsFile();
609 if (htFile
!= null) {
610 if (htFile
.exists()) {
611 properties
.put(NonNullUtils
.checkNotNull(Messages
.TmfStateSystemAnalysisModule_PropertiesFileSize
), FileUtils
.byteCountToDisplaySize(htFile
.length()));
613 properties
.put(NonNullUtils
.checkNotNull(Messages
.TmfStateSystemAnalysisModule_PropertiesFileSize
), NonNullUtils
.checkNotNull(Messages
.TmfStateSystemAnalysisModule_PropertiesAnalysisNotExecuted
));