1 /*******************************************************************************
2 * Copyright (c) 2011-2012 Ericsson, Ecole Polytechnique de Montreal and others
4 * All rights reserved. This program and the accompanying materials are made
5 * 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
9 * Contributors: Matthew Khouzam - Initial API and implementation
10 * Contributors: Alexandre Montplaisir - Initial API and implementation
11 *******************************************************************************/
13 package org
.eclipse
.linuxtools
.ctf
.core
.trace
;
16 import java
.io
.FileFilter
;
17 import java
.io
.FileInputStream
;
18 import java
.io
.IOException
;
19 import java
.io
.Serializable
;
20 import java
.nio
.ByteOrder
;
21 import java
.nio
.MappedByteBuffer
;
22 import java
.nio
.channels
.FileChannel
;
23 import java
.nio
.channels
.FileChannel
.MapMode
;
24 import java
.util
.Arrays
;
25 import java
.util
.Comparator
;
26 import java
.util
.HashMap
;
27 import java
.util
.Iterator
;
28 import java
.util
.LinkedList
;
29 import java
.util
.List
;
31 import java
.util
.Map
.Entry
;
33 import java
.util
.UUID
;
35 import org
.eclipse
.linuxtools
.ctf
.core
.event
.CTFClock
;
36 import org
.eclipse
.linuxtools
.ctf
.core
.event
.EventDeclaration
;
37 import org
.eclipse
.linuxtools
.ctf
.core
.event
.EventDefinition
;
38 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.ArrayDefinition
;
39 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.Definition
;
40 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.IDefinitionScope
;
41 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.IntegerDefinition
;
42 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.StructDeclaration
;
43 import org
.eclipse
.linuxtools
.ctf
.core
.event
.types
.StructDefinition
;
44 import org
.eclipse
.linuxtools
.internal
.ctf
.core
.event
.io
.BitBuffer
;
45 import org
.eclipse
.linuxtools
.internal
.ctf
.core
.event
.metadata
.exceptions
.ParseException
;
46 import org
.eclipse
.linuxtools
.internal
.ctf
.core
.trace
.Stream
;
47 import org
.eclipse
.linuxtools
.internal
.ctf
.core
.trace
.StreamInput
;
48 import org
.eclipse
.linuxtools
.internal
.ctf
.core
.trace
.StreamInputPacketIndex
;
51 * A CTF trace on the file system.
53 * Represents a trace on the filesystem. It is responsible of parsing the
54 * metadata, creating declarations data structures, indexing the event packets
55 * (in other words, all the work that can be shared between readers), but the
56 * actual reading of events is left to TraceReader.
58 * @author Matthew Khouzam
59 * @version $Revision: 1.0 $
61 public class CTFTrace
implements IDefinitionScope
{
63 // ------------------------------------------------------------------------
65 // ------------------------------------------------------------------------
67 private static final String OFFSET
= "offset"; //$NON-NLS-1$
74 * @see java.lang.Object#toString()
76 @SuppressWarnings("nls")
78 public String
toString() {
79 /* Only for debugging, shouldn't be externalized */
80 return "CTFTrace [path=" + path
+ ", major=" + major
+ ", minor="
81 + minor
+ ", uuid=" + uuid
+ "]";
85 * The trace directory on the filesystem.
87 private final File path
;
90 * The metadata parsing object.
92 private final Metadata metadata
;
95 * Major CTF version number
100 * Minor CTF version number
112 private ByteOrder byteOrder
;
115 * Packet header structure declaration
117 private StructDeclaration packetHeaderDecl
= null;
120 * Packet header structure definition
122 * This is only used when opening the trace files, to read the first packet
123 * header and see if they are valid trace files.
125 private StructDefinition packetHeaderDef
;
128 * Collection of streams contained in the trace.
130 private final HashMap
<Long
, Stream
> streams
;
133 * Collection of environment variables set by the tracer
135 private final HashMap
<String
, String
> environment
;
138 * Collection of all the clocks in a system.
140 private final HashMap
<String
, CTFClock
> clocks
;
142 /** FileChannels to the streams */
143 private final List
<FileChannel
> streamFileChannels
;
145 /** Handlers for the metadata files */
146 private final static FileFilter metadataFileFilter
= new MetadataFileFilter();
147 private final static Comparator
<File
> metadataComparator
= new MetadataComparator(); // $codepro.audit.disable
150 /** map of all the event types */
151 private final HashMap
<Long
,HashMap
<Long
, EventDeclaration
>> eventDecs
;
152 /** map of all the event types */
153 private final HashMap
<StreamInput
,HashMap
<Long
, EventDefinition
>> eventDefs
;
154 /** map of all the indexes */
155 private final HashMap
<StreamInput
, StreamInputPacketIndex
> indexes
;
159 // ------------------------------------------------------------------------
161 // ------------------------------------------------------------------------
167 * Filesystem path of the trace directory
168 * @throws CTFReaderException
169 * If no CTF trace was found at the path
171 public CTFTrace(String path
) throws CTFReaderException
{
172 this(new File(path
));
180 * Filesystem path of the trace directory.
181 * @throws CTFReaderException
182 * If no CTF trace was found at the path
184 public CTFTrace(File path
) throws CTFReaderException
{
186 this.metadata
= new Metadata(this);
188 /* Set up the internal containers for this trace */
189 streams
= new HashMap
<Long
, Stream
>();
190 environment
= new HashMap
<String
, String
>();
191 clocks
= new HashMap
<String
, CTFClock
>();
192 streamFileChannels
= new LinkedList
<FileChannel
>();
193 eventDecs
= new HashMap
<Long
, HashMap
<Long
, EventDeclaration
>>();
194 eventDefs
= new HashMap
<StreamInput
, HashMap
<Long
, EventDefinition
>>();
196 if (!this.path
.isDirectory()) {
197 throw new CTFReaderException("Path must be a valid directory"); //$NON-NLS-1$
200 /* Open and parse the metadata file */
203 /* Open all the trace files */
204 /* Create the definitions needed to read things from the files */
205 if (packetHeaderDecl
!= null) {
206 packetHeaderDef
= packetHeaderDecl
.createDefinition(this,
207 "packet.header"); //$NON-NLS-1$
210 /* List files not called metadata and not hidden. */
211 File
[] files
= path
.listFiles(metadataFileFilter
);
212 Arrays
.sort(files
, metadataComparator
);
213 indexes
= new HashMap
<StreamInput
, StreamInputPacketIndex
>();
214 /* Try to open each file */
215 for (File streamFile
: files
) {
216 openStreamInput(streamFile
);
219 /* Create their index */
220 for (Map
.Entry
<Long
, Stream
> stream
: streams
.entrySet()) {
221 Set
<StreamInput
> inputs
= stream
.getValue().getStreamInputs();
222 for (StreamInput s
: inputs
) {
226 Iterator
<Entry
<Long
, EventDeclaration
>> it
= s
.getStream()
227 .getEvents().entrySet().iterator();
228 while (it
.hasNext()) {
229 Map
.Entry
<Long
, EventDeclaration
> pairs
= it
.next();
230 Long eventNum
= pairs
.getKey();
231 EventDeclaration eventDec
= pairs
.getValue();
232 getEvents(s
.getStream().getId()).put(eventNum
, eventDec
);
244 protected void finalize() throws Throwable
{
245 /* If this trace gets closed, release the descriptors to the streams */
246 for (FileChannel fc
: streamFileChannels
) {
250 } catch (IOException e
) {
251 // do nothing it's ok, we tried to close it.
259 // ------------------------------------------------------------------------
260 // Getters/Setters/Predicates
261 // ------------------------------------------------------------------------
264 * Gets an event declaration hash map for a given streamID
267 * The ID of the stream from which to read
268 * @return The Hash map with the event declarations
270 public HashMap
<Long
, EventDeclaration
> getEvents(Long streamId
) {
271 return eventDecs
.get(streamId
);
275 * Gets an index for a given StreamInput
276 * @param id the StreamInput
279 public StreamInputPacketIndex
getIndex(StreamInput id
){
280 if(! indexes
.containsKey(id
)){
281 indexes
.put(id
, new StreamInputPacketIndex());
283 return indexes
.get(id
);
287 * Gets an event Declaration hashmap for a given StreamInput
288 * @param id the StreamInput
289 * @return the hashmap with the event definitions
291 public HashMap
<Long
, EventDefinition
> getEventDefs(StreamInput id
) {
292 if(! eventDefs
.containsKey(id
)){
293 eventDefs
.put(id
, new HashMap
<Long
, EventDefinition
>());
295 return eventDefs
.get(id
);
299 * Get an event by it's ID
302 * The ID of the stream from which to read
304 * the ID of the event
305 * @return the event declaration
307 public EventDeclaration
getEventType(long streamId
, long id
) {
308 return getEvents(streamId
).get(id
);
312 * Method getStream gets the stream for a given id
315 * Long the id of the stream
316 * @return Stream the stream that we need
318 public Stream
getStream(Long id
) {
319 return streams
.get(id
);
323 * Method nbStreams gets the number of available streams
325 * @return int the number of streams
327 public int nbStreams() {
328 return streams
.size();
332 * Method setMajor sets the major version of the trace (DO NOT USE)
335 * long the major version
337 public void setMajor(long major
) {
342 * Method setMinor sets the minor version of the trace (DO NOT USE)
345 * long the minor version
347 public void setMinor(long minor
) {
352 * Method setUUID sets the UUID of a trace
357 public void setUUID(UUID uuid
) {
362 * Method setByteOrder sets the byte order
365 * ByteOrder of the trace, can be little-endian or big-endian
367 public void setByteOrder(ByteOrder byteOrder
) {
368 this.byteOrder
= byteOrder
;
372 * Method setPacketHeader sets the packet header of a trace (DO NOT USE)
374 * @param packetHeader
375 * StructDeclaration the header in structdeclaration form
377 public void setPacketHeader(StructDeclaration packetHeader
) {
378 this.packetHeaderDecl
= packetHeader
;
382 * Method majortIsSet is the major version number set?
384 * @return boolean is the major set?
386 public boolean majortIsSet() {
387 return major
!= null;
391 * Method minorIsSet. is the minor version number set?
393 * @return boolean is the minor set?
395 public boolean minorIsSet() {
396 return minor
!= null;
400 * Method UUIDIsSet is the UUID set?
402 * @return boolean is the UUID set?
404 public boolean UUIDIsSet() {
409 * Method byteOrderIsSet is the byteorder set?
411 * @return boolean is the byteorder set?
413 public boolean byteOrderIsSet() {
414 return byteOrder
!= null;
418 * Method packetHeaderIsSet is the packet header set?
420 * @return boolean is the packet header set?
422 public boolean packetHeaderIsSet() {
423 return packetHeaderDecl
!= null;
427 * Method getUUID gets the trace UUID
429 * @return UUID gets the trace UUID
431 public UUID
getUUID() {
436 * Method getMajor gets the trace major version
438 * @return long gets the trace major version
440 public long getMajor() {
445 * Method getMinor gets the trace minor version
447 * @return long gets the trace minor version
449 public long getMinor() {
454 * Method getByteOrder gets the trace byte order
456 * @return ByteOrder gets the trace byte order
458 public ByteOrder
getByteOrder() {
463 * Method getPacketHeader gets the trace packet header
465 * @return StructDeclaration gets the trace packet header
467 public StructDeclaration
getPacketHeader() {
468 return packetHeaderDecl
;
472 * Method getTraceDirectory gets the trace directory
474 * @return File the path in "File" format.
476 public File
getTraceDirectory() {
481 * Method getStreams get all the streams in a map format.
483 * @return Map<Long,Stream> a map of all the streams.
485 public Map
<Long
, Stream
> getStreams() {
490 * Method getPath gets the path of the trace directory
492 * @return String the path of the trace directory, in string format.
493 * @see java.io.File#getPath()
496 public String
getPath() {
497 return path
.getPath();
500 // ------------------------------------------------------------------------
502 // ------------------------------------------------------------------------
505 * Tries to open the given file, reads the first packet header of the file
506 * and check its validity.
509 * A trace file in the trace directory.
511 * Which index in the class' streamFileChannel array this file
513 * @throws CTFReaderException
515 private void openStreamInput(File streamFile
) throws CTFReaderException
{
516 MappedByteBuffer byteBuffer
;
517 BitBuffer streamBitBuffer
;
521 if (!streamFile
.canRead()) {
522 throw new CTFReaderException("Unreadable file : " //$NON-NLS-1$
523 + streamFile
.getPath());
527 /* Open the file and get the FileChannel */
528 fc
= new FileInputStream(streamFile
).getChannel();
529 streamFileChannels
.add(fc
);
531 /* Map one memory page of 4 kiB */
532 byteBuffer
= fc
.map(MapMode
.READ_ONLY
, 0, 4096);
533 } catch (IOException e
) {
534 /* Shouldn't happen at this stage if every other check passed */
535 throw new CTFReaderException();
538 /* Create a BitBuffer with this mapping and the trace byte order */
539 streamBitBuffer
= new BitBuffer(byteBuffer
, this.getByteOrder());
541 if (packetHeaderDef
!= null) {
542 /* Read the packet header */
543 packetHeaderDef
.read(streamBitBuffer
);
545 /* Check the magic number */
546 IntegerDefinition magicDef
= (IntegerDefinition
) packetHeaderDef
547 .lookupDefinition("magic"); //$NON-NLS-1$
548 int magic
= (int) magicDef
.getValue();
549 if (magic
!= Utils
.CTF_MAGIC
) {
550 throw new CTFReaderException("CTF magic mismatch"); //$NON-NLS-1$
554 ArrayDefinition uuidDef
= (ArrayDefinition
) packetHeaderDef
555 .lookupDefinition("uuid"); //$NON-NLS-1$
556 if (uuidDef
!= null) {
557 byte[] uuidArray
= new byte[Utils
.UUID_LEN
];
559 for (int i
= 0; i
< Utils
.UUID_LEN
; i
++) {
560 IntegerDefinition uuidByteDef
= (IntegerDefinition
) uuidDef
562 uuidArray
[i
] = (byte) uuidByteDef
.getValue();
565 UUID otheruuid
= Utils
.makeUUID(uuidArray
);
567 if (!this.uuid
.equals(otheruuid
)) {
568 throw new CTFReaderException("UUID mismatch"); //$NON-NLS-1$
573 // TODO: it hasn't been checked that the stream_id field exists and
576 IntegerDefinition streamIDDef
= (IntegerDefinition
) packetHeaderDef
577 .lookupDefinition("stream_id"); //$NON-NLS-1$
578 assert (streamIDDef
!= null);
580 long streamID
= streamIDDef
.getValue();
582 /* Get the stream to which this trace file belongs to */
583 stream
= streams
.get(streamID
);
585 /* No packet header, we suppose there is only one stream */
586 stream
= streams
.get(null);
589 /* Create the stream input */
590 StreamInput streamInput
= new StreamInput(stream
, fc
, streamFile
);
592 /* Add a reference to the streamInput in the stream */
593 stream
.addInput(streamInput
);
597 * Looks up a definition from packet
602 * @see org.eclipse.linuxtools.ctf.core.event.types.IDefinitionScope#lookupDefinition(String)
605 public Definition
lookupDefinition(String lookupPath
) {
606 if (lookupPath
.equals("trace.packet.header")) { //$NON-NLS-1$
607 return packetHeaderDef
;
613 * Adds a new stream to the trace.
617 * @throws ParseException
618 * If there was some problem reading the metadata
620 public void addStream(Stream stream
) throws ParseException
{
623 * If there is already a stream without id (the null key), it must be
626 if (streams
.get(null) != null) {
627 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
631 * If the stream we try to add has the null key, it must be the onl * one. Thus, if the streams container is not empty, it is not valid.
633 if ((stream
.getId() == null) && (streams
.size() != 0)) {
634 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
637 /* If a stream with the same ID already exists, it is not valid. */
638 if (streams
.get(stream
.getId()) != null) {
639 throw new ParseException("Stream id already exists"); //$NON-NLS-1$
642 /* It should be ok now. */
643 streams
.put(stream
.getId(), stream
);
644 eventDecs
.put(stream
.getId(), new HashMap
<Long
,EventDeclaration
>());
648 * gets the Environment variables from the trace metadata (See CTF spec)
649 * @return the environment variables in a hashmap form (key value)
651 public HashMap
<String
, String
> getEnvironment() {
656 * Look up a specific environment variable
657 * @param key the key to look for
658 * @return the value of the variable, can be null.
660 public String
lookupEnvironment(String key
) {
661 return environment
.get(key
);
665 * Add a variable to the environment variables
666 * @param varName the name of the variable
667 * @param varValue the value of the variable
669 public void addEnvironmentVar(String varName
, String varValue
) {
670 environment
.put(varName
, varValue
);
674 * Add a clock to the clock list
675 * @param nameValue the name of the clock (full name with scope)
676 * @param ctfClock the clock
678 public void addClock(String nameValue
, CTFClock ctfClock
) {
679 clocks
.put(nameValue
, ctfClock
);
683 * gets the clock with a specific name
684 * @param name the name of the clock.
687 public CTFClock
getClock(String name
) {
688 return clocks
.get(name
);
691 private CTFClock singleClock
;
692 private long singleOffset
;
695 * gets the clock if there is only one. (this is 100% of the use cases as of June 2012)
698 public final CTFClock
getClock() {
699 if (clocks
.size() == 1) {
700 if (singleClock
== null) {
701 singleClock
= clocks
.get(clocks
.keySet().toArray()[0]);
702 if (singleClock
.getProperty(OFFSET
) != null) {
703 singleOffset
= (Long
) getClock().getProperty(OFFSET
);
705 singleClock
.addAttribute(OFFSET
, 0);
714 * gets the time offset of a clock with respect to UTC in nanoseconds
715 * @return the time offset of a clock with respect to UTC in nanoseconds
717 public final long getOffset() {
718 if (getClock() == null) {
725 * Does a given stream contain any events?
726 * @param id the stream ID
727 * @return true if the stream has events.
729 public boolean hasEvents(Long id
){
730 return eventDecs
.containsKey(id
);
734 * Add an event declaration map to the events map.
735 * @param id the id of a stream
736 * @return the hashmap containing events.
738 public HashMap
<Long
, EventDeclaration
> createEvents(Long id
){
739 HashMap
<Long
, EventDeclaration
> value
= eventDecs
.get(id
);
740 if( value
== null ) {
741 value
= new HashMap
<Long
, EventDeclaration
>();
742 eventDecs
.put(id
, value
);
749 class MetadataFileFilter
implements FileFilter
{
752 public boolean accept(File pathname
) {
753 if (pathname
.isDirectory()) {
756 if (pathname
.isHidden()) {
759 if (pathname
.getName().equals("metadata")) { //$NON-NLS-1$
767 class MetadataComparator
implements Comparator
<File
>, Serializable
{
769 private static final long serialVersionUID
= 1L;
772 public int compare(File o1
, File o2
) {
773 return o1
.getName().compareTo(o2
.getName());