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