ctf: Introduce IPacketReader
[deliverable/tracecompass.git] / ctf / org.eclipse.tracecompass.ctf.core / src / org / eclipse / tracecompass / ctf / core / trace / CTFTraceReader.java
CommitLineData
866e5b51 1/*******************************************************************************
93a45b54 2 * Copyright (c) 2011, 2014 Ericsson, Ecole Polytechnique de Montreal and others
866e5b51
FC
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 *
4311ac8b
MAL
9 * Contributors:
10 * Matthew Khouzam - Initial API and implementation
11 * Alexandre Montplaisir - Initial API and implementation
866e5b51
FC
12 *******************************************************************************/
13
f357bcd4 14package org.eclipse.tracecompass.ctf.core.trace;
866e5b51 15
90cefe9f
MK
16import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;
17
b3151232 18import java.io.IOException;
0594c61c 19import java.util.ArrayList;
6a0ec7bc 20import java.util.Collections;
fe75d403 21import java.util.HashSet;
0594c61c 22import java.util.List;
866e5b51
FC
23import java.util.PriorityQueue;
24import java.util.Set;
866e5b51 25
680f9173 26import org.eclipse.tracecompass.ctf.core.CTFException;
f357bcd4
AM
27import org.eclipse.tracecompass.ctf.core.event.EventDefinition;
28import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
29import org.eclipse.tracecompass.internal.ctf.core.Activator;
30import org.eclipse.tracecompass.internal.ctf.core.trace.StreamInputReaderTimestampComparator;
ce2388e0 31
866e5b51 32/**
d37aaa7f 33 * A CTF trace reader. Reads the events of a trace.
1d7277f3 34 *
d37aaa7f
FC
35 * @version 1.0
36 * @author Matthew Khouzam
37 * @author Alexandre Montplaisir
866e5b51 38 */
dd9752d5 39public class CTFTraceReader implements AutoCloseable {
866e5b51 40
f068c622
MK
41 private static final int LINE_LENGTH = 60;
42
fe75d403
MK
43 private static final int MIN_PRIO_SIZE = 16;
44
866e5b51
FC
45 // ------------------------------------------------------------------------
46 // Attributes
47 // ------------------------------------------------------------------------
48
49 /**
50 * The trace to read from.
51 */
93a45b54 52 private final CTFTrace fTrace;
866e5b51
FC
53
54 /**
55 * Vector of all the trace file readers.
56 */
90cefe9f 57 private final List<CTFStreamInputReader> fStreamInputReaders = Collections.synchronizedList(new ArrayList<CTFStreamInputReader>());
866e5b51
FC
58
59 /**
60 * Priority queue to order the trace file readers by timestamp.
61 */
d84419e1 62 private PriorityQueue<CTFStreamInputReader> fPrio;
866e5b51
FC
63
64 /**
65 * Array to count the number of event per trace file.
66 */
93a45b54 67 private long[] fEventCountPerTraceFile;
866e5b51
FC
68
69 /**
70 * Timestamp of the first event in the trace
71 */
93a45b54 72 private long fStartTime;
866e5b51
FC
73
74 /**
75 * Timestamp of the last event read so far
76 */
93a45b54 77 private long fEndTime;
866e5b51 78
545d9101
RB
79 /**
80 * Boolean to indicate if the CTFTraceReader has been closed
81 */
82 private boolean fClosed = false;
83
866e5b51
FC
84 // ------------------------------------------------------------------------
85 // Constructors
86 // ------------------------------------------------------------------------
87
88 /**
89 * Constructs a TraceReader to read a trace.
90 *
91 * @param trace
92 * The trace to read from.
680f9173 93 * @throws CTFException
db8e8f7d 94 * if an error occurs
866e5b51 95 */
680f9173 96 public CTFTraceReader(CTFTrace trace) throws CTFException {
93a45b54
MK
97 fTrace = trace;
98 fStreamInputReaders.clear();
866e5b51
FC
99
100 /**
101 * Create the trace file readers.
102 */
103 createStreamInputReaders();
104
105 /**
106 * Populate the timestamp-based priority queue.
107 */
108 populateStreamInputReaderHeap();
109
110 /**
bfe038ff
MK
111 * Get the start Time of this trace bear in mind that the trace could be
112 * empty.
866e5b51 113 */
93a45b54 114 fStartTime = 0;
33656d8e 115 if (hasMoreEvents()) {
42f8feff
MK
116 fStartTime = checkNotNull(getTopStream().getCurrentEvent()).getTimestamp();
117 setEndTime(fStartTime);
33656d8e 118 }
866e5b51
FC
119 }
120
121 /**
122 * Copy constructor
be6df2d8
AM
123 *
124 * @return The new CTFTraceReader
680f9173 125 * @throws CTFException
6a5251eb 126 * if an error occurs
866e5b51 127 */
680f9173 128 public CTFTraceReader copyFrom() throws CTFException {
866e5b51
FC
129 CTFTraceReader newReader = null;
130
93a45b54
MK
131 newReader = new CTFTraceReader(fTrace);
132 newReader.fStartTime = fStartTime;
133 newReader.setEndTime(fEndTime);
866e5b51
FC
134 return newReader;
135 }
136
5d1c6919
PT
137 /**
138 * Dispose the CTFTraceReader
5d1c6919 139 */
dd9752d5
AM
140 @Override
141 public void close() {
6a0ec7bc
AM
142 synchronized (fStreamInputReaders) {
143 for (CTFStreamInputReader reader : fStreamInputReaders) {
144 if (reader != null) {
145 try {
146 reader.close();
147 } catch (IOException e) {
148 Activator.logError(e.getMessage(), e);
149 }
b3151232 150 }
5d1c6919 151 }
6a0ec7bc 152 fStreamInputReaders.clear();
5d1c6919 153 }
74d66aa3 154 fPrio.clear();
545d9101 155 fClosed = true;
5d1c6919
PT
156 }
157
866e5b51
FC
158 // ------------------------------------------------------------------------
159 // Getters/Setters/Predicates
160 // ------------------------------------------------------------------------
161
162 /**
163 * Return the start time of this trace (== timestamp of the first event)
164 *
0d9a6d76 165 * @return the trace start time
866e5b51
FC
166 */
167 public long getStartTime() {
93a45b54 168 return fStartTime;
866e5b51
FC
169 }
170
6f4e8ec0
AM
171 /**
172 * Set the trace's end time
173 *
174 * @param endTime
175 * The end time to use
176 */
0594c61c 177 protected final void setEndTime(long endTime) {
93a45b54 178 fEndTime = endTime;
6f4e8ec0
AM
179 }
180
0594c61c
AM
181 /**
182 * Get the priority queue of this trace reader.
183 *
184 * @return The priority queue of input readers
0594c61c 185 */
d84419e1 186 protected PriorityQueue<CTFStreamInputReader> getPrio() {
93a45b54 187 return fPrio;
0594c61c
AM
188 }
189
866e5b51
FC
190 // ------------------------------------------------------------------------
191 // Operations
192 // ------------------------------------------------------------------------
193
194 /**
195 * Creates one trace file reader per trace file contained in the trace.
db8e8f7d 196 *
680f9173 197 * @throws CTFException
db8e8f7d 198 * if an error occurs
866e5b51 199 */
680f9173 200 private void createStreamInputReaders() throws CTFException {
866e5b51
FC
201 /*
202 * For each stream.
203 */
d84419e1
AM
204 for (CTFStream stream : fTrace.getStreams()) {
205 Set<CTFStreamInput> streamInputs = stream.getStreamInputs();
866e5b51
FC
206
207 /*
208 * For each trace file of the stream.
209 */
d84419e1 210 for (CTFStreamInput streamInput : streamInputs) {
866e5b51
FC
211
212 /*
05ce5fef 213 * Create a reader and add it to the group.
866e5b51 214 */
90cefe9f 215 fStreamInputReaders.add(new CTFStreamInputReader(checkNotNull(streamInput)));
866e5b51
FC
216 }
217 }
218
219 /*
220 * Create the array to count the number of event per trace file.
221 */
93a45b54 222 fEventCountPerTraceFile = new long[fStreamInputReaders.size()];
866e5b51
FC
223 }
224
545d9101
RB
225 /**
226 * Returns whether or not this CTFTraceReader has been closed
227 *
228 * @return true if it has been closed, false else
0336f981 229 * @since 1.1
545d9101
RB
230 */
231 public boolean isClosed() {
232 return fClosed;
233 }
234
fe75d403
MK
235 /**
236 * Update the priority queue to make it match the parent trace
237 *
680f9173 238 * @throws CTFException
fe75d403 239 * An error occured
fe75d403 240 */
680f9173 241 public void update() throws CTFException {
d84419e1
AM
242 Set<CTFStreamInputReader> readers = new HashSet<>();
243 for (CTFStream stream : fTrace.getStreams()) {
244 Set<CTFStreamInput> streamInputs = stream.getStreamInputs();
245 for (CTFStreamInput streamInput : streamInputs) {
fe75d403
MK
246 /*
247 * Create a reader.
248 */
90cefe9f 249 CTFStreamInputReader streamInputReader = new CTFStreamInputReader(checkNotNull(streamInput));
fe75d403 250
42f8feff 251
fe75d403
MK
252 /*
253 * Add it to the group.
254 */
255 if (!fStreamInputReaders.contains(streamInputReader)) {
256 streamInputReader.readNextEvent();
257 fStreamInputReaders.add(streamInputReader);
258 readers.add(streamInputReader);
259 }
260 }
261 }
262 long[] temp = fEventCountPerTraceFile;
263 fEventCountPerTraceFile = new long[readers.size() + temp.length];
d84419e1 264 for (CTFStreamInputReader reader : readers) {
fe75d403
MK
265 fPrio.add(reader);
266 }
267 for (int i = 0; i < temp.length; i++) {
268 fEventCountPerTraceFile[i] = temp[i];
269 }
270 }
271
53359017
MK
272 /**
273 * Gets an iterable of the stream input readers, useful for foreaches
274 *
275 * @return the iterable of the stream input readers
53359017
MK
276 */
277 public Iterable<IEventDeclaration> getEventDeclarations() {
42f8feff 278 Set<IEventDeclaration> retSet = new HashSet<>();
d84419e1 279 for (CTFStreamInputReader sir : fStreamInputReaders) {
42f8feff 280 retSet.addAll(sir.getEventDeclarations());
53359017 281 }
42f8feff
MK
282 retSet.remove(null);
283 return retSet;
53359017
MK
284 }
285
866e5b51
FC
286 /**
287 * Initializes the priority queue used to choose the trace file with the
288 * lower next event timestamp.
db8e8f7d 289 *
680f9173 290 * @throws CTFException
db8e8f7d 291 * if an error occurs
866e5b51 292 */
680f9173 293 private void populateStreamInputReaderHeap() throws CTFException {
93a45b54 294 if (fStreamInputReaders.isEmpty()) {
fe75d403
MK
295 fPrio = new PriorityQueue<>(MIN_PRIO_SIZE,
296 new StreamInputReaderTimestampComparator());
b5354daa
MAL
297 return;
298 }
299
866e5b51
FC
300 /*
301 * Create the priority queue with a size twice as bigger as the number
302 * of reader in order to avoid constant resizing.
303 */
93a45b54 304 fPrio = new PriorityQueue<>(
fe75d403 305 Math.max(fStreamInputReaders.size() * 2, MIN_PRIO_SIZE),
866e5b51
FC
306 new StreamInputReaderTimestampComparator());
307
308 int pos = 0;
309
d84419e1 310 for (CTFStreamInputReader reader : fStreamInputReaders) {
866e5b51
FC
311 /*
312 * Add each trace file reader in the priority queue, if we are able
313 * to read an event from it.
314 */
6a5251eb
MK
315 CTFResponse readNextEvent = reader.readNextEvent();
316 if (readNextEvent == CTFResponse.OK || readNextEvent == CTFResponse.WAIT) {
93a45b54 317 fPrio.add(reader);
866e5b51 318
93a45b54 319 fEventCountPerTraceFile[pos] = 0;
866e5b51
FC
320 reader.setName(pos);
321
322 pos++;
323 }
324 }
325 }
326
327 /**
328 * Get the current event, which is the current event of the trace file
329 * reader with the lowest timestamp.
330 *
331 * @return An event definition, or null of the trace reader reached the end
332 * of the trace.
333 */
334 public EventDefinition getCurrentEventDef() {
d84419e1 335 CTFStreamInputReader top = getTopStream();
866e5b51
FC
336 return (top != null) ? top.getCurrentEvent() : null;
337 }
338
339 /**
340 * Go to the next event.
341 *
342 * @return True if an event was read.
680f9173 343 * @throws CTFException
db8e8f7d 344 * if an error occurs
866e5b51 345 */
680f9173 346 public boolean advance() throws CTFException {
866e5b51
FC
347 /*
348 * Remove the reader from the top of the priority queue.
349 */
d84419e1 350 CTFStreamInputReader top = fPrio.poll();
866e5b51
FC
351
352 /*
353 * If the queue was empty.
354 */
355 if (top == null) {
356 return false;
357 }
866e5b51
FC
358 /*
359 * Read the next event of this reader.
360 */
6a5251eb
MK
361 switch (top.readNextEvent()) {
362 case OK: {
866e5b51
FC
363 /*
364 * Add it back in the queue.
365 */
93a45b54 366 fPrio.add(top);
90cefe9f
MK
367 /*
368 * We're in OK, there's a guaranteed top#getCurrentEvent() unless another
369 * thread does something bad.
370 */
371 EventDefinition currentEvent = checkNotNull(top.getCurrentEvent());
372 final long topEnd = fTrace.timestampCyclesToNanos(currentEvent.getTimestamp());
93a45b54
MK
373 setEndTime(Math.max(topEnd, getEndTime()));
374 fEventCountPerTraceFile[top.getName()]++;
90cefe9f 375 fEndTime = Math.max(currentEvent.getTimestamp(), fEndTime);
6a5251eb
MK
376 break;
377 }
378 case WAIT: {
379 fPrio.add(top);
380 break;
381 }
382 case FINISH:
383 break;
384 case ERROR:
385 default:
386 // something bad happend
bfe038ff 387 }
866e5b51
FC
388 /*
389 * If there is no reader in the queue, it means the trace reader reached
390 * the end of the trace.
391 */
bfe038ff 392 return hasMoreEvents();
866e5b51
FC
393 }
394
395 /**
396 * Go to the last event in the trace.
db8e8f7d 397 *
680f9173 398 * @throws CTFException
db8e8f7d 399 * if an error occurs
866e5b51 400 */
680f9173 401 public void goToLastEvent() throws CTFException {
93a45b54
MK
402 seek(getEndTime());
403 while (fPrio.size() > 1) {
404 advance();
866e5b51
FC
405 }
406 }
407
408 /**
ecb12461
EB
409 * Seeks to a given timestamp. It will seek to the nearest event greater or
410 * equal to timestamp. If a trace is [10 20 30 40] and you are looking for
411 * 19, it will give you 20. If you want 20, you will get 20, if you want 21,
412 * you will get 30. The value -inf will seek to the first element and the
413 * value +inf will seek to the end of the file (past the last event).
866e5b51
FC
414 *
415 * @param timestamp
416 * the timestamp to seek to
6a5251eb
MK
417 * @return true if there are events above or equal the seek timestamp, false
418 * if seek at the end of the trace (no valid event).
680f9173 419 * @throws CTFException
db8e8f7d 420 * if an error occurs
866e5b51 421 */
680f9173 422 public boolean seek(long timestamp) throws CTFException {
866e5b51
FC
423 /*
424 * Remove all the trace readers from the priority queue
425 */
93a45b54 426 fPrio.clear();
d84419e1 427 for (CTFStreamInputReader streamInputReader : fStreamInputReaders) {
866e5b51
FC
428 /*
429 * Seek the trace reader.
430 */
bfe038ff 431 streamInputReader.seek(timestamp);
ce2388e0
FC
432
433 /*
434 * Add it to the priority queue if there is a current event.
435 */
ce2388e0 436 if (streamInputReader.getCurrentEvent() != null) {
93a45b54 437 fPrio.add(streamInputReader);
ce2388e0
FC
438 }
439 }
866e5b51
FC
440 return hasMoreEvents();
441 }
442
9ac2eb62 443 /**
ecb12461 444 * Gets the stream with the oldest event
9ac2eb62
MK
445 *
446 * @return the stream with the oldest event
447 */
d84419e1 448 public CTFStreamInputReader getTopStream() {
93a45b54 449 return fPrio.peek();
ce2388e0
FC
450 }
451
866e5b51
FC
452 /**
453 * Does the trace have more events?
454 *
455 * @return true if yes.
456 */
0594c61c 457 public final boolean hasMoreEvents() {
93a45b54 458 return fPrio.size() > 0;
866e5b51
FC
459 }
460
461 /**
462 * Prints the event count stats.
463 */
464 public void printStats() {
f068c622 465 printStats(LINE_LENGTH);
866e5b51
FC
466 }
467
468 /**
469 * Prints the event count stats.
470 *
471 * @param width
472 * Width of the display.
473 */
474 public void printStats(int width) {
475 int numEvents = 0;
476 if (width == 0) {
477 return;
478 }
479
93a45b54 480 for (long i : fEventCountPerTraceFile) {
866e5b51
FC
481 numEvents += i;
482 }
483
93a45b54 484 for (int j = 0; j < fEventCountPerTraceFile.length; j++) {
d84419e1 485 CTFStreamInputReader se = fStreamInputReaders.get(j);
866e5b51 486
93a45b54 487 long len = (width * fEventCountPerTraceFile[se.getName()])
866e5b51
FC
488 / numEvents;
489
0594c61c
AM
490 StringBuilder sb = new StringBuilder(se.getFilename());
491 sb.append("\t["); //$NON-NLS-1$
866e5b51
FC
492
493 for (int i = 0; i < len; i++) {
494 sb.append('+');
495 }
496
bfe038ff 497 for (long i = len; i < width; i++) {
866e5b51
FC
498 sb.append(' ');
499 }
500
93a45b54 501 sb.append("]\t" + fEventCountPerTraceFile[se.getName()] + " Events"); //$NON-NLS-1$//$NON-NLS-2$
4311ac8b 502 Activator.log(sb.toString());
866e5b51
FC
503 }
504 }
505
9ac2eb62 506 /**
ecb12461 507 * Gets the last event timestamp that was read. This is NOT necessarily the
9ac2eb62
MK
508 * last event in a trace, just the last one read so far.
509 *
510 * @return the last event
511 */
866e5b51 512 public long getEndTime() {
93a45b54 513 return fEndTime;
866e5b51
FC
514 }
515
6a5251eb
MK
516 /**
517 * Sets a trace to be live or not
518 *
519 * @param live
520 * whether the trace is live
6a5251eb
MK
521 */
522 public void setLive(boolean live) {
d84419e1 523 for (CTFStreamInputReader s : fPrio) {
6a5251eb
MK
524 s.setLive(live);
525 }
526 }
527
528 /**
529 * Get if the trace is to read live or not
530 *
531 * @return whether the trace is live or not
6a5251eb
MK
532 */
533 public boolean isLive() {
0af5eb9a 534 return getTopStream().isLive();
6a5251eb
MK
535 }
536
866e5b51
FC
537 @Override
538 public int hashCode() {
539 final int prime = 31;
540 int result = 1;
93a45b54
MK
541 result = (prime * result) + (int) (fStartTime ^ (fStartTime >>> 32));
542 result = (prime * result) + fStreamInputReaders.hashCode();
543 result = (prime * result) + ((fTrace == null) ? 0 : fTrace.hashCode());
866e5b51
FC
544 return result;
545 }
546
547 @Override
548 public boolean equals(Object obj) {
549 if (this == obj) {
550 return true;
551 }
552 if (obj == null) {
553 return false;
554 }
07002e0a 555 if (!(obj instanceof CTFTraceReader)) {
866e5b51
FC
556 return false;
557 }
558 CTFTraceReader other = (CTFTraceReader) obj;
93a45b54 559 if (!fStreamInputReaders.equals(other.fStreamInputReaders)) {
866e5b51
FC
560 return false;
561 }
93a45b54
MK
562 if (fTrace == null) {
563 if (other.fTrace != null) {
866e5b51
FC
564 return false;
565 }
93a45b54 566 } else if (!fTrace.equals(other.fTrace)) {
866e5b51
FC
567 return false;
568 }
569 return true;
570 }
571
866e5b51
FC
572 @Override
573 public String toString() {
574 /* Only for debugging, shouldn't be externalized */
93a45b54 575 return "CTFTraceReader [trace=" + fTrace + ']'; //$NON-NLS-1$
866e5b51
FC
576 }
577
9ac2eb62
MK
578 /**
579 * Gets the parent trace
580 *
581 * @return the parent trace
582 */
866e5b51 583 public CTFTrace getTrace() {
93a45b54 584 return fTrace;
866e5b51 585 }
4a32dd11
MK
586
587 /**
588 * This will read the entire trace and populate all the indexes. The reader
589 * will then be reset to the first event in the trace.
590 *
591 * Do not call in the fast path.
592 *
593 * @throws CTFException
594 * A trace reading error occurred
595 * @since 1.0
596 */
597 public void populateIndex() throws CTFException {
598 for (CTFStreamInputReader sir : fPrio) {
599 sir.goToLastEvent();
600 }
601 seek(0);
602
603 }
866e5b51 604}
This page took 0.123014 seconds and 5 git commands to generate.