Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: bf8f0d7bde22527a046570bdc860faef2cc26077 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
/*******************************************************************************
 * Copyright (c) 2009, 2010 Ericsson
 * 
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *   Francois Chouinard - Initial API and implementation
 *******************************************************************************/

package org.eclipse.linuxtools.tmf.core.trace;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Vector;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.linuxtools.tmf.core.component.TmfEventProvider;
import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
import org.eclipse.linuxtools.tmf.core.event.ITmfTimestamp;
import org.eclipse.linuxtools.tmf.core.event.TmfTimeRange;
import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp;
import org.eclipse.linuxtools.tmf.core.request.ITmfDataRequest;
import org.eclipse.linuxtools.tmf.core.request.ITmfEventRequest;
import org.eclipse.linuxtools.tmf.core.request.TmfDataRequest;
import org.eclipse.linuxtools.tmf.core.request.TmfEventRequest;
import org.eclipse.linuxtools.tmf.core.signal.TmfTraceUpdatedSignal;

/**
 * <b><u>TmfTrace</u></b>
 * <p>
 * Abstract implementation of ITmfTrace. It should be sufficient to extend this class and provide implementation for
 * <code>getCurrentLocation()</code> and <code>seekLocation()</code>, as well as a proper parser, to have a working
 * concrete implementation.
 * <p>
 * Note: The notion of event rank is still under heavy discussion. Although used by the Events View and probably useful
 * in the general case, there is no easy way to implement it for LTTng (actually a strong case is being made that this
 * is useless).
 * <p>
 * That it is not supported by LTTng does by no mean indicate that it is not useful for (just about) every other tracing
 * tool. Therefore, this class provides a minimal (and partial) implementation of rank. However, the current
 * implementation should not be relied on in the general case.
 * 
 * TODO: Add support for live streaming (notifications, incremental indexing, ...)
 */
public abstract class TmfTrace<T extends ITmfEvent> extends TmfEventProvider<T> implements ITmfTrace<T>, Cloneable {

    // ------------------------------------------------------------------------
    // Constants
    // ------------------------------------------------------------------------

    // The default number of events to cache
    // TODO: Make the DEFAULT_CACHE_SIZE a preference
    public static final int DEFAULT_INDEX_PAGE_SIZE = 50000;

    // ------------------------------------------------------------------------
    // Attributes
    // ------------------------------------------------------------------------

    // The trace path
    private String fPath;

    // The trace name
    private String fTraceName;

    // The cache page size AND checkpoints interval
    protected int fIndexPageSize = DEFAULT_INDEX_PAGE_SIZE;

    // The set of event stream checkpoints (for random access)
    protected Vector<TmfCheckpoint> fCheckpoints = new Vector<TmfCheckpoint>();

    // The number of events collected
    protected long fNbEvents = 0;

    // The time span of the event stream
    private ITmfTimestamp fStartTime = TmfTimestamp.BIG_CRUNCH;
    private ITmfTimestamp fEndTime = TmfTimestamp.BIG_BANG;

    // The properties resource
    private IResource fResource;

    // ------------------------------------------------------------------------
    // Constructors
    // ------------------------------------------------------------------------

    public TmfTrace() {
        super();
    }

    @Override
    public void initTrace(String name, String path, Class<T> eventType) throws FileNotFoundException {
        initTmfTrace(name, path, eventType, DEFAULT_INDEX_PAGE_SIZE, false);
    }

    @Override
    public void initTrace(String name, String path, Class<T> eventType, int cacheSize) throws FileNotFoundException {
        initTmfTrace(name, path, eventType, cacheSize, false);
    }

    @Override
    public void initTrace(String name, String path, Class<T> eventType, boolean indexTrace) throws FileNotFoundException {
        initTmfTrace(name, path, eventType, DEFAULT_INDEX_PAGE_SIZE, indexTrace);
    }

    @Override
    public void initTrace(String name, String path, Class<T> eventType, int cacheSize, boolean indexTrace) throws FileNotFoundException {
        initTmfTrace(name, path, eventType, cacheSize, indexTrace);
    }

