-
Notifications
You must be signed in to change notification settings - Fork 40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add initial faux-mgs
dev tool
#1526
Merged
+589
−1
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
[package] | ||
name = "faux-mgs" | ||
version = "0.1.0" | ||
edition = "2021" | ||
license = "MPL-2.0" | ||
|
||
[dependencies] | ||
anyhow = "1.0" | ||
clap = { version = "3.2", features = ["derive"] } | ||
crossbeam-channel = "0.5" | ||
mio = "0.8" | ||
slog = { version = "2.7", features = ["max_level_trace", "release_max_level_debug"] } | ||
slog-async = "2.6" | ||
slog-term = "2.9" | ||
termios = "0.3" | ||
thiserror = "1.0" | ||
|
||
gateway-messages = { path = "../../gateway-messages", features = ["std"] } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
= Faux MGS | ||
|
||
This directory contains a command-line application that acts like MGS. It is | ||
intended to be a development tool for working with the SP. | ||
|
||
== Examples | ||
|
||
Sending the MGS discovery packet: | ||
|
||
``` | ||
% cargo run --bin faux-mgs -- --sp '[fe80::c1d:7dff:feef:9f1d%2]:11111' discover | ||
Ok(Discover(DiscoverResponse { sp_port: One })) | ||
``` | ||
|
||
Asking an SP for its state (as of this writing, the state only contains the SP's | ||
serial number): | ||
|
||
``` | ||
% cargo run --bin faux-mgs -- --sp '[fe80::c1d:7dff:feef:9f1d%2]:11111' state | ||
Ok(SpState(SpState { serial_number: [0, 68, 0, 26, 51, 48, 81, 17, 48, 51, 56, 55, 0, 0, 0, 0] })) | ||
``` | ||
|
||
Attaching to the SP's usart (this forwards stdin to the SP, and prints anything | ||
the SP sends to stdout): | ||
|
||
``` | ||
% cargo run --bin faux-mgs -- --sp '[fe80::c1d:7dff:feef:9f1d%2]:11111' usart-attach | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,198 @@ | ||
// This Source Code Form is subject to the terms of the Mozilla Public | ||
// License, v. 2.0. If a copy of the MPL was not distributed with this | ||
// file, You can obtain one at https://mozilla.org/MPL/2.0/. | ||
|
||
// Copyright 2022 Oxide Computer Company | ||
|
||
use anyhow::bail; | ||
use anyhow::Context; | ||
use anyhow::Result; | ||
use clap::Parser; | ||
use clap::Subcommand; | ||
use gateway_messages::version; | ||
use gateway_messages::Request; | ||
use gateway_messages::RequestKind; | ||
use gateway_messages::ResponseError; | ||
use gateway_messages::ResponseKind; | ||
use gateway_messages::SerializedSize; | ||
use gateway_messages::SpMessage; | ||
use gateway_messages::SpMessageKind; | ||
use slog::debug; | ||
use slog::o; | ||
use slog::trace; | ||
use slog::warn; | ||
use slog::Drain; | ||
use slog::Level; | ||
use slog::Logger; | ||
use std::io; | ||
use std::net::SocketAddrV6; | ||
use std::net::UdpSocket; | ||
use std::sync::atomic::AtomicU32; | ||
use std::sync::atomic::Ordering; | ||
use std::time::Duration; | ||
|
||
mod usart; | ||
|
||
/// Command line program that can send MGS messages to a single SP. | ||
#[derive(Parser, Debug)] | ||
struct Args { | ||
#[clap( | ||
short, | ||
long, | ||
default_value = "info", | ||
value_parser = level_from_str, | ||
help = "Log level for MGS client", | ||
)] | ||
log_level: Level, | ||
|
||
#[clap(long)] | ||
sp: SocketAddrV6, | ||
|
||
#[clap(long, short, default_value = "3000")] | ||
timeout_millis: u64, | ||
|
||
#[clap(subcommand)] | ||
command: Commands, | ||
} | ||
|
||
fn level_from_str(s: &str) -> Result<Level> { | ||
if let Ok(level) = s.parse() { | ||
Ok(level) | ||
} else { | ||
bail!(format!("Invalid log level: {}", s)) | ||
} | ||
} | ||
|
||
#[derive(Subcommand, Debug)] | ||
enum Commands { | ||
/// Ask SP on which port it receives messages from us. | ||
Discover, | ||
|
||
/// Ask SP for its current state. | ||
State, | ||
|
||
/// Attach to the SP's USART. | ||
UsartAttach { | ||
/// Put the local terminal in raw mode. | ||
#[clap(long)] | ||
raw: bool, | ||
}, | ||
} | ||
|
||
fn main() -> Result<()> { | ||
let args = Args::parse(); | ||
let decorator = slog_term::TermDecorator::new().build(); | ||
let drain = slog_term::FullFormat::new(decorator) | ||
.build() | ||
.filter_level(args.log_level) | ||
.fuse(); | ||
let drain = slog_async::Async::new(drain).build().fuse(); | ||
let log = Logger::root(drain, o!("component" => "faux-mgs")); | ||
|
||
let socket = UdpSocket::bind("[::]:0") | ||
.with_context(|| "failed to bind UDP socket")?; | ||
socket | ||
.set_read_timeout(Some(Duration::from_millis(args.timeout_millis))) | ||
.with_context(|| "failed to set read timeout on UDP socket")?; | ||
|
||
let request_kind = match args.command { | ||
Commands::Discover => RequestKind::Discover, | ||
Commands::State => RequestKind::SpState, | ||
Commands::UsartAttach { raw } => { | ||
return usart::run(log, socket, args.sp, raw); | ||
} | ||
}; | ||
|
||
let response = request_response(&log, &socket, args.sp, request_kind)?; | ||
println!("{response:?}"); | ||
|
||
Ok(()) | ||
} | ||
|
||
fn request_response( | ||
log: &Logger, | ||
socket: &UdpSocket, | ||
addr: SocketAddrV6, | ||
kind: RequestKind, | ||
) -> Result<Result<ResponseKind, ResponseError>> { | ||
let request_id = send_request(log, socket, addr, kind)?; | ||
loop { | ||
let message = recv_sp_message(log, socket)?; | ||
match message.kind { | ||
SpMessageKind::Response { request_id: response_id, result } => { | ||
if response_id != request_id { | ||
warn!( | ||
log, "ignoring unexpected response id"; | ||
"response_id" => response_id, | ||
); | ||
continue; | ||
} | ||
return Ok(result); | ||
} | ||
SpMessageKind::SerialConsole(_) => { | ||
debug!(log, "ignoring serial console packet from SP"); | ||
continue; | ||
} | ||
} | ||
} | ||
} | ||
|
||
// On success, returns the request ID we sent. | ||
fn send_request( | ||
log: &Logger, | ||
socket: &UdpSocket, | ||
addr: SocketAddrV6, | ||
kind: RequestKind, | ||
) -> Result<u32> { | ||
static REQUEST_ID: AtomicU32 = AtomicU32::new(1); | ||
|
||
let version = version::V1; | ||
let request_id = REQUEST_ID.fetch_add(1, Ordering::Relaxed); | ||
let request = Request { version, request_id, kind }; | ||
|
||
let mut buf = [0; Request::MAX_SIZE]; | ||
debug!( | ||
log, "sending request to SP"; | ||
"request" => ?request, | ||
"sp" => %addr, | ||
); | ||
let n = gateway_messages::serialize(&mut buf[..], &request).unwrap(); | ||
socket | ||
.send_to(&buf[..n], addr) | ||
.with_context(|| format!("failed to send to {addr}"))?; | ||
|
||
Ok(request_id) | ||
} | ||
|
||
#[derive(Debug, thiserror::Error)] | ||
enum RecvError { | ||
#[error(transparent)] | ||
Io(#[from] io::Error), | ||
#[error("failed to deserialize response: {0}")] | ||
Deserialize(#[from] gateway_messages::HubpackError), | ||
#[error("incorrect message version (expected {expected}, got {got})")] | ||
IncorrectVersion { expected: u32, got: u32 }, | ||
} | ||
|
||
fn recv_sp_message( | ||
log: &Logger, | ||
socket: &UdpSocket, | ||
) -> Result<SpMessage, RecvError> { | ||
let mut resp = [0; SpMessage::MAX_SIZE]; | ||
|
||
let (n, _peer) = socket.recv_from(&mut resp[..])?; | ||
let resp = &resp[..n]; | ||
trace!(log, "received packet"; "data" => ?resp); | ||
|
||
let (message, _) = gateway_messages::deserialize::<SpMessage>(resp)?; | ||
debug!(log, "received response"; "response" => ?message); | ||
|
||
if message.version == version::V1 { | ||
Ok(message) | ||
} else { | ||
Err(RecvError::IncorrectVersion { | ||
expected: version::V1, | ||
got: message.version, | ||
}) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is this atomic? For mutability? I assume you made it static so you wouldn't have to pass it as a parameter.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, just for simplicity - if this function sends all packets, this allows it to keep its own monotonically increasing counter, freeing the caller up from worrying about it.