Skip to content

Commit

Permalink
feat: logging
Browse files Browse the repository at this point in the history
  • Loading branch information
sargon64 committed Apr 21, 2024
1 parent 06108a4 commit 5bd7c6f
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 14 deletions.
7 changes: 7 additions & 0 deletions crates/alerion_core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ impl From<wings::Config> for AlerionConfig {

impl AlerionConfig {
pub fn load(project_dirs: &directories::ProjectDirs) -> anyhow::Result<Self> {
tracing::info!("Loading Alerion config from {}", project_dirs.config_dir().display());
let config_path = project_dirs.config_dir().join("config.json");
let config = std::fs::read_to_string(&config_path).map_err(|e| {
anyhow::anyhow!(
Expand All @@ -276,6 +277,7 @@ impl AlerionConfig {
})?;

let config: AlerionConfig = serde_json::from_str(&config)?;
tracing::debug!("Loaded Alerion config: {:?}", config);
Ok(config)
}

Expand All @@ -291,6 +293,8 @@ impl AlerionConfig {
)
})?;

tracing::info!("Saved Alerion config to {}", config_path.display());

Ok(())
}

Expand All @@ -308,6 +312,9 @@ impl AlerionConfig {
})?;

let config: wings::Config = serde_yaml::from_str(&config)?;

tracing::debug!("Imported Wings config: {:?}", config);

Ok(config.into())
}
}
3 changes: 3 additions & 0 deletions crates/alerion_core/src/filesystem.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
use anyhow::Context;
use directories::ProjectDirs;

#[tracing::instrument]
pub async fn setup_directories() -> anyhow::Result<ProjectDirs> {
let project_dirs = ProjectDirs::from("host", "pyro", "alerion")
.context("couldn't determine a home directory for your operating system")?;

tokio::fs::create_dir_all(project_dirs.config_dir()).await?;
tokio::fs::create_dir_all(project_dirs.data_dir()).await?;
tokio::fs::create_dir_all(project_dirs.cache_dir()).await?;

tracing::info!("Directories created");

Ok(project_dirs)
}
10 changes: 0 additions & 10 deletions crates/alerion_core/src/logging.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
// use env_logger::TimestampPrecision;

