TMF: Add automatic execution of module dependencies
[deliverable/tracecompass.git] / 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 java.util.ArrayList;
16 import java.util.Collections;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Set;
21 import java.util.concurrent.CountDownLatch;
22 import java.util.concurrent.TimeUnit;
23
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;
43
44 /**
45 * Base class that analysis modules main class may extend. It provides default
46 * behavior to some methods of the analysis module
47 *
48 * @author Geneviève Bastien
49 * @since 3.0
50 */
51 @NonNullByDefault
52 public abstract class TmfAbstractAnalysisModule extends TmfComponent implements IAnalysisModule {
53
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;
62
63 private final Object syncObj = new Object();
64
65 /* Latch tracking if the analysis is completed or not */
66 private CountDownLatch fFinishedLatch = new CountDownLatch(0);
67
68 private boolean fAnalysisCancelled = false;
69
70 @Override
71 public boolean isAutomatic() {
72 return fAutomatic;
73 }
74
75 @Override
76 public String getName() {
77 return super.getName();
78 }
79
80 @Override
81 public void setName(String name) {
82 super.setName(name);
83 }
84
85 @Override
86 public void setId(String id) {
87 fId = id;
88 }
89
90 @Override
91 public String getId() {
92 String id = fId;
93 if (id == null) {
94 id = new String(this.getClass().getCanonicalName());
95 fId = id;
96 }
97 return id;
98 }
99
100 @Override
101 public void setAutomatic(boolean auto) {
102 fAutomatic = auto;
103 }
104
105 @Override
106 public void setTrace(ITmfTrace trace) throws TmfAnalysisException {
107 if (fTrace != null) {
108 throw new TmfAnalysisException(NLS.bind(Messages.TmfAbstractAnalysisModule_TraceSetMoreThanOnce, getName()));
109 }
110
111 /* Check that analysis can be executed */
112 if (!canExecute(trace)) {
113 throw new TmfAnalysisException(NLS.bind(Messages.TmfAbstractAnalysisModule_AnalysisCannotExecute, getName()));
114 }
115
116 fTrace = trace;
117 /* Get the parameter providers for this trace */
118 fParameterProviders = TmfAnalysisManager.getParameterProviders(this, trace);
119 for (IAnalysisParameterProvider provider : fParameterProviders) {
120 provider.registerModule(this);
121 }
122 resetAnalysis();
123 fStarted = false;
124 }
125
126 /**
127 * Gets the trace
128 *
129 * @return The trace
130 */
131 protected @Nullable ITmfTrace getTrace() {
132 return fTrace;
133 }
134
135 @Override
136 public void addParameter(String name) {
137 fParameterNames.add(name);
138 }
139
140 @Override
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()));
144 }
145 Object oldValue = fParameters.get(name);
146 fParameters.put(name, value);
147 if ((value != null) && !(value.equals(oldValue))) {
148 parameterChanged(name);
149 }
150 }
151
152 @Override
153 public synchronized void notifyParameterChanged(String name) {
154 if (!fParameterNames.contains(name)) {
155 throw new RuntimeException(NLS.bind(Messages.TmfAbstractAnalysisModule_InvalidParameter, name, getName()));
156 }
157 Object oldValue = fParameters.get(name);
158 Object value = getParameter(name);
159 if ((value != null) && !(value.equals(oldValue))) {
160 parameterChanged(name);
161 }
162 }
163
164 /**
165 * Used to indicate that a parameter value has been changed
166 *
167 * @param name
168 * The name of the modified parameter
169 */
170 protected void parameterChanged(String name) {
171
172 }
173
174 @Override
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) {
182 break;
183 }
184 }
185 }
186 return paramValue;
187 }
188
189 @Override
190 public boolean canExecute(ITmfTrace trace) {
191 for (TmfAnalysisRequirement requirement : getAnalysisRequirements()) {
192 if (!requirement.isFulfilled(trace)) {
193 return false;
194 }
195 }
196 return true;
197 }
198
199 /**
200 * Set the countdown latch back to 1 so the analysis can be executed again
201 */
202 protected void resetAnalysis() {
203 fFinishedLatch.countDown();
204 fFinishedLatch = new CountDownLatch(1);
205 }
206
207 /**
208 * Actually executes the analysis itself
209 *
210 * @param monitor
211 * Progress monitor
212 * @return Whether the analysis was completed successfully or not
213 * @throws TmfAnalysisException
214 * Method may throw an analysis exception
215 */
216 protected abstract boolean executeAnalysis(final IProgressMonitor monitor) throws TmfAnalysisException;
217
218 /**
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.
222 */
223 protected abstract void canceling();
224
225 /**
226 * To be called when the analysis is completed, whether normally or because
227 * it was cancelled or for any other reason.
228 *
229 * It has to be called inside a synchronized block
230 */
231 private void setAnalysisCompleted() {
232 fStarted = false;
233 fJob = null;
234 fFinishedLatch.countDown();
235 }
236
237 /**
238 * Cancels the analysis if it is executing
239 */
240 @Override
241 public final void cancel() {
242 synchronized (syncObj) {
243 if (fJob != null) {
244 if (fJob.cancel()) {
245 fAnalysisCancelled = true;
246 setAnalysisCompleted();
247 }
248 }
249 fStarted = false;
250 }
251 }
252
253 @Override
254 public void dispose() {
255 super.dispose();
256 cancel();
257 }
258
259 /**
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.
264 *
265 * @return An iterable list of analysis this analyzes depends on.
266 */
267 protected Iterable<IAnalysisModule> getDependentAnalyses() {
268 @SuppressWarnings("null")
269 @NonNull Set<IAnalysisModule> emptySet = Collections.EMPTY_SET;
270 return emptySet;
271 }
272
273 private void execute(final ITmfTrace trace) {
274 /*
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
278 */
279
280 /* Do not execute if analysis has already run */
281 if (fFinishedLatch.getCount() == 0) {
282 return;
283 }
284
285 /* Do not execute if analysis already running */
286 synchronized (syncObj) {
287 if (fStarted) {
288 return;
289 }
290 fStarted = true;
291 }
292
293 /* Execute dependent analyses before creating the job for this one */
294 final Iterable<IAnalysisModule> dependentAnalyses = getDependentAnalyses();
295 for (IAnalysisModule module : dependentAnalyses) {
296 module.schedule();
297 }
298
299 /*
300 * Actual analysis will be run on a separate thread
301 */
302 @SuppressWarnings("null")
303 @NonNull String jobName = NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, getName());
304 fJob = new Job(jobName) {
305 @Override
306 protected @Nullable IStatus run(final @Nullable IProgressMonitor monitor) {
307 IProgressMonitor mon = monitor;
308 if (mon == null) {
309 mon = new NullProgressMonitor();
310 }
311 try {
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);
317 }
318 } catch (TmfAnalysisException e) {
319 Activator.logError("Error executing analysis with trace " + trace.getName(), e); //$NON-NLS-1$
320 } finally {
321 synchronized (syncObj) {
322 mon.done();
323 setAnalysisCompleted();
324 }
325 TmfTraceManager.refreshSupplementaryFiles(trace);
326 }
327 if (!fAnalysisCancelled) {
328 return Status.OK_STATUS;
329 }
330 // Reset analysis so that it can be executed again.
331 resetAnalysis();
332 return Status.CANCEL_STATUS;
333 }
334
335 @Override
336 protected void canceling() {
337 TmfAbstractAnalysisModule.this.canceling();
338 }
339
340 };
341 fJob.schedule();
342 }
343
344 @Override
345 public IStatus schedule() {
346 synchronized (syncObj) {
347 final ITmfTrace trace = getTrace();
348 if (trace == null) {
349 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, String.format("No trace specified for analysis %s", getName())); //$NON-NLS-1$
350 }
351 execute(trace);
352 }
353
354 @SuppressWarnings("null")
355 @NonNull IStatus status = Status.OK_STATUS;
356 return status;
357 }
358
359 @Override
360 public Iterable<IAnalysisOutput> getOutputs() {
361 return fOutputs;
362 }
363
364 @Override
365 public void registerOutput(IAnalysisOutput output) {
366 if (!fOutputs.contains(output)) {
367 fOutputs.add(output);
368 }
369 }
370
371 @Override
372 public boolean waitForCompletion() {
373 try {
374 fFinishedLatch.await();
375 } catch (InterruptedException e) {
376 Activator.logError("Error while waiting for module completion", e); //$NON-NLS-1$
377 }
378 return !fAnalysisCancelled;
379 }
380
381 @Override
382 public boolean waitForCompletion(IProgressMonitor monitor) {
383 try {
384 while (!fFinishedLatch.await(500, TimeUnit.MILLISECONDS)) {
385 if (fAnalysisCancelled || monitor.isCanceled()) {
386 fAnalysisCancelled = true;
387 return false;
388 }
389 }
390 } catch (InterruptedException e) {
391 Activator.logError("Error while waiting for module completion", e); //$NON-NLS-1$
392 }
393 return !fAnalysisCancelled;
394 }
395
396 /**
397 * Signal handler for trace closing
398 *
399 * @param signal
400 * Trace closed signal
401 */
402 @TmfSignalHandler
403 public void traceClosed(TmfTraceClosedSignal signal) {
404 /* Is the closing trace the one that was requested? */
405 synchronized (syncObj) {
406 if (signal.getTrace() == fTrace) {
407 cancel();
408 fTrace = null;
409 }
410 }
411 }
412
413 /**
414 * Signal handler for when the trace becomes active
415 *
416 * @param signal
417 * Trace selected signal
418 * @since 3.1
419 */
420 @TmfSignalHandler
421 public void traceSelected(TmfTraceSelectedSignal signal) {
422 /*
423 * Since some parameter providers may handle many traces, we need to
424 * register the current trace to it
425 */
426 if (signal.getTrace() == fTrace) {
427 for (IAnalysisParameterProvider provider : fParameterProviders) {
428 provider.registerModule(this);
429 }
430 }
431 }
432
433 /**
434 * Returns a full help text to display
435 *
436 * @return Full help text for the module
437 */
438 protected String getFullHelpText() {
439 @SuppressWarnings("null")
440 @NonNull String text = NLS.bind(Messages.TmfAbstractAnalysisModule_AnalysisModule, getName());
441 return text;
442 }
443
444 /**
445 * Gets a short help text, to display as header to other help text
446 *
447 * @param trace
448 * The trace to show help for
449 *
450 * @return Short help text describing the module
451 */
452 protected String getShortHelpText(ITmfTrace trace) {
453 @SuppressWarnings("null")
454 @NonNull String text = NLS.bind(Messages.TmfAbstractAnalysisModule_AnalysisForTrace, getName(), trace.getName());
455 return text;
456 }
457
458 /**
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.
462 *
463 * @param trace
464 * The trace to apply the analysis to
465 * @return Help text
466 */
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));
480 }
481 }
482 }
483 @SuppressWarnings("null")
484 @NonNull String helpText = builder.toString();
485 return helpText;
486 }
487
488 @Override
489 public String getHelpText() {
490 return getFullHelpText();
491 }
492
493 @Override
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$
498 }
499 return text;
500 }
501
502 @Override
503 public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() {
504 @SuppressWarnings("null")
505 @NonNull Iterable<TmfAnalysisRequirement> emptySet = Collections.EMPTY_SET;
506 return emptySet;
507 }
508 }
This page took 0.058861 seconds and 6 git commands to generate.