tmf: Fix for bug 415795: IndexOutOfBoundsException in time graph combo
[deliverable/tracecompass.git] / org.eclipse.linuxtools.tmf.help / doc / Developer-Guide.mediawiki
CommitLineData
067490ab 1
73844f9c 2= Introduction =
067490ab
AM
3
4The purpose of the '''Tracing Monitoring Framework (TMF)''' is to facilitate the integration of tracing and monitoring tools into Eclipse, to provide out-of-the-box generic functionalities/views and provide extension mechanisms of the base functionalities for application specific purposes.
5
73844f9c 6= Implementing a New Trace Type =
6f182760 7
73844f9c 8The framework can easily be extended to support more trace types. To make a new trace type, one must define the following items:
6f182760 9
73844f9c
PT
10* The event type
11* The trace reader
12* The trace context
13* The trace location
14* (Optional but recommended) The ''org.eclipse.linuxtools.tmf.ui.tracetype'' plug-in extension point
6f182760 15
73844f9c 16The '''event type''' must implement an ''ITmfEvent'' or extend a class that implements an ''ITmfEvent''. Typically it will extend ''TmfEvent''. The event type must contain all the data of an event. The '''trace reader''' must be of an ''ITmfTrace'' type. The ''TmfTrace'' class will supply many background operations so that the reader only needs to implement certain functions. The '''trace context''' can be seen as the internals of an iterator. It is required by the trace reader to parse events as it iterates the trace and to keep track of its rank and location. It can have a timestamp, a rank, a file position, or any other element, it should be considered to be ephemeral. The '''trace location''' is an element that is cloned often to store checkpoints, it is generally persistent. It is used to rebuild a context, therefore, it needs to contain enough information to unambiguously point to one and only one event. Finally the ''tracetype'' plug-in extension associates a given trace, non-programmatically to a trace type for use in the UI.
6f182760 17
73844f9c 18== An Example: Nexus-lite parser ==
6f182760 19
73844f9c 20=== Description of the file ===
6f182760 21
73844f9c 22This is a very small subset of the nexus trace format, with some changes to make it easier to read. There is one file. This file starts with 64 Strings containing the event names, then an arbitrarily large number of events. The events are each 64 bits long. the first 32 are the timestamp in microseconds, the second 32 are split into 6 bits for the event type, and 26 for the data payload.
6f182760 23
73844f9c 24The trace type will be made of two parts, part 1 is the event description, it is just 64 strings, comma seperated and then a line feed.
6f182760
PT
25
26<pre>
73844f9c 27Startup,Stop,Load,Add, ... ,reserved\n
6f182760
PT
28</pre>
29
73844f9c 30Then there will be the events in this format
6f182760 31
73844f9c
PT
32{| width= "85%"
33|style="width: 50%; background-color: #ffffcc;"|timestamp (32 bits)
34|style="width: 10%; background-color: #ffccff;"|type (6 bits)
35|style="width: 40%; background-color: #ccffcc;"|payload (26 bits)
36|-
37|style="background-color: #ffcccc;" colspan="3"|64 bits total
38|}
6f182760 39
73844f9c 40all events will be the same size (64 bits).
6f182760 41
73844f9c 42=== NexusLite Plug-in ===
6f182760 43
73844f9c 44Create a '''New''', '''Project...''', '''Plug-in Project''', set the title to '''com.example.nexuslite''', click '''Next >''' then click on '''Finish'''.
6f182760 45
73844f9c 46Now the structure for the Nexus trace Plug-in is set up.
6f182760 47
73844f9c 48Add a dependency to TMF core and UI by opening the '''MANIFEST.MF''' in '''META-INF''', selecting the '''Dependencies''' tab and '''Add ...''' '''org.eclipse.linuxtools.tmf.core''' and '''org.eclipse.linuxtools.tmf.ui'''.
6f182760 49
73844f9c
PT
50[[Image:images/NTTAddDepend.png]]<br>
51[[Image:images/NTTSelectProjects.png]]<br>
6f182760 52
73844f9c 53Now the project can access TMF classes.
6f182760 54
73844f9c 55=== Trace Event ===
6f182760 56
73844f9c 57The '''TmfEvent''' class will work for this example. No code required.
6f182760 58
73844f9c 59=== Trace Reader ===
6f182760 60
73844f9c 61The trace reader will extend a '''TmfTrace''' class.
6f182760 62
73844f9c 63It will need to implement:
6f182760 64
73844f9c 65* validate (is the trace format valid?)
6f182760 66
73844f9c 67* initTrace (called as the trace is opened
6f182760 68
73844f9c 69* seekEvent (go to a position in the trace and create a context)
6f182760 70
73844f9c 71* getNext (implemented in the base class)
6f182760 72
73844f9c 73* parseEvent (read the next element in the trace)
6f182760 74
73844f9c 75Here is an example implementation of the Nexus Trace file
6f182760 76
73844f9c
PT
77<pre>/*******************************************************************************
78 * Copyright (c) 2013 Ericsson
79 *
80 * All rights reserved. This program and the accompanying materials are
81 * made available under the terms of the Eclipse Public License v1.0 which
82 * accompanies this distribution, and is available at
83 * http://www.eclipse.org/legal/epl-v10.html
84 *
85 * Contributors:
86 * Matthew Khouzam - Initial API and implementation
87 *******************************************************************************/
6f182760 88
73844f9c 89package com.example.nexuslite;
6f182760 90
73844f9c
PT
91import java.io.BufferedReader;
92import java.io.File;
93import java.io.FileInputStream;
94import java.io.FileNotFoundException;
95import java.io.FileReader;
96import java.io.IOException;
97import java.nio.MappedByteBuffer;
98import java.nio.channels.FileChannel;
99import java.nio.channels.FileChannel.MapMode;
6f182760 100
73844f9c
PT
101import org.eclipse.core.resources.IProject;
102import org.eclipse.core.resources.IResource;
103import org.eclipse.core.runtime.IStatus;
104import org.eclipse.core.runtime.Status;
105import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
106import org.eclipse.linuxtools.tmf.core.event.ITmfEventField;
107import org.eclipse.linuxtools.tmf.core.event.TmfEvent;
108import org.eclipse.linuxtools.tmf.core.event.TmfEventField;
109import org.eclipse.linuxtools.tmf.core.event.TmfEventType;
110import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException;
111import org.eclipse.linuxtools.tmf.core.timestamp.ITmfTimestamp;
112import org.eclipse.linuxtools.tmf.core.timestamp.TmfTimestamp;
113import org.eclipse.linuxtools.tmf.core.trace.ITmfContext;
114import org.eclipse.linuxtools.tmf.core.trace.ITmfEventParser;
115import org.eclipse.linuxtools.tmf.core.trace.ITmfLocation;
116import org.eclipse.linuxtools.tmf.core.trace.TmfContext;
117import org.eclipse.linuxtools.tmf.core.trace.TmfLongLocation;
118import org.eclipse.linuxtools.tmf.core.trace.TmfTrace;
6f182760 119
73844f9c
PT
120/**
121 * Nexus trace type
122 *
123 * @author Matthew Khouzam
124 */
125public class NexusTrace extends TmfTrace implements ITmfEventParser {
6f182760 126
73844f9c
PT
127 private static final int CHUNK_SIZE = 65536; // seems fast on MY system
128 private static final int EVENT_SIZE = 8; // according to spec
6f182760 129
73844f9c
PT
130 private TmfLongLocation fCurrentLocation;
131 private static final TmfLongLocation NULLLOCATION = new TmfLongLocation(
132 (Long) null);
133 private static final TmfContext NULLCONTEXT = new TmfContext(NULLLOCATION,
134 -1L);
6f182760 135
73844f9c
PT
136 private long fSize;
137 private long fOffset;
138 private File fFile;
139 private String[] fEventTypes;
140 private FileChannel fFileChannel;
141 private MappedByteBuffer fMappedByteBuffer;
6f182760 142
73844f9c
PT
143 @Override
144 public IStatus validate(@SuppressWarnings("unused") IProject project,
145 String path) {
146 File f = new File(path);
147 if (!f.exists()) {
148 return new Status(IStatus.ERROR, Activator.PLUGIN_ID,
149 "File does not exist"); //$NON-NLS-1$
150 }
151 if (!f.isFile()) {
152 return new Status(IStatus.ERROR, Activator.PLUGIN_ID, path
153 + " is not a file"); //$NON-NLS-1$
154 }
155 String header = readHeader(f);
156 if (header.split(",", 64).length == 64) { //$NON-NLS-1$
157 return Status.OK_STATUS;
158 }
159 return new Status(IStatus.ERROR, Activator.PLUGIN_ID,
160 "File does not start as a CSV"); //$NON-NLS-1$
161 }
6f182760 162
73844f9c
PT
163 @Override
164 public ITmfLocation getCurrentLocation() {
165 return fCurrentLocation;
166 }
6f182760 167
73844f9c
PT
168 @Override
169 public void initTrace(IResource resource, String path,
170 Class<? extends ITmfEvent> type) throws TmfTraceException {
171 super.initTrace(resource, path, type);
172 fFile = new File(path);
173 fSize = fFile.length();
174 if (fSize == 0) {
175 throw new TmfTraceException("file is empty"); //$NON-NLS-1$
176 }
177 String header = readHeader(fFile);
178 if (header == null) {
179 throw new TmfTraceException("File does not start as a CSV"); //$NON-NLS-1$
180 }
181 fEventTypes = header.split(",", 64); // 64 values of types according to //$NON-NLS-1$
182 // the 'spec'
183 if (fEventTypes.length != 64) {
184 throw new TmfTraceException(
185 "Trace header does not contain 64 event names"); //$NON-NLS-1$
186 }
187 if (getNbEvents() < 1) {
188 throw new TmfTraceException("Trace does not have any events"); //$NON-NLS-1$
189 }
190 try {
191 fFileChannel = new FileInputStream(fFile).getChannel();
192 seek(0);
193 } catch (FileNotFoundException e) {
194 throw new TmfTraceException(e.getMessage());
195 } catch (IOException e) {
196 throw new TmfTraceException(e.getMessage());
197 }
198 }
6f182760 199
73844f9c
PT
200 /**
201 * @return
202 */
203 private String readHeader(File file) {
204 String header = new String();
205 BufferedReader br;
206 try {
207 br = new BufferedReader(new FileReader(file));
208 header = br.readLine();
209 br.close();
210 } catch (IOException e) {
211 return null;
212 }
213 fOffset = header.length() + 1;
214 setNbEvents((fSize - fOffset) / EVENT_SIZE);
215 return header;
216 }
6f182760 217
73844f9c
PT
218 @Override
219 public double getLocationRatio(ITmfLocation location) {
220 return ((TmfLongLocation) location).getLocationInfo().doubleValue()
221 / getNbEvents();
222 }
6f182760 223
73844f9c
PT
224 @Override
225 public ITmfContext seekEvent(ITmfLocation location) {
226 TmfLongLocation nl = (TmfLongLocation) location;
227 if (location == null) {
228 nl = new TmfLongLocation(0L);
229 }
230 try {
231 seek(nl.getLocationInfo());
232 } catch (IOException e) {
233 return NULLCONTEXT;
234 }
235 return new TmfContext(nl, nl.getLocationInfo());
236 }
6f182760 237
73844f9c
PT
238 @Override
239 public ITmfContext seekEvent(double ratio) {
240 long rank = (long) (ratio * getNbEvents());
241 try {
242 seek(rank);
243 } catch (IOException e) {
244 return NULLCONTEXT;
245 }
246 return new TmfContext(new TmfLongLocation(rank), rank);
247 }
6f182760 248
73844f9c
PT
249 private void seek(long rank) throws IOException {
250 final long position = fOffset + (rank * EVENT_SIZE);
251 int size = Math.min((int) (fFileChannel.size() - position), CHUNK_SIZE);
252 fMappedByteBuffer = fFileChannel.map(MapMode.READ_ONLY, position, size);
253 }
6f182760 254
73844f9c
PT
255 @Override
256 public ITmfEvent parseEvent(ITmfContext context) {
257 if ((context == null) || (context.getRank() == -1)) {
258 return null;
259 }
260 TmfEvent event = null;
261 long ts = -1;
262 int type = -1;
263 int payload = -1;
264 long pos = context.getRank();
265 if (pos < getNbEvents()) {
266 try {
267 // if we are approaching the limit size, move to a new window
268 if ((fMappedByteBuffer.position() + EVENT_SIZE) > fMappedByteBuffer
269 .limit()) {
270 seek(context.getRank());
271 }
272 /*
273 * the trace format, is:
274 *
275 * - 32 bits for the time,
276 * - 6 for the event type,
277 * - 26 for the data.
278 *
279 * all the 0x00 stuff are masks.
280 */
6f182760 281
73844f9c
PT
282 /*
283 * it may be interesting to assume if the ts goes back in time,
284 * it actually is rolling over we would need to keep the
285 * previous timestamp for that, keep the high bits and increment
286 * them if the next int ts read is lesser than the previous one
287 */
6f182760 288
73844f9c 289 ts = 0x00000000ffffffffL & fMappedByteBuffer.getInt();
6f182760 290
73844f9c
PT
291 long data = 0x00000000ffffffffL & fMappedByteBuffer.getInt();
292 type = (int) (data >> 26) & (0x03f); // first 6 bits
293 payload = (int) (data & 0x003FFFFFFL); // last 26 bits
294 // the time is in microseconds.
295 TmfTimestamp timestamp = new TmfTimestamp(ts, ITmfTimestamp.MICROSECOND_SCALE);
296 final String title = fEventTypes[type];
297 // put the value in a field
298 final TmfEventField tmfEventField = new TmfEventField(
299 "value", payload, null); //$NON-NLS-1$
300 // the field must be in an array
301 final TmfEventField[] fields = new TmfEventField[1];
302 fields[0] = tmfEventField;
303 final TmfEventField content = new TmfEventField(
304 ITmfEventField.ROOT_FIELD_ID, null, fields);
305 // set the current location
6f182760 306
73844f9c
PT
307 fCurrentLocation = new TmfLongLocation(pos);
308 // create the event
309 event = new TmfEvent(this, pos, timestamp, null,
310 new TmfEventType(title, title, null), content, null);
311 } catch (IOException e) {
312 fCurrentLocation = new TmfLongLocation(-1L);
313 }
314 }
315 return event;
316 }
317}
318</pre>
6f182760 319
73844f9c 320In this example the '''validate''' function checks if the file exists and is not a directory.
6f182760 321
73844f9c 322The '''initTrace''' function will read the event names, and find where the data starts. After this, the number of events is known, and since each event is 8 bytes long according to the specs, the seek is then trivial.
6f182760 323
73844f9c 324The '''seek''' here will just reset the reader to the right location.
6f182760 325
73844f9c 326The '''parseEvent''' method needs to parse and return the current event and store the current location.
6f182760 327
73844f9c 328The '''getNext''' method (in base class) will read the next event and update the context. It calls the '''parseEvent''' method to read the event and update the location. It does not need to be overridden and in this example it is not. The sequence of actions necessary are parse the next event from the trace, create an '''ITmfEvent''' with that data, update the current location, call '''updateAttributes''', update the context then return the event.
6f182760 329
73844f9c 330=== Trace Context ===
6f182760 331
73844f9c 332The trace context will be a '''TmfContext'''
6f182760 333
73844f9c 334=== Trace Location ===
6f182760 335
73844f9c 336The trace location will be a long, representing the rank in the file. The '''TmfLongLocation''' will be the used, once again, no code is required.
6f182760 337
73844f9c 338=== (Optional but recommended) The ''org.eclipse.linuxtools.tmf.ui.tracetype'' plug-in extension point ===
6f182760 339
73844f9c 340One can implement the ''tracetype'' extension in their own plug-in. In this example, the ''com.example.nexuslite'' plug-in will be modified.
6f182760 341
73844f9c 342The '''plugin.xml''' file in the ui plug-in needs to be updated if one wants users to access the given event type. It can be updated in the Eclipse plug-in editor.
6f182760 343
73844f9c
PT
344# In Extensions tab, add the '''org.eclipse.linuxtools.tmf.ui.tracetype''' extension point.
345[[Image:images/NTTExtension.png]]<br>
346[[Image:images/NTTTraceType.png]]<br>
347[[Image:images/NTTExtensionPoint.png]]<br>
6f182760 348
73844f9c 349# Add in the '''org.eclipse.linuxtools.tmf.ui.tracetype''' extension a new type. To do that, '''right click''' on the extension then in the context menu, go to '''New >''', '''type'''.
6f182760 350
73844f9c 351[[Image:images/NTTAddType.png]]<br>
6f182760 352
73844f9c 353The '''id''' is the unique identifier used to refer to the trace.
6f182760 354
73844f9c 355The '''name''' is the field that shall be displayed when a trace type is selected.
6f182760 356
73844f9c 357The '''trace type''' is the canonical path refering to the class of the trace.
6f182760 358
73844f9c 359The '''event type''' is the canonical path refering to the class of the events of a given trace.
6f182760 360
73844f9c 361The '''category''' (optional) is the container in which this trace type will be stored.
6f182760 362
73844f9c 363The '''icon''' (optional) is the image to associate with that trace type.
6f182760 364
73844f9c 365In the end, the extension menu should look like this.
6f182760 366
73844f9c 367[[Image:images/NTTPluginxmlComplete.png]]<br>
6f182760 368
73844f9c 369== Best Practices ==
6f182760 370
73844f9c
PT
371* Do not load the whole trace in RAM, it will limit the size of the trace that can be read.
372* Reuse as much code as possible, it makes the trace format much easier to maintain.
373* Use Eclipse's editor instead of editing the xml directly.
374* Do not forget Java supports only signed data types, there may be special care needed to handle unsigned data.
375* Keep all the code in the same plug-in as the ''tracetype'' if it makes sense from a design point of view. It will make integration easier.
6f182760 376
73844f9c 377== Download the Code ==
6f182760 378
73844f9c 379The plug-in is available [http://wiki.eclipse.org/images/3/34/Com.example.nexuslite.zip here] with a trace generator and a quick test case.
6f182760 380
3be48e26
BH
381== Optional Trace Type Attributes ==
382After defining the trace type as described in the previous chapters it is possible to define optional attributes for the trace type.
383
384=== Default Editor ===
385The attribute '''defaultEditor''' allows for configuring the editor to use for displaying the events. If omitted, the ''TmfEventsEditor'' is used as default. To configure an editor, first add the '''defaultEditor''' attribute to the trace type in the extension definition. This can be done by selecting the trace type in the plug-in manifest editor. Then click the right mouse button and select '''New -> defaultEditor''' in the context sensitive menu. Then select the newly added attribute. Now you can specify the editor id to use on the right side of the manifest editor. For example, this attribute could be used to implement an extension of the class ''org.eclipse.ui.part.MultiPageEditor''. The first page could use the ''TmfEventsEditor''' to display the events in a table as usual and other pages can display other aspects of the trace.
386
387=== Events Table Type ===
388The attribute '''eventsTableType''' allows for configuring the events table class to use in the default events editor. If omitted, the default events table will be used. To configure a trace type specific events table, first add the '''eventsTableType''' attribute to the trace type in the extension definition. This can be done by selecting the trace type in the plug-in manifest editor. Then click the right mouse button and select '''New -> eventsTableType''' in the context sensitive menu. Then select the newly added attribute and click on ''class'' on the right side of the manifest editor. The new class wizard will open. The ''superclass'' field will be already filled with the class ''org.eclipse.linuxtools.tmf.ui.viewers.events.TmfEventsTable''. Using this attribute a table with different columns than the default columns can be defined. See class org.eclipse.linuxtools.internal.lttng2.kernel.ui.viewers.events.Lttng2EventsTable for an example implementation.
389
390=== Statistics Viewer Type ===
391The attribute '''statisticsViewerType''' allows for defining trace type specific statistics. If omitted, only the default statistics will be displayed in the ''Statistics'' view (part of the ''Tracing'' view category). By default this view displays the total number of events and the number of events per event type for the whole trace and for the selected time range. To configure trace type specific statistics, first add the '''statisticsViewerType''' attribute to the trace type in the extension definition. This can be done by selecting the trace type in the plug-in manifest editor. Then click the right mouse button and select '''New -> statisticsViewerType''' in the context sensitive menu. Then select the newly added attribute and click on ''class'' on the right side of the manifest editor. The new class wizard will open. The ''superclass'' field will be already filled with the class ''org.eclipse.linuxtools.tmf.ui.viewers.statistics.TmfStatisticsViewer''. Now overwrite the relevant methods to provide the trace specific statistics. When executing the plug-in extension in Eclipse and opening the ''Statistics'' view the ''Statistics'' view will show an additional tab beside the global tab that shows the default statistics. The new tab will display the trace specific statistics provided in the ''TmfStatisticsViewer'' sub-class implementation.
392
73844f9c 393= View Tutorial =
6f182760 394
73844f9c 395This tutorial describes how to create a simple view using the TMF framework and the SWTChart library. SWTChart is a library based on SWT that can draw several types of charts including a line chart which we will use in this tutorial. We will create a view containing a line chart that displays time stamps on the X axis and the corresponding event values on the Y axis.
6f182760 396
73844f9c 397This tutorial will cover concepts like:
6f182760 398
73844f9c
PT
399* Extending TmfView
400* Signal handling (@TmfSignalHandler)
401* Data requests (TmfEventRequest)
402* SWTChart integration
6f182760 403
73844f9c 404=== Prerequisites ===
6f182760 405
73844f9c 406The tutorial is based on Eclipse 4.3 (Eclipse Kepler), TMF 2.0.0 and SWTChart 0.7.0. You can install SWTChart by using the Orbit update site. http://download.eclipse.org/tools/orbit/downloads/
6f182760 407
73844f9c 408=== Creating an Eclipse UI Plug-in ===
6f182760 409
73844f9c
PT
410To create a new project with name org.eclipse.linuxtools.tmf.sample.ui select '''File -> New -> Project -> Plug-in Development -> Plug-in Project'''. <br>
411[[Image:images/Screenshot-NewPlug-inProject1.png]]<br>
6f182760 412
73844f9c 413[[Image:images/Screenshot-NewPlug-inProject2.png]]<br>
6f182760 414
73844f9c 415[[Image:images/Screenshot-NewPlug-inProject3.png]]<br>
6f182760 416
73844f9c 417=== Creating a View ===
6f182760 418
73844f9c
PT
419To open the plug-in manifest, double-click on the MANIFEST.MF file. <br>
420[[Image:images/SelectManifest.png]]<br>
6f182760 421
73844f9c
PT
422Change to the Dependencies tab and select '''Add...''' of the ''Required Plug-ins'' section. A new dialog box will open. Next find plug-in ''org.eclipse.linuxtools.tmf.core'' and press '''OK'''<br>
423Following the same steps, add ''org.eclipse.linuxtools.tmf.ui'' and ''org.swtchart''.<br>
424[[Image:images/AddDependencyTmfUi.png]]<br>
6f182760 425
73844f9c
PT
426Change to the Extensions tab and select '''Add...''' of the ''All Extension'' section. A new dialog box will open. Find the view extension ''org.eclipse.ui.views'' and press '''Finish'''.<br>
427[[Image:images/AddViewExtension1.png]]<br>
6f182760 428
73844f9c
PT
429To create a view, click the right mouse button. Then select '''New -> view'''<br>
430[[Image:images/AddViewExtension2.png]]<br>
6f182760 431
73844f9c
PT
432A new view entry has been created. Fill in the fields ''id'' and ''name''. For ''class'' click on the '''class hyperlink''' and it will show the New Java Class dialog. Enter the name ''SampleView'', change the superclass to ''TmfView'' and click Finish. This will create the source file and fill the ''class'' field in the process. We use TmfView as the superclass because it provides extra functionality like getting the active trace, pinning and it has support for signal handling between components.<br>
433[[Image:images/FillSampleViewExtension.png]]<br>
6f182760 434
73844f9c 435This will generate an empty class. Once the quick fixes are applied, the following code is obtained:
6f182760 436
73844f9c
PT
437<pre>
438package org.eclipse.linuxtools.tmf.sample.ui;
6f182760 439
73844f9c
PT
440import org.eclipse.swt.widgets.Composite;
441import org.eclipse.ui.part.ViewPart;
6f182760 442
73844f9c 443public class SampleView extends TmfView {
6f182760 444
73844f9c
PT
445 public SampleView(String viewName) {
446 super(viewName);
447 // TODO Auto-generated constructor stub
448 }
6f182760 449
73844f9c
PT
450 @Override
451 public void createPartControl(Composite parent) {
452 // TODO Auto-generated method stub
6f182760 453
73844f9c 454 }
6f182760 455
73844f9c
PT
456 @Override
457 public void setFocus() {
458 // TODO Auto-generated method stub
6f182760 459
73844f9c 460 }
6f182760 461
73844f9c
PT
462}
463</pre>
6f182760 464
73844f9c 465This creates an empty view, however the basic structure is now is place.
6f182760 466
73844f9c 467=== Implementing a view ===
6f182760 468
73844f9c 469We will start by adding a empty chart then it will need to be populated with the trace data. Finally, we will make the chart more visually pleasing by adjusting the range and formating the time stamps.
6f182760 470
73844f9c 471==== Adding an Empty Chart ====
6f182760 472
73844f9c 473First, we can add an empty chart to the view and initialize some of its components.
6f182760 474
73844f9c
PT
475<pre>
476 private static final String SERIES_NAME = "Series";
477 private static final String Y_AXIS_TITLE = "Signal";
478 private static final String X_AXIS_TITLE = "Time";
479 private static final String FIELD = "value"; // The name of the field that we want to display on the Y axis
480 private static final String VIEW_ID = "org.eclipse.linuxtools.tmf.sample.ui.view";
481 private Chart chart;
482 private ITmfTrace currentTrace;
6f182760 483
73844f9c
PT
484 public SampleView() {
485 super(VIEW_ID);
486 }
6f182760 487
73844f9c
PT
488 @Override
489 public void createPartControl(Composite parent) {
490 chart = new Chart(parent, SWT.BORDER);
491 chart.getTitle().setVisible(false);
492 chart.getAxisSet().getXAxis(0).getTitle().setText(X_AXIS_TITLE);
493 chart.getAxisSet().getYAxis(0).getTitle().setText(Y_AXIS_TITLE);
494 chart.getSeriesSet().createSeries(SeriesType.LINE, SERIES_NAME);
495 chart.getLegend().setVisible(false);
496 }
6f182760 497
73844f9c
PT
498 @Override
499 public void setFocus() {
500 chart.setFocus();
501 }
502</pre>
6f182760 503
73844f9c
PT
504The view is prepared. Run the Example. To launch the an Eclipse Application select the ''Overview'' tab and click on '''Launch an Eclipse Application'''<br>
505[[Image:images/RunEclipseApplication.png]]<br>
6f182760 506
73844f9c
PT
507A new Eclipse application window will show. In the new window go to '''Windows -> Show View -> Other... -> Other -> Sample View'''.<br>
508[[Image:images/ShowViewOther.png]]<br>
6f182760 509
73844f9c
PT
510You should now see a view containing an empty chart<br>
511[[Image:images/EmptySampleView.png]]<br>
6f182760 512
73844f9c 513==== Signal Handling ====
6f182760 514
73844f9c 515We would like to populate the view when a trace is selected. To achieve this, we can use a signal hander which is specified with the '''@TmfSignalHandler''' annotation.
6f182760 516
73844f9c
PT
517<pre>
518 @TmfSignalHandler
519 public void traceSelected(final TmfTraceSelectedSignal signal) {
6f182760 520
73844f9c
PT
521 }
522</pre>
067490ab 523
73844f9c 524==== Requesting Data ====
067490ab 525
73844f9c 526Then we need to actually gather data from the trace. This is done asynchronously using a ''TmfEventRequest''
067490ab 527
73844f9c
PT
528<pre>
529 @TmfSignalHandler
530 public void traceSelected(final TmfTraceSelectedSignal signal) {
531 // Don't populate the view again if we're already showing this trace
532 if (currentTrace == signal.getTrace()) {
533 return;
534 }
535 currentTrace = signal.getTrace();
067490ab 536
73844f9c 537 // Create the request to get data from the trace
067490ab 538
73844f9c
PT
539 TmfEventRequest req = new TmfEventRequest(TmfEvent.class,
540 TmfTimeRange.ETERNITY, TmfEventRequest.ALL_DATA,
541 ExecutionType.BACKGROUND) {
067490ab 542
73844f9c
PT
543 @Override
544 public void handleData(ITmfEvent data) {
545 // Called for each event
546 super.handleData(data);
547 }
067490ab 548
73844f9c
PT
549 @Override
550 public void handleSuccess() {
551 // Request successful, not more data available
552 super.handleSuccess();
553 }
554
555 @Override
556 public void handleFailure() {
557 // Request failed, not more data available
558 super.handleFailure();
559 }
560 };
561 ITmfTrace trace = signal.getTrace();
562 trace.sendRequest(req);
563 }
067490ab
AM
564</pre>
565
73844f9c 566==== Transferring Data to the Chart ====
067490ab 567
73844f9c 568The chart expects an array of doubles for both the X and Y axis values. To provide that, we can accumulate each event's time and value in their respective list then convert the list to arrays when all events are processed.
067490ab 569
73844f9c
PT
570<pre>
571 TmfEventRequest req = new TmfEventRequest(TmfEvent.class,
572 TmfTimeRange.ETERNITY, TmfEventRequest.ALL_DATA,
573 ExecutionType.BACKGROUND) {
067490ab 574
73844f9c
PT
575 ArrayList<Double> xValues = new ArrayList<Double>();
576 ArrayList<Double> yValues = new ArrayList<Double>();
067490ab 577
73844f9c
PT
578 @Override
579 public void handleData(ITmfEvent data) {
580 // Called for each event
581 super.handleData(data);
582 ITmfEventField field = data.getContent().getField(FIELD);
583 if (field != null) {
584 yValues.add((Double) field.getValue());
585 xValues.add((double) data.getTimestamp().getValue());
586 }
587 }
067490ab 588
73844f9c
PT
589 @Override
590 public void handleSuccess() {
591 // Request successful, not more data available
592 super.handleSuccess();
067490ab 593
73844f9c
PT
594 final double x[] = toArray(xValues);
595 final double y[] = toArray(yValues);
067490ab 596
73844f9c
PT
597 // This part needs to run on the UI thread since it updates the chart SWT control
598 Display.getDefault().asyncExec(new Runnable() {
067490ab 599
73844f9c
PT
600 @Override
601 public void run() {
602 chart.getSeriesSet().getSeries()[0].setXSeries(x);
603 chart.getSeriesSet().getSeries()[0].setYSeries(y);
067490ab 604
73844f9c
PT
605 chart.redraw();
606 }
067490ab 607
73844f9c
PT
608 });
609 }
067490ab 610
73844f9c
PT
611 /**
612 * Convert List<Double> to double[]
613 */
614 private double[] toArray(List<Double> list) {
615 double[] d = new double[list.size()];
616 for (int i = 0; i < list.size(); ++i) {
617 d[i] = list.get(i);
618 }
067490ab 619
73844f9c
PT
620 return d;
621 }
622 };
623</pre>
067490ab 624
73844f9c 625==== Adjusting the Range ====
067490ab 626
73844f9c 627The chart now contains values but they might be out of range and not visible. We can adjust the range of each axis by computing the minimum and maximum values as we add events.
067490ab 628
73844f9c 629<pre>
067490ab 630
73844f9c
PT
631 ArrayList<Double> xValues = new ArrayList<Double>();
632 ArrayList<Double> yValues = new ArrayList<Double>();
633 private double maxY = -Double.MAX_VALUE;
634 private double minY = Double.MAX_VALUE;
635 private double maxX = -Double.MAX_VALUE;
636 private double minX = Double.MAX_VALUE;
067490ab 637
73844f9c
PT
638 @Override
639 public void handleData(ITmfEvent data) {
640 super.handleData(data);
641 ITmfEventField field = data.getContent().getField(FIELD);
642 if (field != null) {
643 Double yValue = (Double) field.getValue();
644 minY = Math.min(minY, yValue);
645 maxY = Math.max(maxY, yValue);
646 yValues.add(yValue);
067490ab 647
73844f9c
PT
648 double xValue = (double) data.getTimestamp().getValue();
649 xValues.add(xValue);
650 minX = Math.min(minX, xValue);
651 maxX = Math.max(maxX, xValue);
652 }
653 }
067490ab 654
73844f9c
PT
655 @Override
656 public void handleSuccess() {
657 super.handleSuccess();
658 final double x[] = toArray(xValues);
659 final double y[] = toArray(yValues);
067490ab 660
73844f9c
PT
661 // This part needs to run on the UI thread since it updates the chart SWT control
662 Display.getDefault().asyncExec(new Runnable() {
067490ab 663
73844f9c
PT
664 @Override
665 public void run() {
666 chart.getSeriesSet().getSeries()[0].setXSeries(x);
667 chart.getSeriesSet().getSeries()[0].setYSeries(y);
067490ab 668
73844f9c
PT
669 // Set the new range
670 if (!xValues.isEmpty() && !yValues.isEmpty()) {
671 chart.getAxisSet().getXAxis(0).setRange(new Range(0, x[x.length - 1]));
672 chart.getAxisSet().getYAxis(0).setRange(new Range(minY, maxY));
673 } else {
674 chart.getAxisSet().getXAxis(0).setRange(new Range(0, 1));
675 chart.getAxisSet().getYAxis(0).setRange(new Range(0, 1));
676 }
677 chart.getAxisSet().adjustRange();
067490ab 678
73844f9c
PT
679 chart.redraw();
680 }
681 });
682 }
683</pre>
067490ab 684
73844f9c 685==== Formatting the Time Stamps ====
067490ab 686
73844f9c 687To display the time stamps on the X axis nicely, we need to specify a format or else the time stamps will be displayed as ''long''. We use TmfTimestampFormat to make it consistent with the other TMF views. We also need to handle the '''TmfTimestampFormatUpdateSignal''' to make sure that the time stamps update when the preferences change.
067490ab 688
73844f9c
PT
689<pre>
690 @Override
691 public void createPartControl(Composite parent) {
692 ...
067490ab 693
73844f9c
PT
694 chart.getAxisSet().getXAxis(0).getTick().setFormat(new TmfChartTimeStampFormat());
695 }
067490ab 696
73844f9c
PT
697 public class TmfChartTimeStampFormat extends SimpleDateFormat {
698 private static final long serialVersionUID = 1L;
699 @Override
700 public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
701 long time = date.getTime();
702 toAppendTo.append(TmfTimestampFormat.getDefaulTimeFormat().format(time));
703 return toAppendTo;
704 }
705 }
067490ab 706
73844f9c
PT
707 @TmfSignalHandler
708 public void timestampFormatUpdated(TmfTimestampFormatUpdateSignal signal) {
709 // Called when the time stamp preference is changed
710 chart.getAxisSet().getXAxis(0).getTick().setFormat(new TmfChartTimeStampFormat());
711 chart.redraw();
712 }
713</pre>
067490ab 714
73844f9c 715We also need to populate the view when a trace is already selected and the view is opened. We can reuse the same code by having the view send the '''TmfTraceSelectedSignal''' to itself.
067490ab 716
73844f9c
PT
717<pre>
718 @Override
719 public void createPartControl(Composite parent) {
720 ...
067490ab 721
73844f9c
PT
722 ITmfTrace trace = getActiveTrace();
723 if (trace != null) {
724 traceSelected(new TmfTraceSelectedSignal(this, trace));
725 }
726 }
727</pre>
067490ab 728
73844f9c 729The view is now ready but we need a proper trace to test it. For this example, a trace was generated using LTTng-UST so that it would produce a sine function.<br>
067490ab 730
73844f9c 731[[Image:images/SampleView.png]]<br>
067490ab 732
73844f9c 733In summary, we have implemented a simple TMF view using the SWTChart library. We made use of signals and requests to populate the view at the appropriate time and we formated the time stamps nicely. We also made sure that the time stamp format is updated when the preferences change.
067490ab 734
73844f9c 735= Component Interaction =
067490ab 736
73844f9c 737TMF provides a mechanism for different components to interact with each other using signals. The signals can carry information that is specific to each signal.
067490ab 738
73844f9c 739The TMF Signal Manager handles registration of components and the broadcasting of signals to their intended receivers.
067490ab 740
73844f9c 741Components can register as VIP receivers which will ensure they will receive the signal before non-VIP receivers.
067490ab 742
73844f9c 743== Sending Signals ==
067490ab 744
73844f9c 745In order to send a signal, an instance of the signal must be created and passed as argument to the signal manager to be dispatched. Every component that can handle the signal will receive it. The receivers do not need to be known by the sender.
067490ab 746
73844f9c
PT
747<pre>
748TmfExampleSignal signal = new TmfExampleSignal(this, ...);
749TmfSignalManager.dispatchSignal(signal);
750</pre>
067490ab 751
73844f9c 752If the sender is an instance of the class TmfComponent, the broadcast method can be used:
067490ab
AM
753
754<pre>
73844f9c
PT
755TmfExampleSignal signal = new TmfExampleSignal(this, ...);
756broadcast(signal);
757</pre>
067490ab 758
73844f9c 759== Receiving Signals ==
067490ab 760
73844f9c 761In order to receive any signal, the receiver must first be registered with the signal manager. The receiver can register as a normal or VIP receiver.
067490ab 762
73844f9c
PT
763<pre>
764TmfSignalManager.register(this);
765TmfSignalManager.registerVIP(this);
766</pre>
067490ab 767
73844f9c 768If the receiver is an instance of the class TmfComponent, it is automatically registered as a normal receiver in the constructor.
067490ab 769
73844f9c 770When the receiver is destroyed or disposed, it should deregister itself from the signal manager.
067490ab 771
73844f9c
PT
772<pre>
773TmfSignalManager.deregister(this);
774</pre>
067490ab 775
73844f9c 776To actually receive and handle any specific signal, the receiver must use the @TmfSignalHandler annotation and implement a method that will be called when the signal is broadcast. The name of the method is irrelevant.
067490ab 777
73844f9c
PT
778<pre>
779@TmfSignalHandler
780public void example(TmfExampleSignal signal) {
781 ...
782}
067490ab
AM
783</pre>
784
73844f9c 785The source of the signal can be used, if necessary, by a component to filter out and ignore a signal that was broadcast by itself when the component is also a receiver of the signal but only needs to handle it when it was sent by another component or another instance of the component.
067490ab 786
73844f9c
PT
787== Signal Throttling ==
788
789It is possible for a TmfComponent instance to buffer the dispatching of signals so that only the last signal queued after a specified delay without any other signal queued is sent to the receivers. All signals that are preempted by a newer signal within the delay are discarded.
790
791The signal throttler must first be initialized:
067490ab
AM
792
793<pre>
73844f9c
PT
794final int delay = 100; // in ms
795TmfSignalThrottler throttler = new TmfSignalThrottler(this, delay);
796</pre>
067490ab 797
73844f9c 798Then the sending of signals should be queued through the throttler:
067490ab 799
73844f9c
PT
800<pre>
801TmfExampleSignal signal = new TmfExampleSignal(this, ...);
802throttler.queue(signal);
803</pre>
067490ab 804
73844f9c 805When the throttler is no longer needed, it should be disposed:
067490ab 806
73844f9c
PT
807<pre>
808throttler.dispose();
809</pre>
067490ab 810
73844f9c 811== Signal Reference ==
067490ab 812
73844f9c 813The following is a list of built-in signals defined in the framework.
067490ab 814
73844f9c 815=== TmfStartSynchSignal ===
067490ab 816
73844f9c 817''Purpose''
067490ab 818
73844f9c 819This signal is used to indicate the start of broadcasting of a signal. Internally, the data provider will not fire event requests until the corresponding TmfEndSynchSignal signal is received. This allows coalescing of requests triggered by multiple receivers of the broadcast signal.
067490ab 820
73844f9c 821''Senders''
067490ab 822
73844f9c 823Sent by TmfSignalManager before dispatching a signal to all receivers.
067490ab 824
73844f9c 825''Receivers''
067490ab 826
73844f9c 827Received by TmfDataProvider.
067490ab 828
73844f9c 829=== TmfEndSynchSignal ===
067490ab 830
73844f9c 831''Purpose''
067490ab 832
73844f9c 833This signal is used to indicate the end of broadcasting of a signal. Internally, the data provider fire all pending event requests that were received and buffered since the corresponding TmfStartSynchSignal signal was received. This allows coalescing of requests triggered by multiple receivers of the broadcast signal.
067490ab 834
73844f9c 835''Senders''
067490ab 836
73844f9c 837Sent by TmfSignalManager after dispatching a signal to all receivers.
067490ab 838
73844f9c 839''Receivers''
067490ab 840
73844f9c 841Received by TmfDataProvider.
067490ab 842
73844f9c 843=== TmfTraceOpenedSignal ===
067490ab 844
73844f9c 845''Purpose''
067490ab 846
73844f9c 847This signal is used to indicate that a trace has been opened in an editor.
067490ab 848
73844f9c 849''Senders''
067490ab 850
73844f9c 851Sent by a TmfEventsEditor instance when it is created.
067490ab 852
73844f9c 853''Receivers''
067490ab 854
73844f9c 855Received by TmfTrace, TmfExperiment, TmfTraceManager and every view that shows trace data. Components that show trace data should handle this signal.
067490ab 856
73844f9c 857=== TmfTraceSelectedSignal ===
067490ab 858
73844f9c 859''Purpose''
067490ab 860
73844f9c 861This signal is used to indicate that a trace has become the currently selected trace.
067490ab 862
73844f9c 863''Senders''
067490ab 864
73844f9c 865Sent by a TmfEventsEditor instance when it receives focus. Components can send this signal to make a trace editor be brought to front.
067490ab 866
73844f9c 867''Receivers''
067490ab 868
73844f9c 869Received by TmfTraceManager and every view that shows trace data. Components that show trace data should handle this signal.
067490ab 870
73844f9c 871=== TmfTraceClosedSignal ===
067490ab 872
73844f9c 873''Purpose''
067490ab 874
73844f9c 875This signal is used to indicate that a trace editor has been closed.
067490ab 876
73844f9c 877''Senders''
067490ab 878
73844f9c 879Sent by a TmfEventsEditor instance when it is disposed.
067490ab 880
73844f9c 881''Receivers''
067490ab 882
73844f9c 883Received by TmfTraceManager and every view that shows trace data. Components that show trace data should handle this signal.
067490ab 884
73844f9c 885=== TmfTraceRangeUpdatedSignal ===
067490ab 886
73844f9c 887''Purpose''
067490ab 888
73844f9c 889This signal is used to indicate that the valid time range of a trace has been updated. This triggers indexing of the trace up to the end of the range. In the context of streaming, this end time is considered a safe time up to which all events are guaranteed to have been completely received. For non-streaming traces, the end time is set to infinity indicating that all events can be read immediately. Any processing of trace events that wants to take advantage of request coalescing should be triggered by this signal.
067490ab 890
73844f9c 891''Senders''
11252342 892
73844f9c 893Sent by TmfExperiment and non-streaming TmfTrace. Streaming traces should send this signal in the TmfTrace subclass when a new safe time is determined by a specific implementation.
067490ab 894
73844f9c 895''Receivers''
067490ab 896
73844f9c 897Received by TmfTrace, TmfExperiment and components that process trace events. Components that need to process trace events should handle this signal.
067490ab 898
73844f9c 899=== TmfTraceUpdatedSignal ===
067490ab 900
73844f9c 901''Purpose''
067490ab 902
73844f9c 903This signal is used to indicate that new events have been indexed for a trace.
067490ab 904
73844f9c 905''Senders''
067490ab 906
73844f9c 907Sent by TmfCheckpointIndexer when new events have been indexed and the number of events has changed.
067490ab 908
73844f9c 909''Receivers''
067490ab 910
73844f9c 911Received by components that need to be notified of a new trace event count.
067490ab 912
73844f9c 913=== TmfTimeSynchSignal ===
067490ab 914
73844f9c 915''Purpose''
067490ab 916
73844f9c 917This signal is used to indicate that a new time has been selected.
067490ab 918
73844f9c 919''Senders''
067490ab 920
73844f9c 921Sent by any component that allows the user to select a time.
067490ab 922
73844f9c 923''Receivers''
067490ab 924
73844f9c 925Received by any component that needs to be notified of the currently selected time.
067490ab 926
73844f9c 927=== TmfRangeSynchSignal ===
067490ab 928
73844f9c 929''Purpose''
067490ab 930
73844f9c 931This signal is used to indicate that a new time range window has been set.
067490ab 932
73844f9c 933''Senders''
067490ab 934
73844f9c 935Sent by any component that allows the user to set a time range window.
067490ab 936
73844f9c 937''Receivers''
067490ab 938
73844f9c 939Received by any component that needs to be notified of the current visible time range window.
067490ab 940
73844f9c 941=== TmfEventFilterAppliedSignal ===
067490ab 942
73844f9c 943''Purpose''
067490ab 944
73844f9c 945This signal is used to indicate that a filter has been applied to a trace.
067490ab 946
73844f9c 947''Senders''
067490ab 948
73844f9c 949Sent by TmfEventsTable when a filter is applied.
067490ab 950
73844f9c 951''Receivers''
067490ab 952
73844f9c 953Received by any component that shows trace data and needs to be notified of applied filters.
067490ab 954
73844f9c 955=== TmfEventSearchAppliedSignal ===
067490ab 956
73844f9c 957''Purpose''
067490ab 958
73844f9c 959This signal is used to indicate that a search has been applied to a trace.
067490ab 960
73844f9c 961''Senders''
067490ab 962
73844f9c 963Sent by TmfEventsTable when a search is applied.
067490ab 964
73844f9c 965''Receivers''
067490ab 966
73844f9c 967Received by any component that shows trace data and needs to be notified of applied searches.
067490ab 968
73844f9c 969=== TmfTimestampFormatUpdateSignal ===
067490ab 970
73844f9c 971''Purpose''
067490ab 972
73844f9c 973This signal is used to indicate that the timestamp format preference has been updated.
067490ab 974
73844f9c 975''Senders''
067490ab 976
73844f9c 977Sent by TmfTimestampFormat when the default timestamp format preference is changed.
067490ab 978
73844f9c 979''Receivers''
067490ab 980
73844f9c 981Received by any component that needs to refresh its display for the new timestamp format.
067490ab 982
73844f9c 983=== TmfStatsUpdatedSignal ===
067490ab 984
73844f9c 985''Purpose''
067490ab 986
73844f9c 987This signal is used to indicate that the statistics data model has been updated.
067490ab 988
73844f9c 989''Senders''
067490ab 990
73844f9c 991Sent by statistic providers when new statistics data has been processed.
067490ab 992
73844f9c 993''Receivers''
067490ab 994
73844f9c 995Received by statistics viewers and any component that needs to be notified of a statistics update.
067490ab 996
73844f9c 997== Debugging ==
067490ab 998
73844f9c 999TMF has built-in Eclipse tracing support for the debugging of signal interaction between components. To enable it, open the '''Run/Debug Configuration...''' dialog, select a configuration, click the '''Tracing''' tab, select the plug-in '''org.eclipse.linuxtools.tmf.core''', and check the '''signal''' item.
067490ab 1000
73844f9c 1001All signals sent and received will be logged to the file TmfTrace.log located in the Eclipse home directory.
067490ab 1002
73844f9c 1003= Generic State System =
067490ab 1004
73844f9c 1005== Introduction ==
067490ab 1006
73844f9c
PT
1007The Generic State System is a utility available in TMF to track different states
1008over the duration of a trace. It works by first sending some or all events of
1009the trace into a state provider, which defines the state changes for a given
1010trace type. Once built, views and analysis modules can then query the resulting
1011database of states (called "state history") to get information.
067490ab 1012
73844f9c
PT
1013For example, let's suppose we have the following sequence of events in a kernel
1014trace:
067490ab 1015
73844f9c
PT
1016 10 s, sys_open, fd = 5, file = /home/user/myfile
1017 ...
1018 15 s, sys_read, fd = 5, size=32
1019 ...
1020 20 s, sys_close, fd = 5
067490ab 1021
73844f9c
PT
1022Now let's say we want to implement an analysis module which will track the
1023amount of bytes read and written to eachfile. Here, of course the sys_read is
1024interesting. However, by just looking at that event, we have no information on
1025which file is being read, only its fd (5) is known. To get the match
1026fd5 = /home/user/myfile, we have to go back to the sys_open event which happens
10275 seconds earlier.
067490ab 1028
73844f9c
PT
1029But since we don't know exactly where this sys_open event is, we will have to go
1030back to the very start of the trace, and look through events one by one! This is
1031obviously not efficient, and will not scale well if we want to analyze many
1032similar patterns, or for very large traces.
067490ab 1033
73844f9c
PT
1034A solution in this case would be to use the state system to keep track of the
1035amount of bytes read/written to every *filename* (instead of every file
1036descriptor, like we get from the events). Then the module could ask the state
1037system "what is the amount of bytes read for file "/home/user/myfile" at time
103816 s", and it would return the answer "32" (assuming there is no other read
1039than the one shown).
067490ab 1040
73844f9c 1041== High-level components ==
067490ab 1042
73844f9c
PT
1043The State System infrastructure is composed of 3 parts:
1044* The state provider
1045* The central state system
1046* The storage backend
067490ab 1047
73844f9c
PT
1048The state provider is the customizable part. This is where the mapping from
1049trace events to state changes is done. This is what you want to implement for
1050your specific trace type and analysis type. It's represented by the
1051ITmfStateProvider interface (with a threaded implementation in
1052AbstractTmfStateProvider, which you can extend).
067490ab 1053
73844f9c
PT
1054The core of the state system is exposed through the ITmfStateSystem and
1055ITmfStateSystemBuilder interfaces. The former allows only read-only access and
1056is typically used for views doing queries. The latter also allows writing to the
1057state history, and is typically used by the state provider.
067490ab 1058
73844f9c
PT
1059Finally, each state system has its own separate backend. This determines how the
1060intervals, or the "state history", are saved (in RAM, on disk, etc.) You can
1061select the type of backend at construction time in the TmfStateSystemFactory.
067490ab 1062
73844f9c 1063== Definitions ==
067490ab 1064
73844f9c
PT
1065Before we dig into how to use the state system, we should go over some useful
1066definitions:
067490ab 1067
73844f9c 1068=== Attribute ===
067490ab 1069
73844f9c
PT
1070An attribute is the smallest element of the model that can be in any particular
1071state. When we refer to the "full state", in fact it means we are interested in
1072the state of every single attribute of the model.
067490ab 1073
73844f9c 1074=== Attribute Tree ===
067490ab 1075
73844f9c
PT
1076Attributes in the model can be placed in a tree-like structure, a bit like files
1077and directories in a file system. However, note that an attribute can always
1078have both a value and sub-attributes, so they are like files and directories at
1079the same time. We are then able to refer to every single attribute with its
1080path in the tree.
067490ab 1081
73844f9c
PT
1082For example, in the attribute tree for LTTng kernel traces, we use the following
1083attributes, among others:
067490ab 1084
73844f9c
PT
1085<pre>
1086|- Processes
1087| |- 1000
1088| | |- PPID
1089| | |- Exec_name
1090| |- 1001
1091| | |- PPID
1092| | |- Exec_name
1093| ...
1094|- CPUs
1095 |- 0
1096 | |- Status
1097 | |- Current_pid
1098 ...
1099</pre>
067490ab 1100
73844f9c
PT
1101In this model, the attribute "Processes/1000/PPID" refers to the PPID of process
1102with PID 1000. The attribute "CPUs/0/Status" represents the status (running,
1103idle, etc.) of CPU 0. "Processes/1000/PPID" and "Processes/1001/PPID" are two
1104different attribute, even though their base name is the same: the whole path is
1105the unique identifier.
067490ab 1106
73844f9c
PT
1107The value of each attribute can change over the duration of the trace,
1108independently of the other ones, and independently of its position in the tree.
067490ab 1109
73844f9c
PT
1110The tree-like organization is optional, all attributes could be at the same
1111level. But it's possible to put them in a tree, and it helps make things
1112clearer.
067490ab 1113
73844f9c 1114=== Quark ===
067490ab 1115
73844f9c
PT
1116In addition to a given path, each attribute also has a unique integer
1117identifier, called the "quark". To continue with the file system analogy, this
1118is like the inode number. When a new attribute is created, a new unique quark
1119will be assigned automatically. They are assigned incrementally, so they will
1120normally be equal to their order of creation, starting at 0.
067490ab 1121
73844f9c
PT
1122Methods are offered to get the quark of an attribute from its path. The API
1123methods for inserting state changes and doing queries normally use quarks
1124instead of paths. This is to encourage users to cache the quarks and re-use
1125them, which avoids re-walking the attribute tree over and over, which avoids
1126unneeded hashing of strings.
067490ab 1127
73844f9c 1128=== State value ===
067490ab 1129
73844f9c
PT
1130The path and quark of an attribute will remain constant for the whole duration
1131of the trace. However, the value carried by the attribute will change. The value
1132of a specific attribute at a specific time is called the state value.
067490ab 1133
73844f9c
PT
1134In the TMF implementation, state values can be integers, longs, or strings.
1135There is also a "null value" type, which is used to indicate that no particular
1136value is active for this attribute at this time, but without resorting to a
1137'null' reference.
067490ab 1138
73844f9c
PT
1139Any other type of value could be used, as long as the backend knows how to store
1140it.
067490ab 1141
73844f9c
PT
1142Note that the TMF implementation also forces every attribute to always carry the
1143same type of state value. This is to make it simpler for views, so they can
1144expect that an attribute will always use a given type, without having to check
1145every single time. Null values are an exception, they are always allowed for all
1146attributes, since they can safely be "unboxed" into all types.
067490ab 1147
73844f9c 1148=== State change ===
067490ab 1149
73844f9c
PT
1150A state change is the element that is inserted in the state system. It consists
1151of:
1152* a timestamp (the time at which the state change occurs)
1153* an attribute (the attribute whose value will change)
1154* a state value (the new value that the attribute will carry)
067490ab 1155
73844f9c
PT
1156It's not an object per se in the TMF implementation (it's represented by a
1157function call in the state provider). Typically, the state provider will insert
1158zero, one or more state changes for every trace event, depending on its event
1159type, payload, etc.
067490ab 1160
73844f9c
PT
1161Note, we use "timestamp" here, but it's in fact a generic term that could be
1162referred to as "index". For example, if a given trace type has no notion of
1163timestamp, the event rank could be used.
067490ab 1164
73844f9c 1165In the TMF implementation, the timestamp is a long (64-bit integer).
067490ab 1166
73844f9c 1167=== State interval ===
067490ab 1168
73844f9c
PT
1169State changes are inserted into the state system, but state intervals are the
1170objects that come out on the other side. Those are stocked in the storage
1171backend. A state interval represents a "state" of an attribute we want to track.
1172When doing queries on the state system, intervals are what is returned. The
1173components of a state interval are:
1174* Start time
1175* End time
1176* State value
1177* Quark
067490ab 1178
73844f9c
PT
1179The start and end times represent the time range of the state. The state value
1180is the same as the state value in the state change that started this interval.
1181The interval also keeps a reference to its quark, although you normally know
1182your quark in advance when you do queries.
f5b8868d 1183
73844f9c 1184=== State history ===
f5b8868d 1185
73844f9c
PT
1186The state history is the name of the container for all the intervals created by
1187the state system. The exact implementation (how the intervals are stored) is
1188determined by the storage backend that is used.
f5b8868d 1189
73844f9c
PT
1190Some backends will use a state history that is peristent on disk, others do not.
1191When loading a trace, if a history file is available and the backend supports
1192it, it will be loaded right away, skipping the need to go through another
1193construction phase.
f5b8868d 1194
73844f9c 1195=== Construction phase ===
f5b8868d 1196
73844f9c
PT
1197Before we can query a state system, we need to build the state history first. To
1198do so, trace events are sent one-by-one through the state provider, which in
1199turn sends state changes to the central component, which then creates intervals
1200and stores them in the backend. This is called the construction phase.
f5b8868d 1201
73844f9c
PT
1202Note that the state system needs to receive its events into chronological order.
1203This phase will end once the end of the trace is reached.
f5b8868d 1204
73844f9c
PT
1205Also note that it is possible to query the state system while it is being build.
1206Any timestamp between the start of the trace and the current end time of the
1207state system (available with ITmfStateSystem#getCurrentEndTime()) is a valid
1208timestamp that can be queried.
f5b8868d 1209
73844f9c 1210=== Queries ===
f5b8868d 1211
73844f9c
PT
1212As mentioned previously, when doing queries on the state system, the returned
1213objects will be state intervals. In most cases it's the state *value* we are
1214interested in, but since the backend has to instantiate the interval object
1215anyway, there is no additional cost to return the interval instead. This way we
1216also get the start and end times of the state "for free".
f5b8868d 1217
73844f9c 1218There are two types of queries that can be done on the state system:
f5b8868d 1219
73844f9c 1220==== Full queries ====
f5b8868d 1221
73844f9c
PT
1222A full query means that we want to retrieve the whole state of the model for one
1223given timestamp. As we remember, this means "the state of every single attribute
1224in the model". As parameter we only need to pass the timestamp (see the API
1225methods below). The return value will be an array of intervals, where the offset
1226in the array represents the quark of each attribute.
f5b8868d 1227
73844f9c 1228==== Single queries ====
f5b8868d 1229
73844f9c
PT
1230In other cases, we might only be interested in the state of one particular
1231attribute at one given timestamp. For these cases it's better to use a
1232single query. For a single query. we need to pass both a timestamp and a
1233quark in parameter. The return value will be a single interval, representing
1234the state that this particular attribute was at that time.
f5b8868d 1235
73844f9c
PT
1236Single queries are typically faster than full queries (but once again, this
1237depends on the backend that is used), but not by much. Even if you only want the
1238state of say 10 attributes out of 200, it could be faster to use a full query
1239and only read the ones you need. Single queries should be used for cases where
1240you only want one attribute per timestamp (for example, if you follow the state
1241of the same attribute over a time range).
f5b8868d 1242
f5b8868d 1243
73844f9c 1244== Relevant interfaces/classes ==
f5b8868d 1245
73844f9c
PT
1246This section will describe the public interface and classes that can be used if
1247you want to use the state system.
f5b8868d 1248
73844f9c 1249=== Main classes in org.eclipse.linuxtools.tmf.core.statesystem ===
f5b8868d 1250
73844f9c 1251==== ITmfStateProvider / AbstractTmfStateProvider ====
f5b8868d 1252
73844f9c
PT
1253ITmfStateProvider is the interface you have to implement to define your state
1254provider. This is where most of the work has to be done to use a state system
1255for a custom trace type or analysis type.
f5b8868d 1256
73844f9c
PT
1257For first-time users, it's recommended to extend AbstractTmfStateProvider
1258instead. This class takes care of all the initialization mumbo-jumbo, and also
1259runs the event handler in a separate thread. You will only need to implement
1260eventHandle, which is the call-back that will be called for every event in the
1261trace.
f5b8868d 1262
73844f9c
PT
1263For an example, you can look at StatsStateProvider in the TMF tree, or at the
1264small example below.
f5b8868d 1265
73844f9c 1266==== TmfStateSystemFactory ====
f5b8868d 1267
73844f9c
PT
1268Once you have defined your state provider, you need to tell your trace type to
1269build a state system with this provider during its initialization. This consists
1270of overriding TmfTrace#buildStateSystems() and in there of calling the method in
1271TmfStateSystemFactory that corresponds to the storage backend you want to use
1272(see the section [[#Comparison of state system backends]]).
f5b8868d 1273
73844f9c
PT
1274You will have to pass in parameter the state provider you want to use, which you
1275should have defined already. Each backend can also ask for more configuration
1276information.
f5b8868d 1277
73844f9c
PT
1278You must then call registerStateSystem(id, statesystem) to make your state
1279system visible to the trace objects and the views. The ID can be any string of
1280your choosing. To access this particular state system, the views or modules will
1281need to use this ID.
f5b8868d 1282
73844f9c
PT
1283Also, don't forget to call super.buildStateSystems() in your implementation,
1284unless you know for sure you want to skip the state providers built by the
1285super-classes.
f5b8868d 1286
73844f9c
PT
1287You can look at how LttngKernelTrace does it for an example. It could also be
1288possible to build a state system only under certain conditions (like only if the
1289trace contains certain event types).
f5b8868d 1290
f5b8868d 1291
73844f9c 1292==== ITmfStateSystem ====
f5b8868d 1293
73844f9c
PT
1294ITmfStateSystem is the main interface through which views or analysis modules
1295will access the state system. It offers a read-only view of the state system,
1296which means that no states can be inserted, and no attributes can be created.
1297Calling TmfTrace#getStateSystems().get(id) will return you a ITmfStateSystem
1298view of the requested state system. The main methods of interest are:
f5b8868d 1299
73844f9c 1300===== getQuarkAbsolute()/getQuarkRelative() =====
f5b8868d 1301
73844f9c
PT
1302Those are the basic quark-getting methods. The goal of the state system is to
1303return the state values of given attributes at given timestamps. As we've seen
1304earlier, attributes can be described with a file-system-like path. The goal of
1305these methods is to convert from the path representation of the attribute to its
1306quark.
f5b8868d 1307
73844f9c
PT
1308Since quarks are created on-the-fly, there is no guarantee that the same
1309attributes will have the same quark for two traces of the same type. The views
1310should always query their quarks when dealing with a new trace or a new state
1311provider. Beyond that however, quarks should be cached and reused as much as
1312possible, to avoid potentially costly string re-hashing.
f5b8868d 1313
73844f9c
PT
1314getQuarkAbsolute() takes a variable amount of Strings in parameter, which
1315represent the full path to the attribute. Some of them can be constants, some
1316can come programatically, often from the event's fields.
f5b8868d 1317
73844f9c
PT
1318getQuarkRelative() is to be used when you already know the quark of a certain
1319attribute, and want to access on of its sub-attributes. Its first parameter is
1320the origin quark, followed by a String varagrs which represent the relative path
1321to the final attribute.
f5b8868d 1322
73844f9c
PT
1323These two methods will throw an AttributeNotFoundException if trying to access
1324an attribute that does not exist in the model.
f5b8868d 1325
73844f9c
PT
1326These methods also imply that the view has the knowledge of how the attribute
1327tree is organized. This should be a reasonable hypothesis, since the same
1328analysis plugin will normally ship both the state provider and the view, and
1329they will have been written by the same person. In other cases, it's possible to
1330use getSubAttributes() to explore the organization of the attribute tree first.
f5b8868d 1331
73844f9c 1332===== waitUntilBuilt() =====
f5b8868d 1333
73844f9c
PT
1334This is a simple method used to block the caller until the construction phase of
1335this state system is done. If the view prefers to wait until all information is
1336available before starting to do queries (to get all known attributes right away,
1337for example), this is the guy to call.
f5b8868d 1338
73844f9c 1339===== queryFullState() =====
f5b8868d 1340
73844f9c
PT
1341This is the method to do full queries. As mentioned earlier, you only need to
1342pass a target timestamp in parameter. It will return a List of state intervals,
1343in which the offset corresponds to the attribute quark. This will represent the
1344complete state of the model at the requested time.
f5b8868d 1345
73844f9c 1346===== querySingleState() =====
f5b8868d 1347
73844f9c
PT
1348The method to do single queries. You pass in parameter both a timestamp and an
1349attribute quark. This will return the single state matching this
1350timestamp/attribute pair.
f5b8868d 1351
73844f9c
PT
1352Other methods are available, you are encouraged to read their Javadoc and see if
1353they can be potentially useful.
f5b8868d 1354
73844f9c 1355==== ITmfStateSystemBuilder ====
f5b8868d 1356
73844f9c
PT
1357ITmfStateSystemBuilder is the read-write interface to the state system. It
1358extends ITmfStateSystem itself, so all its methods are available. It then adds
1359methods that can be used to write to the state system, either by creating new
1360attributes of inserting state changes.
f5b8868d 1361
73844f9c
PT
1362It is normally reserved for the state provider and should not be visible to
1363external components. However it will be available in AbstractTmfStateProvider,
1364in the field 'ss'. That way you can call ss.modifyAttribute() etc. in your state
1365provider to write to the state.
f5b8868d 1366
73844f9c 1367The main methods of interest are:
f5b8868d 1368
73844f9c 1369===== getQuark*AndAdd() =====
f5b8868d 1370
73844f9c
PT
1371getQuarkAbsoluteAndAdd() and getQuarkRelativeAndAdd() work exactly like their
1372non-AndAdd counterparts in ITmfStateSystem. The difference is that the -AndAdd
1373versions will not throw any exception: if the requested attribute path does not
1374exist in the system, it will be created, and its newly-assigned quark will be
1375returned.
f5b8868d 1376
73844f9c
PT
1377When in a state provider, the -AndAdd version should normally be used (unless
1378you know for sure the attribute already exist and don't want to create it
1379otherwise). This means that there is no need to define the whole attribute tree
1380in advance, the attributes will be created on-demand.
f5b8868d 1381
73844f9c 1382===== modifyAttribute() =====
f5b8868d 1383
73844f9c
PT
1384This is the main state-change-insertion method. As was explained before, a state
1385change is defined by a timestamp, an attribute and a state value. Those three
1386elements need to be passed to modifyAttribute as parameters.
f5b8868d 1387
73844f9c
PT
1388Other state change insertion methods are available (increment-, push-, pop- and
1389removeAttribute()), but those are simply convenience wrappers around
1390modifyAttribute(). Check their Javadoc for more information.
f5b8868d 1391
73844f9c 1392===== closeHistory() =====
f5b8868d 1393
73844f9c
PT
1394When the construction phase is done, do not forget to call closeHistory() to
1395tell the backend that no more intervals will be received. Depending on the
1396backend type, it might have to save files, close descriptors, etc. This ensures
1397that a persitent file can then be re-used when the trace is opened again.
f5b8868d 1398
73844f9c
PT
1399If you use the AbstractTmfStateProvider, it will call closeHistory()
1400automatically when it reaches the end of the trace.
f5b8868d 1401
73844f9c 1402=== Other relevant interfaces ===
f5b8868d 1403
73844f9c 1404==== o.e.l.tmf.core.statevalue.ITmfStateValue ====
f5b8868d 1405
73844f9c
PT
1406This is the interface used to represent state values. Those are used when
1407inserting state changes in the provider, and is also part of the state intervals
1408obtained when doing queries.
f5b8868d 1409
73844f9c
PT
1410The abstract TmfStateValue class contains the factory methods to create new
1411state values of either int, long or string types. To retrieve the real object
1412inside the state value, one can use the .unbox* methods.
f5b8868d 1413
73844f9c 1414Note: Do not instantiate null values manually, use TmfStateValue.nullValue()
f5b8868d 1415
73844f9c 1416==== o.e.l.tmf.core.interval.ITmfStateInterval ====
f5b8868d 1417
73844f9c
PT
1418This is the interface to represent the state intervals, which are stored in the
1419state history backend, and are returned when doing state system queries. A very
1420simple implementation is available in TmfStateInterval. Its methods should be
1421self-descriptive.
f5b8868d 1422
73844f9c 1423=== Exceptions ===
f5b8868d 1424
73844f9c
PT
1425The following exceptions, found in o.e.l.tmf.core.exceptions, are related to
1426state system activities.
f5b8868d 1427
73844f9c 1428==== AttributeNotFoundException ====
f5b8868d 1429
73844f9c
PT
1430This is thrown by getQuarkRelative() and getQuarkAbsolute() (but not byt the
1431-AndAdd versions!) when passing an attribute path that is not present in the
1432state system. This is to ensure that no new attribute is created when using
1433these versions of the methods.
f5b8868d 1434
73844f9c
PT
1435Views can expect some attributes to be present, but they should handle these
1436exceptions for when the attributes end up not being in the state system (perhaps
1437this particular trace didn't have a certain type of events, etc.)
f5b8868d 1438
73844f9c 1439==== StateValueTypeException ====
f5b8868d 1440
73844f9c
PT
1441This exception will be thrown when trying to unbox a state value into a type
1442different than its own. You should always check with ITmfStateValue#getType()
1443beforehand if you are not sure about the type of a given state value.
f5b8868d 1444
73844f9c 1445==== TimeRangeException ====
f5b8868d 1446
73844f9c
PT
1447This exception is thrown when trying to do a query on the state system for a
1448timestamp that is outside of its range. To be safe, you should check with
1449ITmfStateSystem#getStartTime() and #getCurrentEndTime() for the current valid
1450range of the state system. This is especially important when doing queries on
1451a state system that is currently being built.
f5b8868d 1452
73844f9c 1453==== StateSystemDisposedException ====
f5b8868d 1454
73844f9c
PT
1455This exception is thrown when trying to access a state system that has been
1456disposed, with its dispose() method. This can potentially happen at shutdown,
1457since Eclipse is not always consistent with the order in which the components
1458are closed.
f5b8868d 1459
f5b8868d 1460
73844f9c 1461== Comparison of state system backends ==
f5b8868d 1462
73844f9c
PT
1463As we have seen in section [[#High-level components]], the state system needs
1464a storage backend to save the intervals. Different implementations are
1465available when building your state system from TmfStateSystemFactory.
f5b8868d 1466
73844f9c
PT
1467Do not confuse full/single queries with full/partial history! All backend types
1468should be able to handle any type of queries defined in the ITmfStateSystem API,
1469unless noted otherwise.
f5b8868d 1470
73844f9c 1471=== Full history ===
2819a797 1472
73844f9c
PT
1473Available with TmfStateSystemFactory#newFullHistory(). The full history uses a
1474History Tree data structure, which is an optimized structure store state
1475intervals on disk. Once built, it can respond to queries in a ''log(n)'' manner.
2819a797 1476
73844f9c
PT
1477You need to specify a file at creation time, which will be the container for
1478the history tree. Once it's completely built, it will remain on disk (until you
1479delete the trace from the project). This way it can be reused from one session
1480to another, which makes subsequent loading time much faster.
2819a797 1481
73844f9c
PT
1482This the backend used by the LTTng kernel plugin. It offers good scalability and
1483performance, even at extreme sizes (it's been tested with traces of sizes up to
1484500 GB). Its main downside is the amount of disk space required: since every
1485single interval is written to disk, the size of the history file can quite
1486easily reach and even surpass the size of the trace itself.
2819a797 1487
73844f9c 1488=== Null history ===
2819a797 1489
73844f9c
PT
1490Available with TmfStateSystemFactory#newNullHistory(). As its name implies the
1491null history is in fact an absence of state history. All its query methods will
1492return null (see the Javadoc in NullBackend).
2819a797 1493
73844f9c 1494Obviously, no file is required, and almost no memory space is used.
2819a797 1495
73844f9c
PT
1496It's meant to be used in cases where you are not interested in past states, but
1497only in the "ongoing" one. It can also be useful for debugging and benchmarking.
2819a797 1498
73844f9c 1499=== In-memory history ===
2819a797 1500
73844f9c
PT
1501Available with TmfStateSystemFactory#newInMemHistory(). This is a simple wrapper
1502using an ArrayList to store all state intervals in memory. The implementation
1503at the moment is quite simple, it will iterate through all entries when doing
1504queries to find the ones that match.
2819a797 1505
73844f9c
PT
1506The advantage of this method is that it's very quick to build and query, since
1507all the information resides in memory. However, you are limited to 2^31 entries
1508(roughly 2 billions), and depending on your state provider and trace type, that
1509can happen really fast!
2819a797 1510
73844f9c
PT
1511There are no safeguards, so if you bust the limit you will end up with
1512ArrayOutOfBoundsException's everywhere. If your trace or state history can be
1513arbitrarily big, it's probably safer to use a Full History instead.
2819a797 1514
73844f9c 1515=== Partial history ===
2819a797 1516
73844f9c
PT
1517Available with TmfStateSystemFactory#newPartialHistory(). The partial history is
1518a more advanced form of the full history. Instead of writing all state intervals
1519to disk like with the full history, we only write a small fraction of them, and
1520go back to read the trace to recreate the states in-between.
2819a797 1521
73844f9c
PT
1522It has a big advantage over a full history in terms of disk space usage. It's
1523very possible to reduce the history tree file size by a factor of 1000, while
1524keeping query times within a factor of two. Its main downside comes from the
1525fact that you cannot do efficient single queries with it (they are implemented
1526by doing full queries underneath).
2819a797 1527
73844f9c
PT
1528This makes it a poor choice for views like the Control Flow view, where you do
1529a lot of range queries and single queries. However, it is a perfect fit for
1530cases like statistics, where you usually do full queries already, and you store
1531lots of small states which are very easy to "compress".
2819a797 1532
73844f9c 1533However, it can't really be used until bug 409630 is fixed.
2819a797 1534
73844f9c 1535== Code example ==
2819a797 1536
73844f9c
PT
1537Here is a small example of code that will use the state system. For this
1538example, let's assume we want to track the state of all the CPUs in a LTTng
1539kernel trace. To do so, we will watch for the "sched_switch" event in the state
1540provider, and will update an attribute indicating if the associated CPU should
1541be set to "running" or "idle".
2819a797 1542
73844f9c
PT
1543We will use an attribute tree that looks like this:
1544<pre>
1545CPUs
1546 |--0
1547 | |--Status
1548 |
1549 |--1
1550 | |--Status
1551 |
1552 | 2
1553 | |--Status
1554...
1555</pre>
2819a797 1556
73844f9c
PT
1557The second-level attributes will be named from the information available in the
1558trace events. Only the "Status" attributes will carry a state value (this means
1559we could have just used "1", "2", "3",... directly, but we'll do it in a tree
1560for the example's sake).
2819a797 1561
73844f9c
PT
1562Also, we will use integer state values to represent "running" or "idle", instead
1563of saving the strings that would get repeated every time. This will help in
1564reducing the size of the history file.
2819a797 1565
73844f9c
PT
1566First we will define a state provider in MyStateProvider. Then, assuming we
1567have already implemented a custom trace type extending CtfTmfTrace, we will add
1568a section to it to make it build a state system using the provider we defined
1569earlier. Finally, we will show some example code that can query the state
1570system, which would normally go in a view or analysis module.
2819a797 1571
73844f9c 1572=== State Provider ===
2819a797 1573
73844f9c
PT
1574<pre>
1575import org.eclipse.linuxtools.tmf.core.ctfadaptor.CtfTmfEvent;
1576import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
1577import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException;
1578import org.eclipse.linuxtools.tmf.core.exceptions.StateValueTypeException;
1579import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException;
1580import org.eclipse.linuxtools.tmf.core.statesystem.AbstractTmfStateProvider;
1581import org.eclipse.linuxtools.tmf.core.statevalue.ITmfStateValue;
1582import org.eclipse.linuxtools.tmf.core.statevalue.TmfStateValue;
1583import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace;
2819a797 1584
73844f9c
PT
1585/**
1586 * Example state system provider.
1587 *
1588 * @author Alexandre Montplaisir
1589 */
1590public class MyStateProvider extends AbstractTmfStateProvider {
2819a797 1591
73844f9c
PT
1592 /** State value representing the idle state */
1593 public static ITmfStateValue IDLE = TmfStateValue.newValueInt(0);
2819a797 1594
73844f9c
PT
1595 /** State value representing the running state */
1596 public static ITmfStateValue RUNNING = TmfStateValue.newValueInt(1);
2819a797 1597
73844f9c
PT
1598 /**
1599 * Constructor
1600 *
1601 * @param trace
1602 * The trace to which this state provider is associated
1603 */
1604 public MyStateProvider(ITmfTrace trace) {
1605 super(trace, CtfTmfEvent.class, "Example"); //$NON-NLS-1$
1606 /*
1607 * The third parameter here is not important, it's only used to name a
1608 * thread internally.
1609 */
1610 }
2819a797 1611
73844f9c
PT
1612 @Override
1613 public int getVersion() {
1614 /*
1615 * If the version of an existing file doesn't match the version supplied
1616 * in the provider, a rebuild of the history will be forced.
1617 */
1618 return 1;
1619 }
2819a797 1620
73844f9c
PT
1621 @Override
1622 public MyStateProvider getNewInstance() {
1623 return new MyStateProvider(getTrace());
1624 }
2819a797 1625
73844f9c
PT
1626 @Override
1627 protected void eventHandle(ITmfEvent ev) {
1628 /*
1629 * AbstractStateChangeInput should have already checked for the correct
1630 * class type.
1631 */
1632 CtfTmfEvent event = (CtfTmfEvent) ev;
2819a797 1633
73844f9c
PT
1634 final long ts = event.getTimestamp().getValue();
1635 Integer nextTid = ((Long) event.getContent().getField("next_tid").getValue()).intValue();
1636
1637 try {
1638
1639 if (event.getEventName().equals("sched_switch")) {
1640 int quark = ss.getQuarkAbsoluteAndAdd("CPUs", String.valueOf(event.getCPU()), "Status");
1641 ITmfStateValue value;
1642 if (nextTid > 0) {
1643 value = RUNNING;
1644 } else {
1645 value = IDLE;
1646 }
1647 ss.modifyAttribute(ts, value, quark);
1648 }
1649
1650 } catch (TimeRangeException e) {
1651 /*
1652 * This should not happen, since the timestamp comes from a trace
1653 * event.
1654 */
1655 throw new IllegalStateException(e);
1656 } catch (AttributeNotFoundException e) {
1657 /*
1658 * This should not happen either, since we're only accessing a quark
1659 * we just created.
1660 */
1661 throw new IllegalStateException(e);
1662 } catch (StateValueTypeException e) {
1663 /*
1664 * This wouldn't happen here, but could potentially happen if we try
1665 * to insert mismatching state value types in the same attribute.
1666 */
1667 e.printStackTrace();
1668 }
1669
1670 }
1671
1672}
1673</pre>
1674
1675=== Trace type definition ===
1676
1677<pre>
2819a797 1678import java.io.File;
2819a797
MK
1679
1680import org.eclipse.core.resources.IProject;
2819a797
MK
1681import org.eclipse.core.runtime.IStatus;
1682import org.eclipse.core.runtime.Status;
73844f9c 1683import org.eclipse.linuxtools.tmf.core.ctfadaptor.CtfTmfTrace;
2819a797 1684import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException;
73844f9c
PT
1685import org.eclipse.linuxtools.tmf.core.statesystem.ITmfStateProvider;
1686import org.eclipse.linuxtools.tmf.core.statesystem.ITmfStateSystem;
1687import org.eclipse.linuxtools.tmf.core.statesystem.TmfStateSystemFactory;
1688import org.eclipse.linuxtools.tmf.core.trace.TmfTraceManager;
2819a797
MK
1689
1690/**
73844f9c 1691 * Example of a custom trace type using a custom state provider.
2819a797 1692 *
73844f9c 1693 * @author Alexandre Montplaisir
2819a797 1694 */
73844f9c 1695public class MyTraceType extends CtfTmfTrace {
2819a797 1696
73844f9c
PT
1697 /** The file name of the history file */
1698 public final static String HISTORY_FILE_NAME = "mystatefile.ht";
2819a797 1699
73844f9c
PT
1700 /** ID of the state system we will build */
1701 public static final String STATE_ID = "org.eclipse.linuxtools.lttng2.example";
2819a797 1702
73844f9c
PT
1703 /**
1704 * Default constructor
1705 */
1706 public MyTraceType() {
1707 super();
2819a797
MK
1708 }
1709
1710 @Override
73844f9c
PT
1711 public IStatus validate(final IProject project, final String path) {
1712 /*
1713 * Add additional validation code here, and return a IStatus.ERROR if
1714 * validation fails.
1715 */
1716 return Status.OK_STATUS;
2819a797
MK
1717 }
1718
1719 @Override
73844f9c
PT
1720 protected void buildStateSystem() throws TmfTraceException {
1721 super.buildStateSystem();
1722
1723 /* Build the custom state system for this trace */
1724 String directory = TmfTraceManager.getSupplementaryFileDir(this);
1725 final File htFile = new File(directory + HISTORY_FILE_NAME);
1726 final ITmfStateProvider htInput = new MyStateProvider(this);
1727
1728 ITmfStateSystem ss = TmfStateSystemFactory.newFullHistory(htFile, htInput, false);
1729 fStateSystems.put(STATE_ID, ss);
2819a797
MK
1730 }
1731
73844f9c
PT
1732}
1733</pre>
1734
1735=== Query code ===
1736
1737<pre>
1738import java.util.List;
1739
1740import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException;
1741import org.eclipse.linuxtools.tmf.core.exceptions.StateSystemDisposedException;
1742import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException;
1743import org.eclipse.linuxtools.tmf.core.interval.ITmfStateInterval;
1744import org.eclipse.linuxtools.tmf.core.statesystem.ITmfStateSystem;
1745import org.eclipse.linuxtools.tmf.core.statevalue.ITmfStateValue;
1746import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace;
1747
1748/**
1749 * Class showing examples of state system queries.
1750 *
1751 * @author Alexandre Montplaisir
1752 */
1753public class QueryExample {
1754
1755 private final ITmfStateSystem ss;
1756
2819a797 1757 /**
73844f9c
PT
1758 * Constructor
1759 *
1760 * @param trace
1761 * Trace that this "view" will display.
2819a797 1762 */
73844f9c
PT
1763 public QueryExample(ITmfTrace trace) {
1764 ss = trace.getStateSystems().get(MyTraceType.STATE_ID);
2819a797
MK
1765 }
1766
73844f9c
PT
1767 /**
1768 * Example method of querying one attribute in the state system.
1769 *
1770 * We pass it a cpu and a timestamp, and it returns us if that cpu was
1771 * executing a process (true/false) at that time.
1772 *
1773 * @param cpu
1774 * The CPU to check
1775 * @param timestamp
1776 * The timestamp of the query
1777 * @return True if the CPU was running, false otherwise
1778 */
1779 public boolean cpuIsRunning(int cpu, long timestamp) {
2819a797 1780 try {
73844f9c
PT
1781 int quark = ss.getQuarkAbsolute("CPUs", String.valueOf(cpu), "Status");
1782 ITmfStateValue value = ss.querySingleState(timestamp, quark).getStateValue();
2819a797 1783
73844f9c
PT
1784 if (value.equals(MyStateProvider.RUNNING)) {
1785 return true;
1786 }
2819a797 1787
73844f9c
PT
1788 /*
1789 * Since at this level we have no guarantee on the contents of the state
1790 * system, it's important to handle these cases correctly.
1791 */
1792 } catch (AttributeNotFoundException e) {
1793 /*
1794 * Handle the case where the attribute does not exist in the state
1795 * system (no CPU with this number, etc.)
1796 */
1797 ...
1798 } catch (TimeRangeException e) {
1799 /*
1800 * Handle the case where 'timestamp' is outside of the range of the
1801 * history.
1802 */
1803 ...
1804 } catch (StateSystemDisposedException e) {
1805 /*
1806 * Handle the case where the state system is being disposed. If this
1807 * happens, it's normally when shutting down, so the view can just
1808 * return immediately and wait it out.
1809 */
1810 }
1811 return false;
2819a797
MK
1812 }
1813
2819a797 1814
73844f9c
PT
1815 /**
1816 * Example method of using a full query.
1817 *
1818 * We pass it a timestamp, and it returns us how many CPUs were executing a
1819 * process at that moment.
1820 *
1821 * @param timestamp
1822 * The target timestamp
1823 * @return The amount of CPUs that were running at that time
1824 */
1825 public int getNbRunningCpus(long timestamp) {
1826 int count = 0;
2819a797 1827
73844f9c
PT
1828 try {
1829 /* Get the list of the quarks we are interested in. */
1830 List<Integer> quarks = ss.getQuarks("CPUs", "*", "Status");
2819a797 1831
73844f9c
PT
1832 /*
1833 * Get the full state at our target timestamp (it's better than
1834 * doing an arbitrary number of single queries).
1835 */
1836 List<ITmfStateInterval> state = ss.queryFullState(timestamp);
2819a797 1837
73844f9c
PT
1838 /* Look at the value of the state for each quark */
1839 for (Integer quark : quarks) {
1840 ITmfStateValue value = state.get(quark).getStateValue();
1841 if (value.equals(MyStateProvider.RUNNING)) {
1842 count++;
1843 }
2819a797 1844 }
73844f9c
PT
1845
1846 } catch (TimeRangeException e) {
1847 /*
1848 * Handle the case where 'timestamp' is outside of the range of the
1849 * history.
1850 */
1851 ...
1852 } catch (StateSystemDisposedException e) {
1853 /* Handle the case where the state system is being disposed. */
1854 ...
2819a797 1855 }
73844f9c 1856 return count;
2819a797
MK
1857 }
1858}
1859</pre>
1860
73844f9c 1861= UML2 Sequence Diagram Framework =
2819a797 1862
73844f9c
PT
1863The purpose of the UML2 Sequence Diagram Framework of TMF is to provide a framework for generation of UML2 sequence diagrams. It provides
1864*UML2 Sequence diagram drawing capabilities (i.e. lifelines, messages, activations, object creation and deletion)
1865*a generic, re-usable Sequence Diagram View
1866*Eclipse Extension Point for the creation of sequence diagrams
1867*callback hooks for searching and filtering within the Sequence Diagram View
1868*scalability<br>
1869The following chapters describe the Sequence Diagram Framework as well as a reference implementation and its usage.
2819a797 1870
73844f9c 1871== TMF UML2 Sequence Diagram Extensions ==
2819a797 1872
73844f9c 1873In the UML2 Sequence Diagram Framework an Eclipse extension point is defined so that other plug-ins can contribute code to create sequence diagram.
2819a797 1874
73844f9c
PT
1875'''Identifier''': org.eclipse.linuxtools.tmf.ui.uml2SDLoader<br>
1876'''Since''': Since 0.3.2 (based on UML2SD of org.eclipse.tptp.common.ui)<br>
1877'''Description''': This extension point aims to list and connect any UML2 Sequence Diagram loader.<br>
1878'''Configuration Markup''':<br>
2819a797 1879
73844f9c
PT
1880<pre>
1881<!ELEMENT extension (uml2SDLoader)+>
1882<!ATTLIST extension
1883point CDATA #REQUIRED
1884id CDATA #IMPLIED
1885name CDATA #IMPLIED
1886>
1887</pre>
2819a797 1888
73844f9c
PT
1889*point - A fully qualified identifier of the target extension point.
1890*id - An optional identifier of the extension instance.
1891*name - An optional name of the extension instance.
2819a797 1892
73844f9c
PT
1893<pre>
1894<!ELEMENT uml2SDLoader EMPTY>
1895<!ATTLIST uml2SDLoader
1896id CDATA #REQUIRED
1897name CDATA #REQUIRED
1898class CDATA #REQUIRED
1899view CDATA #REQUIRED
1900default (true | false)
1901</pre>
2819a797 1902
73844f9c
PT
1903*id - A unique identifier for this uml2SDLoader. This is not mandatory as long as the id attribute cannot be retrieved by the provider plug-in. The class attribute is the one on which the underlying algorithm relies.
1904*name - An name of the extension instance.
1905*class - The implementation of this UML2 SD viewer loader. The class must implement org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader.
1906*view - The view ID of the view that this loader aims to populate. Either org.eclipse.linuxtools.tmf.ui.views.uml2sd.SDView itself or a extension of org.eclipse.linuxtools.tmf.ui.views.uml2sd.SDView.
1907*default - Set to true to make this loader the default one for the view; in case of several default loaders, first one coming from extensions list is taken.
2819a797 1908
2819a797 1909
73844f9c 1910== Management of the Extension Point ==
2819a797 1911
73844f9c
PT
1912The TMF UI plug-in is responsible for evaluating each contribution to the extension point.
1913<br>
1914<br>
1915With this extension point, a loader class is associated with a Sequence Diagram View. Multiple loaders can be associated to a single Sequence Diagram View. However, additional means have to be implemented to specify which loader should be used when opening the view. For example, an eclipse action or command could be used for that. This additional code is not necessary if there is only one loader for a given Sequence Diagram View associated and this loader has the attribute "default" set to "true". (see also [[#Using one Sequence Diagram View with Multiple Loaders | Using one Sequence Diagram View with Multiple Loaders]])
2819a797 1916
73844f9c 1917== Sequence Diagram View ==
2819a797 1918
73844f9c 1919For this extension point a Sequence Diagram View has to be defined as well. The Sequence Diagram View class implementation is provided by the plug-in ''org.eclipse.linuxtools.tmf.ui'' (''org.eclipse.linuxtools.tmf.ui.views.uml2sd.SDView'') and can be used as is or can also be sub-classed. For that, a view extension has to be added to the ''plugin.xml''.
2819a797 1920
73844f9c 1921=== Supported Widgets ===
2819a797 1922
73844f9c 1923The loader class provides a frame containing all the UML2 widgets to be displayed. The following widgets exist:
2819a797 1924
73844f9c
PT
1925*Lifeline
1926*Activation
1927*Synchronous Message
1928*Asynchronous Message
1929*Synchronous Message Return
1930*Asynchronous Message Return
1931*Stop
2819a797 1932
73844f9c 1933For a lifeline, a category can be defined. The lifeline category defines icons, which are displayed in the lifeline header.
2819a797 1934
73844f9c 1935=== Zooming ===
2819a797 1936
73844f9c 1937The Sequence Diagram View allows the user to zoom in, zoom out and reset the zoom factor.
2819a797 1938
73844f9c 1939=== Printing ===
2819a797 1940
73844f9c 1941It is possible to print the whole sequence diagram as well as part of it.
2819a797 1942
73844f9c 1943=== Key Bindings ===
2819a797 1944
73844f9c
PT
1945*SHIFT+ALT+ARROW-DOWN - to scroll down within sequence diagram one view page at a time
1946*SHIFT+ALT+ARROW-UP - to scroll up within sequence diagram one view page at a time
1947*SHIFT+ALT+ARROW-RIGHT - to scroll right within sequence diagram one view page at a time
1948*SHIFT+ALT+ARROW-LEFT - to scroll left within sequence diagram one view page at a time
1949*SHIFT+ALT+ARROW-HOME - to jump to the beginning of the selected message if not already visible in page
1950*SHIFT+ALT+ARROW-END - to jump to the end of the selected message if not already visible in page
1951*CTRL+F - to open find dialog if either the basic or extended find provider is defined (see [[#Using the Find Provider Interface | Using the Find Provider Interface]])
1952*CTRL+P - to open print dialog
067490ab 1953
73844f9c 1954=== Preferences ===
5f7ef209 1955
73844f9c
PT
1956The UML2 Sequence Diagram Framework provides preferences to customize the appearance of the Sequence Diagram View. The color of all widgets and text as well as the fonts of the text of all widget can be adjust. Amongst others the default lifeline width can be alternated. To change preferences select '''Windows->Preferences->Tracing->UML2 Sequence Diagrams'''. The following preference page will show:<br>
1957[[Image:images/SeqDiagramPref.png]] <br>
1958After changing the preferences select '''OK'''.
067490ab 1959
73844f9c 1960=== Callback hooks ===
067490ab 1961
73844f9c
PT
1962The Sequence Diagram View provides several callback hooks so that extension can provide application specific functionality. The following interfaces can be provided:
1963* Basic find provider or extended find Provider<br> For finding within the sequence diagram
1964* Basic filter provider and extended Filter Provider<br> For filtering within the sequnce diagram.
1965* Basic paging provider or advanced paging provider<br> For scalability reasons, used to limit number of displayed messages
1966* Properies provider<br> To provide properties of selected elements
1967* Collapse provider <br> To collapse areas of the sequence diagram
067490ab 1968
73844f9c 1969== Tutorial ==
067490ab 1970
73844f9c 1971This tutorial describes how to create a UML2 Sequence Diagram Loader extension and use this loader in the in Eclipse.
067490ab 1972
73844f9c 1973=== Prerequisites ===
067490ab 1974
73844f9c 1975The tutorial is based on Eclipse 3.7 (Eclipse Indigo) and TMF 0.3.2.
067490ab 1976
73844f9c 1977=== Creating an Eclipse UI Plug-in ===
067490ab 1978
73844f9c
PT
1979To create a new project with name org.eclipse.linuxtools.tmf.sample.ui select '''File -> New -> Project -> Plug-in Development -> Plug-in Project'''. <br>
1980[[Image:images/Screenshot-NewPlug-inProject1.png]]<br>
067490ab 1981
73844f9c 1982[[Image:images/Screenshot-NewPlug-inProject2.png]]<br>
067490ab 1983
73844f9c 1984[[Image:images/Screenshot-NewPlug-inProject3.png]]<br>
067490ab 1985
73844f9c 1986=== Creating a Sequence Diagram View ===
067490ab 1987
73844f9c
PT
1988To open the plug-in manifest, double-click on the MANIFEST.MF file. <br>
1989[[Image:images/SelectManifest.png]]<br>
5f7ef209 1990
73844f9c
PT
1991Change to the Dependencies tab and select '''Add...''' of the ''Required Plug-ins'' section. A new dialog box will open. Next find plug-in ''org.eclipse.linuxtools.tmf.ui'' and press '''OK'''<br>
1992[[Image:images/AddDependencyTmfUi.png]]<br>
067490ab 1993
73844f9c
PT
1994Change to the Extensions tab and select '''Add...''' of the ''All Extension'' section. A new dialog box will open. Find the view extension ''org.eclipse.ui.views'' and press '''Finish'''.<br>
1995[[Image:images/AddViewExtension1.png]]<br>
067490ab 1996
73844f9c
PT
1997To create a Sequence Diagram View, click the right mouse button. Then select '''New -> view'''<br>
1998[[Image:images/AddViewExtension2.png]]<br>
32897d73 1999
73844f9c
PT
2000A new view entry has been created. Fill in the fields ''id'', ''name'' and ''class''. Note that for ''class'' the SD view implementation (''org.eclipse.linuxtools.tmf.ui.views.SDView'') of the TMF UI plug-in is used.<br>
2001[[Image:images/FillSampleSeqDiagram.png]]<br>
32897d73 2002
73844f9c
PT
2003The view is prepared. Run the Example. To launch the an Eclipse Application select the ''Overview'' tab and click on '''Launch an Eclipse Application'''<br>
2004[[Image:images/RunEclipseApplication.png]]<br>
32897d73 2005
73844f9c
PT
2006A new Eclipse application window will show. In the new window go to '''Windows -> Show View -> Other... -> Other -> Sample Sequence Diagram'''.<br>
2007[[Image:images/ShowViewOther.png]]<br>
32897d73 2008
73844f9c
PT
2009The Sequence Diagram View will open with an blank page.<br>
2010[[Image:images/BlankSampleSeqDiagram.png]]<br>
32897d73 2011
73844f9c 2012Close the Example Application.
32897d73 2013
73844f9c 2014=== Defining the uml2SDLoader Extension ===
32897d73 2015
73844f9c 2016After defining the Sequence Diagram View it's time to create the ''uml2SDLoader'' Extension. <br>
32897d73 2017
73844f9c
PT
2018Before doing that add a dependency to TMF. For that select '''Add...''' of the ''Required Plug-ins'' section. A new dialog box will open. Next find plug-in ''org.eclipse.linuxtools.tmf'' and press '''OK'''<br>
2019[[Image:images/AddDependencyTmf.png]]<br>
32897d73 2020
73844f9c
PT
2021To create the loader extension, change to the Extensions tab and select '''Add...''' of the ''All Extension'' section. A new dialog box will open. Find the extension ''org.eclipse.linuxtools.tmf.ui.uml2SDLoader'' and press '''Finish'''.<br>
2022[[Image:images/AddTmfUml2SDLoader.png]]<br>
32897d73 2023
73844f9c
PT
2024A new 'uml2SDLoader'' extension has been created. Fill in fields ''id'', ''name'', ''class'', ''view'' and ''default''. Use ''default'' equal true for this example. For the view add the id of the Sequence Diagram View of chapter [[#Creating a Sequence Diagram View | Creating a Sequence Diagram View]]. <br>
2025[[Image:images/FillSampleLoader.png]]<br>
32897d73 2026
73844f9c
PT
2027Then click on ''class'' (see above) to open the new class dialog box. Fill in the relevant fields and select '''Finish'''. <br>
2028[[Image:images/NewSampleLoaderClass.png]]<br>
32897d73 2029
73844f9c 2030A new Java class will be created which implements the interface ''org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader''.<br>
32897d73 2031
73844f9c
PT
2032<pre>
2033package org.eclipse.linuxtools.tmf.sample.ui;
32897d73 2034
73844f9c
PT
2035import org.eclipse.linuxtools.tmf.ui.views.uml2sd.SDView;
2036import org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader;
32897d73 2037
73844f9c 2038public class SampleLoader implements IUml2SDLoader {
32897d73 2039
73844f9c
PT
2040 public SampleLoader() {
2041 // TODO Auto-generated constructor stub
2042 }
32897d73 2043
73844f9c
PT
2044 @Override
2045 public void dispose() {
2046 // TODO Auto-generated method stub
32897d73 2047
73844f9c 2048 }
32897d73 2049
73844f9c
PT
2050 @Override
2051 public String getTitleString() {
2052 // TODO Auto-generated method stub
2053 return null;
2054 }
32897d73 2055
73844f9c
PT
2056 @Override
2057 public void setViewer(SDView arg0) {
2058 // TODO Auto-generated method stub
32897d73 2059
73844f9c 2060 }
32897d73
AM
2061</pre>
2062
73844f9c 2063=== Implementing the Loader Class ===
32897d73 2064
73844f9c 2065Next is to implement the methods of the IUml2SDLoader interface method. The following code snippet shows how to create the major sequence diagram elements. Please note that no time information is stored.<br>
32897d73 2066
73844f9c
PT
2067<pre>
2068package org.eclipse.linuxtools.tmf.sample.ui;
32897d73 2069
73844f9c
PT
2070import org.eclipse.linuxtools.tmf.ui.views.uml2sd.SDView;
2071import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.AsyncMessage;
2072import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.AsyncMessageReturn;
2073import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.ExecutionOccurrence;
2074import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.Frame;
2075import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.Lifeline;
2076import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.Stop;
2077import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.SyncMessage;
2078import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.SyncMessageReturn;
2079import org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader;
32897d73 2080
73844f9c 2081public class SampleLoader implements IUml2SDLoader {
32897d73 2082
73844f9c
PT
2083 private SDView fSdView;
2084
2085 public SampleLoader() {
2086 }
32897d73 2087
73844f9c
PT
2088 @Override
2089 public void dispose() {
2090 }
32897d73 2091
73844f9c
PT
2092 @Override
2093 public String getTitleString() {
2094 return "Sample Diagram";
2095 }
32897d73 2096
73844f9c
PT
2097 @Override
2098 public void setViewer(SDView arg0) {
2099 fSdView = arg0;
2100 createFrame();
2101 }
2102
2103 private void createFrame() {
32897d73 2104
73844f9c
PT
2105 Frame testFrame = new Frame();
2106 testFrame.setName("Sample Frame");
32897d73 2107
73844f9c
PT
2108 /*
2109 * Create lifelines
2110 */
2111
2112 Lifeline lifeLine1 = new Lifeline();
2113 lifeLine1.setName("Object1");
2114 testFrame.addLifeLine(lifeLine1);
2115
2116 Lifeline lifeLine2 = new Lifeline();
2117 lifeLine2.setName("Object2");
2118 testFrame.addLifeLine(lifeLine2);
2119
32897d73 2120
73844f9c
PT
2121 /*
2122 * Create Sync Message
2123 */
2124 // Get new occurrence on lifelines
2125 lifeLine1.getNewEventOccurrence();
2126
2127 // Get Sync message instances
2128 SyncMessage start = new SyncMessage();
2129 start.setName("Start");
2130 start.setEndLifeline(lifeLine1);
2131 testFrame.addMessage(start);
32897d73 2132
73844f9c
PT
2133 /*
2134 * Create Sync Message
2135 */
2136 // Get new occurrence on lifelines
2137 lifeLine1.getNewEventOccurrence();
2138 lifeLine2.getNewEventOccurrence();
2139
2140 // Get Sync message instances
2141 SyncMessage syn1 = new SyncMessage();
2142 syn1.setName("Sync Message 1");
2143 syn1.setStartLifeline(lifeLine1);
2144 syn1.setEndLifeline(lifeLine2);
2145 testFrame.addMessage(syn1);
32897d73 2146
73844f9c
PT
2147 /*
2148 * Create corresponding Sync Message Return
2149 */
2150
2151 // Get new occurrence on lifelines
2152 lifeLine1.getNewEventOccurrence();
2153 lifeLine2.getNewEventOccurrence();
32897d73 2154
73844f9c
PT
2155 SyncMessageReturn synReturn1 = new SyncMessageReturn();
2156 synReturn1.setName("Sync Message Return 1");
2157 synReturn1.setStartLifeline(lifeLine2);
2158 synReturn1.setEndLifeline(lifeLine1);
2159 synReturn1.setMessage(syn1);
2160 testFrame.addMessage(synReturn1);
2161
2162 /*
2163 * Create Activations (Execution Occurrence)
2164 */
2165 ExecutionOccurrence occ1 = new ExecutionOccurrence();
2166 occ1.setStartOccurrence(start.getEventOccurrence());
2167 occ1.setEndOccurrence(synReturn1.getEventOccurrence());
2168 lifeLine1.addExecution(occ1);
2169 occ1.setName("Activation 1");
2170
2171 ExecutionOccurrence occ2 = new ExecutionOccurrence();
2172 occ2.setStartOccurrence(syn1.getEventOccurrence());
2173 occ2.setEndOccurrence(synReturn1.getEventOccurrence());
2174 lifeLine2.addExecution(occ2);
2175 occ2.setName("Activation 2");
2176
2177 /*
2178 * Create Sync Message
2179 */
2180 // Get new occurrence on lifelines
2181 lifeLine1.getNewEventOccurrence();
2182 lifeLine2.getNewEventOccurrence();
2183
2184 // Get Sync message instances
2185 AsyncMessage asyn1 = new AsyncMessage();
2186 asyn1.setName("Async Message 1");
2187 asyn1.setStartLifeline(lifeLine1);
2188 asyn1.setEndLifeline(lifeLine2);
2189 testFrame.addMessage(asyn1);
32897d73 2190
73844f9c
PT
2191 /*
2192 * Create corresponding Sync Message Return
2193 */
2194
2195 // Get new occurrence on lifelines
2196 lifeLine1.getNewEventOccurrence();
2197 lifeLine2.getNewEventOccurrence();
32897d73 2198
73844f9c
PT
2199 AsyncMessageReturn asynReturn1 = new AsyncMessageReturn();
2200 asynReturn1.setName("Async Message Return 1");
2201 asynReturn1.setStartLifeline(lifeLine2);
2202 asynReturn1.setEndLifeline(lifeLine1);
2203 asynReturn1.setMessage(asyn1);
2204 testFrame.addMessage(asynReturn1);
2205
2206 /*
2207 * Create a note
2208 */
2209
2210 // Get new occurrence on lifelines
2211 lifeLine1.getNewEventOccurrence();
2212
2213 EllipsisisMessage info = new EllipsisisMessage();
2214 info.setName("Object deletion");
2215 info.setStartLifeline(lifeLine2);
2216 testFrame.addNode(info);
2217
2218 /*
2219 * Create a Stop
2220 */
2221 Stop stop = new Stop();
2222 stop.setLifeline(lifeLine2);
2223 stop.setEventOccurrence(lifeLine2.getNewEventOccurrence());
2224 lifeLine2.addNode(stop);
2225
2226 fSdView.setFrame(testFrame);
2227 }
2228}
2229</pre>
32897d73 2230
73844f9c
PT
2231Now it's time to run the example application. To launch the Example Application select the ''Overview'' tab and click on '''Launch an Eclipse Application'''<br>
2232[[Image:images/SampleDiagram1.png]] <br>
32897d73 2233
73844f9c 2234=== Adding time information ===
32897d73 2235
73844f9c 2236To add time information in sequence diagram the timestamp has to be set for each message. The sequence diagram framework uses the ''TmfTimestamp'' class of plug-in ''org.eclipse.linuxtools.tmf''. Use ''setTime()'' on each message ''SyncMessage'' since start and end time are the same. For each ''AsyncMessage'' set start and end time separately by using methods ''setStartTime'' and ''setEndTime''. For example: <br>
32897d73 2237
73844f9c
PT
2238<pre>
2239 private void createFrame() {
2240 //...
2241 start.setTime(new TmfTimestamp(1000, -3));
2242 syn1.setTime(new TmfTimestamp(1005, -3));
2243 synReturn1.setTime(new TmfTimestamp(1050, -3));
2244 asyn1.setStartTime(new TmfTimestamp(1060, -3));
2245 asyn1.setEndTime(new TmfTimestamp(1070, -3));
2246 asynReturn1.setStartTime(new TmfTimestamp(1060, -3));
2247 asynReturn1.setEndTime(new TmfTimestamp(1070, -3));
2248 //...
2249 }
2250</pre>
32897d73 2251
73844f9c 2252When running the example application, a time compression bar on the left appears which indicates the time elapsed between consecutive events. The time compression scale shows where the time falls between the minimum and maximum delta times. The intensity of the color is used to indicate the length of time, namely, the deeper the intensity, the higher the delta time. The minimum and maximum delta times are configurable through the collbar menu ''Configure Min Max''. The time compression bar and scale may provide an indication about which events consumes the most time. By hovering over the time compression bar a tooltip appears containing more information. <br>
32897d73 2253
73844f9c 2254[[Image:images/SampleDiagramTimeComp.png]] <br>
32897d73 2255
73844f9c 2256By hovering over a message it will show the time information in the appearing tooltip. For each ''SyncMessage'' it shows its time occurrence and for each ''AsyncMessage'' it shows the start and end time.
32897d73 2257
73844f9c
PT
2258[[Image:images/SampleDiagramSyncMessage.png]] <br>
2259[[Image:images/SampleDiagramAsyncMessage.png]] <br>
32897d73 2260
73844f9c
PT
2261To see the time elapsed between 2 messages, select one message and hover over a second message. A tooltip will show with the delta in time. Note if the second message is before the first then a negative delta is displayed. Note that for ''AsynMessage'' the end time is used for the delta calculation.<br>
2262[[Image:images/SampleDiagramMessageDelta.png]] <br>
32897d73 2263
73844f9c 2264=== Default Coolbar and Menu Items ===
32897d73 2265
73844f9c
PT
2266The Sequence Diagram View comes with default coolbar and menu items. By default, each sequence diagram shows the following actions:
2267* Zoom in
2268* Zoom out
2269* Reset Zoom Factor
2270* Selection
2271* Configure Min Max (drop-down menu only)
2272* Navigation -> Show the node end (drop-down menu only)
2273* Navigation -> Show the node start (drop-down menu only)
32897d73 2274
73844f9c 2275[[Image:images/DefaultCoolbarMenu.png]]<br>
32897d73 2276
73844f9c 2277=== Implementing Optional Callbacks ===
32897d73 2278
73844f9c 2279The following chapters describe how to use all supported provider interfaces.
32897d73 2280
73844f9c 2281==== Using the Paging Provider Interface ====
32897d73 2282
73844f9c
PT
2283For scalability reasons, the paging provider interfaces exists to limit the number of messages displayed in the Sequence Diagram View at a time. For that, two interfaces exist, the basic paging provider and the advanced paging provider. When using the basic paging interface, actions for traversing page by page through the sequence diagram of a trace will be provided.
2284<br>
2285To use the basic paging provider, first the interface methods of the ''ISDPagingProvider'' have to be implemented by a class. (i.e. ''hasNextPage()'', ''hasPrevPage()'', ''nextPage()'', ''prevPage()'', ''firstPage()'' and ''endPage()''. Typically, this is implemented in the loader class. Secondly, the provider has to be set in the Sequence Diagram View. This will be done in the ''setViewer()'' method of the loader class. Lastly, the paging provider has to be removed from the view, when the ''dispose()'' method of the loader class is called.
32897d73 2286
73844f9c
PT
2287<pre>
2288public class SampleLoader implements IUml2SDLoader, ISDPagingProvider {
2289 //...
2290 private page = 0;
2291
2292 @Override
2293 public void dispose() {
2294 if (fSdView != null) {
2295 fSdView.resetProviders();
2296 }
2297 }
2298
2299 @Override
2300 public void setViewer(SDView arg0) {
2301 fSdView = arg0;
2302 fSdView.setSDPagingProvider(this);
2303 createFrame();
2304 }
2305
2306 private void createSecondFrame() {
2307 Frame testFrame = new Frame();
2308 testFrame.setName("SecondFrame");
2309 Lifeline lifeline = new Lifeline();
2310 lifeline.setName("LifeLine 0");
2311 testFrame.addLifeLine(lifeline);
2312 lifeline = new Lifeline();
2313 lifeline.setName("LifeLine 1");
2314 testFrame.addLifeLine(lifeline);
2315 for (int i = 1; i < 5; i++) {
2316 SyncMessage message = new SyncMessage();
2317 message.autoSetStartLifeline(testFrame.getLifeline(0));
2318 message.autoSetEndLifeline(testFrame.getLifeline(0));
2319 message.setName((new StringBuilder("Message ")).append(i).toString());
2320 testFrame.addMessage(message);
2321
2322 SyncMessageReturn messageReturn = new SyncMessageReturn();
2323 messageReturn.autoSetStartLifeline(testFrame.getLifeline(0));
2324 messageReturn.autoSetEndLifeline(testFrame.getLifeline(0));
2325
2326 testFrame.addMessage(messageReturn);
2327 messageReturn.setName((new StringBuilder("Message return ")).append(i).toString());
2328 ExecutionOccurrence occ = new ExecutionOccurrence();
2329 occ.setStartOccurrence(testFrame.getSyncMessage(i - 1).getEventOccurrence());
2330 occ.setEndOccurrence(testFrame.getSyncMessageReturn(i - 1).getEventOccurrence());
2331 testFrame.getLifeline(0).addExecution(occ);
2332 }
2333 fSdView.setFrame(testFrame);
2334 }
32897d73 2335
73844f9c
PT
2336 @Override
2337 public boolean hasNextPage() {
2338 return page == 0;
2339 }
32897d73 2340
73844f9c
PT
2341 @Override
2342 public boolean hasPrevPage() {
2343 return page == 1;
2344 }
32897d73 2345
73844f9c
PT
2346 @Override
2347 public void nextPage() {
2348 page = 1;
2349 createSecondFrame();
2350 }
32897d73 2351
73844f9c
PT
2352 @Override
2353 public void prevPage() {
2354 page = 0;
2355 createFrame();
2356 }
32897d73 2357
73844f9c
PT
2358 @Override
2359 public void firstPage() {
2360 page = 0;
2361 createFrame();
2362 }
32897d73 2363
73844f9c
PT
2364 @Override
2365 public void lastPage() {
2366 page = 1;
2367 createSecondFrame();
2368 }
2369 //...
2370}
32897d73 2371
73844f9c 2372</pre>
32897d73 2373
73844f9c 2374When running the example application, new actions will be shown in the coolbar and the coolbar menu. <br>
32897d73 2375
73844f9c 2376[[Image:images/PageProviderAdded.png]]
32897d73 2377
73844f9c
PT
2378<br><br>
2379To use the advanced paging provider, the interface ''ISDAdvancePagingProvider'' has to be implemented. It extends the basic paging provider. The methods ''currentPage()'', ''pagesCount()'' and ''pageNumberChanged()'' have to be added.
2380<br>
2381
2382==== Using the Find Provider Interface ====
32897d73 2383
73844f9c
PT
2384For finding nodes in a sequence diagram two interfaces exists. One for basic finding and one for extended finding. The basic find comes with a dialog box for entering find criteria as regular expressions. This find criteria can be used to execute the find. Find criteria a persisted in the Eclipse workspace.
2385<br>
2386For the extended find provider interface a ''org.eclipse.jface.action.Action'' class has to be provided. The actual find handling has to be implemented and triggered by the action.
2387<br>
2388Only on at a time can be active. If the extended find provder is defined it obsoletes the basic find provider.
2389<br>
2390To use the basic find provider, first the interface methods of the ''ISDFindProvider'' have to be implemented by a class. Typically, this is implemented in the loader class. Add the ISDFindProvider to the list of implemented interfaces, implement the methods ''find()'' and ''cancel()'' and set the provider in the ''setViewer()'' method as well as remove the provider in the ''dispose()'' method of the loader class. Please note that the ''ISDFindProvider'' extends the interface ''ISDGraphNodeSupporter'' which methods (''isNodeSupported()'' and ''getNodeName()'') have to be implemented, too. The following shows an example implementation. Please note that only search for lifelines and SynchMessage are supported. The find itself will always find only the first occurrence the pattern to match.
32897d73 2391
73844f9c
PT
2392<pre>
2393public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider {
32897d73 2394
73844f9c
PT
2395 //...
2396 @Override
2397 public void dispose() {
2398 if (fSdView != null) {
2399 fSdView.resetProviders();
2400 }
2401 }
32897d73 2402
73844f9c
PT
2403 @Override
2404 public void setViewer(SDView arg0) {
2405 fSdView = arg0;
2406 fSdView.setSDPagingProvider(this);
2407 fSdView.setSDFindProvider(this);
2408 createFrame();
2409 }
32897d73 2410
73844f9c
PT
2411 @Override
2412 public boolean isNodeSupported(int nodeType) {
2413 switch (nodeType) {
2414 case ISDGraphNodeSupporter.LIFELINE:
2415 case ISDGraphNodeSupporter.SYNCMESSAGE:
2416 return true;
32897d73 2417
73844f9c
PT
2418 default:
2419 break;
2420 }
2421 return false;
2422 }
2423
2424 @Override
2425 public String getNodeName(int nodeType, String loaderClassName) {
2426 switch (nodeType) {
2427 case ISDGraphNodeSupporter.LIFELINE:
2428 return "Lifeline";
2429 case ISDGraphNodeSupporter.SYNCMESSAGE:
2430 return "Sync Message";
2431 }
2432 return "";
2433 }
32897d73 2434
73844f9c
PT
2435 @Override
2436 public boolean find(Criteria criteria) {
2437 Frame frame = fSdView.getFrame();
2438 if (criteria.isLifeLineSelected()) {
2439 for (int i = 0; i < frame.lifeLinesCount(); i++) {
2440 if (criteria.matches(frame.getLifeline(i).getName())) {
2441 fSdView.getSDWidget().moveTo(frame.getLifeline(i));
2442 return true;
2443 }
2444 }
2445 }
2446 if (criteria.isSyncMessageSelected()) {
2447 for (int i = 0; i < frame.syncMessageCount(); i++) {
2448 if (criteria.matches(frame.getSyncMessage(i).getName())) {
2449 fSdView.getSDWidget().moveTo(frame.getSyncMessage(i));
2450 return true;
2451 }
2452 }
2453 }
2454 return false;
2455 }
32897d73 2456
73844f9c
PT
2457 @Override
2458 public void cancel() {
2459 // reset find parameters
2460 }
2461 //...
2462}
2463</pre>
32897d73 2464
73844f9c
PT
2465When running the example application, the find action will be shown in the coolbar and the coolbar menu. <br>
2466[[Image:images/FindProviderAdded.png]]
32897d73 2467
73844f9c
PT
2468To find a sequence diagram node press on the find button of the coolbar (see above). A new dialog box will open. Enter a regular expression in the ''Matching String'' text box, select the node types (e.g. Sync Message) and press '''Find'''. If found the corresponding node will be selected. If not found the dialog box will indicate not found. <br>
2469[[Image:images/FindDialog.png]]<br>
32897d73 2470
73844f9c 2471Note that the find dialog will be opened by typing the key shortcut CRTL+F.
32897d73 2472
73844f9c 2473==== Using the Filter Provider Interface ====
32897d73 2474
73844f9c
PT
2475For filtering of sequence diagram elements two interfaces exists. One basic for filtering and one for extended filtering. The basic filtering comes with two dialog for entering filter criteria as regular expressions and one for selecting the filter to be used. Multiple filters can be active at a time. Filter criteria are persisted in the Eclipse workspace.
2476<br>
2477To use the basic filter provider, first the interface method of the ''ISDFilterProvider'' has to be implemented by a class. Typically, this is implemented in the loader class. Add the ''ISDFilterProvider'' to the list of implemented interfaces, implement the method ''filter()''and set the provider in the ''setViewer()'' method as well as remove the provider in the ''dispose()'' method of the loader class. Please note that the ''ISDFindProvider'' extends the interface ''ISDGraphNodeSupporter'' which methods (''isNodeSupported()'' and ''getNodeName()'') have to be implemented, too. <br>
2478Note that no example implementation of ''filter()'' is provided.
2479<br>
32897d73 2480
73844f9c
PT
2481<pre>
2482public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider, ISDFilterProvider {
32897d73 2483
73844f9c
PT
2484 //...
2485 @Override
2486 public void dispose() {
2487 if (fSdView != null) {
2488 fSdView.resetProviders();
2489 }
2490 }
32897d73 2491
73844f9c
PT
2492 @Override
2493 public void setViewer(SDView arg0) {
2494 fSdView = arg0;
2495 fSdView.setSDPagingProvider(this);
2496 fSdView.setSDFindProvider(this);
2497 fSdView.setSDFilterProvider(this);
2498 createFrame();
2499 }
32897d73 2500
73844f9c
PT
2501 @Override
2502 public boolean filter(List<?> list) {
2503 return false;
2504 }
2505 //...
2506}
2507</pre>
32897d73 2508
73844f9c
PT
2509When running the example application, the filter action will be shown in the coolbar menu. <br>
2510[[Image:images/HidePatternsMenuItem.png]]
32897d73 2511
73844f9c
PT
2512To filter select the '''Hide Patterns...''' of the coolbar menu. A new dialog box will open. <br>
2513[[Image:images/DialogHidePatterns.png]]
32897d73 2514
73844f9c
PT
2515To Add a new filter press '''Add...'''. A new dialog box will open. Enter a regular expression in the ''Matching String'' text box, select the node types (e.g. Sync Message) and press '''Create''''. <br>
2516[[Image:images/DialogHidePatterns.png]] <br>
32897d73 2517
73844f9c 2518Now back at the Hide Pattern dialog. Select one or more filter and select '''OK'''.
32897d73 2519
73844f9c 2520To use the extended filter provider, the interface ''ISDExtendedFilterProvider'' has to be implemented. It will provide a ''org.eclipse.jface.action.Action'' class containing the actual filter handling and filter algorithm.
32897d73 2521
73844f9c 2522==== Using the Extended Action Bar Provider Interface ====
32897d73 2523
73844f9c
PT
2524The extended action bar provider can be used to add customized actions to the Sequence Diagram View.
2525To use the extended action bar provider, first the interface method of the interface ''ISDExtendedActionBarProvider'' has to be implemented by a class. Typically, this is implemented in the loader class. Add the ''ISDExtendedActionBarProvider'' to the list of implemented interfaces, implement the method ''supplementCoolbarContent()'' and set the provider in the ''setViewer()'' method as well as remove the provider in the ''dispose()'' method of the loader class. <br>
32897d73 2526
73844f9c
PT
2527<pre>
2528public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider, ISDFilterProvider, ISDExtendedActionBarProvider {
2529 //...
2530
2531 @Override
2532 public void dispose() {
2533 if (fSdView != null) {
2534 fSdView.resetProviders();
2535 }
2536 }
32897d73 2537
73844f9c
PT
2538 @Override
2539 public void setViewer(SDView arg0) {
2540 fSdView = arg0;
2541 fSdView.setSDPagingProvider(this);
2542 fSdView.setSDFindProvider(this);
2543 fSdView.setSDFilterProvider(this);
2544 fSdView.setSDExtendedActionBarProvider(this);
2545 createFrame();
2546 }
32897d73 2547
73844f9c
PT
2548 @Override
2549 public void supplementCoolbarContent(IActionBars iactionbars) {
2550 Action action = new Action("Refresh") {
2551 @Override
2552 public void run() {
2553 System.out.println("Refreshing...");
2554 }
2555 };
2556 iactionbars.getMenuManager().add(action);
2557 iactionbars.getToolBarManager().add(action);
2558 }
2559 //...
2560}
2561</pre>
32897d73 2562
73844f9c
PT
2563When running the example application, all new actions will be added to the coolbar and coolbar menu according to the implementation of ''supplementCoolbarContent()''<br>.
2564For the example above the coolbar and coolbar menu will look as follows.
32897d73 2565
73844f9c 2566[[Image:images/SupplCoolbar.png]]
32897d73 2567
73844f9c 2568==== Using the Properties Provider Interface====
32897d73 2569
73844f9c 2570This interface can be used to provide property information. A property provider which returns an ''IPropertyPageSheet'' (see ''org.eclipse.ui.views'') has to be implemented and set in the Sequence Diagram View. <br>
32897d73 2571
73844f9c 2572To use the property provider, first the interface method of the ''ISDPropertiesProvider'' has to be implemented by a class. Typically, this is implemented in the loader class. Add the ''ISDPropertiesProvider'' to the list of implemented interfaces, implement the method ''getPropertySheetEntry()'' and set the provider in the ''setViewer()'' method as well as remove the provider in the ''dispose()'' method of the loader class. Please note that no example is provided here.
32897d73 2573
73844f9c
PT
2574Please refer to the following Eclipse articles for more information about properties and tabed properties.
2575*[http://www.eclipse.org/articles/Article-Properties-View/properties-view.html | Take control of your properties]
2576*[http://www.eclipse.org/articles/Article-Tabbed-Properties/tabbed_properties_view.html | The Eclipse Tabbed Properties View]
32897d73 2577
73844f9c 2578==== Using the Collapse Provider Interface ====
32897d73 2579
73844f9c 2580This interface can be used to define a provider which responsibility is to collapse two selected lifelines. This can be used to hide a pair of lifelines.
32897d73 2581
73844f9c 2582To use the collapse provider, first the interface method of the ''ISDCollapseProvider'' has to be implemented by a class. Typically, this is implemented in the loader class. Add the ISDCollapseProvider to the list of implemented interfaces, implement the method ''collapseTwoLifelines()'' and set the provider in the ''setViewer()'' method as well as remove the provider in the ''dispose()'' method of the loader class. Please note that no example is provided here.
32897d73 2583
73844f9c 2584==== Using the Selection Provider Service ====
32897d73 2585
73844f9c 2586The Sequence Diagram View comes with a build in selection provider service. To this service listeners can be added. To use the selection provider service, the interface ''ISelectionListener'' of plug-in ''org.eclipse.ui'' has to implemented. Typically this is implemented in loader class. Firstly, add the ''ISelectionListener'' interface to the list of implemented interfaces, implement the method ''selectionChanged()'' and set the listener in method ''setViewer()'' as well as remove the listener in the ''dispose()'' method of the loader class.
32897d73 2587
73844f9c
PT
2588<pre>
2589public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider, ISDFilterProvider, ISDExtendedActionBarProvider, ISelectionListener {
32897d73 2590
73844f9c
PT
2591 //...
2592 @Override
2593 public void dispose() {
2594 if (fSdView != null) {
2595 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().removePostSelectionListener(this);
2596 fSdView.resetProviders();
2597 }
2598 }
32897d73 2599
73844f9c
PT
2600 @Override
2601 public String getTitleString() {
2602 return "Sample Diagram";
2603 }
32897d73 2604
73844f9c
PT
2605 @Override
2606 public void setViewer(SDView arg0) {
2607 fSdView = arg0;
2608 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().addPostSelectionListener(this);
2609 fSdView.setSDPagingProvider(this);
2610 fSdView.setSDFindProvider(this);
2611 fSdView.setSDFilterProvider(this);
2612 fSdView.setSDExtendedActionBarProvider(this);
32897d73 2613
73844f9c
PT
2614 createFrame();
2615 }
32897d73 2616
73844f9c
PT
2617 @Override
2618 public void selectionChanged(IWorkbenchPart part, ISelection selection) {
2619 ISelection sel = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
2620 if (sel != null && (sel instanceof StructuredSelection)) {
2621 StructuredSelection stSel = (StructuredSelection) sel;
2622 if (stSel.getFirstElement() instanceof BaseMessage) {
2623 BaseMessage syncMsg = ((BaseMessage) stSel.getFirstElement());
2624 System.out.println("Message '" + syncMsg.getName() + "' selected.");
2625 }
2626 }
2627 }
2628
2629 //...
2630}
2631</pre>
32897d73 2632
73844f9c 2633=== Printing a Sequence Diagram ===
32897d73 2634
73844f9c 2635To print a the whole sequence diagram or only parts of it, select the Sequence Diagram View and select '''File -> Print...''' or type the key combination ''CTRL+P''. A new print dialog will open. <br>
32897d73 2636
73844f9c 2637[[Image:images/PrintDialog.png]] <br>
32897d73 2638
73844f9c 2639Fill in all the relevant information, select '''Printer...''' to choose the printer and the press '''OK'''.
32897d73 2640
73844f9c 2641=== Using one Sequence Diagram View with Multiple Loaders ===
32897d73 2642
73844f9c 2643A Sequence Diagram View definition can be used with multiple sequence diagram loaders. However, the active loader to be used when opening the view has to be set. For this define an Eclipse action or command and assign the current loader to the view. Here is a code snippet for that:
32897d73 2644
73844f9c
PT
2645<pre>
2646public class OpenSDView extends AbstractHandler {
2647 @Override
2648 public Object execute(ExecutionEvent event) throws ExecutionException {
2649 try {
2650 IWorkbenchPage persp = TmfUiPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
2651 SDView view = (SDView) persp.showView("org.eclipse.linuxtools.ust.examples.ui.componentinteraction");
2652 LoadersManager.getLoadersManager().createLoader("org.eclipse.linuxtools.tmf.ui.views.uml2sd.impl.TmfUml2SDSyncLoader", view);
2653 } catch (PartInitException e) {
2654 throw new ExecutionException("PartInitException caught: ", e);
2655 }
2656 return null;
2657 }
2658}
2659</pre>
32897d73 2660
73844f9c 2661=== Downloading the Tutorial ===
32897d73 2662
73844f9c 2663Use the following link to download the source code of the tutorial [http://wiki.eclipse.org/images/e/e6/SamplePlugin.zip Plug-in of Tutorial].
32897d73 2664
73844f9c 2665== Integration of Tracing and Monitoring Framework with Sequence Diagram Framework ==
32897d73 2666
73844f9c 2667In the previous sections the Sequence Diagram Framework has been described and a tutorial was provided. In the following sections the integration of the Sequence Diagram Framework with other features of TMF will be described. Together it is a powerful framework to analyze and visualize content of traces. The integration is explained using the reference implementation of a UML2 sequence diagram loader which part of the TMF UI delivery. The reference implementation can be used as is, can be sub-classed or simply be an example for other sequence diagram loaders to be implemented.
32897d73 2668
73844f9c 2669=== Reference Implementation ===
32897d73 2670
73844f9c 2671A Sequence Diagram View Extension is defined in the plug-in TMF UI as well as a uml2SDLoader Extension with the reference loader.
32897d73 2672
73844f9c 2673[[Image:images/ReferenceExtensions.png]]
32897d73 2674
73844f9c 2675=== Used Sequence Diagram Features ===
32897d73 2676
73844f9c
PT
2677Besides the default features of the Sequence Diagram Framework, the reference implementation uses the following additional features:
2678*Advanced paging
2679*Basic finding
2680*Basic filtering
2681*Selection Service
32897d73 2682
73844f9c 2683==== Advanced paging ====
32897d73 2684
73844f9c 2685The reference loader implements the interface ''ISDAdvancedPagingProvider'' interface. Please refer to section [[#Using the Paging Provider Interface | Using the Paging Provider Interface]] for more details about the advanced paging feature.
32897d73 2686
73844f9c 2687==== Basic finding ====
32897d73 2688
73844f9c 2689The reference loader implements the interface ''ISDFindProvider'' interface. The user can search for ''Lifelines'' and ''Interactions''. The find is done across pages. If the expression to match is not on the current page a new thread is started to search on other pages. If expression is found the corresponding page is shown as well as the searched item is displayed. If not found then a message is displayed in the ''Progress View'' of Eclipse. Please refer to section [[#Using the Find Provider Interface | Using the Find Provider Interface]] for more details about the basic find feature.
32897d73 2690
73844f9c 2691==== Basic filtering ====
32897d73 2692
73844f9c 2693The reference loader implements the interface ''ISDFilterProvider'' interface. The user can filter on ''Lifelines'' and ''Interactions''. Please refer to section [[#Using the Filter Provider Interface | Using the Filter Provider Interface]] for more details about the basic filter feature.
32897d73 2694
73844f9c 2695==== Selection Service ====
32897d73 2696
73844f9c 2697The reference loader implements the interface ''ISelectionListener'' interface. When an interaction is selected a ''TmfTimeSynchSignal'' is broadcast (see [[#TMF Signal Framework | TMF Signal Framework]]). Please also refer to section [[#Using the Selection Provider Service | Using the Selection Provider Service]] for more details about the selection service and .
32897d73 2698
73844f9c 2699=== Used TMF Features ===
32897d73 2700
73844f9c
PT
2701The reference implementation uses the following features of TMF:
2702*TMF Experiment and Trace for accessing traces
2703*Event Request Framework to request TMF events from the experiment and respective traces
2704*Signal Framework for broadcasting and receiving TMF signals for synchronization purposes
32897d73 2705
73844f9c 2706==== TMF Experiment and Trace for accessing traces ====
32897d73 2707
73844f9c 2708The reference loader uses TMF Experiments to access traces and to request data from the traces.
32897d73 2709
73844f9c 2710==== TMF Event Request Framework ====
32897d73 2711
73844f9c 2712The reference loader use the TMF Event Request Framework to request events from the experiment and its traces.
32897d73 2713
73844f9c 2714When opening a traces (which is triggered by signal ''TmfExperimentSelected'') or when opening the Sequence Diagram View after a trace had been opened previously, a TMF background request is initiated to index the trace and to fill in the first page of the sequence diagram. The purpose of the indexing is to store time ranges for pages with 10000 messages per page. This allows quickly to move to certain pages in a trace without having to re-parse from the beginning. The request is called indexing request.
32897d73 2715
73844f9c 2716When switching pages, the a TMF foreground event request is initiated to retrieve the corresponding events from the experiment. It uses the time range stored in the index for the respective page.
32897d73 2717
73844f9c 2718A third type of event request is issued for finding specific data across pages.
32897d73 2719
73844f9c 2720==== TMF Signal Framework ====
32897d73 2721
73844f9c
PT
2722The reference loader extends the class ''TmfComponent''. By doing that the loader is register as TMF signal handler for sending and receiving TMF signals. The loader implements signal handlers for the following TMF signals:
2723*''TmfTraceSelectedSignal''
2724This signal indicates that a trace or experiment was selected. When receiving this signal the indexing request is initiated and the first page is displayed after receiving the relevant information.
2725*''traceClosed''
2726This signal indicates that a trace or experiment was closed. When receiving this signal the loader resets its data and a blank page is loaded in the Sequence Diagram View.
2727*''TmfTimeSynchSignal''
2728This signal indicates that a event with a certain timestamp is selected. When receiving this signal the corresponding message is selected in the Sequence Diagram View. If necessary, the page is changed.
2729*''TmfRangeSynchSignal''
2730This signal indicates that a new time range is in focus. When receiving this signal the loader loads the page which corresponds to the start time of the time range signal. The message with the start time will be in focus.
32897d73 2731
73844f9c 2732Besides acting on receiving signals, the reference loader is also sending signals. A ''TmfTimeSynchSignal'' is broadcasted with the timestamp of the message which was selected in the Sequence Diagram View. ''TmfRangeSynchSignal'' is sent when a page is changed in the Sequence Diagram View. The start timestamp of the time range sent is the timestamp of the first message. The end timestamp sent is the timestamp of the first message plus the current time range window. The current time range window is the time window that was indicated in the last received ''TmfRangeSynchSignal''.
32897d73 2733
73844f9c 2734=== Supported Traces ===
32897d73 2735
73844f9c 2736The reference implementation is able to analyze traces from a single component that traces the interaction with other components. For example, a server node could have trace information about its interaction with client nodes. The server node could be traced and then analyzed using TMF and the Sequence Diagram Framework of TMF could used to visualize the interactions with the client nodes.<br>
32897d73 2737
73844f9c 2738Note that combined traces of multiple components, that contain the trace information about the same interactions are not supported in the reference implementation!
32897d73 2739
73844f9c 2740=== Trace Format ===
32897d73 2741
73844f9c 2742The reference implementation in class ''TmfUml2SDSyncLoader'' in package ''org.eclipse.linuxtools.tmf.ui.views.uml2sd.impl'' analyzes events from type ''ITmfEvent'' and creates events type ''ITmfSyncSequenceDiagramEvent'' if the ''ITmfEvent'' contains all relevant information information. The parsing algorithm looks like as follows:
32897d73 2743
73844f9c
PT
2744<pre>
2745 /**
2746 * @param tmfEvent Event to parse for sequence diagram event details
2747 * @return sequence diagram event if details are available else null
2748 */
2749 protected ITmfSyncSequenceDiagramEvent getSequenceDiagramEvent(ITmfEvent tmfEvent){
2750 //type = .*RECEIVE.* or .*SEND.*
2751 //content = sender:<sender name>:receiver:<receiver name>,signal:<signal name>
2752 String eventType = tmfEvent.getType().toString();
2753 if (eventType.contains(Messages.TmfUml2SDSyncLoader_EventTypeSend) || eventType.contains(Messages.TmfUml2SDSyncLoader_EventTypeReceive)) {
2754 Object sender = tmfEvent.getContent().getField(Messages.TmfUml2SDSyncLoader_FieldSender);
2755 Object receiver = tmfEvent.getContent().getField(Messages.TmfUml2SDSyncLoader_FieldReceiver);
2756 Object name = tmfEvent.getContent().getField(Messages.TmfUml2SDSyncLoader_FieldSignal);
2757 if ((sender instanceof ITmfEventField) && (receiver instanceof ITmfEventField) && (name instanceof ITmfEventField)) {
2758 ITmfSyncSequenceDiagramEvent sdEvent = new TmfSyncSequenceDiagramEvent(tmfEvent,
2759 ((ITmfEventField) sender).getValue().toString(),
2760 ((ITmfEventField) receiver).getValue().toString(),
2761 ((ITmfEventField) name).getValue().toString());
32897d73 2762
73844f9c
PT
2763 return sdEvent;
2764 }
2765 }
2766 return null;
32897d73 2767 }
32897d73
AM
2768</pre>
2769
73844f9c 2770The analysis looks for event type Strings containing ''SEND'' and ''RECEIVE''. If event type matches these key words, the analyzer will look for strings ''sender'', ''receiver'' and ''signal'' in the event fields of type ''ITmfEventField''. If all the data is found a sequence diagram event from can be created. Note that Sync Messages are assumed, which means start and end time are the same.
32897d73 2771
73844f9c 2772=== How to use the Reference Implementation ===
32897d73 2773
73844f9c
PT
2774An example trace visualizer is provided that uses a trace in binary format. It contains trace events with sequence diagram information. To parse the data using TMF a class is provided that implements ''ITmfTrace''. Additionally, a parser is provided that reads from the file and converts a trace event to ''TmfEvent''. This parser implements the interface ''ITmfEventParser''. To get the source code see [[#Downloading the Reference Plug-in | Download the Reference Plug-in]]
2775<br>
2776The plug-in structure will look like this:<br>
2777[[Image:images/ReferencePlugin.png]]<br>
32897d73 2778
73844f9c
PT
2779To open the plug-in manifest, double-click on the MANIFEST.MF file. <br>
2780[[Image:images/SelectManifestRef.png]]<br>
32897d73 2781
73844f9c
PT
2782Run the Reference Application. To launch the Eclipse Application select the ''Overview'' tab and click on '''Launch an Eclipse Application'''<br>
2783[[Image:images/RunApplicationRef.png]]<br>
32897d73 2784
73844f9c
PT
2785To open the Reference Sequence Diagram View, select '''Windows -> Show View -> Other... -> TMF -> Sequence Diagram''' <br>
2786[[Image:images/ShowTmfSDView.png]]<br>
32897d73 2787
73844f9c 2788An blank Sequence Diagram View will open.
32897d73 2789
73844f9c
PT
2790Select the '''Select Experiment''' button of the toolbar to load the sequence diagram from the data provided in the trace file. What this does is open the file ''tracesets/sdEvents'', parse this file through TMF and analyze all events of type ''TmfEvent'' and generates the Sequence Diagram out of it. <br>
2791[[Image:images/ReferenceSeqDiagram.png]]<br>
32897d73 2792
73844f9c
PT
2793Now the reference application can be explored. To demonstrate the view features try the following things:
2794*Select a message in the Sequence diagram. As result the corresponding event will be selected in the Events View.
2795*Select an event in the Events View. As result the corresponding message in the Sequence Diagram View will be selected. If necessary, the page will be changed.
2796*In the Events View, press key ''End''. As result, the Sequence Diagram view will jump to the last page.
2797*In the Events View, press key ''Home''. As result, the Sequence Diagram view will jump to the first page.
2798*In the Sequence Diagram View select the find button. Enter the expression '''REGISTER.*''', select '''Search for Interaction''' and press '''Find'''. As result the corresponding message will be selected in the Sequence Diagram and the corresponding event in the Events View will be selected. Select again '''Find''' the next occurrence of will be selected. Since the second occurrence is on a different page than the first, the corresponding page will be loaded.
2799* In the Sequence Diagram View, select menu item '''Hide Patterns...'''. Add the filter '''BALL.*''' for '''Interaction''' only and select '''OK'''. As result all messages with name ''BALL_REQUEST'' and ''BALL_REPLY'' will be hidden. To remove the filter, select menu item '''Hide Patterns...''', deselect the corresponding filter and press '''OK'''. All the messages will be shown again.<br>
2800
2801To dispose the diagram, select the '''Dispose Experiment''' button of the toolbar. The current sequence diagram will be disposed and an empty diagram will be loaded.
32897d73 2802
73844f9c 2803=== Extending the Reference Loader ===
32897d73 2804
73844f9c 2805In some case it might be necessary to change the implementation of the analysis of each ''TmfEvent'' for the generation of ''Sequence Diagram Events''. For that just extend the class ''TmfUml2SDSyncLoader'' and overwrite the method ''protected ITmfSyncSequenceDiagramEvent getSequnceDiagramEvent(TmfEvent tmfEvent)'' with your own implementation.
32897d73 2806
73844f9c
PT
2807=== Downloading the Reference Plug-in ===
2808To download the reference plug-in that demonstrates the reference loader, use the following link: [http://wiki.eclipse.org/images/d/d3/ReferencePlugin.zip Reference Plug-in]. Just extract the zip file and import the extracted Eclipse plug-in (plug-in name: ''org.eclipse.linuxtools.tmf.reference.ui'') to your Eclipse workspace. <br>
32897d73 2809
73844f9c 2810= CTF Parser =
32897d73 2811
73844f9c
PT
2812== CTF Format ==
2813CTF is a format used to store traces. It is self defining, binary and made to be easy to write to.
2814Before going further, the full specification of the CTF file format can be found at http://www.efficios.com/ .
32897d73 2815
73844f9c 2816For the purpose of the reader some basic description will be given. A CTF trace typically is made of several files all in the same folder.
32897d73 2817
73844f9c
PT
2818These files can be split into two types :
2819* Metadata
2820* Event streams
32897d73 2821
73844f9c
PT
2822=== Metadata ===
2823The metadata is either raw text or packetized text. It is tsdl encoded. it contains a description of the type of data in the event streams. It can grow over time if new events are added to a trace but it will never overwrite what is already there.
32897d73 2824
73844f9c
PT
2825=== Event Streams ===
2826The event streams are a file per stream per cpu. These streams are binary and packet based. The streams store events and event information (ie lost events) The event data is stored in headers and field payloads.
32897d73 2827
73844f9c 2828So if you have two streams (channels) "channel1" and "channel2" and 4 cores, you will have the following files in your trace directory: "channel1_0" , "channel1_1" , "channel1_2" , "channel1_3" , "channel2_0" , "channel2_1" , "channel2_2" & "channel2_3"
32897d73 2829
73844f9c
PT
2830== Reading a trace ==
2831In order to read a CTF trace, two steps must be done.
2832* The metadata must be read to know how to read the events.
2833* the events must be read.
32897d73 2834
73844f9c 2835The metadata is a written in a subset of the C language called TSDL. To read it, first it is depacketized (if it is not in plain text) then the raw text is parsed by an antlr grammer. The parsing is done in two phases. There is a lexer (CTFLexer.g) which separated the metatdata text into tokens. The tokens are then pattern matched using the parser (CTFParser.g) to form an AST. This AST is walked through using "IOStructGen.java" to populate streams and traces in trace parent object.
32897d73 2836
73844f9c
PT
2837When the metadata is loaded and read, the trace object will be populated with 3 items:
2838* the event definitions available per stream: a definition is a description of the datatype.
2839* the event declarations available per stream: this will save declaration creation on a per event basis. They will all be created in advance, just not populated.
2840* the beginning of a packet index.
32897d73 2841
73844f9c 2842Now all the trace readers for the event streams have everything they need to read a trace. They will each point to one file, and read the file from packet to packet. Everytime the trace reader changes packet, the index is updated with the new packet's information. The readers are in a priority queue and sorted by timestamp. This ensures that the events are read in a sequential order. They are also sorted by file name so that in the eventuality that two events occur at the same time, they stay in the same order.
32897d73 2843
73844f9c
PT
2844== Seeking in a trace ==
2845The reason for maintaining an index is to speed up seeks. In the case that a user wishes to seek to a certain timestamp, they just have to find the index entry that contains the timestamp, and go there to iterate in that packet until the proper event is found. this will reduce the searches time by an order of 8000 for a 256k paket size (kernel default).
32897d73 2846
73844f9c
PT
2847== Interfacing to TMF ==
2848The trace can be read easily now but the data is still awkward to extract.
32897d73 2849
73844f9c
PT
2850=== CtfLocation ===
2851A location in a given trace, it is currently the timestamp of a trace and the index of the event. The index shows for a given timestamp if it is the first second or nth element.
32897d73 2852
73844f9c
PT
2853=== CtfTmfTrace ===
2854The CtfTmfTrace is a wrapper for the standard CTF trace that allows it to perform the following actions:
2855* '''initTrace()''' create a trace
2856* '''validateTrace()''' is the trace a CTF trace?
2857* '''getLocationRatio()''' how far in the trace is my location?
2858* '''seekEvent()''' sets the cursor to a certain point in a trace.
2859* '''readNextEvent()''' reads the next event and then advances the cursor
2860* '''getTraceProperties()''' gets the 'env' structures of the metadata
2861
2862=== CtfIterator ===
2863The CtfIterator is a wrapper to the CTF file reader. It behaves like an iterator on a trace. However, it contains a file pointer and thus cannot be duplicated too often or the system will run out of file handles. To alleviate the situation, a pool of iterators is created at the very beginning and stored in the CtfTmfTrace. They can be retried by calling the GetIterator() method.
2864
2865=== CtfIteratorManager ===
2866Since each CtfIterator will have a file reader, the OS will run out of handles if too many iterators are spawned. The solution is to use the iterator manager. This will allow the user to get an iterator. If there is a context at the requested position, the manager will return that one, if not, a context will be selected at random and set to the correct location. Using random replacement minimizes contention as it will settle quickly at a new balance point.
2867
2868=== CtfTmfContext ===
2869The CtfTmfContext implements the ITmfContext type. It is the CTF equivalent of TmfContext. It has a CtfLocation and points to an iterator in the CtfTmfTrace iterator pool as well as the parent trace. it is made to be cloned easily and not affect system resources much. Contexts behave much like C file pointers (FILE*) but they can be copied until one runs out of RAM.
2870
2871=== CtfTmfTimestamp ===
2872The CtfTmfTimestamp take a CTF time (normally a long int) and outputs the time formats it as a TmfTimestamp, allowing it to be compared to other timestamps. The time is stored with the UTC offset already applied. It also features a simple toString() function that allows it to output the time in more Human readable ways: "yyyy/mm/dd/hh:mm:ss.nnnnnnnnn ns" for example. An additional feature is the getDelta() function that allows two timestamps to be substracted, showing the time difference between A and B.
2873
2874=== CtfTmfEvent ===
2875The CtfTmfEvent is an ITmfEvent that is used to wrap event declarations and event definitions from the CTF side into easier to read and parse chunks of information. It is a final class with final fields made to be newed very often without incurring performance costs. Most of the information is already available. It should be noted that one type of event can appear called "lost event" these are synthetic events that do not exist in the trace. They will not appear in other trace readers such as babeltrace.
2876
2877=== Other ===
2878There are other helper files that format given events for views, they are simpler and the architecture does not depend on them.
2879
2880=== Limitations ===
2881For the moment live trace reading is not supported, there are no sources of traces to test on.
32897d73 2882
This page took 0.263342 seconds and 5 git commands to generate.