Skip to content

Commit

Permalink
wip: fix agent build errors
Browse files Browse the repository at this point in the history
  • Loading branch information
cilki committed Jan 6, 2025
1 parent 26272a1 commit 8e9cb50
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 36 deletions.
4 changes: 2 additions & 2 deletions sandpolis/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ sysinfo = { version = "0.33.0", optional = true }
[features]
# Instances
server = [ "dep:axum", "dep:axum-server", "dep:axum-macros", "dep:rcgen" ]
agent = [ "dep:sysinfo" ]
agent = [ "dep:axum", "dep:axum-server", "dep:axum-macros", "dep:sysinfo" ]
client = [ "dep:bevy", "dep:bevy_rapier2d", "dep:bevy_egui", "dep:egui" ]

# Layers
Expand All @@ -76,6 +76,6 @@ layer-sysinfo = []
layer-probe = []
layer-tunnel = []

default = [ "layer-desktop", "layer-filesystem", "layer-shell", "layer-inventory", "layer-account", "layer-logging" ]
default = [ "layer-desktop", "layer-filesystem", "layer-shell", "layer-sysinfo", "layer-inventory", "layer-account", "layer-logging" ]
wayland = [ "bevy/wayland" ]
rcgen = ["dep:rcgen"]
2 changes: 1 addition & 1 deletion sandpolis/src/agent/layer/desktop/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use axum::Router;

pub fn router() -> Router {
todo!()
Router::new()
}
15 changes: 13 additions & 2 deletions sandpolis/src/agent/layer/sysinfo/mod.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
use anyhow::Result;
use axum::Router;
use os::memory::MemoryMonitor;
use serde::{Deserialize, Serialize};

use crate::core::database::Document;

pub mod os;

#[derive(Serialize, Deserialize, Default)]
pub struct SysinfoLayerData {}

pub struct SysinfoLayer {
pub data: Document<SysinfoLayerData>,
pub memory: MemoryMonitor,
}

