1 /*******************************************************************************
2 * Copyright (c) 2015, 2016 EfficiOS Inc., Alexandre Montplaisir
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 *******************************************************************************/
10 package org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.module
;
12 import static org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
.checkNotNull
;
13 import static org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
.checkNotNullContents
;
14 import static org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
.nullToEmptyString
;
16 import java
.io
.BufferedReader
;
18 import java
.io
.IOException
;
19 import java
.io
.InputStreamReader
;
20 import java
.nio
.file
.Files
;
21 import java
.nio
.file
.Paths
;
22 import java
.util
.ArrayList
;
23 import java
.util
.Arrays
;
24 import java
.util
.Collection
;
25 import java
.util
.Collections
;
26 import java
.util
.function
.Predicate
;
27 import java
.util
.List
;
29 import java
.util
.regex
.Pattern
;
30 import java
.util
.stream
.Collectors
;
31 import java
.util
.stream
.Stream
;
33 import org
.eclipse
.core
.runtime
.CoreException
;
34 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
35 import org
.eclipse
.core
.runtime
.IStatus
;
36 import org
.eclipse
.core
.runtime
.MultiStatus
;
37 import org
.eclipse
.core
.runtime
.Status
;
38 import org
.eclipse
.jdt
.annotation
.NonNull
;
39 import org
.eclipse
.jdt
.annotation
.Nullable
;
40 import org
.eclipse
.tracecompass
.internal
.analysis
.lami
.core
.Activator
;
41 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.LamiStrings
;
42 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiGenericAspect
;
43 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiIRQNameAspect
;
44 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiIRQNumberAspect
;
45 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiIRQTypeAspect
;
46 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiMixedAspect
;
47 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiProcessNameAspect
;
48 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiProcessPIDAspect
;
49 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiProcessTIDAspect
;
50 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiDurationAspect
;
51 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiEmptyAspect
;
52 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiTableEntryAspect
;
53 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiTimeRangeBeginAspect
;
54 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiTimeRangeDurationAspect
;
55 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiTimeRangeEndAspect
;
56 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.aspect
.LamiTimestampAspect
;
57 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.types
.LamiData
;
58 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.types
.LamiData
.DataType
;
59 import org
.eclipse
.tracecompass
.internal
.provisional
.analysis
.lami
.core
.types
.LamiTimeRange
;
60 import org
.eclipse
.tracecompass
.tmf
.core
.analysis
.ondemand
.IOnDemandAnalysis
;
61 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimeRange
;
62 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
63 import org
.json
.JSONArray
;
64 import org
.json
.JSONException
;
65 import org
.json
.JSONObject
;
67 import com
.google
.common
.annotations
.VisibleForTesting
;
68 import com
.google
.common
.collect
.ImmutableList
;
69 import com
.google
.common
.collect
.ImmutableMap
;
70 import com
.google
.common
.collect
.ImmutableMultimap
;
71 import com
.google
.common
.collect
.Multimap
;
74 * Base class for analysis modules that call external scripts implementing the
77 * @author Alexandre Montplaisir
79 public class LamiAnalysis
implements IOnDemandAnalysis
{
81 /** Maximum major version of the LAMI protocol we support */
82 private static final int MAX_SUPPORTED_MAJOR_VERSION
= 1;
84 private static final String DOUBLE_QUOTES
= "\""; //$NON-NLS-1$
86 /* Flags passed to the analysis scripts */
87 private static final String METADATA_FLAG
= "--metadata"; //$NON-NLS-1$
88 private static final String PROGRESS_FLAG
= "--output-progress"; //$NON-NLS-1$
89 private static final String BEGIN_FLAG
= "--begin"; //$NON-NLS-1$
90 private static final String END_FLAG
= "--end"; //$NON-NLS-1$
92 /** Log message for commands being run */
93 private static final String RUNNING_MESSAGE
= "Running command:"; //$NON-NLS-1$
95 private final List
<String
> fScriptCommand
;
98 * The LAMI analysis is considered initialized after we have read the
99 * script's --metadata once. This will assign the fields below.
101 private boolean fInitialized
= false;
103 private boolean fIsAvailable
;
104 private final String fName
;
105 private final boolean fIsUserDefined
;
106 private final Predicate
<ITmfTrace
> fAppliesTo
;
108 /* Data defined by the analysis's metadata */
109 private @Nullable String fAnalysisTitle
;
110 private @Nullable Map
<String
, LamiTableClass
> fTableClasses
;
111 private boolean fUseProgressOutput
;
114 * Constructor. To be called by implementing classes.
117 * Name of this analysis
118 * @param isUserDefined
119 * {@code true} if this is a user-defined analysis
121 * Predicate to use to check whether or not this analysis applies
124 * Analysis arguments, including the executable name (first
127 public LamiAnalysis(String name
, boolean isUserDefined
, Predicate
<ITmfTrace
> appliesTo
,
129 fScriptCommand
= ImmutableList
.copyOf(args
);
131 fIsUserDefined
= isUserDefined
;
132 fAppliesTo
= appliesTo
;
136 * Map of pre-defined charts, for every table class names.
138 * If a table class is not in this map then it means that table has no
141 * @return The chart models, per table class names
143 protected Multimap
<String
, LamiChartModel
> getPredefinedCharts() {
144 return ImmutableMultimap
.of();
148 public final boolean appliesTo(ITmfTrace trace
) {
149 return fAppliesTo
.test(trace
);
153 public boolean canExecute(ITmfTrace trace
) {
159 * Perform initialization of the LAMI script. This means verifying that it
160 * is actually present on disk, and that it returns correct --metadata.
163 protected synchronized void initialize() {
168 /* Do the analysis's initialization */
170 /* Check if the script's expected executable is on the PATH */
171 String executable
= fScriptCommand
.get(0);
172 boolean exists
= Stream
.of(System
.getenv("PATH").split(checkNotNull(Pattern
.quote(File
.pathSeparator
)))) //$NON-NLS-1$
174 .anyMatch(path
-> Files
.exists(path
.resolve(executable
)));
176 /* Script is not found */
177 fIsAvailable
= false;
182 fIsAvailable
= checkMetadata();
187 * Verify that this script returns valid metadata.
189 * This will populate all remaining non-final fields of this class.
191 * @return If the metadata is valid or not
194 protected boolean checkMetadata() {
196 * The initialize() phase of the analysis will be used to check the
197 * script's metadata. Actual runs of the script will use the execute()
200 List
<String
> command
= ImmutableList
.<@NonNull String
> builder()
201 .addAll(fScriptCommand
).add(METADATA_FLAG
).build();
203 Activator
.instance().logInfo(RUNNING_MESSAGE
+ ' ' + command
.toString());
205 String output
= getOutputFromCommand(command
);
206 if (output
== null || output
.isEmpty()) {
212 * Metadata should look this this:
215 * "version": [1, 5, 2, "dev"],
216 * "title": "I/O latency statistics",
218 * "Julien Desfossez",
221 * "description": "Provides statistics about the latency involved in various I/O operations.",
222 * "url": "https://github.com/lttng/lttng-analyses",
230 * "syscall-latency": {
231 * "title": "System calls latency statistics",
232 * "column-descriptions": [
233 * {"title": "System call", "type": "syscall"},
234 * {"title": "Count", "type": "int", "unit": "operations"},
235 * {"title": "Minimum duration", "type": "duration"},
236 * {"title": "Average duration", "type": "duration"},
237 * {"title": "Maximum duration", "type": "duration"},
238 * {"title": "Standard deviation", "type": "duration"}
242 * "title": "Disk latency statistics",
243 * "column-descriptions": [
244 * {"title": "Disk name", "type": "disk"},
245 * {"title": "Count", "type": "int", "unit": "operations"},
246 * {"title": "Minimum duration", "type": "duration"},
247 * {"title": "Average duration", "type": "duration"},
248 * {"title": "Maximum duration", "type": "duration"},
249 * {"title": "Standard deviation", "type": "duration"}
258 JSONObject obj
= new JSONObject(output
);
259 fAnalysisTitle
= obj
.getString(LamiStrings
.TITLE
);
261 /* Very early scripts may not contain the "mi-version" */
262 JSONObject miVersion
= obj
.optJSONObject(LamiStrings
.MI_VERSION
);
263 if (miVersion
== null) {
264 /* Before version 0.1 */
265 fUseProgressOutput
= false;
267 int majorVersion
= miVersion
.getInt(LamiStrings
.MAJOR
);
268 if (majorVersion
<= MAX_SUPPORTED_MAJOR_VERSION
) {
269 fUseProgressOutput
= true;
271 /* Unknown version, we do not support it */
276 JSONObject tableClasses
= obj
.getJSONObject(LamiStrings
.TABLE_CLASSES
);
277 @NonNull String
[] tableClassNames
= checkNotNullContents(JSONObject
.getNames(tableClasses
));
279 ImmutableMap
.Builder
<String
, LamiTableClass
> tablesBuilder
= ImmutableMap
.builder();
280 for (String tableClassName
: tableClassNames
) {
281 JSONObject tableClass
= tableClasses
.getJSONObject(tableClassName
);
283 final String tableTitle
= checkNotNull(tableClass
.getString(LamiStrings
.TITLE
));
284 @NonNull JSONArray columnDescriptions
= checkNotNull(tableClass
.getJSONArray(LamiStrings
.COLUMN_DESCRIPTIONS
));
286 List
<LamiTableEntryAspect
> aspects
= getAspectsFromColumnDescriptions(columnDescriptions
);
287 Collection
<LamiChartModel
> chartModels
= getPredefinedCharts().get(tableClassName
);
289 tablesBuilder
.put(tableClassName
, new LamiTableClass(tableClassName
, tableTitle
, aspects
, chartModels
));
293 fTableClasses
= tablesBuilder
.build();
294 } catch (IllegalArgumentException e
) {
296 * This is thrown if there are duplicate keys in the map
299 throw new JSONException("Duplicate table class entry in " + fAnalysisTitle
); //$NON-NLS-1$
302 } catch (JSONException e
) {
303 /* Error in the parsing of the JSON, script is broken? */
304 Activator
.instance().logError(e
.getMessage());
310 private static List
<LamiTableEntryAspect
> getAspectsFromColumnDescriptions(JSONArray columnDescriptions
) throws JSONException
{
311 ImmutableList
.Builder
<LamiTableEntryAspect
> aspectsBuilder
= new ImmutableList
.Builder
<>();
312 for (int j
= 0; j
< columnDescriptions
.length(); j
++) {
313 JSONObject column
= columnDescriptions
.getJSONObject(j
);
314 DataType columnDataType
;
315 String columnClass
= column
.optString(LamiStrings
.CLASS
, null);
317 if (columnClass
== null) {
318 columnDataType
= DataType
.MIXED
;
320 columnDataType
= getDataTypeFromString(columnClass
);
323 String columnTitle
= column
.optString(LamiStrings
.TITLE
, null);
325 if (columnTitle
== null) {
326 columnTitle
= String
.format("%s #%d", columnDataType
.getTitle(), j
+ 1); //$NON-NLS-1$
329 final int colIndex
= j
;
330 switch (columnDataType
) {
333 * We will add 3 aspects, to represent the start, end and
334 * duration of this time range.
336 aspectsBuilder
.add(new LamiTimeRangeBeginAspect(columnTitle
, colIndex
));
337 aspectsBuilder
.add(new LamiTimeRangeEndAspect(columnTitle
, colIndex
));
338 aspectsBuilder
.add(new LamiTimeRangeDurationAspect(columnTitle
, colIndex
));
342 aspectsBuilder
.add(new LamiTimestampAspect(columnTitle
, colIndex
));
346 aspectsBuilder
.add(new LamiProcessNameAspect(columnTitle
, colIndex
));
347 aspectsBuilder
.add(new LamiProcessPIDAspect(columnTitle
, colIndex
));
348 aspectsBuilder
.add(new LamiProcessTIDAspect(columnTitle
, colIndex
));
352 aspectsBuilder
.add(new LamiIRQTypeAspect(columnTitle
, colIndex
));
353 aspectsBuilder
.add(new LamiIRQNameAspect(columnTitle
, colIndex
));
354 aspectsBuilder
.add(new LamiIRQNumberAspect(columnTitle
, colIndex
));
358 aspectsBuilder
.add(new LamiDurationAspect(columnTitle
, colIndex
));
362 aspectsBuilder
.add(new LamiMixedAspect(columnTitle
, colIndex
));
367 String units
= column
.optString(LamiStrings
.UNIT
, null);
370 units
= columnDataType
.getUnits();
373 /* We will add only one aspect representing the element */
374 LamiTableEntryAspect aspect
= new LamiGenericAspect(columnTitle
,
375 units
, colIndex
, columnDataType
.isContinuous(), false);
376 aspectsBuilder
.add(aspect
);
381 * SWT quirk : we need an empty column at the end or else the last data
382 * column will clamp to the right edge of the view if it is
385 aspectsBuilder
.add(LamiEmptyAspect
.INSTANCE
);
387 return aspectsBuilder
.build();
390 private static DataType
getDataTypeFromString(String value
) throws JSONException
{
392 return DataType
.fromString(value
);
393 } catch (IllegalArgumentException e
) {
394 throw new JSONException("Unrecognized data type: " + value
); //$NON-NLS-1$
399 * Get the title of this analysis, as read from the script's metadata.
401 * @return The analysis title. Should not be null after the initialization
402 * completed successfully.
404 public @Nullable String
getAnalysisTitle() {
405 return fAnalysisTitle
;
409 * Get the result table classes defined by this analysis, as read from the
412 * @return The analysis' result table classes. Should not be null after the
413 * execution completed successfully.
415 public @Nullable Map
<String
, LamiTableClass
> getTableClasses() {
416 return fTableClasses
;
420 * Print the full command that will be run when calling {@link #execute},
421 * with the exception of the 'extraParams' that will be passed to execute().
423 * This can be used to display the command in the UI before it is actually
427 * The trace on which to run the analysis
429 * The time range to specify. Null will not specify a time range,
430 * which means the whole trace will be taken.
431 * @return The command as a single, space-separated string
433 public String
getFullCommandAsString(ITmfTrace trace
, @Nullable TmfTimeRange range
) {
434 String tracePath
= checkNotNull(trace
.getPath());
436 ImmutableList
.Builder
<String
> builder
= getBaseCommand(range
);
438 * We can add double-quotes around the trace path, which could contain
439 * spaces, so that the resulting command can be easily copy-pasted into
442 builder
.add(DOUBLE_QUOTES
+ tracePath
+ DOUBLE_QUOTES
);
443 List
<String
> list
= builder
.build();
444 String ret
= list
.stream().collect(Collectors
.joining(" ")); //$NON-NLS-1$
445 return checkNotNull(ret
);
449 * Get the base part of the command that will be executed to run this
450 * analysis, supplying the given time range. Base part meaning:
453 * [script executable] [statically-defined parameters] [--begin/--end (if applicable)]
456 * Note that it does not include the path to the trace, that is to be added
460 * The time range that will be passed
461 * @return The elements of the command
463 private ImmutableList
.Builder
<String
> getBaseCommand(@Nullable TmfTimeRange range
) {
467 begin
= range
.getStartTime().getValue();
468 end
= range
.getEndTime().getValue();
471 ImmutableList
.Builder
<String
> builder
= ImmutableList
.builder();
472 builder
.addAll(fScriptCommand
);
474 if (fUseProgressOutput
) {
475 builder
.add(PROGRESS_FLAG
);
479 builder
.add(BEGIN_FLAG
).add(String
.valueOf(begin
));
480 builder
.add(END_FLAG
).add(String
.valueOf(end
));
486 * Call the currently defined LAMI script with the given arguments.
489 * The time range. Null for the whole trace.
491 * The progress monitor used to report progress
492 * @return The script's output, formatted into {@link LamiTableEntry}'s.
493 * @throws CoreException
494 * If execution did not terminate normally
497 public List
<LamiResultTable
> execute(ITmfTrace trace
, @Nullable TmfTimeRange timeRange
,
498 String extraParams
, IProgressMonitor monitor
) throws CoreException
{
499 /* Should have been called already, but in case it was not */
502 final @NonNull String tracePath
= checkNotNull(trace
.getPath());
503 final @NonNull String
[] splitParams
= extraParams
.trim().split(" "); //$NON-NLS-1$
505 ImmutableList
.Builder
<String
> builder
= getBaseCommand(timeRange
);
507 if (!extraParams
.trim().equals("")) { //$NON-NLS-1$
508 builder
.addAll(Arrays
.asList(splitParams
));
510 builder
.add(tracePath
);
511 List
<String
> command
= builder
.build();
513 Activator
.instance().logInfo(RUNNING_MESSAGE
+ ' ' + command
.toString());
514 String output
= getResultsFromCommand(command
, monitor
);
516 if (output
.isEmpty()) {
517 IStatus status
= new Status(IStatus
.INFO
, Activator
.instance().getPluginId(), Messages
.LamiAnalysis_NoResults
);
518 throw new CoreException(status
);
526 * "type": "time-range",
527 * "begin": 1444334398154194201,
528 * "end": 1444334425194487548
530 * "class": "syscall-latency",
533 * {"type": "syscall", "name": "open"},
535 * {"type": "duration", "value": 5562},
536 * {"type": "duration", "value": 13835},
537 * {"type": "duration", "value": 77683},
538 * {"type": "duration", "value": 15263}
541 * {"type": "syscall", "name": "read"},
543 * {"type": "duration", "value": 316},
544 * {"type": "duration", "value": 5774},
545 * {"type": "duration", "value": 62569},
546 * {"type": "duration", "value": 9277}
552 * "type": "time-range",
553 * "begin": 1444334425194487549,
554 * "end": 1444334425254887190
556 * "class": "syscall-latency",
559 * {"type": "syscall", "name": "open"},
561 * {"type": "duration", "value": 1578},
562 * {"type": "duration", "value": 16648},
563 * {"type": "duration", "value": 15444},
564 * {"type": "duration", "value": 68540}
567 * {"type": "syscall", "name": "read"},
569 * {"type": "duration", "value": 78},
570 * {"type": "duration", "value": 1948},
571 * {"type": "duration", "value": 11184},
572 * {"type": "duration", "value": 94670}
581 ImmutableList
.Builder
<LamiResultTable
> resultsBuilder
= new ImmutableList
.Builder
<>();
584 JSONObject obj
= new JSONObject(output
);
585 JSONArray results
= obj
.getJSONArray(LamiStrings
.RESULTS
);
587 if (results
.length() == 0) {
589 * No results were reported. This may be normal, but warn the
590 * user why a report won't be created.
592 IStatus status
= new Status(IStatus
.INFO
, Activator
.instance().getPluginId(), Messages
.LamiAnalysis_NoResults
);
593 throw new CoreException(status
);
596 for (int i
= 0; i
< results
.length(); i
++) {
597 JSONObject result
= results
.getJSONObject(i
);
599 /* Parse the time-range */
600 JSONObject trObject
= result
.getJSONObject(LamiStrings
.TIME_RANGE
);
601 long start
= trObject
.getLong(LamiStrings
.BEGIN
);
602 long end
= trObject
.getLong(LamiStrings
.END
);
603 LamiTimeRange tr
= new LamiTimeRange(start
, end
);
605 /* Parse the table's class */
606 LamiTableClass tableClass
;
607 JSONObject tableClassObject
= result
.optJSONObject(LamiStrings
.CLASS
);
608 if (tableClassObject
== null) {
610 * "class" is just a standard string, indicating we use a
611 * metadata-defined table class as-is
613 @NonNull String tableClassName
= checkNotNull(result
.getString(LamiStrings
.CLASS
));
614 tableClass
= getTableClassFromName(tableClassName
);
616 // FIXME Rest will become more generic eventually in the LAMI format.
617 } else if (tableClassObject
.has(LamiStrings
.INHERIT
)) {
619 * Dynamic title: We reuse an existing table class but
620 * override the title.
622 String baseTableName
= checkNotNull(tableClassObject
.getString(LamiStrings
.INHERIT
));
623 LamiTableClass baseTableClass
= getTableClassFromName(baseTableName
);
624 String newTitle
= checkNotNull(tableClassObject
.getString(LamiStrings
.TITLE
));
626 tableClass
= new LamiTableClass(baseTableClass
, newTitle
);
629 * Dynamic column descriptions: we implement a new table
632 String title
= checkNotNull(tableClassObject
.getString(LamiStrings
.TITLE
));
633 JSONArray columnDescriptions
= checkNotNull(tableClassObject
.getJSONArray(LamiStrings
.COLUMN_DESCRIPTIONS
));
634 List
<LamiTableEntryAspect
> aspects
= getAspectsFromColumnDescriptions(columnDescriptions
);
636 tableClass
= new LamiTableClass(nullToEmptyString(Messages
.LamiAnalysis_DefaultDynamicTableName
), title
, aspects
, Collections
.EMPTY_SET
);
639 /* Parse the "data", which is the array of rows */
640 JSONArray data
= result
.getJSONArray(LamiStrings
.DATA
);
641 ImmutableList
.Builder
<LamiTableEntry
> dataBuilder
= new ImmutableList
.Builder
<>();
643 for (int j
= 0; j
< data
.length(); j
++) {
644 /* A row is an array of cells */
645 JSONArray row
= data
.getJSONArray(j
);
646 ImmutableList
.Builder
<LamiData
> rowBuilder
= ImmutableList
.builder();
648 for (int k
= 0; k
< row
.length(); k
++) {
649 Object cellObject
= checkNotNull(row
.get(k
));
650 LamiData cellValue
= LamiData
.createFromObject(cellObject
);
651 rowBuilder
.add(cellValue
);
654 dataBuilder
.add(new LamiTableEntry(rowBuilder
.build()));
656 resultsBuilder
.add(new LamiResultTable(tr
, tableClass
, dataBuilder
.build()));
659 } catch (JSONException e
) {
660 IStatus status
= new Status(IStatus
.ERROR
, Activator
.instance().getPluginId(), e
.getMessage(), e
);
661 throw new CoreException(status
);
664 return resultsBuilder
.build();
667 private LamiTableClass
getTableClassFromName(String tableClassName
) throws JSONException
{
668 Map
<String
, LamiTableClass
> map
= checkNotNull(fTableClasses
);
669 LamiTableClass tableClass
= map
.get(tableClassName
);
670 if (tableClass
== null) {
671 throw new JSONException("Table class " + tableClassName
+ //$NON-NLS-1$
672 " was not declared in the metadata"); //$NON-NLS-1$
678 * Get the output of an external command, used for getting the metadata.
679 * Cannot be cancelled, and will not report errors, simply returns null if
680 * the process ended abnormally.
683 * The parameters of the command, passed to
684 * {@link ProcessBuilder}
685 * @return The command output as a string
688 protected @Nullable String
getOutputFromCommand(List
<String
> command
) {
690 ProcessBuilder builder
= new ProcessBuilder(command
);
691 builder
.redirectErrorStream(true);
693 Process p
= builder
.start();
694 try (BufferedReader br
= new BufferedReader(new InputStreamReader(p
.getInputStream()));) {
695 int ret
= p
.waitFor();
696 String output
= br
.lines().collect(Collectors
.joining());
698 return (ret
== 0 ? output
: null);
700 } catch (IOException
| InterruptedException e
) {
706 * Get the results of invoking the specified command.
708 * The result should start with '{"results":...', as specified by the LAMI
709 * JSON protocol. The JSON itself may be split over multiple lines.
712 * The command to run (program and its arguments)
714 * The progress monitor
715 * @return The analysis results
716 * @throws CoreException
717 * If the command ended abnormally, and normal results were not
721 protected String
getResultsFromCommand(List
<String
> command
, IProgressMonitor monitor
)
722 throws CoreException
{
724 final int scale
= 1000;
725 double workedSoFar
= 0.0;
727 ProcessCanceller cancellerRunnable
= null;
728 Thread cancellerThread
= null;
731 monitor
.beginTask(Messages
.LamiAnalysis_MainTaskName
, scale
);
733 ProcessBuilder builder
= new ProcessBuilder(command
);
734 builder
.redirectErrorStream(false);
736 Process p
= checkNotNull(builder
.start());
738 cancellerRunnable
= new ProcessCanceller(p
, monitor
);
739 cancellerThread
= new Thread(cancellerRunnable
);
740 cancellerThread
.start();
742 List
<String
> results
= new ArrayList
<>();
744 try (BufferedReader in
= new BufferedReader(new InputStreamReader(p
.getInputStream()));) {
745 String line
= in
.readLine();
746 while (line
!= null && !line
.matches("\\s*\\{.*")) { //$NON-NLS-1$
748 * This is a line indicating progress, it has the form:
750 * 0.123 3000 of 5000 events processed
752 * The first part indicates the estimated fraction (out of
753 * 1.0) of work done. The second part is status text.
756 // Trim the line first to make sure the first character is
760 // Split at the first space
761 String
[] elems
= line
.split(" ", 2); //$NON-NLS-1$
763 if (elems
[0].matches("\\d.*")) { //$NON-NLS-1$
764 // It looks like we have a progress indication
766 // Try parsing the number
767 double cumulativeWork
= Double
.parseDouble(elems
[0]) * scale
;
768 double workedThisLoop
= cumulativeWork
- workedSoFar
;
770 // We're going backwards? Do not update the
772 if (workedThisLoop
> 0) {
773 monitor
.internalWorked(workedThisLoop
);
774 workedSoFar
= cumulativeWork
;
777 // There is a message: update the monitor's task name
778 if (elems
.length
>= 2) {
779 monitor
.setTaskName(elems
[1].trim());
781 } catch (NumberFormatException e
) {
782 // Continue reading progress lines anyway
786 line
= in
.readLine();
788 while (line
!= null) {
790 * We have seen the first line containing a '{', this is our
794 line
= in
.readLine();
797 int ret
= p
.waitFor();
799 if (monitor
.isCanceled()) {
800 /* We were interrupted by the canceller thread. */
801 IStatus status
= new Status(IStatus
.CANCEL
, Activator
.instance().getPluginId(), null);
802 throw new CoreException(status
);
807 * Something went wrong running the external script. We will
808 * gather the stderr and report it to the user.
810 BufferedReader br
= new BufferedReader(new InputStreamReader(p
.getErrorStream()));
811 List
<String
> stdErrOutput
= br
.lines().collect(Collectors
.toList());
813 MultiStatus status
= new MultiStatus(Activator
.instance().getPluginId(),
814 IStatus
.ERROR
, Messages
.LamiAnalysis_ErrorDuringExecution
, null);
815 for (String str
: stdErrOutput
) {
816 status
.add(new Status(IStatus
.ERROR
, Activator
.instance().getPluginId(), str
));
818 if (stdErrOutput
.isEmpty()) {
820 * At least say "no output", so an error message actually
823 status
.add(new Status(IStatus
.ERROR
, Activator
.instance().getPluginId(), Messages
.LamiAnalysis_ErrorNoOutput
));
825 throw new CoreException(status
);
828 /* External script ended successfully, all is fine! */
829 String resultsStr
= results
.stream().collect(Collectors
.joining());
830 return checkNotNull(resultsStr
);
832 } catch (IOException
| InterruptedException e
) {
833 IStatus status
= new Status(IStatus
.ERROR
, Activator
.instance().getPluginId(), Messages
.LamiAnalysis_ExecutionInterrupted
, e
);
834 throw new CoreException(status
);
837 if (cancellerRunnable
!= null) {
838 cancellerRunnable
.setFinished();
840 if (cancellerThread
!= null) {
842 cancellerThread
.join();
843 } catch (InterruptedException e
) {
851 private static class ProcessCanceller
implements Runnable
{
853 private final Process fProcess
;
854 private final IProgressMonitor fMonitor
;
856 private boolean fIsFinished
= false;
858 public ProcessCanceller(Process process
, IProgressMonitor monitor
) {
863 public void setFinished() {
870 while (!fIsFinished
) {
872 if (fMonitor
.isCanceled()) {
877 } catch (InterruptedException e
) {
884 public @NonNull String
getName() {
889 public boolean isUserDefined() {
890 return fIsUserDefined
;