Skip to content

Commit

Permalink
Flamegraph: Add switch for color scheme by value or by package (#70770)
Browse files Browse the repository at this point in the history
  • Loading branch information
aocenas authored and harisrozajac committed Jun 30, 2023
1 parent 3a678a4 commit 608235d
Show file tree
Hide file tree
Showing 12 changed files with 354 additions and 38 deletions.
Expand Up @@ -51,8 +51,8 @@ it('should not allow colors with a contrast ratio < 3 in light mode', () => {
});

it('should not allow colors with a contrast ratio < 3 in dark mode', () => {
expect(colorsToFilter.indexOf('#890F02')).toBe(11);
expect(colorsToFilter.indexOf('#0A437C')).toBe(12);
expect(colorsToFilter.indexOf('#890F02')).toBe(12);
expect(colorsToFilter.indexOf('#0A437C')).toBe(13);
const filteredColors = getFilteredColors(colorsToFilter, createTheme({ colors: { mode: 'dark' } }));
expect(filteredColors.indexOf('#890F02')).toBe(-1);
expect(filteredColors.indexOf('#0A437C')).toBe(-1);
Expand Down
Expand Up @@ -132,19 +132,20 @@ export function getRgbColorByKey(key: string, theme: GrafanaTheme2): [number, nu
}

export function getFilteredColors(colorsHex: string[], theme: GrafanaTheme2) {
const filtered = [...colorsHex];
// Remove red as a span color because it looks like an error
const redIndex = colorsHex.indexOf('#E24D42');
const redIndex = filtered.indexOf('#E24D42');
if (redIndex > -1) {
colorsHex.splice(redIndex, 1);
filtered.splice(redIndex, 1);
}
const redIndex2 = colorsHex.indexOf('#BF1B00');
if (redIndex2 > -1) {
colorsHex.splice(redIndex2, 1);
filtered.splice(redIndex2, 1);
}

// Only add colors that have a contrast ratio >= 3 for the current theme
let filteredColors = [];
for (const color of colorsHex) {
for (const color of filtered) {
if (tinycolor.readability(theme.colors.background.primary, color) >= 3) {
filteredColors.push(color);
}
Expand Down
Expand Up @@ -3,6 +3,8 @@ import React from 'react';

import { createDataFrame } from '@grafana/data';

import { ColorScheme } from '../types';

import FlameGraph from './FlameGraph';
import { FlameGraphDataContainer } from './dataTransform';
import { data } from './testData/dataNestedSet';
Expand Down Expand Up @@ -45,6 +47,7 @@ describe('FlameGraph', () => {
onSandwich={onSandwich}
onFocusPillClick={onFocusPillClick}
onSandwichPillClick={onSandwichPillClick}
colorScheme={ColorScheme.ValueBased}
/>
);
return {
Expand Down
Expand Up @@ -23,7 +23,7 @@ import { useMeasure } from 'react-use';
import { Icon, useStyles2 } from '@grafana/ui';

import { PIXELS_PER_LEVEL } from '../../constants';
import { ClickedItemData, TextAlign } from '../types';
import { ClickedItemData, ColorScheme, TextAlign } from '../types';

import FlameGraphContextMenu from './FlameGraphContextMenu';
import FlameGraphMetadata from './FlameGraphMetadata';
Expand All @@ -46,6 +46,7 @@ type Props = {
onSandwich: (label: string) => void;
onFocusPillClick: () => void;
onSandwichPillClick: () => void;
colorScheme: ColorScheme;
};

const FlameGraph = ({
Expand All @@ -62,6 +63,7 @@ const FlameGraph = ({
sandwichItem,
onFocusPillClick,
onSandwichPillClick,
colorScheme,
}: Props) => {
const styles = useStyles2(getStyles);

Expand Down Expand Up @@ -96,6 +98,7 @@ const FlameGraph = ({
search,
textAlign,
totalTicks,
colorScheme,
focusedItemData
);

Expand Down
@@ -0,0 +1,25 @@
import { createTheme } from '@grafana/data';

import { getBarColorByPackage, getBarColorByValue } from './colors';

describe('getBarColorByValue', () => {
it('converts value to color', () => {
expect(getBarColorByValue(1, 100, 0, 1).toHslString()).toBe('hsl(50, 100%, 65%)');
expect(getBarColorByValue(100, 100, 0, 1).toHslString()).toBe('hsl(0, 100%, 72%)');
expect(getBarColorByValue(10, 100, 0, 0.1).toHslString()).toBe('hsl(0, 100%, 72%)');
});
});

describe('getBarColorByPackage', () => {
it('converts package to color', () => {
const theme = createTheme();
const c = getBarColorByPackage('net/http.HandlerFunc.ServeHTTP', theme);
expect(c.toHslString()).toBe('hsl(246, 40%, 65%)');
// same package should have same color
expect(getBarColorByPackage('net/http.(*conn).serve', theme).toHslString()).toBe(c.toHslString());

expect(getBarColorByPackage('github.com/grafana/phlare/pkg/util.Log.Wrap.func1', theme).toHslString()).toBe(
'hsl(105, 40%, 76%)'
);
});
});
@@ -0,0 +1,95 @@
import color from 'tinycolor2';

import { GrafanaTheme2 } from '@grafana/data';

import murmurhash3_32_gc from './murmur3';

// Colors taken from pyroscope, they should be from Grafana originally, but I didn't find from where exactly.
const packageColors = [
color({ h: 24, s: 69, l: 60 }),
color({ h: 34, s: 65, l: 65 }),
color({ h: 194, s: 52, l: 61 }),
color({ h: 163, s: 45, l: 55 }),
color({ h: 211, s: 48, l: 60 }),
color({ h: 246, s: 40, l: 65 }),
color({ h: 305, s: 63, l: 79 }),
color({ h: 47, s: 100, l: 73 }),

color({ r: 183, g: 219, b: 171 }),
color({ r: 244, g: 213, b: 152 }),
color({ r: 78, g: 146, b: 249 }),
color({ r: 249, g: 186, b: 143 }),
color({ r: 242, g: 145, b: 145 }),
color({ r: 130, g: 181, b: 216 }),
color({ r: 229, g: 168, b: 226 }),
color({ r: 174, g: 162, b: 224 }),
color({ r: 154, g: 196, b: 138 }),
color({ r: 242, g: 201, b: 109 }),
color({ r: 101, g: 197, b: 219 }),
color({ r: 249, g: 147, b: 78 }),
color({ r: 234, g: 100, b: 96 }),
color({ r: 81, g: 149, b: 206 }),
color({ r: 214, g: 131, b: 206 }),
color({ r: 128, g: 110, b: 183 }),
];

const byValueMinColor = getBarColorByValue(1, 100, 0, 1);
const byValueMaxColor = getBarColorByValue(100, 100, 0, 1);
export const byValueGradient = `linear-gradient(90deg, ${byValueMinColor} 0%, ${byValueMaxColor} 100%)`;

// Handpicked some vaguely rainbow-ish colors
export const byPackageGradient = `linear-gradient(90deg, ${packageColors[0]} 0%, ${packageColors[2]} 30%, ${packageColors[6]} 50%, ${packageColors[7]} 70%, ${packageColors[8]} 100%)`;

export function getBarColorByValue(value: number, totalTicks: number, rangeMin: number, rangeMax: number) {
// / (rangeMax - rangeMin) here so when you click a bar it will adjust the top (clicked)bar to the most 'intense' color
const intensity = Math.min(1, value / totalTicks / (rangeMax - rangeMin));
const h = 50 - 50 * intensity;
const l = 65 + 7 * intensity;

return color({ h, s: 100, l });
}

export function getBarColorByPackage(label: string, theme: GrafanaTheme2) {
const packageName = getPackageName(label);
// TODO: similar thing happens in trace view with selecting colors of the spans, so maybe this could be unified.
const hash = murmurhash3_32_gc(packageName || '', 0);
const colorIndex = hash % packageColors.length;
let packageColor = packageColors[colorIndex];
if (theme.isLight) {
packageColor = packageColor.clone().brighten(15);
}
return packageColor;
}

// const getColors = memoizeOne((theme) => getFilteredColors(colors, theme));

// Different regexes to get the package name and function name from the label. We may at some point get an info about
// the language from the backend and use the right regex but right now we just try all of them from most to least
// specific.
const matchers = [
['phpspy', /^(?<packageName>(.*\/)*)(?<filename>.*\.php+)(?<line_info>.*)$/],
['pyspy', /^(?<packageName>(.*\/)*)(?<filename>.*\.py+)(?<line_info>.*)$/],
['rbspy', /^(?<packageName>(.*\/)*)(?<filename>.*\.rb+)(?<line_info>.*)$/],
[
'nodespy',
/^(\.\/node_modules\/)?(?<packageName>[^/]*)(?<filename>.*\.?(jsx?|tsx?)?):(?<functionName>.*):(?<line_info>.*)$/,
],
['gospy', /^(?<packageName>.*?\/.*?\.|.*?\.|.+)(?<functionName>.*)$/], // also 'scrape'
['javaspy', /^(?<packageName>.+\/)(?<filename>.+\.)(?<functionName>.+)$/],
['dotnetspy', /^(?<packageName>.+)\.(.+)\.(.+)\(.*\)$/],
['tracing', /^(?<packageName>.+?):.*$/],
['pyroscope-rs', /^(?<packageName>[^::]+)/],
['ebpfspy', /^(?<packageName>.+)$/],
['unknown', /^(?<packageName>.+)$/],
];

// Get the package name from the symbol. Try matchers from the list and return first one that matches.
function getPackageName(name: string): string | undefined {
for (const [_, matcher] of matchers) {
const match = name.match(matcher);
if (match) {
return match.groups?.packageName || '';
}
}
return undefined;
}
@@ -0,0 +1,84 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
/* eslint-disable @typescript-eslint/restrict-plus-operands */
/*
Copyright (c) 2011 Gary Court
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/* eslint-disable no-plusplus */
/* eslint-disable prefer-const */
/* eslint-disable no-bitwise */
/* eslint-disable camelcase */

export default function murmurhash3_32_gc(key: string, seed = 0) {
let remainder;
let bytes;
let h1;
let h1b;
let c1;
let c2;
let k1;
let i;

remainder = key.length & 3; // key.length % 4
bytes = key.length - remainder;
h1 = seed;
c1 = 0xcc9e2d51;
c2 = 0x1b873593;
i = 0;

while (i < bytes) {
k1 =
(key.charCodeAt(i) & 0xff) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;

k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;

h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b = ((h1 & 0xffff) * 5 + ((((h1 >>> 16) * 5) & 0xffff) << 16)) & 0xffffffff;
h1 = (h1b & 0xffff) + 0x6b64 + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16);
}

k1 = 0;

switch (remainder) {
case 3:
k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
// fall through
case 2:
k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
// fall through
case 1:
k1 ^= key.charCodeAt(i) & 0xff;
// fall through
default:
k1 = ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1;
}

h1 ^= key.length;

h1 ^= h1 >>> 16;
h1 = ((h1 & 0xffff) * 0x85ebca6b + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 13;
h1 = ((h1 & 0xffff) * 0xc2b2ae35 + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 16;

return h1 >>> 0;
}

0 comments on commit 608235d

Please sign in to comment.