RAM usage and player count graphs. Now uses serverHooks

This commit is contained in:
Benjamin Elsdon
2022-05-07 21:36:17 +08:00
Unverified
parent e6a94436dc
commit 9ed0d17975
14 changed files with 284 additions and 96 deletions
+4 -1
View File
@@ -1,8 +1,11 @@
import { WebsocketProvider } from './Context/WebsocketProvider';
import Dashboard from './Dashboard';
function App() {
return (
<Dashboard />
<WebsocketProvider>
<Dashboard />
</WebsocketProvider>
);
}
@@ -1,12 +1,11 @@
.graph {
position: absolute;
transform: translate(-50%, 0%);
top: 6%;
left: 50%;
float: left;
border-color: grey;
border-width: 1px;
border-style: solid;
border-radius: 8px;
width: 800px;
margin: 10px;
margin-left: 50px;
text-align: center;
}
@@ -1,94 +1,114 @@
import React, { useState, useEffect } from "react";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
import { useWebSocket, ReadyState } from "react-use-websocket/dist/lib/use-websocket";
import React, { Component, useState, useEffect } from "react";
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend } from "chart.js";
import { Line } from "react-chartjs-2";
import "./StatsWidget.css";
import WebsocketContext, { useWebsocket } from "../../Context/WebsocketProvider";
import { toHaveStyle } from "@testing-library/jest-dom/dist/matchers";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
);
ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement);
const CHART_COLORS = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
const CHART_COLORS = {
red: "rgb(255, 99, 132)",
orange: "rgb(255, 159, 64)",
yellow: "rgb(255, 205, 86)",
green: "rgb(75, 192, 192)",
blue: "rgb(54, 162, 235)",
purple: "rgb(153, 102, 255)",
grey: "rgb(201, 203, 207)",
};
const TICK_COUNT = 50;
const TICK_COUNT = 25;
const labels = [];
for (let i = 0; i <= TICK_COUNT; ++i) {
labels.push(i.toString());
labels.push(i.toString());
}
export default function StatsWidget() {
const protocol = window.location.protocol === "https:" ? "wss" : "wss"
const host = window.location.host;
const port = window.location.port;
export default class StatsWidget extends Component {
constructor(props) {
super(props);
const { sendMessage, lastMessage, readyState } = useWebSocket(protocol + "://"+ host +":" + port + "/gm");
this.state = {
graphHistory: [],
};
}
componentDidUpdate(lastProps) {
if (this.props.data !== this.props.ignoreData) {
if (this.props.serverUptime !== lastProps.serverUptime) {
var newGraph = this.state.graphHistory;
console.log(this.props);
newGraph.push({ tick: this.props.data });
if (newGraph.length > TICK_COUNT) {
newGraph.splice(0, 1);
}
this.setState({
graphHistory: newGraph,
});
}
}
}
render() {
return (
<div className="graph">
<p> { this.props.title } </p>
<p> {JSON.stringify(this.state.data)} </p>
<Line
datasetIdKey="1"
data={{
labels: this.state.graphHistory.map((gh, i) => this.state.graphHistory.length - i),
datasets: [
{
label: "",
data: this.state.graphHistory.map((gh) => gh.tick),
borderColor: CHART_COLORS.red,
fill: false,
cubicInterpolationMode: "monotone",
tension: 0.4,
},
],
}}
options={{
y: {
suggestedMin: this.props.suggestedYMin,
suggestedMax: this.props.suggestedYMax,
},
}}
/>
</div>
);
}
}
/*export default function StatsWidget() {
const [graphHistory, setGraphHistory] = useState([]);
const [lastMessage, connectionStatus, sendMessage] = useWebsocket();
useEffect(() => {
if (lastMessage !== null) {
const data = JSON.parse(lastMessage.data);
console.log(lastMessage())
if (lastMessage() !== null) {
const { data } = JSON.parse(lastMessage().data);
var newGraph = graphHistory;
newGraph.push({ time: new Date().getTime(), tick: data.object});
newGraph.push({ time: new Date().getTime(), tick: data.tickTimeElapsed });
if(newGraph.length > TICK_COUNT) {
newGraph.splice(0, 1);
}
setGraphHistory(newGraph);
}
}, [lastMessage, setGraphHistory]);
}, [graphHistory, lastMessage, setGraphHistory]);
/*const connectionStatus = {
const connectionStatus = {
[ReadyState.CONNECTING]: "Connecting",
[ReadyState.OPEN]: "Open",
[ReadyState.CLOSING]: "Closing",
[ReadyState.CLOSED]: "Closed",
[ReadyState.UNINSTANTIATED]: "Uninstantiated",
}[readyState];*/
}[readyState];
return (
<div className="graph">
<p> Server Performance (Ticks) </p>
<Line
datasetIdKey="1"
data={{
labels,
datasets: [
{
label: '',
data: graphHistory.map((l) => l.tick),
borderColor: CHART_COLORS.red,
fill: false,
cubicInterpolationMode: 'monotone',
tension: 0.4
}
]
}}
options={{
y: {
suggestedMin: 995,
suggestedMax: 1005
}
}}/>
</div>
);
}
}*/
@@ -0,0 +1,61 @@
import React, { useContext, useCallback, useState } from 'react'
import { useWebSocket as Websocket, ReadyState } from "react-use-websocket/dist/lib/use-websocket";
import { ReactIsInDevelopmentMode } from '../util/util';
const WebsocketContext = React.createContext();
const protocol = window.location.protocol === "https:" ? "wss" : "wss"
const host = window.location.host;
const port = window.location.port;
function getWebsocketURL() {
if(ReactIsInDevelopmentMode) {
return "wss://localhost:443/gm";
} else {
return protocol + "://"+ host +":" + port + "/gm";
}
}
export function useWebsocket() {
return useContext(WebsocketContext);
}
export function WebsocketProvider({ children }) {
const { sendMessage, lastMessage, readyState } = Websocket(getWebsocketURL());
const connectionStatus = useCallback(() => {
if(readyState === ReadyState.CONNECTING) {
return "Connecting";
} else if(readyState === ReadyState.OPEN) {
return "Open";
} else if(readyState === ReadyState.CLOSING) {
return "Closing";
} else if(readyState === ReadyState.CLOSED) {
return "Closed";
} else if(readyState === ReadyState.UNINSTANTIATED) {
return "Uninstantiated";
}
}, [readyState]);
const getLastMessage = useCallback(() => {
if(lastMessage != null) {
if(lastMessage.data != null) {
return JSON.parse(lastMessage.data);
}
}
return {};
}, [lastMessage]);
const send = useCallback((data) => {
sendMessage(data, false);
}, [sendMessage]);
return (
<WebsocketContext.Provider value={{lastMessage: getLastMessage, connectionStatus, sendMessage: send}}>
{children}
</WebsocketContext.Provider>
)
}
export default WebsocketContext;
+5
View File
@@ -3,4 +3,9 @@
background-color: #F8F9FB;
width: 100vw;
height: 100vh;
}
.content {
float: left;
width: calc(100vw - 350px);
}
+41 -11
View File
@@ -1,16 +1,46 @@
import React, { Component } from 'react'
import Sidepanel from './Components/Dashboard/Sidepanel/Sidepanel'
import StatsWidget from './Components/Dashboard/StatsWidget'
import React, { Component } from "react";
import Sidepanel from "./Components/Dashboard/Sidepanel/Sidepanel";
import StatsWidget from "./Components/Dashboard/StatsWidget";
import WebsocketContext, { useWebsocket } from "./Context/WebsocketProvider";
import './Dashboard.css'
import "./Dashboard.css";
import { bytesToMegabytes } from "./util/util";
export default class Dashboard extends Component {
render() {
return (
<div className='dashboard'>
<Sidepanel />
<StatsWidget />
static contextType = WebsocketContext;
constructor(props) {
super(props);
this.state = {
lastMessage: {
serverUptime: 0,
},
};
}
componentDidUpdate() {
if (typeof this.context.lastMessage().data !== "undefined") {
if (this.context.lastMessage().data.serverUptime !== this.state.lastMessage.serverUptime) {
//console.log(this.context.lastMessage().data);
this.setState({
lastMessage: this.context.lastMessage().data,
});
}
}
}
render() {
return (
<div className="dashboard">
<Sidepanel />
<div className="content">
<StatsWidget title="Server Performance (Ticks)" serverUptime={this.state.lastMessage.serverUptime} data={typeof this.state.lastMessage.tickTimeElapsed !== "undefined" ? this.state.lastMessage.tickTimeElapsed : -1} ignoreData={-1} suggestedYMin={995} suggestedYMax={1005} />
<StatsWidget title="Server Performance (RAM)" serverUptime={this.state.lastMessage.serverUptime} data={typeof this.state.lastMessage.getFreeMemory !== "undefined" ? bytesToMegabytes(this.state.lastMessage.getAllocatedMemory - this.state.lastMessage.getFreeMemory, 2) : -1} ignoreData={-1} suggestedYMin={0} suggestedYMax={bytesToMegabytes(this.state.lastMessage.getAllocatedMemory)} />
<StatsWidget title="Online Players" serverUptime={this.state.lastMessage.serverUptime} data={typeof this.state.lastMessage.playerCount !== "undefined" ? this.state.lastMessage.playerCount : -1} ignoreData={-1} suggestedYMin={0} suggestedYMax={10} />
</div>
)
}
</div>
);
}
}
+24
View File
@@ -0,0 +1,24 @@
import React from 'react';
export function ReactIsInDevelopmentMode() {
return '_self' in React.createElement('div');
}
export function formatBytesToString(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
export function bytesToMegabytes(bytes, decimals = 2) {
const dm = decimals < 0 ? 0 : decimals;
const k = 1024;
return parseFloat((bytes / Math.pow(k, 2)).toFixed(dm));
}