Skip to content

Commit

Permalink
adding connection method, tracing, shared struct with WASM to generic…
Browse files Browse the repository at this point in the history
…ally create network + ready to implement read&write
  • Loading branch information
Erik Chi committed Sep 26, 2023
1 parent e215b92 commit ee1d226
Show file tree
Hide file tree
Showing 9 changed files with 237 additions and 25 deletions.
75 changes: 75 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 @@ -15,6 +15,8 @@ path = "src/main.rs"

[dependencies]
anyhow = "1.0.7"
tracing = "0.1"
tracing-subscriber = "0.3.17"
clap = { version="4.2.1", features = ["derive"] }
wasmtime = "12.0.1"
wasmtime-wasi = "12.0.1"
Expand Down
Binary file modified proxy.wasm
Binary file not shown.
20 changes: 20 additions & 0 deletions src/config/sharedconfig.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::mem;
use serde::{Serialize, Deserialize};

#[repr(C)]
pub struct WASMSharedConfig {
Expand Down Expand Up @@ -28,3 +29,22 @@ impl WASMSharedConfig {
// Some(*struct_ref)
// }
}

#[derive(Serialize, Deserialize)]
#[repr(C)]
pub struct StreamConfig {
pub addr: String,
pub port: u32,
pub name: String,
}

impl StreamConfig {
pub fn to_bytes(&self) -> Vec<u8> {
let size = mem::size_of::<StreamConfig>();
let ptr = self as *const Self;

let bytes_slice = unsafe { std::slice::from_raw_parts(ptr as *const u8, size) };
let bytes = bytes_slice.to_vec();
bytes
}
}
1 change: 1 addition & 0 deletions src/globals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const DEALLOC_FN: &str = "dealloc";
pub const MAIN: &str = "main";
pub const VERSION_FN: &str = "_version";
pub const INIT_FN: &str = "_init";
pub const CONFIG_FN: &str = "_process_config";
pub const USER_READ_FN: &str = "_user_will_read";
pub const WRITE_DONE_FN: &str = "_user_write_done";

Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ use std::sync::Arc;
pub use config::Config;

pub fn execute(conf: Config) -> Result<(), anyhow::Error> {
let mut connector = runtime::WATERStreamConnector::new(conf)?;
let mut water_client = runtime::WATERClient::new(conf)?;

let mut rs = connector.connect()?;
let mut rs = water_client.connect()?;
// rs.connect(&connector.config)?;

Ok(())
Expand Down
6 changes: 6 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
mod cli;

use wasmable_transport;
use tracing_subscriber;
use tracing::Level;

fn main() -> Result<(), anyhow::Error> {
tracing_subscriber::fmt()
.with_max_level(Level::INFO)
.init();

cli::parse_and_execute()
}
87 changes: 74 additions & 13 deletions src/runtime/funcs.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::runtime::*;
use crate::sharedconfig::StreamConfig;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};

// Generically link dial functions
// pub fn linkDialFuns(linker: &mut Linker<Host>) {
Expand All @@ -17,8 +19,68 @@ use crate::runtime::*;
// }
// }

pub fn export_tcp_connect(linker: &mut Linker<Host>) {
linker.func_wrap("env", "connect_tcp", move |mut caller: Caller<'_, Host>, ptr: u32, size: u32, fd: u32| -> i32{

info!("[WASM] invoking Host exported Dial func connect_tcp...");

let memory = match caller.get_export("memory") {
Some(Extern::Memory(memory)) => memory,
_ => return -1,
};

// Get a slice of the memory.
let mem_slice = memory.data_mut(&mut caller);

// Use the offset and size to get the relevant part of the memory.
let data = &mut mem_slice[ptr as usize..(ptr as usize + size as usize)];

let mut config: StreamConfig;
unsafe {
config = bincode::deserialize(&data).expect("Failed to deserialize");
}

let connect_file = File::Connect(ConnectFile::Tcp {
name: Some(config.name.clone().try_into().unwrap()),
port: config.port as u16,
host: config.addr.clone().into()
});

// Get the pair here addr:port
let (host, port) = match connect_file {
File::Connect(listen_file) => match listen_file {
ConnectFile::Tcp { host, port, .. } | ConnectFile::Tls { host, port, .. } => (host, port),
},
_ => { ("Wrong".into(), 0) }
};

let tcp = match (host.as_str(), port) {
("localhost", port) => std::net::TcpStream::connect(SocketAddr::V4(SocketAddrV4::new(
Ipv4Addr::LOCALHOST,
port,
))),
addr => std::net::TcpStream::connect(addr),
}
.map(TcpStream::from_std)
.context("failed to connect to endpoint").unwrap();

// Connecting Tcp
let socket_file: Box<dyn WasiFile> = wasmtime_wasi::net::Socket::from(tcp).into();

let socket_fd: usize = (fd).try_into().unwrap();

// Get the WasiCtx of the caller(WASM), then insert_file into it
let mut ctx: &mut WasiCtx = caller.data_mut().preview1_ctx.as_mut().unwrap();
ctx.insert_file(socket_fd as u32, socket_file, FileAccessMode::all());

socket_fd as i32
}).unwrap();
}

