Skip to content

Commit

Permalink
Styling improvements
Browse files Browse the repository at this point in the history
Restructured code
Update docs and README.md
  • Loading branch information
dormant-user committed Sep 23, 2024
1 parent a58614c commit 7a749da
Show file tree
Hide file tree
Showing 25 changed files with 251 additions and 88 deletions.
4 changes: 3 additions & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,9 @@ jobs:

name: Upload asset for ${{ matrix.platform.release_for }}
if: needs.release.outputs.release-flag == 'true'
runs-on: ${{ matrix.platform.os }}
runs-on:
- thevickypedia-default
- ${{ matrix.platform.os }}
permissions:
contents: write

Expand Down
115 changes: 114 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,114 @@
# SysMonk
# SysMonk

[![made-with-rust][rust-logo]][rust-src-page]

[![crates.io][crates-logo]][crate]

[![build][gh-logo]][build]
[![none-shall-pass][nsp-logo]][nsp]

#### Summary
[`SysMonk`][repo] is a system monitoring tool that provides a simple and easy-to-use interface to monitor system resources. It is designed to be lightweight and fast.

### Installation

```shell
cargo add SysMonk
```

### Usage
```rust
use sysmonk;

#[actix_rt::main]
async fn main() {
match sysmonk::start().await {
Ok(_) => {
println!("SysMonk session has ended")
}
Err(err) => {
eprintln!("Error starting SysMonk: {}", err)
}
}
}
```

<details>
<summary><strong>Download OS specific Executable</strong></summary>

###### macOS
```shell
curl -o SysMonk-Darwin-x86_64.tar.gz -LH "Accept: application/octet-stream" "https://github.com/thevickypedia/SysMonk/releases/latest/download/SysMonk-Darwin-x86_64.tar.gz"
```

###### Linux
```shell
curl -o SysMonk-Linux-x86_64.tar.gz -LH "Accept: application/octet-stream" "https://github.com/thevickypedia/SysMonk/releases/latest/download/SysMonk-Linux-x86_64.tar.gz"
```

###### RaspberryPi
```shell
curl -o SysMonk-RaspberryPi.tar.gz -LH "Accept: application/octet-stream" "https://github.com/thevickypedia/SysMonk/releases/latest/download/SysMonk-RaspberryPi.tar.gz"
```

###### Windows
```shell
curl -o SysMonk-Windows-x86_64.zip -LH "Accept: application/octet-stream" "https://github.com/thevickypedia/SysMonk/releases/latest/download/SysMonk-Windows-x86_64.zip"
```
</details>

#### Environment Variables

**Mandatory**
- **username**: Username for the API server.
- **password**: Password for the API server.

**Optional**
- **debug**: Boolean flag to enable debug level logging. Defaults to `false`
- **utc_logging**: Boolean flag to set timezone to UTC in the output logs. Defaults to `true`
- **host**: IP address to host the server. Defaults to `127.0.0.1` / `localhost`
- **port**: Port number to host the application. Defaults to `8000`
- **session_duration**: Time _(in seconds)_ each authenticated session should last. Defaults to `3600`
- **workers**: Number of workers to spin up for the server. Defaults to the number of physical cores.
- **max_connections**: Maximum number of concurrent connections per worker. Defaults to `3`
- **websites**: Vector of websites (_supports regex_) to add to CORS configuration. _Required only if tunneled via CDN_

