Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions statime-csptp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ default = ["std"]
std = ["statime-wire/std"]

[dependencies]
statime-wire = { workspace = true }
statime-base = { workspace = true }
log.workspace = true
rand = { workspace = true, default-features = false }
statime-base = { workspace = true }
statime-wire = { workspace = true }
5 changes: 4 additions & 1 deletion statime-csptp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ mod source;

pub use manager::{CsptpConfig, CsptpManager};
pub use platform::{InternalState, StateMutex};
pub use server::{ServerRecvResult, ServerSocket, serve};
pub use server::{
DummyStatHandler, ServerReason, ServerRecvResult, ServerResponse, ServerSocket,
ServerStatHandler, serve,
};
pub use source::{ClientRecvResult, ClientSocket, CsptpSource, CsptpSourceConfig};

/// Observable CSPTP state
Expand Down
86 changes: 75 additions & 11 deletions statime-csptp/src/server.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use core::{future::poll_fn, task::Poll};

use log::{debug, trace};
use statime_wire::Timestamp;

use crate::{
Expand All @@ -8,6 +9,49 @@ use crate::{
platform::StateMutex,
};

/// The reason for a given response by the server.
///
/// Used for collecting stats through the [`ServerStatHandler`] trait.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ServerReason {
/// Packet could not be parsed because it was malformed in some way
ParseError,
/// Internal error in the server
InternalError,
/// Error sending a message
SendError,
/// Configuration was used to decide response
Policy,
}

/// What response the server actually provided.
///
/// Used for collecting stats through the [`ServerStatHandler`] trait.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ServerResponse {
/// Did not provide a response packet.
Ignore,
/// Sent only the event message but not the follow up with the required time.
PartialRepsonse,
/// Accepted packet and provided time to requestor
ProvideTime,
}

/// Handler for collecting stats on a server.
pub trait ServerStatHandler {
/// Called by the server handle once per packet
fn register(&mut self, reason: ServerReason, response: ServerResponse);
}

/// Dummy handler which does nothing.
pub struct DummyStatHandler;

impl ServerStatHandler for DummyStatHandler {
fn register(&mut self, _reason: ServerReason, _response: ServerResponse) {
// do nothing
}
}

/// Serve CSPTP on the provided socket.
///
/// On completion of the shutdown future, this will finish handling the current
Expand All @@ -16,6 +60,7 @@ pub async fn serve(
mut socket: impl ServerSocket,
shutdown: impl Future<Output = ()>,
manager: &CsptpManager<impl StateMutex>,
mut stat_handler: impl ServerStatHandler,
) {
let mut shutdown = core::pin::pin!(shutdown);
loop {
Expand Down Expand Up @@ -49,11 +94,12 @@ pub async fn serve(
remote_addr,
local_addr,
timestamp,
&mut stat_handler,
)
.await;
}
Some(Err(_)) => {
// FIXME: Optionally log the errors
Some(Err(error)) => {
debug!("Problem receiving packet from interface: {error:?}");
}
None => break,
}
Expand All @@ -67,14 +113,20 @@ async fn handle_packet<S: ServerSocket>(
remote: S::Addr,
local: S::Addr,
timestamp: Timestamp,
stat_handler: &mut impl ServerStatHandler,
) {
let Ok(message) = CsptpMessage::deserialize(packet) else {
// FIXME: Optionally log the errors
debug!("Message could not be parsed, ignoring");
stat_handler.register(ServerReason::ParseError, ServerResponse::Ignore);
return;
};

if !message.is_request() {
// FIXME: Optionally log this
trace!(
"Received response in server, ignoring. This is expected if this machine also acts as a client."
);
// For pure servers, this is interesting, but mixed client/server will have spurious registrations here.
stat_handler.register(ServerReason::ParseError, ServerResponse::Ignore);
return;
}

Expand All @@ -89,34 +141,46 @@ async fn handle_packet<S: ServerSocket>(
&state.csptp_state,
)
}) else {
// FIXME: Optionally log this
debug!("Could not generate response to csptp request.");
stat_handler.register(ServerReason::InternalError, ServerResponse::Ignore);
return;
};

let mut send_buf = [0u8; MAX_MESSAGE_SIZE];
let Ok(size) = response.serialize(&mut send_buf) else {
// Fixme: Optionally log this
debug!("Could not serialize response to csptp request.");
stat_handler.register(ServerReason::InternalError, ServerResponse::Ignore);
return;
};
let Ok(send_timestamp) = socket.send_event(&send_buf[0..size], local, remote).await else {
// Fixme: Optionally log this
debug!("Could not send event message.");
stat_handler.register(ServerReason::SendError, ServerResponse::Ignore);
return;
};

