-
Notifications
You must be signed in to change notification settings - Fork 9
/
FlameGraphView.java
1609 lines (1474 loc) · 66 KB
/
FlameGraphView.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2016 Ericsson
*
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0 which
* accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Author:
* Sonia Farrah
*******************************************************************************/
package org.eclipse.tracecompass.incubator.internal.callstack.ui.flamegraph;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiFunction;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MenuDetectEvent;
import org.eclipse.swt.events.MenuDetectListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.tracecompass.common.core.NonNullUtils;
import org.eclipse.tracecompass.common.core.log.TraceCompassLogUtils.FlowScopeLog;
import org.eclipse.tracecompass.common.core.log.TraceCompassLogUtils.FlowScopeLogBuilder;
import org.eclipse.tracecompass.incubator.analysis.core.weighted.tree.AllGroupDescriptor;
import org.eclipse.tracecompass.incubator.analysis.core.weighted.tree.IWeightedTreeGroupDescriptor;
import org.eclipse.tracecompass.incubator.analysis.core.weighted.tree.IWeightedTreeProvider;
import org.eclipse.tracecompass.incubator.callstack.core.callgraph.ICallGraphProvider;
import org.eclipse.tracecompass.incubator.internal.callstack.core.flamegraph.DataProviderUtils;
import org.eclipse.tracecompass.incubator.internal.callstack.core.flamegraph.FlameGraphDataProvider;
import org.eclipse.tracecompass.incubator.internal.callstack.ui.Activator;
import org.eclipse.tracecompass.internal.provisional.tmf.core.model.filters.TmfFilterAppliedSignal;
import org.eclipse.tracecompass.internal.provisional.tmf.core.model.filters.TraceCompassFilter;
import org.eclipse.tracecompass.internal.provisional.tmf.ui.widgets.timegraph.BaseDataProviderTimeGraphPresentationProvider;
import org.eclipse.tracecompass.internal.tmf.core.model.filters.FetchParametersUtils;
import org.eclipse.tracecompass.statesystem.core.StateSystemUtils;
import org.eclipse.tracecompass.tmf.core.analysis.IAnalysisModule;
import org.eclipse.tracecompass.tmf.core.dataprovider.DataProviderManager;
import org.eclipse.tracecompass.tmf.core.dataprovider.DataProviderParameterUtils;
import org.eclipse.tracecompass.tmf.core.model.CoreFilterProperty;
import org.eclipse.tracecompass.tmf.core.model.IOutputElement;
import org.eclipse.tracecompass.tmf.core.model.filters.SelectionTimeQueryFilter;
import org.eclipse.tracecompass.tmf.core.model.timegraph.ITimeGraphDataProvider;
import org.eclipse.tracecompass.tmf.core.model.timegraph.ITimeGraphRowModel;
import org.eclipse.tracecompass.tmf.core.model.timegraph.ITimeGraphState;
import org.eclipse.tracecompass.tmf.core.model.timegraph.TimeGraphEntryModel;
import org.eclipse.tracecompass.tmf.core.model.timegraph.TimeGraphModel;
import org.eclipse.tracecompass.tmf.core.model.timegraph.TimeGraphState;
import org.eclipse.tracecompass.tmf.core.model.tree.TmfTreeModel;
import org.eclipse.tracecompass.tmf.core.response.ITmfResponse;
import org.eclipse.tracecompass.tmf.core.response.TmfModelResponse;
import org.eclipse.tracecompass.tmf.core.signal.TmfSignalHandler;
import org.eclipse.tracecompass.tmf.core.signal.TmfSignalManager;
import org.eclipse.tracecompass.tmf.core.signal.TmfStartAnalysisSignal;
import org.eclipse.tracecompass.tmf.core.signal.TmfTraceClosedSignal;
import org.eclipse.tracecompass.tmf.core.signal.TmfTraceSelectedSignal;
import org.eclipse.tracecompass.tmf.core.symbols.ISymbolProvider;
import org.eclipse.tracecompass.tmf.core.symbols.SymbolProviderManager;
import org.eclipse.tracecompass.tmf.core.timestamp.ITmfTimestamp;
import org.eclipse.tracecompass.tmf.core.trace.ITmfTrace;
import org.eclipse.tracecompass.tmf.core.trace.TmfTraceManager;
import org.eclipse.tracecompass.tmf.core.trace.TmfTraceUtils;
import org.eclipse.tracecompass.tmf.ui.TmfUiRefreshHandler;
import org.eclipse.tracecompass.tmf.ui.editors.ITmfTraceEditor;
import org.eclipse.tracecompass.tmf.ui.symbols.ISymbolProviderPreferencePage;
import org.eclipse.tracecompass.tmf.ui.symbols.SymbolProviderConfigDialog;
import org.eclipse.tracecompass.tmf.ui.symbols.TmfSymbolProviderUpdatedSignal;
import org.eclipse.tracecompass.tmf.ui.views.SaveImageUtil;
import org.eclipse.tracecompass.tmf.ui.views.TmfView;
import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.TimeGraphViewer;
import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.ITimeEvent;
import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.ITimeGraphEntry;
import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.NamedTimeEvent;
import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.NullTimeEvent;
import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.TimeEvent;
import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.TimeGraphEntry;
import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.model.TimeGraphEntry.Sampling;
import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.TimeGraphControl;
import org.eclipse.tracecompass.tmf.ui.widgets.timegraph.widgets.Utils.TimeFormat;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.progress.IWorkbenchSiteProgressService;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
/**
* View to display the flame graph .This uses the flameGraphNode tree generated
* by CallGraphAnalysisUI.
*
* @author Sonia Farrah
*/
@NonNullByDefault({})
public class FlameGraphView extends TmfView {
/**
* ID of the view
*/
public static final String ID = FlameGraphView.class.getPackage().getName() + ".flamegraphView"; //$NON-NLS-1$
private static final @NonNull String SYMBOL_MAPPING_ICON_PATH = "icons/obj16/binaries_obj.gif"; //$NON-NLS-1$
private static final @NonNull String GROUP_BY_ICON_PATH = "icons/etool16/group_by.gif"; //$NON-NLS-1$
private static final String SORT_OPTION_KEY = "sort.option"; //$NON-NLS-1$
private static final ImageDescriptor SORT_BY_NAME_ICON = Activator.getDefault().getImageDescripterFromPath("icons/etool16/sort_alpha.gif"); //$NON-NLS-1$
private static final ImageDescriptor SORT_BY_NAME_REV_ICON = Activator.getDefault().getImageDescripterFromPath("icons/etool16/sort_alpha_rev.gif"); //$NON-NLS-1$
private static final ImageDescriptor SORT_BY_ID_ICON = Activator.getDefault().getImageDescripterFromPath("icons/etool16/sort_num.gif"); //$NON-NLS-1$
private static final ImageDescriptor SORT_BY_ID_REV_ICON = Activator.getDefault().getImageDescripterFromPath("icons/etool16/sort_num_rev.gif"); //$NON-NLS-1$
private static final ImageDescriptor AGGREGATE_BY_ICON = Activator.getDefault().getImageDescripterFromPath(GROUP_BY_ICON_PATH);
private static final int DEFAULT_BUFFER_SIZE = 3;
private TimeGraphViewer fTimeGraphViewer;
private SortOption fSortOption = SortOption.BY_NAME;
private BaseDataProviderTimeGraphPresentationProvider fPresentationProvider;
private ITmfTrace fTrace;
private static final @NonNull Logger LOGGER = Logger.getLogger(FlameGraphView.class.getName());
private final @NonNull MenuManager fEventMenuManager = new MenuManager();
private Action fAggregateByAction;
private Action fSortByNameAction;
private Action fSortByIdAction;
// The action to import a binary file mapping */
private Action fConfigureSymbolsAction;
private @Nullable IWeightedTreeGroupDescriptor fGroupBy = null;
/**
* A plain old semaphore is used since different threads will be competing
* for the same resource.
*/
private final Semaphore fLock = new Semaphore(1);
// Variable to specify when the graph is dirty, ie waiting for data refresh
private final AtomicInteger fDirty = new AtomicInteger();
/** The trace to build thread hash map */
private final Map<ITmfTrace, Job> fBuildJobMap = new HashMap<>();
private final Map<ITimeGraphDataProvider<? extends @NonNull TimeGraphEntryModel>, Map<Long, @NonNull TimeGraphEntry>> fEntries = new HashMap<>();
/**
* Set of visible entries to zoom on.
*/
private @NonNull Set<@NonNull TimeGraphEntry> fVisibleEntries = Collections.emptySet();
private long fEndTime = Long.MIN_VALUE;
/** The trace to entry list hash map */
private final Map<ITmfTrace, List<@NonNull TimeGraphEntry>> fEntryListMap = new HashMap<>();
private int fDisplayWidth;
private @Nullable ZoomThread fZoomThread;
private final Object fZoomThreadResultLock = new Object();
/**
* Constructor
*/
public FlameGraphView() {
super(ID);
}
/**
* Constructor with ID
*
* @param id
* The ID of the view
*/
protected FlameGraphView(String id) {
super(id);
}
@Override
public void createPartControl(Composite parent) {
super.createPartControl(parent);
fDisplayWidth = Display.getDefault().getBounds().width;
fTimeGraphViewer = new TimeGraphViewer(parent, SWT.NONE);
fPresentationProvider = new BaseDataProviderTimeGraphPresentationProvider();
fTimeGraphViewer.setTimeGraphProvider(fPresentationProvider);
fTimeGraphViewer.setTimeFormat(TimeFormat.NUMBER);
IEditorPart editor = getSite().getPage().getActiveEditor();
ITmfTrace trace = null;
if (editor instanceof ITmfTraceEditor) {
trace = ((ITmfTraceEditor) editor).getTrace();
} else {
// Get the active trace, the editor might be opened on a script
trace = TmfTraceManager.getInstance().getActiveTrace();
}
if (trace != null) {
traceSelected(new TmfTraceSelectedSignal(this, trace));
}
contributeToActionBars();
loadSortOption();
TmfSignalManager.register(this);
getSite().setSelectionProvider(fTimeGraphViewer.getSelectionProvider());
createTimeEventContextMenu();
fTimeGraphViewer.getTimeGraphControl().addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e) {
TimeGraphControl timeGraphControl = getTimeGraphViewer().getTimeGraphControl();
ISelection selection = timeGraphControl.getSelection();
if (selection instanceof IStructuredSelection) {
for (Object object : ((IStructuredSelection) selection).toList()) {
if (object instanceof TimeEvent) {
TimeEvent event = (TimeEvent) object;
long startTime = event.getTime();
long endTime = startTime + event.getDuration();
getTimeGraphViewer().setStartFinishTime(startTime, endTime);
break;
}
}
}
}
});
fTimeGraphViewer.addRangeListener(event -> {
startZoomThread(event.getStartTime(), event.getEndTime(), false);
});
TimeGraphControl timeGraphControl = fTimeGraphViewer.getTimeGraphControl();
timeGraphControl.addPaintListener(new PaintListener() {
/**
* This paint control allows the virtual time graph refresh to occur
* on paint events instead of just scrolling the time axis or
* zooming. To avoid refreshing the model on every paint event, we
* use a TmfUiRefreshHandler to coalesce requests and only execute
* the last one, we also check if the entries have changed to avoid
* useless model refresh.
*
* @param e
* paint event on the visible area
*/
@Override
public void paintControl(PaintEvent e) {
TmfUiRefreshHandler.getInstance().queueUpdate(this, () -> {
if (timeGraphControl.isDisposed()) {
return;
}
Set<@NonNull TimeGraphEntry> newSet = getVisibleItems(DEFAULT_BUFFER_SIZE);
if (!fVisibleEntries.equals(newSet)) {
/*
* Start a zoom thread if the set of visible entries has
* changed. We do not use lists as the order is not
* important. We cannot use the start index / size of
* the visible entries as we can collapse / reorder
* events.
*/
fVisibleEntries = newSet;
startZoomThread(getTimeGraphViewer().getTime0(), getTimeGraphViewer().getTime1(), false);
}
});
}
});
}
/**
* Get the time graph viewer
*
* @return the time graph viewer
*/
@VisibleForTesting
public TimeGraphViewer getTimeGraphViewer() {
return fTimeGraphViewer;
}
/**
* Handler for the trace selected signal
*
* @param signal
* The incoming signal
*/
@TmfSignalHandler
public void traceSelected(final TmfTraceSelectedSignal signal) {
ITmfTrace trace = signal.getTrace();
fTrace = trace;
if (trace == null) {
return;
}
// If entries for this trace are already available, just zoom on them,
// otherwise, rebuild
List<@NonNull TimeGraphEntry> list = fEntryListMap.get(trace);
if (list == null) {
refresh();
Display.getDefault().asyncExec(() -> buildFlameGraph(trace, null, null));
} else {
// Reset end time
long endTime = Long.MIN_VALUE;
for (TimeGraphEntry entry : list) {
endTime = Math.max(endTime, entry.getEndTime());
}
setEndTime(endTime);
refresh();
startZoomThread(0, endTime, false);
}
}
/**
* Get the callgraph modules used to build the view
*
* @return The call graph provider modules
*/
protected Iterable<ICallGraphProvider> getCallgraphModules() {
ITmfTrace trace = fTrace;
if (trace == null) {
return null;
}
String analysisId = NonNullUtils.nullToEmptyString(getViewSite().getSecondaryId());
Iterable<ICallGraphProvider> modules = TmfTraceUtils.getAnalysisModulesOfClass(trace, ICallGraphProvider.class);
return StreamSupport.stream(modules.spliterator(), false)
.filter(m -> {
if (m instanceof IAnalysisModule) {
return ((IAnalysisModule) m).getId().equals(analysisId);
}
return true;
})
.collect(Collectors.toSet());
}
private String getProviderId() {
String secondaryId = this.getViewSite().getSecondaryId();
// The secondary ID may contain the '[COLON]' text, in which case, it
// should be replace with a real ':' and this is the complete
// providerId. This kind of secondary ID may come from external sources
// of data provider, such as scripting
return (secondaryId == null) ? FlameGraphDataProvider.ID : (secondaryId.contains("[COLON]")) ? secondaryId.replace("[COLON]", ":") : FlameGraphDataProvider.ID + ':' + secondaryId; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
private class BuildRunnable {
private final @NonNull ITmfTrace fBuildTrace;
private final @NonNull ITmfTrace fParentTrace;
private final @NonNull FlowScopeLog fScope;
private final @NonNull Map<String, Object> fParameters;
public BuildRunnable(final @NonNull ITmfTrace trace, final @NonNull ITmfTrace parentTrace, @Nullable ITmfTimestamp selStart, @Nullable ITmfTimestamp selEnd, final @NonNull FlowScopeLog log) {
fBuildTrace = trace;
fParentTrace = parentTrace;
fScope = log;
if (selStart != null && selEnd != null) {
fParameters = ImmutableMap.of(FlameGraphDataProvider.SELECTION_RANGE_KEY, ImmutableList.of(selStart.toNanos(), selEnd.toNanos()));
} else {
fParameters = Collections.emptyMap();
}
}
public void run(IProgressMonitor monitor) {
try (FlowScopeLog log = new FlowScopeLogBuilder(LOGGER, Level.FINE, "FlameGraphView:BuildThread", "trace", fBuildTrace.getName()).setParentScope(fScope).build()) { //$NON-NLS-1$ //$NON-NLS-2$
buildEntryList(fBuildTrace, fParentTrace, fParameters, Objects.requireNonNull(monitor));
synchronized (fBuildJobMap) {
fBuildJobMap.remove(fBuildTrace);
}
}
}
}
private void buildEntryList(@NonNull ITmfTrace trace, @NonNull ITmfTrace parentTrace, @NonNull Map<String, Object> additionalParams, @NonNull IProgressMonitor monitor) {
ITimeGraphDataProvider<@NonNull TimeGraphEntryModel> dataProvider = DataProviderManager
.getInstance().getOrCreateDataProvider(trace, getProviderId(), ITimeGraphDataProvider.class);
if (dataProvider == null) {
return;
}
BaseDataProviderTimeGraphPresentationProvider presentationProvider = fPresentationProvider;
if (presentationProvider != null) {
presentationProvider.addProvider(dataProvider, getTooltipResolver(dataProvider));
}
boolean complete = false;
while (!complete && !monitor.isCanceled()) {
Map<String, Object> parameters = new HashMap<>(additionalParams);
parameters.put(DataProviderParameterUtils.REQUESTED_TIME_KEY, ImmutableList.of(0, Long.MAX_VALUE));
IWeightedTreeGroupDescriptor groupBy = fGroupBy;
if (groupBy != null) {
parameters.put(FlameGraphDataProvider.GROUP_BY_KEY, groupBy.getName());
}
TmfModelResponse<TmfTreeModel<@NonNull TimeGraphEntryModel>> response = dataProvider.fetchTree(parameters, monitor);
if (response.getStatus() == ITmfResponse.Status.FAILED) {
Activator.getDefault().logError(getClass().getSimpleName() + " Data Provider failed: " + response.getStatusMessage()); //$NON-NLS-1$
return;
} else if (response.getStatus() == ITmfResponse.Status.CANCELLED) {
return;
}
complete = response.getStatus() == ITmfResponse.Status.COMPLETED;
TmfTreeModel<@NonNull TimeGraphEntryModel> model = response.getModel();
long endTime = Long.MIN_VALUE;
if (model != null) {
Map<Long, TimeGraphEntry> entries;
synchronized (fEntries) {
entries = fEntries.computeIfAbsent(dataProvider, dp -> new HashMap<>());
/*
* The provider may send entries unordered and parents may
* not exist when child is constructor, we'll re-unite
* families at the end
*/
List<TimeGraphEntry> orphaned = new ArrayList<>();
for (TimeGraphEntryModel entry : model.getEntries()) {
TimeGraphEntry uiEntry = entries.get(entry.getId());
if (entry.getParentId() != -1) {
if (uiEntry == null) {
uiEntry = new TimeGraphEntry(entry);
TimeGraphEntry parent = entries.get(entry.getParentId());
if (parent != null) {
parent.addChild(uiEntry);
} else {
orphaned.add(uiEntry);
}
entries.put(entry.getId(), uiEntry);
} else {
uiEntry.updateModel(entry);
}
} else {
endTime = Long.max(endTime, entry.getEndTime() + 1);
if (uiEntry != null) {
uiEntry.updateModel(entry);
} else {
// Do not assume that parentless entries are
// trace entries
uiEntry = new ParentEntry(entry, dataProvider);
entries.put(entry.getId(), uiEntry);
addToEntryList(parentTrace, Collections.singletonList(uiEntry));
}
}
}
setEndTime(endTime);
// Find missing parents
for (TimeGraphEntry orphanedEntry : orphaned) {
TimeGraphEntry parent = entries.get(orphanedEntry.getEntryModel().getParentId());
if (parent != null) {
parent.addChild(orphanedEntry);
}
}
}
long start = 0;
long end = getEndTime();
final long resolution = Long.max(1, (end - start) / getDisplayWidth());
zoomEntries(ImmutableList.copyOf(entries.values()), start, end, resolution, monitor);
}
if (monitor.isCanceled()) {
return;
}
if (parentTrace.equals(getTrace())) {
refresh();
}
monitor.worked(1);
if (!complete && !monitor.isCanceled()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Activator.getDefault().logError("Failed to wait for data provider", e); //$NON-NLS-1$
}
}
}
}
/**
* Get the presentation provider
*
* @return the presentation provider
*/
@VisibleForTesting
public BaseDataProviderTimeGraphPresentationProvider getPresentationProvider() {
return fPresentationProvider;
}
private static BiFunction<ITimeEvent, Long, Map<String, String>> getTooltipResolver(ITimeGraphDataProvider<? extends TimeGraphEntryModel> provider) {
return (event, time) -> {
return getTooltip(event, time, provider, false);
};
}
private static Map<String, String> getTooltip(ITimeEvent event, Long time, ITimeGraphDataProvider<? extends TimeGraphEntryModel> provider, boolean getActions) {
ITimeGraphEntry entry = event.getEntry();
if (!(entry instanceof TimeGraphEntry)) {
return Collections.emptyMap();
}
long entryId = ((TimeGraphEntry) entry).getEntryModel().getId();
IOutputElement element = null;
if (event instanceof TimeEvent) {
element = ((TimeEvent) event).getModel();
}
Map<@NonNull String, @NonNull Object> parameters = getFetchTooltipParameters(time, entryId, element);
if (getActions) {
parameters.put(FlameGraphDataProvider.TOOLTIP_ACTION_KEY, true);
}
TmfModelResponse<Map<String, String>> response = provider.fetchTooltip(parameters, new NullProgressMonitor());
Map<String, String> tooltip = response.getModel();
return (tooltip == null) ? Collections.emptyMap() : tooltip;
}
private static Map<String, Object> getFetchTooltipParameters(long time, long item, @Nullable IOutputElement element) {
@NonNull Map<String, Object> parameters = new HashMap<>();
parameters.put(DataProviderParameterUtils.REQUESTED_TIME_KEY, Collections.singletonList(time));
parameters.put(DataProviderParameterUtils.REQUESTED_ITEMS_KEY, Collections.singletonList(item));
if (element != null) {
parameters.put(DataProviderParameterUtils.REQUESTED_ELEMENT_KEY, element);
}
return parameters;
}
/**
* Zoom thread
*
* @since 1.1
*/
protected class ZoomThread extends Thread {
private final long fZoomStartTime;
private final long fZoomEndTime;
private final long fResolution;
private int fScopeId = -1;
private final @NonNull IProgressMonitor fMonitor;
private @NonNull Collection<@NonNull TimeGraphEntry> fCurrentEntries;
private boolean fForce;
/**
* Constructor
*
* @param entries
* The entries to zoom on
* @param startTime
* the start time
* @param endTime
* the end time
* @param resolution
* the resolution
* @param force
* Whether to force the zoom of all entries or only those
* that have not the same sampling
*/
public ZoomThread(@NonNull Collection<@NonNull TimeGraphEntry> entries, long startTime, long endTime, long resolution, boolean force) {
super(FlameGraphView.this.getName() + " zoom"); //$NON-NLS-1$
fZoomStartTime = startTime;
fZoomEndTime = endTime;
fResolution = resolution;
fCurrentEntries = entries;
fMonitor = new NullProgressMonitor();
fForce = force;
}
/**
* @return the zoom start time
*/
public long getZoomStartTime() {
return fZoomStartTime;
}
/**
* @return the zoom end time
*/
public long getZoomEndTime() {
return fZoomEndTime;
}
/**
* @return the resolution
*/
public long getResolution() {
return fResolution;
}
/**
* @return the monitor
*/
public @NonNull IProgressMonitor getMonitor() {
return fMonitor;
}
/**
* Cancel the zoom thread
*/
public void cancel() {
fMonitor.setCanceled(true);
}
@Override
public final void run() {
try (FlowScopeLog log = new FlowScopeLogBuilder(LOGGER, Level.FINE, "FlameGraphView:ZoomThread", "start", fZoomStartTime, "end", fZoomEndTime).setCategoryAndId(getViewId(), fScopeId).build()) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (fCurrentEntries.isEmpty()) {
// No rows to zoom on
return;
}
Sampling sampling = new Sampling(getZoomStartTime(), getZoomEndTime(), getResolution());
Iterable<@NonNull TimeGraphEntry> incorrectSample = fForce ? fCurrentEntries : Iterables.filter(fCurrentEntries, entry -> !sampling.equals(entry.getSampling()));
zoomEntries(incorrectSample, getZoomStartTime(), getZoomEndTime(), getResolution(), getMonitor());
} finally {
if (fDirty.decrementAndGet() < 0) {
Activator.getDefault().logError("Dirty underflow", new Throwable()); //$NON-NLS-1$
}
}
}
/**
* Set the ID of the calling flow scope. This data will allow to
* determine the causality between the zoom thread and its caller if
* tracing is enabled.
*
* @param scopeId
* The ID of the calling flow scope
* @since 3.0
*/
public void setScopeId(int scopeId) {
fScopeId = scopeId;
}
}
/**
* Start or restart the zoom thread.
*
* @param startTime
* the zoom start time
* @param endTime
* the zoom end time
* @param force
* Whether to force the fetch of all rows, or only those that
* don't have the same range
*/
protected final void startZoomThread(long startTime, long endTime, boolean force) {
ITmfTrace trace = getTrace();
if (trace == null) {
return;
}
fDirty.incrementAndGet();
try (FlowScopeLog log = new FlowScopeLogBuilder(LOGGER, Level.FINE, "FlameGraphView:ZoomThreadCreated").setCategory(getViewId()).build()) { //$NON-NLS-1$
long clampedStartTime = Math.max(0, Math.min(startTime, getEndTime()));
long clampedEndTime = Math.min(getEndTime(), Math.max(endTime, 0));
// Ignore if end time < start time, data is not set correctly [yet]
if (clampedEndTime < clampedStartTime) {
return;
}
ZoomThread zoomThread = fZoomThread;
if (zoomThread != null) {
zoomThread.cancel();
}
int timeSpace = getTimeGraphViewer().getTimeSpace();
if (timeSpace > 0) {
long resolution = Long.max(1, (clampedEndTime - clampedStartTime) / timeSpace);
zoomThread = new ZoomThread(getVisibleItems(DEFAULT_BUFFER_SIZE), clampedStartTime, clampedEndTime, resolution, force);
} else {
zoomThread = null;
}
fZoomThread = zoomThread;
if (zoomThread != null) {
zoomThread.setScopeId(log.getId());
/*
* Don't start a new thread right away if results are being
* applied from an old ZoomThread. Otherwise, the old results
* might overwrite the new results if it finishes after.
*/
synchronized (fZoomThreadResultLock) {
zoomThread.start();
// zoomThread decrements, so we increment here
fDirty.incrementAndGet();
}
}
} finally {
if (fDirty.decrementAndGet() < 0) {
Activator.getDefault().logError("Dirty underflow", new Throwable()); //$NON-NLS-1$
}
}
}
private @NonNull Set<@NonNull TimeGraphEntry> getVisibleItems(int buffer) {
TimeGraphControl timeGraphControl = fTimeGraphViewer.getTimeGraphControl();
if (timeGraphControl.isDisposed()) {
return Collections.emptySet();
}
int start = Integer.max(0, fTimeGraphViewer.getTopIndex() - buffer);
int end = Integer.min(fTimeGraphViewer.getExpandedElementCount() - 1,
fTimeGraphViewer.getTopIndex() + timeGraphControl.countPerPage() + buffer);
Set<@NonNull TimeGraphEntry> visible = new HashSet<>(end - start + 1);
for (int i = start; i <= end; i++) {
/*
* Use the getExpandedElement by index to avoid creating a copy of
* all the the elements.
*/
TimeGraphEntry element = (TimeGraphEntry) timeGraphControl.getExpandedElement(i);
if (element != null) {
visible.add(element);
}
}
return visible;
}
private void zoomEntries(@NonNull Iterable<@NonNull TimeGraphEntry> entries, long zoomStartTime, long zoomEndTime, long resolution, @NonNull IProgressMonitor monitor) {
if (resolution < 0) {
// StateSystemUtils.getTimes would throw an IllegalArgumentException
return;
}
long start = Long.min(zoomStartTime, zoomEndTime);
long end = Long.max(zoomStartTime, zoomEndTime);
List<@NonNull Long> times = StateSystemUtils.getTimes(start, end, resolution);
Sampling sampling = new Sampling(start, end, resolution);
Multimap<ITimeGraphDataProvider<? extends TimeGraphEntryModel>, Long> providersToModelIds = filterGroupEntries(entries, zoomStartTime, zoomEndTime);
SubMonitor subMonitor = SubMonitor.convert(monitor, getClass().getSimpleName() + "#zoomEntries", providersToModelIds.size()); //$NON-NLS-1$
for (Entry<ITimeGraphDataProvider<? extends TimeGraphEntryModel>, Collection<Long>> entry : providersToModelIds.asMap().entrySet()) {
ITimeGraphDataProvider<? extends TimeGraphEntryModel> dataProvider = entry.getKey();
SelectionTimeQueryFilter filter = new SelectionTimeQueryFilter(times, entry.getValue());
Map<@NonNull String, @NonNull Object> parameters = FetchParametersUtils.selectionTimeQueryToMap(filter);
Multimap<@NonNull Integer, @NonNull String> regexesMap = getRegexes();
if (!regexesMap.isEmpty()) {
parameters.put(DataProviderParameterUtils.REGEX_MAP_FILTERS_KEY, regexesMap.asMap());
}
TmfModelResponse<TimeGraphModel> response = dataProvider.fetchRowModel(parameters, monitor);
TimeGraphModel model = response.getModel();
if (model != null) {
zoomEntries(fEntries.get(dataProvider), model.getRows(), response.getStatus() == ITmfResponse.Status.COMPLETED, sampling);
}
subMonitor.worked(1);
}
redraw();
}
/**
* This method build the multimap of regexes by property that will be used
* to filter the timegraph states
*
* Override this method to add other regexes with their properties. The data
* provider should handle everything after.
*
* @return The multimap of regexes by property
*/
private @NonNull Multimap<@NonNull Integer, @NonNull String> getRegexes() {
Multimap<@NonNull Integer, @NonNull String> regexes = HashMultimap.create();
ITmfTrace trace = getTrace();
if (trace == null) {
return regexes;
}
TraceCompassFilter globalFilter = TraceCompassFilter.getFilterForTrace(trace);
if (globalFilter == null) {
return regexes;
}
regexes.putAll(CoreFilterProperty.DIMMED, globalFilter.getRegexes());
return regexes;
}
private void zoomEntries(Map<Long, TimeGraphEntry> map, List<ITimeGraphRowModel> model, boolean completed, Sampling sampling) {
boolean isZoomThread = false; // Thread.currentThread() instanceof
// ZoomThread;
for (ITimeGraphRowModel rowModel : model) {
TimeGraphEntry entry = map.get(rowModel.getEntryID());
if (entry != null) {
List<ITimeEvent> events = createTimeEvents(entry, rowModel.getStates());
if (isZoomThread) {
synchronized (fZoomThreadResultLock) {
Display.getDefault().asyncExec(() -> {
entry.setZoomedEventList(events);
if (completed) {
entry.setSampling(sampling);
}
});
}
} else {
entry.setEventList(events);
}
}
}
}
/**
* Create {@link ITimeEvent}s for an entry from the list of
* {@link ITimeGraphState}s, filling in the gaps.
*
* @param entry
* the {@link TimeGraphEntry} on which we are working
* @param values
* the list of {@link ITimeGraphState}s from the
* {@link ITimeGraphDataProvider}.
* @return a contiguous List of {@link ITimeEvent}s
*/
private List<ITimeEvent> createTimeEvents(TimeGraphEntry entry, List<ITimeGraphState> values) {
List<ITimeEvent> events = new ArrayList<>(values.size());
ITimeEvent prev = null;
for (ITimeGraphState state : values) {
ITimeEvent event = createTimeEvent(entry, state);
if (prev != null) {
long prevEnd = prev.getTime() + prev.getDuration();
if (prevEnd < event.getTime()) {
// fill in the gap.
TimeEvent timeEvent = new TimeEvent(entry, prevEnd, event.getTime() - prevEnd);
events.add(timeEvent);
}
}
prev = event;
events.add(event);
}
return events;
}
/**
* Create a {@link TimeEvent} for a {@link TimeGraphEntry} and a
* {@link TimeGraphState}
*
* @param entry
* {@link TimeGraphEntry} for which we create a state
* @param state
* {@link ITimeGraphState} from the data provider
* @return a new {@link TimeEvent} for these arguments
*/
protected TimeEvent createTimeEvent(TimeGraphEntry entry, ITimeGraphState state) {
String label = state.getLabel();
if (state.getValue() == Integer.MIN_VALUE && label == null && state.getStyle() == null) {
return new NullTimeEvent(entry, state.getStartTime(), state.getDuration());
}
if (label != null) {
return new NamedTimeEvent(entry, label, state);
}
return new TimeEvent(entry, state);
}
/**
* Filter the entries to return only the Non Null {@link TimeGraphEntry}
* which intersect the time range.
*
* @param visible
* the input list of visible entries
* @param zoomStartTime
* the leftmost time bound of the view
* @param zoomEndTime
* the rightmost time bound of the view
* @return A Multimap of data providers to their visible entries' model IDs.
*/
private static Multimap<ITimeGraphDataProvider<? extends TimeGraphEntryModel>, Long> filterGroupEntries(Iterable<TimeGraphEntry> visible,
long zoomStartTime, long zoomEndTime) {
Multimap<ITimeGraphDataProvider<? extends TimeGraphEntryModel>, Long> providersToModelIds = HashMultimap.create();
for (TimeGraphEntry entry : visible) {
if (zoomStartTime <= entry.getEndTime() && zoomEndTime >= entry.getStartTime() && entry.hasTimeEvents()) {
ITimeGraphDataProvider<? extends TimeGraphEntryModel> provider = getProvider(entry);
if (provider != null) {
providersToModelIds.put(provider, entry.getEntryModel().getId());
}
}
}
return providersToModelIds;
}
/**
* Get the {@link ITimeGraphDataProvider} from a {@link TimeGraphEntry}'s
* parent.
*
* @param entry
* queried {@link TimeGraphEntry}.
* @return the {@link ITimeGraphDataProvider}
* @since 3.3
*/
public static ITimeGraphDataProvider<? extends TimeGraphEntryModel> getProvider(ITimeGraphEntry entry) {
ITimeGraphEntry parent = entry;
while (parent != null) {
if (parent instanceof ParentEntry) {
return ((ParentEntry) parent).getProvider();
}
parent = parent.getParent();
}
throw new IllegalStateException(entry + " should have a TraceEntry parent"); //$NON-NLS-1$
}
/**
* Get the trace associated with this view
*
* @return The trace
*/
protected ITmfTrace getTrace() {
return fTrace;
}
private void refresh() {
try (FlowScopeLog parentLogger = new FlowScopeLogBuilder(LOGGER, Level.FINE, "FlameGraphView:RefreshRequested").setCategory(getViewId()).build()) { //$NON-NLS-1$
final boolean isZoomThread = Thread.currentThread() instanceof ZoomThread;
TmfUiRefreshHandler.getInstance().queueUpdate(this, () -> {
try (FlowScopeLog log = new FlowScopeLogBuilder(LOGGER, Level.FINE, "FlameGraphView:Refresh").setParentScope(parentLogger).build()) { //$NON-NLS-1$
fDirty.incrementAndGet();
if (fTimeGraphViewer.getControl().isDisposed()) {
return;
}
List<TimeGraphEntry> entries;
synchronized (fEntryListMap) {
entries = fEntryListMap.get(getTrace());
Comparator<ITimeGraphEntry> entryComparator = getEntryComparator();
if (entries == null) {
entries = new CopyOnWriteArrayList<>();
} else if (entryComparator != null) {
List<TimeGraphEntry> list = new ArrayList<>(entries);
Collections.sort(list, entryComparator);
for (ITimeGraphEntry entry : list) {
sortChildren(entry, entryComparator);
}
entries.clear();
entries.addAll(list);
}
}
boolean inputChanged = entries != fTimeGraphViewer.getInput();
if (inputChanged) {
fTimeGraphViewer.setInput(entries);
} else {
fTimeGraphViewer.refresh();
}
long startBound = 0;
long endBound = getEndTime();
endBound = (endBound == Long.MIN_VALUE ? SWT.DEFAULT : endBound);
fTimeGraphViewer.setTimeBounds(startBound, endBound);
if (inputChanged && !isZoomThread) {
fTimeGraphViewer.resetStartFinishTime();
}
} finally {
if (fDirty.decrementAndGet() < 0) {
Activator.getDefault().logError("Dirty underflow", new Throwable()); //$NON-NLS-1$
}
}
});
}
}
private Comparator<ITimeGraphEntry> getEntryComparator() {
switch (fSortOption) {
case BY_ID:
return ThreadIdComparator.getInstance();
case BY_ID_REV:
return ThreadIdComparator.getInstance().reversed();
case BY_NAME:
return ThreadNameComparator.getInstance();
case BY_NAME_REV:
return ThreadNameComparator.getInstance().reversed();
default: