ss: Move ownership of the SSID to the backend
[deliverable/tracecompass.git] / org.eclipse.tracecompass.tmf.core / src / org / eclipse / tracecompass / tmf / core / statesystem / TmfStateSystemAnalysisModule.java
CommitLineData
8a6ff07f 1/*******************************************************************************
ed902a2b 2 * Copyright (c) 2013, 2015 École Polytechnique de Montréal
8a6ff07f
GB
3 *
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
8 *
9 * Contributors:
10 * Geneviève Bastien - Initial API and implementation
baa96b1d 11 * Bernd Hufmann - Integrated history builder functionality
8a6ff07f
GB
12 *******************************************************************************/
13
2bdf0193 14package org.eclipse.tracecompass.tmf.core.statesystem;
8a6ff07f 15
5db5a3a4
AM
16import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;
17
8a6ff07f 18import java.io.File;
baa96b1d 19import java.io.IOException;
5237a931 20import java.util.Collections;
09ec275e 21import java.util.concurrent.CountDownLatch;
8a6ff07f
GB
22
23import org.eclipse.core.runtime.IProgressMonitor;
e1c415b3 24import org.eclipse.core.runtime.IStatus;
baa96b1d 25import org.eclipse.core.runtime.NullProgressMonitor;
baa96b1d 26import org.eclipse.jdt.annotation.Nullable;
2bdf0193
AM
27import org.eclipse.tracecompass.internal.tmf.core.statesystem.backends.partial.PartialHistoryBackend;
28import org.eclipse.tracecompass.internal.tmf.core.statesystem.backends.partial.PartialStateSystem;
e894a508
AM
29import org.eclipse.tracecompass.statesystem.core.ITmfStateSystem;
30import org.eclipse.tracecompass.statesystem.core.ITmfStateSystemBuilder;
31import org.eclipse.tracecompass.statesystem.core.StateSystemFactory;
32import org.eclipse.tracecompass.statesystem.core.backend.IStateHistoryBackend;
33import org.eclipse.tracecompass.statesystem.core.backend.InMemoryBackend;
34import org.eclipse.tracecompass.statesystem.core.backend.NullBackend;
35import org.eclipse.tracecompass.statesystem.core.backend.historytree.HistoryTreeBackend;
36import org.eclipse.tracecompass.statesystem.core.backend.historytree.ThreadedHistoryTreeBackend;
2bdf0193
AM
37import org.eclipse.tracecompass.tmf.core.analysis.TmfAbstractAnalysisModule;
38import org.eclipse.tracecompass.tmf.core.event.ITmfEvent;
39import org.eclipse.tracecompass.tmf.core.exceptions.TmfTraceException;
40import org.eclipse.tracecompass.tmf.core.request.ITmfEventRequest;
41import org.eclipse.tracecompass.tmf.core.request.TmfEventRequest;
de83d1ab
MAL
42import org.eclipse.tracecompass.tmf.core.signal.TmfSignalHandler;
43import org.eclipse.tracecompass.tmf.core.signal.TmfTraceRangeUpdatedSignal;
2bdf0193
AM
44import org.eclipse.tracecompass.tmf.core.timestamp.TmfTimeRange;
45import org.eclipse.tracecompass.tmf.core.trace.ITmfTrace;
de83d1ab 46import org.eclipse.tracecompass.tmf.core.trace.ITmfTraceCompleteness;
2bdf0193 47import org.eclipse.tracecompass.tmf.core.trace.TmfTraceManager;
b8585c7c 48import org.eclipse.tracecompass.tmf.core.trace.TmfTraceUtils;
5c5fa260 49import org.eclipse.tracecompass.tmf.core.trace.experiment.TmfExperiment;
8a6ff07f
GB
50
51/**
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.
55 *
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)
59 *
60 * @author Geneviève Bastien
61 * @since 3.0
62 */
63public abstract class TmfStateSystemAnalysisModule extends TmfAbstractAnalysisModule
5237a931 64 implements ITmfAnalysisModuleWithStateSystems {
8a6ff07f 65
8a6ff07f
GB
66 private static final String EXTENSION = ".ht"; //$NON-NLS-1$
67
09ec275e 68 private final CountDownLatch fInitialized = new CountDownLatch(1);
de83d1ab 69 private final Object fRequestSyncObj = new Object();
09ec275e 70
baa96b1d
BH
71 @Nullable private ITmfStateSystemBuilder fStateSystem;
72 @Nullable private ITmfStateProvider fStateProvider;
73 @Nullable private IStateHistoryBackend fHtBackend;
74 @Nullable private ITmfEventRequest fRequest;
de83d1ab
MAL
75 @Nullable private TmfTimeRange fTimeRange = null;
76
77 private int fNbRead = 0;
5237a931 78
8a6ff07f
GB
79 /**
80 * State system backend types
81 *
82 * @author Geneviève Bastien
83 */
84 protected enum StateSystemBackendType {
85 /** Full history in file */
86 FULL,
87 /** In memory state system */
88 INMEM,
89 /** Null history */
90 NULL,
91 /** State system backed with partial history */
92 PARTIAL
93 }
94
72221aa4
AM
95 /**
96 * Retrieve a state system belonging to trace, by passing the ID of the
97 * relevant analysis module.
98 *
99 * This will start the execution of the analysis module, and start the
100 * construction of the state system, if needed.
101 *
102 * @param trace
103 * The trace for which you want the state system
104 * @param moduleId
105 * The ID of the state system analysis module
106 * @return The state system, or null if there was no match
107 * @since 3.1
108 */
109 public static @Nullable ITmfStateSystem getStateSystem(ITmfTrace trace, String moduleId) {
110 TmfStateSystemAnalysisModule module =
b8585c7c 111 TmfTraceUtils.getAnalysisModuleOfClass(trace, TmfStateSystemAnalysisModule.class, moduleId);
72221aa4 112 if (module != null) {
e1c415b3
BH
113 IStatus status = module.schedule();
114 if (status.isOK()) {
115 module.waitForInitialization();
e1c415b3
BH
116 return module.getStateSystem();
117 }
72221aa4
AM
118 }
119 return null;
120 }
121
8a6ff07f
GB
122 /**
123 * Get the state provider for this analysis module
124 *
125 * @return the state provider
126 */
8a6ff07f
GB
127 protected abstract ITmfStateProvider createStateProvider();
128
129 /**
130 * Get the state system backend type used by this module
131 *
132 * @return The {@link StateSystemBackendType}
133 */
a3b864c0
AM
134 protected StateSystemBackendType getBackendType() {
135 /* Using full history by default, sub-classes can override */
136 return StateSystemBackendType.FULL;
137 }
8a6ff07f
GB
138
139 /**
140 * Get the supplementary file name where to save this state system. The
141 * default is the ID of the analysis followed by the extension.
142 *
143 * @return The supplementary file name
144 */
145 protected String getSsFileName() {
146 return getId() + EXTENSION;
147 }
148
149 /**
baa96b1d
BH
150 * Get the state system generated by this analysis, or null if it is not yet
151 * created.
8a6ff07f
GB
152 *
153 * @return The state system
154 */
baa96b1d 155 @Nullable
8a6ff07f
GB
156 public ITmfStateSystem getStateSystem() {
157 return fStateSystem;
158 }
159
09ec275e
AM
160 /**
161 * Block the calling thread until the analysis module has been initialized.
162 * After this method returns, {@link #getStateSystem()} should not return
163 * null anymore.
164 */
165 public void waitForInitialization() {
166 try {
167 fInitialized.await();
168 } catch (InterruptedException e) {}
169 }
170
baa96b1d
BH
171 // ------------------------------------------------------------------------
172 // TmfAbstractAnalysisModule
173 // ------------------------------------------------------------------------
8a6ff07f 174
baa96b1d
BH
175 @Override
176 protected boolean executeAnalysis(@Nullable final IProgressMonitor monitor) {
177 IProgressMonitor mon = (monitor == null ? new NullProgressMonitor() : monitor);
178 final ITmfStateProvider provider = createStateProvider();
8a6ff07f 179
84a9548a 180 String id = getId();
84a9548a 181
8a6ff07f
GB
182 /* FIXME: State systems should make use of the monitor, to be cancelled */
183 try {
184 /* Get the state system according to backend */
185 StateSystemBackendType backend = getBackendType();
186 String directory;
baa96b1d 187 File htFile;
e1c415b3
BH
188
189 ITmfTrace trace = getTrace();
190 if (trace == null) {
191 // Analysis was cancelled in the meantime
192 fInitialized.countDown();
193 return false;
194 }
8a6ff07f
GB
195 switch (backend) {
196 case FULL:
e1c415b3 197 directory = TmfTraceManager.getSupplementaryFileDir(trace);
baa96b1d 198 htFile = new File(directory + getSsFileName());
84a9548a 199 createFullHistory(id, provider, htFile);
8a6ff07f
GB
200 break;
201 case PARTIAL:
e1c415b3 202 directory = TmfTraceManager.getSupplementaryFileDir(trace);
baa96b1d 203 htFile = new File(directory + getSsFileName());
84a9548a 204 createPartialHistory(id, provider, htFile);
8a6ff07f
GB
205 break;
206 case INMEM:
84a9548a 207 createInMemoryHistory(id, provider);
8a6ff07f
GB
208 break;
209 case NULL:
84a9548a 210 createNullHistory(id, provider);
8a6ff07f
GB
211 break;
212 default:
213 break;
214 }
215 } catch (TmfTraceException e) {
e1c415b3 216 fInitialized.countDown();
8a6ff07f
GB
217 return false;
218 }
baa96b1d 219 return !mon.isCanceled();
8a6ff07f
GB
220 }
221
222 @Override
223 protected void canceling() {
baa96b1d
BH
224 ITmfEventRequest req = fRequest;
225 if ((req != null) && (!req.isCompleted())) {
226 req.cancel();
227 }
228 }
229
a1529f38
AM
230 @Override
231 public void dispose() {
130e6f4e 232 super.dispose();
a1529f38
AM
233 if (fStateSystem != null) {
234 fStateSystem.dispose();
235 }
a1529f38
AM
236 }
237
baa96b1d
BH
238 // ------------------------------------------------------------------------
239 // History creation methods
240 // ------------------------------------------------------------------------
241
242 /*
243 * Load the history file matching the target trace. If the file already
244 * exists, it will be opened directly. If not, it will be created from
245 * scratch.
246 */
84a9548a 247 private void createFullHistory(String id, ITmfStateProvider provider, File htFile) throws TmfTraceException {
baa96b1d
BH
248
249 /* If the target file already exists, do not rebuild it uselessly */
250 // TODO for now we assume it's complete. Might be a good idea to check
251 // at least if its range matches the trace's range.
252
253 if (htFile.exists()) {
254 /* Load an existing history */
255 final int version = provider.getVersion();
256 try {
b2f62cb5 257 IStateHistoryBackend backend = new HistoryTreeBackend(id, htFile, version);
84a9548a 258 fHtBackend = backend;
b2f62cb5 259 fStateSystem = StateSystemFactory.newStateSystem(backend, false);
09ec275e 260 fInitialized.countDown();
baa96b1d
BH
261 return;
262 } catch (IOException e) {
263 /*
264 * There was an error opening the existing file. Perhaps it was
265 * corrupted, perhaps it's an old version? We'll just
266 * fall-through and try to build a new one from scratch instead.
267 */
268 }
269 }
270
271 /* Size of the blocking queue to use when building a state history */
272 final int QUEUE_SIZE = 10000;
273
274 try {
b2f62cb5 275 IStateHistoryBackend backend = new ThreadedHistoryTreeBackend(id, htFile,
baa96b1d 276 provider.getStartTime(), provider.getVersion(), QUEUE_SIZE);
84a9548a 277 fHtBackend = backend;
b2f62cb5 278 fStateSystem = StateSystemFactory.newStateSystem(backend);
baa96b1d
BH
279 provider.assignTargetStateSystem(fStateSystem);
280 build(provider);
281 } catch (IOException e) {
282 /*
283 * If it fails here however, it means there was a problem writing to
284 * the disk, so throw a real exception this time.
285 */
286 throw new TmfTraceException(e.toString(), e);
287 }
288 }
289
290 /*
291 * Create a new state system backed with a partial history. A partial
292 * history is similar to a "full" one (which you get with
293 * {@link #newFullHistory}), except that the file on disk is much smaller,
294 * but queries are a bit slower.
295 *
296 * Also note that single-queries are implemented using a full-query
297 * underneath, (which are much slower), so this might not be a good fit for
298 * a use case where you have to do lots of single queries.
299 */
84a9548a 300 private void createPartialHistory(String id, ITmfStateProvider provider, File htPartialFile)
baa96b1d
BH
301 throws TmfTraceException {
302 /*
303 * The order of initializations is very tricky (but very important!)
304 * here. We need to follow this pattern:
305 * (1 is done before the call to this method)
306 *
307 * 1- Instantiate realStateProvider
308 * 2- Instantiate realBackend
309 * 3- Instantiate partialBackend, with prereqs:
310 * 3a- Instantiate partialProvider, via realProvider.getNew()
311 * 3b- Instantiate nullBackend (partialSS's backend)
312 * 3c- Instantiate partialSS
313 * 3d- partialProvider.assignSS(partialSS)
314 * 4- Instantiate realSS
315 * 5- partialSS.assignUpstream(realSS)
316 * 6- realProvider.assignSS(realSS)
317 * 7- Call HistoryBuilder(realProvider, realSS, partialBackend) to build the thing.
318 */
319
320 /* Size of the blocking queue to use when building a state history */
321 final int QUEUE_SIZE = 10000;
322
323 final long granularity = 50000;
324
325 /* 2 */
326 IStateHistoryBackend realBackend = null;
327 try {
b2f62cb5 328 realBackend = new ThreadedHistoryTreeBackend(id, htPartialFile,
baa96b1d
BH
329 provider.getStartTime(), provider.getVersion(), QUEUE_SIZE);
330 } catch (IOException e) {
331 throw new TmfTraceException(e.toString(), e);
332 }
333
334 /* 3a */
335 ITmfStateProvider partialProvider = provider.getNewInstance();
336
337 /* 3b-3c, constructor automatically uses a NullBackend */
338 PartialStateSystem pss = new PartialStateSystem();
339
340 /* 3d */
341 partialProvider.assignTargetStateSystem(pss);
342
343 /* 3 */
b2f62cb5 344 String partialId = new String(id + ".partial"); //$NON-NLS-1$
baa96b1d 345 IStateHistoryBackend partialBackend =
b2f62cb5 346 new PartialHistoryBackend(partialId, partialProvider, pss, realBackend, granularity);
baa96b1d
BH
347
348 /* 4 */
bcec0116 349 @SuppressWarnings("restriction")
e894a508 350 org.eclipse.tracecompass.internal.statesystem.core.StateSystem realSS =
b2f62cb5 351 (org.eclipse.tracecompass.internal.statesystem.core.StateSystem) StateSystemFactory.newStateSystem(partialBackend);
baa96b1d
BH
352
353 /* 5 */
354 pss.assignUpstream(realSS);
355
356 /* 6 */
357 provider.assignTargetStateSystem(realSS);
358
359 /* 7 */
360 fHtBackend = partialBackend;
361 fStateSystem = realSS;
362
363 build(provider);
364 }
365
366 /*
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.
370 */
84a9548a 371 private void createNullHistory(String id, ITmfStateProvider provider) {
b2f62cb5 372 IStateHistoryBackend backend = new NullBackend(id);
84a9548a 373 fHtBackend = backend;
b2f62cb5 374 fStateSystem = StateSystemFactory.newStateSystem(backend);
baa96b1d
BH
375 provider.assignTargetStateSystem(fStateSystem);
376 build(provider);
377 }
378
379 /*
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
382 * to 2^31 intervals.
383 */
84a9548a 384 private void createInMemoryHistory(String id, ITmfStateProvider provider) {
b2f62cb5 385 IStateHistoryBackend backend = new InMemoryBackend(id, provider.getStartTime());
84a9548a 386 fHtBackend = backend;
b2f62cb5 387 fStateSystem = StateSystemFactory.newStateSystem(backend);
baa96b1d
BH
388 provider.assignTargetStateSystem(fStateSystem);
389 build(provider);
390 }
391
a1529f38 392 private void disposeProvider(boolean deleteFiles) {
baa96b1d
BH
393 ITmfStateProvider provider = fStateProvider;
394 if (provider != null) {
395 provider.dispose();
396 }
397 if (deleteFiles && (fHtBackend != null)) {
398 fHtBackend.removeFiles();
399 }
400 }
401
402 private void build(ITmfStateProvider provider) {
403 if ((fStateSystem == null) || (fHtBackend == null)) {
404 throw new IllegalArgumentException();
405 }
406
407 ITmfEventRequest request = fRequest;
408 if ((request != null) && (!request.isCompleted())) {
409 request.cancel();
410 }
411
de83d1ab
MAL
412 fTimeRange = TmfTimeRange.ETERNITY;
413 final ITmfTrace trace = provider.getTrace();
d0c7e4ba 414 if (!isCompleteTrace(trace)) {
de83d1ab
MAL
415 TmfTimeRange traceTimeRange = trace.getTimeRange();
416 if (traceTimeRange != null) {
417 fTimeRange = traceTimeRange;
418 }
419 }
baa96b1d 420
baa96b1d 421 fStateProvider = provider;
de83d1ab
MAL
422 synchronized (fRequestSyncObj) {
423 startRequest();
424 }
baa96b1d 425
09ec275e
AM
426 /*
427 * The state system object is now created, we can consider this module
428 * "initialized" (components can retrieve it and start doing queries).
429 */
430 fInitialized.countDown();
431
432 /*
433 * Block the executeAnalysis() construction is complete (so that the
434 * progress monitor displays that it is running).
435 */
baa96b1d 436 try {
de83d1ab
MAL
437 if (fRequest != null) {
438 fRequest.waitForCompletion();
439 }
baa96b1d
BH
440 } catch (InterruptedException e) {
441 e.printStackTrace();
442 }
443 }
444
445 private class StateSystemEventRequest extends TmfEventRequest {
446 private final ITmfStateProvider sci;
447 private final ITmfTrace trace;
448
de83d1ab 449 public StateSystemEventRequest(ITmfStateProvider sp, TmfTimeRange timeRange, int index) {
e2bcc8a5 450 super(ITmfEvent.class,
de83d1ab
MAL
451 timeRange,
452 index,
baa96b1d
BH
453 ITmfEventRequest.ALL_DATA,
454 ITmfEventRequest.ExecutionType.BACKGROUND);
455 this.sci = sp;
456
457 // sci.getTrace() will eventually return a @NonNull
5db5a3a4 458 trace = checkNotNull(sci.getTrace());
baa96b1d 459
baa96b1d
BH
460 }
461
462 @Override
41f3b36b 463 public void handleData(final ITmfEvent event) {
baa96b1d 464 super.handleData(event);
41f3b36b 465 if (event.getTrace() == trace) {
baa96b1d 466 sci.processEvent(event);
2d208fb7
GB
467 } else if (trace instanceof TmfExperiment) {
468 /*
469 * If the request is for an experiment, check if the event is
470 * from one of the child trace
471 */
472 for (ITmfTrace childTrace : ((TmfExperiment) trace).getTraces()) {
473 if (childTrace == event.getTrace()) {
474 sci.processEvent(event);
475 }
476 }
baa96b1d
BH
477 }
478 }
479
480 @Override
481 public void handleSuccess() {
482 super.handleSuccess();
de83d1ab
MAL
483 if (isCompleteTrace(trace)) {
484 disposeProvider(false);
485 } else {
486 fNbRead += getNbRead();
487 synchronized (fRequestSyncObj) {
488 final TmfTimeRange timeRange = fTimeRange;
489 if (timeRange != null) {
490 if (getRange().getEndTime().getValue() < timeRange.getEndTime().getValue()) {
491 startRequest();
492 }
493 }
494 }
495 }
baa96b1d
BH
496 }
497
498 @Override
499 public void handleCancel() {
500 super.handleCancel();
de83d1ab
MAL
501 if (isCompleteTrace(trace)) {
502 disposeProvider(true);
503 }
baa96b1d
BH
504 }
505
506 @Override
507 public void handleFailure() {
508 super.handleFailure();
a1529f38 509 disposeProvider(true);
baa96b1d 510 }
8a6ff07f
GB
511 }
512
5237a931
AM
513 // ------------------------------------------------------------------------
514 // ITmfAnalysisModuleWithStateSystems
515 // ------------------------------------------------------------------------
516
517 @Override
baa96b1d
BH
518 @Nullable
519 public ITmfStateSystem getStateSystem(String id) {
5237a931
AM
520 if (id.equals(getId())) {
521 return fStateSystem;
522 }
523 return null;
524 }
525
8a6ff07f 526 @Override
5237a931 527 public Iterable<ITmfStateSystem> getStateSystems() {
5db5a3a4 528 return checkNotNull(Collections.<ITmfStateSystem> singleton(fStateSystem));
8a6ff07f 529 }
de83d1ab
MAL
530
531 /**
532 * Signal handler for the TmfTraceRangeUpdatedSignal signal
533 *
534 * @param signal The incoming signal
535 */
536 @TmfSignalHandler
537 public void traceRangeUpdated(final TmfTraceRangeUpdatedSignal signal) {
538 fTimeRange = signal.getRange();
539 ITmfStateProvider stateProvider = fStateProvider;
540 synchronized (fRequestSyncObj) {
541 if (signal.getTrace() == getTrace() && stateProvider != null && stateProvider.getAssignedStateSystem() != null) {
542 ITmfEventRequest request = fRequest;
543 if ((request == null) || request.isCompleted()) {
544 startRequest();
545 }
546 }
547 }
548 }
549
550 private void startRequest() {
551 ITmfStateProvider stateProvider = fStateProvider;
552 TmfTimeRange timeRange = fTimeRange;
553 if (stateProvider == null || timeRange == null) {
554 return;
555 }
556 ITmfEventRequest request = new StateSystemEventRequest(stateProvider, timeRange, fNbRead);
557 stateProvider.getTrace().sendRequest(request);
558 fRequest = request;
559 }
560
561 private static boolean isCompleteTrace(ITmfTrace trace) {
562 return !(trace instanceof ITmfTraceCompleteness) || ((ITmfTraceCompleteness) trace).isComplete();
563 }
8a6ff07f 564}
This page took 0.081756 seconds and 5 git commands to generate.