## Crate
[https://crates.io/crates/SysMonk][crate]

### Cargo Docs - Official Runbook
[https://docs.rs/SysMonk/latest/sysmonk/][docs]

**Generator**
```shell
cargo doc --document-private-items --no-deps
```

## Linting
### Requirement
```shell
rustup component add clippy
```
### Usage
```shell
cargo clippy --no-deps --fix
```

## License & copyright

&copy; Vignesh Rao

Licensed under the [MIT License][license]

[repo]: https://github.com/thevickypedia/SysMonk
[license]: https://github.com/thevickypedia/SysMonk/blob/main/LICENSE
[build]: https://github.com/thevickypedia/SysMonk/actions/workflows/rust.yml
[rust-src-page]: https://www.rust-lang.org/
[rust-logo]: https://img.shields.io/badge/Made%20with-Rust-black?style=for-the-badge&logo=Rust
[gh-logo]: https://github.com/thevickypedia/SysMonk/actions/workflows/rust.yml/badge.svg
[nsp-logo]: https://github.com/thevickypedia/SysMonk/actions/workflows/none.yml/badge.svg
[nsp]: https://github.com/thevickypedia/SysMonk/actions/workflows/none.yml
[crate]: https://crates.io/crates/SysMonk
[gh-checks]: https://github.com/thevickypedia/SysMonk/actions/workflows/rust.yml
[crates-logo]: https://img.shields.io/crates/v/SysMonk.svg
[docs]: https://docs.rs/SysMonk/latest/sysmonk/
2 changes: 1 addition & 1 deletion src/constant.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use fernet::Fernet;
use std::collections::HashMap;
use std::env;
use std::sync::{Arc, Mutex};
use fernet::Fernet;

/// Struct to store the cargo information gathered at compile time using the `env!` macro.
#[allow(dead_code)]
Expand Down
19 changes: 8 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ extern crate actix_web;

use std::io;

use actix_web::{App, HttpServer, middleware, web};
use actix_web::{middleware, web, App, HttpServer};

/// Module for the structs and functions called during startup.
mod constant;
Expand Down Expand Up @@ -76,14 +76,11 @@ pub async fn start() -> io::Result<()> {
let server = HttpServer::new(application)
.workers(config.workers)
.max_connections(config.max_connections);
server.bind(host)?
.run()
.await
// match server.bind(host) {
// Ok(bound_server) => bound_server.run().await,
// Err(err) => {
// log::error!("Failed to bind server: {}", err);
// Err(err)
// }
// }
match server.bind(host) {
Ok(bound_server) => bound_server.run().await,
Err(err) => {
log::error!("Failed to bind server: {}", err);
Err(err)
}
}
}
4 changes: 2 additions & 2 deletions src/resources/disks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn size_converter(byte_size: f64) -> String {
format!("{:.2} {}", byte_size / 1024.0_f64.powi(index as i32), size_name[index])
}

/// Function to parse size string.
/// Function to parse size string for Linux.
///
/// # Arguments
///
Expand Down Expand Up @@ -50,7 +50,7 @@ fn parse_size(size_str: &str) -> String {
.replace("P", " PB")
}

/// Function to check if disk is physical for macOS specific.
/// Function to check if a disk is physical/virtual for macOS.
///
/// # Arguments
///
Expand Down
6 changes: 3 additions & 3 deletions src/resources/info.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashMap;
use crate::{resources, squire};
use chrono::Utc;
use std::collections::HashMap;
use sysinfo::{DiskExt, System, SystemExt};
use crate::{squire, resources};

/// Function to get total disk usage.
///
Expand Down Expand Up @@ -47,7 +47,7 @@ pub fn get_sys_info() -> HashMap<&'static str, HashMap<&'static str, String>> {
("architecture", os_arch.architecture),
("uptime", uptime),
("CPU_cores_raw", sys.cpus().len().to_string()
)]);
)]);
let mut hash_vec = vec![
("memory", total_memory),
("storage", total_storage)
Expand Down
3 changes: 3 additions & 0 deletions src/resources/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ pub mod info;
pub mod network;
/// This module contains processor related functions.
pub mod processor;
/// This module contains disk related functions.
pub mod disks;
/// This module contains system related functions.
pub mod system;
/// This module contains functions that are responsible to stream information via websockets.
pub mod stream;
4 changes: 2 additions & 2 deletions src/resources/network.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::collections::HashMap;
use crate::squire;
use reqwest;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::UdpSocket;
use crate::squire;

/// Function to retrieve the public IP address
///
Expand Down
2 changes: 1 addition & 1 deletion src/resources/processor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ pub fn get_name() -> Option<String> {
_ => {
log::error!("Unsupported operating system: {}", os);
Err("Unsupported operating system")
},
}
};
match result {
Ok(info) => Some(info),
Expand Down
10 changes: 5 additions & 5 deletions src/resources/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use std::collections::HashMap;
use sysinfo::{CpuExt, System, SystemExt};


use serde_json;
use crate::squire;
use serde_json;

/// Function to get docker stats via commandline.
///
Expand All @@ -18,24 +18,24 @@ fn get_docker_stats() -> Result<Vec<serde_json::Value>, Box<dyn std::error::Erro
Ok(output) if !output.is_empty() => {
let stats_result = squire::util::run_command(
"docker",
&["stats", "--no-stream", "--format", "{{json .}}"]
&["stats", "--no-stream", "--format", "{{json .}}"],
);
match stats_result {
Ok(stats) => stats,
Err(err) => {
log::error!("Error running docker stats: {}", err);
return Ok(vec![]);
},
}
}
}
Ok(_) => {
log::debug!("No running containers");
return Ok(vec![]);
},
}
Err(err) => {
log::error!("Error checking containers: {}", err);
return Ok(vec![]);
},
}
};
let stats: Vec<serde_json::Value> = stats_result
.lines()
Expand Down
8 changes: 4 additions & 4 deletions src/resources/system.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::str;
use serde::{Deserialize, Serialize};
use crate::squire;
use serde::{Deserialize, Serialize};
use std::str;

