1 /*******************************************************************************
2 * Copyright (c) 2010, 2016 Ericsson
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
10 * Patrick Tasse - Initial API and implementation
11 * Bernd Hufmann - Add trace type id handling
12 *******************************************************************************/
14 package org
.eclipse
.tracecompass
.tmf
.core
.parsers
.custom
;
16 import static org
.eclipse
.tracecompass
.common
.core
.NonNullUtils
.checkNotNull
;
19 import java
.io
.FileNotFoundException
;
20 import java
.io
.IOException
;
21 import java
.nio
.ByteBuffer
;
22 import java
.util
.HashMap
;
23 import java
.util
.Iterator
;
24 import java
.util
.List
;
25 import java
.util
.Map
.Entry
;
26 import java
.util
.regex
.Matcher
;
28 import org
.eclipse
.core
.resources
.IProject
;
29 import org
.eclipse
.core
.resources
.IResource
;
30 import org
.eclipse
.core
.runtime
.IStatus
;
31 import org
.eclipse
.core
.runtime
.Status
;
32 import org
.eclipse
.jdt
.annotation
.NonNull
;
33 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.Activator
;
34 import org
.eclipse
.tracecompass
.internal
.tmf
.core
.parsers
.custom
.CustomEventAspects
;
35 import org
.eclipse
.tracecompass
.tmf
.core
.event
.ITmfEvent
;
36 import org
.eclipse
.tracecompass
.tmf
.core
.event
.ITmfEventField
;
37 import org
.eclipse
.tracecompass
.tmf
.core
.event
.aspect
.ITmfEventAspect
;
38 import org
.eclipse
.tracecompass
.tmf
.core
.exceptions
.TmfTraceException
;
39 import org
.eclipse
.tracecompass
.tmf
.core
.io
.BufferedRandomAccessFile
;
40 import org
.eclipse
.tracecompass
.tmf
.core
.parsers
.custom
.CustomTxtTraceDefinition
.InputLine
;
41 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalHandler
;
42 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceRangeUpdatedSignal
;
43 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimestamp
;
44 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfContext
;
45 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfContext
;
46 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTrace
;
47 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceUtils
;
48 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TraceValidationStatus
;
49 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.ITmfPersistentlyIndexable
;
50 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.ITmfTraceIndexer
;
51 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.TmfBTreeTraceIndexer
;
52 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.checkpoint
.ITmfCheckpoint
;
53 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.checkpoint
.TmfCheckpoint
;
54 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.location
.ITmfLocation
;
55 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.location
.TmfLongLocation
;
58 * Base class for custom plain text traces.
60 * @author Patrick Tassé
62 public class CustomTxtTrace
extends TmfTrace
implements ITmfPersistentlyIndexable
{
64 private static final TmfLongLocation NULL_LOCATION
= new TmfLongLocation(-1L);
65 private static final int DEFAULT_CACHE_SIZE
= 100;
66 private static final int MAX_LINES
= 100;
67 private static final int MAX_CONFIDENCE
= 100;
69 private final CustomTxtTraceDefinition fDefinition
;
70 private final ITmfEventField fRootField
;
71 private BufferedRandomAccessFile fFile
;
72 private final @NonNull String fTraceTypeId
;
74 private static final char SEPARATOR
= ':';
75 private static final String CUSTOM_TXT_TRACE_TYPE_PREFIX
= "custom.txt.trace" + SEPARATOR
; //$NON-NLS-1$
76 private static final String LINUX_TOOLS_CUSTOM_TXT_TRACE_TYPE_PREFIX
= "org.eclipse.linuxtools.tmf.core.parsers.custom.CustomTxtTrace" + SEPARATOR
; //$NON-NLS-1$
77 private static final String EARLY_TRACE_COMPASS_CUSTOM_TXT_TRACE_TYPE_PREFIX
= "org.eclipse.tracecompass.tmf.core.parsers.custom.CustomTxtTrace" + SEPARATOR
; //$NON-NLS-1$
83 * Text trace definition
85 public CustomTxtTrace(final CustomTxtTraceDefinition definition
) {
86 fDefinition
= definition
;
87 fRootField
= CustomEventType
.getRootField(definition
);
88 fTraceTypeId
= buildTraceTypeId(definition
.categoryName
, definition
.definitionName
);
89 setCacheSize(DEFAULT_CACHE_SIZE
);
98 * Text trace definition
100 * Path to the trace file
103 * @throws TmfTraceException
104 * If we couldn't open the trace at 'path'
106 public CustomTxtTrace(final IResource resource
,
107 final CustomTxtTraceDefinition definition
, final String path
,
108 final int cacheSize
) throws TmfTraceException
{
110 setCacheSize((cacheSize
> 0) ? cacheSize
: DEFAULT_CACHE_SIZE
);
111 initTrace(resource
, path
, CustomTxtEvent
.class);
115 public void initTrace(final IResource resource
, final String path
, final Class
<?
extends ITmfEvent
> eventType
) throws TmfTraceException
{
116 super.initTrace(resource
, path
, eventType
);
120 private void initFile() throws TmfTraceException
{
123 fFile
= new BufferedRandomAccessFile(getPath(), "r"); //$NON-NLS-1$
124 } catch (IOException e
) {
125 throw new TmfTraceException(e
.getMessage(), e
);
130 public synchronized void dispose() {
135 private void closeFile() {
139 } catch (IOException e
) {
147 public ITmfTraceIndexer
getIndexer() {
148 return super.getIndexer();
152 public Iterable
<ITmfEventAspect
<?
>> getEventAspects() {
153 return CustomEventAspects
.generateAspects(fDefinition
);
157 public synchronized TmfContext
seekEvent(final ITmfLocation location
) {
158 final CustomTxtTraceContext context
= new CustomTxtTraceContext(NULL_LOCATION
, ITmfContext
.UNKNOWN_RANK
);
159 if (NULL_LOCATION
.equals(location
) || fFile
== null) {
163 if (location
== null) {
165 } else if (location
.getLocationInfo() instanceof Long
) {
166 fFile
.seek((Long
) location
.getLocationInfo());
168 long rawPos
= fFile
.getFilePointer();
169 String line
= fFile
.getNextLine();
170 while (line
!= null) {
171 for (final InputLine input
: getFirstLines()) {
172 final Matcher matcher
= input
.getPattern().matcher(line
);
173 if (matcher
.matches()) {
174 context
.setLocation(new TmfLongLocation(rawPos
));
175 context
.firstLineMatcher
= matcher
;
176 context
.firstLine
= line
;
177 context
.nextLineLocation
= fFile
.getFilePointer();
178 context
.inputLine
= input
;
182 rawPos
= fFile
.getFilePointer();
183 line
= fFile
.getNextLine();
186 } catch (final FileNotFoundException e
) {
187 Activator
.logError("Error seeking event. File not found: " + getPath(), e
); //$NON-NLS-1$
189 } catch (final IOException e
) {
190 Activator
.logError("Error seeking event. File: " + getPath(), e
); //$NON-NLS-1$
197 public synchronized TmfContext
seekEvent(final double ratio
) {
199 return new CustomTxtTraceContext(NULL_LOCATION
, ITmfContext
.UNKNOWN_RANK
);
202 long pos
= Math
.round(ratio
* fFile
.length());
205 if (fFile
.read() == '\n') {
210 final ITmfLocation location
= new TmfLongLocation(pos
);
211 final TmfContext context
= seekEvent(location
);
212 context
.setRank(ITmfContext
.UNKNOWN_RANK
);
214 } catch (final IOException e
) {
215 Activator
.logError("Error seeking event. File: " + getPath(), e
); //$NON-NLS-1$
216 return new CustomTxtTraceContext(NULL_LOCATION
, ITmfContext
.UNKNOWN_RANK
);
221 public synchronized double getLocationRatio(final ITmfLocation location
) {
226 if (location
.getLocationInfo() instanceof Long
) {
227 return ((Long
) location
.getLocationInfo()).doubleValue() / fFile
.length();
229 } catch (final IOException e
) {
230 Activator
.logError("Error seeking event. File: " + getPath(), e
); //$NON-NLS-1$
236 public ITmfLocation
getCurrentLocation() {
237 // TODO Auto-generated method stub
242 public synchronized CustomTxtEvent
parseEvent(final ITmfContext tmfContext
) {
243 ITmfContext context
= seekEvent(tmfContext
.getLocation());
244 return parse(context
);
248 public synchronized CustomTxtEvent
getNext(final ITmfContext context
) {
249 final ITmfContext savedContext
= new TmfContext(context
.getLocation(), context
.getRank());
250 final CustomTxtEvent event
= parse(context
);
252 updateAttributes(savedContext
, event
);
253 context
.increaseRank();
258 private synchronized CustomTxtEvent
parse(final ITmfContext tmfContext
) {
262 if (!(tmfContext
instanceof CustomTxtTraceContext
)) {
266 final CustomTxtTraceContext context
= (CustomTxtTraceContext
) tmfContext
;
267 ITmfLocation location
= context
.getLocation();
268 if (location
== null || !(location
.getLocationInfo() instanceof Long
) || NULL_LOCATION
.equals(location
)) {
272 CustomTxtEvent event
= parseFirstLine(context
);
274 final HashMap
<InputLine
, Integer
> countMap
= new HashMap
<>();
275 InputLine currentInput
= null;
276 if (context
.inputLine
.childrenInputs
!= null && context
.inputLine
.childrenInputs
.size() > 0) {
277 currentInput
= context
.inputLine
.childrenInputs
.get(0);
278 countMap
.put(currentInput
, 0);
282 if (fFile
.getFilePointer() != context
.nextLineLocation
) {
283 fFile
.seek(context
.nextLineLocation
);
285 long rawPos
= fFile
.getFilePointer();
286 String line
= fFile
.getNextLine();
287 while (line
!= null) {
288 boolean processed
= false;
289 if (currentInput
== null) {
290 for (final InputLine input
: getFirstLines()) {
291 final Matcher matcher
= input
.getPattern().matcher(line
);
292 if (matcher
.matches()) {
293 context
.setLocation(new TmfLongLocation(rawPos
));
294 context
.firstLineMatcher
= matcher
;
295 context
.firstLine
= line
;
296 context
.nextLineLocation
= fFile
.getFilePointer();
297 context
.inputLine
= input
;
302 if (checkNotNull(countMap
.get(currentInput
)) >= currentInput
.getMinCount()) {
303 final List
<InputLine
> nextInputs
= currentInput
.getNextInputs(countMap
);
304 if (nextInputs
.size() == 0 || nextInputs
.get(nextInputs
.size() - 1).getMinCount() == 0) {
305 for (final InputLine input
: getFirstLines()) {
306 final Matcher matcher
= input
.getPattern().matcher(line
);
307 if (matcher
.matches()) {
308 context
.setLocation(new TmfLongLocation(rawPos
));
309 context
.firstLineMatcher
= matcher
;
310 context
.firstLine
= line
;
311 context
.nextLineLocation
= fFile
.getFilePointer();
312 context
.inputLine
= input
;
317 for (final InputLine input
: nextInputs
) {
318 final Matcher matcher
= input
.getPattern().matcher(line
);
319 if (matcher
.matches()) {
320 event
.processGroups(input
, matcher
);
321 currentInput
= input
;
322 if (countMap
.get(currentInput
) == null) {
323 countMap
.put(currentInput
, 1);
325 countMap
.put(currentInput
, checkNotNull(countMap
.get(currentInput
)) + 1);
327 Iterator
<InputLine
> iter
= countMap
.keySet().iterator();
328 while (iter
.hasNext()) {
329 final InputLine inputLine
= iter
.next();
330 if (inputLine
.level
> currentInput
.level
) {
334 if (currentInput
.childrenInputs
!= null && currentInput
.childrenInputs
.size() > 0) {
335 currentInput
= currentInput
.childrenInputs
.get(0);
336 countMap
.put(currentInput
, 0);
337 } else if (checkNotNull(countMap
.get(currentInput
)) >= currentInput
.getMaxCount()) {
338 if (currentInput
.getNextInputs(countMap
).size() > 0) {
339 currentInput
= currentInput
.getNextInputs(countMap
).get(0);
340 if (countMap
.get(currentInput
) == null) {
341 countMap
.put(currentInput
, 0);
343 iter
= countMap
.keySet().iterator();
344 while (iter
.hasNext()) {
345 final InputLine inputLine
= iter
.next();
346 if (inputLine
.level
> currentInput
.level
) {
359 if (!processed
&& currentInput
!= null) {
360 final Matcher matcher
= currentInput
.getPattern().matcher(line
);
361 if (matcher
.matches()) {
362 event
.processGroups(currentInput
, matcher
);
363 countMap
.put(currentInput
, checkNotNull(countMap
.get(currentInput
)) + 1);
364 if (currentInput
.childrenInputs
!= null && currentInput
.childrenInputs
.size() > 0) {
365 currentInput
= currentInput
.childrenInputs
.get(0);
366 countMap
.put(currentInput
, 0);
367 } else if (checkNotNull(countMap
.get(currentInput
)) >= currentInput
.getMaxCount()) {
368 if (currentInput
.getNextInputs(countMap
).size() > 0) {
369 currentInput
= currentInput
.getNextInputs(countMap
).get(0);
370 if (countMap
.get(currentInput
) == null) {
371 countMap
.put(currentInput
, 0);
373 final Iterator
<InputLine
> iter
= countMap
.keySet().iterator();
374 while (iter
.hasNext()) {
375 final InputLine inputLine
= iter
.next();
376 if (inputLine
.level
> currentInput
.level
) {
385 ((StringBuffer
) event
.getContentValue()).append("\n").append(line
); //$NON-NLS-1$
388 rawPos
= fFile
.getFilePointer();
389 line
= fFile
.getNextLine();
391 } catch (final IOException e
) {
392 Activator
.logError("Error seeking event. File: " + getPath(), e
); //$NON-NLS-1$
394 for (final Entry
<InputLine
, Integer
> entry
: countMap
.entrySet()) {
395 if (entry
.getValue() < entry
.getKey().getMinCount()) {
399 context
.setLocation(NULL_LOCATION
);
404 * @return The first few lines of the text file
406 public List
<InputLine
> getFirstLines() {
407 return fDefinition
.inputs
;
411 * Parse the first line of the trace (to recognize the type).
415 * @return The first event
417 public CustomTxtEvent
parseFirstLine(final CustomTxtTraceContext context
) {
418 CustomTxtEventType eventType
= new CustomTxtEventType(checkNotNull(fDefinition
.definitionName
), fRootField
);
419 final CustomTxtEvent event
= new CustomTxtEvent(fDefinition
, this, TmfTimestamp
.ZERO
, eventType
);
420 event
.processGroups(context
.inputLine
, context
.firstLineMatcher
);
421 event
.setContent(new CustomEventContent(event
, new StringBuffer(context
.firstLine
)));
426 * Get the trace definition.
428 * @return The trace definition
430 public CustomTraceDefinition
getDefinition() {
437 * The default implementation computes the confidence as the percentage of
438 * lines in the first 100 lines of the file which match any of the root
439 * input line patterns.
442 public IStatus
validate(IProject project
, String path
) {
443 File file
= new File(path
);
444 if (!file
.exists() || !file
.isFile() || !file
.canRead()) {
445 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, Messages
.CustomTrace_FileNotFound
+ ": " + path
); //$NON-NLS-1$
449 if (!TmfTraceUtils
.isText(file
)) {
450 return new TraceValidationStatus(confidence
, Activator
.PLUGIN_ID
);
452 } catch (IOException e
) {
453 Activator
.logError("Error validating file: " + path
, e
); //$NON-NLS-1$
454 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, "IOException validating file: " + path
, e
); //$NON-NLS-1$
456 try (BufferedRandomAccessFile rafile
= new BufferedRandomAccessFile(path
, "r")) { //$NON-NLS-1$
458 double matches
= 0.0;
459 String line
= rafile
.getNextLine();
461 while ((line
!= null) && (lineCount
++ < MAX_LINES
)) {
462 for (InputLine inputLine
: fDefinition
.inputs
) {
463 Matcher matcher
= inputLine
.getPattern().matcher(line
);
464 if (matcher
.matches()) {
465 int groupCount
= matcher
.groupCount();
466 matches
+= (1.0 + groupCount
/ ((double) groupCount
+ 1));
470 confidence
= (int) (MAX_CONFIDENCE
* matches
/ lineCount
);
471 line
= rafile
.getNextLine();
473 } catch (IOException e
) {
474 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, "IOException validating file: " + path
, e
); //$NON-NLS-1$
476 return new TraceValidationStatus(confidence
, Activator
.PLUGIN_ID
);
479 private static int fCheckpointSize
= -1;
482 public synchronized int getCheckpointSize() {
483 if (fCheckpointSize
== -1) {
484 TmfCheckpoint c
= new TmfCheckpoint(TmfTimestamp
.ZERO
, new TmfLongLocation(0L), 0);
485 ByteBuffer b
= ByteBuffer
.allocate(ITmfCheckpoint
.MAX_SERIALIZE_SIZE
);
488 fCheckpointSize
= b
.position();
491 return fCheckpointSize
;
495 public ITmfLocation
restoreLocation(ByteBuffer bufferIn
) {
496 return new TmfLongLocation(bufferIn
);
500 protected ITmfTraceIndexer
createIndexer(int interval
) {
501 return new TmfBTreeTraceIndexer(this, interval
);
505 public String
getTraceTypeId() {
510 * Build the trace type id for a custom text trace
514 * @param definitionName
515 * the definition name
516 * @return the trace type id
518 public static @NonNull String
buildTraceTypeId(String category
, String definitionName
) {
519 return CUSTOM_TXT_TRACE_TYPE_PREFIX
+ category
+ SEPARATOR
+ definitionName
;
523 * Checks whether the given trace type ID is a custom text trace type ID
526 * the trace type ID to check
527 * @return <code>true</code> if it's a custom text trace type ID else <code>false</code>
529 public static boolean isCustomTraceTypeId(@NonNull String traceTypeId
) {
530 return traceTypeId
.startsWith(CUSTOM_TXT_TRACE_TYPE_PREFIX
);
534 * This methods builds a trace type ID from a given ID taking into
535 * consideration any format changes that were done for the IDs of custom
536 * text traces. For example, such format change took place when moving to
537 * Trace Compass. Trace type IDs that are part of the plug-in extension for
538 * trace types won't be changed.
540 * This method is useful for IDs that were persisted in the workspace before
541 * the format changes (e.g. in the persistent properties of a trace
544 * It ensures backwards compatibility of the workspace for custom text
548 * the legacy trace type ID
549 * @return the trace type id in Trace Compass format
551 public static @NonNull String
buildCompatibilityTraceTypeId(@NonNull String traceTypeId
) {
552 // Handle early Trace Compass custom text trace type IDs
553 if (traceTypeId
.startsWith(EARLY_TRACE_COMPASS_CUSTOM_TXT_TRACE_TYPE_PREFIX
)) {
554 return CUSTOM_TXT_TRACE_TYPE_PREFIX
+ traceTypeId
.substring(EARLY_TRACE_COMPASS_CUSTOM_TXT_TRACE_TYPE_PREFIX
.length());
557 // Handle Linux Tools custom text trace type IDs (with and without category)
558 int index
= traceTypeId
.lastIndexOf(SEPARATOR
);
559 if ((index
!= -1) && (traceTypeId
.startsWith(LINUX_TOOLS_CUSTOM_TXT_TRACE_TYPE_PREFIX
))) {
560 String definitionName
= index
< traceTypeId
.length() ? traceTypeId
.substring(index
+ 1) : ""; //$NON-NLS-1$
561 if (traceTypeId
.contains(CustomTxtTrace
.class.getSimpleName() + SEPARATOR
) && traceTypeId
.indexOf(SEPARATOR
) == index
) {
562 return buildTraceTypeId(CustomTxtTraceDefinition
.CUSTOM_TXT_CATEGORY
, definitionName
);
564 return CUSTOM_TXT_TRACE_TYPE_PREFIX
+ traceTypeId
.substring(LINUX_TOOLS_CUSTOM_TXT_TRACE_TYPE_PREFIX
.length());
571 public void traceRangeUpdated(TmfTraceRangeUpdatedSignal signal
) {
572 if (signal
.getTrace() == this) {
574 synchronized (this) {
575 // Reset the file handle in case it has reached the end of the
576 // file already. Otherwise, it will not be able to read new data
577 // pass the previous end.
580 } catch (TmfTraceException e
) {
581 Activator
.logError(e
.getLocalizedMessage(), e
);
584 super.traceRangeUpdated(signal
);