-
Notifications
You must be signed in to change notification settings - Fork 43
Support multiple quorums on a single LighthouseServer using gRPC metadata-based room assignment #189
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
base: main
Are you sure you want to change the base?
Support multiple quorums on a single LighthouseServer using gRPC metadata-based room assignment #189
Changes from 4 commits
fedd473
eb482e5
5ab4c0c
0a9ce34
273d3ee
8aed1fc
53ec8be
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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) | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
use tonic::{Request, Status, service::Interceptor}; | ||
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} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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; | ||
|
@@ -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::{ | ||
|
@@ -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(()) | ||
} | ||
|
@@ -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 }) | ||
}) | ||
} | ||
|
||
|
@@ -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, | ||
} | ||
|
@@ -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, | ||
}) | ||
}) | ||
|
@@ -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()) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. | ||
|
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)] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why does Router need to be Cloneable? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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> { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should this be typed There was a problem hiding this comment. Choose a reason for hiding this commentThe 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()) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can we pass in the There was a problem hiding this comment. Choose a reason for hiding this commentThe 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)); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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() | ||
} | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 ( If I were to keep at this, I'd see if I could get something working that relies more on There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
|
||
// Forward tonic’s NamedService marker | ||
impl NamedService for Router { | ||
const NAME: &'static str = <GrpcSvc as NamedService>::NAME; | ||
} |
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.
Is this file intentional?
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.
Ah that's unintentional, removing in next commit