Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[APM] Service maps layout enhancements #76481

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions x-pack/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@
"concat-stream": "1.6.2",
"content-disposition": "0.5.3",
"cytoscape": "^3.10.0",
"cytoscape-dagre": "^2.2.2",
"d3-array": "1.2.4",
"dedent": "^0.7.0",
"del": "^5.1.0",
Expand Down
88 changes: 32 additions & 56 deletions x-pack/plugins/apm/public/components/app/ServiceMap/Cytoscape.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import React, {
useState,
} from 'react';
import cytoscape from 'cytoscape';
import dagre from 'cytoscape-dagre';
import { debounce } from 'lodash';
import { useTheme } from '../../../hooks/useTheme';
import {
Expand All @@ -22,6 +23,8 @@ import {
} from './cytoscapeOptions';
import { useUiTracker } from '../../../../../observability/public';

cytoscape.use(dagre);

export const CytoscapeContext = createContext<cytoscape.Core | undefined>(
undefined
);
Expand All @@ -30,7 +33,6 @@ interface CytoscapeProps {
children?: ReactNode;
elements: cytoscape.ElementDefinition[];
height: number;
width: number;
serviceName?: string;
style?: CSSProperties;
}
Expand All @@ -57,59 +59,42 @@ function useCytoscape(options: cytoscape.CytoscapeOptions) {
return [ref, cy] as [React.MutableRefObject<any>, cytoscape.Core | undefined];
}

function rotatePoint(
{ x, y }: { x: number; y: number },
degreesRotated: number
) {
const radiansPerDegree = Math.PI / 180;
const θ = radiansPerDegree * degreesRotated;
const cosθ = Math.cos(θ);
const sinθ = Math.sin(θ);
return {
x: x * cosθ - y * sinθ,
y: x * sinθ + y * cosθ,
};
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No more custom calculations? Feels good!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah the new layout supports left->right rank direction out of the box!


function getLayoutOptions(
selectedRoots: string[],
height: number,
width: number,
nodeHeight: number
): cytoscape.LayoutOptions {
function getLayoutOptions(nodeHeight: number): cytoscape.LayoutOptions {
return {
name: 'breadthfirst',
// @ts-ignore DefinitelyTyped is incorrect here. Roots can be an Array
roots: selectedRoots.length ? selectedRoots : undefined,
name: 'dagre',
fit: true,
padding: nodeHeight,
spacingFactor: 1.2,
// @ts-ignore
// Rotate nodes counter-clockwise to transform layout from top→bottom to left→right.
// The extra 5° achieves the effect of separating overlapping taxi-styled edges.
transform: (node: any, pos: cytoscape.Position) => rotatePoint(pos, -95),
// swap width/height of boundingBox to compensate for the rotation
boundingBox: { x1: 0, y1: 0, w: height, h: width },
nodeSep: nodeHeight,
edgeSep: 32,
rankSep: 128,
rankDir: 'LR',
ranker: 'network-simplex',
};
}

function selectRoots(cy: cytoscape.Core): string[] {
const bfs = cy.elements().bfs({
roots: cy.elements().leaves(),
function applyCubicBezierStyles(edges: cytoscape.EdgeCollection) {
edges.forEach((edge) => {
const { x: x0, y: y0 } = edge.source().position();
const { x: x1, y: y1 } = edge.target().position();
const x = x1 - x0;
const y = y1 - y0;
const z = Math.sqrt(x * x + y * y);
const costheta = z === 0 ? 0 : x / z;
const alpha = 0.25;
edge.style('control-point-distances', [
-alpha * y * costheta,
alpha * y * costheta,
]);
edge.style('control-point-weights', [alpha, 1 - alpha]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a comment to this section what this is doing?

});
const furthestNodeFromLeaves = bfs.path.last();
return cy
.elements()
.roots()
.union(furthestNodeFromLeaves)
.map((el) => el.id());
}

export function Cytoscape({
children,
elements,
height,
width,
serviceName,
style,
}: CytoscapeProps) {
Expand Down Expand Up @@ -151,13 +136,7 @@ export function Cytoscape({
} else {
resetConnectedEdgeStyle();
}

const selectedRoots = selectRoots(event.cy);
const layout = cy.layout(
getLayoutOptions(selectedRoots, height, width, nodeHeight)
);

layout.run();
cy.layout(getLayoutOptions(nodeHeight)).run();
}
};
let layoutstopDelayTimeout: NodeJS.Timeout;
Expand All @@ -180,6 +159,7 @@ export function Cytoscape({
event.cy.fit(undefined, nodeHeight);
}
}, 0);
applyCubicBezierStyles(event.cy.edges());
};
// debounce hover tracking so it doesn't spam telemetry with redundant events
const trackNodeEdgeHover = debounce(
Expand Down Expand Up @@ -211,6 +191,9 @@ export function Cytoscape({
console.debug('cytoscape:', event);
}
};
const dragHandler: cytoscape.EventHandler = (event) => {
applyCubicBezierStyles(event.target.connectedEdges());
};

if (cy) {
cy.on('data layoutstop select unselect', debugHandler);
Expand All @@ -220,6 +203,7 @@ export function Cytoscape({
cy.on('mouseout', 'edge, node', mouseoutHandler);
cy.on('select', 'node', selectHandler);
cy.on('unselect', 'node', unselectHandler);
cy.on('drag', 'node', dragHandler);

cy.remove(cy.elements());
cy.add(elements);
Expand All @@ -239,19 +223,11 @@ export function Cytoscape({
cy.removeListener('mouseout', 'edge, node', mouseoutHandler);
cy.removeListener('select', 'node', selectHandler);
cy.removeListener('unselect', 'node', unselectHandler);
cy.removeListener('drag', 'node', dragHandler);
}
clearTimeout(layoutstopDelayTimeout);
};
}, [
cy,
elements,
height,
serviceName,
trackApmEvent,
width,
nodeHeight,
theme,
]);
}, [cy, elements, height, serviceName, trackApmEvent, nodeHeight, theme]);

return (
<CytoscapeContext.Provider value={cy}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,15 @@ export function Popover({ focusedServiceName }: PopoverProps) {
cy.on('select', 'node', selectHandler);
cy.on('unselect', 'node', deselect);
cy.on('data viewport', deselect);
cy.on('drag', 'node', deselect);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will dragging cause the popover to show for a brief period of time? Or will it not be displayed at all?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Node dragging doesn't trigger the select event, so it won't display the popover at all.

}

return () => {
if (cy) {
cy.removeListener('select', 'node', selectHandler);
cy.removeListener('unselect', 'node', deselect);
cy.removeListener('data viewport', undefined, deselect);
cy.removeListener('drag', 'node', deselect);
}
};
}, [cy, deselect]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,11 @@ storiesOf('app/ServiceMap/Cytoscape', module)
},
];
const height = 300;
const width = 1340;
const serviceName = 'opbeans-python';
return (
<Cytoscape
elements={elements}
height={height}
width={width}
serviceName={serviceName}
/>
);
Expand Down Expand Up @@ -330,7 +328,7 @@ storiesOf('app/ServiceMap/Cytoscape', module)
},
},
];
return <Cytoscape elements={elements} height={600} width={1340} />;
return <Cytoscape elements={elements} height={600} />;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did we hardcode the width in the first place? And why is it no longer needed? (same question about height)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, this is for storybook. Then it's not a big deal 👍

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did we hardcode the width in the first place? And why is it no longer needed? (same question about height)

