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