Files
Checkmate/client/src/Pages/Infrastructure/Create/index.jsx
T

638 lines
17 KiB
React
Raw Normal View History

//Components
import Breadcrumbs from "../../../Components/Breadcrumbs";
import ConfigBox from "../../../Components/ConfigBox";
import Dialog from "../../../Components/Dialog";
import FieldWrapper from "../../../Components/Inputs/FieldWrapper";
import Link from "../../../Components/Link";
import PauseCircleOutlineIcon from "@mui/icons-material/PauseCircleOutline";
import PlayCircleOutlineRoundedIcon from "@mui/icons-material/PlayCircleOutlineRounded";
import PulseDot from "../../../Components/Animated/PulseDot";
import Select from "../../../Components/Inputs/Select";
import TextInput from "../../../Components/Inputs/TextInput";
import { Box, Stack, Tooltip, Typography, Button, ButtonGroup } from "@mui/material";
import { CustomThreshold } from "./Components/CustomThreshold";
import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
import { createToast } from "../../../Utils/toastUtils";
// Utils
import NotificationsConfig from "../../../Components/NotificationConfig";
import { capitalizeFirstLetter } from "../../../Utils/stringUtils";
import { infrastructureMonitorValidation } from "../../../Validation/validation";
import { useGetNotificationsByTeamId } from "../../../Hooks/useNotifications";
import { useMonitorUtils } from "../../../Hooks/useMonitorUtils";
2025-06-12 12:44:46 +08:00
import { useParams } from "react-router-dom";
import { useSelector } from "react-redux";
import { useState, useEffect } from "react";
import { useTheme } from "@emotion/react";
2025-03-12 00:56:28 +05:30
import { useTranslation } from "react-i18next";
2025-07-29 00:42:56 +05:30
import {
useCreateMonitor,
useDeleteMonitor,
2025-07-29 00:42:56 +05:30
useFetchGlobalSettings,
useFetchHardwareMonitorById,
usePauseMonitor,
useUpdateMonitor,
2025-07-29 00:42:56 +05:30
} from "../../../Hooks/monitorHooks";
2024-12-09 13:35:48 +08:00
2024-10-31 15:19:57 -04:00
const CreateInfrastructureMonitor = () => {
const { user } = useSelector((state) => state.auth);
2025-03-14 22:12:52 -04:00
const { monitorId } = useParams();
const isCreate = typeof monitorId === "undefined";
const theme = useTheme();
const { t } = useTranslation();
2024-12-09 13:35:48 +08:00
// State
const [errors, setErrors] = useState({});
const [https, setHttps] = useState(false);
const [isOpen, setIsOpen] = useState(false);
const [updateTrigger, setUpdateTrigger] = useState(false);
const [infrastructureMonitor, setInfrastructureMonitor] = useState({
url: "",
name: "",
notifications: [],
notify_email: false,
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: "",
});
// Fetch monitor details if editing
const { statusColor, pagespeedStatusMsg, determineState } = useMonitorUtils();
const [monitor, isLoading] = useFetchHardwareMonitorById({
monitorId,
updateTrigger,
});
const [createMonitor, isCreating] = useCreateMonitor();
const [deleteMonitor, isDeleting] = useDeleteMonitor();
const [globalSettings, globalSettingsLoading] = useFetchGlobalSettings();
const [notifications, notificationsAreLoading] = useGetNotificationsByTeamId();
const [pauseMonitor, isPausing] = usePauseMonitor();
const [updateMonitor, isUpdating] = useUpdateMonitor();
const FREQUENCIES = [
{ _id: 0.25, name: t("time.fifteenSeconds") },
{ _id: 0.5, name: t("time.thirtySeconds") },
{ _id: 1, name: t("time.oneMinute") },
{ _id: 2, name: t("time.twoMinutes") },
{ _id: 5, name: t("time.fiveMinutes") },
{ _id: 10, name: t("time.tenMinutes") },
];
const CRUMBS = [
{ name: "Infrastructure monitors", path: "/infrastructure" },
...(isCreate
? [{ name: "Create", path: "/infrastructure/create" }]
: [
{ name: "Details", path: `/infrastructure/${monitorId}` },
{ name: "Configure", path: `/infrastructure/configure/${monitorId}` },
]),
];
const METRICS = ["cpu", "memory", "disk", "temperature"];
const METRIC_PREFIX = "usage_";
const MS_PER_MINUTE = 60000;
2025-07-26 15:24:25 +05:30
const hasAlertError = (errors) => {
return Object.keys(errors).filter((k) => k.startsWith(METRIC_PREFIX)).length > 0;
};
const getAlertError = (errors) => {
const errorKey = Object.keys(errors).find((key) => key.startsWith(METRIC_PREFIX));
return errorKey ? errors[errorKey] : null;
};
// Populate form fields if editing
useEffect(() => {
if (isCreate) {
if (globalSettingsLoading) return;
2025-07-30 23:14:35 +05:30
2025-07-31 16:04:41 +05:30
const gt = globalSettings?.data?.settings?.globalThresholds || {};
setHttps(false);
setInfrastructureMonitor({
url: "",
name: "",
notifications: [],
interval: 0.25,
2025-07-31 16:04:41 +05:30
cpu: gt.cpu !== undefined,
usage_cpu: gt.cpu !== undefined ? gt.cpu.toString() : "",
memory: gt.memory !== undefined,
usage_memory: gt.memory !== undefined ? gt.memory.toString() : "",
disk: gt.disk !== undefined,
usage_disk: gt.disk !== undefined ? gt.disk.toString() : "",
temperature: gt.temperature !== undefined,
usage_temperature: gt.temperature !== undefined ? gt.temperature.toString() : "",
secret: "",
});
} else if (monitor) {
2025-07-31 16:04:41 +05:30
const { thresholds = {} } = monitor;
setHttps(monitor.url.startsWith("https"));
setInfrastructureMonitor({
url: monitor.url.replace(/^https?:\/\//, ""),
name: monitor.name || "",
notifications: monitor.notifications || [],
interval: monitor.interval / MS_PER_MINUTE,
2025-07-31 16:04:41 +05:30
cpu: thresholds.usage_cpu !== undefined,
2025-07-30 23:14:35 +05:30
usage_cpu:
2025-07-31 16:04:41 +05:30
thresholds.usage_cpu !== undefined
? (thresholds.usage_cpu * 100).toString()
2025-07-30 23:14:35 +05:30
: "",
2025-07-31 16:04:41 +05:30
memory: thresholds.usage_memory !== undefined,
2025-07-30 23:14:35 +05:30
usage_memory:
2025-07-31 16:04:41 +05:30
thresholds.usage_memory !== undefined
? (thresholds.usage_memory * 100).toString()
2025-07-30 23:14:35 +05:30
: "",
2025-07-31 16:04:41 +05:30
disk: thresholds.usage_disk !== undefined,
2025-07-30 23:14:35 +05:30
usage_disk:
2025-07-31 16:04:41 +05:30
thresholds.usage_disk !== undefined
? (thresholds.usage_disk * 100).toString()
2025-07-30 23:14:35 +05:30
: "",
2025-07-31 16:04:41 +05:30
temperature: thresholds.usage_temperature !== undefined,
2025-07-30 23:14:35 +05:30
usage_temperature:
2025-07-31 16:04:41 +05:30
thresholds.usage_temperature !== undefined
? (thresholds.usage_temperature * 100).toString()
2025-07-30 23:14:35 +05:30
: "",
secret: monitor.secret || "",
2025-07-31 16:04:41 +05:30
});
}
}, [isCreate, monitor, globalSettings, globalSettingsLoading]);
2024-12-09 13:35:48 +08:00
// Handlers
const onSubmit = 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
});
console.log(newErrors);
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 = {
2025-03-15 02:48:02 -04:00
...(cpu ? { usage_cpu: usage_cpu / 100 } : {}),
...(memory ? { usage_memory: usage_memory / 100 } : {}),
...(disk ? { usage_disk: usage_disk / 100 } : {}),
...(temperature ? { usage_temperature: usage_temperature / 100 } : {}),
2024-12-09 13:35:48 +08:00
};
form = {
2025-06-12 12:44:46 +08:00
...(isCreate ? {} : { _id: monitorId }),
2024-12-09 13:35:48 +08:00
...rest,
description: form.name,
type: "hardware",
notifications: infrastructureMonitor.notifications,
thresholds,
};
2024-12-09 13:35:48 +08:00
2025-03-14 22:16:57 -04:00
// Handle create or update
2025-06-12 12:44:46 +08:00
isCreate
? await createMonitor({ monitor: form, redirect: "/infrastructure" })
: await updateMonitor({ monitor: form, redirect: "/infrastructure" });
};
2024-12-09 13:35:48 +08:00
const triggerUpdate = () => {
setUpdateTrigger(!updateTrigger);
};
const onChange = (event) => {
2024-12-10 11:30:38 +08:00
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 handlePause = async () => {
await pauseMonitor({ monitorId, triggerUpdate });
};
const handleRemove = async (event) => {
event.preventDefault();
await deleteMonitor({ monitor, redirect: "/infrastructure" });
};
const isBusy =
isLoading ||
isUpdating ||
isCreating ||
isDeleting ||
isPausing ||
notificationsAreLoading;
2024-10-31 15:19:57 -04:00
return (
<Box className="create-infrastructure-monitor">
<Breadcrumbs list={CRUMBS} />
2024-10-31 15:19:57 -04:00
<Stack
component="form"
onSubmit={onSubmit}
2024-10-31 15:19:57 -04:00
noValidate
spellCheck="false"
gap={theme.spacing(12)}
mt={theme.spacing(6)}
>
<Stack
direction="row"
gap={theme.spacing(2)}
2024-10-31 15:19:57 -04:00
>
<Box>
<Typography
component="h1"
variant="h1"
>
<Typography
component="span"
fontSize="inherit"
color={
!isCreate ? theme.palette.primary.contrastTextSecondary : undefined
}
>
{!isCreate ? infrastructureMonitor.name : t("createYour") + " "}
</Typography>
{isCreate ? (
<Typography
component="span"
fontSize="inherit"
fontWeight="inherit"
color={theme.palette.primary.contrastTextSecondary}
>
{t("monitor")}
</Typography>
) : (
<></>
)}
</Typography>
{!isCreate && (
<Stack
direction="row"
alignItems="center"
height="fit-content"
gap={theme.spacing(2)}
>
<Tooltip
title={pagespeedStatusMsg[determineState(monitor)]}
disableInteractive
slotProps={{
popper: {
modifiers: [
{
name: "offset",
options: { offset: [0, -8] },
},
],
},
}}
>
<Box>
<PulseDot color={statusColor[determineState(monitor)]} />
</Box>
</Tooltip>
<Typography
component="h2"
variant="monitorUrl"
>
{infrastructureMonitor.url?.replace(/^https?:\/\//, "") || "..."}
</Typography>
<Typography
position="relative"
variant="body2"
ml={theme.spacing(6)}
mt={theme.spacing(1)}
sx={{
"&:before": {
position: "absolute",
content: `""`,
width: theme.spacing(2),
height: theme.spacing(2),
borderRadius: "50%",
backgroundColor: theme.palette.primary.contrastTextTertiary,
opacity: 0.8,
left: theme.spacing(-5),
top: "50%",
transform: "translateY(-50%)",
},
}}
>
{t("editing")}
</Typography>
</Stack>
)}
</Box>
{!isCreate && (
<Box
alignSelf="flex-end"
ml="auto"
>
<Button
onClick={handlePause}
loading={isBusy}
variant="contained"
color="secondary"
sx={{
pl: theme.spacing(4),
pr: theme.spacing(6),
"& svg": {
mr: theme.spacing(2),
"& path": {
stroke: theme.palette.primary.contrastTextTertiary,
strokeWidth: 0.1,
},
},
}}
>
{monitor?.isActive ? (
<>
<PauseCircleOutlineIcon />
{t("pause")}
</>
) : (
<>
<PlayCircleOutlineRoundedIcon />
{t("resume")}
</>
)}
</Button>
<Button
loading={isBusy}
variant="contained"
color="error"
onClick={() => setIsOpen(true)}
sx={{ ml: theme.spacing(6) }}
>
{t("remove")}
</Button>
</Box>
)}
</Stack>
2024-10-31 15:19:57 -04:00
<ConfigBox>
2025-07-28 16:28:44 -04:00
<Stack>
2025-05-27 09:10:32 -07:00
<Typography
component="h2"
variant="h2"
>
{t("settingsGeneralSettings")}
</Typography>
2024-12-09 13:35:48 +08:00
<Typography component="p">
2025-03-12 00:56:28 +05:30
{t("infrastructureCreateGeneralSettingsDescription")}
2024-12-09 13:35:48 +08:00
</Typography>
<Typography component="p">
2025-03-12 00:56:28 +05:30
{t("infrastructureServerRequirement")}{" "}
2024-12-09 13:35:48 +08:00
<Link
level="primary"
url="https://github.com/bluewave-labs/checkmate-agent"
label={t("common.monitoringAgentName")}
2024-12-09 13:35:48 +08:00
/>
</Typography>
</Stack>
<Stack gap={theme.spacing(8)}>
<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"}
2025-03-12 00:56:28 +05:30
label={t("infrastructureServerUrlLabel")}
2024-12-09 13:35:48 +08:00
https={https}
2024-10-31 15:19:57 -04:00
value={infrastructureMonitor.url}
onChange={onChange}
error={errors["url"] ? true : false}
helperText={errors["url"]}
disabled={!isCreate}
2024-10-31 15:19:57 -04:00
/>
{isCreate && (
<FieldWrapper
label={t("infrastructureProtocol")}
labelVariant="p"
>
2025-05-27 09:10:32 -07:00
<ButtonGroup>
<Button
variant="group"
filled={https.toString()}
onClick={() => setHttps(true)}
>
{t("https")}
</Button>
<Button
variant="group"
filled={(!https).toString()}
onClick={() => setHttps(false)}
>
{t("http")}
</Button>
</ButtonGroup>
</FieldWrapper>
)}
<TextInput
2024-10-31 15:19:57 -04:00
type="text"
id="name"
2024-12-10 11:30:38 +08:00
name="name"
2025-03-12 00:56:28 +05:30
label={t("infrastructureDisplayNameLabel")}
2024-11-29 10:17:09 -05:00
placeholder="Google"
2024-10-31 15:19:57 -04:00
isOptional={true}
value={infrastructureMonitor.name}
onChange={onChange}
2024-10-31 15:19:57 -04:00
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"
2025-03-12 00:56:28 +05:30
label={t("infrastructureAuthorizationSecretLabel")}
2024-11-04 10:06:00 -05:00
value={infrastructureMonitor.secret}
onChange={onChange}
error={errors["secret"] ? true : false}
helperText={errors["secret"]}
2024-10-31 15:19:57 -04:00
/>
</Stack>
</ConfigBox>
<ConfigBox>
<Box>
2025-07-28 16:28:44 -04:00
<Typography
component="h2"
variant="h2"
>
{t("notificationConfig.title")}
</Typography>
<Typography component="p">{t("notificationConfig.description")}</Typography>
2024-10-31 15:19:57 -04:00
</Box>
<NotificationsConfig
notifications={notifications}
setMonitor={setInfrastructureMonitor}
setNotifications={infrastructureMonitor.notifications}
/>
2024-11-04 21:02:28 -05:00
</ConfigBox>
<ConfigBox>
<Box>
2025-05-27 09:10:32 -07:00
<Typography
component="h2"
variant="h2"
>
{t("infrastructureCustomizeAlerts")}
</Typography>
2024-11-04 21:02:28 -05:00
<Typography component="p">
2025-03-12 00:56:28 +05:30
{t("infrastructureAlertNotificationDescription")}
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}
2025-03-15 02:48:02 -04:00
fieldValue={String(infrastructureMonitor[METRIC_PREFIX + metric])}
onFieldChange={onChange}
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>
2025-05-27 09:10:32 -07:00
<Typography
component="h2"
variant="h2"
>
{t("distributedUptimeCreateAdvancedSettings")}
</Typography>
2024-10-31 15:19:57 -04:00
</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}
onChange={onChange}
items={FREQUENCIES}
2024-10-31 15:19:57 -04:00
/>
</Stack>
</ConfigBox>
<Stack
direction="row"
justifyContent="flex-end"
>
2025-02-13 15:20:12 -08:00
<Button
type="submit"
2024-10-31 15:19:57 -04:00
variant="contained"
2025-01-14 08:09:03 -05:00
color="accent"
loading={isBusy}
2024-10-31 15:19:57 -04:00
>
2025-05-27 09:10:32 -07:00
{t(isCreate ? "infrastructureCreateMonitor" : "infrastructureEditMonitor")}
2025-02-13 15:20:12 -08:00
</Button>
2024-10-31 15:19:57 -04:00
</Stack>
</Stack>
{!isCreate && (
<Dialog
open={isOpen}
theme={theme}
title={t("deleteDialogTitle")}
description={t("deleteDialogDescription")}
onCancel={() => setIsOpen(false)}
confirmationButtonLabel={t("delete")}
onConfirm={handleRemove}
/>
)}
2024-10-31 15:19:57 -04:00
</Box>
);
};
export default CreateInfrastructureMonitor;