The width was needed to define the boundingBox of the previous layout. This option isn't necessary with the new layout, so i was able to remove it. height is still necessary to set the root div height (which is always full width).

},
{
info: { propTables: false, source: false },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ function setSessionJson(json: string) {
window.sessionStorage.setItem(SESSION_STORAGE_KEY, json);
}

const getCytoscapeHeight = () => window.innerHeight - 300;

storiesOf(STORYBOOK_PATH, module)
.addDecorator((storyFn) => <EuiThemeProvider>{storyFn()}</EuiThemeProvider>)
.add(
Expand All @@ -43,16 +45,17 @@ storiesOf(STORYBOOK_PATH, module)
const [size, setSize] = useState<number>(10);
const [json, setJson] = useState<string>('');
const [elements, setElements] = useState<any[]>(
generateServiceMapElements(size)
generateServiceMapElements({ size, hasAnomalies: true })
);

return (
<div>
<EuiFlexGroup>
<EuiFlexItem>
<EuiButton
onClick={() => {
setElements(generateServiceMapElements(size));
setElements(
generateServiceMapElements({ size, hasAnomalies: true })
);
setJson('');
}}
>
Expand All @@ -79,7 +82,7 @@ storiesOf(STORYBOOK_PATH, module)
</EuiFlexItem>
</EuiFlexGroup>

<Cytoscape elements={elements} height={600} width={1340} />
<Cytoscape elements={elements} height={getCytoscapeHeight()} />

{json && (
<EuiCodeEditor
Expand Down Expand Up @@ -121,7 +124,7 @@ storiesOf(STORYBOOK_PATH, module)

return (
<div>
<Cytoscape elements={elements} height={600} width={1340} />
<Cytoscape elements={elements} height={getCytoscapeHeight()} />
<EuiForm isInvalid={error !== undefined} error={error}>
<EuiFlexGroup>
<EuiFlexItem>
Expand Down Expand Up @@ -204,8 +207,7 @@ storiesOf(STORYBOOK_PATH, module)
<div>
<Cytoscape
elements={exampleResponseTodo.elements}
height={600}
width={1340}
height={getCytoscapeHeight()}
/>
</div>
);
Expand All @@ -224,8 +226,7 @@ storiesOf(STORYBOOK_PATH, module)
<div>
<Cytoscape
elements={exampleResponseOpbeansBeats.elements}
height={600}
width={1340}
height={getCytoscapeHeight()}
/>
</div>
);
Expand All @@ -244,8 +245,7 @@ storiesOf(STORYBOOK_PATH, module)
<div>
<Cytoscape
elements={exampleResponseHipsterStore.elements}
height={600}
width={1340}
height={getCytoscapeHeight()}
/>
</div>
);
Expand All @@ -264,8 +264,7 @@ storiesOf(STORYBOOK_PATH, module)
<div>
<Cytoscape
elements={exampleResponseOneDomainManyIPs.elements}
height={600}
width={1340}
height={getCytoscapeHeight()}
/>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { getSeverity } from '../Popover/getSeverity';

export function generateServiceMapElements(size: number): any[] {
export function generateServiceMapElements({
size,
hasAnomalies,
}: {
size: number;
hasAnomalies: boolean;
}): any[] {
const services = range(size).map((i) => {
const name = getName();
const anomalyScore = randn(101);
Expand All @@ -15,11 +19,14 @@ export function generateServiceMapElements(size: number): any[] {
'service.environment': 'production',
'service.name': name,
'agent.name': getAgentName(),
anomaly_score: anomalyScore,
anomaly_severity: getSeverity(anomalyScore),
actual_value: Math.random() * 2000000,
typical_value: Math.random() * 1000000,
ml_job_id: `${name}-request-high_mean_response_time`,
serviceAnomalyStats: hasAnomalies
? {
transactionType: 'request',
anomalyScore,
actualValue: Math.random() * 2000000,
jobId: `${name}-request-high_mean_response_time`,
}
: undefined,
};
});

Expand Down Expand Up @@ -146,7 +153,7 @@ const NAMES = [
'leech',
'loki',
'longshot',
'lumpkin,',
'lumpkin',
'madame-web',
'magician',
'magneto',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,7 @@ const getStyle = (theme: EuiTheme): cytoscape.Stylesheet[] => {
{
selector: 'edge',
style: {
'curve-style': 'taxi',
// @ts-ignore
'taxi-direction': 'auto',
'curve-style': 'unbundled-bezier',
'line-color': lineColor,
'overlay-opacity': 0,
'target-arrow-color': lineColor,
Expand Down Expand Up @@ -264,7 +262,6 @@ ${theme.eui.euiColorLightShade}`,
export const getCytoscapeOptions = (
theme: EuiTheme
): cytoscape.CytoscapeOptions => ({
autoungrabify: true,
boxSelectionEnabled: false,
maxZoom: 3,
minZoom: 0.2,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export function ServiceMap({ serviceName }: ServiceMapProps) {
}
}, [license, serviceName, urlParams]);

const { ref, height, width } = useRefDimensions();
const { ref, height } = useRefDimensions();

useTrackPageview({ app: 'apm', path: 'service_map' });
useTrackPageview({ app: 'apm', path: 'service_map', delay: 15000 });
Expand All @@ -78,7 +78,6 @@ export function ServiceMap({ serviceName }: ServiceMapProps) {
height={height}
serviceName={serviceName}
style={getCytoscapeDivStyle(theme)}
width={width}
>
<Controls />
<BetaBadge />
Expand Down
7 changes: 7 additions & 0 deletions x-pack/plugins/apm/typings/cytoscape_dagre.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

declare module 'cytoscape-dagre';
Loading