Improve API.
[deliverable/tracecompass.git] / org.eclipse.linuxtools.ctf.core / src / org / eclipse / linuxtools / ctf / core / trace / CTFTrace.java
1 /*******************************************************************************
2 * Copyright (c) 2011-2012 Ericsson, Ecole Polytechnique de Montreal and others
3 *
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
8 *
9 * Contributors: Matthew Khouzam - Initial API and implementation
10 * Contributors: Alexandre Montplaisir - Initial API and implementation
11 *******************************************************************************/
12
13 package org.eclipse.linuxtools.ctf.core.trace;
14
15 import java.io.File;
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;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Set;
33 import java.util.UUID;
34
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.types.ArrayDefinition;
38 import org.eclipse.linuxtools.ctf.core.event.types.Definition;
39 import org.eclipse.linuxtools.ctf.core.event.types.IDefinitionScope;
40 import org.eclipse.linuxtools.ctf.core.event.types.IntegerDefinition;
41 import org.eclipse.linuxtools.ctf.core.event.types.StructDeclaration;
42 import org.eclipse.linuxtools.ctf.core.event.types.StructDefinition;
43 import org.eclipse.linuxtools.internal.ctf.core.Activator;
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
49 /**
50 * <b><u>CTFTrace</u></b>
51 * <p>
52 * Represents a trace on the filesystem. It is responsible of parsing the
53 * metadata, creating declarations data structures, indexing the event packets
54 * (in other words, all the work that can be shared between readers), but the
55 * actual reading of events is left to TraceReader.
56 *
57 * @author Matthew Khouzam
58 * @version $Revision: 1.0 $
59 */
60 public class CTFTrace implements IDefinitionScope {
61
62 // ------------------------------------------------------------------------
63 // Attributes
64 // ------------------------------------------------------------------------
65
66 /*
67 * (non-Javadoc)
68 *
69 * @see java.lang.Object#toString()
70 */
71 @SuppressWarnings("nls")
72 @Override
73 public String toString() {
74 /* Only for debugging, shouldn't be externalized */
75 return "CTFTrace [path=" + path + ", major=" + major + ", minor="
76 + minor + ", uuid=" + uuid + "]";
77 }
78
79 /**
80 * The trace directory on the filesystem.
81 */
82 private final File path;
83
84 /**
85 * The metadata parsing object.
86 */
87 private final Metadata metadata;
88
89 /**
90 * Major CTF version number
91 */
92 private Long major;
93
94 /**
95 * Minor CTF version number
96 */
97 private Long minor;
98
99 /**
100 * Trace UUID
101 */
102 private UUID uuid;
103
104 /**
105 * Trace byte order
106 */
107 private ByteOrder byteOrder;
108
109 /**
110 * Packet header structure declaration
111 */
112 private StructDeclaration packetHeaderDecl = null;
113
114 /**
115 * Packet header structure definition
116 *
117 * This is only used when opening the trace files, to read the first packet
118 * header and see if they are valid trace files.
119 */
120 private StructDefinition packetHeaderDef;
121
122 /**
123 * Collection of streams contained in the trace.
124 */
125 private final HashMap<Long, Stream> streams;
126
127 /**
128 * Collection of environment variables set by the tracer
129 */
130 private final HashMap<String, String> environment;
131
132 /**
133 * Collection of all the clocks in a system.
134 */
135 private final HashMap<String, CTFClock> clocks;
136
137 /** FileChannels to the streams */
138 private final List<FileChannel> streamFileChannels;
139
140 /** Handlers for the metadata files */
141 private final static FileFilter metadataFileFilter = new MetadataFileFilter();
142 private final static Comparator<File> metadataComparator = new MetadataComparator();
143
144 /** map of all the event types */
145 private final HashMap<Long, EventDeclaration> events;
146
147 // ------------------------------------------------------------------------
148 // Constructors
149 // ------------------------------------------------------------------------
150
151 /**
152 * Trace constructor.
153 *
154 * @param path
155 * Filesystem path of the trace directory.
156 * @throws IOException
157 */
158 public CTFTrace(String path) throws CTFReaderException {
159 this(new File(path));
160
161 }
162
163 /**
164 * Trace constructor.
165 *
166 * @param path
167 * Filesystem path of the trace directory.
168 * @throws CTFReaderException
169 */
170 public CTFTrace(File path) throws CTFReaderException {
171 this.path = path;
172 this.metadata = new Metadata(this);
173
174 /* Set up the internal containers for this trace */
175 streams = new HashMap<Long, Stream>();
176 environment = new HashMap<String, String>();
177 clocks = new HashMap<String, CTFClock>();
178 streamFileChannels = new LinkedList<FileChannel>();
179
180 if (!this.path.isDirectory()) {
181 throw new CTFReaderException("Path must be a valid directory"); //$NON-NLS-1$
182 }
183
184 /* Open and parse the metadata file */
185 metadata.parse();
186
187 if (Activator.getDefault() != null) {
188 Activator.getDefault().log(metadata.toString());
189 }
190
191 /* Open all the trace files */
192 /* Create the definitions needed to read things from the files */
193 if (packetHeaderDecl != null) {
194 packetHeaderDef = packetHeaderDecl.createDefinition(this,
195 "packet.header"); //$NON-NLS-1$
196 }
197
198 /* List files not called metadata and not hidden. */
199 File[] files = path.listFiles(metadataFileFilter);
200 Arrays.sort(files, metadataComparator);
201
202 /* Try to open each file */
203 for (File streamFile : files) {
204 openStreamInput(streamFile);
205 }
206 events = new HashMap<Long, EventDeclaration>();
207 /* Create their index */
208 for (Map.Entry<Long, Stream> stream : streams.entrySet()) {
209 Set<StreamInput> inputs = stream.getValue().getStreamInputs();
210 for (StreamInput s : inputs) {
211 /*
212 * Copy the events
213 */
214 Iterator<Entry<Long, EventDeclaration>> it = s.getStream()
215 .getEvents().entrySet().iterator();
216 while (it.hasNext()) {
217 Map.Entry<Long, EventDeclaration> pairs = it.next();
218 Long eventNum = pairs.getKey();
219 EventDeclaration eventDec = pairs.getValue();
220 events.put(eventNum, eventDec);
221 }
222
223 /*
224 * index the trace
225 */
226 s.createIndex();
227 }
228 }
229 }
230
231 @Override
232 protected void finalize() {
233 /* If this trace gets closed, release the descriptors to the streams */
234 for (FileChannel fc : streamFileChannels) {
235 if (fc != null) {
236 try {
237 fc.close();
238 } catch (IOException e) {
239 // do nothing it's ok, we tried to close it.
240 }
241 }
242 }
243 }
244
245 // ------------------------------------------------------------------------
246 // Getters/Setters/Predicates
247 // ------------------------------------------------------------------------
248
249 /**
250 * Get an event by it's ID
251 *
252 * @param id
253 * the ID of the event
254 * @return the event declaration
255 */
256 public EventDeclaration getEventType(long id) {
257 return events.get(id);
258 }
259
260 /**
261 * Get the number of events in the trace so far.
262 *
263 * @return the number of events in the trace
264 */
265 public int getNbEventTypes() {
266 return events.size();
267 }
268
269 /**
270 * Method getStream gets the stream for a given id
271 *
272 * @param id
273 * Long the id of the stream
274 * @return Stream the stream that we need
275 */
276 public Stream getStream(Long id) {
277 return streams.get(id);
278 }
279
280 /**
281 * Method nbStreams gets the number of available streams
282 *
283 * @return int the number of streams
284 */
285 public int nbStreams() {
286 return streams.size();
287 }
288
289 /**
290 * Method setMajor sets the major version of the trace (DO NOT USE)
291 *
292 * @param major
293 * long the major version
294 */
295 public void setMajor(long major) {
296 this.major = major;
297 }
298
299 /**
300 * Method setMinor sets the minor version of the trace (DO NOT USE)
301 *
302 * @param minor
303 * long the minor version
304 */
305 public void setMinor(long minor) {
306 this.minor = minor;
307 }
308
309 /**
310 * Method setUUID sets the UUID of a trace
311 *
312 * @param uuid
313 * UUID
314 */
315 public void setUUID(UUID uuid) {
316 this.uuid = uuid;
317 }
318
319 /**
320 * Method setByteOrder sets the byte order
321 *
322 * @param byteOrder
323 * ByteOrder of the trace, can be little-endian or big-endian
324 */
325 public void setByteOrder(ByteOrder byteOrder) {
326 this.byteOrder = byteOrder;
327 }
328
329 /**
330 * Method setPacketHeader sets the packet header of a trace (DO NOT USE)
331 *
332 * @param packetHeader
333 * StructDeclaration the header in structdeclaration form
334 */
335 public void setPacketHeader(StructDeclaration packetHeader) {
336 this.packetHeaderDecl = packetHeader;
337 }
338
339 /**
340 * Method majortIsSet is the major version number set?
341 *
342 * @return boolean is the major set?
343 */
344 public boolean majortIsSet() {
345 return major != null;
346 }
347
348 /**
349 * Method minorIsSet. is the minor version number set?
350 *
351 * @return boolean is the minor set?
352 */
353 public boolean minorIsSet() {
354 return minor != null;
355 }
356
357 /**
358 * Method UUIDIsSet is the UUID set?
359 *
360 * @return boolean is the UUID set?
361 */
362 public boolean UUIDIsSet() {
363 return uuid != null;
364 }
365
366 /**
367 * Method byteOrderIsSet is the byteorder set?
368 *
369 * @return boolean is the byteorder set?
370 */
371 public boolean byteOrderIsSet() {
372 return byteOrder != null;
373 }
374
375 /**
376 * Method packetHeaderIsSet is the packet header set?
377 *
378 * @return boolean is the packet header set?
379 */
380 public boolean packetHeaderIsSet() {
381 return packetHeaderDecl != null;
382 }
383
384 /**
385 * Method getUUID gets the trace UUID
386 *
387 * @return UUID gets the trace UUID
388 */
389 public UUID getUUID() {
390 return uuid;
391 }
392
393 /**
394 * Method getMajor gets the trace major version
395 *
396 * @return long gets the trace major version
397 */
398 public long getMajor() {
399 return major;
400 }
401
402 /**
403 * Method getMinor gets the trace minor version
404 *
405 * @return long gets the trace minor version
406 */
407 public long getMinor() {
408 return minor;
409 }
410
411 /**
412 * Method getByteOrder gets the trace byte order
413 *
414 * @return ByteOrder gets the trace byte order
415 */
416 public ByteOrder getByteOrder() {
417 return byteOrder;
418 }
419
420 /**
421 * Method getPacketHeader gets the trace packet header
422 *
423 * @return StructDeclaration gets the trace packet header
424 */
425 public StructDeclaration getPacketHeader() {
426 return packetHeaderDecl;
427 }
428
429 /**
430 * Method getTraceDirectory gets the trace directory
431 *
432 * @return File the path in "File" format.
433 */
434 public File getTraceDirectory() {
435 return path;
436 }
437
438 /**
439 * Method getStreams get all the streams in a map format.
440 *
441 * @return Map<Long,Stream> a map of all the streams.
442 */
443 public Map<Long, Stream> getStreams() {
444 return streams;
445 }
446
447 /**
448 * Method getPath gets the path of the trace directory
449 *
450 * @return String the path of the trace directory, in string format.
451 * @see java.io.File#getPath()
452 */
453 @Override
454 public String getPath() {
455 return path.getPath();
456 }
457
458 // ------------------------------------------------------------------------
459 // Operations
460 // ------------------------------------------------------------------------
461
462 /**
463 * Tries to open the given file, reads the first packet header of the file
464 * and check its validity.
465 *
466 * @param streamFile
467 * A trace file in the trace directory.
468 * @param index
469 * Which index in the class' streamFileChannel array this file
470 * must use
471 * @throws CTFReaderException
472 */
473 private void openStreamInput(File streamFile) throws CTFReaderException {
474 MappedByteBuffer byteBuffer;
475 BitBuffer streamBitBuffer;
476 Stream stream;
477 FileChannel fc;
478
479 if (!streamFile.canRead()) {
480 throw new CTFReaderException("Unreadable file : " //$NON-NLS-1$
481 + streamFile.getPath());
482 }
483
484 try {
485 /* Open the file and get the FileChannel */
486 fc = new FileInputStream(streamFile).getChannel();
487 streamFileChannels.add(fc);
488
489 /* Map one memory page of 4 kiB */
490 byteBuffer = fc.map(MapMode.READ_ONLY, 0, 4096);
491 } catch (IOException e) {
492 /* Shouldn't happen at this stage if every other check passed */
493 throw new CTFReaderException();
494 }
495
496 /* Create a BitBuffer with this mapping and the trace byte order */
497 streamBitBuffer = new BitBuffer(byteBuffer, this.getByteOrder());
498
499 if (packetHeaderDef != null) {
500 /* Read the packet header */
501 packetHeaderDef.read(streamBitBuffer);
502
503 /* Check the magic number */
504 IntegerDefinition magicDef = (IntegerDefinition) packetHeaderDef
505 .lookupDefinition("magic"); //$NON-NLS-1$
506 int magic = (int) magicDef.getValue();
507 if (magic != Utils.CTF_MAGIC) {
508 throw new CTFReaderException("CTF magic mismatch"); //$NON-NLS-1$
509 }
510
511 /* Check UUID */
512 ArrayDefinition uuidDef = (ArrayDefinition) packetHeaderDef
513 .lookupDefinition("uuid"); //$NON-NLS-1$
514 assert ((uuidDef != null) && (uuidDef.getDeclaration().getLength() == Utils.UUID_LEN));
515 if (uuidDef != null) {
516 byte[] uuidArray = new byte[Utils.UUID_LEN];
517
518 for (int i = 0; i < Utils.UUID_LEN; i++) {
519 IntegerDefinition uuidByteDef = (IntegerDefinition) uuidDef
520 .getElem(i);
521 uuidArray[i] = (byte) uuidByteDef.getValue();
522 }
523
524 UUID otheruuid = Utils.makeUUID(uuidArray);
525
526 if (!this.uuid.equals(otheruuid)) {
527 throw new CTFReaderException("UUID mismatch"); //$NON-NLS-1$
528 }
529 }
530
531 /* Read stream ID */
532 // TODO: it hasn't been checked that the stream_id field exists and
533 // is an unsigned
534 // integer
535 IntegerDefinition streamIDDef = (IntegerDefinition) packetHeaderDef
536 .lookupDefinition("stream_id"); //$NON-NLS-1$
537 assert (streamIDDef != null);
538
539 long streamID = streamIDDef.getValue();
540
541 /* Get the stream to which this trace file belongs to */
542 stream = streams.get(streamID);
543 } else {
544 /* No packet header, we suppose there is only one stream */
545 stream = streams.get(null);
546 }
547
548 /* Create the stream input */
549 StreamInput streamInput = new StreamInput(stream, fc, streamFile);
550
551 /* Add a reference to the streamInput in the stream */
552 stream.addInput(streamInput);
553 }
554
555 /**
556 * Looks up a definition from packet
557 *
558 * @param lookupPath
559 * String
560 * @return Definition
561 * @see org.eclipse.linuxtools.ctf.core.event.types.IDefinitionScope#lookupDefinition(String)
562 */
563 @Override
564 public Definition lookupDefinition(String lookupPath) {
565 if (lookupPath.equals("trace.packet.header")) { //$NON-NLS-1$
566 return packetHeaderDef;
567 }
568 return null;
569 }
570
571 /**
572 * Adds a new stream to the trace.
573 *
574 * @param stream
575 * A stream object.
576 *
577 * @throws ParseException
578 */
579 public void addStream(Stream stream) throws ParseException {
580
581 /*
582 * If there is already a stream without id (the null key), it must be
583 * the only one
584 */
585 if (streams.get(null) != null) {
586 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
587 }
588
589 /*
590 * If the stream we try to add has the null key, it must be the only
591 * one. Thus, if the streams container is not empty, it is not valid.
592 */
593 if ((stream.getId() == null) && (streams.size() != 0)) {
594 throw new ParseException("Stream without id with multiple streams"); //$NON-NLS-1$
595 }
596
597 /* If a stream with the same ID already exists, it is not valid. */
598 if (streams.get(stream.getId()) != null) {
599 throw new ParseException("Stream id already exists"); //$NON-NLS-1$
600 }
601
602 /* It should be ok now. */
603 streams.put(stream.getId(), stream);
604 }
605
606 public HashMap<String, String> getEnvironment() {
607 return environment;
608 }
609
610 public String lookupEnvironment(String key) {
611 return environment.get(key);
612 }
613
614 public void addEnvironmentVar(String varName, String varValue) {
615 environment.put(varName, varValue);
616 }
617
618 public void addClock(String nameValue, CTFClock ctfClock) {
619 clocks.put(nameValue, ctfClock);
620 }
621
622 public CTFClock getClock(String name) {
623 return clocks.get(name);
624 }
625
626 public CTFClock getClock() {
627 if (clocks.size() == 1) {
628 String key = (String) clocks.keySet().toArray()[0];
629 return clocks.get(key);
630 }
631 return null;
632 }
633
634 public long getOffset() {
635 if (getClock() == null) {
636 return 0;
637 }
638 return (Long) getClock().getProperty("offset"); //$NON-NLS-1$
639 }
640
641 }
642
643 class MetadataFileFilter implements FileFilter {
644
645 @Override
646 public boolean accept(File pathname) {
647 if (pathname.isDirectory()) {
648 return false;
649 }
650 if (pathname.isHidden()) {
651 return false;
652 }
653 if (pathname.getName().equals("metadata")) { //$NON-NLS-1$
654 return false;
655 }
656 return true;
657 }
658
659 }
660
661 class MetadataComparator implements Comparator<File>, Serializable {
662
663 @Override
664 public int compare(File o1, File o2) {
665 return o1.getName().compareTo(o2.getName());
666 }
667 }
This page took 0.046137 seconds and 5 git commands to generate.