Adds widget to fetch and display system stats

This commit is contained in:
Alicia Sykes 2021-12-16 04:03:36 +00:00
parent 6e84dacd51
commit e0b09d48ee
6 changed files with 222 additions and 1 deletions

View File

@ -445,6 +445,24 @@ Pull recent load usage in 1, 5 and 15 minute intervals, from NetData.
--- ---
### System Info
Displays info about the server which Dashy is hosted on. Includes user + host, operating system, uptime and basic memory & load data.
<p align="center"><img width="400" src="https://i.ibb.co/rvDPBDF/system-info.png" /></p>
##### Options
No config options.
##### Example
```yaml
- type: system-info
```
---
## Dynamic Widgets ## Dynamic Widgets
### Iframe Widget ### Iframe Widget

View File

@ -24,7 +24,8 @@ require('./services/config-validator'); // Include and kicks off the config file
const statusCheck = require('./services/status-check'); // Used by the status check feature, uses GET const statusCheck = require('./services/status-check'); // Used by the status check feature, uses GET
const saveConfig = require('./services/save-config'); // Saves users new conf.yml to file-system const saveConfig = require('./services/save-config'); // Saves users new conf.yml to file-system
const rebuild = require('./services/rebuild-app'); // A script to programmatically trigger a build const rebuild = require('./services/rebuild-app'); // A script to programmatically trigger a build
const sslServer = require('./services/ssl-server'); const systemInfo = require('./services/system-info'); // Basic system info, for resource widget
const sslServer = require('./services/ssl-server'); // TLS-enabled web server
/* Helper functions, and default config */ /* Helper functions, and default config */
const printMessage = require('./services/print-message'); // Function to print welcome msg on start const printMessage = require('./services/print-message'); // Function to print welcome msg on start
@ -91,6 +92,16 @@ const app = express()
}).catch((response) => { }).catch((response) => {
res.end(JSON.stringify(response)); res.end(JSON.stringify(response));
}); });
})
// GET endpoint to return system info, for widget
.use(ENDPOINTS.systemInfo, (req, res) => {
try {
const results = systemInfo();
systemInfo.success = true;
res.end(JSON.stringify(results));
} catch (e) {
res.end(JSON.stringify({ success: false, message: e }));
}
}); });
/* Create HTTP server from app on port, and print welcome message */ /* Create HTTP server from app on port, and print welcome message */

24
services/system-info.js Normal file
View File

@ -0,0 +1,24 @@
/**
* Gets basic system info, for the resource usage widget
*/
const os = require('os');
module.exports = () => {
const meta = {
timestamp: new Date(),
uptime: os.uptime(),
hostname: os.hostname(),
username: os.userInfo().username,
system: `${os.version()} (${os.platform()})`,
};
const memory = {
total: `${Math.round(os.totalmem() / (1024 * 1024 * 1024))} GB`,
freePercent: (os.freemem() / os.totalmem()).toFixed(2),
};
const loadAv = os.loadavg();
const load = { one: loadAv[0], five: loadAv[1], fifteen: loadAv[2] };
return { meta, memory, load };
};

View File

