Files
Checkmate/Client/src/Pages/Infrastructure/CreateMonitor/index.jsx
T

422 lines
11 KiB
React
Raw Normal View History

2024-12-09 13:35:48 +08:00
// React, Redux, Router
import { useTheme } from "@emotion/react";
2024-12-10 11:30:38 +08:00
import { useNavigate } from "react-router-dom";
2024-10-31 15:19:57 -04:00
import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
2024-12-09 13:35:48 +08:00
// Utility and Network
2024-11-15 14:49:27 -05:00
import { infrastructureMonitorValidation } from "../../../Validation/validation";
2024-12-10 11:30:38 +08:00
import { createInfrastructureMonitor } from "../../../Features/InfrastructureMonitors/infrastructureMonitorsSlice";
2024-12-09 13:35:48 +08:00
import { capitalizeFirstLetter } from "../../../Utils/stringUtils";
// MUI
import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
//Components
import Breadcrumbs from "../../../Components/Breadcrumbs";
import Link from "../../../Components/Link";
2024-12-18 12:20:18 -08:00
import ConfigBox from "../../../Components/ConfigBox";
import TextInput from "../../../Components/Inputs/TextInput";
2024-12-09 13:35:48 +08:00
import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
import { createToast } from "../../../Utils/toastUtils";
2024-10-31 15:19:57 -04:00
import Checkbox from "../../../Components/Inputs/Checkbox";
2024-12-09 13:35:48 +08:00
import Select from "../../../Components/Inputs/Select";
import { CustomThreshold } from "./CustomThreshold";
const SELECT_VALUES = [
{ _id: 0.25, name: "15 seconds" },
{ _id: 0.5, name: "30 seconds" },
{ _id: 1, name: "1 minute" },
{ _id: 2, name: "2 minutes" },
{ _id: 5, name: "5 minutes" },
{ _id: 10, name: "10 minutes" },
];
const METRICS = ["cpu", "memory", "disk", "temperature"];
const METRIC_PREFIX = "usage_";
const MS_PER_MINUTE = 60000;
const hasAlertError = (errors) => {
return Object.keys(errors).filter((k) => k.startsWith(METRIC_PREFIX)).length > 0;
};
const getAlertError = (errors) => {
return Object.keys(errors).find((key) => key.startsWith(METRIC_PREFIX))
? errors[Object.keys(errors).find((key) => key.startsWith(METRIC_PREFIX))]
: null;
};
2024-10-31 15:19:57 -04:00
const CreateInfrastructureMonitor = () => {
2024-12-09 13:35:48 +08:00
const theme = useTheme();
const { user, authToken } = useSelector((state) => state.auth);
const monitorState = useSelector((state) => state.infrastructureMonitor);
const dispatch = useDispatch();
const navigate = useNavigate();
// State
const [errors, setErrors] = useState({});
const [https, setHttps] = useState(false);
const [infrastructureMonitor, setInfrastructureMonitor] = useState({
url: "",
name: "",
notifications: [],
interval: 0.25,
cpu: false,
usage_cpu: "",
2024-11-08 15:23:33 -05:00
memory: false,
usage_memory: "",
2024-11-08 15:23:33 -05:00
disk: false,
usage_disk: "",
temperature: false,
usage_temperature: "",
secret: "",
});
2024-12-09 13:35:48 +08:00
// Handlers
const handleCreateInfrastructureMonitor = async (event) => {
2024-11-11 11:16:06 -05:00
event.preventDefault();
2024-11-27 15:48:06 +08:00
2024-12-09 13:35:48 +08:00
// Build the form
let form = {
url: `http${https ? "s" : ""}://` + infrastructureMonitor.url,
name:
infrastructureMonitor.name === ""
? infrastructureMonitor.url
: infrastructureMonitor.name,
interval: infrastructureMonitor.interval * MS_PER_MINUTE,
cpu: infrastructureMonitor.cpu,
...(infrastructureMonitor.cpu
? { usage_cpu: infrastructureMonitor.usage_cpu }
: {}),
memory: infrastructureMonitor.memory,
...(infrastructureMonitor.memory
? { usage_memory: infrastructureMonitor.usage_memory }
: {}),
disk: infrastructureMonitor.disk,
...(infrastructureMonitor.disk
? { usage_disk: infrastructureMonitor.usage_disk }
: {}),
temperature: infrastructureMonitor.temperature,
...(infrastructureMonitor.temperature
? { usage_temperature: infrastructureMonitor.usage_temperature }
: {}),
secret: infrastructureMonitor.secret,
};
2024-11-27 15:48:06 +08:00
2024-12-09 13:35:48 +08:00
const { error } = infrastructureMonitorValidation.validate(form, {
abortEarly: false,
});
2024-10-31 15:19:57 -04:00
2024-12-09 13:35:48 +08:00
if (error) {
const newErrors = {};
error.details.forEach((err) => {
newErrors[err.path[0]] = err.message;
2024-10-31 15:19:57 -04:00
});
2024-12-09 13:35:48 +08:00
setErrors(newErrors);
createToast({ body: "Please check the form for errors." });
return;
2024-10-31 15:19:57 -04:00
}
2024-12-09 13:35:48 +08:00
// Build the thresholds for the form
const {
cpu,
usage_cpu,
memory,
usage_memory,
disk,
usage_disk,
temperature,
usage_temperature,
...rest
} = form;
const thresholds = {
...(cpu ? { usage_cpu: usage_cpu / 100 } : {}),
...(memory ? { usage_memory: usage_memory / 100 } : {}),
...(disk ? { usage_disk: usage_disk / 100 } : {}),
...(temperature ? { usage_temperature: usage_temperature / 100 } : {}),
};
form = {
2024-12-09 13:35:48 +08:00
...rest,
description: form.name,
teamId: user.teamId,
userId: user._id,
type: "hardware",
notifications: infrastructureMonitor.notifications,
thresholds,
};
2024-12-09 13:35:48 +08:00
const action = await dispatch(
createInfrastructureMonitor({ authToken, monitor: form })
);
if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Infrastructure monitor created successfully!" });
navigate("/infrastructure");
} else {
createToast({ body: "Failed to create monitor." });
}
};
2024-12-09 13:35:48 +08:00
2024-12-10 11:30:38 +08:00
const handleChange = (event) => {
const { value, name } = event.target;
2024-12-09 13:35:48 +08:00
setInfrastructureMonitor({
...infrastructureMonitor,
2024-12-10 11:30:38 +08:00
[name]: value,
2024-12-09 13:35:48 +08:00
});
2024-12-09 13:35:48 +08:00
const { error } = infrastructureMonitorValidation.validate(
2024-12-10 11:30:38 +08:00
{ [name]: value },
2024-12-09 13:35:48 +08:00
{ abortEarly: false }
);
setErrors((prev) => ({
...prev,
2024-12-10 11:30:38 +08:00
...(error ? { [name]: error.details[0].message } : { [name]: undefined }),
2024-12-09 13:35:48 +08:00
}));
};
2024-12-10 11:30:38 +08:00
const handleCheckboxChange = (event) => {
const { name } = event.target;
2024-12-09 13:35:48 +08:00
const { checked } = event.target;
setInfrastructureMonitor({
...infrastructureMonitor,
2024-12-10 11:30:38 +08:00
[name]: checked,
2024-12-09 13:35:48 +08:00
});
};
const handleNotifications = (event, type) => {
const { value } = event.target;
let notifications = [...infrastructureMonitor.notifications];
const notificationExists = notifications.some((notification) => {
if (notification.type === type && notification.address === value) {
return true;
2024-10-31 15:19:57 -04:00
}
2024-12-09 13:35:48 +08:00
return false;
});
if (notificationExists) {
notifications = notifications.filter((notification) => {
if (notification.type === type && notification.address === value) {
return false;
}
return true;
});
} else {
notifications.push({ type, address: value });
2024-10-31 15:19:57 -04:00
}
2024-12-09 13:35:48 +08:00
setInfrastructureMonitor((prev) => ({
...prev,
notifications,
}));
};
2024-10-31 15:19:57 -04:00
return (
<Box className="create-infrastructure-monitor">
<Breadcrumbs
list={[
2024-12-06 13:18:59 +08:00
{ name: "Infrastructure monitors", path: "/infrastructure" },
{ name: "create", path: `/infrastructure/create` },
2024-10-31 15:19:57 -04:00
]}
/>
<Stack
component="form"
className="create-infrastructure-monitor-form"
onSubmit={handleCreateInfrastructureMonitor}
noValidate
spellCheck="false"
gap={theme.spacing(12)}
mt={theme.spacing(6)}
>
<Typography
component="h1"
variant="h1"
>
<Typography
component="span"
fontSize="inherit"
>
Create your{" "}
</Typography>
<Typography
component="span"
variant="h2"
fontSize="inherit"
fontWeight="inherit"
>
2024-12-09 13:35:48 +08:00
monitor
2024-10-31 15:19:57 -04:00
</Typography>
</Typography>
<ConfigBox>
2024-12-09 13:35:48 +08:00
<Stack gap={theme.spacing(6)}>
<Typography component="h2">General settings</Typography>
<Typography component="p">
Here you can select the URL of the host, together with the friendly name and
authorization secret to connect to the server agent.
</Typography>
<Typography component="p">
The server you are monitoring must be running the{" "}
<Link
level="primary"
url="https://github.com/bluewave-labs/checkmate-agent"
label="Checkmate Monitoring Agent"
/>
</Typography>
</Stack>
2024-10-31 15:19:57 -04:00
<Stack gap={theme.spacing(15)}>
<TextInput
2024-12-09 13:35:48 +08:00
type="url"
id="url"
2024-12-10 11:30:38 +08:00
name="url"
2024-12-09 13:35:48 +08:00
startAdornment={<HttpAdornment https={https} />}
placeholder={"localhost:59232/api/v1/metrics"}
2024-11-04 10:06:00 -05:00
label="Server URL"
2024-12-09 13:35:48 +08:00
https={https}
2024-10-31 15:19:57 -04:00
value={infrastructureMonitor.url}
onChange={handleChange}
error={errors["url"] ? true : false}
helperText={errors["url"]}
2024-10-31 15:19:57 -04:00
/>
2024-12-09 13:35:48 +08:00
<Box>
<Typography component="p">Protocol</Typography>
<ButtonGroup>
<Button
variant="group"
filled={https.toString()}
onClick={() => setHttps(true)}
>
HTTPS
</Button>
<Button
variant="group"
filled={(!https).toString()}
onClick={() => setHttps(false)}
>
HTTP
</Button>
</ButtonGroup>
</Box>
<TextInput
2024-10-31 15:19:57 -04:00
type="text"
id="name"
2024-12-10 11:30:38 +08:00
name="name"
2024-11-29 10:17:09 -05:00
label="Display name"
placeholder="Google"
2024-10-31 15:19:57 -04:00
isOptional={true}
value={infrastructureMonitor.name}
onChange={handleChange}
error={errors["name"]}
/>
<TextInput
2024-11-04 10:06:00 -05:00
type="text"
id="secret"
2024-12-10 11:30:38 +08:00
name="secret"
2024-11-04 10:06:00 -05:00
label="Authorization secret"
value={infrastructureMonitor.secret}
onChange={handleChange}
error={errors["secret"] ? true : false}
helperText={errors["secret"]}
2024-10-31 15:19:57 -04:00
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
<Typography component="h2">Incident notifications</Typography>
<Typography component="p">
When there is an incident, notify users.
</Typography>
</Box>
<Stack gap={theme.spacing(6)}>
<Checkbox
id="notify-email-default"
label={`Notify via email (to ${user.email})`}
isChecked={infrastructureMonitor.notifications.some(
(notification) => notification.type === "email"
)}
value={user?.email}
2024-12-09 13:35:48 +08:00
onChange={(event) => handleNotifications(event, "email")}
2024-10-31 15:19:57 -04:00
/>
2024-11-04 21:02:28 -05:00
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
<Typography component="h2">Customize alerts</Typography>
<Typography component="p">
Send a notification to user(s) when thresholds exceed a specified
percentage.
2024-11-04 21:02:28 -05:00
</Typography>
</Box>
2024-11-05 14:20:17 -05:00
<Stack gap={theme.spacing(6)}>
2024-12-09 13:35:48 +08:00
{METRICS.map((metric) => {
return (
<CustomThreshold
key={metric}
infrastructureMonitor={infrastructureMonitor}
errors={errors}
checkboxId={metric}
2024-12-10 11:30:38 +08:00
checkboxName={metric}
2024-12-09 13:35:48 +08:00
checkboxLabel={
metric !== "cpu"
? capitalizeFirstLetter(metric)
: metric.toUpperCase()
}
2024-12-10 11:30:38 +08:00
onCheckboxChange={handleCheckboxChange}
2024-12-09 13:35:48 +08:00
isChecked={infrastructureMonitor[metric]}
fieldId={METRIC_PREFIX + metric}
2024-12-10 11:30:38 +08:00
fieldName={METRIC_PREFIX + metric}
2024-12-09 13:35:48 +08:00
fieldValue={infrastructureMonitor[METRIC_PREFIX + metric]}
2024-12-10 11:30:38 +08:00
onFieldChange={handleChange}
2024-12-09 13:35:48 +08:00
alertUnit={metric == "temperature" ? "°C" : "%"}
/>
);
})}
{/* Error text */}
{hasAlertError(errors) && (
2024-11-11 20:10:49 -05:00
<Typography
component="span"
className="input-error"
color={theme.palette.error.main}
2024-11-11 20:10:49 -05:00
mt={theme.spacing(2)}
sx={{
opacity: 0.8,
}}
>
2024-12-09 13:35:48 +08:00
{getAlertError(errors)}
2024-11-11 20:10:49 -05:00
</Typography>
)}
2024-10-31 15:19:57 -04:00
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
<Typography component="h2">Advanced settings</Typography>
</Box>
<Stack gap={theme.spacing(12)}>
<Select
id="interval"
2024-12-10 11:30:38 +08:00
name="interval"
2024-10-31 15:19:57 -04:00
label="Check frequency"
2024-11-07 15:27:40 -05:00
value={infrastructureMonitor.interval || 15}
2024-12-10 11:30:38 +08:00
onChange={handleChange}
2024-12-09 13:35:48 +08:00
items={SELECT_VALUES}
2024-10-31 15:19:57 -04:00
/>
</Stack>
</ConfigBox>
<Stack
direction="row"
justifyContent="flex-end"
>
<LoadingButton
variant="contained"
2025-01-14 08:09:03 -05:00
color="accent"
2024-10-31 15:19:57 -04:00
onClick={handleCreateInfrastructureMonitor}
loading={monitorState?.isLoading}
>
Create infrastructure monitor
</LoadingButton>
</Stack>
</Stack>
</Box>
);
};
export default CreateInfrastructureMonitor;