Compare commits

..

14 Commits

20 changed files with 2321 additions and 145 deletions

1452
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -15,15 +15,22 @@ default = ["core", "events", "mc-vanilla"]
# Core runtime requirements for the currently implemented functionality.
core = ["dep:thiserror", "dep:tokio", "dep:tokio-stream", "dep:tokio-util"]
# Placeholder for upcoming event-driven functionality.
events = []
events = ["dep:uuid", "dep:chrono", "dep:regex"]
mc-vanilla = []
mc-vanilla = ["dep:serde", "dep:serde_json", "dep:reqwest"]
# Add new feature groups here; attach their optional dependencies to the relevant feature list.
[dependencies]
async-trait = "0.1.89"
chrono = {version = "0.4.42", optional = true}
regex = {version = "1.12.2", optional = true}
reqwest = { version = "0.12.24", optional = true, features = ["json"] }
serde = { version = "1.0.228", optional = true, features = ["derive"] }
serde_json = {version = "1.0.145", optional = true}
thiserror = { version = "2.0.17", optional = true }
# Core async runtime and utilities
# Add new feature-specific optional dependencies alongside the relevant feature entry above.
tokio = { version = "1.48.0", features = ["process", "rt-multi-thread", "macros", "io-std", "io-util"], optional = true }
tokio-stream = { version = "0.1.17", features = ["full", "io-util", "signal", "tokio-util"], optional = true }
tokio-util = { version = "0.7.17", features = ["full"], optional = true }
uuid = { version = "1.19.0", features = ["serde", "v4"], optional = true }

View File

