tmf.core: Make getParamater synchronized
[deliverable/tracecompass.git] / tmf / org.eclipse.tracecompass.tmf.core / src / org / eclipse / tracecompass / tmf / core / analysis / TmfAbstractAnalysisModule.java
CommitLineData
c068a752 1/*******************************************************************************
60ae41e1 2 * Copyright (c) 2013, 2014 École Polytechnique de Montréal
c068a752
GB
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
2bdf0193 13package org.eclipse.tracecompass.tmf.core.analysis;
c068a752 14
5db5a3a4
AM
15import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;
16
c068a752 17import java.util.ArrayList;
63c43609 18import java.util.Collections;
c068a752 19import java.util.HashMap;
55d8eb5e 20import java.util.HashSet;
c068a752
GB
21import java.util.List;
22import java.util.Map;
54eae41f 23import java.util.Set;
c068a752
GB
24import java.util.concurrent.CountDownLatch;
25import java.util.concurrent.TimeUnit;
26
27import org.eclipse.core.runtime.IProgressMonitor;
28import org.eclipse.core.runtime.IStatus;
ba27dd38 29import org.eclipse.core.runtime.NullProgressMonitor;
c068a752
GB
30import org.eclipse.core.runtime.Status;
31import org.eclipse.core.runtime.jobs.Job;
a01f6266 32import org.eclipse.jdt.annotation.NonNull;
ba27dd38
GB
33import org.eclipse.jdt.annotation.NonNullByDefault;
34import org.eclipse.jdt.annotation.Nullable;
c068a752 35import org.eclipse.osgi.util.NLS;
5db5a3a4 36import org.eclipse.tracecompass.common.core.NonNullUtils;
2bdf0193 37import org.eclipse.tracecompass.internal.tmf.core.Activator;
6dc36f66 38import org.eclipse.tracecompass.internal.tmf.core.TmfCoreTracer;
58080002 39import org.eclipse.tracecompass.tmf.core.analysis.requirements.TmfAbstractAnalysisRequirement;
2bdf0193
AM
40import org.eclipse.tracecompass.tmf.core.component.TmfComponent;
41import org.eclipse.tracecompass.tmf.core.exceptions.TmfAnalysisException;
a01f6266 42import org.eclipse.tracecompass.tmf.core.project.model.ITmfPropertiesProvider;
2bdf0193
AM
43import org.eclipse.tracecompass.tmf.core.signal.TmfSignalHandler;
44import org.eclipse.tracecompass.tmf.core.signal.TmfStartAnalysisSignal;
45import org.eclipse.tracecompass.tmf.core.signal.TmfTraceClosedSignal;
46import org.eclipse.tracecompass.tmf.core.signal.TmfTraceSelectedSignal;
47import org.eclipse.tracecompass.tmf.core.trace.ITmfTrace;
48import org.eclipse.tracecompass.tmf.core.trace.TmfTraceManager;
c068a752
GB
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
c068a752 55 */
ba27dd38 56@NonNullByDefault
a01f6266
GB
57public abstract class TmfAbstractAnalysisModule extends TmfComponent
58 implements IAnalysisModule, ITmfPropertiesProvider {
c068a752 59
ba27dd38 60 private @Nullable String fId;
c068a752 61 private boolean fAutomatic = false, fStarted = false;
ba27dd38 62 private volatile @Nullable ITmfTrace fTrace;
4c4e2816 63 private final Map<String, @Nullable Object> fParameters = new HashMap<>();
a4524c1b
AM
64 private final List<String> fParameterNames = new ArrayList<>();
65 private final List<IAnalysisOutput> fOutputs = new ArrayList<>();
55d8eb5e 66 private Set<IAnalysisParameterProvider> fParameterProviders = new HashSet<>();
ba27dd38 67 private @Nullable Job fJob = null;
0021a734 68 private int fDependencyLevel = 0;
c068a752
GB
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() {
ba27dd38 84 return super.getName();
c068a752
GB
85 }
86
87 @Override
88 public void setName(String name) {
ba27dd38 89 super.setName(name);
c068a752
GB
90 }
91
92 @Override
93 public void setId(String id) {
94 fId = id;
95 }
96
97 @Override
98 public String getId() {
dc58a1fb
GB
99 String id = fId;
100 if (id == null) {
8356c9fe
AM
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 */
0e4f957e 107 id = this.getClass().getName();
8356c9fe 108 }
11835c0f 109 fId = id;
dc58a1fb
GB
110 }
111 return id;
c068a752
GB
112 }
113
114 @Override
115 public void setAutomatic(boolean auto) {
116 fAutomatic = auto;
117 }
118
f479550c
GB
119 /**
120 * @since 1.0
121 */
c068a752 122 @Override
f479550c 123 public boolean setTrace(ITmfTrace trace) throws TmfAnalysisException {
c068a752
GB
124 if (fTrace != null) {
125 throw new TmfAnalysisException(NLS.bind(Messages.TmfAbstractAnalysisModule_TraceSetMoreThanOnce, getName()));
126 }
127
6dc36f66
GB
128 TmfCoreTracer.traceAnalysis(getId(), trace, "setting trace for analysis"); //$NON-NLS-1$
129
c068a752 130 /* Check that analysis can be executed */
7e452c97 131 fTrace = trace;
c068a752 132 if (!canExecute(trace)) {
7e452c97 133 fTrace = null;
f479550c 134 return false;
c068a752 135 }
26683871 136
c068a752 137 /* Get the parameter providers for this trace */
55d8eb5e 138 fParameterProviders = TmfAnalysisManager.getParameterProvidersForModule(this, trace);
c068a752 139 for (IAnalysisParameterProvider provider : fParameterProviders) {
6dc36f66 140 TmfCoreTracer.traceAnalysis(getId(), trace, "registered to parameter provider " + provider.getName()); //$NON-NLS-1$
c068a752
GB
141 provider.registerModule(this);
142 }
143 resetAnalysis();
144 fStarted = false;
f479550c 145 return true;
c068a752
GB
146 }
147
148 /**
149 * Gets the trace
150 *
151 * @return The trace
152 */
ba27dd38 153 protected @Nullable ITmfTrace getTrace() {
c068a752
GB
154 return fTrace;
155 }
156
157 @Override
158 public void addParameter(String name) {
159 fParameterNames.add(name);
160 }
161
162 @Override
ba27dd38 163 public synchronized void setParameter(String name, @Nullable Object value) {
c068a752
GB
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
3127c6b8 197 public @Nullable synchronized Object getParameter(String name) {
c068a752
GB
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
ba27dd38 212 public boolean canExecute(ITmfTrace trace) {
58080002 213 for (TmfAbstractAnalysisRequirement requirement : getAnalysisRequirements()) {
e44d6313 214 if (!requirement.test(trace)) {
26683871
GB
215 return false;
216 }
217 }
c068a752
GB
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() {
6dc36f66 225 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "reset: ready for execution"); //$NON-NLS-1$
1a01cbfd
MK
226 synchronized (syncObj) {
227 fFinishedLatch.countDown();
228 fFinishedLatch = new CountDownLatch(1);
229 }
c068a752
GB
230 }
231
232 /**
233 * Actually executes the analysis itself
234 *
235 * @param monitor
236 * Progress monitor
237 * @return Whether the analysis was completed successfully or not
238 * @throws TmfAnalysisException
239 * Method may throw an analysis exception
240 */
241 protected abstract boolean executeAnalysis(final IProgressMonitor monitor) throws TmfAnalysisException;
242
243 /**
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.
247 */
248 protected abstract void canceling();
249
250 /**
251 * To be called when the analysis is completed, whether normally or because
252 * it was cancelled or for any other reason.
253 *
254 * It has to be called inside a synchronized block
255 */
256 private void setAnalysisCompleted() {
6dc36f66
GB
257 synchronized (syncObj) {
258 fStarted = false;
259 fJob = null;
260 fFinishedLatch.countDown();
261 }
c068a752
GB
262 }
263
264 /**
265 * Cancels the analysis if it is executing
266 */
267 @Override
268 public final void cancel() {
269 synchronized (syncObj) {
6dc36f66 270 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "cancelled by application"); //$NON-NLS-1$
1a01cbfd
MK
271 Job job = fJob;
272 if (job != null) {
273 job.cancel();
7256553f
MK
274 fAnalysisCancelled = true;
275 setAnalysisCompleted();
c068a752
GB
276 }
277 fStarted = false;
278 }
279 }
280
130e6f4e
MAL
281 @Override
282 public void dispose() {
283 super.dispose();
284 cancel();
285 }
286
0b4160dc
GB
287 /**
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.
292 *
293 * @return An iterable list of analysis this analyzes depends on.
294 */
295 protected Iterable<IAnalysisModule> getDependentAnalyses() {
aa353506 296 return Collections.EMPTY_LIST;
0b4160dc 297 }
c068a752 298
0021a734
GB
299 /**
300 * @since 2.0
301 */
302 @Override
303 public int getDependencyLevel() {
304 return fDependencyLevel;
305 }
306
0b4160dc 307 private void execute(final ITmfTrace trace) {
c068a752
GB
308 /*
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
312 */
313
314 /* Do not execute if analysis has already run */
315 if (fFinishedLatch.getCount() == 0) {
6dc36f66 316 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "already executed"); //$NON-NLS-1$
c068a752
GB
317 return;
318 }
319
320 /* Do not execute if analysis already running */
321 synchronized (syncObj) {
322 if (fStarted) {
6dc36f66 323 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "already started, not starting again"); //$NON-NLS-1$
c068a752
GB
324 return;
325 }
326 fStarted = true;
327 }
328
0b4160dc
GB
329 /* Execute dependent analyses before creating the job for this one */
330 final Iterable<IAnalysisModule> dependentAnalyses = getDependentAnalyses();
0021a734 331 int depLevel = 0;
0b4160dc
GB
332 for (IAnalysisModule module : dependentAnalyses) {
333 module.schedule();
0021a734
GB
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;
0b4160dc 337 }
0021a734 338 fDependencyLevel = depLevel;
0b4160dc 339
c068a752
GB
340 /*
341 * Actual analysis will be run on a separate thread
342 */
5db5a3a4 343 String jobName = checkNotNull(NLS.bind(Messages.TmfAbstractAnalysisModule_RunningAnalysis, getName()));
ba27dd38 344 fJob = new Job(jobName) {
c068a752 345 @Override
ba27dd38
GB
346 protected @Nullable IStatus run(final @Nullable IProgressMonitor monitor) {
347 IProgressMonitor mon = monitor;
348 if (mon == null) {
349 mon = new NullProgressMonitor();
350 }
c068a752 351 try {
ba27dd38 352 mon.beginTask("", IProgressMonitor.UNKNOWN); //$NON-NLS-1$
c068a752 353 broadcast(new TmfStartAnalysisSignal(TmfAbstractAnalysisModule.this, TmfAbstractAnalysisModule.this));
6dc36f66 354 TmfCoreTracer.traceAnalysis(TmfAbstractAnalysisModule.this.getId(), TmfAbstractAnalysisModule.this.getTrace(), "started"); //$NON-NLS-1$
ba27dd38 355 fAnalysisCancelled = !executeAnalysis(mon);
0b4160dc
GB
356 for (IAnalysisModule module : dependentAnalyses) {
357 module.waitForCompletion(mon);
358 }
6dc36f66 359 TmfCoreTracer.traceAnalysis(TmfAbstractAnalysisModule.this.getId(), TmfAbstractAnalysisModule.this.getTrace(), "finished"); //$NON-NLS-1$
c068a752 360 } catch (TmfAnalysisException e) {
e1c415b3 361 Activator.logError("Error executing analysis with trace " + trace.getName(), e); //$NON-NLS-1$
c068a752
GB
362 } finally {
363 synchronized (syncObj) {
ba27dd38 364 mon.done();
c068a752
GB
365 setAnalysisCompleted();
366 }
88567ed2 367 TmfTraceManager.refreshSupplementaryFiles(trace);
c068a752
GB
368 }
369 if (!fAnalysisCancelled) {
370 return Status.OK_STATUS;
371 }
baa96b1d
BH
372 // Reset analysis so that it can be executed again.
373 resetAnalysis();
c068a752
GB
374 return Status.CANCEL_STATUS;
375 }
376
377 @Override
378 protected void canceling() {
6dc36f66 379 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "job cancelled"); //$NON-NLS-1$
c068a752
GB
380 TmfAbstractAnalysisModule.this.canceling();
381 }
382
383 };
384 fJob.schedule();
385 }
386
387 @Override
388 public IStatus schedule() {
e1c415b3
BH
389 synchronized (syncObj) {
390 final ITmfTrace trace = getTrace();
391 if (trace == null) {
392 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, String.format("No trace specified for analysis %s", getName())); //$NON-NLS-1$
393 }
6dc36f66 394 TmfCoreTracer.traceAnalysis(getId(), getTrace(), "scheduled"); //$NON-NLS-1$
e1c415b3 395 execute(trace);
c068a752 396 }
c068a752 397
0e4f957e 398 return Status.OK_STATUS;
c068a752
GB
399 }
400
401 @Override
d9810555
AM
402 public Iterable<IAnalysisOutput> getOutputs() {
403 return fOutputs;
c068a752
GB
404 }
405
406 @Override
407 public void registerOutput(IAnalysisOutput output) {
408 if (!fOutputs.contains(output)) {
409 fOutputs.add(output);
410 }
411 }
412
7d6122fc
AM
413 @Override
414 public boolean waitForCompletion() {
1a01cbfd
MK
415 CountDownLatch finishedLatch;
416 boolean started;
417 synchronized (syncObj) {
418 finishedLatch = fFinishedLatch;
419 started = fStarted;
420 }
7d6122fc 421 try {
1a01cbfd
MK
422 if (started) {
423 finishedLatch.await();
424 }
7d6122fc
AM
425 } catch (InterruptedException e) {
426 Activator.logError("Error while waiting for module completion", e); //$NON-NLS-1$
427 }
428 return !fAnalysisCancelled;
429 }
430
c068a752
GB
431 @Override
432 public boolean waitForCompletion(IProgressMonitor monitor) {
433 try {
0d3a54a3
AM
434 while (!fFinishedLatch.await(500, TimeUnit.MILLISECONDS)) {
435 if (fAnalysisCancelled || monitor.isCanceled()) {
c068a752
GB
436 fAnalysisCancelled = true;
437 return false;
438 }
439 }
440 } catch (InterruptedException e) {
441 Activator.logError("Error while waiting for module completion", e); //$NON-NLS-1$
442 }
443 return !fAnalysisCancelled;
444 }
445
446 /**
447 * Signal handler for trace closing
448 *
449 * @param signal
450 * Trace closed signal
451 */
452 @TmfSignalHandler
453 public void traceClosed(TmfTraceClosedSignal signal) {
454 /* Is the closing trace the one that was requested? */
e1c415b3
BH
455 synchronized (syncObj) {
456 if (signal.getTrace() == fTrace) {
457 cancel();
458 fTrace = null;
459 }
c068a752
GB
460 }
461 }
462
715154b1
GB
463 /**
464 * Signal handler for when the trace becomes active
465 *
466 * @param signal
467 * Trace selected signal
715154b1
GB
468 */
469 @TmfSignalHandler
470 public void traceSelected(TmfTraceSelectedSignal signal) {
471 /*
472 * Since some parameter providers may handle many traces, we need to
473 * register the current trace to it
474 */
475 if (signal.getTrace() == fTrace) {
476 for (IAnalysisParameterProvider provider : fParameterProviders) {
477 provider.registerModule(this);
478 }
479 }
480 }
481
c068a752
GB
482 /**
483 * Returns a full help text to display
484 *
485 * @return Full help text for the module
486 */
487 protected String getFullHelpText() {
5db5a3a4
AM
488 return NonNullUtils.nullToEmptyString(NLS.bind(
489 Messages.TmfAbstractAnalysisModule_AnalysisModule,
490 getName()));
c068a752
GB
491 }
492
493 /**
494 * Gets a short help text, to display as header to other help text
495 *
496 * @param trace
497 * The trace to show help for
498 *
499 * @return Short help text describing the module
500 */
501 protected String getShortHelpText(ITmfTrace trace) {
5db5a3a4
AM
502 return NonNullUtils.nullToEmptyString(NLS.bind(
503 Messages.TmfAbstractAnalysisModule_AnalysisForTrace,
504 getName(), trace.getName()));
c068a752
GB
505 }
506
507 /**
508 * Gets the help text specific for a trace who does not have required
54eae41f
GB
509 * characteristics for module to execute. The default implementation uses
510 * the analysis requirements.
c068a752
GB
511 *
512 * @param trace
513 * The trace to apply the analysis to
514 * @return Help text
515 */
ba27dd38 516 protected String getTraceCannotExecuteHelpText(ITmfTrace trace) {
54eae41f
GB
517 StringBuilder builder = new StringBuilder();
518 builder.append(NLS.bind(Messages.TmfAbstractAnalysisModule_AnalysisCannotExecute, getName()));
58080002 519 for (TmfAbstractAnalysisRequirement requirement : getAnalysisRequirements()) {
e44d6313 520 if (!requirement.test(trace)) {
54eae41f 521 builder.append("\n\n"); //$NON-NLS-1$
66ee355d 522 builder.append(NLS.bind(Messages.TmfAnalysis_RequirementNotFulfilled, requirement.getPriorityLevel()));
54eae41f 523 builder.append("\n"); //$NON-NLS-1$
66ee355d 524 builder.append(NLS.bind(Messages.TmfAnalysis_RequirementMandatoryValues, requirement.getValues()));
54eae41f
GB
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));
529 }
530 }
531 }
0e4f957e 532 return builder.toString();
c068a752
GB
533 }
534
535 @Override
536 public String getHelpText() {
537 return getFullHelpText();
538 }
539
540 @Override
541 public String getHelpText(ITmfTrace trace) {
c068a752
GB
542 String text = getShortHelpText(trace);
543 if (!canExecute(trace)) {
54eae41f 544 text = text + "\n\n" + getTraceCannotExecuteHelpText(trace); //$NON-NLS-1$
c068a752
GB
545 }
546 return text;
547 }
548
63c43609 549 @Override
58080002 550 public Iterable<@NonNull TmfAbstractAnalysisRequirement> getAnalysisRequirements() {
aa353506 551 return Collections.EMPTY_SET;
63c43609 552 }
a01f6266
GB
553
554 // ------------------------------------------------------------------------
555 // ITmfPropertiesProvider
556 // ------------------------------------------------------------------------
557
558 /**
559 * @since 2.0
560 */
561 @Override
562 public Map<@NonNull String, @NonNull String> getProperties() {
563 Map<@NonNull String, @NonNull String> properties = new HashMap<>();
564
565 properties.put(NonNullUtils.checkNotNull(Messages.TmfAbstractAnalysisModule_LabelId), getId());
566
567 return properties;
568 }
c068a752 569}
This page took 0.113242 seconds and 5 git commands to generate.