@ -0,0 +1,158 @@
<template>
<div class="system-info-wrapper">
<div class="some-info" v-if="info">
<p class="host">
{{ info.username | isUsername }}{{ info.hostname }}
</p>
<p class="system">
{{ info.system }} <span class="gap">|</span> Uptime: {{ info.uptime | makeUptime }}
</p>
</div>
<div class="some-charts">
<div :id="`memory-${chartId}`" class="mem-chart"></div>
<div :id="`load-${chartId}`" class="load-chart"></div>
</div>
</div>
</template>
<script>
import axios from 'axios';
import WidgetMixin from '@/mixins/WidgetMixin';
import ChartingMixin from '@/mixins/ChartingMixin';
import { serviceEndpoints } from '@/utils/defaults';
export default {
mixins: [WidgetMixin, ChartingMixin],
components: {},
data() {
return {
info: null,
};
},
computed: {
endpoint() {
const baseUrl = process.env.VUE_APP_DOMAIN || window.location.origin;
return `${baseUrl}${serviceEndpoints.systemInfo}`;
},
},
filters: {
isUsername(username) {
return username ? `${username}@` : '';
},
makeUptime(seconds) {
if (!seconds || seconds === 0) return '';
if (seconds < 60) return `${seconds} seconds`;
if (seconds < 3600) return `${(seconds / 60).toFixed(1)} minutes`;
if (seconds < 86400) return `${(seconds / 3600).toFixed(2)} hours`;
if (seconds < 604800) return `${(seconds / 86400).toFixed(2)} days`;
if (seconds < 2629800) return `${(seconds / 604800).toFixed(2)} weeks`;
if (seconds < 31557600) return `${(seconds / 2629800).toFixed(2)} months`;
if (seconds >= 31557600) return `${(seconds / 31557600).toFixed(2)} years`;
return '';
},
},
methods: {
/* Extends mixin, and updates data. Called by parent component */
update() {
this.startLoading();
this.fetchData();
},
/* Make GET request to CoinGecko API endpoint */
fetchData() {
axios.get(this.endpoint)
.then((response) => {
if (!response.data.success) this.error('Error generating backend data');
this.processData(response.data);
})
.catch((dataFetchError) => {
this.error('Unable to fetch system info', dataFetchError);
})
.finally(() => {
this.finishLoading();
});
},
/* Assign data variables to the returned data */
processData(data) {
// Set class attributes for rendering
this.info = data.meta;
// Data for memory pie chart
const freeMem = parseInt(data.memory.freePercent, 10);
const memoryChartData = {
labels: ['Free', 'Used'],
datasets: [{
values: [freeMem, 100 - freeMem],
}],
};
this.generateMemoryPie(memoryChartData);
// Data for load bar chart
const loadBarChartData = {
labels: ['1 Min', '5 Mins', '15 Mins'],
datasets: [
{ values: [data.load.one, data.load.five, data.load.fifteen] },
],
};
this.generateLoadBar(loadBarChartData);
},
/* Using available memory info, generate simple pie chart */
generateMemoryPie(memoryChartData) {
return new this.Chart(`#memory-${this.chartId}`, {
title: 'Memory Usage',
data: memoryChartData,
type: 'donut',
height: 200,
strokeWidth: 12,
colors: ['#20e253', '#f80363'],
tooltipOptions: {
formatTooltipY: d => `${Math.round(d)}%`,
},
});
},
/* Using available load info, generate simple bar chart */
generateLoadBar(loadBarChartData) {
return new this.Chart(`#load-${this.chartId}`, {
title: 'Load Averages',
data: loadBarChartData,
type: 'bar',
height: 180,
colors: ['#04e4f4'],
barOptions: {
spaceRatio: 0.1,
},
});
},
},
};
</script>
<style lang="scss">
.system-info-wrapper {
color: var(--widget-text-color);
.some-info {
padding-bottom: 0.25rem;
border-bottom: 1px dashed var(--widget-text-color);
p.host {
font-size: 1.2rem;
margin: 0.25rem 0;
}
p.system {
font-size: 0.8rem;
margin: 0.25rem 0;
opacity: var(--dimming-factor);
}
span.gap {
margin: 0 0.4rem;
}
}
.some-charts {
display: flex;
.mem-chart, .load-chart {
width: 50%;
.chart-legend {
transform: translate(50px, 140px);
}
}
}
}
</style>

View File

@ -102,6 +102,13 @@
@error="handleError" @error="handleError"
:ref="widgetRef" :ref="widgetRef"
/> />
<SystemInfo
v-else-if="widgetType === 'system-info'"
:options="widgetOptions"
@loading="setLoaderState"
@error="handleError"
:ref="widgetRef"
/>
<NdCpuHistory <NdCpuHistory
v-else-if="widgetType === 'nd-cpu-history'" v-else-if="widgetType === 'nd-cpu-history'"
:options="widgetOptions" :options="widgetOptions"
@ -164,6 +171,7 @@ import ExchangeRates from '@/components/Widgets/ExchangeRates.vue';
import StockPriceChart from '@/components/Widgets/StockPriceChart.vue'; import StockPriceChart from '@/components/Widgets/StockPriceChart.vue';
import Jokes from '@/components/Widgets/Jokes.vue'; import Jokes from '@/components/Widgets/Jokes.vue';
import Flights from '@/components/Widgets/Flights.vue'; import Flights from '@/components/Widgets/Flights.vue';
import SystemInfo from '@/components/Widgets/SystemInfo.vue';
import NdCpuHistory from '@/components/Widgets/NdCpuHistory.vue'; import NdCpuHistory from '@/components/Widgets/NdCpuHistory.vue';
import NdLoadHistory from '@/components/Widgets/NdLoadHistory.vue'; import NdLoadHistory from '@/components/Widgets/NdLoadHistory.vue';
import NdRamHistory from '@/components/Widgets/NdRamHistory.vue'; import NdRamHistory from '@/components/Widgets/NdRamHistory.vue';
@ -189,6 +197,7 @@ export default {
StockPriceChart, StockPriceChart,
Jokes, Jokes,
Flights, Flights,
SystemInfo,
NdCpuHistory, NdCpuHistory,
NdLoadHistory, NdLoadHistory,
NdRamHistory, NdRamHistory,

View File

@ -45,6 +45,7 @@ module.exports = {
statusCheck: '/status-check', statusCheck: '/status-check',
save: '/config-manager/save', save: '/config-manager/save',
rebuild: '/config-manager/rebuild', rebuild: '/config-manager/rebuild',
systemInfo: '/system-info',
}, },
/* List of built-in themes, to be displayed within the theme-switcher dropdown */ /* List of built-in themes, to be displayed within the theme-switcher dropdown */
builtInThemes: [ builtInThemes: [