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