#[derive(Deserialize, Serialize, Debug)]
pub struct OperatingSystem {
Expand All @@ -21,7 +21,7 @@ fn unamem() -> String {
Err(_) => {
log::error!("Failed to execute command");
"".to_string()
},
}
}
}

Expand All @@ -38,7 +38,7 @@ fn unameu() -> String {
Err(_) => {
log::error!("Failed to execute command");
std::env::consts::OS.to_uppercase()
},
}
}
}

Expand Down
4 changes: 1 addition & 3 deletions src/routes/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,14 +115,13 @@ pub async fn logout(request: HttpRequest,
cookie.make_removal();
response.cookie(cookie);
} else {
log::debug!("No stored session found for {}", host);
log::debug!("{} - {}", auth_response.detail, host);
rendered = logout_template.render(minijinja::context!(
version => metadata.pkg_version,
detail => "You are not logged in. Please click the button below to proceed.",
show_login => true
)).unwrap();
}
// response.finish() is not required since setting the body will close the response
response.body(rendered)
}

Expand Down Expand Up @@ -176,7 +175,6 @@ pub async fn error(request: HttpRequest,
/// # Returns
///
/// Returns an `HttpResponse` with a redirect, setting a cookie with the failure detail.
#[allow(dead_code)]
pub fn failed_auth(auth_response: squire::authenticator::AuthToken) -> HttpResponse {
let mut response = HttpResponse::build(StatusCode::FOUND);
let detail = auth_response.detail;
Expand Down
6 changes: 3 additions & 3 deletions src/routes/basics.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::sync::Arc;
use actix_web::{web, HttpRequest, HttpResponse};
use actix_web::http::StatusCode;
use crate::{constant, squire};
use actix_web::http::StatusCode;
use actix_web::{web, HttpRequest, HttpResponse};
use std::sync::Arc;

/// Handles the health endpoint, returning a JSON response indicating the server is healthy.
///
Expand Down
5 changes: 5 additions & 0 deletions src/routes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ pub mod websocket;

use actix_web::web;

/// Configures the websocket service.
///
/// # Arguments
///
/// * `cfg` - A mutable reference to the Actix web `ServiceConfig` object.
pub fn configure_websocket(cfg: &mut web::ServiceConfig) {
cfg.service(websocket::echo);
}
Loading

0 comments on commit 7a749da

Please sign in to comment.