metricChart.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. import * as React from 'react';
  2. import {withRouter} from 'react-router';
  3. import {WithRouterProps} from 'react-router/lib/withRouter';
  4. import styled from '@emotion/styled';
  5. import color from 'color';
  6. import moment from 'moment';
  7. import momentTimezone from 'moment-timezone';
  8. import {Client} from 'app/api';
  9. import Feature from 'app/components/acl/feature';
  10. import Button from 'app/components/button';
  11. import ChartZoom from 'app/components/charts/chartZoom';
  12. import Graphic from 'app/components/charts/components/graphic';
  13. import MarkArea from 'app/components/charts/components/markArea';
  14. import MarkLine from 'app/components/charts/components/markLine';
  15. import EventsRequest from 'app/components/charts/eventsRequest';
  16. import LineChart, {LineChartSeries} from 'app/components/charts/lineChart';
  17. import {SectionHeading} from 'app/components/charts/styles';
  18. import {
  19. parseStatsPeriod,
  20. StatsPeriodType,
  21. } from 'app/components/organizations/globalSelectionHeader/getParams';
  22. import {Panel, PanelBody, PanelFooter} from 'app/components/panels';
  23. import Placeholder from 'app/components/placeholder';
  24. import {IconCheckmark, IconFire, IconWarning} from 'app/icons';
  25. import {t} from 'app/locale';
  26. import ConfigStore from 'app/stores/configStore';
  27. import space from 'app/styles/space';
  28. import {AvatarProject, DateString, Organization, Project} from 'app/types';
  29. import {ReactEchartsRef} from 'app/types/echarts';
  30. import {getUtcDateString} from 'app/utils/dates';
  31. import theme from 'app/utils/theme';
  32. import {alertDetailsLink} from 'app/views/alerts/details';
  33. import {makeDefaultCta} from 'app/views/alerts/incidentRules/incidentRulePresets';
  34. import {IncidentRule} from 'app/views/alerts/incidentRules/types';
  35. import {AlertWizardAlertNames} from 'app/views/alerts/wizard/options';
  36. import {getAlertTypeFromAggregateDataset} from 'app/views/alerts/wizard/utils';
  37. import {Incident, IncidentActivityType, IncidentStatus} from '../../types';
  38. import {TimePeriodType} from './constants';
  39. const X_AXIS_BOUNDARY_GAP = 20;
  40. const VERTICAL_PADDING = 22;
  41. type Props = WithRouterProps & {
  42. api: Client;
  43. rule: IncidentRule;
  44. incidents?: Incident[];
  45. timePeriod: TimePeriodType;
  46. selectedIncident?: Incident | null;
  47. organization: Organization;
  48. projects: Project[] | AvatarProject[];
  49. interval: string;
  50. filter: React.ReactNode;
  51. query: string;
  52. orgId: string;
  53. handleZoom: (start: DateString, end: DateString) => void;
  54. };
  55. type State = {
  56. width: number;
  57. height: number;
  58. };
  59. function formatTooltipDate(date: moment.MomentInput, format: string): string {
  60. const {
  61. options: {timezone},
  62. } = ConfigStore.get('user');
  63. return momentTimezone.tz(date, timezone).format(format);
  64. }
  65. function createThresholdSeries(lineColor: string, threshold: number): LineChartSeries {
  66. return {
  67. seriesName: 'Threshold Line',
  68. type: 'line',
  69. markLine: MarkLine({
  70. silent: true,
  71. lineStyle: {color: lineColor, type: 'dashed', width: 1},
  72. data: [{yAxis: threshold} as any],
  73. label: {
  74. show: false,
  75. },
  76. }),
  77. data: [],
  78. };
  79. }
  80. function createStatusAreaSeries(
  81. lineColor: string,
  82. startTime: number,
  83. endTime: number
  84. ): LineChartSeries {
  85. return {
  86. seriesName: 'Status Area',
  87. type: 'line',
  88. markLine: MarkLine({
  89. silent: true,
  90. lineStyle: {color: lineColor, type: 'solid', width: 4},
  91. data: [[{coord: [startTime, 0]}, {coord: [endTime, 0]}] as any],
  92. }),
  93. data: [],
  94. };
  95. }
  96. function createIncidentSeries(
  97. router: Props['router'],
  98. organization: Organization,
  99. lineColor: string,
  100. incidentTimestamp: number,
  101. incident: Incident,
  102. dataPoint?: LineChartSeries['data'][0],
  103. seriesName?: string
  104. ) {
  105. const series = {
  106. seriesName: 'Incident Line',
  107. type: 'line',
  108. markLine: MarkLine({
  109. silent: false,
  110. lineStyle: {color: lineColor, type: 'solid'},
  111. data: [
  112. {
  113. xAxis: incidentTimestamp,
  114. onClick: () => {
  115. router.push({
  116. pathname: alertDetailsLink(organization, incident),
  117. query: {alert: incident.identifier},
  118. });
  119. },
  120. },
  121. ] as any,
  122. label: {
  123. show: incident.identifier,
  124. position: 'insideEndBottom',
  125. formatter: incident.identifier,
  126. color: lineColor,
  127. fontSize: 10,
  128. fontFamily: 'Rubik',
  129. } as any,
  130. }),
  131. data: [],
  132. };
  133. // tooltip conflicts with MarkLine types
  134. (series.markLine as any).tooltip = {
  135. trigger: 'item',
  136. alwaysShowContent: true,
  137. formatter: ({value, marker}) => {
  138. const time = formatTooltipDate(moment(value), 'MMM D, YYYY LT');
  139. return [
  140. `<div class="tooltip-series"><div>`,
  141. `<span class="tooltip-label">${marker} <strong>${t('Alert')} #${
  142. incident.identifier
  143. }</strong></span>${seriesName} ${dataPoint?.value?.toLocaleString()}`,
  144. `</div></div>`,
  145. `<div class="tooltip-date">${time}</div>`,
  146. `<div class="tooltip-arrow"></div>`,
  147. ].join('');
  148. },
  149. };
  150. return series;
  151. }
  152. class MetricChart extends React.PureComponent<Props, State> {
  153. state = {
  154. width: -1,
  155. height: -1,
  156. };
  157. ref: null | ReactEchartsRef = null;
  158. /**
  159. * Syncs component state with the chart's width/heights
  160. */
  161. updateDimensions = () => {
  162. const chartRef = this.ref?.getEchartsInstance?.();
  163. if (!chartRef) {
  164. return;
  165. }
  166. const width = chartRef.getWidth();
  167. const height = chartRef.getHeight();
  168. if (width !== this.state.width || height !== this.state.height) {
  169. this.setState({
  170. width,
  171. height,
  172. });
  173. }
  174. };
  175. handleRef = (ref: ReactEchartsRef): void => {
  176. if (ref && !this.ref) {
  177. this.ref = ref;
  178. this.updateDimensions();
  179. }
  180. if (!ref) {
  181. this.ref = null;
  182. }
  183. };
  184. getRuleChangeThresholdElements = (data: LineChartSeries[]): any[] => {
  185. const {height, width} = this.state;
  186. const {dateModified} = this.props.rule || {};
  187. if (!data.length || !data[0].data.length || !dateModified) {
  188. return [];
  189. }
  190. const seriesData = data[0].data;
  191. const seriesStart = seriesData[0].name as number;
  192. const seriesEnd = seriesData[seriesData.length - 1].name as number;
  193. const ruleChanged = moment(dateModified).valueOf();
  194. if (ruleChanged < seriesStart) {
  195. return [];
  196. }
  197. const chartWidth = width - X_AXIS_BOUNDARY_GAP;
  198. const position =
  199. X_AXIS_BOUNDARY_GAP +
  200. Math.round((chartWidth * (ruleChanged - seriesStart)) / (seriesEnd - seriesStart));
  201. return [
  202. {
  203. type: 'line',
  204. draggable: false,
  205. position: [position, 0],
  206. shape: {y1: 0, y2: height - VERTICAL_PADDING, x1: 1, x2: 1},
  207. style: {
  208. stroke: theme.gray200,
  209. },
  210. },
  211. {
  212. type: 'rect',
  213. draggable: false,
  214. position: [X_AXIS_BOUNDARY_GAP, 0],
  215. shape: {
  216. // +1 makes the gray area go midway onto the dashed line above
  217. width: position - X_AXIS_BOUNDARY_GAP + 1,
  218. height: height - VERTICAL_PADDING,
  219. },
  220. style: {
  221. fill: color(theme.gray100).alpha(0.42).rgb().string(),
  222. },
  223. },
  224. ];
  225. };
  226. renderChartActions(
  227. totalDuration: number,
  228. criticalDuration: number,
  229. warningDuration: number
  230. ) {
  231. const {rule, orgId, projects, timePeriod, query} = this.props;
  232. const ctaOpts = {
  233. orgSlug: orgId,
  234. projects: projects as Project[],
  235. rule,
  236. eventType: query,
  237. start: timePeriod.start,
  238. end: timePeriod.end,
  239. };
  240. const {buttonText, ...props} = makeDefaultCta(ctaOpts);
  241. const resolvedPercent = (
  242. (100 * Math.max(totalDuration - criticalDuration - warningDuration, 0)) /
  243. totalDuration
  244. ).toFixed(2);
  245. const criticalPercent = (100 * Math.min(criticalDuration / totalDuration, 1)).toFixed(
  246. 2
  247. );
  248. const warningPercent = (100 * Math.min(warningDuration / totalDuration, 1)).toFixed(
  249. 2
  250. );
  251. return (
  252. <ChartActions>
  253. <ChartSummary>
  254. <SummaryText>{t('SUMMARY')}</SummaryText>
  255. <SummaryStats>
  256. <StatItem>
  257. <IconCheckmark color="green300" isCircled />
  258. <StatCount>{resolvedPercent}%</StatCount>
  259. </StatItem>
  260. <StatItem>
  261. <IconWarning color="yellow300" />
  262. <StatCount>{warningPercent}%</StatCount>
  263. </StatItem>
  264. <StatItem>
  265. <IconFire color="red300" />
  266. <StatCount>{criticalPercent}%</StatCount>
  267. </StatItem>
  268. </SummaryStats>
  269. </ChartSummary>
  270. <Feature features={['discover-basic']}>
  271. <Button size="small" {...props}>
  272. {buttonText}
  273. </Button>
  274. </Feature>
  275. </ChartActions>
  276. );
  277. }
  278. renderChart(
  279. data: LineChartSeries[],
  280. series: LineChartSeries[],
  281. areaSeries: any[],
  282. maxThresholdValue: number,
  283. maxSeriesValue: number
  284. ) {
  285. const {
  286. router,
  287. interval,
  288. handleZoom,
  289. timePeriod: {start, end},
  290. } = this.props;
  291. const {dateModified, timeWindow} = this.props.rule || {};
  292. return (
  293. <ChartZoom
  294. router={router}
  295. start={start}
  296. end={end}
  297. onZoom={zoomArgs => handleZoom(zoomArgs.start, zoomArgs.end)}
  298. >
  299. {zoomRenderProps => (
  300. <LineChart
  301. {...zoomRenderProps}
  302. isGroupedByDate
  303. showTimeInTooltip
  304. forwardedRef={this.handleRef}
  305. grid={{
  306. left: 0,
  307. right: space(2),
  308. top: space(2),
  309. bottom: 0,
  310. }}
  311. yAxis={
  312. maxThresholdValue > maxSeriesValue ? {max: maxThresholdValue} : undefined
  313. }
  314. series={[...series, ...areaSeries]}
  315. graphic={Graphic({
  316. elements: this.getRuleChangeThresholdElements(data),
  317. })}
  318. tooltip={{
  319. formatter: seriesParams => {
  320. // seriesParams can be object instead of array
  321. const pointSeries = Array.isArray(seriesParams)
  322. ? seriesParams
  323. : [seriesParams];
  324. const {marker, data: pointData, seriesName} = pointSeries[0];
  325. const [pointX, pointY] = pointData as [number, number];
  326. const isModified =
  327. dateModified && pointX <= new Date(dateModified).getTime();
  328. const startTime = formatTooltipDate(moment(pointX), 'MMM D LT');
  329. const {period, periodLength} = parseStatsPeriod(interval) ?? {
  330. periodLength: 'm',
  331. period: `${timeWindow}`,
  332. };
  333. const endTime = formatTooltipDate(
  334. moment(pointX).add(
  335. parseInt(period, 10),
  336. periodLength as StatsPeriodType
  337. ),
  338. 'MMM D LT'
  339. );
  340. const title = isModified
  341. ? `<strong>${t('Alert Rule Modified')}</strong>`
  342. : `${marker} <strong>${seriesName}</strong>`;
  343. const value = isModified
  344. ? `${seriesName} ${pointY.toLocaleString()}`
  345. : pointY.toLocaleString();
  346. return [
  347. `<div class="tooltip-series"><div>`,
  348. `<span class="tooltip-label">${title}</span>${value}`,
  349. `</div></div>`,
  350. `<div class="tooltip-date">${startTime} &mdash; ${endTime}</div>`,
  351. `<div class="tooltip-arrow"></div>`,
  352. ].join('');
  353. },
  354. }}
  355. onFinished={() => {
  356. // We want to do this whenever the chart finishes re-rendering so that we can update the dimensions of
  357. // any graphics related to the triggers (e.g. the threshold areas + boundaries)
  358. this.updateDimensions();
  359. }}
  360. />
  361. )}
  362. </ChartZoom>
  363. );
  364. }
  365. renderEmpty() {
  366. return (
  367. <ChartPanel>
  368. <PanelBody withPadding>
  369. <Placeholder height="200px" />
  370. </PanelBody>
  371. </ChartPanel>
  372. );
  373. }
  374. render() {
  375. const {
  376. api,
  377. router,
  378. rule,
  379. organization,
  380. timePeriod,
  381. selectedIncident,
  382. projects,
  383. interval,
  384. filter,
  385. query,
  386. incidents,
  387. } = this.props;
  388. const criticalTrigger = rule.triggers.find(({label}) => label === 'critical');
  389. const warningTrigger = rule.triggers.find(({label}) => label === 'warning');
  390. // If the chart duration isn't as long as the rollup duration the events-stats
  391. // endpoint will return an invalid timeseriesData data set
  392. const viableStartDate = getUtcDateString(
  393. moment.min(
  394. moment.utc(timePeriod.start),
  395. moment.utc(timePeriod.end).subtract(rule.timeWindow, 'minutes')
  396. )
  397. );
  398. const viableEndDate = getUtcDateString(
  399. moment.utc(timePeriod.end).add(rule.timeWindow, 'minutes')
  400. );
  401. return (
  402. <EventsRequest
  403. api={api}
  404. organization={organization}
  405. query={query}
  406. environment={rule.environment ? [rule.environment] : undefined}
  407. project={(projects as Project[])
  408. .filter(p => p && p.slug)
  409. .map(project => Number(project.id))}
  410. interval={interval}
  411. start={viableStartDate}
  412. end={viableEndDate}
  413. yAxis={rule.aggregate}
  414. includePrevious={false}
  415. currentSeriesName={rule.aggregate}
  416. partial={false}
  417. >
  418. {({loading, timeseriesData}) => {
  419. if (loading || !timeseriesData) {
  420. return this.renderEmpty();
  421. }
  422. const series: LineChartSeries[] = [...timeseriesData];
  423. const areaSeries: any[] = [];
  424. // Ensure series data appears above incident lines
  425. series[0].z = 100;
  426. const dataArr = timeseriesData[0].data;
  427. const maxSeriesValue = dataArr.reduce(
  428. (currMax, coord) => Math.max(currMax, coord.value),
  429. 0
  430. );
  431. const firstPoint = Number(dataArr[0].name);
  432. const lastPoint = dataArr[dataArr.length - 1].name as number;
  433. const totalDuration = lastPoint - firstPoint;
  434. let criticalDuration = 0;
  435. let warningDuration = 0;
  436. series.push(createStatusAreaSeries(theme.green300, firstPoint, lastPoint));
  437. if (incidents) {
  438. // select incidents that fall within the graph range
  439. const periodStart = moment.utc(firstPoint);
  440. incidents
  441. .filter(
  442. incident =>
  443. !incident.dateClosed || moment(incident.dateClosed).isAfter(periodStart)
  444. )
  445. .forEach(incident => {
  446. const statusChanges = incident.activities
  447. ?.filter(
  448. ({type, value}) =>
  449. type === IncidentActivityType.STATUS_CHANGE &&
  450. value &&
  451. [
  452. `${IncidentStatus.WARNING}`,
  453. `${IncidentStatus.CRITICAL}`,
  454. ].includes(value)
  455. )
  456. .sort(
  457. (a, b) =>
  458. moment(a.dateCreated).valueOf() - moment(b.dateCreated).valueOf()
  459. );
  460. const incidentEnd = incident.dateClosed ?? moment().valueOf();
  461. const timeWindowMs = rule.timeWindow * 60 * 1000;
  462. const incidentColor =
  463. warningTrigger &&
  464. statusChanges &&
  465. !statusChanges.find(({value}) => value === `${IncidentStatus.CRITICAL}`)
  466. ? theme.yellow300
  467. : theme.red300;
  468. const incidentStartDate = moment(incident.dateStarted).valueOf();
  469. const incidentCloseDate = incident.dateClosed
  470. ? moment(incident.dateClosed).valueOf()
  471. : lastPoint;
  472. const incidentStartValue = dataArr.find(
  473. point => point.name >= incidentStartDate
  474. );
  475. series.push(
  476. createIncidentSeries(
  477. router,
  478. organization,
  479. incidentColor,
  480. incidentStartDate,
  481. incident,
  482. incidentStartValue,
  483. series[0].seriesName
  484. )
  485. );
  486. const areaStart = Math.max(
  487. moment(incident.dateStarted).valueOf(),
  488. firstPoint
  489. );
  490. const areaEnd = Math.min(
  491. statusChanges?.length && statusChanges[0].dateCreated
  492. ? moment(statusChanges[0].dateCreated).valueOf() - timeWindowMs
  493. : moment(incidentEnd).valueOf(),
  494. lastPoint
  495. );
  496. const areaColor = warningTrigger ? theme.yellow300 : theme.red300;
  497. if (areaEnd > areaStart) {
  498. series.push(createStatusAreaSeries(areaColor, areaStart, areaEnd));
  499. if (areaColor === theme.yellow300) {
  500. warningDuration += Math.abs(areaEnd - areaStart);
  501. } else {
  502. criticalDuration += Math.abs(areaEnd - areaStart);
  503. }
  504. }
  505. statusChanges?.forEach((activity, idx) => {
  506. const statusAreaStart = Math.max(
  507. moment(activity.dateCreated).valueOf() - timeWindowMs,
  508. firstPoint
  509. );
  510. const statusAreaEnd = Math.min(
  511. idx === statusChanges.length - 1
  512. ? moment(incidentEnd).valueOf()
  513. : moment(statusChanges[idx + 1].dateCreated).valueOf() -
  514. timeWindowMs,
  515. lastPoint
  516. );
  517. const statusAreaColor =
  518. activity.value === `${IncidentStatus.CRITICAL}`
  519. ? theme.red300
  520. : theme.yellow300;
  521. if (statusAreaEnd > statusAreaStart) {
  522. series.push(
  523. createStatusAreaSeries(
  524. statusAreaColor,
  525. statusAreaStart,
  526. statusAreaEnd
  527. )
  528. );
  529. if (statusAreaColor === theme.yellow300) {
  530. warningDuration += Math.abs(statusAreaEnd - statusAreaStart);
  531. } else {
  532. criticalDuration += Math.abs(statusAreaEnd - statusAreaStart);
  533. }
  534. }
  535. });
  536. if (selectedIncident && incident.id === selectedIncident.id) {
  537. const selectedIncidentColor =
  538. incidentColor === theme.yellow300 ? theme.yellow100 : theme.red100;
  539. areaSeries.push({
  540. type: 'line',
  541. markArea: MarkArea({
  542. silent: true,
  543. itemStyle: {
  544. color: color(selectedIncidentColor).alpha(0.42).rgb().string(),
  545. },
  546. data: [
  547. [{xAxis: incidentStartDate}, {xAxis: incidentCloseDate}],
  548. ] as any,
  549. }),
  550. data: [],
  551. });
  552. }
  553. });
  554. }
  555. let maxThresholdValue = 0;
  556. if (warningTrigger?.alertThreshold) {
  557. const {alertThreshold} = warningTrigger;
  558. const warningThresholdLine = createThresholdSeries(
  559. theme.yellow300,
  560. alertThreshold
  561. );
  562. series.push(warningThresholdLine);
  563. maxThresholdValue = Math.max(maxThresholdValue, alertThreshold);
  564. }
  565. if (criticalTrigger?.alertThreshold) {
  566. const {alertThreshold} = criticalTrigger;
  567. const criticalThresholdLine = createThresholdSeries(
  568. theme.red300,
  569. alertThreshold
  570. );
  571. series.push(criticalThresholdLine);
  572. maxThresholdValue = Math.max(maxThresholdValue, alertThreshold);
  573. }
  574. return (
  575. <ChartPanel>
  576. <StyledPanelBody withPadding>
  577. <ChartHeader>
  578. <ChartTitle>
  579. {AlertWizardAlertNames[getAlertTypeFromAggregateDataset(rule)]}
  580. </ChartTitle>
  581. {filter}
  582. </ChartHeader>
  583. {this.renderChart(
  584. timeseriesData,
  585. series,
  586. areaSeries,
  587. maxThresholdValue,
  588. maxSeriesValue
  589. )}
  590. </StyledPanelBody>
  591. {this.renderChartActions(totalDuration, criticalDuration, warningDuration)}
  592. </ChartPanel>
  593. );
  594. }}
  595. </EventsRequest>
  596. );
  597. }
  598. }
  599. export default withRouter(MetricChart);
  600. const ChartPanel = styled(Panel)`
  601. margin-top: ${space(2)};
  602. `;
  603. const ChartHeader = styled('div')`
  604. margin-bottom: ${space(3)};
  605. `;
  606. const ChartTitle = styled('header')`
  607. display: flex;
  608. flex-direction: row;
  609. `;
  610. const ChartActions = styled(PanelFooter)`
  611. display: flex;
  612. justify-content: flex-end;
  613. align-items: center;
  614. padding: ${space(1)} 20px;
  615. `;
  616. const ChartSummary = styled('div')`
  617. display: flex;
  618. margin-right: auto;
  619. `;
  620. const SummaryText = styled(SectionHeading)`
  621. flex: 1;
  622. display: flex;
  623. align-items: center;
  624. margin: 0;
  625. font-weight: bold;
  626. font-size: ${p => p.theme.fontSizeSmall};
  627. line-height: 1;
  628. `;
  629. const SummaryStats = styled('div')`
  630. display: flex;
  631. align-items: center;
  632. margin: 0 ${space(2)};
  633. `;
  634. const StatItem = styled('div')`
  635. display: flex;
  636. align-items: center;
  637. margin: 0 ${space(2)} 0 0;
  638. `;
  639. /* Override padding to make chart appear centered */
  640. const StyledPanelBody = styled(PanelBody)`
  641. padding-right: 6px;
  642. `;
  643. const StatCount = styled('span')`
  644. margin-left: ${space(0.5)};
  645. margin-top: ${space(0.25)};
  646. color: ${p => p.theme.textColor};
  647. `;