impl SysinfoLayer {
pub fn new() -> Self {
todo!()
pub fn new(data: Document<SysinfoLayerData>) -> Result<Self> {
Ok(Self {
memory: MemoryMonitor::new(data.document("/memory")?),
data,
})
}
}

Expand Down
12 changes: 6 additions & 6 deletions sandpolis/src/agent/layer/sysinfo/os/memory.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
use crate::agent::Monitor;
use crate::core::database::Document;
use crate::core::layer::sysinfo::os::memory::MemoryData;
use crate::core::layer::sysinfo::os::memory::{MemoryData, MemoryDataDelta};
use anyhow::Result;
use sysinfo::{MemoryRefreshKind, RefreshKind, System};
use tracing::trace;

pub struct MemoryMonitor {
document: Document<MemoryData>,
data: Document<MemoryData>,
system: System,
}

impl MemoryMonitor {
pub fn new(document: Document<MemoryData>) -> Self {
pub fn new(data: Document<MemoryData>) -> Self {
Self {
document,
data,
system: System::new_with_specifics(
RefreshKind::nothing().with_memory(MemoryRefreshKind::everything()),
),
Expand All @@ -24,7 +24,7 @@ impl MemoryMonitor {
impl Monitor for MemoryMonitor {
fn refresh(&mut self) -> Result<()> {
self.system.refresh_memory();
self.document.mutate(|data| {
self.data.mutate(|data| {
data.total = self.system.total_memory();
data.free = self.system.free_memory();
data.swap_free = self.system.free_swap();
Expand All @@ -51,7 +51,7 @@ mod tests {
let mut monitor = super::MemoryMonitor::new(db.document("/test")?);
monitor.refresh()?;

assert!(monitor.document.data.total > 0);
assert!(monitor.data.data.total > 0);
Ok(())
}
}
2 changes: 1 addition & 1 deletion sandpolis/src/agent/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ pub async fn main(args: CommandLine) -> Result<()> {
let state = AgentState {
local: Arc::new(AgentInstance {
#[cfg(feature = "layer-sysinfo")]
sysinfo: crate::agent::layer::sysinfo::SysinfoLayer::new(),
sysinfo: crate::agent::layer::sysinfo::SysinfoLayer::new(db.document("/sysinfo")?)?,
}),
db,
};
Expand Down
74 changes: 52 additions & 22 deletions sandpolis/src/core/database.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use anyhow::{bail, Result};
use anyhow::{anyhow, Result};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Write};
use std::marker::PhantomData;
use std::{path::Path, sync::Arc};
use tracing::debug;
use tracing::{debug, trace};

use super::InstanceId;

Expand All @@ -25,25 +25,35 @@ impl Database {

pub fn document<T>(&self, oid: impl TryInto<Oid>) -> Result<Document<T>>
where
T: Serialize + DeserializeOwned,
T: Serialize + DeserializeOwned + Default,
{
let oid = oid.try_into()?;
todo!()
let oid = oid.try_into().map_err(|_| anyhow!("Invalid OID"))?;
let db = self.0.open_tree("default")?;
Ok(Document {
data: if let Some(data) = db.get(&oid)? {
serde_cbor::from_slice::<T>(&data)?
} else {
T::default()
},
db,
oid,
})
}

pub fn collection<T>(&self, oid: impl TryInto<Oid>) -> Result<Collection<T>>
where
T: Serialize + DeserializeOwned,
{
let oid = oid.try_into()?;
let oid = oid.try_into().map_err(|_| anyhow!("Invalid OID"))?;
todo!()
}

pub fn instance(&self, id: impl Into<InstanceId>) -> Result<Oid> {
Ok(Oid {
db: self.db.open_tree(id.into())?,
path: vec!['/' as u8],
})
// Ok(Oid {
// db: self.db.open_tree(id.into())?,
// path: vec!['/' as u8],
// })
todo!()
}
}

Expand Down Expand Up @@ -90,25 +100,26 @@ mod test_display {

impl Oid {
pub fn extend(&self, oid: impl TryInto<Oid>) -> Result<Oid> {
let oid = oid.try_into().map_err(|_| anyhow!("Invalid OID"))?;
let mut path = self.0.clone();

path.push('/' as u8);
path.extend_from_slice(&oid.try_into()?.0);
path.extend_from_slice(&oid.0);
Ok(Oid(path))
}

/// Add or replace the timestamp.
pub fn timestamp(mut self, timestamp: u64) -> Result<Oid> {
pub fn timestamp(&self, timestamp: u64) -> Result<Oid> {
// TODO overwrite timestamp if one exists
for byte in self.path.iter().rev() {
if *byte == ':' as u8 {
// TODO
}
}

self.path.push(':' as u8);
self.path.extend_from_slice(&id.to_be_bytes());
Ok(self)
// for byte in self.path.iter().rev() {
// if *byte == ':' as u8 {
// // TODO
// }
// }

// self.path.push(':' as u8);
// self.path.extend_from_slice(&id.to_be_bytes());
todo!()
}

pub fn history(&self) -> Oid {
Expand All @@ -128,7 +139,8 @@ impl TryFrom<&str> for Oid {
type Error = anyhow::Error;

fn try_from(value: &str) -> Result<Self> {
todo!()
// TODO validate
Ok(Oid(value.as_bytes().to_vec()))
}
}

Expand Down Expand Up @@ -208,6 +220,24 @@ where

impl<T: Serialize + DeserializeOwned> Document<T> {
// pub fn update<U>(&mut self, update: )

pub fn document<U>(&self, oid: impl TryInto<Oid>) -> Result<Document<U>>
where
U: Serialize + DeserializeOwned + Default,
{
let oid = self.oid.extend(oid)?;

Ok(Document {
db: self.db.clone(),
data: if let Some(data) = self.db.get(&oid)? {
serde_cbor::from_slice::<U>(&data)?
} else {
trace!(oid = %oid, "Creating new document");
U::default()
},
oid,
})
}
}

impl<T: Serialize + DeserializeOwned + Clone> Document<T> {
Expand Down
1 change: 1 addition & 0 deletions sandpolis/src/core/layer/network/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use futures::StreamExt;
use reqwest::ClientBuilder;
use reqwest_websocket::RequestBuilderExt;
use serde::{Deserialize, Serialize};
use serde_with::chrono::serde::ts_seconds_option;
use std::{cmp::min, collections::HashMap, net::SocketAddr, sync::Arc, time::Duration};
use tokio::time::sleep;
use tracing::debug;
Expand Down
3 changes: 2 additions & 1 deletion sandpolis/src/core/layer/sysinfo/os/memory.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use sandpolis_macros::Delta;
use serde::{Deserialize, Serialize};

#[derive(Clone, Serialize, Deserialize, Debug)]
#[derive(Clone, Serialize, Deserialize, Default, Debug, Delta)]
pub struct MemoryData {
/// The amount of physical RAM in bytes
pub total: u64,
Expand Down
9 changes: 8 additions & 1 deletion sandpolis/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ use tracing::info;

#[tokio::main]
async fn main() -> Result<ExitCode> {
#[cfg(all(
not(feature = "server"),
not(feature = "agent"),
not(feature = "client")
))]
bail!("No instance was enabled at build time");

let args = CommandLine::parse();
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
Expand Down Expand Up @@ -42,5 +49,5 @@ async fn main() -> Result<ExitCode> {
#[cfg(feature = "agent")]
tokio::join!(agent_thread).0??;

bail!("No instance was enabled at build time")
Ok(ExitCode::SUCCESS)
}

0 comments on commit 8e9cb50

Please sign in to comment.