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