    private void initTmfTrace(String name, String path, Class<T> eventType, int cacheSize, boolean indexTrace) throws FileNotFoundException {
        fPath = path;
        if (name != null) {
            fTraceName = name;
        }
        if (fTraceName == null) {
            fTraceName = ""; //$NON-NLS-1$
            if (path != null) {
                int sep = path.lastIndexOf(Path.SEPARATOR);
                fTraceName = (sep >= 0) ? path.substring(sep + 1) : path;
            }
        }
        super.init(fTraceName, eventType);
        fIndexPageSize = (cacheSize > 0) ? cacheSize : DEFAULT_INDEX_PAGE_SIZE;
        if (indexTrace)
            indexTrace(false);
    }

    @Override
    public boolean validate(IProject project, String path) {
        File file = new File(path);
        return file.exists();
    }

    /**
     * @param path
     * @throws FileNotFoundException
     */
    protected TmfTrace(String name, Class<T> type, String path) throws FileNotFoundException {
        this(name, type, path, DEFAULT_INDEX_PAGE_SIZE, true);
    }

    /**
     * @param path
     * @param cacheSize
     * @throws FileNotFoundException
     */
    protected TmfTrace(String name, Class<T> type, String path, int cacheSize) throws FileNotFoundException {
        this(name, type, path, cacheSize, true);
    }

    /**
     * @param path
     * @param indexTrace
     * @throws FileNotFoundException
     */
    protected TmfTrace(String name, Class<T> type, String path, boolean indexTrace) throws FileNotFoundException {
        this(name, type, path, DEFAULT_INDEX_PAGE_SIZE, indexTrace);
    }

    /**
     * @param path
     * @param cacheSize
     * @param indexTrace
     * @throws FileNotFoundException
     */
    protected TmfTrace(String name, Class<T> type, String path, int cacheSize, boolean indexTrace) throws FileNotFoundException {
        super();
        fTraceName = name;
        initTrace(name, path, type, cacheSize, indexTrace);
    }

    @SuppressWarnings("unchecked")
    @Override
    public TmfTrace<T> clone() throws CloneNotSupportedException {
        TmfTrace<T> clone = (TmfTrace<T>) super.clone();
        clone.fCheckpoints = fCheckpoints;
        clone.fStartTime = fStartTime.clone();
        clone.fEndTime = fEndTime.clone();
        return clone;
    }

    // ------------------------------------------------------------------------
    // Accessors
    // ------------------------------------------------------------------------

    /**
     * @return the trace path
     */
    @Override
    public String getPath() {
        return fPath;
    }

    /* (non-Javadoc)
     * @see org.eclipse.linuxtools.tmf.stream.ITmfEventStream#getNbEvents()
     */
    @Override
    public synchronized long getNbEvents() {
        return fNbEvents;
    }

    /**
     * @return the size of the cache
     */
    @Override
    public int getCacheSize() {
        return fIndexPageSize;
    }

    /* (non-Javadoc)
     * @see org.eclipse.linuxtools.tmf.stream.ITmfEventStream#getTimeRange()
     */
    @Override
    public TmfTimeRange getTimeRange() {
        return new TmfTimeRange(fStartTime, fEndTime);
    }

    /* (non-Javadoc)
     * @see org.eclipse.linuxtools.tmf.trace.ITmfTrace#getStartTime()
     */
    @Override
    public ITmfTimestamp getStartTime() {
        return fStartTime;
    }

    /* (non-Javadoc)
     * @see org.eclipse.linuxtools.tmf.trace.ITmfTrace#getEndTime()
     */
    @Override
    public ITmfTimestamp getEndTime() {
        return fEndTime;
    }

    /* (non-Javadoc)
     * @see org.eclipse.linuxtools.tmf.trace.ITmfTrace#getStreamingInterval()
     */
    @Override
    public long getStreamingInterval() {
        return 0;
    }

    @SuppressWarnings("unchecked")
    public Vector<TmfCheckpoint> getCheckpoints() {
        return (Vector<TmfCheckpoint>) fCheckpoints.clone();
    }

    /**
     * Returns the rank of the first event with the requested timestamp. If none, returns the index of the next event
     * (if any).
     * 
     * @param timestamp
     * @return
     */
    @Override
    public long getRank(ITmfTimestamp timestamp) {
        TmfContext context = seekEvent(timestamp);
        return context.getRank();
    }

    // ------------------------------------------------------------------------
    // Operators
    // ------------------------------------------------------------------------

    protected void setTimeRange(TmfTimeRange range) {
        fStartTime = range.getStartTime();
        fEndTime = range.getEndTime();
    }

