Partial fix for bug345440 - More warning fixes
[deliverable/tracecompass.git] / org.eclipse.linuxtools.lttng.core / src / org / eclipse / linuxtools / lttng / core / trace / LTTngTrace.java
1 /*******************************************************************************
2 * Copyright (c) 2009, 2011 Ericsson, MontaVista Software
3 *
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
8 *
9 * Contributors:
10 * William Bourque (wbourque@gmail.com) - Initial API and implementation
11 * Yufen Kuo (ykuo@mvista.com) - add support to allow user specify trace library path
12 *******************************************************************************/
13
14 package org.eclipse.linuxtools.lttng.core.trace;
15
16 import java.io.FileNotFoundException;
17 import java.util.HashMap;
18 import java.util.Iterator;
19 import java.util.Vector;
20
21 import org.eclipse.core.resources.IProject;
22 import org.eclipse.linuxtools.lttng.core.TraceHelper;
23 import org.eclipse.linuxtools.lttng.core.event.LttngEvent;
24 import org.eclipse.linuxtools.lttng.core.event.LttngEventContent;
25 import org.eclipse.linuxtools.lttng.core.event.LttngEventType;
26 import org.eclipse.linuxtools.lttng.core.event.LttngLocation;
27 import org.eclipse.linuxtools.lttng.core.event.LttngTimestamp;
28 import org.eclipse.linuxtools.lttng.core.exceptions.LttngException;
29 import org.eclipse.linuxtools.lttng.core.tracecontrol.utility.LiveTraceManager;
30 import org.eclipse.linuxtools.lttng.jni.JniEvent;
31 import org.eclipse.linuxtools.lttng.jni.JniMarker;
32 import org.eclipse.linuxtools.lttng.jni.JniTrace;
33 import org.eclipse.linuxtools.lttng.jni.JniTracefile;
34 import org.eclipse.linuxtools.lttng.jni.common.JniTime;
35 import org.eclipse.linuxtools.lttng.jni.exception.JniException;
36 import org.eclipse.linuxtools.lttng.jni.factory.JniTraceFactory;
37 import org.eclipse.linuxtools.tmf.core.event.ITmfTimestamp;
38 import org.eclipse.linuxtools.tmf.core.event.TmfEvent;
39 import org.eclipse.linuxtools.tmf.core.event.TmfTimeRange;
40 import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp;
41 import org.eclipse.linuxtools.tmf.core.experiment.TmfExperiment;
42 import org.eclipse.linuxtools.tmf.core.request.ITmfDataRequest.ExecutionType;
43 import org.eclipse.linuxtools.tmf.core.request.TmfEventRequest;
44 import org.eclipse.linuxtools.tmf.core.signal.TmfTraceUpdatedSignal;
45 import org.eclipse.linuxtools.tmf.core.trace.ITmfContext;
46 import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation;
47 import org.eclipse.linuxtools.tmf.core.trace.TmfCheckpoint;
48 import org.eclipse.linuxtools.tmf.core.trace.TmfContext;
49 import org.eclipse.linuxtools.tmf.core.trace.TmfTrace;
50
51 class LTTngTraceException extends LttngException {
52 static final long serialVersionUID = -1636648737081868146L;
53
54 public LTTngTraceException(String errMsg) {
55 super(errMsg);
56 }
57 }
58
59 /**
60 * <b><u>LTTngTrace</u></b>
61 * <p>
62 *
63 * LTTng trace implementation. It accesses the C trace handling library (seeking, reading and parsing) through the JNI
64 * component.
65 */
66 public class LTTngTrace extends TmfTrace<LttngEvent> {
67
68 public static boolean PrintDebug = false;
69 public static boolean UniqueEvent = true;
70
71 private final static boolean SHOW_LTT_DEBUG_DEFAULT = false;
72 private final static boolean IS_PARSING_NEEDED_DEFAULT = !UniqueEvent;
73 private final static int CHECKPOINT_PAGE_SIZE = 50000;
74 private final static long LTTNG_STREAMING_INTERVAL = 2000; // in ms
75
76 // Reference to our JNI trace
77 private JniTrace currentJniTrace;
78
79 LttngTimestamp eventTimestamp;
80 String eventSource;
81 LttngEventContent eventContent;
82 String eventReference;
83
84 // The actual event
85 LttngEvent currentLttngEvent;
86
87 // The current location
88 LttngLocation previousLocation;
89
90 LttngEventType eventType;
91
92 // Hashmap of the possible types of events (Tracefile/CPU/Marker in the JNI)
93 HashMap<Integer, LttngEventType> traceTypes;
94
95 // This vector will be used to quickly find a marker name from a position
96 Vector<Integer> traceTypeNames;
97
98 private String traceLibPath;
99
100 private long fStreamingInterval = 0;
101
102 public LTTngTrace() {
103 }
104
105 @Override
106 public boolean validate(IProject project, String path) {
107 if (super.validate(project, path)) {
108 String traceLibPath = TraceHelper.getTraceLibDirFromProject(project);
109 try {
110 LTTngTraceVersion version = new LTTngTraceVersion(path, traceLibPath);
111 return version.isValidLttngTrace();
112 } catch (LttngException e) {
113 }
114 }
115 return false;
116 }
117
118 @Override
119 public void initTrace(String name, String path, Class<LttngEvent> eventType) throws FileNotFoundException {
120 initLTTngTrace(name, path, eventType, CHECKPOINT_PAGE_SIZE, false);
121 }
122
123 @Override
124 public void initTrace(String name, String path, Class<LttngEvent> eventType, int cacheSize) throws FileNotFoundException {
125 initLTTngTrace(name, path, eventType, cacheSize, false);
126 }
127
128 @Override
129 public void initTrace(String name, String path, Class<LttngEvent> eventType, boolean indexTrace) throws FileNotFoundException {
130 initLTTngTrace(name, path, eventType, CHECKPOINT_PAGE_SIZE, indexTrace);
131 }
132
133 @Override
134 public void initTrace(String name, String path, Class<LttngEvent> eventType, int cacheSize, boolean indexTrace) throws FileNotFoundException {
135 initLTTngTrace(name, path, eventType, cacheSize, indexTrace);
136 }
137
138 private void initLTTngTrace(String name, String path, Class<LttngEvent> eventType, int cacheSize, boolean indexTrace) throws FileNotFoundException {
139 super.initTrace(name, path, eventType, indexTrace);
140 try {
141 currentJniTrace = JniTraceFactory.getJniTrace(path, traceLibPath, SHOW_LTT_DEBUG_DEFAULT);
142 } catch (Exception e) {
143 throw new FileNotFoundException(e.getMessage());
144 }
145
146 // Export all the event types from the JNI side
147 traceTypes = new HashMap<Integer, LttngEventType>();
148 traceTypeNames = new Vector<Integer>();
149 initialiseEventTypes(currentJniTrace);
150
151 // Build the re-used event structure
152 eventTimestamp = new LttngTimestamp();
153 eventSource = ""; //$NON-NLS-1$
154 this.eventType = new LttngEventType();
155 eventContent = new LttngEventContent(currentLttngEvent);
156 eventReference = getName();
157
158 // Create the skeleton event
159 currentLttngEvent = new LttngEvent(this, eventTimestamp, eventSource, this.eventType, eventContent,
160 eventReference, null);
161
162 // Create a new current location
163 previousLocation = new LttngLocation();
164
165 // Set the currentEvent to the eventContent
166 eventContent.setEvent(currentLttngEvent);
167
168 // // Bypass indexing if asked
169 // if ( bypassIndexing == false ) {
170 // indexTrace(true);
171 // }
172 // else {
173 // Even if we don't have any index, set ONE checkpoint
174 // fCheckpoints.add(new TmfCheckpoint(new LttngTimestamp(0L) , new
175 // LttngLocation() ) );
176
177 initializeStreamingMonitor();
178 }
179
180 private void initializeStreamingMonitor() {
181 JniTrace jniTrace = getCurrentJniTrace();
182 if (jniTrace == null || (!jniTrace.isLiveTraceSupported() || !LiveTraceManager.isLiveTrace(jniTrace.getTracepath()))) {
183 // Set the time range of the trace
184 TmfContext context = seekLocation(null);
185 LttngEvent event = getNextEvent(context);
186 LttngTimestamp startTime = new LttngTimestamp(event.getTimestamp());
187 LttngTimestamp endTime = new LttngTimestamp(currentJniTrace.getEndTime().getTime());
188 setTimeRange(new TmfTimeRange(startTime, endTime));
189 TmfTraceUpdatedSignal signal = new TmfTraceUpdatedSignal(this, this, getTimeRange());
190 broadcast(signal);
191 return;
192 }
193
194 // Set the time range of the trace
195 TmfContext context = seekLocation(null);
196 LttngEvent event = getNextEvent(context);
197 setEndTime(TmfTimestamp.BigBang);
198 final long startTime = event != null ? event.getTimestamp().getValue() : TmfTimestamp.BigBang.getValue();
199 fStreamingInterval = LTTNG_STREAMING_INTERVAL;
200
201 final Thread thread = new Thread("Streaming Monitor for trace " + getName()) { //$NON-NLS-1$
202 LttngTimestamp safeTimestamp = null;
203 TmfTimeRange timeRange = null;
204
205 @SuppressWarnings("unchecked")
206 @Override
207 public void run() {
208 while (!fExecutor.isShutdown()) {
209 TmfExperiment<?> experiment = TmfExperiment.getCurrentExperiment();
210 if (experiment != null) {
211 @SuppressWarnings("rawtypes")
212 final TmfEventRequest request = new TmfEventRequest<TmfEvent>(TmfEvent.class, TmfTimeRange.Eternity, 0, ExecutionType.FOREGROUND) {
213 @Override
214 public void handleCompleted() {
215 updateJniTrace();
216 }
217 };
218 synchronized (experiment) {
219 experiment.sendRequest(request);
220 }
221 try {
222 request.waitForCompletion();
223 } catch (InterruptedException e) {
224 e.printStackTrace();
225 }
226 } else {
227 updateJniTrace();
228 }
229 try {
230 Thread.sleep(LTTNG_STREAMING_INTERVAL);
231 } catch (InterruptedException e) {
232 e.printStackTrace();
233 }
234 }
235 }
236
237 private void updateJniTrace() {
238 JniTrace jniTrace = getCurrentJniTrace();
239 currentJniTrace.updateTrace();
240 long endTime = jniTrace.getEndTime().getTime();
241 LttngTimestamp startTimestamp = new LttngTimestamp(startTime);
242 LttngTimestamp endTimestamp = new LttngTimestamp(endTime);
243 if (safeTimestamp != null && safeTimestamp.compareTo(getTimeRange().getEndTime(), false) > 0) {
244 timeRange = new TmfTimeRange(startTimestamp, safeTimestamp);
245 } else {
246 timeRange = null;
247 }
248 safeTimestamp = endTimestamp;
249 if (timeRange != null) {
250 setTimeRange(timeRange);
251 }
252 }
253 };
254 thread.start();
255 }
256
257 /* (non-Javadoc)
258 * @see org.eclipse.linuxtools.tmf.trace.TmfTrace#getStreamingInterval()
259 */
260 @Override
261 public long getStreamingInterval() {
262 return fStreamingInterval;
263 }
264
265 /**
266 * Default Constructor.
267 * <p>
268 *
269 * @param name
270 * Name of the trace
271 * @param path
272 * Path to a <b>directory</b> that contain an LTTng trace.
273 *
274 * @exception Exception
275 * (most likely LTTngTraceException or FileNotFoundException)
276 */
277 public LTTngTrace(String name, String path) throws Exception {
278 // Call with "wait for completion" true and "skip indexing" false
279 this(name, path, null, true, false);
280 }
281
282 /**
283 * Constructor, with control over the indexing.
284 * <p>
285 *
286 * @param name
287 * Name of the trace
288 * @param path
289 * Path to a <b>directory</b> that contain an LTTng trace.
290 * @param waitForCompletion
291 * Should we wait for indexign to complete before moving on.
292 *
293 * @exception Exception
294 * (most likely LTTngTraceException or FileNotFoundException)
295 */
296 public LTTngTrace(String name, String path, boolean waitForCompletion) throws Exception {
297 // Call with "skip indexing" false
298 this(name, path, null, waitForCompletion, true);
299 }
300
301 /**
302 * Default constructor, with control over the indexing and possibility to bypass indexation
303 * <p>
304 *
305 * @param name
306 * Name of the trace
307 * @param path
308 * Path to a <b>directory</b> that contain an LTTng trace.
309 * @param traceLibPath
310 * Path to a <b>directory</b> that contains LTTng trace libraries.
311 * @param waitForCompletion
312 * Should we wait for indexign to complete before moving on.
313 * @param bypassIndexing
314 * Should we bypass indexing completly? This is should only be useful for unit testing.
315 *
316 * @exception Exception
317 * (most likely LTTngTraceException or FileNotFoundException)
318 *
319 */
320 public LTTngTrace(String name, String path, String traceLibPath, boolean waitForCompletion, boolean bypassIndexing)
321 throws Exception {
322 super(name, LttngEvent.class, path, CHECKPOINT_PAGE_SIZE, false);
323 initTrace(name, path, LttngEvent.class, !bypassIndexing);
324 this.traceLibPath = traceLibPath;
325 }
326
327 /*
328 * Copy constructor is forbidden for LttngEvenmStream
329 */
330 public LTTngTrace(LTTngTrace other) throws Exception {
331 this(other.getName(), other.getPath(), other.getTraceLibPath(), false, true);
332 this.fCheckpoints = other.fCheckpoints;
333 setTimeRange(new TmfTimeRange(new LttngTimestamp(other.getStartTime()), new LttngTimestamp(other.getEndTime())));
334 }
335
336 @Override
337 public LTTngTrace copy() {
338 LTTngTrace returnedTrace = null;
339
340 try {
341 returnedTrace = new LTTngTrace(this);
342 } catch (Exception e) {
343 System.out
344 .println("ERROR : Could not create LTTngTrace copy (createTraceCopy).\nError is : " + e.getStackTrace()); //$NON-NLS-1$
345 }
346
347 return returnedTrace;
348 }
349
350 @Override
351 public synchronized LTTngTrace clone() {
352 LTTngTrace clone = null;
353 try {
354 clone = (LTTngTrace) super.clone();
355 try {
356 clone.currentJniTrace = JniTraceFactory.getJniTrace(getPath(), getTraceLibPath(),
357 SHOW_LTT_DEBUG_DEFAULT);
358 } catch (JniException e) {
359 // e.printStackTrace();
360 }
361
362 // Export all the event types from the JNI side
363 clone.traceTypes = new HashMap<Integer, LttngEventType>();
364 clone.traceTypeNames = new Vector<Integer>();
365 clone.initialiseEventTypes(clone.currentJniTrace);
366
367 // Verify that all those "default constructor" are safe to use
368 clone.eventTimestamp = new LttngTimestamp();
369 clone.eventSource = ""; //$NON-NLS-1$
370 clone.eventType = new LttngEventType();
371 clone.eventContent = new LttngEventContent(clone.currentLttngEvent);
372 clone.eventReference = getName();
373
374 // Create the skeleton event
375 clone.currentLttngEvent = new LttngEvent(this, clone.eventTimestamp, clone.eventSource, clone.eventType,
376 clone.eventContent, clone.eventReference, null);
377
378 // Create a new current location
379 clone.previousLocation = new LttngLocation();
380
381 // Set the currentEvent to the eventContent
382 clone.eventContent.setEvent(clone.currentLttngEvent);
383
384 // Set the start time of the trace
385 setTimeRange(new TmfTimeRange(new LttngTimestamp(clone.currentJniTrace.getStartTime().getTime()),
386 new LttngTimestamp(clone.currentJniTrace.getEndTime().getTime())));
387 } catch (CloneNotSupportedException e) {
388 }
389
390 return clone;
391 }
392
393 public String getTraceLibPath() {
394 return traceLibPath;
395 }
396
397 /*
398 * Fill out the HashMap with "Type" (Tracefile/Marker)
399 *
400 * This should be called at construction once the trace is open
401 */
402 private void initialiseEventTypes(JniTrace trace) {
403 // Work variables
404 LttngEventType tmpType = null;
405 String[] markerFieldsLabels = null;
406
407 String newTracefileKey = null;
408 Integer newMarkerKey = null;
409
410 JniTracefile newTracefile = null;
411 JniMarker newMarker = null;
412
413 // First, obtain an iterator on TRACEFILES of owned by the TRACE
414 Iterator<String> tracefileItr = trace.getTracefilesMap().keySet().iterator();
415
416 while (tracefileItr.hasNext()) {
417 newTracefileKey = tracefileItr.next();
418 newTracefile = trace.getTracefilesMap().get(newTracefileKey);
419
420 // From the TRACEFILE read, obtain its MARKER
421 Iterator<Integer> markerItr = newTracefile.getTracefileMarkersMap().keySet().iterator();
422 while (markerItr.hasNext()) {
423 newMarkerKey = markerItr.next();
424 newMarker = newTracefile.getTracefileMarkersMap().get(newMarkerKey);
425
426 // From the MARKER we can obtain the MARKERFIELDS keys (i.e.
427 // labels)
428 markerFieldsLabels = newMarker.getMarkerFieldsHashMap().keySet()
429 .toArray(new String[newMarker.getMarkerFieldsHashMap().size()]);
430
431 tmpType = new LttngEventType(newTracefile.getTracefileName(), newTracefile.getCpuNumber(),
432 newMarker.getName(), newMarkerKey.intValue(), markerFieldsLabels);
433
434 // Add the type to the map/vector
435 addEventTypeToMap(tmpType);
436 }
437 }
438 }
439
440 /*
441 * Add a new type to the HashMap
442 *
443 * As the hashmap use a key format that is a bit dangerous to use, we should always add using this function.
444 */
445 private void addEventTypeToMap(LttngEventType newEventType) {
446 int newTypeKey = EventTypeKey.getEventTypeHash(newEventType);
447
448 this.traceTypes.put(newTypeKey, newEventType);
449 this.traceTypeNames.add(newTypeKey);
450 }
451
452 /**
453 * Return the latest saved location. Note : Modifying the returned location may result in buggy positionning!
454 *
455 * @return The LttngLocation as it was after the last operation.
456 *
457 * @see org.eclipse.linuxtools.lttng.core.event.LttngLocation
458 */
459 @Override
460 public synchronized ITmfLocation<?> getCurrentLocation() {
461 return previousLocation;
462 }
463
464 /**
465 * Position the trace to the event at the given location.
466 * <p>
467 * NOTE : Seeking by location is very fast compare to seeking by position but is still slower than "ReadNext", avoid
468 * using it for small interval.
469 *
470 * @param location
471 * Location of the event in the trace. If no event available at this exact location, we will position
472 * ourself to the next one.
473 *
474 * @return The TmfContext that point to this event
475 *
476 * @see org.eclipse.linuxtools.lttng.core.event.LttngLocation
477 * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext
478 */
479 @Override
480 public synchronized TmfContext seekLocation(ITmfLocation<?> location) {
481
482 // // [lmcfrch]
483 // lastTime = 0;
484
485 if (PrintDebug) {
486 System.out.println("seekLocation(location) location -> " + location); //$NON-NLS-1$
487 }
488
489 // If the location in context is null, create a new one
490 LttngLocation curLocation = null;
491 if (location == null) {
492 curLocation = new LttngLocation();
493 TmfContext context = seekEvent(curLocation.getOperationTime());
494 context.setRank(ITmfContext.INITIAL_RANK);
495 return context;
496 } else {
497 curLocation = (LttngLocation) location;
498 }
499
500 // *** NOTE :
501 // Update to location should (and will) be done in SeekEvent.
502
503 // The only seek valid in LTTng is with the time, we call
504 // seekEvent(timestamp)
505 TmfContext context = seekEvent(curLocation.getOperationTime());
506
507 return context;
508 }
509
510 /**
511 * Position the trace to the event at the given time.
512 * <p>
513 * NOTE : Seeking by time is very fast compare to seeking by position but is still slower than "ReadNext", avoid
514 * using it for small interval.
515 *
516 * @param timestamp
517 * Time of the event in the trace. If no event available at this exact time, we will position ourself to
518 * the next one.
519 *
520 * @return The TmfContext that point to this event
521 *
522 * @see org.eclipse.linuxtools.lttng.core.event.LttngLocation
523 * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext
524 */
525 @Override
526 public synchronized TmfContext seekEvent(ITmfTimestamp timestamp) {
527
528 if (PrintDebug) {
529 System.out.println("seekEvent(timestamp) timestamp -> " + timestamp); //$NON-NLS-1$
530 }
531
532 // Call JNI to seek
533 currentJniTrace.seekToTime(new JniTime(timestamp.getValue()));
534
535 // Save the time at which we seeked
536 previousLocation.setOperationTime(timestamp.getValue());
537 // Set the operation marker as seek, to be able to detect we did "seek"
538 // this event
539 previousLocation.setLastOperationSeek();
540
541 LttngLocation curLocation = new LttngLocation(previousLocation);
542
543 return new TmfContext(curLocation);
544 }
545
546 /**
547 * Position the trace to the event at the given position (rank).
548 * <p>
549 * NOTE : Seeking by position is very slow in LTTng, consider seeking by timestamp.
550 *
551 * @param position
552 * Position (or rank) of the event in the trace, starting at 0.
553 *
554 * @return The TmfContext that point to this event
555 *
556 * @see org.eclipse.linuxtools.lttng.core.event.LttngLocation
557 * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext
558 */
559 @Override
560 public synchronized TmfContext seekEvent(long position) {
561
562 if (PrintDebug) {
563 System.out.println("seekEvent(position) position -> " + position); //$NON-NLS-1$
564 }
565
566 ITmfTimestamp timestamp = null;
567 long index = position / getCacheSize();
568
569 // Get the timestamp of the closest check point to the given position
570 if (fCheckpoints.size() > 0) {
571 if (index >= fCheckpoints.size()) {
572 index = fCheckpoints.size() - 1;
573 }
574 timestamp = fCheckpoints.elementAt((int) index).getTimestamp();
575 }
576 // If none, take the start time of the trace
577 else {
578 timestamp = getStartTime();
579 }
580
581 // Seek to the found time
582 TmfContext tmpContext = seekEvent(timestamp);
583 tmpContext.setRank((index + 1) * fIndexPageSize);
584 previousLocation = (LttngLocation) tmpContext.getLocation();
585
586 // Ajust the index of the event we found at this check point position
587 Long currentPosition = index * getCacheSize();
588
589 Long lastTimeValueRead = 0L;
590
591 // Get the event at current position. This won't move to the next one
592 JniEvent tmpJniEvent = currentJniTrace.findNextEvent();
593 // Now that we are positionned at the checkpoint,
594 // we need to "readNext" (Position - CheckpointPosition) times or until
595 // trace "run out"
596 while ((tmpJniEvent != null) && (currentPosition < position)) {
597 tmpJniEvent = currentJniTrace.readNextEvent();
598 currentPosition++;
599 }
600
601 // If we found our event, save its timestamp
602 if (tmpJniEvent != null) {
603 lastTimeValueRead = tmpJniEvent.getEventTime().getTime();
604 }
605
606 // Set the operation marker as seek, to be able to detect we did "seek"
607 // this event
608 previousLocation.setLastOperationSeek();
609 // Save read event time
610 previousLocation.setOperationTime(lastTimeValueRead);
611
612 // *** VERIFY ***
613 // Is that too paranoid?
614 //
615 // We don't trust what upper level could do with our internal location
616 // so we create a new one to return instead
617 LttngLocation curLocation = new LttngLocation(previousLocation);
618
619 return new TmfContext(curLocation);
620 }
621
622 @Override
623 public TmfContext seekLocation(double ratio) {
624 // TODO Auto-generated method stub
625 return null;
626 }
627
628 @Override
629 public double getLocationRatio(ITmfLocation<?> location) {
630 // TODO Auto-generated method stub
631 return 0;
632 }
633
634 /**
635 * Return the event in the trace according to the given context. Read it if necessary.
636 * <p>
637 * Similar (same?) as ParseEvent except that calling GetNext twice read the next one the second time.
638 *
639 * @param context
640 * Current TmfContext where to get the event
641 *
642 * @return The LttngEvent we read of null if no event are available
643 *
644 * @see org.eclipse.linuxtools.lttng.core.event.LttngLocation
645 * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext
646 */
647
648 public int nbEventsRead = 0;
649
650 @Override
651 public synchronized LttngEvent getNextEvent(TmfContext context) {
652
653 if (PrintDebug) {
654 System.out.println("getNextEvent(context) context.getLocation() -> " //$NON-NLS-1$
655 + context.getLocation());
656 }
657
658 LttngEvent returnedEvent = null;
659 LttngLocation curLocation = null;
660
661 curLocation = (LttngLocation) context.getLocation();
662 // If the location in context is null, create a new one
663 if (curLocation == null) {
664 curLocation = getCurrentLocation(context);
665 }
666
667 // *** Positioning trick :
668 // GetNextEvent only read the trace if :
669 // 1- The last operation was NOT a ParseEvent --> A read is required
670 // OR
671 // 2- The time of the previous location is different from the current
672 // one --> A seek + a read is required
673 if ((!(curLocation.isLastOperationParse()))
674 || (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue())) {
675 if (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue()) {
676 if (PrintDebug) {
677 System.out.println("\t\tSeeking in getNextEvent. [ LastTime : " //$NON-NLS-1$
678 + previousLocation.getOperationTimeValue() + " CurrentTime" //$NON-NLS-1$
679 + curLocation.getOperationTimeValue() + " ]"); //$NON-NLS-1$
680 }
681 seekEvent(curLocation.getOperationTime());
682 }
683 // Read the next event from the trace. The last one will NO LONGER
684 // BE VALID.
685 returnedEvent = readNextEvent(curLocation);
686
687 } else {
688 // No event was read, just return the one currently loaded (the last
689 // one we read)
690 returnedEvent = currentLttngEvent;
691
692 // *** IMPORTANT!
693 // Reset (erase) the operation marker to both location, to be able
694 // to detect we did NOT "read" this event
695 previousLocation.resetLocationState();
696 curLocation.resetLocationState();
697 }
698
699 // If we read an event, set it's time to the locations (both previous
700 // and current)
701 if (returnedEvent != null) {
702 setPreviousAndCurrentTimes(context, returnedEvent, curLocation);
703 }
704
705 return returnedEvent;
706 }
707
708 // this method was extracted for profiling purposes
709 private void setPreviousAndCurrentTimes(TmfContext context, LttngEvent returnedEvent, LttngLocation curLocation) {
710
711 ITmfTimestamp eventTimestamp = returnedEvent.getTimestamp();
712 // long eventTime = eventTimestamp.getValue();
713 previousLocation.setOperationTime(eventTimestamp.getValue());
714 curLocation.setOperationTime(eventTimestamp.getValue());
715 updateIndex(context, context.getRank(), eventTimestamp);
716 context.updateRank(1);
717 }
718
719 protected void updateIndex(TmfContext context, long rank, ITmfTimestamp timestamp) {
720
721 if (getStartTime().compareTo(timestamp, false) > 0)
722 setStartTime(timestamp);
723 if (getEndTime().compareTo(timestamp, false) < 0)
724 setEndTime(timestamp);
725 if (rank != ITmfContext.UNKNOWN_RANK) {
726 if (fNbEvents <= rank)
727 fNbEvents = rank + 1;
728 // Build the index as we go along
729 if ((rank % fIndexPageSize) == 0) {
730 // Determine the table position
731 long position = rank / fIndexPageSize;
732 // Add new entry at proper location (if empty)
733 if (fCheckpoints.size() == position) {
734 addCheckPoint(context, timestamp);
735 }
736 }
737 }
738 }
739
740 private void addCheckPoint(TmfContext context, ITmfTimestamp timestamp) {
741 ITmfLocation<?> location = context.getLocation().clone();
742 fCheckpoints.add(new TmfCheckpoint(timestamp.clone(), location));
743 }
744
745 // this method was extracted for profiling purposes
746 private LttngEvent readNextEvent(LttngLocation curLocation) {
747 LttngEvent returnedEvent;
748 // Read the next event from the trace. The last one will NO LONGER BE
749 // VALID.
750 returnedEvent = readEvent(curLocation);
751 nbEventsRead++;
752
753 // Set the operation marker as read to both location, to be able to
754 // detect we did "read" this event
755 previousLocation.setLastOperationReadNext();
756 curLocation.setLastOperationReadNext();
757 return returnedEvent;
758 }
759
760 // this method was extracted for profiling purposes
761 private LttngLocation getCurrentLocation(TmfContext context) {
762 LttngLocation curLocation;
763 curLocation = new LttngLocation();
764 context.setLocation(curLocation);
765 return curLocation;
766 }
767
768 /**
769 * Return the event in the trace according to the given context. Read it if necessary.
770 * <p>
771 * Similar (same?) as GetNextEvent except that calling ParseEvent twice will return the same event
772 *
773 * @param context
774 * Current TmfContext where to get the event
775 *
776 * @return The LttngEvent we read of null if no event are available
777 *
778 * @see org.eclipse.linuxtools.lttng.core.event.LttngLocation
779 * @see org.eclipse.linuxtools.tmf.core.trace.TmfContext
780 */
781 @Override
782 public synchronized LttngEvent parseEvent(TmfContext context) {
783
784 if (PrintDebug) {
785 System.out.println("parseEvent(context) context.getLocation() -> " //$NON-NLS-1$
786 + context.getLocation());
787 }
788
789 LttngEvent returnedEvent = null;
790 LttngLocation curLocation = null;
791
792 // If the location in context is null, create a new one
793 if (context.getLocation() == null) {
794 curLocation = new LttngLocation();
795 context.setLocation(curLocation);
796 }
797 // Otherwise, we use the one in context; it should be a valid
798 // LttngLocation
799 else {
800 curLocation = (LttngLocation) context.getLocation();
801 }
802
803 // *** HACK ***
804 // TMF assumes it is possible to read (GetNextEvent) to the next Event
805 // once ParseEvent() is called
806 // In LTTNG, there is not difference between "Parsing" and "Reading" an
807 // event.
808 // So, before "Parsing" an event, we have to make sure we didn't "Read"
809 // it alreafy.
810 // Also, "Reading" invalidate the previous Event in LTTNG and seek back
811 // is very costly,
812 // so calling twice "Parse" will return the same event, giving a way to
813 // get the "Currently loaded" event
814
815 // *** Positionning trick :
816 // ParseEvent only read the trace if :
817 // 1- The last operation was NOT a ParseEvent or a GetNextEvent --> A
818 // read is required
819 // OR
820 // 2- The time of the previous location is different from the current
821 // one --> A seek + a read is required
822 if (((!(curLocation.isLastOperationParse())) && ((!(curLocation.isLastOperationReadNext()))))
823 || (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue())) {
824 // Previous time != Current time : We need to reposition to the
825 // current time
826 if (previousLocation.getOperationTimeValue() != curLocation.getOperationTimeValue()) {
827 if (PrintDebug) {
828 System.out.println("\t\tSeeking in getNextEvent. [ LastTime : " //$NON-NLS-1$
829 + previousLocation.getOperationTimeValue() + " CurrentTime" //$NON-NLS-1$
830 + curLocation.getOperationTimeValue() + " ]"); //$NON-NLS-1$
831 }
832 seekEvent(curLocation.getOperationTime());
833 }
834
835 // Read the next event from the trace. The last one will NO LONGER
836 // BE VALID.
837 returnedEvent = readEvent(curLocation);
838 } else {
839 // No event was read, just return the one currently loaded (the last
840 // one we read)
841 returnedEvent = currentLttngEvent;
842 }
843
844 // If we read an event, set it's time to the locations (both previous
845 // and current)
846 if (returnedEvent != null) {
847 previousLocation.setOperationTime((LttngTimestamp) returnedEvent.getTimestamp());
848 curLocation.setOperationTime((LttngTimestamp) returnedEvent.getTimestamp());
849 }
850
851 // Set the operation marker as parse to both location, to be able to
852 // detect we already "read" this event
853 previousLocation.setLastOperationParse();
854 curLocation.setLastOperationParse();
855
856 return returnedEvent;
857 }
858
859 /*
860 * Read the next event from the JNI and convert it as Lttng Event<p>
861 *
862 * @param location Current LttngLocation that to be updated with the event timestamp
863 *
864 * @return The LttngEvent we read of null if no event are available
865 *
866 * @see org.eclipse.linuxtools.lttng.event.LttngLocation
867 *
868 * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace
869 */
870 private synchronized LttngEvent readEvent(LttngLocation location) {
871 LttngEvent returnedEvent = null;
872 JniEvent tmpEvent = null;
873
874 // Read the next event from JNI. THIS WILL INVALIDATE THE CURRENT LTTNG
875 // EVENT.
876 tmpEvent = currentJniTrace.readNextEvent();
877
878 if (tmpEvent != null) {
879 // *** NOTE
880 // Convert will update the currentLttngEvent
881 returnedEvent = convertJniEventToTmf(tmpEvent);
882
883 location.setOperationTime((LttngTimestamp) returnedEvent.getTimestamp());
884 }
885 // *** NOTE
886 // If the read failed (likely the last event in the trace), set the
887 // LastReadTime to the JNI time
888 // That way, even if we try to read again, we will step over the bogus
889 // seek and read
890 else {
891 location.setOperationTime(getEndTime().getValue() + 1);
892 }
893
894 return returnedEvent;
895 }
896
897 /**
898 * Method to convert a JniEvent into a LttngEvent.
899 * <p>
900 *
901 * Note : This method will call LttngEvent convertEventJniToTmf(JniEvent, boolean) with a default value for
902 * isParsingNeeded
903 *
904 * @param newEvent
905 * The JniEvent to convert into LttngEvent
906 *
907 * @return The converted LttngEvent
908 *
909 * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniEvent
910 * @see org.eclipse.linuxtools.lttng.core.event.LttngEvent
911 */
912 public synchronized LttngEvent convertJniEventToTmf(JniEvent newEvent) {
913 currentLttngEvent = convertJniEventToTmf(newEvent, IS_PARSING_NEEDED_DEFAULT);
914
915 return currentLttngEvent;
916 }
917
918 /**
919 * Method to convert a JniEvent into a LttngEvent
920 *
921 * @param jniEvent
922 * The JniEvent to convert into LttngEvent
923 * @param isParsingNeeded
924 * A boolean value telling if the event should be parsed or not.
925 *
926 * @return The converted LttngEvent
927 *
928 * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniEvent
929 * @see org.eclipse.linuxtools.lttng.core.event.LttngEvent
930 */
931 public synchronized LttngEvent convertJniEventToTmf(JniEvent jniEvent, boolean isParsingNeeded) {
932
933 if (UniqueEvent) {
934
935 // ***
936 // UNHACKED : We can no longer do that because TCF need to maintain
937 // several events at once.
938 // This is very slow to do so in LTTng, this has to be temporary.
939 // *** HACK ***
940 // To save time here, we only set value instead of allocating new
941 // object
942 // This give an HUGE performance improvement
943 // all allocation done in the LttngTrace constructor
944 // ***
945 eventTimestamp.setValue(jniEvent.getEventTime().getTime());
946 eventSource = jniEvent.requestEventSource();
947
948 eventType = traceTypes.get(EventTypeKey.getEventTypeHash(jniEvent));
949
950 String fullTracePath = getName();
951 String reference = fullTracePath.substring(fullTracePath.lastIndexOf('/') + 1);
952 currentLttngEvent.setReference(reference);
953
954 eventContent.emptyContent();
955
956 currentLttngEvent.setType(eventType);
957 // Save the jni reference
958 currentLttngEvent.updateJniEventReference(jniEvent);
959
960 // Parse now if was asked
961 // Warning : THIS IS SLOW
962 if (isParsingNeeded) {
963 eventContent.getFields();
964 }
965
966 return currentLttngEvent;
967 } else {
968 return convertJniEventToTmfMultipleEventEvilFix(jniEvent, isParsingNeeded);
969 }
970
971 }
972
973 /**
974 * This method is a temporary fix to support multiple events at once in TMF This is expected to be slow and should
975 * be fixed in another way. See comment in convertJniEventToTmf();
976 *
977 * @param jniEvent
978 * The current JNI Event
979 * @return Current Lttng Event fully parsed
980 */
981 private synchronized LttngEvent convertJniEventToTmfMultipleEventEvilFix(JniEvent jniEvent, boolean isParsingNeeded) {
982 // *** HACK ***
983 // Below : the "fix" with all the new and the full-parse
984 // Allocating new memory is slow.
985 // Parsing every events is very slow.
986 eventTimestamp = new LttngTimestamp(jniEvent.getEventTime().getTime());
987 eventSource = jniEvent.requestEventSource();
988 eventReference = getName();
989 eventType = new LttngEventType(traceTypes.get(EventTypeKey.getEventTypeHash(jniEvent)));
990 eventContent = new LttngEventContent(currentLttngEvent);
991 currentLttngEvent = new LttngEvent(this, eventTimestamp, eventSource, eventType, eventContent, eventReference,
992 null);
993
994 // The jni reference is no longer reliable but we will keep it anyhow
995 currentLttngEvent.updateJniEventReference(jniEvent);
996 // Ensure that the content is correctly set
997 eventContent.setEvent(currentLttngEvent);
998
999 // Parse the event if it was needed
1000 // *** WARNING ***
1001 // ONLY for testing, NOT parsing events with non-unique events WILL
1002 // result in segfault in the JVM
1003 if (isParsingNeeded) {
1004 eventContent.getFields();
1005 }
1006
1007 return currentLttngEvent;
1008 }
1009
1010 /**
1011 * Reference to the current LttngTrace we are reading from.
1012 * <p>
1013 *
1014 * Note : This bypass the framework and should not be use, except for testing!
1015 *
1016 * @return Reference to the current LttngTrace
1017 *
1018 * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace
1019 */
1020 public JniTrace getCurrentJniTrace() {
1021 return currentJniTrace;
1022 }
1023
1024 /**
1025 * Return a reference to the current LttngEvent we have in memory.
1026 *
1027 * @return The current (last read) LttngEvent
1028 *
1029 * @see org.eclipse.linuxtools.lttng.core.event.LttngEvent
1030 */
1031 public synchronized LttngEvent getCurrentEvent() {
1032 return currentLttngEvent;
1033 }
1034
1035 /**
1036 * Get the major version number for the current trace
1037 *
1038 * @return Version major or -1 if unknown
1039 *
1040 * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace
1041 *
1042 */
1043 public short getVersionMajor() {
1044 if (currentJniTrace != null) {
1045 return currentJniTrace.getLttMajorVersion();
1046 } else {
1047 return -1;
1048 }
1049 }
1050
1051 /**
1052 * Get the minor version number for the current trace
1053 *
1054 * @return Version minor or -1 if unknown
1055 *
1056 * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace
1057 *
1058 */
1059 public short getVersionMinor() {
1060 if (currentJniTrace != null) {
1061 return currentJniTrace.getLttMinorVersion();
1062 } else {
1063 return -1;
1064 }
1065 }
1066
1067 /**
1068 * Get the number of CPU for this trace
1069 *
1070 * @return Number of CPU or -1 if unknown
1071 *
1072 * @see org.eclipse.linuxtools.org.eclipse.linuxtools.lttng.jni.JniTrace
1073 *
1074 */
1075 public int getCpuNumber() {
1076 if (currentJniTrace != null) {
1077 return currentJniTrace.getCpuNumber();
1078 } else {
1079 return -1;
1080 }
1081 }
1082
1083 /**
1084 * Print the content of the checkpoint vector.
1085 * <p>
1086 *
1087 * This is intended for debug purpose only.
1088 */
1089 public void printCheckpointsVector() {
1090 System.out.println("StartTime : " //$NON-NLS-1$
1091 + getTimeRange().getStartTime().getValue());
1092 System.out.println("EndTime : " //$NON-NLS-1$
1093 + getTimeRange().getEndTime().getValue());
1094
1095 for (int pos = 0; pos < fCheckpoints.size(); pos++) {
1096 System.out.print(pos + ": " + "\t"); //$NON-NLS-1$ //$NON-NLS-2$
1097 System.out.print(fCheckpoints.get(pos).getTimestamp() + "\t"); //$NON-NLS-1$
1098 System.out.println(fCheckpoints.get(pos).getLocation());
1099 }
1100 }
1101
1102 @Override
1103 public synchronized void dispose() {
1104 if (currentJniTrace != null)
1105 currentJniTrace.closeTrace();
1106 super.dispose();
1107 }
1108
1109 /**
1110 * Return a String identifying this trace.
1111 *
1112 * @return String that identify this trace
1113 */
1114 @Override
1115 @SuppressWarnings("nls")
1116 public String toString() {
1117 String returnedData = "";
1118
1119 returnedData += "Path :" + getPath() + " ";
1120 returnedData += "Trace:" + currentJniTrace + " ";
1121 returnedData += "Event:" + currentLttngEvent;
1122
1123 return returnedData;
1124 }
1125
1126 }
1127
1128 /*
1129 * EventTypeKey inner class
1130 *
1131 * This class is used to make the process of generating the HashMap key more transparent and so less error prone to use
1132 */
1133 final class EventTypeKey {
1134 // *** WARNING ***
1135 // These two getEventTypeKey() functions should ALWAYS construct the key the
1136 // same ways!
1137 // Otherwise, every type search will fail!
1138
1139 // added final to encourage inlining.
1140
1141 // generating a hash code by hand to avoid a string creation
1142 final static public int getEventTypeHash(LttngEventType newEventType) {
1143 return generateHash(newEventType.getTracefileName(), newEventType.getCpuId(), newEventType.getMarkerName());
1144 }
1145
1146 final private static int generateHash(String traceFileName, long cpuNumber, String markerName) {
1147 // 0x1337 is a prime number. The number of CPUs is always under 8192 on
1148 // the current kernel, so this will work with the current linux kernel.
1149 int cpuHash = (int) (cpuNumber * (0x1337));
1150 return traceFileName.hashCode() ^ (cpuHash) ^ markerName.hashCode();
1151 }
1152
1153 // generating a hash code by hand to avoid a string creation
1154 final static public int getEventTypeHash(JniEvent newEvent) {
1155 return generateHash(newEvent.getParentTracefile().getTracefileName(), newEvent.getParentTracefile()
1156 .getCpuNumber(), newEvent.requestEventMarker().getName());
1157 }
1158
1159 }
This page took 0.058924 seconds and 5 git commands to generate.