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
.tracecompass
.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
.tracecompass
.internal
.tmf
.core
.Activator
;
33 import org
.eclipse
.tracecompass
.tmf
.core
.analysis
.IAnalysisModule
;
34 import org
.eclipse
.tracecompass
.tmf
.core
.analysis
.IAnalysisModuleHelper
;
35 import org
.eclipse
.tracecompass
.tmf
.core
.analysis
.TmfAnalysisManager
;
36 import org
.eclipse
.tracecompass
.tmf
.core
.component
.TmfEventProvider
;
37 import org
.eclipse
.tracecompass
.tmf
.core
.event
.ITmfEvent
;
38 import org
.eclipse
.tracecompass
.tmf
.core
.exceptions
.TmfAnalysisException
;
39 import org
.eclipse
.tracecompass
.tmf
.core
.exceptions
.TmfTraceException
;
40 import org
.eclipse
.tracecompass
.tmf
.core
.request
.ITmfEventRequest
;
41 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalHandler
;
42 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalManager
;
43 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceOpenedSignal
;
44 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceRangeUpdatedSignal
;
45 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceUpdatedSignal
;
46 import org
.eclipse
.tracecompass
.tmf
.core
.synchronization
.ITmfTimestampTransform
;
47 import org
.eclipse
.tracecompass
.tmf
.core
.synchronization
.TimestampTransformFactory
;
48 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.ITmfTimestamp
;
49 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfNanoTimestamp
;
50 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimeRange
;
51 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimestamp
;
52 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.ITmfTraceIndexer
;
53 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.indexer
.checkpoint
.TmfCheckpointIndexer
;
54 import org
.eclipse
.tracecompass
.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 throw new IllegalArgumentException();
210 initTrace(resource
, path
, type
);
214 public void initTrace(final IResource resource
, final String path
, final Class
<?
extends ITmfEvent
> type
) throws TmfTraceException
{
215 initialize(resource
, path
, type
);
219 * Initialize the trace common attributes and the base component.
221 * @param resource the Eclipse resource (trace)
222 * @param path the trace path
223 * @param type the trace event type
225 * @throws TmfTraceException If something failed during the initialization
227 protected void initialize(final IResource resource
,
229 final Class
<?
extends ITmfEvent
> type
)
230 throws TmfTraceException
{
232 throw new TmfTraceException("Invalid trace path"); //$NON-NLS-1$
235 fResource
= resource
;
236 String traceName
= getName();
237 if (traceName
.isEmpty()) {
238 traceName
= (resource
!= null) ? resource
.getName() : new Path(path
).lastSegment();
240 if (fParser
== null) {
241 if (this instanceof ITmfEventParser
) {
242 fParser
= (ITmfEventParser
) this;
244 throw new TmfTraceException("Invalid trace parser"); //$NON-NLS-1$
247 super.init(traceName
, type
);
248 // register as VIP after super.init() because TmfComponent registers to signal manager there
249 TmfSignalManager
.registerVIP(this);
250 if (fIndexer
!= null) {
253 fIndexer
= createIndexer(fCacheSize
);
257 * Indicates if the path points to an existing file/directory
259 * @param path the path to test
260 * @return true if the file/directory exists
262 protected boolean fileExists(final String path
) {
263 final File file
= new File(path
);
264 return file
.exists();
271 public void indexTrace(boolean waitForCompletion
) {
272 getIndexer().buildIndex(0, TmfTimeRange
.ETERNITY
, waitForCompletion
);
276 * Instantiate the applicable analysis modules and executes the analysis
277 * modules that are meant to be automatically executed
279 * @return An IStatus indicating whether the analysis could be run
280 * successfully or not
283 protected IStatus
executeAnalysis() {
284 MultiStatus status
= new MultiStatus(Activator
.PLUGIN_ID
, IStatus
.OK
, null, null);
285 Map
<String
, IAnalysisModuleHelper
> modules
= TmfAnalysisManager
.getAnalysisModules(this.getClass());
286 for (IAnalysisModuleHelper helper
: modules
.values()) {
288 IAnalysisModule module
= helper
.newModule(this);
289 fAnalysisModules
.put(module
.getId(), module
);
290 if (module
.isAutomatic()) {
291 status
.add(module
.schedule());
293 } catch (TmfAnalysisException e
) {
294 status
.add(new Status(IStatus
.WARNING
, Activator
.PLUGIN_ID
, e
.getMessage()));
304 public IAnalysisModule
getAnalysisModule(String analysisId
) {
305 return fAnalysisModules
.get(analysisId
);
313 public Iterable
<IAnalysisModule
> getAnalysisModules() {
314 synchronized (fAnalysisModules
) {
315 Set
<IAnalysisModule
> modules
= new HashSet
<>(fAnalysisModules
.values());
324 public <T
extends IAnalysisModule
> T
getAnalysisModuleOfClass(Class
<T
> moduleClass
, String id
) {
325 Iterable
<T
> modules
= getAnalysisModulesOfClass(moduleClass
);
326 for (T module
: modules
) {
327 if (id
.equals(module
.getId())) {
338 public <T
> Iterable
<T
> getAnalysisModulesOfClass(Class
<T
> moduleClass
) {
339 Set
<T
> modules
= new HashSet
<>();
340 synchronized (fAnalysisModules
) {
341 for (Entry
<String
, IAnalysisModule
> entry
: fAnalysisModules
.entrySet()) {
342 if (moduleClass
.isAssignableFrom(entry
.getValue().getClass())) {
343 modules
.add(moduleClass
.cast(entry
.getValue()));
354 public synchronized void dispose() {
355 /* Clean up the index if applicable */
356 if (getIndexer() != null) {
357 getIndexer().dispose();
360 /* Clean up the analysis modules */
361 synchronized (fAnalysisModules
) {
362 for (IAnalysisModule module
: fAnalysisModules
.values()) {
365 fAnalysisModules
.clear();
371 // ------------------------------------------------------------------------
372 // ITmfTrace - Basic getters
373 // ------------------------------------------------------------------------
376 public Class
<?
extends ITmfEvent
> getEventType() {
377 return super.getType();
381 public IResource
getResource() {
386 public String
getPath() {
391 public int getCacheSize() {
396 public long getStreamingInterval() {
397 return fStreamingInterval
;
401 * @return the trace indexer
404 protected ITmfTraceIndexer
getIndexer() {
409 * @return the trace parser
411 protected ITmfEventParser
getParser() {
415 // ------------------------------------------------------------------------
416 // ITmfTrace - Trace characteristics getters
417 // ------------------------------------------------------------------------
420 public long getNbEvents() {
428 public TmfTimeRange
getTimeRange() {
429 return new TmfTimeRange(fStartTime
, fEndTime
);
436 public ITmfTimestamp
getStartTime() {
444 public ITmfTimestamp
getEndTime() {
452 public ITmfTimestamp
getInitialRangeOffset() {
453 final long DEFAULT_INITIAL_OFFSET_VALUE
= (1L * 100 * 1000 * 1000); // .1sec
454 return new TmfTimestamp(DEFAULT_INITIAL_OFFSET_VALUE
, ITmfTimestamp
.NANOSECOND_SCALE
);
461 public String
getHostId() {
462 return this.getName();
465 // ------------------------------------------------------------------------
466 // Convenience setters
467 // ------------------------------------------------------------------------
470 * Set the trace cache size. Must be done at initialization time.
472 * @param cacheSize The trace cache size
474 protected void setCacheSize(final int cacheSize
) {
475 fCacheSize
= cacheSize
;
479 * Set the trace known number of events. This can be quite dynamic
480 * during indexing or for live traces.
482 * @param nbEvents The number of events
484 protected synchronized void setNbEvents(final long nbEvents
) {
485 fNbEvents
= (nbEvents
> 0) ? nbEvents
: 0;
489 * Update the trace events time range
491 * @param range the new time range
494 protected void setTimeRange(final TmfTimeRange range
) {
495 fStartTime
= range
.getStartTime();
496 fEndTime
= range
.getEndTime();
500 * Update the trace chronologically first event timestamp
502 * @param startTime the new first event timestamp
505 protected void setStartTime(final ITmfTimestamp startTime
) {
506 fStartTime
= startTime
;
510 * Update the trace chronologically last event timestamp
512 * @param endTime the new last event timestamp
515 protected void setEndTime(final ITmfTimestamp endTime
) {
520 * Set the polling interval for live traces (default = 0 = no streaming).
522 * @param interval the new trace streaming interval
524 protected void setStreamingInterval(final long interval
) {
525 fStreamingInterval
= (interval
> 0) ? interval
: 0;
529 * Set the trace parser. Must be done at initialization time.
531 * @param parser the new trace parser
533 protected void setParser(final ITmfEventParser parser
) {
537 // ------------------------------------------------------------------------
538 // ITmfTrace - SeekEvent operations (returning a trace context)
539 // ------------------------------------------------------------------------
542 public synchronized ITmfContext
seekEvent(final long rank
) {
544 // A rank <= 0 indicates to seek the first event
546 ITmfContext context
= seekEvent((ITmfLocation
) null);
551 // Position the trace at the checkpoint
552 final ITmfContext context
= fIndexer
.seekIndex(rank
);
554 // And locate the requested event context
555 long pos
= context
.getRank();
557 ITmfEvent event
= getNext(context
);
558 while ((event
!= null) && (++pos
< rank
)) {
559 event
= getNext(context
);
569 public synchronized ITmfContext
seekEvent(final ITmfTimestamp timestamp
) {
571 // A null timestamp indicates to seek the first event
572 if (timestamp
== null) {
573 ITmfContext context
= seekEvent((ITmfLocation
) null);
578 // Position the trace at the checkpoint
579 ITmfContext context
= fIndexer
.seekIndex(timestamp
);
581 // And locate the requested event context
582 ITmfLocation previousLocation
= context
.getLocation();
583 long previousRank
= context
.getRank();
584 ITmfEvent event
= getNext(context
);
585 while (event
!= null && event
.getTimestamp().compareTo(timestamp
) < 0) {
586 previousLocation
= context
.getLocation();
587 previousRank
= context
.getRank();
588 event
= getNext(context
);
591 context
.setLocation(null);
592 context
.setRank(ITmfContext
.UNKNOWN_RANK
);
595 context
= seekEvent(previousLocation
);
596 context
.setRank(previousRank
);
601 // ------------------------------------------------------------------------
602 // ITmfTrace - Read operations (returning an actual event)
603 // ------------------------------------------------------------------------
606 public synchronized ITmfEvent
getNext(final ITmfContext context
) {
607 // parseEvent() does not update the context
608 final ITmfEvent event
= fParser
.parseEvent(context
);
610 updateAttributes(context
, event
.getTimestamp());
611 context
.setLocation(getCurrentLocation());
612 context
.increaseRank();
619 * Hook for special event processing by the concrete class
620 * (called by TmfTrace.getEvent())
622 * @param event the event
624 protected void processEvent(final ITmfEvent event
) {
629 * Update the trace attributes
631 * @param context the current trace context
632 * @param timestamp the corresponding timestamp
635 protected synchronized void updateAttributes(final ITmfContext context
, final ITmfTimestamp timestamp
) {
636 if (fStartTime
.equals(TmfTimestamp
.BIG_BANG
) || (fStartTime
.compareTo(timestamp
) > 0)) {
637 fStartTime
= timestamp
;
639 if (fEndTime
.equals(TmfTimestamp
.BIG_CRUNCH
) || (fEndTime
.compareTo(timestamp
) < 0)) {
640 fEndTime
= timestamp
;
642 if (context
.hasValidRank()) {
643 long rank
= context
.getRank();
644 if (fNbEvents
<= rank
) {
645 fNbEvents
= rank
+ 1;
647 if (fIndexer
!= null) {
648 fIndexer
.updateIndex(context
, timestamp
);
653 // ------------------------------------------------------------------------
655 // ------------------------------------------------------------------------
661 public synchronized ITmfContext
armRequest(final ITmfEventRequest request
) {
662 if (executorIsShutdown()) {
665 if (!TmfTimestamp
.BIG_BANG
.equals(request
.getRange().getStartTime())
666 && (request
.getIndex() == 0)) {
667 final ITmfContext context
= seekEvent(request
.getRange().getStartTime());
668 request
.setStartIndex((int) context
.getRank());
672 return seekEvent(request
.getIndex());
675 // ------------------------------------------------------------------------
677 // ------------------------------------------------------------------------
680 * Handler for the Trace Opened signal
683 * The incoming signal
687 public void traceOpened(TmfTraceOpenedSignal signal
) {
688 boolean signalIsForUs
= false;
689 for (ITmfTrace trace
: TmfTraceManager
.getTraceSet(signal
.getTrace())) {
691 signalIsForUs
= true;
696 if (!signalIsForUs
) {
701 * The signal is either for this trace, or for an experiment containing
704 IStatus status
= executeAnalysis();
705 if (!status
.isOK()) {
706 Activator
.log(status
);
709 TmfTraceManager
.refreshSupplementaryFiles(this);
711 if (signal
.getTrace() == this) {
712 /* Additionally, the signal is directly for this trace. */
713 if (getNbEvents() == 0) {
717 /* For a streaming trace, the range updated signal should be sent
718 * by the subclass when a new safe time is determined.
720 if (getStreamingInterval() > 0) {
725 final TmfTimeRange timeRange
= new TmfTimeRange(getStartTime(), TmfTimestamp
.BIG_CRUNCH
);
726 final TmfTraceRangeUpdatedSignal rangeUpdatedsignal
= new TmfTraceRangeUpdatedSignal(this, this, timeRange
);
728 // Broadcast in separate thread to prevent deadlock
729 broadcastAsync(rangeUpdatedsignal
);
736 * Signal handler for the TmfTraceRangeUpdatedSignal signal
738 * @param signal The incoming signal
742 public void traceRangeUpdated(final TmfTraceRangeUpdatedSignal signal
) {
743 if (signal
.getTrace() == this) {
744 getIndexer().buildIndex(getNbEvents(), signal
.getRange(), false);
749 * Signal handler for the TmfTraceUpdatedSignal signal
751 * @param signal The incoming signal
755 public void traceUpdated(final TmfTraceUpdatedSignal signal
) {
756 if (signal
.getSource() == getIndexer()) {
757 fNbEvents
= signal
.getNbEvents();
758 fStartTime
= signal
.getRange().getStartTime();
759 fEndTime
= signal
.getRange().getEndTime();
763 // ------------------------------------------------------------------------
764 // Timestamp transformation functions
765 // ------------------------------------------------------------------------
771 public ITmfTimestampTransform
getTimestampTransform() {
772 if (fTsTransform
== null) {
773 fTsTransform
= TimestampTransformFactory
.getTimestampTransform(getResource());
782 public void setTimestampTransform(final ITmfTimestampTransform tt
) {
784 TimestampTransformFactory
.setTimestampTransform(getResource(), tt
);
791 public ITmfTimestamp
createTimestamp(long ts
) {
792 return new TmfNanoTimestamp(getTimestampTransform().transform(ts
));
795 // ------------------------------------------------------------------------
797 // ------------------------------------------------------------------------
800 @SuppressWarnings("nls")
801 public synchronized String
toString() {
802 return "TmfTrace [fPath=" + fPath
+ ", fCacheSize=" + fCacheSize
803 + ", fNbEvents=" + fNbEvents
+ ", fStartTime=" + fStartTime
804 + ", fEndTime=" + fEndTime
+ ", fStreamingInterval=" + fStreamingInterval
+ "]";
811 public boolean isComplete() {
813 * Be default, all traces are "complete" which means no more data will
823 public void setComplete(boolean isComplete
) {
825 * This should be overridden by trace classes that can support live
826 * reading (traces in an incomplete state)