Upgrade jdt.annotation to 4.4
[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 {
84a9548a
AM
257 IStateHistoryBackend backend = new HistoryTreeBackend(htFile, version);
258 fHtBackend = backend;
bcec0116 259 fStateSystem = StateSystemFactory.newStateSystem(id, 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 {
84a9548a 275 IStateHistoryBackend backend = new ThreadedHistoryTreeBackend(htFile,
baa96b1d 276 provider.getStartTime(), provider.getVersion(), QUEUE_SIZE);
84a9548a 277 fHtBackend = backend;
bcec0116 278 fStateSystem = StateSystemFactory.newStateSystem(id, 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 {
328 realBackend = new ThreadedHistoryTreeBackend(htPartialFile,
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 */
344 IStateHistoryBackend partialBackend =
345 new PartialHistoryBackend(partialProvider, pss, realBackend, granularity);
346
347 /* 4 */
bcec0116 348 @SuppressWarnings("restriction")
e894a508
AM
349 org.eclipse.tracecompass.internal.statesystem.core.StateSystem realSS =
350 (org.eclipse.tracecompass.internal.statesystem.core.StateSystem) StateSystemFactory.newStateSystem(id, partialBackend);
baa96b1d
BH
351
352 /* 5 */
353 pss.assignUpstream(realSS);
354
355 /* 6 */
356 provider.assignTargetStateSystem(realSS);
357
358 /* 7 */
359 fHtBackend = partialBackend;
360 fStateSystem = realSS;
361
362 build(provider);
363 }
364
365 /*
366 * Create a new state system using a null history back-end. This means that
367 * no history intervals will be saved anywhere, and as such only
368 * {@link ITmfStateSystem#queryOngoingState} will be available.
369 */
84a9548a
AM
370 private void createNullHistory(String id, ITmfStateProvider provider) {
371 IStateHistoryBackend backend = new NullBackend();
372 fHtBackend = backend;
bcec0116 373 fStateSystem = StateSystemFactory.newStateSystem(id, backend);
baa96b1d
BH
374 provider.assignTargetStateSystem(fStateSystem);
375 build(provider);
376 }
377
378 /*
379 * Create a new state system using in-memory interval storage. This should
380 * only be done for very small state system, and will be naturally limited
381 * to 2^31 intervals.
382 */
84a9548a
AM
383 private void createInMemoryHistory(String id, ITmfStateProvider provider) {
384 IStateHistoryBackend backend = new InMemoryBackend(provider.getStartTime());
385 fHtBackend = backend;
bcec0116 386 fStateSystem = StateSystemFactory.newStateSystem(id, backend);
baa96b1d
BH
387 provider.assignTargetStateSystem(fStateSystem);
388 build(provider);
389 }
390
a1529f38 391 private void disposeProvider(boolean deleteFiles) {
baa96b1d
BH
392 ITmfStateProvider provider = fStateProvider;
393 if (provider != null) {
394 provider.dispose();
395 }
396 if (deleteFiles && (fHtBackend != null)) {
397 fHtBackend.removeFiles();
398 }
399 }
400
401 private void build(ITmfStateProvider provider) {
402 if ((fStateSystem == null) || (fHtBackend == null)) {
403 throw new IllegalArgumentException();
404 }
405
406 ITmfEventRequest request = fRequest;
407 if ((request != null) && (!request.isCompleted())) {
408 request.cancel();
409 }
410
de83d1ab
MAL
411 fTimeRange = TmfTimeRange.ETERNITY;
412 final ITmfTrace trace = provider.getTrace();
d0c7e4ba 413 if (!isCompleteTrace(trace)) {
de83d1ab
MAL
414 TmfTimeRange traceTimeRange = trace.getTimeRange();
415 if (traceTimeRange != null) {
416 fTimeRange = traceTimeRange;
417 }
418 }
baa96b1d 419
baa96b1d 420 fStateProvider = provider;
de83d1ab
MAL
421 synchronized (fRequestSyncObj) {
422 startRequest();
423 }
baa96b1d 424
09ec275e
AM
425 /*
426 * The state system object is now created, we can consider this module
427 * "initialized" (components can retrieve it and start doing queries).
428 */
429 fInitialized.countDown();
430
431 /*
432 * Block the executeAnalysis() construction is complete (so that the
433 * progress monitor displays that it is running).
434 */
baa96b1d 435 try {
de83d1ab
MAL
436 if (fRequest != null) {
437 fRequest.waitForCompletion();
438 }
baa96b1d
BH
439 } catch (InterruptedException e) {
440 e.printStackTrace();
441 }
442 }
443
444 private class StateSystemEventRequest extends TmfEventRequest {
445 private final ITmfStateProvider sci;
446 private final ITmfTrace trace;
447
de83d1ab 448 public StateSystemEventRequest(ITmfStateProvider sp, TmfTimeRange timeRange, int index) {
e2bcc8a5 449 super(ITmfEvent.class,
de83d1ab
MAL
450 timeRange,
451 index,
baa96b1d
BH
452 ITmfEventRequest.ALL_DATA,
453 ITmfEventRequest.ExecutionType.BACKGROUND);
454 this.sci = sp;
455
456 // sci.getTrace() will eventually return a @NonNull
5db5a3a4 457 trace = checkNotNull(sci.getTrace());
baa96b1d 458
baa96b1d
BH
459 }
460
461 @Override
41f3b36b 462 public void handleData(final ITmfEvent event) {
baa96b1d 463 super.handleData(event);
41f3b36b 464 if (event.getTrace() == trace) {
baa96b1d 465 sci.processEvent(event);
2d208fb7
GB
466 } else if (trace instanceof TmfExperiment) {
467 /*
468 * If the request is for an experiment, check if the event is
469 * from one of the child trace
470 */
471 for (ITmfTrace childTrace : ((TmfExperiment) trace).getTraces()) {
472 if (childTrace == event.getTrace()) {
473 sci.processEvent(event);
474 }
475 }
baa96b1d
BH
476 }
477 }
478
479 @Override
480 public void handleSuccess() {
481 super.handleSuccess();
de83d1ab
MAL
482 if (isCompleteTrace(trace)) {
483 disposeProvider(false);
484 } else {
485 fNbRead += getNbRead();
486 synchronized (fRequestSyncObj) {
487 final TmfTimeRange timeRange = fTimeRange;
488 if (timeRange != null) {
489 if (getRange().getEndTime().getValue() < timeRange.getEndTime().getValue()) {
490 startRequest();
491 }
492 }
493 }
494 }
baa96b1d
BH
495 }
496
497 @Override
498 public void handleCancel() {
499 super.handleCancel();
de83d1ab
MAL
500 if (isCompleteTrace(trace)) {
501 disposeProvider(true);
502 }
baa96b1d
BH
503 }
504
505 @Override
506 public void handleFailure() {
507 super.handleFailure();
a1529f38 508 disposeProvider(true);
baa96b1d 509 }
8a6ff07f
GB
510 }
511
5237a931
AM
512 // ------------------------------------------------------------------------
513 // ITmfAnalysisModuleWithStateSystems
514 // ------------------------------------------------------------------------
515
516 @Override
baa96b1d
BH
517 @Nullable
518 public ITmfStateSystem getStateSystem(String id) {
5237a931
AM
519 if (id.equals(getId())) {
520 return fStateSystem;
521 }
522 return null;
523 }
524
8a6ff07f 525 @Override
5237a931 526 public Iterable<ITmfStateSystem> getStateSystems() {
5db5a3a4 527 return checkNotNull(Collections.<ITmfStateSystem> singleton(fStateSystem));
8a6ff07f 528 }
de83d1ab
MAL
529
530 /**
531 * Signal handler for the TmfTraceRangeUpdatedSignal signal
532 *
533 * @param signal The incoming signal
534 */
535 @TmfSignalHandler
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()) {
543 startRequest();
544 }
545 }
546 }
547 }
548
549 private void startRequest() {
550 ITmfStateProvider stateProvider = fStateProvider;
551 TmfTimeRange timeRange = fTimeRange;
552 if (stateProvider == null || timeRange == null) {
553 return;
554 }
555 ITmfEventRequest request = new StateSystemEventRequest(stateProvider, timeRange, fNbRead);
556 stateProvider.getTrace().sendRequest(request);
557 fRequest = request;
558 }
559
560 private static boolean isCompleteTrace(ITmfTrace trace) {
561 return !(trace instanceof ITmfTraceCompleteness) || ((ITmfTraceCompleteness) trace).isComplete();
562 }
8a6ff07f 563}
This page took 0.077038 seconds and 5 git commands to generate.