Lttng: Attempt to resolve SWTBot test failure.
[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
f2072ab5 406The tutorial is based on Eclipse 4.4 (Eclipse Luna), TMF 3.0.0 and SWTChart 0.7.0. If you are using TMF from the source repository, SWTChart is already included in the target definition file (see org.eclipse.linuxtools.lttng.target). You can also install it manually 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 539 TmfEventRequest req = new TmfEventRequest(TmfEvent.class,
f2072ab5
MAL
540 TmfTimeRange.ETERNITY, 0, ITmfEventRequest.ALL_DATA,
541 ITmfEventRequest.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,
f2072ab5
MAL
572 TmfTimeRange.ETERNITY, 0, ITmfEventRequest.ALL_DATA,
573 ITmfEventRequest.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
421b90a1
BH
917This signal is used to indicate that a new time or time range has been
918selected. It contains a begin and end time. If a single time is selected then
919the begin and end time are the same.
067490ab 920
73844f9c 921''Senders''
067490ab 922
421b90a1 923Sent by any component that allows the user to select a time or time range.
067490ab 924
73844f9c 925''Receivers''
067490ab 926
421b90a1 927Received by any component that needs to be notified of the currently selected time or time range.
067490ab 928
73844f9c 929=== TmfRangeSynchSignal ===
067490ab 930
73844f9c 931''Purpose''
067490ab 932
73844f9c 933This signal is used to indicate that a new time range window has been set.
067490ab 934
73844f9c 935''Senders''
067490ab 936
73844f9c 937Sent by any component that allows the user to set a time range window.
067490ab 938
73844f9c 939''Receivers''
067490ab 940
73844f9c 941Received by any component that needs to be notified of the current visible time range window.
067490ab 942
73844f9c 943=== TmfEventFilterAppliedSignal ===
067490ab 944
73844f9c 945''Purpose''
067490ab 946
73844f9c 947This signal is used to indicate that a filter has been applied to a trace.
067490ab 948
73844f9c 949''Senders''
067490ab 950
73844f9c 951Sent by TmfEventsTable when a filter is applied.
067490ab 952
73844f9c 953''Receivers''
067490ab 954
73844f9c 955Received by any component that shows trace data and needs to be notified of applied filters.
067490ab 956
73844f9c 957=== TmfEventSearchAppliedSignal ===
067490ab 958
73844f9c 959''Purpose''
067490ab 960
73844f9c 961This signal is used to indicate that a search has been applied to a trace.
067490ab 962
73844f9c 963''Senders''
067490ab 964
73844f9c 965Sent by TmfEventsTable when a search is applied.
067490ab 966
73844f9c 967''Receivers''
067490ab 968
73844f9c 969Received by any component that shows trace data and needs to be notified of applied searches.
067490ab 970
73844f9c 971=== TmfTimestampFormatUpdateSignal ===
067490ab 972
73844f9c 973''Purpose''
067490ab 974
73844f9c 975This signal is used to indicate that the timestamp format preference has been updated.
067490ab 976
73844f9c 977''Senders''
067490ab 978
73844f9c 979Sent by TmfTimestampFormat when the default timestamp format preference is changed.
067490ab 980
73844f9c 981''Receivers''
067490ab 982
73844f9c 983Received by any component that needs to refresh its display for the new timestamp format.
067490ab 984
73844f9c 985=== TmfStatsUpdatedSignal ===
067490ab 986
73844f9c 987''Purpose''
067490ab 988
73844f9c 989This signal is used to indicate that the statistics data model has been updated.
067490ab 990
73844f9c 991''Senders''
067490ab 992
73844f9c 993Sent by statistic providers when new statistics data has been processed.
067490ab 994
73844f9c 995''Receivers''
067490ab 996
73844f9c 997Received by statistics viewers and any component that needs to be notified of a statistics update.
067490ab 998
2c20bbb3
VP
999=== TmfPacketStreamSelected ===
1000
1001''Purpose''
1002
1003This signal is used to indicate that the user has selected a packet stream to analyze.
1004
1005''Senders''
1006
1007Sent by the Stream List View when the user selects a new packet stream.
1008
1009''Receivers''
1010
1011Received by views that analyze packet streams.
1012
73844f9c 1013== Debugging ==
067490ab 1014
73844f9c 1015TMF 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 1016
73844f9c 1017All signals sent and received will be logged to the file TmfTrace.log located in the Eclipse home directory.
067490ab 1018
73844f9c 1019= Generic State System =
067490ab 1020
73844f9c 1021== Introduction ==
067490ab 1022
73844f9c
PT
1023The Generic State System is a utility available in TMF to track different states
1024over the duration of a trace. It works by first sending some or all events of
1025the trace into a state provider, which defines the state changes for a given
1026trace type. Once built, views and analysis modules can then query the resulting
1027database of states (called "state history") to get information.
067490ab 1028
73844f9c
PT
1029For example, let's suppose we have the following sequence of events in a kernel
1030trace:
067490ab 1031
73844f9c
PT
1032 10 s, sys_open, fd = 5, file = /home/user/myfile
1033 ...
1034 15 s, sys_read, fd = 5, size=32
1035 ...
1036 20 s, sys_close, fd = 5
067490ab 1037
73844f9c 1038Now let's say we want to implement an analysis module which will track the
2c20bbb3 1039amount of bytes read and written to each file. Here, of course the sys_read is
73844f9c
PT
1040interesting. However, by just looking at that event, we have no information on
1041which file is being read, only its fd (5) is known. To get the match
1042fd5 = /home/user/myfile, we have to go back to the sys_open event which happens
10435 seconds earlier.
067490ab 1044
73844f9c
PT
1045But since we don't know exactly where this sys_open event is, we will have to go
1046back to the very start of the trace, and look through events one by one! This is
1047obviously not efficient, and will not scale well if we want to analyze many
1048similar patterns, or for very large traces.
067490ab 1049
73844f9c
PT
1050A solution in this case would be to use the state system to keep track of the
1051amount of bytes read/written to every *filename* (instead of every file
1052descriptor, like we get from the events). Then the module could ask the state
1053system "what is the amount of bytes read for file "/home/user/myfile" at time
105416 s", and it would return the answer "32" (assuming there is no other read
1055than the one shown).
067490ab 1056
73844f9c 1057== High-level components ==
067490ab 1058
73844f9c
PT
1059The State System infrastructure is composed of 3 parts:
1060* The state provider
1061* The central state system
1062* The storage backend
067490ab 1063
73844f9c
PT
1064The state provider is the customizable part. This is where the mapping from
1065trace events to state changes is done. This is what you want to implement for
1066your specific trace type and analysis type. It's represented by the
1067ITmfStateProvider interface (with a threaded implementation in
1068AbstractTmfStateProvider, which you can extend).
067490ab 1069
73844f9c
PT
1070The core of the state system is exposed through the ITmfStateSystem and
1071ITmfStateSystemBuilder interfaces. The former allows only read-only access and
1072is typically used for views doing queries. The latter also allows writing to the
1073state history, and is typically used by the state provider.
067490ab 1074
73844f9c
PT
1075Finally, each state system has its own separate backend. This determines how the
1076intervals, or the "state history", are saved (in RAM, on disk, etc.) You can
1077select the type of backend at construction time in the TmfStateSystemFactory.
067490ab 1078
73844f9c 1079== Definitions ==
067490ab 1080
73844f9c
PT
1081Before we dig into how to use the state system, we should go over some useful
1082definitions:
067490ab 1083
73844f9c 1084=== Attribute ===
067490ab 1085
73844f9c
PT
1086An attribute is the smallest element of the model that can be in any particular
1087state. When we refer to the "full state", in fact it means we are interested in
1088the state of every single attribute of the model.
067490ab 1089
73844f9c 1090=== Attribute Tree ===
067490ab 1091
73844f9c
PT
1092Attributes in the model can be placed in a tree-like structure, a bit like files
1093and directories in a file system. However, note that an attribute can always
1094have both a value and sub-attributes, so they are like files and directories at
1095the same time. We are then able to refer to every single attribute with its
1096path in the tree.
067490ab 1097
73844f9c
PT
1098For example, in the attribute tree for LTTng kernel traces, we use the following
1099attributes, among others:
067490ab 1100
73844f9c
PT
1101<pre>
1102|- Processes
1103| |- 1000
1104| | |- PPID
1105| | |- Exec_name
1106| |- 1001
1107| | |- PPID
1108| | |- Exec_name
1109| ...
1110|- CPUs
1111 |- 0
1112 | |- Status
1113 | |- Current_pid
1114 ...
1115</pre>
067490ab 1116
73844f9c
PT
1117In this model, the attribute "Processes/1000/PPID" refers to the PPID of process
1118with PID 1000. The attribute "CPUs/0/Status" represents the status (running,
1119idle, etc.) of CPU 0. "Processes/1000/PPID" and "Processes/1001/PPID" are two
1120different attribute, even though their base name is the same: the whole path is
1121the unique identifier.
067490ab 1122
73844f9c
PT
1123The value of each attribute can change over the duration of the trace,
1124independently of the other ones, and independently of its position in the tree.
067490ab 1125
73844f9c
PT
1126The tree-like organization is optional, all attributes could be at the same
1127level. But it's possible to put them in a tree, and it helps make things
1128clearer.
067490ab 1129
73844f9c 1130=== Quark ===
067490ab 1131
73844f9c
PT
1132In addition to a given path, each attribute also has a unique integer
1133identifier, called the "quark". To continue with the file system analogy, this
1134is like the inode number. When a new attribute is created, a new unique quark
1135will be assigned automatically. They are assigned incrementally, so they will
1136normally be equal to their order of creation, starting at 0.
067490ab 1137
73844f9c
PT
1138Methods are offered to get the quark of an attribute from its path. The API
1139methods for inserting state changes and doing queries normally use quarks
1140instead of paths. This is to encourage users to cache the quarks and re-use
1141them, which avoids re-walking the attribute tree over and over, which avoids
1142unneeded hashing of strings.
067490ab 1143
73844f9c 1144=== State value ===
067490ab 1145
73844f9c
PT
1146The path and quark of an attribute will remain constant for the whole duration
1147of the trace. However, the value carried by the attribute will change. The value
1148of a specific attribute at a specific time is called the state value.
067490ab 1149
7d59bbef 1150In the TMF implementation, state values can be integers, longs, doubles, or strings.
73844f9c
PT
1151There is also a "null value" type, which is used to indicate that no particular
1152value is active for this attribute at this time, but without resorting to a
1153'null' reference.
067490ab 1154
73844f9c
PT
1155Any other type of value could be used, as long as the backend knows how to store
1156it.
067490ab 1157
73844f9c
PT
1158Note that the TMF implementation also forces every attribute to always carry the
1159same type of state value. This is to make it simpler for views, so they can
1160expect that an attribute will always use a given type, without having to check
1161every single time. Null values are an exception, they are always allowed for all
1162attributes, since they can safely be "unboxed" into all types.
067490ab 1163
73844f9c 1164=== State change ===
067490ab 1165
73844f9c
PT
1166A state change is the element that is inserted in the state system. It consists
1167of:
1168* a timestamp (the time at which the state change occurs)
1169* an attribute (the attribute whose value will change)
1170* a state value (the new value that the attribute will carry)
067490ab 1171
73844f9c
PT
1172It's not an object per se in the TMF implementation (it's represented by a
1173function call in the state provider). Typically, the state provider will insert
1174zero, one or more state changes for every trace event, depending on its event
1175type, payload, etc.
067490ab 1176
73844f9c
PT
1177Note, we use "timestamp" here, but it's in fact a generic term that could be
1178referred to as "index". For example, if a given trace type has no notion of
1179timestamp, the event rank could be used.
067490ab 1180
73844f9c 1181In the TMF implementation, the timestamp is a long (64-bit integer).
067490ab 1182
73844f9c 1183=== State interval ===
067490ab 1184
73844f9c
PT
1185State changes are inserted into the state system, but state intervals are the
1186objects that come out on the other side. Those are stocked in the storage
1187backend. A state interval represents a "state" of an attribute we want to track.
1188When doing queries on the state system, intervals are what is returned. The
1189components of a state interval are:
1190* Start time
1191* End time
1192* State value
1193* Quark
067490ab 1194
73844f9c
PT
1195The start and end times represent the time range of the state. The state value
1196is the same as the state value in the state change that started this interval.
1197The interval also keeps a reference to its quark, although you normally know
1198your quark in advance when you do queries.
f5b8868d 1199
73844f9c 1200=== State history ===
f5b8868d 1201
73844f9c
PT
1202The state history is the name of the container for all the intervals created by
1203the state system. The exact implementation (how the intervals are stored) is
1204determined by the storage backend that is used.
f5b8868d 1205
73844f9c
PT
1206Some backends will use a state history that is peristent on disk, others do not.
1207When loading a trace, if a history file is available and the backend supports
1208it, it will be loaded right away, skipping the need to go through another
1209construction phase.
f5b8868d 1210
73844f9c 1211=== Construction phase ===
f5b8868d 1212
73844f9c
PT
1213Before we can query a state system, we need to build the state history first. To
1214do so, trace events are sent one-by-one through the state provider, which in
1215turn sends state changes to the central component, which then creates intervals
1216and stores them in the backend. This is called the construction phase.
f5b8868d 1217
73844f9c
PT
1218Note that the state system needs to receive its events into chronological order.
1219This phase will end once the end of the trace is reached.
f5b8868d 1220
73844f9c
PT
1221Also note that it is possible to query the state system while it is being build.
1222Any timestamp between the start of the trace and the current end time of the
1223state system (available with ITmfStateSystem#getCurrentEndTime()) is a valid
1224timestamp that can be queried.
f5b8868d 1225
73844f9c 1226=== Queries ===
f5b8868d 1227
73844f9c
PT
1228As mentioned previously, when doing queries on the state system, the returned
1229objects will be state intervals. In most cases it's the state *value* we are
1230interested in, but since the backend has to instantiate the interval object
1231anyway, there is no additional cost to return the interval instead. This way we
1232also get the start and end times of the state "for free".
f5b8868d 1233
73844f9c 1234There are two types of queries that can be done on the state system:
f5b8868d 1235
73844f9c 1236==== Full queries ====
f5b8868d 1237
73844f9c
PT
1238A full query means that we want to retrieve the whole state of the model for one
1239given timestamp. As we remember, this means "the state of every single attribute
1240in the model". As parameter we only need to pass the timestamp (see the API
1241methods below). The return value will be an array of intervals, where the offset
1242in the array represents the quark of each attribute.
f5b8868d 1243
73844f9c 1244==== Single queries ====
f5b8868d 1245
73844f9c
PT
1246In other cases, we might only be interested in the state of one particular
1247attribute at one given timestamp. For these cases it's better to use a
1248single query. For a single query. we need to pass both a timestamp and a
1249quark in parameter. The return value will be a single interval, representing
1250the state that this particular attribute was at that time.
f5b8868d 1251
73844f9c
PT
1252Single queries are typically faster than full queries (but once again, this
1253depends on the backend that is used), but not by much. Even if you only want the
1254state of say 10 attributes out of 200, it could be faster to use a full query
1255and only read the ones you need. Single queries should be used for cases where
1256you only want one attribute per timestamp (for example, if you follow the state
1257of the same attribute over a time range).
f5b8868d 1258
f5b8868d 1259
73844f9c 1260== Relevant interfaces/classes ==
f5b8868d 1261
73844f9c
PT
1262This section will describe the public interface and classes that can be used if
1263you want to use the state system.
f5b8868d 1264
73844f9c 1265=== Main classes in org.eclipse.linuxtools.tmf.core.statesystem ===
f5b8868d 1266
73844f9c 1267==== ITmfStateProvider / AbstractTmfStateProvider ====
f5b8868d 1268
73844f9c
PT
1269ITmfStateProvider is the interface you have to implement to define your state
1270provider. This is where most of the work has to be done to use a state system
1271for a custom trace type or analysis type.
f5b8868d 1272
73844f9c
PT
1273For first-time users, it's recommended to extend AbstractTmfStateProvider
1274instead. This class takes care of all the initialization mumbo-jumbo, and also
1275runs the event handler in a separate thread. You will only need to implement
1276eventHandle, which is the call-back that will be called for every event in the
1277trace.
f5b8868d 1278
73844f9c
PT
1279For an example, you can look at StatsStateProvider in the TMF tree, or at the
1280small example below.
f5b8868d 1281
73844f9c 1282==== TmfStateSystemFactory ====
f5b8868d 1283
73844f9c
PT
1284Once you have defined your state provider, you need to tell your trace type to
1285build a state system with this provider during its initialization. This consists
1286of overriding TmfTrace#buildStateSystems() and in there of calling the method in
1287TmfStateSystemFactory that corresponds to the storage backend you want to use
1288(see the section [[#Comparison of state system backends]]).
f5b8868d 1289
73844f9c
PT
1290You will have to pass in parameter the state provider you want to use, which you
1291should have defined already. Each backend can also ask for more configuration
1292information.
f5b8868d 1293
73844f9c
PT
1294You must then call registerStateSystem(id, statesystem) to make your state
1295system visible to the trace objects and the views. The ID can be any string of
1296your choosing. To access this particular state system, the views or modules will
1297need to use this ID.
f5b8868d 1298
73844f9c
PT
1299Also, don't forget to call super.buildStateSystems() in your implementation,
1300unless you know for sure you want to skip the state providers built by the
1301super-classes.
f5b8868d 1302
73844f9c
PT
1303You can look at how LttngKernelTrace does it for an example. It could also be
1304possible to build a state system only under certain conditions (like only if the
1305trace contains certain event types).
f5b8868d 1306
f5b8868d 1307
73844f9c 1308==== ITmfStateSystem ====
f5b8868d 1309
73844f9c
PT
1310ITmfStateSystem is the main interface through which views or analysis modules
1311will access the state system. It offers a read-only view of the state system,
1312which means that no states can be inserted, and no attributes can be created.
1313Calling TmfTrace#getStateSystems().get(id) will return you a ITmfStateSystem
1314view of the requested state system. The main methods of interest are:
f5b8868d 1315
73844f9c 1316===== getQuarkAbsolute()/getQuarkRelative() =====
f5b8868d 1317
73844f9c
PT
1318Those are the basic quark-getting methods. The goal of the state system is to
1319return the state values of given attributes at given timestamps. As we've seen
1320earlier, attributes can be described with a file-system-like path. The goal of
1321these methods is to convert from the path representation of the attribute to its
1322quark.
f5b8868d 1323
73844f9c
PT
1324Since quarks are created on-the-fly, there is no guarantee that the same
1325attributes will have the same quark for two traces of the same type. The views
1326should always query their quarks when dealing with a new trace or a new state
1327provider. Beyond that however, quarks should be cached and reused as much as
1328possible, to avoid potentially costly string re-hashing.
f5b8868d 1329
73844f9c
PT
1330getQuarkAbsolute() takes a variable amount of Strings in parameter, which
1331represent the full path to the attribute. Some of them can be constants, some
1332can come programatically, often from the event's fields.
f5b8868d 1333
73844f9c
PT
1334getQuarkRelative() is to be used when you already know the quark of a certain
1335attribute, and want to access on of its sub-attributes. Its first parameter is
1336the origin quark, followed by a String varagrs which represent the relative path
1337to the final attribute.
f5b8868d 1338
73844f9c
PT
1339These two methods will throw an AttributeNotFoundException if trying to access
1340an attribute that does not exist in the model.
f5b8868d 1341
73844f9c
PT
1342These methods also imply that the view has the knowledge of how the attribute
1343tree is organized. This should be a reasonable hypothesis, since the same
1344analysis plugin will normally ship both the state provider and the view, and
1345they will have been written by the same person. In other cases, it's possible to
1346use getSubAttributes() to explore the organization of the attribute tree first.
f5b8868d 1347
73844f9c 1348===== waitUntilBuilt() =====
f5b8868d 1349
73844f9c
PT
1350This is a simple method used to block the caller until the construction phase of
1351this state system is done. If the view prefers to wait until all information is
1352available before starting to do queries (to get all known attributes right away,
1353for example), this is the guy to call.
f5b8868d 1354
73844f9c 1355===== queryFullState() =====
f5b8868d 1356
73844f9c
PT
1357This is the method to do full queries. As mentioned earlier, you only need to
1358pass a target timestamp in parameter. It will return a List of state intervals,
1359in which the offset corresponds to the attribute quark. This will represent the
1360complete state of the model at the requested time.
f5b8868d 1361
73844f9c 1362===== querySingleState() =====
f5b8868d 1363
73844f9c
PT
1364The method to do single queries. You pass in parameter both a timestamp and an
1365attribute quark. This will return the single state matching this
1366timestamp/attribute pair.
f5b8868d 1367
73844f9c
PT
1368Other methods are available, you are encouraged to read their Javadoc and see if
1369they can be potentially useful.
f5b8868d 1370
73844f9c 1371==== ITmfStateSystemBuilder ====
f5b8868d 1372
73844f9c
PT
1373ITmfStateSystemBuilder is the read-write interface to the state system. It
1374extends ITmfStateSystem itself, so all its methods are available. It then adds
1375methods that can be used to write to the state system, either by creating new
1376attributes of inserting state changes.
f5b8868d 1377
73844f9c
PT
1378It is normally reserved for the state provider and should not be visible to
1379external components. However it will be available in AbstractTmfStateProvider,
1380in the field 'ss'. That way you can call ss.modifyAttribute() etc. in your state
1381provider to write to the state.
f5b8868d 1382
73844f9c 1383The main methods of interest are:
f5b8868d 1384
73844f9c 1385===== getQuark*AndAdd() =====
f5b8868d 1386
73844f9c
PT
1387getQuarkAbsoluteAndAdd() and getQuarkRelativeAndAdd() work exactly like their
1388non-AndAdd counterparts in ITmfStateSystem. The difference is that the -AndAdd
1389versions will not throw any exception: if the requested attribute path does not
1390exist in the system, it will be created, and its newly-assigned quark will be
1391returned.
f5b8868d 1392
73844f9c
PT
1393When in a state provider, the -AndAdd version should normally be used (unless
1394you know for sure the attribute already exist and don't want to create it
1395otherwise). This means that there is no need to define the whole attribute tree
1396in advance, the attributes will be created on-demand.
f5b8868d 1397
73844f9c 1398===== modifyAttribute() =====
f5b8868d 1399
73844f9c
PT
1400This is the main state-change-insertion method. As was explained before, a state
1401change is defined by a timestamp, an attribute and a state value. Those three
1402elements need to be passed to modifyAttribute as parameters.
f5b8868d 1403
73844f9c
PT
1404Other state change insertion methods are available (increment-, push-, pop- and
1405removeAttribute()), but those are simply convenience wrappers around
1406modifyAttribute(). Check their Javadoc for more information.
f5b8868d 1407
73844f9c 1408===== closeHistory() =====
f5b8868d 1409
73844f9c
PT
1410When the construction phase is done, do not forget to call closeHistory() to
1411tell the backend that no more intervals will be received. Depending on the
1412backend type, it might have to save files, close descriptors, etc. This ensures
1413that a persitent file can then be re-used when the trace is opened again.
f5b8868d 1414
73844f9c
PT
1415If you use the AbstractTmfStateProvider, it will call closeHistory()
1416automatically when it reaches the end of the trace.
f5b8868d 1417
73844f9c 1418=== Other relevant interfaces ===
f5b8868d 1419
73844f9c 1420==== o.e.l.tmf.core.statevalue.ITmfStateValue ====
f5b8868d 1421
73844f9c
PT
1422This is the interface used to represent state values. Those are used when
1423inserting state changes in the provider, and is also part of the state intervals
1424obtained when doing queries.
f5b8868d 1425
73844f9c 1426The abstract TmfStateValue class contains the factory methods to create new
7d59bbef
JCK
1427state values of either int, long, double or string types. To retrieve the real
1428object inside the state value, one can use the .unbox* methods.
f5b8868d 1429
73844f9c 1430Note: Do not instantiate null values manually, use TmfStateValue.nullValue()
f5b8868d 1431
73844f9c 1432==== o.e.l.tmf.core.interval.ITmfStateInterval ====
f5b8868d 1433
73844f9c
PT
1434This is the interface to represent the state intervals, which are stored in the
1435state history backend, and are returned when doing state system queries. A very
1436simple implementation is available in TmfStateInterval. Its methods should be
1437self-descriptive.
f5b8868d 1438
73844f9c 1439=== Exceptions ===
f5b8868d 1440
73844f9c
PT
1441The following exceptions, found in o.e.l.tmf.core.exceptions, are related to
1442state system activities.
f5b8868d 1443
73844f9c 1444==== AttributeNotFoundException ====
f5b8868d 1445
73844f9c
PT
1446This is thrown by getQuarkRelative() and getQuarkAbsolute() (but not byt the
1447-AndAdd versions!) when passing an attribute path that is not present in the
1448state system. This is to ensure that no new attribute is created when using
1449these versions of the methods.
f5b8868d 1450
73844f9c
PT
1451Views can expect some attributes to be present, but they should handle these
1452exceptions for when the attributes end up not being in the state system (perhaps
1453this particular trace didn't have a certain type of events, etc.)
f5b8868d 1454
73844f9c 1455==== StateValueTypeException ====
f5b8868d 1456
73844f9c
PT
1457This exception will be thrown when trying to unbox a state value into a type
1458different than its own. You should always check with ITmfStateValue#getType()
1459beforehand if you are not sure about the type of a given state value.
f5b8868d 1460
73844f9c 1461==== TimeRangeException ====
f5b8868d 1462
73844f9c
PT
1463This exception is thrown when trying to do a query on the state system for a
1464timestamp that is outside of its range. To be safe, you should check with
1465ITmfStateSystem#getStartTime() and #getCurrentEndTime() for the current valid
1466range of the state system. This is especially important when doing queries on
1467a state system that is currently being built.
f5b8868d 1468
73844f9c 1469==== StateSystemDisposedException ====
f5b8868d 1470
73844f9c
PT
1471This exception is thrown when trying to access a state system that has been
1472disposed, with its dispose() method. This can potentially happen at shutdown,
1473since Eclipse is not always consistent with the order in which the components
1474are closed.
f5b8868d 1475
f5b8868d 1476
73844f9c 1477== Comparison of state system backends ==
f5b8868d 1478
73844f9c
PT
1479As we have seen in section [[#High-level components]], the state system needs
1480a storage backend to save the intervals. Different implementations are
1481available when building your state system from TmfStateSystemFactory.
f5b8868d 1482
73844f9c
PT
1483Do not confuse full/single queries with full/partial history! All backend types
1484should be able to handle any type of queries defined in the ITmfStateSystem API,
1485unless noted otherwise.
f5b8868d 1486
73844f9c 1487=== Full history ===
2819a797 1488
73844f9c
PT
1489Available with TmfStateSystemFactory#newFullHistory(). The full history uses a
1490History Tree data structure, which is an optimized structure store state
1491intervals on disk. Once built, it can respond to queries in a ''log(n)'' manner.
2819a797 1492
73844f9c
PT
1493You need to specify a file at creation time, which will be the container for
1494the history tree. Once it's completely built, it will remain on disk (until you
1495delete the trace from the project). This way it can be reused from one session
1496to another, which makes subsequent loading time much faster.
2819a797 1497
73844f9c
PT
1498This the backend used by the LTTng kernel plugin. It offers good scalability and
1499performance, even at extreme sizes (it's been tested with traces of sizes up to
1500500 GB). Its main downside is the amount of disk space required: since every
1501single interval is written to disk, the size of the history file can quite
1502easily reach and even surpass the size of the trace itself.
2819a797 1503
73844f9c 1504=== Null history ===
2819a797 1505
73844f9c
PT
1506Available with TmfStateSystemFactory#newNullHistory(). As its name implies the
1507null history is in fact an absence of state history. All its query methods will
1508return null (see the Javadoc in NullBackend).
2819a797 1509
73844f9c 1510Obviously, no file is required, and almost no memory space is used.
2819a797 1511
73844f9c
PT
1512It's meant to be used in cases where you are not interested in past states, but
1513only in the "ongoing" one. It can also be useful for debugging and benchmarking.
2819a797 1514
73844f9c 1515=== In-memory history ===
2819a797 1516
73844f9c 1517Available with TmfStateSystemFactory#newInMemHistory(). This is a simple wrapper
7d59bbef
JCK
1518using a TreeSet to store all state intervals in memory. The implementation at
1519the moment is quite simple, it will perform a binary search on entries when
1520doing queries to find the ones that match.
2819a797 1521
73844f9c
PT
1522The advantage of this method is that it's very quick to build and query, since
1523all the information resides in memory. However, you are limited to 2^31 entries
1524(roughly 2 billions), and depending on your state provider and trace type, that
1525can happen really fast!
2819a797 1526
73844f9c
PT
1527There are no safeguards, so if you bust the limit you will end up with
1528ArrayOutOfBoundsException's everywhere. If your trace or state history can be
1529arbitrarily big, it's probably safer to use a Full History instead.
2819a797 1530
73844f9c 1531=== Partial history ===
2819a797 1532
73844f9c
PT
1533Available with TmfStateSystemFactory#newPartialHistory(). The partial history is
1534a more advanced form of the full history. Instead of writing all state intervals
1535to disk like with the full history, we only write a small fraction of them, and
1536go back to read the trace to recreate the states in-between.
2819a797 1537
73844f9c
PT
1538It has a big advantage over a full history in terms of disk space usage. It's
1539very possible to reduce the history tree file size by a factor of 1000, while
1540keeping query times within a factor of two. Its main downside comes from the
1541fact that you cannot do efficient single queries with it (they are implemented
1542by doing full queries underneath).
2819a797 1543
73844f9c
PT
1544This makes it a poor choice for views like the Control Flow view, where you do
1545a lot of range queries and single queries. However, it is a perfect fit for
1546cases like statistics, where you usually do full queries already, and you store
1547lots of small states which are very easy to "compress".
2819a797 1548
73844f9c 1549However, it can't really be used until bug 409630 is fixed.
2819a797 1550
7d59bbef
JCK
1551== State System Operations ==
1552
1553TmfStateSystemOperations is a static class that implements additional
1554statistical operations that can be performed on attributes of the state system.
1555
1556These operations require that the attribute be one of the numerical values
1557(int, long or double).
1558
1559The speed of these operations can be greatly improved for large data sets if
1560the attribute was inserted in the state system as a mipmap attribute. Refer to
1561the [[#Mipmap feature | Mipmap feature]] section.
1562
1563===== queryRangeMax() =====
1564
1565This method returns the maximum numerical value of an attribute in the
1566specified time range. The attribute must be of type int, long or double.
1567Null values are ignored. The returned value will be of the same state value
1568type as the base attribute, or a null value if there is no state interval
1569stored in the given time range.
1570
1571===== queryRangeMin() =====
1572
1573This method returns the minimum numerical value of an attribute in the
1574specified time range. The attribute must be of type int, long or double.
1575Null values are ignored. The returned value will be of the same state value
1576type as the base attribute, or a null value if there is no state interval
1577stored in the given time range.
1578
1579===== queryRangeAverage() =====
1580
1581This method returns the average numerical value of an attribute in the
1582specified time range. The attribute must be of type int, long or double.
1583Each state interval value is weighted according to time. Null values are
1584counted as zero. The returned value will be a double primitive, which will
1585be zero if there is no state interval stored in the given time range.
1586
73844f9c 1587== Code example ==
2819a797 1588
73844f9c
PT
1589Here is a small example of code that will use the state system. For this
1590example, let's assume we want to track the state of all the CPUs in a LTTng
1591kernel trace. To do so, we will watch for the "sched_switch" event in the state
1592provider, and will update an attribute indicating if the associated CPU should
1593be set to "running" or "idle".
2819a797 1594
73844f9c
PT
1595We will use an attribute tree that looks like this:
1596<pre>
1597CPUs
1598 |--0
1599 | |--Status
1600 |
1601 |--1
1602 | |--Status
1603 |
1604 | 2
1605 | |--Status
1606...
1607</pre>
2819a797 1608
73844f9c
PT
1609The second-level attributes will be named from the information available in the
1610trace events. Only the "Status" attributes will carry a state value (this means
1611we could have just used "1", "2", "3",... directly, but we'll do it in a tree
1612for the example's sake).
2819a797 1613
73844f9c
PT
1614Also, we will use integer state values to represent "running" or "idle", instead
1615of saving the strings that would get repeated every time. This will help in
1616reducing the size of the history file.
2819a797 1617
73844f9c
PT
1618First we will define a state provider in MyStateProvider. Then, assuming we
1619have already implemented a custom trace type extending CtfTmfTrace, we will add
1620a section to it to make it build a state system using the provider we defined
1621earlier. Finally, we will show some example code that can query the state
1622system, which would normally go in a view or analysis module.
2819a797 1623
73844f9c 1624=== State Provider ===
2819a797 1625
73844f9c
PT
1626<pre>
1627import org.eclipse.linuxtools.tmf.core.ctfadaptor.CtfTmfEvent;
1628import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
1629import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException;
1630import org.eclipse.linuxtools.tmf.core.exceptions.StateValueTypeException;
1631import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException;
1632import org.eclipse.linuxtools.tmf.core.statesystem.AbstractTmfStateProvider;
1633import org.eclipse.linuxtools.tmf.core.statevalue.ITmfStateValue;
1634import org.eclipse.linuxtools.tmf.core.statevalue.TmfStateValue;
1635import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace;
2819a797 1636
73844f9c
PT
1637/**
1638 * Example state system provider.
1639 *
1640 * @author Alexandre Montplaisir
1641 */
1642public class MyStateProvider extends AbstractTmfStateProvider {
2819a797 1643
73844f9c
PT
1644 /** State value representing the idle state */
1645 public static ITmfStateValue IDLE = TmfStateValue.newValueInt(0);
2819a797 1646
73844f9c
PT
1647 /** State value representing the running state */
1648 public static ITmfStateValue RUNNING = TmfStateValue.newValueInt(1);
2819a797 1649
73844f9c
PT
1650 /**
1651 * Constructor
1652 *
1653 * @param trace
1654 * The trace to which this state provider is associated
1655 */
1656 public MyStateProvider(ITmfTrace trace) {
1657 super(trace, CtfTmfEvent.class, "Example"); //$NON-NLS-1$
1658 /*
1659 * The third parameter here is not important, it's only used to name a
1660 * thread internally.
1661 */
1662 }
2819a797 1663
73844f9c
PT
1664 @Override
1665 public int getVersion() {
1666 /*
1667 * If the version of an existing file doesn't match the version supplied
1668 * in the provider, a rebuild of the history will be forced.
1669 */
1670 return 1;
1671 }
2819a797 1672
73844f9c
PT
1673 @Override
1674 public MyStateProvider getNewInstance() {
1675 return new MyStateProvider(getTrace());
1676 }
2819a797 1677
73844f9c
PT
1678 @Override
1679 protected void eventHandle(ITmfEvent ev) {
1680 /*
1681 * AbstractStateChangeInput should have already checked for the correct
1682 * class type.
1683 */
1684 CtfTmfEvent event = (CtfTmfEvent) ev;
2819a797 1685
73844f9c
PT
1686 final long ts = event.getTimestamp().getValue();
1687 Integer nextTid = ((Long) event.getContent().getField("next_tid").getValue()).intValue();
1688
1689 try {
1690
1691 if (event.getEventName().equals("sched_switch")) {
1692 int quark = ss.getQuarkAbsoluteAndAdd("CPUs", String.valueOf(event.getCPU()), "Status");
1693 ITmfStateValue value;
1694 if (nextTid > 0) {
1695 value = RUNNING;
1696 } else {
1697 value = IDLE;
1698 }
1699 ss.modifyAttribute(ts, value, quark);
1700 }
1701
1702 } catch (TimeRangeException e) {
1703 /*
1704 * This should not happen, since the timestamp comes from a trace
1705 * event.
1706 */
1707 throw new IllegalStateException(e);
1708 } catch (AttributeNotFoundException e) {
1709 /*
1710 * This should not happen either, since we're only accessing a quark
1711 * we just created.
1712 */
1713 throw new IllegalStateException(e);
1714 } catch (StateValueTypeException e) {
1715 /*
1716 * This wouldn't happen here, but could potentially happen if we try
1717 * to insert mismatching state value types in the same attribute.
1718 */
1719 e.printStackTrace();
1720 }
1721
1722 }
1723
1724}
1725</pre>
1726
1727=== Trace type definition ===
1728
1729<pre>
2819a797 1730import java.io.File;
2819a797
MK
1731
1732import org.eclipse.core.resources.IProject;
2819a797
MK
1733import org.eclipse.core.runtime.IStatus;
1734import org.eclipse.core.runtime.Status;
73844f9c 1735import org.eclipse.linuxtools.tmf.core.ctfadaptor.CtfTmfTrace;
2819a797 1736import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException;
73844f9c
PT
1737import org.eclipse.linuxtools.tmf.core.statesystem.ITmfStateProvider;
1738import org.eclipse.linuxtools.tmf.core.statesystem.ITmfStateSystem;
1739import org.eclipse.linuxtools.tmf.core.statesystem.TmfStateSystemFactory;
1740import org.eclipse.linuxtools.tmf.core.trace.TmfTraceManager;
2819a797
MK
1741
1742/**
73844f9c 1743 * Example of a custom trace type using a custom state provider.
2819a797 1744 *
73844f9c 1745 * @author Alexandre Montplaisir
2819a797 1746 */
73844f9c 1747public class MyTraceType extends CtfTmfTrace {
2819a797 1748
73844f9c
PT
1749 /** The file name of the history file */
1750 public final static String HISTORY_FILE_NAME = "mystatefile.ht";
2819a797 1751
73844f9c
PT
1752 /** ID of the state system we will build */
1753 public static final String STATE_ID = "org.eclipse.linuxtools.lttng2.example";
2819a797 1754
73844f9c
PT
1755 /**
1756 * Default constructor
1757 */
1758 public MyTraceType() {
1759 super();
2819a797
MK
1760 }
1761
1762 @Override
73844f9c
PT
1763 public IStatus validate(final IProject project, final String path) {
1764 /*
1765 * Add additional validation code here, and return a IStatus.ERROR if
1766 * validation fails.
1767 */
1768 return Status.OK_STATUS;
2819a797
MK
1769 }
1770
1771 @Override
73844f9c
PT
1772 protected void buildStateSystem() throws TmfTraceException {
1773 super.buildStateSystem();
1774
1775 /* Build the custom state system for this trace */
1776 String directory = TmfTraceManager.getSupplementaryFileDir(this);
1777 final File htFile = new File(directory + HISTORY_FILE_NAME);
1778 final ITmfStateProvider htInput = new MyStateProvider(this);
1779
1780 ITmfStateSystem ss = TmfStateSystemFactory.newFullHistory(htFile, htInput, false);
1781 fStateSystems.put(STATE_ID, ss);
2819a797
MK
1782 }
1783
73844f9c
PT
1784}
1785</pre>
1786
1787=== Query code ===
1788
1789<pre>
1790import java.util.List;
1791
1792import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException;
1793import org.eclipse.linuxtools.tmf.core.exceptions.StateSystemDisposedException;
1794import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException;
1795import org.eclipse.linuxtools.tmf.core.interval.ITmfStateInterval;
1796import org.eclipse.linuxtools.tmf.core.statesystem.ITmfStateSystem;
1797import org.eclipse.linuxtools.tmf.core.statevalue.ITmfStateValue;
1798import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace;
1799
1800/**
1801 * Class showing examples of state system queries.
1802 *
1803 * @author Alexandre Montplaisir
1804 */
1805public class QueryExample {
1806
1807 private final ITmfStateSystem ss;
1808
2819a797 1809 /**
73844f9c
PT
1810 * Constructor
1811 *
1812 * @param trace
1813 * Trace that this "view" will display.
2819a797 1814 */
73844f9c
PT
1815 public QueryExample(ITmfTrace trace) {
1816 ss = trace.getStateSystems().get(MyTraceType.STATE_ID);
2819a797
MK
1817 }
1818
73844f9c
PT
1819 /**
1820 * Example method of querying one attribute in the state system.
1821 *
1822 * We pass it a cpu and a timestamp, and it returns us if that cpu was
1823 * executing a process (true/false) at that time.
1824 *
1825 * @param cpu
1826 * The CPU to check
1827 * @param timestamp
1828 * The timestamp of the query
1829 * @return True if the CPU was running, false otherwise
1830 */
1831 public boolean cpuIsRunning(int cpu, long timestamp) {
2819a797 1832 try {
73844f9c
PT
1833 int quark = ss.getQuarkAbsolute("CPUs", String.valueOf(cpu), "Status");
1834 ITmfStateValue value = ss.querySingleState(timestamp, quark).getStateValue();
2819a797 1835
73844f9c
PT
1836 if (value.equals(MyStateProvider.RUNNING)) {
1837 return true;
1838 }
2819a797 1839
73844f9c
PT
1840 /*
1841 * Since at this level we have no guarantee on the contents of the state
1842 * system, it's important to handle these cases correctly.
1843 */
1844 } catch (AttributeNotFoundException e) {
1845 /*
1846 * Handle the case where the attribute does not exist in the state
1847 * system (no CPU with this number, etc.)
1848 */
1849 ...
1850 } catch (TimeRangeException e) {
1851 /*
1852 * Handle the case where 'timestamp' is outside of the range of the
1853 * history.
1854 */
1855 ...
1856 } catch (StateSystemDisposedException e) {
1857 /*
1858 * Handle the case where the state system is being disposed. If this
1859 * happens, it's normally when shutting down, so the view can just
1860 * return immediately and wait it out.
1861 */
1862 }
1863 return false;
2819a797
MK
1864 }
1865
2819a797 1866
73844f9c
PT
1867 /**
1868 * Example method of using a full query.
1869 *
1870 * We pass it a timestamp, and it returns us how many CPUs were executing a
1871 * process at that moment.
1872 *
1873 * @param timestamp
1874 * The target timestamp
1875 * @return The amount of CPUs that were running at that time
1876 */
1877 public int getNbRunningCpus(long timestamp) {
1878 int count = 0;
2819a797 1879
73844f9c
PT
1880 try {
1881 /* Get the list of the quarks we are interested in. */
1882 List<Integer> quarks = ss.getQuarks("CPUs", "*", "Status");
2819a797 1883
73844f9c
PT
1884 /*
1885 * Get the full state at our target timestamp (it's better than
1886 * doing an arbitrary number of single queries).
1887 */
1888 List<ITmfStateInterval> state = ss.queryFullState(timestamp);
2819a797 1889
73844f9c
PT
1890 /* Look at the value of the state for each quark */
1891 for (Integer quark : quarks) {
1892 ITmfStateValue value = state.get(quark).getStateValue();
1893 if (value.equals(MyStateProvider.RUNNING)) {
1894 count++;
1895 }
2819a797 1896 }
73844f9c
PT
1897
1898 } catch (TimeRangeException e) {
1899 /*
1900 * Handle the case where 'timestamp' is outside of the range of the
1901 * history.
1902 */
1903 ...
1904 } catch (StateSystemDisposedException e) {
1905 /* Handle the case where the state system is being disposed. */
1906 ...
2819a797 1907 }
73844f9c 1908 return count;
2819a797
MK
1909 }
1910}
1911</pre>
1912
7d59bbef
JCK
1913== Mipmap feature ==
1914
1915The mipmap feature allows attributes to be inserted into the state system with
1916additional computations performed to automatically store sub-attributes that
1917can later be used for statistical operations. The mipmap has a resolution which
1918represents the number of state attribute changes that are used to compute the
1919value at the next mipmap level.
1920
1921The supported mipmap features are: max, min, and average. Each one of these
1922features requires that the base attribute be a numerical state value (int, long
1923or double). An attribute can be mipmapped for one or more of the features at
1924the same time.
1925
1926To use a mipmapped attribute in queries, call the corresponding methods of the
1927static class [[#State System Operations | TmfStateSystemOperations]].
1928
1929=== AbstractTmfMipmapStateProvider ===
1930
1931AbstractTmfMipmapStateProvider is an abstract provider class that allows adding
1932features to a specific attribute into a mipmap tree. It extends AbstractTmfStateProvider.
1933
1934If a provider wants to add mipmapped attributes to its tree, it must extend
1935AbstractTmfMipmapStateProvider and call modifyMipmapAttribute() in the event
1936handler, specifying one or more mipmap features to compute. Then the structure
1937of the attribute tree will be :
1938
1939<pre>
1940|- <attribute>
1941| |- <mipmapFeature> (min/max/avg)
1942| | |- 1
1943| | |- 2
1944| | |- 3
1945| | ...
1946| | |- n (maximum mipmap level)
1947| |- <mipmapFeature> (min/max/avg)
1948| | |- 1
1949| | |- 2
1950| | |- 3
1951| | ...
1952| | |- n (maximum mipmap level)
1953| ...
1954</pre>
1955
73844f9c 1956= UML2 Sequence Diagram Framework =
2819a797 1957
73844f9c
PT
1958The purpose of the UML2 Sequence Diagram Framework of TMF is to provide a framework for generation of UML2 sequence diagrams. It provides
1959*UML2 Sequence diagram drawing capabilities (i.e. lifelines, messages, activations, object creation and deletion)
1960*a generic, re-usable Sequence Diagram View
1961*Eclipse Extension Point for the creation of sequence diagrams
1962*callback hooks for searching and filtering within the Sequence Diagram View
1963*scalability<br>
1964The following chapters describe the Sequence Diagram Framework as well as a reference implementation and its usage.
2819a797 1965
73844f9c 1966== TMF UML2 Sequence Diagram Extensions ==
2819a797 1967
73844f9c 1968In the UML2 Sequence Diagram Framework an Eclipse extension point is defined so that other plug-ins can contribute code to create sequence diagram.
2819a797 1969
73844f9c 1970'''Identifier''': org.eclipse.linuxtools.tmf.ui.uml2SDLoader<br>
0c54f1fe 1971'''Since''': 1.0<br>
73844f9c
PT
1972'''Description''': This extension point aims to list and connect any UML2 Sequence Diagram loader.<br>
1973'''Configuration Markup''':<br>
2819a797 1974
73844f9c
PT
1975<pre>
1976<!ELEMENT extension (uml2SDLoader)+>
1977<!ATTLIST extension
1978point CDATA #REQUIRED
1979id CDATA #IMPLIED
1980name CDATA #IMPLIED
1981>
1982</pre>
2819a797 1983
73844f9c
PT
1984*point - A fully qualified identifier of the target extension point.
1985*id - An optional identifier of the extension instance.
1986*name - An optional name of the extension instance.
2819a797 1987
73844f9c
PT
1988<pre>
1989<!ELEMENT uml2SDLoader EMPTY>
1990<!ATTLIST uml2SDLoader
1991id CDATA #REQUIRED
1992name CDATA #REQUIRED
1993class CDATA #REQUIRED
1994view CDATA #REQUIRED
1995default (true | false)
1996</pre>
2819a797 1997
73844f9c
PT
1998*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.
1999*name - An name of the extension instance.
2000*class - The implementation of this UML2 SD viewer loader. The class must implement org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader.
2001*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.
2002*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 2003
2819a797 2004
73844f9c 2005== Management of the Extension Point ==
2819a797 2006
73844f9c
PT
2007The TMF UI plug-in is responsible for evaluating each contribution to the extension point.
2008<br>
2009<br>
2010With 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 2011
73844f9c 2012== Sequence Diagram View ==
2819a797 2013
73844f9c 2014For 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 2015
73844f9c 2016=== Supported Widgets ===
2819a797 2017
73844f9c 2018The loader class provides a frame containing all the UML2 widgets to be displayed. The following widgets exist:
2819a797 2019
73844f9c
PT
2020*Lifeline
2021*Activation
2022*Synchronous Message
2023*Asynchronous Message
2024*Synchronous Message Return
2025*Asynchronous Message Return
2026*Stop
2819a797 2027
73844f9c 2028For a lifeline, a category can be defined. The lifeline category defines icons, which are displayed in the lifeline header.
2819a797 2029
73844f9c 2030=== Zooming ===
2819a797 2031
73844f9c 2032The Sequence Diagram View allows the user to zoom in, zoom out and reset the zoom factor.
2819a797 2033
73844f9c 2034=== Printing ===
2819a797 2035
73844f9c 2036It is possible to print the whole sequence diagram as well as part of it.
2819a797 2037
73844f9c 2038=== Key Bindings ===
2819a797 2039
73844f9c
PT
2040*SHIFT+ALT+ARROW-DOWN - to scroll down within sequence diagram one view page at a time
2041*SHIFT+ALT+ARROW-UP - to scroll up within sequence diagram one view page at a time
2042*SHIFT+ALT+ARROW-RIGHT - to scroll right within sequence diagram one view page at a time
2043*SHIFT+ALT+ARROW-LEFT - to scroll left within sequence diagram one view page at a time
2044*SHIFT+ALT+ARROW-HOME - to jump to the beginning of the selected message if not already visible in page
2045*SHIFT+ALT+ARROW-END - to jump to the end of the selected message if not already visible in page
2046*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]])
2047*CTRL+P - to open print dialog
067490ab 2048
73844f9c 2049=== Preferences ===
5f7ef209 2050
73844f9c
PT
2051The 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>
2052[[Image:images/SeqDiagramPref.png]] <br>
2053After changing the preferences select '''OK'''.
067490ab 2054
73844f9c 2055=== Callback hooks ===
067490ab 2056
73844f9c
PT
2057The Sequence Diagram View provides several callback hooks so that extension can provide application specific functionality. The following interfaces can be provided:
2058* Basic find provider or extended find Provider<br> For finding within the sequence diagram
2059* Basic filter provider and extended Filter Provider<br> For filtering within the sequnce diagram.
2060* Basic paging provider or advanced paging provider<br> For scalability reasons, used to limit number of displayed messages
2061* Properies provider<br> To provide properties of selected elements
2062* Collapse provider <br> To collapse areas of the sequence diagram
067490ab 2063
73844f9c 2064== Tutorial ==
067490ab 2065
73844f9c 2066This tutorial describes how to create a UML2 Sequence Diagram Loader extension and use this loader in the in Eclipse.
067490ab 2067
73844f9c 2068=== Prerequisites ===
067490ab 2069
0c54f1fe 2070The tutorial is based on Eclipse 4.4 (Eclipse Luna) and TMF 3.0.0.
067490ab 2071
73844f9c 2072=== Creating an Eclipse UI Plug-in ===
067490ab 2073
73844f9c
PT
2074To create a new project with name org.eclipse.linuxtools.tmf.sample.ui select '''File -> New -> Project -> Plug-in Development -> Plug-in Project'''. <br>
2075[[Image:images/Screenshot-NewPlug-inProject1.png]]<br>
067490ab 2076
73844f9c 2077[[Image:images/Screenshot-NewPlug-inProject2.png]]<br>
067490ab 2078
73844f9c 2079[[Image:images/Screenshot-NewPlug-inProject3.png]]<br>
067490ab 2080
73844f9c 2081=== Creating a Sequence Diagram View ===
067490ab 2082
73844f9c
PT
2083To open the plug-in manifest, double-click on the MANIFEST.MF file. <br>
2084[[Image:images/SelectManifest.png]]<br>
5f7ef209 2085
0c54f1fe 2086Change to the Dependencies tab and select '''Add...''' of the ''Required Plug-ins'' section. A new dialog box will open. Next find plug-ins ''org.eclipse.linuxtools.tmf.ui'' and ''org.eclipse.linuxtools.tmf.core'' and then press '''OK'''<br>
73844f9c 2087[[Image:images/AddDependencyTmfUi.png]]<br>
067490ab 2088
73844f9c
PT
2089Change 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>
2090[[Image:images/AddViewExtension1.png]]<br>
067490ab 2091
73844f9c
PT
2092To create a Sequence Diagram View, click the right mouse button. Then select '''New -> view'''<br>
2093[[Image:images/AddViewExtension2.png]]<br>
32897d73 2094
73844f9c
PT
2095A 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>
2096[[Image:images/FillSampleSeqDiagram.png]]<br>
32897d73 2097
73844f9c
PT
2098The view is prepared. Run the Example. To launch the an Eclipse Application select the ''Overview'' tab and click on '''Launch an Eclipse Application'''<br>
2099[[Image:images/RunEclipseApplication.png]]<br>
32897d73 2100
73844f9c
PT
2101A new Eclipse application window will show. In the new window go to '''Windows -> Show View -> Other... -> Other -> Sample Sequence Diagram'''.<br>
2102[[Image:images/ShowViewOther.png]]<br>
32897d73 2103
73844f9c
PT
2104The Sequence Diagram View will open with an blank page.<br>
2105[[Image:images/BlankSampleSeqDiagram.png]]<br>
32897d73 2106
73844f9c 2107Close the Example Application.
32897d73 2108
73844f9c 2109=== Defining the uml2SDLoader Extension ===
32897d73 2110
73844f9c 2111After defining the Sequence Diagram View it's time to create the ''uml2SDLoader'' Extension. <br>
32897d73 2112
73844f9c
PT
2113Before 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>
2114[[Image:images/AddDependencyTmf.png]]<br>
32897d73 2115
73844f9c
PT
2116To 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>
2117[[Image:images/AddTmfUml2SDLoader.png]]<br>
32897d73 2118
73844f9c
PT
2119A 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>
2120[[Image:images/FillSampleLoader.png]]<br>
32897d73 2121
73844f9c
PT
2122Then click on ''class'' (see above) to open the new class dialog box. Fill in the relevant fields and select '''Finish'''. <br>
2123[[Image:images/NewSampleLoaderClass.png]]<br>
32897d73 2124
73844f9c 2125A new Java class will be created which implements the interface ''org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader''.<br>
32897d73 2126
73844f9c
PT
2127<pre>
2128package org.eclipse.linuxtools.tmf.sample.ui;
32897d73 2129
73844f9c
PT
2130import org.eclipse.linuxtools.tmf.ui.views.uml2sd.SDView;
2131import org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader;
32897d73 2132
73844f9c 2133public class SampleLoader implements IUml2SDLoader {
32897d73 2134
73844f9c
PT
2135 public SampleLoader() {
2136 // TODO Auto-generated constructor stub
2137 }
32897d73 2138
73844f9c
PT
2139 @Override
2140 public void dispose() {
2141 // TODO Auto-generated method stub
32897d73 2142
73844f9c 2143 }
32897d73 2144
73844f9c
PT
2145 @Override
2146 public String getTitleString() {
2147 // TODO Auto-generated method stub
2148 return null;
2149 }
32897d73 2150
73844f9c
PT
2151 @Override
2152 public void setViewer(SDView arg0) {
2153 // TODO Auto-generated method stub
32897d73 2154
73844f9c 2155 }
32897d73
AM
2156</pre>
2157
73844f9c 2158=== Implementing the Loader Class ===
32897d73 2159
73844f9c 2160Next 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 2161
73844f9c
PT
2162<pre>
2163package org.eclipse.linuxtools.tmf.sample.ui;
32897d73 2164
73844f9c
PT
2165import org.eclipse.linuxtools.tmf.ui.views.uml2sd.SDView;
2166import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.AsyncMessage;
2167import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.AsyncMessageReturn;
2168import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.ExecutionOccurrence;
2169import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.Frame;
2170import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.Lifeline;
2171import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.Stop;
2172import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.SyncMessage;
2173import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.SyncMessageReturn;
2174import org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader;
32897d73 2175
73844f9c 2176public class SampleLoader implements IUml2SDLoader {
32897d73 2177
73844f9c
PT
2178 private SDView fSdView;
2179
2180 public SampleLoader() {
2181 }
32897d73 2182
73844f9c
PT
2183 @Override
2184 public void dispose() {
2185 }
32897d73 2186
73844f9c
PT
2187 @Override
2188 public String getTitleString() {
2189 return "Sample Diagram";
2190 }
32897d73 2191
73844f9c
PT
2192 @Override
2193 public void setViewer(SDView arg0) {
2194 fSdView = arg0;
2195 createFrame();
2196 }
2197
2198 private void createFrame() {
32897d73 2199
73844f9c
PT
2200 Frame testFrame = new Frame();
2201 testFrame.setName("Sample Frame");
32897d73 2202
73844f9c
PT
2203 /*
2204 * Create lifelines
2205 */
2206
2207 Lifeline lifeLine1 = new Lifeline();
2208 lifeLine1.setName("Object1");
2209 testFrame.addLifeLine(lifeLine1);
2210
2211 Lifeline lifeLine2 = new Lifeline();
2212 lifeLine2.setName("Object2");
2213 testFrame.addLifeLine(lifeLine2);
2214
32897d73 2215
73844f9c
PT
2216 /*
2217 * Create Sync Message
2218 */
2219 // Get new occurrence on lifelines
2220 lifeLine1.getNewEventOccurrence();
2221
2222 // Get Sync message instances
2223 SyncMessage start = new SyncMessage();
2224 start.setName("Start");
2225 start.setEndLifeline(lifeLine1);
2226 testFrame.addMessage(start);
32897d73 2227
73844f9c
PT
2228 /*
2229 * Create Sync Message
2230 */
2231 // Get new occurrence on lifelines
2232 lifeLine1.getNewEventOccurrence();
2233 lifeLine2.getNewEventOccurrence();
2234
2235 // Get Sync message instances
2236 SyncMessage syn1 = new SyncMessage();
2237 syn1.setName("Sync Message 1");
2238 syn1.setStartLifeline(lifeLine1);
2239 syn1.setEndLifeline(lifeLine2);
2240 testFrame.addMessage(syn1);
32897d73 2241
73844f9c
PT
2242 /*
2243 * Create corresponding Sync Message Return
2244 */
2245
2246 // Get new occurrence on lifelines
2247 lifeLine1.getNewEventOccurrence();
2248 lifeLine2.getNewEventOccurrence();
32897d73 2249
73844f9c
PT
2250 SyncMessageReturn synReturn1 = new SyncMessageReturn();
2251 synReturn1.setName("Sync Message Return 1");
2252 synReturn1.setStartLifeline(lifeLine2);
2253 synReturn1.setEndLifeline(lifeLine1);
2254 synReturn1.setMessage(syn1);
2255 testFrame.addMessage(synReturn1);
2256
2257 /*
2258 * Create Activations (Execution Occurrence)
2259 */
2260 ExecutionOccurrence occ1 = new ExecutionOccurrence();
2261 occ1.setStartOccurrence(start.getEventOccurrence());
2262 occ1.setEndOccurrence(synReturn1.getEventOccurrence());
2263 lifeLine1.addExecution(occ1);
2264 occ1.setName("Activation 1");
2265
2266 ExecutionOccurrence occ2 = new ExecutionOccurrence();
2267 occ2.setStartOccurrence(syn1.getEventOccurrence());
2268 occ2.setEndOccurrence(synReturn1.getEventOccurrence());
2269 lifeLine2.addExecution(occ2);
2270 occ2.setName("Activation 2");
2271
2272 /*
2273 * Create Sync Message
2274 */
2275 // Get new occurrence on lifelines
2276 lifeLine1.getNewEventOccurrence();
2277 lifeLine2.getNewEventOccurrence();
2278
2279 // Get Sync message instances
2280 AsyncMessage asyn1 = new AsyncMessage();
2281 asyn1.setName("Async Message 1");
2282 asyn1.setStartLifeline(lifeLine1);
2283 asyn1.setEndLifeline(lifeLine2);
2284 testFrame.addMessage(asyn1);
32897d73 2285
73844f9c
PT
2286 /*
2287 * Create corresponding Sync Message Return
2288 */
2289
2290 // Get new occurrence on lifelines
2291 lifeLine1.getNewEventOccurrence();
2292 lifeLine2.getNewEventOccurrence();
32897d73 2293
73844f9c
PT
2294 AsyncMessageReturn asynReturn1 = new AsyncMessageReturn();
2295 asynReturn1.setName("Async Message Return 1");
2296 asynReturn1.setStartLifeline(lifeLine2);
2297 asynReturn1.setEndLifeline(lifeLine1);
2298 asynReturn1.setMessage(asyn1);
2299 testFrame.addMessage(asynReturn1);
2300
2301 /*
2302 * Create a note
2303 */
2304
2305 // Get new occurrence on lifelines
2306 lifeLine1.getNewEventOccurrence();
2307
0c54f1fe 2308 EllipsisMessage info = new EllipsisMessage();
73844f9c
PT
2309 info.setName("Object deletion");
2310 info.setStartLifeline(lifeLine2);
2311 testFrame.addNode(info);
2312
2313 /*
2314 * Create a Stop
2315 */
2316 Stop stop = new Stop();
2317 stop.setLifeline(lifeLine2);
2318 stop.setEventOccurrence(lifeLine2.getNewEventOccurrence());
2319 lifeLine2.addNode(stop);
2320
2321 fSdView.setFrame(testFrame);
2322 }
2323}
2324</pre>
32897d73 2325
73844f9c
PT
2326Now 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>
2327[[Image:images/SampleDiagram1.png]] <br>
32897d73 2328
73844f9c 2329=== Adding time information ===
32897d73 2330
0c54f1fe 2331To 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.core''. 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 2332
73844f9c
PT
2333<pre>
2334 private void createFrame() {
2335 //...
2336 start.setTime(new TmfTimestamp(1000, -3));
2337 syn1.setTime(new TmfTimestamp(1005, -3));
2338 synReturn1.setTime(new TmfTimestamp(1050, -3));
2339 asyn1.setStartTime(new TmfTimestamp(1060, -3));
2340 asyn1.setEndTime(new TmfTimestamp(1070, -3));
2341 asynReturn1.setStartTime(new TmfTimestamp(1060, -3));
2342 asynReturn1.setEndTime(new TmfTimestamp(1070, -3));
2343 //...
2344 }
2345</pre>
32897d73 2346
73844f9c 2347When 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 2348
73844f9c 2349[[Image:images/SampleDiagramTimeComp.png]] <br>
32897d73 2350
73844f9c 2351By 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 2352
73844f9c
PT
2353[[Image:images/SampleDiagramSyncMessage.png]] <br>
2354[[Image:images/SampleDiagramAsyncMessage.png]] <br>
32897d73 2355
0c54f1fe 2356To 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 ''AsyncMessage'' the end time is used for the delta calculation.<br>
73844f9c 2357[[Image:images/SampleDiagramMessageDelta.png]] <br>
32897d73 2358
73844f9c 2359=== Default Coolbar and Menu Items ===
32897d73 2360
73844f9c
PT
2361The Sequence Diagram View comes with default coolbar and menu items. By default, each sequence diagram shows the following actions:
2362* Zoom in
2363* Zoom out
2364* Reset Zoom Factor
2365* Selection
2366* Configure Min Max (drop-down menu only)
2367* Navigation -> Show the node end (drop-down menu only)
2368* Navigation -> Show the node start (drop-down menu only)
32897d73 2369
73844f9c 2370[[Image:images/DefaultCoolbarMenu.png]]<br>
32897d73 2371
73844f9c 2372=== Implementing Optional Callbacks ===
32897d73 2373
73844f9c 2374The following chapters describe how to use all supported provider interfaces.
32897d73 2375
73844f9c 2376==== Using the Paging Provider Interface ====
32897d73 2377
73844f9c
PT
2378For 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.
2379<br>
2380To 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 2381
73844f9c
PT
2382<pre>
2383public class SampleLoader implements IUml2SDLoader, ISDPagingProvider {
2384 //...
2385 private page = 0;
2386
2387 @Override
2388 public void dispose() {
2389 if (fSdView != null) {
2390 fSdView.resetProviders();
2391 }
2392 }
2393
2394 @Override
2395 public void setViewer(SDView arg0) {
2396 fSdView = arg0;
2397 fSdView.setSDPagingProvider(this);
2398 createFrame();
2399 }
2400
2401 private void createSecondFrame() {
2402 Frame testFrame = new Frame();
2403 testFrame.setName("SecondFrame");
2404 Lifeline lifeline = new Lifeline();
2405 lifeline.setName("LifeLine 0");
2406 testFrame.addLifeLine(lifeline);
2407 lifeline = new Lifeline();
2408 lifeline.setName("LifeLine 1");
2409 testFrame.addLifeLine(lifeline);
2410 for (int i = 1; i < 5; i++) {
2411 SyncMessage message = new SyncMessage();
2412 message.autoSetStartLifeline(testFrame.getLifeline(0));
2413 message.autoSetEndLifeline(testFrame.getLifeline(0));
2414 message.setName((new StringBuilder("Message ")).append(i).toString());
2415 testFrame.addMessage(message);
2416
2417 SyncMessageReturn messageReturn = new SyncMessageReturn();
2418 messageReturn.autoSetStartLifeline(testFrame.getLifeline(0));
2419 messageReturn.autoSetEndLifeline(testFrame.getLifeline(0));
2420
2421 testFrame.addMessage(messageReturn);
2422 messageReturn.setName((new StringBuilder("Message return ")).append(i).toString());
2423 ExecutionOccurrence occ = new ExecutionOccurrence();
2424 occ.setStartOccurrence(testFrame.getSyncMessage(i - 1).getEventOccurrence());
2425 occ.setEndOccurrence(testFrame.getSyncMessageReturn(i - 1).getEventOccurrence());
2426 testFrame.getLifeline(0).addExecution(occ);
2427 }
2428 fSdView.setFrame(testFrame);
2429 }
32897d73 2430
73844f9c
PT
2431 @Override
2432 public boolean hasNextPage() {
2433 return page == 0;
2434 }
32897d73 2435
73844f9c
PT
2436 @Override
2437 public boolean hasPrevPage() {
2438 return page == 1;
2439 }
32897d73 2440
73844f9c
PT
2441 @Override
2442 public void nextPage() {
2443 page = 1;
2444 createSecondFrame();
2445 }
32897d73 2446
73844f9c
PT
2447 @Override
2448 public void prevPage() {
2449 page = 0;
2450 createFrame();
2451 }
32897d73 2452
73844f9c
PT
2453 @Override
2454 public void firstPage() {
2455 page = 0;
2456 createFrame();
2457 }
32897d73 2458
73844f9c
PT
2459 @Override
2460 public void lastPage() {
2461 page = 1;
2462 createSecondFrame();
2463 }
2464 //...
2465}
32897d73 2466
73844f9c 2467</pre>
32897d73 2468
73844f9c 2469When running the example application, new actions will be shown in the coolbar and the coolbar menu. <br>
32897d73 2470
73844f9c 2471[[Image:images/PageProviderAdded.png]]
32897d73 2472
73844f9c
PT
2473<br><br>
2474To 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.
2475<br>
2476
2477==== Using the Find Provider Interface ====
32897d73 2478
73844f9c
PT
2479For 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.
2480<br>
2481For 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.
2482<br>
2483Only on at a time can be active. If the extended find provder is defined it obsoletes the basic find provider.
2484<br>
2485To 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 2486
73844f9c
PT
2487<pre>
2488public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider {
32897d73 2489
73844f9c
PT
2490 //...
2491 @Override
2492 public void dispose() {
2493 if (fSdView != null) {
2494 fSdView.resetProviders();
2495 }
2496 }
32897d73 2497
73844f9c
PT
2498 @Override
2499 public void setViewer(SDView arg0) {
2500 fSdView = arg0;
2501 fSdView.setSDPagingProvider(this);
2502 fSdView.setSDFindProvider(this);
2503 createFrame();
2504 }
32897d73 2505
73844f9c
PT
2506 @Override
2507 public boolean isNodeSupported(int nodeType) {
2508 switch (nodeType) {
2509 case ISDGraphNodeSupporter.LIFELINE:
2510 case ISDGraphNodeSupporter.SYNCMESSAGE:
2511 return true;
32897d73 2512
73844f9c
PT
2513 default:
2514 break;
2515 }
2516 return false;
2517 }
2518
2519 @Override
2520 public String getNodeName(int nodeType, String loaderClassName) {
2521 switch (nodeType) {
2522 case ISDGraphNodeSupporter.LIFELINE:
2523 return "Lifeline";
2524 case ISDGraphNodeSupporter.SYNCMESSAGE:
2525 return "Sync Message";
2526 }
2527 return "";
2528 }
32897d73 2529
73844f9c
PT
2530 @Override
2531 public boolean find(Criteria criteria) {
2532 Frame frame = fSdView.getFrame();
2533 if (criteria.isLifeLineSelected()) {
2534 for (int i = 0; i < frame.lifeLinesCount(); i++) {
2535 if (criteria.matches(frame.getLifeline(i).getName())) {
2536 fSdView.getSDWidget().moveTo(frame.getLifeline(i));
2537 return true;
2538 }
2539 }
2540 }
2541 if (criteria.isSyncMessageSelected()) {
2542 for (int i = 0; i < frame.syncMessageCount(); i++) {
2543 if (criteria.matches(frame.getSyncMessage(i).getName())) {
2544 fSdView.getSDWidget().moveTo(frame.getSyncMessage(i));
2545 return true;
2546 }
2547 }
2548 }
2549 return false;
2550 }
32897d73 2551
73844f9c
PT
2552 @Override
2553 public void cancel() {
2554 // reset find parameters
2555 }
2556 //...
2557}
2558</pre>
32897d73 2559
73844f9c
PT
2560When running the example application, the find action will be shown in the coolbar and the coolbar menu. <br>
2561[[Image:images/FindProviderAdded.png]]
32897d73 2562
73844f9c
PT
2563To 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>
2564[[Image:images/FindDialog.png]]<br>
32897d73 2565
73844f9c 2566Note that the find dialog will be opened by typing the key shortcut CRTL+F.
32897d73 2567
73844f9c 2568==== Using the Filter Provider Interface ====
32897d73 2569
0c54f1fe 2570For filtering of sequence diagram elements two interfaces exist. 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.
73844f9c
PT
2571<br>
2572To 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>
2573Note that no example implementation of ''filter()'' is provided.
2574<br>
32897d73 2575
73844f9c
PT
2576<pre>
2577public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider, ISDFilterProvider {
32897d73 2578
73844f9c
PT
2579 //...
2580 @Override
2581 public void dispose() {
2582 if (fSdView != null) {
2583 fSdView.resetProviders();
2584 }
2585 }
32897d73 2586
73844f9c
PT
2587 @Override
2588 public void setViewer(SDView arg0) {
2589 fSdView = arg0;
2590 fSdView.setSDPagingProvider(this);
2591 fSdView.setSDFindProvider(this);
2592 fSdView.setSDFilterProvider(this);
2593 createFrame();
2594 }
32897d73 2595
73844f9c
PT
2596 @Override
2597 public boolean filter(List<?> list) {
2598 return false;
2599 }
2600 //...
2601}
2602</pre>
32897d73 2603
73844f9c
PT
2604When running the example application, the filter action will be shown in the coolbar menu. <br>
2605[[Image:images/HidePatternsMenuItem.png]]
32897d73 2606
73844f9c
PT
2607To filter select the '''Hide Patterns...''' of the coolbar menu. A new dialog box will open. <br>
2608[[Image:images/DialogHidePatterns.png]]
32897d73 2609
73844f9c
PT
2610To 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>
2611[[Image:images/DialogHidePatterns.png]] <br>
32897d73 2612
73844f9c 2613Now back at the Hide Pattern dialog. Select one or more filter and select '''OK'''.
32897d73 2614
73844f9c 2615To 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 2616
73844f9c 2617==== Using the Extended Action Bar Provider Interface ====
32897d73 2618
73844f9c
PT
2619The extended action bar provider can be used to add customized actions to the Sequence Diagram View.
2620To 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 2621
73844f9c
PT
2622<pre>
2623public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider, ISDFilterProvider, ISDExtendedActionBarProvider {
2624 //...
2625
2626 @Override
2627 public void dispose() {
2628 if (fSdView != null) {
2629 fSdView.resetProviders();
2630 }
2631 }
32897d73 2632
73844f9c
PT
2633 @Override
2634 public void setViewer(SDView arg0) {
2635 fSdView = arg0;
2636 fSdView.setSDPagingProvider(this);
2637 fSdView.setSDFindProvider(this);
2638 fSdView.setSDFilterProvider(this);
2639 fSdView.setSDExtendedActionBarProvider(this);
2640 createFrame();
2641 }
32897d73 2642
73844f9c
PT
2643 @Override
2644 public void supplementCoolbarContent(IActionBars iactionbars) {
2645 Action action = new Action("Refresh") {
2646 @Override
2647 public void run() {
2648 System.out.println("Refreshing...");
2649 }
2650 };
2651 iactionbars.getMenuManager().add(action);
2652 iactionbars.getToolBarManager().add(action);
2653 }
2654 //...
2655}
2656</pre>
32897d73 2657
73844f9c
PT
2658When running the example application, all new actions will be added to the coolbar and coolbar menu according to the implementation of ''supplementCoolbarContent()''<br>.
2659For the example above the coolbar and coolbar menu will look as follows.
32897d73 2660
73844f9c 2661[[Image:images/SupplCoolbar.png]]
32897d73 2662
73844f9c 2663==== Using the Properties Provider Interface====
32897d73 2664
73844f9c 2665This 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 2666
73844f9c 2667To 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 2668
73844f9c
PT
2669Please refer to the following Eclipse articles for more information about properties and tabed properties.
2670*[http://www.eclipse.org/articles/Article-Properties-View/properties-view.html | Take control of your properties]
2671*[http://www.eclipse.org/articles/Article-Tabbed-Properties/tabbed_properties_view.html | The Eclipse Tabbed Properties View]
32897d73 2672
73844f9c 2673==== Using the Collapse Provider Interface ====
32897d73 2674
73844f9c 2675This 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 2676
73844f9c 2677To 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 2678
73844f9c 2679==== Using the Selection Provider Service ====
32897d73 2680
73844f9c 2681The 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 2682
73844f9c
PT
2683<pre>
2684public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider, ISDFilterProvider, ISDExtendedActionBarProvider, ISelectionListener {
32897d73 2685
73844f9c
PT
2686 //...
2687 @Override
2688 public void dispose() {
2689 if (fSdView != null) {
2690 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().removePostSelectionListener(this);
2691 fSdView.resetProviders();
2692 }
2693 }
32897d73 2694
73844f9c
PT
2695 @Override
2696 public String getTitleString() {
2697 return "Sample Diagram";
2698 }
32897d73 2699
73844f9c
PT
2700 @Override
2701 public void setViewer(SDView arg0) {
2702 fSdView = arg0;
2703 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().addPostSelectionListener(this);
2704 fSdView.setSDPagingProvider(this);
2705 fSdView.setSDFindProvider(this);
2706 fSdView.setSDFilterProvider(this);
2707 fSdView.setSDExtendedActionBarProvider(this);
32897d73 2708
73844f9c
PT
2709 createFrame();
2710 }
32897d73 2711
73844f9c
PT
2712 @Override
2713 public void selectionChanged(IWorkbenchPart part, ISelection selection) {
2714 ISelection sel = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
2715 if (sel != null && (sel instanceof StructuredSelection)) {
2716 StructuredSelection stSel = (StructuredSelection) sel;
2717 if (stSel.getFirstElement() instanceof BaseMessage) {
2718 BaseMessage syncMsg = ((BaseMessage) stSel.getFirstElement());
2719 System.out.println("Message '" + syncMsg.getName() + "' selected.");
2720 }
2721 }
2722 }
2723
2724 //...
2725}
2726</pre>
32897d73 2727
73844f9c 2728=== Printing a Sequence Diagram ===
32897d73 2729
73844f9c 2730To 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 2731
73844f9c 2732[[Image:images/PrintDialog.png]] <br>
32897d73 2733
73844f9c 2734Fill in all the relevant information, select '''Printer...''' to choose the printer and the press '''OK'''.
32897d73 2735
73844f9c 2736=== Using one Sequence Diagram View with Multiple Loaders ===
32897d73 2737
73844f9c 2738A 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 2739
73844f9c
PT
2740<pre>
2741public class OpenSDView extends AbstractHandler {
2742 @Override
2743 public Object execute(ExecutionEvent event) throws ExecutionException {
2744 try {
2745 IWorkbenchPage persp = TmfUiPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
2746 SDView view = (SDView) persp.showView("org.eclipse.linuxtools.ust.examples.ui.componentinteraction");
2747 LoadersManager.getLoadersManager().createLoader("org.eclipse.linuxtools.tmf.ui.views.uml2sd.impl.TmfUml2SDSyncLoader", view);
2748 } catch (PartInitException e) {
2749 throw new ExecutionException("PartInitException caught: ", e);
2750 }
2751 return null;
2752 }
2753}
2754</pre>
32897d73 2755
73844f9c 2756=== Downloading the Tutorial ===
32897d73 2757
73844f9c 2758Use 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 2759
73844f9c 2760== Integration of Tracing and Monitoring Framework with Sequence Diagram Framework ==
32897d73 2761
73844f9c 2762In 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 2763
73844f9c 2764=== Reference Implementation ===
32897d73 2765
73844f9c 2766A Sequence Diagram View Extension is defined in the plug-in TMF UI as well as a uml2SDLoader Extension with the reference loader.
32897d73 2767
73844f9c 2768[[Image:images/ReferenceExtensions.png]]
32897d73 2769
73844f9c 2770=== Used Sequence Diagram Features ===
32897d73 2771
73844f9c
PT
2772Besides the default features of the Sequence Diagram Framework, the reference implementation uses the following additional features:
2773*Advanced paging
2774*Basic finding
2775*Basic filtering
2776*Selection Service
32897d73 2777
73844f9c 2778==== Advanced paging ====
32897d73 2779
73844f9c 2780The 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 2781
73844f9c 2782==== Basic finding ====
32897d73 2783
73844f9c 2784The 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 2785
73844f9c 2786==== Basic filtering ====
32897d73 2787
73844f9c 2788The 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 2789
73844f9c 2790==== Selection Service ====
32897d73 2791
73844f9c 2792The 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 2793
73844f9c 2794=== Used TMF Features ===
32897d73 2795
73844f9c
PT
2796The reference implementation uses the following features of TMF:
2797*TMF Experiment and Trace for accessing traces
2798*Event Request Framework to request TMF events from the experiment and respective traces
2799*Signal Framework for broadcasting and receiving TMF signals for synchronization purposes
32897d73 2800
73844f9c 2801==== TMF Experiment and Trace for accessing traces ====
32897d73 2802
73844f9c 2803The reference loader uses TMF Experiments to access traces and to request data from the traces.
32897d73 2804
73844f9c 2805==== TMF Event Request Framework ====
32897d73 2806
73844f9c 2807The reference loader use the TMF Event Request Framework to request events from the experiment and its traces.
32897d73 2808
73844f9c 2809When 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 2810
73844f9c 2811When 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 2812
73844f9c 2813A third type of event request is issued for finding specific data across pages.
32897d73 2814
73844f9c 2815==== TMF Signal Framework ====
32897d73 2816
0c54f1fe 2817The reference loader extends the class ''TmfComponent''. By doing that the loader is registered as a TMF signal handler for sending and receiving TMF signals. The loader implements signal handlers for the following TMF signals:
73844f9c
PT
2818*''TmfTraceSelectedSignal''
2819This 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.
0c54f1fe 2820*''TmfTraceClosedSignal''
73844f9c
PT
2821This 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.
2822*''TmfTimeSynchSignal''
0c54f1fe 2823This signal is used to indicate that a new time or time range has been selected. It contains a begin and end time. If a single time is selected then the begin and end time are the same. When receiving this signal the corresponding message matching the begin time is selected in the Sequence Diagram View. If necessary, the page is changed.
73844f9c
PT
2824*''TmfRangeSynchSignal''
2825This 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 2826
73844f9c 2827Besides 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 2828
73844f9c 2829=== Supported Traces ===
32897d73 2830
73844f9c 2831The 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 2832
73844f9c 2833Note that combined traces of multiple components, that contain the trace information about the same interactions are not supported in the reference implementation!
32897d73 2834
73844f9c 2835=== Trace Format ===
32897d73 2836
73844f9c 2837The 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 2838
73844f9c
PT
2839<pre>
2840 /**
2841 * @param tmfEvent Event to parse for sequence diagram event details
2842 * @return sequence diagram event if details are available else null
2843 */
2844 protected ITmfSyncSequenceDiagramEvent getSequenceDiagramEvent(ITmfEvent tmfEvent){
2845 //type = .*RECEIVE.* or .*SEND.*
2846 //content = sender:<sender name>:receiver:<receiver name>,signal:<signal name>
2847 String eventType = tmfEvent.getType().toString();
2848 if (eventType.contains(Messages.TmfUml2SDSyncLoader_EventTypeSend) || eventType.contains(Messages.TmfUml2SDSyncLoader_EventTypeReceive)) {
2849 Object sender = tmfEvent.getContent().getField(Messages.TmfUml2SDSyncLoader_FieldSender);
2850 Object receiver = tmfEvent.getContent().getField(Messages.TmfUml2SDSyncLoader_FieldReceiver);
2851 Object name = tmfEvent.getContent().getField(Messages.TmfUml2SDSyncLoader_FieldSignal);
2852 if ((sender instanceof ITmfEventField) && (receiver instanceof ITmfEventField) && (name instanceof ITmfEventField)) {
2853 ITmfSyncSequenceDiagramEvent sdEvent = new TmfSyncSequenceDiagramEvent(tmfEvent,
2854 ((ITmfEventField) sender).getValue().toString(),
2855 ((ITmfEventField) receiver).getValue().toString(),
2856 ((ITmfEventField) name).getValue().toString());
32897d73 2857
73844f9c
PT
2858 return sdEvent;
2859 }
2860 }
2861 return null;
32897d73 2862 }
32897d73
AM
2863</pre>
2864
0c54f1fe 2865The 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 can be created using this information. Note that Sync Messages are assumed, which means start and end time are the same.
32897d73 2866
73844f9c 2867=== How to use the Reference Implementation ===
32897d73 2868
0c54f1fe 2869An example CTF (Common Trace Format) trace is provided that contains trace events with sequence diagram information. To download the reference trace, use the following link: [https://wiki.eclipse.org/images/3/35/ReferenceTrace.zip Reference Trace].
32897d73 2870
0c54f1fe 2871Run an Eclipse application with TMF 3.0 or later installed. To open the Reference Sequence Diagram View, select '''Windows -> Show View -> Other... -> TMF -> Sequence Diagram''' <br>
73844f9c 2872[[Image:images/ShowTmfSDView.png]]<br>
32897d73 2873
0c54f1fe 2874A blank Sequence Diagram View will open.
32897d73 2875
0c54f1fe
BH
2876Then import the reference trace to the '''Project Explorer''' using the '''Import Trace Package...''' menu option.<br>
2877[[Image:images/ImportTracePackage.png]]
2878
2879Next, open the trace by double-clicking on the trace element in the '''Project Explorer'''. The trace will be opened and the Sequence Diagram view will be filled.
73844f9c 2880[[Image:images/ReferenceSeqDiagram.png]]<br>
32897d73 2881
0c54f1fe 2882Now the reference implementation can be explored. To demonstrate the view features try the following things:
73844f9c
PT
2883*Select a message in the Sequence diagram. As result the corresponding event will be selected in the Events View.
2884*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.
2885*In the Events View, press key ''End''. As result, the Sequence Diagram view will jump to the last page.
2886*In the Events View, press key ''Home''. As result, the Sequence Diagram view will jump to the first page.
2887*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.
2888* 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>
2889
73844f9c 2890=== Extending the Reference Loader ===
32897d73 2891
73844f9c 2892In 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 2893
73844f9c 2894= CTF Parser =
32897d73 2895
73844f9c
PT
2896== CTF Format ==
2897CTF is a format used to store traces. It is self defining, binary and made to be easy to write to.
2898Before going further, the full specification of the CTF file format can be found at http://www.efficios.com/ .
32897d73 2899
73844f9c 2900For 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 2901
73844f9c
PT
2902These files can be split into two types :
2903* Metadata
2904* Event streams
32897d73 2905
73844f9c
PT
2906=== Metadata ===
2907The 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 2908
73844f9c
PT
2909=== Event Streams ===
2910The 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 2911
73844f9c 2912So 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 2913
73844f9c
PT
2914== Reading a trace ==
2915In order to read a CTF trace, two steps must be done.
2916* The metadata must be read to know how to read the events.
2917* the events must be read.
32897d73 2918
73844f9c 2919The 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 2920
73844f9c
PT
2921When the metadata is loaded and read, the trace object will be populated with 3 items:
2922* the event definitions available per stream: a definition is a description of the datatype.
2923* 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.
2924* the beginning of a packet index.
32897d73 2925
73844f9c 2926Now 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 2927
73844f9c
PT
2928== Seeking in a trace ==
2929The 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 2930
73844f9c
PT
2931== Interfacing to TMF ==
2932The trace can be read easily now but the data is still awkward to extract.
32897d73 2933
73844f9c
PT
2934=== CtfLocation ===
2935A 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 2936
73844f9c
PT
2937=== CtfTmfTrace ===
2938The CtfTmfTrace is a wrapper for the standard CTF trace that allows it to perform the following actions:
2939* '''initTrace()''' create a trace
2940* '''validateTrace()''' is the trace a CTF trace?
2941* '''getLocationRatio()''' how far in the trace is my location?
2942* '''seekEvent()''' sets the cursor to a certain point in a trace.
2943* '''readNextEvent()''' reads the next event and then advances the cursor
2944* '''getTraceProperties()''' gets the 'env' structures of the metadata
2945
2946=== CtfIterator ===
2947The 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.
2948
2949=== CtfIteratorManager ===
2950Since 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.
2951
2952=== CtfTmfContext ===
2953The 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.
2954
2955=== CtfTmfTimestamp ===
2956The 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.
2957
2958=== CtfTmfEvent ===
2959The 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.
2960
2961=== Other ===
2962There are other helper files that format given events for views, they are simpler and the architecture does not depend on them.
2963
2964=== Limitations ===
2965For the moment live trace reading is not supported, there are no sources of traces to test on.
32897d73 2966
fc3177d9
GB
2967= Event matching and trace synchronization =
2968
2969Event matching consists in taking an event from a trace and linking it to another event in a possibly different trace. The example that comes to mind is matching network packets sent from one traced machine to another traced machine. These matches can be used to synchronize traces.
2970
2971Trace synchronization consists in taking traces, taken on different machines, with a different time reference, and finding the formula to transform the timestamps of some of the traces, so that they all have the same time reference.
2972
2973== Event matching interfaces ==
2974
2975Here's a description of the major parts involved in event matching. These classes are all in the ''org.eclipse.linuxtools.tmf.core.event.matching'' package:
2976
2977* '''ITmfEventMatching''': Controls the event matching process
2978* '''ITmfMatchEventDefinition''': Describes how events are matched
2979* '''IMatchProcessingUnit''': Processes the matched events
2980
2981== Implementation details and how to extend it ==
2982
2983=== ITmfEventMatching interface and derived classes ===
2984
2985This interface and its default abstract implementation '''TmfEventMatching''' control the event matching itself. Their only public method is ''matchEvents''. The class needs to manage how to setup the traces, and any initialization or finalization procedures.
2986
2987The abstract class generates an event request for each trace from which events are matched and waits for the request to complete before calling the one from another trace. The ''handleData'' method from the request calls the ''matchEvent'' method that needs to be implemented in children classes.
2988
2989Class '''TmfNetworkEventMatching''' is a concrete implementation of this interface. It applies to all use cases where a ''in'' event can be matched with a ''out' event (''in'' and ''out'' can be the same event, with different data). It creates a '''TmfEventDependency''' between the source and destination events. The dependency is added to the processing unit.
2990
2991To match events requiring other mechanisms (for instance, a series of events can be matched with another series of events), one would need to implement another class either extending '''TmfEventMatching''' or implementing '''ITmfEventMatching'''. It would most probably also require a new '''ITmfMatchEventDefinition''' implementation.
2992
2993=== ITmfMatchEventDefinition interface and its derived classes ===
2994
2995These are the classes that describe how to actually match specific events together.
2996
2997The '''canMatchTrace''' method will tell if a definition is compatible with a given trace.
2998
2999The '''getUniqueField''' method will return a list of field values that uniquely identify this event and can be used to find a previous event to match with.
3000
3001Typically, there would be a match definition abstract class/interface per event matching type.
3002
3003The interface '''ITmfNetworkMatchDefinition''' adds the ''getDirection'' method to indicate whether this event is a ''in'' or ''out'' event to be matched with one from the opposite direction.
3004
3005As examples, two concrete network match definitions have been implemented in the ''org.eclipse.linuxtools.lttng2.kernel.core.event.matching'' package for two compatible methods of matching TCP packets (See the LTTng User Guide on ''trace synchronization'' for information on those matching methods). Each one tells which events need to be present in the metadata of a CTF trace for this matching method to be applicable. It also returns the field values from each event that will uniquely match 2 events together.
3006
3007=== IMatchProcessingUnit interface and derived classes ===
3008
3009While matching events is an exercice in itself, it's what to do with the match that really makes this functionality interesting. This is the job of the '''IMatchProcessingUnit''' interface.
3010
3011'''TmfEventMatches''' provides a default implementation that only stores the matches to count them. When a new match is obtained, the ''addMatch'' is called with the match and the processing unit can do whatever needs to be done with it.
3012
3013A match processing unit can be an analysis in itself. For example, trace synchronization is done through such a processing unit. One just needs to set the processing unit in the TmfEventMatching constructor.
3014
3015== Code examples ==
3016
3017=== Using network packets matching in an analysis ===
3018
3019This example shows how one can create a processing unit inline to create a link between two events. In this example, the code already uses an event request, so there is no need here to call the ''matchEvents'' method, that will only create another request.
3020
3021<pre>
3022class MyAnalysis extends TmfAbstractAnalysisModule {
3023
3024 private TmfNetworkEventMatching tcpMatching;
3025
3026 ...
3027
3028 protected void executeAnalysis() {
3029
3030 IMatchProcessingUnit matchProcessing = new IMatchProcessingUnit() {
3031 @Override
3032 public void matchingEnded() {
3033 }
3034
3035 @Override
3036 public void init(ITmfTrace[] fTraces) {
3037 }
3038
3039 @Override
3040 public int countMatches() {
3041 return 0;
3042 }
3043
3044 @Override
3045 public void addMatch(TmfEventDependency match) {
3046 log.debug("we got a tcp match! " + match.getSourceEvent().getContent() + " " + match.getDestinationEvent().getContent());
3047 TmfEvent source = match.getSourceEvent();
3048 TmfEvent destination = match.getDestinationEvent();
3049 /* Create a link between the two events */
3050 }
3051 };
3052
3053 ITmfTrace[] traces = { getTrace() };
3054 tcpMatching = new TmfNetworkEventMatching(traces, matchProcessing);
3055 tcpMatching.initMatching();
3056
3057 MyEventRequest request = new MyEventRequest(this, i);
3058 getTrace().sendRequest(request);
3059 }
3060
3061 public void analyzeEvent(TmfEvent event) {
3062 ...
3063 tcpMatching.matchEvent(event, 0);
3064 ...
3065 }
3066
3067 ...
3068
3069}
3070
3071class MyEventRequest extends TmfEventRequest {
3072
3073 private final MyAnalysis analysis;
3074
3075 MyEventRequest(MyAnalysis analysis, int traceno) {
3076 super(CtfTmfEvent.class,
3077 TmfTimeRange.ETERNITY,
3078 0,
3079 TmfDataRequest.ALL_DATA,
3080 ITmfDataRequest.ExecutionType.FOREGROUND);
3081 this.analysis = analysis;
3082 }
3083
3084 @Override
3085 public void handleData(final ITmfEvent event) {
3086 super.handleData(event);
3087 if (event != null) {
3088 analysis.analyzeEvent(event);
3089 }
3090 }
3091}
3092</pre>
3093
3094=== Match network events from UST traces ===
3095
3096Suppose a client-server application is instrumented using LTTng-UST. Traces are collected on the server and some clients on different machines. The traces can be synchronized using network event matching.
3097
3098The following metadata describes the events:
3099
3100<pre>
3101 event {
3102 name = "myapp:send";
3103 id = 0;
3104 stream_id = 0;
3105 loglevel = 13;
3106 fields := struct {
3107 integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _sendto;
3108 integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _messageid;
3109 integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _data;
3110 };
3111 };
3112
3113 event {
3114 name = "myapp:receive";
3115 id = 1;
3116 stream_id = 0;
3117 loglevel = 13;
3118 fields := struct {
3119 integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _from;
3120 integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _messageid;
3121 integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _data;
3122 };
3123 };
3124</pre>
3125
3126One would need to write an event match definition for those 2 events as follows:
3127
3128<pre>
3129public class MyAppUstEventMatching implements ITmfNetworkMatchDefinition {
3130
3131 @Override
3132 public Direction getDirection(ITmfEvent event) {
3133 String evname = event.getType().getName();
3134 if (evname.equals("myapp:receive")) {
3135 return Direction.IN;
3136 } else if (evname.equals("myapp:send")) {
3137 return Direction.OUT;
3138 }
3139 return null;
3140 }
3141
3142 @Override
3143 public List<Object> getUniqueField(ITmfEvent event) {
3144 List<Object> keys = new ArrayList<Object>();
3145
3146 if (evname.equals("myapp:receive")) {
3147 keys.add(event.getContent().getField("from").getValue());
3148 keys.add(event.getContent().getField("messageid").getValue());
3149 } else {
3150 keys.add(event.getContent().getField("sendto").getValue());
3151 keys.add(event.getContent().getField("messageid").getValue());
3152 }
3153
3154 return keys;
3155 }
3156
3157 @Override
3158 public boolean canMatchTrace(ITmfTrace trace) {
3159 if (!(trace instanceof CtfTmfTrace)) {
3160 return false;
3161 }
3162 CtfTmfTrace ktrace = (CtfTmfTrace) trace;
3163 String[] events = { "myapp:receive", "myapp:send" };
3164 return ktrace.hasAtLeastOneOfEvents(events);
3165 }
3166
3167 @Override
3168 public MatchingType[] getApplicableMatchingTypes() {
3169 MatchingType[] types = { MatchingType.NETWORK };
3170 return types;
3171 }
3172
3173}
3174</pre>
3175
3176Somewhere in code that will be executed at the start of the plugin (like in the Activator), the following code will have to be run:
3177
3178<pre>
3179TmfEventMatching.registerMatchObject(new MyAppUstEventMatching());
3180</pre>
3181
3182Now, only adding the traces in an experiment and clicking the '''Synchronize traces''' menu element would synchronize the traces using the new definition for event matching.
3183
3184== Trace synchronization ==
3185
3186Trace synchronization classes and interfaces are located in the ''org.eclipse.linuxtools.tmf.core.synchronization'' package.
3187
3188=== Synchronization algorithm ===
3189
3190Synchronization algorithms are used to synchronize traces from events matched between traces. After synchronization, traces taken on different machines with different time references see their timestamps modified such that they all use the same time reference (typically, the time of at least one of the traces). With traces from different machines, it is impossible to have perfect synchronization, so the result is a best approximation that takes network latency into account.
3191
3192The abstract class '''SynchronizationAlgorithm''' is a processing unit for matches. New synchronization algorithms must extend this one, it already contains the functions to get the timestamp transforms for different traces.
3193
3194The ''fully incremental convex hull'' synchronization algorithm is the default synchronization algorithm.
3195
3196While the synchronization system provisions for more synchronization algorithms, there is not yet a way to select one, the experiment's trace synchronization uses the default algorithm. To test a new synchronization algorithm, the synchronization should be called directly like this:
3197
3198<pre>
3199SynchronizationAlgorithm syncAlgo = new MyNewSynchronizationAlgorithm();
3200syncAlgo = SynchronizationManager.synchronizeTraces(syncFile, traces, syncAlgo, true);
3201</pre>
3202
3203=== Timestamp transforms ===
3204
3205Timestamp transforms are the formulae used to transform the timestamps from a trace into the reference time. The '''ITmfTimestampTransform''' is the interface to implement to add a new transform.
3206
3207The following classes implement this interface:
3208
3209* '''TmfTimestampTransform''': default transform. It cannot be instantiated, it has a single static object TmfTimestampTransform.IDENTITY, which returns the original timestamp.
3210* '''TmfTimestampTransformLinear''': transforms the timestamp using a linear formula: ''f(t) = at + b'', where ''a'' and ''b'' are computed by the synchronization algorithm.
3211
3212One could extend the interface for other timestamp transforms, for instance to have a transform where the formula would change over the course of the trace.
3213
3214== Todo ==
3215
3216Here's a list of features not yet implemented that would enhance trace synchronization and event matching:
3217
3218* Ability to select a synchronization algorithm
3219* Implement a better way to select the reference trace instead of arbitrarily taking the first in alphabetical order (for instance, the minimum spanning tree algorithm by Masoume Jabbarifar (article on the subject not published yet))
3220* Ability to join traces from the same host so that even if one of the traces is not synchronized with the reference trace, it will take the same timestamp transform as the one on the same machine.
3221* Instead of having the timestamp transforms per trace, have the timestamp transform as part of an experiment context, so that the trace's specific analysis, like the state system, are in the original trace, but are transformed only when needed for an experiment analysis.
3222* Add more views to display the synchronization information (only textual statistics are available for now)
42f1f820
GB
3223
3224= Analysis Framework =
3225
3226Analysis modules are useful to tell the user exactly what can be done with a trace. The analysis framework provides an easy way to access and execute the modules and open the various outputs available.
3227
3228Analyses can have parameters they can use in their code. They also have outputs registered to them to display the results from their execution.
3229
3230== Creating a new module ==
3231
3232All analysis modules must implement the '''IAnalysisModule''' interface from the o.e.l.tmf.core project. An abstract class, '''TmfAbstractAnalysisModule''', provides a good base implementation. It is strongly suggested to use it as a superclass of any new analysis.
3233
3234=== Example ===
3235
3236This example shows how to add a simple analysis module for an LTTng kernel trace with two parameters.
3237
3238<pre>
3239public class MyLttngKernelAnalysis extends TmfAbstractAnalysisModule {
3240
3241 public static final String PARAM1 = "myparam";
3242 public static final String PARAM2 = "myotherparam";
3243
3244 @Override
3245 public boolean canExecute(ITmfTrace trace) {
3246 /* This just makes sure the trace is an Lttng kernel trace, though
3247 usually that should have been done by specifying the trace type
3248 this analysis module applies to */
3249 if (!LttngKernelTrace.class.isAssignableFrom(trace.getClass())) {
3250 return false;
3251 }
3252
3253 /* Does the trace contain the appropriate events? */
3254 String[] events = { "sched_switch", "sched_wakeup" };
3255 return ((LttngKernelTrace) trace).hasAllEvents(events);
3256 }
3257
3258 @Override
3259 protected void canceling() {
3260 /* The job I am running in is being cancelled, let's clean up */
3261 }
3262
3263 @Override
3264 protected boolean executeAnalysis(final IProgressMonitor monitor) {
3265 /*
3266 * I am running in an Eclipse job, and I already know I can execute
3267 * on a given trace.
3268 *
3269 * In the end, I will return true if I was successfully completed or
3270 * false if I was either interrupted or something wrong occurred.
3271 */
3272 Object param1 = getParameter(PARAM1);
3273 int param2 = (Integer) getParameter(PARAM2);
3274 }
3275
3276 @Override
3277 public Object getParameter(String name) {
3278 Object value = super.getParameter(name);
3279 /* Make sure the value of param2 is of the right type. For sake of
3280 simplicity, the full parameter format validation is not presented
3281 here */
3282 if ((value != null) && name.equals(PARAM2) && (value instanceof String)) {
3283 return Integer.parseInt((String) value);
3284 }
3285 return value;
3286 }
3287
3288}
3289</pre>
3290
3291=== Available base analysis classes and interfaces ===
3292
3293The following are available as base classes for analysis modules. They also extend the abstract '''TmfAbstractAnalysisModule'''
3294
3295* '''TmfStateSystemAnalysisModule''': A base analysis module that builds one state system. A module extending this class only needs to provide a state provider and the type of state system backend to use. All state systems should now use this base class as it also contains all the methods to actually create the state sytem with a given backend.
3296
3297The following interfaces can optionally be implemented by analysis modules if they use their functionalities. For instance, some utility views, like the State System Explorer, may have access to the module's data through these interfaces.
3298
3299* '''ITmfAnalysisModuleWithStateSystems''': Modules implementing this have one or more state systems included in them. For example, a module may "hide" 2 state system modules for its internal workings. By implementing this interface, it tells that it has state systems and can return them if required.
3300
3301=== How it works ===
3302
3303Analyses are managed through the '''TmfAnalysisManager'''. The analysis manager is a singleton in the application and keeps track of all available analysis modules, with the help of '''IAnalysisModuleHelper'''. It can be queried to get the available analysis modules, either all of them or only those for a given tracetype. The helpers contain the non-trace specific information on an analysis module: its id, its name, the tracetypes it applies to, etc.
3304
3305When a trace is opened, the helpers for the applicable analysis create new instances of the analysis modules. The analysis are then kept in a field of the trace and can be executed automatically or on demand.
3306
3307The analysis is executed by calling the '''IAnalysisModule#schedule()''' method. This method makes sure the analysis is executed only once and, if it is already running, it won't start again. The analysis itself is run inside an Eclipse job that can be cancelled by the user or the application. The developer must consider the progress monitor that comes as a parameter of the '''executeAnalysis()''' method, to handle the proper cancellation of the processing. The '''IAnalysisModule#waitForCompletion()''' method will block the calling thread until the analysis is completed. The method will return whether the analysis was successfully completed or if it was cancelled.
3308
3309A running analysis can be cancelled by calling the '''IAnalysisModule#cancel()''' method. This will set the analysis as done, so it cannot start again unless it is explicitly reset. This is done by calling the protected method '''resetAnalysis'''.
3310
3311== Telling TMF about the analysis module ==
3312
3313Now that the analysis module class exists, it is time to hook it to the rest of TMF so that it appears under the traces in the project explorer. The way to do so is to add an extension of type ''org.eclipse.linuxtools.tmf.core.analysis'' to a plugin, either through the ''Extensions'' tab of the Plug-in Manifest Editor or by editing directly the plugin.xml file.
3314
3315The following code shows what the resulting plugin.xml file should look like.
3316
3317<pre>
3318<extension
3319 point="org.eclipse.linuxtools.tmf.core.analysis">
3320 <module
3321 id="my.lttng.kernel.analysis.id"
3322 name="My LTTng Kernel Analysis"
3323 analysis_module="my.plugin.package.MyLttngKernelAnalysis"
3324 automatic="true">
3325 <parameter
3326 name="myparam">
3327 </parameter>
3328 <parameter
3329 default_value="3"
3330 name="myotherparam">
3331 <tracetype
3332 class="org.eclipse.linuxtools.lttng2.kernel.core.trace.LttngKernelTrace">
3333 </tracetype>
3334 </module>
3335</extension>
3336</pre>
3337
3338This defines an analysis module where the ''analysis_module'' attribute corresponds to the module class and must implement IAnalysisModule. This module has 2 parameters: ''myparam'' and ''myotherparam'' which has default value of 3. The ''tracetype'' element tells which tracetypes this analysis applies to. There can be many tracetypes. Also, the ''automatic'' attribute of the module indicates whether this analysis should be run when the trace is opened, or wait for the user's explicit request.
3339
3340Note that with these extension points, it is possible to use the same module class for more than one analysis (with different ids and names). That is a desirable behavior. For instance, a third party plugin may add a new tracetype different from the one the module is meant for, but on which the analysis can run. Also, different analyses could provide different results with the same module class but with different default values of parameters.
3341
3342== Attaching outputs and views to the analysis module ==
3343
3344Analyses will typically produce outputs the user can examine. Outputs can be a text dump, a .dot file, an XML file, a view, etc. All output types must implement the '''IAnalysisOutput''' interface.
3345
0c043a90 3346An output can be registered to an analysis module at any moment by calling the '''IAnalysisModule#registerOutput()''' method. Analyses themselves may know what outputs are available and may register them in the analysis constructor or after analysis completion.
42f1f820
GB
3347
3348The various concrete output types are:
3349
3350* '''TmfAnalysisViewOutput''': It takes a view ID as parameter and, when selected, opens the view.
3351
0c043a90
GB
3352=== Using the extension point to add outputs ===
3353
3354Analysis outputs can also be hooked to an analysis using the same extension point ''org.eclipse.linuxtools.tmf.core.analysis'' in the plugin.xml file. Outputs can be matched either to a specific analysis identified by an ID, or to all analysis modules extending or implementing a given class or interface.
3355
3356The following code shows how to add a view output to the analysis defined above directly in the plugin.xml file. This extension does not have to be in the same plugin as the extension defining the analysis. Typically, an analysis module can be defined in a core plugin, along with some outputs that do not require UI elements. Other outputs, like views, who need UI elements, will be defined in a ui plugin.
3357
3358<pre>
3359<extension
3360 point="org.eclipse.linuxtools.tmf.core.analysis">
3361 <output
3362 class="org.eclipse.linuxtools.tmf.ui.analysis.TmfAnalysisViewOutput"
3363 id="my.plugin.package.ui.views.myView">
3364 <analysisId
3365 id="my.lttng.kernel.analysis.id">
3366 </analysisId>
3367 </output>
3368 <output
3369 class="org.eclipse.linuxtools.tmf.ui.analysis.TmfAnalysisViewOutput"
3370 id="my.plugin.package.ui.views.myMoreGenericView">
3371 <analysisModuleClass
3372 class="my.plugin.package.core.MyAnalysisModuleClass">
3373 </analysisModuleClass>
3374 </output>
3375</extension>
3376</pre>
3377
42f1f820
GB
3378== Providing help for the module ==
3379
3380For now, the only way to provide a meaningful help message to the user is by overriding the '''IAnalysisModule#getHelpText()''' method and return a string that will be displayed in a message box.
3381
3382What still needs to be implemented is for a way to add a full user/developer documentation with mediawiki text file for each module and automatically add it to Eclipse Help. Clicking on the Help menu item of an analysis module would open the corresponding page in the help.
3383
3384== Using analysis parameter providers ==
3385
3386An analysis may have parameters that can be used during its execution. Default values can be set when describing the analysis module in the plugin.xml file, or they can use the '''IAnalysisParameterProvider''' interface to provide values for parameters. '''TmfAbstractAnalysisParamProvider''' provides an abstract implementation of this interface, that automatically notifies the module of a parameter change.
3387
3388=== Example parameter provider ===
3389
3390The following example shows how to have a parameter provider listen to a selection in the LTTng kernel Control Flow view and send the thread id to the analysis.
3391
3392<pre>
3393public class MyLttngKernelParameterProvider extends TmfAbstractAnalysisParamProvider {
3394
3395 private ControlFlowEntry fCurrentEntry = null;
3396
3397 private static final String NAME = "My Lttng kernel parameter provider"; //$NON-NLS-1$
3398
3399 private ISelectionListener selListener = new ISelectionListener() {
3400 @Override
3401 public void selectionChanged(IWorkbenchPart part, ISelection selection) {
3402 if (selection instanceof IStructuredSelection) {
3403 Object element = ((IStructuredSelection) selection).getFirstElement();
3404 if (element instanceof ControlFlowEntry) {
3405 ControlFlowEntry entry = (ControlFlowEntry) element;
3406 setCurrentThreadEntry(entry);
3407 }
3408 }
3409 }
3410 };
3411
3412 /*
3413 * Constructor
3414 */
3415 public CriticalPathParameterProvider() {
3416 super();
3417 registerListener();
3418 }
3419
3420 @Override
3421 public String getName() {
3422 return NAME;
3423 }
3424
3425 @Override
3426 public Object getParameter(String name) {
3427 if (fCurrentEntry == null) {
3428 return null;
3429 }
3430 if (name.equals(MyLttngKernelAnalysis.PARAM1)) {
3431 return fCurrentEntry.getThreadId()
3432 }
3433 return null;
3434 }
3435
3436 @Override
3437 public boolean appliesToTrace(ITmfTrace trace) {
3438 return (trace instanceof LttngKernelTrace);
3439 }
3440
3441 private void setCurrentThreadEntry(ControlFlowEntry entry) {
3442 if (!entry.equals(fCurrentEntry)) {
3443 fCurrentEntry = entry;
3444 this.notifyParameterChanged(MyLttngKernelAnalysis.PARAM1);
3445 }
3446 }
3447
3448 private void registerListener() {
3449 final IWorkbench wb = PlatformUI.getWorkbench();
3450
3451 final IWorkbenchPage activePage = wb.getActiveWorkbenchWindow().getActivePage();
3452
3453 /* Add the listener to the control flow view */
3454 view = activePage.findView(ControlFlowView.ID);
3455 if (view != null) {
3456 view.getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(selListener);
3457 view.getSite().getWorkbenchWindow().getPartService().addPartListener(partListener);
3458 }
3459 }
3460
3461}
3462</pre>
3463
3464=== Register the parameter provider to the analysis ===
3465
3466To have the parameter provider class register to analysis modules, it must first register through the analysis manager. It can be done in a plugin's activator as follows:
3467
3468<pre>
3469@Override
3470public void start(BundleContext context) throws Exception {
3471 /* ... */
3472 TmfAnalysisManager.registerParameterProvider("my.lttng.kernel.analysis.id", MyLttngKernelParameterProvider.class)
3473}
3474</pre>
3475
3476where '''MyLttngKernelParameterProvider''' will be registered to analysis ''"my.lttng.kernel.analysis.id"''. When the analysis module is created, the new module will register automatically to the singleton parameter provider instance. Only one module is registered to a parameter provider at a given time, the one corresponding to the currently selected trace.
3477
b1de2f7d
GM
3478== Providing requirements to analyses ==
3479
3480=== Analysis requirement provider API ===
3481
3482A requirement defines the needs of an analysis. For example, an analysis could need an event named ''"sched_switch"'' in order to be properly executed. The requirements are represented by the class '''TmfAnalysisRequirement'''. Since '''IAnalysisModule''' extends the '''IAnalysisRequirementProvider''' interface, all analysis modules must provide their requirements. If the analysis module extends '''TmfAbstractAnalysisModule''', it has the choice between overriding the requirements getter ('''IAnalysisRequirementProvider#getAnalysisRequirements()''') or not, since the abstract class returns an empty collection by default (no requirements).
3483
3484=== Requirement values ===
3485
3486When instantiating a requirement, the developer needs to specify a type to which all the values added to the requirement will be linked. In the earlier example, there would be an ''"event"'' or ''"eventName"'' type. The type is represented by a string, like all values added to the requirement object. With an 'event' type requirement, a trace generator like the LTTng Control could automatically enable the required events. This is possible by calling the '''TmfAnalysisRequirementHelper''' class. Another point we have to take into consideration is the priority level of each value added to the requirement object. The enum '''TmfAnalysisRequirement#ValuePriorityLevel''' gives the choice between '''ValuePriorityLevel#MANDATORY''' and '''ValuePriorityLevel#OPTIONAL'''. That way, we can tell if an analysis can run without a value or not. To add values, one must call '''TmfAnalysisRequirement#addValue()'''.
3487
3488Moreover, information can be added to requirements. That way, the developer can explicitly give help details at the requirement level instead of at the analysis level (which would just be a general help text). To add information to a requirement, the method '''TmfAnalysisRequirement#addInformation()''' must be called. Adding information is not mandatory.
3489
3490=== Example of providing requirements ===
3491
3492In this example, we will implement a method that initializes a requirement object and return it in the '''IAnalysisRequirementProvider#getAnalysisRequirements()''' getter. The example method will return a set with two requirements. The first one will indicate the events needed by a specific analysis and the last one will tell on what domain type the analysis applies. In the event type requirement, we will indicate that the analysis needs a mandatory event and an optional one.
3493
3494<pre>
3495@Override
3496public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() {
3497 Set<TmfAnalysisRequirement> requirements = new HashSet<>();
3498
3499 /* Create requirements of type 'event' and 'domain' */
3500 TmfAnalysisRequirement eventRequirement = new TmfAnalysisRequirement("event");
3501 TmfAnalysisRequirement domainRequirement = new TmfAnalysisRequirement("domain");
3502
3503 /* Add the values */
3504 domainRequirement.addValue("kernel", TmfAnalysisRequirement.ValuePriorityLevel.MANDATORY);
3505 eventRequirement.addValue("sched_switch", TmfAnalysisRequirement.ValuePriorityLevel.MANDATORY);
3506 eventRequirement.addValue("sched_wakeup", TmfAnalysisRequirement.ValuePriorityLevel.OPTIONAL);
3507
3508 /* An information about the events */
3509 eventRequirement.addInformation("The event sched_wakeup is optional because it's not properly handled by this analysis yet.");
3510
3511 /* Add them to the set */
3512 requirements.add(domainRequirement);
3513 requirements.add(eventRequirement);
3514
3515 return requirements;
3516}
3517</pre>
3518
3519
42f1f820
GB
3520== TODO ==
3521
3522Here's a list of features not yet implemented that would improve the analysis module user experience:
3523
3524* Implement help using the Eclipse Help facility (without forgetting an eventual command line request)
3525* The abstract class '''TmfAbstractAnalysisModule''' executes an analysis as a job, but nothing compels a developer to do so for an analysis implementing the '''IAnalysisModule''' interface. We should force the execution of the analysis as a job, either from the trace itself or using the TmfAnalysisManager or by some other mean.
3526* Views and outputs are often registered by the analysis themselves (forcing them often to be in the .ui packages because of the views), because there is no other easy way to do so. We should extend the analysis extension point so that .ui plugins or other third-party plugins can add outputs to a given analysis that resides in the core.
3527* Improve the user experience with the analysis:
3528** Allow the user to select which analyses should be available, per trace or per project.
3529** Allow the user to view all available analyses even though he has no imported traces.
3530** Allow the user to generate traces for a given analysis, or generate a template to generate the trace that can be sent as parameter to the tracer.
3531** Give the user a visual status of the analysis: not executed, in progress, completed, error.
3532** Give a small screenshot of the output as icon for it.
3533** Allow to specify parameter values from the GUI.
b1de2f7d
GM
3534* Add the possibility for an analysis requirement to be composed of another requirement.
3535* Generate a trace session from analysis requirements.
a59835d4
GB
3536
3537
3538= Performance Tests =
3539
3540Performance testing allows to calculate some metrics (CPU time, Memory Usage, etc) that some part of the code takes during its execution. These metrics can then be used as is for information on the system's execution, or they can be compared either with other execution scenarios, or previous runs of the same scenario, for instance, after some optimization has been done on the code.
3541
3542For automatic performance metric computation, we use the ''org.eclipse.test.performance'' plugin, provided by the Eclipse Test Feature.
3543
3544== Add performance tests ==
3545
3546=== Where ===
3547
3548Performance tests are unit tests and they are added to the corresponding unit tests plugin. To separate performance tests from unit tests, a separate source folder, typically named ''perf'', is added to the plug-in.
3549
3550Tests are to be added to a package under the ''perf'' directory, the package name would typically match the name of the package it is testing. For each package, a class named '''AllPerfTests''' would list all the performance tests classes inside this package. And like for unit tests, a class named '''AllPerfTests''' for the plug-in would list all the packages' '''AllPerfTests''' classes.
3551
3552When adding performance tests for the first time in a plug-in, the plug-in's '''AllPerfTests''' class should be added to the global list of performance tests, found in package ''org.eclipse.linuxtools.lttng.alltests'', in class '''RunAllPerfTests'''. This will ensure that performance tests for the plug-in are run along with the other performance tests
3553
3554=== How ===
3555
3556TMF is using the org.eclipse.test.performance framework for performance tests. Using this, performance metrics are automatically taken and, if many runs of the tests are run, average and standard deviation are automatically computed. Results can optionally be stored to a database for later use.
3557
3558Here is an example of how to use the test framework in a performance test:
3559
3560<pre>
3561public class AnalysisBenchmark {
3562
3563 private static final String TEST_ID = "org.eclipse.linuxtools#LTTng kernel analysis";
3564 private static final CtfTmfTestTrace testTrace = CtfTmfTestTrace.TRACE2;
3565 private static final int LOOP_COUNT = 10;
3566
3567 /**
3568 * Performance test
3569 */
3570 @Test
3571 public void testTrace() {
3572 assumeTrue(testTrace.exists());
3573
3574 /** Create a new performance meter for this scenario */
3575 Performance perf = Performance.getDefault();
3576 PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID);
3577
3578 /** Optionally, tag this test for summary or global summary on a given dimension */
3579 perf.tagAsSummary(pm, "LTTng Kernel Analysis", Dimension.CPU_TIME);
3580 perf.tagAsGlobalSummary(pm, "LTTng Kernel Analysis", Dimension.CPU_TIME);
3581
3582 /** The test will be run LOOP_COUNT times */
3583 for (int i = 0; i < LOOP_COUNT; i++) {
3584
3585 /** Start each run of the test with new objects to avoid different code paths */
3586 try (IAnalysisModule module = new LttngKernelAnalysisModule();
3587 LttngKernelTrace trace = new LttngKernelTrace()) {
3588 module.setId("test");
3589 trace.initTrace(null, testTrace.getPath(), CtfTmfEvent.class);
3590 module.setTrace(trace);
3591
3592 /** The analysis execution is being tested, so performance metrics
3593 * are taken before and after the execution */
3594 pm.start();
3595 TmfTestHelper.executeAnalysis(module);
3596 pm.stop();
3597
3598 /*
3599 * Delete the supplementary files, so next iteration rebuilds
3600 * the state system.
3601 */
3602 File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(trace));
3603 for (File file : suppDir.listFiles()) {
3604 file.delete();
3605 }
3606
3607 } catch (TmfAnalysisException | TmfTraceException e) {
3608 fail(e.getMessage());
3609 }
3610 }
3611
3612 /** Once the test has been run many times, committing the results will
3613 * calculate average, standard deviation, and, if configured, save the
3614 * data to a database */
3615 pm.commit();
3616 }
3617}
3618
3619</pre>
3620
3621For more information, see [http://wiki.eclipse.org/Performance/Automated_Tests The Eclipse Performance Test How-to]
3622
3623Some rules to help write performance tests are explained in section [[ABC of performance testing | ABC of performance testing]].
3624
3625=== Run a performance test ===
3626
3627Performance tests are unit tests, so, just like unit tests, they can be run by right-clicking on a performance test class and selecting ''Run As'' -> ''Junit Plug-in Test''.
3628
3629By default, if no database has been configured, results will be displayed in the Console at the end of the test.
3630
3631Here is the sample output from the test described in the previous section. It shows all the metrics that have been calculated during the test.
3632
3633<pre>
3634Scenario 'org.eclipse.linuxtools#LTTng kernel analysis' (average over 10 samples):
3635 System Time: 3.04s (95% in [2.77s, 3.3s]) Measurable effect: 464ms (1.3 SDs) (required sample size for an effect of 5% of mean: 94)
3636 Used Java Heap: -1.43M (95% in [-33.67M, 30.81M]) Measurable effect: 57.01M (1.3 SDs) (required sample size for an effect of 5% of stdev: 6401)
3637 Working Set: 14.43M (95% in [-966.01K, 29.81M]) Measurable effect: 27.19M (1.3 SDs) (required sample size for an effect of 5% of stdev: 6400)
3638 Elapsed Process: 3.04s (95% in [2.77s, 3.3s]) Measurable effect: 464ms (1.3 SDs) (required sample size for an effect of 5% of mean: 94)
3639 Kernel time: 621ms (95% in [586ms, 655ms]) Measurable effect: 60ms (1.3 SDs) (required sample size for an effect of 5% of mean: 39)
3640 CPU Time: 6.06s (95% in [5.02s, 7.09s]) Measurable effect: 1.83s (1.3 SDs) (required sample size for an effect of 5% of mean: 365)
3641 Hard Page Faults: 0 (95% in [0, 0]) Measurable effect: 0 (1.3 SDs) (required sample size for an effect of 5% of stdev: 6400)
3642 Soft Page Faults: 9.27K (95% in [3.28K, 15.27K]) Measurable effect: 10.6K (1.3 SDs) (required sample size for an effect of 5% of mean: 5224)
3643 Text Size: 0 (95% in [0, 0])
3644 Data Size: 0 (95% in [0, 0])
3645 Library Size: 32.5M (95% in [-12.69M, 77.69M]) Measurable effect: 79.91M (1.3 SDs) (required sample size for an effect of 5% of stdev: 6401)
3646</pre>
3647
3648Results from performance tests can be saved automatically to a derby database. Derby can be run either in embedded mode, locally on a machine, or on a server. More information on setting up derby for performance tests can be found here: [http://wiki.eclipse.org/Performance/Automated_Tests The Eclipse Performance Test How-to]. The following documentation will show how to configure an Eclipse run configuration to store results on a derby database located on a server.
3649
3650Note that to store results in a derby database, the ''org.apache.derby'' plug-in must be available within your Eclipse. Since it is an optional dependency, it is not included in the target definition. It can be installed via the '''Orbit''' repository, in ''Help'' -> ''Install new software...''. If the '''Orbit''' repository is not listed, click on the latest one from [http://download.eclipse.org/tools/orbit/downloads/] and copy the link under ''Orbit Build Repository''.
3651
3652To store the data to a database, it needs to be configured in the run configuration. In ''Run'' -> ''Run configurations..'', under ''Junit Plug-in Test'', find the run configuration that corresponds to the test you wish to run, or create one if it is not present yet.
3653
3654In the ''Arguments'' tab, in the box under ''VM Arguments'', add on separate lines the following information
3655
3656<pre>
3657-Declipse.perf.dbloc=//javaderby.dorsal.polymtl.ca
3658-Declipse.perf.config=build=mybuild;host=myhost;config=linux;jvm=1.7
3659</pre>
3660
3661The ''eclipse.perf.dbloc'' parameter is the url (or filename) of the derby database. The database is by default named ''perfDB'', with username and password ''guest''/''guest''. If the database does not exist, it will be created, initialized and populated.
3662
3663The ''eclipse.perf.config'' parameter identifies a '''variation''': It typically identifies the build on which is it run (commitId and/or build date, etc), the machine (host) on which it is run, the configuration of the system (for example Linux or Windows), the jvm etc. That parameter is a list of ';' separated key-value pairs. To be backward-compatible with the Eclipse Performance Tests Framework, the 4 keys mentioned above are mandatory, but any key-value pairs can be used.
3664
3665== ABC of performance testing ==
3666
3667Here follow some rules to help design good and meaningful performance tests.
3668
3669=== Determine what to test ===
3670
3671For tests to be significant, it is important to choose what exactly is to be tested and make sure it is reproducible every run. To limit the amount of noise caused by the TMF framework, the performance test code should be tweaked so that only the method under test is run. For instance, a trace should not be "opened" (by calling the ''traceOpened()'' method) to test an analysis, since the ''traceOpened'' method will also trigger the indexing and the execution of all applicable automatic analysis.
3672
3673For each code path to test, multiple scenarios can be defined. For instance, an analysis could be run on different traces, with different sizes. The results will show how the system scales and/or varies depending on the objects it is executed on.
3674
3675The number of '''samples''' used to compute the results is also important. The code to test will typically be inside a '''for''' loop that runs exactly the same code each time for a given number of times. All objects used for the test must start in the same state at each iteration of the loop. For instance, any trace used during an execution should be disposed of at the end of the loop, and any supplementary file that may have been generated in the run should be deleted.
3676
3677Before submitting a performance test to the code review, you should run it a few times (with results in the Console) and see if the standard deviation is not too large and if the results are reproducible.
3678
3679=== Metrics descriptions and considerations ===
3680
3681CPU time: CPU time represent the total time spent on CPU by the current process, for the time of the test execution. It is the sum of the time spent by all threads. On one hand, it is more significant than the elapsed time, since it should be the same no matter how many CPU cores the computer has. But since it calculates the time of every thread, one has to make sure that only threads related to what is being tested are executed during that time, or else the results will include the times of those other threads. For an application like TMF, it is hard to control all the threads, and empirically, it is found to vary a lot more than the system time from one run to the other.
3682
3683System time (Elapsed time): The time between the start and the end of the execution. It will vary depending on the parallelisation of the threads and the load of the machine.
3684
3685Kernel time: Time spent in kernel mode
3686
e7e04cb1 3687Used Java Heap: It is the difference between the memory used at the beginning of the execution and at the end. This metric may be useful to calculate the overall size occupied by the data generated by the test run, by forcing a garbage collection before taking the metrics at the beginning and at the end of the execution. But it will not show the memory used throughout the execution. There can be a large standard deviation. The reason for this is that when benchmarking methods that trigger tasks in different threads, like signals and/or analysis, these other threads might be in various states at each run of the test, which will impact the memory usage calculated. When using this metric, either make sure the method to test does not trigger external threads or make sure you wait for them to finish.
2c20bbb3
VP
3688
3689= Network Tracing =
3690
3691== Adding a protocol ==
3692
3693Supporting a new network protocol in TMF is straightforward. Minimal effort is required to support new protocols. In this tutorial, the UDP protocol will be added to the list of supported protocols.
3694
3695=== Architecture ===
3696
3697All the TMF pcap-related code is divided in three projects (not considering the tests plugins):
3698* '''org.eclipse.linuxtools.pcap.core''', which contains the parser that will read pcap files and constructs the different packets from a ByteBuffer. It also contains means to build packet streams, which are conversation (list of packets) between two endpoints. To add a protocol, almost all of the work will be in that project.
3699* '''org.eclipse.linuxtools.tmf.pcap.core''', which contains TMF-specific concepts and act as a wrapper between TMF and the pcap parsing library. It only depends on org.eclipse.linuxtools.tmf.core and org.eclipse.pcap.core. To add a protocol, one file must be edited in this project.
3700* '''org.eclipse.linuxtools.tmf.pcap.ui''', which contains all TMF pcap UI-specific concepts, such as the views and perspectives. No work is needed in that project.
3701
3702=== UDP Packet Structure ===
3703
3704The UDP is a transport-layer protocol that does not guarantee message delivery nor in-order message reception. A UDP packet (datagram) has the following [http://en.wikipedia.org/wiki/User_Datagram_Protocol#Packet_structure structure]:
3705
3706{| class="wikitable" style="margin: 0 auto; text-align: center;"
3707|-
3708! style="border-bottom:none; border-right:none;"| ''Offsets''
3709! style="border-left:none;"| Octet
3710! colspan="8" | 0
3711! colspan="8" | 1
3712! colspan="8" | 2
3713! colspan="8" | 3
3714|-
3715! style="border-top: none" | Octet
3716! <tt>Bit</tt>!!<tt>&nbsp;0</tt>!!<tt>&nbsp;1</tt>!!<tt>&nbsp;2</tt>!!<tt>&nbsp;3</tt>!!<tt>&nbsp;4</tt>!!<tt>&nbsp;5</tt>!!<tt>&nbsp;6</tt>!!<tt>&nbsp;7</tt>!!<tt>&nbsp;8</tt>!!<tt>&nbsp;9</tt>!!<tt>10</tt>!!<tt>11</tt>!!<tt>12</tt>!!<tt>13</tt>!!<tt>14</tt>!!<tt>15</tt>!!<tt>16</tt>!!<tt>17</tt>!!<tt>18</tt>!!<tt>19</tt>!!<tt>20</tt>!!<tt>21</tt>!!<tt>22</tt>!!<tt>23</tt>!!<tt>24</tt>!!<tt>25</tt>!!<tt>26</tt>!!<tt>27</tt>!!<tt>28</tt>!!<tt>29</tt>!!<tt>30</tt>!!<tt>31</tt>
3717|-
3718! 0
3719!<tt> 0</tt>
3720| colspan="16" style="background:#fdd;"| Source port || colspan="16"| Destination port
3721|-
3722! 4
3723!<tt>32</tt>
3724| colspan="16"| Length || colspan="16" style="background:#fdd;"| Checksum
3725|}
3726
3727Knowing that, we can define an UDPPacket class that contains those fields.
3728
3729=== Creating the UDPPacket ===
3730
3731First, in org.eclipse.linuxtools.pcap.core, create a new package named '''org.eclipse.linuxtools.pcap.core.protocol.name''' with name being the name of the new protocol. In our case name is udp so we create the package '''org.eclipse.linuxtools.pcap.core.protocol.udp'''. All our work is going in this package.
3732
3733In this package, we create a new class named UDPPacket that extends Packet. All new protocol must define a packet type that extends the abstract class Packet. We also add different fields:
3734* ''Packet'' '''fChildPacket''', which is the packet encapsulated by this UDP packet, if it exists. This field will be initialized by findChildPacket().
3735* ''ByteBuffer'' '''fPayload''', which is the payload of this packet. Basically, it is the UDP packet without its header.
3736* ''int'' '''fSourcePort''', which is an unsigned 16-bits field, that contains the source port of the packet (see packet structure).
3737* ''int'' '''fDestinationPort''', which is an unsigned 16-bits field, that contains the destination port of the packet (see packet structure).
3738* ''int'' '''fTotalLength''', which is an unsigned 16-bits field, that contains the total length (header + payload) of the packet.
3739* ''int'' '''fChecksum''', which is an unsigned 16-bits field, that contains a checksum to verify the integrity of the data.
3740* ''UDPEndpoint'' '''fSourceEndpoint''', which contains the source endpoint of the UDPPacket. The UDPEndpoint class will be created later in this tutorial.
3741* ''UDPEndpoint'' '''fDestinationEndpoint''', which contains the destination endpoint of the UDPPacket.
3742* ''ImmutableMap<String, String>'' '''fFields''', which is a map that contains all the packet fields (see in data structure) which assign a field name with its value. Those values will be displayed on the UI.
3743
3744We also create the UDPPacket(PcapFile file, @Nullable Packet parent, ByteBuffer packet) constructor. The parameters are:
3745* ''PcapFile'' '''file''', which is the pcap file to which this packet belongs.
3746* ''Packet'' '''parent''', which is the packet encasulating this UDPPacket
3747* ''ByteBuffer'' '''packet''', which is a ByteBuffer that contains all the data necessary to initialize the fields of this UDPPacket. We will retrieve bytes from it during object construction.
3748
3749The following class is obtained:
3750
3751<pre>
3752package org.eclipse.linuxtools.pcap.core.protocol.udp;
3753
3754import java.nio.ByteBuffer;
3755import java.util.Map;
3756
3757import org.eclipse.linuxtools.pcap.core.endpoint.ProtocolEndpoint;
3758import org.eclipse.linuxtools.pcap.core.packet.BadPacketException;
3759import org.eclipse.linuxtools.pcap.core.packet.Packet;
3760
3761public class UDPPacket extends Packet {
3762
3763 private final @Nullable Packet fChildPacket;
3764 private final @Nullable ByteBuffer fPayload;
3765
3766 private final int fSourcePort;
3767 private final int fDestinationPort;
3768 private final int fTotalLength;
3769 private final int fChecksum;
3770
3771 private @Nullable UDPEndpoint fSourceEndpoint;
3772 private @Nullable UDPEndpoint fDestinationEndpoint;
3773
3774 private @Nullable ImmutableMap<String, String> fFields;
3775
3776 /**
3777 * Constructor of the UDP Packet class.
3778 *
3779 * @param file
3780 * The file that contains this packet.
3781 * @param parent
3782 * The parent packet of this packet (the encapsulating packet).
3783 * @param packet
3784 * The entire packet (header and payload).
3785 * @throws BadPacketException
3786 * Thrown when the packet is erroneous.
3787 */
3788 public UDPPacket(PcapFile file, @Nullable Packet parent, ByteBuffer packet) throws BadPacketException {
3789 super(file, parent, Protocol.UDP);
3790 // TODO Auto-generated constructor stub
3791 }
3792
3793
3794 @Override
3795 public Packet getChildPacket() {
3796 // TODO Auto-generated method stub
3797 return null;
3798 }
3799
3800 @Override
3801 public ByteBuffer getPayload() {
3802 // TODO Auto-generated method stub
3803 return null;
3804 }
3805
3806 @Override
3807 public boolean validate() {
3808 // TODO Auto-generated method stub
3809 return false;
3810 }
3811
3812 @Override
3813 protected Packet findChildPacket() throws BadPacketException {
3814 // TODO Auto-generated method stub
3815 return null;
3816 }
3817
3818 @Override
3819 public ProtocolEndpoint getSourceEndpoint() {
3820 // TODO Auto-generated method stub
3821 return null;
3822 }
3823
3824 @Override
3825 public ProtocolEndpoint getDestinationEndpoint() {
3826 // TODO Auto-generated method stub
3827 return null;
3828 }
3829
3830 @Override
3831 public Map<String, String> getFields() {
3832 // TODO Auto-generated method stub
3833 return null;
3834 }
3835
3836 @Override
3837 public String getLocalSummaryString() {
3838 // TODO Auto-generated method stub
3839 return null;
3840 }
3841
3842 @Override
3843 protected String getSignificationString() {
3844 // TODO Auto-generated method stub
3845 return null;
3846 }
3847
3848 @Override
3849 public boolean equals(Object obj) {
3850 // TODO Auto-generated method stub
3851 return false;
3852 }
3853
3854 @Override
3855 public int hashCode() {
3856 // TODO Auto-generated method stub
3857 return 0;
3858 }
3859
3860}
3861</pre>
3862
3863Now, we implement the constructor. It is done in four steps:
3864* We initialize fSourceEndpoint, fDestinationEndpoint and fFields to null, since those are lazy-loaded. This allows faster construction of the packet and thus faster parsing.
3865* We initialize fSourcePort, fDestinationPort, fTotalLength, fChecksum using ByteBuffer packet. Thanks to the packet data structure, we can simply retrieve packet.getShort() to get the value. Since there is no unsigned in Java, special care is taken to avoid negative number. We use the utility method ConversionHelper.unsignedShortToInt() to convert it to an integer, and initialize the fields.
3866* Now that the header is parsed, we take the rest of the ByteBuffer packet to initialize the payload, if there is one. To do this, we simply generate a new ByteBuffer starting from the current position.
3867* We initialize the field fChildPacket using the method findChildPacket()
3868
3869The following constructor is obtained:
3870<pre>
3871 public UDPPacket(PcapFile file, @Nullable Packet parent, ByteBuffer packet) throws BadPacketException {
3872 super(file, parent, Protocol.UDP);
3873
3874 // The endpoints and fFields are lazy loaded. They are defined in the get*Endpoint()
3875 // methods.
3876 fSourceEndpoint = null;
3877 fDestinationEndpoint = null;
3878 fFields = null;
3879
3880 // Initialize the fields from the ByteBuffer
3881 packet.order(ByteOrder.BIG_ENDIAN);
3882 packet.position(0);
3883
3884 fSourcePort = ConversionHelper.unsignedShortToInt(packet.getShort());
3885 fDestinationPort = ConversionHelper.unsignedShortToInt(packet.getShort());
3886 fTotalLength = ConversionHelper.unsignedShortToInt(packet.getShort());
3887 fChecksum = ConversionHelper.unsignedShortToInt(packet.getShort());
3888
3889 // Initialize the payload
3890 if (packet.array().length - packet.position() > 0) {
3891 byte[] array = new byte[packet.array().length - packet.position()];
3892 packet.get(array);
3893
3894 ByteBuffer payload = ByteBuffer.wrap(array);
3895 payload.order(ByteOrder.BIG_ENDIAN);
3896 payload.position(0);
3897 fPayload = payload;
3898 } else {
3899 fPayload = null;
3900 }
3901
3902 // Find child
3903 fChildPacket = findChildPacket();
3904
3905 }
3906</pre>
3907
3908Then, we implement the following methods:
3909* ''public Packet'' '''getChildPacket()''': simple getter of fChildPacket
3910* ''public ByteBuffer'' '''getPayload()''': simple getter of fPayload
3911* ''public boolean'' '''validate()''': method that checks if the packet is valid. In our case, the packet is valid if the retrieved checksum fChecksum and the real checksum (that we can compute using the fields and payload of UDPPacket) are the same.
3912* ''protected Packet'' '''findChildPacket()''': method that create a new packet if a encapsulated protocol is found. For instance, based on the fDestinationPort, it could determine what the encapsulated protocol is and creates a new packet object.
3913* ''public ProtocolEndpoint'' '''getSourceEndpoint()''': method that initializes and returns the source endpoint.
3914* ''public ProtocolEndpoint'' '''getDestinationEndpoint()''': method that initializes and returns the destination endpoint.
3915* ''public Map<String, String>'' '''getFields()''': method that initializes and returns the map containing the fields matched to their value.
3916* ''public String'' '''getLocalSummaryString()''': method that returns a string summarizing the most important fields of the packet. There is no need to list all the fields, just the most important one. This will be displayed on UI.
3917* ''protected String'' '''getSignificationString()''': method that returns a string describing the meaning of the packet. If there is no particular meaning, it is possible to return getLocalSummaryString().
3918* public boolean'' '''equals(Object obj)''': Object's equals method.
3919* public int'' '''hashCode()''': Object's hashCode method.
3920
3921We get the following code:
3922<pre>
3923 @Override
3924 public @Nullable Packet getChildPacket() {
3925 return fChildPacket;
3926 }
3927
3928 @Override
3929 public @Nullable ByteBuffer getPayload() {
3930 return fPayload;
3931 }
3932
3933 /**
3934 * Getter method that returns the UDP Source Port.
3935 *
3936 * @return The source Port.
3937 */
3938 public int getSourcePort() {
3939 return fSourcePort;
3940 }
3941
3942 /**
3943 * Getter method that returns the UDP Destination Port.
3944 *
3945 * @return The destination Port.
3946 */
3947 public int getDestinationPort() {
3948 return fDestinationPort;
3949 }
3950
3951 /**
3952 * {@inheritDoc}
3953 *
3954 * See http://www.iana.org/assignments/service-names-port-numbers/service-
3955 * names-port-numbers.xhtml or
3956 * http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
3957 */
3958 @Override
3959 protected @Nullable Packet findChildPacket() throws BadPacketException {
3960 // When more protocols are implemented, we can simply do a switch on the fDestinationPort field to find the child packet.
3961 // For instance, if the destination port is 80, then chances are the HTTP protocol is encapsulated. We can create a new HTTP
3962 // packet (after some verification that it is indeed the HTTP protocol).
3963 ByteBuffer payload = fPayload;
3964 if (payload == null) {
3965 return null;
3966 }
3967
3968 return new UnknownPacket(getPcapFile(), this, payload);
3969 }
3970
3971 @Override
3972 public boolean validate() {
3973 // Not yet implemented. ATM, we consider that all packets are valid.
3974 // TODO Implement it. We can compute the real checksum and compare it to fChecksum.
3975 return true;
3976 }
3977
3978 @Override
3979 public UDPEndpoint getSourceEndpoint() {
3980 @Nullable
3981 UDPEndpoint endpoint = fSourceEndpoint;
3982 if (endpoint == null) {
3983 endpoint = new UDPEndpoint(this, true);
3984 }
3985 fSourceEndpoint = endpoint;
3986 return fSourceEndpoint;
3987 }
3988
3989 @Override
3990 public UDPEndpoint getDestinationEndpoint() {
3991 @Nullable UDPEndpoint endpoint = fDestinationEndpoint;
3992 if (endpoint == null) {
3993 endpoint = new UDPEndpoint(this, false);
3994 }
3995 fDestinationEndpoint = endpoint;
3996 return fDestinationEndpoint;
3997 }
3998
3999 @Override
4000 public Map<String, String> getFields() {
4001 ImmutableMap<String, String> map = fFields;
4002 if (map == null) {
4003 @SuppressWarnings("null")
4004 @NonNull ImmutableMap<String, String> newMap = ImmutableMap.<String, String> builder()
4005 .put("Source Port", String.valueOf(fSourcePort)) //$NON-NLS-1$
4006 .put("Destination Port", String.valueOf(fDestinationPort)) //$NON-NLS-1$
4007 .put("Length", String.valueOf(fTotalLength) + " bytes") //$NON-NLS-1$ //$NON-NLS-2$
4008 .put("Checksum", String.format("%s%04x", "0x", fChecksum)) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
4009 .build();
4010 fFields = newMap;
4011 return newMap;
4012 }
4013 return map;
4014 }
4015
4016 @Override
4017 public String getLocalSummaryString() {
4018 return "Src Port: " + fSourcePort + ", Dst Port: " + fDestinationPort; //$NON-NLS-1$ //$NON-NLS-2$
4019 }
4020
4021 @Override
4022 protected String getSignificationString() {
4023 return "Source Port: " + fSourcePort + ", Destination Port: " + fDestinationPort; //$NON-NLS-1$ //$NON-NLS-2$
4024 }
4025
4026 @Override
4027 public int hashCode() {
4028 final int prime = 31;
4029 int result = 1;
4030 result = prime * result + fChecksum;
4031 final Packet child = fChildPacket;
4032 if (child != null) {
4033 result = prime * result + child.hashCode();
4034 } else {
4035 result = prime * result;
4036 }
4037 result = prime * result + fDestinationPort;
4038 final ByteBuffer payload = fPayload;
4039 if (payload != null) {
4040 result = prime * result + payload.hashCode();
4041 } else {
4042 result = prime * result;
4043 }
4044 result = prime * result + fSourcePort;
4045 result = prime * result + fTotalLength;
4046 return result;
4047 }
4048
4049 @Override
4050 public boolean equals(@Nullable Object obj) {
4051 if (this == obj) {
4052 return true;
4053 }
4054 if (obj == null) {
4055 return false;
4056 }
4057 if (getClass() != obj.getClass()) {
4058 return false;
4059 }
4060 UDPPacket other = (UDPPacket) obj;
4061 if (fChecksum != other.fChecksum) {
4062 return false;
4063 }
4064 final Packet child = fChildPacket;
4065 if (child != null) {
4066 if (!child.equals(other.fChildPacket)) {
4067 return false;
4068 }
4069 } else {
4070 if (other.fChildPacket != null) {
4071 return false;
4072 }
4073 }
4074 if (fDestinationPort != other.fDestinationPort) {
4075 return false;
4076 }
4077 final ByteBuffer payload = fPayload;
4078 if (payload != null) {
4079 if (!payload.equals(other.fPayload)) {
4080 return false;
4081 }
4082 } else {
4083 if (other.fPayload != null) {
4084 return false;
4085 }
4086 }
4087 if (fSourcePort != other.fSourcePort) {
4088 return false;
4089 }
4090 if (fTotalLength != other.fTotalLength) {
4091 return false;
4092 }
4093 return true;
4094 }
4095</pre>
4096
4097The UDPPacket class is implemented. We now have the define the UDPEndpoint.
4098
4099=== Creating the UDPEndpoint ===
4100
4101For the UDP protocol, an endpoint will be its source or its destination port, depending if it is the source endpoint or destination endpoint. Knowing that, we can create our UDPEndpoint class.
4102
4103We create in our package a new class named UDPEndpoint that extends ProtocolEndpoint. We also add a field: fPort, which contains the source or destination port. We finally add a constructor public ExampleEndpoint(Packet packet, boolean isSourceEndpoint):
4104* ''Packet'' '''packet''': the packet to build the endpoint from.
4105* ''boolean'' '''isSourceEndpoint''': whether the endpoint is the source endpoint or destination endpoint.
4106
4107We obtain the following unimplemented class:
4108
4109<pre>
4110package org.eclipse.linuxtools.pcap.core.protocol.udp;
4111
4112import org.eclipse.linuxtools.pcap.core.endpoint.ProtocolEndpoint;
4113import org.eclipse.linuxtools.pcap.core.packet.Packet;
4114
4115public class UDPEndpoint extends ProtocolEndpoint {
4116
4117 private final int fPort;
4118
4119 public UDPEndpoint(Packet packet, boolean isSourceEndpoint) {
4120 super(packet, isSourceEndpoint);
4121 // TODO Auto-generated constructor stub
4122 }
4123
4124 @Override
4125 public int hashCode() {
4126 // TODO Auto-generated method stub
4127 return 0;
4128 }
4129
4130 @Override
4131 public boolean equals(Object obj) {
4132 // TODO Auto-generated method stub
4133 return false;
4134 }
4135
4136 @Override
4137 public String toString() {
4138 // TODO Auto-generated method stub
4139 return null;
4140 }
4141
4142}
4143</pre>
4144
4145For the constructor, we simply initialize fPort. If isSourceEndpoint is true, then we take packet.getSourcePort(), else we take packet.getDestinationPort().
4146
4147<pre>
4148 /**
4149 * Constructor of the {@link UDPEndpoint} class. It takes a packet to get
4150 * its endpoint. Since every packet has two endpoints (source and
4151 * destination), the isSourceEndpoint parameter is used to specify which
4152 * endpoint to take.
4153 *
4154 * @param packet
4155 * The packet that contains the endpoints.
4156 * @param isSourceEndpoint
4157 * Whether to take the source or the destination endpoint of the
4158 * packet.
4159 */
4160 public UDPEndpoint(UDPPacket packet, boolean isSourceEndpoint) {
4161 super(packet, isSourceEndpoint);
4162 fPort = isSourceEndpoint ? packet.getSourcePort() : packet.getDestinationPort();
4163 }
4164</pre>
4165
4166Then we implement the methods:
4167* ''public int'' '''hashCode()''': method that returns an integer based on the fields value. In our case, it will return an integer depending on fPort, and the parent endpoint that we can retrieve with getParentEndpoint().
4168* ''public boolean'' '''equals(Object obj)''': method that returns true if two objects are equals. In our case, two UDPEndpoints are equal if they both have the same fPort and have the same parent endpoint that we can retrieve with getParentEndpoint().
4169* ''public String'' '''toString()''': method that returns a description of the UDPEndpoint as a string. In our case, it will be a concatenation of the string of the parent endpoint and fPort as a string.
4170
4171<pre>
4172 @Override
4173 public int hashCode() {
4174 final int prime = 31;
4175 int result = 1;
4176 ProtocolEndpoint endpoint = getParentEndpoint();
4177 if (endpoint == null) {
4178 result = 0;
4179 } else {
4180 result = endpoint.hashCode();
4181 }
4182 result = prime * result + fPort;
4183 return result;
4184 }
4185
4186 @Override
4187 public boolean equals(@Nullable Object obj) {
4188 if (this == obj) {
4189 return true;
4190 }
4191 if (!(obj instanceof UDPEndpoint)) {
4192 return false;
4193 }
4194
4195 UDPEndpoint other = (UDPEndpoint) obj;
4196
4197 // Check on layer
4198 boolean localEquals = (fPort == other.fPort);
4199 if (!localEquals) {
4200 return false;
4201 }
4202
4203 // Check above layers.
4204 ProtocolEndpoint endpoint = getParentEndpoint();
4205 if (endpoint != null) {
4206 return endpoint.equals(other.getParentEndpoint());
4207 }
4208 return true;
4209 }
4210
4211 @Override
4212 public String toString() {
4213 ProtocolEndpoint endpoint = getParentEndpoint();
4214 if (endpoint == null) {
4215 @SuppressWarnings("null")
4216 @NonNull String ret = String.valueOf(fPort);
4217 return ret;
4218 }
4219 return endpoint.toString() + '/' + fPort;
4220 }
4221</pre>
4222
4223=== Registering the UDP protocol ===
4224
4225The last step is to register the new protocol. There are three places where the protocol has to be registered. First, the parser has to know that a new protocol has been added. This is defined in the enum org.eclipse.linuxtools.pcap.core.protocol.Protocol. Simply add the protocol name here, along with a few arguments:
4226* ''String'' '''longname''', which is the long version of name of the protocol. In our case, it is "User Datagram Protocol".
4227* ''String'' '''shortName''', which is the shortened name of the protocol. In our case, it is "UDP".
4228* ''int'' '''layer''', which is the layer to which the protocol belongs in the OSI model. In our case, this is the layer 4.
4229* ''boolean'' '''supportsStream''', which defines whether or not the protocol supports packet streams. In our case, this is set to true.
4230
4231Thus, the following line is added in the Prtotocol enum:
4232<pre>
4233 UDP("User Datagram Protocol", "udp", ProtocolValues.LAYER_4, true),
4234</pre>
4235
4236Also, TMF has to know about the new protocol. This is defined in org.eclipse.linuxtools.tmf.pcap.core.protocol.TmfProtocol. We simply add it with the '''EXACT SAME NAME''' as in the Protocol enum. Thus, the following line is added in the TmfProtocol enum:
4237<pre>
4238 UDP,
4239</pre>
4240
4241Finally, all the protocols that could be the parent of the new protocol (in our case, IPv4 and IPv6) have to be notified of the new protocol. This is done by modifying the findChildPacket() method of the packet class of those protocols. For instance, in IPv4Packet, we add a case in the switch statement of findChildPacket, if the Protocol number matches UDP's protocol number at the network layer:
4242<pre>
4243 @Override
4244 protected @Nullable Packet findChildPacket() throws BadPacketException {
4245 ByteBuffer payload = fPayload;
4246 if (payload == null) {
4247 return null;
4248 }
4249
4250 switch (fIpDatagramProtocol) {
4251 case IPProtocolNumberHelper.PROTOCOL_NUMBER_TCP:
4252 return new TCPPacket(getPcapFile(), this, payload);
4253 case IPProtocolNumberHelper.PROTOCOL_NUMBER_UDP:
4254 return new UDPPacket(getPcapFile(), this, payload);
4255 default:
4256 return new UnknownPacket(getPcapFile(), this, payload);
4257 }
4258 }
4259</pre>
4260
4261The new protocol has been added. Running TMF should work just fine, and the new protocol is now recognized.
4262
4263== Adding stream-based views ==
4264
4265To add a stream-based View, simply monitor the TmfPacketStreamSelectedSignal in your view. It contains the new stream that you can retrieve with signal.getStream(). You must then make an event request to the current trace to get the events, and use the stream to filter the events of interest. Therefore, you must also monitor TmfTraceOpenedSignal, TmfTraceClosedSignal and TmfTraceSelectedSignal. Examples of stream-based views include a view that represents the packets as a sequence diagram, or that shows the TCP connection state based on the packets SYN/ACK/FIN/RST flags. A (very very very early) draft of such a view can be found at https://git.eclipse.org/r/#/c/31054/.
4266
4267== TODO ==
4268
4269* Add more protocols. At the moment, only four protocols are supported. The following protocols would need to be implemented: ARP, SLL, WLAN, USB, IPv6, ICMP, ICMPv6, IGMP, IGMPv6, SCTP, DNS, FTP, HTTP, RTP, SIP, SSH and Telnet. Other VoIP protocols would be nice.
4270* Add a network graph view. It would be useful to produce graphs that are meaningful to network engineers, and that they could use (for presentation purpose, for instance). We could use the XML-based analysis to do that!
4271* Add a Stream Diagram view. This view would represent a stream as a Sequence Diagram. It would be updated when a TmfNewPacketStreamSignal is thrown. It would be easy to see the packet exchange and the time delta between each packet. Also, when a packet is selected in the Stream Diagram, it should be selected in the event table and its content should be shown in the Properties View. See https://git.eclipse.org/r/#/c/31054/ for a draft of such a view.
4272* Make adding protocol more "plugin-ish", via extension points for instance. This would make it easier to support new protocols, without modifying the source code.
4273* Control dumpcap directly from eclipse, similar to how LTTng is controlled in the Control View.
4274* Support pcapng. See: http://www.winpcap.org/ntar/draft/PCAP-DumpFileFormat.html for the file format.
4275* Add SWTBOT tests to org.eclipse.linuxtools.tmf.pcap.ui
4276* Add a Raw Viewer, similar to Wireshark. We could use the “Show Raw” in the event editor to do that.
4277* Externalize strings in org.eclipse.linuxtools.pcap.core. At the moment, all the strings are hardcoded. It would be good to externalize them all.
This page took 0.242061 seconds and 5 git commands to generate.