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

505 lines
15 KiB
React
Raw Normal View History

2024-11-19 11:40:45 +08:00
import { useParams } from "react-router-dom";
2024-11-19 16:01:08 +08:00
import { useEffect, useState } from "react";
2024-11-19 11:40:45 +08:00
import Breadcrumbs from "../../../Components/Breadcrumbs";
import { Stack, Box, Typography } from "@mui/material";
import { useTheme } from "@emotion/react";
2024-11-19 12:02:37 +08:00
import CustomGauge from "../../../Components/Charts/CustomGauge";
2024-11-19 13:35:00 +08:00
import AreaChart from "../../../Components/Charts/AreaChart";
import { useSelector } from "react-redux";
import { networkService } from "../../../main";
2024-11-20 12:42:06 +08:00
import PulseDot from "../../../Components/Animated/PulseDot";
import useUtils from "../../Monitors/utils";
2024-11-23 17:20:34 +08:00
import { useNavigate } from "react-router-dom";
2024-11-23 17:14:05 +08:00
import Empty from "./empty";
import { logger } from "../../../Utils/Logger";
2024-11-20 12:42:06 +08:00
import { formatDurationRounded, formatDurationSplit } from "../../../Utils/timeUtils";
2024-11-19 13:35:00 +08:00
import {
TzTick,
PercentTick,
InfrastructureTooltip,
} from "../../../Components/Charts/Utils/chartUtils";
import PropTypes from "prop-types";
2024-11-19 11:40:45 +08:00
const BASE_BOX_PADDING_VERTICAL = 4;
const BASE_BOX_PADDING_HORIZONTAL = 8;
const TYPOGRAPHY_PADDING = 8;
/**
* Converts bytes to gigabytes
* @param {number} bytes - Number of bytes to convert
* @returns {number} Converted value in gigabytes
*/
2024-11-19 16:01:08 +08:00
const formatBytes = (bytes) => {
2024-11-25 10:22:21 +08:00
if (bytes === undefined || bytes === null) return "0 GB";
2024-11-19 16:01:08 +08:00
if (typeof bytes !== "number") return "0 GB";
if (bytes === 0) return "0 GB";
2024-11-19 11:40:45 +08:00
const GB = bytes / (1024 * 1024 * 1024);
2024-11-19 16:01:08 +08:00
const MB = bytes / (1024 * 1024);
if (GB >= 1) {
return `${Number(GB.toFixed(0))} GB`;
} else {
return `${Number(MB.toFixed(0))} MB`;
}
2024-11-19 11:40:45 +08:00
};
2024-11-25 10:22:21 +08:00
/**
* Converts a decimal value to a percentage
*
* @function decimalToPercentage
* @param {number} value - Decimal value to convert
* @returns {number} Percentage representation
*
* @example
* decimalToPercentage(0.75) // Returns 75
* decimalToPercentage(null) // Returns 0
*/
const decimalToPercentage = (value) => {
2024-11-25 10:33:52 +08:00
if (value === null || value === undefined) return 0;
2024-11-25 10:22:21 +08:00
return value * 100;
};
/**
* Renders a base box with consistent styling
* @param {Object} props - Component properties
* @param {React.ReactNode} props.children - Child components to render inside the box
* @param {Object} props.sx - Additional styling for the box
* @returns {React.ReactElement} Styled box component
*/
const BaseBox = ({ children, sx = {} }) => {
2024-11-19 11:40:45 +08:00
const theme = useTheme();
return (
<Box
sx={{
height: "100%",
padding: `${theme.spacing(BASE_BOX_PADDING_VERTICAL)} ${theme.spacing(BASE_BOX_PADDING_HORIZONTAL)}`,
2024-11-19 11:40:45 +08:00
minWidth: 200,
width: 225,
backgroundColor: theme.palette.background.main,
border: 1,
borderStyle: "solid",
borderColor: theme.palette.border.light,
...sx,
2024-11-19 11:40:45 +08:00
}}
>
{children}
</Box>
);
};
BaseBox.propTypes = {
children: PropTypes.node.isRequired,
sx: PropTypes.object,
};
/**
* Renders a statistic box with a heading and subheading
* @param {Object} props - Component properties
* @param {string} props.heading - Primary heading text
* @param {string} props.subHeading - Secondary heading text
* @returns {React.ReactElement} Stat box component
*/
2024-11-19 11:40:45 +08:00
const StatBox = ({ heading, subHeading }) => {
return (
<BaseBox>
<Typography component="h2">{heading}</Typography>
<Typography>{subHeading}</Typography>
</BaseBox>
);
};
StatBox.propTypes = {
heading: PropTypes.string.isRequired,
subHeading: PropTypes.string.isRequired,
};
/**
* Renders a gauge box with usage visualization
* @param {Object} props - Component properties
* @param {number} props.value - Percentage value for gauge
* @param {string} props.heading - Box heading
* @param {string} props.metricOne - First metric label
* @param {string} props.valueOne - First metric value
* @param {string} props.metricTwo - Second metric label
* @param {string} props.valueTwo - Second metric value
* @returns {React.ReactElement} Gauge box component
*/
2024-11-19 11:40:45 +08:00
const GaugeBox = ({ value, heading, metricOne, valueOne, metricTwo, valueTwo }) => {
const theme = useTheme();
2024-11-19 11:40:45 +08:00
return (
<BaseBox>
2024-11-19 12:02:37 +08:00
<Stack
direction="column"
gap={theme.spacing(2)}
alignItems="center"
>
<CustomGauge
progress={value}
radius={100}
color={theme.palette.primary.main}
/>
<Typography component="h2">{heading}</Typography>
<Box
sx={{
width: "100%",
borderTop: `1px solid ${theme.palette.border.light}`,
}}
>
<Stack
justifyContent={"space-between"}
direction="row"
gap={theme.spacing(2)}
>
<Typography>{metricOne}</Typography>
<Typography>{valueOne}</Typography>
</Stack>
<Stack
justifyContent={"space-between"}
direction="row"
gap={theme.spacing(2)}
>
<Typography>{metricTwo}</Typography>
<Typography>{valueTwo}</Typography>
</Stack>
</Box>
</Stack>
2024-11-19 11:40:45 +08:00
</BaseBox>
);
};
GaugeBox.propTypes = {
2024-11-19 16:01:08 +08:00
value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
heading: PropTypes.string.isRequired,
metricOne: PropTypes.string.isRequired,
2024-11-19 16:01:08 +08:00
valueOne: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
metricTwo: PropTypes.string.isRequired,
2024-11-19 16:01:08 +08:00
valueTwo: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
};
/**
* Renders the infrastructure details page
* @returns {React.ReactElement} Infrastructure details page component
*/
2024-11-19 11:40:45 +08:00
const InfrastructureDetails = () => {
2024-11-23 17:20:34 +08:00
const navigate = useNavigate();
2024-11-19 11:40:45 +08:00
const theme = useTheme();
const { monitorId } = useParams();
const navList = [
{ name: "infrastructure monitors", path: "/infrastructure" },
{ name: "details", path: `/infrastructure/${monitorId}` },
];
2024-11-19 16:01:08 +08:00
const [monitor, setMonitor] = useState(null);
const { authToken } = useSelector((state) => state.auth);
2024-11-22 09:50:02 +08:00
const [dateRange, setDateRange] = useState("all");
2024-11-20 12:42:06 +08:00
const { statusColor, determineState } = useUtils();
// These calculations are needed because ResponsiveContainer
// doesn't take padding of parent/siblings into account
// when calculating height.
const chartContainerHeight = 300;
const totalChartContainerPadding =
parseInt(theme.spacing(BASE_BOX_PADDING_VERTICAL), 10) * 2;
const totalTypographyPadding = parseInt(theme.spacing(TYPOGRAPHY_PADDING), 10) * 2;
const areaChartHeight =
(chartContainerHeight - totalChartContainerPadding - totalTypographyPadding) * 0.95;
// end height calculations
2024-11-19 16:01:08 +08:00
const buildStatBoxes = (monitor) => {
let latestCheck = monitor?.checks[0] ?? null;
if (latestCheck === null) return [];
// Extract values from latest check
const physicalCores = latestCheck?.cpu?.physical_core ?? null;
const logicalCores = latestCheck?.cpu?.logical_core ?? null;
const cpuFrequency = latestCheck?.cpu?.frequency ?? null;
const cpuTemperature =
latestCheck?.cpu?.temperature?.reduce((acc, curr) => acc + curr, 0) /
latestCheck?.cpu?.temperature?.length ?? 0;
const memoryTotalBytes = latestCheck?.memory?.total_bytes ?? null;
const diskTotalBytes = latestCheck?.disk[0]?.total_bytes ?? null;
const os = latestCheck?.host?.os ?? null;
const platform = latestCheck?.host?.platform ?? null;
const osPlatform = os === null && platform === null ? null : `${os} ${platform}`;
return [
{
id: 0,
heading: "CPU (Physical)",
subHeading: physicalCores ? `${physicalCores} cores` : null,
},
{
id: 1,
heading: "CPU (Logical)",
subHeading: logicalCores ? `${logicalCores} cores` : null,
},
{
id: 2,
heading: "CPU Frequency",
subHeading: cpuFrequency ? `${(cpuFrequency / 1000).toFixed(2)} Ghz` : null,
},
{
id: 3,
heading: "Average CPU Temperature",
subHeading: cpuTemperature ? `${cpuTemperature.toFixed(2)} C` : null,
},
{
id: 4,
heading: "Memory",
subHeading: memoryTotalBytes ? formatBytes(memoryTotalBytes) : null,
},
{
id: 5,
heading: "Disk",
subHeading: diskTotalBytes ? formatBytes(diskTotalBytes) : null,
},
{ id: 6, heading: "Uptime", subHeading: "100%" },
{
id: 7,
heading: "Status",
subHeading: monitor?.status === true ? "Active" : "Inactive",
},
{
id: 8,
heading: "OS",
subHeading: osPlatform,
},
].filter((box) => box.subHeading !== null);
};
const buildGaugeBoxConfigs = (monitor) => {
let latestCheck = monitor?.checks[0] ?? null;
if (latestCheck === null) return [];
// Extract values from latest check
const memoryUsagePercent = latestCheck?.memory?.usage_percent ?? null;
const memoryUsedBytes = latestCheck?.memory?.used_bytes ?? null;
const memoryTotalBytes = latestCheck?.memory?.total_bytes ?? null;
const cpuUsagePercent = latestCheck?.cpu?.usage_percent ?? null;
const cpuPhysicalCores = latestCheck?.cpu?.physical_core ?? null;
const cpuFrequency = latestCheck?.cpu?.frequency ?? null;
return [
{
type: "memory",
value: memoryUsagePercent ? decimalToPercentage(memoryUsagePercent) : null,
heading: "Memory Usage",
metricOne: "Used",
valueOne: memoryUsedBytes ? formatBytes(memoryUsedBytes) : null,
metricTwo: "Total",
valueTwo: memoryTotalBytes ? formatBytes(memoryTotalBytes) : null,
},
{
type: "cpu",
value: cpuUsagePercent ? decimalToPercentage(cpuUsagePercent) : null,
heading: "CPU Usage",
metricOne: "Cores",
valueOne: cpuPhysicalCores ?? 0,
metricTwo: "Frequency",
valueTwo: cpuFrequency ? `${(cpuFrequency / 1000).toFixed(2)} Ghz` : null,
},
...(latestCheck?.disk ?? []).map((disk, idx) => ({
type: "disk",
diskIndex: idx,
value: decimalToPercentage(disk.usage_percent),
heading: `Disk${idx} usage`,
metricOne: "Used",
valueOne: formatBytes(disk.total_bytes - disk.free_bytes),
metricTwo: "Total",
valueTwo: formatBytes(disk.total_bytes),
})),
].filter(
(box) => box.value !== null && box.valueOne !== null && box.valueTwo !== null
);
};
const buildAreaChartConfigs = (monitor) => {
let latestCheck = monitor?.checks[0] ?? null;
if (latestCheck === null) return [];
const temps = monitor?.checks?.map((check) =>
check.cpu.temperature.map((temp, idx) => {
return { [`core${idx + 1}`]: temp };
})
);
console.log(temps);
console.log(latestCheck);
return [
{
type: "memory",
dataKey: latestCheck?.memory?.usage_percent ? "memory.usage_percent" : null,
heading: "Memory usage",
strokeColor: theme.palette.primary.main,
yLabel: "Memory Usage",
yDomain: [0, 1],
},
{
type: "cpu",
dataKey: latestCheck?.cpu?.usage_percent ? "cpu.usage_percent" : null,
heading: "CPU usage",
strokeColor: theme.palette.success.main,
yLabel: "CPU Usage",
yDomain: [0, 1],
},
...(latestCheck?.disk?.map((disk, idx) => ({
type: "disk",
diskIndex: idx,
dataKey: `disk[${idx}].usage_percent`,
heading: `Disk${idx} usage`,
strokeColor: theme.palette.warning.main,
yLabel: "Disk Usage",
yDomain: [0, 1],
})) || []),
].filter((box) => box.dataKey !== null);
};
// Fetch data
2024-11-19 16:01:08 +08:00
useEffect(() => {
const fetchData = async () => {
try {
const response = await networkService.getStatsByMonitorId({
authToken: authToken,
monitorId: monitorId,
2024-11-22 09:50:02 +08:00
sortOrder: "asc",
limit: null,
dateRange: dateRange,
numToDisplay: 50,
2024-11-22 09:50:02 +08:00
normalize: false,
2024-11-19 16:01:08 +08:00
});
setMonitor(response.data.data);
} catch (error) {
2024-11-23 17:20:34 +08:00
navigate("/not-found", { replace: true });
2024-11-25 10:49:16 +08:00
logger.error(error);
2024-11-19 16:01:08 +08:00
}
};
fetchData();
2024-11-25 11:22:19 +08:00
}, [authToken, monitorId, dateRange, navigate]);
2024-11-19 11:40:45 +08:00
const statBoxConfigs = buildStatBoxes(monitor);
const gaugeBoxConfigs = buildGaugeBoxConfigs(monitor);
const areaChartConfigs = buildAreaChartConfigs(monitor);
2024-11-19 11:40:45 +08:00
return (
<Box>
<Breadcrumbs list={navList} />
{monitor?.checks?.length > 0 ? (
2024-11-19 11:40:45 +08:00
<Stack
2024-11-19 16:01:08 +08:00
direction="column"
gap={theme.spacing(10)}
mt={theme.spacing(10)}
2024-11-19 11:40:45 +08:00
>
2024-11-19 16:01:08 +08:00
<Stack
direction="row"
gap={theme.spacing(8)}
>
2024-11-20 12:42:06 +08:00
<Box>
<PulseDot color={statusColor[determineState(monitor)]} />
</Box>
<Typography
alignSelf="end"
component="h1"
variant="h1"
>
{monitor.name}
</Typography>
<Typography alignSelf="end">{monitor.url || "..."}</Typography>
<Box sx={{ flexGrow: 1 }} />
<Typography alignSelf="end">
Checking every {formatDurationRounded(monitor?.interval)}
</Typography>
<Typography alignSelf="end">
Last checked {formatDurationSplit(monitor?.lastChecked).time}{" "}
{formatDurationSplit(monitor?.lastChecked).format} ago
</Typography>
2024-11-19 16:01:08 +08:00
</Stack>
<Stack
direction="row"
flexWrap="wrap"
2024-11-19 16:01:08 +08:00
gap={theme.spacing(8)}
>
{statBoxConfigs.map((statBox) => (
<StatBox
key={statBox.id}
{...statBox}
/>
))}
2024-11-19 16:01:08 +08:00
</Stack>
<Stack
direction="row"
gap={theme.spacing(8)}
>
{gaugeBoxConfigs.map((config) => (
<GaugeBox
key={`${config.type}-${config.diskIndex ?? ""}`}
value={config.value}
heading={config.heading}
metricOne={config.metricOne}
valueOne={config.valueOne}
metricTwo={config.metricTwo}
valueTwo={config.valueTwo}
/>
))}
2024-11-19 16:01:08 +08:00
</Stack>
<Stack
direction={"row"}
height={chartContainerHeight} // FE team HELP!
2024-11-19 16:01:08 +08:00
gap={theme.spacing(8)} // FE team HELP!
flexWrap="wrap" // //FE team HELP! Better way to do this?
sx={{
"& > *": {
flexBasis: `calc(50% - ${theme.spacing(8)})`,
maxWidth: `calc(50% - ${theme.spacing(8)})`,
},
}}
>
{areaChartConfigs.map((config) => (
<BaseBox key={`${config.type}-${config.diskIndex ?? ""}`}>
<Typography
component="h2"
padding={theme.spacing(8)}
>
{config.heading}
</Typography>
<AreaChart
height={areaChartHeight}
data={monitor?.checks ?? []}
dataKeys={[config.dataKey]}
xKey="createdAt"
yKey={config.dataKey}
2024-11-25 10:49:16 +08:00
yDomain={config.yDomain}
customTooltip={({ active, payload, label }) => (
<InfrastructureTooltip
label={label}
yKey={
config.type === "disk" ? "disk.usage_percent" : config.dataKey
}
yLabel={config.yLabel}
yIdx={config.diskIndex}
active={active}
payload={payload}
/>
)}
xTick={<TzTick />}
yTick={<PercentTick />}
strokeColor={config.strokeColor}
gradient={true}
gradientStartColor={config.strokeColor}
gradientEndColor="#ffffff"
/>
</BaseBox>
))}
2024-11-19 16:01:08 +08:00
</Stack>
2024-11-19 13:35:00 +08:00
</Stack>
) : (
2024-11-23 17:14:05 +08:00
<Empty
styles={{
border: 1,
borderColor: theme.palette.border.light,
borderRadius: theme.shape.borderRadius,
backgroundColor: theme.palette.background.main,
p: theme.spacing(30),
}}
/>
)}
</Box>
2024-11-19 11:40:45 +08:00
);
};
export default InfrastructureDetails;