tmf : Make waitForInitialization() return a boolean
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.core / src / org / eclipse / tracecompass / tmf / core / statesystem / TmfStateSystemAnalysisModule.java
1 /*******************************************************************************
2 * Copyright (c) 2013, 2015 École Polytechnique de Montréal
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
11 * Bernd Hufmann - Integrated history builder functionality
12 *******************************************************************************/
13
14 package org.eclipse.tracecompass.tmf.core.statesystem;
15
16 import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;
17
18 import java.io.File;
19 import java.io.IOException;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.Map;
23 import java.util.concurrent.CountDownLatch;
24
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;
53
54 /**
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.
58 *
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)
62 *
63 * @author Geneviève Bastien
64 */
65 public abstract class TmfStateSystemAnalysisModule extends TmfAbstractAnalysisModule
66 implements ITmfAnalysisModuleWithStateSystems, ITmfPropertiesProvider {
67
68 private static final String EXTENSION = ".ht"; //$NON-NLS-1$
69
70 private final CountDownLatch fInitialized = new CountDownLatch(1);
71 private final Object fRequestSyncObj = new Object();
72
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;
78
79 private int fNbRead = 0;
80 private boolean fInitializationSucceeded;
81
82 /**
83 * State system backend types
84 *
85 * @author Geneviève Bastien
86 */
87 protected enum StateSystemBackendType {
88 /** Full history in file */
89 FULL,
90 /** In memory state system */
91 INMEM,
92 /** Null history */
93 NULL,
94 /** State system backed with partial history */
95 PARTIAL
96 }
97
98 /**
99 * Retrieve a state system belonging to trace, by passing the ID of the
100 * relevant analysis module.
101 *
102 * This will start the execution of the analysis module, and start the
103 * construction of the state system, if needed.
104 *
105 * @param trace
106 * The trace for which you want the state system
107 * @param moduleId
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
111 */
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();
117 if (ss != null) {
118 return ss;
119 }
120 IStatus status = module.schedule();
121 if (status.isOK()) {
122 return module.waitForInitialization() ? module.getStateSystem() : null;
123 }
124 }
125 return null;
126 }
127
128 /**
129 * Get the state provider for this analysis module
130 *
131 * @return the state provider
132 */
133 protected abstract ITmfStateProvider createStateProvider();
134
135 /**
136 * Get the state system backend type used by this module
137 *
138 * @return The {@link StateSystemBackendType}
139 */
140 protected StateSystemBackendType getBackendType() {
141 /* Using full history by default, sub-classes can override */
142 return StateSystemBackendType.FULL;
143 }
144
145 /**
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.
148 *
149 * @return The supplementary file name
150 */
151 protected String getSsFileName() {
152 return getId() + EXTENSION;
153 }
154
155 /**
156 * Get the state system generated by this analysis, or null if it is not yet
157 * created.
158 *
159 * @return The state system
160 */
161 @Nullable
162 public ITmfStateSystem getStateSystem() {
163 return fStateSystem;
164 }
165
166 /**
167 * @since 2.0
168 */
169 @Override
170 public boolean waitForInitialization() {
171 try {
172 fInitialized.await();
173 } catch (InterruptedException e) {
174 return false;
175 }
176 return fInitializationSucceeded;
177 }
178
179 // ------------------------------------------------------------------------
180 // TmfAbstractAnalysisModule
181 // ------------------------------------------------------------------------
182
183 private @Nullable File getSsFile() {
184 ITmfTrace trace = getTrace();
185 if (trace == null) {
186 return null;
187 }
188 String directory = TmfTraceManager.getSupplementaryFileDir(trace);
189 File htFile = new File(directory + getSsFileName());
190 return htFile;
191 }
192
193 @Override
194 protected boolean executeAnalysis(@Nullable final IProgressMonitor monitor) {
195 IProgressMonitor mon = (monitor == null ? new NullProgressMonitor() : monitor);
196 final ITmfStateProvider provider = createStateProvider();
197
198 String id = getId();
199
200 /* FIXME: State systems should make use of the monitor, to be cancelled */
201 try {
202 /* Get the state system according to backend */
203 StateSystemBackendType backend = getBackendType();
204
205
206 ITmfTrace trace = getTrace();
207 if (trace == null) {
208 // Analysis was cancelled in the meantime
209 fInitializationSucceeded = false;
210 fInitialized.countDown();
211 return false;
212 }
213 switch (backend) {
214 case FULL: {
215 File htFile = getSsFile();
216 if (htFile == null) {
217 return false;
218 }
219 createFullHistory(id, provider, htFile);
220 }
221 break;
222 case PARTIAL: {
223 File htFile = getSsFile();
224 if (htFile == null) {
225 return false;
226 }
227 createPartialHistory(id, provider, htFile);
228 }
229 break;
230 case INMEM:
231 createInMemoryHistory(id, provider);
232 break;
233 case NULL:
234 createNullHistory(id, provider);
235 break;
236 default:
237 break;
238 }
239 } catch (TmfTraceException e) {
240 fInitializationSucceeded = false;
241 fInitialized.countDown();
242 return false;
243 }
244 return !mon.isCanceled();
245 }
246
247 @Override
248 protected void canceling() {
249 ITmfEventRequest req = fRequest;
250 if ((req != null) && (!req.isCompleted())) {
251 req.cancel();
252 }
253 }
254
255 @Override
256 public void dispose() {
257 super.dispose();
258 if (fStateSystem != null) {
259 fStateSystem.dispose();
260 }
261 }
262
263 // ------------------------------------------------------------------------
264 // History creation methods
265 // ------------------------------------------------------------------------
266
267 /*
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
270 * scratch.
271 */
272 private void createFullHistory(String id, ITmfStateProvider provider, File htFile) throws TmfTraceException {
273
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.
277
278 if (htFile.exists()) {
279 /* Load an existing history */
280 final int version = provider.getVersion();
281 try {
282 IStateHistoryBackend backend = StateHistoryBackendFactory.createHistoryTreeBackendExistingFile(
283 id, htFile, version);
284 fHtBackend = backend;
285 fStateSystem = StateSystemFactory.newStateSystem(backend, false);
286 fInitializationSucceeded = true;
287 fInitialized.countDown();
288 return;
289 } catch (IOException e) {
290 /*
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.
294 */
295 }
296 }
297
298 /* Size of the blocking queue to use when building a state history */
299 final int QUEUE_SIZE = 10000;
300
301 try {
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);
307 build(provider);
308 } catch (IOException e) {
309 /*
310 * If it fails here however, it means there was a problem writing to
311 * the disk, so throw a real exception this time.
312 */
313 throw new TmfTraceException(e.toString(), e);
314 }
315 }
316
317 /*
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.
322 *
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.
326 */
327 private void createPartialHistory(String id, ITmfStateProvider provider, File htPartialFile)
328 throws TmfTraceException {
329 /*
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)
333 *
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.
345 */
346
347 /* Size of the blocking queue to use when building a state history */
348 final int QUEUE_SIZE = 10000;
349
350 final long granularity = 50000;
351
352 /* 2 */
353 IStateHistoryBackend realBackend = null;
354 try {
355 realBackend = StateHistoryBackendFactory.createHistoryTreeBackendNewFile(
356 id, htPartialFile, provider.getVersion(), provider.getStartTime(), QUEUE_SIZE);
357 } catch (IOException e) {
358 throw new TmfTraceException(e.toString(), e);
359 }
360
361 /* 3a */
362 ITmfStateProvider partialProvider = provider.getNewInstance();
363
364 /* 3b-3c, constructor automatically uses a NullBackend */
365 PartialStateSystem pss = new PartialStateSystem();
366
367 /* 3d */
368 partialProvider.assignTargetStateSystem(pss);
369
370 /* 3 */
371 IStateHistoryBackend partialBackend = new PartialHistoryBackend(id + ".partial", partialProvider, pss, realBackend, granularity); //$NON-NLS-1$
372
373 /* 4 */
374 @SuppressWarnings("restriction")
375 org.eclipse.tracecompass.internal.statesystem.core.StateSystem realSS =
376 (org.eclipse.tracecompass.internal.statesystem.core.StateSystem) StateSystemFactory.newStateSystem(partialBackend);
377
378 /* 5 */
379 pss.assignUpstream(realSS);
380
381 /* 6 */
382 provider.assignTargetStateSystem(realSS);
383
384 /* 7 */
385 fHtBackend = partialBackend;
386 fStateSystem = realSS;
387
388 build(provider);
389 }
390
391 /*
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.
395 */
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);
401 build(provider);
402 }
403
404 /*
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
407 * to 2^31 intervals.
408 */
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);
414 build(provider);
415 }
416
417 private void disposeProvider(boolean deleteFiles) {
418 ITmfStateProvider provider = fStateProvider;
419 if (provider != null) {
420 provider.dispose();
421 }
422 if (deleteFiles && (fHtBackend != null)) {
423 fHtBackend.removeFiles();
424 }
425 }
426
427 private void build(ITmfStateProvider provider) {
428 if ((fStateSystem == null) || (fHtBackend == null)) {
429 throw new IllegalArgumentException();
430 }
431
432 ITmfEventRequest request = fRequest;
433 if ((request != null) && (!request.isCompleted())) {
434 request.cancel();
435 }
436
437 fTimeRange = TmfTimeRange.ETERNITY;
438 final ITmfTrace trace = provider.getTrace();
439 if (!isCompleteTrace(trace)) {
440 fTimeRange = trace.getTimeRange();
441 }
442
443 fStateProvider = provider;
444 synchronized (fRequestSyncObj) {
445 startRequest();
446 }
447
448 /*
449 * The state system object is now created, we can consider this module
450 * "initialized" (components can retrieve it and start doing queries).
451 */
452 fInitializationSucceeded = true;
453 fInitialized.countDown();
454
455 /*
456 * Block the executeAnalysis() construction is complete (so that the
457 * progress monitor displays that it is running).
458 */
459 try {
460 if (fRequest != null) {
461 fRequest.waitForCompletion();
462 }
463 } catch (InterruptedException e) {
464 e.printStackTrace();
465 }
466 }
467
468 private class StateSystemEventRequest extends TmfEventRequest {
469 private final ITmfStateProvider sci;
470 private final ITmfTrace trace;
471
472 public StateSystemEventRequest(ITmfStateProvider sp, TmfTimeRange timeRange, int index) {
473 super(ITmfEvent.class,
474 timeRange,
475 index,
476 ITmfEventRequest.ALL_DATA,
477 ITmfEventRequest.ExecutionType.BACKGROUND);
478 this.sci = sp;
479
480 // sci.getTrace() will eventually return a @NonNull
481 trace = checkNotNull(sci.getTrace());
482
483 }
484
485 @Override
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) {
491 /*
492 * If the request is for an experiment, check if the event is
493 * from one of the child trace
494 */
495 for (ITmfTrace childTrace : ((TmfExperiment) trace).getTraces()) {
496 if (childTrace == event.getTrace()) {
497 sci.processEvent(event);
498 }
499 }
500 }
501 }
502
503 @Override
504 public void handleSuccess() {
505 super.handleSuccess();
506 if (isCompleteTrace(trace)) {
507 disposeProvider(false);
508 } else {
509 fNbRead += getNbRead();
510 synchronized (fRequestSyncObj) {
511 final TmfTimeRange timeRange = fTimeRange;
512 if (timeRange != null) {
513 if (getRange().getEndTime().getValue() < timeRange.getEndTime().getValue()) {
514 startRequest();
515 }
516 }
517 }
518 }
519 }
520
521 @Override
522 public void handleCancel() {
523 super.handleCancel();
524 if (isCompleteTrace(trace)) {
525 disposeProvider(true);
526 }
527 }
528
529 @Override
530 public void handleFailure() {
531 super.handleFailure();
532 disposeProvider(true);
533 }
534 }
535
536 // ------------------------------------------------------------------------
537 // ITmfAnalysisModuleWithStateSystems
538 // ------------------------------------------------------------------------
539
540 @Override
541 @Nullable
542 public ITmfStateSystem getStateSystem(String id) {
543 if (id.equals(getId())) {
544 return fStateSystem;
545 }
546 return null;
547 }
548
549 @Override
550 public @NonNull Iterable<@NonNull ITmfStateSystem> getStateSystems() {
551 ITmfStateSystemBuilder stateSystem = fStateSystem;
552 if (stateSystem == null) {
553 return Collections.EMPTY_SET;
554 }
555 return Collections.singleton(stateSystem);
556 }
557
558 /**
559 * Signal handler for the TmfTraceRangeUpdatedSignal signal
560 *
561 * @param signal The incoming signal
562 */
563 @TmfSignalHandler
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()) {
571 startRequest();
572 }
573 }
574 }
575 }
576
577 private void startRequest() {
578 ITmfStateProvider stateProvider = fStateProvider;
579 TmfTimeRange timeRange = fTimeRange;
580 if (stateProvider == null || timeRange == null) {
581 return;
582 }
583 ITmfEventRequest request = new StateSystemEventRequest(stateProvider, timeRange, fNbRead);
584 stateProvider.getTrace().sendRequest(request);
585 fRequest = request;
586 }
587
588 private static boolean isCompleteTrace(ITmfTrace trace) {
589 return !(trace instanceof ITmfTraceCompleteness) || ((ITmfTraceCompleteness) trace).isComplete();
590 }
591
592 // ------------------------------------------------------------------------
593 // ITmfPropertiesProvider
594 // ------------------------------------------------------------------------
595
596 /**
597 * @since 2.0
598 */
599 @Override
600 public @NonNull Map<@NonNull String, @NonNull String> getProperties() {
601 Map<@NonNull String, @NonNull String> properties = new HashMap<>();
602
603 StateSystemBackendType backend = getBackendType();
604 properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesBackend), NonNullUtils.checkNotNull(backend.name()));
605 switch (backend) {
606 case FULL:
607 case PARTIAL:
608 File htFile = getSsFile();
609 if (htFile != null) {
610 if (htFile.exists()) {
611 properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesFileSize), FileUtils.byteCountToDisplaySize(htFile.length()));
612 } else {
613 properties.put(NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesFileSize), NonNullUtils.checkNotNull(Messages.TmfStateSystemAnalysisModule_PropertiesAnalysisNotExecuted));
614 }
615 }
616 break;
617 case INMEM:
618 case NULL:
619 default:
620 break;
621
622 }
623 return properties;
624 }
625 }
This page took 0.045092 seconds and 6 git commands to generate.