pub fn export_tcplistener_create(linker: &mut Linker<Host>) {
linker.func_wrap("env", "create_listen", move |mut caller: Caller<'_, Host>, ptr: u32, size: u32| -> i32{
linker.func_wrap("env", "create_listen", move |mut caller: Caller<'_, Host>, ptr: u32, size: u32, fd: u32| -> i32{

info!("[WASM] invoking Host exported Dial func create_tcp_listener...");

let memory = match caller.get_export("memory") {
Some(Extern::Memory(memory)) => memory,
Expand All @@ -29,19 +91,21 @@ pub fn export_tcplistener_create(linker: &mut Linker<Host>) {
let mem_slice = memory.data_mut(&mut caller);

// Use the offset and size to get the relevant part of the memory.
// TODO: use data here to get the filename, ip:port for creating config
let data = &mut mem_slice[ptr as usize..(ptr as usize + size as usize)];
// println!("Data: {:?}", data);

let mut config: StreamConfig;
unsafe {
config = bincode::deserialize(&data).expect("Failed to deserialize");
}

// FIXME: currently hardcoded config here
let test_file = File::Listen(ListenFile::Tcp {
name: "LISTEN".try_into().unwrap(),
port: 9005,
addr: "127.0.0.1".into()
let listener_file = File::Listen(ListenFile::Tcp {
name: config.name.clone().try_into().unwrap(),
port: config.port as u16,
addr: config.addr.clone().into()
});

// Get the pair here addr:port
let (addr, port) = match test_file {
let (addr, port) = match listener_file {
File::Listen(listen_file) => match listen_file {
ListenFile::Tcp { addr, port, .. } | ListenFile::Tls { addr, port, .. } => (addr, port),
},
Expand All @@ -53,11 +117,8 @@ pub fn export_tcplistener_create(linker: &mut Linker<Host>) {
let tcp = TcpListener::from_std(tcp);
tcp.set_nonblocking(true);
let socket_file: Box<dyn WasiFile> = wasmtime_wasi::net::Socket::from(tcp).into();

// FIXME: currently hardcoded the fd mapped into WASM -- need to configed by WASM if there are multiple connections later
let wanted_fd = 3;

let socket_fd: usize = (wanted_fd).try_into().unwrap();
let socket_fd: usize = (fd).try_into().unwrap();

// Get the WasiCtx of the caller(WASM), then insert_file into it
let mut ctx: &mut WasiCtx = caller.data_mut().preview1_ctx.as_mut().unwrap();
Expand Down
Loading

0 comments on commit ee1d226

Please sign in to comment.