Compare commits

..

No commits in common. "master" and "release" have entirely different histories.

6 changed files with 71 additions and 122 deletions

2
Cargo.lock generated
View File

@ -1206,7 +1206,7 @@ dependencies = [
[[package]]
name = "rasp_mgr"
version = "2.0.4"
version = "1.0.0"
dependencies = [
"async-std",
"clap",

View File

@ -1,6 +1,6 @@
[package]
name = "rasp_mgr"
version = "2.0.4"
version = "1.0.0"
description = "A simple server manager for local newtrok"
authors = ["PiyushXCoder <piyush.raj.kit@gmail.com>"]
license = "GPL-3.0-only"
@ -12,17 +12,17 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = "2.33"
toml = "0.5"
clap = "2.33.3"
toml = "0.5.8"
tide = "0.16"
async-std = { version = "1.6", features = ["attributes"] }
tide = "0.16.0"
async-std = { version = "1.6.0", features = ["attributes"] }
serde = { version = "1.0", features = ["derive"] }
humantime = "2.1"
humantime = "2.1.0"
sys-info = "0.9"
libc = "0.2"
mnt = "0.3"
sys-info = "0.9.0"
libc = "0.2.97"
mnt = "0.3.1"
libmedium = "0.6"
libmedium = "0.6.0"

View File

@ -1,33 +0,0 @@
GET http://0.0.0.0:8080/sysinfo
HTTP/1.1 200 - OK
content-length: 788
content-type: application/json
date: Fri, 24 Dec 2021 16:01:32 GMT
###
GET http://0.0.0.0:8080/cmdquery
HTTP/1.1 200 - OK
content-length: 179
content-type: application/json
date: Fri, 24 Dec 2021 15:58:24 GMT
###
GET http://0.0.0.0:8080/exec/lsblk
HTTP/1.1 200 - OK
content-length: 533
content-type: text/plain;charset=utf-8
date: Fri, 24 Dec 2021 15:48:27 GMT
###
GET http://0.0.0.0:8080/exec/random
HTTP/1.1 400 - Bad Request
content-length: 30
content-type: application/json
date: Fri, 24 Dec 2021 16:05:03 GMT

View File

@ -1,29 +1,35 @@
# Maintainer: Rajnish Mishra <contact.rajnishmishra@gmail.com>
pkgname=raspmgr
pkgname=raspmgr-git
_pkgname=Rasp-Manager
pkgver=2.0.2
pkgver=1.0.0.r11.1901188
pkgrel=1
pkgdesc="A simple server manager for local network (especially for Raspberry Pi)"
arch=('any')
url="https://github.com/PiyushXCoder/${_pkgname}"
license=('GPL3')
makedepends=('git' 'cargo')
source=("${_pkgname}-${pkgver}.tar.gz::https://github.com/PiyushXCoder/${_pkgname}/archive/V${pkgver}.tar.gz")
sha256sums=('76df28aa278424420914737567085a358eddbbe23840103e72d59f2749d26838')
source=("git+${url}.git")
md5sums=('SKIP')
pkgver() {
cd "${_pkgname}"
v=$(grep -R -A3 '^version =' Cargo.toml | grep 'version =' | cut -d\" -f2)
printf "$v.r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)"
}
prepare() {
cd "${_pkgname}-${pkgver}"
cd "${_pkgname}"
sed -i 's/port = 8080/port = 80/g;s/\".\/static\"/\"\/var\/lib\/rasp_mgr\/static\"/g' Config.toml
}
build() {
cd "${_pkgname}-${pkgver}"
cd "${_pkgname}"
cargo build --release
}
package() {
cd "${_pkgname}-${pkgver}"
cd "${_pkgname}"
install -Dm755 "target/release/rasp_mgr" "${pkgdir}/usr/bin/rasp_mgr"
install -Dm644 "Config.toml" "${pkgdir}/etc/rasp_mgr/Config.toml"
install -Dm644 "rasp_mgr.service" "${pkgdir}/usr/lib/systemd/system/rasp_mgr.service"

View File

@ -14,11 +14,8 @@
use std::{path::Path, process::Command};
use config::Config;
use libmedium::{
parse_hwmons,
sensors::{Input, Sensor},
};
use tide::{http::StatusCode, log::warn, prelude::*, utils::After, Request, Response};
use tide::{prelude::*, Request, Response, http::StatusCode, log::warn};
use libmedium::{parse_hwmons,sensors::{Input, Sensor}};
mod config;
mod disks;
@ -39,20 +36,20 @@ struct SystemInfo {
swap_total: f64,
swap_used: f64,
disk: Vec<Disk>,
temperature: Vec<Temprature>,
temperature: Vec<Temprature>
}
#[derive(Serialize)]
struct Disk {
mount: String,
total: f64,
available: f64,
available: f64
}
#[derive(Serialize)]
struct Temprature {
label: String,
temp: f64,
temp: f64
}
#[async_std::main]
@ -62,21 +59,11 @@ async fn main() -> tide::Result<()> {
tide::log::start();
let mut app = tide::with_state(conf.clone());
app.with(After(|mut res: Response| async move {
if let Some(err) = res.downcast_error::<&str>() {
let err = err.to_owned();
res.set_body(json!({ "message": err }));
}
Ok(res)
}));
if let Some(val) = conf.static_dir {
let path = Path::new(&val);
if path.exists() && path.is_dir() {
app.at("").serve_dir(path.to_str().unwrap())?;
} else {
warn!("Static Directory dosen't exists!")
}
} else { warn!("Static Directory dosen't exists!") }
let path = path.join("index.html");
if path.exists() {
@ -84,11 +71,11 @@ async fn main() -> tide::Result<()> {
}
}
app.at("/sysinfo").get(system_info);
app.at("/cmdquery").get(cmd_query);
app.at("/exec/:command").get(exec_cmd);
app.at("/poweroff").get(poweroff);
app.at("/reboot").get(reboot);
app.at("/sysinfo").get(system_info);
app.at("/cmdquery").get(cmd_query);
app.listen(format!("{}:{}", conf.addr, conf.port)).await?;
Ok(())
}
@ -96,9 +83,7 @@ async fn main() -> tide::Result<()> {
async fn poweroff(_: Request<Config>) -> tide::Result {
async_std::task::spawn(async {
async_std::task::sleep(std::time::Duration::from_secs(3)).await;
Command::new("poweroff")
.spawn()
.expect("Failed to poweroff!");
Command::new("poweroff").spawn().expect("Failed to poweroff!");
});
Ok("Reqesting to poweroff. Please see green led for for activity".into())
}
@ -135,7 +120,7 @@ async fn system_info(_: Request<Config>) -> tide::Result {
disk.push(Disk {
mount: d.mount,
total: d.total as f64 / 1048576.0, // bytes to mb
available: d.available as f64 / 1048576.0, // bytes to mb
available: d.available as f64 / 1048576.0 // bytes to mb
});
}
@ -146,14 +131,15 @@ async fn system_info(_: Request<Config>) -> tide::Result {
let tmp = temp_sensor.read_input().unwrap();
temperature.push(Temprature {
label: temp_sensor.name(),
temp: tmp.as_degrees_celsius(),
temp: tmp.as_degrees_celsius()
});
}
}
let boottime = std::time::Duration::from_secs(match sys_info::boottime() {
Ok(s) => s.tv_sec as u64,
Err(_) => 0,
Err(_) => 0
});
let sys_info = SystemInfo {
@ -171,15 +157,10 @@ async fn system_info(_: Request<Config>) -> tide::Result {
swap_total,
swap_used,
disk,
temperature,
temperature
};
let body = tide::Body::from_json(&sys_info).map_err(|e| {
tide::log::error!("Error: {}", e);
tide::Error::from_str(StatusCode::ServiceUnavailable, "Internal server error!")
})?;
let res = Response::builder(StatusCode::Ok).body(body).build();
Ok(res)
Ok(json!(sys_info).to_string().into())
}
fn last_update() -> Option<String> {
@ -188,15 +169,14 @@ fn last_update() -> Option<String> {
let stdout = match cmd.output() {
Ok(out) => out.stdout,
Err(_) => return None,
Err(_) => return None
};
match String::from_utf8(stdout) {
Ok(val) => {
let s = val.split(" ").next()?;
return Some(s[1..s.len()-1].to_owned());
}
Err(_) => return None,
}, Err(_) => return None
}
}
@ -209,21 +189,19 @@ fn exec(cmd: &mut Command) -> String {
match String::from_utf8(out.unwrap().stdout) {
Ok(out) => return out,
Err(_) => return "Request timeout".to_owned(),
Err(_) => return "Request timeout".to_owned()
}
}
async fn exec_cmd(req: Request<Config>) -> tide::Result {
let cmd = req
.state()
.commands
.get(req.param("command").map_err(|e| {
let cmd = req.state().commands.get(
req.param("command").map_err(|e| {
tide::log::error!("Error: {}", e);
tide::Error::from_str(StatusCode::BadRequest, "Invalid Request!")
})?)
.ok_or_else(|| tide::Error::from_str(StatusCode::BadRequest, "No such command!"))?
.command
.as_str();
})?
).ok_or_else(|| {
tide::Error::from_str(StatusCode::BadRequest, "No such command!")
})?.command.as_str();
let args: Vec<_> = cmd.split_ascii_whitespace().collect();
Ok(exec(Command::new(&args[0]).args(&args[1..])).into())
}

View File

@ -1,6 +1,5 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
@ -9,7 +8,6 @@
<title>Rasp Manager</title>
<link rel="stylesheet" href="awsm.min.css">
</head>
<body>
<header>
<h1>Rasp Manager</h1>
@ -33,6 +31,7 @@
<script src="jquery-3.6.0.min.js"></script>
<script>
$.get("/sysinfo", function(data) {
var data = JSON.parse(data);
var area = $('#sysinfo');
var pushin = function(parent, label, dat) {
parent.append($('<b>').append(label))
@ -103,5 +102,4 @@
});
</script>
</body>
</html>