let Ok(follow_up) = CsptpMessage::new_follow_up(&response, send_timestamp) else {
// FIXME: Optionally log this
debug!("Could not generate follow up message.");
stat_handler.register(ServerReason::InternalError, ServerResponse::PartialRepsonse);
return;
};

let mut send_buf = [0u8; MAX_MESSAGE_SIZE];
let Ok(size) = follow_up.serialize(&mut send_buf) else {
// Fixme: Optionally log this
debug!("Could not serialize follow up message.");
stat_handler.register(ServerReason::InternalError, ServerResponse::PartialRepsonse);
return;
};
socket
if socket
.send_general(&send_buf[0..size], local, remote)
.await
.ok();
.is_ok()
{
trace!("Handled and responded to csptp request.");
stat_handler.register(ServerReason::Policy, ServerResponse::ProvideTime);
} else {
debug!("Could not send follow up message.");
stat_handler.register(ServerReason::SendError, ServerResponse::PartialRepsonse);
}
}

/// Result from receiving a packet from the server socket.
Expand Down
62 changes: 55 additions & 7 deletions statime/src/daemon/csptp_server.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
use std::{future::pending, sync::RwLock};
use std::{
future::pending,
sync::{Arc, RwLock},
};

use statime_csptp::{CsptpManager, InternalState, ServerRecvResult, ServerSocket, serve};
use statime_csptp::{
CsptpManager, InternalState, ServerReason, ServerRecvResult, ServerResponse, ServerSocket,
ServerStatHandler, serve,
};
use statime_netptp::{NetworkManager, OpenSocket, PtpAddressFamily};
use tokio::task::JoinHandle;

use crate::daemon::system::ServerHandle;
use crate::daemon::{system::ServerHandle, util::Counter};

use super::observer::ObservableServerState;

Expand All @@ -14,11 +20,49 @@ pub struct CsptpServerConfig {}

struct ServerSocketWrapper<A: PtpAddressFamily>(OpenSocket<A>);

struct CsptpServerHandle {}
struct CsptpServerHandle {
stats: ServerStats,
}

impl ServerHandle for CsptpServerHandle {
fn observe(&self) -> ObservableServerState {
ObservableServerState::Csptp {}
ObservableServerState::Csptp {
received_packets: self.stats.0.received_packets.get(),
accepted_packets: self.stats.0.accepted_packets.get(),
ignored_packets: self.stats.0.ignored_packets.get(),
partial_responses: self.stats.0.partial_responses.get(),
internal_errors: self.stats.0.internal_errors.get(),
send_errors: self.stats.0.send_errors.get(),
}
}
}

#[derive(Debug, Clone, Default)]
struct ServerStats(Arc<ServerStatsData>);

#[derive(Debug, Default)]
struct ServerStatsData {
received_packets: Counter,
accepted_packets: Counter,
ignored_packets: Counter,
partial_responses: Counter,
internal_errors: Counter,
send_errors: Counter,
}

impl ServerStatHandler for ServerStats {
fn register(&mut self, reason: ServerReason, response: ServerResponse) {
self.0.received_packets.inc();
match response {
ServerResponse::Ignore => self.0.ignored_packets.inc(),
ServerResponse::PartialRepsonse => self.0.partial_responses.inc(),
ServerResponse::ProvideTime => self.0.accepted_packets.inc(),
}
match reason {
ServerReason::InternalError => self.0.internal_errors.inc(),
ServerReason::SendError => self.0.send_errors.inc(),
_ => {}
}
}
}

Expand Down Expand Up @@ -79,13 +123,17 @@ impl CsptpServerTask {
network: NetworkManager<A>,
_config: CsptpServerConfig,
) -> (Box<dyn ServerHandle>, JoinHandle<()>) {
let stats = ServerStats::default();
let handle = Box::new(CsptpServerHandle {
stats: stats.clone(),
});
(
Box::new(CsptpServerHandle {}),
handle,
tokio::spawn(async move {
let interface = network.open_general();
let socket = interface.listen_socket();
tracing::warn!("Spawned server");
serve(ServerSocketWrapper(socket), pending(), csptp_manager).await;
serve(ServerSocketWrapper(socket), pending(), csptp_manager, stats).await;
}),
)
}
Expand Down
9 changes: 8 additions & 1 deletion statime/src/daemon/observer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,14 @@ pub enum ObservableServerState {
nts_nak_packets: u64,
},
Ntske {},
Csptp {},
Csptp {
received_packets: u64,
accepted_packets: u64,
ignored_packets: u64,
partial_responses: u64,
internal_errors: u64,
send_errors: u64,
},
None,
}

Expand Down
Loading