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
.IStatus
;
34 import org
.eclipse
.core
.runtime
.MultiStatus
;
35 import org
.eclipse
.core
.runtime
.Path
;
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
.signal
.TmfTraceUpdatedSignal
;
49 import org
.eclipse
.linuxtools
.tmf
.core
.statesystem
.ITmfStateSystem
;
50 import org
.eclipse
.linuxtools
.tmf
.core
.statistics
.ITmfStatistics
;
51 import org
.eclipse
.linuxtools
.tmf
.core
.statistics
.TmfStateStatistics
;
52 import org
.eclipse
.linuxtools
.tmf
.core
.synchronization
.ITmfTimestampTransform
;
53 import org
.eclipse
.linuxtools
.tmf
.core
.synchronization
.TmfTimestampTransform
;
54 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.ITmfTimestamp
;
55 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.TmfTimeRange
;
56 import org
.eclipse
.linuxtools
.tmf
.core
.timestamp
.TmfTimestamp
;
57 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.indexer
.ITmfTraceIndexer
;
58 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.indexer
.checkpoint
.TmfCheckpointIndexer
;
59 import org
.eclipse
.linuxtools
.tmf
.core
.trace
.location
.ITmfLocation
;
62 * Abstract implementation of ITmfTrace.
64 * Since the concept of 'location' is trace specific, the concrete classes have
65 * to provide the related methods, namely:
67 * <li> public ITmfLocation<?> getCurrentLocation()
68 * <li> public double getLocationRatio(ITmfLocation<?> location)
69 * <li> public ITmfContext seekEvent(ITmfLocation<?> location)
70 * <li> public ITmfContext seekEvent(double ratio)
71 * <li> public IStatus validate(IProject project, String path)
73 * A concrete trace must provide its corresponding parser. A common way to
74 * accomplish this is by making the concrete class extend TmfTrace and
75 * implement ITmfEventParser.
77 * The concrete class can either specify its own indexer or use the provided
78 * TmfCheckpointIndexer (default). In this case, the trace cache size will be
79 * used as checkpoint interval.
82 * @author Francois Chouinard
85 * @see ITmfTraceIndexer
86 * @see ITmfEventParser
88 public abstract class TmfTrace
extends TmfEventProvider
implements ITmfTrace
{
90 // ------------------------------------------------------------------------
92 // ------------------------------------------------------------------------
94 // The resource used for persistent properties for this trace
95 private IResource fResource
;
100 // The trace cache page size
101 private int fCacheSize
= ITmfTrace
.DEFAULT_TRACE_CACHE_SIZE
;
103 // The number of events collected (so far)
104 private long fNbEvents
= 0;
106 // The time span of the event stream
107 private ITmfTimestamp fStartTime
= TmfTimestamp
.BIG_BANG
;
108 private ITmfTimestamp fEndTime
= TmfTimestamp
.BIG_BANG
;
110 // The trace streaming interval (0 = no streaming)
111 private long fStreamingInterval
= 0;
114 private ITmfTraceIndexer fIndexer
;
117 private ITmfEventParser fParser
;
119 // The trace's statistics
120 private ITmfStatistics fStatistics
;
123 * The collection of state systems that are registered with this trace. Each
124 * sub-class can decide to add its (one or many) state system to this map
125 * during their {@link #buildStateSystem()}.
129 protected final Map
<String
, ITmfStateSystem
> fStateSystems
=
130 new LinkedHashMap
<String
, ITmfStateSystem
>();
132 private ITmfTimestampTransform fTsTransform
;
134 private static final String SYNCHRONIZATION_FORMULA_FILE
= "sync_formula"; //$NON-NLS-1$
136 // ------------------------------------------------------------------------
138 // ------------------------------------------------------------------------
141 * The default, parameterless, constructor
145 fIndexer
= createIndexer(DEFAULT_BLOCK_SIZE
);
152 * The resource associated to the trace
154 * The type of events that will be read from this trace
156 * The path to the trace on the filesystem
158 * The trace cache size. Pass '-1' to use the default specified
159 * in {@link ITmfTrace#DEFAULT_TRACE_CACHE_SIZE}
161 * The trace streaming interval. You can use '0' for post-mortem
164 * The trace event parser. Use 'null' if (and only if) the trace
165 * object itself is also the ITmfEventParser to be used.
166 * @throws TmfTraceException
167 * If something failed during the opening
169 protected TmfTrace(final IResource resource
,
170 final Class
<?
extends ITmfEvent
> type
,
174 final ITmfEventParser parser
)
175 throws TmfTraceException
{
177 fCacheSize
= (cacheSize
> 0) ? cacheSize
: ITmfTrace
.DEFAULT_TRACE_CACHE_SIZE
;
178 fStreamingInterval
= interval
;
180 initialize(resource
, path
, type
);
186 * @param trace the original trace
187 * @throws TmfTraceException Should not happen usually
189 public TmfTrace(final TmfTrace trace
) throws TmfTraceException
{
192 throw new IllegalArgumentException();
194 fCacheSize
= trace
.getCacheSize();
195 fStreamingInterval
= trace
.getStreamingInterval();
196 fParser
= trace
.fParser
;
197 initialize(trace
.getResource(), trace
.getPath(), trace
.getEventType());
201 * Creates the indexer instance. Classes extending this class can override
202 * this to provide a different indexer implementation.
204 * @param interval the checkpoints interval
206 * @return the indexer
209 protected ITmfTraceIndexer
createIndexer(int interval
) {
210 return new TmfCheckpointIndexer(this, interval
);
213 // ------------------------------------------------------------------------
214 // ITmfTrace - Initializers
215 // ------------------------------------------------------------------------
218 public void initTrace(final IResource resource
, final String path
, final Class
<?
extends ITmfEvent
> type
) throws TmfTraceException
{
219 initialize(resource
, path
, type
);
223 * Initialize the trace common attributes and the base component.
225 * @param resource the Eclipse resource (trace)
226 * @param path the trace path
227 * @param type the trace event type
229 * @throws TmfTraceException If something failed during the initialization
231 protected void initialize(final IResource resource
,
233 final Class
<?
extends ITmfEvent
> type
)
234 throws TmfTraceException
{
236 throw new TmfTraceException("Invalid trace path"); //$NON-NLS-1$
239 fResource
= resource
;
240 String traceName
= (resource
!= null) ? resource
.getName() : null;
241 // If no resource was provided, extract the display name the trace path
242 if (traceName
== null) {
243 traceName
= new Path(path
).lastSegment();
245 if (fParser
== null) {
246 if (this instanceof ITmfEventParser
) {
247 fParser
= (ITmfEventParser
) this;
249 throw new TmfTraceException("Invalid trace parser"); //$NON-NLS-1$
252 super.init(traceName
, type
);
253 // register as VIP after super.init() because TmfComponent registers to signal manager there
254 TmfSignalManager
.registerVIP(this);
255 fIndexer
= createIndexer(fCacheSize
);
259 * Indicates if the path points to an existing file/directory
261 * @param path the path to test
262 * @return true if the file/directory exists
264 protected boolean fileExists(final String path
) {
265 final File file
= new File(path
);
266 return file
.exists();
273 public void indexTrace(boolean waitForCompletion
) {
274 getIndexer().buildIndex(0, TmfTimeRange
.ETERNITY
, waitForCompletion
);
278 * The default implementation of TmfTrace uses a TmfStatistics back-end.
279 * Override this if you want to specify another type (or none at all).
281 * @return An IStatus indicating if the statistics could be built
282 * successfully or not.
285 protected IStatus
buildStatistics() {
287 * Initialize the statistics provider, but only if a Resource has been
288 * set (so we don't build it for experiments, for unit tests, etc.)
291 fStatistics
= (fResource
== null ?
null : new TmfStateStatistics(this) );
292 } catch (TmfTraceException e
) {
293 return new Status(IStatus
.ERROR
, Activator
.PLUGIN_ID
, e
.getMessage(), e
);
295 return Status
.OK_STATUS
;
299 * Build the state system(s) associated with this trace type.
301 * @return An IStatus indicating if the state system could be build
302 * successfully or not.
305 protected IStatus
buildStateSystem() {
307 * Nothing is done in the base implementation, please specify
308 * how/if to register a new state system in derived classes.
310 return Status
.OK_STATUS
;
317 public synchronized void dispose() {
318 /* Clean up the index if applicable */
319 if (getIndexer() != null) {
320 getIndexer().dispose();
323 /* Clean up the statistics */
324 if (fStatistics
!= null) {
325 fStatistics
.dispose();
328 /* Clean up the state systems */
329 for (ITmfStateSystem ss
: fStateSystems
.values()) {
336 // ------------------------------------------------------------------------
337 // ITmfTrace - Basic getters
338 // ------------------------------------------------------------------------
341 public Class
<ITmfEvent
> getEventType() {
342 return (Class
<ITmfEvent
>) super.getType();
346 public IResource
getResource() {
351 public String
getPath() {
356 public int getCacheSize() {
361 public long getStreamingInterval() {
362 return fStreamingInterval
;
366 * @return the trace indexer
369 protected ITmfTraceIndexer
getIndexer() {
374 * @return the trace parser
376 protected ITmfEventParser
getParser() {
384 public ITmfStatistics
getStatistics() {
392 public final Map
<String
, ITmfStateSystem
> getStateSystems() {
393 return Collections
.unmodifiableMap(fStateSystems
);
400 public final void registerStateSystem(String id
, ITmfStateSystem ss
) {
401 fStateSystems
.put(id
, ss
);
404 // ------------------------------------------------------------------------
405 // ITmfTrace - Trace characteristics getters
406 // ------------------------------------------------------------------------
409 public synchronized long getNbEvents() {
417 public TmfTimeRange
getTimeRange() {
418 return new TmfTimeRange(fStartTime
, fEndTime
);
425 public ITmfTimestamp
getStartTime() {
433 public ITmfTimestamp
getEndTime() {
441 public ITmfTimestamp
getInitialRangeOffset() {
442 final long DEFAULT_INITIAL_OFFSET_VALUE
= (1L * 100 * 1000 * 1000); // .1sec
443 return new TmfTimestamp(DEFAULT_INITIAL_OFFSET_VALUE
, ITmfTimestamp
.NANOSECOND_SCALE
);
450 public String
getHostId() {
451 return this.getName();
454 // ------------------------------------------------------------------------
455 // Convenience setters
456 // ------------------------------------------------------------------------
459 * Set the trace cache size. Must be done at initialization time.
461 * @param cacheSize The trace cache size
463 protected void setCacheSize(final int cacheSize
) {
464 fCacheSize
= cacheSize
;
468 * Set the trace known number of events. This can be quite dynamic
469 * during indexing or for live traces.
471 * @param nbEvents The number of events
473 protected synchronized void setNbEvents(final long nbEvents
) {
474 fNbEvents
= (nbEvents
> 0) ? nbEvents
: 0;
478 * Update the trace events time range
480 * @param range the new time range
483 protected void setTimeRange(final TmfTimeRange range
) {
484 fStartTime
= range
.getStartTime();
485 fEndTime
= range
.getEndTime();
489 * Update the trace chronologically first event timestamp
491 * @param startTime the new first event timestamp
494 protected void setStartTime(final ITmfTimestamp startTime
) {
495 fStartTime
= startTime
;
499 * Update the trace chronologically last event timestamp
501 * @param endTime the new last event timestamp
504 protected void setEndTime(final ITmfTimestamp endTime
) {
509 * Set the polling interval for live traces (default = 0 = no streaming).
511 * @param interval the new trace streaming interval
513 protected void setStreamingInterval(final long interval
) {
514 fStreamingInterval
= (interval
> 0) ? interval
: 0;
518 * Set the trace parser. Must be done at initialization time.
520 * @param parser the new trace parser
522 protected void setParser(final ITmfEventParser parser
) {
526 // ------------------------------------------------------------------------
527 // ITmfTrace - SeekEvent operations (returning a trace context)
528 // ------------------------------------------------------------------------
531 public synchronized ITmfContext
seekEvent(final long rank
) {
533 // A rank <= 0 indicates to seek the first event
535 ITmfContext context
= seekEvent((ITmfLocation
) null);
540 // Position the trace at the checkpoint
541 final ITmfContext context
= fIndexer
.seekIndex(rank
);
543 // And locate the requested event context
544 long pos
= context
.getRank();
546 ITmfEvent event
= getNext(context
);
547 while ((event
!= null) && (++pos
< rank
)) {
548 event
= getNext(context
);
558 public synchronized ITmfContext
seekEvent(final ITmfTimestamp timestamp
) {
560 // A null timestamp indicates to seek the first event
561 if (timestamp
== null) {
562 ITmfContext context
= seekEvent((ITmfLocation
) null);
567 // Position the trace at the checkpoint
568 ITmfContext context
= fIndexer
.seekIndex(timestamp
);
570 // And locate the requested event context
571 ITmfLocation previousLocation
= context
.getLocation();
572 long previousRank
= context
.getRank();
573 ITmfEvent event
= getNext(context
);
574 while (event
!= null && event
.getTimestamp().compareTo(timestamp
, false) < 0) {
575 previousLocation
= context
.getLocation();
576 previousRank
= context
.getRank();
577 event
= getNext(context
);
580 context
.setLocation(null);
581 context
.setRank(ITmfContext
.UNKNOWN_RANK
);
584 context
= seekEvent(previousLocation
);
585 context
.setRank(previousRank
);
590 // ------------------------------------------------------------------------
591 // ITmfTrace - Read operations (returning an actual event)
592 // ------------------------------------------------------------------------
595 public synchronized ITmfEvent
getNext(final ITmfContext context
) {
596 // parseEvent() does not update the context
597 final ITmfEvent event
= fParser
.parseEvent(context
);
599 updateAttributes(context
, event
.getTimestamp());
600 context
.setLocation(getCurrentLocation());
601 context
.increaseRank();
608 * Hook for special event processing by the concrete class
609 * (called by TmfTrace.getEvent())
611 * @param event the event
613 protected void processEvent(final ITmfEvent event
) {
618 * Update the trace attributes
620 * @param context the current trace context
621 * @param timestamp the corresponding timestamp
624 protected synchronized void updateAttributes(final ITmfContext context
, final ITmfTimestamp timestamp
) {
625 if (fStartTime
.equals(TmfTimestamp
.BIG_BANG
) || (fStartTime
.compareTo(timestamp
, false) > 0)) {
626 fStartTime
= timestamp
;
628 if (fEndTime
.equals(TmfTimestamp
.BIG_CRUNCH
) || (fEndTime
.compareTo(timestamp
, false) < 0)) {
629 fEndTime
= timestamp
;
631 if (context
.hasValidRank()) {
632 long rank
= context
.getRank();
633 if (fNbEvents
<= rank
) {
634 fNbEvents
= rank
+ 1;
636 if (fIndexer
!= null) {
637 fIndexer
.updateIndex(context
, timestamp
);
642 // ------------------------------------------------------------------------
644 // ------------------------------------------------------------------------
650 public synchronized ITmfContext
armRequest(final ITmfDataRequest request
) {
651 if (executorIsShutdown()) {
654 if ((request
instanceof ITmfEventRequest
)
655 && !TmfTimestamp
.BIG_BANG
.equals(((ITmfEventRequest
) request
).getRange().getStartTime())
656 && (request
.getIndex() == 0))
658 final ITmfContext context
= seekEvent(((ITmfEventRequest
) request
).getRange().getStartTime());
659 ((ITmfEventRequest
) request
).setStartIndex((int) context
.getRank());
663 return seekEvent(request
.getIndex());
666 // ------------------------------------------------------------------------
668 // ------------------------------------------------------------------------
671 * Handler for the Trace Opened signal
674 * The incoming signal
678 public void traceOpened(TmfTraceOpenedSignal signal
) {
679 boolean signalIsForUs
= false;
680 for (ITmfTrace trace
: TmfTraceManager
.getTraceSet(signal
.getTrace())) {
682 signalIsForUs
= true;
687 if (!signalIsForUs
) {
692 * The signal is either for this trace, or for an experiment containing
695 MultiStatus status
= new MultiStatus(Activator
.PLUGIN_ID
, IStatus
.OK
, null, null);
696 status
.add(buildStatistics());
697 status
.add(buildStateSystem());
698 if (!status
.isOK()) {
699 Activator
.log(status
);
702 /* Refresh the project, so it can pick up new files that got created. */
704 if (fResource
!= null) {
705 fResource
.getProject().refreshLocal(IResource
.DEPTH_INFINITE
, null);
707 } catch (CoreException e
) {
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) {
724 final TmfTimeRange timeRange
= new TmfTimeRange(getStartTime(), TmfTimestamp
.BIG_CRUNCH
);
725 final TmfTraceRangeUpdatedSignal rangeUpdatedsignal
= new TmfTraceRangeUpdatedSignal(this, this, timeRange
);
727 // Broadcast in separate thread to prevent deadlock
731 broadcast(rangeUpdatedsignal
);
739 * Signal handler for the TmfTraceRangeUpdatedSignal signal
741 * @param signal The incoming signal
745 public void traceRangeUpdated(final TmfTraceRangeUpdatedSignal signal
) {
746 if (signal
.getTrace() == this) {
747 getIndexer().buildIndex(getNbEvents(), signal
.getRange(), false);
752 * Signal handler for the TmfTraceUpdatedSignal signal
754 * @param signal The incoming signal
758 public void traceUpdated(final TmfTraceUpdatedSignal signal
) {
759 if (signal
.getSource() == getIndexer()) {
760 fNbEvents
= signal
.getNbEvents();
761 fStartTime
= signal
.getRange().getStartTime();
762 fEndTime
= signal
.getRange().getEndTime();
767 * Returns the file resource used to store synchronization formula. The file
770 * @return the synchronization file
772 private File
getSyncFormulaFile() {
774 if (fResource
instanceof IFolder
) {
776 String supplDirectory
;
778 supplDirectory
= fResource
.getPersistentProperty(TmfCommonConstants
.TRACE_SUPPLEMENTARY_FOLDER
);
780 file
= new File(supplDirectory
+ File
.separator
+ SYNCHRONIZATION_FORMULA_FILE
);
782 } catch (CoreException e
) {
789 // ------------------------------------------------------------------------
790 // Timestamp transformation functions
791 // ------------------------------------------------------------------------
797 public ITmfTimestampTransform
getTimestampTransform() {
798 if (fTsTransform
== null) {
799 /* Check if a formula is stored somewhere in the resources */
800 File sync_file
= getSyncFormulaFile();
801 if (sync_file
!= null && sync_file
.exists()) {
804 FileInputStream fis
= new FileInputStream(sync_file
);
805 ObjectInputStream ois
= new ObjectInputStream(fis
);
806 fTsTransform
= (ITmfTimestampTransform
) ois
.readObject();
810 } catch (ClassNotFoundException e1
) {
811 fTsTransform
= TmfTimestampTransform
.IDENTITY
;
812 } catch (FileNotFoundException e1
) {
813 fTsTransform
= TmfTimestampTransform
.IDENTITY
;
814 } catch (IOException e1
) {
815 fTsTransform
= TmfTimestampTransform
.IDENTITY
;
818 fTsTransform
= TmfTimestampTransform
.IDENTITY
;
828 public void setTimestampTransform(final ITmfTimestampTransform tt
) {
831 /* Save the timestamp transform to a file */
832 File sync_file
= getSyncFormulaFile();
833 if (sync_file
!= null) {
834 if (sync_file
.exists()) {
837 FileOutputStream fos
;
838 ObjectOutputStream oos
;
840 /* Save the header of the file */
842 fos
= new FileOutputStream(sync_file
, false);
843 oos
= new ObjectOutputStream(fos
);
845 oos
.writeObject(fTsTransform
);
848 } catch (IOException e1
) {
849 Activator
.logError("Error writing timestamp transform for trace", e1
); //$NON-NLS-1$
858 public ITmfTimestamp
createTimestamp(long ts
) {
859 return new TmfTimestamp(getTimestampTransform().transform(ts
));
862 // ------------------------------------------------------------------------
864 // ------------------------------------------------------------------------
867 @SuppressWarnings("nls")
868 public synchronized String
toString() {
869 return "TmfTrace [fPath=" + fPath
+ ", fCacheSize=" + fCacheSize
870 + ", fNbEvents=" + fNbEvents
+ ", fStartTime=" + fStartTime
871 + ", fEndTime=" + fEndTime
+ ", fStreamingInterval=" + fStreamingInterval
+ "]";