4bc464bc27150468d8e53a08497bd51c22d4f059
[deliverable/tracecompass.git] / ctf / org.eclipse.tracecompass.tmf.ctf.core / src / org / eclipse / tracecompass / tmf / ctf / core / trace / CtfTmfTrace.java
1 /*******************************************************************************
2 * Copyright (c) 2012, 2015 Ericsson, École Polytechnique de Montréal
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:
10 * Matthew Khouzam - Initial API and implementation
11 * Patrick Tasse - Updated for removal of context clone
12 * Geneviève Bastien - Added the createTimestamp function
13 *******************************************************************************/
14
15 package org.eclipse.tracecompass.tmf.ctf.core.trace;
16
17 import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull;
18
19 import java.nio.BufferOverflowException;
20 import java.nio.ByteBuffer;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28
29 import org.eclipse.core.resources.IProject;
30 import org.eclipse.core.resources.IResource;
31 import org.eclipse.core.runtime.CoreException;
32 import org.eclipse.core.runtime.IStatus;
33 import org.eclipse.core.runtime.Status;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.eclipse.tracecompass.ctf.core.CTFException;
36 import org.eclipse.tracecompass.ctf.core.event.CTFClock;
37 import org.eclipse.tracecompass.ctf.core.event.IEventDeclaration;
38 import org.eclipse.tracecompass.ctf.core.event.types.StructDeclaration;
39 import org.eclipse.tracecompass.ctf.core.trace.CTFTrace;
40 import org.eclipse.tracecompass.ctf.core.trace.CTFTraceReader;
41 import org.eclipse.tracecompass.ctf.core.trace.Metadata;
42 import org.eclipse.tracecompass.internal.tmf.ctf.core.Activator;
43 import org.eclipse.tracecompass.internal.tmf.ctf.core.trace.iterator.CtfIterator;
44 import org.eclipse.tracecompass.internal.tmf.ctf.core.trace.iterator.CtfIteratorManager;
45 import org.eclipse.tracecompass.tmf.core.event.ITmfEvent;
46 import org.eclipse.tracecompass.tmf.core.event.ITmfEventField;
47 import org.eclipse.tracecompass.tmf.core.event.TmfEventField;
48 import org.eclipse.tracecompass.tmf.core.event.aspect.ITmfEventAspect;
49 import org.eclipse.tracecompass.tmf.core.exceptions.TmfTraceException;
50 import org.eclipse.tracecompass.tmf.core.timestamp.ITmfTimestamp;
51 import org.eclipse.tracecompass.tmf.core.timestamp.TmfNanoTimestamp;
52 import org.eclipse.tracecompass.tmf.core.timestamp.TmfTimestamp;
53 import org.eclipse.tracecompass.tmf.core.trace.ITmfContext;
54 import org.eclipse.tracecompass.tmf.core.trace.ITmfTraceProperties;
55 import org.eclipse.tracecompass.tmf.core.trace.ITmfTraceWithPreDefinedEvents;
56 import org.eclipse.tracecompass.tmf.core.trace.TmfTrace;
57 import org.eclipse.tracecompass.tmf.core.trace.TraceValidationStatus;
58 import org.eclipse.tracecompass.tmf.core.trace.indexer.ITmfPersistentlyIndexable;
59 import org.eclipse.tracecompass.tmf.core.trace.indexer.ITmfTraceIndexer;
60 import org.eclipse.tracecompass.tmf.core.trace.indexer.TmfBTreeTraceIndexer;
61 import org.eclipse.tracecompass.tmf.core.trace.indexer.checkpoint.ITmfCheckpoint;
62 import org.eclipse.tracecompass.tmf.core.trace.indexer.checkpoint.TmfCheckpoint;
63 import org.eclipse.tracecompass.tmf.core.trace.location.ITmfLocation;
64 import org.eclipse.tracecompass.tmf.ctf.core.CtfConstants;
65 import org.eclipse.tracecompass.tmf.ctf.core.context.CtfLocation;
66 import org.eclipse.tracecompass.tmf.ctf.core.context.CtfLocationInfo;
67 import org.eclipse.tracecompass.tmf.ctf.core.context.CtfTmfContext;
68 import org.eclipse.tracecompass.tmf.ctf.core.event.CtfTmfEvent;
69 import org.eclipse.tracecompass.tmf.ctf.core.event.CtfTmfEventFactory;
70 import org.eclipse.tracecompass.tmf.ctf.core.event.CtfTmfEventType;
71 import org.eclipse.tracecompass.tmf.ctf.core.event.aspect.CtfChannelAspect;
72 import org.eclipse.tracecompass.tmf.ctf.core.event.aspect.CtfCpuAspect;
73
74 import com.google.common.collect.ImmutableList;
75 import com.google.common.collect.ImmutableSet;
76
77 /**
78 * The CTf trace handler
79 *
80 * @version 1.0
81 * @author Matthew khouzam
82 */
83 public class CtfTmfTrace extends TmfTrace
84 implements ITmfTraceProperties, ITmfPersistentlyIndexable,
85 ITmfTraceWithPreDefinedEvents {
86
87 // -------------------------------------------
88 // Constants
89 // -------------------------------------------
90
91 /**
92 * Default cache size for CTF traces
93 */
94 protected static final int DEFAULT_CACHE_SIZE = 50000;
95
96 /**
97 * Event aspects available for all CTF traces
98 * @since 1.0
99 */
100 protected static final @NonNull Collection<@NonNull ITmfEventAspect> CTF_ASPECTS =
101 checkNotNull(ImmutableList.of(
102 ITmfEventAspect.BaseAspects.TIMESTAMP,
103 new CtfChannelAspect(),
104 new CtfCpuAspect(),
105 ITmfEventAspect.BaseAspects.EVENT_TYPE,
106 ITmfEventAspect.BaseAspects.CONTENTS
107 ));
108
109 /**
110 * The Ctf clock unique identifier field
111 */
112 private static final String CLOCK_HOST_PROPERTY = "uuid"; //$NON-NLS-1$
113 private static final int CONFIDENCE = 10;
114 private static final int MIN_CONFIDENCE = 1;
115
116 // -------------------------------------------
117 // Fields
118 // -------------------------------------------
119
120 private final Map<@NonNull String, @NonNull CtfTmfEventType> fContainedEventTypes =
121 Collections.synchronizedMap(new HashMap<>());
122
123 private final CtfIteratorManager fIteratorManager = new CtfIteratorManager(this);
124
125 private final @NonNull CtfTmfEventFactory fEventFactory;
126
127 /** Reference to the CTF Trace */
128 private CTFTrace fTrace;
129
130 // -------------------------------------------
131 // Constructor
132 // -------------------------------------------
133
134 /**
135 * Default constructor
136 */
137 public CtfTmfTrace() {
138 super();
139
140 /* Use default event factory */
141 fEventFactory = CtfTmfEventFactory.instance();
142 }
143
144 /**
145 * Constructor for sub-classes to specify their own event factory.
146 *
147 * @param eventFactory
148 * The event factory to use to generate trace events
149 * @since 2.0
150 */
151 protected CtfTmfTrace(@NonNull CtfTmfEventFactory eventFactory) {
152 super();
153 fEventFactory = eventFactory;
154 }
155
156 // -------------------------------------------
157 // TmfTrace Overrides
158 // -------------------------------------------
159 /**
160 * Method initTrace.
161 *
162 * @param resource
163 * The resource associated with this trace
164 * @param path
165 * The path to the trace file
166 * @param eventType
167 * The type of events that will be read from this trace
168 * @throws TmfTraceException
169 * If something went wrong while reading the trace
170 */
171 @Override
172 public void initTrace(final IResource resource, final String path, final Class<? extends ITmfEvent> eventType)
173 throws TmfTraceException {
174 /*
175 * Set the cache size. This has to be done before the call to super()
176 * because the super needs to know the cache size.
177 */
178 setCacheSize();
179
180 super.initTrace(resource, path, eventType);
181
182 try {
183 this.fTrace = new CTFTrace(path);
184 CtfTmfContext ctx;
185 /* Set the start and (current) end times for this trace */
186 ctx = (CtfTmfContext) seekEvent(0L);
187 CtfTmfEvent event = getNext(ctx);
188 if ((ctx.getLocation().equals(CtfIterator.NULL_LOCATION)) || (ctx.getCurrentEvent() == null)) {
189 /* Handle the case where the trace is empty */
190 this.setStartTime(TmfTimestamp.BIG_BANG);
191 } else {
192 final ITmfTimestamp curTime = event.getTimestamp();
193 this.setStartTime(curTime);
194 this.setEndTime(curTime);
195 }
196 /*
197 * Register every event type. When you call getType, it will
198 * register a trace to that type in the TmfEventTypeManager
199 */
200 try (CtfIterator iter = fIteratorManager.getIterator(ctx)) {
201 for (IEventDeclaration ied : iter.getEventDeclarations()) {
202 CtfTmfEventType ctfTmfEventType = fContainedEventTypes.get(ied.getName());
203 if (ctfTmfEventType == null) {
204 List<ITmfEventField> content = new ArrayList<>();
205 /* Should only return null the first time */
206 final StructDeclaration fields = ied.getFields();
207 if (fields != null) {
208 for (String fieldName : fields.getFieldsList()) {
209 content.add(new TmfEventField(checkNotNull(fieldName), null, null));
210 }
211 ITmfEventField contentTree = new TmfEventField(
212 ITmfEventField.ROOT_FIELD_ID,
213 null,
214 content.toArray(new ITmfEventField[content.size()]));
215
216 ctfTmfEventType = new CtfTmfEventType(ied.getName(), contentTree);
217 fContainedEventTypes.put(ctfTmfEventType.getName(), ctfTmfEventType);
218 }
219 }
220 }
221 }
222 ctx.dispose();
223 } catch (final CTFException e) {
224 /*
225 * If it failed at the init(), we can assume it's because the file
226 * was not found or was not recognized as a CTF trace. Throw into
227 * the new type of exception expected by the rest of TMF.
228 */
229 throw new TmfTraceException(e.getMessage(), e);
230 }
231 }
232
233 @Override
234 public synchronized void dispose() {
235 fIteratorManager.dispose();
236 if (fTrace != null) {
237 fTrace = null;
238 }
239 super.dispose();
240 }
241
242 /**
243 * {@inheritDoc}
244 * <p>
245 * The default implementation of a CTF trace.
246 *
247 * Firstly a weak validation of the metadata is done to determine if the
248 * path is actually for a CTF trace. After that a full validation is done.
249 *
250 * If the weak and full validation are successful the confidence is set
251 * to 10.
252 *
253 * If the weak validation was successful, but the full validation fails
254 * a TraceValidationStatus with severity warning and confidence of 1 is
255 * returned.
256 *
257 * If both weak and full validation fails an error status is returned.
258 */
259 @Override
260 public IStatus validate(final IProject project, final String path) {
261 boolean isMetadataFile = false;
262 try {
263 isMetadataFile = Metadata.preValidate(path);
264 } catch (final CTFException e) {
265 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.CtfTmfTrace_ReadingError + ": " + e.toString(), e); //$NON-NLS-1$
266 }
267
268 if (isMetadataFile) {
269 // Trace is pre-validated, continue will full validation
270 try {
271 final CTFTrace trace = new CTFTrace(path);
272 if (!trace.majorIsSet()) {
273 if (isMetadataFile) {
274 return new TraceValidationStatus(MIN_CONFIDENCE, IStatus.WARNING, Activator.PLUGIN_ID, Messages.CtfTmfTrace_MajorNotSet, null);
275 }
276 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.CtfTmfTrace_MajorNotSet);
277 }
278
279 // Validate using reader initialization
280 try (CTFTraceReader ctfTraceReader = new CTFTraceReader(trace)) {}
281
282 // Trace is validated, return with confidence
283 return new CtfTraceValidationStatus(CONFIDENCE, Activator.PLUGIN_ID, trace.getEnvironment());
284
285 } catch (final CTFException | BufferOverflowException e ) {
286 // return warning since it's a CTF trace but with errors in it
287 return new TraceValidationStatus(MIN_CONFIDENCE, IStatus.WARNING, Activator.PLUGIN_ID, Messages.CtfTmfTrace_ReadingError + ": " + e.toString(), e); //$NON-NLS-1$
288 }
289 }
290 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, Messages.CtfTmfTrace_ReadingError);
291 }
292
293 @Override
294 public Iterable<ITmfEventAspect> getEventAspects() {
295 return CTF_ASPECTS;
296 }
297
298 /**
299 * Method getCurrentLocation. This is not applicable in CTF
300 *
301 * @return null, since the trace has no knowledge of the current location
302 * @see org.eclipse.tracecompass.tmf.core.trace.ITmfTrace#getCurrentLocation()
303 */
304 @Override
305 public ITmfLocation getCurrentLocation() {
306 return null;
307 }
308
309 @Override
310 public double getLocationRatio(ITmfLocation location) {
311 final CtfLocation curLocation = (CtfLocation) location;
312 final long startTime = getStartTime().getValue();
313 final double diff = curLocation.getLocationInfo().getTimestamp() - startTime;
314 final double total = getEndTime().getValue() - startTime;
315 return Math.max(0.0, Math.min(1.0, diff / total));
316 }
317
318 /**
319 * Method seekEvent.
320 *
321 * @param location
322 * ITmfLocation<?>
323 * @return ITmfContext
324 */
325 @Override
326 public synchronized ITmfContext seekEvent(final ITmfLocation location) {
327 CtfLocation currentLocation = (CtfLocation) location;
328 CtfTmfContext context = new CtfTmfContext(this);
329 if (fTrace == null) {
330 context.setLocation(null);
331 context.setRank(ITmfContext.UNKNOWN_RANK);
332 return context;
333 }
334 /*
335 * The rank is set to 0 if the iterator seeks the beginning. If not, it
336 * will be set to UNKNOWN_RANK, since CTF traces don't support seeking
337 * by rank for now.
338 */
339 if (currentLocation == null) {
340 currentLocation = new CtfLocation(new CtfLocationInfo(0L, 0L));
341 context.setRank(0);
342 } else {
343 context.setRank(ITmfContext.UNKNOWN_RANK);
344 }
345 /* This will seek and update the location after the seek */
346 context.setLocation(currentLocation);
347 return context;
348 }
349
350 @Override
351 public synchronized ITmfContext seekEvent(double ratio) {
352 CtfTmfContext context = new CtfTmfContext(this);
353 if (fTrace == null) {
354 context.setLocation(null);
355 context.setRank(ITmfContext.UNKNOWN_RANK);
356 return context;
357 }
358 final long end = getEndTime().getValue();
359 final long start = getStartTime().getValue();
360 final long diff = end - start;
361 final long ratioTs = Math.round(diff * ratio) + start;
362 context.seek(ratioTs);
363 context.setRank(ITmfContext.UNKNOWN_RANK);
364 return context;
365 }
366
367 /**
368 * Method readNextEvent.
369 *
370 * @param context
371 * ITmfContext
372 * @return CtfTmfEvent
373 * @see org.eclipse.tracecompass.tmf.core.trace.ITmfTrace#getNext(ITmfContext)
374 */
375 @Override
376 public synchronized CtfTmfEvent getNext(final ITmfContext context) {
377 if (fTrace == null) {
378 return null;
379 }
380 CtfTmfEvent event = null;
381 if (context instanceof CtfTmfContext) {
382 if (context.getLocation() == null || CtfLocation.INVALID_LOCATION.equals(context.getLocation().getLocationInfo())) {
383 return null;
384 }
385 CtfTmfContext ctfContext = (CtfTmfContext) context;
386 event = ctfContext.getCurrentEvent();
387
388 if (event != null) {
389 updateAttributes(context, event);
390 ctfContext.advance();
391 ctfContext.increaseRank();
392 }
393 }
394
395 return event;
396 }
397
398 /**
399 * Ctf traces have a clock with a unique uuid that will be used to identify
400 * the host. Traces with the same clock uuid will be known to have been made
401 * on the same machine.
402 *
403 * Note: uuid is an optional field, it may not be there for a clock.
404 */
405 @Override
406 public String getHostId() {
407 CTFClock clock = fTrace.getClock();
408 if (clock != null) {
409 String clockHost = (String) clock.getProperty(CLOCK_HOST_PROPERTY);
410 if (clockHost != null) {
411 return clockHost;
412 }
413 }
414 return super.getHostId();
415 }
416
417 /**
418 * Get the CTF environment variables defined in this CTF trace, in <name,
419 * value> form. This comes from the trace's CTF metadata.
420 *
421 * @return The CTF environment
422 */
423 public Map<String, String> getEnvironment() {
424 return fTrace.getEnvironment();
425 }
426
427 // -------------------------------------------
428 // ITmfTraceProperties
429 // -------------------------------------------
430
431 @Override
432 public Map<String, String> getTraceProperties() {
433 Map<String, String> properties = new HashMap<>();
434 properties.putAll(fTrace.getEnvironment());
435 properties.put(Messages.CtfTmfTrace_HostID, getHostId());
436 return properties;
437 }
438
439 // -------------------------------------------
440 // Clocks
441 // -------------------------------------------
442
443 /**
444 * gets the clock offset
445 *
446 * @return the clock offset in ns
447 */
448 public long getOffset() {
449 if (fTrace != null) {
450 return fTrace.getOffset();
451 }
452 return 0;
453 }
454
455 /**
456 * Convert a CTF timestamp in CPU cycles to its equivalent in nanoseconds
457 * for this trace.
458 *
459 * @param cycles
460 * The timestamp in cycles
461 * @return The timestamp in nanoseconds
462 */
463 public long timestampCyclesToNanos(long cycles) {
464 return fTrace.timestampCyclesToNanos(cycles);
465 }
466
467 /**
468 * Convert a CTF timestamp in nanoseconds to its equivalent in CPU cycles
469 * for this trace.
470 *
471 * @param nanos
472 * The timestamp in nanoseconds
473 * @return The timestamp in cycles
474 */
475 public long timestampNanoToCycles(long nanos) {
476 return fTrace.timestampNanoToCycles(nanos);
477 }
478
479 /**
480 * Gets the list of declared events
481 */
482 @Override
483 public Set<@NonNull CtfTmfEventType> getContainedEventTypes() {
484 return ImmutableSet.copyOf(fContainedEventTypes.values());
485 }
486
487 /**
488 * Register an event type to this trace.
489 *
490 * Public visibility so that {@link CtfTmfEvent#getType} can call it.
491 *
492 * FIXME This could probably be made cleaner?
493 *
494 * @param eventType
495 * The event type to register
496 */
497 public void registerEventType(CtfTmfEventType eventType) {
498 fContainedEventTypes.put(eventType.getName(), eventType);
499 }
500
501 // -------------------------------------------
502 // Parser
503 // -------------------------------------------
504
505 @Override
506 public CtfTmfEvent parseEvent(ITmfContext context) {
507 CtfTmfEvent event = null;
508 if (context instanceof CtfTmfContext) {
509 final ITmfContext tmpContext = seekEvent(context.getLocation());
510 event = getNext(tmpContext);
511 }
512 return event;
513 }
514
515 /**
516 * Sets the cache size for a CtfTmfTrace.
517 */
518 protected void setCacheSize() {
519 setCacheSize(DEFAULT_CACHE_SIZE);
520 }
521
522 // -------------------------------------------
523 // CtfIterator factory methods
524 // -------------------------------------------
525
526 /**
527 * Get the event factory for this trace to generate new events for it.
528 *
529 * @return The event factory
530 * @since 2.0
531 */
532 public @NonNull CtfTmfEventFactory getEventFactory() {
533 return fEventFactory;
534 }
535
536 /**
537 * Get an iterator to the trace
538 *
539 * @return an iterator to the trace
540 */
541 public ITmfContext createIterator() {
542 try {
543 return new CtfIterator(fTrace, this);
544 } catch (CTFException e) {
545 Activator.getDefault().logError(e.getMessage(), e);
546 }
547 return null;
548 }
549
550 /**
551 * Get an iterator to the trace, , which will initially point to the given
552 * location/rank.
553 *
554 * @param ctfLocationData
555 * The initial timestamp the iterator will be pointing to
556 * @param rank
557 * The initial rank
558 * @return The new iterator
559 */
560 public ITmfContext createIterator(CtfLocationInfo ctfLocationData, long rank) {
561 try {
562 return new CtfIterator(fTrace, this, ctfLocationData, rank);
563 } catch (CTFException e) {
564 Activator.getDefault().logError(e.getMessage(), e);
565 }
566 return null;
567 }
568
569 /**
570 * Create the 'CtfIterator' object from a CtfTmfContext.
571 *
572 * @param context
573 * The iterator will initially be pointing to this context
574 * @return A new CtfIterator object
575 * @since 1.0
576 */
577 public ITmfContext createIteratorFromContext(CtfTmfContext context) {
578 return fIteratorManager.getIterator(context);
579 }
580
581 /**
582 * Dispose an iterator that was create with
583 * {@link #createIteratorFromContext}
584 *
585 * @param context
586 * The last context that was pointed to by the iterator (this is
587 * the 'key' to find the correct iterator to dispose).
588 * @since 1.0
589 */
590 public void disposeContext(CtfTmfContext context) {
591 fIteratorManager.removeIterator(context);
592 }
593
594 // ------------------------------------------------------------------------
595 // Timestamp transformation functions
596 // ------------------------------------------------------------------------
597
598 /**
599 * @since 1.0
600 */
601 @Override
602 public @NonNull TmfNanoTimestamp createTimestamp(long ts) {
603 return new TmfNanoTimestamp(getTimestampTransform().transform(ts));
604 }
605
606 private static int fCheckpointSize = -1;
607
608 @Override
609 public synchronized int getCheckpointSize() {
610 if (fCheckpointSize == -1) {
611 TmfCheckpoint c = new TmfCheckpoint(new TmfNanoTimestamp(0), new CtfLocation(0, 0), 0);
612 ByteBuffer b = ByteBuffer.allocate(ITmfCheckpoint.MAX_SERIALIZE_SIZE);
613 b.clear();
614 c.serialize(b);
615 fCheckpointSize = b.position();
616 }
617
618 return fCheckpointSize;
619 }
620
621 @Override
622 protected ITmfTraceIndexer createIndexer(int interval) {
623 return new TmfBTreeTraceIndexer(this, interval);
624 }
625
626 @Override
627 public ITmfLocation restoreLocation(ByteBuffer bufferIn) {
628 return new CtfLocation(bufferIn);
629 }
630
631 @Override
632 public boolean isComplete() {
633 if (getResource() == null) {
634 return true;
635 }
636
637 String host = null;
638 String port = null;
639 String sessionName = null;
640 try {
641 host = getResource().getPersistentProperty(CtfConstants.LIVE_HOST);
642 port = getResource().getPersistentProperty(CtfConstants.LIVE_PORT);
643 sessionName = getResource().getPersistentProperty(CtfConstants.LIVE_SESSION_NAME);
644 } catch (CoreException e) {
645 Activator.getDefault().logError(e.getMessage(), e);
646 // Something happened to the resource, assume we won't get any more
647 // data from it
648 return true;
649 }
650 return host == null || port == null || sessionName == null;
651 }
652
653 @Override
654 public void setComplete(final boolean isComplete) {
655 super.setComplete(isComplete);
656 try {
657 if (isComplete) {
658 getResource().setPersistentProperty(CtfConstants.LIVE_HOST, null);
659 getResource().setPersistentProperty(CtfConstants.LIVE_PORT, null);
660 getResource().setPersistentProperty(CtfConstants.LIVE_SESSION_NAME, null);
661 }
662 } catch (CoreException e) {
663 Activator.getDefault().logError(e.getMessage(), e);
664 }
665 }
666 }
This page took 0.051425 seconds and 4 git commands to generate.