    protected void setStartTime(ITmfTimestamp startTime) {
        fStartTime = startTime;
    }

    protected void setEndTime(ITmfTimestamp endTime) {
        fEndTime = endTime;
    }

    // ------------------------------------------------------------------------
    // TmfProvider
    // ------------------------------------------------------------------------

    @Override
    public ITmfContext armRequest(ITmfDataRequest<T> request) {
        if (request instanceof ITmfEventRequest<?>
                && !TmfTimestamp.BIG_BANG.equals(((ITmfEventRequest<T>) request).getRange().getStartTime()) && request.getIndex() == 0) {
            ITmfContext context = seekEvent(((ITmfEventRequest<T>) request).getRange().getStartTime());
            ((ITmfEventRequest<T>) request).setStartIndex((int) context.getRank());
            return context;

        }
        return seekEvent(request.getIndex());
    }

    /**
     * Return the next piece of data based on the context supplied. The context would typically be updated for the
     * subsequent read.
     * 
     * @param context
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public T getNext(ITmfContext context) {
        if (context instanceof TmfContext) {
            return (T) getNextEvent((TmfContext) context);
        }
        return null;
    }

    // ------------------------------------------------------------------------
    // ITmfTrace
    // ------------------------------------------------------------------------

    /* (non-Javadoc)
     * @see org.eclipse.linuxtools.tmf.trace.ITmfTrace#seekEvent(org.eclipse.linuxtools.tmf.event.TmfTimestamp)
     */
    @Override
    public TmfContext seekEvent(ITmfTimestamp ts) {

        ITmfTimestamp timestamp = ts;
        if (timestamp == null) {
            timestamp = TmfTimestamp.BIG_BANG;
        }

        // First, find the right checkpoint
        int index = Collections.binarySearch(fCheckpoints, new TmfCheckpoint(timestamp, null));

        // In the very likely case that the checkpoint was not found, bsearch
        // returns its negated would-be location (not an offset...). From that
        // index, we can then position the stream and get the event.
        if (index < 0) {
            index = Math.max(0, -(index + 2));
        }

        // Position the stream at the checkpoint
        ITmfLocation<?> location;
        synchronized (fCheckpoints) {
            if (!fCheckpoints.isEmpty()) {
                if (index >= fCheckpoints.size()) {
                    index = fCheckpoints.size() - 1;
                }
                location = fCheckpoints.elementAt(index).getLocation();
            } else {
                location = null;
            }
        }
        TmfContext context = seekLocation(location);
        context.setRank(index * fIndexPageSize);

        // And locate the event
        TmfContext nextEventContext = context.clone(); // Must use clone() to get the right subtype...
        ITmfEvent event = getNextEvent(nextEventContext);
        while (event != null && event.getTimestamp().compareTo(timestamp, false) < 0) {
            context.setLocation(nextEventContext.getLocation().clone());
            context.updateRank(1);
            event = getNextEvent(nextEventContext);
        }

        return context;
    }

    /* (non-Javadoc)
     * @see org.eclipse.linuxtools.tmf.trace.ITmfTrace#seekEvent(int)
     */
    @Override
    public TmfContext seekEvent(long rank) {

        // Position the stream at the previous checkpoint
        int index = (int) rank / fIndexPageSize;
        ITmfLocation<?> location;
        synchronized (fCheckpoints) {
            if (fCheckpoints.isEmpty()) {
                location = null;
            } else {
                if (index >= fCheckpoints.size()) {
                    index = fCheckpoints.size() - 1;
                }
                location = fCheckpoints.elementAt(index).getLocation();
            }
        }

        TmfContext context = seekLocation(location);
        long pos = index * fIndexPageSize;
        context.setRank(pos);

        if (pos < rank) {
            ITmfEvent event = getNextEvent(context);
            while (event != null && ++pos < rank) {
                event = getNextEvent(context);
            }
        }

        return context;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.linuxtools.tmf.trace.ITmfTrace#getNextEvent(org.eclipse.
     * linuxtools.tmf.trace.ITmfTrace.TraceContext)
     */
    @Override
    public synchronized ITmfEvent getNextEvent(ITmfContext context) {
        // parseEvent() does not update the context
        ITmfEvent event = parseEvent(context);
        if (event != null) {
            updateIndex(context, context.getRank(), event.getTimestamp());
            context.setLocation(getCurrentLocation());
            context.updateRank(1);
            processEvent(event);
        }
        return event;
    }