@@ -1,13 +1,21 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="assets/banner-dark.png">
<source media="(prefers-color-scheme: light)" srcset="assets/banner-light.png">
<img src="assets/banner-light.png" alt="Project Banner">
</picture>
<img src="assets/banner.svg" alt="Project Banner">
> [!IMPORTANT]
> MineGuard is currently in active development and breaking updates can be merged to the main branch any time
![Language](https://img.shields.io/badge/Language-Rust-orange?logo=rust&style=flat-square)
![Status](https://img.shields.io/badge/Status-In%20Development-blueviolet?style=flat-square)
![License](https://img.shields.io/github/license/H3ct0r55/mineguard?style=flat-square)
![Last Commit](https://img.shields.io/github/last-commit/H3ct0r55/mineguard?style=flat-square)
# MineGuard
Rust based Minecraft server lifecycle controller and interface
---
<div align="center">
<a href="./LICENSE">MIT License</a> • H3cx
<a href="./LICENSE">MIT License</a> • h3cx
Built on coffee, late nights, and a fully up-to-date Arch install (btw).
</div>

7
assets/banner.svg Normal file
View File

@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 960 288" version="1.1" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;"><style>
:root { color-scheme: light dark; }
#Candi2 { fill: #000000; }
@media (prefers-color-scheme: dark) {
#Candi2 { fill: #ffffff; }
}
</style><rect id="Artboard1" x="0" y="0" width="960" height="288" style="fill:none;" /><path id="Candi2" d="M572.408,105.247l-0,50.499c-0,27.084 -58.055,74.003 -92.408,84.254c-34.353,-10.25 -92.408,-57.17 -92.408,-84.254l-0,-107.746l38.689,0l45.705,45.705l45.705,-45.705l54.715,0l-0,43.383l-27.358,0l0,-16.026l-16.026,-0l-57.037,57.037l-57.037,-57.037l0,79.563c0.096,2.885 9.718,14.902 14.778,20.045c14.344,14.58 34.069,28.878 50.272,35.919c16.203,-7.041 35.928,-21.339 50.272,-35.919c5.06,-5.143 14.683,-17.16 14.778,-20.045l0,-22.526l-45.705,0l27.147,-27.147l45.915,0Z" /></svg>

After

Width:  |  Height:  |  Size: 941 B

View File

@@ -0,0 +1,93 @@
use std::fmt::{self, Display};
use uuid::{Uuid, timestamp};
use crate::instance::InstanceStatus;
use super::line::StreamLine;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventPayload {
#[cfg(feature = "events")]
StateChange {
old: InstanceStatus,
new: InstanceStatus,
},
StdLine {
line: StreamLine,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstanceEvent {
pub id: Uuid,
pub timestamp: chrono::DateTime<chrono::Utc>,
pub payload: EventPayload,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InternalEvent {
ServerStarted,
}
impl InstanceEvent {
pub fn stdout<S: Into<String>>(line: S) -> Self {
let line = line.into();
let s_line = StreamLine::stdout(line);
let timestamp = s_line.extract_timestamp().unwrap_or(chrono::Utc::now());
let payload = EventPayload::StdLine { line: s_line };
Self {
id: Uuid::new_v4(),
timestamp,
payload,
}
}
pub fn stderr<S: Into<String>>(line: S) -> Self {
let line = line.into();
let s_line = StreamLine::stderr(line);
let timestamp = s_line.extract_timestamp().unwrap_or(chrono::Utc::now());
let payload = EventPayload::StdLine { line: s_line };
Self {
id: Uuid::new_v4(),
timestamp,
payload,
}
}
pub fn new(payload: EventPayload) -> Self {
let timestamp = chrono::Utc::now();
Self {
id: Uuid::new_v4(),
timestamp,
payload,
}
}
}
impl Display for InstanceEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let head = format!(
"UUID: {}\nTimestamp:{}\nPayload:\n",
self.id, self.timestamp
);
match self.payload.clone() {
EventPayload::StdLine { line } => {
let full = format!("{}{}", head, line);
writeln!(f, "{}", full)
}
#[cfg(feature = "events")]
EventPayload::StateChange { old, new } => {
let full = format!("{}State changed: {:?} -> {:?}", head, old, new);
writeln!(f, "{}", full)
}
}
}
}

72
src/config/stream/line.rs Normal file
View File

@@ -0,0 +1,72 @@
use std::fmt::{self, Display};
use regex::Regex;
#[cfg(feature = "events")]
use chrono::{DateTime, Local, NaiveTime, TimeZone, Utc};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamSource {
Stdout,
Stderr,
#[cfg(feature = "events")]
Event,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamLine {
pub line: String,
pub source: StreamSource,
}
impl StreamLine {
pub fn new<S: Into<String>>(line: S, source: StreamSource) -> Self {
let line = line.into();
let re = Regex::new(r#"^\[[^\]]*\]\s*\[[^\]]*\]:\s*"#).unwrap();
let line = re.replace(&line, "").to_string();
Self { line, source }
}
pub fn stdout<S: Into<String>>(line: S) -> Self {
let line = line.into();
Self {
line,
source: StreamSource::Stdout,
}
}
pub fn stderr<S: Into<String>>(line: S) -> Self {
let line = line.into();
Self {
line,
source: StreamSource::Stderr,
}
}
pub fn msg(&self) -> String {
self.line.clone()
}
pub fn extract_timestamp(&self) -> Option<DateTime<Utc>> {
let input = self.line.as_str();
let re = Regex::new(r"\[(.*?)\]").unwrap();
let time_s = re.captures(input).map(|v| v[1].to_string());
time_s.as_ref()?;
let time = NaiveTime::parse_from_str(&time_s.unwrap(), "%H:%M:%S").ok()?;
let today = Local::now().date_naive();
let naive_dt = today.and_time(time);
let local_dt = Local.from_local_datetime(&naive_dt).unwrap();
let utc_dt = local_dt.with_timezone(&Utc);
Some(utc_dt)
}
}
impl Display for StreamLine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.line)
}
}

View File

@@ -1,39 +1,17 @@
use std::fmt::{self, Display};
#[cfg(feature = "mc-vanilla")]
use crate::error::ParserError;
/// Identifies which process stream produced a line of output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamSource {
Stdout,
Stderr,
#[cfg(feature = "events")]
Event,
}
/// Captures a single line of process output along with its origin stream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamLine {
line: String,
source: StreamSource,
}
#[cfg(feature = "events")]
pub struct InstanceEvent {}
#[cfg(feature = "events")]
pub enum Events {}
#[cfg(feature = "mc-vanilla")]
pub struct LogMeta {
time: String,
thread: String,
level: LogLevel,
msg: String,
pub time: String,
pub thread: String,
pub level: LogLevel,
pub msg: String,
}
#[cfg(feature = "mc-vanilla")]
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum LogLevel {
Info,
Warn,
@@ -119,36 +97,3 @@ impl Display for LogLevel {
}
}
}
impl StreamLine {
pub fn new<S: Into<String>>(line: S, source: StreamSource) -> Self {
Self {
line: line.into(),
source,
}
}
pub fn stdout<S: Into<String>>(line: S) -> Self {
Self {
line: line.into(),
source: StreamSource::Stdout,
}
}
pub fn stderr<S: Into<String>>(line: S) -> Self {
Self {
line: line.into(),
source: StreamSource::Stderr,
}
}
pub fn msg(&self) -> String {
self.line.clone()
}
}
impl Display for StreamLine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.line)
}
}

