Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
6 changes: 6 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ askama = "0.12.1"
atty = "0.2.14"
axum = "0.7.7"
chrono = "0.4.40"
dashmap = "6.1"
fern = {version = "0.7.1", features = ["colored"]}
futures = "0.3"
gethostname = "0.5.0"
hyper = "0.14"
http = "0.2"
log = "0.4.22"
prost = "0.13.3"
prost-types = "0.13.3"
Expand All @@ -21,7 +25,9 @@ slog-stdlog = "4.1.1"
stderrlog = "0.6.0"
structopt = "0.3.26"
tokio = {version = "1.40.0", features = ["full", "test-util", "tracing", "macros", "rt-multi-thread"] }
tokio-stream = "0.1"
tonic = "0.12.2"
tower = "0.4"

[build-dependencies]
tonic-build = "0.12.2"
Expand Down
14 changes: 11 additions & 3 deletions src/bin/lighthouse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.

use std::net::SocketAddr;
use structopt::StructOpt;
use torchft::lighthouse::{Lighthouse, LighthouseOpt};
use tonic::transport::Server;
use torchft::lighthouse::LighthouseOpt;
use torchft::router::Router;

#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
async fn main() {
Expand All @@ -17,7 +20,12 @@ async fn main() {
.unwrap();

let opt = LighthouseOpt::from_args();
let lighthouse = Lighthouse::new(opt).await.unwrap();
let router = Router::new(opt.clone());
let addr: SocketAddr = opt.bind.parse().expect("invalid --bind address");

lighthouse.run().await.unwrap();
Server::builder()
.add_service(router)
.serve(addr)
.await
.unwrap();
}
23 changes: 23 additions & 0 deletions src/interceptor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
use tonic::{service::Interceptor, metadata::MetadataValue, Request, Status};

/// Attaches user-assigned room-id header to every outbound RPC
#[derive(Clone)]
pub struct RoomIdInterceptor {
room: String,
}

impl RoomIdInterceptor {
pub fn new(room: String) -> Self {
Self { room }
}
}

impl Interceptor for RoomIdInterceptor {
fn call(&mut self, mut req: Request<()>) -> Result<Request<()>, Status> {
req.metadata_mut().insert(
crate::router::ROOM_ID_HEADER,
MetadataValue::try_from(self.room.as_str()).expect("ascii header"),
);
Ok(req)
}
}
12 changes: 12 additions & 0 deletions src/interceptor.rs~
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
use tonic::{Request, Status, service::Interceptor};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this file intentional?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah that's unintentional, removing in next commit

use tonic::metadata::MetadataValue;

pub fn room_id_interceptor(room: String) -> impl Interceptor {
move |mut req: Request<()>| {
req.metadata_mut().insert(
crate::router::ROOM_ID_HEADER,
MetadataValue::try_from(room.as_str()).expect("ascii header"),
);
Ok(req) // returning Err(Status) would cancel the call :contentReference[oaicite:0]{index=0}
}
}
85 changes: 60 additions & 25 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,31 @@
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.

mod interceptor;
pub mod lighthouse;
pub mod manager;
mod net;
mod retry;
pub mod router;
mod timeout;

pub use crate::router::Router;

use anyhow::Result;
use atty::Stream;
use core::time::Duration;
use pyo3::exceptions::{PyRuntimeError, PyTimeoutError};
use std::cmp;
use std::env;
use std::net::SocketAddr;
use std::sync::Arc;
use std::thread::available_parallelism;
use structopt::StructOpt;
use tokio::runtime::Runtime;
use tokio::task::JoinHandle;
use tonic::transport::Channel;
use tokio_stream::wrappers::TcpListenerStream;
use tonic::service::interceptor::InterceptedService;
use tonic::transport::{Channel, Endpoint};
use tonic::Status;

use chrono::Local;
Expand All @@ -32,6 +39,7 @@ pub mod torchftpb {
tonic::include_proto!("torchft");
}

use crate::interceptor::RoomIdInterceptor;
use crate::torchftpb::lighthouse_service_client::LighthouseServiceClient;
use crate::torchftpb::manager_service_client::ManagerServiceClient;
use crate::torchftpb::{
Expand Down Expand Up @@ -339,9 +347,13 @@ fn lighthouse_main(py: Python<'_>) -> PyResult<()> {
}

async fn lighthouse_main_async(opt: lighthouse::LighthouseOpt) -> Result<()> {
let lighthouse = lighthouse::Lighthouse::new(opt).await?;
let router = Router::new(opt.clone());
let addr: SocketAddr = opt.bind.parse()?;

lighthouse.run().await?;
tonic::transport::Server::builder()
.add_service(router)
.serve(addr)
.await?;

Ok(())
}
Expand Down Expand Up @@ -477,28 +489,39 @@ fn convert_quorum(py: Python, q: &torchftpb::Quorum) -> PyResult<Quorum> {
/// connect_timeout (timedelta): The timeout for connecting to the lighthouse server.
#[pyclass]
struct LighthouseClient {
client: LighthouseServiceClient<Channel>,
client: LighthouseServiceClient<InterceptedService<Channel, RoomIdInterceptor>>,
runtime: Runtime,
}

#[pymethods]
impl LighthouseClient {
#[pyo3(signature = (addr, connect_timeout))]
#[pyo3(signature = (addr, connect_timeout, room_id = None))]
#[new]
fn new(py: Python<'_>, addr: String, connect_timeout: Duration) -> PyResult<Self> {
fn new(
py: Python<'_>,
addr: String,
connect_timeout: Duration,
room_id: Option<String>,
) -> PyResult<Self> {
py.allow_threads(move || {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(num_threads())
.thread_name("torchft-lhclnt")
.enable_all()
.build()?;
let client = runtime
.block_on(manager::lighthouse_client_new(addr, connect_timeout))

let endpoint = Endpoint::from_shared(addr.clone())
.map_err(|e| PyRuntimeError::new_err(e.to_string()))?;
Ok(Self {
client: client,
runtime: runtime,
})
let channel = runtime
.block_on(endpoint.connect_timeout(connect_timeout).connect())
.map_err(|e| PyRuntimeError::new_err(e.to_string()))?;

let interceptor =
RoomIdInterceptor::new(room_id.unwrap_or_else(|| "default".to_owned()));

let client = LighthouseServiceClient::with_interceptor(channel, interceptor);

Ok(Self { client, runtime })
})
}

Expand Down Expand Up @@ -603,7 +626,7 @@ impl LighthouseClient {
/// heartbeat_timeout_ms (int): The timeout for heartbeats.
#[pyclass]
struct LighthouseServer {
lighthouse: Arc<lighthouse::Lighthouse>,
bind: String,
handle: JoinHandle<Result<()>>,
_runtime: Runtime,
}
Expand Down Expand Up @@ -631,19 +654,31 @@ impl LighthouseServer {
.enable_all()
.build()?;

let lighthouse = rt
.block_on(lighthouse::Lighthouse::new(lighthouse::LighthouseOpt {
bind: bind,
min_replicas: min_replicas,
join_timeout_ms: join_timeout_ms,
quorum_tick_ms: quorum_tick_ms,
heartbeat_timeout_ms: heartbeat_timeout_ms,
}))
.map_err(|e| PyRuntimeError::new_err(e.to_string()))?;
let opt = lighthouse::LighthouseOpt {
bind: bind.clone(),
min_replicas,
join_timeout_ms,
quorum_tick_ms,
heartbeat_timeout_ms,
};

let listener = rt.block_on(tokio::net::TcpListener::bind(&bind))?;
let bound_sock = listener.local_addr()?;
let bound = format!("http://{}", bound_sock);
let incoming = TcpListenerStream::new(listener);
let router = Router::new(opt.clone());

let handle = rt.spawn(async move {
tonic::transport::Server::builder()
.add_service(router)
.serve_with_incoming(incoming)
.await
.map_err(|e: tonic::transport::Error| anyhow::anyhow!(e))
});

Ok(Self {
handle: rt.spawn(lighthouse.clone().run()),
lighthouse: lighthouse,
bind: bound,
handle,
_runtime: rt,
})
})
Expand All @@ -654,7 +689,7 @@ impl LighthouseServer {
/// Returns:
/// str: The address of the lighthouse server.
fn address(&self) -> PyResult<String> {
Ok(self.lighthouse.address().to_string())
Ok(self.bind.clone())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this unfortunately isn't sufficient -- bind could be something like "0.0.0.0:0" which will bind to a random port. Address needs to be the routable http address i.e. http://foo.bar:1324

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, perhaps we could use similar calls as the Lighthouse class uses to resolve host IP and address? Will include a version of this in next commit, though am also down to change it

}

/// shutdown shuts down the lighthouse server.
Expand Down
2 changes: 1 addition & 1 deletion src/lighthouse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ impl ChangeLogger {
}
}

#[derive(StructOpt, Debug)]
#[derive(StructOpt, Debug, Clone)]
#[structopt()]
pub struct LighthouseOpt {
// bind is the address to bind the server to.
Expand Down
110 changes: 110 additions & 0 deletions src/router.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use std::{
convert::Infallible,
future::Future,
pin::Pin,
sync::Arc,
task::{Context, Poll},
};

use dashmap::{mapref::entry::Entry, DashMap};
use futures::FutureExt;
use tonic::{
body::BoxBody,
codegen::http::{HeaderMap, Request, Response}, // http-0.2 types
server::NamedService,
};
use tower::Service;

use crate::{
lighthouse::{Lighthouse, LighthouseOpt},
torchftpb::lighthouse_service_server::LighthouseServiceServer,
};

/// Metadata header recognised by both client interceptor and this router.
pub const ROOM_ID_HEADER: &str = "room-id";

/// gRPC server for a single room (inner state = `Arc<Lighthouse>`).
type GrpcSvc = LighthouseServiceServer<Arc<Lighthouse>>;

#[derive(Clone)]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why does Router need to be Cloneable?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mainly made Router Cloneable so that calls to tonic's add_service would compile when constructing the LighthouseServer in src/bin/lighthouse.rs and src/lib.rs

pub struct Router {
rooms: Arc<DashMap<String, Arc<GrpcSvc>>>,
tmpl_opt: LighthouseOpt,
}

impl Router {
pub fn new(tmpl_opt: LighthouseOpt) -> Self {
Self {
rooms: Arc::new(DashMap::new()),
tmpl_opt,
}
}

fn room_id(hdrs: &HeaderMap) -> &str {
hdrs.get(ROOM_ID_HEADER)
.and_then(|v| v.to_str().ok())
.unwrap_or("default")
}

async fn room_service(
rooms: Arc<DashMap<String, Arc<GrpcSvc>>>,
tmpl: LighthouseOpt,
id: &str,
) -> Arc<GrpcSvc> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be typed Arc<LighthouseServiceServer> instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sounds good - am changing in line with the below thread (returning an Arc and then wrapping with a LighthouseServiceServer once the method returns).

if let Some(svc) = rooms.get(id) {
return svc.clone();
}

// Build room state once.
let lh = Lighthouse::new(tmpl.clone())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we pass in the id into Lighthouse so we can prepend it to the Lighthouse log messages?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sounds good, will include in next commit

.await
.expect("failed to create Lighthouse");

let svc_new = Arc::new(LighthouseServiceServer::new(lh));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we be just returning Arc from this method and constructing the LighthouseServiceServer wrapper on demand so we don't need to clone it in the parent method?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh true, will include in next commit


match rooms.entry(id.to_owned()) {
Entry::Occupied(e) => e.get().clone(),
Entry::Vacant(v) => {
v.insert(svc_new.clone());
svc_new
}
}
}
}

// Tower::Service implementation
impl Service<Request<BoxBody>> for Router {
type Response = Response<BoxBody>;
type Error = Infallible;
type Future =
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;

fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}

fn call(&mut self, req: Request<BoxBody>) -> Self::Future {
let rooms = self.rooms.clone();
let tmpl = self.tmpl_opt.clone();
let room = Self::room_id(req.headers()).to_owned();

async move {
let svc_arc = Self::room_service(rooms, tmpl, &room).await;

// `Arc<GrpcSvc>` itself isn’t a Service; clone the inner value.
let mut svc = (*svc_arc).clone();
let resp = svc
.call(req)
.await
.map_err(|_e| -> Infallible { unreachable!() })?;

Ok(resp)
}
.boxed()
}
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is fine as is since this is fairly minimal boilerplate per request but I think we can do even better.

By doing this at the Service layer instead of LighthouseService layer we can have it automatically work for all endpoints on the LighthouseService

Can you look into this and see how feasible it is? If it's not any cleaner we can land this as is

Some pointers:

There's also https://github.com/teimuraz/tonic-middleware which might be useful

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried an initial attempt to do the routing at the Service layer rather than the LighthouseService layer, but have had trouble adapting between the initial tonic message types (tonic::Request/Response) and the Tower message types (http::Request/Response) - tonic::Request/Response wraps the body in tonic::body::BoxBody and carries gRPC-specific extensions, while the Tower stack we’re intercepting expects a bare http::Request/Response<B> where the body implements HttpBody. I haven't yet found a concise way to do this.

If I were to keep at this, I'd see if I could get something working that relies more on tonic-middleware - perhaps there's a way to stay entirely in the tonic domain that keeps the implementation and debugging cleaner?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mixing the two is a bit tricky -- we probably need to stay at the tower layer. Why do you need to access the tonic::Request/Response objects? It's all HTTP at the end of the day so seems like we should be able to operate at the tower/http layer and view the metadata as a header?

middleware might work though it may be too high level

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah I see, it became easier when I had router.rs operate entirely at the tower layer rather than trying to mix Service and tonic. Most recent commit has router.rs at the tower level, which lets us start the lighthouse server with a call to
Server::builder().add_service(router).serve(addr)


// Forward tonic’s NamedService marker
impl NamedService for Router {
const NAME: &'static str = <GrpcSvc as NamedService>::NAME;
}
Loading
Loading