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