10
src/config/stream/mod.rs Normal file
View File

@@ -0,0 +1,10 @@
mod event;
mod line;
#[cfg(feature = "mc-vanilla")]
mod log;
pub use event::InternalEvent;
pub use event::{EventPayload, InstanceEvent};
pub use line::{StreamLine, StreamSource};
#[cfg(feature = "mc-vanilla")]
pub use log::{LogLevel, LogMeta};

View File

@@ -3,16 +3,19 @@ use std::{
str::FromStr,
};
use serde::{Deserialize, Serialize};
use tokio::sync::watch;
use crate::error::VersionError;
/// Identifies the type of Minecraft distribution supported by the configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub enum MinecraftType {
Vanilla,
}
/// Semantic release version parsed from strings like `1.20.4`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Version {
pub major: u32,
pub minor: u32,
@@ -20,7 +23,7 @@ pub struct Version {
}
/// Snapshot version parsed from strings like `23w13b`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Snapshot {
pub year: u32,
pub week: u32,
@@ -28,7 +31,7 @@ pub struct Snapshot {
}
/// Enum covering both release and snapshot Minecraft version formats.
#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub enum MinecraftVersion {
Release(Version),
Snapshot(Snapshot),
@@ -46,6 +49,15 @@ impl Display for Snapshot {
}
}
impl Display for MinecraftVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MinecraftVersion::Release(version) => write!(f, "{}", version.to_string()),
MinecraftVersion::Snapshot(snapshot) => write!(f, "{}", snapshot.to_string()),
}
}
}
impl FromStr for Version {
type Err = VersionError;

View File

@@ -91,6 +91,14 @@ pub enum ServerError {
#[error("Failed to write to stdin")]
StdinWriteFailed,
#[error("Failed to open eula.txt")]
NoEULA,
#[error("Failed to write eula.txt")]
WriteEULAFailed,
#[error("File io error")]
FileIO,
}
#[cfg(feature = "events")]
@@ -99,3 +107,31 @@ pub enum ParserError {
#[error("ParserError")]
ParserError,
}
#[derive(Debug, Clone, Error)]
pub enum CreationError {
#[error("CreationError")]
CreationError,
#[error("Invalid directory")]
DirectoryError,
#[error("Failed to parse manifest")]
ManifestError,
#[error("Version does not exist")]
VersionError,
#[error("Network Error")]
NetworkError,
}
#[derive(Debug, Clone, Error)]
pub enum ManifestError {
#[error("ManifestError")]
ManifestError,
#[error("Failed to load mainfest")]
LoadUrlError,
#[error("Failed to parse manifest json")]
JsonParseError,
}

View File

@@ -1,73 +1,79 @@
use std::{path::PathBuf, process::Stdio, sync::Arc};
use std::{path::PathBuf, process::Stdio, sync::Arc, time::Duration};
use chrono::Utc;
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader, BufWriter},
process::{self, Child},
sync::{RwLock, broadcast, mpsc},
time::sleep,
};
use tokio_stream::StreamExt;
use tokio_stream::wrappers::BroadcastStream;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;
#[cfg(feature = "events")]
use crate::config::stream::InstanceEvent;
use crate::{
config::{MinecraftType, MinecraftVersion, StreamLine, StreamSource},
config::{
MinecraftType, MinecraftVersion, StreamSource,
stream::{EventPayload, InternalEvent},
},
error::{HandleError, ServerError, SubscribeError},
server::domain::MineGuardConfig,
};
use tokio_stream::StreamExt;
#[derive(Debug, Clone)]
pub struct InstanceData {
pub root_dir: PathBuf,
pub jar_path: PathBuf,
pub mc_version: MinecraftVersion,
pub mc_type: MinecraftType,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InstanceStatus {
Starting,
Running,
Stopping,
Stopped,
Crashed,
Killing,
Killed,
}
use super::{InstanceData, InstanceStatus};
#[derive(Debug)]
pub struct InstanceHandle {
pub data: InstanceData,
pub status: Arc<RwLock<InstanceStatus>>,
stdout_tx: broadcast::Sender<StreamLine>,
stderr_tx: Option<broadcast::Sender<StreamLine>>,
stdout_tx: broadcast::Sender<InstanceEvent>,
stderr_tx: Option<broadcast::Sender<InstanceEvent>>,
#[cfg(feature = "events")]
events_tx: broadcast::Sender<StreamLine>,
events_tx: broadcast::Sender<InstanceEvent>,
#[cfg(feature = "events")]
internal_events_tx: mpsc::Sender<InstanceEvent>,
#[cfg(feature = "events")]
internal_events_rx: Option<mpsc::Receiver<InstanceEvent>>,
stdin_tx: mpsc::Sender<String>,
stdin_rx: Option<mpsc::Receiver<String>>,
child: Option<Arc<RwLock<Child>>>,
shutdown: CancellationToken,
internal_bus_tx: broadcast::Sender<InternalEvent>,
}
impl InstanceHandle {
pub fn new_with_config(config: MineGuardConfig) -> Result<Self, HandleError> {
InstanceHandle::new_with_params(
config.server_dir,
config.jar_path,
config.mc_version,
config.mc_type,
)
}
pub fn new_with_params(
root_dir: &str,
jar_path: &str,
mc_version: &str,
root_dir: PathBuf,
jar_path: PathBuf,
mc_version: MinecraftVersion,
mc_type: MinecraftType,
) -> Result<Self, HandleError> {
let parsed_version: MinecraftVersion = mc_version
.parse()
.map_err(|_| HandleError::InvalidVersion(mc_version.to_string()))?;
let parsed_version: MinecraftVersion = mc_version;
let root: PathBuf = root_dir.into();
let root: PathBuf = root_dir.clone().into();
if !root.exists() || !root.is_dir() {
return Err(HandleError::InvalidDirectory(root_dir.to_string()));
return Err(HandleError::InvalidDirectory(
root_dir.to_str().unwrap().to_string(),
));
}
let path: PathBuf = jar_path.into();
let path: PathBuf = jar_path.clone().into();
let conc = root.join(path.clone());
if !path.is_relative() || !conc.is_file() {
return Err(HandleError::InvalidPathJAR(jar_path.to_string()));
return Err(HandleError::InvalidPathJAR(
jar_path.to_str().unwrap().to_string(),
));
}
let data = InstanceData {
@@ -80,6 +86,7 @@ impl InstanceHandle {
let status = InstanceStatus::Stopped;
let (stdin_tx, stdin_rx) = mpsc::channel(1024);
let (internal_tx, internal_rx) = mpsc::channel(1024);
Ok(Self {
data,
status: Arc::new(RwLock::new(status)),
@@ -87,10 +94,15 @@ impl InstanceHandle {
stderr_tx: None,
#[cfg(feature = "events")]
events_tx: broadcast::Sender::new(2048),
#[cfg(feature = "events")]
internal_events_tx: internal_tx,
#[cfg(feature = "events")]
internal_events_rx: Some(internal_rx),
stdin_tx,
stdin_rx: Some(stdin_rx),
child: None,
shutdown: CancellationToken::new(),
internal_bus_tx: broadcast::Sender::new(2048),
})
}
@@ -110,6 +122,7 @@ impl InstanceHandle {
pub async fn start(&mut self) -> Result<(), ServerError> {
self.validate_start_parameters().await?;
self.setup_loopback()?;
self.transition_status(InstanceStatus::Starting).await;
@@ -118,10 +131,23 @@ impl InstanceHandle {
self.setup_stream_pumps(child)?;
self.transition_status(InstanceStatus::Running).await;
self.setup_parser()?;
let mut rx = self.internal_bus_tx.subscribe();
loop {
match rx.recv().await {
Ok(event) => {
if event == InternalEvent::ServerStarted {
self.transition_status(InstanceStatus::Running).await;
break;
}
continue;
}
_ => continue,
}
}
Ok(())
}
@@ -134,9 +160,25 @@ impl InstanceHandle {
}
async fn transition_status(&self, status: InstanceStatus) {
let r_guard = self.status.read().await;
let old = r_guard.clone();
drop(r_guard);
let new = status.clone();
let mut guard = self.status.write().await;
*guard = status;
drop(guard);
let event = InstanceEvent {
id: Uuid::new_v4(),
timestamp: Utc::now(),
payload: EventPayload::StateChange { old, new },
};
_ = self.internal_events_tx.send(event).await;
}
fn build_start_command(&self) -> process::Command {
@@ -173,22 +215,36 @@ impl InstanceHandle {
let stdout_status = self.status.clone();
let stderr_status = self.status.clone();
let internal_tx1 = self.internal_events_tx.clone();
let internal_tx2 = self.internal_events_tx.clone();
tokio::spawn(async move {
let mut stdout_reader = BufReader::new(stdout).lines();
loop {
match stdout_reader.next_line().await {
Ok(Some(line)) => {
let _ = stdout_tx.send(StreamLine::stdout(line));
let _ = stdout_tx.send(InstanceEvent::stdout(line));
}
_ => {
let status_guard = stdout_status.read().await;
if *status_guard != InstanceStatus::Killing
|| *status_guard != InstanceStatus::Stopping
{
let state = status_guard.clone();
if state == InstanceStatus::Running && state == InstanceStatus::Starting {
let old = status_guard.clone();
drop(status_guard);
let mut status = stdout_status.write().await;
*status = InstanceStatus::Crashed;
let event = InstanceEvent {
id: Uuid::new_v4(),
timestamp: Utc::now(),
payload: EventPayload::StateChange {
old,
new: status.clone(),
},
};
_ = internal_tx1.send(event).await;
drop(status);
break;
}
@@ -203,16 +259,28 @@ impl InstanceHandle {
loop {
match stderr_reader.next_line().await {
Ok(Some(line)) => {
let _ = stderr_tx.send(StreamLine::stderr(line));
let _ = stderr_tx.send(InstanceEvent::stderr(line));
}
_ => {
let status_guard = stderr_status.read().await;
if *status_guard != InstanceStatus::Killing
|| *status_guard != InstanceStatus::Stopping
{
let state = status_guard.clone();
if state == InstanceStatus::Running && state == InstanceStatus::Starting {
let old = status_guard.clone();
drop(status_guard);
let mut status = stderr_status.write().await;
*status = InstanceStatus::Crashed;
let event = InstanceEvent {
id: Uuid::new_v4(),
timestamp: Utc::now(),
payload: EventPayload::StateChange {
old,
new: status.clone(),
},
};
_ = internal_tx2.send(event).await;
drop(status);
break;
}
@@ -245,34 +313,74 @@ impl InstanceHandle {
Ok(())
}
#[cfg(all(feature = "events", any(feature = "mc-vanilla")))]
fn setup_loopback(&mut self) -> Result<(), ServerError> {
let shutdown1 = self.shutdown.clone();
let event_tx1 = self.events_tx.clone();
//internal mpsc to broadcast loopback
if let Some(mut internal_rx) = self.internal_events_rx.take() {
tokio::spawn(async move {
let tx = event_tx1;
loop {
tokio::select! {
_ = shutdown1.cancelled() => {
break;
}
maybe_event = internal_rx.recv() => {
if let Some(event) = maybe_event {
_ = tx.send(event);
}
}
}
}
});
}
Ok(())
}
#[cfg(all(feature = "events", any(feature = "mc-vanilla")))]
fn setup_parser(&mut self) -> Result<(), ServerError> {
use crate::config::LogMeta;
let stdout_stream = self
.subscribe(StreamSource::Stdout)
.map_err(|_| ServerError::NoStdoutPipe)?;
let shutdown = self.shutdown.clone();
// TODO: Stream events!!!!
let _event_tx = self.events_tx.clone();
let shutdown2 = self.shutdown.clone();
let bus_tx = self.internal_bus_tx.clone();
#[cfg(feature = "mc-vanilla")]
if self.data.mc_type == MinecraftType::Vanilla {
use crate::config::LogMeta;
tokio::spawn(async move {
let mut rx = stdout_stream;
let tx = bus_tx;
loop {
tokio::select! {
_ = shutdown.cancelled() => {
_ = shutdown2.cancelled() => {
break;
}
line = rx.next() => {
if let Some(Ok(val)) = line {
let msg = val.msg();
let meta = LogMeta::new(msg);
if let Ok(val) = meta
&& val.is_some() {
println!("{}", val.unwrap());
}
next_line = rx.next() => {
if let Some(Ok(val)) = next_line {
let event_line = match val.payload {
EventPayload::StdLine{line} => {
line
},
_ => continue,
};
let meta = match LogMeta::new(event_line.line) {
Ok(Some(log_meta)) => {
log_meta
},
_ => continue,
};
match meta.parse_event() {
Ok(Some(event)) => _ = tx.send(event),
_ => continue,
}
}
}
}
@@ -289,10 +397,10 @@ impl InstanceHandle {
child.kill().await.map_err(|_| ServerError::CommandFailed)?;
self.transition_status(InstanceStatus::Killed).await;
sleep(Duration::from_secs(1)).await;
self.shutdown.cancel();
self.child = None;
self.transition_status(InstanceStatus::Killed).await;
Ok(())
} else {
Err(ServerError::NotRunning)
@@ -306,10 +414,11 @@ impl InstanceHandle {
_ = self.send_command("stop").await;
let mut child = child_arc.write().await;
child.wait().await.map_err(|_| ServerError::CommandFailed)?;
self.shutdown.cancel();
self.child = None;
self.transition_status(InstanceStatus::Stopped).await;
sleep(Duration::from_secs(1)).await;
self.shutdown.cancel();
self.child = None;
Ok(())
} else {
Err(ServerError::NotRunning)
@@ -319,7 +428,7 @@ impl InstanceHandle {
pub fn subscribe(
&self,
stream: StreamSource,
) -> Result<BroadcastStream<StreamLine>, SubscribeError> {
) -> Result<BroadcastStream<InstanceEvent>, SubscribeError> {
match stream {
StreamSource::Stdout => {
let rx = self.stdout_tx.subscribe();

5
src/instance/mod.rs Normal file
View File

@@ -0,0 +1,5 @@
mod handle;
mod types;
pub use handle::InstanceHandle;
pub use types::{InstanceData, InstanceStatus};

22
src/instance/types.rs Normal file
View File

@@ -0,0 +1,22 @@
use std::path::PathBuf;
use crate::config::{MinecraftType, MinecraftVersion};
#[derive(Debug, Clone)]
pub struct InstanceData {
pub root_dir: PathBuf,
pub jar_path: PathBuf,
pub mc_version: MinecraftVersion,
pub mc_type: MinecraftType,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InstanceStatus {
Starting,
Running,
Stopping,
Stopped,
Crashed,
Killing,
Killed,
}

View File

@@ -1,3 +1,7 @@
pub mod config;
pub mod error;
pub mod instance;
pub mod manifests;
pub mod parser;
pub mod server;
pub mod utils;

1
src/manifests/mod.rs Normal file
View File

@@ -0,0 +1 @@
pub mod vanilla;

114
src/manifests/vanilla.rs Normal file
View File

@@ -0,0 +1,114 @@
#![cfg(feature = "mc-vanilla")]
use async_trait::async_trait;
use reqwest::Client;
use serde::Deserialize;
use crate::{config::MinecraftVersion, error::ManifestError};
#[derive(Debug, Clone, Deserialize)]
pub struct VanillaManifestV2 {
latest: VanillaManifestV2Latest,
versions: Vec<VanillaManifestV2Version>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct VanillaManifestV2Latest {
release: String,
snapshot: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct VanillaManifestV2Version {
id: String,
#[serde(rename = "type")]
mc_type: String,
url: String,
time: String,
#[serde(rename = "releaseTime")]
release_time: String,
sha1: String,
#[serde(rename = "complianceLevel")]
compliance_level: u32,
}
#[derive(Debug, Clone, Deserialize)]
pub struct VanillaReleaseManifest {
downloads: VanillaReleaseManifestDownloads,
}
#[derive(Debug, Clone, Deserialize)]
pub struct VanillaReleaseManifestDownloads {
client: VanillaReleaseManifestDownloadsItem,
client_mappings: VanillaReleaseManifestDownloadsItem,
server: VanillaReleaseManifestDownloadsItem,
server_mappings: VanillaReleaseManifestDownloadsItem,
}
#[derive(Debug, Clone, Deserialize)]
pub struct VanillaReleaseManifestDownloadsItem {
sha1: String,
size: u32,
url: String,
}
impl VanillaReleaseManifest {
pub async fn load(version: VanillaManifestV2Version) -> Result<Self, ManifestError> {
let client = Client::new();
let manifest: VanillaReleaseManifest = client
.get(&version.url)
.send()
.await
.map_err(|_| ManifestError::LoadUrlError)?
.error_for_status()
.map_err(|_| ManifestError::LoadUrlError)?
.json()
.await
.map_err(|e| {
eprintln!("{}", e);
ManifestError::JsonParseError
})?;
Ok(manifest)
}
pub fn server_url(&self) -> String {
self.downloads.server.url.clone()
}
}
impl VanillaManifestV2 {
pub async fn load() -> Result<Self, ManifestError> {
let client = Client::new();
let manifest: VanillaManifestV2 = client
.get("https://piston-meta.mojang.com/mc/game/version_manifest_v2.json")
.send()
.await
.map_err(|_| ManifestError::LoadUrlError)?
.error_for_status()
.map_err(|_| ManifestError::LoadUrlError)?
.json()
.await
.map_err(|e| {
eprintln!("{}", e);
ManifestError::JsonParseError
})?;
Ok(manifest)
}
pub fn find(
&self,
version: MinecraftVersion,
) -> Result<Option<VanillaManifestV2Version>, ManifestError> {
let id = version.to_string();
let found = match self.versions.iter().find(|p| p.id == id) {
Some(val) => Some(val.clone()),
None => None,
};
Ok(found)
}
}

26
src/parser/mod.rs Normal file
View File

@@ -0,0 +1,26 @@
use regex::Regex;
use crate::{
config::{
LogMeta,
stream::{EventPayload, InstanceEvent, InternalEvent, LogLevel},
},
error::ParserError,
};
impl LogMeta {
pub fn parse_event(&self) -> Result<Option<InternalEvent>, ParserError> {
if self.thread == "Server thread" && self.level == LogLevel::Info {
return self.parse_server_thread_info_lv2();
}
Ok(None)
}
fn parse_server_thread_info_lv2(&self) -> Result<Option<InternalEvent>, ParserError> {
let re = Regex::new(r"Done \([0-9.]+s\)!").unwrap();
if re.is_match(&self.msg) {
return Ok(Some(InternalEvent::ServerStarted));
}
Ok(None)
}
}

248
src/server/domain.rs Normal file
View File

@@ -0,0 +1,248 @@
use std::{ops::RangeInclusive, path::PathBuf, str::FromStr};
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::{
fs::{File, create_dir, read, read_dir},
io::{self, AsyncWriteExt},
sync::{RwLock, watch},
};
use tokio_stream::wrappers::BroadcastStream;
use uuid::Uuid;
use crate::{
config::{self, MinecraftType, MinecraftVersion, StreamSource, Version, stream::InstanceEvent},
error::{CreationError, ServerError, SubscribeError},
instance::InstanceHandle,
manifests::vanilla::{VanillaManifestV2, VanillaManifestV2Version, VanillaReleaseManifest},
server,
};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MineGuardConfig {
uuid: Uuid,
pub server_dir: PathBuf,
pub jar_path: PathBuf,
pub mc_version: MinecraftVersion,
pub mc_type: MinecraftType,
}
#[derive(Debug)]
pub struct MineGuardServer {
pub handle: RwLock<InstanceHandle>,
pub config: RwLock<MineGuardConfig>,
}
impl MineGuardConfig {
pub fn new() -> Self {
Self {
uuid: Uuid::new_v4(),
server_dir: PathBuf::new(),
jar_path: PathBuf::new(),
mc_version: MinecraftVersion::Release(Version::from_str("0.00.00").unwrap()),
mc_type: MinecraftType::Vanilla,
}
}
}
impl MineGuardServer {
async fn load_cfg_handle(
config: MineGuardConfig,
handle: InstanceHandle,
) -> Result<Self, CreationError> {
Ok(Self {
config: RwLock::new(config),
handle: RwLock::new(handle),
})
}
pub async fn create(
mc_version: MinecraftVersion,
mc_type: MinecraftType,
directory: PathBuf,
) -> Result<Self, CreationError> {
if !directory.is_dir() {
return Err(CreationError::DirectoryError);
}
let uuid = Uuid::new_v4();
let server_root = directory.join(uuid.to_string());
let jar_path_rel =
PathBuf::from_str("server.jar").map_err(|_| CreationError::DirectoryError)?;
let jar_path_full = server_root.join(jar_path_rel.clone());
create_dir(server_root.clone())
.await
.map_err(|_| CreationError::DirectoryError)?;
let internal_dir = server_root.join(".mineguard");
create_dir(internal_dir)
.await
.map_err(|_| CreationError::DirectoryError)?;
let mut url = String::new();
if mc_type == MinecraftType::Vanilla {
let vanilla_manifest = VanillaManifestV2::load()
.await
.map_err(|_| CreationError::ManifestError)?;
let find_ver = match vanilla_manifest
.find(mc_version.clone())
.map_err(|_| CreationError::ManifestError)?
{
Some(val) => val,
None => return Err(CreationError::VersionError),
};
let release_manifest = VanillaReleaseManifest::load(find_ver)
.await
.map_err(|_| CreationError::ManifestError)?;
url = release_manifest.server_url();
}
let resp = reqwest::get(url)
.await
.map_err(|_| CreationError::NetworkError)?;
let mut body = resp
.bytes()
.await
.map_err(|_| CreationError::NetworkError)?;
let mut out = File::create(jar_path_full)
.await
.map_err(|_| CreationError::DirectoryError)?;
out.write_all_buf(&mut body)
.await
.map_err(|_| CreationError::DirectoryError)?;
let config = MineGuardConfig {
uuid: uuid,
server_dir: server_root,
jar_path: jar_path_rel,
mc_version: mc_version,
mc_type: mc_type,
};
let handle = InstanceHandle::new_with_params(
config.server_dir.clone(),
config.jar_path.clone(),
config.mc_version.clone(),
config.mc_type.clone(),
)
.map_err(|_| CreationError::CreationError)?;
let server = MineGuardServer {
config: RwLock::new(config),
handle: RwLock::new(handle),
};
Ok(server)
}
pub async fn start(&self) -> Result<(), ServerError> {
let mut handle_w = self.handle.write().await;
let res = handle_w.start().await;
res
}
pub async fn kill(&self) -> Result<(), ServerError> {
let mut handle_w = self.handle.write().await;
let res = handle_w.kill().await;
res
}
pub async fn stop(&self) -> Result<(), ServerError> {
let mut handle_w = self.handle.write().await;
let res = handle_w.stop().await;
res
}
pub async fn subscribe(
&self,
stream: StreamSource,
) -> Result<BroadcastStream<InstanceEvent>, SubscribeError> {
let handle_r = self.handle.read().await;
let res = handle_r.subscribe(stream);
res
}
pub async fn accept_eula(&self) -> Result<(), ServerError> {
let config_r = self.config.read().await;
let eula_path = config_r.server_dir.join("eula.txt");
let mut out = File::create(eula_path)
.await
.map_err(|_| ServerError::NoEULA)?;
out.write_all(b"#Generated by MineGuard\neula=true\n")
.await
.map_err(|_| ServerError::WriteEULAFailed)?;
Ok(())
}
pub async fn write_config(&self) -> Result<(), ServerError> {
let config_r = self.config.read().await;
let root_path = config_r.server_dir.clone();
let config_clone = config_r.clone();
drop(config_r);
let config_path = root_path.join(".mineguard/config.json");
let json = serde_json::to_vec_pretty(&config_clone).map_err(|_| ServerError::FileIO)?;
File::create(config_path)
.await
.map_err(|_| ServerError::FileIO)?
.write_all(&json)
.await
.map_err(|_| ServerError::FileIO)?;
Ok(())
}
pub async fn load(path: &PathBuf) -> Result<Self, CreationError> {
let config_path = path.join(".mineguard/config.json");
let data = read(config_path)
.await
.map_err(|_| CreationError::DirectoryError)?;
let config: MineGuardConfig =
serde_json::from_slice(&data).map_err(|_| CreationError::CreationError)?;
let handle = InstanceHandle::new_with_config(config.clone())
.map_err(|_| CreationError::CreationError)?;
MineGuardServer::load_cfg_handle(config, handle).await
}
pub async fn load_all(path: PathBuf) -> Result<Vec<Self>, CreationError> {
let mut dirs = Vec::new();
let mut entries = read_dir(path)
.await
.map_err(|_| CreationError::DirectoryError)?;
while let Some(entry) = entries
.next_entry()
.await
.map_err(|_| CreationError::DirectoryError)?
{
let meta = entry
.metadata()
.await
.map_err(|_| CreationError::DirectoryError)?;
if meta.is_dir() {
dirs.push(entry.path());
}
}
let mut servers: Vec<Self> = Vec::new();
for v in dirs {
println!("{}", v.to_str().unwrap());
servers.push(Self::load(&v).await?);
}
Ok(servers)
}
}

1
src/server/mod.rs Normal file
View File

@@ -0,0 +1 @@
pub mod domain;

24
src/utils.rs Normal file
View File

@@ -0,0 +1,24 @@
use chrono::{DateTime, Datelike, Local, NaiveTime, TimeZone, Timelike, Utc};
use regex::Regex;
pub fn extract_timestamp(input: &str) -> Option<DateTime<Utc>> {
let re = Regex::new(r"\[(.*?)\]").unwrap();
let time_s = re.captures(input).map(|v| v[1].to_string());
time_s.as_ref()?;
let time = NaiveTime::parse_from_str(&time_s.unwrap(), "%H:%M:%S").ok()?;
let today = Local::now().date_naive();
let local_dt = Local
.with_ymd_and_hms(
today.year(),
today.month(),
today.day(),
time.hour(),
time.minute(),
time.second(),
)
.single()?;
Some(local_dt.with_timezone(&Utc))
}