forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGrafanaEvaluationBehavior.tsx
339 lines (308 loc) · 11.3 KB
/
GrafanaEvaluationBehavior.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
import { css } from '@emotion/css';
import React, { useCallback, useEffect, useState } from 'react';
import { RegisterOptions, useFormContext } from 'react-hook-form';
import { GrafanaTheme2, SelectableValue } from '@grafana/data';
import { Stack } from '@grafana/experimental';
import { Field, Icon, IconButton, Input, InputControl, Label, Switch, Tooltip, useStyles2 } from '@grafana/ui';
import { CombinedRuleGroup, CombinedRuleNamespace } from '../../../../../types/unified-alerting';
import { logInfo, LogMessages } from '../../Analytics';
import { useCombinedRuleNamespaces } from '../../hooks/useCombinedRuleNamespaces';
import { useUnifiedAlertingSelector } from '../../hooks/useUnifiedAlertingSelector';
import { RuleFormValues } from '../../types/rule-form';
import { GRAFANA_RULES_SOURCE_NAME } from '../../utils/datasource';
import { parsePrometheusDuration } from '../../utils/time';
import { CollapseToggle } from '../CollapseToggle';
import { EditCloudGroupModal } from '../rules/EditRuleGroupModal';
import { FolderAndGroup, useGetGroupOptionsFromFolder } from './FolderAndGroup';
import { GrafanaAlertStatePicker } from './GrafanaAlertStatePicker';
import { NeedHelpInfo } from './NeedHelpInfo';
import { RuleEditorSection } from './RuleEditorSection';
export const MIN_TIME_RANGE_STEP_S = 10; // 10 seconds
const forValidationOptions = (evaluateEvery: string): RegisterOptions => ({
required: {
value: true,
message: 'Required.',
},
validate: (value: string) => {
// parsePrometheusDuration does not allow 0 but does allow 0s
if (value === '0') {
return true;
}
try {
const millisFor = parsePrometheusDuration(value);
// 0 is a special value meaning for equals evaluation interval
if (millisFor === 0) {
return true;
}
try {
const millisEvery = parsePrometheusDuration(evaluateEvery);
return millisFor >= millisEvery
? true
: 'For duration must be greater than or equal to the evaluation interval.';
} catch (err) {
// if we fail to parse "every", assume validation is successful, or the error messages
// will overlap in the UI
return true;
}
} catch (error) {
return error instanceof Error ? error.message : 'Failed to parse duration';
}
},
});
const useIsNewGroup = (folder: string, group: string) => {
const { groupOptions } = useGetGroupOptionsFromFolder(folder);
const groupIsInGroupOptions = useCallback(
(group_: string) => groupOptions.some((groupInList: SelectableValue<string>) => groupInList.label === group_),
[groupOptions]
);
return !groupIsInGroupOptions(group);
};
function FolderGroupAndEvaluationInterval({
evaluateEvery,
setEvaluateEvery,
}: {
evaluateEvery: string;
setEvaluateEvery: (value: string) => void;
}) {
const styles = useStyles2(getStyles);
const { watch, setValue, getValues } = useFormContext<RuleFormValues>();
const [isEditingGroup, setIsEditingGroup] = useState(false);
const [groupName, folderName] = watch(['group', 'folder.title']);
const rulerRuleRequests = useUnifiedAlertingSelector((state) => state.rulerRules);
const groupfoldersForGrafana = rulerRuleRequests[GRAFANA_RULES_SOURCE_NAME];
const grafanaNamespaces = useCombinedRuleNamespaces(GRAFANA_RULES_SOURCE_NAME);
const existingNamespace = grafanaNamespaces.find((ns) => ns.name === folderName);
const existingGroup = existingNamespace?.groups.find((g) => g.name === groupName);
const isNewGroup = useIsNewGroup(folderName ?? '', groupName);
useEffect(() => {
if (!isNewGroup && existingGroup?.interval) {
setEvaluateEvery(existingGroup.interval);
}
}, [setEvaluateEvery, isNewGroup, setValue, existingGroup]);
const closeEditGroupModal = (saved = false) => {
if (!saved) {
logInfo(LogMessages.leavingRuleGroupEdit);
}
setIsEditingGroup(false);
};
const onOpenEditGroupModal = () => setIsEditingGroup(true);
const editGroupDisabled = groupfoldersForGrafana?.loading || isNewGroup || !folderName || !groupName;
const emptyNamespace: CombinedRuleNamespace = {
name: folderName,
rulesSource: GRAFANA_RULES_SOURCE_NAME,
groups: [],
};
const emptyGroup: CombinedRuleGroup = { name: groupName, interval: evaluateEvery, rules: [], totals: {} };
return (
<div>
<FolderAndGroup groupfoldersForGrafana={groupfoldersForGrafana?.result} />
{folderName && isEditingGroup && (
<EditCloudGroupModal
namespace={existingNamespace ?? emptyNamespace}
group={existingGroup ?? emptyGroup}
onClose={() => closeEditGroupModal()}
intervalEditOnly
hideFolder={true}
/>
)}
{folderName && groupName && (
<div className={styles.evaluationContainer}>
<Stack direction="column" gap={0}>
<div className={styles.marginTop}>
<Stack direction="column" gap={1}>
{getValues('group') && getValues('evaluateEvery') && (
<span>
All rules in the selected group are evaluated every {evaluateEvery}.{' '}
{!isNewGroup && (
<IconButton
name="pen"
aria-label="Edit"
disabled={editGroupDisabled}
onClick={onOpenEditGroupModal}
/>
)}
</span>
)}
</Stack>
</div>
</Stack>
</div>
)}
</div>
);
}
function ForInput({ evaluateEvery }: { evaluateEvery: string }) {
const styles = useStyles2(getStyles);
const {
register,
formState: { errors },
} = useFormContext<RuleFormValues>();
const evaluateForId = 'eval-for-input';
return (
<Stack direction="row" justify-content="flex-start" align-items="flex-start">
<Field
label={
<Label
htmlFor="evaluateFor"
description="Period in which an alert rule can be in breach of the condition until the alert rule fires."
>
Pending period
</Label>
}
className={styles.inlineField}
error={errors.evaluateFor?.message}
invalid={!!errors.evaluateFor?.message}
validationMessageHorizontalOverflow={true}
>
<Input id={evaluateForId} width={8} {...register('evaluateFor', forValidationOptions(evaluateEvery))} />
</Field>
</Stack>
);
}
function getDescription() {
const textToRender = 'Define how the alert rule is evaluated.';
const docsLink = 'https://grafana.com/docs/grafana/latest/alerting/fundamentals/alert-rules/rule-evaluation/';
return (
<Stack gap={0.5}>
{`${textToRender}`}
<NeedHelpInfo
contentText="Evaluation groups are containers for evaluating alert and recording rules. An evaluation group defines an evaluation interval - how often a rule is checked. Alert rules within the same evaluation group are evaluated sequentially"
externalLink={docsLink}
linkText={`Read about evaluation`}
title="Evaluation"
/>
</Stack>
);
}
export function GrafanaEvaluationBehavior({
evaluateEvery,
setEvaluateEvery,
existing,
}: {
evaluateEvery: string;
setEvaluateEvery: (value: string) => void;
existing: boolean;
}) {
const styles = useStyles2(getStyles);
const [showErrorHandling, setShowErrorHandling] = useState(false);
const { watch, setValue } = useFormContext<RuleFormValues>();
const isPaused = watch('isPaused');
return (
// TODO remove "and alert condition" for recording rules
<RuleEditorSection stepNo={3} title="Set alert evaluation behavior" description={getDescription()}>
<Stack direction="column" justify-content="flex-start" align-items="flex-start">
<FolderGroupAndEvaluationInterval setEvaluateEvery={setEvaluateEvery} evaluateEvery={evaluateEvery} />
<ForInput evaluateEvery={evaluateEvery} />
{existing && (
<Field htmlFor="pause-alert-switch">
<InputControl
render={() => (
<Stack gap={1} direction="row" alignItems="center">
<Switch
id="pause-alert"
onChange={(value) => {
setValue('isPaused', value.currentTarget.checked);
}}
value={Boolean(isPaused)}
/>
<label htmlFor="pause-alert" className={styles.switchLabel}>
Pause evaluation
<Tooltip placement="top" content="Turn on to pause evaluation for this alert rule." theme={'info'}>
<Icon tabIndex={0} name="info-circle" size="sm" className={styles.infoIcon} />
</Tooltip>
</label>
</Stack>
)}
name="isPaused"
/>
</Field>
)}
</Stack>
<CollapseToggle
isCollapsed={!showErrorHandling}
onToggle={(collapsed) => setShowErrorHandling(!collapsed)}
text="Configure no data and error handling"
className={styles.collapseToggle}
/>
{showErrorHandling && (
<>
<Field htmlFor="no-data-state-input" label="Alert state if no data or all values are null">
<InputControl
render={({ field: { onChange, ref, ...field } }) => (
<GrafanaAlertStatePicker
{...field}
inputId="no-data-state-input"
width={42}
includeNoData={true}
includeError={false}
onChange={(value) => onChange(value?.value)}
/>
)}
name="noDataState"
/>
</Field>
<Field htmlFor="exec-err-state-input" label="Alert state if execution error or timeout">
<InputControl
render={({ field: { onChange, ref, ...field } }) => (
<GrafanaAlertStatePicker
{...field}
inputId="exec-err-state-input"
width={42}
includeNoData={false}
includeError={true}
onChange={(value) => onChange(value?.value)}
/>
)}
name="execErrState"
/>
</Field>
</>
)}
</RuleEditorSection>
);
}
const getStyles = (theme: GrafanaTheme2) => ({
inlineField: css`
margin-bottom: 0;
`,
collapseToggle: css`
margin: ${theme.spacing(2, 0, 2, -1)};
`,
evaluateLabel: css`
margin-right: ${theme.spacing(1)};
`,
evaluationContainer: css`
color: ${theme.colors.text.secondary};
max-width: ${theme.breakpoints.values.sm}px;
font-size: ${theme.typography.size.sm};
`,
intervalChangedLabel: css`
margin-bottom: ${theme.spacing(1)};
`,
warningIcon: css`
justify-self: center;
margin-right: ${theme.spacing(1)};
color: ${theme.colors.warning.text};
`,
infoIcon: css`
margin-left: 10px;
`,
warningMessage: css`
color: ${theme.colors.warning.text};
`,
bold: css`
font-weight: bold;
`,
alignInterval: css`
margin-top: ${theme.spacing(1)};
margin-left: -${theme.spacing(1)};
`,
marginTop: css`
margin-top: ${theme.spacing(1)};
`,
switchLabel: css(`
color: ${theme.colors.text.primary},
cursor: 'pointer',
fontSize: ${theme.typography.bodySmall.fontSize},
`),
});