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

Replace plotly line chart with pf-react area chart #1448

Merged
Merged
Show file tree
Hide file tree
Changes from all 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 frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
},
"dependencies": {
"@patternfly/patternfly": "1.0.219",
"@patternfly/react-charts": "^3.4.5",
"@patternfly/react-core": "2.4.1",
"brace": "0.11.x",
"classnames": "2.x",
Expand Down
7 changes: 7 additions & 0 deletions frontend/public/components/app.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,13 @@ class App extends React.PureComponent {
}

_onNavToggle() {

// Some components, like svg charts, need to reflow when nav is toggled.
// Fire event after a short delay to allow nav animation to complete.
setTimeout(() => {
window.dispatchEvent(new Event('nav_toggle'));
}, 100);
TheRealJon marked this conversation as resolved.
Show resolved Hide resolved

this.setState(prevState => {
return {
isNavOpen: !prevState.isNavOpen,
Expand Down
10 changes: 5 additions & 5 deletions frontend/public/components/build.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import { K8sResourceKindReference, referenceFor, K8sResourceKind } from '../modu
import { cloneBuild, formatBuildDuration, BuildPhase, getBuildNumber } from '../module/k8s/builds';
import { ColHead, DetailsPage, List, ListHeader, ListPage } from './factory';
import { errorModal } from './modals';
import { BuildHooks, BuildStrategy, Kebab, SectionHeading, history, navFactory, ResourceKebab, ResourceLink, resourceObjPath, ResourceSummary, Timestamp, AsyncComponent, resourcePath, StatusIcon } from './utils';
import { BuildHooks, BuildStrategy, Kebab, SectionHeading, history, navFactory, ResourceKebab, ResourceLink, resourceObjPath, ResourceSummary, Timestamp, AsyncComponent, resourcePath, StatusIcon, humanizeDecimalBytes, humanizeCpuCores } from './utils';
import { BuildPipeline, BuildPipelineLogLink } from './build-pipeline';
import { breadcrumbsForOwnerRefs } from './utils/breadcrumbs';
import { fromNow } from './utils/datetime';
import { BuildLogs } from './build-logs';
import { ResourceEventStream } from './events';
import { Line, requirePrometheus } from './graphs';
import { Area, requirePrometheus } from './graphs';

const BuildsReference: K8sResourceKindReference = 'Build';

Expand Down Expand Up @@ -92,13 +92,13 @@ const BuildGraphs = requirePrometheus(({build}) => {
return <React.Fragment>
<div className="row">
<div className="col-md-4">
<Line title="Memory Usage" namespace={namespace} query={`pod_name:container_memory_usage_bytes:sum{pod_name='${podName}',container_name='',namespace='${namespace}'}`} />
<Area title="Memory Usage" humanizeValue={humanizeDecimalBytes} namespace={namespace} query={`pod_name:container_memory_usage_bytes:sum{pod_name='${podName}',container_name='',namespace='${namespace}'}`} />
</div>
<div className="col-md-4">
<Line title="CPU Usage" namespace={namespace} query={`pod_name:container_cpu_usage:sum{pod_name='${podName}',container_name='',namespace='${namespace}'}`} />
<Area title="CPU Usage" humanizeValue={humanizeCpuCores} namespace={namespace} query={`pod_name:container_cpu_usage:sum{pod_name='${podName}',container_name='',namespace='${namespace}'}`} />
</div>
<div className="col-md-4">
<Line title="Filesystem" namespace={namespace} query={`pod_name:container_fs_usage_bytes:sum{pod_name='${podName}',container_name='',namespace='${namespace}'}`} />
<Area title="Filesystem" humanizeValue={humanizeDecimalBytes} namespace={namespace} query={`pod_name:container_fs_usage_bytes:sum{pod_name='${podName}',container_name='',namespace='${namespace}'}`} />
</div>
</div>

Expand Down
14 changes: 11 additions & 3 deletions frontend/public/components/graphs/_graphs.scss
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,27 @@
padding-top: 15px; // So graph title doesn't abut border
margin-top: 0;
margin-bottom: 16px;
overflow: hidden;
overflow: visible; // Tooltips may overflow
}

.graph-wrapper svg {
overflow: visible !important; // Tooltips may overflow
}

.graph-title {
margin: 0;
text-align: center;
margin: 0 0 10px 0;
color: black;
overflow: hidden;
text-overflow: ellipsis;
text-align: center;
white-space: nowrap;
line-height: 1.4; // so descenders don't clip
}

.graph-title--left {
text-align: left;
}

.query-browser__wrapper {
border: 1px solid $color-grey-background-border;
margin: 0 0 20px 0;
Expand Down
67 changes: 67 additions & 0 deletions frontend/public/components/graphs/area.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import * as _ from 'lodash-es';
import * as React from 'react';
import { Chart, ChartArea, ChartVoronoiContainer, ChartAxis, ChartTheme, ChartGroup } from '@patternfly/react-charts';

import { humanizeNumber } from '../utils';
import { twentyFourHourTime } from '../utils/datetime';
import { areaStyles, cartesianChartStyles } from './themes';
import { useRefWidth } from '../utils/use-ref-width';
import { usePrometheusPoll, PrometheusQuery } from './use-prometheus-poll';
import { PrometheusGraph } from './prometheus-graph';

export const Area: React.FC<AreaProps> = ({
basePath,
className,
height = 90,
humanizeTime = twentyFourHourTime,
humanizeValue = humanizeNumber,
namespace,
numSamples,
query,
theme = ChartTheme.light.multi,
tickCount = 3,
timeout,
timeSpan,
title,
}) => {
const [containerRef, width] = useRefWidth();
const [data] = usePrometheusPoll({basePath, namespace, numSamples, query, timeout, timeSpan, defaultQueryName: title});
TheRealJon marked this conversation as resolved.
Show resolved Hide resolved
// Override theme. Once PF React Charts is released and we update, there should be much less we need to override here.
const _theme = _.merge(theme, cartesianChartStyles, areaStyles);
const getLabel = ({name, y}) => (data.length > 1) ? `${name}: ${humanizeValue(y)}` : humanizeValue(y);
const container = <ChartVoronoiContainer voronoiDimension="x" labels={getLabel} />;
return <PrometheusGraph className={className} query={query} title={title} >
<div ref={containerRef} style={{width: '100%'}}>
<Chart
containerComponent={container}
domainPadding={{y: 20}}
height={height}
width={width}
theme={_theme}
scale={{x: 'time', y: 'linear'}}
>
<ChartAxis tickCount={tickCount} tickFormat={humanizeTime} />
<ChartAxis dependentAxis tickCount={tickCount} tickFormat={humanizeValue} />
<ChartGroup>
{ _.map(data, (values, i) => <ChartArea key={i} data={values} />) }
</ChartGroup>
</Chart>
</div>
</PrometheusGraph>;
};

type AreaProps = {
basePath: string;
className: string;
height: number,
humanizeTime: (date: Date) => string;
humanizeValue: (value: string | number) => string;
namespace: string;
numSamples: number;
query: PrometheusQuery[] | string;
theme: any;
tickCount: number;
timeout: number;
timeSpan: number;
title: string;
}
1 change: 1 addition & 0 deletions frontend/public/components/graphs/graph-loader.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { Bar } from './bar';
export { Gauge } from './gauge';
export { Area } from './area';
export { Line } from './line';
export { QueryBrowser } from './query-browser';
export { Donut } from './donut';
5 changes: 3 additions & 2 deletions frontend/public/components/graphs/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ export const prometheusBasePath = window.SERVER_FLAGS.prometheusBaseURL;
export const prometheusTenancyBasePath = window.SERVER_FLAGS.prometheusTenancyBaseURL;
export const alertManagerBasePath = window.SERVER_FLAGS.alertManagerBaseURL;

export const QueryBrowser = props => <AsyncComponent loader={() => import('./graph-loader').then(c => c.QueryBrowser)} {...props} />;
export const Area = props => <AsyncComponent loader={() => import('./graph-loader').then(c => c.Area)} {...props} />;
export const Bar = props => <AsyncComponent loader={() => import('./graph-loader').then(c => c.Bar)} {...props} />;
export const Donut = props => <AsyncComponent loader={() => import('./graph-loader').then(c => c.Donut)} {...props} />;
export const Gauge = props => <AsyncComponent loader={() => import('./graph-loader').then(c => c.Gauge)} {...props} />;
export const Line = props => <AsyncComponent loader={() => import('./graph-loader').then(c => c.Line)} {...props} />;
export const Donut = props => <AsyncComponent loader={() => import('./graph-loader').then(c => c.Donut)} {...props} />;
export const QueryBrowser = props => <AsyncComponent loader={() => import('./graph-loader').then(c => c.QueryBrowser)} {...props} />;

const canAccessPrometheus = (prometheusFlag) => prometheusFlag && !!prometheusBasePath && !!prometheusTenancyBasePath;

Expand Down
63 changes: 63 additions & 0 deletions frontend/public/components/graphs/prometheus-graph.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/* eslint-disable no-undef, no-unused-vars */
import * as _ from 'lodash-es';
import * as React from 'react';
import * as classNames from 'classnames';

import { connectToURLs, MonitoringRoutes } from '../../monitoring';

const getPrometheusUrl = (urls: string[], query: PrometheusQuery[] | string): string => {
const base = urls && urls[MonitoringRoutes.Prometheus];
if (!base || !query) {
return null;
}

const queries = _.isArray(query) ? query : [{query}];
spadgett marked this conversation as resolved.
Show resolved Hide resolved
const params = new URLSearchParams();
_.each(queries, (q, i) => {
params.set(`g${i}.range_input`, '1h');
params.set(`g${i}.expr`, q.query);
params.set(`g${i}.tab`, '0');
});

return `${base}/graph?${params.toString()}`;
};

const PrometheusGraphLink = connectToURLs(MonitoringRoutes.Prometheus)(
({children, query, urls}: React.PropsWithChildren<PrometheusGraphLinkProps>) => {
const url = getPrometheusUrl(urls, query);
return <React.Fragment>
{
url
? <a href={url} target="_blank" rel="noopener noreferrer" style={{ textDecoration: 'none' }}>
{children}
</a>
: {children}
}
</React.Fragment>;
}
);

export const PrometheusGraph: React.FunctionComponent<PrometheusGraphProps> = ({children, title, className, query}) => {
return <div className={classNames('graph-wrapper', className)}>
{ title && <h5 className="graph-title graph-title--left">{title}</h5> }
<PrometheusGraphLink query={query}>
{children}
</PrometheusGraphLink>
</div>;
};

type PrometheusQuery = {
name: string;
query: string;
};

type PrometheusGraphLinkProps = {
query: PrometheusQuery[] | string;
urls?: string[];
};

type PrometheusGraphProps = {
className?: string;
query: PrometheusQuery[] | string;
title?: string;
}
75 changes: 75 additions & 0 deletions frontend/public/components/graphs/themes.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/* eslint-disable camelcase */

import { global_FontFamily_sans_serif } from '@patternfly/react-tokens';

const independentAxisStyles = {
independentAxis: {
style: {
axis: { stroke: '#D1D1D1' },
tickLabels: { fontFamily: global_FontFamily_sans_serif.value },
},
},
};

const dependentAxisStyles = {
dependentAxis: {
style: {
axis: { stroke: '#D1D1D1' },
grid: { stroke: '#EDEDED' },
tickLabels: { fontFamily: global_FontFamily_sans_serif.value },
},
},
};

const tooltipStyles = {
// General tooltip style
tooltip: {
flyoutStyle: {
fill: '#151515',
},
style: {
labels: {
fontFamily: global_FontFamily_sans_serif.value,
fill: '#FFF',
},
},
},

// Voronoi container tooltip theme, overrides general tooltip style
voronoi: {
style: {
flyout: {
fill: '#151515',
},
labels: {
fontFamily: global_FontFamily_sans_serif.value,
fill: '#FFF',
},
},
},
};

export const areaStyles = {
area: {
style: {
data: {
labels: global_FontFamily_sans_serif.value,
fillOpacity: .15,
},
},
},
};

export const cartesianChartStyles = {
chart: {
padding: {
bottom: 30,
left: 60,
right: 0,
top: 0,
},
},
...independentAxisStyles,
...dependentAxisStyles,
...tooltipStyles,
};
82 changes: 82 additions & 0 deletions frontend/public/components/graphs/use-prometheus-poll.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import * as _ from 'lodash-es';
import { useEffect, useRef } from 'react';
import { prometheusTenancyBasePath, prometheusBasePath } from '.';
import { coFetchJSON } from '../../co-fetch';
import { useSafetyFirst } from '../safety-first';

// TODO This effect only handles polling prometheus data range queries. For now,
// area charts are the only component using this, so that's okay, but will need
// to be expanded to handle singular vector queries as well.
export const usePrometheusPoll = ({
basePath,
defaultQueryName = '',
namespace,
numSamples,
query,
timeout,
timeSpan = 60 * 60 * 1000,
}: PrometheusPollProps ) => {
const [data, setData] = useSafetyFirst([]);
const interval = useRef(null);

useEffect(() => {
const fetch = () => {
const end = Date.now();
const start = end - timeSpan;
const baseUrl = basePath || (namespace ? prometheusTenancyBasePath : prometheusBasePath);
const pollFrequency = Math.max(timeSpan / 120, 3000); // Update every 3 seconds at most
const stepSize = (numSamples ? (timeSpan / numSamples) : pollFrequency) / 1000;
const timeoutParam = timeout ? `&timeout=${encodeURIComponent(timeout.toString())}` : '';
const queries = !_.isArray(query) ? [{query, name: defaultQueryName}] : query;
const promises = queries.map(q => {
const nsParam = namespace ? `&namespace=${encodeURIComponent(namespace)}` : '';
const url = `${baseUrl}/api/v1/query_range?query=${encodeURIComponent(q.query)}&start=${start / 1000}&end=${end / 1000}&step=${stepSize}${nsParam}${timeoutParam}`;
return coFetchJSON(url).then(result => {
const values = _.get(result, 'data.result[0].values');
return _.map(values, v => ({
name: q.name,
x: new Date(v[0] * 1000),
y: parseFloat(v[1]),
}));
});
});
Promise.all(promises)
.then(d => setData(d))
/* eslint-disable-next-line no-console */
.catch(e => console.warn(`Error retrieving Prometheus data: ${e}`))
.then(() => {
interval.current = setTimeout(fetch, pollFrequency);
});
};

if (query) {
fetch();
}
return () => {
clearInterval(interval.current);
};
}, [basePath, defaultQueryName, namespace, numSamples, query, timeout, timeSpan, setData]);

return [data] as [GraphDataPoint[][]];
};

export type PrometheusQuery = {
name: string;
query: string;
};

type PrometheusPollProps = {
basePath?: string;
defaultQueryName?: string;
namespace?: string;
numSamples?: number;
query: PrometheusQuery[] | string;
timeout?: number;
timeSpan?: number;
}

type GraphDataPoint = {
name?: string;
x: Date;
y: number;
};
Loading