pub fn splash() {
println!(
"
Expand All @@ -10,11 +8,3 @@ pub fn splash() {
██ ██ ███████ ███████ ██ ██ ██ ██████ ██ ████ "
);
}

//pub fn setup() {
// env_logger::Builder::from_default_env()
// .filter_level(log::LevelFilter::Debug)
// .format_timestamp(Some(TimestampPrecision::Seconds))
// .format_module_path(true)
// .init();
//}
28 changes: 25 additions & 3 deletions crates/alerion_core/src/servers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,11 @@ impl ServerPoolBuilder {

Ok(self)
}


#[tracing::instrument(skip(self))]
pub fn build(self) -> ServerPool {
tracing::debug!("Server pool built");

ServerPool {
servers: RwLock::new(self.servers),
remote_api: self.remote_api,
Expand All @@ -84,9 +87,13 @@ impl ServerPool {
let map = self.servers.read().await;

match map.get(&uuid) {
Some(s) => Ok(Arc::clone(s)),
Some(s) => {
tracing::debug!("Server {uuid} found");
Ok(Arc::clone(s))
},

None => {
tracing::debug!("Server {uuid} not found, creating");
drop(map);
self.create_server(uuid).await
}
Expand All @@ -112,7 +119,8 @@ impl ServerPool {
self.servers.read().await.get(&uuid).cloned()
}
}

//TODO: Remove allow(dead_code) when implemented
#[allow(dead_code)]
pub struct ServerInfo {
container: ContainerConfig,
}
Expand Down Expand Up @@ -142,6 +150,8 @@ impl From<IntoStringZst> for String {
}
}

//TODO: Remove allow(dead_code) when implemented
#[allow(dead_code)]
pub struct Server {
start_time: Instant,
uuid: Uuid,
Expand All @@ -155,12 +165,14 @@ pub struct Server {
}

impl Server {
#[tracing::instrument(skip(server_info, remote_api, docker))]
pub async fn new(
uuid: Uuid,
server_info: ServerInfo,
remote_api: Arc<remote::RemoteClient>,
docker: Arc<Docker>,
) -> Result<Arc<Self>, ServerError> {
tracing::debug!("Creating new server {uuid}");
let (send, recv) = channel(128);

let server = Arc::new(Self {
Expand All @@ -180,6 +192,8 @@ impl Server {

server.create_docker_container().await?;

tracing::info!("Server {uuid} created");

Ok(server)
}

Expand Down Expand Up @@ -215,6 +229,8 @@ impl Server {
where
F: FnOnce(ServerConnection) -> actix_web::Result<(ConnectionAddr, HttpResponse)>,
{
tracing::info!("Setting up new websocket connection");

let id = self.websocket_id_counter.fetch_add(1, Ordering::SeqCst);

// setup the request channel for the websocket
Expand All @@ -235,6 +251,9 @@ impl Server {
}

pub async fn send_to_available_websockets(&self, msg: ServerMessage) {
tracing::info!("Sending message to all available websockets");
tracing::debug!("message: {:?}", msg);

let lock = self.websockets.read().await;

for sender in lock.values() {
Expand All @@ -247,7 +266,10 @@ impl Server {
}
}

#[tracing::instrument(skip(server))]
async fn monitor_performance_metrics(server: Arc<Server>) {
tracing::info!("Starting performance metrics monitor for {}", &server.uuid);

loop {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;

Expand Down
1 change: 1 addition & 0 deletions crates/alerion_core/src/sftp/server.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// This file intentionally left blank.
6 changes: 6 additions & 0 deletions crates/alerion_core/src/websocket/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ impl actix::Message for PanelMessage {

pub type ConnectionAddr = Addr<WebsocketConnectionImpl>;

//TODO: Remove allow(dead_code) when implemented
#[allow(dead_code)]
enum MessageError {
InvalidJwt,
Generic(String),
Expand Down Expand Up @@ -102,6 +104,10 @@ impl WebsocketConnectionImpl {
permissions: Cell::new(Permissions::empty()),
}
}

pub fn id(&self) -> Uuid {
self.server_uuid
}

pub fn handle_text(&self, msg: &str, ctx: &mut <Self as Actor>::Context) -> Option<()> {
// todo: behavior on bad JSON payload? right now just ignore
Expand Down
16 changes: 15 additions & 1 deletion crates/alerion_core/src/websocket/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ impl ServerConnection {
sender: Sender<(u32, PanelMessage)>,
id: u32,
) -> Self {
tracing::debug!("Server connection created with id {}", id);

ServerConnection {
auth_tracker,
sender,
Expand All @@ -25,24 +27,29 @@ impl ServerConnection {
}

pub fn set_authenticated(&self) {
tracing::debug!("Server connection {} authenticated", self.id);
self.auth_tracker.set_auth(true);
}

pub fn is_authenticated(&self) -> bool {
tracing::debug!("Checking if server connection {} is authenticated", self.id);
self.auth_tracker.get_auth()
}

pub fn send_if_authenticated(&self, msg: PanelMessage) {
tracing::debug!("Sending message to server connection {}", self.id);
if self.auth_tracker.get_auth() {
let _ = self.sender.try_send((self.id, msg));
}
}

pub fn force_send(&self, msg: PanelMessage) {
tracing::debug!("Forcing message to server connection {}", self.id);
let _ = self.sender.try_send((self.id, msg));
}

pub fn auth_tracker(&self) -> Arc<AuthTracker> {
tracing::debug!("Getting auth tracker for server connection {}", self.id);
Arc::clone(&self.auth_tracker)
}
}
Expand All @@ -53,7 +60,10 @@ pub struct ClientConnection {
}

impl ClientConnection {
#[tracing::instrument(skip(auth_tracker))]
pub fn new(auth_tracker: Arc<AuthTracker>, ws_sender: ConnectionAddr) -> Self {
tracing::info!("Client connection created");

Self {
auth_tracker,
ws_sender,
Expand Down Expand Up @@ -82,12 +92,16 @@ impl ClientConnection {
///
/// This would easily be fixable with another atomic check, but I'd rather avoid
/// seemingly unnecessary atomic loads.
#[tracing::instrument(skip(self), fields(id=format!("{:?}", self.ws_sender)))]
pub fn terminate(&self) {
tracing::info!("Terminating websocket connection");
self.expire_auth();
self.ws_sender.do_send(ServerMessage::Kill);
}


#[tracing::instrument(skip(self), fields(id=format!("{:?}", self.ws_sender)))]
pub fn expire_auth(&self) {
tracing::debug!("Auth expired.");
self.auth_tracker.set_auth(false);
}

Expand Down

0 comments on commit 5bd7c6f

Please sign in to comment.