-
Notifications
You must be signed in to change notification settings - Fork 248
Expand file tree
/
Copy pathindex.tsx
More file actions
439 lines (399 loc) · 13.9 KB
/
index.tsx
File metadata and controls
439 lines (399 loc) · 13.9 KB
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
// Copyright 2022 The Parca Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import React, {LegacyRef, ReactNode, useCallback, useEffect, useMemo, useState} from 'react';
import cx from 'classnames';
import {AnimatePresence, motion} from 'framer-motion';
import {useMeasure} from 'react-use';
import {FlamegraphArrow} from '@parca/client';
import {
Button,
FlameGraphSkeleton,
SandwichFlameGraphSkeleton,
useParcaContext,
useURLState,
} from '@parca/components';
import {ProfileType} from '@parca/parser';
import {TEST_IDS, testId} from '@parca/test-utils';
import {capitalizeOnlyFirstLetter, divide} from '@parca/utilities';
import {MergedProfileSource, ProfileSource} from '../ProfileSource';
import DiffLegend from '../ProfileView/components/DiffLegend';
import {useProfileViewContext} from '../ProfileView/context/ProfileViewContext';
import {useProfileMetadata} from '../ProfileView/hooks/useProfileMetadata';
import {useVisualizationState} from '../ProfileView/hooks/useVisualizationState';
import {TimelineGuide} from '../TimelineGuide';
import {useAutoConfigureFlamechart} from '../hooks/useAutoConfigureFlamechart';
import {FlameGraphArrow} from './FlameGraphArrow';
import {CurrentPathFrame, boundsFromProfileSource} from './FlameGraphArrow/utils';
const numberFormatter = new Intl.NumberFormat('en-US');
export type ResizeHandler = (width: number, height: number) => void;
interface ProfileFlameGraphProps {
width: number;
arrow?: FlamegraphArrow;
total: bigint;
filtered: bigint;
profileType?: ProfileType;
profileSource: ProfileSource;
curPathArrow: CurrentPathFrame[] | [];
setNewCurPathArrow: (path: CurrentPathFrame[]) => void;
loading: boolean;
setActionButtons?: (buttons: React.JSX.Element) => void;
error?: any;
isHalfScreen: boolean;
metadataMappingFiles?: string[];
metadataLoading?: boolean;
isFlameChart?: boolean;
isInSandwichView?: boolean;
isRenderedAsFlamegraph?: boolean;
tooltipId?: string;
maxFrameCount?: number;
isExpanded?: boolean;
}
const ErrorContent = ({errorMessage}: {errorMessage: string | ReactNode}): JSX.Element => {
return (
<div className="flex flex-col justify-center p-10 text-center gap-6 text-sm">
{errorMessage}
</div>
);
};
const AutoConfigButton = ({onClick}: {onClick: () => void}): JSX.Element => (
<Button onClick={onClick} variant="secondary" className="my-2">
Auto-configure for optimal Flame Chart viewing
</Button>
);
export const validateFlameChartQuery = (
profileSource: MergedProfileSource
): {isValid: boolean; isNonDelta: boolean; isDurationTooLong: boolean} => {
const isNonDelta = !profileSource.ProfileType().delta;
const duration = profileSource.mergeTo - profileSource.mergeFrom;
console.log('duration of flame chart query: ', duration, 'ns');
const isDurationTooLong = duration > 60_000_000_000n; // 60 seconds in nanoseconds
return {isValid: !isNonDelta && !isDurationTooLong, isNonDelta, isDurationTooLong};
};
const ProfileFlameGraph = function ProfileFlameGraphNonMemo({
arrow,
total,
filtered,
curPathArrow,
setNewCurPathArrow,
profileType,
loading,
error,
width,
isHalfScreen,
metadataMappingFiles,
isFlameChart = false,
profileSource,
isInSandwichView = false,
isRenderedAsFlamegraph = false,
tooltipId,
maxFrameCount,
isExpanded = false,
metadataLoading = false,
}: ProfileFlameGraphProps): JSX.Element {
const {onError, authenticationErrorMessage, isDarkMode, flamechartHelpText} = useParcaContext();
const {compareMode} = useProfileViewContext();
const [isLoading, setIsLoading] = useState<boolean>(true);
const [flameChartRef, {height: flameChartHeight}] = useMeasure();
const {colorBy, setColorBy} = useVisualizationState();
const handleAutoConfigureFlameChart = useAutoConfigureFlamechart();
// Create local state for paths when in sandwich view to avoid URL updates
const [localCurPathArrow, setLocalCurPathArrow] = useState<CurrentPathFrame[]>([]);
const setCurPathArrowWrapper = useCallback(
(path: CurrentPathFrame[]) => {
if (isInSandwichView) {
setLocalCurPathArrow(path);
} else {
setNewCurPathArrow(path);
}
},
[isInSandwichView, setNewCurPathArrow]
);
// Determine which paths to use based on isInSandwichView flag
const effectiveCurPathArrow = isInSandwichView ? localCurPathArrow : curPathArrow;
const {mappingsList, filenamesList} = useProfileMetadata({
flamegraphArrow: arrow,
metadataMappingFiles,
metadataLoading,
colorBy,
});
// By default, we want delta profiles (CPU) to be relatively compared.
// For non-delta profiles, like goroutines or memory, we want the profiles to be compared absolutely.
const compareAbsoluteDefault = profileType?.delta === false ? 'true' : 'false';
const [compareAbsolute = compareAbsoluteDefault] = useURLState('compare_absolute');
const isCompareAbsolute = compareAbsolute === 'true';
const mappingsListCount = useMemo(
() => mappingsList.filter(m => m !== '').length,
[mappingsList]
);
const [
totalFormatted,
totalUnfilteredFormatted,
isTrimmed,
trimmedFormatted,
trimmedPercentage,
isFiltered,
filteredPercentage,
] = useMemo(() => {
if (arrow === undefined) {
return ['0', '0', false, '0', '0', false, '0', '0'];
}
const trimmed: bigint = arrow?.trimmed ?? 0n;
const totalUnfiltered = total + filtered;
// safeguard against division by zero
const totalUnfilteredDivisor = totalUnfiltered > 0 ? totalUnfiltered : 1n;
return [
numberFormatter.format(total),
numberFormatter.format(totalUnfiltered),
trimmed > 0,
numberFormatter.format(trimmed),
numberFormatter.format(divide(trimmed * 100n, totalUnfilteredDivisor)),
filtered > 0,
numberFormatter.format(divide(total * 100n, totalUnfilteredDivisor)),
];
}, [arrow, filtered, total]);
const loadingState = !loading && arrow !== undefined && metadataMappingFiles !== undefined;
// If there is only one mapping file, we want to color by filename by default.
useEffect(() => {
if (mappingsListCount === 1 && colorBy !== 'filename') {
setColorBy('filename');
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [mappingsListCount]);
useEffect(() => {
if (loadingState) {
setIsLoading(false);
} else {
setIsLoading(true);
}
}, [loadingState]);
const flameGraph = useMemo(() => {
const {
isValid: isFlameChartValid,
isNonDelta,
isDurationTooLong,
} = isFlameChart
? validateFlameChartQuery(profileSource as MergedProfileSource)
: {isValid: true, isNonDelta: false, isDurationTooLong: false};
const isInvalidFlameChartQuery = isFlameChart && !isFlameChartValid;
if (isLoading && !isInvalidFlameChartQuery) {
return (
<div className="h-auto overflow-clip">
{isRenderedAsFlamegraph ? (
<SandwichFlameGraphSkeleton isHalfScreen={isHalfScreen} isDarkMode={isDarkMode} />
) : (
<FlameGraphSkeleton isHalfScreen={isHalfScreen} isDarkMode={isDarkMode} />
)}
</div>
);
}
// Do necessary checks to ensure that flame chart can be rendered for this query.
if (isInvalidFlameChartQuery) {
if (isNonDelta) {
return (
<ErrorContent
errorMessage={
<>
<span>To use the Flame chart, please switch to a Delta profile.</span>
{flamechartHelpText ?? null}
</>
}
/>
);
} else if (isDurationTooLong) {
return (
<ErrorContent
errorMessage={
<div className="flex flex-col items-center">
<span>
Flame chart is unavailable for queries longer than one minute. Please select a
point in the metrics graph to continue.
</span>
{!compareMode && <AutoConfigButton onClick={handleAutoConfigureFlameChart} />}
{flamechartHelpText ?? null}
</div>
}
/>
);
} else {
return (
<ErrorContent
errorMessage={
<div className="flex flex-col items-center">
<span>The Flame chart is not available for this query.</span>
{!compareMode && <AutoConfigButton onClick={handleAutoConfigureFlameChart} />}
{flamechartHelpText ?? null}
</div>
}
/>
);
}
}
if (arrow === undefined) return <div className="mx-auto text-center">No data...</div>;
if (total === 0n && !loading)
return <div className="mx-auto text-center">Profile has no samples</div>;
if (arrow !== undefined) {
return (
<div className="relative">
{isFlameChart ? (
<TimelineGuide
bounds={boundsFromProfileSource(profileSource)}
width={width}
height={flameChartHeight ?? 420}
margin={0}
ticks={12}
timeUnit="nanoseconds"
/>
) : null}
<div ref={flameChartRef as LegacyRef<HTMLDivElement>}>
<FlameGraphArrow
width={width}
arrow={arrow}
total={total}
filtered={filtered}
curPath={effectiveCurPathArrow}
setCurPath={setCurPathArrowWrapper}
profileType={profileType}
isHalfScreen={isHalfScreen}
mappingsListFromMetadata={mappingsList}
filenamesListFromMetadata={filenamesList}
compareAbsolute={isCompareAbsolute}
isFlameChart={isFlameChart}
profileSource={profileSource}
isRenderedAsFlamegraph={isRenderedAsFlamegraph}
isInSandwichView={isInSandwichView}
tooltipId={tooltipId}
maxFrameCount={maxFrameCount}
isExpanded={isExpanded}
colorBy={colorBy}
/>
</div>
</div>
);
}
}, [
isLoading,
arrow,
total,
loading,
width,
filtered,
profileType,
isHalfScreen,
isDarkMode,
isCompareAbsolute,
isFlameChart,
profileSource,
flameChartHeight,
flameChartRef,
flamechartHelpText,
isRenderedAsFlamegraph,
isInSandwichView,
effectiveCurPathArrow,
setCurPathArrowWrapper,
tooltipId,
maxFrameCount,
isExpanded,
mappingsList,
filenamesList,
colorBy,
handleAutoConfigureFlameChart,
compareMode,
]);
useEffect(() => {
if (isTrimmed) {
console.info(`Trimmed ${trimmedFormatted} (${trimmedPercentage}%) too small values.`);
}
}, [isTrimmed, trimmedFormatted, trimmedPercentage]);
if (error != null) {
onError?.(error);
if (authenticationErrorMessage !== undefined && error.code === 'UNAUTHENTICATED') {
return <ErrorContent errorMessage={authenticationErrorMessage} />;
}
// Check for specific merge errors
const errorMessageLower = error.message?.toLowerCase() ?? '';
const isMergeError: boolean = errorMessageLower.includes('failed to merge flame chart records');
const isTimestampError: boolean = errorMessageLower.includes(
'multiple samples for the same timestamp is not allowed'
);
if (isMergeError || isTimestampError) {
return (
<ErrorContent
errorMessage={
<>
<span className="font-semibold">Unable to display overlapping data</span>
<span className="text-gray-600 dark:text-gray-400">
The selected data contains overlapping samples from multiple nodes or threads that
cannot be merged.
</span>
<span className="text-gray-600 dark:text-gray-400">
To view this data, please apply more specific filters:
</span>
<ul className="list-disc list-inside text-left max-w-md mx-auto text-gray-600 dark:text-gray-400">
<li>Select a specific node from the node selector</li>
<li>Filter by either CPU or thread</li>
</ul>
</>
}
/>
);
}
return (
<ErrorContent
errorMessage={
<>
<span>
{error.message != null
? capitalizeOnlyFirstLetter(error.message)
: 'An error occurred'}
</span>
{isFlameChart ? flamechartHelpText ?? null : null}
</>
}
/>
);
}
return (
<AnimatePresence>
<motion.div
className="relative h-full w-full"
key="flame-graph-loaded"
initial={{opacity: 0}}
animate={{opacity: 1}}
transition={{duration: 0.5}}
>
{compareMode ? <DiffLegend /> : null}
<div
className={cx(!isInSandwichView ? 'min-h-48' : '')}
id="h-flame-graph"
{...testId(TEST_IDS.FLAMEGRAPH_CONTAINER)}
>
<>{flameGraph}</>
</div>
{!isInSandwichView && (
<p className="my-2 text-xs">
Showing {totalFormatted}{' '}
{isFiltered ? (
<span>
({filteredPercentage}%) filtered of {totalUnfilteredFormatted}{' '}
</span>
) : (
<></>
)}
values.{' '}
</p>
)}
</motion.div>
</AnimatePresence>
);
};
export default ProfileFlameGraph;