Skip to content

Commit

Permalink
feat(all): networking
Browse files Browse the repository at this point in the history
  • Loading branch information
SpikeHD committed Sep 25, 2023
1 parent 12df85e commit b95508e
Show file tree
Hide file tree
Showing 11 changed files with 143 additions and 32 deletions.
11 changes: 11 additions & 0 deletions backend/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub fn register_routes(app: &mut tide::Server<State>, settings: ApiSettings) {
app.at("/api/swap").get(swap);
app.at("/api/cpu").get(cpu);
app.at("/api/disk").get(disk);
app.at("/api/network").get(network);
app.at("/api/processes").get(processes);
app.at("/api/sysinfo").get(sysinfo);
}
Expand Down Expand Up @@ -112,6 +113,16 @@ pub async fn disk(_req: tide::Request<State>) -> Result<tide::Response, tide::Er
Ok(res)
}

pub async fn network(_req: tide::Request<State>) -> Result<tide::Response, tide::Error> {
let watcher = unsafe { RESOURCE_WATCHER.as_ref().unwrap() };
let mut res = tide::Response::new(200);

res.set_body(serde_json::to_vec(&watcher.network).unwrap());
res.set_content_type("application/json");

Ok(res)
}

pub async fn sysinfo(_req: tide::Request<State>) -> Result<tide::Response, tide::Error> {
unsafe {
if SYSTEM_INFO.is_none() {
Expand Down
23 changes: 22 additions & 1 deletion backend/src/resource_watcher.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::sync::{Arc, Mutex};
use serde::Serialize;
use sysinfo::{System, SystemExt, CpuExt, ProcessExt, PidExt, DiskExt};
use sysinfo::{System, SystemExt, CpuExt, ProcessExt, PidExt, DiskExt, NetworkExt};

use crate::api::ApiSettings;

Expand Down Expand Up @@ -34,13 +34,21 @@ pub struct Disk {
used: u64,
}

#[derive(Clone, Serialize)]
pub struct Network {
name: String,
recieve: u64,
transmit: u64,
}

#[derive(Clone)]
pub struct ResourceWatcher {
update_rate: u64,
pub mem_history: Arc<Mutex<Vec<Memory>>>,
pub swap_history: Arc<Mutex<Vec<Memory>>>,
pub cpu_history: Arc<Mutex<Vec<CPU>>>,
pub disks: Arc<Mutex<Vec<Disk>>>,
pub network: Arc<Mutex<Vec<Network>>>,
pub mem_history_max: usize,
pub cpu_history_max: usize,
pub process_list: Arc<Mutex<Vec<Process>>>,
Expand All @@ -55,6 +63,7 @@ impl ResourceWatcher {
swap_history: Arc::new(Mutex::new(Vec::new())),
cpu_history: Arc::new(Mutex::new(Vec::new())),
disks: Arc::new(Mutex::new(Vec::new())),
network: Arc::new(Mutex::new(Vec::new())),
mem_history_max: settings.mem_history_max as usize,
cpu_history_max: settings.cpu_history_max as usize,
process_list: Arc::new(Mutex::new(Vec::new())),
Expand All @@ -80,6 +89,7 @@ impl ResourceWatcher {
let mut swap_history = self.swap_history.as_ref().lock().unwrap();
let mut cpu_history = self.cpu_history.as_ref().lock().unwrap();
let mut disks = self.disks.as_ref().lock().unwrap();
let mut network = self.network.as_ref().lock().unwrap();
let mut process_list = self.process_list.as_ref().lock().unwrap();

system.refresh_cpu();
Expand Down Expand Up @@ -143,6 +153,17 @@ impl ResourceWatcher {
});
}

// Clear the old network list
network.clear();

for (name, data) in system.networks() {
network.push(Network {
name: name.to_string(),
recieve: data.received(),
transmit: data.transmitted(),
});
}

// Clear the old process list
process_list.clear();

Expand Down
39 changes: 31 additions & 8 deletions frontend/src/components/QuickStats.css
Original file line number Diff line number Diff line change
@@ -1,16 +1,39 @@
.quick-stats-outer {
display: flex;
flex-direction: column;
justify-content: space-evenly;
align-items: center;

width: 90%;
height: 120px;
}

.quick-stats {
display: flex;
flex-direction: row;
justify-content: space-around;
justify-content: space-evenly;
align-items: center;

width: 80%;
height: 120px;
width: 100%;
height: 100%;

margin: 24px;
text-align: center;
}

.quick-stats-header {
margin: 18px;
}

.quick-stats-title {
width: 100%;
text-align: center;

font-size: 24px;
font-weight: bold;
}

border: 1px solid var(--color-accent);
border-radius: 6px;
.stat-mini {
font-size: 12px;
}

.stat {
Expand All @@ -23,11 +46,11 @@
}

.stat-big {
font-size: 32px;
font-size: 28px;
font-weight: bold;
}

.stat-small {
font-size: 16px;
font-size: 14px;
font-weight: normal;
}
63 changes: 42 additions & 21 deletions frontend/src/components/QuickStats.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { bytesToReadable } from '../util/byte'
import './QuickStats.css'
import { ArrowDown } from './icons/ArrowDown'
import { ArrowUp } from './icons/ArrowUp'

interface Props {
sysinfo: SystemInfo;
memoryData: Memory[];
swapData: Memory[];
cpuData: CPU[];
diskData: Disk[];
networkData: Network[];
processList: Process[];
}

Expand All @@ -15,35 +18,53 @@ export function QuickStats(props: Props) {
const swapUse = props.swapData[props.swapData.length - 1]?.used
const diskUse = props.diskData.map(d => d.used).reduce((a, b) => a + b)
const diskTotal = props.diskData.map(d => d.total).reduce((a, b) => a + b)
const netRecieve = props.networkData.map(n => n.recieve).reduce((a, b) => a + b)
const netTransmit = props.networkData.map(n => n.transmit).reduce((a, b) => a + b)
const cpuPct = props.cpuData[props.cpuData.length - 1]?.used

return (
<div className="quick-stats">
<div className="stat">
<span className="stat-big">{bytesToReadable(memoryUse)}</span>
<span className="stat-small">{
(memoryUse / props.sysinfo.mem_size * 100).toFixed(2)
}% of total memory ({bytesToReadable(props.sysinfo.mem_size)})</span>
<div className="quick-stats-outer">
<div className="quick-stats-header">
<span className="quick-stats-title">Quick Stats</span>
</div>

<div className="stat">
<span className="stat-big">{bytesToReadable(swapUse)}</span>
<span className="stat-small">{
(swapUse / props.sysinfo.swap_size * 100).toFixed(2)
}% of total swap ({bytesToReadable(props.sysinfo.swap_size)})</span>
</div>
<div className="quick-stats">
<div className="stat">
<span className="stat-big">{bytesToReadable(memoryUse)}</span>
<span className="stat-small">{
(memoryUse / props.sysinfo.mem_size * 100).toFixed(2)
}% of total memory ({bytesToReadable(props.sysinfo.mem_size)})</span>
</div>

<div className="stat">
<span className="stat-big">{cpuPct.toFixed(2)}%</span>
<span className="stat-small">CPU usage</span>
</div>
<div className="stat">
<span className="stat-big">{bytesToReadable(swapUse)}</span>
<span className="stat-small">{
(swapUse / props.sysinfo.swap_size * 100).toFixed(2)
}% of total swap ({bytesToReadable(props.sysinfo.swap_size)})</span>
</div>

<div className="stat">
<span className="stat-big">{cpuPct.toFixed(2)}%</span>
<span className="stat-small">
<span className="stat-mini">({props.sysinfo.cpu_brand})</span>
</span>
</div>

<div className="stat">
<span className="stat-big">{bytesToReadable(diskUse)}</span>
<span className="stat-small">{
(diskUse / diskTotal * 100).toFixed(2)
}% of {props.diskData.length} disks</span>
<div className="stat">
<span className="stat-big">
{bytesToReadable(netRecieve)} <ArrowDown /> / {bytesToReadable(netTransmit)} <ArrowUp />
</span>
<span className="stat-small">Network RX / TX ({props.networkData.length} devices)</span>
</div>

<div className="stat">
<span className="stat-big">{bytesToReadable(diskUse)}</span>
<span className="stat-small">{
(diskUse / diskTotal * 100).toFixed(2)
}% of {props.diskData.length} disks</span>
</div>
</div>
</div>

)
}
9 changes: 9 additions & 0 deletions frontend/src/components/icons/ArrowDown.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import './icon.css'

export function ArrowDown() {
return (
<svg class="icon" focusable="false" aria-hidden="true" viewBox="0 0 24 24" data-testid="ArrowDropDownIcon">
<path d="m2 8 10 10 10-10z"></path>
</svg>
)
}
9 changes: 9 additions & 0 deletions frontend/src/components/icons/ArrowUp.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import './icon.css'

export function ArrowUp() {
return (
<svg class="icon" focusable="false" aria-hidden="true" viewBox="0 0 24 24" data-testid="ArrowDropUpIcon">
<path d="m2 16 10-10 10 10z"></path>
</svg>
)
}
4 changes: 4 additions & 0 deletions frontend/src/components/icons/icon.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.icon {
display: inline-block;
height: 20px;
}
1 change: 0 additions & 1 deletion frontend/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ export function App() {
</main>
</LocationProvider>
</div>

)
}

Expand Down
6 changes: 6 additions & 0 deletions frontend/src/pages/Home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export function Home() {
const [swapData, setSwapData] = useState([] as Memory[])
const [cpuData, setCpuData] = useState([] as CPU[])
const [diskData, setDiskData] = useState([] as Disk[])
const [networkData, setNetworkData] = useState([] as Network[])
const [processList, setProcessList] = useState([] as Process[])

useEffect(() => {
Expand All @@ -29,6 +30,10 @@ export function Home() {
const ddata = await dres.json()
setDiskData(ddata)

const nres = await fetch('/api/network')
const ndata = await nres.json()
setNetworkData(ndata)

const pres = await fetch('/api/processes')
const pdata = await pres.json()
setProcessList(pdata)
Expand Down Expand Up @@ -57,6 +62,7 @@ export function Home() {
swapData={swapData}
cpuData={cpuData}
diskData={diskData}
networkData={networkData}
processList={processList}
/>
</>
Expand Down
6 changes: 6 additions & 0 deletions frontend/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ interface Disk {
used: number,
}

interface Network {
name: string,
recieve: number,
transmit: number,
}

interface Process {
name: string;
pid: number;
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
"name": "procchi",
"scripts": {
"start": "cd ./frontend && bun run build && cd ../backend && cargo run -- -u test -k test",
"build": "cd ./frontend && bun run build && cd ../backend && cargo build --release"
"start:win": "cd ./frontend && pnpm run build && cd ../backend && cargo run -- -u test -k test",
"build": "cd ./frontend && bun run build && cd ../backend && cargo build --release",
"build:win": "cd ./frontend && pnpm run build && cd ../backend && cargo build --release"
}
}

0 comments on commit b95508e

Please sign in to comment.