    protected synchronized void updateIndex(ITmfContext context, long rank, ITmfTimestamp timestamp) {
        if (fStartTime.compareTo(timestamp, false) > 0)
            fStartTime = timestamp;
        if (fEndTime.compareTo(timestamp, false) < 0)
            fEndTime = timestamp;
        if (context.isValidRank()) {
            if (fNbEvents <= rank)
                fNbEvents = rank + 1;
            // Build the index as we go along
            if ((rank % fIndexPageSize) == 0) {
                // Determine the table position
                long position = rank / fIndexPageSize;
                // Add new entry at proper location (if empty)
                if (fCheckpoints.size() == position) {
                    ITmfLocation<?> location = context.getLocation().clone();
                    fCheckpoints.add(new TmfCheckpoint(timestamp.clone(), location));
                    // System.out.println(getName() + "[" + (fCheckpoints.size()
                    // - 1) + "] " + timestamp + ", " + location.toString());
                }
            }
        }
    }

    /**
     * Hook for special processing by the concrete class (called by getNextEvent())
     * 
     * @param event
     */
    protected void processEvent(ITmfEvent event) {
        // Do nothing by default
    }

    // ------------------------------------------------------------------------
    // toString
    // ------------------------------------------------------------------------

    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    @SuppressWarnings("nls")
    public String toString() {
        return "[TmfTrace (" + getName() + ")]";
    }

    // ------------------------------------------------------------------------
    // Indexing
    // ------------------------------------------------------------------------

    /*
     * The purpose of the index is to keep the information needed to rapidly
     * restore the traces contexts at regular intervals (every INDEX_PAGE_SIZE
     * event).
     */

    @SuppressWarnings({ "unchecked" })
    protected void indexTrace(boolean waitForCompletion) {

        final Job job = new Job("Indexing " + getName() + "...") { //$NON-NLS-1$ //$NON-NLS-2$
            @Override
            protected IStatus run(IProgressMonitor monitor) {
                while (!monitor.isCanceled()) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        return Status.OK_STATUS;
                    }
                }
                monitor.done();
                return Status.OK_STATUS;
            }
        };
        job.schedule();

        fCheckpoints.clear();
        ITmfEventRequest<ITmfEvent> request = new TmfEventRequest<ITmfEvent>(ITmfEvent.class, TmfTimeRange.ETERNITY, TmfDataRequest.ALL_DATA,
                fIndexPageSize, ITmfDataRequest.ExecutionType.BACKGROUND) {

            ITmfTimestamp startTime = null;
            ITmfTimestamp lastTime = null;

            @Override
            public void handleData(ITmfEvent event) {
                super.handleData(event);
                if (event != null) {
                    ITmfTimestamp ts = event.getTimestamp();
                    if (startTime == null)
                        startTime = ts.clone();
                    lastTime = ts.clone();

                    if ((getNbRead() % fIndexPageSize) == 0) {
                        updateTrace();
                    }
                }
            }

            @Override
            public void handleSuccess() {
                updateTrace();
            }

            @Override
            public void handleCompleted() {
                job.cancel();
                super.handleCompleted();
            }

            private synchronized void updateTrace() {
                int nbRead = getNbRead();
                if (nbRead != 0) {
                    fStartTime = startTime;
                    fEndTime = lastTime;
                    fNbEvents = nbRead;
                    notifyListeners();
                }
            }
        };

        sendRequest((ITmfDataRequest<T>) request);
        if (waitForCompletion)
            try {
                request.waitForCompletion();
            } catch (InterruptedException e) {
//                e.printStackTrace();
            }
    }

    protected void notifyListeners() {
        broadcast(new TmfTraceUpdatedSignal(this, this, new TmfTimeRange(fStartTime, fEndTime)));
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.linuxtools.tmf.core.trace.ITmfTrace#setResource(org.eclipse.core.resources.IResource)
     */
    @Override
    public void setResource(IResource resource) {
        fResource = resource;
    }

    /*
     * (non-Javadoc)
     * @see org.eclipse.linuxtools.tmf.core.trace.ITmfTrace#getResource()
     */
    @Override
    public IResource getResource() {
        return fResource;
    }
}

Back to the top