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