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 static org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
.checkNotNull
;
17 import java
.util
.ArrayList
;
18 import java
.util
.Collections
;
19 import java
.util
.HashMap
;
20 import java
.util
.HashSet
;
21 import java
.util
.List
;
24 import java
.util
.concurrent
.CountDownLatch
;
25 import java
.util
.concurrent
.TimeUnit
;
27 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
28 import org
.eclipse
.core
.runtime
.IStatus
;
29 import org
.eclipse
.core
.runtime
.NullProgressMonitor
;
30 import org
.eclipse
.core
.runtime
.Status
;
31 import org
.eclipse
.core
.runtime
.jobs
.Job
;
32 import org
.eclipse
.jdt
.annotation
.NonNull
;
33 import org
.eclipse
.jdt
.annotation
.NonNullByDefault
;
34 import org
.eclipse
.jdt
.annotation
.Nullable
;
35 import org
.eclipse
.osgi
.util
.NLS
;
36 import org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
;
37 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.Activator
;
38 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.TmfCoreTracer
;
39 import org
.eclipse
.tracecompass
.tmf
.core
.analysis
.requirements
.TmfAbstractAnalysisRequirement
;
40 import org
.eclipse
.tracecompass
.tmf
.core
.component
.TmfComponent
;
41 import org
.eclipse
.tracecompass
.tmf
.core
.exceptions
.TmfAnalysisException
;
42 import org
.eclipse
.tracecompass
.tmf
.core
.project
.model
.ITmfPropertiesProvider
;
43 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalHandler
;
44 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfStartAnalysisSignal
;
45 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceClosedSignal
;
46 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceSelectedSignal
;
47 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
48 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceManager
;
51 * Base class that analysis modules main class may extend. It provides default
52 * behavior to some methods of the analysis module
54 * @author Geneviève Bastien
57 public abstract class TmfAbstractAnalysisModule
extends TmfComponent
58 implements IAnalysisModule
, ITmfPropertiesProvider
{
60 private @Nullable String fId
;
61 private boolean fAutomatic
= false, fStarted
= false;
62 private volatile @Nullable ITmfTrace fTrace
;
63 private final Map
<String
, @Nullable Object
> fParameters
= new HashMap
<>();
64 private final List
<String
> fParameterNames
= new ArrayList
<>();
65 private final List
<IAnalysisOutput
> fOutputs
= new ArrayList
<>();
66 private Set
<IAnalysisParameterProvider
> fParameterProviders
= new HashSet
<>();
67 private @Nullable Job fJob
= null;
68 private int fDependencyLevel
= 0;
70 private final Object syncObj
= new Object();
72 /* Latch tracking if the analysis is completed or not */
73 private CountDownLatch fFinishedLatch
= new CountDownLatch(0);
75 private boolean fAnalysisCancelled
= false;
78 public boolean isAutomatic() {
83 public String
getName() {
84 return super.getName();
88 public void setName(String name
) {
93 public void setId(String id
) {
98 public String
getId() {
101 id
= this.getClass().getCanonicalName();
104 * Some types, like anonymous classes, don't have a canonical
105 * name. Just use the default name instead.
107 id
= this.getClass().getName();
115 public void setAutomatic(boolean auto
) {
123 public boolean setTrace(ITmfTrace trace
) throws TmfAnalysisException
{
124 if (fTrace
!= null) {
125 throw new TmfAnalysisException(NLS
.bind(Messages
.TmfAbstractAnalysisModule_TraceSetMoreThanOnce
, getName()));
128 TmfCoreTracer
.traceAnalysis(getId(), trace
, "setting trace for analysis"); //$NON-NLS-1$
130 /* Check that analysis can be executed */
132 if (!canExecute(trace
)) {
137 /* Get the parameter providers for this trace */
138 fParameterProviders
= TmfAnalysisManager
.getParameterProvidersForModule(this, trace
);
139 for (IAnalysisParameterProvider provider
: fParameterProviders
) {
140 TmfCoreTracer
.traceAnalysis(getId(), trace
, "registered to parameter provider " + provider
.getName()); //$NON-NLS-1$
141 provider
.registerModule(this);
153 protected @Nullable ITmfTrace
getTrace() {
158 public void addParameter(String name
) {
159 fParameterNames
.add(name
);
163 public synchronized void setParameter(String name
, @Nullable Object value
) {
164 if (!fParameterNames
.contains(name
)) {
165 throw new RuntimeException(NLS
.bind(Messages
.TmfAbstractAnalysisModule_InvalidParameter
, name
, getName()));
167 Object oldValue
= fParameters
.get(name
);
168 fParameters
.put(name
, value
);
169 if ((value
!= null) && !(value
.equals(oldValue
))) {
170 parameterChanged(name
);
175 public synchronized void notifyParameterChanged(String name
) {
176 if (!fParameterNames
.contains(name
)) {
177 throw new RuntimeException(NLS
.bind(Messages
.TmfAbstractAnalysisModule_InvalidParameter
, name
, getName()));
179 Object oldValue
= fParameters
.get(name
);
180 Object value
= getParameter(name
);
181 if ((value
!= null) && !(value
.equals(oldValue
))) {
182 parameterChanged(name
);
187 * Used to indicate that a parameter value has been changed
190 * The name of the modified parameter
192 protected void parameterChanged(String name
) {
197 public @Nullable Object
getParameter(String name
) {
198 Object paramValue
= fParameters
.get(name
);
199 /* The parameter is not set, maybe it can be provided by someone else */
200 if ((paramValue
== null) && (fTrace
!= null)) {
201 for (IAnalysisParameterProvider provider
: fParameterProviders
) {
202 paramValue
= provider
.getParameter(name
);
203 if (paramValue
!= null) {
212 public boolean canExecute(ITmfTrace trace
) {
213 for (TmfAbstractAnalysisRequirement requirement
: getAnalysisRequirements()) {
214 if (!requirement
.test(trace
)) {
222 * Set the countdown latch back to 1 so the analysis can be executed again
224 protected void resetAnalysis() {
225 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "reset: ready for execution"); //$NON-NLS-1$
226 synchronized (syncObj
) {
227 fFinishedLatch
.countDown();
228 fFinishedLatch
= new CountDownLatch(1);
233 * Actually executes the analysis itself
237 * @return Whether the analysis was completed successfully or not
238 * @throws TmfAnalysisException
239 * Method may throw an analysis exception
241 protected abstract boolean executeAnalysis(final IProgressMonitor monitor
) throws TmfAnalysisException
;
244 * Indicate the analysis has been canceled. It is abstract to force
245 * implementing class to cleanup what they are running. This is called by
246 * the job's canceling. It does not need to be called directly.
248 protected abstract void canceling();
251 * To be called when the analysis is completed, whether normally or because
252 * it was cancelled or for any other reason.
254 * It has to be called inside a synchronized block
256 private void setAnalysisCompleted() {
257 synchronized (syncObj
) {
260 fFinishedLatch
.countDown();
265 * Cancels the analysis if it is executing
268 public final void cancel() {
269 synchronized (syncObj
) {
270 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "cancelled by application"); //$NON-NLS-1$
274 fAnalysisCancelled
= true;
275 setAnalysisCompleted();
282 public void dispose() {
288 * Get an iterable list of all analyzes this analysis depends on. These
289 * analyzes will be scheduled before this analysis starts and the current
290 * analysis will not be considered completed until all the dependent
291 * analyzes are finished.
293 * @return An iterable list of analysis this analyzes depends on.
295 protected Iterable
<IAnalysisModule
> getDependentAnalyses() {
296 return Collections
.EMPTY_LIST
;
303 public int getDependencyLevel() {
304 return fDependencyLevel
;
307 private void execute(final ITmfTrace trace
) {
309 * TODO: The analysis in a job should be done at the analysis manager
310 * level instead of depending on this abstract class implementation,
311 * otherwise another analysis implementation may block the main thread
314 /* Do not execute if analysis has already run */
315 if (fFinishedLatch
.getCount() == 0) {
316 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "already executed"); //$NON-NLS-1$
320 /* Do not execute if analysis already running */
321 synchronized (syncObj
) {
323 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "already started, not starting again"); //$NON-NLS-1$
329 /* Execute dependent analyses before creating the job for this one */
330 final Iterable
<IAnalysisModule
> dependentAnalyses
= getDependentAnalyses();
332 for (IAnalysisModule module
: dependentAnalyses
) {
334 // Add the dependency level of the analysis + 1 to make sure that if
335 // an analysis already depends on another, it is taken into account
336 depLevel
+= module
.getDependencyLevel() + 1;
338 fDependencyLevel
= depLevel
;
341 * Actual analysis will be run on a separate thread
343 String jobName
= checkNotNull(NLS
.bind(Messages
.TmfAbstractAnalysisModule_RunningAnalysis
, getName()));
344 fJob
= new Job(jobName
) {
346 protected @Nullable IStatus
run(final @Nullable IProgressMonitor monitor
) {
347 IProgressMonitor mon
= monitor
;
349 mon
= new NullProgressMonitor();
352 mon
.beginTask("", IProgressMonitor
.UNKNOWN
); //$NON-NLS-1$
353 broadcast(new TmfStartAnalysisSignal(TmfAbstractAnalysisModule
.this, TmfAbstractAnalysisModule
.this));
354 TmfCoreTracer
.traceAnalysis(TmfAbstractAnalysisModule
.this.getId(), TmfAbstractAnalysisModule
.this.getTrace(), "started"); //$NON-NLS-1$
355 fAnalysisCancelled
= !executeAnalysis(mon
);
356 for (IAnalysisModule module
: dependentAnalyses
) {
357 module
.waitForCompletion(mon
);
359 TmfCoreTracer
.traceAnalysis(TmfAbstractAnalysisModule
.this.getId(), TmfAbstractAnalysisModule
.this.getTrace(), "finished"); //$NON-NLS-1$
360 } catch (TmfAnalysisException e
) {
361 Activator
.logError("Error executing analysis with trace " + trace
.getName(), e
); //$NON-NLS-1$
363 synchronized (syncObj
) {
365 setAnalysisCompleted();
367 TmfTraceManager
.refreshSupplementaryFiles(trace
);
369 if (!fAnalysisCancelled
) {
370 return Status
.OK_STATUS
;
372 // Reset analysis so that it can be executed again.
374 return Status
.CANCEL_STATUS
;
378 protected void canceling() {
379 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "job cancelled"); //$NON-NLS-1$
380 TmfAbstractAnalysisModule
.this.canceling();
388 public IStatus
schedule() {
389 synchronized (syncObj
) {
390 final ITmfTrace trace
= getTrace();
392 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, String
.format("No trace specified for analysis %s", getName())); //$NON-NLS-1$
394 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "scheduled"); //$NON-NLS-1$
398 return Status
.OK_STATUS
;
402 public Iterable
<IAnalysisOutput
> getOutputs() {
407 public void registerOutput(IAnalysisOutput output
) {
408 if (!fOutputs
.contains(output
)) {
409 fOutputs
.add(output
);
414 public boolean waitForCompletion() {
415 CountDownLatch finishedLatch
;
417 synchronized (syncObj
) {
418 finishedLatch
= fFinishedLatch
;
423 finishedLatch
.await();
425 } catch (InterruptedException e
) {
426 Activator
.logError("Error while waiting for module completion", e
); //$NON-NLS-1$
428 return !fAnalysisCancelled
;
432 public boolean waitForCompletion(IProgressMonitor monitor
) {
434 while (!fFinishedLatch
.await(500, TimeUnit
.MILLISECONDS
)) {
435 if (fAnalysisCancelled
|| monitor
.isCanceled()) {
436 fAnalysisCancelled
= true;
440 } catch (InterruptedException e
) {
441 Activator
.logError("Error while waiting for module completion", e
); //$NON-NLS-1$
443 return !fAnalysisCancelled
;
447 * Signal handler for trace closing
450 * Trace closed signal
453 public void traceClosed(TmfTraceClosedSignal signal
) {
454 /* Is the closing trace the one that was requested? */
455 synchronized (syncObj
) {
456 if (signal
.getTrace() == fTrace
) {
464 * Signal handler for when the trace becomes active
467 * Trace selected signal
470 public void traceSelected(TmfTraceSelectedSignal signal
) {
472 * Since some parameter providers may handle many traces, we need to
473 * register the current trace to it
475 if (signal
.getTrace() == fTrace
) {
476 for (IAnalysisParameterProvider provider
: fParameterProviders
) {
477 provider
.registerModule(this);
483 * Returns a full help text to display
485 * @return Full help text for the module
487 protected String
getFullHelpText() {
488 return NonNullUtils
.nullToEmptyString(NLS
.bind(
489 Messages
.TmfAbstractAnalysisModule_AnalysisModule
,
494 * Gets a short help text, to display as header to other help text
497 * The trace to show help for
499 * @return Short help text describing the module
501 protected String
getShortHelpText(ITmfTrace trace
) {
502 return NonNullUtils
.nullToEmptyString(NLS
.bind(
503 Messages
.TmfAbstractAnalysisModule_AnalysisForTrace
,
504 getName(), trace
.getName()));
508 * Gets the help text specific for a trace who does not have required
509 * characteristics for module to execute. The default implementation uses
510 * the analysis requirements.
513 * The trace to apply the analysis to
516 protected String
getTraceCannotExecuteHelpText(ITmfTrace trace
) {
517 StringBuilder builder
= new StringBuilder();
518 builder
.append(NLS
.bind(Messages
.TmfAbstractAnalysisModule_AnalysisCannotExecute
, getName()));
519 for (TmfAbstractAnalysisRequirement requirement
: getAnalysisRequirements()) {
520 if (!requirement
.test(trace
)) {
521 builder
.append("\n\n"); //$NON-NLS-1$
522 builder
.append(NLS
.bind(Messages
.TmfAnalysis_RequirementNotFulfilled
, requirement
.getPriorityLevel()));
523 builder
.append("\n"); //$NON-NLS-1$
524 builder
.append(NLS
.bind(Messages
.TmfAnalysis_RequirementMandatoryValues
, requirement
.getValues()));
525 Set
<String
> information
= requirement
.getInformation();
526 if (!information
.isEmpty()) {
527 builder
.append("\n"); //$NON-NLS-1$
528 builder
.append(NLS
.bind(Messages
.TmfAnalysis_RequirementInformation
, information
));
532 return builder
.toString();
536 public String
getHelpText() {
537 return getFullHelpText();
541 public String
getHelpText(ITmfTrace trace
) {
542 String text
= getShortHelpText(trace
);
543 if (!canExecute(trace
)) {
544 text
= text
+ "\n\n" + getTraceCannotExecuteHelpText(trace
); //$NON-NLS-1$
550 public Iterable
<@NonNull TmfAbstractAnalysisRequirement
> getAnalysisRequirements() {
551 return Collections
.EMPTY_SET
;
554 // ------------------------------------------------------------------------
555 // ITmfPropertiesProvider
556 // ------------------------------------------------------------------------
562 public Map
<@NonNull String
, @NonNull String
> getProperties() {
563 Map
<@NonNull String
, @NonNull String
> properties
= new HashMap
<>();
565 properties
.put(NonNullUtils
.checkNotNull(Messages
.TmfAbstractAnalysisModule_LabelId
), getId());