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
{
82 * Maximum major version of the LAMI protocol we support.
84 * Currently only 0.x/unversioned MI, outputted by lttng-analyses 0.4.x
86 private static final int MAX_SUPPORTED_MAJOR_VERSION
= 0;
88 private static final String DOUBLE_QUOTES
= "\""; //$NON-NLS-1$
90 /* Flags passed to the analysis scripts */
91 private static final String METADATA_FLAG
= "--metadata"; //$NON-NLS-1$
92 private static final String PROGRESS_FLAG
= "--output-progress"; //$NON-NLS-1$
93 private static final String BEGIN_FLAG
= "--begin"; //$NON-NLS-1$
94 private static final String END_FLAG
= "--end"; //$NON-NLS-1$
96 /** Log message for commands being run */
97 private static final String RUNNING_MESSAGE
= "Running command:"; //$NON-NLS-1$
99 private final List
<String
> fScriptCommand
;
102 * The LAMI analysis is considered initialized after we have read the
103 * script's --metadata once. This will assign the fields below.
105 private boolean fInitialized
= false;
107 private boolean fIsAvailable
;
108 private final String fName
;
109 private final boolean fIsUserDefined
;
110 private final Predicate
<ITmfTrace
> fAppliesTo
;
112 /* Data defined by the analysis's metadata */
113 private @Nullable String fAnalysisTitle
;
114 private @Nullable Map
<String
, LamiTableClass
> fTableClasses
;
115 private boolean fUseProgressOutput
;
118 * Constructor. To be called by implementing classes.
121 * Name of this analysis
122 * @param isUserDefined
123 * {@code true} if this is a user-defined analysis
125 * Predicate to use to check whether or not this analysis applies
128 * Analysis arguments, including the executable name (first
131 public LamiAnalysis(String name
, boolean isUserDefined
, Predicate
<ITmfTrace
> appliesTo
,
133 fScriptCommand
= ImmutableList
.copyOf(args
);
135 fIsUserDefined
= isUserDefined
;
136 fAppliesTo
= appliesTo
;
140 * Map of pre-defined charts, for every table class names.
142 * If a table class is not in this map then it means that table has no
145 * @return The chart models, per table class names
147 protected Multimap
<String
, LamiChartModel
> getPredefinedCharts() {
148 return ImmutableMultimap
.of();
152 public final boolean appliesTo(ITmfTrace trace
) {
153 return fAppliesTo
.test(trace
);
157 public boolean canExecute(ITmfTrace trace
) {
163 * Perform initialization of the LAMI script. This means verifying that it
164 * is actually present on disk, and that it returns correct --metadata.
167 protected synchronized void initialize() {
172 /* Do the analysis's initialization */
174 /* Check if the script's expected executable is on the PATH */
175 String executable
= fScriptCommand
.get(0);
176 boolean exists
= Stream
.of(System
.getenv("PATH").split(checkNotNull(Pattern
.quote(File
.pathSeparator
)))) //$NON-NLS-1$
178 .anyMatch(path
-> Files
.exists(path
.resolve(executable
)));
180 /* Script is not found */
181 fIsAvailable
= false;
186 fIsAvailable
= checkMetadata();
191 * Verify that this script returns valid metadata.
193 * This will populate all remaining non-final fields of this class.
195 * @return If the metadata is valid or not
198 protected boolean checkMetadata() {
200 * The initialize() phase of the analysis will be used to check the
201 * script's metadata. Actual runs of the script will use the execute()
204 List
<String
> command
= ImmutableList
.<@NonNull String
> builder()
205 .addAll(fScriptCommand
).add(METADATA_FLAG
).build();
207 Activator
.instance().logInfo(RUNNING_MESSAGE
+ ' ' + command
.toString());
209 String output
= getOutputFromCommand(command
);
210 if (output
== null || output
.isEmpty()) {
216 * Metadata should look this this:
219 * "version": [1, 5, 2, "dev"],
220 * "title": "I/O latency statistics",
222 * "Julien Desfossez",
225 * "description": "Provides statistics about the latency involved in various I/O operations.",
226 * "url": "https://github.com/lttng/lttng-analyses",
234 * "syscall-latency": {
235 * "title": "System calls latency statistics",
236 * "column-descriptions": [
237 * {"title": "System call", "type": "syscall"},
238 * {"title": "Count", "type": "int", "unit": "operations"},
239 * {"title": "Minimum duration", "type": "duration"},
240 * {"title": "Average duration", "type": "duration"},
241 * {"title": "Maximum duration", "type": "duration"},
242 * {"title": "Standard deviation", "type": "duration"}
246 * "title": "Disk latency statistics",
247 * "column-descriptions": [
248 * {"title": "Disk name", "type": "disk"},
249 * {"title": "Count", "type": "int", "unit": "operations"},
250 * {"title": "Minimum duration", "type": "duration"},
251 * {"title": "Average duration", "type": "duration"},
252 * {"title": "Maximum duration", "type": "duration"},
253 * {"title": "Standard deviation", "type": "duration"}
262 JSONObject obj
= new JSONObject(output
);
263 fAnalysisTitle
= obj
.getString(LamiStrings
.TITLE
);
265 /* Very early scripts may not contain the "mi-version" */
266 JSONObject miVersion
= obj
.optJSONObject(LamiStrings
.MI_VERSION
);
267 if (miVersion
== null) {
268 /* Before version 0.1 */
269 fUseProgressOutput
= false;
271 int majorVersion
= miVersion
.getInt(LamiStrings
.MAJOR
);
272 if (majorVersion
<= MAX_SUPPORTED_MAJOR_VERSION
) {
273 fUseProgressOutput
= true;
275 /* Unknown version, we do not support it */
280 JSONObject tableClasses
= obj
.getJSONObject(LamiStrings
.TABLE_CLASSES
);
281 @NonNull String
[] tableClassNames
= checkNotNullContents(JSONObject
.getNames(tableClasses
));
283 ImmutableMap
.Builder
<String
, LamiTableClass
> tablesBuilder
= ImmutableMap
.builder();
284 for (String tableClassName
: tableClassNames
) {
285 JSONObject tableClass
= tableClasses
.getJSONObject(tableClassName
);
287 final String tableTitle
= checkNotNull(tableClass
.getString(LamiStrings
.TITLE
));
288 @NonNull JSONArray columnDescriptions
= checkNotNull(tableClass
.getJSONArray(LamiStrings
.COLUMN_DESCRIPTIONS
));
290 List
<LamiTableEntryAspect
> aspects
= getAspectsFromColumnDescriptions(columnDescriptions
);
291 Collection
<LamiChartModel
> chartModels
= getPredefinedCharts().get(tableClassName
);
293 tablesBuilder
.put(tableClassName
, new LamiTableClass(tableClassName
, tableTitle
, aspects
, chartModels
));
297 fTableClasses
= tablesBuilder
.build();
298 } catch (IllegalArgumentException e
) {
300 * This is thrown if there are duplicate keys in the map
303 throw new JSONException("Duplicate table class entry in " + fAnalysisTitle
); //$NON-NLS-1$
306 } catch (JSONException e
) {
307 /* Error in the parsing of the JSON, script is broken? */
308 Activator
.instance().logError(e
.getMessage());
314 private static List
<LamiTableEntryAspect
> getAspectsFromColumnDescriptions(JSONArray columnDescriptions
) throws JSONException
{
315 ImmutableList
.Builder
<LamiTableEntryAspect
> aspectsBuilder
= new ImmutableList
.Builder
<>();
316 for (int j
= 0; j
< columnDescriptions
.length(); j
++) {
317 JSONObject column
= columnDescriptions
.getJSONObject(j
);
318 DataType columnDataType
;
319 String columnClass
= column
.optString(LamiStrings
.CLASS
, null);
321 if (columnClass
== null) {
322 columnDataType
= DataType
.MIXED
;
324 columnDataType
= getDataTypeFromString(columnClass
);
327 String columnTitle
= column
.optString(LamiStrings
.TITLE
, null);
329 if (columnTitle
== null) {
330 columnTitle
= String
.format("%s #%d", columnDataType
.getTitle(), j
+ 1); //$NON-NLS-1$
333 final int colIndex
= j
;
334 switch (columnDataType
) {
337 * We will add 3 aspects, to represent the start, end and
338 * duration of this time range.
340 aspectsBuilder
.add(new LamiTimeRangeBeginAspect(columnTitle
, colIndex
));
341 aspectsBuilder
.add(new LamiTimeRangeEndAspect(columnTitle
, colIndex
));
342 aspectsBuilder
.add(new LamiTimeRangeDurationAspect(columnTitle
, colIndex
));
346 aspectsBuilder
.add(new LamiTimestampAspect(columnTitle
, colIndex
));
350 aspectsBuilder
.add(new LamiProcessNameAspect(columnTitle
, colIndex
));
351 aspectsBuilder
.add(new LamiProcessPIDAspect(columnTitle
, colIndex
));
352 aspectsBuilder
.add(new LamiProcessTIDAspect(columnTitle
, colIndex
));
356 aspectsBuilder
.add(new LamiIRQTypeAspect(columnTitle
, colIndex
));
357 aspectsBuilder
.add(new LamiIRQNameAspect(columnTitle
, colIndex
));
358 aspectsBuilder
.add(new LamiIRQNumberAspect(columnTitle
, colIndex
));
362 aspectsBuilder
.add(new LamiDurationAspect(columnTitle
, colIndex
));
366 aspectsBuilder
.add(new LamiMixedAspect(columnTitle
, colIndex
));
371 String units
= column
.optString(LamiStrings
.UNIT
, null);
374 units
= columnDataType
.getUnits();
377 /* We will add only one aspect representing the element */
378 LamiTableEntryAspect aspect
= new LamiGenericAspect(columnTitle
,
379 units
, colIndex
, columnDataType
.isContinuous(), false);
380 aspectsBuilder
.add(aspect
);
385 * SWT quirk : we need an empty column at the end or else the last data
386 * column will clamp to the right edge of the view if it is
389 aspectsBuilder
.add(LamiEmptyAspect
.INSTANCE
);
391 return aspectsBuilder
.build();
394 private static DataType
getDataTypeFromString(String value
) throws JSONException
{
396 return DataType
.fromString(value
);
397 } catch (IllegalArgumentException e
) {
398 throw new JSONException("Unrecognized data type: " + value
); //$NON-NLS-1$
403 * Get the title of this analysis, as read from the script's metadata.
405 * @return The analysis title. Should not be null after the initialization
406 * completed successfully.
408 public @Nullable String
getAnalysisTitle() {
409 return fAnalysisTitle
;
413 * Get the result table classes defined by this analysis, as read from the
416 * @return The analysis' result table classes. Should not be null after the
417 * execution completed successfully.
419 public @Nullable Map
<String
, LamiTableClass
> getTableClasses() {
420 return fTableClasses
;
424 * Print the full command that will be run when calling {@link #execute},
425 * with the exception of the 'extraParams' that will be passed to execute().
427 * This can be used to display the command in the UI before it is actually
431 * The trace on which to run the analysis
433 * The time range to specify. Null will not specify a time range,
434 * which means the whole trace will be taken.
435 * @return The command as a single, space-separated string
437 public String
getFullCommandAsString(ITmfTrace trace
, @Nullable TmfTimeRange range
) {
438 String tracePath
= checkNotNull(trace
.getPath());
440 ImmutableList
.Builder
<String
> builder
= getBaseCommand(range
);
442 * We can add double-quotes around the trace path, which could contain
443 * spaces, so that the resulting command can be easily copy-pasted into
446 builder
.add(DOUBLE_QUOTES
+ tracePath
+ DOUBLE_QUOTES
);
447 List
<String
> list
= builder
.build();
448 String ret
= list
.stream().collect(Collectors
.joining(" ")); //$NON-NLS-1$
449 return checkNotNull(ret
);
453 * Get the base part of the command that will be executed to run this
454 * analysis, supplying the given time range. Base part meaning:
457 * [script executable] [statically-defined parameters] [--begin/--end (if applicable)]
460 * Note that it does not include the path to the trace, that is to be added
464 * The time range that will be passed
465 * @return The elements of the command
467 private ImmutableList
.Builder
<String
> getBaseCommand(@Nullable TmfTimeRange range
) {
471 begin
= range
.getStartTime().getValue();
472 end
= range
.getEndTime().getValue();
475 ImmutableList
.Builder
<String
> builder
= ImmutableList
.builder();
476 builder
.addAll(fScriptCommand
);
478 if (fUseProgressOutput
) {
479 builder
.add(PROGRESS_FLAG
);
483 builder
.add(BEGIN_FLAG
).add(String
.valueOf(begin
));
484 builder
.add(END_FLAG
).add(String
.valueOf(end
));
490 * Call the currently defined LAMI script with the given arguments.
493 * The time range. Null for the whole trace.
495 * The progress monitor used to report progress
496 * @return The script's output, formatted into {@link LamiTableEntry}'s.
497 * @throws CoreException
498 * If execution did not terminate normally
501 public List
<LamiResultTable
> execute(ITmfTrace trace
, @Nullable TmfTimeRange timeRange
,
502 String extraParams
, IProgressMonitor monitor
) throws CoreException
{
503 /* Should have been called already, but in case it was not */
506 final @NonNull String tracePath
= checkNotNull(trace
.getPath());
507 final @NonNull String
[] splitParams
= extraParams
.trim().split(" "); //$NON-NLS-1$
509 ImmutableList
.Builder
<String
> builder
= getBaseCommand(timeRange
);
511 if (!extraParams
.trim().equals("")) { //$NON-NLS-1$
512 builder
.addAll(Arrays
.asList(splitParams
));
514 builder
.add(tracePath
);
515 List
<String
> command
= builder
.build();
517 Activator
.instance().logInfo(RUNNING_MESSAGE
+ ' ' + command
.toString());
518 String output
= getResultsFromCommand(command
, monitor
);
520 if (output
.isEmpty()) {
521 IStatus status
= new Status(IStatus
.INFO
, Activator
.instance().getPluginId(), Messages
.LamiAnalysis_NoResults
);
522 throw new CoreException(status
);
530 * "type": "time-range",
531 * "begin": 1444334398154194201,
532 * "end": 1444334425194487548
534 * "class": "syscall-latency",
537 * {"type": "syscall", "name": "open"},
539 * {"type": "duration", "value": 5562},
540 * {"type": "duration", "value": 13835},
541 * {"type": "duration", "value": 77683},
542 * {"type": "duration", "value": 15263}
545 * {"type": "syscall", "name": "read"},
547 * {"type": "duration", "value": 316},
548 * {"type": "duration", "value": 5774},
549 * {"type": "duration", "value": 62569},
550 * {"type": "duration", "value": 9277}
556 * "type": "time-range",
557 * "begin": 1444334425194487549,
558 * "end": 1444334425254887190
560 * "class": "syscall-latency",
563 * {"type": "syscall", "name": "open"},
565 * {"type": "duration", "value": 1578},
566 * {"type": "duration", "value": 16648},
567 * {"type": "duration", "value": 15444},
568 * {"type": "duration", "value": 68540}
571 * {"type": "syscall", "name": "read"},
573 * {"type": "duration", "value": 78},
574 * {"type": "duration", "value": 1948},
575 * {"type": "duration", "value": 11184},
576 * {"type": "duration", "value": 94670}
585 ImmutableList
.Builder
<LamiResultTable
> resultsBuilder
= new ImmutableList
.Builder
<>();
588 JSONObject obj
= new JSONObject(output
);
589 JSONArray results
= obj
.getJSONArray(LamiStrings
.RESULTS
);
591 if (results
.length() == 0) {
593 * No results were reported. This may be normal, but warn the
594 * user why a report won't be created.
596 IStatus status
= new Status(IStatus
.INFO
, Activator
.instance().getPluginId(), Messages
.LamiAnalysis_NoResults
);
597 throw new CoreException(status
);
600 for (int i
= 0; i
< results
.length(); i
++) {
601 JSONObject result
= results
.getJSONObject(i
);
603 /* Parse the time-range */
604 JSONObject trObject
= result
.getJSONObject(LamiStrings
.TIME_RANGE
);
605 long start
= trObject
.getLong(LamiStrings
.BEGIN
);
606 long end
= trObject
.getLong(LamiStrings
.END
);
607 LamiTimeRange tr
= new LamiTimeRange(start
, end
);
609 /* Parse the table's class */
610 LamiTableClass tableClass
;
611 JSONObject tableClassObject
= result
.optJSONObject(LamiStrings
.CLASS
);
612 if (tableClassObject
== null) {
614 * "class" is just a standard string, indicating we use a
615 * metadata-defined table class as-is
617 @NonNull String tableClassName
= checkNotNull(result
.getString(LamiStrings
.CLASS
));
618 tableClass
= getTableClassFromName(tableClassName
);
620 // FIXME Rest will become more generic eventually in the LAMI format.
621 } else if (tableClassObject
.has(LamiStrings
.INHERIT
)) {
623 * Dynamic title: We reuse an existing table class but
624 * override the title.
626 String baseTableName
= checkNotNull(tableClassObject
.getString(LamiStrings
.INHERIT
));
627 LamiTableClass baseTableClass
= getTableClassFromName(baseTableName
);
628 String newTitle
= checkNotNull(tableClassObject
.getString(LamiStrings
.TITLE
));
630 tableClass
= new LamiTableClass(baseTableClass
, newTitle
);
633 * Dynamic column descriptions: we implement a new table
636 String title
= checkNotNull(tableClassObject
.getString(LamiStrings
.TITLE
));
637 JSONArray columnDescriptions
= checkNotNull(tableClassObject
.getJSONArray(LamiStrings
.COLUMN_DESCRIPTIONS
));
638 List
<LamiTableEntryAspect
> aspects
= getAspectsFromColumnDescriptions(columnDescriptions
);
640 tableClass
= new LamiTableClass(nullToEmptyString(Messages
.LamiAnalysis_DefaultDynamicTableName
), title
, aspects
, Collections
.EMPTY_SET
);
643 /* Parse the "data", which is the array of rows */
644 JSONArray data
= result
.getJSONArray(LamiStrings
.DATA
);
645 ImmutableList
.Builder
<LamiTableEntry
> dataBuilder
= new ImmutableList
.Builder
<>();
647 for (int j
= 0; j
< data
.length(); j
++) {
648 /* A row is an array of cells */
649 JSONArray row
= data
.getJSONArray(j
);
650 ImmutableList
.Builder
<LamiData
> rowBuilder
= ImmutableList
.builder();
652 for (int k
= 0; k
< row
.length(); k
++) {
653 Object cellObject
= checkNotNull(row
.get(k
));
654 LamiData cellValue
= LamiData
.createFromObject(cellObject
);
655 rowBuilder
.add(cellValue
);
658 dataBuilder
.add(new LamiTableEntry(rowBuilder
.build()));
660 resultsBuilder
.add(new LamiResultTable(tr
, tableClass
, dataBuilder
.build()));
663 } catch (JSONException e
) {
664 IStatus status
= new Status(IStatus
.ERROR
, Activator
.instance().getPluginId(), e
.getMessage(), e
);
665 throw new CoreException(status
);
668 return resultsBuilder
.build();
671 private LamiTableClass
getTableClassFromName(String tableClassName
) throws JSONException
{
672 Map
<String
, LamiTableClass
> map
= checkNotNull(fTableClasses
);
673 LamiTableClass tableClass
= map
.get(tableClassName
);
674 if (tableClass
== null) {
675 throw new JSONException("Table class " + tableClassName
+ //$NON-NLS-1$
676 " was not declared in the metadata"); //$NON-NLS-1$
682 * Get the output of an external command, used for getting the metadata.
683 * Cannot be cancelled, and will not report errors, simply returns null if
684 * the process ended abnormally.
687 * The parameters of the command, passed to
688 * {@link ProcessBuilder}
689 * @return The command output as a string
692 protected @Nullable String
getOutputFromCommand(List
<String
> command
) {
694 ProcessBuilder builder
= new ProcessBuilder(command
);
695 builder
.redirectErrorStream(true);
697 Process p
= builder
.start();
698 try (BufferedReader br
= new BufferedReader(new InputStreamReader(p
.getInputStream()));) {
699 int ret
= p
.waitFor();
700 String output
= br
.lines().collect(Collectors
.joining());
702 return (ret
== 0 ? output
: null);
704 } catch (IOException
| InterruptedException e
) {
710 * Get the results of invoking the specified command.
712 * The result should start with '{"results":...', as specified by the LAMI
713 * JSON protocol. The JSON itself may be split over multiple lines.
716 * The command to run (program and its arguments)
718 * The progress monitor
719 * @return The analysis results
720 * @throws CoreException
721 * If the command ended abnormally, and normal results were not
725 protected String
getResultsFromCommand(List
<String
> command
, IProgressMonitor monitor
)
726 throws CoreException
{
728 final int scale
= 1000;
729 double workedSoFar
= 0.0;
731 ProcessCanceller cancellerRunnable
= null;
732 Thread cancellerThread
= null;
735 monitor
.beginTask(Messages
.LamiAnalysis_MainTaskName
, scale
);
737 ProcessBuilder builder
= new ProcessBuilder(command
);
738 builder
.redirectErrorStream(false);
740 Process p
= checkNotNull(builder
.start());
742 cancellerRunnable
= new ProcessCanceller(p
, monitor
);
743 cancellerThread
= new Thread(cancellerRunnable
);
744 cancellerThread
.start();
746 List
<String
> results
= new ArrayList
<>();
748 try (BufferedReader in
= new BufferedReader(new InputStreamReader(p
.getInputStream()));) {
749 String line
= in
.readLine();
750 while (line
!= null && !line
.matches("\\s*\\{.*")) { //$NON-NLS-1$
752 * This is a line indicating progress, it has the form:
754 * 0.123 3000 of 5000 events processed
756 * The first part indicates the estimated fraction (out of
757 * 1.0) of work done. The second part is status text.
760 // Trim the line first to make sure the first character is
764 // Split at the first space
765 String
[] elems
= line
.split(" ", 2); //$NON-NLS-1$
767 if (elems
[0].matches("\\d.*")) { //$NON-NLS-1$
768 // It looks like we have a progress indication
770 // Try parsing the number
771 double cumulativeWork
= Double
.parseDouble(elems
[0]) * scale
;
772 double workedThisLoop
= cumulativeWork
- workedSoFar
;
774 // We're going backwards? Do not update the
776 if (workedThisLoop
> 0) {
777 monitor
.internalWorked(workedThisLoop
);
778 workedSoFar
= cumulativeWork
;
781 // There is a message: update the monitor's task name
782 if (elems
.length
>= 2) {
783 monitor
.setTaskName(elems
[1].trim());
785 } catch (NumberFormatException e
) {
786 // Continue reading progress lines anyway
790 line
= in
.readLine();
792 while (line
!= null) {
794 * We have seen the first line containing a '{', this is our
798 line
= in
.readLine();
801 int ret
= p
.waitFor();
803 if (monitor
.isCanceled()) {
804 /* We were interrupted by the canceller thread. */
805 IStatus status
= new Status(IStatus
.CANCEL
, Activator
.instance().getPluginId(), null);
806 throw new CoreException(status
);
811 * Something went wrong running the external script. We will
812 * gather the stderr and report it to the user.
814 BufferedReader br
= new BufferedReader(new InputStreamReader(p
.getErrorStream()));
815 List
<String
> stdErrOutput
= br
.lines().collect(Collectors
.toList());
817 MultiStatus status
= new MultiStatus(Activator
.instance().getPluginId(),
818 IStatus
.ERROR
, Messages
.LamiAnalysis_ErrorDuringExecution
, null);
819 for (String str
: stdErrOutput
) {
820 status
.add(new Status(IStatus
.ERROR
, Activator
.instance().getPluginId(), str
));
822 if (stdErrOutput
.isEmpty()) {
824 * At least say "no output", so an error message actually
827 status
.add(new Status(IStatus
.ERROR
, Activator
.instance().getPluginId(), Messages
.LamiAnalysis_ErrorNoOutput
));
829 throw new CoreException(status
);
832 /* External script ended successfully, all is fine! */
833 String resultsStr
= results
.stream().collect(Collectors
.joining());
834 return checkNotNull(resultsStr
);
836 } catch (IOException
| InterruptedException e
) {
837 IStatus status
= new Status(IStatus
.ERROR
, Activator
.instance().getPluginId(), Messages
.LamiAnalysis_ExecutionInterrupted
, e
);
838 throw new CoreException(status
);
841 if (cancellerRunnable
!= null) {
842 cancellerRunnable
.setFinished();
844 if (cancellerThread
!= null) {
846 cancellerThread
.join();
847 } catch (InterruptedException e
) {
855 private static class ProcessCanceller
implements Runnable
{
857 private final Process fProcess
;
858 private final IProgressMonitor fMonitor
;
860 private boolean fIsFinished
= false;
862 public ProcessCanceller(Process process
, IProgressMonitor monitor
) {
867 public void setFinished() {
874 while (!fIsFinished
) {
876 if (fMonitor
.isCanceled()) {
881 } catch (InterruptedException e
) {
888 public @NonNull String
getName() {
893 public boolean isUserDefined() {
894 return fIsUserDefined
;