Upgrade to Tycho 0.22.0 (again) and newly released JBoss plugin 0.22.0
[deliverable/tracecompass.git] / org.eclipse.tracecompass.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
c3181353
MK
14* The ''org.eclipse.linuxtools.tmf.core.tracetype'' plug-in extension point
15* (Optional) The ''org.eclipse.linuxtools.tmf.ui.tracetypeui'' plug-in extension point
6f182760 16
73844f9c 17The '''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 18
73844f9c 19== An Example: Nexus-lite parser ==
6f182760 20
73844f9c 21=== Description of the file ===
6f182760 22
73844f9c 23This 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 24
73844f9c 25The 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
26
27<pre>
73844f9c 28Startup,Stop,Load,Add, ... ,reserved\n
6f182760
PT
29</pre>
30
73844f9c 31Then there will be the events in this format
6f182760 32
73844f9c
PT
33{| width= "85%"
34|style="width: 50%; background-color: #ffffcc;"|timestamp (32 bits)
35|style="width: 10%; background-color: #ffccff;"|type (6 bits)
36|style="width: 40%; background-color: #ccffcc;"|payload (26 bits)
37|-
38|style="background-color: #ffcccc;" colspan="3"|64 bits total
39|}
6f182760 40
73844f9c 41all events will be the same size (64 bits).
6f182760 42
73844f9c 43=== NexusLite Plug-in ===
6f182760 44
73844f9c 45Create a '''New''', '''Project...''', '''Plug-in Project''', set the title to '''com.example.nexuslite''', click '''Next >''' then click on '''Finish'''.
6f182760 46
73844f9c 47Now the structure for the Nexus trace Plug-in is set up.
6f182760 48
73844f9c 49Add 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 50
73844f9c
PT
51[[Image:images/NTTAddDepend.png]]<br>
52[[Image:images/NTTSelectProjects.png]]<br>
6f182760 53
73844f9c 54Now the project can access TMF classes.
6f182760 55
73844f9c 56=== Trace Event ===
6f182760 57
73844f9c 58The '''TmfEvent''' class will work for this example. No code required.
6f182760 59
73844f9c 60=== Trace Reader ===
6f182760 61
73844f9c 62The trace reader will extend a '''TmfTrace''' class.
6f182760 63
73844f9c 64It will need to implement:
6f182760 65
73844f9c 66* validate (is the trace format valid?)
6f182760 67
73844f9c 68* initTrace (called as the trace is opened
6f182760 69
73844f9c 70* seekEvent (go to a position in the trace and create a context)
6f182760 71
73844f9c 72* getNext (implemented in the base class)
6f182760 73
73844f9c 74* parseEvent (read the next element in the trace)
6f182760 75
c3181353
MK
76For reference, there is an example implementation of the Nexus Trace file in
77org.eclipse.linuxtools.tracing.examples.core.trace.nexus.NexusTrace.java.
6f182760 78
c3181353
MK
79In this example, the '''validate''' function checks first checks if the file
80exists, then makes sure that it is really a file, and not a directory. Then we
81attempt to read the file header, to make sure that it is really a Nexus Trace.
82If that check passes, we return a TmfValidationStatus with a confidence of 20.
6f182760 83
c3181353
MK
84Typically, TmfValidationStatus confidences should range from 1 to 100. 1 meaning
85"there is a very small chance that this trace is of this type", and 100 meaning
86"it is this type for sure, and cannot be anything else". At run-time, the
87auto-detection will pick the the type which returned the highest confidence. So
88checks of the type "does the file exist?" should not return a too high
89confidence.
6f182760 90
c3181353
MK
91Here we used a confidence of 20, to leave "room" for more specific trace types
92in the Nexus format that could be defined in TMF.
6f182760 93
73844f9c 94The '''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 95
73844f9c 96The '''seek''' here will just reset the reader to the right location.
6f182760 97
73844f9c 98The '''parseEvent''' method needs to parse and return the current event and store the current location.
6f182760 99
73844f9c 100The '''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 101
c3181353
MK
102Traces will typically implement an index, to make seeking faster. The index can
103be rebuilt every time the trace is opened. Alternatively, it can be saved to
104disk, to make future openings of the same trace quicker. To do so, the trace
105object can implement the '''ITmfPersistentlyIndexable''' interface.
106
73844f9c 107=== Trace Context ===
6f182760 108
73844f9c 109The trace context will be a '''TmfContext'''
6f182760 110
73844f9c 111=== Trace Location ===
6f182760 112
73844f9c 113The 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 114
c3181353 115=== The ''org.eclipse.linuxtools.tmf.core.tracetype'' and ''org.eclipse.linuxtools.tmf.ui.tracetypeui'' plug-in extension point ===
6f182760 116
c3181353
MK
117One should implement the ''tmf.core.tracetype'' extension in their own plug-in.
118In this example, the Nexus trace plug-in will be modified.
6f182760 119
73844f9c 120The '''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 121
c3181353 122# In Extensions tab, add the '''org.eclipse.linuxtools.tmf.core.tracetype''' extension point.
73844f9c
PT
123[[Image:images/NTTExtension.png]]<br>
124[[Image:images/NTTTraceType.png]]<br>
125[[Image:images/NTTExtensionPoint.png]]<br>
6f182760 126
73844f9c 127# 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 128
73844f9c 129[[Image:images/NTTAddType.png]]<br>
6f182760 130
73844f9c 131The '''id''' is the unique identifier used to refer to the trace.
6f182760 132
73844f9c 133The '''name''' is the field that shall be displayed when a trace type is selected.
6f182760 134
73844f9c 135The '''trace type''' is the canonical path refering to the class of the trace.
6f182760 136
73844f9c 137The '''event type''' is the canonical path refering to the class of the events of a given trace.
6f182760 138
73844f9c 139The '''category''' (optional) is the container in which this trace type will be stored.
6f182760 140
c3181353
MK
141# (Optional) To also add UI-specific properties to your trace type, use the '''org.eclipse.linuxtools.tmf.ui.tracetypeui''' extension. To do that,
142'''right click''' on the extension then in the context menu, go to
143'''New >''', '''type'''.
144
145The '''tracetype''' here is the '''id''' of the
146''org.eclipse.linuxtools.tmf.core.tracetype'' mentioned above.
147
148The '''icon''' is the image to associate with that trace type.
6f182760 149
73844f9c 150In the end, the extension menu should look like this.
6f182760 151
73844f9c 152[[Image:images/NTTPluginxmlComplete.png]]<br>
6f182760 153
7e802456
BH
154== Other Considerations ==
155The ''org.eclipse.linuxtools.tmf.ui.viewers.events.TmfEventsTable'' provides additional features that are active when the event class (defined in '''event type''') implements certain additional interfaces.
156
157=== Collapsing of repetitive events ===
158By implementing the interface ''org.eclipse.linuxtools.tmf.core.event.collapse.ITmfCollapsibleEvent'' the events table will allow to collapse repetitive events by selecting the menu item '''Collapse Events''' after pressing the right mouse button in the table.
159
73844f9c 160== Best Practices ==
6f182760 161
73844f9c
PT
162* Do not load the whole trace in RAM, it will limit the size of the trace that can be read.
163* Reuse as much code as possible, it makes the trace format much easier to maintain.
c3181353 164* Use Eclipse's editor instead of editing the XML directly.
73844f9c 165* Do not forget Java supports only signed data types, there may be special care needed to handle unsigned data.
c3181353
MK
166* If the support for your trace has custom UI elements (like icons, views, etc.), split the core and UI parts in separate plugins, named identically except for a ''.core'' or ''.ui'' suffix.
167** Implement the ''tmf.core.tracetype'' extension in the core plugin, and the ''tmf.ui.tracetypeui'' extension in the UI plugin if applicable.
6f182760 168
73844f9c 169== Download the Code ==
6f182760 170
c3181353
MK
171The described example is available in the
172org.eclipse.linuxtools.tracing.examples.(tests.)trace.nexus packages with a
173trace generator and a quick test case.
6f182760 174
3be48e26 175== Optional Trace Type Attributes ==
c3181353 176
3be48e26
BH
177After defining the trace type as described in the previous chapters it is possible to define optional attributes for the trace type.
178
179=== Default Editor ===
c3181353
MK
180
181The '''defaultEditor''' attribute of the '''org.eclipse.tmf.ui.tracetypeui'''
182extension point allows for configuring the editor to use for displaying the
183events. If omitted, the ''TmfEventsEditor'' is used as default.
184
185To configure an editor, first add the '''defaultEditor''' attribute to the trace
186type in the extension definition. This can be done by selecting the trace type
187in the plug-in manifest editor. Then click the right mouse button and select
188'''New -> defaultEditor''' in the context sensitive menu. Then select the newly
189added attribute. Now you can specify the editor id to use on the right side of
190the manifest editor. For example, this attribute could be used to implement an
191extension of the class ''org.eclipse.ui.part.MultiPageEditor''. The first page
192could use the ''TmfEventsEditor''' to display the events in a table as usual and
193other pages can display other aspects of the trace.
3be48e26
BH
194
195=== Events Table Type ===
3be48e26 196
c3181353
MK
197The '''eventsTableType''' attribute of the '''org.eclipse.tmf.ui.tracetypeui'''
198extension point allows for configuring the events table class to use in the
199default events editor. If omitted, the default events table will be used.
200
201To configure a trace type specific events table, first add the
202'''eventsTableType''' attribute to the trace type in the extension definition.
203This can be done by selecting the trace type in the plug-in manifest editor.
204Then click the right mouse button and select '''New -> eventsTableType''' in the
205context sensitive menu. Then select the newly added attribute and click on
206''class'' on the right side of the manifest editor. The new class wizard will
207open. The ''superclass'' field will be already filled with the class ''org.eclipse.linuxtools.tmf.ui.viewers.events.TmfEventsTable''.
208
209By using this attribute, a table with different columns than the default columns
210can be defined. See the class org.eclipse.linuxtools.internal.lttng2.kernel.ui.viewers.events.Lttng2EventsTable
211for an example implementation.
3be48e26 212
c3181353 213= View Tutorial =
6f182760 214
73844f9c 215This 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 216
73844f9c 217This tutorial will cover concepts like:
6f182760 218
73844f9c
PT
219* Extending TmfView
220* Signal handling (@TmfSignalHandler)
221* Data requests (TmfEventRequest)
222* SWTChart integration
6f182760 223
c3181353
MK
224'''Note''': TMF 3.0.0 provides base implementations for generating SWTChart viewers and views. For more details please refer to chapter [[#TMF Built-in Views and Viewers]].
225
73844f9c 226=== Prerequisites ===
6f182760 227
f2072ab5 228The 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 229
73844f9c 230=== Creating an Eclipse UI Plug-in ===
6f182760 231
73844f9c
PT
232To create a new project with name org.eclipse.linuxtools.tmf.sample.ui select '''File -> New -> Project -> Plug-in Development -> Plug-in Project'''. <br>
233[[Image:images/Screenshot-NewPlug-inProject1.png]]<br>
6f182760 234
73844f9c 235[[Image:images/Screenshot-NewPlug-inProject2.png]]<br>
6f182760 236
73844f9c 237[[Image:images/Screenshot-NewPlug-inProject3.png]]<br>
6f182760 238
73844f9c 239=== Creating a View ===
6f182760 240
73844f9c
PT
241To open the plug-in manifest, double-click on the MANIFEST.MF file. <br>
242[[Image:images/SelectManifest.png]]<br>
6f182760 243
73844f9c
PT
244Change 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>
245Following the same steps, add ''org.eclipse.linuxtools.tmf.ui'' and ''org.swtchart''.<br>
246[[Image:images/AddDependencyTmfUi.png]]<br>
6f182760 247
73844f9c
PT
248Change 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>
249[[Image:images/AddViewExtension1.png]]<br>
6f182760 250
73844f9c
PT
251To create a view, click the right mouse button. Then select '''New -> view'''<br>
252[[Image:images/AddViewExtension2.png]]<br>
6f182760 253
73844f9c
PT
254A 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>
255[[Image:images/FillSampleViewExtension.png]]<br>
6f182760 256
73844f9c 257This will generate an empty class. Once the quick fixes are applied, the following code is obtained:
6f182760 258
73844f9c
PT
259<pre>
260package org.eclipse.linuxtools.tmf.sample.ui;
6f182760 261
73844f9c
PT
262import org.eclipse.swt.widgets.Composite;
263import org.eclipse.ui.part.ViewPart;
6f182760 264
73844f9c 265public class SampleView extends TmfView {
6f182760 266
73844f9c
PT
267 public SampleView(String viewName) {
268 super(viewName);
269 // TODO Auto-generated constructor stub
270 }
6f182760 271
73844f9c
PT
272 @Override
273 public void createPartControl(Composite parent) {
274 // TODO Auto-generated method stub
6f182760 275
73844f9c 276 }
6f182760 277
73844f9c
PT
278 @Override
279 public void setFocus() {
280 // TODO Auto-generated method stub
6f182760 281
73844f9c 282 }
6f182760 283
73844f9c
PT
284}
285</pre>
6f182760 286
73844f9c 287This creates an empty view, however the basic structure is now is place.
6f182760 288
73844f9c 289=== Implementing a view ===
6f182760 290
73844f9c 291We 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 292
73844f9c 293==== Adding an Empty Chart ====
6f182760 294
73844f9c 295First, we can add an empty chart to the view and initialize some of its components.
6f182760 296
73844f9c
PT
297<pre>
298 private static final String SERIES_NAME = "Series";
299 private static final String Y_AXIS_TITLE = "Signal";
300 private static final String X_AXIS_TITLE = "Time";
301 private static final String FIELD = "value"; // The name of the field that we want to display on the Y axis
302 private static final String VIEW_ID = "org.eclipse.linuxtools.tmf.sample.ui.view";
303 private Chart chart;
304 private ITmfTrace currentTrace;
6f182760 305
73844f9c
PT
306 public SampleView() {
307 super(VIEW_ID);
308 }
6f182760 309
73844f9c
PT
310 @Override
311 public void createPartControl(Composite parent) {
312 chart = new Chart(parent, SWT.BORDER);
313 chart.getTitle().setVisible(false);
314 chart.getAxisSet().getXAxis(0).getTitle().setText(X_AXIS_TITLE);
315 chart.getAxisSet().getYAxis(0).getTitle().setText(Y_AXIS_TITLE);
316 chart.getSeriesSet().createSeries(SeriesType.LINE, SERIES_NAME);
317 chart.getLegend().setVisible(false);
318 }
6f182760 319
73844f9c
PT
320 @Override
321 public void setFocus() {
322 chart.setFocus();
323 }
324</pre>
6f182760 325
73844f9c
PT
326The view is prepared. Run the Example. To launch the an Eclipse Application select the ''Overview'' tab and click on '''Launch an Eclipse Application'''<br>
327[[Image:images/RunEclipseApplication.png]]<br>
6f182760 328
73844f9c
PT
329A new Eclipse application window will show. In the new window go to '''Windows -> Show View -> Other... -> Other -> Sample View'''.<br>
330[[Image:images/ShowViewOther.png]]<br>
6f182760 331
73844f9c
PT
332You should now see a view containing an empty chart<br>
333[[Image:images/EmptySampleView.png]]<br>
6f182760 334
73844f9c 335==== Signal Handling ====
6f182760 336
73844f9c 337We 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 338
73844f9c
PT
339<pre>
340 @TmfSignalHandler
341 public void traceSelected(final TmfTraceSelectedSignal signal) {
6f182760 342
73844f9c
PT
343 }
344</pre>
067490ab 345
73844f9c 346==== Requesting Data ====
067490ab 347
73844f9c 348Then we need to actually gather data from the trace. This is done asynchronously using a ''TmfEventRequest''
067490ab 349
73844f9c
PT
350<pre>
351 @TmfSignalHandler
352 public void traceSelected(final TmfTraceSelectedSignal signal) {
353 // Don't populate the view again if we're already showing this trace
354 if (currentTrace == signal.getTrace()) {
355 return;
356 }
357 currentTrace = signal.getTrace();
067490ab 358
73844f9c 359 // Create the request to get data from the trace
067490ab 360
73844f9c 361 TmfEventRequest req = new TmfEventRequest(TmfEvent.class,
f2072ab5
MAL
362 TmfTimeRange.ETERNITY, 0, ITmfEventRequest.ALL_DATA,
363 ITmfEventRequest.ExecutionType.BACKGROUND) {
067490ab 364
73844f9c
PT
365 @Override
366 public void handleData(ITmfEvent data) {
367 // Called for each event
368 super.handleData(data);
369 }
067490ab 370
73844f9c
PT
371 @Override
372 public void handleSuccess() {
373 // Request successful, not more data available
374 super.handleSuccess();
375 }
376
377 @Override
378 public void handleFailure() {
379 // Request failed, not more data available
380 super.handleFailure();
381 }
382 };
383 ITmfTrace trace = signal.getTrace();
384 trace.sendRequest(req);
385 }
067490ab
AM
386</pre>
387
73844f9c 388==== Transferring Data to the Chart ====
067490ab 389
73844f9c 390The 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 391
73844f9c
PT
392<pre>
393 TmfEventRequest req = new TmfEventRequest(TmfEvent.class,
f2072ab5
MAL
394 TmfTimeRange.ETERNITY, 0, ITmfEventRequest.ALL_DATA,
395 ITmfEventRequest.ExecutionType.BACKGROUND) {
067490ab 396
73844f9c
PT
397 ArrayList<Double> xValues = new ArrayList<Double>();
398 ArrayList<Double> yValues = new ArrayList<Double>();
067490ab 399
73844f9c
PT
400 @Override
401 public void handleData(ITmfEvent data) {
402 // Called for each event
403 super.handleData(data);
404 ITmfEventField field = data.getContent().getField(FIELD);
405 if (field != null) {
406 yValues.add((Double) field.getValue());
407 xValues.add((double) data.getTimestamp().getValue());
408 }
409 }
067490ab 410
73844f9c
PT
411 @Override
412 public void handleSuccess() {
413 // Request successful, not more data available
414 super.handleSuccess();
067490ab 415
73844f9c
PT
416 final double x[] = toArray(xValues);
417 final double y[] = toArray(yValues);
067490ab 418
73844f9c
PT
419 // This part needs to run on the UI thread since it updates the chart SWT control
420 Display.getDefault().asyncExec(new Runnable() {
067490ab 421
73844f9c
PT
422 @Override
423 public void run() {
424 chart.getSeriesSet().getSeries()[0].setXSeries(x);
425 chart.getSeriesSet().getSeries()[0].setYSeries(y);
067490ab 426
73844f9c
PT
427 chart.redraw();
428 }
067490ab 429
73844f9c
PT
430 });
431 }
067490ab 432
73844f9c
PT
433 /**
434 * Convert List<Double> to double[]
435 */
436 private double[] toArray(List<Double> list) {
437 double[] d = new double[list.size()];
438 for (int i = 0; i < list.size(); ++i) {
439 d[i] = list.get(i);
440 }
067490ab 441
73844f9c
PT
442 return d;
443 }
444 };
445</pre>
067490ab 446
73844f9c 447==== Adjusting the Range ====
067490ab 448
73844f9c 449The 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 450
73844f9c 451<pre>
067490ab 452
73844f9c
PT
453 ArrayList<Double> xValues = new ArrayList<Double>();
454 ArrayList<Double> yValues = new ArrayList<Double>();
455 private double maxY = -Double.MAX_VALUE;
456 private double minY = Double.MAX_VALUE;
457 private double maxX = -Double.MAX_VALUE;
458 private double minX = Double.MAX_VALUE;
067490ab 459
73844f9c
PT
460 @Override
461 public void handleData(ITmfEvent data) {
462 super.handleData(data);
463 ITmfEventField field = data.getContent().getField(FIELD);
464 if (field != null) {
465 Double yValue = (Double) field.getValue();
466 minY = Math.min(minY, yValue);
467 maxY = Math.max(maxY, yValue);
468 yValues.add(yValue);
067490ab 469
73844f9c
PT
470 double xValue = (double) data.getTimestamp().getValue();
471 xValues.add(xValue);
472 minX = Math.min(minX, xValue);
473 maxX = Math.max(maxX, xValue);
474 }
475 }
067490ab 476
73844f9c
PT
477 @Override
478 public void handleSuccess() {
479 super.handleSuccess();
480 final double x[] = toArray(xValues);
481 final double y[] = toArray(yValues);
067490ab 482
73844f9c
PT
483 // This part needs to run on the UI thread since it updates the chart SWT control
484 Display.getDefault().asyncExec(new Runnable() {
067490ab 485
73844f9c
PT
486 @Override
487 public void run() {
488 chart.getSeriesSet().getSeries()[0].setXSeries(x);
489 chart.getSeriesSet().getSeries()[0].setYSeries(y);
067490ab 490
73844f9c
PT
491 // Set the new range
492 if (!xValues.isEmpty() && !yValues.isEmpty()) {
493 chart.getAxisSet().getXAxis(0).setRange(new Range(0, x[x.length - 1]));
494 chart.getAxisSet().getYAxis(0).setRange(new Range(minY, maxY));
495 } else {
496 chart.getAxisSet().getXAxis(0).setRange(new Range(0, 1));
497 chart.getAxisSet().getYAxis(0).setRange(new Range(0, 1));
498 }
499 chart.getAxisSet().adjustRange();
067490ab 500
73844f9c
PT
501 chart.redraw();
502 }
503 });
504 }
505</pre>
067490ab 506
73844f9c 507==== Formatting the Time Stamps ====
067490ab 508
73844f9c 509To 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 510
73844f9c
PT
511<pre>
512 @Override
513 public void createPartControl(Composite parent) {
514 ...
067490ab 515
73844f9c
PT
516 chart.getAxisSet().getXAxis(0).getTick().setFormat(new TmfChartTimeStampFormat());
517 }
067490ab 518
73844f9c
PT
519 public class TmfChartTimeStampFormat extends SimpleDateFormat {
520 private static final long serialVersionUID = 1L;
521 @Override
522 public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
523 long time = date.getTime();
524 toAppendTo.append(TmfTimestampFormat.getDefaulTimeFormat().format(time));
525 return toAppendTo;
526 }
527 }
067490ab 528
73844f9c
PT
529 @TmfSignalHandler
530 public void timestampFormatUpdated(TmfTimestampFormatUpdateSignal signal) {
531 // Called when the time stamp preference is changed
532 chart.getAxisSet().getXAxis(0).getTick().setFormat(new TmfChartTimeStampFormat());
533 chart.redraw();
534 }
535</pre>
067490ab 536
73844f9c 537We 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 538
73844f9c
PT
539<pre>
540 @Override
541 public void createPartControl(Composite parent) {
542 ...
067490ab 543
73844f9c
PT
544 ITmfTrace trace = getActiveTrace();
545 if (trace != null) {
546 traceSelected(new TmfTraceSelectedSignal(this, trace));
547 }
548 }
549</pre>
067490ab 550
73844f9c 551The 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 552
73844f9c 553[[Image:images/SampleView.png]]<br>
067490ab 554
73844f9c 555In 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 556
c3181353
MK
557== TMF Built-in Views and Viewers ==
558
559TMF provides base implementations for several types of views and viewers for generating custom X-Y-Charts, Time Graphs, or Trees. They are well integrated with various TMF features such as reading traces and time synchronization with other views. They also handle mouse events for navigating the trace and view, zooming or presenting detailed information at mouse position. The code can be found in the TMF UI plug-in ''org.eclipse.linuxtools.tmf.ui''. See below for a list of relevant java packages:
560
561* Generic
562** ''org.eclipse.linuxtools.tmf.ui.views'': Common TMF view base classes
563* X-Y-Chart
564** ''org.eclipse.linuxtools.tmf.ui.viewers.xycharts'': Common base classes for X-Y-Chart viewers based on SWTChart
565** ''org.eclipse.linuxtools.tmf.ui.viewers.xycharts.barcharts'': Base classes for bar charts
566** ''org.eclipse.linuxtools.tmf.ui.viewers.xycharts.linecharts'': Base classes for line charts
567* Time Graph View
568** ''org.eclipse.linuxtools.tmf.ui.widgets.timegraph'': Base classes for time graphs e.g. Gantt-charts
569* Tree Viewer
570** ''org.eclipse.linuxtools.tmf.ui.viewers.tree'': Base classes for TMF specific tree viewers
571
572Several features in TMF and the Eclipse LTTng integration are using this framework and can be used as example for further developments:
573* X-Y- Chart
574** ''org.eclipse.linuxtools.internal.lttng2.ust.ui.views.memusage.MemUsageView.java''
575** ''org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.cpuusage.CpuUsageView.java''
576** ''org.eclipse.linuxtools.tracing.examples.ui.views.histogram.NewHistogramView.java''
577* Time Graph View
578** ''org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.controlflow.ControlFlowView.java''
579** ''org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.resources.ResourcesView.java''
580* Tree Viewer
581** ''org.eclipse.linuxtools.tmf.ui.views.statesystem.TmfStateSystemExplorer.java''
582** ''org.eclipse.linuxtools.internal.lttng2.kernel.ui.views.cpuusage.CpuUsageComposite.java''
583
73844f9c 584= Component Interaction =
067490ab 585
73844f9c 586TMF 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 587
73844f9c 588The TMF Signal Manager handles registration of components and the broadcasting of signals to their intended receivers.
067490ab 589
73844f9c 590Components can register as VIP receivers which will ensure they will receive the signal before non-VIP receivers.
067490ab 591
73844f9c 592== Sending Signals ==
067490ab 593
73844f9c 594In 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 595
73844f9c
PT
596<pre>
597TmfExampleSignal signal = new TmfExampleSignal(this, ...);
598TmfSignalManager.dispatchSignal(signal);
599</pre>
067490ab 600
73844f9c 601If the sender is an instance of the class TmfComponent, the broadcast method can be used:
067490ab
AM
602
603<pre>
73844f9c
PT
604TmfExampleSignal signal = new TmfExampleSignal(this, ...);
605broadcast(signal);
606</pre>
067490ab 607
73844f9c 608== Receiving Signals ==
067490ab 609
73844f9c 610In 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 611
73844f9c
PT
612<pre>
613TmfSignalManager.register(this);
614TmfSignalManager.registerVIP(this);
615</pre>
067490ab 616
73844f9c 617If the receiver is an instance of the class TmfComponent, it is automatically registered as a normal receiver in the constructor.
067490ab 618
73844f9c 619When the receiver is destroyed or disposed, it should deregister itself from the signal manager.
067490ab 620
73844f9c
PT
621<pre>
622TmfSignalManager.deregister(this);
623</pre>
067490ab 624
73844f9c 625To 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 626
73844f9c
PT
627<pre>
628@TmfSignalHandler
629public void example(TmfExampleSignal signal) {
630 ...
631}
067490ab
AM
632</pre>
633
73844f9c 634The 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 635
73844f9c
PT
636== Signal Throttling ==
637
638It 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.
639
640The signal throttler must first be initialized:
067490ab
AM
641
642<pre>
73844f9c
PT
643final int delay = 100; // in ms
644TmfSignalThrottler throttler = new TmfSignalThrottler(this, delay);
645</pre>
067490ab 646
73844f9c 647Then the sending of signals should be queued through the throttler:
067490ab 648
73844f9c
PT
649<pre>
650TmfExampleSignal signal = new TmfExampleSignal(this, ...);
651throttler.queue(signal);
652</pre>
067490ab 653
73844f9c 654When the throttler is no longer needed, it should be disposed:
067490ab 655
73844f9c
PT
656<pre>
657throttler.dispose();
658</pre>
067490ab 659
73844f9c 660== Signal Reference ==
067490ab 661
73844f9c 662The following is a list of built-in signals defined in the framework.
067490ab 663
73844f9c 664=== TmfStartSynchSignal ===
067490ab 665
73844f9c 666''Purpose''
067490ab 667
73844f9c 668This 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 669
73844f9c 670''Senders''
067490ab 671
73844f9c 672Sent by TmfSignalManager before dispatching a signal to all receivers.
067490ab 673
73844f9c 674''Receivers''
067490ab 675
73844f9c 676Received by TmfDataProvider.
067490ab 677
73844f9c 678=== TmfEndSynchSignal ===
067490ab 679
73844f9c 680''Purpose''
067490ab 681
73844f9c 682This 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 683
73844f9c 684''Senders''
067490ab 685
73844f9c 686Sent by TmfSignalManager after dispatching a signal to all receivers.
067490ab 687
73844f9c 688''Receivers''
067490ab 689
73844f9c 690Received by TmfDataProvider.
067490ab 691
73844f9c 692=== TmfTraceOpenedSignal ===
067490ab 693
73844f9c 694''Purpose''
067490ab 695
73844f9c 696This signal is used to indicate that a trace has been opened in an editor.
067490ab 697
73844f9c 698''Senders''
067490ab 699
73844f9c 700Sent by a TmfEventsEditor instance when it is created.
067490ab 701
73844f9c 702''Receivers''
067490ab 703
73844f9c 704Received by TmfTrace, TmfExperiment, TmfTraceManager and every view that shows trace data. Components that show trace data should handle this signal.
067490ab 705
73844f9c 706=== TmfTraceSelectedSignal ===
067490ab 707
73844f9c 708''Purpose''
067490ab 709
73844f9c 710This signal is used to indicate that a trace has become the currently selected trace.
067490ab 711
73844f9c 712''Senders''
067490ab 713
73844f9c 714Sent by a TmfEventsEditor instance when it receives focus. Components can send this signal to make a trace editor be brought to front.
067490ab 715
73844f9c 716''Receivers''
067490ab 717
73844f9c 718Received by TmfTraceManager and every view that shows trace data. Components that show trace data should handle this signal.
067490ab 719
73844f9c 720=== TmfTraceClosedSignal ===
067490ab 721
73844f9c 722''Purpose''
067490ab 723
73844f9c 724This signal is used to indicate that a trace editor has been closed.
067490ab 725
73844f9c 726''Senders''
067490ab 727
73844f9c 728Sent by a TmfEventsEditor instance when it is disposed.
067490ab 729
73844f9c 730''Receivers''
067490ab 731
73844f9c 732Received by TmfTraceManager and every view that shows trace data. Components that show trace data should handle this signal.
067490ab 733
73844f9c 734=== TmfTraceRangeUpdatedSignal ===
067490ab 735
73844f9c 736''Purpose''
067490ab 737
73844f9c 738This 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 739
73844f9c 740''Senders''
11252342 741
73844f9c 742Sent 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 743
73844f9c 744''Receivers''
067490ab 745
73844f9c 746Received by TmfTrace, TmfExperiment and components that process trace events. Components that need to process trace events should handle this signal.
067490ab 747
73844f9c 748=== TmfTraceUpdatedSignal ===
067490ab 749
73844f9c 750''Purpose''
067490ab 751
73844f9c 752This signal is used to indicate that new events have been indexed for a trace.
067490ab 753
73844f9c 754''Senders''
067490ab 755
73844f9c 756Sent by TmfCheckpointIndexer when new events have been indexed and the number of events has changed.
067490ab 757
73844f9c 758''Receivers''
067490ab 759
73844f9c 760Received by components that need to be notified of a new trace event count.
067490ab 761
73844f9c 762=== TmfTimeSynchSignal ===
067490ab 763
73844f9c 764''Purpose''
067490ab 765
421b90a1
BH
766This signal is used to indicate that a new time or time range has been
767selected. It contains a begin and end time. If a single time is selected then
768the begin and end time are the same.
067490ab 769
73844f9c 770''Senders''
067490ab 771
421b90a1 772Sent by any component that allows the user to select a time or time range.
067490ab 773
73844f9c 774''Receivers''
067490ab 775
421b90a1 776Received by any component that needs to be notified of the currently selected time or time range.
067490ab 777
73844f9c 778=== TmfRangeSynchSignal ===
067490ab 779
73844f9c 780''Purpose''
067490ab 781
73844f9c 782This signal is used to indicate that a new time range window has been set.
067490ab 783
73844f9c 784''Senders''
067490ab 785
73844f9c 786Sent by any component that allows the user to set a time range window.
067490ab 787
73844f9c 788''Receivers''
067490ab 789
73844f9c 790Received by any component that needs to be notified of the current visible time range window.
067490ab 791
73844f9c 792=== TmfEventFilterAppliedSignal ===
067490ab 793
73844f9c 794''Purpose''
067490ab 795
73844f9c 796This signal is used to indicate that a filter has been applied to a trace.
067490ab 797
73844f9c 798''Senders''
067490ab 799
73844f9c 800Sent by TmfEventsTable when a filter is applied.
067490ab 801
73844f9c 802''Receivers''
067490ab 803
73844f9c 804Received by any component that shows trace data and needs to be notified of applied filters.
067490ab 805
73844f9c 806=== TmfEventSearchAppliedSignal ===
067490ab 807
73844f9c 808''Purpose''
067490ab 809
73844f9c 810This signal is used to indicate that a search has been applied to a trace.
067490ab 811
73844f9c 812''Senders''
067490ab 813
73844f9c 814Sent by TmfEventsTable when a search is applied.
067490ab 815
73844f9c 816''Receivers''
067490ab 817
73844f9c 818Received by any component that shows trace data and needs to be notified of applied searches.
067490ab 819
73844f9c 820=== TmfTimestampFormatUpdateSignal ===
067490ab 821
73844f9c 822''Purpose''
067490ab 823
73844f9c 824This signal is used to indicate that the timestamp format preference has been updated.
067490ab 825
73844f9c 826''Senders''
067490ab 827
73844f9c 828Sent by TmfTimestampFormat when the default timestamp format preference is changed.
067490ab 829
73844f9c 830''Receivers''
067490ab 831
73844f9c 832Received by any component that needs to refresh its display for the new timestamp format.
067490ab 833
73844f9c 834=== TmfStatsUpdatedSignal ===
067490ab 835
73844f9c 836''Purpose''
067490ab 837
73844f9c 838This signal is used to indicate that the statistics data model has been updated.
067490ab 839
73844f9c 840''Senders''
067490ab 841
73844f9c 842Sent by statistic providers when new statistics data has been processed.
067490ab 843
73844f9c 844''Receivers''
067490ab 845
73844f9c 846Received by statistics viewers and any component that needs to be notified of a statistics update.
067490ab 847
2c20bbb3
VP
848=== TmfPacketStreamSelected ===
849
850''Purpose''
851
852This signal is used to indicate that the user has selected a packet stream to analyze.
853
854''Senders''
855
856Sent by the Stream List View when the user selects a new packet stream.
857
858''Receivers''
859
860Received by views that analyze packet streams.
861
73844f9c 862== Debugging ==
067490ab 863
73844f9c 864TMF 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 865
73844f9c 866All signals sent and received will be logged to the file TmfTrace.log located in the Eclipse home directory.
067490ab 867
73844f9c 868= Generic State System =
067490ab 869
73844f9c 870== Introduction ==
067490ab 871
73844f9c
PT
872The Generic State System is a utility available in TMF to track different states
873over the duration of a trace. It works by first sending some or all events of
874the trace into a state provider, which defines the state changes for a given
875trace type. Once built, views and analysis modules can then query the resulting
876database of states (called "state history") to get information.
067490ab 877
73844f9c
PT
878For example, let's suppose we have the following sequence of events in a kernel
879trace:
067490ab 880
73844f9c
PT
881 10 s, sys_open, fd = 5, file = /home/user/myfile
882 ...
883 15 s, sys_read, fd = 5, size=32
884 ...
885 20 s, sys_close, fd = 5
067490ab 886
73844f9c 887Now let's say we want to implement an analysis module which will track the
2c20bbb3 888amount of bytes read and written to each file. Here, of course the sys_read is
73844f9c
PT
889interesting. However, by just looking at that event, we have no information on
890which file is being read, only its fd (5) is known. To get the match
891fd5 = /home/user/myfile, we have to go back to the sys_open event which happens
8925 seconds earlier.
067490ab 893
73844f9c
PT
894But since we don't know exactly where this sys_open event is, we will have to go
895back to the very start of the trace, and look through events one by one! This is
896obviously not efficient, and will not scale well if we want to analyze many
897similar patterns, or for very large traces.
067490ab 898
73844f9c
PT
899A solution in this case would be to use the state system to keep track of the
900amount of bytes read/written to every *filename* (instead of every file
901descriptor, like we get from the events). Then the module could ask the state
902system "what is the amount of bytes read for file "/home/user/myfile" at time
90316 s", and it would return the answer "32" (assuming there is no other read
904than the one shown).
067490ab 905
73844f9c 906== High-level components ==
067490ab 907
73844f9c
PT
908The State System infrastructure is composed of 3 parts:
909* The state provider
910* The central state system
911* The storage backend
067490ab 912
73844f9c
PT
913The state provider is the customizable part. This is where the mapping from
914trace events to state changes is done. This is what you want to implement for
915your specific trace type and analysis type. It's represented by the
916ITmfStateProvider interface (with a threaded implementation in
917AbstractTmfStateProvider, which you can extend).
067490ab 918
73844f9c
PT
919The core of the state system is exposed through the ITmfStateSystem and
920ITmfStateSystemBuilder interfaces. The former allows only read-only access and
921is typically used for views doing queries. The latter also allows writing to the
922state history, and is typically used by the state provider.
067490ab 923
73844f9c
PT
924Finally, each state system has its own separate backend. This determines how the
925intervals, or the "state history", are saved (in RAM, on disk, etc.) You can
926select the type of backend at construction time in the TmfStateSystemFactory.
067490ab 927
73844f9c 928== Definitions ==
067490ab 929
73844f9c
PT
930Before we dig into how to use the state system, we should go over some useful
931definitions:
067490ab 932
73844f9c 933=== Attribute ===
067490ab 934
73844f9c
PT
935An attribute is the smallest element of the model that can be in any particular
936state. When we refer to the "full state", in fact it means we are interested in
937the state of every single attribute of the model.
067490ab 938
73844f9c 939=== Attribute Tree ===
067490ab 940
73844f9c
PT
941Attributes in the model can be placed in a tree-like structure, a bit like files
942and directories in a file system. However, note that an attribute can always
943have both a value and sub-attributes, so they are like files and directories at
944the same time. We are then able to refer to every single attribute with its
945path in the tree.
067490ab 946
73844f9c
PT
947For example, in the attribute tree for LTTng kernel traces, we use the following
948attributes, among others:
067490ab 949
73844f9c
PT
950<pre>
951|- Processes
952| |- 1000
953| | |- PPID
954| | |- Exec_name
955| |- 1001
956| | |- PPID
957| | |- Exec_name
958| ...
959|- CPUs
960 |- 0
961 | |- Status
962 | |- Current_pid
963 ...
964</pre>
067490ab 965
73844f9c
PT
966In this model, the attribute "Processes/1000/PPID" refers to the PPID of process
967with PID 1000. The attribute "CPUs/0/Status" represents the status (running,
968idle, etc.) of CPU 0. "Processes/1000/PPID" and "Processes/1001/PPID" are two
969different attribute, even though their base name is the same: the whole path is
970the unique identifier.
067490ab 971
73844f9c
PT
972The value of each attribute can change over the duration of the trace,
973independently of the other ones, and independently of its position in the tree.
067490ab 974
73844f9c
PT
975The tree-like organization is optional, all attributes could be at the same
976level. But it's possible to put them in a tree, and it helps make things
977clearer.
067490ab 978
73844f9c 979=== Quark ===
067490ab 980
73844f9c
PT
981In addition to a given path, each attribute also has a unique integer
982identifier, called the "quark". To continue with the file system analogy, this
983is like the inode number. When a new attribute is created, a new unique quark
984will be assigned automatically. They are assigned incrementally, so they will
985normally be equal to their order of creation, starting at 0.
067490ab 986
73844f9c
PT
987Methods are offered to get the quark of an attribute from its path. The API
988methods for inserting state changes and doing queries normally use quarks
989instead of paths. This is to encourage users to cache the quarks and re-use
990them, which avoids re-walking the attribute tree over and over, which avoids
991unneeded hashing of strings.
067490ab 992
73844f9c 993=== State value ===
067490ab 994
73844f9c
PT
995The path and quark of an attribute will remain constant for the whole duration
996of the trace. However, the value carried by the attribute will change. The value
997of a specific attribute at a specific time is called the state value.
067490ab 998
7d59bbef 999In the TMF implementation, state values can be integers, longs, doubles, or strings.
73844f9c
PT
1000There is also a "null value" type, which is used to indicate that no particular
1001value is active for this attribute at this time, but without resorting to a
1002'null' reference.
067490ab 1003
73844f9c
PT
1004Any other type of value could be used, as long as the backend knows how to store
1005it.
067490ab 1006
73844f9c
PT
1007Note that the TMF implementation also forces every attribute to always carry the
1008same type of state value. This is to make it simpler for views, so they can
1009expect that an attribute will always use a given type, without having to check
1010every single time. Null values are an exception, they are always allowed for all
1011attributes, since they can safely be "unboxed" into all types.
067490ab 1012
73844f9c 1013=== State change ===
067490ab 1014
73844f9c
PT
1015A state change is the element that is inserted in the state system. It consists
1016of:
1017* a timestamp (the time at which the state change occurs)
1018* an attribute (the attribute whose value will change)
1019* a state value (the new value that the attribute will carry)
067490ab 1020
73844f9c
PT
1021It's not an object per se in the TMF implementation (it's represented by a
1022function call in the state provider). Typically, the state provider will insert
1023zero, one or more state changes for every trace event, depending on its event
1024type, payload, etc.
067490ab 1025
73844f9c
PT
1026Note, we use "timestamp" here, but it's in fact a generic term that could be
1027referred to as "index". For example, if a given trace type has no notion of
1028timestamp, the event rank could be used.
067490ab 1029
73844f9c 1030In the TMF implementation, the timestamp is a long (64-bit integer).
067490ab 1031
73844f9c 1032=== State interval ===
067490ab 1033
73844f9c
PT
1034State changes are inserted into the state system, but state intervals are the
1035objects that come out on the other side. Those are stocked in the storage
1036backend. A state interval represents a "state" of an attribute we want to track.
1037When doing queries on the state system, intervals are what is returned. The
1038components of a state interval are:
1039* Start time
1040* End time
1041* State value
1042* Quark
067490ab 1043
73844f9c
PT
1044The start and end times represent the time range of the state. The state value
1045is the same as the state value in the state change that started this interval.
1046The interval also keeps a reference to its quark, although you normally know
1047your quark in advance when you do queries.
f5b8868d 1048
73844f9c 1049=== State history ===
f5b8868d 1050
73844f9c
PT
1051The state history is the name of the container for all the intervals created by
1052the state system. The exact implementation (how the intervals are stored) is
1053determined by the storage backend that is used.
f5b8868d 1054
73844f9c
PT
1055Some backends will use a state history that is peristent on disk, others do not.
1056When loading a trace, if a history file is available and the backend supports
1057it, it will be loaded right away, skipping the need to go through another
1058construction phase.
f5b8868d 1059
73844f9c 1060=== Construction phase ===
f5b8868d 1061
73844f9c
PT
1062Before we can query a state system, we need to build the state history first. To
1063do so, trace events are sent one-by-one through the state provider, which in
1064turn sends state changes to the central component, which then creates intervals
1065and stores them in the backend. This is called the construction phase.
f5b8868d 1066
73844f9c
PT
1067Note that the state system needs to receive its events into chronological order.
1068This phase will end once the end of the trace is reached.
f5b8868d 1069
73844f9c
PT
1070Also note that it is possible to query the state system while it is being build.
1071Any timestamp between the start of the trace and the current end time of the
1072state system (available with ITmfStateSystem#getCurrentEndTime()) is a valid
1073timestamp that can be queried.
f5b8868d 1074
73844f9c 1075=== Queries ===
f5b8868d 1076
73844f9c
PT
1077As mentioned previously, when doing queries on the state system, the returned
1078objects will be state intervals. In most cases it's the state *value* we are
1079interested in, but since the backend has to instantiate the interval object
1080anyway, there is no additional cost to return the interval instead. This way we
1081also get the start and end times of the state "for free".
f5b8868d 1082
73844f9c 1083There are two types of queries that can be done on the state system:
f5b8868d 1084
73844f9c 1085==== Full queries ====
f5b8868d 1086
73844f9c
PT
1087A full query means that we want to retrieve the whole state of the model for one
1088given timestamp. As we remember, this means "the state of every single attribute
1089in the model". As parameter we only need to pass the timestamp (see the API
1090methods below). The return value will be an array of intervals, where the offset
1091in the array represents the quark of each attribute.
f5b8868d 1092
73844f9c 1093==== Single queries ====
f5b8868d 1094
73844f9c
PT
1095In other cases, we might only be interested in the state of one particular
1096attribute at one given timestamp. For these cases it's better to use a
1097single query. For a single query. we need to pass both a timestamp and a
1098quark in parameter. The return value will be a single interval, representing
1099the state that this particular attribute was at that time.
f5b8868d 1100
73844f9c
PT
1101Single queries are typically faster than full queries (but once again, this
1102depends on the backend that is used), but not by much. Even if you only want the
1103state of say 10 attributes out of 200, it could be faster to use a full query
1104and only read the ones you need. Single queries should be used for cases where
1105you only want one attribute per timestamp (for example, if you follow the state
1106of the same attribute over a time range).
f5b8868d 1107
f5b8868d 1108
73844f9c 1109== Relevant interfaces/classes ==
f5b8868d 1110
73844f9c
PT
1111This section will describe the public interface and classes that can be used if
1112you want to use the state system.
f5b8868d 1113
73844f9c 1114=== Main classes in org.eclipse.linuxtools.tmf.core.statesystem ===
f5b8868d 1115
73844f9c 1116==== ITmfStateProvider / AbstractTmfStateProvider ====
f5b8868d 1117
73844f9c
PT
1118ITmfStateProvider is the interface you have to implement to define your state
1119provider. This is where most of the work has to be done to use a state system
1120for a custom trace type or analysis type.
f5b8868d 1121
73844f9c
PT
1122For first-time users, it's recommended to extend AbstractTmfStateProvider
1123instead. This class takes care of all the initialization mumbo-jumbo, and also
1124runs the event handler in a separate thread. You will only need to implement
1125eventHandle, which is the call-back that will be called for every event in the
1126trace.
f5b8868d 1127
73844f9c
PT
1128For an example, you can look at StatsStateProvider in the TMF tree, or at the
1129small example below.
f5b8868d 1130
73844f9c 1131==== TmfStateSystemFactory ====
f5b8868d 1132
73844f9c
PT
1133Once you have defined your state provider, you need to tell your trace type to
1134build a state system with this provider during its initialization. This consists
1135of overriding TmfTrace#buildStateSystems() and in there of calling the method in
1136TmfStateSystemFactory that corresponds to the storage backend you want to use
1137(see the section [[#Comparison of state system backends]]).
f5b8868d 1138
73844f9c
PT
1139You will have to pass in parameter the state provider you want to use, which you
1140should have defined already. Each backend can also ask for more configuration
1141information.
f5b8868d 1142
73844f9c
PT
1143You must then call registerStateSystem(id, statesystem) to make your state
1144system visible to the trace objects and the views. The ID can be any string of
1145your choosing. To access this particular state system, the views or modules will
1146need to use this ID.
f5b8868d 1147
73844f9c
PT
1148Also, don't forget to call super.buildStateSystems() in your implementation,
1149unless you know for sure you want to skip the state providers built by the
1150super-classes.
f5b8868d 1151
73844f9c
PT
1152You can look at how LttngKernelTrace does it for an example. It could also be
1153possible to build a state system only under certain conditions (like only if the
1154trace contains certain event types).
f5b8868d 1155
f5b8868d 1156
73844f9c 1157==== ITmfStateSystem ====
f5b8868d 1158
73844f9c
PT
1159ITmfStateSystem is the main interface through which views or analysis modules
1160will access the state system. It offers a read-only view of the state system,
1161which means that no states can be inserted, and no attributes can be created.
1162Calling TmfTrace#getStateSystems().get(id) will return you a ITmfStateSystem
1163view of the requested state system. The main methods of interest are:
f5b8868d 1164
73844f9c 1165===== getQuarkAbsolute()/getQuarkRelative() =====
f5b8868d 1166
73844f9c
PT
1167Those are the basic quark-getting methods. The goal of the state system is to
1168return the state values of given attributes at given timestamps. As we've seen
1169earlier, attributes can be described with a file-system-like path. The goal of
1170these methods is to convert from the path representation of the attribute to its
1171quark.
f5b8868d 1172
73844f9c
PT
1173Since quarks are created on-the-fly, there is no guarantee that the same
1174attributes will have the same quark for two traces of the same type. The views
1175should always query their quarks when dealing with a new trace or a new state
1176provider. Beyond that however, quarks should be cached and reused as much as
1177possible, to avoid potentially costly string re-hashing.
f5b8868d 1178
73844f9c
PT
1179getQuarkAbsolute() takes a variable amount of Strings in parameter, which
1180represent the full path to the attribute. Some of them can be constants, some
1181can come programatically, often from the event's fields.
f5b8868d 1182
73844f9c
PT
1183getQuarkRelative() is to be used when you already know the quark of a certain
1184attribute, and want to access on of its sub-attributes. Its first parameter is
1185the origin quark, followed by a String varagrs which represent the relative path
1186to the final attribute.
f5b8868d 1187
73844f9c
PT
1188These two methods will throw an AttributeNotFoundException if trying to access
1189an attribute that does not exist in the model.
f5b8868d 1190
73844f9c
PT
1191These methods also imply that the view has the knowledge of how the attribute
1192tree is organized. This should be a reasonable hypothesis, since the same
1193analysis plugin will normally ship both the state provider and the view, and
1194they will have been written by the same person. In other cases, it's possible to
1195use getSubAttributes() to explore the organization of the attribute tree first.
f5b8868d 1196
73844f9c 1197===== waitUntilBuilt() =====
f5b8868d 1198
73844f9c
PT
1199This is a simple method used to block the caller until the construction phase of
1200this state system is done. If the view prefers to wait until all information is
1201available before starting to do queries (to get all known attributes right away,
1202for example), this is the guy to call.
f5b8868d 1203
73844f9c 1204===== queryFullState() =====
f5b8868d 1205
73844f9c
PT
1206This is the method to do full queries. As mentioned earlier, you only need to
1207pass a target timestamp in parameter. It will return a List of state intervals,
1208in which the offset corresponds to the attribute quark. This will represent the
1209complete state of the model at the requested time.
f5b8868d 1210
73844f9c 1211===== querySingleState() =====
f5b8868d 1212
73844f9c
PT
1213The method to do single queries. You pass in parameter both a timestamp and an
1214attribute quark. This will return the single state matching this
1215timestamp/attribute pair.
f5b8868d 1216
73844f9c
PT
1217Other methods are available, you are encouraged to read their Javadoc and see if
1218they can be potentially useful.
f5b8868d 1219
73844f9c 1220==== ITmfStateSystemBuilder ====
f5b8868d 1221
73844f9c
PT
1222ITmfStateSystemBuilder is the read-write interface to the state system. It
1223extends ITmfStateSystem itself, so all its methods are available. It then adds
1224methods that can be used to write to the state system, either by creating new
1225attributes of inserting state changes.
f5b8868d 1226
73844f9c
PT
1227It is normally reserved for the state provider and should not be visible to
1228external components. However it will be available in AbstractTmfStateProvider,
1229in the field 'ss'. That way you can call ss.modifyAttribute() etc. in your state
1230provider to write to the state.
f5b8868d 1231
73844f9c 1232The main methods of interest are:
f5b8868d 1233
73844f9c 1234===== getQuark*AndAdd() =====
f5b8868d 1235
73844f9c
PT
1236getQuarkAbsoluteAndAdd() and getQuarkRelativeAndAdd() work exactly like their
1237non-AndAdd counterparts in ITmfStateSystem. The difference is that the -AndAdd
1238versions will not throw any exception: if the requested attribute path does not
1239exist in the system, it will be created, and its newly-assigned quark will be
1240returned.
f5b8868d 1241
73844f9c
PT
1242When in a state provider, the -AndAdd version should normally be used (unless
1243you know for sure the attribute already exist and don't want to create it
1244otherwise). This means that there is no need to define the whole attribute tree
1245in advance, the attributes will be created on-demand.
f5b8868d 1246
73844f9c 1247===== modifyAttribute() =====
f5b8868d 1248
73844f9c
PT
1249This is the main state-change-insertion method. As was explained before, a state
1250change is defined by a timestamp, an attribute and a state value. Those three
1251elements need to be passed to modifyAttribute as parameters.
f5b8868d 1252
73844f9c
PT
1253Other state change insertion methods are available (increment-, push-, pop- and
1254removeAttribute()), but those are simply convenience wrappers around
1255modifyAttribute(). Check their Javadoc for more information.
f5b8868d 1256
73844f9c 1257===== closeHistory() =====
f5b8868d 1258
73844f9c
PT
1259When the construction phase is done, do not forget to call closeHistory() to
1260tell the backend that no more intervals will be received. Depending on the
1261backend type, it might have to save files, close descriptors, etc. This ensures
1262that a persitent file can then be re-used when the trace is opened again.
f5b8868d 1263
73844f9c
PT
1264If you use the AbstractTmfStateProvider, it will call closeHistory()
1265automatically when it reaches the end of the trace.
f5b8868d 1266
73844f9c 1267=== Other relevant interfaces ===
f5b8868d 1268
73844f9c 1269==== o.e.l.tmf.core.statevalue.ITmfStateValue ====
f5b8868d 1270
73844f9c
PT
1271This is the interface used to represent state values. Those are used when
1272inserting state changes in the provider, and is also part of the state intervals
1273obtained when doing queries.
f5b8868d 1274
73844f9c 1275The abstract TmfStateValue class contains the factory methods to create new
7d59bbef
JCK
1276state values of either int, long, double or string types. To retrieve the real
1277object inside the state value, one can use the .unbox* methods.
f5b8868d 1278
73844f9c 1279Note: Do not instantiate null values manually, use TmfStateValue.nullValue()
f5b8868d 1280
73844f9c 1281==== o.e.l.tmf.core.interval.ITmfStateInterval ====
f5b8868d 1282
73844f9c
PT
1283This is the interface to represent the state intervals, which are stored in the
1284state history backend, and are returned when doing state system queries. A very
1285simple implementation is available in TmfStateInterval. Its methods should be
1286self-descriptive.
f5b8868d 1287
73844f9c 1288=== Exceptions ===
f5b8868d 1289
73844f9c
PT
1290The following exceptions, found in o.e.l.tmf.core.exceptions, are related to
1291state system activities.
f5b8868d 1292
73844f9c 1293==== AttributeNotFoundException ====
f5b8868d 1294
73844f9c
PT
1295This is thrown by getQuarkRelative() and getQuarkAbsolute() (but not byt the
1296-AndAdd versions!) when passing an attribute path that is not present in the
1297state system. This is to ensure that no new attribute is created when using
1298these versions of the methods.
f5b8868d 1299
73844f9c
PT
1300Views can expect some attributes to be present, but they should handle these
1301exceptions for when the attributes end up not being in the state system (perhaps
1302this particular trace didn't have a certain type of events, etc.)
f5b8868d 1303
73844f9c 1304==== StateValueTypeException ====
f5b8868d 1305
73844f9c
PT
1306This exception will be thrown when trying to unbox a state value into a type
1307different than its own. You should always check with ITmfStateValue#getType()
1308beforehand if you are not sure about the type of a given state value.
f5b8868d 1309
73844f9c 1310==== TimeRangeException ====
f5b8868d 1311
73844f9c
PT
1312This exception is thrown when trying to do a query on the state system for a
1313timestamp that is outside of its range. To be safe, you should check with
1314ITmfStateSystem#getStartTime() and #getCurrentEndTime() for the current valid
1315range of the state system. This is especially important when doing queries on
1316a state system that is currently being built.
f5b8868d 1317
73844f9c 1318==== StateSystemDisposedException ====
f5b8868d 1319
73844f9c
PT
1320This exception is thrown when trying to access a state system that has been
1321disposed, with its dispose() method. This can potentially happen at shutdown,
1322since Eclipse is not always consistent with the order in which the components
1323are closed.
f5b8868d 1324
f5b8868d 1325
73844f9c 1326== Comparison of state system backends ==
f5b8868d 1327
73844f9c
PT
1328As we have seen in section [[#High-level components]], the state system needs
1329a storage backend to save the intervals. Different implementations are
1330available when building your state system from TmfStateSystemFactory.
f5b8868d 1331
73844f9c
PT
1332Do not confuse full/single queries with full/partial history! All backend types
1333should be able to handle any type of queries defined in the ITmfStateSystem API,
1334unless noted otherwise.
f5b8868d 1335
73844f9c 1336=== Full history ===
2819a797 1337
73844f9c
PT
1338Available with TmfStateSystemFactory#newFullHistory(). The full history uses a
1339History Tree data structure, which is an optimized structure store state
1340intervals on disk. Once built, it can respond to queries in a ''log(n)'' manner.
2819a797 1341
73844f9c
PT
1342You need to specify a file at creation time, which will be the container for
1343the history tree. Once it's completely built, it will remain on disk (until you
1344delete the trace from the project). This way it can be reused from one session
1345to another, which makes subsequent loading time much faster.
2819a797 1346
73844f9c
PT
1347This the backend used by the LTTng kernel plugin. It offers good scalability and
1348performance, even at extreme sizes (it's been tested with traces of sizes up to
1349500 GB). Its main downside is the amount of disk space required: since every
1350single interval is written to disk, the size of the history file can quite
1351easily reach and even surpass the size of the trace itself.
2819a797 1352
73844f9c 1353=== Null history ===
2819a797 1354
73844f9c
PT
1355Available with TmfStateSystemFactory#newNullHistory(). As its name implies the
1356null history is in fact an absence of state history. All its query methods will
1357return null (see the Javadoc in NullBackend).
2819a797 1358
73844f9c 1359Obviously, no file is required, and almost no memory space is used.
2819a797 1360
73844f9c
PT
1361It's meant to be used in cases where you are not interested in past states, but
1362only in the "ongoing" one. It can also be useful for debugging and benchmarking.
2819a797 1363
73844f9c 1364=== In-memory history ===
2819a797 1365
73844f9c 1366Available with TmfStateSystemFactory#newInMemHistory(). This is a simple wrapper
7d59bbef
JCK
1367using a TreeSet to store all state intervals in memory. The implementation at
1368the moment is quite simple, it will perform a binary search on entries when
1369doing queries to find the ones that match.
2819a797 1370
73844f9c
PT
1371The advantage of this method is that it's very quick to build and query, since
1372all the information resides in memory. However, you are limited to 2^31 entries
1373(roughly 2 billions), and depending on your state provider and trace type, that
1374can happen really fast!
2819a797 1375
73844f9c
PT
1376There are no safeguards, so if you bust the limit you will end up with
1377ArrayOutOfBoundsException's everywhere. If your trace or state history can be
1378arbitrarily big, it's probably safer to use a Full History instead.
2819a797 1379
73844f9c 1380=== Partial history ===
2819a797 1381
73844f9c
PT
1382Available with TmfStateSystemFactory#newPartialHistory(). The partial history is
1383a more advanced form of the full history. Instead of writing all state intervals
1384to disk like with the full history, we only write a small fraction of them, and
1385go back to read the trace to recreate the states in-between.
2819a797 1386
73844f9c
PT
1387It has a big advantage over a full history in terms of disk space usage. It's
1388very possible to reduce the history tree file size by a factor of 1000, while
1389keeping query times within a factor of two. Its main downside comes from the
1390fact that you cannot do efficient single queries with it (they are implemented
1391by doing full queries underneath).
2819a797 1392
73844f9c
PT
1393This makes it a poor choice for views like the Control Flow view, where you do
1394a lot of range queries and single queries. However, it is a perfect fit for
1395cases like statistics, where you usually do full queries already, and you store
1396lots of small states which are very easy to "compress".
2819a797 1397
73844f9c 1398However, it can't really be used until bug 409630 is fixed.
2819a797 1399
7d59bbef
JCK
1400== State System Operations ==
1401
1402TmfStateSystemOperations is a static class that implements additional
1403statistical operations that can be performed on attributes of the state system.
1404
1405These operations require that the attribute be one of the numerical values
1406(int, long or double).
1407
1408The speed of these operations can be greatly improved for large data sets if
1409the attribute was inserted in the state system as a mipmap attribute. Refer to
1410the [[#Mipmap feature | Mipmap feature]] section.
1411
1412===== queryRangeMax() =====
1413
1414This method returns the maximum numerical value of an attribute in the
1415specified time range. The attribute must be of type int, long or double.
1416Null values are ignored. The returned value will be of the same state value
1417type as the base attribute, or a null value if there is no state interval
1418stored in the given time range.
1419
1420===== queryRangeMin() =====
1421
1422This method returns the minimum numerical value of an attribute in the
1423specified time range. The attribute must be of type int, long or double.
1424Null values are ignored. The returned value will be of the same state value
1425type as the base attribute, or a null value if there is no state interval
1426stored in the given time range.
1427
1428===== queryRangeAverage() =====
1429
1430This method returns the average numerical value of an attribute in the
1431specified time range. The attribute must be of type int, long or double.
1432Each state interval value is weighted according to time. Null values are
1433counted as zero. The returned value will be a double primitive, which will
1434be zero if there is no state interval stored in the given time range.
1435
73844f9c 1436== Code example ==
2819a797 1437
73844f9c
PT
1438Here is a small example of code that will use the state system. For this
1439example, let's assume we want to track the state of all the CPUs in a LTTng
1440kernel trace. To do so, we will watch for the "sched_switch" event in the state
1441provider, and will update an attribute indicating if the associated CPU should
1442be set to "running" or "idle".
2819a797 1443
73844f9c
PT
1444We will use an attribute tree that looks like this:
1445<pre>
1446CPUs
1447 |--0
1448 | |--Status
1449 |
1450 |--1
1451 | |--Status
1452 |
1453 | 2
1454 | |--Status
1455...
1456</pre>
2819a797 1457
73844f9c
PT
1458The second-level attributes will be named from the information available in the
1459trace events. Only the "Status" attributes will carry a state value (this means
1460we could have just used "1", "2", "3",... directly, but we'll do it in a tree
1461for the example's sake).
2819a797 1462
73844f9c
PT
1463Also, we will use integer state values to represent "running" or "idle", instead
1464of saving the strings that would get repeated every time. This will help in
1465reducing the size of the history file.
2819a797 1466
73844f9c
PT
1467First we will define a state provider in MyStateProvider. Then, assuming we
1468have already implemented a custom trace type extending CtfTmfTrace, we will add
1469a section to it to make it build a state system using the provider we defined
1470earlier. Finally, we will show some example code that can query the state
1471system, which would normally go in a view or analysis module.
2819a797 1472
73844f9c 1473=== State Provider ===
2819a797 1474
73844f9c
PT
1475<pre>
1476import org.eclipse.linuxtools.tmf.core.ctfadaptor.CtfTmfEvent;
1477import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
1478import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException;
1479import org.eclipse.linuxtools.tmf.core.exceptions.StateValueTypeException;
1480import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException;
1481import org.eclipse.linuxtools.tmf.core.statesystem.AbstractTmfStateProvider;
1482import org.eclipse.linuxtools.tmf.core.statevalue.ITmfStateValue;
1483import org.eclipse.linuxtools.tmf.core.statevalue.TmfStateValue;
1484import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace;
2819a797 1485
73844f9c
PT
1486/**
1487 * Example state system provider.
1488 *
1489 * @author Alexandre Montplaisir
1490 */
1491public class MyStateProvider extends AbstractTmfStateProvider {
2819a797 1492
73844f9c
PT
1493 /** State value representing the idle state */
1494 public static ITmfStateValue IDLE = TmfStateValue.newValueInt(0);
2819a797 1495
73844f9c
PT
1496 /** State value representing the running state */
1497 public static ITmfStateValue RUNNING = TmfStateValue.newValueInt(1);
2819a797 1498
73844f9c
PT
1499 /**
1500 * Constructor
1501 *
1502 * @param trace
1503 * The trace to which this state provider is associated
1504 */
1505 public MyStateProvider(ITmfTrace trace) {
1506 super(trace, CtfTmfEvent.class, "Example"); //$NON-NLS-1$
1507 /*
1508 * The third parameter here is not important, it's only used to name a
1509 * thread internally.
1510 */
1511 }
2819a797 1512
73844f9c
PT
1513 @Override
1514 public int getVersion() {
1515 /*
1516 * If the version of an existing file doesn't match the version supplied
1517 * in the provider, a rebuild of the history will be forced.
1518 */
1519 return 1;
1520 }
2819a797 1521
73844f9c
PT
1522 @Override
1523 public MyStateProvider getNewInstance() {
1524 return new MyStateProvider(getTrace());
1525 }
2819a797 1526
73844f9c
PT
1527 @Override
1528 protected void eventHandle(ITmfEvent ev) {
1529 /*
1530 * AbstractStateChangeInput should have already checked for the correct
1531 * class type.
1532 */
1533 CtfTmfEvent event = (CtfTmfEvent) ev;
2819a797 1534
73844f9c
PT
1535 final long ts = event.getTimestamp().getValue();
1536 Integer nextTid = ((Long) event.getContent().getField("next_tid").getValue()).intValue();
1537
1538 try {
1539
1540 if (event.getEventName().equals("sched_switch")) {
1541 int quark = ss.getQuarkAbsoluteAndAdd("CPUs", String.valueOf(event.getCPU()), "Status");
1542 ITmfStateValue value;
1543 if (nextTid > 0) {
1544 value = RUNNING;
1545 } else {
1546 value = IDLE;
1547 }
1548 ss.modifyAttribute(ts, value, quark);
1549 }
1550
1551 } catch (TimeRangeException e) {
1552 /*
1553 * This should not happen, since the timestamp comes from a trace
1554 * event.
1555 */
1556 throw new IllegalStateException(e);
1557 } catch (AttributeNotFoundException e) {
1558 /*
1559 * This should not happen either, since we're only accessing a quark
1560 * we just created.
1561 */
1562 throw new IllegalStateException(e);
1563 } catch (StateValueTypeException e) {
1564 /*
1565 * This wouldn't happen here, but could potentially happen if we try
1566 * to insert mismatching state value types in the same attribute.
1567 */
1568 e.printStackTrace();
1569 }
1570
1571 }
1572
1573}
1574</pre>
1575
1576=== Trace type definition ===
1577
1578<pre>
2819a797 1579import java.io.File;
2819a797
MK
1580
1581import org.eclipse.core.resources.IProject;
2819a797
MK
1582import org.eclipse.core.runtime.IStatus;
1583import org.eclipse.core.runtime.Status;
73844f9c 1584import org.eclipse.linuxtools.tmf.core.ctfadaptor.CtfTmfTrace;
2819a797 1585import org.eclipse.linuxtools.tmf.core.exceptions.TmfTraceException;
73844f9c
PT
1586import org.eclipse.linuxtools.tmf.core.statesystem.ITmfStateProvider;
1587import org.eclipse.linuxtools.tmf.core.statesystem.ITmfStateSystem;
1588import org.eclipse.linuxtools.tmf.core.statesystem.TmfStateSystemFactory;
1589import org.eclipse.linuxtools.tmf.core.trace.TmfTraceManager;
2819a797
MK
1590
1591/**
73844f9c 1592 * Example of a custom trace type using a custom state provider.
2819a797 1593 *
73844f9c 1594 * @author Alexandre Montplaisir
2819a797 1595 */
73844f9c 1596public class MyTraceType extends CtfTmfTrace {
2819a797 1597
73844f9c
PT
1598 /** The file name of the history file */
1599 public final static String HISTORY_FILE_NAME = "mystatefile.ht";
2819a797 1600
73844f9c
PT
1601 /** ID of the state system we will build */
1602 public static final String STATE_ID = "org.eclipse.linuxtools.lttng2.example";
2819a797 1603
73844f9c
PT
1604 /**
1605 * Default constructor
1606 */
1607 public MyTraceType() {
1608 super();
2819a797
MK
1609 }
1610
1611 @Override
73844f9c
PT
1612 public IStatus validate(final IProject project, final String path) {
1613 /*
1614 * Add additional validation code here, and return a IStatus.ERROR if
1615 * validation fails.
1616 */
1617 return Status.OK_STATUS;
2819a797
MK
1618 }
1619
1620 @Override
73844f9c
PT
1621 protected void buildStateSystem() throws TmfTraceException {
1622 super.buildStateSystem();
1623
1624 /* Build the custom state system for this trace */
1625 String directory = TmfTraceManager.getSupplementaryFileDir(this);
1626 final File htFile = new File(directory + HISTORY_FILE_NAME);
1627 final ITmfStateProvider htInput = new MyStateProvider(this);
1628
1629 ITmfStateSystem ss = TmfStateSystemFactory.newFullHistory(htFile, htInput, false);
1630 fStateSystems.put(STATE_ID, ss);
2819a797
MK
1631 }
1632
73844f9c
PT
1633}
1634</pre>
1635
1636=== Query code ===
1637
1638<pre>
1639import java.util.List;
1640
1641import org.eclipse.linuxtools.tmf.core.exceptions.AttributeNotFoundException;
1642import org.eclipse.linuxtools.tmf.core.exceptions.StateSystemDisposedException;
1643import org.eclipse.linuxtools.tmf.core.exceptions.TimeRangeException;
1644import org.eclipse.linuxtools.tmf.core.interval.ITmfStateInterval;
1645import org.eclipse.linuxtools.tmf.core.statesystem.ITmfStateSystem;
1646import org.eclipse.linuxtools.tmf.core.statevalue.ITmfStateValue;
1647import org.eclipse.linuxtools.tmf.core.trace.ITmfTrace;
1648
1649/**
1650 * Class showing examples of state system queries.
1651 *
1652 * @author Alexandre Montplaisir
1653 */
1654public class QueryExample {
1655
1656 private final ITmfStateSystem ss;
1657
2819a797 1658 /**
73844f9c
PT
1659 * Constructor
1660 *
1661 * @param trace
1662 * Trace that this "view" will display.
2819a797 1663 */
73844f9c
PT
1664 public QueryExample(ITmfTrace trace) {
1665 ss = trace.getStateSystems().get(MyTraceType.STATE_ID);
2819a797
MK
1666 }
1667
73844f9c
PT
1668 /**
1669 * Example method of querying one attribute in the state system.
1670 *
1671 * We pass it a cpu and a timestamp, and it returns us if that cpu was
1672 * executing a process (true/false) at that time.
1673 *
1674 * @param cpu
1675 * The CPU to check
1676 * @param timestamp
1677 * The timestamp of the query
1678 * @return True if the CPU was running, false otherwise
1679 */
1680 public boolean cpuIsRunning(int cpu, long timestamp) {
2819a797 1681 try {
73844f9c
PT
1682 int quark = ss.getQuarkAbsolute("CPUs", String.valueOf(cpu), "Status");
1683 ITmfStateValue value = ss.querySingleState(timestamp, quark).getStateValue();
2819a797 1684
73844f9c
PT
1685 if (value.equals(MyStateProvider.RUNNING)) {
1686 return true;
1687 }
2819a797 1688
73844f9c
PT
1689 /*
1690 * Since at this level we have no guarantee on the contents of the state
1691 * system, it's important to handle these cases correctly.
1692 */
1693 } catch (AttributeNotFoundException e) {
1694 /*
1695 * Handle the case where the attribute does not exist in the state
1696 * system (no CPU with this number, etc.)
1697 */
1698 ...
1699 } catch (TimeRangeException e) {
1700 /*
1701 * Handle the case where 'timestamp' is outside of the range of the
1702 * history.
1703 */
1704 ...
1705 } catch (StateSystemDisposedException e) {
1706 /*
1707 * Handle the case where the state system is being disposed. If this
1708 * happens, it's normally when shutting down, so the view can just
1709 * return immediately and wait it out.
1710 */
1711 }
1712 return false;
2819a797
MK
1713 }
1714
2819a797 1715
73844f9c
PT
1716 /**
1717 * Example method of using a full query.
1718 *
1719 * We pass it a timestamp, and it returns us how many CPUs were executing a
1720 * process at that moment.
1721 *
1722 * @param timestamp
1723 * The target timestamp
1724 * @return The amount of CPUs that were running at that time
1725 */
1726 public int getNbRunningCpus(long timestamp) {
1727 int count = 0;
2819a797 1728
73844f9c
PT
1729 try {
1730 /* Get the list of the quarks we are interested in. */
1731 List<Integer> quarks = ss.getQuarks("CPUs", "*", "Status");
2819a797 1732
73844f9c
PT
1733 /*
1734 * Get the full state at our target timestamp (it's better than
1735 * doing an arbitrary number of single queries).
1736 */
1737 List<ITmfStateInterval> state = ss.queryFullState(timestamp);
2819a797 1738
73844f9c
PT
1739 /* Look at the value of the state for each quark */
1740 for (Integer quark : quarks) {
1741 ITmfStateValue value = state.get(quark).getStateValue();
1742 if (value.equals(MyStateProvider.RUNNING)) {
1743 count++;
1744 }
2819a797 1745 }
73844f9c
PT
1746
1747 } catch (TimeRangeException e) {
1748 /*
1749 * Handle the case where 'timestamp' is outside of the range of the
1750 * history.
1751 */
1752 ...
1753 } catch (StateSystemDisposedException e) {
1754 /* Handle the case where the state system is being disposed. */
1755 ...
2819a797 1756 }
73844f9c 1757 return count;
2819a797
MK
1758 }
1759}
1760</pre>
1761
7d59bbef
JCK
1762== Mipmap feature ==
1763
1764The mipmap feature allows attributes to be inserted into the state system with
1765additional computations performed to automatically store sub-attributes that
1766can later be used for statistical operations. The mipmap has a resolution which
1767represents the number of state attribute changes that are used to compute the
1768value at the next mipmap level.
1769
1770The supported mipmap features are: max, min, and average. Each one of these
1771features requires that the base attribute be a numerical state value (int, long
1772or double). An attribute can be mipmapped for one or more of the features at
1773the same time.
1774
1775To use a mipmapped attribute in queries, call the corresponding methods of the
1776static class [[#State System Operations | TmfStateSystemOperations]].
1777
1778=== AbstractTmfMipmapStateProvider ===
1779
1780AbstractTmfMipmapStateProvider is an abstract provider class that allows adding
1781features to a specific attribute into a mipmap tree. It extends AbstractTmfStateProvider.
1782
1783If a provider wants to add mipmapped attributes to its tree, it must extend
1784AbstractTmfMipmapStateProvider and call modifyMipmapAttribute() in the event
1785handler, specifying one or more mipmap features to compute. Then the structure
1786of the attribute tree will be :
1787
1788<pre>
1789|- <attribute>
1790| |- <mipmapFeature> (min/max/avg)
1791| | |- 1
1792| | |- 2
1793| | |- 3
1794| | ...
1795| | |- n (maximum mipmap level)
1796| |- <mipmapFeature> (min/max/avg)
1797| | |- 1
1798| | |- 2
1799| | |- 3
1800| | ...
1801| | |- n (maximum mipmap level)
1802| ...
1803</pre>
1804
73844f9c 1805= UML2 Sequence Diagram Framework =
2819a797 1806
73844f9c
PT
1807The purpose of the UML2 Sequence Diagram Framework of TMF is to provide a framework for generation of UML2 sequence diagrams. It provides
1808*UML2 Sequence diagram drawing capabilities (i.e. lifelines, messages, activations, object creation and deletion)
1809*a generic, re-usable Sequence Diagram View
1810*Eclipse Extension Point for the creation of sequence diagrams
1811*callback hooks for searching and filtering within the Sequence Diagram View
1812*scalability<br>
1813The following chapters describe the Sequence Diagram Framework as well as a reference implementation and its usage.
2819a797 1814
73844f9c 1815== TMF UML2 Sequence Diagram Extensions ==
2819a797 1816
73844f9c 1817In the UML2 Sequence Diagram Framework an Eclipse extension point is defined so that other plug-ins can contribute code to create sequence diagram.
2819a797 1818
73844f9c 1819'''Identifier''': org.eclipse.linuxtools.tmf.ui.uml2SDLoader<br>
0c54f1fe 1820'''Since''': 1.0<br>
73844f9c
PT
1821'''Description''': This extension point aims to list and connect any UML2 Sequence Diagram loader.<br>
1822'''Configuration Markup''':<br>
2819a797 1823
73844f9c
PT
1824<pre>
1825<!ELEMENT extension (uml2SDLoader)+>
1826<!ATTLIST extension
1827point CDATA #REQUIRED
1828id CDATA #IMPLIED
1829name CDATA #IMPLIED
1830>
1831</pre>
2819a797 1832
73844f9c
PT
1833*point - A fully qualified identifier of the target extension point.
1834*id - An optional identifier of the extension instance.
1835*name - An optional name of the extension instance.
2819a797 1836
73844f9c
PT
1837<pre>
1838<!ELEMENT uml2SDLoader EMPTY>
1839<!ATTLIST uml2SDLoader
1840id CDATA #REQUIRED
1841name CDATA #REQUIRED
1842class CDATA #REQUIRED
1843view CDATA #REQUIRED
1844default (true | false)
1845</pre>
2819a797 1846
73844f9c
PT
1847*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.
1848*name - An name of the extension instance.
1849*class - The implementation of this UML2 SD viewer loader. The class must implement org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader.
1850*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.
1851*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 1852
2819a797 1853
73844f9c 1854== Management of the Extension Point ==
2819a797 1855
73844f9c
PT
1856The TMF UI plug-in is responsible for evaluating each contribution to the extension point.
1857<br>
1858<br>
1859With 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 1860
73844f9c 1861== Sequence Diagram View ==
2819a797 1862
73844f9c 1863For 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 1864
73844f9c 1865=== Supported Widgets ===
2819a797 1866
73844f9c 1867The loader class provides a frame containing all the UML2 widgets to be displayed. The following widgets exist:
2819a797 1868
73844f9c
PT
1869*Lifeline
1870*Activation
1871*Synchronous Message
1872*Asynchronous Message
1873*Synchronous Message Return
1874*Asynchronous Message Return
1875*Stop
2819a797 1876
73844f9c 1877For a lifeline, a category can be defined. The lifeline category defines icons, which are displayed in the lifeline header.
2819a797 1878
73844f9c 1879=== Zooming ===
2819a797 1880
73844f9c 1881The Sequence Diagram View allows the user to zoom in, zoom out and reset the zoom factor.
2819a797 1882
73844f9c 1883=== Printing ===
2819a797 1884
73844f9c 1885It is possible to print the whole sequence diagram as well as part of it.
2819a797 1886
73844f9c 1887=== Key Bindings ===
2819a797 1888
73844f9c
PT
1889*SHIFT+ALT+ARROW-DOWN - to scroll down within sequence diagram one view page at a time
1890*SHIFT+ALT+ARROW-UP - to scroll up within sequence diagram one view page at a time
1891*SHIFT+ALT+ARROW-RIGHT - to scroll right within sequence diagram one view page at a time
1892*SHIFT+ALT+ARROW-LEFT - to scroll left within sequence diagram one view page at a time
1893*SHIFT+ALT+ARROW-HOME - to jump to the beginning of the selected message if not already visible in page
1894*SHIFT+ALT+ARROW-END - to jump to the end of the selected message if not already visible in page
1895*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]])
1896*CTRL+P - to open print dialog
067490ab 1897
73844f9c 1898=== Preferences ===
5f7ef209 1899
73844f9c
PT
1900The 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>
1901[[Image:images/SeqDiagramPref.png]] <br>
1902After changing the preferences select '''OK'''.
067490ab 1903
73844f9c 1904=== Callback hooks ===
067490ab 1905
73844f9c
PT
1906The Sequence Diagram View provides several callback hooks so that extension can provide application specific functionality. The following interfaces can be provided:
1907* Basic find provider or extended find Provider<br> For finding within the sequence diagram
1908* Basic filter provider and extended Filter Provider<br> For filtering within the sequnce diagram.
1909* Basic paging provider or advanced paging provider<br> For scalability reasons, used to limit number of displayed messages
1910* Properies provider<br> To provide properties of selected elements
1911* Collapse provider <br> To collapse areas of the sequence diagram
067490ab 1912
73844f9c 1913== Tutorial ==
067490ab 1914
73844f9c 1915This tutorial describes how to create a UML2 Sequence Diagram Loader extension and use this loader in the in Eclipse.
067490ab 1916
73844f9c 1917=== Prerequisites ===
067490ab 1918
0c54f1fe 1919The tutorial is based on Eclipse 4.4 (Eclipse Luna) and TMF 3.0.0.
067490ab 1920
73844f9c 1921=== Creating an Eclipse UI Plug-in ===
067490ab 1922
73844f9c
PT
1923To create a new project with name org.eclipse.linuxtools.tmf.sample.ui select '''File -> New -> Project -> Plug-in Development -> Plug-in Project'''. <br>
1924[[Image:images/Screenshot-NewPlug-inProject1.png]]<br>
067490ab 1925
73844f9c 1926[[Image:images/Screenshot-NewPlug-inProject2.png]]<br>
067490ab 1927
73844f9c 1928[[Image:images/Screenshot-NewPlug-inProject3.png]]<br>
067490ab 1929
73844f9c 1930=== Creating a Sequence Diagram View ===
067490ab 1931
73844f9c
PT
1932To open the plug-in manifest, double-click on the MANIFEST.MF file. <br>
1933[[Image:images/SelectManifest.png]]<br>
5f7ef209 1934
0c54f1fe 1935Change 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 1936[[Image:images/AddDependencyTmfUi.png]]<br>
067490ab 1937
73844f9c
PT
1938Change 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>
1939[[Image:images/AddViewExtension1.png]]<br>
067490ab 1940
73844f9c
PT
1941To create a Sequence Diagram View, click the right mouse button. Then select '''New -> view'''<br>
1942[[Image:images/AddViewExtension2.png]]<br>
32897d73 1943
73844f9c
PT
1944A 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>
1945[[Image:images/FillSampleSeqDiagram.png]]<br>
32897d73 1946
73844f9c
PT
1947The view is prepared. Run the Example. To launch the an Eclipse Application select the ''Overview'' tab and click on '''Launch an Eclipse Application'''<br>
1948[[Image:images/RunEclipseApplication.png]]<br>
32897d73 1949
73844f9c
PT
1950A new Eclipse application window will show. In the new window go to '''Windows -> Show View -> Other... -> Other -> Sample Sequence Diagram'''.<br>
1951[[Image:images/ShowViewOther.png]]<br>
32897d73 1952
73844f9c
PT
1953The Sequence Diagram View will open with an blank page.<br>
1954[[Image:images/BlankSampleSeqDiagram.png]]<br>
32897d73 1955
73844f9c 1956Close the Example Application.
32897d73 1957
73844f9c 1958=== Defining the uml2SDLoader Extension ===
32897d73 1959
73844f9c 1960After defining the Sequence Diagram View it's time to create the ''uml2SDLoader'' Extension. <br>
32897d73 1961
73844f9c
PT
1962Before 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>
1963[[Image:images/AddDependencyTmf.png]]<br>
32897d73 1964
73844f9c
PT
1965To 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>
1966[[Image:images/AddTmfUml2SDLoader.png]]<br>
32897d73 1967
73844f9c
PT
1968A 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>
1969[[Image:images/FillSampleLoader.png]]<br>
32897d73 1970
73844f9c
PT
1971Then click on ''class'' (see above) to open the new class dialog box. Fill in the relevant fields and select '''Finish'''. <br>
1972[[Image:images/NewSampleLoaderClass.png]]<br>
32897d73 1973
73844f9c 1974A new Java class will be created which implements the interface ''org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader''.<br>
32897d73 1975
73844f9c
PT
1976<pre>
1977package org.eclipse.linuxtools.tmf.sample.ui;
32897d73 1978
73844f9c
PT
1979import org.eclipse.linuxtools.tmf.ui.views.uml2sd.SDView;
1980import org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader;
32897d73 1981
73844f9c 1982public class SampleLoader implements IUml2SDLoader {
32897d73 1983
73844f9c
PT
1984 public SampleLoader() {
1985 // TODO Auto-generated constructor stub
1986 }
32897d73 1987
73844f9c
PT
1988 @Override
1989 public void dispose() {
1990 // TODO Auto-generated method stub
32897d73 1991
73844f9c 1992 }
32897d73 1993
73844f9c
PT
1994 @Override
1995 public String getTitleString() {
1996 // TODO Auto-generated method stub
1997 return null;
1998 }
32897d73 1999
73844f9c
PT
2000 @Override
2001 public void setViewer(SDView arg0) {
2002 // TODO Auto-generated method stub
32897d73 2003
73844f9c 2004 }
32897d73
AM
2005</pre>
2006
73844f9c 2007=== Implementing the Loader Class ===
32897d73 2008
73844f9c 2009Next 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 2010
73844f9c
PT
2011<pre>
2012package org.eclipse.linuxtools.tmf.sample.ui;
32897d73 2013
73844f9c
PT
2014import org.eclipse.linuxtools.tmf.ui.views.uml2sd.SDView;
2015import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.AsyncMessage;
2016import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.AsyncMessageReturn;
2017import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.ExecutionOccurrence;
2018import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.Frame;
2019import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.Lifeline;
2020import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.Stop;
2021import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.SyncMessage;
2022import org.eclipse.linuxtools.tmf.ui.views.uml2sd.core.SyncMessageReturn;
2023import org.eclipse.linuxtools.tmf.ui.views.uml2sd.load.IUml2SDLoader;
32897d73 2024
73844f9c 2025public class SampleLoader implements IUml2SDLoader {
32897d73 2026
73844f9c
PT
2027 private SDView fSdView;
2028
2029 public SampleLoader() {
2030 }
32897d73 2031
73844f9c
PT
2032 @Override
2033 public void dispose() {
2034 }
32897d73 2035
73844f9c
PT
2036 @Override
2037 public String getTitleString() {
2038 return "Sample Diagram";
2039 }
32897d73 2040
73844f9c
PT
2041 @Override
2042 public void setViewer(SDView arg0) {
2043 fSdView = arg0;
2044 createFrame();
2045 }
2046
2047 private void createFrame() {
32897d73 2048
73844f9c
PT
2049 Frame testFrame = new Frame();
2050 testFrame.setName("Sample Frame");
32897d73 2051
73844f9c
PT
2052 /*
2053 * Create lifelines
2054 */
2055
2056 Lifeline lifeLine1 = new Lifeline();
2057 lifeLine1.setName("Object1");
2058 testFrame.addLifeLine(lifeLine1);
2059
2060 Lifeline lifeLine2 = new Lifeline();
2061 lifeLine2.setName("Object2");
2062 testFrame.addLifeLine(lifeLine2);
2063
32897d73 2064
73844f9c
PT
2065 /*
2066 * Create Sync Message
2067 */
2068 // Get new occurrence on lifelines
2069 lifeLine1.getNewEventOccurrence();
2070
2071 // Get Sync message instances
2072 SyncMessage start = new SyncMessage();
2073 start.setName("Start");
2074 start.setEndLifeline(lifeLine1);
2075 testFrame.addMessage(start);
32897d73 2076
73844f9c
PT
2077 /*
2078 * Create Sync Message
2079 */
2080 // Get new occurrence on lifelines
2081 lifeLine1.getNewEventOccurrence();
2082 lifeLine2.getNewEventOccurrence();
2083
2084 // Get Sync message instances
2085 SyncMessage syn1 = new SyncMessage();
2086 syn1.setName("Sync Message 1");
2087 syn1.setStartLifeline(lifeLine1);
2088 syn1.setEndLifeline(lifeLine2);
2089 testFrame.addMessage(syn1);
32897d73 2090
73844f9c
PT
2091 /*
2092 * Create corresponding Sync Message Return
2093 */
2094
2095 // Get new occurrence on lifelines
2096 lifeLine1.getNewEventOccurrence();
2097 lifeLine2.getNewEventOccurrence();
32897d73 2098
73844f9c
PT
2099 SyncMessageReturn synReturn1 = new SyncMessageReturn();
2100 synReturn1.setName("Sync Message Return 1");
2101 synReturn1.setStartLifeline(lifeLine2);
2102 synReturn1.setEndLifeline(lifeLine1);
2103 synReturn1.setMessage(syn1);
2104 testFrame.addMessage(synReturn1);
2105
2106 /*
2107 * Create Activations (Execution Occurrence)
2108 */
2109 ExecutionOccurrence occ1 = new ExecutionOccurrence();
2110 occ1.setStartOccurrence(start.getEventOccurrence());
2111 occ1.setEndOccurrence(synReturn1.getEventOccurrence());
2112 lifeLine1.addExecution(occ1);
2113 occ1.setName("Activation 1");
2114
2115 ExecutionOccurrence occ2 = new ExecutionOccurrence();
2116 occ2.setStartOccurrence(syn1.getEventOccurrence());
2117 occ2.setEndOccurrence(synReturn1.getEventOccurrence());
2118 lifeLine2.addExecution(occ2);
2119 occ2.setName("Activation 2");
2120
2121 /*
2122 * Create Sync Message
2123 */
2124 // Get new occurrence on lifelines
2125 lifeLine1.getNewEventOccurrence();
2126 lifeLine2.getNewEventOccurrence();
2127
2128 // Get Sync message instances
2129 AsyncMessage asyn1 = new AsyncMessage();
2130 asyn1.setName("Async Message 1");
2131 asyn1.setStartLifeline(lifeLine1);
2132 asyn1.setEndLifeline(lifeLine2);
2133 testFrame.addMessage(asyn1);
32897d73 2134
73844f9c
PT
2135 /*
2136 * Create corresponding Sync Message Return
2137 */
2138
2139 // Get new occurrence on lifelines
2140 lifeLine1.getNewEventOccurrence();
2141 lifeLine2.getNewEventOccurrence();
32897d73 2142
73844f9c
PT
2143 AsyncMessageReturn asynReturn1 = new AsyncMessageReturn();
2144 asynReturn1.setName("Async Message Return 1");
2145 asynReturn1.setStartLifeline(lifeLine2);
2146 asynReturn1.setEndLifeline(lifeLine1);
2147 asynReturn1.setMessage(asyn1);
2148 testFrame.addMessage(asynReturn1);
2149
2150 /*
2151 * Create a note
2152 */
2153
2154 // Get new occurrence on lifelines
2155 lifeLine1.getNewEventOccurrence();
2156
0c54f1fe 2157 EllipsisMessage info = new EllipsisMessage();
73844f9c
PT
2158 info.setName("Object deletion");
2159 info.setStartLifeline(lifeLine2);
2160 testFrame.addNode(info);
2161
2162 /*
2163 * Create a Stop
2164 */
2165 Stop stop = new Stop();
2166 stop.setLifeline(lifeLine2);
2167 stop.setEventOccurrence(lifeLine2.getNewEventOccurrence());
2168 lifeLine2.addNode(stop);
2169
2170 fSdView.setFrame(testFrame);
2171 }
2172}
2173</pre>
32897d73 2174
73844f9c
PT
2175Now 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>
2176[[Image:images/SampleDiagram1.png]] <br>
32897d73 2177
73844f9c 2178=== Adding time information ===
32897d73 2179
0c54f1fe 2180To 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 2181
73844f9c
PT
2182<pre>
2183 private void createFrame() {
2184 //...
2185 start.setTime(new TmfTimestamp(1000, -3));
2186 syn1.setTime(new TmfTimestamp(1005, -3));
2187 synReturn1.setTime(new TmfTimestamp(1050, -3));
2188 asyn1.setStartTime(new TmfTimestamp(1060, -3));
2189 asyn1.setEndTime(new TmfTimestamp(1070, -3));
2190 asynReturn1.setStartTime(new TmfTimestamp(1060, -3));
2191 asynReturn1.setEndTime(new TmfTimestamp(1070, -3));
2192 //...
2193 }
2194</pre>
32897d73 2195
73844f9c 2196When 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 2197
73844f9c 2198[[Image:images/SampleDiagramTimeComp.png]] <br>
32897d73 2199
73844f9c 2200By 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 2201
73844f9c
PT
2202[[Image:images/SampleDiagramSyncMessage.png]] <br>
2203[[Image:images/SampleDiagramAsyncMessage.png]] <br>
32897d73 2204
0c54f1fe 2205To 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 2206[[Image:images/SampleDiagramMessageDelta.png]] <br>
32897d73 2207
73844f9c 2208=== Default Coolbar and Menu Items ===
32897d73 2209
73844f9c
PT
2210The Sequence Diagram View comes with default coolbar and menu items. By default, each sequence diagram shows the following actions:
2211* Zoom in
2212* Zoom out
2213* Reset Zoom Factor
2214* Selection
2215* Configure Min Max (drop-down menu only)
2216* Navigation -> Show the node end (drop-down menu only)
2217* Navigation -> Show the node start (drop-down menu only)
32897d73 2218
73844f9c 2219[[Image:images/DefaultCoolbarMenu.png]]<br>
32897d73 2220
73844f9c 2221=== Implementing Optional Callbacks ===
32897d73 2222
73844f9c 2223The following chapters describe how to use all supported provider interfaces.
32897d73 2224
73844f9c 2225==== Using the Paging Provider Interface ====
32897d73 2226
73844f9c
PT
2227For 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.
2228<br>
2229To 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 2230
73844f9c
PT
2231<pre>
2232public class SampleLoader implements IUml2SDLoader, ISDPagingProvider {
2233 //...
2234 private page = 0;
2235
2236 @Override
2237 public void dispose() {
2238 if (fSdView != null) {
2239 fSdView.resetProviders();
2240 }
2241 }
2242
2243 @Override
2244 public void setViewer(SDView arg0) {
2245 fSdView = arg0;
2246 fSdView.setSDPagingProvider(this);
2247 createFrame();
2248 }
2249
2250 private void createSecondFrame() {
2251 Frame testFrame = new Frame();
2252 testFrame.setName("SecondFrame");
2253 Lifeline lifeline = new Lifeline();
2254 lifeline.setName("LifeLine 0");
2255 testFrame.addLifeLine(lifeline);
2256 lifeline = new Lifeline();
2257 lifeline.setName("LifeLine 1");
2258 testFrame.addLifeLine(lifeline);
2259 for (int i = 1; i < 5; i++) {
2260 SyncMessage message = new SyncMessage();
2261 message.autoSetStartLifeline(testFrame.getLifeline(0));
2262 message.autoSetEndLifeline(testFrame.getLifeline(0));
2263 message.setName((new StringBuilder("Message ")).append(i).toString());
2264 testFrame.addMessage(message);
2265
2266 SyncMessageReturn messageReturn = new SyncMessageReturn();
2267 messageReturn.autoSetStartLifeline(testFrame.getLifeline(0));
2268 messageReturn.autoSetEndLifeline(testFrame.getLifeline(0));
2269
2270 testFrame.addMessage(messageReturn);
2271 messageReturn.setName((new StringBuilder("Message return ")).append(i).toString());
2272 ExecutionOccurrence occ = new ExecutionOccurrence();
2273 occ.setStartOccurrence(testFrame.getSyncMessage(i - 1).getEventOccurrence());
2274 occ.setEndOccurrence(testFrame.getSyncMessageReturn(i - 1).getEventOccurrence());
2275 testFrame.getLifeline(0).addExecution(occ);
2276 }
2277 fSdView.setFrame(testFrame);
2278 }
32897d73 2279
73844f9c
PT
2280 @Override
2281 public boolean hasNextPage() {
2282 return page == 0;
2283 }
32897d73 2284
73844f9c
PT
2285 @Override
2286 public boolean hasPrevPage() {
2287 return page == 1;
2288 }
32897d73 2289
73844f9c
PT
2290 @Override
2291 public void nextPage() {
2292 page = 1;
2293 createSecondFrame();
2294 }
32897d73 2295
73844f9c
PT
2296 @Override
2297 public void prevPage() {
2298 page = 0;
2299 createFrame();
2300 }
32897d73 2301
73844f9c
PT
2302 @Override
2303 public void firstPage() {
2304 page = 0;
2305 createFrame();
2306 }
32897d73 2307
73844f9c
PT
2308 @Override
2309 public void lastPage() {
2310 page = 1;
2311 createSecondFrame();
2312 }
2313 //...
2314}
32897d73 2315
73844f9c 2316</pre>
32897d73 2317
73844f9c 2318When running the example application, new actions will be shown in the coolbar and the coolbar menu. <br>
32897d73 2319
73844f9c 2320[[Image:images/PageProviderAdded.png]]
32897d73 2321
73844f9c
PT
2322<br><br>
2323To 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.
2324<br>
2325
2326==== Using the Find Provider Interface ====
32897d73 2327
73844f9c
PT
2328For 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.
2329<br>
2330For 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.
2331<br>
2332Only on at a time can be active. If the extended find provder is defined it obsoletes the basic find provider.
2333<br>
2334To 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 2335
73844f9c
PT
2336<pre>
2337public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider {
32897d73 2338
73844f9c
PT
2339 //...
2340 @Override
2341 public void dispose() {
2342 if (fSdView != null) {
2343 fSdView.resetProviders();
2344 }
2345 }
32897d73 2346
73844f9c
PT
2347 @Override
2348 public void setViewer(SDView arg0) {
2349 fSdView = arg0;
2350 fSdView.setSDPagingProvider(this);
2351 fSdView.setSDFindProvider(this);
2352 createFrame();
2353 }
32897d73 2354
73844f9c
PT
2355 @Override
2356 public boolean isNodeSupported(int nodeType) {
2357 switch (nodeType) {
2358 case ISDGraphNodeSupporter.LIFELINE:
2359 case ISDGraphNodeSupporter.SYNCMESSAGE:
2360 return true;
32897d73 2361
73844f9c
PT
2362 default:
2363 break;
2364 }
2365 return false;
2366 }
2367
2368 @Override
2369 public String getNodeName(int nodeType, String loaderClassName) {
2370 switch (nodeType) {
2371 case ISDGraphNodeSupporter.LIFELINE:
2372 return "Lifeline";
2373 case ISDGraphNodeSupporter.SYNCMESSAGE:
2374 return "Sync Message";
2375 }
2376 return "";
2377 }
32897d73 2378
73844f9c
PT
2379 @Override
2380 public boolean find(Criteria criteria) {
2381 Frame frame = fSdView.getFrame();
2382 if (criteria.isLifeLineSelected()) {
2383 for (int i = 0; i < frame.lifeLinesCount(); i++) {
2384 if (criteria.matches(frame.getLifeline(i).getName())) {
2385 fSdView.getSDWidget().moveTo(frame.getLifeline(i));
2386 return true;
2387 }
2388 }
2389 }
2390 if (criteria.isSyncMessageSelected()) {
2391 for (int i = 0; i < frame.syncMessageCount(); i++) {
2392 if (criteria.matches(frame.getSyncMessage(i).getName())) {
2393 fSdView.getSDWidget().moveTo(frame.getSyncMessage(i));
2394 return true;
2395 }
2396 }
2397 }
2398 return false;
2399 }
32897d73 2400
73844f9c
PT
2401 @Override
2402 public void cancel() {
2403 // reset find parameters
2404 }
2405 //...
2406}
2407</pre>
32897d73 2408
73844f9c
PT
2409When running the example application, the find action will be shown in the coolbar and the coolbar menu. <br>
2410[[Image:images/FindProviderAdded.png]]
32897d73 2411
73844f9c
PT
2412To 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>
2413[[Image:images/FindDialog.png]]<br>
32897d73 2414
73844f9c 2415Note that the find dialog will be opened by typing the key shortcut CRTL+F.
32897d73 2416
73844f9c 2417==== Using the Filter Provider Interface ====
32897d73 2418
0c54f1fe 2419For 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
2420<br>
2421To 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>
2422Note that no example implementation of ''filter()'' is provided.
2423<br>
32897d73 2424
73844f9c
PT
2425<pre>
2426public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider, ISDFilterProvider {
32897d73 2427
73844f9c
PT
2428 //...
2429 @Override
2430 public void dispose() {
2431 if (fSdView != null) {
2432 fSdView.resetProviders();
2433 }
2434 }
32897d73 2435
73844f9c
PT
2436 @Override
2437 public void setViewer(SDView arg0) {
2438 fSdView = arg0;
2439 fSdView.setSDPagingProvider(this);
2440 fSdView.setSDFindProvider(this);
2441 fSdView.setSDFilterProvider(this);
2442 createFrame();
2443 }
32897d73 2444
73844f9c
PT
2445 @Override
2446 public boolean filter(List<?> list) {
2447 return false;
2448 }
2449 //...
2450}
2451</pre>
32897d73 2452
73844f9c
PT
2453When running the example application, the filter action will be shown in the coolbar menu. <br>
2454[[Image:images/HidePatternsMenuItem.png]]
32897d73 2455
73844f9c
PT
2456To filter select the '''Hide Patterns...''' of the coolbar menu. A new dialog box will open. <br>
2457[[Image:images/DialogHidePatterns.png]]
32897d73 2458
73844f9c
PT
2459To 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>
2460[[Image:images/DialogHidePatterns.png]] <br>
32897d73 2461
73844f9c 2462Now back at the Hide Pattern dialog. Select one or more filter and select '''OK'''.
32897d73 2463
73844f9c 2464To 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 2465
73844f9c 2466==== Using the Extended Action Bar Provider Interface ====
32897d73 2467
73844f9c
PT
2468The extended action bar provider can be used to add customized actions to the Sequence Diagram View.
2469To 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 2470
73844f9c
PT
2471<pre>
2472public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider, ISDFilterProvider, ISDExtendedActionBarProvider {
2473 //...
2474
2475 @Override
2476 public void dispose() {
2477 if (fSdView != null) {
2478 fSdView.resetProviders();
2479 }
2480 }
32897d73 2481
73844f9c
PT
2482 @Override
2483 public void setViewer(SDView arg0) {
2484 fSdView = arg0;
2485 fSdView.setSDPagingProvider(this);
2486 fSdView.setSDFindProvider(this);
2487 fSdView.setSDFilterProvider(this);
2488 fSdView.setSDExtendedActionBarProvider(this);
2489 createFrame();
2490 }
32897d73 2491
73844f9c
PT
2492 @Override
2493 public void supplementCoolbarContent(IActionBars iactionbars) {
2494 Action action = new Action("Refresh") {
2495 @Override
2496 public void run() {
2497 System.out.println("Refreshing...");
2498 }
2499 };
2500 iactionbars.getMenuManager().add(action);
2501 iactionbars.getToolBarManager().add(action);
2502 }
2503 //...
2504}
2505</pre>
32897d73 2506
73844f9c
PT
2507When running the example application, all new actions will be added to the coolbar and coolbar menu according to the implementation of ''supplementCoolbarContent()''<br>.
2508For the example above the coolbar and coolbar menu will look as follows.
32897d73 2509
73844f9c 2510[[Image:images/SupplCoolbar.png]]
32897d73 2511
73844f9c 2512==== Using the Properties Provider Interface====
32897d73 2513
73844f9c 2514This 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 2515
73844f9c 2516To 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 2517
73844f9c
PT
2518Please refer to the following Eclipse articles for more information about properties and tabed properties.
2519*[http://www.eclipse.org/articles/Article-Properties-View/properties-view.html | Take control of your properties]
2520*[http://www.eclipse.org/articles/Article-Tabbed-Properties/tabbed_properties_view.html | The Eclipse Tabbed Properties View]
32897d73 2521
73844f9c 2522==== Using the Collapse Provider Interface ====
32897d73 2523
73844f9c 2524This 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 2525
73844f9c 2526To 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 2527
73844f9c 2528==== Using the Selection Provider Service ====
32897d73 2529
73844f9c 2530The 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 2531
73844f9c
PT
2532<pre>
2533public class SampleLoader implements IUml2SDLoader, ISDPagingProvider, ISDFindProvider, ISDFilterProvider, ISDExtendedActionBarProvider, ISelectionListener {
32897d73 2534
73844f9c
PT
2535 //...
2536 @Override
2537 public void dispose() {
2538 if (fSdView != null) {
2539 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().removePostSelectionListener(this);
2540 fSdView.resetProviders();
2541 }
2542 }
32897d73 2543
73844f9c
PT
2544 @Override
2545 public String getTitleString() {
2546 return "Sample Diagram";
2547 }
32897d73 2548
73844f9c
PT
2549 @Override
2550 public void setViewer(SDView arg0) {
2551 fSdView = arg0;
2552 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().addPostSelectionListener(this);
2553 fSdView.setSDPagingProvider(this);
2554 fSdView.setSDFindProvider(this);
2555 fSdView.setSDFilterProvider(this);
2556 fSdView.setSDExtendedActionBarProvider(this);
32897d73 2557
73844f9c
PT
2558 createFrame();
2559 }
32897d73 2560
73844f9c
PT
2561 @Override
2562 public void selectionChanged(IWorkbenchPart part, ISelection selection) {
2563 ISelection sel = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();
2564 if (sel != null && (sel instanceof StructuredSelection)) {
2565 StructuredSelection stSel = (StructuredSelection) sel;
2566 if (stSel.getFirstElement() instanceof BaseMessage) {
2567 BaseMessage syncMsg = ((BaseMessage) stSel.getFirstElement());
2568 System.out.println("Message '" + syncMsg.getName() + "' selected.");
2569 }
2570 }
2571 }
2572
2573 //...
2574}
2575</pre>
32897d73 2576
73844f9c 2577=== Printing a Sequence Diagram ===
32897d73 2578
73844f9c 2579To 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 2580
73844f9c 2581[[Image:images/PrintDialog.png]] <br>
32897d73 2582
73844f9c 2583Fill in all the relevant information, select '''Printer...''' to choose the printer and the press '''OK'''.
32897d73 2584
73844f9c 2585=== Using one Sequence Diagram View with Multiple Loaders ===
32897d73 2586
73844f9c 2587A 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 2588
73844f9c
PT
2589<pre>
2590public class OpenSDView extends AbstractHandler {
2591 @Override
2592 public Object execute(ExecutionEvent event) throws ExecutionException {
2593 try {
2594 IWorkbenchPage persp = TmfUiPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
2595 SDView view = (SDView) persp.showView("org.eclipse.linuxtools.ust.examples.ui.componentinteraction");
2596 LoadersManager.getLoadersManager().createLoader("org.eclipse.linuxtools.tmf.ui.views.uml2sd.impl.TmfUml2SDSyncLoader", view);
2597 } catch (PartInitException e) {
2598 throw new ExecutionException("PartInitException caught: ", e);
2599 }
2600 return null;
2601 }
2602}
2603</pre>
32897d73 2604
73844f9c 2605=== Downloading the Tutorial ===
32897d73 2606
73844f9c 2607Use 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 2608
73844f9c 2609== Integration of Tracing and Monitoring Framework with Sequence Diagram Framework ==
32897d73 2610
73844f9c 2611In 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 2612
73844f9c 2613=== Reference Implementation ===
32897d73 2614
73844f9c 2615A Sequence Diagram View Extension is defined in the plug-in TMF UI as well as a uml2SDLoader Extension with the reference loader.
32897d73 2616
73844f9c 2617[[Image:images/ReferenceExtensions.png]]
32897d73 2618
73844f9c 2619=== Used Sequence Diagram Features ===
32897d73 2620
73844f9c
PT
2621Besides the default features of the Sequence Diagram Framework, the reference implementation uses the following additional features:
2622*Advanced paging
2623*Basic finding
2624*Basic filtering
2625*Selection Service
32897d73 2626
73844f9c 2627==== Advanced paging ====
32897d73 2628
73844f9c 2629The 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 2630
73844f9c 2631==== Basic finding ====
32897d73 2632
73844f9c 2633The 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 2634
73844f9c 2635==== Basic filtering ====
32897d73 2636
73844f9c 2637The 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 2638
73844f9c 2639==== Selection Service ====
32897d73 2640
73844f9c 2641The 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 2642
73844f9c 2643=== Used TMF Features ===
32897d73 2644
73844f9c
PT
2645The reference implementation uses the following features of TMF:
2646*TMF Experiment and Trace for accessing traces
2647*Event Request Framework to request TMF events from the experiment and respective traces
2648*Signal Framework for broadcasting and receiving TMF signals for synchronization purposes
32897d73 2649
73844f9c 2650==== TMF Experiment and Trace for accessing traces ====
32897d73 2651
73844f9c 2652The reference loader uses TMF Experiments to access traces and to request data from the traces.
32897d73 2653
73844f9c 2654==== TMF Event Request Framework ====
32897d73 2655
73844f9c 2656The reference loader use the TMF Event Request Framework to request events from the experiment and its traces.
32897d73 2657
73844f9c 2658When 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 2659
73844f9c 2660When 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 2661
73844f9c 2662A third type of event request is issued for finding specific data across pages.
32897d73 2663
73844f9c 2664==== TMF Signal Framework ====
32897d73 2665
0c54f1fe 2666The 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
2667*''TmfTraceSelectedSignal''
2668This 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 2669*''TmfTraceClosedSignal''
73844f9c
PT
2670This 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.
2671*''TmfTimeSynchSignal''
0c54f1fe 2672This 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
2673*''TmfRangeSynchSignal''
2674This 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 2675
73844f9c 2676Besides 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 2677
73844f9c 2678=== Supported Traces ===
32897d73 2679
73844f9c 2680The 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 2681
73844f9c 2682Note that combined traces of multiple components, that contain the trace information about the same interactions are not supported in the reference implementation!
32897d73 2683
73844f9c 2684=== Trace Format ===
32897d73 2685
73844f9c 2686The 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 2687
73844f9c
PT
2688<pre>
2689 /**
2690 * @param tmfEvent Event to parse for sequence diagram event details
2691 * @return sequence diagram event if details are available else null
2692 */
2693 protected ITmfSyncSequenceDiagramEvent getSequenceDiagramEvent(ITmfEvent tmfEvent){
2694 //type = .*RECEIVE.* or .*SEND.*
2695 //content = sender:<sender name>:receiver:<receiver name>,signal:<signal name>
2696 String eventType = tmfEvent.getType().toString();
2697 if (eventType.contains(Messages.TmfUml2SDSyncLoader_EventTypeSend) || eventType.contains(Messages.TmfUml2SDSyncLoader_EventTypeReceive)) {
2698 Object sender = tmfEvent.getContent().getField(Messages.TmfUml2SDSyncLoader_FieldSender);
2699 Object receiver = tmfEvent.getContent().getField(Messages.TmfUml2SDSyncLoader_FieldReceiver);
2700 Object name = tmfEvent.getContent().getField(Messages.TmfUml2SDSyncLoader_FieldSignal);
2701 if ((sender instanceof ITmfEventField) && (receiver instanceof ITmfEventField) && (name instanceof ITmfEventField)) {
2702 ITmfSyncSequenceDiagramEvent sdEvent = new TmfSyncSequenceDiagramEvent(tmfEvent,
2703 ((ITmfEventField) sender).getValue().toString(),
2704 ((ITmfEventField) receiver).getValue().toString(),
2705 ((ITmfEventField) name).getValue().toString());
32897d73 2706
73844f9c
PT
2707 return sdEvent;
2708 }
2709 }
2710 return null;
32897d73 2711 }
32897d73
AM
2712</pre>
2713
0c54f1fe 2714The 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 2715
73844f9c 2716=== How to use the Reference Implementation ===
32897d73 2717
0c54f1fe 2718An 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 2719
0c54f1fe 2720Run 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 2721[[Image:images/ShowTmfSDView.png]]<br>
32897d73 2722
0c54f1fe 2723A blank Sequence Diagram View will open.
32897d73 2724
0c54f1fe
BH
2725Then import the reference trace to the '''Project Explorer''' using the '''Import Trace Package...''' menu option.<br>
2726[[Image:images/ImportTracePackage.png]]
2727
2728Next, 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 2729[[Image:images/ReferenceSeqDiagram.png]]<br>
32897d73 2730
0c54f1fe 2731Now the reference implementation can be explored. To demonstrate the view features try the following things:
73844f9c
PT
2732*Select a message in the Sequence diagram. As result the corresponding event will be selected in the Events View.
2733*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.
2734*In the Events View, press key ''End''. As result, the Sequence Diagram view will jump to the last page.
2735*In the Events View, press key ''Home''. As result, the Sequence Diagram view will jump to the first page.
2736*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.
2737* 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>
2738
73844f9c 2739=== Extending the Reference Loader ===
32897d73 2740
73844f9c 2741In 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 2742
73844f9c 2743= CTF Parser =
32897d73 2744
73844f9c
PT
2745== CTF Format ==
2746CTF is a format used to store traces. It is self defining, binary and made to be easy to write to.
2747Before going further, the full specification of the CTF file format can be found at http://www.efficios.com/ .
32897d73 2748
73844f9c 2749For 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 2750
73844f9c
PT
2751These files can be split into two types :
2752* Metadata
2753* Event streams
32897d73 2754
73844f9c
PT
2755=== Metadata ===
2756The 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 2757
73844f9c
PT
2758=== Event Streams ===
2759The 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 2760
73844f9c 2761So 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 2762
73844f9c
PT
2763== Reading a trace ==
2764In order to read a CTF trace, two steps must be done.
2765* The metadata must be read to know how to read the events.
2766* the events must be read.
32897d73 2767
73844f9c 2768The 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 2769
73844f9c
PT
2770When the metadata is loaded and read, the trace object will be populated with 3 items:
2771* the event definitions available per stream: a definition is a description of the datatype.
2772* 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.
2773* the beginning of a packet index.
32897d73 2774
73844f9c 2775Now 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 2776
73844f9c
PT
2777== Seeking in a trace ==
2778The 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 2779
73844f9c
PT
2780== Interfacing to TMF ==
2781The trace can be read easily now but the data is still awkward to extract.
32897d73 2782
73844f9c
PT
2783=== CtfLocation ===
2784A 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 2785
73844f9c
PT
2786=== CtfTmfTrace ===
2787The CtfTmfTrace is a wrapper for the standard CTF trace that allows it to perform the following actions:
2788* '''initTrace()''' create a trace
2789* '''validateTrace()''' is the trace a CTF trace?
2790* '''getLocationRatio()''' how far in the trace is my location?
2791* '''seekEvent()''' sets the cursor to a certain point in a trace.
2792* '''readNextEvent()''' reads the next event and then advances the cursor
2793* '''getTraceProperties()''' gets the 'env' structures of the metadata
2794
2795=== CtfIterator ===
2796The 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.
2797
2798=== CtfIteratorManager ===
2799Since 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.
2800
2801=== CtfTmfContext ===
2802The 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.
2803
2804=== CtfTmfTimestamp ===
2805The 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.
2806
2807=== CtfTmfEvent ===
2808The 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.
2809
2810=== Other ===
2811There are other helper files that format given events for views, they are simpler and the architecture does not depend on them.
2812
2813=== Limitations ===
2814For the moment live trace reading is not supported, there are no sources of traces to test on.
32897d73 2815
fc3177d9
GB
2816= Event matching and trace synchronization =
2817
2818Event 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.
2819
2820Trace 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.
2821
2822== Event matching interfaces ==
2823
2824Here'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:
2825
2826* '''ITmfEventMatching''': Controls the event matching process
2827* '''ITmfMatchEventDefinition''': Describes how events are matched
2828* '''IMatchProcessingUnit''': Processes the matched events
2829
2830== Implementation details and how to extend it ==
2831
2832=== ITmfEventMatching interface and derived classes ===
2833
2834This 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.
2835
2836The 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.
2837
2838Class '''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.
2839
2840To 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.
2841
2842=== ITmfMatchEventDefinition interface and its derived classes ===
2843
2844These are the classes that describe how to actually match specific events together.
2845
2846The '''canMatchTrace''' method will tell if a definition is compatible with a given trace.
2847
2848The '''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.
2849
2850Typically, there would be a match definition abstract class/interface per event matching type.
2851
2852The 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.
2853
2854As 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.
2855
2856=== IMatchProcessingUnit interface and derived classes ===
2857
2858While 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.
2859
2860'''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.
2861
2862A 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.
2863
2864== Code examples ==
2865
2866=== Using network packets matching in an analysis ===
2867
2868This 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.
2869
2870<pre>
2871class MyAnalysis extends TmfAbstractAnalysisModule {
2872
2873 private TmfNetworkEventMatching tcpMatching;
2874
2875 ...
2876
2877 protected void executeAnalysis() {
2878
2879 IMatchProcessingUnit matchProcessing = new IMatchProcessingUnit() {
2880 @Override
2881 public void matchingEnded() {
2882 }
2883
2884 @Override
2885 public void init(ITmfTrace[] fTraces) {
2886 }
2887
2888 @Override
2889 public int countMatches() {
2890 return 0;
2891 }
2892
2893 @Override
2894 public void addMatch(TmfEventDependency match) {
2895 log.debug("we got a tcp match! " + match.getSourceEvent().getContent() + " " + match.getDestinationEvent().getContent());
2896 TmfEvent source = match.getSourceEvent();
2897 TmfEvent destination = match.getDestinationEvent();
2898 /* Create a link between the two events */
2899 }
2900 };
2901
2902 ITmfTrace[] traces = { getTrace() };
2903 tcpMatching = new TmfNetworkEventMatching(traces, matchProcessing);
2904 tcpMatching.initMatching();
2905
2906 MyEventRequest request = new MyEventRequest(this, i);
2907 getTrace().sendRequest(request);
2908 }
2909
2910 public void analyzeEvent(TmfEvent event) {
2911 ...
2912 tcpMatching.matchEvent(event, 0);
2913 ...
2914 }
2915
2916 ...
2917
2918}
2919
2920class MyEventRequest extends TmfEventRequest {
2921
2922 private final MyAnalysis analysis;
2923
2924 MyEventRequest(MyAnalysis analysis, int traceno) {
2925 super(CtfTmfEvent.class,
2926 TmfTimeRange.ETERNITY,
2927 0,
2928 TmfDataRequest.ALL_DATA,
2929 ITmfDataRequest.ExecutionType.FOREGROUND);
2930 this.analysis = analysis;
2931 }
2932
2933 @Override
2934 public void handleData(final ITmfEvent event) {
2935 super.handleData(event);
2936 if (event != null) {
2937 analysis.analyzeEvent(event);
2938 }
2939 }
2940}
2941</pre>
2942
2943=== Match network events from UST traces ===
2944
2945Suppose 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.
2946
2947The following metadata describes the events:
2948
2949<pre>
2950 event {
2951 name = "myapp:send";
2952 id = 0;
2953 stream_id = 0;
2954 loglevel = 13;
2955 fields := struct {
2956 integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _sendto;
2957 integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _messageid;
2958 integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _data;
2959 };
2960 };
2961
2962 event {
2963 name = "myapp:receive";
2964 id = 1;
2965 stream_id = 0;
2966 loglevel = 13;
2967 fields := struct {
2968 integer { size = 32; align = 8; signed = 1; encoding = none; base = 10; } _from;
2969 integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _messageid;
2970 integer { size = 64; align = 8; signed = 1; encoding = none; base = 10; } _data;
2971 };
2972 };
2973</pre>
2974
2975One would need to write an event match definition for those 2 events as follows:
2976
2977<pre>
2978public class MyAppUstEventMatching implements ITmfNetworkMatchDefinition {
2979
2980 @Override
2981 public Direction getDirection(ITmfEvent event) {
2982 String evname = event.getType().getName();
2983 if (evname.equals("myapp:receive")) {
2984 return Direction.IN;
2985 } else if (evname.equals("myapp:send")) {
2986 return Direction.OUT;
2987 }
2988 return null;
2989 }
2990
2991 @Override
2992 public List<Object> getUniqueField(ITmfEvent event) {
2993 List<Object> keys = new ArrayList<Object>();
2994
2995 if (evname.equals("myapp:receive")) {
2996 keys.add(event.getContent().getField("from").getValue());
2997 keys.add(event.getContent().getField("messageid").getValue());
2998 } else {
2999 keys.add(event.getContent().getField("sendto").getValue());
3000 keys.add(event.getContent().getField("messageid").getValue());
3001 }
3002
3003 return keys;
3004 }
3005
3006 @Override
3007 public boolean canMatchTrace(ITmfTrace trace) {
3008 if (!(trace instanceof CtfTmfTrace)) {
3009 return false;
3010 }
3011 CtfTmfTrace ktrace = (CtfTmfTrace) trace;
3012 String[] events = { "myapp:receive", "myapp:send" };
3013 return ktrace.hasAtLeastOneOfEvents(events);
3014 }
3015
3016 @Override
3017 public MatchingType[] getApplicableMatchingTypes() {
3018 MatchingType[] types = { MatchingType.NETWORK };
3019 return types;
3020 }
3021
3022}
3023</pre>
3024
3025Somewhere in code that will be executed at the start of the plugin (like in the Activator), the following code will have to be run:
3026
3027<pre>
3028TmfEventMatching.registerMatchObject(new MyAppUstEventMatching());
3029</pre>
3030
3031Now, 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.
3032
3033== Trace synchronization ==
3034
3035Trace synchronization classes and interfaces are located in the ''org.eclipse.linuxtools.tmf.core.synchronization'' package.
3036
3037=== Synchronization algorithm ===
3038
3039Synchronization 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.
3040
3041The 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.
3042
3043The ''fully incremental convex hull'' synchronization algorithm is the default synchronization algorithm.
3044
3045While 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:
3046
3047<pre>
3048SynchronizationAlgorithm syncAlgo = new MyNewSynchronizationAlgorithm();
3049syncAlgo = SynchronizationManager.synchronizeTraces(syncFile, traces, syncAlgo, true);
3050</pre>
3051
3052=== Timestamp transforms ===
3053
3054Timestamp 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.
3055
3056The following classes implement this interface:
3057
3058* '''TmfTimestampTransform''': default transform. It cannot be instantiated, it has a single static object TmfTimestampTransform.IDENTITY, which returns the original timestamp.
3059* '''TmfTimestampTransformLinear''': transforms the timestamp using a linear formula: ''f(t) = at + b'', where ''a'' and ''b'' are computed by the synchronization algorithm.
3060
3061One 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.
3062
3063== Todo ==
3064
3065Here's a list of features not yet implemented that would enhance trace synchronization and event matching:
3066
3067* Ability to select a synchronization algorithm
3068* 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))
3069* 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.
3070* 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.
3071* Add more views to display the synchronization information (only textual statistics are available for now)
42f1f820
GB
3072
3073= Analysis Framework =
3074
3075Analysis 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.
3076
3077Analyses can have parameters they can use in their code. They also have outputs registered to them to display the results from their execution.
3078
3079== Creating a new module ==
3080
3081All 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.
3082
3083=== Example ===
3084
3085This example shows how to add a simple analysis module for an LTTng kernel trace with two parameters.
3086
3087<pre>
3088public class MyLttngKernelAnalysis extends TmfAbstractAnalysisModule {
3089
3090 public static final String PARAM1 = "myparam";
3091 public static final String PARAM2 = "myotherparam";
3092
3093 @Override
3094 public boolean canExecute(ITmfTrace trace) {
3095 /* This just makes sure the trace is an Lttng kernel trace, though
3096 usually that should have been done by specifying the trace type
3097 this analysis module applies to */
3098 if (!LttngKernelTrace.class.isAssignableFrom(trace.getClass())) {
3099 return false;
3100 }
3101
3102 /* Does the trace contain the appropriate events? */
3103 String[] events = { "sched_switch", "sched_wakeup" };
3104 return ((LttngKernelTrace) trace).hasAllEvents(events);
3105 }
3106
3107 @Override
3108 protected void canceling() {
3109 /* The job I am running in is being cancelled, let's clean up */
3110 }
3111
3112 @Override
3113 protected boolean executeAnalysis(final IProgressMonitor monitor) {
3114 /*
3115 * I am running in an Eclipse job, and I already know I can execute
3116 * on a given trace.
3117 *
3118 * In the end, I will return true if I was successfully completed or
3119 * false if I was either interrupted or something wrong occurred.
3120 */
3121 Object param1 = getParameter(PARAM1);
3122 int param2 = (Integer) getParameter(PARAM2);
3123 }
3124
3125 @Override
3126 public Object getParameter(String name) {
3127 Object value = super.getParameter(name);
3128 /* Make sure the value of param2 is of the right type. For sake of
3129 simplicity, the full parameter format validation is not presented
3130 here */
3131 if ((value != null) && name.equals(PARAM2) && (value instanceof String)) {
3132 return Integer.parseInt((String) value);
3133 }
3134 return value;
3135 }
3136
3137}
3138</pre>
3139
3140=== Available base analysis classes and interfaces ===
3141
3142The following are available as base classes for analysis modules. They also extend the abstract '''TmfAbstractAnalysisModule'''
3143
3144* '''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.
3145
3146The 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.
3147
3148* '''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.
3149
3150=== How it works ===
3151
3152Analyses 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.
3153
3154When 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.
3155
3156The 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.
3157
3158A 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'''.
3159
3160== Telling TMF about the analysis module ==
3161
3162Now 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.
3163
3164The following code shows what the resulting plugin.xml file should look like.
3165
3166<pre>
3167<extension
3168 point="org.eclipse.linuxtools.tmf.core.analysis">
3169 <module
3170 id="my.lttng.kernel.analysis.id"
3171 name="My LTTng Kernel Analysis"
3172 analysis_module="my.plugin.package.MyLttngKernelAnalysis"
3173 automatic="true">
3174 <parameter
3175 name="myparam">
3176 </parameter>
3177 <parameter
3178 default_value="3"
3179 name="myotherparam">
3180 <tracetype
3181 class="org.eclipse.linuxtools.lttng2.kernel.core.trace.LttngKernelTrace">
3182 </tracetype>
3183 </module>
3184</extension>
3185</pre>
3186
3187This 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.
3188
3189Note 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.
3190
3191== Attaching outputs and views to the analysis module ==
3192
3193Analyses 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.
3194
0c043a90 3195An 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
3196
3197The various concrete output types are:
3198
3199* '''TmfAnalysisViewOutput''': It takes a view ID as parameter and, when selected, opens the view.
3200
0c043a90
GB
3201=== Using the extension point to add outputs ===
3202
3203Analysis 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.
3204
3205The 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.
3206
3207<pre>
3208<extension
3209 point="org.eclipse.linuxtools.tmf.core.analysis">
3210 <output
3211 class="org.eclipse.linuxtools.tmf.ui.analysis.TmfAnalysisViewOutput"
3212 id="my.plugin.package.ui.views.myView">
3213 <analysisId
3214 id="my.lttng.kernel.analysis.id">
3215 </analysisId>
3216 </output>
3217 <output
3218 class="org.eclipse.linuxtools.tmf.ui.analysis.TmfAnalysisViewOutput"
3219 id="my.plugin.package.ui.views.myMoreGenericView">
3220 <analysisModuleClass
3221 class="my.plugin.package.core.MyAnalysisModuleClass">
3222 </analysisModuleClass>
3223 </output>
3224</extension>
3225</pre>
3226
42f1f820
GB
3227== Providing help for the module ==
3228
3229For 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.
3230
3231What 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.
3232
3233== Using analysis parameter providers ==
3234
3235An 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.
3236
3237=== Example parameter provider ===
3238
3239The 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.
3240
3241<pre>
3242public class MyLttngKernelParameterProvider extends TmfAbstractAnalysisParamProvider {
3243
3244 private ControlFlowEntry fCurrentEntry = null;
3245
3246 private static final String NAME = "My Lttng kernel parameter provider"; //$NON-NLS-1$
3247
3248 private ISelectionListener selListener = new ISelectionListener() {
3249 @Override
3250 public void selectionChanged(IWorkbenchPart part, ISelection selection) {
3251 if (selection instanceof IStructuredSelection) {
3252 Object element = ((IStructuredSelection) selection).getFirstElement();
3253 if (element instanceof ControlFlowEntry) {
3254 ControlFlowEntry entry = (ControlFlowEntry) element;
3255 setCurrentThreadEntry(entry);
3256 }
3257 }
3258 }
3259 };
3260
3261 /*
3262 * Constructor
3263 */
3264 public CriticalPathParameterProvider() {
3265 super();
3266 registerListener();
3267 }
3268
3269 @Override
3270 public String getName() {
3271 return NAME;
3272 }
3273
3274 @Override
3275 public Object getParameter(String name) {
3276 if (fCurrentEntry == null) {
3277 return null;
3278 }
3279 if (name.equals(MyLttngKernelAnalysis.PARAM1)) {
3280 return fCurrentEntry.getThreadId()
3281 }
3282 return null;
3283 }
3284
3285 @Override
3286 public boolean appliesToTrace(ITmfTrace trace) {
3287 return (trace instanceof LttngKernelTrace);
3288 }
3289
3290 private void setCurrentThreadEntry(ControlFlowEntry entry) {
3291 if (!entry.equals(fCurrentEntry)) {
3292 fCurrentEntry = entry;
3293 this.notifyParameterChanged(MyLttngKernelAnalysis.PARAM1);
3294 }
3295 }
3296
3297 private void registerListener() {
3298 final IWorkbench wb = PlatformUI.getWorkbench();
3299
3300 final IWorkbenchPage activePage = wb.getActiveWorkbenchWindow().getActivePage();
3301
3302 /* Add the listener to the control flow view */
3303 view = activePage.findView(ControlFlowView.ID);
3304 if (view != null) {
3305 view.getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(selListener);
3306 view.getSite().getWorkbenchWindow().getPartService().addPartListener(partListener);
3307 }
3308 }
3309
3310}
3311</pre>
3312
3313=== Register the parameter provider to the analysis ===
3314
3315To 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:
3316
3317<pre>
3318@Override
3319public void start(BundleContext context) throws Exception {
3320 /* ... */
3321 TmfAnalysisManager.registerParameterProvider("my.lttng.kernel.analysis.id", MyLttngKernelParameterProvider.class)
3322}
3323</pre>
3324
3325where '''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.
3326
b1de2f7d
GM
3327== Providing requirements to analyses ==
3328
3329=== Analysis requirement provider API ===
3330
3331A 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).
3332
3333=== Requirement values ===
3334
3335When 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()'''.
3336
3337Moreover, 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.
3338
3339=== Example of providing requirements ===
3340
3341In 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.
3342
3343<pre>
3344@Override
3345public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() {
3346 Set<TmfAnalysisRequirement> requirements = new HashSet<>();
3347
3348 /* Create requirements of type 'event' and 'domain' */
3349 TmfAnalysisRequirement eventRequirement = new TmfAnalysisRequirement("event");
3350 TmfAnalysisRequirement domainRequirement = new TmfAnalysisRequirement("domain");
3351
3352 /* Add the values */
3353 domainRequirement.addValue("kernel", TmfAnalysisRequirement.ValuePriorityLevel.MANDATORY);
3354 eventRequirement.addValue("sched_switch", TmfAnalysisRequirement.ValuePriorityLevel.MANDATORY);
3355 eventRequirement.addValue("sched_wakeup", TmfAnalysisRequirement.ValuePriorityLevel.OPTIONAL);
3356
3357 /* An information about the events */
3358 eventRequirement.addInformation("The event sched_wakeup is optional because it's not properly handled by this analysis yet.");
3359
3360 /* Add them to the set */
3361 requirements.add(domainRequirement);
3362 requirements.add(eventRequirement);
3363
3364 return requirements;
3365}
3366</pre>
3367
3368
42f1f820
GB
3369== TODO ==
3370
3371Here's a list of features not yet implemented that would improve the analysis module user experience:
3372
3373* Implement help using the Eclipse Help facility (without forgetting an eventual command line request)
3374* 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.
3375* 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.
3376* Improve the user experience with the analysis:
3377** Allow the user to select which analyses should be available, per trace or per project.
3378** Allow the user to view all available analyses even though he has no imported traces.
3379** 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.
3380** Give the user a visual status of the analysis: not executed, in progress, completed, error.
3381** Give a small screenshot of the output as icon for it.
3382** Allow to specify parameter values from the GUI.
b1de2f7d
GM
3383* Add the possibility for an analysis requirement to be composed of another requirement.
3384* Generate a trace session from analysis requirements.
a59835d4
GB
3385
3386
3387= Performance Tests =
3388
3389Performance 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.
3390
3391For automatic performance metric computation, we use the ''org.eclipse.test.performance'' plugin, provided by the Eclipse Test Feature.
3392
3393== Add performance tests ==
3394
3395=== Where ===
3396
3397Performance 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.
3398
3399Tests 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.
3400
3401When 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
3402
3403=== How ===
3404
3405TMF 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.
3406
3407Here is an example of how to use the test framework in a performance test:
3408
3409<pre>
3410public class AnalysisBenchmark {
3411
3412 private static final String TEST_ID = "org.eclipse.linuxtools#LTTng kernel analysis";
3413 private static final CtfTmfTestTrace testTrace = CtfTmfTestTrace.TRACE2;
3414 private static final int LOOP_COUNT = 10;
3415
3416 /**
3417 * Performance test
3418 */
3419 @Test
3420 public void testTrace() {
3421 assumeTrue(testTrace.exists());
3422
3423 /** Create a new performance meter for this scenario */
3424 Performance perf = Performance.getDefault();
3425 PerformanceMeter pm = perf.createPerformanceMeter(TEST_ID);
3426
3427 /** Optionally, tag this test for summary or global summary on a given dimension */
3428 perf.tagAsSummary(pm, "LTTng Kernel Analysis", Dimension.CPU_TIME);
3429 perf.tagAsGlobalSummary(pm, "LTTng Kernel Analysis", Dimension.CPU_TIME);
3430
3431 /** The test will be run LOOP_COUNT times */
3432 for (int i = 0; i < LOOP_COUNT; i++) {
3433
3434 /** Start each run of the test with new objects to avoid different code paths */
3435 try (IAnalysisModule module = new LttngKernelAnalysisModule();
3436 LttngKernelTrace trace = new LttngKernelTrace()) {
3437 module.setId("test");
3438 trace.initTrace(null, testTrace.getPath(), CtfTmfEvent.class);
3439 module.setTrace(trace);
3440
3441 /** The analysis execution is being tested, so performance metrics
3442 * are taken before and after the execution */
3443 pm.start();
3444 TmfTestHelper.executeAnalysis(module);
3445 pm.stop();
3446
3447 /*
3448 * Delete the supplementary files, so next iteration rebuilds
3449 * the state system.
3450 */
3451 File suppDir = new File(TmfTraceManager.getSupplementaryFileDir(trace));
3452 for (File file : suppDir.listFiles()) {
3453 file.delete();
3454 }
3455
3456 } catch (TmfAnalysisException | TmfTraceException e) {
3457 fail(e.getMessage());
3458 }
3459 }
3460
3461 /** Once the test has been run many times, committing the results will
3462 * calculate average, standard deviation, and, if configured, save the
3463 * data to a database */
3464 pm.commit();
3465 }
3466}
3467
3468</pre>
3469
3470For more information, see [http://wiki.eclipse.org/Performance/Automated_Tests The Eclipse Performance Test How-to]
3471
3b8ab983 3472Some rules to help write performance tests are explained in section [[#ABC of performance testing | ABC of performance testing]].
a59835d4
GB
3473
3474=== Run a performance test ===
3475
3476Performance 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''.
3477
3478By default, if no database has been configured, results will be displayed in the Console at the end of the test.
3479
3480Here is the sample output from the test described in the previous section. It shows all the metrics that have been calculated during the test.
3481
3482<pre>
3483Scenario 'org.eclipse.linuxtools#LTTng kernel analysis' (average over 10 samples):
3484 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)
3485 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)
3486 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)
3487 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)
3488 Kernel time: 621ms (95% in [586ms, 655ms]) Measurable effect: 60ms (1.3 SDs) (required sample size for an effect of 5% of mean: 39)
3489 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)
3490 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)
3491 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)
3492 Text Size: 0 (95% in [0, 0])
3493 Data Size: 0 (95% in [0, 0])
3494 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)
3495</pre>
3496
3497Results 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.
3498
3499Note 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''.
3500
3501To 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.
3502
3503In the ''Arguments'' tab, in the box under ''VM Arguments'', add on separate lines the following information
3504
3505<pre>
3506-Declipse.perf.dbloc=//javaderby.dorsal.polymtl.ca
3507-Declipse.perf.config=build=mybuild;host=myhost;config=linux;jvm=1.7
3508</pre>
3509
3510The ''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.
3511
3512The ''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.
3513
3514== ABC of performance testing ==
3515
3516Here follow some rules to help design good and meaningful performance tests.
3517
3518=== Determine what to test ===
3519
3520For 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.
3521
3522For 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.
3523
3524The 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.
3525
3526Before 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.
3527
3528=== Metrics descriptions and considerations ===
3529
3530CPU 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.
3531
3532System 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.
3533
3534Kernel time: Time spent in kernel mode
3535
e7e04cb1 3536Used 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
3537
3538= Network Tracing =
3539
3540== Adding a protocol ==
3541
3542Supporting 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.
3543
3544=== Architecture ===
3545
3546All the TMF pcap-related code is divided in three projects (not considering the tests plugins):
3547* '''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.
3548* '''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.
3549* '''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.
3550
3551=== UDP Packet Structure ===
3552
3553The 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]:
3554
3555{| class="wikitable" style="margin: 0 auto; text-align: center;"
3556|-
3557! style="border-bottom:none; border-right:none;"| ''Offsets''
3558! style="border-left:none;"| Octet
3559! colspan="8" | 0
3560! colspan="8" | 1
3561! colspan="8" | 2
3562! colspan="8" | 3
3563|-
3564! style="border-top: none" | Octet
3565! <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>
3566|-
3567! 0
3568!<tt> 0</tt>
3569| colspan="16" style="background:#fdd;"| Source port || colspan="16"| Destination port
3570|-
3571! 4
3572!<tt>32</tt>
3573| colspan="16"| Length || colspan="16" style="background:#fdd;"| Checksum
3574|}
3575
3576Knowing that, we can define an UDPPacket class that contains those fields.
3577
3578=== Creating the UDPPacket ===
3579
3580First, 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.
3581
3582In 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:
3583* ''Packet'' '''fChildPacket''', which is the packet encapsulated by this UDP packet, if it exists. This field will be initialized by findChildPacket().
3584* ''ByteBuffer'' '''fPayload''', which is the payload of this packet. Basically, it is the UDP packet without its header.
3585* ''int'' '''fSourcePort''', which is an unsigned 16-bits field, that contains the source port of the packet (see packet structure).
3586* ''int'' '''fDestinationPort''', which is an unsigned 16-bits field, that contains the destination port of the packet (see packet structure).
3587* ''int'' '''fTotalLength''', which is an unsigned 16-bits field, that contains the total length (header + payload) of the packet.
3588* ''int'' '''fChecksum''', which is an unsigned 16-bits field, that contains a checksum to verify the integrity of the data.
3589* ''UDPEndpoint'' '''fSourceEndpoint''', which contains the source endpoint of the UDPPacket. The UDPEndpoint class will be created later in this tutorial.
3590* ''UDPEndpoint'' '''fDestinationEndpoint''', which contains the destination endpoint of the UDPPacket.
3591* ''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.
3592
3593We also create the UDPPacket(PcapFile file, @Nullable Packet parent, ByteBuffer packet) constructor. The parameters are:
3594* ''PcapFile'' '''file''', which is the pcap file to which this packet belongs.
3595* ''Packet'' '''parent''', which is the packet encasulating this UDPPacket
3596* ''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.
3597
3598The following class is obtained:
3599
3600<pre>
3601package org.eclipse.linuxtools.pcap.core.protocol.udp;
3602
3603import java.nio.ByteBuffer;
3604import java.util.Map;
3605
93d1d135
AM
3606import org.eclipse.linuxtools.internal.pcap.core.endpoint.ProtocolEndpoint;
3607import org.eclipse.linuxtools.internal.pcap.core.packet.BadPacketException;
3608import org.eclipse.linuxtools.internal.pcap.core.packet.Packet;
2c20bbb3
VP
3609
3610public class UDPPacket extends Packet {
3611
3612 private final @Nullable Packet fChildPacket;
3613 private final @Nullable ByteBuffer fPayload;
3614
3615 private final int fSourcePort;
3616 private final int fDestinationPort;
3617 private final int fTotalLength;
3618 private final int fChecksum;
3619
3620 private @Nullable UDPEndpoint fSourceEndpoint;
3621 private @Nullable UDPEndpoint fDestinationEndpoint;
3622
3623 private @Nullable ImmutableMap<String, String> fFields;
3624
3625 /**
3626 * Constructor of the UDP Packet class.
3627 *
3628 * @param file
3629 * The file that contains this packet.
3630 * @param parent
3631 * The parent packet of this packet (the encapsulating packet).
3632 * @param packet
3633 * The entire packet (header and payload).
3634 * @throws BadPacketException
3635 * Thrown when the packet is erroneous.
3636 */
3637 public UDPPacket(PcapFile file, @Nullable Packet parent, ByteBuffer packet) throws BadPacketException {
3638 super(file, parent, Protocol.UDP);
3639 // TODO Auto-generated constructor stub
3640 }
3641
3642
3643 @Override
3644 public Packet getChildPacket() {
3645 // TODO Auto-generated method stub
3646 return null;
3647 }
3648
3649 @Override
3650 public ByteBuffer getPayload() {
3651 // TODO Auto-generated method stub
3652 return null;
3653 }
3654
3655 @Override
3656 public boolean validate() {
3657 // TODO Auto-generated method stub
3658 return false;
3659 }
3660
3661 @Override
3662 protected Packet findChildPacket() throws BadPacketException {
3663 // TODO Auto-generated method stub
3664 return null;
3665 }
3666
3667 @Override
3668 public ProtocolEndpoint getSourceEndpoint() {
3669 // TODO Auto-generated method stub
3670 return null;
3671 }
3672
3673 @Override
3674 public ProtocolEndpoint getDestinationEndpoint() {
3675 // TODO Auto-generated method stub
3676 return null;
3677 }
3678
3679 @Override
3680 public Map<String, String> getFields() {
3681 // TODO Auto-generated method stub
3682 return null;
3683 }
3684
3685 @Override
3686 public String getLocalSummaryString() {
3687 // TODO Auto-generated method stub
3688 return null;
3689 }
3690
3691 @Override
3692 protected String getSignificationString() {
3693 // TODO Auto-generated method stub
3694 return null;
3695 }
3696
3697 @Override
3698 public boolean equals(Object obj) {
3699 // TODO Auto-generated method stub
3700 return false;
3701 }
3702
3703 @Override
3704 public int hashCode() {
3705 // TODO Auto-generated method stub
3706 return 0;
3707 }
3708
3709}
3710</pre>
3711
3712Now, we implement the constructor. It is done in four steps:
3713* We initialize fSourceEndpoint, fDestinationEndpoint and fFields to null, since those are lazy-loaded. This allows faster construction of the packet and thus faster parsing.
3714* 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.
3715* 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.
3716* We initialize the field fChildPacket using the method findChildPacket()
3717
3718The following constructor is obtained:
3719<pre>
3720 public UDPPacket(PcapFile file, @Nullable Packet parent, ByteBuffer packet) throws BadPacketException {
3721 super(file, parent, Protocol.UDP);
3722
3723 // The endpoints and fFields are lazy loaded. They are defined in the get*Endpoint()
3724 // methods.
3725 fSourceEndpoint = null;
3726 fDestinationEndpoint = null;
3727 fFields = null;
3728
3729 // Initialize the fields from the ByteBuffer
3730 packet.order(ByteOrder.BIG_ENDIAN);
3731 packet.position(0);
3732
3733 fSourcePort = ConversionHelper.unsignedShortToInt(packet.getShort());
3734 fDestinationPort = ConversionHelper.unsignedShortToInt(packet.getShort());
3735 fTotalLength = ConversionHelper.unsignedShortToInt(packet.getShort());
3736 fChecksum = ConversionHelper.unsignedShortToInt(packet.getShort());
3737
3738 // Initialize the payload
3739 if (packet.array().length - packet.position() > 0) {
3740 byte[] array = new byte[packet.array().length - packet.position()];
3741 packet.get(array);
3742
3743 ByteBuffer payload = ByteBuffer.wrap(array);
3744 payload.order(ByteOrder.BIG_ENDIAN);
3745 payload.position(0);
3746 fPayload = payload;
3747 } else {
3748 fPayload = null;
3749 }
3750
3751 // Find child
3752 fChildPacket = findChildPacket();
3753
3754 }
3755</pre>
3756
3757Then, we implement the following methods:
3758* ''public Packet'' '''getChildPacket()''': simple getter of fChildPacket
3759* ''public ByteBuffer'' '''getPayload()''': simple getter of fPayload
3760* ''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.
3761* ''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.
3762* ''public ProtocolEndpoint'' '''getSourceEndpoint()''': method that initializes and returns the source endpoint.
3763* ''public ProtocolEndpoint'' '''getDestinationEndpoint()''': method that initializes and returns the destination endpoint.
3764* ''public Map<String, String>'' '''getFields()''': method that initializes and returns the map containing the fields matched to their value.
3765* ''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.
3766* ''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().
3767* public boolean'' '''equals(Object obj)''': Object's equals method.
3768* public int'' '''hashCode()''': Object's hashCode method.
3769
3770We get the following code:
3771<pre>
3772 @Override
3773 public @Nullable Packet getChildPacket() {
3774 return fChildPacket;
3775 }
3776
3777 @Override
3778 public @Nullable ByteBuffer getPayload() {
3779 return fPayload;
3780 }
3781
3782 /**
3783 * Getter method that returns the UDP Source Port.
3784 *
3785 * @return The source Port.
3786 */
3787 public int getSourcePort() {
3788 return fSourcePort;
3789 }
3790
3791 /**
3792 * Getter method that returns the UDP Destination Port.
3793 *
3794 * @return The destination Port.
3795 */
3796 public int getDestinationPort() {
3797 return fDestinationPort;
3798 }
3799
3800 /**
3801 * {@inheritDoc}
3802 *
3803 * See http://www.iana.org/assignments/service-names-port-numbers/service-
3804 * names-port-numbers.xhtml or
3805 * http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
3806 */
3807 @Override
3808 protected @Nullable Packet findChildPacket() throws BadPacketException {
3809 // When more protocols are implemented, we can simply do a switch on the fDestinationPort field to find the child packet.
3810 // For instance, if the destination port is 80, then chances are the HTTP protocol is encapsulated. We can create a new HTTP
3811 // packet (after some verification that it is indeed the HTTP protocol).
3812 ByteBuffer payload = fPayload;
3813 if (payload == null) {
3814 return null;
3815 }
3816
3817 return new UnknownPacket(getPcapFile(), this, payload);
3818 }
3819
3820 @Override
3821 public boolean validate() {
3822 // Not yet implemented. ATM, we consider that all packets are valid.
3823 // TODO Implement it. We can compute the real checksum and compare it to fChecksum.
3824 return true;
3825 }
3826
3827 @Override
3828 public UDPEndpoint getSourceEndpoint() {
3829 @Nullable
3830 UDPEndpoint endpoint = fSourceEndpoint;
3831 if (endpoint == null) {
3832 endpoint = new UDPEndpoint(this, true);
3833 }
3834 fSourceEndpoint = endpoint;
3835 return fSourceEndpoint;
3836 }
3837
3838 @Override
3839 public UDPEndpoint getDestinationEndpoint() {
3840 @Nullable UDPEndpoint endpoint = fDestinationEndpoint;
3841 if (endpoint == null) {
3842 endpoint = new UDPEndpoint(this, false);
3843 }
3844 fDestinationEndpoint = endpoint;
3845 return fDestinationEndpoint;
3846 }
3847
3848 @Override
3849 public Map<String, String> getFields() {
3850 ImmutableMap<String, String> map = fFields;
3851 if (map == null) {
3852 @SuppressWarnings("null")
3853 @NonNull ImmutableMap<String, String> newMap = ImmutableMap.<String, String> builder()
3854 .put("Source Port", String.valueOf(fSourcePort)) //$NON-NLS-1$
3855 .put("Destination Port", String.valueOf(fDestinationPort)) //$NON-NLS-1$
3856 .put("Length", String.valueOf(fTotalLength) + " bytes") //$NON-NLS-1$ //$NON-NLS-2$
3857 .put("Checksum", String.format("%s%04x", "0x", fChecksum)) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
3858 .build();
3859 fFields = newMap;
3860 return newMap;
3861 }
3862 return map;
3863 }
3864
3865 @Override
3866 public String getLocalSummaryString() {
3867 return "Src Port: " + fSourcePort + ", Dst Port: " + fDestinationPort; //$NON-NLS-1$ //$NON-NLS-2$
3868 }
3869
3870 @Override
3871 protected String getSignificationString() {
3872 return "Source Port: " + fSourcePort + ", Destination Port: " + fDestinationPort; //$NON-NLS-1$ //$NON-NLS-2$
3873 }
3874
3875 @Override
3876 public int hashCode() {
3877 final int prime = 31;
3878 int result = 1;
3879 result = prime * result + fChecksum;
3880 final Packet child = fChildPacket;
3881 if (child != null) {
3882 result = prime * result + child.hashCode();
3883 } else {
3884 result = prime * result;
3885 }
3886 result = prime * result + fDestinationPort;
3887 final ByteBuffer payload = fPayload;
3888 if (payload != null) {
3889 result = prime * result + payload.hashCode();
3890 } else {
3891 result = prime * result;
3892 }
3893 result = prime * result + fSourcePort;
3894 result = prime * result + fTotalLength;
3895 return result;
3896 }
3897
3898 @Override
3899 public boolean equals(@Nullable Object obj) {
3900 if (this == obj) {
3901 return true;
3902 }
3903 if (obj == null) {
3904 return false;
3905 }
3906 if (getClass() != obj.getClass()) {
3907 return false;
3908 }
3909 UDPPacket other = (UDPPacket) obj;
3910 if (fChecksum != other.fChecksum) {
3911 return false;
3912 }
3913 final Packet child = fChildPacket;
3914 if (child != null) {
3915 if (!child.equals(other.fChildPacket)) {
3916 return false;
3917 }
3918 } else {
3919 if (other.fChildPacket != null) {
3920 return false;
3921 }
3922 }
3923 if (fDestinationPort != other.fDestinationPort) {
3924 return false;
3925 }
3926 final ByteBuffer payload = fPayload;
3927 if (payload != null) {
3928 if (!payload.equals(other.fPayload)) {
3929 return false;
3930 }
3931 } else {
3932 if (other.fPayload != null) {
3933 return false;
3934 }
3935 }
3936 if (fSourcePort != other.fSourcePort) {
3937 return false;
3938 }
3939 if (fTotalLength != other.fTotalLength) {
3940 return false;
3941 }
3942 return true;
3943 }
3944</pre>
3945
3946The UDPPacket class is implemented. We now have the define the UDPEndpoint.
3947
3948=== Creating the UDPEndpoint ===
3949
3950For 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.
3951
3952We 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):
3953* ''Packet'' '''packet''': the packet to build the endpoint from.
3954* ''boolean'' '''isSourceEndpoint''': whether the endpoint is the source endpoint or destination endpoint.
3955
3956We obtain the following unimplemented class:
3957
3958<pre>
3959package org.eclipse.linuxtools.pcap.core.protocol.udp;
3960
93d1d135
AM
3961import org.eclipse.linuxtools.internal.pcap.core.endpoint.ProtocolEndpoint;
3962import org.eclipse.linuxtools.internal.pcap.core.packet.Packet;
2c20bbb3
VP
3963
3964public class UDPEndpoint extends ProtocolEndpoint {
3965
3966 private final int fPort;
3967
3968 public UDPEndpoint(Packet packet, boolean isSourceEndpoint) {
3969 super(packet, isSourceEndpoint);
3970 // TODO Auto-generated constructor stub
3971 }
3972
3973 @Override
3974 public int hashCode() {
3975 // TODO Auto-generated method stub
3976 return 0;
3977 }
3978
3979 @Override
3980 public boolean equals(Object obj) {
3981 // TODO Auto-generated method stub
3982 return false;
3983 }
3984
3985 @Override
3986 public String toString() {
3987 // TODO Auto-generated method stub
3988 return null;
3989 }
3990
3991}
3992</pre>
3993
3994For the constructor, we simply initialize fPort. If isSourceEndpoint is true, then we take packet.getSourcePort(), else we take packet.getDestinationPort().
3995
3996<pre>
3997 /**
3998 * Constructor of the {@link UDPEndpoint} class. It takes a packet to get
3999 * its endpoint. Since every packet has two endpoints (source and
4000 * destination), the isSourceEndpoint parameter is used to specify which
4001 * endpoint to take.
4002 *
4003 * @param packet
4004 * The packet that contains the endpoints.
4005 * @param isSourceEndpoint
4006 * Whether to take the source or the destination endpoint of the
4007 * packet.
4008 */
4009 public UDPEndpoint(UDPPacket packet, boolean isSourceEndpoint) {
4010 super(packet, isSourceEndpoint);
4011 fPort = isSourceEndpoint ? packet.getSourcePort() : packet.getDestinationPort();
4012 }
4013</pre>
4014
4015Then we implement the methods:
4016* ''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().
4017* ''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().
4018* ''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.
4019
4020<pre>
4021 @Override
4022 public int hashCode() {
4023 final int prime = 31;
4024 int result = 1;
4025 ProtocolEndpoint endpoint = getParentEndpoint();
4026 if (endpoint == null) {
4027 result = 0;
4028 } else {
4029 result = endpoint.hashCode();
4030 }
4031 result = prime * result + fPort;
4032 return result;
4033 }
4034
4035 @Override
4036 public boolean equals(@Nullable Object obj) {
4037 if (this == obj) {
4038 return true;
4039 }
4040 if (!(obj instanceof UDPEndpoint)) {
4041 return false;
4042 }
4043
4044 UDPEndpoint other = (UDPEndpoint) obj;
4045
4046 // Check on layer
4047 boolean localEquals = (fPort == other.fPort);
4048 if (!localEquals) {
4049 return false;
4050 }
4051
4052 // Check above layers.
4053 ProtocolEndpoint endpoint = getParentEndpoint();
4054 if (endpoint != null) {
4055 return endpoint.equals(other.getParentEndpoint());
4056 }
4057 return true;
4058 }
4059
4060 @Override
4061 public String toString() {
4062 ProtocolEndpoint endpoint = getParentEndpoint();
4063 if (endpoint == null) {
4064 @SuppressWarnings("null")
4065 @NonNull String ret = String.valueOf(fPort);
4066 return ret;
4067 }
4068 return endpoint.toString() + '/' + fPort;
4069 }
4070</pre>
4071
4072=== Registering the UDP protocol ===
4073
7a0ecb40 4074The 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.PcapProtocol. Simply add the protocol name here, along with a few arguments:
2c20bbb3
VP
4075* ''String'' '''longname''', which is the long version of name of the protocol. In our case, it is "User Datagram Protocol".
4076* ''String'' '''shortName''', which is the shortened name of the protocol. In our case, it is "UDP".
7a0ecb40 4077* ''Layer'' '''layer''', which is the layer to which the protocol belongs in the OSI model. In our case, this is the layer 4.
2c20bbb3
VP
4078* ''boolean'' '''supportsStream''', which defines whether or not the protocol supports packet streams. In our case, this is set to true.
4079
7a0ecb40 4080Thus, the following line is added in the PcapProtocol enum:
2c20bbb3 4081<pre>
7a0ecb40 4082 UDP("User Datagram Protocol", "udp", Layer.LAYER_4, true),
2c20bbb3
VP
4083</pre>
4084
7a0ecb40 4085Also, TMF has to know about the new protocol. This is defined in org.eclipse.linuxtools.tmf.pcap.core.protocol.TmfPcapProtocol. We simply add it, with a reference to the corresponding protocol in PcapProtocol. Thus, the following line is added in the TmfPcapProtocol enum:
2c20bbb3 4086<pre>
7a0ecb40 4087 UDP(PcapProtocol.UDP),
2c20bbb3
VP
4088</pre>
4089
87e8cb47
MK
4090You will also have to update the ''ProtocolConversion'' class to register the protocol in the switch statements. Thus, for UDP, we add:
4091<pre>
4092 case UDP:
7a0ecb40 4093 return TmfPcapProtocol.UDP;
87e8cb47
MK
4094</pre>
4095and
4096<pre>
4097 case UDP:
7a0ecb40 4098 return PcapProtocol.UDP;
87e8cb47
MK
4099</pre>
4100
2c20bbb3
VP
4101Finally, 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:
4102<pre>
4103 @Override
4104 protected @Nullable Packet findChildPacket() throws BadPacketException {
4105 ByteBuffer payload = fPayload;
4106 if (payload == null) {
4107 return null;
4108 }
4109
4110 switch (fIpDatagramProtocol) {
4111 case IPProtocolNumberHelper.PROTOCOL_NUMBER_TCP:
4112 return new TCPPacket(getPcapFile(), this, payload);
4113 case IPProtocolNumberHelper.PROTOCOL_NUMBER_UDP:
4114 return new UDPPacket(getPcapFile(), this, payload);
4115 default:
4116 return new UnknownPacket(getPcapFile(), this, payload);
4117 }
4118 }
4119</pre>
4120
4121The new protocol has been added. Running TMF should work just fine, and the new protocol is now recognized.
4122
4123== Adding stream-based views ==
4124
4125To 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/.
4126
4127== TODO ==
4128
4129* 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.
4130* 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!
4131* 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.
4132* 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.
4133* Control dumpcap directly from eclipse, similar to how LTTng is controlled in the Control View.
4134* Support pcapng. See: http://www.winpcap.org/ntar/draft/PCAP-DumpFileFormat.html for the file format.
4135* Add SWTBOT tests to org.eclipse.linuxtools.tmf.pcap.ui
4136* Add a Raw Viewer, similar to Wireshark. We could use the “Show Raw” in the event editor to do that.
c3181353 4137* 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.260224 seconds and 5 git commands to generate.