Skip to content
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
merged 3 commits into from
Aug 2, 2022
Merged
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
25 changes: 25 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ members = [
"ddm-admin-client",
"deploy",
"gateway",
"gateway/faux-mgs",
"gateway-cli",
"gateway-client",
"gateway-messages",
Expand Down Expand Up @@ -40,6 +41,7 @@ default-members = [
"ddm-admin-client",
"deploy",
"gateway",
"gateway/faux-mgs",
"gateway-cli",
"gateway-client",
"gateway-messages",
Expand Down
2 changes: 1 addition & 1 deletion gateway/examples/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ switch1 = ["switch", 1]

[switch.port.1]
data_link_addr = "[::]:33201"
multicast_addr = "[ff15:0:1de::1]:33310"
multicast_addr = "[ff15:0:1de::1%2]:11111"
[switch.port.1.location]
switch0 = ["sled", 0]
switch1 = ["sled", 0]
Expand Down
18 changes: 18 additions & 0 deletions gateway/faux-mgs/Cargo.toml
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"] }
28 changes: 28 additions & 0 deletions gateway/faux-mgs/README.adoc
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
```
198 changes: 198 additions & 0 deletions gateway/faux-mgs/src/main.rs
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);
Copy link
Contributor

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.

Copy link
Contributor Author

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.


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,
})
}
}
Loading