tmf.core: Add a dependency level to analyses
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.core / src / org / eclipse / tracecompass / tmf / core / analysis / TmfAbstractAnalysisModule.java
1 /*******************************************************************************
2 * Copyright (c) 2013, 2014 École Polytechnique de Montréal
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
13 package org.eclipse.tracecompass.tmf.core.analysis;
14
15 import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;
16
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;
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.concurrent.CountDownLatch;
25 import java.util.concurrent.TimeUnit;
26
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;
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
56 */
57 @NonNullByDefault
58 public abstract class TmfAbstractAnalysisModule extends TmfComponent
59 implements IAnalysisModule, ITmfPropertiesProvider {
60
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;
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() {
85 return super.getName();
86 }
87
88 @Override
89 public void setName(String name) {
90 super.setName(name);
91 }
92
93 @Override
94 public void setId(String id) {
95 fId = id;
96 }
97
98 @Override
99 public String getId() {
100 String id = fId;
101 if (id == null) {
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 */
108 id = this.getClass().getName();
109 }
110 fId = id;
111 }
112 return id;
113 }
114
115 @Override
116 public void setAutomatic(boolean auto) {
117 fAutomatic = auto;
118 }
119
120 /**
121 * @since 1.0
122 */
123 @Override
124 public boolean setTrace(ITmfTrace trace) throws TmfAnalysisException {
125 if (fTrace != null) {
126 throw new TmfAnalysisException(NLS.bind(Messages.TmfAbstractAnalysisModule_TraceSetMoreThanOnce, getName()));
127 }
128
129 TmfCoreTracer.traceAnalysis(getId(), trace, "setting trace for analysis"); //$NON-NLS-1$
130
131 /* Check that analysis can be executed */
132 fTrace = trace;
133 if (!canExecute(trace)) {
134 fTrace = null;
135 return false;
136 }
137
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);
143 }
144 resetAnalysis();
145 fStarted = false;
146 return true;
147 }
148
149 /**
150 * Gets the trace
151 *
152 * @return The trace
153 */
154 protected @Nullable ITmfTrace getTrace() {
155 return fTrace;
156 }
157
158 @Override
159 public void addParameter(String name) {
160 fParameterNames.add(name);
161 }
162
163 @Override
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()));
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
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) {
205 break;
206 }
207 }
208 }
209 return paramValue;
210 }
211
212 @Override
213 public boolean canExecute(ITmfTrace trace) {
214 for (TmfAnalysisRequirement requirement : getAnalysisRequirements()) {
215 if (!requirement.test(trace)) {
216 return false;
217 }
218 }
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() {
226 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "reset: ready for execution"); //$NON-NLS-1$
227 fFinishedLatch.countDown();
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() {
256 synchronized (syncObj) {
257 fStarted = false;
258 fJob = null;
259 fFinishedLatch.countDown();
260 }
261 }
262
263 /**
264 * Cancels the analysis if it is executing
265 */
266 @Override
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();
273 }
274 fStarted = false;
275 }
276 }
277
278 @Override
279 public void dispose() {
280 super.dispose();
281 cancel();
282 }
283
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() {
293 return Collections.EMPTY_LIST;
294 }
295
296 /**
297 * @since 2.0
298 */
299 @Override
300 public int getDependencyLevel() {
301 return fDependencyLevel;
302 }
303
304 private void execute(final ITmfTrace trace) {
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) {
313 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "already executed"); //$NON-NLS-1$
314 return;
315 }
316
317 /* Do not execute if analysis already running */
318 synchronized (syncObj) {
319 if (fStarted) {
320 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "already started, not starting again"); //$NON-NLS-1$
321 return;
322 }
323 fStarted = true;
324 }
325
326 /* Execute dependent analyses before creating the job for this one */
327 final Iterable<IAnalysisModule> dependentAnalyses = getDependentAnalyses();
328 int depLevel = 0;
329 for (IAnalysisModule module : dependentAnalyses) {
330 module.schedule();
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;
334 }
335 fDependencyLevel = depLevel;
336
337 /*
338 * Actual analysis will be run on a separate thread
339 */
340 String jobName = checkNotNull(NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, getName()));
341 fJob = new Job(jobName) {
342 @Override
343 protected @Nullable IStatus run(final @Nullable IProgressMonitor monitor) {
344 IProgressMonitor mon = monitor;
345 if (mon == null) {
346 mon = new NullProgressMonitor();
347 }
348 try {
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);
355 }
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$
359 } finally {
360 synchronized (syncObj) {
361 mon.done();
362 setAnalysisCompleted();
363 }
364 TmfTraceManager.refreshSupplementaryFiles(trace);
365 }
366 if (!fAnalysisCancelled) {
367 return Status.OK_STATUS;
368 }
369 // Reset analysis so that it can be executed again.
370 resetAnalysis();
371 return Status.CANCEL_STATUS;
372 }
373
374 @Override
375 protected void canceling() {
376 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "job cancelled"); //$NON-NLS-1$
377 TmfAbstractAnalysisModule.this.canceling();
378 }
379
380 };
381 fJob.schedule();
382 }
383
384 @Override
385 public IStatus schedule() {
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 }
391 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "scheduled"); //$NON-NLS-1$
392 execute(trace);
393 }
394
395 return Status.OK_STATUS;
396 }
397
398 @Override
399 public Iterable<IAnalysisOutput> getOutputs() {
400 return fOutputs;
401 }
402
403 @Override
404 public void registerOutput(IAnalysisOutput output) {
405 if (!fOutputs.contains(output)) {
406 fOutputs.add(output);
407 }
408 }
409
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
420 @Override
421 public boolean waitForCompletion(IProgressMonitor monitor) {
422 try {
423 while (!fFinishedLatch.await(500, TimeUnit.MILLISECONDS)) {
424 if (fAnalysisCancelled || monitor.isCanceled()) {
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? */
444 synchronized (syncObj) {
445 if (signal.getTrace() == fTrace) {
446 cancel();
447 fTrace = null;
448 }
449 }
450 }
451
452 /**
453 * Signal handler for when the trace becomes active
454 *
455 * @param signal
456 * Trace selected signal
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
471 /**
472 * Returns a full help text to display
473 *
474 * @return Full help text for the module
475 */
476 protected String getFullHelpText() {
477 return NonNullUtils.nullToEmptyString(NLS.bind(
478 Messages.TmfAbstractAnalysisModule_AnalysisModule,
479 getName()));
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) {
491 return NonNullUtils.nullToEmptyString(NLS.bind(
492 Messages.TmfAbstractAnalysisModule_AnalysisForTrace,
493 getName(), trace.getName()));
494 }
495
496 /**
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.
500 *
501 * @param trace
502 * The trace to apply the analysis to
503 * @return Help text
504 */
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));
518 }
519 }
520 }
521 return builder.toString();
522 }
523
524 @Override
525 public String getHelpText() {
526 return getFullHelpText();
527 }
528
529 @Override
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$
534 }
535 return text;
536 }
537
538 @Override
539 public Iterable<@NonNull TmfAnalysisRequirement> getAnalysisRequirements() {
540 return Collections.EMPTY_SET;
541 }
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 }
558 }
This page took 0.058151 seconds and 5 git commands to generate.