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
.TmfAnalysisRequirement
;
40 import org
.eclipse
.tracecompass
.tmf
.core
.analysis
.requirements
.TmfAnalysisRequirement
.ValuePriorityLevel
;
41 import org
.eclipse
.tracecompass
.tmf
.core
.component
.TmfComponent
;
42 import org
.eclipse
.tracecompass
.tmf
.core
.exceptions
.TmfAnalysisException
;
43 import org
.eclipse
.tracecompass
.tmf
.core
.project
.model
.ITmfPropertiesProvider
;
44 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalHandler
;
45 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfStartAnalysisSignal
;
46 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceClosedSignal
;
47 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceSelectedSignal
;
48 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
49 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceManager
;
52 * Base class that analysis modules main class may extend. It provides default
53 * behavior to some methods of the analysis module
55 * @author Geneviève Bastien
58 public abstract class TmfAbstractAnalysisModule
extends TmfComponent
59 implements IAnalysisModule
, ITmfPropertiesProvider
{
61 private @Nullable String fId
;
62 private boolean fAutomatic
= false, fStarted
= false;
63 private volatile @Nullable ITmfTrace fTrace
;
64 private final Map
<String
, @Nullable Object
> fParameters
= new HashMap
<>();
65 private final List
<String
> fParameterNames
= new ArrayList
<>();
66 private final List
<IAnalysisOutput
> fOutputs
= new ArrayList
<>();
67 private Set
<IAnalysisParameterProvider
> fParameterProviders
= new HashSet
<>();
68 private @Nullable Job fJob
= null;
69 private int fDependencyLevel
= 0;
71 private final Object syncObj
= new Object();
73 /* Latch tracking if the analysis is completed or not */
74 private CountDownLatch fFinishedLatch
= new CountDownLatch(0);
76 private boolean fAnalysisCancelled
= false;
79 public boolean isAutomatic() {
84 public String
getName() {
85 return super.getName();
89 public void setName(String name
) {
94 public void setId(String id
) {
99 public String
getId() {
102 id
= this.getClass().getCanonicalName();
105 * Some types, like anonymous classes, don't have a canonical
106 * name. Just use the default name instead.
108 id
= this.getClass().getName();
116 public void setAutomatic(boolean auto
) {
124 public boolean setTrace(ITmfTrace trace
) throws TmfAnalysisException
{
125 if (fTrace
!= null) {
126 throw new TmfAnalysisException(NLS
.bind(Messages
.TmfAbstractAnalysisModule_TraceSetMoreThanOnce
, getName()));
129 TmfCoreTracer
.traceAnalysis(getId(), trace
, "setting trace for analysis"); //$NON-NLS-1$
131 /* Check that analysis can be executed */
133 if (!canExecute(trace
)) {
138 /* Get the parameter providers for this trace */
139 fParameterProviders
= TmfAnalysisManager
.getParameterProvidersForModule(this, trace
);
140 for (IAnalysisParameterProvider provider
: fParameterProviders
) {
141 TmfCoreTracer
.traceAnalysis(getId(), trace
, "registered to parameter provider " + provider
.getName()); //$NON-NLS-1$
142 provider
.registerModule(this);
154 protected @Nullable ITmfTrace
getTrace() {
159 public void addParameter(String name
) {
160 fParameterNames
.add(name
);
164 public synchronized void setParameter(String name
, @Nullable Object value
) {
165 if (!fParameterNames
.contains(name
)) {
166 throw new RuntimeException(NLS
.bind(Messages
.TmfAbstractAnalysisModule_InvalidParameter
, name
, getName()));
168 Object oldValue
= fParameters
.get(name
);
169 fParameters
.put(name
, value
);
170 if ((value
!= null) && !(value
.equals(oldValue
))) {
171 parameterChanged(name
);
176 public synchronized void notifyParameterChanged(String name
) {
177 if (!fParameterNames
.contains(name
)) {
178 throw new RuntimeException(NLS
.bind(Messages
.TmfAbstractAnalysisModule_InvalidParameter
, name
, getName()));
180 Object oldValue
= fParameters
.get(name
);
181 Object value
= getParameter(name
);
182 if ((value
!= null) && !(value
.equals(oldValue
))) {
183 parameterChanged(name
);
188 * Used to indicate that a parameter value has been changed
191 * The name of the modified parameter
193 protected void parameterChanged(String name
) {
198 public @Nullable Object
getParameter(String name
) {
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) {
213 public boolean canExecute(ITmfTrace trace
) {
214 for (TmfAnalysisRequirement requirement
: getAnalysisRequirements()) {
215 if (!requirement
.test(trace
)) {
223 * Set the countdown latch back to 1 so the analysis can be executed again
225 protected void resetAnalysis() {
226 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "reset: ready for execution"); //$NON-NLS-1$
227 fFinishedLatch
.countDown();
228 fFinishedLatch
= new CountDownLatch(1);
232 * Actually executes the analysis itself
236 * @return Whether the analysis was completed successfully or not
237 * @throws TmfAnalysisException
238 * Method may throw an analysis exception
240 protected abstract boolean executeAnalysis(final IProgressMonitor monitor
) throws TmfAnalysisException
;
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.
247 protected abstract void canceling();
250 * To be called when the analysis is completed, whether normally or because
251 * it was cancelled or for any other reason.
253 * It has to be called inside a synchronized block
255 private void setAnalysisCompleted() {
256 synchronized (syncObj
) {
259 fFinishedLatch
.countDown();
264 * Cancels the analysis if it is executing
267 public final void cancel() {
268 synchronized (syncObj
) {
269 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "cancelled by application"); //$NON-NLS-1$
270 if (fJob
!= null && fJob
.cancel()) {
271 fAnalysisCancelled
= true;
272 setAnalysisCompleted();
279 public void dispose() {
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.
290 * @return An iterable list of analysis this analyzes depends on.
292 protected Iterable
<IAnalysisModule
> getDependentAnalyses() {
293 return Collections
.EMPTY_LIST
;
300 public int getDependencyLevel() {
301 return fDependencyLevel
;
304 private void execute(final ITmfTrace trace
) {
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
311 /* Do not execute if analysis has already run */
312 if (fFinishedLatch
.getCount() == 0) {
313 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "already executed"); //$NON-NLS-1$
317 /* Do not execute if analysis already running */
318 synchronized (syncObj
) {
320 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "already started, not starting again"); //$NON-NLS-1$
326 /* Execute dependent analyses before creating the job for this one */
327 final Iterable
<IAnalysisModule
> dependentAnalyses
= getDependentAnalyses();
329 for (IAnalysisModule module
: dependentAnalyses
) {
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;
335 fDependencyLevel
= depLevel
;
338 * Actual analysis will be run on a separate thread
340 String jobName
= checkNotNull(NLS
.bind(Messages
.TmfAbstractAnalysisModule_RunningAnalysis
, getName()));
341 fJob
= new Job(jobName
) {
343 protected @Nullable IStatus
run(final @Nullable IProgressMonitor monitor
) {
344 IProgressMonitor mon
= monitor
;
346 mon
= new NullProgressMonitor();
349 mon
.beginTask("", IProgressMonitor
.UNKNOWN
); //$NON-NLS-1$
350 broadcast(new TmfStartAnalysisSignal(TmfAbstractAnalysisModule
.this, TmfAbstractAnalysisModule
.this));
351 TmfCoreTracer
.traceAnalysis(TmfAbstractAnalysisModule
.this.getId(), TmfAbstractAnalysisModule
.this.getTrace(), "started"); //$NON-NLS-1$
352 fAnalysisCancelled
= !executeAnalysis(mon
);
353 for (IAnalysisModule module
: dependentAnalyses
) {
354 module
.waitForCompletion(mon
);
356 TmfCoreTracer
.traceAnalysis(TmfAbstractAnalysisModule
.this.getId(), TmfAbstractAnalysisModule
.this.getTrace(), "finished"); //$NON-NLS-1$
357 } catch (TmfAnalysisException e
) {
358 Activator
.logError("Error executing analysis with trace " + trace
.getName(), e
); //$NON-NLS-1$
360 synchronized (syncObj
) {
362 setAnalysisCompleted();
364 TmfTraceManager
.refreshSupplementaryFiles(trace
);
366 if (!fAnalysisCancelled
) {
367 return Status
.OK_STATUS
;
369 // Reset analysis so that it can be executed again.
371 return Status
.CANCEL_STATUS
;
375 protected void canceling() {
376 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "job cancelled"); //$NON-NLS-1$
377 TmfAbstractAnalysisModule
.this.canceling();
385 public IStatus
schedule() {
386 synchronized (syncObj
) {
387 final ITmfTrace trace
= getTrace();
389 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, String
.format("No trace specified for analysis %s", getName())); //$NON-NLS-1$
391 TmfCoreTracer
.traceAnalysis(getId(), getTrace(), "scheduled"); //$NON-NLS-1$
395 return Status
.OK_STATUS
;
399 public Iterable
<IAnalysisOutput
> getOutputs() {
404 public void registerOutput(IAnalysisOutput output
) {
405 if (!fOutputs
.contains(output
)) {
406 fOutputs
.add(output
);
411 public boolean waitForCompletion() {
413 fFinishedLatch
.await();
414 } catch (InterruptedException e
) {
415 Activator
.logError("Error while waiting for module completion", e
); //$NON-NLS-1$
417 return !fAnalysisCancelled
;
421 public boolean waitForCompletion(IProgressMonitor monitor
) {
423 while (!fFinishedLatch
.await(500, TimeUnit
.MILLISECONDS
)) {
424 if (fAnalysisCancelled
|| monitor
.isCanceled()) {
425 fAnalysisCancelled
= true;
429 } catch (InterruptedException e
) {
430 Activator
.logError("Error while waiting for module completion", e
); //$NON-NLS-1$
432 return !fAnalysisCancelled
;
436 * Signal handler for trace closing
439 * Trace closed signal
442 public void traceClosed(TmfTraceClosedSignal signal
) {
443 /* Is the closing trace the one that was requested? */
444 synchronized (syncObj
) {
445 if (signal
.getTrace() == fTrace
) {
453 * Signal handler for when the trace becomes active
456 * Trace selected signal
459 public void traceSelected(TmfTraceSelectedSignal signal
) {
461 * Since some parameter providers may handle many traces, we need to
462 * register the current trace to it
464 if (signal
.getTrace() == fTrace
) {
465 for (IAnalysisParameterProvider provider
: fParameterProviders
) {
466 provider
.registerModule(this);
472 * Returns a full help text to display
474 * @return Full help text for the module
476 protected String
getFullHelpText() {
477 return NonNullUtils
.nullToEmptyString(NLS
.bind(
478 Messages
.TmfAbstractAnalysisModule_AnalysisModule
,
483 * Gets a short help text, to display as header to other help text
486 * The trace to show help for
488 * @return Short help text describing the module
490 protected String
getShortHelpText(ITmfTrace trace
) {
491 return NonNullUtils
.nullToEmptyString(NLS
.bind(
492 Messages
.TmfAbstractAnalysisModule_AnalysisForTrace
,
493 getName(), trace
.getName()));
497 * Gets the help text specific for a trace who does not have required
498 * characteristics for module to execute. The default implementation uses
499 * the analysis requirements.
502 * The trace to apply the analysis to
505 protected String
getTraceCannotExecuteHelpText(ITmfTrace trace
) {
506 StringBuilder builder
= new StringBuilder();
507 builder
.append(NLS
.bind(Messages
.TmfAbstractAnalysisModule_AnalysisCannotExecute
, getName()));
508 for (TmfAnalysisRequirement requirement
: getAnalysisRequirements()) {
509 if (!requirement
.test(trace
)) {
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
));
521 return builder
.toString();
525 public String
getHelpText() {
526 return getFullHelpText();
530 public String
getHelpText(ITmfTrace trace
) {
531 String text
= getShortHelpText(trace
);
532 if (!canExecute(trace
)) {
533 text
= text
+ "\n\n" + getTraceCannotExecuteHelpText(trace
); //$NON-NLS-1$
539 public Iterable
<@NonNull TmfAnalysisRequirement
> getAnalysisRequirements() {
540 return Collections
.EMPTY_SET
;
543 // ------------------------------------------------------------------------
544 // ITmfPropertiesProvider
545 // ------------------------------------------------------------------------
551 public Map
<@NonNull String
, @NonNull String
> getProperties() {
552 Map
<@NonNull String
, @NonNull String
> properties
= new HashMap
<>();
554 properties
.put(NonNullUtils
.checkNotNull(Messages
.TmfAbstractAnalysisModule_LabelId
), getId());