tmf: fix displaying of analysis properties in Properties view
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.core / src / org / eclipse / tracecompass / tmf / core / analysis / TmfAbstractAnalysisModule.java
CommitLineData
c068a752 1/*******************************************************************************
60ae41e1 2 * Copyright (c) 2013, 2014 École Polytechnique de Montréal
c068a752
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
11 *******************************************************************************/
12
2bdf0193 13package org.eclipse.tracecompass.tmf.core.analysis;
c068a752 14
5db5a3a4
AM
15import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;
16
c068a752 17import java.util.ArrayList;
63c43609 18import java.util.Collections;
c068a752 19import java.util.HashMap;
55d8eb5e 20import java.util.HashSet;
c068a752
GB
21import java.util.List;
22import java.util.Map;
54eae41f 23import java.util.Set;
c068a752
GB
24import java.util.concurrent.CountDownLatch;
25import java.util.concurrent.TimeUnit;
26
27import org.eclipse.core.runtime.IProgressMonitor;
28import org.eclipse.core.runtime.IStatus;
ba27dd38 29import org.eclipse.core.runtime.NullProgressMonitor;
c068a752
GB
30import org.eclipse.core.runtime.Status;
31import org.eclipse.core.runtime.jobs.Job;
a01f6266 32import org.eclipse.jdt.annotation.NonNull;
ba27dd38
GB
33import org.eclipse.jdt.annotation.NonNullByDefault;
34import org.eclipse.jdt.annotation.Nullable;
c068a752 35import org.eclipse.osgi.util.NLS;
5db5a3a4 36import org.eclipse.tracecompass.common.core.NonNullUtils;
2bdf0193 37import org.eclipse.tracecompass.internal.tmf.core.Activator;
6dc36f66 38import org.eclipse.tracecompass.internal.tmf.core.TmfCoreTracer;
ca0f94c4
GB
39import org.eclipse.tracecompass.tmf.core.analysis.requirements.TmfAnalysisRequirement;
40import org.eclipse.tracecompass.tmf.core.analysis.requirements.TmfAnalysisRequirement.ValuePriorityLevel;
2bdf0193
AM
41import org.eclipse.tracecompass.tmf.core.component.TmfComponent;
42import org.eclipse.tracecompass.tmf.core.exceptions.TmfAnalysisException;
a01f6266 43import org.eclipse.tracecompass.tmf.core.project.model.ITmfPropertiesProvider;
2bdf0193
AM
44import org.eclipse.tracecompass.tmf.core.signal.TmfSignalHandler;
45import org.eclipse.tracecompass.tmf.core.signal.TmfStartAnalysisSignal;
46import org.eclipse.tracecompass.tmf.core.signal.TmfTraceClosedSignal;
47import org.eclipse.tracecompass.tmf.core.signal.TmfTraceSelectedSignal;
48import org.eclipse.tracecompass.tmf.core.trace.ITmfTrace;
49import org.eclipse.tracecompass.tmf.core.trace.TmfTraceManager;
c068a752
GB
50
51/**
52 * Base class that analysis modules main class may extend. It provides default
53 * behavior to some methods of the analysis module
54 *
55 * @author Geneviève Bastien
c068a752 56 */
ba27dd38 57@NonNullByDefault
a01f6266
GB
58public abstract class TmfAbstractAnalysisModule extends TmfComponent
59 implements IAnalysisModule, ITmfPropertiesProvider {
c068a752 60
ba27dd38 61 private @Nullable String fId;
c068a752 62 private boolean fAutomatic = false, fStarted = false;
ba27dd38 63 private volatile @Nullable ITmfTrace fTrace;
4c4e2816 64 private final Map<String, @Nullable Object> fParameters = new HashMap<>();
a4524c1b
AM
65 private final List<String> fParameterNames = new ArrayList<>();
66 private final List<IAnalysisOutput> fOutputs = new ArrayList<>();
55d8eb5e 67 private Set<IAnalysisParameterProvider> fParameterProviders = new HashSet<>();
ba27dd38 68 private @Nullable Job fJob = null;
0021a734 69 private int fDependencyLevel = 0;
c068a752
GB
70
71 private final Object syncObj = new Object();
72
73 /* Latch tracking if the analysis is completed or not */
74 private CountDownLatch fFinishedLatch = new CountDownLatch(0);
75
76 private boolean fAnalysisCancelled = false;
77
78 @Override
79 public boolean isAutomatic() {
80 return fAutomatic;
81 }
82
83 @Override
84 public String getName() {
ba27dd38 85 return super.getName();
c068a752
GB
86 }
87
88 @Override
89 public void setName(String name) {
ba27dd38 90 super.setName(name);
c068a752
GB
91 }
92
93 @Override
94 public void setId(String id) {
95 fId = id;
96 }
97
98 @Override
99 public String getId() {
dc58a1fb
GB
100 String id = fId;
101 if (id == null) {
8356c9fe
AM
102 id = this.getClass().getCanonicalName();
103 if (id == null) {
104 /*
105 * Some types, like anonymous classes, don't have a canonical
106 * name. Just use the default name instead.
107 */
0e4f957e 108 id = this.getClass().getName();
8356c9fe 109 }
11835c0f 110 fId = id;
dc58a1fb
GB
111 }
112 return id;
c068a752
GB
113 }
114
115 @Override
116 public void setAutomatic(boolean auto) {
117 fAutomatic = auto;
118 }
119
f479550c
GB
120 /**
121 * @since 1.0
122 */
c068a752 123 @Override
f479550c 124 public boolean setTrace(ITmfTrace trace) throws TmfAnalysisException {
c068a752
GB
125 if (fTrace != null) {
126 throw new TmfAnalysisException(NLS.bind(Messages.TmfAbstractAnalysisModule_TraceSetMoreThanOnce, getName()));
127 }
128
6dc36f66
GB
129 TmfCoreTracer.traceAnalysis(getId(), trace, "setting trace for analysis"); //$NON-NLS-1$
130
c068a752 131 /* Check that analysis can be executed */
7e452c97 132 fTrace = trace;
c068a752 133 if (!canExecute(trace)) {
7e452c97 134 fTrace = null;
f479550c 135 return false;
c068a752 136 }
26683871 137
c068a752 138 /* Get the parameter providers for this trace */
55d8eb5e 139 fParameterProviders = TmfAnalysisManager.getParameterProvidersForModule(this, trace);
c068a752 140 for (IAnalysisParameterProvider provider : fParameterProviders) {
6dc36f66 141 TmfCoreTracer.traceAnalysis(getId(), trace, "registered to parameter provider " + provider.getName()); //$NON-NLS-1$
c068a752
GB
142 provider.registerModule(this);
143 }
144 resetAnalysis();
145 fStarted = false;
f479550c 146 return true;
c068a752
GB
147 }
148
149 /**
150 * Gets the trace
151 *
152 * @return The trace
153 */
ba27dd38 154 protected @Nullable ITmfTrace getTrace() {
c068a752
GB
155 return fTrace;
156 }
157
158 @Override
159 public void addParameter(String name) {
160 fParameterNames.add(name);
161 }
162
163 @Override
ba27dd38 164 public synchronized void setParameter(String name, @Nullable Object value) {
c068a752
GB
165 if (!fParameterNames.contains(name)) {
166 throw new RuntimeException(NLS.bind(Messages.TmfAbstractAnalysisModule_InvalidParameter, name, getName()));
167 }
168 Object oldValue = fParameters.get(name);
169 fParameters.put(name, value);
170 if ((value != null) && !(value.equals(oldValue))) {
171 parameterChanged(name);
172 }
173 }
174
175 @Override
176 public synchronized void notifyParameterChanged(String name) {
177 if (!fParameterNames.contains(name)) {
178 throw new RuntimeException(NLS.bind(Messages.TmfAbstractAnalysisModule_InvalidParameter, name, getName()));
179 }
180 Object oldValue = fParameters.get(name);
181 Object value = getParameter(name);
182 if ((value != null) && !(value.equals(oldValue))) {
183 parameterChanged(name);
184 }
185 }
186
187 /**
188 * Used to indicate that a parameter value has been changed
189 *
190 * @param name
191 * The name of the modified parameter
192 */
193 protected void parameterChanged(String name) {
194
195 }
196
197 @Override
ba27dd38 198 public @Nullable Object getParameter(String name) {
c068a752
GB
199 Object paramValue = fParameters.get(name);
200 /* The parameter is not set, maybe it can be provided by someone else */
201 if ((paramValue == null) && (fTrace != null)) {
202 for (IAnalysisParameterProvider provider : fParameterProviders) {
203 paramValue = provider.getParameter(name);
204 if (paramValue != null) {
205 break;
206 }
207 }
208 }
209 return paramValue;
210 }
211
212 @Override
ba27dd38 213 public boolean canExecute(ITmfTrace trace) {
26683871 214 for (TmfAnalysisRequirement requirement : getAnalysisRequirements()) {
e44d6313 215 if (!requirement.test(trace)) {
26683871
GB
216 return false;
217 }
218 }
c068a752
GB
219 return true;
220 }
221
222 /**
223 * Set the countdown latch back to 1 so the analysis can be executed again
224 */
225 protected void resetAnalysis() {
6dc36f66 226 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "reset: ready for execution"); //$NON-NLS-1$
0d3a54a3 227 fFinishedLatch.countDown();
c068a752
GB
228 fFinishedLatch = new CountDownLatch(1);
229 }
230
231 /**
232 * Actually executes the analysis itself
233 *
234 * @param monitor
235 * Progress monitor
236 * @return Whether the analysis was completed successfully or not
237 * @throws TmfAnalysisException
238 * Method may throw an analysis exception
239 */
240 protected abstract boolean executeAnalysis(final IProgressMonitor monitor) throws TmfAnalysisException;
241
242 /**
243 * Indicate the analysis has been canceled. It is abstract to force
244 * implementing class to cleanup what they are running. This is called by
245 * the job's canceling. It does not need to be called directly.
246 */
247 protected abstract void canceling();
248
249 /**
250 * To be called when the analysis is completed, whether normally or because
251 * it was cancelled or for any other reason.
252 *
253 * It has to be called inside a synchronized block
254 */
255 private void setAnalysisCompleted() {
6dc36f66
GB
256 synchronized (syncObj) {
257 fStarted = false;
258 fJob = null;
259 fFinishedLatch.countDown();
260 }
c068a752
GB
261 }
262
263 /**
264 * Cancels the analysis if it is executing
265 */
266 @Override
267 public final void cancel() {
268 synchronized (syncObj) {
6dc36f66 269 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "cancelled by application"); //$NON-NLS-1$
7256553f
MK
270 if (fJob != null && fJob.cancel()) {
271 fAnalysisCancelled = true;
272 setAnalysisCompleted();
c068a752
GB
273 }
274 fStarted = false;
275 }
276 }
277
130e6f4e
MAL
278 @Override
279 public void dispose() {
280 super.dispose();
281 cancel();
282 }
283
0b4160dc
GB
284 /**
285 * Get an iterable list of all analyzes this analysis depends on. These
286 * analyzes will be scheduled before this analysis starts and the current
287 * analysis will not be considered completed until all the dependent
288 * analyzes are finished.
289 *
290 * @return An iterable list of analysis this analyzes depends on.
291 */
292 protected Iterable<IAnalysisModule> getDependentAnalyses() {
aa353506 293 return Collections.EMPTY_LIST;
0b4160dc 294 }
c068a752 295
0021a734
GB
296 /**
297 * @since 2.0
298 */
299 @Override
300 public int getDependencyLevel() {
301 return fDependencyLevel;
302 }
303
0b4160dc 304 private void execute(final ITmfTrace trace) {
c068a752
GB
305 /*
306 * TODO: The analysis in a job should be done at the analysis manager
307 * level instead of depending on this abstract class implementation,
308 * otherwise another analysis implementation may block the main thread
309 */
310
311 /* Do not execute if analysis has already run */
312 if (fFinishedLatch.getCount() == 0) {
6dc36f66 313 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "already executed"); //$NON-NLS-1$
c068a752
GB
314 return;
315 }
316
317 /* Do not execute if analysis already running */
318 synchronized (syncObj) {
319 if (fStarted) {
6dc36f66 320 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "already started, not starting again"); //$NON-NLS-1$
c068a752
GB
321 return;
322 }
323 fStarted = true;
324 }
325
0b4160dc
GB
326 /* Execute dependent analyses before creating the job for this one */
327 final Iterable<IAnalysisModule> dependentAnalyses = getDependentAnalyses();
0021a734 328 int depLevel = 0;
0b4160dc
GB
329 for (IAnalysisModule module : dependentAnalyses) {
330 module.schedule();
0021a734
GB
331 // Add the dependency level of the analysis + 1 to make sure that if
332 // an analysis already depends on another, it is taken into account
333 depLevel += module.getDependencyLevel() + 1;
0b4160dc 334 }
0021a734 335 fDependencyLevel = depLevel;
0b4160dc 336
c068a752
GB
337 /*
338 * Actual analysis will be run on a separate thread
339 */
5db5a3a4 340 String jobName = checkNotNull(NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, getName()));
ba27dd38 341 fJob = new Job(jobName) {
c068a752 342 @Override
ba27dd38
GB
343 protected @Nullable IStatus run(final @Nullable IProgressMonitor monitor) {
344 IProgressMonitor mon = monitor;
345 if (mon == null) {
346 mon = new NullProgressMonitor();
347 }
c068a752 348 try {
ba27dd38 349 mon.beginTask("", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
c068a752 350 broadcast(new TmfStartAnalysisSignal(TmfAbstractAnalysisModule.this, TmfAbstractAnalysisModule.this));
6dc36f66 351 TmfCoreTracer.traceAnalysis(TmfAbstractAnalysisModule.this.getId(), TmfAbstractAnalysisModule.this.getTrace(), "started"); //$NON-NLS-1$
ba27dd38 352 fAnalysisCancelled = !executeAnalysis(mon);
0b4160dc
GB
353 for (IAnalysisModule module : dependentAnalyses) {
354 module.waitForCompletion(mon);
355 }
6dc36f66 356 TmfCoreTracer.traceAnalysis(TmfAbstractAnalysisModule.this.getId(), TmfAbstractAnalysisModule.this.getTrace(), "finished"); //$NON-NLS-1$
c068a752 357 } catch (TmfAnalysisException e) {
e1c415b3 358 Activator.logError("Error executing analysis with trace " + trace.getName(), e); //$NON-NLS-1$
c068a752
GB
359 } finally {
360 synchronized (syncObj) {
ba27dd38 361 mon.done();
c068a752
GB
362 setAnalysisCompleted();
363 }
88567ed2 364 TmfTraceManager.refreshSupplementaryFiles(trace);
c068a752
GB
365 }
366 if (!fAnalysisCancelled) {
367 return Status.OK_STATUS;
368 }
baa96b1d
BH
369 // Reset analysis so that it can be executed again.
370 resetAnalysis();
c068a752
GB
371 return Status.CANCEL_STATUS;
372 }
373
374 @Override
375 protected void canceling() {
6dc36f66 376 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "job cancelled"); //$NON-NLS-1$
c068a752
GB
377 TmfAbstractAnalysisModule.this.canceling();
378 }
379
380 };
381 fJob.schedule();
382 }
383
384 @Override
385 public IStatus schedule() {
e1c415b3
BH
386 synchronized (syncObj) {
387 final ITmfTrace trace = getTrace();
388 if (trace == null) {
389 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, String.format("No trace specified for analysis %s", getName())); //$NON-NLS-1$
390 }
6dc36f66 391 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "scheduled"); //$NON-NLS-1$
e1c415b3 392 execute(trace);
c068a752 393 }
c068a752 394
0e4f957e 395 return Status.OK_STATUS;
c068a752
GB
396 }
397
398 @Override
d9810555
AM
399 public Iterable<IAnalysisOutput> getOutputs() {
400 return fOutputs;
c068a752
GB
401 }
402
403 @Override
404 public void registerOutput(IAnalysisOutput output) {
405 if (!fOutputs.contains(output)) {
406 fOutputs.add(output);
407 }
408 }
409
7d6122fc
AM
410 @Override
411 public boolean waitForCompletion() {
412 try {
413 fFinishedLatch.await();
414 } catch (InterruptedException e) {
415 Activator.logError("Error while waiting for module completion", e); //$NON-NLS-1$
416 }
417 return !fAnalysisCancelled;
418 }
419
c068a752
GB
420 @Override
421 public boolean waitForCompletion(IProgressMonitor monitor) {
422 try {
0d3a54a3
AM
423 while (!fFinishedLatch.await(500, TimeUnit.MILLISECONDS)) {
424 if (fAnalysisCancelled || monitor.isCanceled()) {
c068a752
GB
425 fAnalysisCancelled = true;
426 return false;
427 }
428 }
429 } catch (InterruptedException e) {
430 Activator.logError("Error while waiting for module completion", e); //$NON-NLS-1$
431 }
432 return !fAnalysisCancelled;
433 }
434
435 /**
436 * Signal handler for trace closing
437 *
438 * @param signal
439 * Trace closed signal
440 */
441 @TmfSignalHandler
442 public void traceClosed(TmfTraceClosedSignal signal) {
443 /* Is the closing trace the one that was requested? */
e1c415b3
BH
444 synchronized (syncObj) {
445 if (signal.getTrace() == fTrace) {
446 cancel();
447 fTrace = null;
448 }
c068a752
GB
449 }
450 }
451
715154b1
GB
452 /**
453 * Signal handler for when the trace becomes active
454 *
455 * @param signal
456 * Trace selected signal
715154b1
GB
457 */
458 @TmfSignalHandler
459 public void traceSelected(TmfTraceSelectedSignal signal) {
460 /*
461 * Since some parameter providers may handle many traces, we need to
462 * register the current trace to it
463 */
464 if (signal.getTrace() == fTrace) {
465 for (IAnalysisParameterProvider provider : fParameterProviders) {
466 provider.registerModule(this);
467 }
468 }
469 }
470
c068a752
GB
471 /**
472 * Returns a full help text to display
473 *
474 * @return Full help text for the module
475 */
476 protected String getFullHelpText() {
5db5a3a4
AM
477 return NonNullUtils.nullToEmptyString(NLS.bind(
478 Messages.TmfAbstractAnalysisModule_AnalysisModule,
479 getName()));
c068a752
GB
480 }
481
482 /**
483 * Gets a short help text, to display as header to other help text
484 *
485 * @param trace
486 * The trace to show help for
487 *
488 * @return Short help text describing the module
489 */
490 protected String getShortHelpText(ITmfTrace trace) {
5db5a3a4
AM
491 return NonNullUtils.nullToEmptyString(NLS.bind(
492 Messages.TmfAbstractAnalysisModule_AnalysisForTrace,
493 getName(), trace.getName()));
c068a752
GB
494 }
495
496 /**
497 * Gets the help text specific for a trace who does not have required
54eae41f
GB
498 * characteristics for module to execute. The default implementation uses
499 * the analysis requirements.
c068a752
GB
500 *
501 * @param trace
502 * The trace to apply the analysis to
503 * @return Help text
504 */
ba27dd38 505 protected String getTraceCannotExecuteHelpText(ITmfTrace trace) {
54eae41f
GB
506 StringBuilder builder = new StringBuilder();
507 builder.append(NLS.bind(Messages.TmfAbstractAnalysisModule_AnalysisCannotExecute, getName()));
508 for (TmfAnalysisRequirement requirement : getAnalysisRequirements()) {
e44d6313 509 if (!requirement.test(trace)) {
54eae41f
GB
510 builder.append("\n\n"); //$NON-NLS-1$
511 builder.append(NLS.bind(Messages.TmfAnalysis_RequirementNotFulfilled, requirement.getType()));
512 builder.append("\n"); //$NON-NLS-1$
513 builder.append(NLS.bind(Messages.TmfAnalysis_RequirementMandatoryValues, requirement.getValues(ValuePriorityLevel.MANDATORY)));
514 Set<String> information = requirement.getInformation();
515 if (!information.isEmpty()) {
516 builder.append("\n"); //$NON-NLS-1$
517 builder.append(NLS.bind(Messages.TmfAnalysis_RequirementInformation, information));
518 }
519 }
520 }
0e4f957e 521 return builder.toString();
c068a752
GB
522 }
523
524 @Override
525 public String getHelpText() {
526 return getFullHelpText();
527 }
528
529 @Override
530 public String getHelpText(ITmfTrace trace) {
c068a752
GB
531 String text = getShortHelpText(trace);
532 if (!canExecute(trace)) {
54eae41f 533 text = text + "\n\n" + getTraceCannotExecuteHelpText(trace); //$NON-NLS-1$
c068a752
GB
534 }
535 return text;
536 }
537
63c43609 538 @Override
ca0f94c4 539 public Iterable<@NonNull TmfAnalysisRequirement> getAnalysisRequirements() {
aa353506 540 return Collections.EMPTY_SET;
63c43609 541 }
a01f6266
GB
542
543 // ------------------------------------------------------------------------
544 // ITmfPropertiesProvider
545 // ------------------------------------------------------------------------
546
547 /**
548 * @since 2.0
549 */
550 @Override
551 public Map<@NonNull String, @NonNull String> getProperties() {
552 Map<@NonNull String, @NonNull String> properties = new HashMap<>();
553
554 properties.put(NonNullUtils.checkNotNull(Messages.TmfAbstractAnalysisModule_LabelId), getId());
555
556 return properties;
557 }
c068a752 558}
This page took 0.151466 seconds and 5 git commands to generate.