os.linux: Add Next/Previous TID event action in CFV
[deliverable/tracecompass.git] / analysis / org.eclipse.tracecompass.analysis.os.linux.ui / src / org / eclipse / tracecompass / internal / analysis / os / linux / ui / views / controlflow / ControlFlowView.java
1 /*******************************************************************************
2 * Copyright (c) 2012, 2016 Ericsson, École Polytechnique de Montréal and others.
3 *
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
8 *
9 * Contributors:
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 *******************************************************************************/
15
16 package org.eclipse.tracecompass.internal.analysis.os.linux.ui.views.controlflow;
17
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.Comparator;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.LinkedHashMap;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Set;
27 import java.util.function.Predicate;
28 import java.util.stream.Collectors;
29 import java.util.stream.Stream;
30
31 import org.eclipse.core.runtime.IProgressMonitor;
32 import org.eclipse.core.runtime.IStatus;
33 import org.eclipse.core.runtime.Status;
34 import org.eclipse.core.runtime.jobs.ISchedulingRule;
35 import org.eclipse.core.runtime.jobs.Job;
36 import org.eclipse.jdt.annotation.NonNull;
37 import org.eclipse.jdt.annotation.Nullable;
38 import org.eclipse.jface.action.Action;
39 import org.eclipse.jface.action.IAction;
40 import org.eclipse.jface.action.IMenuManager;
41 import org.eclipse.jface.action.IToolBarManager;
42 import org.eclipse.jface.action.MenuManager;
43 import org.eclipse.jface.action.Separator;
44 import org.eclipse.jface.dialogs.IDialogSettings;
45 import org.eclipse.jface.viewers.ISelection;
46 import org.eclipse.jface.viewers.StructuredSelection;
47 import org.eclipse.swt.widgets.Composite;
48 import org.eclipse.swt.widgets.Event;
49 import org.eclipse.tracecompass.analysis.os.linux.core.kernel.KernelAnalysisModule;
50 import org.eclipse.tracecompass.analysis.os.linux.core.kernel.KernelTidAspect;
51 import org.eclipse.tracecompass.common.core.StreamUtils.StreamFlattener;
52 import org.eclipse.tracecompass.internal.analysis.os.linux.core.kernel.Attributes;
53 import org.eclipse.tracecompass.internal.analysis.os.linux.ui.Activator;
54 import org.eclipse.tracecompass.internal.analysis.os.linux.ui.Messages;
55 import org.eclipse.tracecompass.internal.analysis.os.linux.ui.actions.FollowThreadAction;
56 import org.eclipse.tracecompass.statesystem.core.ITmfStateSystem;
57 import org.eclipse.tracecompass.statesystem.core.exceptions.AttributeNotFoundException;
58 import org.eclipse.tracecompass.statesystem.core.exceptions.StateSystemDisposedException;
59 import org.eclipse.tracecompass.statesystem.core.exceptions.StateValueTypeException;
60 import org.eclipse.tracecompass.statesystem.core.exceptions.TimeRangeException;
61 import org.eclipse.tracecompass.statesystem.core.interval.ITmfStateInterval;
62 import org.eclipse.tracecompass.statesystem.core.statevalue.ITmfStateValue;
63 import org.eclipse.tracecompass.tmf.core.event.ITmfEvent;
64 import org.eclipse.tracecompass.tmf.core.signal.TmfSelectionRangeUpdatedSignal;
65 import org.eclipse.tracecompass.tmf.core.signal.TmfSignalHandler;
66 import org.eclipse.tracecompass.tmf.core.signal.TmfSignalManager;
67 import org.eclipse.tracecompass.tmf.core.signal.TmfTraceSelectedSignal;
68 import org.eclipse.tracecompass.tmf.core.statesystem.TmfStateSystemAnalysisModule;
69 import org.eclipse.tracecompass.tmf.core.timestamp.TmfTimestamp;
70 import org.eclipse.tracecompass.tmf.core.trace.ITmfContext;
71 import org.eclipse.tracecompass.tmf.core.trace.ITmfTrace;
72 import org.eclipse.tracecompass.tmf.core.trace.TmfTraceManager;
73 import org.eclipse.tracecompass.tmf.core.trace.TmfTraceUtils;
74 import org.eclipse.tracecompass.tmf.core.util.Pair;
75 import org.eclipse.tracecompass.tmf.ui.views.timegraph.AbstractStateSystemTimeGraphView;
76 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.ILinkEvent;
77 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.ITimeEvent;
78 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.ITimeGraphEntry;
79 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.NullTimeEvent;
80 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.TimeEvent;
81 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.TimeGraphEntry;
82 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.TimeLinkEvent;
83 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.TimeGraphControl;
84 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.Utils;
85 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.Utils.Resolution;
86 import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.Utils.TimeFormat;
87
88 import com.google.common.collect.ImmutableList;
89
90 /**
91 * The Control Flow view main object
92 *
93 */
94 public class ControlFlowView extends AbstractStateSystemTimeGraphView {
95
96 // ------------------------------------------------------------------------
97 // Constants
98 // ------------------------------------------------------------------------
99 /**
100 * View ID.
101 */
102 public static final String ID = "org.eclipse.tracecompass.analysis.os.linux.views.controlflow"; //$NON-NLS-1$
103
104 private static final String ICONS_PATH = "icons/"; //$NON-NLS-1$
105 private static final String OPTIMIZE_ICON = ICONS_PATH + "elcl16/Optimization.png"; //$NON-NLS-1$
106
107 private static final String PROCESS_COLUMN = Messages.ControlFlowView_processColumn;
108 private static final String TID_COLUMN = Messages.ControlFlowView_tidColumn;
109 private static final String PTID_COLUMN = Messages.ControlFlowView_ptidColumn;
110 private static final String BIRTH_TIME_COLUMN = Messages.ControlFlowView_birthTimeColumn;
111 private static final String INVISIBLE_COLUMN = Messages.ControlFlowView_invisibleColumn;
112 private Action fOptimizationAction;
113
114 private static final String NEXT_EVENT_ICON_PATH = "icons/elcl16/shift_r_edit.gif"; //$NON-NLS-1$
115 private static final String PREV_EVENT_ICON_PATH = "icons/elcl16/shift_l_edit.gif"; //$NON-NLS-1$
116
117 private static final String[] COLUMN_NAMES = new String[] {
118 PROCESS_COLUMN,
119 TID_COLUMN,
120 PTID_COLUMN,
121 BIRTH_TIME_COLUMN
122 };
123
124 private static final String[] FILTER_COLUMN_NAMES = new String[] {
125 PROCESS_COLUMN,
126 TID_COLUMN
127 };
128
129 // Timeout between updates in the build thread in ms
130 private static final long BUILD_UPDATE_TIMEOUT = 500;
131
132 private static final Comparator<ITimeGraphEntry>[] COLUMN_COMPARATORS;
133
134 private static final int INITIAL_SORT_COLUMN_INDEX = 3;
135
136 static {
137 ImmutableList.Builder<Comparator<ITimeGraphEntry>> builder = ImmutableList.builder();
138 builder.add(ControlFlowColumnComparators.PROCESS_NAME_COLUMN_COMPARATOR)
139 .add(ControlFlowColumnComparators.TID_COLUMN_COMPARATOR)
140 .add(ControlFlowColumnComparators.PTID_COLUMN_COMPARATOR)
141 .add(ControlFlowColumnComparators.BIRTH_TIME_COLUMN_COMPARATOR);
142 List<Comparator<ITimeGraphEntry>> l = builder.build();
143 COLUMN_COMPARATORS = l.toArray(new Comparator[l.size()]);
144 }
145
146 /**
147 * Mutex rule for search action jobs, making sure they execute sequentially
148 */
149 private final ISchedulingRule fSearchActionMutexRule = new ISchedulingRule() {
150 @Override
151 public boolean isConflicting(ISchedulingRule rule) {
152 return (rule == this);
153 }
154 @Override
155 public boolean contains(ISchedulingRule rule) {
156 return (rule == this);
157 }
158 };
159
160 private final Set<ITmfTrace> fFlatTraces = new HashSet<>();
161
162
163 private IAction fFlatAction;
164
165 private IAction fHierarchicalAction;
166
167 // ------------------------------------------------------------------------
168 // Constructors
169 // ------------------------------------------------------------------------
170
171 /**
172 * Constructor
173 */
174 public ControlFlowView() {
175 super(ID, new ControlFlowPresentationProvider());
176 setTreeColumns(COLUMN_NAMES, COLUMN_COMPARATORS, INITIAL_SORT_COLUMN_INDEX);
177 setTreeLabelProvider(new ControlFlowTreeLabelProvider());
178 setFilterColumns(FILTER_COLUMN_NAMES);
179 setFilterLabelProvider(new ControlFlowFilterLabelProvider());
180 setEntryComparator(ControlFlowColumnComparators.BIRTH_TIME_COLUMN_COMPARATOR);
181 }
182
183 @Override
184 public void createPartControl(Composite parent) {
185 super.createPartControl(parent);
186 // add "Check active" Button to TimeGraphFilterDialog
187 super.getTimeGraphCombo().addTimeGraphFilterCheckActiveButton(
188 new ControlFlowCheckActiveProvider(Messages.ControlFlowView_checkActiveLabel, Messages.ControlFlowView_checkActiveToolTip));
189 // add "Uncheck inactive" Button to TimeGraphFilterDialog
190 super.getTimeGraphCombo().addTimeGraphFilterUncheckInactiveButton(
191 new ControlFlowCheckActiveProvider(Messages.ControlFlowView_uncheckInactiveLabel, Messages.ControlFlowView_uncheckInactiveToolTip));
192 }
193
194 /**
195 * @since 2.0
196 */
197 @Override
198 protected void fillTimeGraphEntryContextMenu(@NonNull IMenuManager menuManager) {
199 ISelection selection = getSite().getSelectionProvider().getSelection();
200 if (selection instanceof StructuredSelection) {
201 StructuredSelection sSel = (StructuredSelection) selection;
202 if (sSel.getFirstElement() instanceof ControlFlowEntry) {
203 ControlFlowEntry entry = (ControlFlowEntry) sSel.getFirstElement();
204 menuManager.add(new FollowThreadAction(ControlFlowView.this, entry.getName(), entry.getThreadId(), entry.getTrace()));
205 }
206 }
207 }
208
209 @Override
210 protected void fillLocalToolBar(IToolBarManager manager) {
211 // add "Optimization" Button to local tool bar of Controlflow
212 IAction optimizationAction = getOptimizationAction();
213 manager.add(optimizationAction);
214
215 // add a separator to local tool bar
216 manager.add(new Separator());
217
218 super.fillLocalToolBar(manager);
219 IDialogSettings settings = Activator.getDefault().getDialogSettings();
220 IDialogSettings section = settings.getSection(getClass().getName());
221 if (section == null) {
222 section = settings.addNewSection(getClass().getName());
223 }
224
225 IAction hideArrowsAction = getTimeGraphCombo().getTimeGraphViewer().getHideArrowsAction(section);
226 manager.add(hideArrowsAction);
227
228 IAction followArrowBwdAction = getTimeGraphCombo().getTimeGraphViewer().getFollowArrowBwdAction();
229 followArrowBwdAction.setText(Messages.ControlFlowView_followCPUBwdText);
230 followArrowBwdAction.setToolTipText(Messages.ControlFlowView_followCPUBwdText);
231 manager.add(followArrowBwdAction);
232
233 IAction followArrowFwdAction = getTimeGraphCombo().getTimeGraphViewer().getFollowArrowFwdAction();
234 followArrowFwdAction.setText(Messages.ControlFlowView_followCPUFwdText);
235 followArrowFwdAction.setToolTipText(Messages.ControlFlowView_followCPUFwdText);
236 manager.add(followArrowFwdAction);
237
238 IAction previousEventAction = new SearchEventAction(false, PackageMessages.ControlFlowView_PreviousEventJobName);
239 previousEventAction.setText(PackageMessages.ControlFlowView_PreviousEventActionName);
240 previousEventAction.setToolTipText(PackageMessages.ControlFlowView_PreviousEventActionTooltip);
241 previousEventAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(PREV_EVENT_ICON_PATH));
242 manager.add(previousEventAction);
243
244 IAction nextEventAction = new SearchEventAction(true, PackageMessages.ControlFlowView_NextEventJobName);
245 nextEventAction.setText(PackageMessages.ControlFlowView_NextEventActionName);
246 nextEventAction.setToolTipText(PackageMessages.ControlFlowView_NextEventActionTooltip);
247 nextEventAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(NEXT_EVENT_ICON_PATH));
248 manager.add(nextEventAction);
249 }
250
251 private IAction getOptimizationAction() {
252 if (fOptimizationAction == null) {
253 fOptimizationAction = new OptimizationAction();
254 fOptimizationAction.setImageDescriptor(Activator.getDefault().getImageDescripterFromPath(OPTIMIZE_ICON));
255 fOptimizationAction.setText(Messages.ControlFlowView_optimizeLabel);
256 fOptimizationAction.setToolTipText(Messages.ControlFlowView_optimizeToolTip);
257 }
258 return fOptimizationAction;
259 }
260
261 @Override
262 protected void fillLocalMenu(IMenuManager manager) {
263 super.fillLocalMenu(manager);
264 final MenuManager item = new MenuManager(Messages.ControlFlowView_threadPresentation);
265 fFlatAction = createFlatAction();
266 item.add(fFlatAction);
267
268 fHierarchicalAction = createHierarchicalAction();
269 item.add(fHierarchicalAction);
270 manager.add(item);
271
272 }
273
274 /**
275 * Base Action for the "Go to Next/Previous Event for thread" actions
276 */
277 private class SearchEventAction extends Action {
278
279 private final boolean ifDirection;
280 private final String ifJobName;
281
282 /**
283 * Constructor
284 *
285 * @param direction
286 * The direction of the search, "true" for forwards and
287 * "false" for backwards.
288 * @param jobName
289 * The name of the job that will be spawned
290 */
291 public SearchEventAction(boolean direction, String jobName) {
292 ifDirection = direction;
293 ifJobName = jobName;
294 }
295
296 @Override
297 public void run() {
298 Job job = new Job(ifJobName) {
299 @Override
300 protected IStatus run(IProgressMonitor monitor) {
301 TimeGraphControl ctrl = getTimeGraphViewer().getTimeGraphControl();
302 ITimeGraphEntry traceEntry = ctrl.getSelectedTrace();
303
304 long ts = getTimeGraphViewer().getSelectionBegin();
305 ITimeEvent selectedState = Utils.findEvent(traceEntry, ts, 0);
306
307 if (selectedState == null) {
308 /* No selection currently in the view, do nothing */
309 return Status.OK_STATUS;
310 }
311 ITimeGraphEntry entry = selectedState.getEntry();
312 if (!(entry instanceof ControlFlowEntry)) {
313 return Status.OK_STATUS;
314 }
315 ControlFlowEntry cfEntry = (ControlFlowEntry) entry;
316 int tid = cfEntry.getThreadId();
317
318 ITmfTrace trace = cfEntry.getTrace();
319 ITmfContext ctx = trace.seekEvent(TmfTimestamp.fromNanos(ts));
320 long rank = ctx.getRank();
321 ctx.dispose();
322
323 Predicate<@NonNull ITmfEvent> predicate = event -> {
324 /*
325 * TODO Specific to the Control Flow View and kernel
326 * traces for now. Could be eventually generalized to
327 * anything represented by the time graph row.
328 */
329 Integer eventTid = KernelTidAspect.INSTANCE.resolve(event);
330 return (eventTid != null && eventTid.intValue() == tid);
331 };
332
333 ITmfEvent event = (ifDirection ?
334 TmfTraceUtils.getNextEventMatching(cfEntry.getTrace(), rank, predicate, monitor) :
335 TmfTraceUtils.getPreviousEventMatching(cfEntry.getTrace(), rank, predicate, monitor));
336 if (event != null) {
337 TmfSignalManager.dispatchSignal(new TmfSelectionRangeUpdatedSignal(this, event.getTimestamp()));
338 }
339 return Status.OK_STATUS;
340
341 }
342 };
343 /*
344 * Make subsequent jobs not run concurrently, but wait after one
345 * another.
346 */
347 job.setRule(fSearchActionMutexRule);
348 job.schedule();
349 }
350 }
351
352 private IAction createHierarchicalAction() {
353 IAction action = new Action(Messages.ControlFlowView_hierarchicalViewLabel, IAction.AS_RADIO_BUTTON) {
354 @Override
355 public void run() {
356 ITmfTrace parentTrace = getTrace();
357 synchronized (fFlatTraces) {
358 fFlatTraces.remove(parentTrace);
359 for (ITmfTrace trace : TmfTraceManager.getTraceSet(parentTrace)) {
360 final ITmfStateSystem ss = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID);
361 for (TimeGraphEntry traceEntry : getEntryList(ss)) {
362 List<ControlFlowEntry> currentRootList = traceEntry.getChildren().stream()
363 .filter(e -> e instanceof ControlFlowEntry)
364 .map(e -> (ControlFlowEntry) e)
365 .collect(Collectors.toList());
366 addEntriesToHierarchicalTree(currentRootList, traceEntry);
367 }
368 }
369 }
370 refresh();
371 }
372 };
373 action.setChecked(true);
374 action.setToolTipText(Messages.ControlFlowView_hierarchicalViewToolTip);
375 return action;
376 }
377
378 private IAction createFlatAction() {
379 IAction action = new Action(Messages.ControlFlowView_flatViewLabel, IAction.AS_RADIO_BUTTON) {
380 @Override
381 public void run() {
382 ITmfTrace parentTrace = getTrace();
383 synchronized (fFlatTraces) {
384 fFlatTraces.add(parentTrace);
385 for (ITmfTrace trace : TmfTraceManager.getTraceSet(parentTrace)) {
386 final ITmfStateSystem ss = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID);
387 for (TimeGraphEntry traceEntry : getEntryList(ss)) {
388 hierarchicalToFlatTree(traceEntry);
389 }
390 }
391 }
392 refresh();
393 }
394 };
395 action.setToolTipText(Messages.ControlFlowView_flatViewToolTip);
396 return action;
397 }
398
399 @Override
400 protected String getNextText() {
401 return Messages.ControlFlowView_nextProcessActionNameText;
402 }
403
404 @Override
405 protected String getNextTooltip() {
406 return Messages.ControlFlowView_nextProcessActionToolTipText;
407 }
408
409 @Override
410 protected String getPrevText() {
411 return Messages.ControlFlowView_previousProcessActionNameText;
412 }
413
414 @Override
415 protected String getPrevTooltip() {
416 return Messages.ControlFlowView_previousProcessActionToolTipText;
417 }
418
419 /**
420 * This is an optimization action used to find cliques of entries due to
421 * links and put them closer together
422 *
423 * @author Samuel Gagnon
424 */
425 private final class OptimizationAction extends Action {
426 @Override
427 public void runWithEvent(Event event) {
428 ITmfTrace trace = getTrace();
429 if (trace == null) {
430 return;
431 }
432
433 createFlatAction().run();
434
435 /*
436 * "transitions" contains the count of every arrows between
437 * two tids (Pair<Integer, Integer>). For constructing the
438 * Pair, we always put the smallest tid first
439 */
440 Map<Pair<Integer, Integer>, Integer> transitions = new HashMap<>();
441
442 /*
443 * This method only returns the arrows in the current time
444 * interval [a,b] of ControlFlowView. Thus, we only optimize
445 * for that time interval
446 */
447 List<ILinkEvent> arrows = getTimeGraphViewer().getTimeGraphControl().getArrows();
448
449 /*
450 * We iterate in arrows to count the number of transitions
451 * between every pair (tid,tid) in the current view
452 */
453 for (ILinkEvent arrow : arrows) {
454 ITimeGraphEntry from = arrow.getEntry();
455 ITimeGraphEntry to = arrow.getDestinationEntry();
456 if (!(from instanceof ControlFlowEntry) || !(to instanceof ControlFlowEntry)) {
457 continue;
458 }
459 int fromTid = ((ControlFlowEntry) from).getThreadId();
460 int toTid = ((ControlFlowEntry) to).getThreadId();
461 if (fromTid != toTid) {
462 Pair<Integer, Integer> key = new Pair<>(Math.min(fromTid, toTid), Math.max(fromTid, toTid));
463 Integer count = transitions.getOrDefault(key, 0);
464 transitions.put(key, count + 1);
465 }
466 }
467
468 /*
469 * We now have a transition count for every pair (tid,tid).
470 * The next step is to sort every pair according to its
471 * count in decreasing order
472 */
473 List<Pair<Integer, Integer>> sortedTransitionsByCount = transitions.entrySet().stream().sorted(Map.Entry.<Pair<Integer, Integer>, Integer> comparingByValue().reversed()).map(Map.Entry::getKey).collect(Collectors.toList());
474
475 /*
476 * Next, we find the order in which we want to display our
477 * threads. We simply iterate in every pair (tid,tid) in
478 * orderedTidList. Each time we see a new tid, we add it at
479 * the end of orderedTidList. This way, threads with lots of
480 * transitions will be grouped in the top. While very naive,
481 * this algorithm is fast, simple and gives decent results.
482 */
483 Map<Integer, Integer> orderedTidMap = new LinkedHashMap<>();
484 int pos = 0;
485 for (Pair<Integer, Integer> threadPair : sortedTransitionsByCount) {
486 if (orderedTidMap.get(threadPair.getFirst()) == null) {
487 orderedTidMap.put(threadPair.getFirst(), pos);
488 pos++;
489 }
490 if (orderedTidMap.get(threadPair.getSecond()) == null) {
491 orderedTidMap.put(threadPair.getSecond(), pos);
492 pos++;
493 }
494 }
495
496 /*
497 * Now that we have our list of ordered tid, it's time to
498 * assign a position for each threads in the view. For this,
499 * we assign a value to an invisible column and sort
500 * according to the values in this column.
501 */
502 final ITmfStateSystem ss = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID);
503 List<TimeGraphEntry> currentList = getEntryList(ss);
504 for (TimeGraphEntry entry : currentList) {
505 if (entry instanceof TraceEntry) {
506 for (TimeGraphEntry child : ((TraceEntry) entry).getChildren()) {
507 if (child instanceof ControlFlowEntry) {
508 ControlFlowEntry cEntry = (ControlFlowEntry) child;
509 /*
510 * If the thread is in our list, we give it
511 * a position. Otherwise, it means there's
512 * no activity in the current interval for
513 * that thread. We set its position to
514 * Long.MAX_VALUE so it goes to the bottom.
515 */
516 Integer threadPos = orderedTidMap.get(cEntry.getThreadId());
517 if (threadPos != null) {
518 cEntry.setSchedulingPosition(threadPos);
519 } else {
520 cEntry.setSchedulingPosition(Long.MAX_VALUE);
521 }
522 }
523 }
524 }
525 }
526
527 setEntryComparator(ControlFlowColumnComparators.SCHEDULING_COLUMN_COMPARATOR);
528 refresh();
529 }
530 }
531
532 /**
533 * @author gbastien
534 *
535 */
536 protected static class ControlFlowTreeLabelProvider extends TreeLabelProvider {
537
538 @Override
539 public String getColumnText(Object element, int columnIndex) {
540 if (element instanceof TraceEntry) {
541 if (columnIndex == 0) {
542 return ((TraceEntry) element).getName();
543 }
544 return ""; //$NON-NLS-1$
545 }
546 ControlFlowEntry entry = (ControlFlowEntry) element;
547
548 if (COLUMN_NAMES[columnIndex].equals(Messages.ControlFlowView_processColumn)) {
549 return entry.getName();
550 } else if (COLUMN_NAMES[columnIndex].equals(Messages.ControlFlowView_tidColumn)) {
551 return Integer.toString(entry.getThreadId());
552 } else if (COLUMN_NAMES[columnIndex].equals(Messages.ControlFlowView_ptidColumn)) {
553 if (entry.getParentThreadId() > 0) {
554 return Integer.toString(entry.getParentThreadId());
555 }
556 } else if (COLUMN_NAMES[columnIndex].equals(Messages.ControlFlowView_birthTimeColumn)) {
557 return Utils.formatTime(entry.getStartTime(), TimeFormat.CALENDAR, Resolution.NANOSEC);
558 } else if (COLUMN_NAMES[columnIndex].equals(Messages.ControlFlowView_traceColumn)) {
559 return entry.getTrace().getName();
560 } else if (COLUMN_NAMES[columnIndex].equals(INVISIBLE_COLUMN)) {
561 return Long.toString(entry.getSchedulingPosition());
562 }
563 return ""; //$NON-NLS-1$
564 }
565
566 }
567
568 private static class ControlFlowFilterLabelProvider extends TreeLabelProvider {
569
570 @Override
571 public String getColumnText(Object element, int columnIndex) {
572 if (element instanceof TraceEntry) {
573 if (columnIndex == 0) {
574 return ((TraceEntry) element).getName();
575 }
576 return ""; //$NON-NLS-1$
577 }
578 ControlFlowEntry entry = (ControlFlowEntry) element;
579
580 if (columnIndex == 0) {
581 return entry.getName();
582 } else if (columnIndex == 1) {
583 return Integer.toString(entry.getThreadId());
584 }
585 return ""; //$NON-NLS-1$
586 }
587
588 }
589
590 private static class TraceEntry extends TimeGraphEntry {
591
592 public TraceEntry(String name, long startTime, long endTime) {
593 super(name, startTime, endTime);
594 }
595
596 @Override
597 public boolean hasTimeEvents() {
598 return false;
599 }
600 }
601
602 @TmfSignalHandler
603 @Override
604 public void traceClosed(org.eclipse.tracecompass.tmf.core.signal.TmfTraceClosedSignal signal) {
605 super.traceClosed(signal);
606 synchronized (fFlatTraces) {
607 fFlatTraces.remove(signal.getTrace());
608 }
609 }
610
611 @TmfSignalHandler
612 @Override
613 public void traceSelected(TmfTraceSelectedSignal signal) {
614 super.traceSelected(signal);
615 synchronized (fFlatTraces) {
616 if (fFlatTraces.contains(signal.getTrace())) {
617 fHierarchicalAction.setChecked(false);
618 fFlatAction.setChecked(true);
619 } else {
620 fFlatAction.setChecked(false);
621 fHierarchicalAction.setChecked(true);
622 }
623 }
624 }
625
626 // ------------------------------------------------------------------------
627 // Internal
628 // ------------------------------------------------------------------------
629
630 @Override
631 protected void buildEntryList(final ITmfTrace trace, final ITmfTrace parentTrace, final IProgressMonitor monitor) {
632 final ITmfStateSystem ssq = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID);
633 if (ssq == null) {
634 return;
635 }
636
637 final List<ControlFlowEntry> entryList = new ArrayList<>();
638 /** Map of trace entries */
639 Map<ITmfTrace, TraceEntry> traceEntryMap = new HashMap<>();
640 /** Map of control flow entries, key is a pair [threadId, cpuId] */
641 final Map<Pair<Integer, Integer>, ControlFlowEntry> entryMap = new HashMap<>();
642
643 long start = ssq.getStartTime();
644 setStartTime(Math.min(getStartTime(), start));
645
646 boolean complete = false;
647 while (!complete) {
648 if (monitor.isCanceled()) {
649 return;
650 }
651 complete = ssq.waitUntilBuilt(BUILD_UPDATE_TIMEOUT);
652 if (ssq.isCancelled()) {
653 return;
654 }
655 long end = ssq.getCurrentEndTime();
656 if (start == end && !complete) { // when complete execute one last time regardless of end time
657 continue;
658 }
659
660 TraceEntry aTraceEntry = traceEntryMap.get(trace);
661 if (aTraceEntry == null) {
662 aTraceEntry = new TraceEntry(trace.getName(), start, end + 1);
663 traceEntryMap.put(trace, aTraceEntry);
664 addToEntryList(parentTrace, ssq, Collections.singletonList(aTraceEntry));
665 } else {
666 aTraceEntry.updateEndTime(end + 1);
667 }
668 final TraceEntry traceEntry = aTraceEntry;
669
670 final long resolution = Math.max(1, (end - ssq.getStartTime()) / getDisplayWidth());
671 setEndTime(Math.max(getEndTime(), end + 1));
672 final List<Integer> threadQuarks = ssq.getQuarks(Attributes.THREADS, "*"); //$NON-NLS-1$
673 queryFullStates(ssq, start, end, resolution, monitor, new IQueryHandler() {
674 @Override
675 public void handle(List<List<ITmfStateInterval>> fullStates, List<ITmfStateInterval> prevFullState) {
676 for (int threadQuark : threadQuarks) {
677 String threadAttributeName = ssq.getAttributeName(threadQuark);
678
679 Pair<Integer, Integer> entryKey = Attributes.parseThreadAttributeName(threadAttributeName);
680 int threadId = entryKey.getFirst();
681
682 if (threadId < 0) { // ignore the 'unknown' (-1) thread
683 continue;
684 }
685
686 int execNameQuark;
687 int ppidQuark;
688 try {
689 execNameQuark = ssq.getQuarkRelative(threadQuark, Attributes.EXEC_NAME);
690 ppidQuark = ssq.getQuarkRelative(threadQuark, Attributes.PPID);
691 } catch (AttributeNotFoundException e) {
692 /* No information on this thread (yet?), skip it for now */
693 continue;
694 }
695 ITmfStateInterval lastExecNameInterval = prevFullState == null || execNameQuark >= prevFullState.size() ? null : prevFullState.get(execNameQuark);
696 long lastExecNameStartTime = lastExecNameInterval == null ? -1 : lastExecNameInterval.getStartTime();
697 long lastExecNameEndTime = lastExecNameInterval == null ? -1 : lastExecNameInterval.getEndTime() + 1;
698 long lastPpidStartTime = prevFullState == null || ppidQuark >= prevFullState.size() ? -1 : prevFullState.get(ppidQuark).getStartTime();
699 for (List<ITmfStateInterval> fullState : fullStates) {
700 if (monitor.isCanceled()) {
701 return;
702 }
703 if (execNameQuark >= fullState.size() || ppidQuark >= fullState.size()) {
704 /* No information on this thread (yet?), skip it for now */
705 continue;
706 }
707 ITmfStateInterval execNameInterval = fullState.get(execNameQuark);
708 ITmfStateInterval ppidInterval = fullState.get(ppidQuark);
709 long startTime = execNameInterval.getStartTime();
710 long endTime = execNameInterval.getEndTime() + 1;
711 if (startTime == lastExecNameStartTime && ppidInterval.getStartTime() == lastPpidStartTime) {
712 continue;
713 }
714 boolean isNull = execNameInterval.getStateValue().isNull();
715 if (isNull && lastExecNameEndTime < startTime && lastExecNameEndTime != -1) {
716 /*
717 * There was a non-null interval in between the
718 * full states, try to use it.
719 */
720 try {
721 execNameInterval = ssq.querySingleState(startTime - 1, execNameQuark);
722 ppidInterval = ssq.querySingleState(startTime - 1, ppidQuark);
723 startTime = execNameInterval.getStartTime();
724 endTime = execNameInterval.getEndTime() + 1;
725 } catch (StateSystemDisposedException e) {
726 /* ignored */
727 }
728 }
729 if (!execNameInterval.getStateValue().isNull() &&
730 execNameInterval.getStateValue().getType() == ITmfStateValue.Type.STRING) {
731 String execName = execNameInterval.getStateValue().unboxStr();
732 int ppid = ppidInterval.getStateValue().unboxInt();
733 ControlFlowEntry entry = entryMap.get(entryKey);
734 if (entry == null) {
735 entry = new ControlFlowEntry(threadQuark, trace, execName, threadId, ppid, startTime, endTime);
736 entryList.add(entry);
737 entryMap.put(entryKey, entry);
738 } else {
739 /*
740 * Update the name of the entry to the
741 * latest execName and the parent thread id
742 * to the latest ppid.
743 */
744 entry.setName(execName);
745 entry.setParentThreadId(ppid);
746 entry.updateEndTime(endTime);
747 }
748 }
749 if (isNull) {
750 entryMap.remove(entryKey);
751 }
752 lastExecNameStartTime = startTime;
753 lastExecNameEndTime = endTime;
754 lastPpidStartTime = ppidInterval.getStartTime();
755 }
756 }
757 synchronized (fFlatTraces) {
758 if (fFlatTraces.contains(parentTrace)) {
759 addEntriesToFlatTree(entryList, traceEntry);
760 } else {
761 addEntriesToHierarchicalTree(entryList, traceEntry);
762 }
763 }
764 }
765 });
766
767 queryFullStates(ssq, ssq.getStartTime(), end, resolution, monitor, new IQueryHandler() {
768 @Override
769 public void handle(@NonNull List<List<ITmfStateInterval>> fullStates, @Nullable List<ITmfStateInterval> prevFullState) {
770 for (final TimeGraphEntry entry : traceEntry.getChildren()) {
771 if (monitor.isCanceled()) {
772 return;
773 }
774 buildStatusEvents(trace, parentTrace, ssq, fullStates, prevFullState, (ControlFlowEntry) entry, monitor, ssq.getStartTime(), end);
775 }
776 }
777 });
778
779 if (parentTrace.equals(getTrace())) {
780 refresh();
781 }
782
783 start = end;
784 }
785 }
786
787 /**
788 * Add entries to the traces's child list in a flat fashion (no hierarchy).
789 * If one entry has children, we do a depth first search to add each child
790 * to the trace's child list and update the parent and child relations.
791 */
792 private static void hierarchicalToFlatTree(TimeGraphEntry traceEntry) {
793 List<@NonNull TimeGraphEntry> rootList = traceEntry.getChildren();
794 // We visit the children of every entry to add
795 StreamFlattener<TimeGraphEntry> sf = new StreamFlattener<>(entry -> entry.getChildren().stream());
796 Stream<TimeGraphEntry> allEntries = rootList.stream().flatMap(entry -> sf.flatten(entry));
797
798 // We add every entry that is missing from the trace's entry list
799 List<@NonNull TimeGraphEntry> rootListToAdd = allEntries
800 .filter(entry -> !rootList.contains(entry))
801 .collect(Collectors.toList());
802 rootList.forEach(entry -> {
803 entry.clearChildren();
804 });
805 rootListToAdd.forEach(entry -> {
806 traceEntry.addChild(entry);
807 entry.clearChildren();
808 });
809 }
810
811 /**
812 * Add entries to the traces's child list in a flat fashion (no hierarchy).
813 */
814 private static void addEntriesToFlatTree(List<@NonNull ControlFlowEntry> entryList, TimeGraphEntry traceEntry) {
815 List<TimeGraphEntry> rootList = traceEntry.getChildren();
816 for (ControlFlowEntry entry : entryList) {
817 if (!rootList.contains(entry)) {
818 traceEntry.addChild(entry);
819 }
820 }
821 }
822
823 /**
824 * Add entries to the trace's child list in a hierarchical fashion.
825 */
826 private static void addEntriesToHierarchicalTree(List<ControlFlowEntry> entryList, TimeGraphEntry traceEntry) {
827 List<TimeGraphEntry> rootList = traceEntry.getChildren();
828
829 for (ControlFlowEntry entry : entryList) {
830 boolean root = (entry.getParent() == null || entry.getParent() == traceEntry);
831 if (root && entry.getParentThreadId() > 0) {
832 for (ControlFlowEntry parent : entryList) {
833 /*
834 * Associate the parent entry only if their time overlap. A
835 * child entry may start before its parent, for example at
836 * the beginning of the trace if a parent has not yet
837 * appeared in the state system. We just want to make sure
838 * that the entry didn't start after the parent ended or
839 * ended before the parent started.
840 */
841 if (parent.getThreadId() == entry.getParentThreadId() &&
842 !(entry.getStartTime() > parent.getEndTime() ||
843 entry.getEndTime() < parent.getStartTime())) {
844 parent.addChild(entry);
845 root = false;
846 if (rootList.contains(entry)) {
847 traceEntry.removeChild(entry);
848 }
849 break;
850 }
851 }
852 }
853 if (root && (!rootList.contains(entry))) {
854 traceEntry.addChild(entry);
855 }
856 }
857 }
858
859 private void buildStatusEvents(ITmfTrace trace, ITmfTrace parentTrace, ITmfStateSystem ss, @NonNull List<List<ITmfStateInterval>> fullStates,
860 @Nullable List<ITmfStateInterval> prevFullState, ControlFlowEntry entry, @NonNull IProgressMonitor monitor, long start, long end) {
861 if (start < entry.getEndTime() && end > entry.getStartTime()) {
862 List<ITimeEvent> eventList = getEventList(entry, ss, fullStates, prevFullState, monitor);
863 if (eventList == null) {
864 return;
865 }
866 /* Start a new event list on first iteration, then append to it */
867 if (prevFullState == null) {
868 entry.setEventList(eventList);
869 } else {
870 for (ITimeEvent event : eventList) {
871 entry.addEvent(event);
872 }
873 }
874 if (parentTrace.equals(getTrace())) {
875 redraw();
876 }
877 }
878 for (ITimeGraphEntry child : entry.getChildren()) {
879 if (monitor.isCanceled()) {
880 return;
881 }
882 buildStatusEvents(trace, parentTrace, ss, fullStates, prevFullState, (ControlFlowEntry) child, monitor, start, end);
883 }
884 }
885
886 @Override
887 protected @Nullable List<ITimeEvent> getEventList(@NonNull TimeGraphEntry tgentry, ITmfStateSystem ss,
888 @NonNull List<List<ITmfStateInterval>> fullStates, @Nullable List<ITmfStateInterval> prevFullState, @NonNull IProgressMonitor monitor) {
889 List<ITimeEvent> eventList = null;
890 if (!(tgentry instanceof ControlFlowEntry)) {
891 return eventList;
892 }
893 ControlFlowEntry entry = (ControlFlowEntry) tgentry;
894 try {
895 int threadQuark = entry.getThreadQuark();
896 int statusQuark = ss.getQuarkRelative(threadQuark, Attributes.STATUS);
897 eventList = new ArrayList<>(fullStates.size());
898 ITmfStateInterval lastInterval = prevFullState == null || statusQuark >= prevFullState.size() ? null : prevFullState.get(statusQuark);
899 long lastStartTime = lastInterval == null ? -1 : lastInterval.getStartTime();
900 long lastEndTime = lastInterval == null ? -1 : lastInterval.getEndTime() + 1;
901 for (List<ITmfStateInterval> fullState : fullStates) {
902 if (monitor.isCanceled()) {
903 return null;
904 }
905 if (statusQuark >= fullState.size()) {
906 /* No information on this thread (yet?), skip it for now */
907 continue;
908 }
909 ITmfStateInterval statusInterval = fullState.get(statusQuark);
910 long time = statusInterval.getStartTime();
911 if (time == lastStartTime) {
912 continue;
913 }
914 long duration = statusInterval.getEndTime() - time + 1;
915 int status = -1;
916 try {
917 status = statusInterval.getStateValue().unboxInt();
918 } catch (StateValueTypeException e) {
919 Activator.getDefault().logError(e.getMessage());
920 }
921 if (lastEndTime != time && lastEndTime != -1) {
922 eventList.add(new TimeEvent(entry, lastEndTime, time - lastEndTime));
923 }
924 if (!statusInterval.getStateValue().isNull()) {
925 eventList.add(new TimeEvent(entry, time, duration, status));
926 } else {
927 eventList.add(new NullTimeEvent(entry, time, duration));
928 }
929 lastStartTime = time;
930 lastEndTime = time + duration;
931 }
932 } catch (AttributeNotFoundException | TimeRangeException e) {
933 Activator.getDefault().logError(e.getMessage());
934 }
935 return eventList;
936 }
937
938 /**
939 * Returns a value corresponding to the selected entry.
940 *
941 * Used in conjunction with synchingToTime to change the selected entry. If
942 * one of these methods is overridden in child class, then both should be.
943 *
944 * @param time
945 * The currently selected time
946 * @return a value identifying the entry
947 */
948 private int getSelectionValue(long time) {
949 int thread = -1;
950 for (ITmfTrace trace : TmfTraceManager.getTraceSet(getTrace())) {
951 if (thread > 0) {
952 break;
953 }
954 ITmfStateSystem ssq = TmfStateSystemAnalysisModule.getStateSystem(trace, KernelAnalysisModule.ID);
955 if (ssq == null) {
956 continue;
957 }
958 if (time >= ssq.getStartTime() && time <= ssq.getCurrentEndTime()) {
959 List<Integer> currentThreadQuarks = ssq.getQuarks(Attributes.CPUS, "*", Attributes.CURRENT_THREAD); //$NON-NLS-1$
960 for (int currentThreadQuark : currentThreadQuarks) {
961 try {
962 ITmfStateInterval currentThreadInterval = ssq.querySingleState(time, currentThreadQuark);
963 int currentThread = currentThreadInterval.getStateValue().unboxInt();
964 if (currentThread > 0) {
965 int statusQuark = ssq.getQuarkAbsolute(Attributes.THREADS, Integer.toString(currentThread), Attributes.STATUS);
966 ITmfStateInterval statusInterval = ssq.querySingleState(time, statusQuark);
967 if (statusInterval.getStartTime() == time) {
968 thread = currentThread;
969 break;
970 }
971 }
972 } catch (AttributeNotFoundException | TimeRangeException | StateValueTypeException e) {
973 Activator.getDefault().logError(e.getMessage());
974 } catch (StateSystemDisposedException e) {
975 /* Ignored */
976 }
977 }
978 }
979 }
980 return thread;
981 }
982
983 @Override
984 protected void synchingToTime(long time) {
985 int selected = getSelectionValue(time);
986 if (selected > 0) {
987 for (Object element : getTimeGraphViewer().getExpandedElements()) {
988 if (element instanceof ControlFlowEntry) {
989 ControlFlowEntry entry = (ControlFlowEntry) element;
990 if (entry.getThreadId() == selected) {
991 getTimeGraphCombo().setSelection(entry);
992 break;
993 }
994 }
995 }
996 }
997 }
998
999 @Override
1000 protected @NonNull List<ILinkEvent> getLinkList(ITmfStateSystem ss,
1001 @NonNull List<List<ITmfStateInterval>> fullStates, @Nullable List<ITmfStateInterval> prevFullState, @NonNull IProgressMonitor monitor) {
1002 List<ILinkEvent> list = new ArrayList<>();
1003 List<TimeGraphEntry> entryList = getEntryList(ss);
1004 if (entryList == null) {
1005 return list;
1006 }
1007 for (ITmfTrace trace : TmfTraceManager.getTraceSet(getTrace())) {
1008 List<Integer> currentThreadQuarks = ss.getQuarks(Attributes.CPUS, "*", Attributes.CURRENT_THREAD); //$NON-NLS-1$
1009 for (int currentThreadQuark : currentThreadQuarks) {
1010 if (currentThreadQuark >= fullStates.get(0).size()) {
1011 /* No information on this cpu (yet?), skip it for now */
1012 continue;
1013 }
1014 List<ITmfStateInterval> currentThreadIntervals = new ArrayList<>(fullStates.size() + 2);
1015 try {
1016 /*
1017 * Add the previous interval if it is the first query
1018 * iteration and the first interval has currentThread=0. Add
1019 * the following interval if the last interval has
1020 * currentThread=0. These are diagonal arrows crossing the
1021 * query iteration range.
1022 */
1023 if (prevFullState == null) {
1024 ITmfStateInterval currentThreadInterval = fullStates.get(0).get(currentThreadQuark);
1025 if (currentThreadInterval.getStateValue().unboxInt() == 0) {
1026 long start = Math.max(currentThreadInterval.getStartTime() - 1, ss.getStartTime());
1027 currentThreadIntervals.add(ss.querySingleState(start, currentThreadQuark));
1028 }
1029 }
1030 for (List<ITmfStateInterval> fullState : fullStates) {
1031 currentThreadIntervals.add(fullState.get(currentThreadQuark));
1032 }
1033 ITmfStateInterval currentThreadInterval = fullStates.get(fullStates.size() - 1).get(currentThreadQuark);
1034 if (currentThreadInterval.getStateValue().unboxInt() == 0) {
1035 long end = Math.min(currentThreadInterval.getEndTime() + 1, ss.getCurrentEndTime());
1036 currentThreadIntervals.add(ss.querySingleState(end, currentThreadQuark));
1037 }
1038 } catch (StateSystemDisposedException e) {
1039 /* Ignored */
1040 return list;
1041 }
1042 int prevThread = 0;
1043 long prevEnd = 0;
1044 long lastEnd = 0;
1045 for (ITmfStateInterval currentThreadInterval : currentThreadIntervals) {
1046 if (monitor.isCanceled()) {
1047 return list;
1048 }
1049 if (currentThreadInterval.getEndTime() + 1 == lastEnd) {
1050 continue;
1051 }
1052 long time = currentThreadInterval.getStartTime();
1053 if (time != lastEnd) {
1054 // don't create links where there are gaps in intervals due to the resolution
1055 prevThread = 0;
1056 prevEnd = 0;
1057 }
1058 int thread = currentThreadInterval.getStateValue().unboxInt();
1059 if (thread > 0 && prevThread > 0) {
1060 ITimeGraphEntry prevEntry = findEntry(entryList, trace, prevThread);
1061 ITimeGraphEntry nextEntry = findEntry(entryList, trace, thread);
1062 list.add(new TimeLinkEvent(prevEntry, nextEntry, prevEnd, time - prevEnd, 0));
1063 }
1064 lastEnd = currentThreadInterval.getEndTime() + 1;
1065 if (thread != 0) {
1066 prevThread = thread;
1067 prevEnd = lastEnd;
1068 }
1069 }
1070 }
1071 }
1072 return list;
1073 }
1074
1075 private ControlFlowEntry findEntry(List<TimeGraphEntry> entryList, ITmfTrace trace, int threadId) {
1076 for (TimeGraphEntry entry : entryList) {
1077 if (entry instanceof ControlFlowEntry) {
1078 ControlFlowEntry controlFlowEntry = (ControlFlowEntry) entry;
1079 if (controlFlowEntry.getThreadId() == threadId && controlFlowEntry.getTrace() == trace) {
1080 return controlFlowEntry;
1081 }
1082 }
1083 if (entry.hasChildren()) {
1084 ControlFlowEntry controlFlowEntry = findEntry(entry.getChildren(), trace, threadId);
1085 if (controlFlowEntry != null) {
1086 return controlFlowEntry;
1087 }
1088 }
1089 }
1090 return null;
1091 }
1092 }
This page took 0.075083 seconds and 6 git commands to generate.