1 /*******************************************************************************
2 * Copyright (c) 2009, 2013 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
.io
.FileInputStream
;
21 import java
.io
.FileNotFoundException
;
22 import java
.io
.FileOutputStream
;
23 import java
.io
.IOException
;
24 import java
.io
.ObjectInputStream
;
25 import java
.io
.ObjectOutputStream
;
26 import java
.util
.Collections
;
27 import java
.util
.LinkedHashMap
;
30 import org
.eclipse
.core
.resources
.IFolder
;
31 import org
.eclipse
.core
.resources
.IResource
;
32 import org
.eclipse
.core
.runtime
.CoreException
;
33 import org
.eclipse
.core
.runtime
.IPath
;
34 import org
.eclipse
.core
.runtime
.IStatus
;
35 import org
.eclipse
.core
.runtime
.MultiStatus
;
36 import org
.eclipse
.core
.runtime
.Status
;
37 import org
.eclipse
.linuxtools
.internal
.tmf
.core
.Activator
;
38 import org
.eclipse
.linuxtools
.tmf
.core
.TmfCommonConstants
;
39 import org
.eclipse
.linuxtools
.tmf
.core
.component
.TmfEventProvider
;
40 import org
.eclipse
.linuxtools
.tmf
.core
.event
.ITmfEvent
;
41 import org
.eclipse
.linuxtools
.tmf
.core
.exceptions
.TmfTraceException
;
42 import org
.eclipse
.linuxtools
.tmf
.core
.request
.ITmfDataRequest
;
43 import org
.eclipse
.linuxtools
.tmf
.core
.request
.ITmfEventRequest
;
44 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfSignalHandler
;
45 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfSignalManager
;
46 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfTraceOpenedSignal
;
47 import org
.eclipse
.linuxtools
.tmf
.core
.signal
.TmfTraceRangeUpdatedSignal
;
48 import org
.eclipse
.linuxtools
.tmf
.core
.statesystem
.ITmfStateSystem
;
49 import org
.eclipse
.linuxtools
.tmf
.core
.statistics
.ITmfStatistics
;
50 import org
.eclipse
.linuxtools
.tmf
.core
.statistics
.TmfStateStatistics
;
51 import org
.eclipse
.linuxtools
.tmf
.core
.synchronization
.ITmfTimestampTransform
;
52 import org
.eclipse
.linuxtools
.tmf
.core
.synchronization
.TmfTimestampTransform
;
53 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.ITmfTimestamp
;
54 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.TmfTimeRange
;
55 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.TmfTimestamp
;
56 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.indexer
.ITmfTraceIndexer
;
57 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.indexer
.checkpoint
.TmfCheckpointIndexer
;
58 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.location
.ITmfLocation
;
61 * Abstract implementation of ITmfTrace.
63 * Since the concept of 'location' is trace specific, the concrete classes have
64 * to provide the related methods, namely:
66 * <li> public ITmfLocation<?> getCurrentLocation()
67 * <li> public double getLocationRatio(ITmfLocation<?> location)
68 * <li> public ITmfContext seekEvent(ITmfLocation<?> location)
69 * <li> public ITmfContext seekEvent(double ratio)
70 * <li> public IStatus validate(IProject project, String path)
72 * A concrete trace must provide its corresponding parser. A common way to
73 * accomplish this is by making the concrete class extend TmfTrace and
74 * implement ITmfEventParser.
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
{
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 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 // The trace's statistics
119 private ITmfStatistics fStatistics
;
122 * The collection of state systems that are registered with this trace. Each
123 * sub-class can decide to add its (one or many) state system to this map
124 * during their {@link #buildStateSystem()}.
128 protected final Map
<String
, ITmfStateSystem
> fStateSystems
=
129 new LinkedHashMap
<String
, ITmfStateSystem
>();
131 private ITmfTimestampTransform fTsTransform
;
133 private static final String SYNCHRONIZATION_FORMULA_FILE
= "sync_formula"; //$NON-NLS-1$
135 // ------------------------------------------------------------------------
137 // ------------------------------------------------------------------------
140 * The default, parameterless, constructor
150 * The resource associated to the trace
152 * The type of events that will be read from this trace
154 * The path to the trace on the filesystem
156 * The trace cache size. Pass '-1' to use the default specified
157 * in {@link ITmfTrace#DEFAULT_TRACE_CACHE_SIZE}
159 * The trace streaming interval. You can use '0' for post-mortem
162 * The trace indexer. You can pass 'null' to use a default
163 * checkpoint indexer.
165 * The trace event parser. Use 'null' if (and only if) the trace
166 * object itself is also the ITmfEventParser to be used.
167 * @throws TmfTraceException
168 * If something failed during the opening
170 protected TmfTrace(final IResource resource
,
171 final Class
<?
extends ITmfEvent
> type
,
175 final ITmfTraceIndexer indexer
,
176 final ITmfEventParser parser
)
177 throws TmfTraceException
{
179 fCacheSize
= (cacheSize
> 0) ? cacheSize
: ITmfTrace
.DEFAULT_TRACE_CACHE_SIZE
;
180 fStreamingInterval
= interval
;
181 fIndexer
= (indexer
!= null) ? indexer
: new TmfCheckpointIndexer(this, fCacheSize
);
183 initialize(resource
, path
, type
);
189 * @param trace the original trace
190 * @throws TmfTraceException Should not happen usually
192 public TmfTrace(final TmfTrace trace
) throws TmfTraceException
{
195 throw new IllegalArgumentException();
197 fCacheSize
= trace
.getCacheSize();
198 fStreamingInterval
= trace
.getStreamingInterval();
199 fIndexer
= new TmfCheckpointIndexer(this);
200 fParser
= trace
.fParser
;
201 initialize(trace
.getResource(), trace
.getPath(), trace
.getEventType());
204 // ------------------------------------------------------------------------
205 // ITmfTrace - Initializers
206 // ------------------------------------------------------------------------
209 public void initTrace(final IResource resource
, final String path
, final Class
<?
extends ITmfEvent
> type
) throws TmfTraceException
{
210 fIndexer
= new TmfCheckpointIndexer(this, fCacheSize
);
211 initialize(resource
, path
, type
);
215 * Initialize the trace common attributes and the base component.
217 * @param resource the Eclipse resource (trace)
218 * @param path the trace path
219 * @param type the trace event type
221 * @throws TmfTraceException If something failed during the initialization
223 protected void initialize(final IResource resource
,
225 final Class
<?
extends ITmfEvent
> type
)
226 throws TmfTraceException
{
228 throw new TmfTraceException("Invalid trace path"); //$NON-NLS-1$
231 fResource
= resource
;
232 String traceName
= (resource
!= null) ? resource
.getName() : null;
233 // If no resource was provided, extract the display name the trace path
234 if (traceName
== null) {
235 final int sep
= path
.lastIndexOf(IPath
.SEPARATOR
);
236 traceName
= (sep
>= 0) ? path
.substring(sep
+ 1) : path
;
238 if (fParser
== null) {
239 if (this instanceof ITmfEventParser
) {
240 fParser
= (ITmfEventParser
) this;
242 throw new TmfTraceException("Invalid trace parser"); //$NON-NLS-1$
245 super.init(traceName
, type
);
246 // register as VIP after super.init() because TmfComponent registers to signal manager there
247 TmfSignalManager
.registerVIP(this);
251 * Indicates if the path points to an existing file/directory
253 * @param path the path to test
254 * @return true if the file/directory exists
256 protected boolean fileExists(final String path
) {
257 final File file
= new File(path
);
258 return file
.exists();
265 public void indexTrace(boolean waitForCompletion
) {
266 getIndexer().buildIndex(0, TmfTimeRange
.ETERNITY
, waitForCompletion
);
270 * The default implementation of TmfTrace uses a TmfStatistics back-end.
271 * Override this if you want to specify another type (or none at all).
273 * @return An IStatus indicating if the statistics could be built
274 * successfully or not.
277 protected IStatus
buildStatistics() {
279 * Initialize the statistics provider, but only if a Resource has been
280 * set (so we don't build it for experiments, for unit tests, etc.)
283 fStatistics
= (fResource
== null ?
null : new TmfStateStatistics(this) );
284 } catch (TmfTraceException e
) {
285 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, e
.getMessage(), e
);
287 return Status
.OK_STATUS
;
291 * Build the state system(s) associated with this trace type.
293 * @return An IStatus indicating if the state system could be build
294 * successfully or not.
297 protected IStatus
buildStateSystem() {
299 * Nothing is done in the base implementation, please specify
300 * how/if to register a new state system in derived classes.
302 return Status
.OK_STATUS
;
309 public synchronized void dispose() {
310 /* Clean up the index if applicable */
311 if (getIndexer() != null) {
312 getIndexer().dispose();
315 /* Clean up the statistics */
316 if (fStatistics
!= null) {
317 fStatistics
.dispose();
320 /* Clean up the state systems */
321 for (ITmfStateSystem ss
: fStateSystems
.values()) {
328 // ------------------------------------------------------------------------
329 // ITmfTrace - Basic getters
330 // ------------------------------------------------------------------------
333 public Class
<ITmfEvent
> getEventType() {
334 return (Class
<ITmfEvent
>) super.getType();
338 public IResource
getResource() {
343 public String
getPath() {
348 public int getCacheSize() {
353 public long getStreamingInterval() {
354 return fStreamingInterval
;
358 * @return the trace indexer
361 protected ITmfTraceIndexer
getIndexer() {
366 * @return the trace parser
368 protected ITmfEventParser
getParser() {
376 public ITmfStatistics
getStatistics() {
384 public final Map
<String
, ITmfStateSystem
> getStateSystems() {
385 return Collections
.unmodifiableMap(fStateSystems
);
392 public final void registerStateSystem(String id
, ITmfStateSystem ss
) {
393 fStateSystems
.put(id
, ss
);
396 // ------------------------------------------------------------------------
397 // ITmfTrace - Trace characteristics getters
398 // ------------------------------------------------------------------------
401 public synchronized long getNbEvents() {
409 public TmfTimeRange
getTimeRange() {
410 return new TmfTimeRange(fStartTime
, fEndTime
);
417 public ITmfTimestamp
getStartTime() {
425 public ITmfTimestamp
getEndTime() {
433 public ITmfTimestamp
getInitialRangeOffset() {
434 final long DEFAULT_INITIAL_OFFSET_VALUE
= (1L * 100 * 1000 * 1000); // .1sec
435 return new TmfTimestamp(DEFAULT_INITIAL_OFFSET_VALUE
, ITmfTimestamp
.NANOSECOND_SCALE
);
442 public String
getHostId() {
443 return this.getName();
446 // ------------------------------------------------------------------------
447 // Convenience setters
448 // ------------------------------------------------------------------------
451 * Set the trace cache size. Must be done at initialization time.
453 * @param cacheSize The trace cache size
455 protected void setCacheSize(final int cacheSize
) {
456 fCacheSize
= cacheSize
;
460 * Set the trace known number of events. This can be quite dynamic
461 * during indexing or for live traces.
463 * @param nbEvents The number of events
465 protected synchronized void setNbEvents(final long nbEvents
) {
466 fNbEvents
= (nbEvents
> 0) ? nbEvents
: 0;
470 * Update the trace events time range
472 * @param range the new time range
475 protected void setTimeRange(final TmfTimeRange range
) {
476 fStartTime
= range
.getStartTime();
477 fEndTime
= range
.getEndTime();
481 * Update the trace chronologically first event timestamp
483 * @param startTime the new first event timestamp
486 protected void setStartTime(final ITmfTimestamp startTime
) {
487 fStartTime
= startTime
;
491 * Update the trace chronologically last event timestamp
493 * @param endTime the new last event timestamp
496 protected void setEndTime(final ITmfTimestamp endTime
) {
501 * Set the polling interval for live traces (default = 0 = no streaming).
503 * @param interval the new trace streaming interval
505 protected void setStreamingInterval(final long interval
) {
506 fStreamingInterval
= (interval
> 0) ? interval
: 0;
510 * Set the trace indexer. Must be done at initialization time.
512 * @param indexer the trace indexer
515 protected void setIndexer(final ITmfTraceIndexer indexer
) {
520 * Set the trace parser. Must be done at initialization time.
522 * @param parser the new trace parser
524 protected void setParser(final ITmfEventParser parser
) {
528 // ------------------------------------------------------------------------
529 // ITmfTrace - SeekEvent operations (returning a trace context)
530 // ------------------------------------------------------------------------
533 public synchronized ITmfContext
seekEvent(final long rank
) {
535 // A rank <= 0 indicates to seek the first event
537 ITmfContext context
= seekEvent((ITmfLocation
) null);
542 // Position the trace at the checkpoint
543 final ITmfContext context
= fIndexer
.seekIndex(rank
);
545 // And locate the requested event context
546 long pos
= context
.getRank();
548 ITmfEvent event
= getNext(context
);
549 while ((event
!= null) && (++pos
< rank
)) {
550 event
= getNext(context
);
560 public synchronized ITmfContext
seekEvent(final ITmfTimestamp timestamp
) {
562 // A null timestamp indicates to seek the first event
563 if (timestamp
== null) {
564 ITmfContext context
= seekEvent((ITmfLocation
) null);
569 // Position the trace at the checkpoint
570 ITmfContext context
= fIndexer
.seekIndex(timestamp
);
572 // And locate the requested event context
573 ITmfLocation previousLocation
= context
.getLocation();
574 long previousRank
= context
.getRank();
575 ITmfEvent event
= getNext(context
);
576 while (event
!= null && event
.getTimestamp().compareTo(timestamp
, false) < 0) {
577 previousLocation
= context
.getLocation();
578 previousRank
= context
.getRank();
579 event
= getNext(context
);
582 context
.setLocation(null);
583 context
.setRank(ITmfContext
.UNKNOWN_RANK
);
586 context
= seekEvent(previousLocation
);
587 context
.setRank(previousRank
);
592 // ------------------------------------------------------------------------
593 // ITmfTrace - Read operations (returning an actual event)
594 // ------------------------------------------------------------------------
597 public synchronized ITmfEvent
getNext(final ITmfContext context
) {
598 // parseEvent() does not update the context
599 final ITmfEvent event
= fParser
.parseEvent(context
);
601 updateAttributes(context
, event
.getTimestamp());
602 context
.setLocation(getCurrentLocation());
603 context
.increaseRank();
610 * Hook for special event processing by the concrete class
611 * (called by TmfTrace.getEvent())
613 * @param event the event
615 protected void processEvent(final ITmfEvent event
) {
620 * Update the trace attributes
622 * @param context the current trace context
623 * @param timestamp the corresponding timestamp
626 protected synchronized void updateAttributes(final ITmfContext context
, final ITmfTimestamp timestamp
) {
627 if (fStartTime
.equals(TmfTimestamp
.BIG_BANG
) || (fStartTime
.compareTo(timestamp
, false) > 0)) {
628 fStartTime
= timestamp
;
630 if (fEndTime
.equals(TmfTimestamp
.BIG_CRUNCH
) || (fEndTime
.compareTo(timestamp
, false) < 0)) {
631 fEndTime
= timestamp
;
633 if (context
.hasValidRank()) {
634 long rank
= context
.getRank();
635 if (fNbEvents
<= rank
) {
636 fNbEvents
= rank
+ 1;
638 if (fIndexer
!= null) {
639 fIndexer
.updateIndex(context
, timestamp
);
644 // ------------------------------------------------------------------------
646 // ------------------------------------------------------------------------
652 public synchronized ITmfContext
armRequest(final ITmfDataRequest request
) {
653 if (executorIsShutdown()) {
656 if ((request
instanceof ITmfEventRequest
)
657 && !TmfTimestamp
.BIG_BANG
.equals(((ITmfEventRequest
) request
).getRange().getStartTime())
658 && (request
.getIndex() == 0))
660 final ITmfContext context
= seekEvent(((ITmfEventRequest
) request
).getRange().getStartTime());
661 ((ITmfEventRequest
) request
).setStartIndex((int) context
.getRank());
665 return seekEvent(request
.getIndex());
668 // ------------------------------------------------------------------------
670 // ------------------------------------------------------------------------
673 * Handler for the Trace Opened signal
676 * The incoming signal
680 public void traceOpened(TmfTraceOpenedSignal signal
) {
681 boolean signalIsForUs
= false;
682 for (ITmfTrace trace
: TmfTraceManager
.getTraceSet(signal
.getTrace())) {
684 signalIsForUs
= true;
689 if (!signalIsForUs
) {
694 * The signal is either for this trace, or for an experiment containing
697 MultiStatus status
= new MultiStatus(Activator
.PLUGIN_ID
, IStatus
.OK
, null, null);
698 status
.add(buildStatistics());
699 status
.add(buildStateSystem());
700 if (!status
.isOK()) {
701 Activator
.log(status
);
704 /* Refresh the project, so it can pick up new files that got created. */
706 if (fResource
!= null) {
707 fResource
.getProject().refreshLocal(IResource
.DEPTH_INFINITE
, null);
709 } catch (CoreException e
) {
713 if (signal
.getTrace() == this) {
714 /* Additionally, the signal is directly for this trace. */
715 if (getNbEvents() == 0) {
719 /* For a streaming trace, the range updated signal should be sent
720 * by the subclass when a new safe time is determined.
722 if (getStreamingInterval() > 0) {
726 final TmfTimeRange timeRange
= new TmfTimeRange(getStartTime(), TmfTimestamp
.BIG_CRUNCH
);
727 final TmfTraceRangeUpdatedSignal rangeUpdatedsignal
= new TmfTraceRangeUpdatedSignal(this, this, timeRange
);
729 // Broadcast in separate thread to prevent deadlock
733 broadcast(rangeUpdatedsignal
);
741 * Signal handler for the TmfTraceRangeUpdatedSignal signal
743 * @param signal The incoming signal
747 public void traceRangeUpdated(final TmfTraceRangeUpdatedSignal signal
) {
748 if (signal
.getTrace() == this) {
749 getIndexer().buildIndex(getNbEvents(), signal
.getRange(), false);
754 * Returns the file resource used to store synchronization formula. The file
757 * @return the synchronization file
759 private File
getSyncFormulaFile() {
761 if (fResource
instanceof IFolder
) {
763 String supplDirectory
;
765 supplDirectory
= fResource
.getPersistentProperty(TmfCommonConstants
.TRACE_SUPPLEMENTARY_FOLDER
);
767 file
= new File(supplDirectory
+ File
.separator
+ SYNCHRONIZATION_FORMULA_FILE
);
769 } catch (CoreException e
) {
776 // ------------------------------------------------------------------------
777 // Timestamp transformation functions
778 // ------------------------------------------------------------------------
784 public ITmfTimestampTransform
getTimestampTransform() {
785 if (fTsTransform
== null) {
786 /* Check if a formula is stored somewhere in the resources */
787 File sync_file
= getSyncFormulaFile();
788 if (sync_file
!= null && sync_file
.exists()) {
791 FileInputStream fis
= new FileInputStream(sync_file
);
792 ObjectInputStream ois
= new ObjectInputStream(fis
);
793 fTsTransform
= (ITmfTimestampTransform
) ois
.readObject();
797 } catch (ClassNotFoundException e1
) {
798 fTsTransform
= TmfTimestampTransform
.IDENTITY
;
799 } catch (FileNotFoundException e1
) {
800 fTsTransform
= TmfTimestampTransform
.IDENTITY
;
801 } catch (IOException e1
) {
802 fTsTransform
= TmfTimestampTransform
.IDENTITY
;
805 fTsTransform
= TmfTimestampTransform
.IDENTITY
;
815 public void setTimestampTransform(final ITmfTimestampTransform tt
) {
818 /* Save the timestamp transform to a file */
819 File sync_file
= getSyncFormulaFile();
820 if (sync_file
!= null) {
821 if (sync_file
.exists()) {
824 FileOutputStream fos
;
825 ObjectOutputStream oos
;
827 /* Save the header of the file */
829 fos
= new FileOutputStream(sync_file
, false);
830 oos
= new ObjectOutputStream(fos
);
832 oos
.writeObject(fTsTransform
);
835 } catch (IOException e1
) {
836 Activator
.logError("Error writing timestamp transform for trace", e1
); //$NON-NLS-1$
845 public ITmfTimestamp
createTimestamp(long ts
) {
846 return new TmfTimestamp(getTimestampTransform().transform(ts
));
849 // ------------------------------------------------------------------------
851 // ------------------------------------------------------------------------
854 @SuppressWarnings("nls")
855 public synchronized String
toString() {
856 return "TmfTrace [fPath=" + fPath
+ ", fCacheSize=" + fCacheSize
857 + ", fNbEvents=" + fNbEvents
+ ", fStartTime=" + fStartTime
858 + ", fEndTime=" + fEndTime
+ ", fStreamingInterval=" + fStreamingInterval
+ "]";