forked from elastic/kibana
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeseriesexplorer.js
1377 lines (1239 loc) · 48.5 KB
/
timeseriesexplorer.js
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.
*/
/*
* React component for rendering Single Metric Viewer.
*/
import { debounce, each, find, get, has, isEqual } from 'lodash';
import moment from 'moment-timezone';
import { Subject, Subscription, forkJoin } from 'rxjs';
import { map, debounceTime, switchMap, tap, withLatestFrom } from 'rxjs/operators';
import PropTypes from 'prop-types';
import React, { createRef, Fragment } from 'react';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n/react';
import {
EuiCallOut,
EuiCheckbox,
EuiFlexGroup,
EuiFlexItem,
EuiFormRow,
EuiSelect,
EuiSpacer,
EuiTitle,
} from '@elastic/eui';
import { getToastNotifications } from '../util/dependency_cache';
import { ResizeChecker } from '../../../../../../src/plugins/kibana_utils/public';
import { ANOMALIES_TABLE_DEFAULT_QUERY_SIZE } from '../../../common/constants/search';
import {
isModelPlotEnabled,
isSourceDataChartableForDetector,
isTimeSeriesViewDetector,
mlFunctionToESAggregation,
} from '../../../common/util/job_utils';
import { AnnotationFlyout } from '../components/annotations/annotation_flyout';
import { AnnotationsTable } from '../components/annotations/annotations_table';
import { AnomaliesTable } from '../components/anomalies_table/anomalies_table';
import { ChartTooltip } from '../components/chart_tooltip';
import { EntityControl } from './components/entity_control';
import { ForecastingModal } from './components/forecasting_modal/forecasting_modal';
import { LoadingIndicator } from '../components/loading_indicator/loading_indicator';
import { SelectInterval } from '../components/controls/select_interval/select_interval';
import { SelectSeverity } from '../components/controls/select_severity/select_severity';
import { TimeseriesChart } from './components/timeseries_chart/timeseries_chart';
import { TimeseriesexplorerNoChartData } from './components/timeseriesexplorer_no_chart_data';
import { TimeSeriesExplorerPage } from './timeseriesexplorer_page';
import { ml } from '../services/ml_api_service';
import { mlFieldFormatService } from '../services/field_format_service';
import { mlForecastService } from '../services/forecast_service';
import { mlJobService } from '../services/job_service';
import { mlResultsService } from '../services/results_service';
import { getBoundsRoundedToInterval } from '../util/time_buckets';
import {
APP_STATE_ACTION,
CHARTS_POINT_TARGET,
TIME_FIELD_NAME,
} from './timeseriesexplorer_constants';
import { mlTimeSeriesSearchService } from './timeseries_search_service';
import {
calculateAggregationInterval,
calculateDefaultFocusRange,
calculateInitialFocusRange,
createTimeSeriesJobData,
processForecastResults,
processMetricPlotResults,
processRecordScoreResults,
getFocusData,
} from './timeseriesexplorer_utils';
import { EMPTY_FIELD_VALUE_LABEL } from './components/entity_control/entity_control';
// Used to indicate the chart is being plotted across
// all partition field values, where the cardinality of the field cannot be
// obtained as it is not aggregatable e.g. 'all distinct kpi_indicator values'
const allValuesLabel = i18n.translate('xpack.ml.timeSeriesExplorer.allPartitionValuesLabel', {
defaultMessage: 'all',
});
function getEntityControlOptions(fieldValues) {
if (!Array.isArray(fieldValues)) {
return [];
}
fieldValues.sort();
return fieldValues.map(value => {
return { label: value === '' ? EMPTY_FIELD_VALUE_LABEL : value, value };
});
}
function getViewableDetectors(selectedJob) {
const jobDetectors = selectedJob.analysis_config.detectors;
const viewableDetectors = [];
each(jobDetectors, (dtr, index) => {
if (isTimeSeriesViewDetector(selectedJob, index)) {
viewableDetectors.push({
index,
detector_description: dtr.detector_description,
});
}
});
return viewableDetectors;
}
function getTimeseriesexplorerDefaultState() {
return {
chartDetails: undefined,
contextAggregationInterval: undefined,
contextChartData: undefined,
contextForecastData: undefined,
// Not chartable if e.g. model plot with terms for a varp detector
dataNotChartable: false,
entitiesLoading: false,
entityValues: {},
focusAnnotationData: [],
focusChartData: undefined,
focusForecastData: undefined,
fullRefresh: true,
hasResults: false,
// Counter to keep track of what data sets have been loaded.
loadCounter: 0,
loading: false,
modelPlotEnabled: false,
// Toggles display of annotations in the focus chart
showAnnotations: true,
showAnnotationsCheckbox: true,
// Toggles display of forecast data in the focus chart
showForecast: true,
showForecastCheckbox: false,
// Toggles display of model bounds in the focus chart
showModelBounds: true,
showModelBoundsCheckbox: false,
svgWidth: 0,
tableData: undefined,
zoomFrom: undefined,
zoomTo: undefined,
zoomFromFocusLoaded: undefined,
zoomToFocusLoaded: undefined,
};
}
const containerPadding = 34;
export class TimeSeriesExplorer extends React.Component {
static propTypes = {
appStateHandler: PropTypes.func.isRequired,
autoZoomDuration: PropTypes.number.isRequired,
bounds: PropTypes.object.isRequired,
dateFormatTz: PropTypes.string.isRequired,
lastRefresh: PropTypes.number.isRequired,
previousRefresh: PropTypes.number.isRequired,
selectedJobId: PropTypes.string.isRequired,
selectedDetectorIndex: PropTypes.number,
selectedEntities: PropTypes.object,
selectedForecastId: PropTypes.string,
tableInterval: PropTypes.string,
tableSeverity: PropTypes.number,
zoom: PropTypes.object,
};
state = getTimeseriesexplorerDefaultState();
subscriptions = new Subscription();
resizeRef = createRef();
resizeChecker = undefined;
resizeHandler = () => {
this.setState({
svgWidth:
this.resizeRef.current !== null ? this.resizeRef.current.offsetWidth - containerPadding : 0,
});
};
/**
* Subject for listening brush time range selection.
*/
contextChart$ = new Subject();
/**
* Returns field names that don't have a selection yet.
*/
getFieldNamesWithEmptyValues = () => {
const latestEntityControls = this.getControlsForDetector();
return latestEntityControls
.filter(({ fieldValue }) => fieldValue === null)
.map(({ fieldName }) => fieldName);
};
/**
* Checks if all entity control dropdowns have a selection.
*/
arePartitioningFieldsProvided = () => {
const fieldNamesWithEmptyValues = this.getFieldNamesWithEmptyValues();
return fieldNamesWithEmptyValues.length === 0;
};
detectorIndexChangeHandler = e => {
const { appStateHandler } = this.props;
const id = e.target.value;
if (id !== undefined) {
appStateHandler(APP_STATE_ACTION.SET_DETECTOR_INDEX, +id);
}
};
toggleShowAnnotationsHandler = () => {
this.setState(prevState => ({
showAnnotations: !prevState.showAnnotations,
}));
};
toggleShowForecastHandler = () => {
this.setState(prevState => ({
showForecast: !prevState.showForecast,
}));
};
toggleShowModelBoundsHandler = () => {
this.setState({
showModelBounds: !this.state.showModelBounds,
});
};
previousChartProps = {};
previousShowAnnotations = undefined;
previousShowForecast = undefined;
previousShowModelBounds = undefined;
tableFilter = (field, value, operator) => {
const entities = this.getControlsForDetector();
const entity = entities.find(({ fieldName }) => fieldName === field);
if (entity === undefined) {
return;
}
const { appStateHandler } = this.props;
let resultValue = '';
if (operator === '+' && entity.fieldValue !== value) {
resultValue = value;
} else if (operator === '-' && entity.fieldValue === value) {
resultValue = null;
} else {
return;
}
const resultEntities = {
...entities.reduce((appStateEntities, appStateEntity) => {
appStateEntities[appStateEntity.fieldName] = appStateEntity.fieldValue;
return appStateEntities;
}, {}),
[entity.fieldName]: resultValue,
};
appStateHandler(APP_STATE_ACTION.SET_ENTITIES, resultEntities);
};
contextChartSelectedInitCallDone = false;
getFocusAggregationInterval(selection) {
const { selectedJobId } = this.props;
const jobs = createTimeSeriesJobData(mlJobService.jobs);
const selectedJob = mlJobService.getJob(selectedJobId);
// Calculate the aggregation interval for the focus chart.
const bounds = { min: moment(selection.from), max: moment(selection.to) };
return calculateAggregationInterval(bounds, CHARTS_POINT_TARGET, jobs, selectedJob);
}
/**
* Gets focus data for the current component state/
*/
getFocusData(selection) {
const { selectedJobId, selectedForecastId, selectedDetectorIndex } = this.props;
const { modelPlotEnabled } = this.state;
const selectedJob = mlJobService.getJob(selectedJobId);
const entityControls = this.getControlsForDetector();
// Calculate the aggregation interval for the focus chart.
const bounds = { min: moment(selection.from), max: moment(selection.to) };
const focusAggregationInterval = this.getFocusAggregationInterval(selection);
// Ensure the search bounds align to the bucketing interval so that the first and last buckets are complete.
// For sum or count detectors, short buckets would hold smaller values, and model bounds would also be affected
// to some extent with all detector functions if not searching complete buckets.
const searchBounds = getBoundsRoundedToInterval(bounds, focusAggregationInterval, false);
return getFocusData(
this.getCriteriaFields(selectedDetectorIndex, entityControls),
selectedDetectorIndex,
focusAggregationInterval,
selectedForecastId,
modelPlotEnabled,
entityControls.filter(entity => entity.fieldValue !== null),
searchBounds,
selectedJob,
TIME_FIELD_NAME
);
}
contextChartSelected = selection => {
const zoomState = {
from: selection.from.toISOString(),
to: selection.to.toISOString(),
};
if (
isEqual(this.props.zoom, zoomState) &&
this.state.focusChartData !== undefined &&
this.props.previousRefresh === this.props.lastRefresh
) {
return;
}
this.contextChart$.next(selection);
this.props.appStateHandler(APP_STATE_ACTION.SET_ZOOM, zoomState);
};
entityFieldValueChanged = (entity, fieldValue) => {
const { appStateHandler } = this.props;
const entityControls = this.getControlsForDetector();
const resultEntities = {
...entityControls.reduce((appStateEntities, appStateEntity) => {
appStateEntities[appStateEntity.fieldName] = appStateEntity.fieldValue;
return appStateEntities;
}, {}),
[entity.fieldName]: fieldValue,
};
appStateHandler(APP_STATE_ACTION.SET_ENTITIES, resultEntities);
};
entityFieldSearchChanged = debounce((entity, queryTerm) => {
const entityControls = this.getControlsForDetector();
this.loadEntityValues(entityControls, {
[entity.fieldType]: queryTerm,
});
}, 500);
loadAnomaliesTableData = (earliestMs, latestMs) => {
const {
dateFormatTz,
selectedDetectorIndex,
selectedJobId,
tableInterval,
tableSeverity,
} = this.props;
const selectedJob = mlJobService.getJob(selectedJobId);
const entityControls = this.getControlsForDetector();
return ml.results
.getAnomaliesTableData(
[selectedJob.job_id],
this.getCriteriaFields(selectedDetectorIndex, entityControls),
[],
tableInterval,
tableSeverity,
earliestMs,
latestMs,
dateFormatTz,
ANOMALIES_TABLE_DEFAULT_QUERY_SIZE
)
.pipe(
map(resp => {
const anomalies = resp.anomalies;
const detectorsByJob = mlJobService.detectorsByJob;
anomalies.forEach(anomaly => {
// Add a detector property to each anomaly.
// Default to functionDescription if no description available.
// TODO - when job_service is moved server_side, move this to server endpoint.
const jobId = anomaly.jobId;
const detector = get(detectorsByJob, [jobId, anomaly.detectorIndex]);
anomaly.detector = get(
detector,
['detector_description'],
anomaly.source.function_description
);
// For detectors with rules, add a property with the rule count.
const customRules = detector.custom_rules;
if (customRules !== undefined) {
anomaly.rulesLength = customRules.length;
}
// Add properties used for building the links menu.
// TODO - when job_service is moved server_side, move this to server endpoint.
if (has(mlJobService.customUrlsByJob, jobId)) {
anomaly.customUrls = mlJobService.customUrlsByJob[jobId];
}
});
return {
tableData: {
anomalies,
interval: resp.interval,
examplesByJobId: resp.examplesByJobId,
showViewSeriesLink: false,
},
};
})
);
};
/**
* Loads available entity values.
* @param {Array} entities - Entity controls configuration
* @param {Object} searchTerm - Search term for partition, e.g. { partition_field: 'partition' }
*/
loadEntityValues = async (entities, searchTerm = {}) => {
this.setState({ entitiesLoading: true });
const { bounds, selectedJobId, selectedDetectorIndex } = this.props;
const selectedJob = mlJobService.getJob(selectedJobId);
// Populate the entity input datalists with the values from the top records by score
// for the selected detector across the full time range. No need to pass through finish().
const detectorIndex = selectedDetectorIndex;
const {
partition_field: partitionField,
over_field: overField,
by_field: byField,
} = await mlResultsService
.fetchPartitionFieldsValues(
selectedJob.job_id,
searchTerm,
[
{
fieldName: 'detector_index',
fieldValue: detectorIndex,
},
],
bounds.min.valueOf(),
bounds.max.valueOf()
)
.toPromise();
const entityValues = {};
entities.forEach(entity => {
let fieldValues;
if (partitionField?.name === entity.fieldName) {
fieldValues = partitionField.values;
}
if (overField?.name === entity.fieldName) {
fieldValues = overField.values;
}
if (byField?.name === entity.fieldName) {
fieldValues = byField.values;
}
entityValues[entity.fieldName] = fieldValues;
});
this.setState({ entitiesLoading: false, entityValues });
};
setForecastId = forecastId => {
this.props.appStateHandler(APP_STATE_ACTION.SET_FORECAST_ID, forecastId);
};
loadSingleMetricData = (fullRefresh = true) => {
const {
autoZoomDuration,
bounds,
selectedDetectorIndex,
selectedForecastId,
selectedJobId,
zoom,
} = this.props;
const { loadCounter: currentLoadCounter } = this.state;
const currentSelectedJob = mlJobService.getJob(selectedJobId);
if (currentSelectedJob === undefined) {
return;
}
this.contextChartSelectedInitCallDone = false;
// Only when `fullRefresh` is true we'll reset all data
// and show the loading spinner within the page.
const entityControls = this.getControlsForDetector();
this.setState(
{
fullRefresh,
loadCounter: currentLoadCounter + 1,
loading: true,
...(fullRefresh
? {
chartDetails: undefined,
contextChartData: undefined,
contextForecastData: undefined,
focusChartData: undefined,
focusForecastData: undefined,
modelPlotEnabled: isModelPlotEnabled(
currentSelectedJob,
selectedDetectorIndex,
entityControls
),
hasResults: false,
dataNotChartable: false,
}
: {}),
},
() => {
const { loadCounter, modelPlotEnabled } = this.state;
const jobs = createTimeSeriesJobData(mlJobService.jobs);
const selectedJob = mlJobService.getJob(selectedJobId);
const detectorIndex = selectedDetectorIndex;
let awaitingCount = 3;
const stateUpdate = {};
// finish() function, called after each data set has been loaded and processed.
// The last one to call it will trigger the page render.
const finish = counterVar => {
awaitingCount--;
if (awaitingCount === 0 && counterVar === loadCounter) {
stateUpdate.hasResults =
(Array.isArray(stateUpdate.contextChartData) &&
stateUpdate.contextChartData.length > 0) ||
(Array.isArray(stateUpdate.contextForecastData) &&
stateUpdate.contextForecastData.length > 0);
stateUpdate.loading = false;
// Set zoomFrom/zoomTo attributes in scope which will result in the metric chart automatically
// selecting the specified range in the context chart, and so loading that date range in the focus chart.
// Only touch the zoom range if data for the context chart has been loaded and all necessary
// partition fields have a selection.
if (
stateUpdate.contextChartData.length &&
this.arePartitioningFieldsProvided() === true
) {
// Check for a zoom parameter in the appState (URL).
let focusRange = calculateInitialFocusRange(
zoom,
stateUpdate.contextAggregationInterval,
bounds
);
if (
focusRange === undefined ||
this.previousSelectedForecastId !== this.props.selectedForecastId
) {
focusRange = calculateDefaultFocusRange(
autoZoomDuration,
stateUpdate.contextAggregationInterval,
stateUpdate.contextChartData,
stateUpdate.contextForecastData
);
this.previousSelectedForecastId = this.props.selectedForecastId;
}
this.contextChartSelected({
from: focusRange[0],
to: focusRange[1],
});
}
this.setState(stateUpdate);
}
};
const nonBlankEntities = entityControls.filter(entity => {
return entity.fieldValue !== null;
});
if (
modelPlotEnabled === false &&
isSourceDataChartableForDetector(selectedJob, detectorIndex) === false &&
nonBlankEntities.length > 0
) {
// For detectors where model plot has been enabled with a terms filter and the
// selected entity(s) are not in the terms list, indicate that data cannot be viewed.
stateUpdate.hasResults = false;
stateUpdate.loading = false;
stateUpdate.dataNotChartable = true;
this.setState(stateUpdate);
return;
}
// Calculate the aggregation interval for the context chart.
// Context chart swimlane will display bucket anomaly score at the same interval.
stateUpdate.contextAggregationInterval = calculateAggregationInterval(
bounds,
CHARTS_POINT_TARGET,
jobs,
selectedJob
);
// Ensure the search bounds align to the bucketing interval so that the first and last buckets are complete.
// For sum or count detectors, short buckets would hold smaller values, and model bounds would also be affected
// to some extent with all detector functions if not searching complete buckets.
const searchBounds = getBoundsRoundedToInterval(
bounds,
stateUpdate.contextAggregationInterval,
false
);
// Query 1 - load metric data at low granularity across full time range.
// Pass a counter flag into the finish() function to make sure we only process the results
// for the most recent call to the load the data in cases where the job selection and time filter
// have been altered in quick succession (such as from the job picker with 'Apply time range').
const counter = loadCounter;
mlTimeSeriesSearchService
.getMetricData(
selectedJob,
detectorIndex,
nonBlankEntities,
searchBounds.min.valueOf(),
searchBounds.max.valueOf(),
stateUpdate.contextAggregationInterval.expression
)
.toPromise()
.then(resp => {
const fullRangeChartData = processMetricPlotResults(resp.results, modelPlotEnabled);
stateUpdate.contextChartData = fullRangeChartData;
finish(counter);
})
.catch(resp => {
console.log(
'Time series explorer - error getting metric data from elasticsearch:',
resp
);
});
// Query 2 - load max record score at same granularity as context chart
// across full time range for use in the swimlane.
mlResultsService
.getRecordMaxScoreByTime(
selectedJob.job_id,
this.getCriteriaFields(detectorIndex, entityControls),
searchBounds.min.valueOf(),
searchBounds.max.valueOf(),
stateUpdate.contextAggregationInterval.expression
)
.then(resp => {
const fullRangeRecordScoreData = processRecordScoreResults(resp.results);
stateUpdate.swimlaneData = fullRangeRecordScoreData;
finish(counter);
})
.catch(resp => {
console.log(
'Time series explorer - error getting bucket anomaly scores from elasticsearch:',
resp
);
});
// Query 3 - load details on the chart used in the chart title (charting function and entity(s)).
mlTimeSeriesSearchService
.getChartDetails(
selectedJob,
detectorIndex,
entityControls,
searchBounds.min.valueOf(),
searchBounds.max.valueOf()
)
.then(resp => {
stateUpdate.chartDetails = resp.results;
finish(counter);
})
.catch(resp => {
console.log(
'Time series explorer - error getting entity counts from elasticsearch:',
resp
);
});
// Plus query for forecast data if there is a forecastId stored in the appState.
if (selectedForecastId !== undefined) {
awaitingCount++;
let aggType = undefined;
const detector = selectedJob.analysis_config.detectors[detectorIndex];
const esAgg = mlFunctionToESAggregation(detector.function);
if (modelPlotEnabled === false && (esAgg === 'sum' || esAgg === 'count')) {
aggType = { avg: 'sum', max: 'sum', min: 'sum' };
}
mlForecastService
.getForecastData(
selectedJob,
detectorIndex,
selectedForecastId,
nonBlankEntities,
searchBounds.min.valueOf(),
searchBounds.max.valueOf(),
stateUpdate.contextAggregationInterval.expression,
aggType
)
.toPromise()
.then(resp => {
stateUpdate.contextForecastData = processForecastResults(resp.results);
finish(counter);
})
.catch(resp => {
console.log(
`Time series explorer - error loading data for forecast ID ${selectedForecastId}`,
resp
);
});
}
}
);
};
/**
* Updates local state of detector related controls from the global state.
* @param callback to invoke after a state update.
*/
getControlsForDetector = () => {
const { selectedDetectorIndex, selectedEntities, selectedJobId } = this.props;
const selectedJob = mlJobService.getJob(selectedJobId);
const entities = [];
if (selectedJob === undefined) {
return entities;
}
// Update the entity dropdown control(s) according to the partitioning fields for the selected detector.
const detectorIndex = selectedDetectorIndex;
const detector = selectedJob.analysis_config.detectors[detectorIndex];
const entitiesState = selectedEntities;
const partitionFieldName = get(detector, 'partition_field_name');
const overFieldName = get(detector, 'over_field_name');
const byFieldName = get(detector, 'by_field_name');
if (partitionFieldName !== undefined) {
const partitionFieldValue = get(entitiesState, partitionFieldName, null);
entities.push({
fieldType: 'partition_field',
fieldName: partitionFieldName,
fieldValue: partitionFieldValue,
});
}
if (overFieldName !== undefined) {
const overFieldValue = get(entitiesState, overFieldName, null);
entities.push({
fieldType: 'over_field',
fieldName: overFieldName,
fieldValue: overFieldValue,
});
}
// For jobs with by and over fields, don't add the 'by' field as this
// field will only be added to the top-level fields for record type results
// if it also an influencer over the bucket.
// TODO - metric data can be filtered by this field, so should only exclude
// from filter for the anomaly records.
if (byFieldName !== undefined && overFieldName === undefined) {
const byFieldValue = get(entitiesState, byFieldName, null);
entities.push({ fieldType: 'by_field', fieldName: byFieldName, fieldValue: byFieldValue });
}
return entities;
};
/**
* Updates criteria fields for API calls, e.g. getAnomaliesTableData
* @param detectorIndex
* @param entities
*/
getCriteriaFields(detectorIndex, entities) {
// Only filter on the entity if the field has a value.
const nonBlankEntities = entities.filter(entity => entity.fieldValue !== null);
return [
{
fieldName: 'detector_index',
fieldValue: detectorIndex,
},
...nonBlankEntities,
];
}
loadForJobId(jobId) {
const { appStateHandler, selectedDetectorIndex } = this.props;
const selectedJob = mlJobService.getJob(jobId);
if (selectedJob === undefined) {
return;
}
const detectors = getViewableDetectors(selectedJob);
// Check the supplied index is valid.
const appStateDtrIdx = selectedDetectorIndex;
let detectorIndex = appStateDtrIdx !== undefined ? appStateDtrIdx : detectors[0].index;
if (find(detectors, { index: detectorIndex }) === undefined) {
const warningText = i18n.translate(
'xpack.ml.timeSeriesExplorer.requestedDetectorIndexNotValidWarningMessage',
{
defaultMessage: 'Requested detector index {detectorIndex} is not valid for job {jobId}',
values: {
detectorIndex,
jobId: selectedJob.job_id,
},
}
);
const toastNotifications = getToastNotifications();
toastNotifications.addWarning(warningText);
detectorIndex = detectors[0].index;
}
const detectorId = detectorIndex;
if (detectorId !== selectedDetectorIndex) {
appStateHandler(APP_STATE_ACTION.SET_DETECTOR_INDEX, detectorId);
}
// Populate the map of jobs / detectors / field formatters for the selected IDs and refresh.
mlFieldFormatService.populateFormats([jobId]).catch(err => {
console.log('Error populating field formats:', err);
});
}
componentDidMount() {
// Required to redraw the time series chart when the container is resized.
this.resizeChecker = new ResizeChecker(this.resizeRef.current);
this.resizeChecker.on('resize', () => {
this.resizeHandler();
});
this.resizeHandler();
// Listen for context chart updates.
this.subscriptions.add(
this.contextChart$
.pipe(
tap(selection => {
this.setState({
zoomFrom: selection.from,
zoomTo: selection.to,
});
}),
debounceTime(500),
tap(selection => {
const {
contextChartData,
contextForecastData,
focusChartData,
zoomFromFocusLoaded,
zoomToFocusLoaded,
} = this.state;
if (
(contextChartData === undefined || contextChartData.length === 0) &&
(contextForecastData === undefined || contextForecastData.length === 0)
) {
return;
}
if (
(this.contextChartSelectedInitCallDone === false && focusChartData === undefined) ||
zoomFromFocusLoaded.getTime() !== selection.from.getTime() ||
zoomToFocusLoaded.getTime() !== selection.to.getTime()
) {
this.contextChartSelectedInitCallDone = true;
this.setState({
loading: true,
fullRefresh: false,
});
}
}),
switchMap(selection => {
const { selectedJobId } = this.props;
const jobs = createTimeSeriesJobData(mlJobService.jobs);
const selectedJob = mlJobService.getJob(selectedJobId);
// Calculate the aggregation interval for the focus chart.
const bounds = { min: moment(selection.from), max: moment(selection.to) };
const focusAggregationInterval = calculateAggregationInterval(
bounds,
CHARTS_POINT_TARGET,
jobs,
selectedJob
);
// Ensure the search bounds align to the bucketing interval so that the first and last buckets are complete.
// For sum or count detectors, short buckets would hold smaller values, and model bounds would also be affected
// to some extent with all detector functions if not searching complete buckets.
const searchBounds = getBoundsRoundedToInterval(
bounds,
focusAggregationInterval,
false
);
return forkJoin([
this.getFocusData(selection),
// Load the data for the anomalies table.
this.loadAnomaliesTableData(searchBounds.min.valueOf(), searchBounds.max.valueOf()),
]);
}),
withLatestFrom(this.contextChart$)
)
.subscribe(([[refreshFocusData, tableData], selection]) => {
const { modelPlotEnabled } = this.state;
// All the data is ready now for a state update.
this.setState({
focusAggregationInterval: this.getFocusAggregationInterval({
from: selection.from,
to: selection.to,
}),
loading: false,
showModelBoundsCheckbox: modelPlotEnabled && refreshFocusData.focusChartData.length > 0,
zoomFromFocusLoaded: selection.from,
zoomToFocusLoaded: selection.to,
...refreshFocusData,
...tableData,
});
})
);
this.componentDidUpdate();
}
componentDidUpdate(previousProps) {
if (previousProps === undefined || previousProps.selectedJobId !== this.props.selectedJobId) {
this.contextChartSelectedInitCallDone = false;
this.setState({ fullRefresh: false, loading: true }, () => {
this.loadForJobId(this.props.selectedJobId);
});
}
if (
previousProps === undefined ||
previousProps.selectedJobId !== this.props.selectedJobId ||
previousProps.selectedDetectorIndex !== this.props.selectedDetectorIndex ||
!isEqual(previousProps.selectedEntities, this.props.selectedEntities)
) {
const entityControls = this.getControlsForDetector();
this.loadEntityValues(entityControls);
}
if (
previousProps === undefined ||
previousProps.selectedForecastId !== this.props.selectedForecastId
) {
if (this.props.selectedForecastId !== undefined) {
// Ensure the forecast data will be shown if hidden previously.
this.setState({ showForecast: true });
// Not best practice but we need the previous value for another comparison
// once all the data was loaded.
if (previousProps !== undefined) {
this.previousSelectedForecastId = previousProps.selectedForecastId;
}
}
}
if (
previousProps === undefined ||
!isEqual(previousProps.bounds, this.props.bounds) ||
!isEqual(previousProps.lastRefresh, this.props.lastRefresh) ||
!isEqual(previousProps.selectedDetectorIndex, this.props.selectedDetectorIndex) ||
!isEqual(previousProps.selectedEntities, this.props.selectedEntities) ||
previousProps.selectedForecastId !== this.props.selectedForecastId ||
previousProps.selectedJobId !== this.props.selectedJobId
) {
const fullRefresh =
previousProps === undefined ||
!isEqual(previousProps.bounds, this.props.bounds) ||
!isEqual(previousProps.selectedDetectorIndex, this.props.selectedDetectorIndex) ||
!isEqual(previousProps.selectedEntities, this.props.selectedEntities) ||
previousProps.selectedForecastId !== this.props.selectedForecastId ||
previousProps.selectedJobId !== this.props.selectedJobId;
this.loadSingleMetricData(fullRefresh);
}
if (previousProps === undefined) {
return;
}
// Reload the anomalies table if the Interval or Threshold controls are changed.
const tableControlsListener = () => {
const { zoomFrom, zoomTo } = this.state;
if (zoomFrom !== undefined && zoomTo !== undefined) {
this.loadAnomaliesTableData(zoomFrom.getTime(), zoomTo.getTime()).subscribe(res =>
this.setState(res)
);
}
};
if (
previousProps.tableInterval !== this.props.tableInterval ||
previousProps.tableSeverity !== this.props.tableSeverity
) {