1 /*******************************************************************************
2 * Copyright (c) 2012, 2016 Ericsson, École Polytechnique de Montréal and others.
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * Patrick Tasse - Initial API and implementation
11 * Geneviève Bastien - Move code to provide base classes for time graph view
12 * Christian Mansky - Add check active / uncheck inactive buttons
13 * Mahdi Zolnouri & Samuel Gagnon - Add flat / hierarchical button
14 *******************************************************************************/
16 package org
.eclipse
.tracecompass
.internal
.analysis
.os
.linux
.ui
.views
.controlflow
;
18 import java
.util
.ArrayList
;
19 import java
.util
.Collection
;
20 import java
.util
.Collections
;
21 import java
.util
.Comparator
;
22 import java
.util
.HashMap
;
23 import java
.util
.HashSet
;
24 import java
.util
.LinkedHashMap
;
25 import java
.util
.List
;
28 import java
.util
.function
.Function
;
29 import java
.util
.function
.Predicate
;
30 import java
.util
.stream
.Collectors
;
31 import java
.util
.stream
.Stream
;
33 import org
.eclipse
.core
.runtime
.IProgressMonitor
;
34 import org
.eclipse
.core
.runtime
.IStatus
;
35 import org
.eclipse
.core
.runtime
.Status
;
36 import org
.eclipse
.core
.runtime
.jobs
.ISchedulingRule
;
37 import org
.eclipse
.core
.runtime
.jobs
.Job
;
38 import org
.eclipse
.jdt
.annotation
.NonNull
;
39 import org
.eclipse
.jdt
.annotation
.Nullable
;
40 import org
.eclipse
.jface
.action
.Action
;
41 import org
.eclipse
.jface
.action
.IAction
;
42 import org
.eclipse
.jface
.action
.IMenuManager
;
43 import org
.eclipse
.jface
.action
.IToolBarManager
;
44 import org
.eclipse
.jface
.action
.MenuManager
;
45 import org
.eclipse
.jface
.action
.Separator
;
46 import org
.eclipse
.jface
.dialogs
.IDialogSettings
;
47 import org
.eclipse
.jface
.viewers
.ISelection
;
48 import org
.eclipse
.jface
.viewers
.StructuredSelection
;
49 import org
.eclipse
.swt
.widgets
.Composite
;
50 import org
.eclipse
.swt
.widgets
.Event
;
51 import org
.eclipse
.tracecompass
.analysis
.os
.linux
.core
.kernel
.KernelAnalysisModule
;
52 import org
.eclipse
.tracecompass
.analysis
.os
.linux
.core
.kernel
.KernelTidAspect
;
53 import org
.eclipse
.tracecompass
.common
.core
.StreamUtils
.StreamFlattener
;
54 import org
.eclipse
.tracecompass
.internal
.analysis
.os
.linux
.core
.kernel
.Attributes
;
55 import org
.eclipse
.tracecompass
.internal
.analysis
.os
.linux
.ui
.Activator
;
56 import org
.eclipse
.tracecompass
.internal
.analysis
.os
.linux
.ui
.Messages
;
57 import org
.eclipse
.tracecompass
.internal
.analysis
.os
.linux
.ui
.actions
.FollowThreadAction
;
58 import org
.eclipse
.tracecompass
.statesystem
.core
.ITmfStateSystem
;
59 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.AttributeNotFoundException
;
60 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.StateSystemDisposedException
;
61 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.StateValueTypeException
;
62 import org
.eclipse
.tracecompass
.statesystem
.core
.exceptions
.TimeRangeException
;
63 import org
.eclipse
.tracecompass
.statesystem
.core
.interval
.ITmfStateInterval
;
64 import org
.eclipse
.tracecompass
.statesystem
.core
.statevalue
.ITmfStateValue
;
65 import org
.eclipse
.tracecompass
.tmf
.core
.event
.ITmfEvent
;
66 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSelectionRangeUpdatedSignal
;
67 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalHandler
;
68 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfSignalManager
;
69 import org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceSelectedSignal
;
70 import org
.eclipse
.tracecompass
.tmf
.core
.statesystem
.TmfStateSystemAnalysisModule
;
71 import org
.eclipse
.tracecompass
.tmf
.core
.timestamp
.TmfTimestamp
;
72 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfContext
;
73 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.ITmfTrace
;
74 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceManager
;
75 import org
.eclipse
.tracecompass
.tmf
.core
.trace
.TmfTraceUtils
;
76 import org
.eclipse
.tracecompass
.tmf
.core
.util
.Pair
;
77 import org
.eclipse
.tracecompass
.tmf
.ui
.views
.timegraph
.AbstractStateSystemTimeGraphView
;
78 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.ILinkEvent
;
79 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.ITimeEvent
;
80 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.ITimeGraphEntry
;
81 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.NullTimeEvent
;
82 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.TimeEvent
;
83 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.TimeGraphEntry
;
84 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.model
.TimeLinkEvent
;
85 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.widgets
.TimeGraphControl
;
86 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.widgets
.Utils
;
87 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.widgets
.Utils
.Resolution
;
88 import org
.eclipse
.tracecompass
.tmf
.ui
.widgets
.timegraph
.widgets
.Utils
.TimeFormat
;
90 import com
.google
.common
.collect
.ImmutableList
;
93 * The Control Flow view main object
96 public class ControlFlowView
extends AbstractStateSystemTimeGraphView
{
98 // ------------------------------------------------------------------------
100 // ------------------------------------------------------------------------
104 public static final String ID
= "org.eclipse.tracecompass.analysis.os.linux.views.controlflow"; //$NON-NLS-1$
106 private static final String ICONS_PATH
= "icons/"; //$NON-NLS-1$
107 private static final String OPTIMIZE_ICON
= ICONS_PATH
+ "elcl16/Optimization.png"; //$NON-NLS-1$
109 private static final String PROCESS_COLUMN
= Messages
.ControlFlowView_processColumn
;
110 private static final String TID_COLUMN
= Messages
.ControlFlowView_tidColumn
;
111 private static final String PTID_COLUMN
= Messages
.ControlFlowView_ptidColumn
;
112 private static final String BIRTH_TIME_COLUMN
= Messages
.ControlFlowView_birthTimeColumn
;
113 private static final String INVISIBLE_COLUMN
= Messages
.ControlFlowView_invisibleColumn
;
114 private Action fOptimizationAction
;
116 private static final String NEXT_EVENT_ICON_PATH
= "icons/elcl16/shift_r_edit.gif"; //$NON-NLS-1$
117 private static final String PREV_EVENT_ICON_PATH
= "icons/elcl16/shift_l_edit.gif"; //$NON-NLS-1$
119 private static final String
[] COLUMN_NAMES
= new String
[] {
126 private static final String
[] FILTER_COLUMN_NAMES
= new String
[] {
131 // Timeout between updates in the build thread in ms
132 private static final long BUILD_UPDATE_TIMEOUT
= 500;
134 private static final Comparator
<ITimeGraphEntry
>[] COLUMN_COMPARATORS
;
136 private final Function
<Collection
<ILinkEvent
>, Map
<Integer
, Long
>> UPDATE_SCHEDULING_COLUMN_ALGO
= new OptimizationAlgorithm();
138 private static final int INITIAL_SORT_COLUMN_INDEX
= 3;
141 ImmutableList
.Builder
<Comparator
<ITimeGraphEntry
>> builder
= ImmutableList
.builder();
142 builder
.add(ControlFlowColumnComparators
.PROCESS_NAME_COLUMN_COMPARATOR
)
143 .add(ControlFlowColumnComparators
.TID_COLUMN_COMPARATOR
)
144 .add(ControlFlowColumnComparators
.PTID_COLUMN_COMPARATOR
)
145 .add(ControlFlowColumnComparators
.BIRTH_TIME_COLUMN_COMPARATOR
);
146 List
<Comparator
<ITimeGraphEntry
>> l
= builder
.build();
147 COLUMN_COMPARATORS
= l
.toArray(new Comparator
[l
.size()]);
151 * Mutex rule for search action jobs, making sure they execute sequentially
153 private final ISchedulingRule fSearchActionMutexRule
= new ISchedulingRule() {
155 public boolean isConflicting(ISchedulingRule rule
) {
156 return (rule
== this);
160 public boolean contains(ISchedulingRule rule
) {
161 return (rule
== this);
165 private final Set
<ITmfTrace
> fFlatTraces
= new HashSet
<>();
167 private IAction fFlatAction
;
169 private IAction fHierarchicalAction
;
171 // ------------------------------------------------------------------------
173 // ------------------------------------------------------------------------
178 public ControlFlowView() {
179 super(ID
, new ControlFlowPresentationProvider());
180 setTreeColumns(COLUMN_NAMES
, COLUMN_COMPARATORS
, INITIAL_SORT_COLUMN_INDEX
);
181 setTreeLabelProvider(new ControlFlowTreeLabelProvider());
182 setFilterColumns(FILTER_COLUMN_NAMES
);
183 setFilterLabelProvider(new ControlFlowFilterLabelProvider());
184 setEntryComparator(ControlFlowColumnComparators
.BIRTH_TIME_COLUMN_COMPARATOR
);
188 public void createPartControl(Composite parent
) {
189 super.createPartControl(parent
);
190 // add "Check active" Button to TimeGraphFilterDialog
191 super.getTimeGraphCombo().addTimeGraphFilterCheckActiveButton(
192 new ControlFlowCheckActiveProvider(Messages
.ControlFlowView_checkActiveLabel
, Messages
.ControlFlowView_checkActiveToolTip
));
193 // add "Uncheck inactive" Button to TimeGraphFilterDialog
194 super.getTimeGraphCombo().addTimeGraphFilterUncheckInactiveButton(
195 new ControlFlowCheckActiveProvider(Messages
.ControlFlowView_uncheckInactiveLabel
, Messages
.ControlFlowView_uncheckInactiveToolTip
));
202 protected void fillTimeGraphEntryContextMenu(@NonNull IMenuManager menuManager
) {
203 ISelection selection
= getSite().getSelectionProvider().getSelection();
204 if (selection
instanceof StructuredSelection
) {
205 StructuredSelection sSel
= (StructuredSelection
) selection
;
206 if (sSel
.getFirstElement() instanceof ControlFlowEntry
) {
207 ControlFlowEntry entry
= (ControlFlowEntry
) sSel
.getFirstElement();
208 menuManager
.add(new FollowThreadAction(ControlFlowView
.this, entry
.getName(), entry
.getThreadId(), entry
.getTrace()));
214 protected void fillLocalToolBar(IToolBarManager manager
) {
215 // add "Optimization" Button to local tool bar of Controlflow
216 IAction optimizationAction
= getOptimizationAction();
217 manager
.add(optimizationAction
);
219 // add a separator to local tool bar
220 manager
.add(new Separator());
222 super.fillLocalToolBar(manager
);
223 IDialogSettings settings
= Activator
.getDefault().getDialogSettings();
224 IDialogSettings section
= settings
.getSection(getClass().getName());
225 if (section
== null) {
226 section
= settings
.addNewSection(getClass().getName());
229 IAction hideArrowsAction
= getTimeGraphCombo().getTimeGraphViewer().getHideArrowsAction(section
);
230 manager
.add(hideArrowsAction
);
232 IAction followArrowBwdAction
= getTimeGraphCombo().getTimeGraphViewer().getFollowArrowBwdAction();
233 followArrowBwdAction
.setText(Messages
.ControlFlowView_followCPUBwdText
);
234 followArrowBwdAction
.setToolTipText(Messages
.ControlFlowView_followCPUBwdText
);
235 manager
.add(followArrowBwdAction
);
237 IAction followArrowFwdAction
= getTimeGraphCombo().getTimeGraphViewer().getFollowArrowFwdAction();
238 followArrowFwdAction
.setText(Messages
.ControlFlowView_followCPUFwdText
);
239 followArrowFwdAction
.setToolTipText(Messages
.ControlFlowView_followCPUFwdText
);
240 manager
.add(followArrowFwdAction
);
242 IAction previousEventAction
= new SearchEventAction(false, PackageMessages
.ControlFlowView_PreviousEventJobName
);
243 previousEventAction
.setText(PackageMessages
.ControlFlowView_PreviousEventActionName
);
244 previousEventAction
.setToolTipText(PackageMessages
.ControlFlowView_PreviousEventActionTooltip
);
245 previousEventAction
.setImageDescriptor(Activator
.getDefault().getImageDescripterFromPath(PREV_EVENT_ICON_PATH
));
246 manager
.add(previousEventAction
);
248 IAction nextEventAction
= new SearchEventAction(true, PackageMessages
.ControlFlowView_NextEventJobName
);
249 nextEventAction
.setText(PackageMessages
.ControlFlowView_NextEventActionName
);
250 nextEventAction
.setToolTipText(PackageMessages
.ControlFlowView_NextEventActionTooltip
);
251 nextEventAction
.setImageDescriptor(Activator
.getDefault().getImageDescripterFromPath(NEXT_EVENT_ICON_PATH
));
252 manager
.add(nextEventAction
);
255 private IAction
getOptimizationAction() {
256 if (fOptimizationAction
== null) {
257 fOptimizationAction
= new OptimizationAction();
258 fOptimizationAction
.setImageDescriptor(Activator
.getDefault().getImageDescripterFromPath(OPTIMIZE_ICON
));
259 fOptimizationAction
.setText(Messages
.ControlFlowView_optimizeLabel
);
260 fOptimizationAction
.setToolTipText(Messages
.ControlFlowView_optimizeToolTip
);
262 return fOptimizationAction
;
266 protected void fillLocalMenu(IMenuManager manager
) {
267 super.fillLocalMenu(manager
);
268 final MenuManager item
= new MenuManager(Messages
.ControlFlowView_threadPresentation
);
269 fFlatAction
= createFlatAction();
270 item
.add(fFlatAction
);
272 fHierarchicalAction
= createHierarchicalAction();
273 item
.add(fHierarchicalAction
);
279 * Base Action for the "Go to Next/Previous Event for thread" actions
281 private class SearchEventAction
extends Action
{
283 private final boolean ifDirection
;
284 private final String ifJobName
;
290 * The direction of the search, "true" for forwards and
291 * "false" for backwards.
293 * The name of the job that will be spawned
295 public SearchEventAction(boolean direction
, String jobName
) {
296 ifDirection
= direction
;
302 Job job
= new Job(ifJobName
) {
304 protected IStatus
run(IProgressMonitor monitor
) {
305 TimeGraphControl ctrl
= getTimeGraphViewer().getTimeGraphControl();
306 ITimeGraphEntry traceEntry
= ctrl
.getSelectedTrace();
308 long ts
= getTimeGraphViewer().getSelectionBegin();
309 ITimeEvent selectedState
= Utils
.findEvent(traceEntry
, ts
, 0);
311 if (selectedState
== null) {
312 /* No selection currently in the view, do nothing */
313 return Status
.OK_STATUS
;
315 ITimeGraphEntry entry
= selectedState
.getEntry();
316 if (!(entry
instanceof ControlFlowEntry
)) {
317 return Status
.OK_STATUS
;
319 ControlFlowEntry cfEntry
= (ControlFlowEntry
) entry
;
320 int tid
= cfEntry
.getThreadId();
322 ITmfTrace trace
= cfEntry
.getTrace();
323 ITmfContext ctx
= trace
.seekEvent(TmfTimestamp
.fromNanos(ts
));
324 long rank
= ctx
.getRank();
327 Predicate
<@NonNull ITmfEvent
> predicate
= event
-> {
329 * TODO Specific to the Control Flow View and kernel
330 * traces for now. Could be eventually generalized to
331 * anything represented by the time graph row.
333 Integer eventTid
= KernelTidAspect
.INSTANCE
.resolve(event
);
334 return (eventTid
!= null && eventTid
.intValue() == tid
);
337 ITmfEvent event
= (ifDirection ?
338 TmfTraceUtils
.getNextEventMatching(cfEntry
.getTrace(), rank
, predicate
, monitor
) :
339 TmfTraceUtils
.getPreviousEventMatching(cfEntry
.getTrace(), rank
, predicate
, monitor
));
341 TmfSignalManager
.dispatchSignal(new TmfSelectionRangeUpdatedSignal(this, event
.getTimestamp()));
343 return Status
.OK_STATUS
;
348 * Make subsequent jobs not run concurrently, but wait after one
351 job
.setRule(fSearchActionMutexRule
);
356 private IAction
createHierarchicalAction() {
357 IAction action
= new Action(Messages
.ControlFlowView_hierarchicalViewLabel
, IAction
.AS_RADIO_BUTTON
) {
360 ITmfTrace parentTrace
= getTrace();
361 synchronized (fFlatTraces
) {
362 fFlatTraces
.remove(parentTrace
);
363 for (ITmfTrace trace
: TmfTraceManager
.getTraceSet(parentTrace
)) {
364 final ITmfStateSystem ss
= TmfStateSystemAnalysisModule
.getStateSystem(trace
, KernelAnalysisModule
.ID
);
365 for (TimeGraphEntry traceEntry
: getEntryList(ss
)) {
366 List
<ControlFlowEntry
> currentRootList
= traceEntry
.getChildren().stream()
367 .filter(e
-> e
instanceof ControlFlowEntry
)
368 .map(e
-> (ControlFlowEntry
) e
)
369 .collect(Collectors
.toList());
370 addEntriesToHierarchicalTree(currentRootList
, traceEntry
);
377 action
.setChecked(true);
378 action
.setToolTipText(Messages
.ControlFlowView_hierarchicalViewToolTip
);
382 private IAction
createFlatAction() {
383 IAction action
= new Action(Messages
.ControlFlowView_flatViewLabel
, IAction
.AS_RADIO_BUTTON
) {
386 ITmfTrace parentTrace
= getTrace();
387 synchronized (fFlatTraces
) {
388 fFlatTraces
.add(parentTrace
);
389 for (ITmfTrace trace
: TmfTraceManager
.getTraceSet(parentTrace
)) {
390 final ITmfStateSystem ss
= TmfStateSystemAnalysisModule
.getStateSystem(trace
, KernelAnalysisModule
.ID
);
391 for (TimeGraphEntry traceEntry
: getEntryList(ss
)) {
392 hierarchicalToFlatTree(traceEntry
);
399 action
.setToolTipText(Messages
.ControlFlowView_flatViewToolTip
);
404 protected String
getNextText() {
405 return Messages
.ControlFlowView_nextProcessActionNameText
;
409 protected String
getNextTooltip() {
410 return Messages
.ControlFlowView_nextProcessActionToolTipText
;
414 protected String
getPrevText() {
415 return Messages
.ControlFlowView_previousProcessActionNameText
;
419 protected String
getPrevTooltip() {
420 return Messages
.ControlFlowView_previousProcessActionToolTipText
;
424 * Get the optimization function for the scheduling column. In the base
425 * implementation, this optimizes by Line arrows, but can be overidden.
427 * It takes a collection of link events, looking at the entries being
428 * linked, and returns a list of the proposed order. The list of indexes
429 * should be in ascending order. There can be duplicates, but the values and
430 * order should always be the same for the same input.
432 * @return the returned column order, where the integer is the tid of the
433 * entry, and the return value is the position, there can be
436 public Function
<Collection
<ILinkEvent
>, Map
<Integer
, Long
>> getUpdatedSchedulingColumn() {
437 return UPDATE_SCHEDULING_COLUMN_ALGO
;
441 * This is an optimization action used to find cliques of entries due to
442 * links and put them closer together
444 * @author Samuel Gagnon
446 private final class OptimizationAction
extends Action
{
449 public void runWithEvent(Event event
) {
450 ITmfTrace trace
= getTrace();
455 createFlatAction().run();
458 * This method only returns the arrows in the current time interval
459 * [a,b] of ControlFlowView. Thus, we only optimize for that time
462 List
<ILinkEvent
> arrows
= getTimeGraphViewer().getTimeGraphControl().getArrows();
463 final ITmfStateSystem ss
= TmfStateSystemAnalysisModule
.getStateSystem(trace
, KernelAnalysisModule
.ID
);
464 List
<TimeGraphEntry
> currentList
= getEntryList(ss
);
466 Map
<Integer
, Long
> orderedTidMap
= getUpdatedSchedulingColumn().apply(arrows
);
469 * Now that we have our list of ordered tid, it's time to assign a
470 * position for each threads in the view. For this, we assign a
471 * value to an invisible column and sort according to the values in
474 for (TimeGraphEntry entry
: currentList
) {
475 if (entry
instanceof TraceEntry
) {
476 for (TimeGraphEntry child
: ((TraceEntry
) entry
).getChildren()) {
477 if (child
instanceof ControlFlowEntry
) {
478 ControlFlowEntry cEntry
= (ControlFlowEntry
) child
;
480 * If the thread is in our list, we give it a
481 * position. Otherwise, it means there's no activity
482 * in the current interval for that thread. We set
483 * its position to Long.MAX_VALUE so it goes to the
486 cEntry
.setSchedulingPosition(orderedTidMap
.getOrDefault(cEntry
.getThreadId(), Long
.MAX_VALUE
));
492 setEntryComparator(ControlFlowColumnComparators
.SCHEDULING_COLUMN_COMPARATOR
);
499 * Optimization algorithm, overridable.
501 * @author Matthew Khouzam
502 * @author Samuel Gagnon
504 public static class OptimizationAlgorithm
implements Function
<Collection
<ILinkEvent
>, Map
<Integer
, Long
>> {
507 * Get the scheduling column order by arrows
510 * the list of visible links
511 * @return the list of weights, by thread ID
514 public Map
<Integer
, Long
> apply(Collection
<ILinkEvent
> arrows
) {
516 * "transitions" contains the count of every arrows between two tids
517 * (Pair<Integer, Integer>). For constructing the Pair, we always
518 * put the smallest tid first
520 Map
<Pair
<Integer
, Integer
>, Integer
> transitions
= new HashMap
<>();
523 * We iterate in arrows to count the number of transitions between
524 * every pair (tid,tid) in the current view
526 for (ILinkEvent arrow
: arrows
) {
527 ITimeGraphEntry from
= arrow
.getEntry();
528 ITimeGraphEntry to
= arrow
.getDestinationEntry();
529 if (!(from
instanceof ControlFlowEntry
) || !(to
instanceof ControlFlowEntry
)) {
532 int fromTid
= ((ControlFlowEntry
) from
).getThreadId();
533 int toTid
= ((ControlFlowEntry
) to
).getThreadId();
534 if (fromTid
!= toTid
) {
535 Pair
<Integer
, Integer
> key
= new Pair
<>(Math
.min(fromTid
, toTid
), Math
.max(fromTid
, toTid
));
536 Integer count
= transitions
.getOrDefault(key
, 0);
537 transitions
.put(key
, count
+ 1);
542 * We now have a transition count for every pair (tid,tid). The next
543 * step is to sort every pair according to its count in decreasing
546 List
<Pair
<Integer
, Integer
>> sortedTransitionsByCount
= transitions
.entrySet().stream().sorted(Map
.Entry
.<Pair
<Integer
, Integer
>, Integer
> comparingByValue().reversed()).map(Map
.Entry
::getKey
).collect(Collectors
.toList());
549 * Next, we find the order in which we want to display our threads.
550 * We simply iterate in every pair (tid,tid) in orderedTidList. Each
551 * time we see a new tid, we add it at the end of orderedTidList.
552 * This way, threads with lots of transitions will be grouped in the
553 * top. While very naive, this algorithm is fast, simple and gives
556 Map
<Integer
, Long
> orderedTidMap
= new LinkedHashMap
<>();
558 for (Pair
<Integer
, Integer
> threadPair
: sortedTransitionsByCount
) {
559 if (orderedTidMap
.get(threadPair
.getFirst()) == null) {
560 orderedTidMap
.put(threadPair
.getFirst(), pos
);
563 if (orderedTidMap
.get(threadPair
.getSecond()) == null) {
564 orderedTidMap
.put(threadPair
.getSecond(), pos
);
569 return orderedTidMap
;
577 protected static class ControlFlowTreeLabelProvider
extends TreeLabelProvider
{
580 public String
getColumnText(Object element
, int columnIndex
) {
581 if (element
instanceof TraceEntry
) {
582 if (columnIndex
== 0) {
583 return ((TraceEntry
) element
).getName();
585 return ""; //$NON-NLS-1$
587 ControlFlowEntry entry
= (ControlFlowEntry
) element
;
589 if (COLUMN_NAMES
[columnIndex
].equals(Messages
.ControlFlowView_processColumn
)) {
590 return entry
.getName();
591 } else if (COLUMN_NAMES
[columnIndex
].equals(Messages
.ControlFlowView_tidColumn
)) {
592 return Integer
.toString(entry
.getThreadId());
593 } else if (COLUMN_NAMES
[columnIndex
].equals(Messages
.ControlFlowView_ptidColumn
)) {
594 if (entry
.getParentThreadId() > 0) {
595 return Integer
.toString(entry
.getParentThreadId());
597 } else if (COLUMN_NAMES
[columnIndex
].equals(Messages
.ControlFlowView_birthTimeColumn
)) {
598 return Utils
.formatTime(entry
.getStartTime(), TimeFormat
.CALENDAR
, Resolution
.NANOSEC
);
599 } else if (COLUMN_NAMES
[columnIndex
].equals(Messages
.ControlFlowView_traceColumn
)) {
600 return entry
.getTrace().getName();
601 } else if (COLUMN_NAMES
[columnIndex
].equals(INVISIBLE_COLUMN
)) {
602 return Long
.toString(entry
.getSchedulingPosition());
604 return ""; //$NON-NLS-1$
609 private static class ControlFlowFilterLabelProvider
extends TreeLabelProvider
{
612 public String
getColumnText(Object element
, int columnIndex
) {
613 if (element
instanceof TraceEntry
) {
614 if (columnIndex
== 0) {
615 return ((TraceEntry
) element
).getName();
617 return ""; //$NON-NLS-1$
619 ControlFlowEntry entry
= (ControlFlowEntry
) element
;
621 if (columnIndex
== 0) {
622 return entry
.getName();
623 } else if (columnIndex
== 1) {
624 return Integer
.toString(entry
.getThreadId());
626 return ""; //$NON-NLS-1$
631 private static class TraceEntry
extends TimeGraphEntry
{
633 public TraceEntry(String name
, long startTime
, long endTime
) {
634 super(name
, startTime
, endTime
);
638 public boolean hasTimeEvents() {
645 public void traceClosed(org
.eclipse
.tracecompass
.tmf
.core
.signal
.TmfTraceClosedSignal signal
) {
646 super.traceClosed(signal
);
647 synchronized (fFlatTraces
) {
648 fFlatTraces
.remove(signal
.getTrace());
654 public void traceSelected(TmfTraceSelectedSignal signal
) {
655 super.traceSelected(signal
);
656 synchronized (fFlatTraces
) {
657 if (fFlatTraces
.contains(signal
.getTrace())) {
658 fHierarchicalAction
.setChecked(false);
659 fFlatAction
.setChecked(true);
661 fFlatAction
.setChecked(false);
662 fHierarchicalAction
.setChecked(true);
667 // ------------------------------------------------------------------------
669 // ------------------------------------------------------------------------
672 protected void buildEntryList(final ITmfTrace trace
, final ITmfTrace parentTrace
, final IProgressMonitor monitor
) {
673 final ITmfStateSystem ssq
= TmfStateSystemAnalysisModule
.getStateSystem(trace
, KernelAnalysisModule
.ID
);
678 final List
<ControlFlowEntry
> entryList
= new ArrayList
<>();
679 /** Map of trace entries */
680 Map
<ITmfTrace
, TraceEntry
> traceEntryMap
= new HashMap
<>();
681 /** Map of control flow entries, key is a pair [threadId, cpuId] */
682 final Map
<Pair
<Integer
, Integer
>, ControlFlowEntry
> entryMap
= new HashMap
<>();
684 long start
= ssq
.getStartTime();
685 setStartTime(Math
.min(getStartTime(), start
));
687 boolean complete
= false;
689 if (monitor
.isCanceled()) {
692 complete
= ssq
.waitUntilBuilt(BUILD_UPDATE_TIMEOUT
);
693 if (ssq
.isCancelled()) {
696 long end
= ssq
.getCurrentEndTime();
697 if (start
== end
&& !complete
) { // when complete execute one last time regardless of end time
701 TraceEntry aTraceEntry
= traceEntryMap
.get(trace
);
702 if (aTraceEntry
== null) {
703 aTraceEntry
= new TraceEntry(trace
.getName(), start
, end
+ 1);
704 traceEntryMap
.put(trace
, aTraceEntry
);
705 addToEntryList(parentTrace
, ssq
, Collections
.singletonList(aTraceEntry
));
707 aTraceEntry
.updateEndTime(end
+ 1);
709 final TraceEntry traceEntry
= aTraceEntry
;
711 final long resolution
= Math
.max(1, (end
- ssq
.getStartTime()) / getDisplayWidth());
712 setEndTime(Math
.max(getEndTime(), end
+ 1));
713 final List
<Integer
> threadQuarks
= ssq
.getQuarks(Attributes
.THREADS
, "*"); //$NON-NLS-1$
714 queryFullStates(ssq
, start
, end
, resolution
, monitor
, new IQueryHandler() {
716 public void handle(List
<List
<ITmfStateInterval
>> fullStates
, List
<ITmfStateInterval
> prevFullState
) {
717 for (int threadQuark
: threadQuarks
) {
718 String threadAttributeName
= ssq
.getAttributeName(threadQuark
);
720 Pair
<Integer
, Integer
> entryKey
= Attributes
.parseThreadAttributeName(threadAttributeName
);
721 int threadId
= entryKey
.getFirst();
723 if (threadId
< 0) { // ignore the 'unknown' (-1) thread
730 execNameQuark
= ssq
.getQuarkRelative(threadQuark
, Attributes
.EXEC_NAME
);
731 ppidQuark
= ssq
.getQuarkRelative(threadQuark
, Attributes
.PPID
);
732 } catch (AttributeNotFoundException e
) {
733 /* No information on this thread (yet?), skip it for now */
736 ITmfStateInterval lastExecNameInterval
= prevFullState
== null || execNameQuark
>= prevFullState
.size() ?
null : prevFullState
.get(execNameQuark
);
737 long lastExecNameStartTime
= lastExecNameInterval
== null ?
-1 : lastExecNameInterval
.getStartTime();
738 long lastExecNameEndTime
= lastExecNameInterval
== null ?
-1 : lastExecNameInterval
.getEndTime() + 1;
739 long lastPpidStartTime
= prevFullState
== null || ppidQuark
>= prevFullState
.size() ?
-1 : prevFullState
.get(ppidQuark
).getStartTime();
740 for (List
<ITmfStateInterval
> fullState
: fullStates
) {
741 if (monitor
.isCanceled()) {
744 if (execNameQuark
>= fullState
.size() || ppidQuark
>= fullState
.size()) {
745 /* No information on this thread (yet?), skip it for now */
748 ITmfStateInterval execNameInterval
= fullState
.get(execNameQuark
);
749 ITmfStateInterval ppidInterval
= fullState
.get(ppidQuark
);
750 long startTime
= execNameInterval
.getStartTime();
751 long endTime
= execNameInterval
.getEndTime() + 1;
752 if (startTime
== lastExecNameStartTime
&& ppidInterval
.getStartTime() == lastPpidStartTime
) {
755 boolean isNull
= execNameInterval
.getStateValue().isNull();
756 if (isNull
&& lastExecNameEndTime
< startTime
&& lastExecNameEndTime
!= -1) {
758 * There was a non-null interval in between the
759 * full states, try to use it.
762 execNameInterval
= ssq
.querySingleState(startTime
- 1, execNameQuark
);
763 ppidInterval
= ssq
.querySingleState(startTime
- 1, ppidQuark
);
764 startTime
= execNameInterval
.getStartTime();
765 endTime
= execNameInterval
.getEndTime() + 1;
766 } catch (StateSystemDisposedException e
) {
770 if (!execNameInterval
.getStateValue().isNull() &&
771 execNameInterval
.getStateValue().getType() == ITmfStateValue
.Type
.STRING
) {
772 String execName
= execNameInterval
.getStateValue().unboxStr();
773 int ppid
= ppidInterval
.getStateValue().unboxInt();
774 ControlFlowEntry entry
= entryMap
.get(entryKey
);
776 entry
= new ControlFlowEntry(threadQuark
, trace
, execName
, threadId
, ppid
, startTime
, endTime
);
777 entryList
.add(entry
);
778 entryMap
.put(entryKey
, entry
);
781 * Update the name of the entry to the
782 * latest execName and the parent thread id
783 * to the latest ppid.
785 entry
.setName(execName
);
786 entry
.setParentThreadId(ppid
);
787 entry
.updateEndTime(endTime
);
791 entryMap
.remove(entryKey
);
793 lastExecNameStartTime
= startTime
;
794 lastExecNameEndTime
= endTime
;
795 lastPpidStartTime
= ppidInterval
.getStartTime();
798 synchronized (fFlatTraces
) {
799 if (fFlatTraces
.contains(parentTrace
)) {
800 addEntriesToFlatTree(entryList
, traceEntry
);
802 addEntriesToHierarchicalTree(entryList
, traceEntry
);
808 queryFullStates(ssq
, ssq
.getStartTime(), end
, resolution
, monitor
, new IQueryHandler() {
810 public void handle(@NonNull List
<List
<ITmfStateInterval
>> fullStates
, @Nullable List
<ITmfStateInterval
> prevFullState
) {
811 for (final TimeGraphEntry entry
: traceEntry
.getChildren()) {
812 if (monitor
.isCanceled()) {
815 buildStatusEvents(trace
, parentTrace
, ssq
, fullStates
, prevFullState
, (ControlFlowEntry
) entry
, monitor
, ssq
.getStartTime(), end
);
820 if (parentTrace
.equals(getTrace())) {
829 * Add entries to the traces's child list in a flat fashion (no hierarchy).
830 * If one entry has children, we do a depth first search to add each child
831 * to the trace's child list and update the parent and child relations.
833 private static void hierarchicalToFlatTree(TimeGraphEntry traceEntry
) {
834 List
<@NonNull TimeGraphEntry
> rootList
= traceEntry
.getChildren();
835 // We visit the children of every entry to add
836 StreamFlattener
<TimeGraphEntry
> sf
= new StreamFlattener
<>(entry
-> entry
.getChildren().stream());
837 Stream
<TimeGraphEntry
> allEntries
= rootList
.stream().flatMap(entry
-> sf
.flatten(entry
));
839 // We add every entry that is missing from the trace's entry list
840 List
<@NonNull TimeGraphEntry
> rootListToAdd
= allEntries
841 .filter(entry
-> !rootList
.contains(entry
))
842 .collect(Collectors
.toList());
843 rootList
.forEach(entry
-> {
844 entry
.clearChildren();
846 rootListToAdd
.forEach(entry
-> {
847 traceEntry
.addChild(entry
);
848 entry
.clearChildren();
853 * Add entries to the traces's child list in a flat fashion (no hierarchy).
855 private static void addEntriesToFlatTree(List
<@NonNull ControlFlowEntry
> entryList
, TimeGraphEntry traceEntry
) {
856 List
<TimeGraphEntry
> rootList
= traceEntry
.getChildren();
857 for (ControlFlowEntry entry
: entryList
) {
858 if (!rootList
.contains(entry
)) {
859 traceEntry
.addChild(entry
);
865 * Add entries to the trace's child list in a hierarchical fashion.
867 private static void addEntriesToHierarchicalTree(List
<ControlFlowEntry
> entryList
, TimeGraphEntry traceEntry
) {
868 List
<TimeGraphEntry
> rootList
= traceEntry
.getChildren();
870 for (ControlFlowEntry entry
: entryList
) {
871 boolean root
= (entry
.getParent() == null || entry
.getParent() == traceEntry
);
872 if (root
&& entry
.getParentThreadId() > 0) {
873 for (ControlFlowEntry parent
: entryList
) {
875 * Associate the parent entry only if their time overlap. A
876 * child entry may start before its parent, for example at
877 * the beginning of the trace if a parent has not yet
878 * appeared in the state system. We just want to make sure
879 * that the entry didn't start after the parent ended or
880 * ended before the parent started.
882 if (parent
.getThreadId() == entry
.getParentThreadId() &&
883 !(entry
.getStartTime() > parent
.getEndTime() ||
884 entry
.getEndTime() < parent
.getStartTime())) {
885 parent
.addChild(entry
);
887 if (rootList
.contains(entry
)) {
888 traceEntry
.removeChild(entry
);
894 if (root
&& (!rootList
.contains(entry
))) {
895 traceEntry
.addChild(entry
);
900 private void buildStatusEvents(ITmfTrace trace
, ITmfTrace parentTrace
, ITmfStateSystem ss
, @NonNull List
<List
<ITmfStateInterval
>> fullStates
,
901 @Nullable List
<ITmfStateInterval
> prevFullState
, ControlFlowEntry entry
, @NonNull IProgressMonitor monitor
, long start
, long end
) {
902 if (start
< entry
.getEndTime() && end
> entry
.getStartTime()) {
903 List
<ITimeEvent
> eventList
= getEventList(entry
, ss
, fullStates
, prevFullState
, monitor
);
904 if (eventList
== null) {
907 /* Start a new event list on first iteration, then append to it */
908 if (prevFullState
== null) {
909 entry
.setEventList(eventList
);
911 for (ITimeEvent event
: eventList
) {
912 entry
.addEvent(event
);
915 if (parentTrace
.equals(getTrace())) {
919 for (ITimeGraphEntry child
: entry
.getChildren()) {
920 if (monitor
.isCanceled()) {
923 buildStatusEvents(trace
, parentTrace
, ss
, fullStates
, prevFullState
, (ControlFlowEntry
) child
, monitor
, start
, end
);
928 protected @Nullable List
<ITimeEvent
> getEventList(@NonNull TimeGraphEntry tgentry
, ITmfStateSystem ss
,
929 @NonNull List
<List
<ITmfStateInterval
>> fullStates
, @Nullable List
<ITmfStateInterval
> prevFullState
, @NonNull IProgressMonitor monitor
) {
930 List
<ITimeEvent
> eventList
= null;
931 if (!(tgentry
instanceof ControlFlowEntry
)) {
934 ControlFlowEntry entry
= (ControlFlowEntry
) tgentry
;
936 int threadQuark
= entry
.getThreadQuark();
937 int statusQuark
= ss
.getQuarkRelative(threadQuark
, Attributes
.STATUS
);
938 eventList
= new ArrayList
<>(fullStates
.size());
939 ITmfStateInterval lastInterval
= prevFullState
== null || statusQuark
>= prevFullState
.size() ?
null : prevFullState
.get(statusQuark
);
940 long lastStartTime
= lastInterval
== null ?
-1 : lastInterval
.getStartTime();
941 long lastEndTime
= lastInterval
== null ?
-1 : lastInterval
.getEndTime() + 1;
942 for (List
<ITmfStateInterval
> fullState
: fullStates
) {
943 if (monitor
.isCanceled()) {
946 if (statusQuark
>= fullState
.size()) {
947 /* No information on this thread (yet?), skip it for now */
950 ITmfStateInterval statusInterval
= fullState
.get(statusQuark
);
951 long time
= statusInterval
.getStartTime();
952 if (time
== lastStartTime
) {
955 long duration
= statusInterval
.getEndTime() - time
+ 1;
958 status
= statusInterval
.getStateValue().unboxInt();
959 } catch (StateValueTypeException e
) {
960 Activator
.getDefault().logError(e
.getMessage());
962 if (lastEndTime
!= time
&& lastEndTime
!= -1) {
963 eventList
.add(new TimeEvent(entry
, lastEndTime
, time
- lastEndTime
));
965 if (!statusInterval
.getStateValue().isNull()) {
966 eventList
.add(new TimeEvent(entry
, time
, duration
, status
));
968 eventList
.add(new NullTimeEvent(entry
, time
, duration
));
970 lastStartTime
= time
;
971 lastEndTime
= time
+ duration
;
973 } catch (AttributeNotFoundException
| TimeRangeException e
) {
974 Activator
.getDefault().logError(e
.getMessage());
980 * Returns a value corresponding to the selected entry.
982 * Used in conjunction with synchingToTime to change the selected entry. If
983 * one of these methods is overridden in child class, then both should be.
986 * The currently selected time
987 * @return a value identifying the entry
989 private int getSelectionValue(long time
) {
991 for (ITmfTrace trace
: TmfTraceManager
.getTraceSet(getTrace())) {
995 ITmfStateSystem ssq
= TmfStateSystemAnalysisModule
.getStateSystem(trace
, KernelAnalysisModule
.ID
);
999 if (time
>= ssq
.getStartTime() && time
<= ssq
.getCurrentEndTime()) {
1000 List
<Integer
> currentThreadQuarks
= ssq
.getQuarks(Attributes
.CPUS
, "*", Attributes
.CURRENT_THREAD
); //$NON-NLS-1$
1001 for (int currentThreadQuark
: currentThreadQuarks
) {
1003 ITmfStateInterval currentThreadInterval
= ssq
.querySingleState(time
, currentThreadQuark
);
1004 int currentThread
= currentThreadInterval
.getStateValue().unboxInt();
1005 if (currentThread
> 0) {
1006 int statusQuark
= ssq
.getQuarkAbsolute(Attributes
.THREADS
, Integer
.toString(currentThread
), Attributes
.STATUS
);
1007 ITmfStateInterval statusInterval
= ssq
.querySingleState(time
, statusQuark
);
1008 if (statusInterval
.getStartTime() == time
) {
1009 thread
= currentThread
;
1013 } catch (AttributeNotFoundException
| TimeRangeException
| StateValueTypeException e
) {
1014 Activator
.getDefault().logError(e
.getMessage());
1015 } catch (StateSystemDisposedException e
) {
1025 protected void synchingToTime(long time
) {
1026 int selected
= getSelectionValue(time
);
1028 for (Object element
: getTimeGraphViewer().getExpandedElements()) {
1029 if (element
instanceof ControlFlowEntry
) {
1030 ControlFlowEntry entry
= (ControlFlowEntry
) element
;
1031 if (entry
.getThreadId() == selected
) {
1032 getTimeGraphCombo().setSelection(entry
);
1041 protected @NonNull List
<ILinkEvent
> getLinkList(ITmfStateSystem ss
,
1042 @NonNull List
<List
<ITmfStateInterval
>> fullStates
, @Nullable List
<ITmfStateInterval
> prevFullState
, @NonNull IProgressMonitor monitor
) {
1043 List
<ILinkEvent
> list
= new ArrayList
<>();
1044 List
<TimeGraphEntry
> entryList
= getEntryList(ss
);
1045 if (entryList
== null) {
1048 for (ITmfTrace trace
: TmfTraceManager
.getTraceSet(getTrace())) {
1049 List
<Integer
> currentThreadQuarks
= ss
.getQuarks(Attributes
.CPUS
, "*", Attributes
.CURRENT_THREAD
); //$NON-NLS-1$
1050 for (int currentThreadQuark
: currentThreadQuarks
) {
1051 if (currentThreadQuark
>= fullStates
.get(0).size()) {
1052 /* No information on this cpu (yet?), skip it for now */
1055 List
<ITmfStateInterval
> currentThreadIntervals
= new ArrayList
<>(fullStates
.size() + 2);
1058 * Add the previous interval if it is the first query
1059 * iteration and the first interval has currentThread=0. Add
1060 * the following interval if the last interval has
1061 * currentThread=0. These are diagonal arrows crossing the
1062 * query iteration range.
1064 if (prevFullState
== null) {
1065 ITmfStateInterval currentThreadInterval
= fullStates
.get(0).get(currentThreadQuark
);
1066 if (currentThreadInterval
.getStateValue().unboxInt() == 0) {
1067 long start
= Math
.max(currentThreadInterval
.getStartTime() - 1, ss
.getStartTime());
1068 currentThreadIntervals
.add(ss
.querySingleState(start
, currentThreadQuark
));
1071 for (List
<ITmfStateInterval
> fullState
: fullStates
) {
1072 currentThreadIntervals
.add(fullState
.get(currentThreadQuark
));
1074 ITmfStateInterval currentThreadInterval
= fullStates
.get(fullStates
.size() - 1).get(currentThreadQuark
);
1075 if (currentThreadInterval
.getStateValue().unboxInt() == 0) {
1076 long end
= Math
.min(currentThreadInterval
.getEndTime() + 1, ss
.getCurrentEndTime());
1077 currentThreadIntervals
.add(ss
.querySingleState(end
, currentThreadQuark
));
1079 } catch (StateSystemDisposedException e
) {
1086 for (ITmfStateInterval currentThreadInterval
: currentThreadIntervals
) {
1087 if (monitor
.isCanceled()) {
1090 if (currentThreadInterval
.getEndTime() + 1 == lastEnd
) {
1093 long time
= currentThreadInterval
.getStartTime();
1094 if (time
!= lastEnd
) {
1095 // don't create links where there are gaps in intervals due to the resolution
1099 int thread
= currentThreadInterval
.getStateValue().unboxInt();
1100 if (thread
> 0 && prevThread
> 0) {
1101 ITimeGraphEntry prevEntry
= findEntry(entryList
, trace
, prevThread
);
1102 ITimeGraphEntry nextEntry
= findEntry(entryList
, trace
, thread
);
1103 list
.add(new TimeLinkEvent(prevEntry
, nextEntry
, prevEnd
, time
- prevEnd
, 0));
1105 lastEnd
= currentThreadInterval
.getEndTime() + 1;
1107 prevThread
= thread
;
1116 private ControlFlowEntry
findEntry(List
<TimeGraphEntry
> entryList
, ITmfTrace trace
, int threadId
) {
1117 for (TimeGraphEntry entry
: entryList
) {
1118 if (entry
instanceof ControlFlowEntry
) {
1119 ControlFlowEntry controlFlowEntry
= (ControlFlowEntry
) entry
;
1120 if (controlFlowEntry
.getThreadId() == threadId
&& controlFlowEntry
.getTrace() == trace
) {
1121 return controlFlowEntry
;
1124 if (entry
.hasChildren()) {
1125 ControlFlowEntry controlFlowEntry
= findEntry(entry
.getChildren(), trace
, threadId
);
1126 if (controlFlowEntry
!= null) {
1127 return controlFlowEntry
;