1 /*******************************************************************************
2 * Copyright (c) 2009, 2014 Ericsson, École Polytechnique de Montréal
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
10 * Francois Chouinard - Initial API and implementation
11 * Francois Chouinard - Updated as per TMF Trace Model 1.0
12 * Patrick Tasse - Updated for removal of context clone
13 * Geneviève Bastien - Added timestamp transforms, its saving to file and
14 * timestamp creation functions
15 *******************************************************************************/
17 package org
.eclipse
.linuxtools
.tmf
.core
.trace
;
20 import java
.util
.Collections
;
21 import java
.util
.HashSet
;
22 import java
.util
.LinkedHashMap
;
24 import java
.util
.Map
.Entry
;
27 import org
.eclipse
.core
.resources
.IResource
;
28 import org
.eclipse
.core
.runtime
.IStatus
;
29 import org
.eclipse
.core
.runtime
.MultiStatus
;
30 import org
.eclipse
.core
.runtime
.Path
;
31 import org
.eclipse
.core
.runtime
.Status
;
32 import org
.eclipse
.linuxtools
.internal
.tmf
.core
.Activator
;
33 import org
.eclipse
.linuxtools
.tmf
.core
.analysis
.IAnalysisModule
;
34 import org
.eclipse
.linuxtools
.tmf
.core
.analysis
.IAnalysisModuleHelper
;
35 import org
.eclipse
.linuxtools
.tmf
.core
.analysis
.TmfAnalysisManager
;
36 import org
.eclipse
.linuxtools
.tmf
.core
.component
.TmfEventProvider
;
37 import org
.eclipse
.linuxtools
.tmf
.core
.event
.ITmfEvent
;
38 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.TmfAnalysisException
;
39 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.TmfTraceException
;
40 import org
.eclipse
.linuxtools
.tmf
.core
.request
.ITmfEventRequest
;
41 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfSignalHandler
;
42 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfSignalManager
;
43 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfTraceOpenedSignal
;
44 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfTraceRangeUpdatedSignal
;
45 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfTraceUpdatedSignal
;
46 import org
.eclipse
.linuxtools
.tmf
.core
.synchronization
.ITmfTimestampTransform
;
47 import org
.eclipse
.linuxtools
.tmf
.core
.synchronization
.TimestampTransformFactory
;
48 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.ITmfTimestamp
;
49 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.TmfNanoTimestamp
;
50 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.TmfTimeRange
;
51 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.TmfTimestamp
;
52 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.indexer
.ITmfTraceIndexer
;
53 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.indexer
.checkpoint
.TmfCheckpointIndexer
;
54 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.location
.ITmfLocation
;
57 * Abstract implementation of ITmfTrace.
59 * Since the concept of 'location' is trace specific, the concrete classes have
60 * to provide the related methods, namely:
62 * <li> public ITmfLocation<?> getCurrentLocation()
63 * <li> public double getLocationRatio(ITmfLocation<?> location)
64 * <li> public ITmfContext seekEvent(ITmfLocation<?> location)
65 * <li> public ITmfContext seekEvent(double ratio)
66 * <li> public IStatus validate(IProject project, String path)
68 * A concrete trace must provide its corresponding parser. A common way to
69 * accomplish this is by making the concrete class extend TmfTrace and
70 * implement ITmfEventParser.
72 * When constructing an event, the concrete trace should use the trace's
73 * timestamp transform to create the timestamp, by either transforming the
74 * parsed time value directly or by using the method createTimestamp().
76 * The concrete class can either specify its own indexer or use the provided
77 * TmfCheckpointIndexer (default). In this case, the trace cache size will be
78 * used as checkpoint interval.
81 * @author Francois Chouinard
84 * @see ITmfTraceIndexer
85 * @see ITmfEventParser
87 public abstract class TmfTrace
extends TmfEventProvider
implements ITmfTrace
, ITmfTraceCompleteness
{
89 // ------------------------------------------------------------------------
91 // ------------------------------------------------------------------------
93 // The resource used for persistent properties for this trace
94 private IResource fResource
;
99 // The trace cache page size
100 private int fCacheSize
= ITmfTrace
.DEFAULT_TRACE_CACHE_SIZE
;
102 // The number of events collected (so far)
103 private volatile long fNbEvents
= 0;
105 // The time span of the event stream
106 private ITmfTimestamp fStartTime
= TmfTimestamp
.BIG_BANG
;
107 private ITmfTimestamp fEndTime
= TmfTimestamp
.BIG_BANG
;
109 // The trace streaming interval (0 = no streaming)
110 private long fStreamingInterval
= 0;
113 private ITmfTraceIndexer fIndexer
;
116 private ITmfEventParser fParser
;
118 private ITmfTimestampTransform fTsTransform
;
120 private final Map
<String
, IAnalysisModule
> fAnalysisModules
=
121 Collections
.synchronizedMap(new LinkedHashMap
<String
, IAnalysisModule
>());
123 // ------------------------------------------------------------------------
125 // ------------------------------------------------------------------------
128 * The default, parameterless, constructor
132 fIndexer
= createIndexer(DEFAULT_BLOCK_SIZE
);
139 * The resource associated to the trace
141 * The type of events that will be read from this trace
143 * The path to the trace on the filesystem
145 * The trace cache size. Pass '-1' to use the default specified
146 * in {@link ITmfTrace#DEFAULT_TRACE_CACHE_SIZE}
148 * The trace streaming interval. You can use '0' for post-mortem
151 * The trace event parser. Use 'null' if (and only if) the trace
152 * object itself is also the ITmfEventParser to be used.
153 * @throws TmfTraceException
154 * If something failed during the opening
156 protected TmfTrace(final IResource resource
,
157 final Class
<?
extends ITmfEvent
> type
,
161 final ITmfEventParser parser
)
162 throws TmfTraceException
{
164 fCacheSize
= (cacheSize
> 0) ? cacheSize
: ITmfTrace
.DEFAULT_TRACE_CACHE_SIZE
;
165 fStreamingInterval
= interval
;
167 initialize(resource
, path
, type
);
173 * @param trace the original trace
174 * @throws TmfTraceException Should not happen usually
176 public TmfTrace(final TmfTrace trace
) throws TmfTraceException
{
179 throw new IllegalArgumentException();
181 fCacheSize
= trace
.getCacheSize();
182 fStreamingInterval
= trace
.getStreamingInterval();
183 fParser
= trace
.fParser
;
184 initialize(trace
.getResource(), trace
.getPath(), trace
.getEventType());
188 * Creates the indexer instance. Classes extending this class can override
189 * this to provide a different indexer implementation.
191 * @param interval the checkpoints interval
193 * @return the indexer
196 protected ITmfTraceIndexer
createIndexer(int interval
) {
197 return new TmfCheckpointIndexer(this, interval
);
200 // ------------------------------------------------------------------------
201 // ITmfTrace - Initializers
202 // ------------------------------------------------------------------------
205 public void initTrace(final IResource resource
, final String path
, final Class
<?
extends ITmfEvent
> type
, String name
) throws TmfTraceException
{
207 initTrace(resource
, path
, type
);
211 public void initTrace(final IResource resource
, final String path
, final Class
<?
extends ITmfEvent
> type
) throws TmfTraceException
{
212 initialize(resource
, path
, type
);
216 * Initialize the trace common attributes and the base component.
218 * @param resource the Eclipse resource (trace)
219 * @param path the trace path
220 * @param type the trace event type
222 * @throws TmfTraceException If something failed during the initialization
224 protected void initialize(final IResource resource
,
226 final Class
<?
extends ITmfEvent
> type
)
227 throws TmfTraceException
{
229 throw new TmfTraceException("Invalid trace path"); //$NON-NLS-1$
232 fResource
= resource
;
233 String traceName
= getName();
234 if (traceName
== null || traceName
.isEmpty()) {
235 traceName
= (resource
!= null) ? resource
.getName() : new Path(path
).lastSegment();
237 if (fParser
== null) {
238 if (this instanceof ITmfEventParser
) {
239 fParser
= (ITmfEventParser
) this;
241 throw new TmfTraceException("Invalid trace parser"); //$NON-NLS-1$
244 super.init(traceName
, type
);
245 // register as VIP after super.init() because TmfComponent registers to signal manager there
246 TmfSignalManager
.registerVIP(this);
247 if (fIndexer
!= null) {
250 fIndexer
= createIndexer(fCacheSize
);
254 * Indicates if the path points to an existing file/directory
256 * @param path the path to test
257 * @return true if the file/directory exists
259 protected boolean fileExists(final String path
) {
260 final File file
= new File(path
);
261 return file
.exists();
268 public void indexTrace(boolean waitForCompletion
) {
269 getIndexer().buildIndex(0, TmfTimeRange
.ETERNITY
, waitForCompletion
);
273 * Instantiate the applicable analysis modules and executes the analysis
274 * modules that are meant to be automatically executed
276 * @return An IStatus indicating whether the analysis could be run
277 * successfully or not
280 protected IStatus
executeAnalysis() {
281 MultiStatus status
= new MultiStatus(Activator
.PLUGIN_ID
, IStatus
.OK
, null, null);
282 Map
<String
, IAnalysisModuleHelper
> modules
= TmfAnalysisManager
.getAnalysisModules(this.getClass());
283 for (IAnalysisModuleHelper helper
: modules
.values()) {
285 IAnalysisModule module
= helper
.newModule(this);
286 fAnalysisModules
.put(module
.getId(), module
);
287 if (module
.isAutomatic()) {
288 status
.add(module
.schedule());
290 } catch (TmfAnalysisException e
) {
291 status
.add(new Status(IStatus
.WARNING
, Activator
.PLUGIN_ID
, e
.getMessage()));
301 public IAnalysisModule
getAnalysisModule(String analysisId
) {
302 return fAnalysisModules
.get(analysisId
);
310 public Iterable
<IAnalysisModule
> getAnalysisModules() {
311 synchronized (fAnalysisModules
) {
312 Set
<IAnalysisModule
> modules
= new HashSet
<>(fAnalysisModules
.values());
321 public <T
extends IAnalysisModule
> T
getAnalysisModuleOfClass(Class
<T
> moduleClass
, String id
) {
322 Iterable
<T
> modules
= getAnalysisModulesOfClass(moduleClass
);
323 for (T module
: modules
) {
324 if (id
.equals(module
.getId())) {
335 public <T
> Iterable
<T
> getAnalysisModulesOfClass(Class
<T
> moduleClass
) {
336 Set
<T
> modules
= new HashSet
<>();
337 synchronized (fAnalysisModules
) {
338 for (Entry
<String
, IAnalysisModule
> entry
: fAnalysisModules
.entrySet()) {
339 if (moduleClass
.isAssignableFrom(entry
.getValue().getClass())) {
340 modules
.add(moduleClass
.cast(entry
.getValue()));
351 public synchronized void dispose() {
352 /* Clean up the index if applicable */
353 if (getIndexer() != null) {
354 getIndexer().dispose();
357 /* Clean up the analysis modules */
358 synchronized (fAnalysisModules
) {
359 for (IAnalysisModule module
: fAnalysisModules
.values()) {
362 fAnalysisModules
.clear();
368 // ------------------------------------------------------------------------
369 // ITmfTrace - Basic getters
370 // ------------------------------------------------------------------------
373 public Class
<?
extends ITmfEvent
> getEventType() {
374 return super.getType();
378 public IResource
getResource() {
383 public String
getPath() {
388 public int getCacheSize() {
393 public long getStreamingInterval() {
394 return fStreamingInterval
;
398 * @return the trace indexer
401 protected ITmfTraceIndexer
getIndexer() {
406 * @return the trace parser
408 protected ITmfEventParser
getParser() {
412 // ------------------------------------------------------------------------
413 // ITmfTrace - Trace characteristics getters
414 // ------------------------------------------------------------------------
417 public long getNbEvents() {
425 public TmfTimeRange
getTimeRange() {
426 return new TmfTimeRange(fStartTime
, fEndTime
);
433 public ITmfTimestamp
getStartTime() {
441 public ITmfTimestamp
getEndTime() {
449 public ITmfTimestamp
getInitialRangeOffset() {
450 final long DEFAULT_INITIAL_OFFSET_VALUE
= (1L * 100 * 1000 * 1000); // .1sec
451 return new TmfTimestamp(DEFAULT_INITIAL_OFFSET_VALUE
, ITmfTimestamp
.NANOSECOND_SCALE
);
458 public String
getHostId() {
459 return this.getName();
462 // ------------------------------------------------------------------------
463 // Convenience setters
464 // ------------------------------------------------------------------------
467 * Set the trace cache size. Must be done at initialization time.
469 * @param cacheSize The trace cache size
471 protected void setCacheSize(final int cacheSize
) {
472 fCacheSize
= cacheSize
;
476 * Set the trace known number of events. This can be quite dynamic
477 * during indexing or for live traces.
479 * @param nbEvents The number of events
481 protected synchronized void setNbEvents(final long nbEvents
) {
482 fNbEvents
= (nbEvents
> 0) ? nbEvents
: 0;
486 * Update the trace events time range
488 * @param range the new time range
491 protected void setTimeRange(final TmfTimeRange range
) {
492 fStartTime
= range
.getStartTime();
493 fEndTime
= range
.getEndTime();
497 * Update the trace chronologically first event timestamp
499 * @param startTime the new first event timestamp
502 protected void setStartTime(final ITmfTimestamp startTime
) {
503 fStartTime
= startTime
;
507 * Update the trace chronologically last event timestamp
509 * @param endTime the new last event timestamp
512 protected void setEndTime(final ITmfTimestamp endTime
) {
517 * Set the polling interval for live traces (default = 0 = no streaming).
519 * @param interval the new trace streaming interval
521 protected void setStreamingInterval(final long interval
) {
522 fStreamingInterval
= (interval
> 0) ? interval
: 0;
526 * Set the trace parser. Must be done at initialization time.
528 * @param parser the new trace parser
530 protected void setParser(final ITmfEventParser parser
) {
534 // ------------------------------------------------------------------------
535 // ITmfTrace - SeekEvent operations (returning a trace context)
536 // ------------------------------------------------------------------------
539 public synchronized ITmfContext
seekEvent(final long rank
) {
541 // A rank <= 0 indicates to seek the first event
543 ITmfContext context
= seekEvent((ITmfLocation
) null);
548 // Position the trace at the checkpoint
549 final ITmfContext context
= fIndexer
.seekIndex(rank
);
551 // And locate the requested event context
552 long pos
= context
.getRank();
554 ITmfEvent event
= getNext(context
);
555 while ((event
!= null) && (++pos
< rank
)) {
556 event
= getNext(context
);
566 public synchronized ITmfContext
seekEvent(final ITmfTimestamp timestamp
) {
568 // A null timestamp indicates to seek the first event
569 if (timestamp
== null) {
570 ITmfContext context
= seekEvent((ITmfLocation
) null);
575 // Position the trace at the checkpoint
576 ITmfContext context
= fIndexer
.seekIndex(timestamp
);
578 // And locate the requested event context
579 ITmfLocation previousLocation
= context
.getLocation();
580 long previousRank
= context
.getRank();
581 ITmfEvent event
= getNext(context
);
582 while (event
!= null && event
.getTimestamp().compareTo(timestamp
, false) < 0) {
583 previousLocation
= context
.getLocation();
584 previousRank
= context
.getRank();
585 event
= getNext(context
);
588 context
.setLocation(null);
589 context
.setRank(ITmfContext
.UNKNOWN_RANK
);
592 context
= seekEvent(previousLocation
);
593 context
.setRank(previousRank
);
598 // ------------------------------------------------------------------------
599 // ITmfTrace - Read operations (returning an actual event)
600 // ------------------------------------------------------------------------
603 public synchronized ITmfEvent
getNext(final ITmfContext context
) {
604 // parseEvent() does not update the context
605 final ITmfEvent event
= fParser
.parseEvent(context
);
607 updateAttributes(context
, event
.getTimestamp());
608 context
.setLocation(getCurrentLocation());
609 context
.increaseRank();
616 * Hook for special event processing by the concrete class
617 * (called by TmfTrace.getEvent())
619 * @param event the event
621 protected void processEvent(final ITmfEvent event
) {
626 * Update the trace attributes
628 * @param context the current trace context
629 * @param timestamp the corresponding timestamp
632 protected synchronized void updateAttributes(final ITmfContext context
, final ITmfTimestamp timestamp
) {
633 if (fStartTime
.equals(TmfTimestamp
.BIG_BANG
) || (fStartTime
.compareTo(timestamp
, false) > 0)) {
634 fStartTime
= timestamp
;
636 if (fEndTime
.equals(TmfTimestamp
.BIG_CRUNCH
) || (fEndTime
.compareTo(timestamp
, false) < 0)) {
637 fEndTime
= timestamp
;
639 if (context
.hasValidRank()) {
640 long rank
= context
.getRank();
641 if (fNbEvents
<= rank
) {
642 fNbEvents
= rank
+ 1;
644 if (fIndexer
!= null) {
645 fIndexer
.updateIndex(context
, timestamp
);
650 // ------------------------------------------------------------------------
652 // ------------------------------------------------------------------------
658 public synchronized ITmfContext
armRequest(final ITmfEventRequest request
) {
659 if (executorIsShutdown()) {
662 if (!TmfTimestamp
.BIG_BANG
.equals(request
.getRange().getStartTime())
663 && (request
.getIndex() == 0)) {
664 final ITmfContext context
= seekEvent(request
.getRange().getStartTime());
665 request
.setStartIndex((int) context
.getRank());
669 return seekEvent(request
.getIndex());
672 // ------------------------------------------------------------------------
674 // ------------------------------------------------------------------------
677 * Handler for the Trace Opened signal
680 * The incoming signal
684 public void traceOpened(TmfTraceOpenedSignal signal
) {
685 boolean signalIsForUs
= false;
686 for (ITmfTrace trace
: TmfTraceManager
.getTraceSet(signal
.getTrace())) {
688 signalIsForUs
= true;
693 if (!signalIsForUs
) {
698 * The signal is either for this trace, or for an experiment containing
701 IStatus status
= executeAnalysis();
702 if (!status
.isOK()) {
703 Activator
.log(status
);
706 TmfTraceManager
.refreshSupplementaryFiles(this);
708 if (signal
.getTrace() == this) {
709 /* Additionally, the signal is directly for this trace. */
710 if (getNbEvents() == 0) {
714 /* For a streaming trace, the range updated signal should be sent
715 * by the subclass when a new safe time is determined.
717 if (getStreamingInterval() > 0) {
722 final TmfTimeRange timeRange
= new TmfTimeRange(getStartTime(), TmfTimestamp
.BIG_CRUNCH
);
723 final TmfTraceRangeUpdatedSignal rangeUpdatedsignal
= new TmfTraceRangeUpdatedSignal(this, this, timeRange
);
725 // Broadcast in separate thread to prevent deadlock
726 broadcastAsync(rangeUpdatedsignal
);
733 * Signal handler for the TmfTraceRangeUpdatedSignal signal
735 * @param signal The incoming signal
739 public void traceRangeUpdated(final TmfTraceRangeUpdatedSignal signal
) {
740 if (signal
.getTrace() == this) {
741 getIndexer().buildIndex(getNbEvents(), signal
.getRange(), false);
746 * Signal handler for the TmfTraceUpdatedSignal signal
748 * @param signal The incoming signal
752 public void traceUpdated(final TmfTraceUpdatedSignal signal
) {
753 if (signal
.getSource() == getIndexer()) {
754 fNbEvents
= signal
.getNbEvents();
755 fStartTime
= signal
.getRange().getStartTime();
756 fEndTime
= signal
.getRange().getEndTime();
760 // ------------------------------------------------------------------------
761 // Timestamp transformation functions
762 // ------------------------------------------------------------------------
768 public ITmfTimestampTransform
getTimestampTransform() {
769 if (fTsTransform
== null) {
770 fTsTransform
= TimestampTransformFactory
.getTimestampTransform(getResource());
779 public void setTimestampTransform(final ITmfTimestampTransform tt
) {
781 TimestampTransformFactory
.setTimestampTransform(getResource(), tt
);
788 public ITmfTimestamp
createTimestamp(long ts
) {
789 return new TmfNanoTimestamp(getTimestampTransform().transform(ts
));
792 // ------------------------------------------------------------------------
794 // ------------------------------------------------------------------------
797 @SuppressWarnings("nls")
798 public synchronized String
toString() {
799 return "TmfTrace [fPath=" + fPath
+ ", fCacheSize=" + fCacheSize
800 + ", fNbEvents=" + fNbEvents
+ ", fStartTime=" + fStartTime
801 + ", fEndTime=" + fEndTime
+ ", fStreamingInterval=" + fStreamingInterval
+ "]";
808 public boolean isComplete() {
810 * Be default, all traces are "complete" which means no more data will
820 public void setComplete(boolean isComplete
) {
822 * This should be overridden by trace classes that can support live
823 * reading (traces in an incomplete state)