-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathConfigureModel.tsx
440 lines (423 loc) · 14.9 KB
/
ConfigureModel.tsx
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
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import {
EuiPageBody,
EuiPageHeader,
EuiPageHeaderSection,
EuiFlexItem,
EuiFlexGroup,
EuiPage,
EuiSmallButton,
EuiSmallButtonEmpty,
EuiSpacer,
EuiText,
EuiLink,
EuiIcon,
} from '@elastic/eui';
import { FormikProps, Formik } from 'formik';
import { get, isEmpty } from 'lodash';
import React, { Fragment, useState, useEffect, ReactElement } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { RouteComponentProps, useLocation } from 'react-router-dom';
import { AppState } from '../../../redux/reducers';
import { getMappings } from '../../../redux/reducers/opensearch';
import { useFetchDetectorInfo } from '../../CreateDetectorSteps/hooks/useFetchDetectorInfo';
import { BREADCRUMBS, BASE_DOCS_LINK, MDS_BREADCRUMBS } from '../../../utils/constants';
import { useHideSideNavBar } from '../../main/hooks/useHideSideNavBar';
import { updateDetector } from '../../../redux/reducers/ad';
import {
validateFeatures,
focusOnFirstWrongFeature,
getCategoryFields,
focusOnCategoryField,
getShingleSizeFromObject,
modelConfigurationToFormik,
} from '../utils/helpers';
import { formikToDetector } from '../../ReviewAndCreate/utils/helpers';
import { formikToModelConfiguration } from '../utils/helpers';
import { Features } from '../components/Features';
import { CategoryField } from '../components/CategoryField';
import { AdvancedSettings } from '../components/AdvancedSettings';
import { SampleAnomalies } from './SampleAnomalies';
import { CoreStart, MountPoint } from '../../../../../../src/core/public';
import { CoreServicesContext } from '../../../components/CoreServices/CoreServices';
import { Detector } from '../../../models/interfaces';
import { prettifyErrorMessage } from '../../../../server/utils/helpers';
import { DetectorDefinitionFormikValues } from '../../DefineDetector/models/interfaces';
import { ModelConfigurationFormikValues } from '../models/interfaces';
import { CreateDetectorFormikValues } from '../../CreateDetectorSteps/models/interfaces';
import { DETECTOR_STATE } from '../../../../server/utils/constants';
import { getErrorMessage } from '../../../utils/utils';
import {
constructHrefWithDataSourceId,
getDataSourceFromURL,
} from '../../../pages/utils/helpers';
import {
getDataSourceManagementPlugin,
getDataSourceEnabled,
getNotifications,
getSavedObjectsClient,
} from '../../../services';
import { DataSourceViewConfig } from '../../../../../../src/plugins/data_source_management/public';
interface ConfigureModelRouterProps {
detectorId?: string;
}
interface ConfigureModelProps
extends RouteComponentProps<ConfigureModelRouterProps> {
isEdit: boolean;
setStep?(stepNumber: number): void;
initialValues?: ModelConfigurationFormikValues;
setInitialValues?(initialValues: ModelConfigurationFormikValues): void;
detectorDefinitionValues?: DetectorDefinitionFormikValues;
setActionMenu: (menuMount: MountPoint | undefined) => void;
}
export function ConfigureModel(props: ConfigureModelProps) {
const core = React.useContext(CoreServicesContext) as CoreStart;
const dispatch = useDispatch();
const location = useLocation();
const MDSQueryParams = getDataSourceFromURL(location);
const dataSourceEnabled = getDataSourceEnabled().enabled;
const dataSourceId = MDSQueryParams.dataSourceId;
useHideSideNavBar(true, false);
const detectorId = get(props, 'match.params.detectorId', '');
const { detector, hasError } = useFetchDetectorInfo(detectorId, dataSourceId);
const indexDataTypes = useSelector(
(state: AppState) => state.opensearch.dataTypes
);
const [isHCDetector, setIsHCDetector] = useState<boolean>(
props.initialValues ? props.initialValues.categoryFieldEnabled : false
);
const isLoading = useSelector(
(state: AppState) => state.opensearch.requesting
);
// Jump to top of page on first load
useEffect(() => {
scroll(0, 0);
}, []);
// When detector is loaded: get any category fields (if applicable) and
// get all index mappings based on detector's selected index
useEffect(() => {
if (detector && get(detector, 'categoryField', []).length > 0) {
setIsHCDetector(true);
}
if (detector?.indices) {
dispatch(getMappings(detector.indices[0], dataSourceId));
}
}, [detector]);
useEffect(() => {
if (dataSourceEnabled) {
if (props.isEdit) {
core.chrome.setBreadcrumbs([
MDS_BREADCRUMBS.ANOMALY_DETECTOR(dataSourceId),
MDS_BREADCRUMBS.DETECTORS(dataSourceId),
{
text: detector && detector.name ? detector.name : '',
href: constructHrefWithDataSourceId(`#/detectors/${detectorId}`, dataSourceId, false)
},
MDS_BREADCRUMBS.EDIT_MODEL_CONFIGURATION,
]);
} else {
core.chrome.setBreadcrumbs([
MDS_BREADCRUMBS.ANOMALY_DETECTOR(dataSourceId),
MDS_BREADCRUMBS.DETECTORS(dataSourceId),
MDS_BREADCRUMBS.CREATE_DETECTOR,
]);
}
} else {
if (props.isEdit) {
core.chrome.setBreadcrumbs([
BREADCRUMBS.ANOMALY_DETECTOR,
BREADCRUMBS.DETECTORS,
{
text: detector && detector.name ? detector.name : '',
href: `#/detectors/${detectorId}`,
},
BREADCRUMBS.EDIT_MODEL_CONFIGURATION,
]);
} else {
core.chrome.setBreadcrumbs([
BREADCRUMBS.ANOMALY_DETECTOR,
BREADCRUMBS.DETECTORS,
BREADCRUMBS.CREATE_DETECTOR,
]);
}
}
}, [detector]);
useEffect(() => {
if (hasError) {
if(dataSourceEnabled) {
props.history.push(
constructHrefWithDataSourceId('/detectors', dataSourceId, false)
);
}
else {
props.history.push('/detectors');
}
}
}, [hasError]);
const handleFormValidation = async (
formikProps: FormikProps<ModelConfigurationFormikValues>
) => {
if (props.isEdit && detector.curState === DETECTOR_STATE.RUNNING) {
core.notifications.toasts.addDanger(
'Detector cannot be updated while it is running'
);
} else {
formikProps.setSubmitting(true);
formikProps.setFieldTouched('featureList');
formikProps.setFieldTouched('categoryField', isHCDetector);
formikProps.setFieldTouched('shingleSize');
formikProps.validateForm().then((errors) => {
if (isEmpty(errors)) {
if (props.isEdit) {
// TODO: possibly add logic to also start RT and/or historical from here. Need to think
// about adding similar logic from edit detector definition page
const detectorToUpdate = formikToModelConfiguration(
formikProps.values,
detector
);
handleUpdateDetector(detectorToUpdate);
} else {
optionallySaveValues({
...formikProps.values,
categoryFieldEnabled: isHCDetector,
});
//@ts-ignore
props.setStep(3);
}
} else {
// TODO: can add focus to all components or possibly customize error message too
if (get(errors, 'featureList')) {
focusOnFirstWrongFeature(errors, formikProps.setFieldTouched);
} else if (get(errors, 'categoryField')) {
focusOnCategoryField();
}
core.notifications.toasts.addDanger(
'One or more input fields is invalid'
);
}
});
}
formikProps.setSubmitting(false);
};
const handleUpdateDetector = async (detectorToUpdate: Detector) => {
dispatch(updateDetector(detectorId, detectorToUpdate, dataSourceId))
.then((response: any) => {
core.notifications.toasts.addSuccess(
`Detector updated: ${response.response.name}`
);
props.history.push(
constructHrefWithDataSourceId(
`/detectors/${detectorId}/configurations/`,
dataSourceId,
false
)
);
})
.catch((err: any) => {
core.notifications.toasts.addDanger(
prettifyErrorMessage(
getErrorMessage(err, 'There was a problem updating the detector')
)
);
});
};
const optionallySaveValues = (values: ModelConfigurationFormikValues) => {
if (props.setInitialValues) {
props.setInitialValues(values);
}
};
const detectorToCreate = props.isEdit
? detector
: formikToDetector({
...props.detectorDefinitionValues,
...props.initialValues,
} as CreateDetectorFormikValues);
let renderDataSourceComponent: ReactElement | null = null;
if (dataSourceEnabled) {
const DataSourceMenu =
getDataSourceManagementPlugin()?.ui.getDataSourceMenu<DataSourceViewConfig>();
renderDataSourceComponent = (
<DataSourceMenu
setMenuMountPoint={props.setActionMenu}
componentType={'DataSourceView'}
componentConfig={{
activeOption: [{ id: dataSourceId }],
fullWidth: false,
savedObjects: getSavedObjectsClient(),
notifications: getNotifications(),
}}
/>
);
}
return (
<Formik
initialValues={
props.initialValues
? props.initialValues
: modelConfigurationToFormik(detector)
}
enableReinitialize={true}
onSubmit={() => {}}
validateOnMount={props.isEdit ? false : true}
validate={validateFeatures}
>
{(formikProps) => (
<Fragment>
{dataSourceEnabled && renderDataSourceComponent}
<EuiPage
style={{
marginTop: '-24px',
}}
>
<EuiPageBody>
<EuiPageHeader>
<EuiPageHeaderSection>
<EuiText
size="s"
data-test-subj="configureOrEditModelConfigurationTitle"
>
<h1>
{props.isEdit
? 'Edit model configuration'
: 'Configure model'}{' '}
</h1>
</EuiText>
<Fragment>
<EuiSpacer size="s" />
<EuiText size="s">
Set the index fields that you want to find anomalies for
by defining the model features. You can also set other
model parameters such as category field and shingle size
for more granular views. After you set the model features
and other optional parameters, you can preview your
anomalies from a sample feature output.{' '}
<EuiLink href={`${BASE_DOCS_LINK}/ad`} target="_blank">
Learn more
</EuiLink>
</EuiText>
<EuiSpacer size="s" />
</Fragment>
</EuiPageHeaderSection>
</EuiPageHeader>
<Features detector={detector} formikProps={formikProps} />
<EuiSpacer />
<CategoryField
isEdit={props.isEdit}
isHCDetector={isHCDetector}
categoryFieldOptions={getCategoryFields(indexDataTypes)}
setIsHCDetector={setIsHCDetector}
isLoading={isLoading}
formikProps={formikProps}
/>
<EuiSpacer />
<AdvancedSettings />
{!isEmpty(detectorToCreate) ? <EuiSpacer /> : null}
{!isEmpty(detectorToCreate) ? (
<SampleAnomalies
detector={detectorToCreate}
featureList={formikProps.values.featureList}
shingleSize={formikProps.values.shingleSize}
categoryFields={formikProps.values.categoryField}
errors={formikProps.errors}
setFieldTouched={formikProps.setFieldTouched}
/>
) : null}
</EuiPageBody>
</EuiPage>
<EuiFlexGroup
alignItems="center"
justifyContent="flexEnd"
gutterSize="s"
style={{ marginRight: '12px' }}
>
<EuiFlexItem grow={false}>
<EuiSmallButtonEmpty
onClick={() => {
if (props.isEdit) {
props.history.push(
constructHrefWithDataSourceId(
`/detectors/${detectorId}/configurations/`,
dataSourceId,
false
)
);
} else {
props.history.push(
constructHrefWithDataSourceId(
'/detectors',
dataSourceId,
false
)
);
}
}}
>
Cancel
</EuiSmallButtonEmpty>
</EuiFlexItem>
{props.isEdit ? null : (
<EuiFlexItem grow={false}>
<EuiSmallButton
iconSide="left"
iconType="arrowLeft"
fill={false}
data-test-subj="configureModelPreviousButton"
//@ts-ignore
onClick={() => {
optionallySaveValues({
...formikProps.values,
categoryFieldEnabled: isHCDetector,
});
//@ts-ignore
props.setStep(1);
}}
>
Previous
</EuiSmallButton>
</EuiFlexItem>
)}
<EuiFlexItem grow={false}>
{props.isEdit ? (
<EuiSmallButton
type="submit"
fill={true}
data-test-subj="updateDetectorButton"
//@ts-ignore
onClick={() => {
handleFormValidation(formikProps);
}}
>
Save changes
</EuiSmallButton>
) : (
<EuiSmallButton
type="submit"
iconSide="right"
iconType="arrowRight"
fill={true}
data-test-subj="configureModelNextButton"
isLoading={formikProps.isSubmitting}
//@ts-ignore
onClick={() => {
handleFormValidation(formikProps);
}}
>
Next
</EuiSmallButton>
)}
</EuiFlexItem>
</EuiFlexGroup>
</Fragment>
)}
</Formik>
);
}