tmf: Clean up tmf.core.trace package
[deliverable/tracecompass.git] / org.eclipse.linuxtools.tmf.core / src / org / eclipse / linuxtools / tmf / core / trace / TmfTrace.java
... / ...
CommitLineData
1/*******************************************************************************
2 * Copyright (c) 2009, 2013 Ericsson
3 *
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
8 *
9 * Contributors:
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 *******************************************************************************/
14
15package org.eclipse.linuxtools.tmf.core.trace;
16
17import java.io.File;
18import java.util.Collections;
19import java.util.LinkedHashMap;
20import java.util.Map;
21
22import org.eclipse.core.resources.IResource;
23import org.eclipse.core.runtime.CoreException;
24import org.eclipse.core.runtime.IPath;
25import org.eclipse.core.runtime.IStatus;
26import org.eclipse.core.runtime.MultiStatus;
27import org.eclipse.core.runtime.Status;
28import org.eclipse.linuxtools.internal.tmf.core.Activator;
29import org.eclipse.linuxtools.tmf.core.component.TmfEventProvider;
30import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
31import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException;
32import org.eclipse.linuxtools.tmf.core.request.ITmfDataRequest;
33import org.eclipse.linuxtools.tmf.core.request.ITmfEventRequest;
34import org.eclipse.linuxtools.tmf.core.signal.TmfSignalHandler;
35import org.eclipse.linuxtools.tmf.core.signal.TmfSignalManager;
36import org.eclipse.linuxtools.tmf.core.signal.TmfTraceOpenedSignal;
37import org.eclipse.linuxtools.tmf.core.signal.TmfTraceRangeUpdatedSignal;
38import org.eclipse.linuxtools.tmf.core.statesystem.ITmfStateSystem;
39import org.eclipse.linuxtools.tmf.core.statistics.ITmfStatistics;
40import org.eclipse.linuxtools.tmf.core.statistics.TmfStateStatistics;
41import org.eclipse.linuxtools.tmf.core.timestamp.ITmfTimestamp;
42import org.eclipse.linuxtools.tmf.core.timestamp.TmfTimeRange;
43import org.eclipse.linuxtools.tmf.core.timestamp.TmfTimestamp;
44import org.eclipse.linuxtools.tmf.core.trace.indexer.ITmfTraceIndexer;
45import org.eclipse.linuxtools.tmf.core.trace.indexer.checkpoint.TmfCheckpointIndexer;
46import org.eclipse.linuxtools.tmf.core.trace.location.ITmfLocation;
47
48/**
49 * Abstract implementation of ITmfTrace.
50 * <p>
51 * Since the concept of 'location' is trace specific, the concrete classes have
52 * to provide the related methods, namely:
53 * <ul>
54 * <li> public ITmfLocation<?> getCurrentLocation()
55 * <li> public double getLocationRatio(ITmfLocation<?> location)
56 * <li> public ITmfContext seekEvent(ITmfLocation<?> location)
57 * <li> public ITmfContext seekEvent(double ratio)
58 * <li> public IStatus validate(IProject project, String path)
59 * </ul>
60 * A concrete trace must provide its corresponding parser. A common way to
61 * accomplish this is by making the concrete class extend TmfTrace and
62 * implement ITmfEventParser.
63 * <p>
64 * The concrete class can either specify its own indexer or use the provided
65 * TmfCheckpointIndexer (default). In this case, the trace cache size will be
66 * used as checkpoint interval.
67 *
68 * @version 1.0
69 * @author Francois Chouinard
70 *
71 * @see ITmfEvent
72 * @see ITmfTraceIndexer
73 * @see ITmfEventParser
74 */
75public abstract class TmfTrace extends TmfEventProvider implements ITmfTrace {
76
77 // ------------------------------------------------------------------------
78 // Attributes
79 // ------------------------------------------------------------------------
80
81 // The resource used for persistent properties for this trace
82 private IResource fResource;
83
84 // The trace path
85 private String fPath;
86
87 // The trace cache page size
88 private int fCacheSize = ITmfTrace.DEFAULT_TRACE_CACHE_SIZE;
89
90 // The number of events collected (so far)
91 private long fNbEvents = 0;
92
93 // The time span of the event stream
94 private ITmfTimestamp fStartTime = TmfTimestamp.BIG_BANG;
95 private ITmfTimestamp fEndTime = TmfTimestamp.BIG_BANG;
96
97 // The trace streaming interval (0 = no streaming)
98 private long fStreamingInterval = 0;
99
100 // The trace indexer
101 private ITmfTraceIndexer fIndexer;
102
103 // The trace parser
104 private ITmfEventParser fParser;
105
106 // The trace's statistics
107 private ITmfStatistics fStatistics;
108
109 /**
110 * The collection of state systems that are registered with this trace. Each
111 * sub-class can decide to add its (one or many) state system to this map
112 * during their {@link #buildStateSystem()}.
113 *
114 * @since 2.0
115 */
116 protected final Map<String, ITmfStateSystem> fStateSystems =
117 new LinkedHashMap<String, ITmfStateSystem>();
118
119 // ------------------------------------------------------------------------
120 // Construction
121 // ------------------------------------------------------------------------
122
123 /**
124 * The default, parameterless, constructor
125 */
126 public TmfTrace() {
127 super();
128 }
129
130 /**
131 * Full constructor.
132 *
133 * @param resource
134 * The resource associated to the trace
135 * @param type
136 * The type of events that will be read from this trace
137 * @param path
138 * The path to the trace on the filesystem
139 * @param cacheSize
140 * The trace cache size. Pass '-1' to use the default specified
141 * in {@link ITmfTrace#DEFAULT_TRACE_CACHE_SIZE}
142 * @param interval
143 * The trace streaming interval. You can use '0' for post-mortem
144 * traces.
145 * @param indexer
146 * The trace indexer. You can pass 'null' to use a default
147 * checkpoint indexer.
148 * @param parser
149 * The trace event parser. Use 'null' if (and only if) the trace
150 * object itself is also the ITmfEventParser to be used.
151 * @throws TmfTraceException
152 * If something failed during the opening
153 */
154 protected TmfTrace(final IResource resource,
155 final Class<? extends ITmfEvent> type,
156 final String path,
157 final int cacheSize,
158 final long interval,
159 final ITmfTraceIndexer indexer,
160 final ITmfEventParser parser)
161 throws TmfTraceException {
162 super();
163 fCacheSize = (cacheSize > 0) ? cacheSize : ITmfTrace.DEFAULT_TRACE_CACHE_SIZE;
164 fStreamingInterval = interval;
165 fIndexer = (indexer != null) ? indexer : new TmfCheckpointIndexer(this, fCacheSize);
166 fParser = parser;
167 initialize(resource, path, type);
168 }
169
170 /**
171 * Copy constructor
172 *
173 * @param trace the original trace
174 * @throws TmfTraceException Should not happen usually
175 */
176 public TmfTrace(final TmfTrace trace) throws TmfTraceException {
177 super();
178 if (trace == null) {
179 throw new IllegalArgumentException();
180 }
181 fCacheSize = trace.getCacheSize();
182 fStreamingInterval = trace.getStreamingInterval();
183 fIndexer = new TmfCheckpointIndexer(this);
184 fParser = trace.fParser;
185 initialize(trace.getResource(), trace.getPath(), trace.getEventType());
186 }
187
188 // ------------------------------------------------------------------------
189 // ITmfTrace - Initializers
190 // ------------------------------------------------------------------------
191
192 @Override
193 public void initTrace(final IResource resource, final String path, final Class<? extends ITmfEvent> type) throws TmfTraceException {
194 fIndexer = new TmfCheckpointIndexer(this, fCacheSize);
195 initialize(resource, path, type);
196 }
197
198 /**
199 * Initialize the trace common attributes and the base component.
200 *
201 * @param resource the Eclipse resource (trace)
202 * @param path the trace path
203 * @param type the trace event type
204 *
205 * @throws TmfTraceException If something failed during the initialization
206 */
207 protected void initialize(final IResource resource,
208 final String path,
209 final Class<? extends ITmfEvent> type)
210 throws TmfTraceException {
211 if (path == null) {
212 throw new TmfTraceException("Invalid trace path"); //$NON-NLS-1$
213 }
214 fPath = path;
215 fResource = resource;
216 String traceName = (resource != null) ? resource.getName() : null;
217 // If no resource was provided, extract the display name the trace path
218 if (traceName == null) {
219 final int sep = path.lastIndexOf(IPath.SEPARATOR);
220 traceName = (sep >= 0) ? path.substring(sep + 1) : path;
221 }
222 if (fParser == null) {
223 if (this instanceof ITmfEventParser) {
224 fParser = (ITmfEventParser) this;
225 } else {
226 throw new TmfTraceException("Invalid trace parser"); //$NON-NLS-1$
227 }
228 }
229 super.init(traceName, type);
230 // register as VIP after super.init() because TmfComponent registers to signal manager there
231 TmfSignalManager.registerVIP(this);
232 }
233
234 /**
235 * Indicates if the path points to an existing file/directory
236 *
237 * @param path the path to test
238 * @return true if the file/directory exists
239 */
240 protected boolean fileExists(final String path) {
241 final File file = new File(path);
242 return file.exists();
243 }
244
245 /**
246 * @since 2.0
247 */
248 @Override
249 public void indexTrace(boolean waitForCompletion) {
250 getIndexer().buildIndex(0, TmfTimeRange.ETERNITY, waitForCompletion);
251 }
252
253 /**
254 * The default implementation of TmfTrace uses a TmfStatistics back-end.
255 * Override this if you want to specify another type (or none at all).
256 *
257 * @return An IStatus indicating if the statistics could be built
258 * successfully or not.
259 * @since 3.0
260 */
261 protected IStatus buildStatistics() {
262 /*
263 * Initialize the statistics provider, but only if a Resource has been
264 * set (so we don't build it for experiments, for unit tests, etc.)
265 */
266 try {
267 fStatistics = (fResource == null ? null : new TmfStateStatistics(this) );
268 } catch (TmfTraceException e) {
269 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e);
270 }
271 return Status.OK_STATUS;
272 }
273
274 /**
275 * Build the state system(s) associated with this trace type.
276 *
277 * Suppressing the warning, because the 'throws' will usually happen in
278 * sub-classes.
279 *
280 * @return An IStatus indicating if the state system could be build
281 * successfully or not.
282 * @since 3.0
283 */
284 protected IStatus buildStateSystem() {
285 /*
286 * Nothing is done in the base implementation, please specify
287 * how/if to register a new state system in derived classes.
288 */
289 return Status.OK_STATUS;
290 }
291
292 /**
293 * Clears the trace
294 */
295 @Override
296 public synchronized void dispose() {
297 /* Clean up the index if applicable */
298 if (getIndexer() != null) {
299 getIndexer().dispose();
300 }
301
302 /* Clean up the statistics */
303 if (fStatistics != null) {
304 fStatistics.dispose();
305 }
306
307 /* Clean up the state systems */
308 for (ITmfStateSystem ss : fStateSystems.values()) {
309 ss.dispose();
310 }
311
312 super.dispose();
313 }
314
315 // ------------------------------------------------------------------------
316 // ITmfTrace - Basic getters
317 // ------------------------------------------------------------------------
318
319 @Override
320 public Class<ITmfEvent> getEventType() {
321 return (Class<ITmfEvent>) super.getType();
322 }
323
324 @Override
325 public IResource getResource() {
326 return fResource;
327 }
328
329 @Override
330 public String getPath() {
331 return fPath;
332 }
333
334 @Override
335 public int getCacheSize() {
336 return fCacheSize;
337 }
338
339 @Override
340 public long getStreamingInterval() {
341 return fStreamingInterval;
342 }
343
344 /**
345 * @return the trace indexer
346 * @since 3.0
347 */
348 protected ITmfTraceIndexer getIndexer() {
349 return fIndexer;
350 }
351
352 /**
353 * @return the trace parser
354 */
355 protected ITmfEventParser getParser() {
356 return fParser;
357 }
358
359 /**
360 * @since 2.0
361 */
362 @Override
363 public ITmfStatistics getStatistics() {
364 return fStatistics;
365 }
366
367 /**
368 * @since 2.0
369 */
370 @Override
371 public final Map<String, ITmfStateSystem> getStateSystems() {
372 return Collections.unmodifiableMap(fStateSystems);
373 }
374
375 /**
376 * @since 2.0
377 */
378 @Override
379 public final void registerStateSystem(String id, ITmfStateSystem ss) {
380 fStateSystems.put(id, ss);
381 }
382
383 // ------------------------------------------------------------------------
384 // ITmfTrace - Trace characteristics getters
385 // ------------------------------------------------------------------------
386
387 @Override
388 public synchronized long getNbEvents() {
389 return fNbEvents;
390 }
391
392 /**
393 * @since 2.0
394 */
395 @Override
396 public TmfTimeRange getTimeRange() {
397 return new TmfTimeRange(fStartTime, fEndTime);
398 }
399
400 /**
401 * @since 2.0
402 */
403 @Override
404 public ITmfTimestamp getStartTime() {
405 return fStartTime;
406 }
407
408 /**
409 * @since 2.0
410 */
411 @Override
412 public ITmfTimestamp getEndTime() {
413 return fEndTime;
414 }
415
416 /**
417 * @since 2.0
418 */
419 @Override
420 public ITmfTimestamp getInitialRangeOffset() {
421 final long DEFAULT_INITIAL_OFFSET_VALUE = (1L * 100 * 1000 * 1000); // .1sec
422 return new TmfTimestamp(DEFAULT_INITIAL_OFFSET_VALUE, ITmfTimestamp.NANOSECOND_SCALE);
423 }
424
425 /**
426 * @since 3.0
427 */
428 @Override
429 public String getHostId() {
430 return this.getName();
431 }
432
433 // ------------------------------------------------------------------------
434 // Convenience setters
435 // ------------------------------------------------------------------------
436
437 /**
438 * Set the trace cache size. Must be done at initialization time.
439 *
440 * @param cacheSize The trace cache size
441 */
442 protected void setCacheSize(final int cacheSize) {
443 fCacheSize = cacheSize;
444 }
445
446 /**
447 * Set the trace known number of events. This can be quite dynamic
448 * during indexing or for live traces.
449 *
450 * @param nbEvents The number of events
451 */
452 protected synchronized void setNbEvents(final long nbEvents) {
453 fNbEvents = (nbEvents > 0) ? nbEvents : 0;
454 }
455
456 /**
457 * Update the trace events time range
458 *
459 * @param range the new time range
460 * @since 2.0
461 */
462 protected void setTimeRange(final TmfTimeRange range) {
463 fStartTime = range.getStartTime();
464 fEndTime = range.getEndTime();
465 }
466
467 /**
468 * Update the trace chronologically first event timestamp
469 *
470 * @param startTime the new first event timestamp
471 * @since 2.0
472 */
473 protected void setStartTime(final ITmfTimestamp startTime) {
474 fStartTime = startTime;
475 }
476
477 /**
478 * Update the trace chronologically last event timestamp
479 *
480 * @param endTime the new last event timestamp
481 * @since 2.0
482 */
483 protected void setEndTime(final ITmfTimestamp endTime) {
484 fEndTime = endTime;
485 }
486
487 /**
488 * Set the polling interval for live traces (default = 0 = no streaming).
489 *
490 * @param interval the new trace streaming interval
491 */
492 protected void setStreamingInterval(final long interval) {
493 fStreamingInterval = (interval > 0) ? interval : 0;
494 }
495
496 /**
497 * Set the trace indexer. Must be done at initialization time.
498 *
499 * @param indexer the trace indexer
500 * @since 3.0
501 */
502 protected void setIndexer(final ITmfTraceIndexer indexer) {
503 fIndexer = indexer;
504 }
505
506 /**
507 * Set the trace parser. Must be done at initialization time.
508 *
509 * @param parser the new trace parser
510 */
511 protected void setParser(final ITmfEventParser parser) {
512 fParser = parser;
513 }
514
515 // ------------------------------------------------------------------------
516 // ITmfTrace - SeekEvent operations (returning a trace context)
517 // ------------------------------------------------------------------------
518
519 @Override
520 public synchronized ITmfContext seekEvent(final long rank) {
521
522 // A rank <= 0 indicates to seek the first event
523 if (rank <= 0) {
524 ITmfContext context = seekEvent((ITmfLocation) null);
525 context.setRank(0);
526 return context;
527 }
528
529 // Position the trace at the checkpoint
530 final ITmfContext context = fIndexer.seekIndex(rank);
531
532 // And locate the requested event context
533 long pos = context.getRank();
534 if (pos < rank) {
535 ITmfEvent event = getNext(context);
536 while ((event != null) && (++pos < rank)) {
537 event = getNext(context);
538 }
539 }
540 return context;
541 }
542
543 /**
544 * @since 2.0
545 */
546 @Override
547 public synchronized ITmfContext seekEvent(final ITmfTimestamp timestamp) {
548
549 // A null timestamp indicates to seek the first event
550 if (timestamp == null) {
551 ITmfContext context = seekEvent((ITmfLocation) null);
552 context.setRank(0);
553 return context;
554 }
555
556 // Position the trace at the checkpoint
557 ITmfContext context = fIndexer.seekIndex(timestamp);
558
559 // And locate the requested event context
560 ITmfLocation previousLocation = context.getLocation();
561 long previousRank = context.getRank();
562 ITmfEvent event = getNext(context);
563 while (event != null && event.getTimestamp().compareTo(timestamp, false) < 0) {
564 previousLocation = context.getLocation();
565 previousRank = context.getRank();
566 event = getNext(context);
567 }
568 if (event == null) {
569 context.setLocation(null);
570 context.setRank(ITmfContext.UNKNOWN_RANK);
571 } else {
572 context.dispose();
573 context = seekEvent(previousLocation);
574 context.setRank(previousRank);
575 }
576 return context;
577 }
578
579 // ------------------------------------------------------------------------
580 // ITmfTrace - Read operations (returning an actual event)
581 // ------------------------------------------------------------------------
582
583 @Override
584 public synchronized ITmfEvent getNext(final ITmfContext context) {
585 // parseEvent() does not update the context
586 final ITmfEvent event = fParser.parseEvent(context);
587 if (event != null) {
588 updateAttributes(context, event.getTimestamp());
589 context.setLocation(getCurrentLocation());
590 context.increaseRank();
591 processEvent(event);
592 }
593 return event;
594 }
595
596 /**
597 * Hook for special event processing by the concrete class
598 * (called by TmfTrace.getEvent())
599 *
600 * @param event the event
601 */
602 protected void processEvent(final ITmfEvent event) {
603 // Do nothing
604 }
605
606 /**
607 * Update the trace attributes
608 *
609 * @param context the current trace context
610 * @param timestamp the corresponding timestamp
611 * @since 2.0
612 */
613 protected synchronized void updateAttributes(final ITmfContext context, final ITmfTimestamp timestamp) {
614 if (fStartTime.equals(TmfTimestamp.BIG_BANG) || (fStartTime.compareTo(timestamp, false) > 0)) {
615 fStartTime = timestamp;
616 }
617 if (fEndTime.equals(TmfTimestamp.BIG_CRUNCH) || (fEndTime.compareTo(timestamp, false) < 0)) {
618 fEndTime = timestamp;
619 }
620 if (context.hasValidRank()) {
621 long rank = context.getRank();
622 if (fNbEvents <= rank) {
623 fNbEvents = rank + 1;
624 }
625 if (fIndexer != null) {
626 fIndexer.updateIndex(context, timestamp);
627 }
628 }
629 }
630
631 // ------------------------------------------------------------------------
632 // TmfDataProvider
633 // ------------------------------------------------------------------------
634
635 /**
636 * @since 2.0
637 */
638 @Override
639 public synchronized ITmfContext armRequest(final ITmfDataRequest request) {
640 if (executorIsShutdown()) {
641 return null;
642 }
643 if ((request instanceof ITmfEventRequest)
644 && !TmfTimestamp.BIG_BANG.equals(((ITmfEventRequest) request).getRange().getStartTime())
645 && (request.getIndex() == 0))
646 {
647 final ITmfContext context = seekEvent(((ITmfEventRequest) request).getRange().getStartTime());
648 ((ITmfEventRequest) request).setStartIndex((int) context.getRank());
649 return context;
650
651 }
652 return seekEvent(request.getIndex());
653 }
654
655 // ------------------------------------------------------------------------
656 // Signal handlers
657 // ------------------------------------------------------------------------
658
659 /**
660 * Handler for the Trace Opened signal
661 *
662 * @param signal
663 * The incoming signal
664 * @since 2.0
665 */
666 @TmfSignalHandler
667 public void traceOpened(TmfTraceOpenedSignal signal) {
668 boolean signalIsForUs = false;
669 for (ITmfTrace trace : TmfTraceManager.getTraceSet(signal.getTrace())) {
670 if (trace == this) {
671 signalIsForUs = true;
672 break;
673 }
674 }
675
676 if (!signalIsForUs) {
677 return;
678 }
679
680 /*
681 * The signal is either for this trace, or for an experiment containing
682 * this trace.
683 */
684 MultiStatus status = new MultiStatus(Activator.PLUGIN_ID, IStatus.OK, null, null);
685 status.add(buildStatistics());
686 status.add(buildStateSystem());
687 if (!status.isOK()) {
688 Activator.log(status);
689 }
690
691 /* Refresh the project, so it can pick up new files that got created. */
692 try {
693 if (fResource != null) {
694 fResource.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
695 }
696 } catch (CoreException e) {
697 e.printStackTrace();
698 }
699
700 if (signal.getTrace() == this) {
701 /* Additionally, the signal is directly for this trace. */
702 if (getNbEvents() == 0) {
703 return;
704 }
705
706 /* For a streaming trace, the range updated signal should be sent
707 * by the subclass when a new safe time is determined.
708 */
709 if (getStreamingInterval() > 0) {
710 return;
711 }
712
713 final TmfTimeRange timeRange = new TmfTimeRange(getStartTime(), TmfTimestamp.BIG_CRUNCH);
714 final TmfTraceRangeUpdatedSignal rangeUpdatedsignal = new TmfTraceRangeUpdatedSignal(this, this, timeRange);
715
716 // Broadcast in separate thread to prevent deadlock
717 new Thread() {
718 @Override
719 public void run() {
720 broadcast(rangeUpdatedsignal);
721 }
722 }.start();
723 return;
724 }
725 }
726
727 /**
728 * Signal handler for the TmfTraceRangeUpdatedSignal signal
729 *
730 * @param signal The incoming signal
731 * @since 2.0
732 */
733 @TmfSignalHandler
734 public void traceRangeUpdated(final TmfTraceRangeUpdatedSignal signal) {
735 if (signal.getTrace() == this) {
736 getIndexer().buildIndex(getNbEvents(), signal.getRange(), false);
737 }
738 }
739
740 // ------------------------------------------------------------------------
741 // toString
742 // ------------------------------------------------------------------------
743
744 @Override
745 @SuppressWarnings("nls")
746 public synchronized String toString() {
747 return "TmfTrace [fPath=" + fPath + ", fCacheSize=" + fCacheSize
748 + ", fNbEvents=" + fNbEvents + ", fStartTime=" + fStartTime
749 + ", fEndTime=" + fEndTime + ", fStreamingInterval=" + fStreamingInterval + "]";
750 }
751
752}
This page took 0.024838 seconds and 5 git commands to generate.