1 /*******************************************************************************
2 * Copyright (c) 2013, 2014 École Polytechnique de Montréal
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
10 * Geneviève Bastien - Initial API and implementation
11 *******************************************************************************/
13 package org
.eclipse
.tracecompass
.tmf
.core
.analysis
;
15 import java
.util
.ArrayList
;
16 import java
.util
.Collections
;
17 import java
.util
.HashMap
;
18 import java
.util
.List
;
21 import java
.util
.concurrent
.CountDownLatch
;
22 import java
.util
.concurrent
.TimeUnit
;
24 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
25 import org
.eclipse
.core
.runtime
.IStatus
;
26 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
27 import org
.eclipse
.core
.runtime
.Status
;
28 import org
.eclipse
.core
.runtime
.jobs
.Job
;
29 import org
.eclipse
.jdt
.annotation
.NonNull
;
30 import org
.eclipse
.jdt
.annotation
.NonNullByDefault
;
31 import org
.eclipse
.jdt
.annotation
.Nullable
;
32 import org
.eclipse
.osgi
.util
.NLS
;
33 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.Activator
;
34 import org
.eclipse
.tracecompass
.tmf
.core
.analysis
.TmfAnalysisRequirement
.ValuePriorityLevel
;
35 import org
.eclipse
.tracecompass
.tmf
.core
.component
.TmfComponent
;
36 import org
.eclipse
.tracecompass
.tmf
.core
.exceptions
.TmfAnalysisException
;
37 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalHandler
;
38 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfStartAnalysisSignal
;
39 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceClosedSignal
;
40 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceSelectedSignal
;
41 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
42 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceManager
;
45 * Base class that analysis modules main class may extend. It provides default
46 * behavior to some methods of the analysis module
48 * @author Geneviève Bastien
52 public abstract class TmfAbstractAnalysisModule
extends TmfComponent
implements IAnalysisModule
{
54 private @Nullable String fId
;
55 private boolean fAutomatic
= false, fStarted
= false;
56 private volatile @Nullable ITmfTrace fTrace
;
57 private final Map
<String
, Object
> fParameters
= new HashMap
<>();
58 private final List
<String
> fParameterNames
= new ArrayList
<>();
59 private final List
<IAnalysisOutput
> fOutputs
= new ArrayList
<>();
60 private List
<IAnalysisParameterProvider
> fParameterProviders
= new ArrayList
<>();
61 private @Nullable Job fJob
= null;
63 private final Object syncObj
= new Object();
65 /* Latch tracking if the analysis is completed or not */
66 private CountDownLatch fFinishedLatch
= new CountDownLatch(0);
68 private boolean fAnalysisCancelled
= false;
71 public boolean isAutomatic() {
76 public String
getName() {
77 return super.getName();
81 public void setName(String name
) {
86 public void setId(String id
) {
91 public String
getId() {
94 id
= new String(this.getClass().getCanonicalName());
101 public void setAutomatic(boolean auto
) {
106 public void setTrace(ITmfTrace trace
) throws TmfAnalysisException
{
107 if (fTrace
!= null) {
108 throw new TmfAnalysisException(NLS
.bind(Messages
.TmfAbstractAnalysisModule_TraceSetMoreThanOnce
, getName()));
111 /* Check that analysis can be executed */
112 if (!canExecute(trace
)) {
113 throw new TmfAnalysisException(NLS
.bind(Messages
.TmfAbstractAnalysisModule_AnalysisCannotExecute
, getName()));
117 /* Get the parameter providers for this trace */
118 fParameterProviders
= TmfAnalysisManager
.getParameterProviders(this, trace
);
119 for (IAnalysisParameterProvider provider
: fParameterProviders
) {
120 provider
.registerModule(this);
131 protected @Nullable ITmfTrace
getTrace() {
136 public void addParameter(String name
) {
137 fParameterNames
.add(name
);
141 public synchronized void setParameter(String name
, @Nullable Object value
) {
142 if (!fParameterNames
.contains(name
)) {
143 throw new RuntimeException(NLS
.bind(Messages
.TmfAbstractAnalysisModule_InvalidParameter
, name
, getName()));
145 Object oldValue
= fParameters
.get(name
);
146 fParameters
.put(name
, value
);
147 if ((value
!= null) && !(value
.equals(oldValue
))) {
148 parameterChanged(name
);
153 public synchronized void notifyParameterChanged(String name
) {
154 if (!fParameterNames
.contains(name
)) {
155 throw new RuntimeException(NLS
.bind(Messages
.TmfAbstractAnalysisModule_InvalidParameter
, name
, getName()));
157 Object oldValue
= fParameters
.get(name
);
158 Object value
= getParameter(name
);
159 if ((value
!= null) && !(value
.equals(oldValue
))) {
160 parameterChanged(name
);
165 * Used to indicate that a parameter value has been changed
168 * The name of the modified parameter
170 protected void parameterChanged(String name
) {
175 public @Nullable Object
getParameter(String name
) {
176 Object paramValue
= fParameters
.get(name
);
177 /* The parameter is not set, maybe it can be provided by someone else */
178 if ((paramValue
== null) && (fTrace
!= null)) {
179 for (IAnalysisParameterProvider provider
: fParameterProviders
) {
180 paramValue
= provider
.getParameter(name
);
181 if (paramValue
!= null) {
190 public boolean canExecute(ITmfTrace trace
) {
191 for (TmfAnalysisRequirement requirement
: getAnalysisRequirements()) {
192 if (!requirement
.isFulfilled(trace
)) {
200 * Set the countdown latch back to 1 so the analysis can be executed again
202 protected void resetAnalysis() {
203 fFinishedLatch
.countDown();
204 fFinishedLatch
= new CountDownLatch(1);
208 * Actually executes the analysis itself
212 * @return Whether the analysis was completed successfully or not
213 * @throws TmfAnalysisException
214 * Method may throw an analysis exception
216 protected abstract boolean executeAnalysis(final IProgressMonitor monitor
) throws TmfAnalysisException
;
219 * Indicate the analysis has been canceled. It is abstract to force
220 * implementing class to cleanup what they are running. This is called by
221 * the job's canceling. It does not need to be called directly.
223 protected abstract void canceling();
226 * To be called when the analysis is completed, whether normally or because
227 * it was cancelled or for any other reason.
229 * It has to be called inside a synchronized block
231 private void setAnalysisCompleted() {
234 fFinishedLatch
.countDown();
238 * Cancels the analysis if it is executing
241 public final void cancel() {
242 synchronized (syncObj
) {
245 fAnalysisCancelled
= true;
246 setAnalysisCompleted();
254 public void dispose() {
260 * Get an iterable list of all analyzes this analysis depends on. These
261 * analyzes will be scheduled before this analysis starts and the current
262 * analysis will not be considered completed until all the dependent
263 * analyzes are finished.
265 * @return An iterable list of analysis this analyzes depends on.
267 protected Iterable
<IAnalysisModule
> getDependentAnalyses() {
268 @SuppressWarnings("null")
269 @NonNull Set
<IAnalysisModule
> emptySet
= Collections
.EMPTY_SET
;
273 private void execute(final ITmfTrace trace
) {
275 * TODO: The analysis in a job should be done at the analysis manager
276 * level instead of depending on this abstract class implementation,
277 * otherwise another analysis implementation may block the main thread
280 /* Do not execute if analysis has already run */
281 if (fFinishedLatch
.getCount() == 0) {
285 /* Do not execute if analysis already running */
286 synchronized (syncObj
) {
293 /* Execute dependent analyses before creating the job for this one */
294 final Iterable
<IAnalysisModule
> dependentAnalyses
= getDependentAnalyses();
295 for (IAnalysisModule module
: dependentAnalyses
) {
300 * Actual analysis will be run on a separate thread
302 @SuppressWarnings("null")
303 @NonNull String jobName
= NLS
.bind(Messages
.TmfAbstractAnalysisModule_RunningAnalysis
, getName());
304 fJob
= new Job(jobName
) {
306 protected @Nullable IStatus
run(final @Nullable IProgressMonitor monitor
) {
307 IProgressMonitor mon
= monitor
;
309 mon
= new NullProgressMonitor();
312 mon
.beginTask("", IProgressMonitor
.UNKNOWN
); //$NON-NLS-1$
313 broadcast(new TmfStartAnalysisSignal(TmfAbstractAnalysisModule
.this, TmfAbstractAnalysisModule
.this));
314 fAnalysisCancelled
= !executeAnalysis(mon
);
315 for (IAnalysisModule module
: dependentAnalyses
) {
316 module
.waitForCompletion(mon
);
318 } catch (TmfAnalysisException e
) {
319 Activator
.logError("Error executing analysis with trace " + trace
.getName(), e
); //$NON-NLS-1$
321 synchronized (syncObj
) {
323 setAnalysisCompleted();
325 TmfTraceManager
.refreshSupplementaryFiles(trace
);
327 if (!fAnalysisCancelled
) {
328 return Status
.OK_STATUS
;
330 // Reset analysis so that it can be executed again.
332 return Status
.CANCEL_STATUS
;
336 protected void canceling() {
337 TmfAbstractAnalysisModule
.this.canceling();
345 public IStatus
schedule() {
346 synchronized (syncObj
) {
347 final ITmfTrace trace
= getTrace();
349 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, String
.format("No trace specified for analysis %s", getName())); //$NON-NLS-1$
354 @SuppressWarnings("null")
355 @NonNull IStatus status
= Status
.OK_STATUS
;
360 public Iterable
<IAnalysisOutput
> getOutputs() {
365 public void registerOutput(IAnalysisOutput output
) {
366 if (!fOutputs
.contains(output
)) {
367 fOutputs
.add(output
);
372 public boolean waitForCompletion() {
374 fFinishedLatch
.await();
375 } catch (InterruptedException e
) {
376 Activator
.logError("Error while waiting for module completion", e
); //$NON-NLS-1$
378 return !fAnalysisCancelled
;
382 public boolean waitForCompletion(IProgressMonitor monitor
) {
384 while (!fFinishedLatch
.await(500, TimeUnit
.MILLISECONDS
)) {
385 if (fAnalysisCancelled
|| monitor
.isCanceled()) {
386 fAnalysisCancelled
= true;
390 } catch (InterruptedException e
) {
391 Activator
.logError("Error while waiting for module completion", e
); //$NON-NLS-1$
393 return !fAnalysisCancelled
;
397 * Signal handler for trace closing
400 * Trace closed signal
403 public void traceClosed(TmfTraceClosedSignal signal
) {
404 /* Is the closing trace the one that was requested? */
405 synchronized (syncObj
) {
406 if (signal
.getTrace() == fTrace
) {
414 * Signal handler for when the trace becomes active
417 * Trace selected signal
421 public void traceSelected(TmfTraceSelectedSignal signal
) {
423 * Since some parameter providers may handle many traces, we need to
424 * register the current trace to it
426 if (signal
.getTrace() == fTrace
) {
427 for (IAnalysisParameterProvider provider
: fParameterProviders
) {
428 provider
.registerModule(this);
434 * Returns a full help text to display
436 * @return Full help text for the module
438 protected String
getFullHelpText() {
439 @SuppressWarnings("null")
440 @NonNull String text
= NLS
.bind(Messages
.TmfAbstractAnalysisModule_AnalysisModule
, getName());
445 * Gets a short help text, to display as header to other help text
448 * The trace to show help for
450 * @return Short help text describing the module
452 protected String
getShortHelpText(ITmfTrace trace
) {
453 @SuppressWarnings("null")
454 @NonNull String text
= NLS
.bind(Messages
.TmfAbstractAnalysisModule_AnalysisForTrace
, getName(), trace
.getName());
459 * Gets the help text specific for a trace who does not have required
460 * characteristics for module to execute. The default implementation uses
461 * the analysis requirements.
464 * The trace to apply the analysis to
467 protected String
getTraceCannotExecuteHelpText(ITmfTrace trace
) {
468 StringBuilder builder
= new StringBuilder();
469 builder
.append(NLS
.bind(Messages
.TmfAbstractAnalysisModule_AnalysisCannotExecute
, getName()));
470 for (TmfAnalysisRequirement requirement
: getAnalysisRequirements()) {
471 if (!requirement
.isFulfilled(trace
)) {
472 builder
.append("\n\n"); //$NON-NLS-1$
473 builder
.append(NLS
.bind(Messages
.TmfAnalysis_RequirementNotFulfilled
, requirement
.getType()));
474 builder
.append("\n"); //$NON-NLS-1$
475 builder
.append(NLS
.bind(Messages
.TmfAnalysis_RequirementMandatoryValues
, requirement
.getValues(ValuePriorityLevel
.MANDATORY
)));
476 Set
<String
> information
= requirement
.getInformation();
477 if (!information
.isEmpty()) {
478 builder
.append("\n"); //$NON-NLS-1$
479 builder
.append(NLS
.bind(Messages
.TmfAnalysis_RequirementInformation
, information
));
483 @SuppressWarnings("null")
484 @NonNull String helpText
= builder
.toString();
489 public String
getHelpText() {
490 return getFullHelpText();
494 public String
getHelpText(ITmfTrace trace
) {
495 String text
= getShortHelpText(trace
);
496 if (!canExecute(trace
)) {
497 text
= text
+ "\n\n" + getTraceCannotExecuteHelpText(trace
); //$NON-NLS-1$
503 public Iterable
<TmfAnalysisRequirement
> getAnalysisRequirements() {
504 @SuppressWarnings("null")
505 @NonNull Iterable
<TmfAnalysisRequirement
> emptySet
= Collections
.EMPTY_SET
;